cortiq-cli 0.7.0

Command-line tools for the CMF model format: inspect, convert, run and serve .cmf models.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
//! Native Rust converter: a Hugging Face checkpoint (config.json +
//! *.safetensors + tokenizer.json) → a `.cmf` container. No Python, numpy, or
//! torch — reads safetensors and quantizes in Rust, then writes with
//! `cortiq_core::CmfModel::write`.
//!
//! Scope: standard dense transformers (qwen2 / qwen3 / llama / mistral-style,
//! RMSNorm + RoPE + SwiGLU, optional attention biases). Tensor handling is
//! arch-agnostic — 1-D tensors are stored f16, 2-D weights are quantized — so
//! it works by tensor presence without a hard-coded tensor set. Mixture-of-experts
//! is supported (router + per-expert matrices), as is GatedDeltaNet linear
//! attention in the Qwen3.5 hub layout (separate in_proj_qkv/z/a/b) and the
//! fused qwen3_next / AgentWorld layout, whose group-interleaved `in_proj_qkvz`
//! / `in_proj_ba` projections are split natively (`split_fused_gdn`).
//!
//! Not in scope: per-skill delta tensors and task masks — this writes backbones.
//! Those come from the DTG-MA path in `converter/`.

use crate::npy;
use cortiq_core::format::{CMF_VERSION, CmfHeader, TensorSpec, TokenizerBundle};
use cortiq_core::quant::{
    Q2TP_CHUNK, Q2TP_LMAX, Q4TP_LMAX, Q4TP_NIB, bf16_to_f32, f16_to_f32, f32_to_f16, q2tp_ladder,
    q4tp_code_stride, q4tp_ladder, q4tp_put_code,
};
use cortiq_core::types::{
    LayerType, LinearCoreConfig, ModelArch, MoeConfig, NormStyle, PrismAffineConfig,
    PrismHadamardConfig, QuantType, Qwen4ExpConfig, TensorDtype, YarnConfig,
};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU8, AtomicU32, AtomicUsize, Ordering};
use std::time::Duration;

const GROUP_SIZE: usize = 32;
/// Smallest normal f16 — floor for degenerate (all-zero) rows so the stored
/// scale never underflows to a subnormal the reader would read back as 0.
const F16_TINY: f32 = 6.103_515_6e-5;
/// Local source-shard consumption is deliberately explicit because it removes
/// the original safetensors files after their output checkpoint is durable.
/// The V4.1 pod conversion sets this when the source and output cannot coexist
/// under the disk budget; ordinary conversions preserve their source files.
const CONSUME_SOURCE_SHARDS_ENV: &str = "CMF_CONSUME_SOURCE_SHARDS";
/// Opt-in certificate directory for a local source whose shards are still
/// being downloaded by another process.  The sibling `source-files.json`
/// pins every filename, byte length and SHA256 before a marker can authorize
/// opening that shard.
const LOCAL_READY_DIR_ENV: &str = "CMF_LOCAL_READY_DIR";
/// Test/operator override for the ready-marker poll interval.  Production
/// uses the conservative default so a marker producer is not busy-polled.
const LOCAL_READY_POLL_MS_ENV: &str = "CMF_LOCAL_READY_POLL_MS";
const LOCAL_READY_POLL_MS_DEFAULT: u64 = 2_000;
/// Optional comma-separated source basenames to process first.  This only
/// affects the streamed source path; an unset variable preserves the index's
/// validated stable order.
const SOURCE_SHARD_PRIORITY_ENV: &str = "CMF_SOURCE_SHARD_PRIORITY";

fn consume_source_shards_enabled() -> bool {
    std::env::var(CONSUME_SOURCE_SHARDS_ENV)
        .ok()
        .is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct SourceFileExpectation {
    size: u64,
    sha256: String,
}

fn local_ready_dir_from_env() -> Option<PathBuf> {
    std::env::var_os(LOCAL_READY_DIR_ENV)
        .map(PathBuf::from)
        .filter(|p| !p.as_os_str().is_empty())
}

fn local_ready_poll_ms() -> u64 {
    std::env::var(LOCAL_READY_POLL_MS_ENV)
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .unwrap_or(LOCAL_READY_POLL_MS_DEFAULT)
}

/// The source manifest lives next to the ready directory (`/root/dsv41` in
/// the pod layout).  Keeping this derived from the one opt-in environment
/// variable avoids a second path that could accidentally point at a
/// different certificate set.
fn local_ready_manifest_path(ready_dir: &Path) -> PathBuf {
    ready_dir
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
        .join("source-files.json")
}

fn ensure_source_filename(name: &str) -> anyhow::Result<()> {
    let path = Path::new(name);
    anyhow::ensure!(
        !name.is_empty()
            && !name.contains('\\')
            && path.is_relative()
            && path.components().count() == 1
            && matches!(path.components().next(), Some(Component::Normal(_))),
        "local-ready source filename must be a plain basename, got {name:?}"
    );
    Ok(())
}

fn parse_sha256(value: &str, context: &str) -> anyhow::Result<String> {
    let normalized = value.trim().to_ascii_lowercase();
    anyhow::ensure!(
        normalized.len() == 64 && normalized.bytes().all(|b| b.is_ascii_hexdigit()),
        "{context}: SHA256 must be exactly 64 hexadecimal characters"
    );
    Ok(normalized)
}

/// Read the pinned parent manifest.  The production manifest is a JSON object
/// keyed by shard basename; each value contains `size` and `sha256`.  The
/// required set comes from the local model index, so unrelated files in the
/// manifest do not silently become conversion inputs.
fn read_source_file_manifest(
    path: &Path,
    required_shards: &[String],
) -> anyhow::Result<HashMap<String, SourceFileExpectation>> {
    let text = fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("read local-ready source manifest {}: {e}", path.display()))?;
    let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
        anyhow::anyhow!("parse local-ready source manifest {}: {e}", path.display())
    })?;
    let object = value.as_object().ok_or_else(|| {
        anyhow::anyhow!(
            "local-ready source manifest {} must be a JSON object keyed by filename",
            path.display()
        )
    })?;
    let mut expected = HashMap::with_capacity(object.len());
    for (name, record) in object {
        ensure_source_filename(name)?;
        let record = record
            .as_object()
            .ok_or_else(|| anyhow::anyhow!("manifest entry {name:?} is not an object"))?;
        let size = record
            .get("size")
            .and_then(serde_json::Value::as_u64)
            .ok_or_else(|| anyhow::anyhow!("manifest entry {name:?} has no u64 size"))?;
        let sha256 = record
            .get("sha256")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| anyhow::anyhow!("manifest entry {name:?} has no sha256"))
            .and_then(|v| parse_sha256(v, &format!("manifest entry {name:?}")))?;
        anyhow::ensure!(
            expected
                .insert(name.clone(), SourceFileExpectation { size, sha256 })
                .is_none(),
            "duplicate local-ready source manifest entry {name:?}"
        );
    }
    for name in required_shards {
        ensure_source_filename(name)?;
        anyhow::ensure!(
            expected.contains_key(name),
            "local-ready source manifest {} has no entry for indexed shard {name}",
            path.display()
        );
    }
    Ok(expected)
}

fn ready_marker_path(ready_dir: &Path, filename: &str) -> anyhow::Result<PathBuf> {
    ensure_source_filename(filename)?;
    Ok(ready_dir.join(format!("{filename}.json")))
}

fn read_ready_marker(
    path: &Path,
    filename: &str,
    expected: &SourceFileExpectation,
) -> anyhow::Result<()> {
    let text = fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("read local-ready marker {}: {e}", path.display()))?;
    let value: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| anyhow::anyhow!("parse local-ready marker {}: {e}", path.display()))?;
    let object = value
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("local-ready marker {} is not an object", path.display()))?;
    let marker_name = object
        .get("filename")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("local-ready marker {} has no filename", path.display()))?;
    anyhow::ensure!(
        marker_name == filename,
        "local-ready marker {} names {marker_name:?}, expected {filename:?}",
        path.display()
    );
    let marker_size = object
        .get("size")
        .and_then(serde_json::Value::as_u64)
        .ok_or_else(|| anyhow::anyhow!("local-ready marker {} has no u64 size", path.display()))?;
    anyhow::ensure!(
        marker_size == expected.size,
        "local-ready marker {} size {} disagrees with pinned size {}",
        path.display(),
        marker_size,
        expected.size
    );
    let marker_sha = object
        .get("sha256")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("local-ready marker {} has no sha256", path.display()))
        .and_then(|v| parse_sha256(v, &format!("local-ready marker {}", path.display())))?;
    anyhow::ensure!(
        marker_sha == expected.sha256,
        "local-ready marker {} SHA256 disagrees with pinned source manifest",
        path.display()
    );
    Ok(())
}

/// Hash one ready source shard with a fixed-size buffer.  This is intentionally
/// done before mmap: a marker is a certificate boundary, while the second
/// metadata check catches a producer that changed a file after certification.
fn sha256_file(path: &Path) -> anyhow::Result<(u64, String)> {
    use sha2::{Digest, Sha256};
    let mut file = fs::File::open(path)
        .map_err(|e| anyhow::anyhow!("open local-ready source {}: {e}", path.display()))?;
    let before = file.metadata()?;
    let mut hasher = Sha256::new();
    let mut buf = vec![0u8; 8 * 1024 * 1024];
    let mut size = 0u64;
    loop {
        let n = file.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
        size = size.checked_add(n as u64).ok_or_else(|| {
            anyhow::anyhow!("local-ready source {} size overflow", path.display())
        })?;
    }
    let after = file.metadata()?;
    anyhow::ensure!(
        before.len() == after.len() && before.modified().ok() == after.modified().ok(),
        "local-ready source {} changed while it was being certified",
        path.display()
    );
    Ok((size, format!("{:x}", hasher.finalize())))
}

/// Validate a marker and its source bytes.  Callers only pass the returned
/// path to `open_safetensors` after this function succeeds, so incomplete
/// `.aria2`/partial files can never enter the mmap path.
fn validate_local_ready_source(
    ready_dir: &Path,
    source_dir: &Path,
    filename: &str,
    expected: &SourceFileExpectation,
) -> anyhow::Result<PathBuf> {
    let marker = ready_marker_path(ready_dir, filename)?;
    read_ready_marker(&marker, filename, expected)?;
    let source = source_dir.join(filename);
    anyhow::ensure!(
        !PathBuf::from(format!("{}.aria2", source.display())).exists(),
        "local-ready source {} still has an aria2 partial marker",
        source.display()
    );
    let metadata = fs::metadata(&source).map_err(|e| {
        anyhow::anyhow!(
            "local-ready marker exists for missing source {}: {e}",
            source.display()
        )
    })?;
    anyhow::ensure!(
        metadata.is_file() && metadata.len() == expected.size,
        "local-ready source {} has {} bytes, expected {}",
        source.display(),
        metadata.len(),
        expected.size
    );
    let (actual_size, actual_sha) = sha256_file(&source)?;
    anyhow::ensure!(
        actual_size == expected.size && actual_sha == expected.sha256,
        "local-ready source {} failed pinned SHA256/size validation",
        source.display()
    );
    Ok(source)
}

fn wait_for_local_ready_source(
    ready_dir: &Path,
    source_dir: &Path,
    filename: &str,
    expected: &SourceFileExpectation,
) -> anyhow::Result<PathBuf> {
    let marker = ready_marker_path(ready_dir, filename)?;
    loop {
        if marker.exists() {
            return validate_local_ready_source(ready_dir, source_dir, filename, expected);
        }
        std::thread::sleep(Duration::from_millis(local_ready_poll_ms()));
    }
}

/// Round a scale to f16 precision (the reader stores/uses it as f16), so the
/// quantized values are computed against the *same* scale the reader dequantizes
/// with. This is what the reference converter does; without it `q` and the
/// stored scale disagree and inference degrades to garbage.
fn f16_scale(raw: f32) -> f32 {
    f16_to_f32(f32_to_f16(raw)).max(F16_TINY)
}

/// tiktoken pre-tokenization pattern (Kimi family, o200k lineage) —
/// verbatim from tokenization_kimi.py; tiktoken itself compiles this
/// with fancy-regex, the same engine the runtime tokenizer uses.
const TIKTOKEN_KIMI_PAT: &str = concat!(
    r"[\p{Han}]+",
    r"|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*",
    r"[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?",
    r"|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+",
    r"[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?",
    r"|\p{N}{1,3}",
    r"| ?[^\s\p{L}\p{N}]+[\r\n]*",
    r"|\s*[\r\n]+",
    r"|\s+(?!\S)",
    r"|\s+",
);

/// GPT-2 byte-level alphabet: raw byte → printable char (identity for
/// the printable ranges, 256+n in first-free order for the rest).
fn byte_level_table() -> [char; 256] {
    let mut table = ['\0'; 256];
    let mut n = 0u32;
    for b in 0..=255u32 {
        let printable =
            (0x21..=0x7E).contains(&b) || (0xA1..=0xAC).contains(&b) || (0xAE..=0xFF).contains(&b);
        table[b as usize] = if printable {
            char::from_u32(b).unwrap()
        } else {
            let c = char::from_u32(256 + n).unwrap();
            n += 1;
            c
        };
    }
    table
}

/// Build an HF tokenizer.json from a tiktoken rank table (Kimi family).
///
/// tiktoken stores `base64(token_bytes) rank` per line and no merge
/// list — the merges ARE the ranks. Recovery (transformers' tiktoken
/// converter): BPE-split every multi-byte token using only merges of
/// strictly lower rank; the two parts it stops at are that token's
/// merge rule. Specials come from tokenizer_config.added_tokens_decoder.
fn tiktoken_to_tokenizer_json(model: &str, tok_cfg: &serde_json::Value) -> anyhow::Result<String> {
    use base64::Engine as _;
    use std::collections::HashMap;
    let b64 = base64::engine::general_purpose::STANDARD;
    let mut ranks: HashMap<Vec<u8>, u32> = HashMap::new();
    let mut ordered: Vec<(Vec<u8>, u32)> = Vec::new();
    for line in model.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let (tok, rank) = line
            .rsplit_once(' ')
            .ok_or_else(|| anyhow::anyhow!("tiktoken: bad line {line:?}"))?;
        let bytes = b64
            .decode(tok)
            .map_err(|e| anyhow::anyhow!("tiktoken: bad base64 {tok:?}: {e}"))?;
        let rank: u32 = rank.parse()?;
        ranks.insert(bytes.clone(), rank);
        ordered.push((bytes, rank));
    }
    anyhow::ensure!(!ordered.is_empty(), "tiktoken: empty rank table");
    ordered.sort_by_key(|(_, r)| *r);

    let table = byte_level_table();
    let to_bl = |bytes: &[u8]| -> String { bytes.iter().map(|&b| table[b as usize]).collect() };

    // Merge recovery: split `token` greedily by lowest-rank pair, using
    // only merges of rank < the token's own.
    let bpe_parts = |token: &[u8], max_rank: u32| -> Vec<Vec<u8>> {
        let mut parts: Vec<Vec<u8>> = token.iter().map(|&b| vec![b]).collect();
        loop {
            let mut best: Option<(usize, u32)> = None;
            for i in 0..parts.len() - 1 {
                let cat = [parts[i].as_slice(), parts[i + 1].as_slice()].concat();
                if let Some(&r) = ranks.get(cat.as_slice()) {
                    if r < max_rank && best.map(|(_, br)| r < br).unwrap_or(true) {
                        best = Some((i, r));
                    }
                }
            }
            match best {
                Some((i, _)) => {
                    let b = parts.remove(i + 1);
                    parts[i].extend(b);
                }
                None => break,
            }
        }
        parts
    };

    let mut vocab = serde_json::Map::new();
    let mut merges: Vec<serde_json::Value> = Vec::new();
    let mut skipped = 0usize;
    for (bytes, rank) in &ordered {
        vocab.insert(to_bl(bytes), serde_json::json!(rank));
        if bytes.len() > 1 {
            let parts = bpe_parts(bytes, *rank);
            if parts.len() == 2 {
                merges.push(serde_json::json!([to_bl(&parts[0]), to_bl(&parts[1])]));
            } else {
                // Unreachable-by-merges token (rare): encodable only as
                // a whole pre-token piece; keep it in the vocab.
                skipped += 1;
            }
        }
    }
    if skipped > 0 {
        tracing::warn!("tiktoken: {skipped} tokens yielded no merge rule (kept vocab-only)");
    }

    let mut added: Vec<serde_json::Value> = Vec::new();
    if let Some(atd) = tok_cfg
        .get("added_tokens_decoder")
        .and_then(|v| v.as_object())
    {
        for (id, tok) in atd {
            if let (Ok(id), Some(content)) = (
                id.parse::<u32>(),
                tok.get("content").and_then(|c| c.as_str()),
            ) {
                added.push(serde_json::json!({
                    "id": id, "content": content, "special": true
                }));
            }
        }
    }

    let json = serde_json::json!({
        "version": "1.0",
        "added_tokens": added,
        "pre_tokenizer": {
            "type": "Split",
            "pattern": { "Regex": TIKTOKEN_KIMI_PAT },
            "behavior": "Isolated",
            "invert": false
        },
        "decoder": { "type": "ByteLevel" },
        "model": {
            "type": "BPE",
            "vocab": serde_json::Value::Object(vocab),
            "merges": merges
        }
    });
    Ok(serde_json::to_string(&json)?)
}

/// Canonicalize a source tensor name to the CMF layout the runtime expects, or
/// `None` to skip it. Multimodal wrappers (Qwen3.5) nest the text model under
/// `model.language_model.*`; vision (`*.visual.*`) and the MTP head (`mtp.*`) are
/// dropped — plain greedy decoding is correct without MTP.
pub(crate) fn canon_name(raw: &str) -> Option<String> {
    if raw.contains(".visual.") || raw.starts_with("visual.") {
        return None;
    }
    // MTP head: kept, and renamed to the layout the loader reads. Qwen3.6
    // spells the projection `fc` and its two input norms
    // `pre_fc_norm_{embedding,hidden}`; the loader (written against the
    // DeepSeek spelling) wants `eh_proj`, `enorm`, `hnorm`. Everything
    // under `layers.0.` passes through — including the MoE mlp, which the
    // block carries here rather than a dense one.
    if let Some(rest) = raw.strip_prefix("mtp.").or_else(|| {
        raw.strip_prefix("model.mtp.")
            .or_else(|| raw.split_once(".mtp.").map(|(_, r)| r))
    }) {
        let mapped = match rest {
            "fc.weight" => "eh_proj.weight".to_string(),
            "pre_fc_norm_embedding.weight" => "enorm.weight".to_string(),
            "pre_fc_norm_hidden.weight" => "hnorm.weight".to_string(),
            other => other.to_string(),
        };
        return Some(format!("model.mtp.{mapped}"));
    }
    // Gemma-4 multimodal towers (text tower converts alone).
    for pfx in [
        "model.vision_embedder.",
        "model.embed_audio.",
        "model.embed_vision.",
        // Kimi-K3 vision tower + projector (text tower converts alone).
        "vision_tower.",
        "mm_projector.",
        // Gemma-3n multimodal towers.
        "model.audio_tower.",
        "model.vision_tower.",
        // Qwen3.5-VL vision tower (Ornith-1.5 among them): 333 tensors
        // that would ride into the file as dead weight under their raw
        // names — the text tower converts alone.
        "model.visual.",
    ] {
        if raw.starts_with(pfx) {
            return None;
        }
    }
    for pfx in [
        "model.language_model.",
        "language_model.model.",
        "language_model.",
    ] {
        if let Some(rest) = raw.strip_prefix(pfx) {
            // Re-enter with the wrapper stripped so every later rewrite
            // (Kimi block_sparse_moe, shared_experts, expert_bias) still
            // applies to nested checkpoints.
            return canon_name(&format!("model.{rest}"));
        }
    }
    // ── DeepSeek-V4/V4.1 (`deepseek_v4*`) ─────────────────────────────
    // Its checkpoint drops the `model.` wrapper entirely and spells the
    // blocks `attn`/`ffn`, so the names arrive at top level: `embed`,
    // `head`, `norm`, `layers.N.attn.*`, `layers.N.ffn.*`. Everything
    // below is a rename into the layout the loader already reads; the
    // architecture-specific tensors (compressor, indexer, hyper-
    // connections) keep their spelling under the layer prefix so the
    // engine can find them once those nodes exist.
    if raw == "embed.weight" {
        return Some("model.embed_tokens.weight".into());
    }
    if raw == "head.weight" {
        return Some("lm_head.weight".into());
    }
    if raw == "norm.weight" {
        return Some("model.norm.weight".into());
    }
    // The hyper-connection head tensors are model-global (hc_head_base /
    // _fn / _scale) — pass them through under `model.`.
    if raw.starts_with("hc_head_") {
        return Some(format!("model.{raw}"));
    }
    if let Some(rest) = raw.strip_prefix("layers.") {
        // `layers.N.` + the rest; N is the layer index.
        if let Some((li, tail)) = rest.split_once('.') {
            if li.chars().all(|c| c.is_ascii_digit()) {
                let mapped = match tail {
                    "attn_norm.weight" => "input_layernorm.weight".to_string(),
                    "ffn_norm.weight" => "post_attention_layernorm.weight".to_string(),
                    // Router: weight + the noaux_tc selection bias, which
                    // the loader reads as `mlp.expert_bias`.
                    "ffn.gate.weight" => "mlp.gate.weight".to_string(),
                    "ffn.gate.bias" => "mlp.expert_bias".to_string(),
                    // V4.1's vision-language router carries a second bias
                    // plane; keep it beside the ordinary expert bias so the
                    // multimodal runtime can apply it explicitly.
                    "ffn.gate.bias_vl" => "mlp.expert_bias_vl".to_string(),
                    // Hash-routed layers carry a token-id → expert table
                    // instead of a learned gate.
                    "ffn.gate.tid2eid" => "mlp.tid2eid".to_string(),
                    other => {
                        // experts.E.w{1,3,2} → experts.E.{gate,up,down}_proj
                        // (DeepSeek's w1 = gate, w3 = up, w2 = down), and
                        // the same for the single shared expert.
                        let mut t = other
                            .replace("ffn.shared_experts.", "mlp.shared_expert.")
                            .replace("ffn.experts.", "mlp.experts.");
                        if t.starts_with("mlp.experts.") || t.starts_with("mlp.shared_expert.") {
                            t = t
                                .replace(".w1.weight", ".gate_proj.weight")
                                .replace(".w3.weight", ".up_proj.weight")
                                .replace(".w2.weight", ".down_proj.weight")
                                .replace(".w1.scale", ".gate_proj.scale")
                                .replace(".w3.scale", ".up_proj.scale")
                                .replace(".w2.scale", ".down_proj.scale");
                        }
                        // Attention keeps DeepSeek's own spelling: the
                        // double-LoRA q/o, the compressed KV, the sink,
                        // the compressor and the sparse indexer have no
                        // equivalent in any arch already supported, so
                        // renaming them would invent a layout nothing
                        // reads. `self_attn.` is the prefix every loader
                        // looks under.
                        t = t.replace("attn.", "self_attn.");
                        t
                    }
                };
                return Some(format!("model.layers.{li}.{mapped}"));
            }
        }
    }

    // Kimi (Kimi Linear / Kimi-K3) MoE block: mixtral-style w1/w3/w2
    // experts and a router with the noaux_tc selection bias.
    // `block_sparse_moe` is Kimi-exclusive among supported archs.
    if raw.contains(".block_sparse_moe.") {
        let mut n = raw
            .replace(
                ".block_sparse_moe.gate.e_score_correction_bias",
                ".mlp.expert_bias",
            )
            .replace(".block_sparse_moe.shared_experts.", ".mlp.shared_expert.")
            .replace(".block_sparse_moe.", ".mlp.");
        if n.contains(".mlp.experts.") || n.contains(".mlp.shared_expert.") {
            n = n
                .replace(".w1.weight", ".gate_proj.weight")
                .replace(".w3.weight", ".up_proj.weight")
                .replace(".w2.weight", ".down_proj.weight");
        }
        return Some(n);
    }
    // Laguna stores the router's auxiliary-loss-free selection bias under
    // `experts`, although it belongs to the router mathematically. CMF keeps
    // the canonical bias beside `mlp.gate.weight`.
    if raw.contains(".mlp.shared_experts.") {
        return Some(raw.replace(".mlp.shared_experts.", ".mlp.shared_expert."));
    }
    if raw.ends_with(".mlp.experts.e_score_correction_bias") {
        return Some(raw.replace(".mlp.experts.e_score_correction_bias", ".mlp.expert_bias"));
    }
    // HunYuan dense (Hy-MT2-1.8B/7B, `hunyuan_v1_dense`): the per-head q/k
    // norms are spelled `query_layernorm` / `key_layernorm`; the loader
    // reads `q_norm` / `k_norm`. The ORDER (norm after RoPE) rides in the
    // header flag `qk_norm_after_rope`, not in the names.
    if raw.contains(".self_attn.query_layernorm.") || raw.contains(".self_attn.key_layernorm.") {
        return Some(
            raw.replace(".self_attn.query_layernorm.", ".self_attn.q_norm.")
                .replace(".self_attn.key_layernorm.", ".self_attn.k_norm."),
        );
    }
    // HunYuan hy_v3 MoE (Hy-MT2-30B-A3B): the router is `mlp.router.gate`,
    // the always-on shared expert `mlp.shared_mlp`; `mlp.expert_bias` (the
    // noaux_tc selection bias) is already the canonical spelling.
    if raw.contains(".mlp.router.gate.") || raw.contains(".mlp.shared_mlp.") {
        return Some(
            raw.replace(".mlp.router.gate.", ".mlp.gate.")
                .replace(".mlp.shared_mlp.", ".mlp.shared_expert."),
        );
    }
    Some(lfm2_canon(raw))
}

/// Prism/Bonsai uses the same text canonical layout as the ordinary Qwen
/// reader, but its checkpoint wraps the language model one level deeper and
/// carries a real vision tower.  Keep the generic `canon_name` multimodal
/// policy unchanged (older readers intentionally drop vision); only this
/// explicit architecture path maps the retained tower into `vis.*`.
fn canon_name_for_arch(arch: &ModelArch, raw: &str) -> Option<String> {
    if arch.prism_hadamard.is_none() {
        return canon_name(raw);
    }
    if let Some(rest) = raw.strip_prefix("language_model.") {
        if rest == "lm_head.weight" || rest == "lm_head.bias" {
            return Some(rest.to_string());
        }
        if let Some(rest) = rest.strip_prefix("model.") {
            return canon_name(&format!("model.{rest}"));
        }
    }
    let raw = raw.strip_prefix("model.").unwrap_or(raw);
    if let Some(rest) = raw.strip_prefix("vision_tower.") {
        // The Qwen3.5 tower already follows the runtime's patch_embed /
        // blocks / merger naming; only the source namespace is different.
        if let Some(rest) = rest.strip_prefix("patch_embed.proj.") {
            return Some(format!("vis.patch_embed.{rest}"));
        }
        return Some(format!("vis.{rest}"));
    }
    canon_name(raw)
}

/// Map LFM2 / LFM2-MoE vendor tensor names onto CMF's canonical (Qwen2)
/// layout so the standard loader reads them unchanged. Every substring
/// below is LFM2-exclusive among the supported architectures, so the
/// rewrite never touches another model's tensors. Returns the name
/// verbatim for non-LFM2 checkpoints.
///
///   operator_norm → input_layernorm      ffn_norm → post_attention_layernorm
///   embedding_norm → norm                 self_attn.out_proj → self_attn.o_proj
///   self_attn.{q,k}_layernorm → {q,k}_norm
///   conv.{in_proj,conv,out_proj} → short_conv.*
///   feed_forward.gate/expert_bias/experts.N → mlp.*
///   feed_forward.w1/w3/w2 → mlp.{gate,up,down}_proj (dense + per expert)
fn lfm2_canon(name: &str) -> String {
    let is_lfm2 = name == "model.embedding_norm.weight"
        || name.contains(".operator_norm")
        || name.contains(".ffn_norm")
        || name.contains(".feed_forward.")
        || name.contains(".conv.")
        || name.contains(".self_attn.out_proj")
        || name.contains(".self_attn.q_layernorm")
        || name.contains(".self_attn.k_layernorm");
    if !is_lfm2 {
        return name.to_string();
    }
    if name == "model.embedding_norm.weight" {
        return "model.norm.weight".to_string();
    }
    let mut n = name.to_string();
    n = n.replace(".operator_norm.", ".input_layernorm.");
    n = n.replace(".ffn_norm.", ".post_attention_layernorm.");
    n = n.replace(".self_attn.out_proj.", ".self_attn.o_proj.");
    n = n.replace(".self_attn.q_layernorm.", ".self_attn.q_norm.");
    n = n.replace(".self_attn.k_layernorm.", ".self_attn.k_norm.");
    n = n.replace(".conv.in_proj.", ".short_conv.in_proj.");
    n = n.replace(".conv.out_proj.", ".short_conv.out_proj.");
    n = n.replace(".conv.conv.", ".short_conv.conv.");
    // FFN: router/bias/experts first, then the dense fallback, then the
    // w1/w3/w2 → gate/up/down rename (applies to both mlp.wK and
    // mlp.experts.N.wK). Order matters — the experts substring carries
    // `.feed_forward.` so it must run before the bare `.feed_forward.`.
    n = n.replace(".feed_forward.gate.weight", ".mlp.gate.weight");
    n = n.replace(".feed_forward.expert_bias", ".mlp.expert_bias");
    n = n.replace(".feed_forward.experts.", ".mlp.experts.");
    n = n.replace(".feed_forward.", ".mlp.");
    n = n.replace(".w1.weight", ".gate_proj.weight");
    n = n.replace(".w3.weight", ".up_proj.weight");
    n = n.replace(".w2.weight", ".down_proj.weight");
    n
}

/// Small, noise-sensitive 2-D projections the reference converter keeps at f16
/// (a bit-flip there is costly): the GDN a/b gate projections and MoE routers.
/// Tensors that must not be quantized OR narrowed: lookup tables whose
/// values are indices, not magnitudes. f16 is exact only to 2048, and
/// DeepSeek-V4's table holds expert ids per vocabulary id (129 280 rows).
fn force_f32(name: &str) -> bool {
    name.ends_with(".tid2eid")
        || name.ends_with(".mlp.expert_bias")
        || name.ends_with(".mlp.expert_bias_vl")
        || name.ends_with(".ffn.gate.bias")
        || name.ends_with(".ffn.gate.bias_vl")
}

/// DeepSeek-V4.1's vision tower and aligner are small relative to the text
/// checkpoint but unusually sensitive to matrix quantization. Keep their
/// matrix weights exact in the q4tp profile. The architecture guard is
/// deliberate: other model families may use the same generic prefixes for
/// unrelated tensors, and existing F32 controls are checked first by the
/// emitter below.
fn force_dsv41_vision_f16(arch: &ModelArch, name: &str, shape: &[usize]) -> bool {
    arch.deepseek_v41.is_some()
        && shape.len() == 2
        && name.ends_with(".weight")
        && (name.starts_with("vision.") || name.starts_with("aligner."))
}

fn force_f16(name: &str) -> bool {
    name.ends_with("linear_attn.in_proj_a.weight")
        || name.ends_with("linear_attn.in_proj_b.weight")
        // KDA (Kimi): decay/β/gate low-rank stages and conv taps are tiny
        // and sit on exp/σ paths — keep them exact.
        || name.ends_with("kda_attn.f_a_proj.weight")
        || name.ends_with("kda_attn.f_b_proj.weight")
        || name.ends_with("kda_attn.b_proj.weight")
        || name.ends_with("kda_attn.g_a_proj.weight")
        || name.ends_with("kda_attn.g_b_proj.weight")
        || name.ends_with("_conv1d.weight")
        // Gemma-3n: 4-wide AltUp coefficient mats and the low-rank /
        // per-layer-input projections sit on tanh/gelu gates.
        || name.ends_with("altup.correction_coefs.weight")
        || name.ends_with("altup.prediction_coefs.weight")
        || name.ends_with("altup.modality_router.weight")
        || name.ends_with("laurel.linear_left.weight")
        || name.ends_with("laurel.linear_right.weight")
        || name.ends_with("per_layer_input_gate.weight")
        || name.ends_with(".per_layer_projection.weight")
        || name.ends_with("mlp.gate.weight")
        || name.ends_with("shared_expert_gate.weight")
        || name.ends_with("self_attn.g_proj.weight")
        // Engram's tiny lookup-attention projections stay exact; only its
        // giant embed table is retained as raw FP8 auxiliary bytes.
        || name.ends_with(".engram.q_weight")
        || name.ends_with(".engram.k_weight")
        // Qwen3.8 hyper-connection projections sit directly on sigmoid
        // residual gates.  They are tiny relative to the experts and are
        // deliberately kept at f16 in a q4tp file.
        || (name.contains("hyper_connection")
            && (name.contains("input_mix_weight_") || name.contains("block_inject_weight")))
}

/// Qwen3.8-Flash-Next is unusually sensitive to error in its small recurrent
/// skeleton: every token traverses the same GDN/QSA projections 48 times,
/// while only ten of 512 routed experts are active. Keep the 172B memory wall
/// (experts + PLE lookup) in q4tp/q2tp, but give the always-active skeleton
/// q8_2f.
/// Its input-channel field preserves activation-outlier columns at essentially
/// the same size as q8-row.  This is the usual "K-medium" mixed-precision idea
/// expressed in CMF: the file/profile remains q4tp and grows only a few
/// percent, whereas a uniform four-bit GDN stack loses coherence after a few
/// dozen layers.
fn quant_for_tensor(arch: &ModelArch, name: &str, base: Quant) -> Quant {
    if !matches!(base, Quant::Q4TiledP | Quant::Q2TiledP) {
        return base;
    }
    let vocabulary_edges = name == "model.embed_tokens.weight" || name == "lm_head.weight";
    // Granite 4.2's 100k-token input/output tables are a quality-sensitive
    // boundary around an otherwise ordinary dense stack.  Keeping just those
    // two matrices in q8_2f costs little beside the 8B/30B bodies (and remains
    // worthwhile on 3B), while avoiding a second four-bit error at both the
    // first and final projection.  The full q8_2f profile is unchanged.
    if arch.arch_name.eq_ignore_ascii_case("granite") && vocabulary_edges {
        return Quant::Q8_2f;
    }
    if arch.qwen4_exp.is_none() {
        return base;
    }
    let recurrent_skeleton = name.contains(".linear_attn.")
        || name.contains(".self_attn.")
        || (name.contains(".ple.")
            && (name.ends_with("key_proj.weight") || name.ends_with("value_proj.weight")));
    if recurrent_skeleton || vocabulary_edges {
        Quant::Q8_2f
    } else {
        base
    }
}

/// Quantization choice for 2-D weight matrices.
#[derive(Clone, Copy, PartialEq, Debug)]
pub(crate) enum Quant {
    Q8Row,
    Q8_2f,
    Q4Block,
    F16,
    /// Grouped variable-bit (per-row 3–8 bit, water-filled by row amplitude).
    Vbit,
    Q4Tiled,
    /// q4 tiled with PREDICTED scales: same nibbles, but the per-tile f16
    /// scale becomes a 5-bit rung on a per-row ladder — 7.3% off a q4t file
    /// for 1.14% RMS weight perturbation (q4t's own error vs fp16 is ~10%).
    Q4TiledP,
    /// 2-bit tiles on the q4tp ladder (Escha-W2 size class). As a whole-model
    /// profile the converter applies it to MoE `gate_up` experts only and
    /// keeps `down` experts and the skeleton at q4tp — the 2/4 split that
    /// mirrors Escha's 2/3-bit choice.
    Q2TiledP,
    /// Existing dtype16 Q2TP payload with the explicit Prism affine operator
    /// `(c - 1.0) * s` enabled by header metadata.
    Q2TiledPAffine,
    /// 1-bit binary (explicit opt-in): for 1-bit-TRAINED models
    /// (Bonsai / BitNet class), where per-group weights already sit on
    /// two levels ±s and the encoding is (near-)lossless. As PTQ of a
    /// normal checkpoint this destroys quality — never a default.
    Q1,
    /// 1-bit PTQ of a NORMAL checkpoint via error diffusion (перетекание):
    /// same on-disk `Q1` tile, but the encoder carries each weight's sign
    /// residual forward so the row sum survives binarization. Training-free;
    /// pair with `cortiq skill bake` (FCD) on the tail layers to recover
    /// quality. Bit-identical to `q1` on a genuinely 1-bit model.
    Q1p,
    /// 1-bit PTQ with an outlier mask (`Q1S` dtype): keeps the heavy tail
    /// (`CMF_Q1S_KEEP` of weights by |value|, default 1%) at full f16 in a
    /// sparse overlay, binarizes the rest with error diffusion. The mask
    /// lever of the error-feedback path — what lets a NORMAL
    /// checkpoint survive 1-bit.
    Q1s,
    Q1t,
}

/// Quantize a 2-D matrix `[out_dim, in_dim]` per the chosen scheme.
pub(crate) fn quantize_2d(
    quant: Quant,
    vals: &[f32],
    out_dim: usize,
    in_dim: usize,
) -> (TensorDtype, Vec<u8>) {
    match quant {
        Quant::Q8Row => (TensorDtype::Q8Row, encode_q8_row(vals, out_dim, in_dim)),
        Quant::Q8_2f => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q4Block => (TensorDtype::Q4Block, encode_q4_block(vals)),
        Quant::F16 => (TensorDtype::F16, encode_f16(vals)),
        // v-bit needs the input dim to be a multiple of the group size; other
        // shapes fall back to the two-field q8_2f (best equal-size alternative).
        Quant::Q4Tiled if in_dim % GROUP_SIZE == 0 => {
            (TensorDtype::Q4Tiled, encode_q4_tiled(vals, out_dim, in_dim))
        }
        Quant::Q4Tiled => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q4TiledP if in_dim % GROUP_SIZE == 0 => {
            (TensorDtype::Q4TiledP, encode_q4tp(vals, out_dim, in_dim))
        }
        Quant::Q4TiledP => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q2TiledP if in_dim % GROUP_SIZE == 0 => {
            (TensorDtype::Q2TiledP, encode_q2tp(vals, out_dim, in_dim))
        }
        Quant::Q2TiledP => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q2TiledPAffine if in_dim % GROUP_SIZE == 0 => {
            (TensorDtype::Q2TiledP, encode_q2tp(vals, out_dim, in_dim))
        }
        Quant::Q2TiledPAffine => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Vbit if in_dim % GROUP_SIZE == 0 => {
            (TensorDtype::VbitRo, encode_vbit_ro(vals, out_dim, in_dim))
        }
        Quant::Vbit => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q1 if in_dim % GROUP_SIZE == 0 => {
            (TensorDtype::Q1, encode_q1(vals, out_dim, in_dim))
        }
        Quant::Q1 => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q1p if in_dim % GROUP_SIZE == 0 => {
            (TensorDtype::Q1, encode_q1_ef(vals, out_dim, in_dim))
        }
        Quant::Q1p => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q1s if in_dim % GROUP_SIZE == 0 => (
            TensorDtype::Q1S,
            encode_q1s(vals, out_dim, in_dim, q1s_keep_frac()),
        ),
        Quant::Q1s => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
        Quant::Q1t if in_dim % GROUP_SIZE == 0 => (
            TensorDtype::Q1T,
            crate::gptq::quantize_q1t(vals, out_dim, in_dim, &vec![1.0; in_dim], 0.0),
        ),
        Quant::Q1t => (TensorDtype::Q8_2f, encode_q8_2f(vals, out_dim, in_dim)),
    }
}

pub(crate) fn parse_quant(s: &str) -> anyhow::Result<Quant> {
    Ok(match s.to_ascii_lowercase().as_str() {
        "q8" | "q8_row" | "q8row" => Quant::Q8Row,
        "q8_2f" | "q82f" | "q8f" => Quant::Q8_2f,
        "q4" | "q4_block" | "q4block" => Quant::Q4Block,
        "f16" | "fp16" => Quant::F16,
        "vbit" | "v_bit" => Quant::Vbit,
        "q4t" | "q4_tiled" => Quant::Q4Tiled,
        "q4tp" | "q4t_pred" => Quant::Q4TiledP,
        "q2tp" | "q2t_pred" => Quant::Q2TiledP,
        "q2tp_affine" | "q2tp-affine" | "q2t_affine" => Quant::Q2TiledPAffine,
        "q1" => Quant::Q1,
        "q1p" | "q1_ptq" => Quant::Q1p,
        "q1s" | "q1_mask" => Quant::Q1s,
        "q1t" | "q1_ternary" => Quant::Q1t,
        other => anyhow::bail!(
            "unknown quant '{other}' (use q8, q8_2f, q4, q4t, q4tp, q2tp, q2tp_affine, f16, vbit, q1, q1p, q1s, or q1t)"
        ),
    })
}

pub(crate) fn quant_name(quant: Quant) -> &'static str {
    match quant {
        Quant::Q8Row => "q8",
        Quant::Q8_2f => "q8_2f",
        Quant::Q4Block => "q4",
        Quant::F16 => "f16",
        Quant::Vbit => "vbit",
        Quant::Q4Tiled => "q4t",
        Quant::Q4TiledP => "q4tp",
        Quant::Q2TiledP => "q2tp",
        Quant::Q2TiledPAffine => "q2tp_affine",
        Quant::Q1 => "q1",
        Quant::Q1p => "q1p",
        Quant::Q1s => "q1s",
        Quant::Q1t => "q1t",
    }
}

/// Quantization profile used by the converter's one-pass multi-output path.
/// `Q2TiledP` is a logical profile: the file keeps the normal q4tp layout for
/// the skeleton/down planes while putting gate/up expert (or dense FFN) planes
/// on q2tp. Keeping this decision here means every requested output sees the
/// same decoded source tensor and only the encoder differs.
fn profile_quant(arch: &ModelArch, requested: Quant, name: &str) -> Quant {
    if matches!(requested, Quant::Q2TiledPAffine) {
        // Prism weights are all trained ternary projections in one rotated
        // basis; never apply q2tp's mixed expert-only policy.
        return requested;
    }
    let gu = requested;
    let base = if matches!(requested, Quant::Q2TiledP) {
        Quant::Q4TiledP
    } else {
        requested
    };
    let expert_gu = q2tp_expert_gate_or_up(name)
        || (matches!(requested, Quant::Q2TiledP)
            && arch.moe.is_none()
            && q2tp_dense_gate_or_up(name));
    let q = if expert_gu { gu } else { base };
    quant_for_tensor(arch, name, q)
}

#[derive(Clone, Copy)]
enum EmitMode {
    /// Apply the normal per-name profile policy (including q2tp gate/up).
    Auto,
    /// Keep this tensor in exact f16 regardless of profile.
    F16,
    /// Keep this tensor in exact f32 regardless of profile.
    F32,
}

/// Encode one canonical tensor into each active output profile. The source
/// values are borrowed and are therefore decoded exactly once per source
/// tensor; each profile owns its independent encoded payload and directory
/// record. `active` is false for outputs that already checkpointed this shard.
fn emit_profiled_tensor(
    batches: &mut [Vec<TensorSpec>],
    profiles: &[Quant],
    active: &[bool],
    arch: &ModelArch,
    name: &str,
    shape: &[usize],
    vals: &[f32],
    mode: EmitMode,
) {
    debug_assert_eq!(batches.len(), profiles.len());
    debug_assert_eq!(active.len(), profiles.len());
    let numel: usize = shape.iter().product();
    for ((batch, &requested), &is_active) in batches.iter_mut().zip(profiles).zip(active) {
        if !is_active {
            continue;
        }
        let (dtype, data) = match mode {
            EmitMode::F32 => (
                TensorDtype::F32,
                vals.iter().flat_map(|v| v.to_le_bytes()).collect(),
            ),
            EmitMode::F16 => (TensorDtype::F16, encode_f16(vals)),
            EmitMode::Auto => {
                if force_f32(name) {
                    (
                        TensorDtype::F32,
                        vals.iter().flat_map(|v| v.to_le_bytes()).collect(),
                    )
                } else if force_dsv41_vision_f16(arch, name, shape) {
                    (TensorDtype::F16, encode_f16(vals))
                } else if shape.len() != 2
                    || numel < GROUP_SIZE
                    || force_f16(name)
                    // Prism's Qwen3 vision tower is retained losslessly.  Its
                    // qwen3vis runtime expects f16/f32 matrices, not the
                    // language-side q2tp transform.
                    || name.starts_with("vis.")
                {
                    (TensorDtype::F16, encode_f16(vals))
                } else {
                    quantize_2d(
                        profile_quant(arch, requested, name),
                        vals,
                        shape[0],
                        shape[1],
                    )
                }
            }
        };
        batch.push(TensorSpec {
            name: name.to_string(),
            dtype,
            shape: shape.to_vec(),
            data,
        });
    }
}

/// q8_row: `[int8 : out·in][f16 : out]` (validated layout, matches the reader).
pub(crate) fn encode_q8_row(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    let mut q = Vec::with_capacity(out_dim * in_dim);
    let mut scales = Vec::with_capacity(out_dim * 2);
    for o in 0..out_dim {
        let row = &vals[o * in_dim..(o + 1) * in_dim];
        let absmax = row.iter().fold(0f32, |m, v| m.max(v.abs()));
        let scale = f16_scale(absmax / 127.0);
        for &v in row {
            // round-half-to-even matches numpy's np.round → byte-identical weights.
            q.push((v / scale).round_ties_even().clamp(-128.0, 127.0) as i8 as u8);
        }
        scales.extend_from_slice(&f32_to_f16(scale).to_le_bytes());
    }
    q.extend_from_slice(&scales);
    q
}

/// q4_block: groups of 32 over the flattened tensor, `[u8 packed][f16 scales]`.
fn encode_q4_block(vals: &[f32]) -> Vec<u8> {
    let n_groups = vals.len().div_ceil(GROUP_SIZE);
    let mut padded = vals.to_vec();
    padded.resize(n_groups * GROUP_SIZE, 0.0);
    let mut packed = Vec::with_capacity(n_groups * 16);
    let mut scales = Vec::with_capacity(n_groups * 2);
    for g in 0..n_groups {
        let group = &padded[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
        let absmax = group.iter().fold(0f32, |m, v| m.max(v.abs()));
        let scale = f16_scale(absmax / 7.0);
        for k in 0..16 {
            let q0 = ((group[k * 2] / scale).round_ties_even().clamp(-8.0, 7.0) as i8 + 8) as u8;
            let q1 = ((group[k * 2 + 1] / scale)
                .round_ties_even()
                .clamp(-8.0, 7.0) as i8
                + 8) as u8;
            packed.push((q0 & 0x0F) | (q1 << 4));
        }
        scales.extend_from_slice(&f32_to_f16(scale).to_le_bytes());
    }
    packed.extend_from_slice(&scales);
    packed
}

/// q8_2f (row/column-scale): `[int8: out·in][f16 row_scale: out][f16 col: in]`.
/// `col[i]` = RMS over rows (absorbs outlier input channels); each row is int8
/// over the residual normalized by col. Dequant: `w = q·scale[o]·col[i]`.
/// Recovers most of the q8→f16 quality gap at the same size.
/// q4_tiled (§4.3): the same 4-bit values/scales as q4_block, laid
/// out as one sequential stream of 18-byte tiles
/// `[f16 scale][16B nibbles]` per 32-group — measured x1.66 (ARM) /
/// x1.13 (AVX2) at kernel level over the split layout.
pub(crate) fn encode_q4_tiled(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    debug_assert_eq!(vals.len(), out_dim * in_dim);
    debug_assert_eq!(in_dim % GROUP_SIZE, 0);
    let legacy = encode_q4_block(vals);
    let n_groups = vals.len() / GROUP_SIZE;
    let (packed, scales) = legacy.split_at(n_groups * 16);
    let mut out = Vec::with_capacity(n_groups * 18);
    for g in 0..n_groups {
        out.extend_from_slice(&scales[g * 2..g * 2 + 2]);
        out.extend_from_slice(&packed[g * 16..(g + 1) * 16]);
    }
    out
}

/// q4tp (§4.10): the same nibbles as `q4_tiled`, but each tile's scale is a
/// 5-bit rung on a per-row geometric ladder — `[nibbles][row (f16 lo, f16
/// step)][5-bit codes]`, 4.17 bits/weight against 4.50.
///
/// Two details carry the accuracy. The row's `lo`/`step` are rounded to f16
/// FIRST and the codes are then chosen against those rounded values, so the
/// rounding of `lo` is absorbed by the code instead of stacking on top of it.
/// And the nibbles are quantized against the RECONSTRUCTED scale, not the
/// exact per-tile absmax — otherwise encoder and reader disagree, which is
/// the same trap `f16_scale` exists to avoid.
///
/// Quantizing the same fp32 weights both ways, q4tp's error against the source
/// is within 0.1% of q4t's at the median within-row scale spread measured on
/// KAT-Coder-V2.5 (1.27 in log2), 0.3% at its 90th percentile — a coarser scale
/// costs almost nothing because the nibbles re-round against it. Rounding the
/// code to nearest beats rounding up (1.19% vs 1.60% RMS against q4t's output):
/// letting the top tile clip a nibble costs less than coarsening the whole row.
/// `q2tp`: the `q4tp` ladder with a 2-bit weight plane (8 B per 32-group).
/// Levels are (c − 1.5)·s, so the group scale fits absmax/1.5. Built for
/// transcoding 2-bit-class checkpoints (Escha-W2) where the source already
/// paid the big quantization cost — and for MoE experts generally.
/// How many threads the row encoders use. `CMF_ENCODE_THREADS` overrides it,
/// which is also how the parity test pins a single thread.
pub(crate) fn encode_threads() -> usize {
    std::env::var("CMF_ENCODE_THREADS")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .filter(|v| *v > 0)
        .unwrap_or_else(|| {
            std::thread::available_parallelism()
                .map(|v| v.get())
                .unwrap_or(1)
        })
}

/// Run a per-row encoder across the machine's cores.
///
/// Every tiled layout here writes three planes indexed by row at a fixed
/// stride, and no row reads another, so splitting on rows is exact — the
/// bytes are identical to the serial loop, which the parity test pins.
///
/// It is worth the plumbing: quantizing a 300B MoE is hours of arithmetic,
/// and on a 48-core box the serial loop used one of them.
fn encode_rows_parallel(
    out_dim: usize,
    strides: [usize; 3],
    planes: [&mut [u8]; 3],
    row: &(dyn Fn(usize, &mut [u8], &mut [u8], &mut [u8]) + Sync),
) {
    let [s0, s1, s2] = strides;
    let [p0, p1, p2] = planes;
    let threads = encode_threads().min(out_dim.max(1)).max(1);
    if threads == 1 {
        for (i, ((a, b), c)) in p0
            .chunks_mut(s0)
            .zip(p1.chunks_mut(s1))
            .zip(p2.chunks_mut(s2))
            .enumerate()
        {
            row(i, a, b, c);
        }
        return;
    }
    let per = out_dim.div_ceil(threads);
    std::thread::scope(|sc| {
        for (ti, ((a, b), c)) in p0
            .chunks_mut(per * s0)
            .zip(p1.chunks_mut(per * s1))
            .zip(p2.chunks_mut(per * s2))
            .enumerate()
        {
            sc.spawn(move || {
                let r0 = ti * per;
                for (i, ((aa, bb), cc)) in a
                    .chunks_mut(s0)
                    .zip(b.chunks_mut(s1))
                    .zip(c.chunks_mut(s2))
                    .enumerate()
                {
                    row(r0 + i, aa, bb, cc);
                }
            });
        }
    });
}

/// The rung search can be turned off (`CMF_Q2TP_SEARCH=0`) so its value is
/// measured rather than assumed. Read once per tensor — not cached for the
/// process, or an A/B inside one test binary silently compares an arm with
/// itself.
fn q2tp_search() -> bool {
    std::env::var("CMF_Q2TP_SEARCH")
        .map(|v| v != "0")
        .unwrap_or(true)
}

pub(crate) fn encode_q2tp(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    debug_assert_eq!(vals.len(), out_dim * in_dim);
    debug_assert_eq!(in_dim % GROUP_SIZE, 0);
    let gpr = in_dim / GROUP_SIZE;
    let stride = q4tp_code_stride(gpr);
    let mut chunks = vec![0u8; out_dim * gpr * Q2TP_CHUNK];
    let mut params = vec![0u8; out_dim * 4];
    let mut codes = vec![0u8; out_dim * stride];
    let search = q2tp_search();

    encode_rows_parallel(
        out_dim,
        [gpr * Q2TP_CHUNK, 4, stride],
        [&mut chunks, &mut params, &mut codes],
        &|r, chunks_row, params_row, codes_row| {
            let mut lg = vec![0f32; gpr];
            let mut dead = vec![false; gpr];

            let row = &vals[r * in_dim..(r + 1) * in_dim];
            let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
            for g in 0..gpr {
                let tile = &row[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
                let absmax = tile.iter().fold(0f32, |m, v| m.max(v.abs()));
                dead[g] = absmax == 0.0;
                lg[g] = f16_scale(absmax / 1.5).log2();
                if !dead[g] {
                    lo = lo.min(lg[g]);
                    hi = hi.max(lg[g]);
                }
            }
            if !lo.is_finite() {
                lo = lg[0];
                hi = lo;
            }
            let lo_h = f32_to_f16(lo);
            let lo_r = f16_to_f32(lo_h);
            // The ladder spans lo..hi, where hi is the largest group scale in the
            // row. One loud group therefore stretches the ladder and coarsens the
            // step for all the quiet ones. Try shorter ladders too and keep the
            // one whose whole row reconstructs best — the same argument as the
            // per-group search, one level up.
            let ladder_for = |top: f32, params: &mut [u8]| -> [f32; 32] {
                let span = (top - lo_r).max(0.0);
                let mut st_h = f32_to_f16(span / Q2TP_LMAX as f32);
                for _ in 0..64 {
                    let st = f16_to_f32(st_h);
                    if st > 0.0 && lo_r + Q2TP_LMAX as f32 * st >= top {
                        break;
                    }
                    st_h += 1;
                }
                params[0..2].copy_from_slice(&lo_h.to_le_bytes());
                params[2..4].copy_from_slice(&st_h.to_le_bytes());
                q2tp_ladder(params, 0)
            };
            let mut tab = ladder_for(hi, params_row);
            if search && hi > lo_r {
                // Candidate tops: the full range, then progressively tighter.
                let mut best = (f32::INFINITY, hi);
                for frac in [1.0f32, 0.9, 0.8, 0.7] {
                    let top = lo_r + (hi - lo_r) * frac;
                    let mut probe = [0u8; 4];
                    let t = ladder_for(top, &mut probe);
                    let mut err = 0.0f32;
                    for g in 0..gpr {
                        if dead[g] {
                            continue;
                        }
                        let tile = &row[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
                        // Probe around the rung this ladder would nominally pick
                        // rather than all 31: the best is always adjacent, and
                        // scanning the ladder end to end costs 8x for nothing.
                        let stc = f16_to_f32(u16::from_le_bytes([probe[2], probe[3]]));
                        let nom = if stc > 0.0 {
                            1 + ((lg[g] - lo_r) / stc)
                                .round_ties_even()
                                .clamp(0.0, Q2TP_LMAX as f32)
                                as usize
                        } else {
                            1
                        };
                        let mut ge = f32::INFINITY;
                        for cand in nom.saturating_sub(2).max(1)..=(nom + 2).min(Q2TP_LMAX + 1) {
                            let sc = t[cand];
                            if sc <= 0.0 {
                                continue;
                            }
                            let iv = 1.0 / sc;
                            let mut e = 0.0f32;
                            for &wv in tile {
                                let q = (wv * iv + 1.5).round_ties_even().clamp(0.0, 3.0);
                                let d = wv - (q - 1.5) * sc;
                                e += d * d;
                            }
                            ge = ge.min(e);
                        }
                        err += ge;
                    }
                    if err < best.0 {
                        best = (err, top);
                    }
                }
                tab = ladder_for(best.1, params_row);
            }
            let st = f16_to_f32(u16::from_le_bytes([params_row[2], params_row[3]]));
            let crow = &mut *codes_row;
            for g in 0..gpr {
                // Rung 0 is the exact zero; live groups start at 1.
                let nominal = if dead[g] {
                    0
                } else if st <= 0.0 {
                    1
                } else {
                    1 + ((lg[g] - lo_r) / st)
                        .round_ties_even()
                        .clamp(0.0, Q2TP_LMAX as f32) as usize
                };
                // The nominal rung comes from absmax/1.5, which pins the outer
                // level to the largest weight — that minimises the WORST error,
                // not the mean one, and with only four levels the difference is
                // large. Try the neighbouring rungs and keep whichever
                // reconstructs the group best. Costs encode time and nothing
                // else: the layout, the decoder and the kernels are unchanged.
                let tile = &row[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
                let c = if nominal == 0 || !search {
                    nominal
                } else {
                    let mut best = (f32::INFINITY, nominal);
                    for cand in nominal.saturating_sub(2).max(1)..=(nominal + 1).min(Q2TP_LMAX + 1)
                    {
                        let s = tab[cand];
                        if s <= 0.0 {
                            continue;
                        }
                        let inv = 1.0 / s;
                        let mut err = 0.0f32;
                        for &w in tile {
                            let q = (w * inv + 1.5).round_ties_even().clamp(0.0, 3.0);
                            let d = w - (q - 1.5) * s;
                            err += d * d;
                        }
                        if err < best.0 {
                            best = (err, cand);
                        }
                    }
                    best.1
                };
                q4tp_put_code(crow, g, c);
                let inv = if tab[c] > 0.0 { 1.0 / tab[c] } else { 0.0 };
                let dst = &mut chunks_row[g * Q2TP_CHUNK..(g + 1) * Q2TP_CHUNK];
                for (k, d) in dst.iter_mut().enumerate() {
                    let mut b = 0u8;
                    for j in 0..4 {
                        // (c − 1.5)·s: quantize w/s + 1.5 onto 0..=3.
                        let q = (tile[k * 4 + j] * inv + 1.5)
                            .round_ties_even()
                            .clamp(0.0, 3.0) as u8;
                        b |= q << (2 * j);
                    }
                    *d = b;
                }
            }
        },
    );
    chunks.extend_from_slice(&params);
    chunks.extend_from_slice(&codes);
    chunks
}

pub(crate) fn encode_q4tp(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    debug_assert_eq!(vals.len(), out_dim * in_dim);
    debug_assert_eq!(in_dim % GROUP_SIZE, 0);
    let gpr = in_dim / GROUP_SIZE;
    let stride = q4tp_code_stride(gpr);
    let mut nib = vec![0u8; out_dim * gpr * Q4TP_NIB];
    let mut params = vec![0u8; out_dim * 4];
    let mut codes = vec![0u8; out_dim * stride];

    let search = q2tp_search();

    encode_rows_parallel(
        out_dim,
        [gpr * Q4TP_NIB, 4, stride],
        [&mut nib, &mut params, &mut codes],
        &|r, nib_row, params_row, codes_row| {
            let mut lg = vec![0f32; gpr];
            let mut dead = vec![false; gpr];

            let row = &vals[r * in_dim..(r + 1) * in_dim];
            let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
            for g in 0..gpr {
                let tile = &row[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
                let absmax = tile.iter().fold(0f32, |m, v| m.max(v.abs()));
                // An all-zero tile dequantizes to zero whatever its scale, so keep
                // it out of the row's range — otherwise `f16_scale`'s tiny floor
                // stretches the ladder and coarsens every live tile in the row.
                dead[g] = absmax == 0.0;
                lg[g] = f16_scale(absmax / 7.0).log2();
                if !dead[g] {
                    lo = lo.min(lg[g]);
                    hi = hi.max(lg[g]);
                }
            }
            if !lo.is_finite() {
                lo = lg[0];
                hi = lo;
            }

            let lo_h = f32_to_f16(lo);
            let lo_r = f16_to_f32(lo_h);
            let span = (hi - lo_r).max(0.0);
            let mut st_h = f32_to_f16(span / Q4TP_LMAX as f32);
            // Round-to-nearest on `step` can land just short of `hi`; walk up by
            // single ULPs until rung 31 provably covers the row's top scale.
            for _ in 0..64 {
                let st = f16_to_f32(st_h);
                if st > 0.0 && lo_r + Q4TP_LMAX as f32 * st >= hi {
                    break;
                }
                st_h += 1;
            }
            params_row[0..2].copy_from_slice(&lo_h.to_le_bytes());
            params_row[2..4].copy_from_slice(&st_h.to_le_bytes());

            let st = f16_to_f32(st_h);
            let tab = q4tp_ladder(params_row, 0);
            let crow = &mut *codes_row;
            for g in 0..gpr {
                let nominal = if dead[g] || st <= 0.0 {
                    0
                } else {
                    ((lg[g] - lo_r) / st)
                        .round_ties_even()
                        .clamp(0.0, Q4TP_LMAX as f32) as usize
                };
                let tile = &row[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
                // Same reasoning as q2tp: absmax fixes the outer level and one
                // outlier coarsens the group behind it. Sixteen levels forgive
                // more than four, so the win is smaller — but it is measured.
                let c = if dead[g] || st <= 0.0 || !search {
                    nominal
                } else {
                    let mut best = (f32::INFINITY, nominal);
                    for cand in nominal.saturating_sub(2)..=(nominal + 1).min(Q4TP_LMAX) {
                        let sc = tab[cand];
                        if sc <= 0.0 {
                            continue;
                        }
                        let iv = 1.0 / sc;
                        let mut err = 0.0f32;
                        for &wv in tile {
                            let q = (wv * iv).round_ties_even().clamp(-8.0, 7.0);
                            let d = wv - q * sc;
                            err += d * d;
                        }
                        if err < best.0 {
                            best = (err, cand);
                        }
                    }
                    best.1
                };
                q4tp_put_code(crow, g, c);
                let inv = if tab[c] > 0.0 { 1.0 / tab[c] } else { 0.0 };
                let dst = &mut nib_row[g * Q4TP_NIB..(g + 1) * Q4TP_NIB];
                for k in 0..16 {
                    let q0 =
                        ((tile[k * 2] * inv).round_ties_even().clamp(-8.0, 7.0) as i8 + 8) as u8;
                    let q1 = ((tile[k * 2 + 1] * inv).round_ties_even().clamp(-8.0, 7.0) as i8 + 8)
                        as u8;
                    dst[k] = (q0 & 0x0F) | (q1 << 4);
                }
            }
        },
    );

    nib.extend_from_slice(&params);
    nib.extend_from_slice(&codes);
    nib
}

/// Re-encode f32 values into an EXISTING tensor's dtype — the offline passes
/// (AWNP) rewrite weights and must put them back in the layout the file
/// already uses, not pick a new one.
pub(crate) fn encode_for(dtype: TensorDtype, vals: &[f32], rows: usize, cols: usize) -> Vec<u8> {
    match dtype {
        TensorDtype::Q4Tiled => encode_q4_tiled(vals, rows, cols),
        TensorDtype::Q4TiledP => encode_q4tp(vals, rows, cols),
        TensorDtype::Q4Block => encode_q4_block(vals),
        TensorDtype::Q8Row => encode_q8_row(vals, rows, cols),
        TensorDtype::Q8_2f => encode_q8_2f(vals, rows, cols),
        _ => encode_f16(vals),
    }
}

/// q1 (dtype 12): per 32-group tile `[f16 scale][4B sign bits]`,
/// bit k of byte j (LSB-first) = weight j·8+k; value = s·(2·bit−1).
/// Scale = group mean |v| — the L2-optimal binary level; for a
/// 1-bit-TRAINED model whose group weights already sit on ±s this
/// recovers the level exactly (encoding is lossless up to f16 range).
fn encode_q1(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    debug_assert_eq!(vals.len(), out_dim * in_dim);
    debug_assert_eq!(in_dim % GROUP_SIZE, 0);
    let n_groups = vals.len() / GROUP_SIZE;
    let mut out = Vec::with_capacity(n_groups * 6);
    for g in 0..n_groups {
        let grp = &vals[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
        let mean_abs = grp.iter().map(|v| v.abs()).sum::<f32>() / GROUP_SIZE as f32;
        let s = f16_scale(mean_abs);
        out.extend_from_slice(&f32_to_f16(s).to_le_bytes());
        for j in 0..GROUP_SIZE / 8 {
            let mut byte = 0u8;
            for k in 0..8 {
                if grp[j * 8 + k] >= 0.0 {
                    byte |= 1 << k;
                }
            }
            out.push(byte);
        }
    }
    out
}

/// Error-diffusion ("перетекание") q1 encoder — the training-free PTQ path
/// for a NON-1-bit-trained model. Naïve q1 throws away every weight's
/// magnitude, keeping only its sign against a shared group scale; for a
/// normal checkpoint that is catastrophic. Here the per-weight rounding
/// residual `w − ŵ` is carried FORWARD along the row's input dimension and
/// folded into the next sign decision (`sign(w + carry)`), so the row's
/// running sum — hence its contribution to the dot product for the
/// slowly-varying part of the activation — is preserved rather than
/// discarded. Same on-disk `Q1` tile as `encode_q1` (reuses the kernel and
/// GPU path unchanged), and bit-identical to it on a genuinely 1-bit model
/// (near-constant |w| per group ⇒ `carry ≈ 0` ⇒ the sign never flips).
/// The carry resets at each row start (each output is an independent sum).
fn encode_q1_ef(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    debug_assert_eq!(vals.len(), out_dim * in_dim);
    debug_assert_eq!(in_dim % GROUP_SIZE, 0);
    let groups_per_row = in_dim / GROUP_SIZE;
    let n_groups = vals.len() / GROUP_SIZE;
    let mut out = Vec::with_capacity(n_groups * 6);
    let mut carry = 0.0f32;
    for g in 0..n_groups {
        if g % groups_per_row == 0 {
            carry = 0.0; // new output row: its dot product starts fresh
        }
        let grp = &vals[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
        let mean_abs = grp.iter().map(|v| v.abs()).sum::<f32>() / GROUP_SIZE as f32;
        let s = f16_scale(mean_abs);
        out.extend_from_slice(&f32_to_f16(s).to_le_bytes());
        for j in 0..GROUP_SIZE / 8 {
            let mut byte = 0u8;
            for k in 0..8 {
                let w = grp[j * 8 + k];
                let v = w + carry;
                let bit = v >= 0.0;
                if bit {
                    byte |= 1 << k;
                }
                carry = v - if bit { s } else { -s };
            }
            out.push(byte);
        }
    }
    out
}

/// Fraction of weights the `q1s` mask keeps at full precision (the outlier
/// budget). `CMF_Q1S_KEEP` overrides; default 1%. Clamped to [0, 25%].
fn q1s_keep_frac() -> f32 {
    std::env::var("CMF_Q1S_KEEP")
        .ok()
        .and_then(|v| v.parse::<f32>().ok())
        .unwrap_or(0.01)
        .clamp(0.0, 0.25)
}

/// 1-bit PTQ with an outlier mask (Stage 2a of the error-feedback
/// path). Keeps the top `keep_frac` of weights by |value| — the heavy tail
/// a normal checkpoint carries — at full f16 precision in a sparse overlay,
/// and binarizes the rest with the error-diffusion base, EXCLUDING the
/// outliers from each group's shared ±s scale (an outlier must not inflate
/// the level the bulk is quantized against). This is the |W| field of the
/// two-field mask; the activation field (`|W|·RMS(x)`) and the covariance
/// fold `Σ_PS·Σ_SS⁻¹` come from the calibration path on top of this.
fn encode_q1s(vals: &[f32], out_dim: usize, in_dim: usize, keep_frac: f32) -> Vec<u8> {
    debug_assert_eq!(vals.len(), out_dim * in_dim);
    debug_assert_eq!(in_dim % GROUP_SIZE, 0);
    let n = vals.len();
    let n_out = (((n as f32) * keep_frac).round() as usize).min(n);
    // Outlier threshold via nth_element (O(n)): the (n − n_out)-th smallest
    // |w| — weights at or above it are the kept heavy tail.
    let threshold = if n_out == 0 {
        f32::INFINITY
    } else {
        let mut absv: Vec<f32> = vals.iter().map(|v| v.abs()).collect();
        let k = n - n_out;
        absv.select_nth_unstable_by(k, |a, b| a.partial_cmp(b).unwrap());
        absv[k]
    };
    let is_out: Vec<bool> = (0..n)
        .map(|i| n_out > 0 && vals[i].abs() >= threshold)
        .collect();

    let groups_per_row = in_dim / GROUP_SIZE;
    let n_groups = n / GROUP_SIZE;
    let n_out_actual = is_out.iter().filter(|&&o| o).count();
    let mut out = Vec::with_capacity(n_groups * 6 + 4 + n_out_actual * 6);
    let mut carry = 0.0f32;
    for g in 0..n_groups {
        if g % groups_per_row == 0 {
            carry = 0.0;
        }
        let base = g * GROUP_SIZE;
        // Scale = mean |w| over the NON-outlier weights of the group.
        let mut sum = 0.0f32;
        let mut cnt = 0usize;
        for j in 0..GROUP_SIZE {
            if !is_out[base + j] {
                sum += vals[base + j].abs();
                cnt += 1;
            }
        }
        let s = f16_scale(if cnt > 0 { sum / cnt as f32 } else { 0.0 });
        out.extend_from_slice(&f32_to_f16(s).to_le_bytes());
        for jb in 0..GROUP_SIZE / 8 {
            let mut byte = 0u8;
            for k in 0..8 {
                let i = base + jb * 8 + k;
                if is_out[i] {
                    // Outlier: bit is only a sign hint (the overlay restores
                    // the exact value); it carries no error forward.
                    if vals[i] >= 0.0 {
                        byte |= 1 << k;
                    }
                } else {
                    let v = vals[i] + carry;
                    let bit = v >= 0.0;
                    if bit {
                        byte |= 1 << k;
                    }
                    carry = v - if bit { s } else { -s };
                }
            }
            out.push(byte);
        }
    }
    // Sparse outlier section: [u32 count][count × (u32 index, f16 value)].
    out.extend_from_slice(&(n_out_actual as u32).to_le_bytes());
    for (i, &o) in is_out.iter().enumerate() {
        if o {
            out.extend_from_slice(&(i as u32).to_le_bytes());
            out.extend_from_slice(&f32_to_f16(vals[i]).to_le_bytes());
        }
    }
    out
}

/// Exact ternary re-encode for weights that ALREADY sit on `{−s, 0, +s}`
/// within every 32-group — a ternary-trained checkpoint such as the STQ1_0
/// GGUF of Hy-MT2-1.8B (AngelSlim 1.25-bit). Per group: scale = the
/// group's max |w| (an f16 in the source, so it survives the round trip),
/// base-3 codes, and an EMPTY outlier overlay. `dequant_q1t` reproduces
/// the input bit for bit; no calibration, no requantization.
pub(crate) fn encode_q1t_exact(
    vals: &[f32],
    out_dim: usize,
    in_dim: usize,
) -> anyhow::Result<Vec<u8>> {
    use cortiq_core::quant::{GROUP_SIZE, Q1T_TILE, q1t_pack};
    anyhow::ensure!(
        vals.len() == out_dim * in_dim,
        "q1t exact: {} values != {out_dim}×{in_dim}",
        vals.len()
    );
    anyhow::ensure!(
        in_dim % GROUP_SIZE == 0,
        "q1t exact: in_dim {in_dim} is not a multiple of {GROUP_SIZE}"
    );
    anyhow::ensure!(
        in_dim <= u16::MAX as usize + 1,
        "q1t overlay: in_dim {in_dim} exceeds u16"
    );
    let n_groups = vals.len() / GROUP_SIZE;
    let mut out = Vec::with_capacity(n_groups * Q1T_TILE + (out_dim + 1) * 4);
    for g in 0..n_groups {
        let grp = &vals[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
        let s = grp.iter().fold(0f32, |m, v| m.max(v.abs()));
        let s16 = f32_to_f16(s);
        let s_rt = f16_to_f32(s16);
        let mut codes = [0u8; 7];
        for (k, &v) in grp.iter().enumerate() {
            let code = if v == 0.0 {
                0
            } else {
                anyhow::ensure!(
                    (v.abs() - s_rt).abs() <= s_rt * 1e-3,
                    "q1t exact: group {g} is not ternary (|w| {} vs scale {s_rt})",
                    v.abs()
                );
                if v > 0.0 { 1 } else { 2 }
            };
            q1t_pack(&mut codes, k, code);
        }
        out.extend_from_slice(&s16.to_le_bytes());
        out.extend_from_slice(&codes);
    }
    // Empty per-row overlay: row_ptr[out_dim + 1], all zero.
    out.resize(out.len() + (out_dim + 1) * 4, 0);
    Ok(out)
}

pub(crate) fn encode_q8_2f(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    // Column field: RMS over rows, f16-rounded (the decoder multiplies by these).
    // Both halves run across the encode threads: this is the codec a 20 B DiT
    // gets packed in, and serially it was the slowest encoder in the crate by
    // an order of magnitude while q4tp next to it used the whole machine.
    // The column reduction is blocked at a FIXED width, not at one block per
    // thread: f64 addition does not associate, so a thread-shaped grouping
    // would make the bytes depend on the core count. Blocks are summed in
    // index order, which is the same arithmetic on one thread and on thirty.
    const CBLK: usize = 256;
    let nblk = out_dim.div_ceil(CBLK);
    let threads = encode_threads().min(nblk.max(1)).max(1);
    let mut col = vec![0f32; in_dim];
    {
        let mut blocks: Vec<Vec<f64>> = vec![Vec::new(); nblk];
        let per = nblk.div_ceil(threads);
        std::thread::scope(|sc| {
            for (ti, chunk) in blocks.chunks_mut(per).enumerate() {
                sc.spawn(move || {
                    for (bi, slot) in chunk.iter_mut().enumerate() {
                        let b = ti * per + bi;
                        let (r0, r1) = (b * CBLK, ((b + 1) * CBLK).min(out_dim));
                        let mut acc = vec![0f64; in_dim];
                        for o in r0..r1 {
                            for (i, a) in acc.iter_mut().enumerate() {
                                let v = vals[o * in_dim + i] as f64;
                                *a += v * v;
                            }
                        }
                        *slot = acc;
                    }
                });
            }
        });
        for (i, c) in col.iter_mut().enumerate() {
            let mut acc = 0f64;
            for b in &blocks {
                acc += b[i];
            }
            let rms = (acc / out_dim as f64).sqrt().max(1e-12) as f32;
            *c = f16_to_f32(f32_to_f16(rms)).max(F16_TINY);
        }
    }
    let mut q = vec![0u8; out_dim * in_dim];
    let mut scales = vec![0u8; out_dim * 2];
    let mut unused = vec![0u8; out_dim];
    encode_rows_parallel(
        out_dim,
        [in_dim, 2, 1],
        [&mut q, &mut scales, &mut unused],
        &|o: usize, qrow: &mut [u8], srow: &mut [u8], _: &mut [u8]| {
            let src = &vals[o * in_dim..(o + 1) * in_dim];
            let mut absmax = 0f32;
            for (v, c) in src.iter().zip(&col) {
                absmax = absmax.max((v / c).abs());
            }
            let scale = f16_scale(absmax.max(1e-12) / 127.0);
            for ((d, v), c) in qrow.iter_mut().zip(src).zip(&col) {
                *d = ((v / c) / scale).round_ties_even().clamp(-127.0, 127.0) as i8 as u8;
            }
            srow.copy_from_slice(&f32_to_f16(scale).to_le_bytes());
        },
    );
    let mut out = q;
    out.extend_from_slice(&scales);
    for &c in &col {
        out.extend_from_slice(&f32_to_f16(c).to_le_bytes());
    }
    out
}

// Grouped variable-bit (v-bit) encoder — the weight-only (round-to-nearest) path
// of the reference converter. On-disk layout read by `cortiq_core::dequant_vbit`:
//   [u8 bits: rows][f16 scales: rows·(in/32)][per row: ceil(in·b/8) bytes,
//    MSB-first b-bit codes, zero-padded]. w = (u − L)·scale, L = 2^(b−1)−1.
// The GPTQ / calibrated variant (needs a Hessian) stays in the Python converter.
const VBIT_LEVELS: [u8; 5] = [3, 4, 5, 6, 8];
/// Target mean bit-width for VBIT water-filling. Default 4.25; overridable via
/// `cortiq convert --mean-bits` (stored ×1000 in a static to avoid signature churn).
static VBIT_MEAN_BITS_MILLI: AtomicU32 = AtomicU32::new(4250);
/// Set the VBIT target mean bit-width (converter CLI knob). Clamped to [3.0, 8.0].
pub fn set_vbit_mean_bits(bits: f32) {
    VBIT_MEAN_BITS_MILLI.store((bits.clamp(3.0, 8.0) * 1000.0) as u32, Ordering::Relaxed);
}
fn vbit_mean_bits() -> f32 {
    VBIT_MEAN_BITS_MILLI.load(Ordering::Relaxed) as f32 / 1000.0
}

/// Snap `x` to the nearest allowed bit-width (first wins on a tie, like argmin).
fn vbit_snap_level(x: f32) -> u8 {
    let mut best = VBIT_LEVELS[0];
    let mut bestd = (x - best as f32).abs();
    for &lv in &VBIT_LEVELS[1..] {
        let d = (x - lv as f32).abs();
        if d < bestd {
            bestd = d;
            best = lv;
        }
    }
    best
}

/// Per-row bit-width via water-filling over log2 row amplitude (floor 3 bits).
fn vbit_bits(vals: &[f32], out_dim: usize, in_dim: usize, mean_bits: f32) -> Vec<u8> {
    let a: Vec<f32> = (0..out_dim)
        .map(|o| {
            let mx = vals[o * in_dim..(o + 1) * in_dim]
                .iter()
                .fold(0f32, |m, v| m.max(v.abs()));
            mx.max(1e-12).log2()
        })
        .collect();
    let amean = a.iter().sum::<f32>() / out_dim as f32;
    a.iter()
        .map(|&ar| vbit_snap_level(mean_bits + (ar - amean)).max(3))
        .collect()
}

/// Big-endian (MSB-first) bit packer; the last byte of each row is zero-padded.
struct BitWriter {
    buf: Vec<u8>,
    cur: u8,
    nbits: u8,
}
impl BitWriter {
    fn with_capacity(n: usize) -> Self {
        Self {
            buf: Vec::with_capacity(n),
            cur: 0,
            nbits: 0,
        }
    }
    fn push(&mut self, v: u32, b: u32) {
        for i in (0..b).rev() {
            self.cur = (self.cur << 1) | ((v >> i) & 1) as u8;
            self.nbits += 1;
            if self.nbits == 8 {
                self.buf.push(self.cur);
                self.cur = 0;
                self.nbits = 0;
            }
        }
    }
    fn flush_row(&mut self) {
        if self.nbits > 0 {
            self.buf.push(self.cur << (8 - self.nbits));
            self.cur = 0;
            self.nbits = 0;
        }
    }
}

fn encode_vbit(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    let ng = in_dim / GROUP_SIZE;
    let bits = vbit_bits(vals, out_dim, in_dim, vbit_mean_bits());

    // Per-(row, group) scale = group absmax / L, f16-rounded and floored.
    let mut scale = vec![0f32; out_dim * ng];
    let mut sc_bytes = Vec::with_capacity(out_dim * ng * 2);
    for o in 0..out_dim {
        let l = (2f32.powi(bits[o] as i32 - 1) - 1.0).max(1.0);
        for g in 0..ng {
            let base = o * in_dim + g * GROUP_SIZE;
            let mx = vals[base..base + GROUP_SIZE]
                .iter()
                .fold(0f32, |m, v| m.max(v.abs()));
            let s = f16_scale(mx / l);
            scale[o * ng + g] = s;
            sc_bytes.extend_from_slice(&f32_to_f16(s).to_le_bytes());
        }
    }

    let mut out = Vec::with_capacity(out_dim + sc_bytes.len() + out_dim * in_dim);
    out.extend_from_slice(&bits);
    out.extend_from_slice(&sc_bytes);
    let mut bw = BitWriter::with_capacity(out_dim * in_dim);
    for o in 0..out_dim {
        let b = bits[o] as u32;
        let l = 2f32.powi(bits[o] as i32 - 1) - 1.0;
        let maxq = 2f32.powi(bits[o] as i32) - 1.0;
        for c in 0..in_dim {
            let s = scale[o * ng + c / GROUP_SIZE];
            let q = ((vals[o * in_dim + c] / s).round_ties_even() + l).clamp(0.0, maxq) as u32;
            bw.push(q, b);
        }
        bw.flush_row();
    }
    out.extend_from_slice(&bw.buf);
    out
}

/// `vbit_ro` (§4.2): the same bits/scales/packed encoding as
/// `encode_vbit`, plus `u32 row_offsets[rows+1]` (relative to the
/// packed area) between the scales and the packed rows — readers get
/// O(1) row access without a prefix scan. New dtype id; the byte
/// semantics of legacy `vbit` are untouched.
fn encode_vbit_ro(vals: &[f32], out_dim: usize, in_dim: usize) -> Vec<u8> {
    let legacy = encode_vbit(vals, out_dim, in_dim);
    let ng = in_dim / GROUP_SIZE;
    let sc_len = out_dim * ng * 2;
    let (head, packed) = legacy.split_at(out_dim + sc_len);
    let bits = &head[..out_dim];
    let mut out = Vec::with_capacity(legacy.len() + (out_dim + 1) * 4);
    out.extend_from_slice(head);
    let mut off = 0u32;
    for &b in bits {
        out.extend_from_slice(&off.to_le_bytes());
        off += ((in_dim * b as usize).div_ceil(8)) as u32;
    }
    out.extend_from_slice(&off.to_le_bytes());
    debug_assert_eq!(off as usize, packed.len());
    out.extend_from_slice(packed);
    out
}

/// f16 blob for a 1-D / small tensor.
pub(crate) fn encode_f16(vals: &[f32]) -> Vec<u8> {
    let mut out = Vec::with_capacity(vals.len() * 2);
    for &v in vals {
        out.extend_from_slice(&f32_to_f16(v).to_le_bytes());
    }
    out
}

/// Decode a safetensors dtype blob into f32 values.
/// Move every produced payload out of RAM and straight into the output file,
/// then drop it. Called after each source shard, so peak residency is one
/// shard's tensors rather than the model's — and because the writer streams
/// into the final file, peak DISK is the finished model rather than twice it.
const RAW_AUX_COPY_CHUNK: usize = 8 * 1024 * 1024;

/// Copy a native auxiliary tensor without decoding it or putting it through a
/// quantizer. DeepSeek-V4.1's Engram embedding planes are enormous FP8 byte
/// tables; they remain `U8` records with their original 2-D shape and are
/// interpreted by the V4.1 runtime. The writer hashes and copies them in
/// bounded chunks directly from the safetensors mmap.
fn push_raw_u8_tensor(
    writers: &mut [Option<cortiq_core::format::CmfStreamWriter>],
    active: &[bool],
    name: &str,
    shape: &[usize],
    data: &[u8],
) -> anyhow::Result<()> {
    anyhow::ensure!(
        writers.len() == active.len(),
        "raw tensor output count mismatch"
    );
    let expected = shape.iter().try_fold(1usize, |n, &d| n.checked_mul(d));
    let expected =
        expected.ok_or_else(|| anyhow::anyhow!("raw tensor '{name}': shape overflow"))?;
    anyhow::ensure!(
        expected == data.len(),
        "raw tensor '{name}': {} bytes for shape {:?} (expected {})",
        data.len(),
        shape,
        expected
    );
    for (i, (writer, &is_active)) in writers.iter_mut().zip(active).enumerate() {
        if !is_active {
            continue;
        }
        let writer = writer
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("output {i} has no active writer for '{name}'"))?;
        writer
            .push_bounded(name, TensorDtype::U8, shape, data, RAW_AUX_COPY_CHUNK)
            .map_err(|e| anyhow::anyhow!("write raw tensor '{name}': {e}"))?;
    }
    Ok(())
}

fn drain_to_writer(
    tensors: &mut Vec<TensorSpec>,
    writer: &mut cortiq_core::format::CmfStreamWriter,
) -> anyhow::Result<()> {
    for t in tensors.drain(..) {
        writer
            .push(&t.name, t.dtype, &t.shape, &t.data)
            .map_err(|e| anyhow::anyhow!("write tensor '{}': {e}", t.name))?;
    }
    Ok(())
}

pub(crate) fn to_f32(dtype: &str, raw: &[u8]) -> anyhow::Result<Vec<f32>> {
    Ok(match dtype {
        "F32" => raw
            .chunks_exact(4)
            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
            .collect(),
        "F16" => raw
            .chunks_exact(2)
            .map(|b| f16_to_f32(u16::from_le_bytes([b[0], b[1]])))
            .collect(),
        "BF16" => raw
            .chunks_exact(2)
            .map(|b| bf16_to_f32(u16::from_le_bytes([b[0], b[1]])))
            .collect(),
        // DeepSeek-V4's hash-routing table is I64 token→expert indices, and
        // I32 shows up in the same role elsewhere. They are LOOKUP TABLES,
        // not weights: widen to f32 so the pipeline can carry them, and let
        // the writer's force_f16 rule keep them exact.
        "I64" => raw
            .chunks_exact(8)
            .map(|b| i64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32)
            .collect(),
        "I32" => raw
            .chunks_exact(4)
            .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f32)
            .collect(),
        other => anyhow::bail!("unsupported safetensors dtype '{other}' (need F32/F16/BF16)"),
    })
}

/// Reorder the source MLX Conv3d patch kernel into the flattened row layout
/// consumed by the CMF Qwen3 vision tower.  MLX's kernel is
/// `[out, temporal, patch_h, patch_w, in_channels]`; the CMF preprocessor
/// presents each patch as `[in_channels, temporal, patch_h, patch_w]`.
fn flatten_prism_patch_weight(
    dtype: &str,
    shape: &[usize],
    raw: &[u8],
) -> anyhow::Result<(Vec<usize>, Vec<f32>)> {
    anyhow::ensure!(
        dtype == "F16",
        "Prism vision patch kernel must be F16, got {dtype}"
    );
    anyhow::ensure!(
        shape.len() == 5,
        "Prism vision patch kernel must be [out,t,h,w,c], got {shape:?}"
    );
    let [out, temporal, patch_h, patch_w, channels] =
        [shape[0], shape[1], shape[2], shape[3], shape[4]];
    anyhow::ensure!(
        [out, temporal, patch_h, patch_w, channels]
            .iter()
            .all(|&n| n > 0),
        "Prism vision patch kernel has an empty dimension: {shape:?}"
    );
    let source = to_f32(dtype, raw)?;
    let source_len = out
        .checked_mul(temporal)
        .and_then(|n| n.checked_mul(patch_h))
        .and_then(|n| n.checked_mul(patch_w))
        .and_then(|n| n.checked_mul(channels))
        .ok_or_else(|| anyhow::anyhow!("Prism vision patch kernel shape overflows"))?;
    anyhow::ensure!(
        source.len() == source_len,
        "Prism vision patch kernel has {} values, expected {source_len}",
        source.len()
    );
    let patch_width = channels
        .checked_mul(temporal)
        .and_then(|n| n.checked_mul(patch_h))
        .and_then(|n| n.checked_mul(patch_w))
        .ok_or_else(|| anyhow::anyhow!("Prism vision patch width overflows"))?;
    let mut out_rows = vec![0.0f32; out * patch_width];
    for o in 0..out {
        for c in 0..channels {
            for t in 0..temporal {
                for y in 0..patch_h {
                    for x in 0..patch_w {
                        let src =
                            ((((o * temporal + t) * patch_h + y) * patch_w + x) * channels) + c;
                        let dst =
                            ((((o * channels + c) * temporal + t) * patch_h + y) * patch_w) + x;
                        out_rows[dst] = source[src];
                    }
                }
            }
        }
    }
    Ok((vec![out, patch_width], out_rows))
}

/// OCP MXFP4 (compressed-tensors "mxfp4-pack-quantized", Kimi-K3):
/// two FP4-E2M1 values per byte (LOW nibble = even element), groups of
/// 32 along the last axis, one E8M0 scale byte (2^(k−127)) per group.
pub(crate) fn unpack_mxfp4(
    packed: &[u8],
    scales: &[u8],
    rows: usize,
    cols_packed: usize,
) -> anyhow::Result<Vec<f32>> {
    // E2M1, bias 1: e=0 subnormal m·0.5; e≥1 normal (1+m/2)·2^(e−1).
    const LUT: [f32; 8] = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0];
    let cols = cols_packed * 2;
    anyhow::ensure!(cols % 32 == 0, "mxfp4: cols {cols} not a multiple of 32");
    let gpr = cols / 32;
    anyhow::ensure!(
        packed.len() == rows * cols_packed && scales.len() == rows * gpr,
        "mxfp4: packed {} / scales {} vs rows {rows} cols {cols}",
        packed.len(),
        scales.len()
    );
    let mut out = vec![0.0f32; rows * cols];
    for r in 0..rows {
        for g in 0..gpr {
            let k = scales[r * gpr + g];
            // E8M0: value = 2^(k−127); 255 = NaN per OCP — refuse loudly.
            anyhow::ensure!(k != 255, "mxfp4: NaN scale at row {r} group {g}");
            let scale = (k as f32 - 127.0).exp2();
            for b in 0..16 {
                let byte = packed[r * cols_packed + g * 16 + b];
                for (half, nib) in [(0usize, byte & 0x0F), (1usize, byte >> 4)] {
                    let mag = LUT[(nib & 0x7) as usize];
                    let v = if nib & 0x8 != 0 { -mag } else { mag };
                    out[r * cols + g * 32 + b * 2 + half] = v * scale;
                }
            }
        }
    }
    Ok(out)
}

/// OCP FP8 E4M3 → f32. 1 sign, 4 exp (bias 7), 3 mantissa; no infinities,
/// and exp=15,mant=7 is the only NaN. Subnormals are m·2^-9.
#[inline]
pub(crate) fn fp8_e4m3_to_f32(b: u8) -> f32 {
    let sign = if b & 0x80 != 0 { -1.0f32 } else { 1.0 };
    let exp = ((b >> 3) & 0x0F) as i32;
    let man = (b & 0x07) as f32;
    // OCP E4M3FN reserves the all-ones exponent/mantissa encoding for NaN
    // (there are no infinities).  Treating 0x7f as a finite 480.0 silently
    // poisons every downstream quantization block.
    if exp == 15 && man == 7.0 {
        return f32::NAN;
    }
    let mag = if exp == 0 {
        man * (2f32).powi(-9)
    } else {
        (1.0 + man / 8.0) * (2f32).powi(exp - 7)
    };
    sign * mag
}

/// DeepSeek-V4 style FP8 weights: E4M3 values with one E8M0 scale per
/// `block`×`block` tile (`quantization_config.weight_block_size`). The
/// scale plane is `ceil(rows/block) × ceil(cols/block)`, row-major, and
/// the tiles at the edges are partial — the model's own layout, not a
/// padded one.
pub(crate) fn unpack_fp8_blocks(
    packed: &[u8],
    scales: &[u8],
    rows: usize,
    cols: usize,
    block: usize,
) -> anyhow::Result<Vec<f32>> {
    anyhow::ensure!(block > 0, "fp8 blocks: block size 0");
    let sr = rows.div_ceil(block);
    let sc = cols.div_ceil(block);
    anyhow::ensure!(
        packed.len() == rows * cols && scales.len() == sr * sc,
        "fp8 blocks: weight {} (want {}) / scales {} (want {}) for {rows}x{cols} block {block}",
        packed.len(),
        rows * cols,
        scales.len(),
        sr * sc
    );
    let mut out = vec![0.0f32; rows * cols];
    for r in 0..rows {
        let br = r / block;
        for c in 0..cols {
            let k = scales[br * sc + c / block];
            // E8M0: 2^(k−127); 255 is NaN per OCP — refuse loudly rather
            // than fold a NaN through the whole row.
            anyhow::ensure!(k != 255, "fp8 blocks: NaN scale at ({r},{c})");
            let v = fp8_e4m3_to_f32(packed[r * cols + c]);
            anyhow::ensure!(v.is_finite(), "fp8 blocks: NaN weight at ({r},{c})");
            out[r * cols + c] = v * (k as f32 - 127.0).exp2();
        }
    }
    Ok(out)
}

/// Fine-grained FP8 with one ordinary f32 inverse scale per source block.
/// V4.1's `weight_block_size` controls the block geometry; older checkpoints
/// use 128 while the V4.1 source uses 32.
fn unpack_fp8_scale_inv(
    packed: &[u8],
    scales: &[f32],
    rows: usize,
    cols: usize,
    block: usize,
) -> anyhow::Result<Vec<f32>> {
    anyhow::ensure!(block > 0, "fp8 scale_inv: block size 0");
    anyhow::ensure!(
        packed.len() == rows * cols,
        "fp8 scale_inv: weight size mismatch"
    );
    let (sr, sc) = (rows.div_ceil(block), cols.div_ceil(block));
    anyhow::ensure!(
        scales.len() == sr * sc,
        "fp8 scale_inv: {} scales, expected {sr}x{sc}",
        scales.len()
    );
    let mut out = vec![0.0f32; rows * cols];
    let threads = encode_threads().min(rows.max(1)).max(1);
    let rows_per_thread = rows.div_ceil(threads);
    std::thread::scope(|scope| -> anyhow::Result<()> {
        let mut workers = Vec::with_capacity(threads);
        for (chunk_index, out_chunk) in out.chunks_mut(rows_per_thread * cols).enumerate() {
            let first_row = chunk_index * rows_per_thread;
            workers.push(scope.spawn(move || -> anyhow::Result<()> {
                for (local_row, out_row) in out_chunk.chunks_mut(cols).enumerate() {
                    let r = first_row + local_row;
                    let packed_row = &packed[r * cols..(r + 1) * cols];
                    for (c, (&byte, dst)) in packed_row.iter().zip(out_row).enumerate() {
                        let v = fp8_e4m3_to_f32(byte);
                        anyhow::ensure!(v.is_finite(), "fp8 scale_inv: NaN weight at ({r},{c})");
                        let scale = scales[(r / block) * sc + c / block];
                        anyhow::ensure!(
                            scale.is_finite(),
                            "fp8 scale_inv: non-finite scale at ({r},{c})"
                        );
                        *dst = v * scale;
                    }
                }
                Ok(())
            }));
        }
        for worker in workers {
            worker
                .join()
                .map_err(|_| anyhow::anyhow!("fp8 scale_inv worker panicked"))??;
        }
        Ok(())
    })?;
    Ok(out)
}

pub(crate) fn unpack_mlx(
    w_raw: &[u8],
    s_raw: &[u8],
    b_raw: Option<&[u8]>,
    out_dim: usize,
    in_dim: usize,
    bits: usize,
) -> anyhow::Result<Vec<f32>> {
    let mut out = vec![0f32; out_dim * in_dim];
    let num_groups = s_raw.len() / 2 / out_dim;
    let group_size = in_dim / num_groups;

    let w_u32: Vec<u32> = w_raw
        .chunks_exact(4)
        .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
        .collect();
    let s_f16: Vec<u16> = s_raw
        .chunks_exact(2)
        .map(|b| u16::from_le_bytes([b[0], b[1]]))
        .collect();
    let b_f16: Option<Vec<u16>> = b_raw.map(|r| {
        r.chunks_exact(2)
            .map(|b| u16::from_le_bytes([b[0], b[1]]))
            .collect()
    });

    let vals_per_u32 = 32 / bits;
    let mask = (1 << bits) - 1;

    for row in 0..out_dim {
        for col in 0..in_dim {
            let group = col / group_size;
            let scale = f16_to_f32(s_f16[row * num_groups + group]);
            let bias = b_f16
                .as_ref()
                .map(|b| f16_to_f32(b[row * num_groups + group]))
                .unwrap_or(0.0);

            let u32_idx = (row * in_dim + col) / vals_per_u32;
            let shift = (col % vals_per_u32) * bits;
            let val = (w_u32[u32_idx] >> shift) & mask;

            // For 1-bit, MLX might map 0->-1 and 1->1, but wait!
            // In 2-bit, MLX maps 0,1,2,3 directly to value * scale + bias.
            // If the model is 1-bit, is the value 0 and 1, or is it sign bits?
            // Actually, bias handles the shift. If it's a 1-bit scale+bias model, `val * scale + bias` works.
            out[row * in_dim + col] = (val as f32) * scale + bias;
        }
    }
    Ok(out)
}

/// Stream the source MLX ternary planes into the production dtype16 Q2TP
/// affine profile.  This is intentionally not an experimental ternary dtype: dtype16
/// reserves rung 0 for an exact zero and has only 31 positive rungs, so row
/// parameters are refit against `q2tp_ladder` while the source 0/1/2 symbol
/// plane is copied unchanged.
fn encode_mlx_q2tp_affine(
    w_raw: &[u8],
    s_raw: &[u8],
    b_raw: &[u8],
    out_dim: usize,
    in_dim: usize,
) -> anyhow::Result<(Vec<u8>, f32)> {
    anyhow::ensure!(
        in_dim % 128 == 0,
        "Prism MLX input width {in_dim} is not g128"
    );
    anyhow::ensure!(
        w_raw.len() == out_dim * in_dim / 16 * 4,
        "Prism MLX packed weight length mismatch"
    );
    anyhow::ensure!(
        s_raw.len() == out_dim * (in_dim / 128) * 2,
        "Prism MLX scale length mismatch"
    );
    anyhow::ensure!(b_raw.len() == s_raw.len(), "Prism MLX bias length mismatch");
    let gpr = in_dim / GROUP_SIZE;
    let src_gpr = in_dim / 128;
    let stride = q4tp_code_stride(gpr);
    let mut chunks = vec![0u8; out_dim * gpr * Q2TP_CHUNK];
    let mut params = vec![0u8; out_dim * 4];
    let mut codes = vec![0u8; out_dim * stride];
    let bad_symbol = AtomicU8::new(0);
    let sum_sq = Mutex::new(0.0f64);
    let n_scales = AtomicUsize::new(0);
    encode_rows_parallel(
        out_dim,
        [gpr * Q2TP_CHUNK, 4, stride],
        [&mut chunks, &mut params, &mut codes],
        &|r, chunks_row, params_row, codes_row| {
            let mut source_scales = vec![F16_TINY; gpr];
            let mut lo = f32::INFINITY;
            let mut hi = f32::NEG_INFINITY;
            for g in 0..gpr {
                let sg = g / 4;
                let off = (r * src_gpr + sg) * 2;
                let s = f16_to_f32(u16::from_le_bytes([s_raw[off], s_raw[off + 1]]));
                let bias = f16_to_f32(u16::from_le_bytes([b_raw[off], b_raw[off + 1]]));
                if !s.is_finite() || s <= 0.0 {
                    bad_symbol.store(255, Ordering::Relaxed);
                    return;
                }
                if (bias + s).abs() > f32::max(2.0e-3, s.abs() * 2.0e-3) {
                    bad_symbol.store(254, Ordering::Relaxed);
                    return;
                }
                source_scales[g] = s;
                let lg = s.log2();
                lo = lo.min(lg);
                hi = hi.max(lg);
            }
            let lo_h = f32_to_f16(lo);
            let lo_r = f16_to_f32(lo_h);
            let mut st_h = f32_to_f16((hi - lo_r).max(0.0) / Q2TP_LMAX as f32);
            for _ in 0..64 {
                let st = f16_to_f32(st_h);
                if st > 0.0 && lo_r + Q2TP_LMAX as f32 * st >= hi {
                    break;
                }
                st_h += 1;
            }
            params_row[..2].copy_from_slice(&lo_h.to_le_bytes());
            params_row[2..].copy_from_slice(&st_h.to_le_bytes());
            let tab = q2tp_ladder(params_row, 0);
            let st = f16_to_f32(st_h);
            for g in 0..gpr {
                // Rung zero is reserved for an exact zero group in dtype16;
                // source ternary scales are positive, so use 1..=31.
                let c = if st > 0.0 {
                    1 + ((source_scales[g].log2() - lo_r) / st)
                        .round_ties_even()
                        .clamp(0.0, Q2TP_LMAX as f32) as usize
                } else {
                    1
                };
                q4tp_put_code(codes_row, g, c);
                let fitted = tab[c];
                let d = fitted - source_scales[g];
                *sum_sq.lock().unwrap() += (d * d) as f64;
                n_scales.fetch_add(1, Ordering::Relaxed);
                let dst = &mut chunks_row[g * Q2TP_CHUNK..(g + 1) * Q2TP_CHUNK];
                for k in 0..Q2TP_CHUNK {
                    let col0 = g * GROUP_SIZE + k * 4;
                    let word0 = (r * (in_dim / 16) + col0 / 16) * 4;
                    let word = u32::from_le_bytes([
                        w_raw[word0],
                        w_raw[word0 + 1],
                        w_raw[word0 + 2],
                        w_raw[word0 + 3],
                    ]);
                    let mut b = 0u8;
                    for j in 0..4 {
                        let c = ((word >> (2 * ((col0 + j) % 16))) & 3) as u8;
                        if c == 3 {
                            bad_symbol.store(3, Ordering::Relaxed);
                        }
                        b |= c << (2 * j);
                    }
                    dst[k] = b;
                }
            }
        },
    );
    let bad = bad_symbol.load(Ordering::Relaxed);
    if bad != 0 {
        anyhow::bail!("Prism MLX source contains invalid scale or reserved code {bad}");
    }
    chunks.extend_from_slice(&params);
    chunks.extend_from_slice(&codes);
    let count = n_scales.load(Ordering::Relaxed);
    let rms = if count == 0 {
        0.0
    } else {
        (sum_sq.into_inner().unwrap() / count as f64).sqrt() as f32
    };
    Ok((chunks, rms))
}

/// Validate the source MLX packed plane before either Prism output profile is
/// written.  Code 3 is reserved by both CMF codecs; accepting it in the
/// ordinary q2tp candidate would make the two files disagree about the
/// source contract and would hide a corrupt checkpoint behind PTQ noise.
fn validate_mlx_ternary_codes(w_raw: &[u8], out_dim: usize, in_dim: usize) -> anyhow::Result<()> {
    anyhow::ensure!(
        in_dim % 16 == 0,
        "Prism MLX input width {in_dim} is not packed-g16"
    );
    let words_per_row = in_dim / 16;
    anyhow::ensure!(
        w_raw.len() == out_dim.saturating_mul(words_per_row).saturating_mul(4),
        "Prism MLX packed weight length mismatch"
    );
    for (word_index, raw) in w_raw.chunks_exact(4).enumerate() {
        let word = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]);
        for j in 0..16 {
            if ((word >> (2 * j)) & 3) == 3 {
                let row = word_index / words_per_row;
                let col = (word_index % words_per_row) * 16 + j;
                anyhow::bail!(
                    "Prism MLX source contains reserved code 3 at row {row}, column {col}"
                );
            }
        }
    }
    Ok(())
}

/// Blob-layout sort key that puts tensors in decode-traversal order:
/// `(phase, layer, group, expert, projection)`. Phase orders embed → layers →
/// final-norm → lm_head → MTP → tail; within a layer, attention precedes the
/// FFN and MoE experts are grouped per expert (each expert's gate/up/down
/// contiguous). A stable name tiebreak keeps it deterministic. Layout only —
/// no effect on decoding (the directory is the offset authority).
pub(crate) fn exec_order_key(name: &str) -> (u32, u32, u32, u32, u32) {
    let num_after = |marker: &str| {
        name.split(marker)
            .nth(1)
            .and_then(|s| s.split('.').next())
            .and_then(|s| s.parse::<u32>().ok())
    };
    let expert = num_after(".experts.").unwrap_or(0);
    // Projection order within a block: q/gate, k/up, v/down, o, else.
    let proj = if name.contains("q_proj") || name.contains("gate_proj") {
        0
    } else if name.contains("k_proj") || name.contains("up_proj") {
        1
    } else if name.contains("v_proj") || name.contains("down_proj") {
        2
    } else if name.contains("o_proj") {
        3
    } else {
        4
    };
    if name.contains("embed_tokens") {
        (0, 0, 0, 0, 0)
    } else if let Some(l) = num_after(".layers.") {
        let group = if name.contains("input_layernorm") {
            0
        } else if name.contains("self_attn")
            || name.contains("linear_attn")
            || name.contains("short_conv")
        {
            1
        } else if name.contains("post_attention_layernorm") {
            2
        } else if name.ends_with("mlp.gate.weight")
            || name.contains("shared_expert")
            || name.contains("expert_bias")
        {
            3 // MoE router / shared expert (before the routed experts)
        } else if name.contains(".experts.") {
            4
        } else {
            5 // dense FFN (gate/up/down_proj) and anything else in the layer
        };
        (1, l, group, expert, proj)
    } else if name.contains("model.mtp") {
        (4, 0, 0, 0, 0)
    } else if name.contains("lm_head") {
        (3, 0, 0, 0, 0)
    } else if name.contains("model.norm") || name.ends_with("norm.weight") {
        (2, 0, 0, 0, 0)
    } else {
        (5, 0, 0, 0, 0)
    }
}

/// A tensor's metadata within a safetensors file (bytes are read lazily from mmap).
pub(crate) struct TensorMeta {
    pub(crate) name: String,
    pub(crate) dtype: String,
    pub(crate) shape: Vec<usize>,
    pub(crate) start: usize,
    pub(crate) end: usize,
}

/// A memory-mapped safetensors file — tensor bytes are borrowed from the mmap, so
/// the raw weights are never fully loaded into RAM (peak stays ~one tensor).
pub(crate) struct SafeTensors {
    mmap: Option<memmap2::Mmap>,
    data_start: usize,
    pub(crate) tensors: Vec<TensorMeta>,
    /// File name, so a resumed conversion can tell which of these are done.
    pub(crate) name: String,
}

impl SafeTensors {
    pub(crate) fn bytes(&self, m: &TensorMeta) -> &[u8] {
        let mmap = self
            .mmap
            .as_ref()
            .expect("safetensors mmap accessed after source shard release");
        &mmap[self.data_start + m.start..self.data_start + m.end]
    }

    /// Release the file mapping after this source shard's converted payloads
    /// and manifest checkpoint are durable. Metadata stays resident so the
    /// caller can retain the index for companion/name lookups.
    pub(crate) fn release(&mut self) {
        self.mmap.take();
    }
}

/// Release and unlink one local source shard after every active output has
/// checkpointed it. The index/config/tokenizer remain untouched; a missing
/// source file is reported as already consumed so a resumed output can finish
/// its cleanup pass without treating the absence as a conversion failure.
fn consume_source_shard(files: &mut [SafeTensors], index: usize, dir: &Path) -> anyhow::Result<()> {
    let source_name = files
        .get(index)
        .map(|f| f.name.clone())
        .ok_or_else(|| anyhow::anyhow!("source shard index {index} out of range"))?;
    files[index].release();
    let source_path = dir.join(&source_name);
    match fs::remove_file(&source_path) {
        Ok(()) => eprintln!("  consumed source shard {source_name}"),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            eprintln!("  source shard {source_name} already absent")
        }
        Err(e) => {
            anyhow::bail!(
                "remove consumed source shard {}: {e}",
                source_path.display()
            )
        }
    }
    Ok(())
}

fn consume_local_ready_source(path: &Path) -> anyhow::Result<()> {
    fs::remove_file(path)
        .map_err(|e| anyhow::anyhow!("remove consumed local-ready source {}: {e}", path.display()))
}

fn open_safetensors(path: &Path) -> anyhow::Result<SafeTensors> {
    let file = fs::File::open(path).map_err(|e| anyhow::anyhow!("open {}: {e}", path.display()))?;
    let mmap = unsafe { memmap2::Mmap::map(&file)? };
    if mmap.len() < 8 {
        anyhow::bail!("{}: too small to be safetensors", path.display());
    }
    let hlen = u64::from_le_bytes(mmap[0..8].try_into().unwrap()) as usize;
    let header: serde_json::Value = serde_json::from_slice(&mmap[8..8 + hlen])?;
    let data_start = 8 + hlen;
    let obj = header
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("bad safetensors header"))?;
    let mut tensors = Vec::new();
    for (name, v) in obj {
        if name == "__metadata__" {
            continue;
        }
        let dtype = v["dtype"].as_str().unwrap_or("").to_string();
        let shape: Vec<usize> = v["shape"]
            .as_array()
            .map(|a| a.iter().map(|x| x.as_u64().unwrap_or(0) as usize).collect())
            .unwrap_or_default();
        let offs = v["data_offsets"]
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("tensor '{name}': no data_offsets"))?;
        let start = offs[0].as_u64().unwrap_or(0) as usize;
        let end = offs[1].as_u64().unwrap_or(0) as usize;
        tensors.push(TensorMeta {
            name: name.clone(),
            dtype,
            shape,
            start,
            end,
        });
    }
    Ok(SafeTensors {
        mmap: Some(mmap),
        data_start,
        tensors,
        name: path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default(),
    })
}

/// Memory-map a model dir's weights (single file or sharded index).
pub(crate) fn open_model(dir: &Path) -> anyhow::Result<Vec<SafeTensors>> {
    open_model_filtered(dir, &std::collections::HashSet::new())
}

/// Return the source shard basename used in manifests and `SafeTensors.name`.
fn source_shard_name(path: &str) -> String {
    Path::new(path)
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string())
}

/// Move the explicitly requested source basenames to the front while keeping
/// every other validated shard in its original order.  The source list has
/// already come from the HF index (or the local source index) when this is
/// called, so an unknown name is a configuration error rather than a reason
/// to probe arbitrary files.  Empty, repeated, and unknown entries fail
/// closed before any streamed shard is opened.
fn apply_source_shard_priority(stream_shards: &mut Vec<String>) -> anyhow::Result<()> {
    let Some(raw) = std::env::var_os(SOURCE_SHARD_PRIORITY_ENV) else {
        return Ok(());
    };
    let raw = raw
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("{SOURCE_SHARD_PRIORITY_ENV} must be valid UTF-8"))?;

    let known: HashSet<String> = stream_shards.iter().cloned().collect();
    anyhow::ensure!(
        known.len() == stream_shards.len(),
        "validated source shard list contains duplicate filenames"
    );
    let mut selected = HashSet::new();
    let mut priority = Vec::new();
    for name in raw.split(',') {
        anyhow::ensure!(
            !name.is_empty(),
            "{SOURCE_SHARD_PRIORITY_ENV} contains an empty entry"
        );
        anyhow::ensure!(
            known.contains(name),
            "{SOURCE_SHARD_PRIORITY_ENV} names unknown source shard {name:?}"
        );
        anyhow::ensure!(
            selected.insert(name.to_string()),
            "{SOURCE_SHARD_PRIORITY_ENV} repeats source shard {name:?}"
        );
        priority.push(name.to_string());
    }
    priority.extend(
        stream_shards
            .iter()
            .filter(|name| !selected.contains(name.as_str()))
            .cloned(),
    );
    *stream_shards = priority;
    Ok(())
}

/// Count tensors from the small safetensors headers/index without mapping the
/// payload. Resume uses this before opening source files so shards deleted by
/// a prior successful checkpoint can still contribute to progress and head
/// sizing.
fn source_shard_counts(dir: &Path) -> anyhow::Result<Vec<(String, usize)>> {
    let single = dir.join("model.safetensors");
    if single.exists() {
        return Ok(vec![(
            "model.safetensors".to_string(),
            safetensors_tensor_count(&single)?,
        )]);
    }
    let index = dir.join("model.safetensors.index.json");
    if index.exists() {
        let mut counts: HashMap<String, usize> = HashMap::new();
        let idx: serde_json::Value = serde_json::from_slice(&fs::read(&index)?)?;
        let map = idx["weight_map"]
            .as_object()
            .ok_or_else(|| anyhow::anyhow!("bad index json"))?;
        for file in map.values().filter_map(|v| v.as_str()) {
            *counts.entry(source_shard_name(file)).or_default() += 1;
        }
        let mut shards: Vec<(String, usize)> = counts.into_iter().collect();
        shards.sort_by(|a, b| a.0.cmp(&b.0));
        return Ok(shards);
    }
    anyhow::bail!(
        "no model.safetensors or model.safetensors.index.json in {}",
        dir.display()
    )
}

fn safetensors_tensor_count(path: &Path) -> anyhow::Result<usize> {
    let mut file =
        fs::File::open(path).map_err(|e| anyhow::anyhow!("open {}: {e}", path.display()))?;
    let mut len_bytes = [0u8; 8];
    file.read_exact(&mut len_bytes)?;
    let header_len = u64::from_le_bytes(len_bytes) as usize;
    let mut header_bytes = vec![0u8; header_len];
    file.read_exact(&mut header_bytes)?;
    let header: serde_json::Value = serde_json::from_slice(&header_bytes)
        .map_err(|e| anyhow::anyhow!("{}: bad safetensors header: {e}", path.display()))?;
    Ok(header
        .as_object()
        .map(|o| {
            o.keys()
                .filter(|name| name.as_str() != "__metadata__")
                .count()
        })
        .unwrap_or(0))
}

/// Open only source shards absent from the supplied completed-mark set. A
/// missing shard is therefore acceptable only when its basename is proven
/// complete by every output manifest; an unmarked missing shard remains a
/// hard error in `open_safetensors`.
pub(crate) fn open_model_filtered(
    dir: &Path,
    completed_shards: &std::collections::HashSet<String>,
) -> anyhow::Result<Vec<SafeTensors>> {
    let single = dir.join("model.safetensors");
    if single.exists() {
        if completed_shards.contains("model.safetensors") {
            return Ok(Vec::new());
        }
        return Ok(vec![open_safetensors(&single)?]);
    }
    let index = dir.join("model.safetensors.index.json");
    if index.exists() {
        let idx: serde_json::Value = serde_json::from_slice(&fs::read(&index)?)?;
        let map = idx["weight_map"]
            .as_object()
            .ok_or_else(|| anyhow::anyhow!("bad index json"))?;
        let mut files: Vec<String> = map
            .values()
            .filter_map(|v| v.as_str().map(String::from))
            .collect();
        files.sort();
        files.dedup();
        return files
            .iter()
            .filter(|f| !completed_shards.contains(&source_shard_name(f)))
            .map(|f| open_safetensors(&dir.join(f)))
            .collect();
    }
    anyhow::bail!(
        "no model.safetensors or model.safetensors.index.json in {}",
        dir.display()
    )
}

/// Read only completed source-shard marks from a manifest. This mirrors the
/// corruption boundary in `CmfStreamWriter::resume`: a malformed/truncated
/// line ends the durable prefix, so later marks are not trusted for filtering
/// source inputs.
fn resume_manifest_marks(path: &Path) -> std::collections::HashSet<String> {
    let Ok(text) = fs::read_to_string(path) else {
        return std::collections::HashSet::new();
    };
    let mut marks = std::collections::HashSet::new();
    for line in text.lines().skip(1) {
        if line.trim().is_empty() {
            continue;
        }
        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
            break;
        };
        if let Some(mark) = value["mark"].as_str() {
            marks.insert(mark.to_string());
        }
    }
    marks
}

fn cfg_usize(c: &serde_json::Value, key: &str) -> Option<usize> {
    c.get(key).and_then(|v| v.as_u64()).map(|x| x as usize)
}

/// Source FP8 tile width for DeepSeek-family checkpoints. V4.1 stores its
/// E4M3 weight and E8M0 scale plane over 32×32 tiles; older V4 files use the
/// 128×128 layout. Keep the source policy separate from the CMF quantizer,
/// since this value controls lossless decode before q4tp/q2tp encoding.
fn source_fp8_block(config: &serde_json::Value) -> usize {
    let model_type = config.get("model_type").and_then(|v| v.as_str());
    if model_type != Some("deepseek_v41") {
        return 128;
    }
    let block = config
        .get("quantization_config")
        .and_then(|q| q.get("weight_block_size"))
        .and_then(|v| v.as_array())
        .and_then(|a| {
            let row = a.first()?.as_u64()? as usize;
            let col = a.get(1)?.as_u64()? as usize;
            (row > 0 && row == col).then_some(row)
        });
    // The published V4.1 config carries [32, 32]. Keep the native default
    // when a compact test/config omits quantization_config entirely.
    block.unwrap_or(32)
}

/// Build ModelArch from a HF config.json (dense transformer families).
fn build_arch(config: &serde_json::Value) -> anyhow::Result<ModelArch> {
    // Vision/multimodal configs nest the text model under "text_config".
    let tc = config.get("text_config").unwrap_or(config);
    let model_type = config
        .get("model_type")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();
    let is_prism = model_type == "prism_hadamard_qwen35";
    // Tencent HunYuan: the dense family (Hy-MT2-1.8B / 7B, `hunyuan_v1_dense`)
    // and the hy_v3 MoE (Hy-MT2-30B-A3B). Dense: Llama block + per-head qk
    // RMSNorm applied AFTER RoPE + NTK-alpha rope base. MoE: sigmoid router
    // with a selection bias, renormalized top-k × router_scaling_factor, one
    // shared expert, first layer dense.
    let is_hunyuan_dense = model_type == "hunyuan_v1_dense";
    if is_hunyuan_dense {
        anyhow::ensure!(
            !tc.get("use_cla").and_then(|v| v.as_bool()).unwrap_or(false),
            "hunyuan_v1_dense: cross-layer attention (use_cla) is not supported"
        );
        anyhow::ensure!(
            tc.get("norm_type").and_then(|v| v.as_str()).unwrap_or("rms") == "rms",
            "hunyuan_v1_dense: only RMS norms are supported"
        );
        anyhow::ensure!(
            !tc.get("add_classification_head")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            "hunyuan_v1_dense: classification heads are not supported"
        );
        anyhow::ensure!(
            tc.get("use_qk_norm").and_then(|v| v.as_bool()).unwrap_or(true),
            "hunyuan_v1_dense: use_qk_norm=false is not supported"
        );
    }
    let is_dsv4 = model_type == "deepseek_v4";
    let is_dsv41 = model_type == "deepseek_v41";
    let tc_model_type = tc.get("model_type").and_then(|v| v.as_str()).unwrap_or("");
    // DeepSeek-V4: the name mapping and both source quantizations (FP8
    // E4M3 with 128x128 block scales, MXFP4 experts) are in place, but
    // five of its blocks have no runtime yet — and without them the file
    // would convert and then decode noise. Say exactly what is missing
    // here, at the config, rather than after a 167 GB download.
    if model_type == "deepseek_v4" {
        tracing::info!(
            "deepseek_v4: converting. The engine now carries all five of its \
             blocks — double-LoRA attention with a compressed KV, the per-layer \
             KV compressor, the sparse indexer, hyper-connections (Sinkhorn) and \
             hash routing — so this file is meant to DECODE, not merely to pack. \
             What has not been established is numerical parity against the \
             reference implementation: treat the first coherent generation as \
             the gate, not this message."
        );
    }
    let hidden = cfg_usize(tc, "hidden_size")
        .ok_or_else(|| anyhow::anyhow!("config: missing hidden_size"))?;
    let n_heads = cfg_usize(tc, "num_attention_heads")
        .ok_or_else(|| anyhow::anyhow!("config: missing num_attention_heads"))?;
    let n_layers = cfg_usize(tc, "num_hidden_layers")
        .ok_or_else(|| anyhow::anyhow!("config: missing num_hidden_layers"))?;
    // Linear-attention (GatedDeltaNet, Qwen3.5): the per-layer schedule comes
    // from config.layer_types; the vendor operator is carried 1:1 and we declare
    // the canonical core so the runtime dispatches it.
    let layer_types: Vec<LayerType> = match tc.get("layer_types").and_then(|v| v.as_array()) {
        Some(a) => a
            .iter()
            .map(|v| match v.as_str() {
                Some("linear_attention") => LayerType::LinearAttention,
                // LFM2 gated short convolution mixer.
                Some("conv") | Some("short_conv") => LayerType::ShortConv,
                Some("sliding_attention") => LayerType::SlidingAttention,
                _ => LayerType::FullAttention,
            })
            .collect(),
        None => vec![LayerType::FullAttention; n_layers],
    };
    // Kimi Linear / Kimi-K3: the per-layer schedule lives in
    // linear_attn_config.full_attn_layers (1-BASED layer numbers);
    // everything else is a KDA layer.
    let is_kimi =
        model_type == "kimi_linear" || model_type == "kimi_k3" || tc_model_type == "kimi_linear";
    let layer_types = if let Some(lac) = tc.get("linear_attn_config").filter(|_| is_kimi) {
        anyhow::ensure!(
            tc.get("attn_res_block_size")
                .map(|v| v.is_null())
                .unwrap_or(true),
            "kimi: attn_res_block_size residual streams (Kimi-K3) are not supported yet"
        );
        anyhow::ensure!(
            !tc.get("latent_moe_use_norm")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            "kimi: latent MoE (routed_expert_up/down_proj, Kimi-K3) is not supported yet"
        );
        anyhow::ensure!(
            !tc.get("mla_use_output_gate")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            "kimi: MLA output gate (Kimi-K3) is not supported yet"
        );
        let full: std::collections::HashSet<usize> = lac
            .get("full_attn_layers")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|v| v.as_u64())
                    .map(|v| v as usize)
                    .collect()
            })
            .unwrap_or_default();
        anyhow::ensure!(
            !full.is_empty(),
            "kimi: linear_attn_config.full_attn_layers is empty"
        );
        (1..=n_layers)
            .map(|i| {
                if full.contains(&i) {
                    LayerType::FullAttention
                } else {
                    LayerType::Kda
                }
            })
            .collect()
    } else {
        layer_types
    };
    let kimi_lac = tc.get("linear_attn_config").filter(|_| is_kimi);
    let has_linear = layer_types
        .iter()
        .any(|t| matches!(t, LayerType::LinearAttention));
    let lnv = cfg_usize(tc, "linear_num_value_heads");
    let lvd = cfg_usize(tc, "linear_value_head_dim");
    let linear_core = if has_linear {
        Some(LinearCoreConfig {
            kind: "gated_delta_net".into(),
            num_heads: lnv.unwrap_or(0),
            nphase: None,
            value_head_dim: lvd.unwrap_or(0),
        })
    } else {
        None
    };
    // Qwen3.5 nests rope params under `rope_parameters`. Laguna goes one
    // level deeper and carries independent full/sliding profiles.
    let rope_root = tc.get("rope_parameters");
    let is_laguna_config = model_type.eq_ignore_ascii_case("laguna");
    let rope = if is_laguna_config {
        rope_root.and_then(|r| r.get("full_attention"))
    } else {
        rope_root
    };
    let local_rope = if is_laguna_config {
        rope_root.and_then(|r| r.get("sliding_attention"))
    } else {
        None
    };
    let rope_theta = tc
        .get("rope_theta")
        .and_then(|v| v.as_f64())
        .or_else(|| {
            rope.and_then(|r| r.get("rope_theta"))
                .and_then(|v| v.as_f64())
        })
        .unwrap_or(10_000.0);
    let prf = tc
        .get("partial_rotary_factor")
        .and_then(|v| v.as_f64())
        .or_else(|| {
            rope.and_then(|r| r.get("partial_rotary_factor"))
                .and_then(|v| v.as_f64())
        })
        .unwrap_or(1.0) as f32;
    let local_prf = local_rope
        .and_then(|r| r.get("partial_rotary_factor"))
        .and_then(|v| v.as_f64())
        .map(|v| v as f32);
    let attention_heads_per_layer = tc
        .get("num_attention_heads_per_layer")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .map(|v| {
                    v.as_u64().map(|n| n as usize).ok_or_else(|| {
                        anyhow::anyhow!("num_attention_heads_per_layer must contain integers")
                    })
                })
                .collect::<anyhow::Result<Vec<_>>>()
        })
        .transpose()?;
    if let Some(heads) = &attention_heads_per_layer {
        anyhow::ensure!(
            heads.len() == n_layers,
            "num_attention_heads_per_layer has {} entries, expected {n_layers}",
            heads.len()
        );
        let nkv = cfg_usize(tc, "num_key_value_heads").unwrap_or(n_heads);
        anyhow::ensure!(
            heads.iter().all(|&nh| nh > 0 && nh % nkv == 0),
            "every per-layer attention head count must be positive and divisible by num_key_value_heads={nkv}"
        );
    }
    // Mixture-of-experts: the FFN becomes a router + per-expert matrices. Tensor
    // handling is unchanged (experts are ordinary 2-D matrices); we just declare
    // the MoE config so the runtime dispatches it. Router presence per layer
    // (in the directory) decides which layers are sparse.
    // DeepSeek-V2 MLA geometry (kv_lora_rank marks the family).
    let mla = cfg_usize(tc, "kv_lora_rank").map(|lora| cortiq_core::MlaConfig {
        kv_lora_rank: lora,
        qk_rope_head_dim: cfg_usize(tc, "qk_rope_head_dim").unwrap_or(64),
        qk_nope_head_dim: cfg_usize(tc, "qk_nope_head_dim").unwrap_or(128),
        v_head_dim: cfg_usize(tc, "v_head_dim").unwrap_or(128),
        q_lora_rank: cfg_usize(tc, "q_lora_rank"),
        // Kimi Linear: full-attention layers run NoPE (KDA carries
        // position) — the rotation is skipped, the layout is kept.
        nope: tc
            .get("mla_use_nope")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
    });
    let moe = tc
        .get("num_experts")
        .and_then(|v| v.as_u64())
        .or_else(|| tc.get("n_routed_experts").and_then(|v| v.as_u64()))
        .filter(|&n| n > 0)
        .map(|ne| {
            let mt = model_type.to_lowercase();
            let ntp_default = mt.starts_with("qwen3_5")
                || is_prism
                || mt.contains("qwen3_next")
                || mt.contains("qwen4_exp")
                || mt.contains("gemma4");
            // LFM2-MoE routes with a sigmoid gate + selection bias (DeepSeek-V3
            // noaux_tc); Qwen keeps the softmax-over-all default.
            let is_lfm2 = mt.starts_with("lfm2");
            let is_laguna = mt == "laguna";
            MoeConfig {
                num_experts: ne as usize,
                top_k: cfg_usize(tc, "num_experts_per_tok")
                    .or_else(|| cfg_usize(tc, "top_k_experts"))
                    // Kimi spells it with the full word.
                    .or_else(|| cfg_usize(tc, "num_experts_per_token"))
                    .unwrap_or(2),
                moe_intermediate_size: cfg_usize(tc, "moe_intermediate_size").unwrap_or(0),
                norm_topk_prob: tc
                    .get("norm_topk_prob")
                    .and_then(|v| v.as_bool())
                    // Kimi: moe_renormalize is the same switch.
                    .or_else(|| tc.get("moe_renormalize").and_then(|v| v.as_bool()))
                    // HunYuan hy_v3: route_norm.
                    .or_else(|| tc.get("route_norm").and_then(|v| v.as_bool()))
                    .unwrap_or(ntp_default),
                shared_expert_intermediate_size: cfg_usize(tc, "shared_expert_intermediate_size")
                    .or_else(|| {
                        // DeepSeek fuses its n shared experts into one
                        // MLP of n·moe_intermediate_size (Kimi spells the
                        // count num_shared_experts).
                        Some(
                            cfg_usize(tc, "n_shared_experts")
                                .or_else(|| cfg_usize(tc, "num_shared_experts"))?
                                * cfg_usize(tc, "moe_intermediate_size")?,
                        )
                    }),
                router_sigmoid: is_lfm2
                    || is_laguna
                    || tc.get("scoring_func").and_then(|v| v.as_str()) == Some("sigmoid")
                    || tc
                        .get("moe_router_activation_func")
                        .and_then(|v| v.as_str())
                        == Some("sigmoid")
                    // HunYuan hy_v3: sigmoid scores, selection by score +
                    // expert_bias, weights from the unbiased scores.
                    || tc
                        .get("moe_router_use_sigmoid")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false),
                // A stored scale of 1.0 is the no-op default; only non-trivial
                // scales need to ride in the header.
                routed_scaling_factor: tc
                    .get("routed_scaling_factor")
                    .or_else(|| tc.get("moe_routed_scaling_factor"))
                    // HunYuan hy_v3 spells it router_scaling_factor.
                    .or_else(|| tc.get("router_scaling_factor"))
                    .and_then(|v| v.as_f64())
                    .map(|v| v as f32)
                    .filter(|&v| (v - 1.0).abs() > 1e-9),
                router_resonance: false,
            }
        });
    let head_dim = cfg_usize(tc, "head_dim").unwrap_or(hidden / n_heads.max(1));
    // Zero-centered RMSNorm x̂·(1+w): Gemma family and native HF
    // Qwen3.5 / Qwen3-Next checkpoints.  Prism/Bonsai is deliberately
    // excluded: its source is the already-sanitized MLX Qwen3.5 runtime
    // (plain nn.RMSNorm weights), so applying the Gemma +1 shift here would
    // add one a second time at every input/post/final/QK norm.
    let mt = model_type.to_lowercase();
    let is_laguna = mt == "laguna";
    let is_granite = mt == "granite";
    if is_laguna {
        anyhow::ensure!(
            !tc.get("swa_attention_sink_enabled")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            "laguna: learned SWA attention sinks are not supported yet"
        );
        anyhow::ensure!(
            tc.get("moe_router_logit_softcapping")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0)
                == 0.0,
            "laguna: non-zero MoE router logit soft-capping is not supported"
        );
        anyhow::ensure!(
            !tc.get("moe_apply_router_weight_on_input")
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            "laguna: moe_apply_router_weight_on_input=true is not supported"
        );
    }
    if is_granite {
        let residual_multiplier = tc
            .get("residual_multiplier")
            .and_then(|v| v.as_f64())
            .unwrap_or(1.0);
        anyhow::ensure!(
            (residual_multiplier - 1.0).abs() <= f64::EPSILON,
            "granite: residual_multiplier={residual_multiplier} is not supported yet"
        );
    }
    let norm_style = if (mt.contains("gemma") && !mt.contains("gemma4") && !mt.contains("gemma3n"))
        || mt.starts_with("qwen3_5")
        || mt.contains("qwen3_next")
        || mt.contains("qwen4_exp")
    {
        NormStyle::Gemma
    } else {
        // Gemma-4 went back to plain x̂·w (Gemma3nRMSNorm lineage).
        NormStyle::Qwen
    };
    // Gemma family: GeGLU FFN, √hidden embedding scale, an attention
    // scale of its own, and (Gemma-3) interleaved sliding-window layers
    // with a separate local RoPE base. Gemma-2's ATTENTION soft-capping
    // is not implemented — refuse it loudly rather than emit a wrong
    // file. (Gemma-4's FINAL-logit capping is supported.)
    let is_gemma = mt.contains("gemma");
    let is_gemma4 = mt.contains("gemma4");
    // Gemma-2: attention-logit soft-capping is a supported operator
    // (tanh(s/c)·c before the causal softmax); its every-other-layer
    // sliding schedule maps onto sliding_window_pattern = 2 (full
    // attention at odd indices), same machinery as gemma-3/Laguna.
    let is_gemma2 = mt.contains("gemma2");
    // Gemma-4 (text tower): plain x̂·w norms (unlike gemma-3), dual-geometry
    // attention (sliding GQA at head_dim + global MQA at global_head_dim
    // with proportional partial rotary), scale-less V-norm, per-layer
    // output scalars and final-logit capping. The dense 12B/31B variants
    // convert; the MoE / E-series machinery is refused honestly.
    if is_gemma4 {
        if cfg_usize(tc, "hidden_size_per_layer_input").unwrap_or(0) > 0 {
            anyhow::bail!(
                "{model_type}: gemma-4 E-series per-layer inputs are not supported yet — \
                 the dense 12B/31B variants convert natively"
            );
        }
        if cfg_usize(tc, "num_kv_shared_layers").unwrap_or(0) > 0 {
            anyhow::bail!("{model_type}: gemma-4 KV-shared layers are not supported yet");
        }
    }
    // Gemma-4 keys rope_parameters by layer type: the global layers'
    // theta is the model theta, the sliding layers' theta is the local
    // base (same split gemma-3 spells with flat keys).
    let (g4_rope_theta, g4_local_theta, g4_global_prf) = match rope {
        Some(r) if is_gemma4 => {
            let full = r.get("full_attention");
            let slide = r.get("sliding_attention");
            (
                full.and_then(|f| f.get("rope_theta"))
                    .and_then(|v| v.as_f64()),
                slide
                    .and_then(|f| f.get("rope_theta"))
                    .and_then(|v| v.as_f64()),
                full.and_then(|f| f.get("partial_rotary_factor"))
                    .and_then(|v| v.as_f64())
                    .map(|v| v as f32),
            )
        }
        _ => (None, None, None),
    };
    let rope_theta = g4_rope_theta.unwrap_or(rope_theta);
    // Both spellings are in the wild: newer configs say `rope_type`, older
    // ones (DeepSeek-V4 among them) say `type`. Reading only one of them
    // drops the profile silently and the model decodes with unscaled
    // frequencies — which looks like a bad conversion, not a missing field.
    let yarn = rope
        .filter(|r| {
            r.get("rope_type")
                .or_else(|| r.get("type"))
                .and_then(|v| v.as_str())
                == Some("yarn")
        })
        .map(|r| {
            Ok::<YarnConfig, anyhow::Error>(YarnConfig {
                factor: r
                    .get("factor")
                    .and_then(|v| v.as_f64())
                    .ok_or_else(|| anyhow::anyhow!("YaRN rope profile is missing factor"))?
                    as f32,
                original_max_position_embeddings: r
                    .get("original_max_position_embeddings")
                    .and_then(|v| v.as_u64())
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "YaRN rope profile is missing original_max_position_embeddings"
                        )
                    })? as usize,
                beta_fast: r.get("beta_fast").and_then(|v| v.as_f64()).unwrap_or(32.0) as f32,
                beta_slow: r.get("beta_slow").and_then(|v| v.as_f64()).unwrap_or(1.0) as f32,
                mscale_all_dim: r
                    .get("mscale_all_dim")
                    .and_then(|v| v.as_f64())
                    .map(|v| v as f32),
                attention_factor: r
                    .get("attention_factor")
                    .and_then(|v| v.as_f64())
                    .unwrap_or_else(|| {
                        let factor = r.get("factor").and_then(|v| v.as_f64()).unwrap_or(1.0);
                        0.1 * factor.ln() + 1.0
                    }) as f32,
            })
        })
        .transpose()?;
    // Sliding pattern from the explicit layer-type list: full layers must
    // sit at every P-th position ((i+1) % P == 0), which is how the
    // runtime models the cadence.
    let g4_pattern: Option<usize> = if is_gemma4 {
        let fulls: Vec<usize> = tc
            .get("layer_types")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .enumerate()
                    .filter(|(_, v)| v.as_str() == Some("full_attention"))
                    .map(|(i, _)| i)
                    .collect()
            })
            .unwrap_or_default();
        let p = fulls.first().map(|f| f + 1).unwrap_or(0);
        if p == 0
            || fulls.iter().enumerate().any(|(k, &i)| i != p * (k + 1) - 1)
            || (n_layers / p) != fulls.len()
        {
            anyhow::bail!("{model_type}: irregular full/sliding layer schedule not supported");
        }
        Some(p)
    } else {
        None
    };
    let hidden_act = match tc
        .get("hidden_activation")
        .or_else(|| tc.get("hidden_act"))
        .and_then(|v| v.as_str())
        .unwrap_or("silu")
    {
        "gelu_pytorch_tanh" | "gelu_tanh" | "gelu_new" => "gelu_tanh".to_string(),
        "silu" | "swish" => "silu".to_string(),
        other => anyhow::bail!("unsupported hidden_act '{other}'"),
    };
    let is_minicpm3 = model_type == "minicpm3";
    let embed_multiplier = if is_granite {
        tc.get("embedding_multiplier")
            .and_then(|v| v.as_f64())
            .unwrap_or(1.0) as f32
    } else if is_gemma {
        (hidden as f32).sqrt()
    } else if is_minicpm3 {
        // MiniCPM: embeddings enter the stack ×scale_emb.
        tc.get("scale_emb").and_then(|v| v.as_f64()).unwrap_or(1.0) as f32
    } else {
        1.0
    };
    // MiniCPM: logits = lm_head(h) · dim_model_base/hidden; the head is
    // tied to the embedding, so the divisor rides in the header.
    let logit_multiplier = if is_granite {
        let divisor = tc
            .get("logits_scaling")
            .and_then(|v| v.as_f64())
            .unwrap_or(1.0);
        anyhow::ensure!(
            divisor.is_finite() && divisor > 0.0,
            "granite: logits_scaling must be finite and positive"
        );
        let multiplier = (1.0 / divisor) as f32;
        ((multiplier - 1.0).abs() > f32::EPSILON).then_some(multiplier)
    } else if is_minicpm3 {
        cfg_usize(tc, "dim_model_base").map(|d| d as f32 / hidden as f32)
    } else {
        None
    };
    // Gemma-3n (E-series): AltUp/LAuReL/PLE/KV-sharing geometry rides
    // in the header; the runtime switches to the dedicated stack.
    let is_gemma3n = model_type.starts_with("gemma3n") || tc_model_type.starts_with("gemma3n");
    let g3n_cfg: Option<cortiq_core::G3nConfig> = if is_gemma3n {
        let need = |k: &str| {
            cfg_usize(tc, k).ok_or_else(|| anyhow::anyhow!("gemma3n: config missing {k}"))
        };
        Some(cortiq_core::G3nConfig {
            altup_num_inputs: need("altup_num_inputs")?,
            laurel_rank: need("laurel_rank")?,
            ple_dim: need("hidden_size_per_layer_input")?,
            ple_vocab: need("vocab_size_per_layer_input")?,
            num_kv_shared_layers: need("num_kv_shared_layers")?,
            activation_sparsity: tc
                .get("activation_sparsity_pattern")
                .and_then(|v| v.as_array())
                .map(|a| {
                    a.iter()
                        .filter_map(|v| v.as_f64())
                        .map(|v| v as f32)
                        .collect()
                })
                .unwrap_or_default(),
        })
    } else {
        None
    };
    let mut rope_freq_factors: Option<Vec<f64>> = None;
    // Phi-3 longrope: exact only within the ORIGINAL context — cap the
    // declared max honestly instead of serving stretched positions.
    let mut max_pos =
        cfg_usize(tc, "max_position_embeddings").unwrap_or(if is_kimi { 1_048_576 } else { 32768 });
    let mut ntk_theta: Option<f64> = None;
    if let Some(rs) = tc.get("rope_scaling").filter(|v| !v.is_null()) {
        let kind = rs
            .get("type")
            .or_else(|| rs.get("rope_type"))
            .and_then(|v| v.as_str());
        // HunYuan "dynamic" + alpha is NTK-alpha: ONE rescaled base,
        // base' = base · alpha^(d/(d−2)), fixed for every position — the
        // reference rotary module computes exactly this and never
        // rescales at inference. (Hy-MT2: 10000 · 1000^(128/126) =
        // 11 158 840, the value llama.cpp writes as rope.freq_base.)
        let ntk_alpha = rs
            .get("alpha")
            .and_then(|v| v.as_f64())
            .filter(|&a| a > 0.0 && (a - 1.0).abs() > 1e-12);
        match kind {
            Some("dynamic") if ntk_alpha.is_some() => {
                let alpha = ntk_alpha.unwrap();
                let d = head_dim as f64;
                let theta = rope_theta * alpha.powf(d / (d - 2.0));
                eprintln!(
                    "  rope: NTK-alpha {alpha} → base {theta:.1} (head_dim {head_dim}); \
                     the full {max_pos}-token window is native"
                );
                ntk_theta = Some(theta);
            }
            Some("longrope") | Some("su") | Some("yarn") | Some("linear") | Some("dynamic")
            | Some("mrope") => {
                let orig = cfg_usize(tc, "original_max_position_embeddings")
                    .or_else(|| {
                        rs.get("original_max_position_embeddings")
                            .and_then(|v| v.as_u64().map(|v| v as usize))
                    })
                    .unwrap_or(4096);
                eprintln!(
                    "  note: rope scaling '{:?}' — serving the exact {orig}-token native window",
                    kind.unwrap()
                );
                max_pos = orig;
                // MiniCPM3: the short factors are the TRAINED rope inside
                // the native window (1.06–16.9 per dim — not ≈1 like phi);
                // carry them so inv_freq divides per frequency at load.
                if is_minicpm3 {
                    if let Some(f) = rs.get("short_factor").and_then(|v| v.as_array()) {
                        let fac: Vec<f64> = f.iter().filter_map(|v| v.as_f64()).collect();
                        anyhow::ensure!(!fac.is_empty(), "minicpm3: empty longrope short_factor");
                        rope_freq_factors = Some(fac);
                    }
                }
            }
            Some(other) => anyhow::bail!("rope_scaling '{other}' not supported yet"),
            None => {}
        }
    }
    Ok(ModelArch {
        arch_name: model_type.clone(),
        hidden_size: hidden,
        intermediate_size: cfg_usize(tc, "intermediate_size")
            .or_else(|| {
                // Gemma-3n stores a per-layer LIST; E-models keep it
                // uniform — take the head and insist on uniformity.
                tc.get("intermediate_size")
                    .and_then(|v| v.as_array())
                    .and_then(|a| {
                        let first = a.first()?.as_u64()?;
                        a.iter()
                            .all(|v| v.as_u64() == Some(first))
                            .then_some(first as usize)
                    })
            })
            .or_else(|| cfg_usize(tc, "moe_intermediate_size"))
            .ok_or_else(|| anyhow::anyhow!("config: missing intermediate_size"))?,
        num_layers: n_layers,
        num_attention_heads: n_heads,
        num_kv_heads: cfg_usize(tc, "num_key_value_heads").unwrap_or(n_heads),
        head_dim,
        vocab_size: cfg_usize(tc, "vocab_size")
            .ok_or_else(|| anyhow::anyhow!("config: missing vocab_size"))?,
        layer_types,
        // LFM2 spells the RMSNorm epsilon `norm_eps`.
        rms_norm_eps: tc
            .get("rms_norm_eps")
            .or_else(|| tc.get("norm_eps"))
            .and_then(|v| v.as_f64())
            .unwrap_or(1e-6),
        norm_style,
        rope_theta: ntk_theta.unwrap_or(rope_theta),
        // Gemma ties embeddings by default and its configs omit the key.
        tie_word_embeddings: config
            .get("tie_word_embeddings")
            .and_then(|v| v.as_bool())
            // MiniCPM3 ships no lm_head tensor — the head is the embedding.
            .unwrap_or(is_gemma || is_minicpm3),
        // DeepSeek-V4 rotates only `qk_rope_head_dim` of each head's 512,
        // and its config states that directly rather than as a fraction.
        // Carrying it here is what lets a retuned checkpoint load without
        // the loader guessing.
        partial_rotary_factor: if is_dsv4 || is_dsv41 {
            match (cfg_usize(tc, "qk_rope_head_dim"), cfg_usize(tc, "head_dim")) {
                (Some(rd), Some(hd)) if hd > 0 => rd as f32 / hd as f32,
                _ => prf,
            }
        } else {
            prf
        },
        yarn,
        attention_heads_per_layer,
        // MTP head, when the checkpoint ships one. Qwen3.6 spells the count
        // `mtp_num_hidden_layers`; DeepSeek-lineage configs say
        // `num_nextn_predict_layers`. Absent → no speculative head, which is
        // the honest default for every model that has none.
        mtp: if mt.contains("qwen4_exp") {
            // qwen4_exp ships a second hyper-connected hybrid stack.  It is
            // not wire-compatible with the legacy DeepSeek/Qwen MTP block;
            // leave it out until that speculative-only head has an exact op.
            None
        } else {
            ["mtp_num_hidden_layers", "num_nextn_predict_layers"]
                .iter()
                .find_map(|k| cfg_usize(tc, k))
                .filter(|n| *n > 0)
                .map(|n| cortiq_core::MtpConfig {
                    num_layers: n,
                    share_lm_head: true,
                    share_embed: true,
                })
        },
        moe,
        qwen4_exp: (model_type == "qwen4_exp").then(|| Qwen4ExpConfig {
            hc_count: cfg_usize(tc, "hc_count").unwrap_or(4),
            hc_lowrank: cfg_usize(tc, "hc_lowrank").unwrap_or(320),
            indexer_n_heads: cfg_usize(tc, "indexer_n_heads").unwrap_or(4),
            indexer_kv_heads: cfg_usize(tc, "indexer_kv_heads").unwrap_or(1),
            indexer_head_dim: cfg_usize(tc, "indexer_head_dim").unwrap_or(128),
            indexer_budget: cfg_usize(tc, "indexer_budget").unwrap_or(2048),
            indexer_compress_ratio: cfg_usize(tc, "indexer_compress_ratio").unwrap_or(4),
            ple_layer_ids: tc
                .get("ple_layer_ids")
                .and_then(|v| v.as_array())
                .map(|a| {
                    a.iter()
                        .filter_map(|v| v.as_u64().map(|n| n as usize))
                        .collect()
                })
                .unwrap_or_else(|| vec![2]),
            ple_embed_dim: cfg_usize(tc, "ple_embed_dim").unwrap_or(hidden),
            ple_conv_kernel_size: cfg_usize(tc, "ple_conv_kernel_size").unwrap_or(4),
            ngram_size: cfg_usize(tc, "ngram_size").unwrap_or(3),
            heads_per_ngram: cfg_usize(tc, "heads_per_ngram").unwrap_or(8),
            ngram_vocab_size_base: cfg_usize(tc, "ngram_vocab_size_base").unwrap_or(20_000_000),
            make_ngram_vocab_size_divisible_by: cfg_usize(tc, "make_ngram_vocab_size_divisible_by")
                .unwrap_or(128),
            split_ngram_parts: cfg_usize(tc, "split_ngram_parts").unwrap_or(128),
            seed: cfg_usize(tc, "seed").unwrap_or(1234) as u64,
        }),
        // Keep the complete original HF object, including the text/vision
        // sub-configs and quantization policy. V4.1 runtime initialization
        // consumes this verbatim for multimodal and Engram geometry.
        deepseek_v41: is_dsv41.then(|| config.clone()),
        linear_core,
        head_clusters: None,
        max_position_embeddings: max_pos,
        // GDN spells it `linear_conv_kernel_dim`; LFM2 spells it
        // `conv_L_cache`; Kimi nests KDA geometry in linear_attn_config.
        linear_conv_kernel_dim: cfg_usize(tc, "linear_conv_kernel_dim")
            .or_else(|| cfg_usize(tc, "conv_L_cache"))
            .or_else(|| kimi_lac.and_then(|l| cfg_usize(l, "short_conv_kernel_size"))),
        linear_num_key_heads: cfg_usize(tc, "linear_num_key_heads")
            .or_else(|| kimi_lac.and_then(|l| cfg_usize(l, "num_heads"))),
        linear_num_value_heads: lnv,
        linear_key_head_dim: cfg_usize(tc, "linear_key_head_dim")
            .or_else(|| kimi_lac.and_then(|l| cfg_usize(l, "head_dim"))),
        linear_value_head_dim: lvd.or_else(|| kimi_lac.and_then(|l| cfg_usize(l, "head_dim"))),
        hidden_act,
        embed_multiplier,
        // Gemma-4 attends with scaling = 1.0 (q-norm carries the scale).
        query_pre_attn_scalar: tc
            .get("query_pre_attn_scalar")
            .and_then(|v| v.as_f64())
            // Granite specifies the DIRECT multiplier on QK^T.  CMF stores
            // the equivalent denominator s where the runtime uses 1/sqrt(s).
            .or_else(|| {
                tc.get("attention_multiplier")
                    .and_then(|v| v.as_f64())
                    .filter(|&v| v.is_finite() && v > 0.0)
                    .map(|v| 1.0 / (v * v))
            })
            // Gemma-4 and Gemma-3n attend with scale 1.0 (q-norm carries it).
            .or(if is_gemma4 || is_gemma3n {
                Some(1.0)
            } else {
                None
            }),
        sliding_window: cfg_usize(tc, "sliding_window").filter(|_| {
            is_laguna
                || is_gemma2
                || is_gemma3n
                || tc.get("sliding_window_pattern").is_some()
                || g4_pattern.is_some()
        }),
        sliding_window_pattern: cfg_usize(tc, "sliding_window_pattern")
            .or(g4_pattern)
            .or(if is_gemma2 { Some(2) } else { None }),
        rope_local_base_freq: tc
            .get("rope_local_base_freq")
            .and_then(|v| v.as_f64())
            .or(g4_local_theta)
            .or_else(|| {
                local_rope
                    .and_then(|r| r.get("rope_theta"))
                    .and_then(|v| v.as_f64())
            }),
        local_partial_rotary_factor: local_prf,
        global_head_dim: cfg_usize(tc, "global_head_dim").filter(|_| is_gemma4),
        num_global_kv_heads: cfg_usize(tc, "num_global_key_value_heads").filter(|_| is_gemma4),
        global_partial_rotary_factor: g4_global_prf,
        final_logit_softcapping: tc.get("final_logit_softcapping").and_then(|v| v.as_f64()),
        attn_logit_softcapping: tc.get("attn_logit_softcapping").and_then(|v| v.as_f64()),
        mla,
        activation_situ_beta: tc.get("activation_situ_beta").and_then(|v| v.as_f64()),
        activation_situ_linear_beta: tc
            .get("activation_situ_linear_beta")
            .and_then(|v| v.as_f64()),
        attn_v_norm: is_gemma4,
        qk_norm_after_rope: is_hunyuan_dense,
        rope_freq_factors,
        logit_multiplier,
        g3n: g3n_cfg,
        // KDA (Kimi-K3): lower-bound decay-gate variant; absent = standard.
        kda_gate_lower_bound: tc
            .get("linear_attn_config")
            .and_then(|c| c.get("gate_lower_bound"))
            .and_then(|v| v.as_f64()),
        // Looped Transformer (Nanbeige 4.2): re-apply the layer stack num_loops times.
        num_loops: cfg_usize(tc, "num_loops").unwrap_or(1),
        // skip_loop_final_norm=false means loop_final_norm=true (apply norm after each loop).
        loop_final_norm: !tc
            .get("skip_loop_final_norm")
            .and_then(|v| v.as_bool())
            .unwrap_or(true),
        prism_hadamard: None,
    })
}

/// Load and validate the source-side Hadamard manifest for Prism/Bonsai.
/// Keeping it in the CMF header makes a converted file independently
/// executable; no `.signs` sidecar is consulted by the runtime.
fn load_prism_hadamard(
    dir: &Path,
    config: &serde_json::Value,
) -> anyhow::Result<Option<PrismHadamardConfig>> {
    if config.get("model_type").and_then(|v| v.as_str()) != Some("prism_hadamard_qwen35") {
        return Ok(None);
    }
    let rel = config
        .get("hadamard_config")
        .and_then(|v| v.as_str())
        .unwrap_or("hadamard.json");
    anyhow::ensure!(
        Path::new(rel).is_relative() && !rel.contains(".."),
        "invalid Prism hadamard_config path {rel:?}"
    );
    let raw = fs::read(dir.join(rel)).map_err(|e| {
        anyhow::anyhow!(
            "Prism checkpoint requires Hadamard manifest {}: {e}",
            dir.join(rel).display()
        )
    })?;
    let source: serde_json::Value = serde_json::from_slice(&raw)?;
    let widths: Vec<usize> = source
        .get("prism.hadamard.sign_widths")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Prism Hadamard manifest has no sign_widths"))?
        .iter()
        .map(|v| {
            v.as_u64()
                .map(|n| n as usize)
                .ok_or_else(|| anyhow::anyhow!("Prism Hadamard sign_widths must be integers"))
        })
        .collect::<anyhow::Result<_>>()?;
    let signs: Vec<f32> = source
        .get("prism.hadamard.sign_values")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Prism Hadamard manifest has no sign_values"))?
        .iter()
        .map(|v| {
            v.as_f64()
                .map(|n| n as f32)
                .ok_or_else(|| anyhow::anyhow!("Prism Hadamard sign_values must be numbers"))
        })
        .collect::<anyhow::Result<_>>()?;
    let cfg = PrismHadamardConfig {
        version: source
            .get("prism.hadamard.version")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as u32,
        block_size: source
            .get("prism.hadamard.block_size")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as usize,
        transform: source
            .get("prism.hadamard.transform")
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string(),
        axis: source
            .get("prism.hadamard.axis")
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string(),
        sign_mode: source
            .get("prism.hadamard.sign_mode")
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string(),
        widths,
        signs,
        forward_weight_names: source
            .get("prism.hadamard.weight_names")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default(),
        inverse_weight_names: source
            .get("prism.hadamard.inverse_weight_names")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default(),
        gdn_v_grouped: source
            .get("prism.hadamard.gdn_v_grouped")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
        activation_f16: true,
        affine: None,
    };
    cfg.validate().map_err(|e| anyhow::anyhow!(e))?;
    Ok(Some(cfg))
}

/// Collect eos ids from generation_config.json / config.json (int or array).
fn eos_ids(gen_cfg: &serde_json::Value, config: &serde_json::Value) -> Vec<u32> {
    for v in [gen_cfg.get("eos_token_id"), config.get("eos_token_id")]
        .into_iter()
        .flatten()
    {
        if let Some(n) = v.as_u64() {
            return vec![n as u32];
        }
        if let Some(a) = v.as_array() {
            return a
                .iter()
                .filter_map(|x| x.as_u64().map(|n| n as u32))
                .collect();
        }
    }
    Vec::new()
}

/// `owner/name` HF repo id (not an existing local path).
pub(crate) fn looks_like_repo(s: &str) -> bool {
    let s = s.trim_matches('/');
    s.split('/').count() == 2 && !s.contains(char::is_whitespace) && !Path::new(s).exists()
}

/// A fresh ureq agent with the same timeouts the downloader uses.
fn hf_agent() -> ureq::Agent {
    ureq::AgentBuilder::new()
        .timeout_connect(Duration::from_secs(20))
        .timeout_read(Duration::from_secs(300))
        .build()
}

/// List a repo's files via the HF API (best-effort; empty on failure). Reused by
/// the GGUF importer to pick a `.gguf` from a repo.
pub(crate) fn hf_repo_files(repo: &str, token: Option<&str>) -> Vec<String> {
    repo_files(&hf_agent(), repo, token)
}

/// Download a single named file from an HF repo into the cache (parallel chunks
/// for large files); returns its local path. Used to fetch one `.gguf`.
pub(crate) fn hf_fetch_file(
    repo: &str,
    filename: &str,
    token: Option<&str>,
) -> anyhow::Result<std::path::PathBuf> {
    let dir = hf_cache_dir(repo)?;
    let dest = dir.join(filename.replace('/', "__"));
    let url = format!("https://huggingface.co/{repo}/resolve/main/{filename}");
    fetch(&hf_agent(), &url, &dest, token, true, hf_threads())?;
    Ok(dest)
}

/// Local cache dir for a downloaded HF repo (`~/.cache/cortiq/hf/owner--name`).
fn hf_cache_dir(repo: &str) -> anyhow::Result<std::path::PathBuf> {
    let base = std::env::var_os("HOME")
        .map(|h| std::path::PathBuf::from(h).join(".cache/cortiq/hf"))
        .unwrap_or_else(|| std::path::PathBuf::from(".cortiq-hf"));
    let dir = base.join(repo.replace('/', "--"));
    fs::create_dir_all(&dir)?;
    Ok(dir)
}

/// Parallel range chunk size (32 MiB), default connection count, and the
/// safety ceiling for user-selected parallelism.  The ceiling bounds worker
/// threads, simultaneous range buffers, and the corresponding HTTP sockets.
const HF_CHUNK: u64 = 32 * 1024 * 1024;
const HF_DEFAULT_THREADS: usize = 8;
const HF_MAX_THREADS: usize = 64;

fn parse_hf_threads(value: Option<&str>) -> usize {
    value
        .map(str::trim)
        .and_then(|v| v.parse::<usize>().ok())
        .filter(|&n| n >= 1)
        .unwrap_or(HF_DEFAULT_THREADS)
        .min(HF_MAX_THREADS)
}

fn hf_threads() -> usize {
    parse_hf_threads(std::env::var("CORTIQ_HF_THREADS").ok().as_deref())
}

/// Build disjoint half-open byte ranges for a remote file.  Keeping this as a
/// small pure helper makes the partitioning contract explicit and testable;
/// the downloader still uses one fixed 32 MiB range size, so each worker has a
/// bounded response buffer.
fn plan_hf_ranges(size: u64, chunk: u64) -> Vec<(u64, u64)> {
    if size == 0 || chunk == 0 {
        return Vec::new();
    }
    let mut ranges = Vec::new();
    let mut start = 0u64;
    while start < size {
        let end = start.saturating_add(chunk).min(size);
        ranges.push((start, end));
        start = end;
    }
    ranges
}

fn cached(dest: &Path) -> bool {
    dest.exists() && fs::metadata(dest).map(|m| m.len() > 0).unwrap_or(false)
}

fn auth(mut req: ureq::Request, token: Option<&str>) -> ureq::Request {
    req = req.set("User-Agent", "cortiq-convert");
    if let Some(t) = token {
        req = req.set("Authorization", &format!("Bearer {t}"));
    }
    req
}

/// Total size of a remote file via a `Range: bytes=0-0` probe (Content-Range),
/// or None if the server doesn't support/report ranges (→ single stream).
fn probe_size(agent: &ureq::Agent, url: &str, token: Option<&str>) -> Option<u64> {
    let resp = auth(agent.get(url).set("Range", "bytes=0-0"), token)
        .call()
        .ok()?;
    resp.header("Content-Range")?
        .rsplit('/')
        .next()?
        .trim()
        .parse::<u64>()
        .ok()
}

fn get_range(
    agent: &ureq::Agent,
    url: &str,
    token: Option<&str>,
    start: u64,
    end: u64,
) -> anyhow::Result<Vec<u8>> {
    let resp = auth(
        agent
            .get(url)
            .set("Range", &format!("bytes={}-{}", start, end - 1)),
        token,
    )
    .call()
    .map_err(|e| anyhow::anyhow!("{e}"))?;
    let mut buf = Vec::with_capacity((end - start) as usize);
    resp.into_reader().read_to_end(&mut buf)?;
    Ok(buf)
}

fn write_at(path: &Path, offset: u64, data: &[u8]) -> std::io::Result<()> {
    use std::io::{Seek, SeekFrom, Write};
    let mut f = fs::OpenOptions::new().write(true).open(path)?;
    f.seek(SeekFrom::Start(offset))?;
    f.write_all(data)
}

/// Retry `f` with exponential backoff — smooths over transient network errors.
fn with_retry<T>(attempts: u32, mut f: impl FnMut() -> anyhow::Result<T>) -> anyhow::Result<T> {
    let mut delay = Duration::from_millis(400);
    let mut last: Option<anyhow::Error> = None;
    for a in 0..attempts {
        match f() {
            Ok(v) => return Ok(v),
            Err(e) => {
                last = Some(e);
                if a + 1 < attempts {
                    std::thread::sleep(delay);
                    delay = (delay * 2).min(Duration::from_secs(8));
                }
            }
        }
    }
    Err(last.unwrap())
}

/// Fetch one file into `dest` (cached). Large range-capable files are pulled in
/// parallel 32 MiB chunks over `threads` reused connections; otherwise a single
/// stream. Returns false on 404 when `required` is false.
fn fetch(
    agent: &ureq::Agent,
    url: &str,
    dest: &Path,
    token: Option<&str>,
    required: bool,
    threads: usize,
) -> anyhow::Result<bool> {
    // Keep the resource bound at the downloader boundary as well as in the
    // environment parser: all current callers use `hf_threads`, but this
    // prevents a future/internal caller from bypassing the 64-worker cap.
    let threads = threads.min(HF_MAX_THREADS);
    if cached(dest) {
        return Ok(true);
    }
    let tmp = dest.with_extension("part");
    let size = probe_size(agent, url, token);
    if let Some(sz) = size {
        if sz > HF_CHUNK && threads > 1 {
            {
                let f = fs::File::create(&tmp)?;
                f.set_len(sz)?;
            }
            let chunks = plan_hf_ranges(sz, HF_CHUNK);
            let total = chunks.len();
            let queue = Mutex::new(chunks);
            let err: Mutex<Option<String>> = Mutex::new(None);
            let done = std::sync::atomic::AtomicUsize::new(0);
            std::thread::scope(|scope| {
                // Do not create idle workers when a small file has only a
                // handful of ranges; this also keeps the resource bound
                // proportional to useful work.
                for _ in 0..threads.min(total) {
                    scope.spawn(|| {
                        loop {
                            if err.lock().unwrap().is_some() {
                                break;
                            }
                            let Some((start, end)) = queue.lock().unwrap().pop() else {
                                break;
                            };
                            // Each chunk retries on a transient failure before aborting.
                            let r = with_retry(4, || get_range(agent, url, token, start, end))
                                .and_then(|buf| write_at(&tmp, start, &buf).map_err(Into::into));
                            match r {
                                Ok(()) => {
                                    let d =
                                        done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
                                    eprint!(
                                        "\r    downloading: {:>3}% ({d}/{total} chunks)",
                                        d * 100 / total
                                    );
                                }
                                Err(e) => {
                                    *err.lock().unwrap() = Some(e.to_string());
                                    break;
                                }
                            }
                        }
                    });
                }
            });
            eprintln!();
            if let Some(e) = err.into_inner().unwrap() {
                anyhow::bail!("download {url}: {e}");
            }
            fs::rename(&tmp, dest)?;
            return Ok(true);
        }
    }
    // Small file / no range support → single stream (with retry). Returns
    // Some(()) on success, None on an allowed 404 (optional file).
    let got = with_retry(4, || match auth(agent.get(url), token).call() {
        Ok(resp) => {
            let mut r = resp.into_reader();
            let mut f = fs::File::create(&tmp)?;
            std::io::copy(&mut r, &mut f)?;
            Ok(Some(()))
        }
        Err(ureq::Error::Status(404, _)) if !required => Ok(None),
        Err(e) => Err(anyhow::anyhow!("download {url}: {e}")),
    })?;
    match got {
        Some(()) => {
            fs::rename(&tmp, dest)?;
            Ok(true)
        }
        None => Ok(false),
    }
}

/// List a repo's file names via the HF API (best-effort; empty on any failure).
fn repo_files(agent: &ureq::Agent, repo: &str, token: Option<&str>) -> Vec<String> {
    let url = format!("https://huggingface.co/api/models/{repo}");
    match auth(agent.get(&url), token).call() {
        Ok(resp) => resp
            .into_json::<serde_json::Value>()
            .ok()
            .and_then(|j| {
                j["siblings"].as_array().map(|a| {
                    a.iter()
                        .filter_map(|s| s["rfilename"].as_str().map(String::from))
                        .collect()
                })
            })
            .unwrap_or_default(),
        Err(_) => Vec::new(),
    }
}

/// Fetch a HF repo's convertible files (config, tokenizer, weights) into the
/// cache, with parallel chunked downloads for the weight shards.
pub(crate) fn hf_download(repo: &str, token: Option<&str>) -> anyhow::Result<std::path::PathBuf> {
    Ok(hf_download_opts(repo, token, true)?.0)
}

/// `weights=false`: fetch only config/tokenizer/index and RETURN the
/// weight-shard names without downloading them — the streaming convert
/// pulls them one at a time (peak disk = one shard + the output).
pub(crate) fn hf_download_opts(
    repo: &str,
    token: Option<&str>,
    weights: bool,
) -> anyhow::Result<(std::path::PathBuf, Vec<String>)> {
    let dir = hf_cache_dir(repo)?;
    let base = format!("https://huggingface.co/{repo}/resolve/main");
    let threads = hf_threads();
    let agent = ureq::AgentBuilder::new()
        .timeout_connect(Duration::from_secs(20))
        .timeout_read(Duration::from_secs(300))
        .build();
    // config.json is mandatory for the safetensors path. If it is absent, give an
    // actionable message rather than a raw 404 — most often the repo is a GGUF-only
    // distribution (has `*.gguf`, no `config.json`), which needs a different tool.
    if !fetch(
        &agent,
        &format!("{base}/config.json"),
        &dir.join("config.json"),
        token,
        false,
        threads,
    )? {
        let files = repo_files(&agent, repo, token);
        let ggufs = files
            .iter()
            .filter(|f| f.to_lowercase().ends_with(".gguf"))
            .count();
        if ggufs > 0 {
            let src = repo
                .strip_suffix("-GGUF")
                .or_else(|| repo.strip_suffix("-gguf"))
                .filter(|s| !s.is_empty());
            anyhow::bail!(
                "'{repo}' is a GGUF repository ({ggufs} .gguf file(s), no config.json); \
                 `cortiq convert` needs a safetensors checkpoint. Either import a GGUF file \
                 directly with `cortiq import-gguf <file.gguf>` (dense llama/qwen2/qwen3, F32/F16/Q8_0), \
                 or convert the source safetensors repo instead{}.",
                match src {
                    Some(s) => format!(" — try `--model {s}`"),
                    None => String::new(),
                }
            );
        }
        anyhow::bail!("'{repo}': no config.json — not a Hugging Face safetensors checkpoint");
    }
    for (f, required) in [
        // Prism/Bonsai's signed FWHT descriptor is part of the checkpoint
        // identity.  It is optional for ordinary HF models and therefore
        // fetched best-effort here.
        ("hadamard.json", false),
        // Kimi ships tiktoken.model instead of tokenizer.json — either
        // satisfies the bundle (checked after conversion).
        ("tokenizer.json", false),
        ("tiktoken.model", false),
        ("tokenizer_config.json", false),
        ("generation_config.json", false),
        // Newer HF checkpoints (LFM2, Qwen3, …) ship the chat template as a
        // sidecar `chat_template.jinja` instead of embedding it in
        // tokenizer_config.json — without it `run` falls back to a generic
        // ChatML default that does not match the model's real format.
        ("chat_template.jinja", false),
    ] {
        fetch(
            &agent,
            &format!("{base}/{f}"),
            &dir.join(f),
            token,
            required,
            threads,
        )?;
    }
    let idx = dir.join("model.safetensors.index.json");
    if fetch(
        &agent,
        &format!("{base}/model.safetensors.index.json"),
        &idx,
        token,
        false,
        1,
    )? {
        let j: serde_json::Value = serde_json::from_slice(&fs::read(&idx)?)?;
        let map = j["weight_map"]
            .as_object()
            .ok_or_else(|| anyhow::anyhow!("bad safetensors index"))?;
        let mut shards: Vec<String> = map
            .values()
            .filter_map(|v| v.as_str().map(String::from))
            .collect();
        shards.sort();
        shards.dedup();
        if weights {
            for (i, s) in shards.iter().enumerate() {
                eprintln!(
                    "  shard {}/{} ({threads}× parallel): {s}",
                    i + 1,
                    shards.len()
                );
                fetch(
                    &agent,
                    &format!("{base}/{s}"),
                    &dir.join(s),
                    token,
                    true,
                    threads,
                )?;
            }
        }
        return Ok((dir, shards));
    } else if weights {
        eprintln!("  model.safetensors ({threads}× parallel)");
        fetch(
            &agent,
            &format!("{base}/model.safetensors"),
            &dir.join("model.safetensors"),
            token,
            true,
            threads,
        )?;
    }
    Ok((dir, vec!["model.safetensors".to_string()]))
}

/// Split a fused GDN projection (`in_proj_qkvz` or `in_proj_ba`) into the
/// canonical hub tensors. The fused weight is `[nk · group_width, hid]`; rows
/// are grouped by k-head. This mirrors transformers' `fix_query_key_value_ordering`
/// inverse — a pure row permutation, no value changes. Returns `(name, values,
/// out_rows)` for each produced tensor.
fn split_fused_gdn(
    name: &str,
    w: &[f32],
    hid: usize,
    nk: usize,
    dk: usize,
    nv: usize,
    dv: usize,
) -> anyhow::Result<Vec<(String, Vec<f32>, usize)>> {
    if nk == 0 || nv % nk != 0 {
        anyhow::bail!("fused GDN: bad head config nk={nk} nv={nv}");
    }
    let r = nv / nk;
    // Row `g·gw + gr` of the source (group g, within-group row gr).
    let row = |w: &[f32], gw: usize, g: usize, gr: usize| -> Vec<f32> {
        let base = (g * gw + gr) * hid;
        w[base..base + hid].to_vec()
    };

    if name.contains("in_proj_qkvz") {
        let gw = 2 * dk + 2 * r * dv;
        if w.len() != nk * gw * hid {
            anyhow::bail!(
                "fused GDN qkvz: {} values, expected {}",
                w.len(),
                nk * gw * hid
            );
        }
        // qkv = [q: nk·dk][k: nk·dk][v: nv·dv]
        let mut qkv = Vec::with_capacity((2 * nk * dk + nv * dv) * hid);
        for g in 0..nk {
            for rr in 0..dk {
                qkv.extend_from_slice(&row(w, gw, g, rr));
            }
        }
        for g in 0..nk {
            for rr in 0..dk {
                qkv.extend_from_slice(&row(w, gw, g, dk + rr));
            }
        }
        for g in 0..nk {
            for rr in 0..r * dv {
                qkv.extend_from_slice(&row(w, gw, g, 2 * dk + rr));
            }
        }
        // z = nv·dv
        let mut z = Vec::with_capacity(nv * dv * hid);
        for g in 0..nk {
            for rr in 0..r * dv {
                z.extend_from_slice(&row(w, gw, g, 2 * dk + r * dv + rr));
            }
        }
        let p = name.strip_suffix("in_proj_qkvz.weight").unwrap_or(name);
        Ok(vec![
            (format!("{p}in_proj_qkv.weight"), qkv, 2 * nk * dk + nv * dv),
            (format!("{p}in_proj_z.weight"), z, nv * dv),
        ])
    } else {
        // in_proj_ba: group width 2·r → b (first r per group), a (next r) → nv rows each.
        let gw = 2 * r;
        if w.len() != nk * gw * hid {
            anyhow::bail!(
                "fused GDN ba: {} values, expected {}",
                w.len(),
                nk * gw * hid
            );
        }
        let mut b = Vec::with_capacity(nv * hid);
        let mut a = Vec::with_capacity(nv * hid);
        for g in 0..nk {
            for rr in 0..r {
                b.extend_from_slice(&row(w, gw, g, rr));
            }
        }
        for g in 0..nk {
            for rr in 0..r {
                a.extend_from_slice(&row(w, gw, g, r + rr));
            }
        }
        let p = name.strip_suffix("in_proj_ba.weight").unwrap_or(name);
        Ok(vec![
            (format!("{p}in_proj_b.weight"), b, nv),
            (format!("{p}in_proj_a.weight"), a, nv),
        ])
    }
}

/// Convert a HF model (local directory or `owner/name` repo id) to a `.cmf`
/// file. `progress` receives fraction 0..1 (streamed as `@PROGRESS` markers).
// ───────────────────────── defrag (spec §11, Patent 2 claims 9/10) ─────────────────────────

enum FfnKind {
    Gate,
    Up,
    Down,
}

/// Match `model.layers.{li}.mlp.{gate|up|down}_proj.weight` → (layer, kind).
fn ffn_kind(name: &str) -> Option<(usize, FfnKind)> {
    let rest = name.strip_prefix("model.layers.")?;
    let dot = rest.find('.')?;
    let li: usize = rest[..dot].parse().ok()?;
    let kind = match &rest[dot + 1..] {
        "mlp.gate_proj.weight" => FfnKind::Gate,
        "mlp.up_proj.weight" => FfnKind::Up,
        "mlp.down_proj.weight" => FfnKind::Down,
        _ => return None,
    };
    Some((li, kind))
}

/// Drop dead neurons: gate/up keep ROWS (axis 0), down keeps COLUMNS
/// (axis 1). `keep` indexes the intermediate dim. Returns (reduced shape,
/// reduced f32 values).
fn slice_ffn(
    kind: &FfnKind,
    shape: &[usize],
    vals: &[f32],
    keep: &[bool],
) -> anyhow::Result<(Vec<usize>, Vec<f32>)> {
    let k = keep.iter().filter(|&&b| b).count();
    match kind {
        FfnKind::Gate | FfnKind::Up => {
            let (inter, hidden) = (shape[0], shape[1]);
            if keep.len() != inter {
                anyhow::bail!("defrag: keep len {} != gate/up rows {inter}", keep.len());
            }
            let mut out = Vec::with_capacity(k * hidden);
            for r in 0..inter {
                if keep[r] {
                    out.extend_from_slice(&vals[r * hidden..(r + 1) * hidden]);
                }
            }
            Ok((vec![k, hidden], out))
        }
        FfnKind::Down => {
            let (hidden, inter) = (shape[0], shape[1]);
            if keep.len() != inter {
                anyhow::bail!("defrag: keep len {} != down cols {inter}", keep.len());
            }
            let mut out = Vec::with_capacity(hidden * k);
            for r in 0..hidden {
                for c in 0..inter {
                    if keep[c] {
                        out.push(vals[r * inter + c]);
                    }
                }
            }
            Ok((vec![hidden, k], out))
        }
    }
}

/// Effective f32 for a canonical tensor: the baked overlay if present,
/// otherwise the backbone tensor from the safetensors files.
fn effective_tensor(
    overlay: &HashMap<String, (Vec<usize>, Vec<f32>)>,
    files: &[SafeTensors],
    name: &str,
) -> anyhow::Result<(Vec<usize>, Vec<f32>)> {
    if let Some((s, v)) = overlay.get(name) {
        return Ok((s.clone(), v.clone()));
    }
    for f in files {
        for m in &f.tensors {
            if canon_name(&m.name).as_deref() == Some(name) {
                return Ok((m.shape.clone(), to_f32(&m.dtype, f.bytes(m))?));
            }
        }
    }
    anyhow::bail!("defrag: tensor '{name}' not in overlay or base model")
}

struct DefragPlan {
    /// Baked FFN replacements (canonical name → shape + f32), overriding
    /// the backbone before pruning (carries FCD-retrained weights).
    overlay: HashMap<String, (Vec<usize>, Vec<f32>)>,
    /// Per-layer live-neuron mask over the intermediate dim.
    keep: HashMap<usize, Vec<bool>>,
}

/// Build the defrag plan from a skill dir: baked overlays (`tensors/*.npy`)
/// and a keep-set — explicit `ffn_keep.npy` if present, else autodetected
/// from zeroed down_proj columns (the Factory-Hard bake).
fn build_defrag_plan(
    dir: &Path,
    arch: &ModelArch,
    files: &[SafeTensors],
) -> anyhow::Result<DefragPlan> {
    let mut overlay: HashMap<String, (Vec<usize>, Vec<f32>)> = HashMap::new();
    let tdir = dir.join("tensors");
    if tdir.is_dir() {
        for entry in fs::read_dir(&tdir)? {
            let p = entry?.path();
            if p.extension().and_then(|e| e.to_str()) != Some("npy") {
                continue;
            }
            let stem = p
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or_default()
                .to_string();
            let a = npy::read(&p)?;
            let vals = match a.data {
                npy::NpyData::F32(v) => v,
                npy::NpyData::Bool(_) => {
                    anyhow::bail!("defrag overlay {stem}: expected float, got bool")
                }
            };
            overlay.insert(stem, (a.shape, vals));
        }
    }
    println!(
        "  Defrag overlay: {} baked tensors from {}",
        overlay.len(),
        dir.display()
    );

    let (nl, inter) = (arch.num_layers, arch.intermediate_size);
    let mut keep: HashMap<usize, Vec<bool>> = HashMap::new();
    let keep_path = dir.join("ffn_keep.npy");
    if keep_path.exists() {
        let a = npy::read(&keep_path)?;
        if a.shape != [nl, inter] {
            anyhow::bail!("ffn_keep.npy shape {:?} != model ({nl}, {inter})", a.shape);
        }
        let flags: Vec<bool> = match a.data {
            npy::NpyData::Bool(v) => v,
            npy::NpyData::F32(v) => v.iter().map(|&x| x != 0.0).collect(),
        };
        for li in 0..nl {
            let row = flags[li * inter..(li + 1) * inter].to_vec();
            if !row.iter().any(|&b| b) {
                anyhow::bail!("defrag: layer {li} has 0 live neurons");
            }
            keep.insert(li, row);
        }
    } else {
        // Producer-free: a neuron is dead iff its down_proj INPUT column is
        // all-zero (Factory-Hard bake). Reads each layer's effective down.
        println!("  Defrag: no ffn_keep.npy — autodetecting from zero down_proj columns");
        for li in 0..nl {
            let name = format!("model.layers.{li}.mlp.down_proj.weight");
            let (shape, vals) = effective_tensor(&overlay, files, &name)?;
            let (hidden, cols) = (shape[0], shape[1]);
            let mut alive = vec![false; cols];
            for r in 0..hidden {
                for c in 0..cols {
                    if vals[r * cols + c] != 0.0 {
                        alive[c] = true;
                    }
                }
            }
            if !alive.iter().any(|&b| b) {
                anyhow::bail!("defrag: layer {li} autodetected 0 live neurons");
            }
            keep.insert(li, alive);
        }
    }
    Ok(DefragPlan { overlay, keep })
}

/// Conservative record count for the streaming writer's fixed head gap.
/// A packed `[experts, out, in]` source tensor becomes one CMF directory
/// record per expert; flat checkpoints merely over-reserve here.
fn directory_record_estimate(source_tensors: usize, arch: &ModelArch) -> usize {
    let expanded_expert_records = arch.moe.as_ref().map_or(0usize, |m| {
        arch.num_layers
            .saturating_mul(m.num_experts)
            .saturating_mul(3)
    });
    source_tensors
        .saturating_add(expanded_expert_records)
        .max(4096)
}

pub fn run_convert(
    model: &str,
    quant: &str,
    output: &str,
    hf_token: Option<&str>,
    defrag: Option<&str>,
    // O(1) Nyström runtime hint (`--o1`): recorded in header provenance,
    // weights untouched — the runtime resolves it at load (loader.rs).
    o1_hint: Option<serde_json::Value>,
    // Continue a conversion that died: the payloads already in `output` are
    // kept, and every source shard the manifest marks done is skipped —
    // download included, which is where the hours are.
    resume: bool,
    progress: impl FnMut(f32),
) -> anyhow::Result<()> {
    let outputs = vec![(quant.to_string(), output.to_string())];
    run_convert_multi(model, &outputs, hf_token, defrag, o1_hint, resume, progress)
}

/// Convert one source checkpoint into one or more independently finalized
/// CMF outputs.  All requested profiles consume each source shard in one
/// streamed pass; the decoded values are borrowed while each profile's
/// encoder writes its own payload.
pub fn run_convert_multi(
    model: &str,
    outputs: &[(String, String)],
    hf_token: Option<&str>,
    defrag: Option<&str>,
    o1_hint: Option<serde_json::Value>,
    resume: bool,
    mut progress: impl FnMut(f32),
) -> anyhow::Result<()> {
    anyhow::ensure!(!outputs.is_empty(), "at least one output is required");
    for (i, (_, path)) in outputs.iter().enumerate() {
        anyhow::ensure!(!path.trim().is_empty(), "output path {} is empty", i + 1);
        anyhow::ensure!(
            outputs[..i].iter().all(|(_, p)| p != path),
            "output path '{}' is repeated",
            path
        );
    }
    let profiles: Vec<Quant> = outputs
        .iter()
        .map(|(q, _)| parse_quant(q))
        .collect::<anyhow::Result<_>>()?;
    let quant = profiles[0];
    // Some codecs intentionally share a physical dtype (q1/q1p both use
    // Q1).  Preserve the requested encoder so later skill grafts can encode
    // replacement tensors with the same algorithm instead of guessing from
    // the directory dtype alone.
    let requested_quant = quant_name(quant);

    // Source: a local HF directory, or an HF repo id — hub checkpoints
    // convert STREAMED: one weight shard on disk at a time.
    let downloaded;
    let mut stream_shards: Vec<String> = Vec::new();
    let mut stream_repo: Option<String> = None;
    let local_ready_dir = local_ready_dir_from_env();
    let dir: &Path = if Path::new(model).join("config.json").exists() {
        Path::new(model)
    } else if looks_like_repo(model) {
        anyhow::ensure!(
            local_ready_dir.is_none(),
            "{LOCAL_READY_DIR_ENV} requires a local model directory; unset it for HF hub streaming"
        );
        eprintln!("downloading {model} from Hugging Face (streamed)…");
        let (d, shards) = hf_download_opts(model, hf_token, false)?;
        stream_shards = shards;
        stream_repo = Some(model.to_string());
        downloaded = d;
        downloaded.as_path()
    } else {
        anyhow::bail!(
            "'{model}': not a local model dir (no config.json) and not an HF repo id (owner/name)"
        );
    };

    let config: serde_json::Value = serde_json::from_slice(
        &fs::read(dir.join("config.json")).map_err(|e| anyhow::anyhow!("read config.json: {e}"))?,
    )?;
    let mut arch = build_arch(&config)?;
    arch.prism_hadamard = load_prism_hadamard(dir, &config)?;
    if arch.prism_hadamard.is_some() {
        let has_ordinary = profiles.iter().any(|q| matches!(q, Quant::Q2TiledP));
        let has_affine = profiles.iter().any(|q| matches!(q, Quant::Q2TiledPAffine));
        eprintln!(
            "  Prism/Bonsai: signed FWHT-1024 enabled (profiles: q2tp={} q2tp_affine={})",
            has_ordinary, has_affine
        );
        anyhow::ensure!(
            profiles
                .iter()
                .all(|q| matches!(q, Quant::Q2TiledP | Quant::Q2TiledPAffine)),
            "Prism/Bonsai conversion supports only q2tp and q2tp_affine profiles; other profiles would discard the signed FWHT contract"
        );
    }
    let source_fp8_block = source_fp8_block(&config);
    let consume_source_shards =
        stream_repo.is_none() && arch.deepseek_v41.is_some() && consume_source_shards_enabled();
    if consume_source_shards {
        eprintln!(
            "  source consumption enabled via {CONSUME_SOURCE_SHARDS_ENV}: each local shard is deleted after its output checkpoint"
        );
    }

    // Read output checkpoints before opening local source shards. A consumed
    // shard may no longer exist, but its manifest mark is proof that every
    // output already wrote it. Only the intersection across all outputs is
    // safe to filter; a shard missing from any active output remains required.
    let mut resume_marks: Vec<std::collections::HashSet<String>> =
        vec![std::collections::HashSet::new(); outputs.len()];
    let mut resume_completed = vec![false; outputs.len()];
    if resume {
        for (i, (_, output_path)) in outputs.iter().enumerate() {
            let output = std::path::Path::new(output_path);
            if !output.exists() {
                continue;
            }
            resume_completed[i] = cortiq_core::format::CmfModel::open(output_path).is_ok();
            let manifest_path = format!("{output_path}.manifest");
            if std::path::Path::new(&manifest_path).exists() {
                resume_marks[i] = resume_manifest_marks(std::path::Path::new(&manifest_path));
            }
        }
    }
    let source_shards = if stream_repo.is_none() {
        source_shard_counts(dir)?
    } else {
        Vec::new()
    };
    if local_ready_dir.is_some() {
        anyhow::ensure!(
            stream_repo.is_none(),
            "{LOCAL_READY_DIR_ENV} cannot be combined with HF hub streaming"
        );
        anyhow::ensure!(
            !source_shards.is_empty(),
            "{LOCAL_READY_DIR_ENV} requires at least one local source shard"
        );
        stream_shards = source_shards.iter().map(|(name, _)| name.clone()).collect();
    }
    let local_ready_manifest = if let Some(ready_dir) = local_ready_dir.as_deref() {
        let required: Vec<String> = source_shards.iter().map(|(name, _)| name.clone()).collect();
        let manifest_path = local_ready_manifest_path(ready_dir);
        Some(read_source_file_manifest(&manifest_path, &required)?)
    } else {
        None
    };
    // Both the HF index and the local-ready certificate have been validated
    // before this point.  Reorder only the streamed list so resume marks and
    // the resident local conversion path retain their existing semantics.
    if !stream_shards.is_empty() {
        apply_source_shard_priority(&mut stream_shards)?;
    }
    let completed_source_shards: std::collections::HashSet<String> = if resume {
        source_shards
            .iter()
            .filter(|(name, _)| {
                outputs
                    .iter()
                    .enumerate()
                    .all(|(i, _)| resume_completed[i] || resume_marks[i].contains(name))
            })
            .map(|(name, _)| name.clone())
            .collect()
    } else {
        std::collections::HashSet::new()
    };
    let resumed_tensor_count: usize = source_shards
        .iter()
        .filter(|(name, _)| completed_source_shards.contains(name))
        .map(|(_, count)| *count)
        .sum();

    // Memory-map the weights and process one tensor at a time — the raw model is
    // never fully loaded into RAM (peak ≈ the .cmf output + one tensor).
    let streamed_source = stream_repo.is_some() || local_ready_dir.is_some();
    let mut files = if streamed_source {
        Vec::new() // shards arrive one at a time below
    } else {
        open_model_filtered(dir, &completed_source_shards)?
    };
    if streamed_source && defrag.is_some() {
        anyhow::bail!("--defrag needs a resident local checkpoint dir (streamed convert)");
    }

    // Physical defragmentation plan (spec §11): drop pruned FFN neurons so
    // they are neither stored nor computed. arch.intermediate_size becomes
    // nominal/max (per-layer truth lives in the reduced tensor shapes).
    let orig_inter = arch.intermediate_size;
    let defrag_plan = match defrag {
        Some(d) => Some(build_defrag_plan(Path::new(d), &arch, &files)?),
        None => None,
    };
    if let Some(plan) = &defrag_plan {
        let max_kept = (0..arch.num_layers)
            .filter_map(|li| plan.keep.get(&li).map(|k| k.iter().filter(|&&b| b).count()))
            .max()
            .unwrap_or(orig_inter);
        arch.intermediate_size = max_kept;
    }
    let total: usize = if stream_repo.is_some() {
        1
    } else {
        source_shards
            .iter()
            .map(|(_, count)| *count)
            .sum::<usize>()
            .max(1)
    };
    // A 300B-class MoE encodes to ~100 GB, and holding that in
    // `Vec<TensorSpec>` until the writer runs OOMs any machine (measured:
    // +1.8 GB/min, a 176 GB box exhausted mid-model). Each encoded tensor
    // therefore goes straight into the output file and is dropped; the head
    // is patched into a reserved gap once the last tensor lands, so the
    // payloads are never held twice — not in RAM and not on disk.
    // Hub streaming has no resident `files`, so `total` is one here. Packed
    // MoE tensors can nevertheless expand into E individual gate/up/down
    // directory records per layer (Qwen3.8 Flash: >73k records). Account for
    // that expansion up front; discovering an undersized head only in
    // `finish()` would otherwise waste the entire multi-hour conversion.
    // Flat-expert checkpoints are deliberately counted twice by this upper
    // bound — a larger zero-filled gap is cheap and keeps resume portable.
    let directory_records = directory_record_estimate(total, &arch);
    let head_reserve = cortiq_core::format::CmfStreamWriter::head_reserve_for(
        2usize.saturating_mul(directory_records),
        96,
    );
    let mut manifests = Vec::with_capacity(outputs.len());
    let mut done_shards: Vec<std::collections::HashSet<String>> = Vec::with_capacity(outputs.len());
    let mut writers: Vec<Option<cortiq_core::format::CmfStreamWriter>> =
        Vec::with_capacity(outputs.len());
    let mut completed = vec![false; outputs.len()];
    for (_, output_path) in outputs {
        let manifest_path = format!("{output_path}.manifest");
        // A valid CMF alongside a stale manifest means a previous multi-output
        // run finished this profile before another profile failed. Treat it as
        // complete and never append a second directory to the finalized file.
        if resume && resume_completed[manifests.len()] {
            completed[manifests.len()] = true;
            manifests.push(manifest_path);
            done_shards.push(std::collections::HashSet::new());
            writers.push(None);
            continue;
        }
        let (writer, marks) = if resume
            && std::path::Path::new(&manifest_path).exists()
            && std::path::Path::new(output_path).exists()
        {
            let (w, st) = cortiq_core::format::CmfStreamWriter::resume(output_path, &manifest_path)
                .map_err(|e| anyhow::anyhow!("resume {output_path}: {e}"))?;
            tracing::info!(
                "resuming {output_path}: {} tensors already written, {} source shards done",
                st.names.len(),
                st.marks.len()
            );
            let w = w
                .appending_manifest(&manifest_path)
                .map_err(|e| anyhow::anyhow!("resume {output_path}: {e}"))?;
            (Some(w), st.marks.into_iter().collect())
        } else {
            let w = cortiq_core::format::CmfStreamWriter::new(output_path, head_reserve)
                .and_then(|w| w.with_manifest(&manifest_path))
                .map_err(|e| anyhow::anyhow!("create {output_path}: {e}"))?;
            (Some(w), std::collections::HashSet::new())
        };
        manifests.push(manifest_path);
        done_shards.push(marks);
        writers.push(writer);
    }
    let mut tensors: Vec<Vec<TensorSpec>> =
        outputs.iter().map(|_| Vec::with_capacity(total)).collect();
    if arch.prism_hadamard.is_some() {
        let mut vision_cfg = config
            .get("vision_config")
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("Prism checkpoint has no vision_config"))?;
        // qwen3vis accepts this optional list; an empty list is the honest
        // value for this source (no deepstack merger tensors are present).
        if let Some(obj) = vision_cfg.as_object_mut() {
            obj.entry("deepstack_visual_indexes")
                .or_insert_with(|| serde_json::json!([]));
        }
        let cfg_bytes = serde_json::to_vec(&vision_cfg)?;
        for (i, batch) in tensors.iter_mut().enumerate() {
            if !completed[i] {
                batch.push(TensorSpec {
                    name: "vis.config_json".into(),
                    dtype: TensorDtype::U8,
                    shape: vec![cfg_bytes.len()],
                    data: cfg_bytes.clone(),
                });
            }
        }
    }
    // Count source tensors whose durable shard marks let us skip opening the
    // (possibly already consumed) input. This keeps progress monotonic across
    // a crash while the remaining files are processed below.
    let mut done = resumed_tensor_count;
    if done > 0 {
        progress(done as f32 / total as f32);
    }
    // Tiny cross-shard tensors (gemma-4 router.scale, ~128 f32 each):
    // stashed as shards stream by, so a projection in shard 2 can fold
    // a scale that lived in the already-deleted shard 1.
    let mut small_stash: std::collections::HashMap<String, Vec<f32>> =
        std::collections::HashMap::new();
    // Per-file conversion body, shared by the resident local path and
    // the streaming hub path (shard downloaded → converted → DELETED;
    // peak disk = one shard + the growing output).
    // MiniCPM residual-branch scale (folded at write).
    let resid_fold: Option<f32> = if arch.arch_name == "minicpm3" {
        let tcv = config.get("text_config").unwrap_or(&config);
        let sd = tcv
            .get("scale_depth")
            .and_then(|v| v.as_f64())
            .unwrap_or(1.0);
        Some((sd / (arch.num_layers as f64).sqrt()) as f32)
    } else {
        None
    };
    // Kimi: which layer indices are KDA (canon retag inside the loop).
    // Kimi: which layer indices are KDA (canon retag inside the loop).
    let kda_layers: std::collections::HashSet<usize> = arch
        .layer_types
        .iter()
        .enumerate()
        .filter(|(_, t)| matches!(t, cortiq_core::LayerType::Kda))
        .map(|(i, _)| i)
        .collect();
    // The source affine scales are fit to a 32-group ladder once per matrix.
    // Keep the measured fit error for the immutable conversion report/header
    // instead of presenting the rung quantization as lossless.
    let mut prism_affine_scale_sq = 0.0f64;
    let mut prism_affine_scale_count = 0usize;

    let mut process_file = |file: &SafeTensors,
                            files: &[SafeTensors],
                            batches: &mut [Vec<TensorSpec>],
                            profiles: &[Quant],
                            active: &[bool],
                            writers: &mut [Option<cortiq_core::format::CmfStreamWriter>],
                            done: &mut usize,
                            total: usize,
                            progress: &mut dyn FnMut(f32)|
     -> anyhow::Result<()> {
        for m in &file.tensors {
            if m.name.ends_with(".router.scale") {
                small_stash.insert(m.name.clone(), to_f32(&m.dtype, file.bytes(m))?);
            }
        }
        for m in &file.tensors {
            *done += 1;
            progress(*done as f32 / total as f32);
            if let Some(prism) = arch.prism_hadamard.as_ref() {
                if m.name.ends_with(".signs") {
                    anyhow::ensure!(
                        m.dtype == "F32" && m.shape.len() == 1,
                        "Prism sign tensor {} must be F32 [width], got {} {:?}",
                        m.name,
                        m.dtype,
                        m.shape
                    );
                    let expected = prism.signs_for_width(m.shape[0]).ok_or_else(|| {
                        anyhow::anyhow!(
                            "Prism sign tensor {} has unsupported width {}",
                            m.name,
                            m.shape[0]
                        )
                    })?;
                    let actual = to_f32(&m.dtype, file.bytes(m))?;
                    anyhow::ensure!(
                        actual.len() == expected.len()
                            && actual
                                .iter()
                                .zip(expected)
                                .all(|(a, b)| a.to_bits() == b.to_bits()),
                        "Prism sign tensor {} does not match hadamard.json",
                        m.name
                    );
                    continue;
                }
            }
            let Some(name) = canon_name_for_arch(&arch, &m.name) else {
                continue;
            };
            // HunYuan dense ships the tied `lm_head.weight` as a second copy
            // of the embedding; the loader reads the embedding when the
            // header says tied, so the copy would only be dead bytes.
            if arch.arch_name == "hunyuan_v1_dense"
                && arch.tie_word_embeddings
                && name == "lm_head.weight"
            {
                tracing::info!("hunyuan_v1_dense: tied lm_head.weight not written (embedding serves)");
                continue;
            }
            if arch.qwen4_exp.is_some()
                && (name.starts_with("model.mtp.")
                    || name.ends_with("ple_embedding.layer_multipliers")
                    || name.ends_with("ple_embedding.ngram_heads_offsets")
                    || name.ends_with("ple_embedding.ngram_heads_vocab_sizes"))
            {
                // qwen4 MTP is speculative-only and uses a different stack.
                // PLE's integer hash tables are deterministic from the header
                // and are recomputed by the runtime, avoiding lossy casts.
                continue;
            }
            // Kimi: KDA layers share the `self_attn.` vendor prefix with
            // the MLA full-attention layers — retag them by the layer
            // schedule so the loader dispatches unambiguously.
            let name = if kda_layers.is_empty() {
                name
            } else {
                match name
                    .strip_prefix("model.layers.")
                    .and_then(|r| r.split_once('.'))
                    .and_then(|(li, rest)| Some((li.parse::<usize>().ok()?, rest)))
                {
                    Some((li, rest))
                        if kda_layers.contains(&li) && rest.starts_with("self_attn.") =>
                    {
                        format!("model.layers.{li}.kda_attn.{}", &rest["self_attn.".len()..])
                    }
                    _ => name,
                }
            };

            // DeepSeek-V4.1 Engram tables are native FP8 byte planes. Keep
            // both planes lossless as explicit U8 auxiliary tensors before
            // any generic scale skipping or FP8 decode can consume them.
            // Their companion shape is checked in the source shard (the
            // published checkpoint co-locates each pair).
            let raw_engram =
                m.name.ends_with(".engram.embed.weight") || m.name.ends_with(".engram.embed.scale");
            if arch.deepseek_v41.is_some() && raw_engram {
                let is_weight = m.name.ends_with(".engram.embed.weight");
                anyhow::ensure!(m.shape.len() == 2, "{name}: Engram table must be 2-D");
                anyhow::ensure!(
                    m.shape.iter().all(|&d| d > 0),
                    "{name}: Engram table has an empty dimension"
                );
                let expected_dtype = if is_weight { "F8_E4M3" } else { "F8_E8M0" };
                anyhow::ensure!(
                    m.dtype == expected_dtype,
                    "{name}: Engram {} has dtype {}, expected {expected_dtype}",
                    if is_weight { "weight" } else { "scale" },
                    m.dtype
                );
                if is_weight {
                    anyhow::ensure!(
                        m.shape[1] % 32 == 0,
                        "{name}: Engram weight columns {} are not divisible by 32",
                        m.shape[1]
                    );
                }
                let stem = if is_weight {
                    m.name
                        .strip_suffix(".weight")
                        .expect("Engram weight suffix checked")
                } else {
                    m.name
                        .strip_suffix(".scale")
                        .expect("Engram scale suffix checked")
                };
                let companion_name = if is_weight {
                    format!("{stem}.scale")
                } else {
                    format!("{stem}.weight")
                };
                let companion = files.iter().find_map(|source| {
                    source
                        .tensors
                        .iter()
                        .find(|t| t.name == companion_name)
                        .map(|t| (t.dtype.clone(), t.shape.clone()))
                });
                let (comp_dtype, comp_shape) = companion.ok_or_else(|| {
                    anyhow::anyhow!("{name}: missing Engram companion '{companion_name}'")
                })?;
                if is_weight {
                    let expected_scale_cols = m.shape[1].div_ceil(32);
                    anyhow::ensure!(
                        comp_dtype == "F8_E8M0"
                            && comp_shape == vec![m.shape[0], expected_scale_cols],
                        "{name}: Engram scale companion has dtype {comp_dtype} shape {:?}, expected F8_E8M0 [{}, {}]",
                        comp_shape,
                        m.shape[0],
                        expected_scale_cols
                    );
                } else {
                    let expected_weight_cols = m.shape[1]
                        .checked_mul(32)
                        .ok_or_else(|| anyhow::anyhow!("{name}: Engram shape overflow"))?;
                    anyhow::ensure!(
                        comp_dtype == "F8_E4M3"
                            && comp_shape == vec![m.shape[0], expected_weight_cols],
                        "{name}: Engram weight companion has dtype {comp_dtype} shape {:?}, expected F8_E4M3 [{}, {}]",
                        comp_shape,
                        m.shape[0],
                        expected_weight_cols
                    );
                }
                push_raw_u8_tensor(writers, active, &name, &m.shape, file.bytes(m))?;
                continue;
            }

            // Skip MLX scales and biases as they are processed with the weight.
            if m.dtype == "F16" && (name.ends_with(".scales") || name.ends_with(".biases")) {
                continue;
            }
            // MXFP4 group scales ride with their .weight_packed twin.
            if m.dtype == "U8" && name.ends_with(".weight_scale") {
                continue;
            }
            // DeepSeek-V4/V4.1 keeps every quantized tensor's E8M0 scale plane in
            // a sibling `.scale`; it rides with the weight below.
            if m.dtype == "F8_E8M0" && name.ends_with(".scale") {
                continue;
            }
            // Fine-grained FP8 scale planes ride with `.weight` below.
            if name.ends_with(".weight_scale_inv") {
                continue;
            }
            let fp8_scale_inv = if m.dtype == "F8_E4M3" && m.shape.len() == 2 {
                let scale_name = m.name.replace(".weight", ".weight_scale_inv");
                let mut scale = None;
                for source in files {
                    if let Some(sm) = source.tensors.iter().find(|t| t.name == scale_name) {
                        scale = Some(to_f32(&sm.dtype, source.bytes(sm))?);
                        break;
                    }
                }
                match scale {
                    Some(scales) => Some((
                        m.shape.clone(),
                        unpack_fp8_scale_inv(
                            file.bytes(m),
                            &scales,
                            m.shape[0],
                            m.shape[1],
                            source_fp8_block,
                        )?,
                    )),
                    None => None,
                }
            } else {
                None
            };
            // Its own two quantizations, decoded to f32 so the rest of the
            // pipeline (defrag, requant to q4tp/q2tp) is layout-agnostic:
            //   * experts  — I8 holding two FP4 (E2M1) values per byte with
            //     one E8M0 scale per 32 values: OCP MXFP4 exactly.
            //   * skeleton — F8_E4M3 with one E8M0 scale per source tile
            //     (128x128 for V4, 32x32 for V4.1).
            let dsv4 = if matches!(m.dtype.as_str(), "I8" | "F8_E4M3") && !name.ends_with(".scale")
            {
                let scale_name = format!("{}.scale", m.name.trim_end_matches(".weight"));
                let mut sb = None;
                for f in files {
                    if let Some(t) = f.tensors.iter().find(|t| t.name == scale_name) {
                        sb = Some(f.bytes(t));
                    }
                }
                match sb {
                    Some(scales) if m.shape.len() == 2 => {
                        let (rows, cols) = (m.shape[0], m.shape[1]);
                        if m.dtype == "I8" {
                            // packed FP4: `cols` bytes = 2*cols values
                            Some((
                                vec![rows, cols * 2],
                                unpack_mxfp4(file.bytes(m), scales, rows, cols)?,
                            ))
                        } else {
                            Some((
                                vec![rows, cols],
                                unpack_fp8_blocks(
                                    file.bytes(m),
                                    scales,
                                    rows,
                                    cols,
                                    source_fp8_block,
                                )?,
                            ))
                        }
                    }
                    _ => None,
                }
            } else {
                None
            };

            let mxfp4 = if m.dtype == "U8" && m.name.ends_with(".weight_packed") {
                // MXFP4 (Kimi-K3 experts): decode to f32 and continue the
                // normal path under the plain `.weight` name.
                let scale_name = m.name.replace(".weight_packed", ".weight_scale");
                let mut scales_blob = None;
                for f in files {
                    if let Some(t) = f.tensors.iter().find(|t| t.name == scale_name) {
                        scales_blob = Some(f.bytes(t));
                    }
                }
                let scales = scales_blob
                    .ok_or_else(|| anyhow::anyhow!("missing {scale_name} for mxfp4 unpacking"))?;
                anyhow::ensure!(m.shape.len() == 2, "{name}: mxfp4 expects 2-D");
                let (rows, cp) = (m.shape[0], m.shape[1]);
                Some((
                    vec![rows, cp * 2],
                    unpack_mxfp4(file.bytes(m), scales, rows, cp)?,
                ))
            } else {
                None
            };
            let name = if mxfp4.is_some() {
                name.strip_suffix("_packed")
                    .expect("suffix checked")
                    .to_string()
            } else {
                name
            };

            // Prism source matrices are MLX U32 bitplanes.  The production
            // q2tp_affine profile preserves the source 0/1/2 symbols in the
            // existing dtype16 plane, while ordinary q2tp uses the existing
            // midrise encoder.  Both outputs can be produced in one streamed
            // pass over the source shard.
            if arch.prism_hadamard.is_some() && m.dtype == "U32" && m.name.ends_with(".weight") {
                anyhow::ensure!(
                    m.shape.len() == 2,
                    "Prism packed matrix {name} must be 2-D, got {:?}",
                    m.shape
                );
                let out_dim = m.shape[0];
                let in_dim = m.shape[1]
                    .checked_mul(16)
                    .ok_or_else(|| anyhow::anyhow!("Prism matrix {name} input width overflows"))?;
                let find_companion = |suffix: &str| {
                    let wanted = m.name.replace(".weight", suffix);
                    files.iter().find_map(|source| {
                        source
                            .tensors
                            .iter()
                            .find(|t| t.name == wanted)
                            .map(|t| (source.bytes(t), t.dtype.as_str(), t.shape.clone()))
                    })
                };
                let (scales, scale_dtype, scale_shape) =
                    find_companion(".scales").ok_or_else(|| {
                        anyhow::anyhow!("missing {}.scales for Prism matrix {name}", m.name)
                    })?;
                let (biases, bias_dtype, bias_shape) =
                    find_companion(".biases").ok_or_else(|| {
                        anyhow::anyhow!("missing {}.biases for Prism matrix {name}", m.name)
                    })?;
                anyhow::ensure!(
                    scale_dtype == "F16"
                        && bias_dtype == "F16"
                        && scale_shape == vec![out_dim, in_dim / 128]
                        && bias_shape == scale_shape,
                    "Prism affine companions for {name} have dtypes/shapes ({scale_dtype} {:?}, {bias_dtype} {:?}), expected F16 [{out_dim}, {}]",
                    scale_shape,
                    bias_shape,
                    in_dim / 128
                );
                let descriptor = arch.prism_hadamard.as_ref().unwrap();
                anyhow::ensure!(
                    descriptor.signs_for_width(in_dim).is_some(),
                    "Prism matrix {name} input width {in_dim} has no signed FWHT vector"
                );
                validate_mlx_ternary_codes(file.bytes(m), out_dim, in_dim)?;

                let affine_payload = if profiles.iter().any(|q| matches!(q, Quant::Q2TiledPAffine))
                {
                    let (payload, fit_rms) =
                        encode_mlx_q2tp_affine(file.bytes(m), scales, biases, out_dim, in_dim)?;
                    anyhow::ensure!(
                        fit_rms.is_finite(),
                        "Prism matrix {name} produced a non-finite affine scale fit"
                    );
                    prism_affine_scale_sq +=
                        (fit_rms as f64).powi(2) * (out_dim * (in_dim / GROUP_SIZE)) as f64;
                    prism_affine_scale_count = prism_affine_scale_count
                        .saturating_add(out_dim.saturating_mul(in_dim / GROUP_SIZE));
                    Some(payload)
                } else {
                    None
                };

                // Only the ordinary profile needs a dense source view.  It is
                // bounded to one matrix and is immediately dropped after
                // both output batches receive their independent payloads.
                let ordinary_vals = if profiles.iter().any(|q| matches!(q, Quant::Q2TiledP)) {
                    Some(unpack_mlx(
                        file.bytes(m),
                        scales,
                        Some(biases),
                        out_dim,
                        in_dim,
                        2,
                    )?)
                } else {
                    None
                };

                for ((batch, requested), &is_active) in batches.iter_mut().zip(profiles).zip(active)
                {
                    if !is_active {
                        continue;
                    }
                    match *requested {
                        Quant::Q2TiledP => {
                            emit_profiled_tensor(
                                std::slice::from_mut(batch),
                                std::slice::from_ref(requested),
                                std::slice::from_ref(&is_active),
                                &arch,
                                &name,
                                &[out_dim, in_dim],
                                ordinary_vals
                                    .as_ref()
                                    .expect("ordinary q2tp source decode built above"),
                                EmitMode::Auto,
                            );
                        }
                        Quant::Q2TiledPAffine => {
                            batch.push(TensorSpec {
                                name: name.clone(),
                                dtype: TensorDtype::Q2TiledP,
                                shape: vec![out_dim, in_dim],
                                data: affine_payload
                                    .as_ref()
                                    .expect("q2tp affine payload built above")
                                    .clone(),
                            });
                        }
                        _ => unreachable!("Prism profile gate above"),
                    }
                }
                continue;
            }
            let mxfp4 = fp8_scale_inv.or(mxfp4).or(dsv4);
            // MLX Conv3d stores Qwen's patch kernel as [out, temporal, height,
            // width, channels], while the CMF vision tower consumes flattened
            // per-patch rows in the source processor's [channels, temporal,
            // height, width] order.  Keep this tower lossless, but make the
            // shape/axis contract explicit so VisionTower::from_cmf receives a
            // normal 2-D projection instead of an unusable 5-D safetensor.
            let prism_patch = arch.prism_hadamard.is_some() && name == "vis.patch_embed.weight";
            let (m_shape, m_vals) = if prism_patch {
                flatten_prism_patch_weight(&m.dtype, &m.shape, file.bytes(m))?
            } else if let Some(v) = mxfp4 {
                v
            } else if m.dtype == "U32" && m.name.ends_with(".weight") {
                let scales_name = m.name.replace(".weight", ".scales");
                let biases_name = m.name.replace(".weight", ".biases");
                let mut scales_blob = None;
                let mut biases_blob = None;
                for f in files {
                    if let Some(t) = f.tensors.iter().find(|t| t.name == scales_name) {
                        scales_blob = Some(f.bytes(t));
                    }
                    if let Some(t) = f.tensors.iter().find(|t| t.name == biases_name) {
                        biases_blob = Some(f.bytes(t));
                    }
                }
                let scales = scales_blob
                    .ok_or_else(|| anyhow::anyhow!("missing {} for MLX unpacking", scales_name))?;
                let out_dim = m.shape[0];
                let w_cols = m.shape[1];
                let num_groups = scales.len() / 2 / out_dim;

                let mut bits = 0;
                let mut in_dim = 0;
                for b in [1, 2, 3, 4, 8] {
                    let possible_in_dim = w_cols * 32 / b;
                    if possible_in_dim % num_groups == 0 {
                        let gs = possible_in_dim / num_groups;
                        if gs == 32 || gs == 64 || gs == 128 {
                            bits = b;
                            in_dim = possible_in_dim;
                            break;
                        }
                    }
                }
                if bits == 0 {
                    anyhow::bail!(
                        "Could not deduce MLX bit width for shape {:?} and {} scale groups",
                        m.shape,
                        num_groups
                    );
                }
                (
                    vec![out_dim, in_dim],
                    unpack_mlx(file.bytes(m), scales, biases_blob, out_dim, in_dim, bits)?,
                )
            } else {
                (m.shape.clone(), to_f32(&m.dtype, file.bytes(m))?)
            };

            let mut m_vals = m_vals;
            // MiniCPM: every residual add is h += branch·(scale_depth/√L)
            // — fold the factor into the branch output rows (o_proj and
            // the dense FFN down_proj) so the runtime stays standard.
            if let Some(fs) = resid_fold {
                if name.ends_with("self_attn.o_proj.weight")
                    || name.ends_with(".mlp.down_proj.weight")
                {
                    for v in m_vals.iter_mut() {
                        *v *= fs;
                    }
                }
            }

            // DeepSeek-V2 MLA: permute each q head to rope-first
            // ([nope|rope] → [rope|nope]) so the runtime's standard
            // partial rotary (first rotary_dim dims) covers it.
            if arch.mla.is_some()
                && (name.ends_with("self_attn.q_proj.weight")
                    || name.ends_with("self_attn.q_b_proj.weight"))
            {
                let mla = arch.mla.as_ref().unwrap();
                let (dr, dn) = (mla.qk_rope_head_dim, mla.qk_nope_head_dim);
                let hd = dr + dn;
                anyhow::ensure!(
                    m_shape.len() == 2 && m_shape[0] % hd == 0,
                    "{name}: rows {:?} not a multiple of qk head dim {hd}",
                    m_shape
                );
                let cols = m_shape[1];
                let nh = m_shape[0] / hd;
                let mut w = vec![0.0f32; m_vals.len()];
                for h in 0..nh {
                    for r in 0..dr {
                        // DeepSeek rotary interleaves pairs (view d/2,2 →
                        // transpose): store rope dims even-first so our
                        // half-split rotation reproduces their math.
                        // Kimi NoPE (no rotation) and MiniCPM3 (plain
                        // half-split rotate_half) keep the rope block
                        // order — only the move in front of nope.
                        let interleaved = !mla.nope && arch.arch_name.contains("deepseek");
                        let src = if !interleaved {
                            r
                        } else if r < dr / 2 {
                            2 * r
                        } else {
                            2 * (r - dr / 2) + 1
                        };
                        w[(h * hd + r) * cols..(h * hd + r + 1) * cols].copy_from_slice(
                            &m_vals[(h * hd + dn + src) * cols..(h * hd + dn + src + 1) * cols],
                        );
                    }
                    for r in 0..dn {
                        w[(h * hd + dr + r) * cols..(h * hd + dr + r + 1) * cols]
                            .copy_from_slice(&m_vals[(h * hd + r) * cols..(h * hd + r + 1) * cols]);
                    }
                }
                emit_profiled_tensor(
                    batches,
                    &profiles,
                    active,
                    &arch,
                    &name,
                    &m_shape,
                    &w,
                    EmitMode::Auto,
                );
                continue;
            }

            // DeepSeek MLA: the shared rope key rows (tail of kv_a) get
            // the same even-first interleave fix. Kimi NoPE skips it —
            // no rotation, the tail rows are already where the loader
            // expects them.
            if arch.mla.as_ref().is_some_and(|m| !m.nope)
                && arch.arch_name.contains("deepseek")
                && name.ends_with("self_attn.kv_a_proj_with_mqa.weight")
            {
                let mla = arch.mla.as_ref().unwrap();
                let (lora, dr) = (mla.kv_lora_rank, mla.qk_rope_head_dim);
                anyhow::ensure!(
                    m_shape.len() == 2 && m_shape[0] == lora + dr,
                    "{name}: rows {:?} != lora+rope",
                    m_shape
                );
                let cols = m_shape[1];
                let mut w = m_vals.clone();
                for r in 0..dr {
                    let src = if r < dr / 2 {
                        2 * r
                    } else {
                        2 * (r - dr / 2) + 1
                    };
                    w[(lora + r) * cols..(lora + r + 1) * cols]
                        .copy_from_slice(&m_vals[(lora + src) * cols..(lora + src + 1) * cols]);
                }
                emit_profiled_tensor(
                    batches,
                    &profiles,
                    active,
                    &arch,
                    &name,
                    &m_shape,
                    &w,
                    EmitMode::Auto,
                );
                continue;
            }

            // Gemma-4 MoE: packed 3-D expert tensors + a router whose
            // input gain (scale-less rms ⊙ router.scale · hidden^-1/2)
            // folds entirely into the projection columns. Experts split
            // into the canonical per-expert 2-D matrices; the fused
            // gate_up halves are [gate | up] along the last axis.
            if name.ends_with(".experts.gate_up_proj") || name.ends_with(".experts.down_proj") {
                anyhow::ensure!(
                    m_shape.len() == 3,
                    "{name}: expected 3-D, got {:?}",
                    m_shape
                );
                let base = name
                    .strip_suffix(".experts.gate_up_proj")
                    .or_else(|| name.strip_suffix(".experts.down_proj"))
                    .unwrap();
                // Two lineages name the packed tensor differently: gemma-4
                // has `layers.N.experts.*`, qwen3.5/3.6 `layers.N.mlp.experts.*`.
                // The output name below appends `.mlp.experts`, so a base that
                // already ends in `.mlp` would double it — and a doubled prefix
                // converts silently, then fails at load with "router present but
                // no expert tensors", which points nowhere near here.
                let base = base.strip_suffix(".mlp").unwrap_or(base);
                let moe = arch
                    .moe
                    .as_ref()
                    .ok_or_else(|| anyhow::anyhow!("no moe cfg"))?;
                let (mi, hid) = (moe.moe_intermediate_size, arch.hidden_size);
                let (ne, d1, d2) = (m_shape[0], m_shape[1], m_shape[2]);
                let is_gu = name.ends_with("gate_up_proj");
                // Both orientations occur in the wild: standard per-expert
                // nn.Linear [out, in] rows (gemma-4 QAT) or the packed
                // [in, out] (Mixtral lineage). Detect by dims.
                let row_major = if is_gu {
                    if (d1, d2) == (2 * mi, hid) {
                        true
                    } else if (d1, d2) == (hid, 2 * mi) {
                        false
                    } else {
                        anyhow::bail!("{name}: dims {:?} match neither orientation", m_shape)
                    }
                } else if (d1, d2) == (hid, mi) {
                    true
                } else if (d1, d2) == (mi, hid) {
                    false
                } else {
                    anyhow::bail!("{name}: dims {:?} match neither orientation", m_shape)
                };
                for e in 0..ne {
                    let ev = &m_vals[e * d1 * d2..(e + 1) * d1 * d2];
                    if is_gu {
                        let mut gate = vec![0.0f32; mi * hid];
                        let mut up = vec![0.0f32; mi * hid];
                        if row_major {
                            gate.copy_from_slice(&ev[..mi * hid]);
                            up.copy_from_slice(&ev[mi * hid..]);
                        } else {
                            for h in 0..hid {
                                for r in 0..mi {
                                    gate[r * hid + h] = ev[h * d2 + r];
                                    up[r * hid + h] = ev[h * d2 + mi + r];
                                }
                            }
                        }
                        let gate_name = format!("{base}.mlp.experts.{e}.gate_proj.weight");
                        emit_profiled_tensor(
                            batches,
                            &profiles,
                            active,
                            &arch,
                            &gate_name,
                            &[mi, hid],
                            &gate,
                            EmitMode::Auto,
                        );
                        let up_name = format!("{base}.mlp.experts.{e}.up_proj.weight");
                        emit_profiled_tensor(
                            batches,
                            &profiles,
                            active,
                            &arch,
                            &up_name,
                            &[mi, hid],
                            &up,
                            EmitMode::Auto,
                        );
                    } else {
                        let mut down = vec![0.0f32; hid * mi];
                        if row_major {
                            down.copy_from_slice(ev);
                        } else {
                            for r in 0..mi {
                                for h in 0..hid {
                                    down[h * mi + r] = ev[r * d2 + h];
                                }
                            }
                        }
                        let down_name = format!("{base}.mlp.experts.{e}.down_proj.weight");
                        emit_profiled_tensor(
                            batches,
                            &profiles,
                            active,
                            &arch,
                            &down_name,
                            &[hid, mi],
                            &down,
                            EmitMode::Auto,
                        );
                    }
                }
                continue;
            }
            if name.ends_with(".router.proj.weight") {
                anyhow::ensure!(
                    m_shape.len() == 2,
                    "{name}: expected 2-D, got {:?}",
                    m_shape
                );
                let (ne, hid) = (m_shape[0], m_shape[1]);
                // Fold router.scale ⊙ hidden^-1/2 into the columns.
                let scale_name = m.name.replace(".proj.weight", ".scale");
                let mut scale_blob = small_stash.get(&scale_name).cloned();
                if scale_blob.is_none() {
                    for f in files {
                        if let Some(t) = f.tensors.iter().find(|t| t.name == scale_name) {
                            scale_blob = Some(to_f32(&t.dtype, f.bytes(t))?);
                        }
                    }
                }
                let scale =
                    scale_blob.ok_or_else(|| anyhow::anyhow!("missing {scale_name} for fold"))?;
                anyhow::ensure!(scale.len() == hid, "{scale_name}: len != hidden");
                let c = 1.0 / (hid as f32).sqrt();
                let mut w = m_vals.clone();
                for r in 0..ne {
                    for j in 0..hid {
                        w[r * hid + j] *= scale[j] * c;
                    }
                }
                let base = name.strip_suffix(".router.proj.weight").unwrap();
                let out_name = format!("{base}.mlp.gate.weight");
                emit_profiled_tensor(
                    batches,
                    &profiles,
                    active,
                    &arch,
                    &out_name,
                    &[ne, hid],
                    &w,
                    EmitMode::F16,
                );
                continue;
            }
            if name.ends_with(".router.scale") {
                continue; // folded into the router projection above
            }
            if name.ends_with(".router.per_expert_scale") {
                let base = name.strip_suffix(".router.per_expert_scale").unwrap();
                let out_name = format!("{base}.mlp.per_expert_scale");
                emit_profiled_tensor(
                    batches,
                    &profiles,
                    active,
                    &arch,
                    &out_name,
                    &[m_vals.len()],
                    &m_vals,
                    EmitMode::F16,
                );
                continue;
            }

            // qwen3_next / AgentWorld fuse the GDN projections (in_proj_qkvz /
            // in_proj_ba) with a group-interleaved layout; split them natively
            // into the canonical hub tensors (in_proj_qkv/z/a/b). Pure row
            // permutation — no value is changed.
            if name.contains(".linear_attn.in_proj_qkvz")
                || name.contains(".linear_attn.in_proj_ba")
            {
                if m_shape.len() != 2 {
                    anyhow::bail!("fused GDN tensor '{name}': expected 2-D, got {:?}", m_shape);
                }
                let w = &m_vals;
                let hid = m_shape[1];
                let miss = |k: &str| anyhow::anyhow!("fused GDN needs {k} in config");
                let nk = arch
                    .linear_num_key_heads
                    .ok_or_else(|| miss("linear_num_key_heads"))?;
                let dk = arch
                    .linear_key_head_dim
                    .ok_or_else(|| miss("linear_key_head_dim"))?;
                let nv = arch
                    .linear_num_value_heads
                    .ok_or_else(|| miss("linear_num_value_heads"))?;
                let dv = arch
                    .linear_value_head_dim
                    .ok_or_else(|| miss("linear_value_head_dim"))?;
                for (out_name, out_vals, out_rows) in
                    split_fused_gdn(&name, w, hid, nk, dk, nv, dv)?
                {
                    emit_profiled_tensor(
                        batches,
                        &profiles,
                        active,
                        &arch,
                        &out_name,
                        &[out_rows, hid],
                        &out_vals,
                        EmitMode::Auto,
                    );
                }
                continue;
            }
            // Phi-3 family fuses QKV (`qkv_proj`) and gate/up
            // (`gate_up_proj`): split into the canonical tensors — a
            // pure row slice, no value changes.
            if name.ends_with(".self_attn.qkv_proj.weight")
                || name.ends_with(".mlp.gate_up_proj.weight")
            {
                anyhow::ensure!(m_shape.len() == 2, "fused '{name}': expected 2-D");
                let w = &m_vals;
                let (rows, cols) = (m_shape[0], m_shape[1]);
                let parts: Vec<(String, usize, usize)> = if name.contains("qkv_proj") {
                    let q = arch.num_attention_heads * arch.head_dim;
                    let kv = arch.num_kv_heads * arch.head_dim;
                    anyhow::ensure!(
                        q + 2 * kv == rows,
                        "'{name}': {rows} rows != q({q}) + 2·kv({kv})"
                    );
                    vec![
                        (name.replace("qkv_proj", "q_proj"), 0, q),
                        (name.replace("qkv_proj", "k_proj"), q, kv),
                        (name.replace("qkv_proj", "v_proj"), q + kv, kv),
                    ]
                } else {
                    anyhow::ensure!(rows % 2 == 0, "'{name}': odd row count {rows}");
                    vec![
                        (name.replace("gate_up_proj", "gate_proj"), 0, rows / 2),
                        (name.replace("gate_up_proj", "up_proj"), rows / 2, rows / 2),
                    ]
                };
                for (out_name, r0, nr) in parts {
                    let vals = &w[r0 * cols..(r0 + nr) * cols];
                    emit_profiled_tensor(
                        batches,
                        &profiles,
                        active,
                        &arch,
                        &out_name,
                        &[nr, cols],
                        vals,
                        EmitMode::Auto,
                    );
                }
                continue;
            }
            // Gemma-4 global (full-attention) layers carry no v_proj —
            // V is the K projection, normalized separately at runtime
            // (attention_k_eq_v). Materialize the duplicate so the
            // runtime keeps its uniform Q/K/V/O contract; the overlay
            // costs one MQA-sized tensor per global layer.
            if arch.global_head_dim.is_some() && name.ends_with(".self_attn.k_proj.weight") {
                let li: Option<usize> = name
                    .split(".layers.")
                    .nth(1)
                    .and_then(|r| r.split('.').next())
                    .and_then(|n| n.parse().ok());
                let pat = arch.sliding_window_pattern.unwrap_or(usize::MAX);
                if let Some(li) = li {
                    if (li + 1) % pat == 0 {
                        anyhow::ensure!(m_shape.len() == 2, "'{name}': expected 2-D");
                        let w = &m_vals;
                        let (rows, cols) = (m_shape[0], m_shape[1]);
                        for out_name in [name.clone(), name.replace("k_proj", "v_proj")] {
                            emit_profiled_tensor(
                                batches,
                                &profiles,
                                active,
                                &arch,
                                &out_name,
                                &[rows, cols],
                                w,
                                EmitMode::Auto,
                            );
                        }
                        continue;
                    }
                }
            }
            // Defrag: for an FFN weight of a pruned layer, take the baked
            // overlay (if any) else the backbone value, drop dead neurons
            // (gate/up rows, down columns), then quantize the reduced shape.
            // The neuron never enters the blob — nor the runtime's math.
            if let Some(plan) = defrag_plan.as_ref() {
                if let Some((li, kind)) = ffn_kind(&name) {
                    if let Some(keep) = plan.keep.get(&li) {
                        let (shape, vals) = match plan.overlay.get(&name) {
                            Some((s, v)) => (s.clone(), v.clone()),
                            None => (m_shape.clone(), m_vals.clone()),
                        };
                        let (out_shape, out_vals) = slice_ffn(&kind, &shape, &vals, keep)?;
                        emit_profiled_tensor(
                            batches,
                            &profiles,
                            active,
                            &arch,
                            &name,
                            &out_shape,
                            &out_vals,
                            EmitMode::Auto,
                        );
                        continue;
                    }
                }
            }
            let vals = m_vals;
            let numel: usize = m_shape.iter().product();
            if numel != vals.len() {
                anyhow::bail!(
                    "tensor '{name}': {} values for shape {:?}",
                    vals.len(),
                    m_shape
                );
            }
            // 1-D tensors, tiny tensors, non-2-D, and gate-critical projections go f16.
            // Index tables ride as raw f32: quantizing them would round
            // expert ids, and f16 cannot even hold a vocabulary id exactly.
            if force_f32(&name) {
                emit_profiled_tensor(
                    batches,
                    &profiles,
                    active,
                    &arch,
                    &name,
                    &m_shape,
                    &vals,
                    EmitMode::F32,
                );
                continue;
            }
            emit_profiled_tensor(
                batches,
                &profiles,
                active,
                &arch,
                &name,
                &m_shape,
                &vals,
                EmitMode::Auto,
            );
        }

        Ok(())
    };
    if stream_repo.is_some() || local_ready_dir.is_some() {
        let base = stream_repo
            .as_deref()
            .map(|repo| format!("https://huggingface.co/{repo}/resolve/main"));
        let threads = hf_threads();
        let agent = ureq::AgentBuilder::new()
            .timeout_connect(Duration::from_secs(20))
            .timeout_read(Duration::from_secs(300))
            .build();
        let ns = stream_shards.len().max(1);
        for (si, sname) in stream_shards.iter().enumerate() {
            let active: Vec<bool> = outputs
                .iter()
                .enumerate()
                .map(|(i, _)| !completed[i] && !done_shards[i].contains(sname))
                .collect();
            if !active.iter().any(|&v| v) {
                eprintln!(
                    "  [stream {}/{}] {sname} — все выходы уже в файле, пропуск",
                    si + 1,
                    ns
                );
                progress((si as f32 + 1.0) / ns as f32);
                continue;
            }
            eprintln!("  [stream {}/{}] {sname}", si + 1, ns);
            let source_path = if let Some(base) = base.as_deref() {
                fetch(
                    &agent,
                    &format!("{base}/{sname}"),
                    &dir.join(sname),
                    hf_token,
                    true,
                    threads,
                )?;
                dir.join(sname)
            } else {
                let ready_dir = local_ready_dir.as_deref().ok_or_else(|| {
                    anyhow::anyhow!("streamed source has neither an HF repo nor a ready directory")
                })?;
                let expected = local_ready_manifest
                    .as_ref()
                    .and_then(|m| m.get(sname))
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "local-ready source manifest has no expectation for shard {sname}"
                        )
                    })?;
                wait_for_local_ready_source(ready_dir, dir, sname, expected)?
            };
            let f = open_safetensors(&source_path)?;
            let one = [f];
            let ft = one[0].tensors.len().max(1);
            let mut fd = 0usize;
            let mut sub = |p: f32| progress((si as f32 + p) / ns as f32);
            process_file(
                &one[0],
                &one,
                &mut tensors,
                &profiles,
                &active,
                &mut writers,
                &mut fd,
                ft,
                &mut sub,
            )?;
            // Spill this shard's payloads before touching the next one:
            // that is what keeps residency at one shard instead of the
            // whole model.
            for i in 0..outputs.len() {
                if !active[i] {
                    continue;
                }
                let writer = writers[i].as_mut().ok_or_else(|| {
                    anyhow::anyhow!("output {} is already finalized", outputs[i].1)
                })?;
                drain_to_writer(&mut tensors[i], writer)?;
                // Only now is this shard's work durable in the output file.
                writer
                    .mark(sname)
                    .map_err(|e| anyhow::anyhow!("manifest: {e}"))?;
                done_shards[i].insert(sname.clone());
            }
            drop(one);
            if stream_repo.is_some() {
                // Preserve the existing hub-stream cleanup behavior. Hub
                // cache files are disposable and this path predates the
                // strict local-ready disk-budget contract.
                let _ = fs::remove_file(&source_path);
            } else if consume_source_shards {
                // Local-ready consumption is the bounded-disk path: a failed
                // unlink must stop conversion instead of silently retaining
                // another 100 GB shard and overrunning the pod volume.
                consume_local_ready_source(&source_path)?;
            }
        }
    } else {
        for file_index in 0..files.len() {
            let file_name = files[file_index].name.clone();
            let file_tensor_count = files[file_index].tensors.len();
            let active: Vec<bool> = outputs
                .iter()
                .enumerate()
                .map(|(i, _)| !completed[i] && !done_shards[i].contains(&file_name))
                .collect();
            if !active.iter().any(|&v| v) {
                eprintln!("  [{file_name}] уже в файле, пропуск");
                done += file_tensor_count;
                progress(done as f32 / total as f32);
                if consume_source_shards {
                    consume_source_shard(&mut files, file_index, dir)?;
                }
                continue;
            }
            process_file(
                &files[file_index],
                &files,
                &mut tensors,
                &profiles,
                &active,
                &mut writers,
                &mut done,
                total,
                &mut progress,
            )?;
            // Marking per source file gives a local conversion the same
            // resumability as a streamed one; the payloads have to reach the
            // output first, so the drain comes before the mark.
            for i in 0..outputs.len() {
                if !active[i] {
                    continue;
                }
                let writer = writers[i].as_mut().ok_or_else(|| {
                    anyhow::anyhow!("output {} is already finalized", outputs[i].1)
                })?;
                drain_to_writer(&mut tensors[i], writer)?;
                writer
                    .mark(&file_name)
                    .map_err(|e| anyhow::anyhow!("manifest: {e}"))?;
                done_shards[i].insert(file_name.clone());
            }
            if consume_source_shards {
                // Drop the mmap before unlinking so the filesystem can
                // reclaim this shard's blocks immediately. Every active
                // output has flushed its payload and manifest mark above.
                consume_source_shard(&mut files, file_index, dir)?;
            }
        }
    }

    // Tokenizer + chat bundle (optional but recommended).
    let tok_cfg: serde_json::Value = fs::read(dir.join("tokenizer_config.json"))
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or(serde_json::Value::Null);
    let vocab = fs::read(dir.join("tokenizer.json")).ok().or_else(|| {
        // Kimi (tiktoken): synthesize a standard tokenizer.json from the
        // rank table so the runtime tokenizer stays unchanged.
        let tk = fs::read_to_string(dir.join("tiktoken.model")).ok()?;
        match tiktoken_to_tokenizer_json(&tk, &tok_cfg) {
            Ok(j) => {
                tracing::info!("tiktoken.model → tokenizer.json ({} bytes)", j.len());
                Some(j.into_bytes())
            }
            Err(e) => {
                eprintln!("  tiktoken.model found but conversion failed: {e}");
                None
            }
        }
    });
    let gen_cfg: serde_json::Value = fs::read(dir.join("generation_config.json"))
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or(serde_json::Value::Null);
    // Sidecar `chat_template.jinja` first, then the tokenizer_config field;
    // ignore an empty/blank file so we correctly fall through to the config.
    let chat_template = fs::read_to_string(dir.join("chat_template.jinja"))
        .ok()
        .filter(|s| !s.trim().is_empty())
        .or_else(|| {
            tok_cfg
                .get("chat_template")
                .and_then(|v| v.as_str().map(String::from))
        });
    let bundle = TokenizerBundle {
        chat_template,
        eos_token_ids: {
            let mut e = eos_ids(&gen_cfg, &config);
            // HunYuan hy_v3 declares a separate end-of-document id; a
            // generation that emits it is finished too.
            if let Some(eod) = config.get("eod_token_id").and_then(|v| v.as_u64()) {
                if !e.contains(&(eod as u32)) {
                    e.push(eod as u32);
                }
            }
            e
        },
        bos_token_id: config
            .get("bos_token_id")
            .and_then(|v| v.as_u64())
            .map(|n| n as u32),
        pad_token_id: config
            .get("pad_token_id")
            .and_then(|v| v.as_u64())
            .map(|n| n as u32),
    };

    let quant_type = |q: Quant| match q {
        Quant::Q8Row => QuantType::Q8Row,
        Quant::Q8_2f => QuantType::Q8_2f,
        Quant::Q4Block => QuantType::Q4Block,
        Quant::F16 => QuantType::F16,
        Quant::Vbit => QuantType::Vbit,
        Quant::Q4Tiled | Quant::Q4TiledP | Quant::Q2TiledP | Quant::Q2TiledPAffine => {
            QuantType::Q4Block
        }
        // File-level label only (per-tensor truth is in the directory);
        // Vbit is the closest existing informational bucket for q1.
        Quant::Q1 | Quant::Q1p | Quant::Q1s | Quant::Q1t => QuantType::Vbit,
    };
    let provenance = match &defrag_plan {
        Some(plan) => {
            let kept: Vec<usize> = (0..arch.num_layers)
                .map(|li| {
                    plan.keep
                        .get(&li)
                        .map(|k| k.iter().filter(|&&b| b).count())
                        .unwrap_or(orig_inter)
                })
                .collect();
            let live: usize = kept.iter().sum();
            let ratio = 1.0 - live as f64 / (arch.num_layers as f64 * orig_inter as f64);
            eprintln!(
                "defrag: FFN pruned per-layer, {live}/{} live ({:.0}% pruned), inter {orig_inter} -> max {} (per-layer variable); masks dropped",
                arch.num_layers * orig_inter,
                ratio * 100.0,
                arch.intermediate_size
            );
            serde_json::json!({
                "tool": "cortiq convert",
                "source_model": model,
                "weight_quant": requested_quant,
                "defrag": {
                    "source_skill": defrag,
                    "pre_intermediate": orig_inter,
                    "post_intermediate_max": arch.intermediate_size,
                    "kept_per_layer": kept,
                    "pruned_ratio": (ratio * 10000.0).round() / 10000.0,
                }
            })
        }
        None => serde_json::json!({
            "tool": "cortiq convert",
            "source_model": model,
            "weight_quant": requested_quant,
        }),
    };
    let provenance = match o1_hint {
        Some(h) => {
            let mut p = provenance;
            p["o1_attn"] = h;
            p
        }
        None => provenance,
    };
    let provenance = if let Some(prism) = arch.prism_hadamard.as_ref() {
        let mut p = provenance;
        p["prism_hadamard"] = serde_json::json!({
            "version": prism.version,
            "block_size": prism.block_size,
            "transform": prism.transform.clone(),
            "sign_mode": prism.sign_mode.clone(),
            "widths": prism.widths.clone(),
            "gdn_v_grouped": prism.gdn_v_grouped,
            "activation_f16": prism.activation_f16,
            "q2tp_affine_profile": profiles
                .iter()
                .any(|q| matches!(q, Quant::Q2TiledPAffine)),
            "q2tp_affine_source_scale_ladder_rms": if prism_affine_scale_count == 0 {
                0.0
            } else {
                (prism_affine_scale_sq / prism_affine_scale_count as f64).sqrt()
            },
            "q2tp_affine_source_scale_ladder_groups": prism_affine_scale_count,
            "ordinary_q2tp_existing_codec": profiles
                .iter()
                .any(|q| matches!(q, Quant::Q2TiledP)),
            "ordinary_q2tp_profile_policy": "existing_mixed_q2tp_gate_up_q4tp_other",
            "ordinary_q2tp_weight_error_is_lossy": true,
            "vision_tensors_preserved": true,
            "vision_runtime": "qwen3vis_tensors_preserved_no_text_fusion",
        });
        p
    } else {
        provenance
    };
    let header_for = |i: usize| {
        let mut p = provenance.clone();
        p["weight_quant"] = serde_json::json!(quant_name(profiles[i]));
        let header_arch = if matches!(profiles[i], Quant::Q2TiledPAffine) {
            let mut a = arch.clone();
            let prism = a
                .prism_hadamard
                .as_mut()
                .expect("Prism affine profile requires Hadamard metadata");
            let mut target_names = prism
                .forward_weight_names
                .iter()
                .chain(prism.inverse_weight_names.iter())
                .map(|name| {
                    name.strip_prefix("language_model.")
                        .unwrap_or(name)
                        .to_string()
                })
                .collect::<Vec<_>>();
            target_names.sort();
            target_names.dedup();
            prism.affine = Some(PrismAffineConfig {
                version: 1,
                profile: "q2tp_affine".into(),
                group_size: GROUP_SIZE,
                correction_scale: 0.5,
                target_names,
            });
            a
        } else {
            arch.clone()
        };
        CmfHeader {
            format: "cmf".into(),
            version: CMF_VERSION,
            arch: header_arch,
            quant_type: quant_type(profiles[i]),
            provenance: Some(p),
            tokenizer_config: Some(bundle.clone()),
            section_hashes: None,
            skills: Vec::new(),
            shard: None,
            calibration: None,
            routing: None,
        }
    };

    // Lay the blob out in EXECUTION order — embed, then each layer's tensors
    // contiguously (attention, then FFN, with MoE experts grouped per expert),
    // then final norm, lm_head, MTP, then any tail. HF safetensors are often
    // alphabetical (`layers.10` before `layers.2`), which scatters the decode
    // traversal across the file; sequential layer layout streams cold-start
    // reads at disk rate and lets a per-layer `madvise(WILLNEED)` cover one
    // contiguous range. Pure layout — the directory carries offsets, so the
    // reader (which addresses tensors by name/offset) is unaffected.
    for i in 0..outputs.len() {
        if completed[i] {
            continue;
        }
        tensors[i].sort_by(|a, b| {
            exec_order_key(&a.name)
                .cmp(&exec_order_key(&b.name))
                .then_with(|| a.name.cmp(&b.name))
        });
        // Anything still resident (small tensors produced outside the main
        // loop) is appended last.
        let writer = writers[i]
            .take()
            .ok_or_else(|| anyhow::anyhow!("output {} has no writer", outputs[i].1))?;
        let mut writer = writer;
        drain_to_writer(&mut tensors[i], &mut writer)?;
        writer
            .finish(&header_for(i), None, vocab.as_deref())
            .map_err(|e| anyhow::anyhow!("write {}: {e}", outputs[i].1))?;
        // The manifest only exists to rescue an interrupted run. Keep it
        // until every requested output has finalized, so a crash between two
        // finish calls can detect the already-valid sibling on resume.
    }
    for manifest_path in manifests {
        let _ = std::fs::remove_file(manifest_path);
    }
    progress(1.0);
    Ok(())
}

/// Whether this tensor is one of an expert's two SwiGLU input planes.
/// Trunk names are canonicalized to gate/up_proj; DeepSeek-V4's MTP stack
/// deliberately keeps its upstream ffn.w1/w3 schema, so both are part of
/// the same q2tp profile.
/// The dense FFN's gate/up projections (no expert in the name) — what the
/// q2tp profile puts on the 2-bit plane when the model has no experts.
pub(crate) fn q2tp_dense_gate_or_up(name: &str) -> bool {
    !name.contains(".experts.")
        && !name.contains(".shared_expert")
        // the MTP draft block stays 4-bit: it is one layer, and its
        // agreement with the trunk is what speculation lives on
        && !name.contains(".mtp.")
        && (name.ends_with(".mlp.gate_proj.weight")
            || name.ends_with(".mlp.up_proj.weight")
            || name.ends_with(".mlp.w1.weight")
            || name.ends_with(".mlp.w3.weight"))
}

pub(crate) fn q2tp_expert_gate_or_up(name: &str) -> bool {
    let expert = name.contains(".experts.")
        || name.contains(".shared_expert.")
        || name.contains(".shared_experts.");
    expert
        && (name.ends_with(".gate_proj.weight")
            || name.ends_with(".up_proj.weight")
            || name.ends_with(".w1.weight")
            || name.ends_with(".w3.weight"))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use cortiq_core::format::CmfModel;

    #[test]
    fn hf_thread_env_is_bounded_and_keeps_legacy_default() {
        assert_eq!(parse_hf_threads(None), HF_DEFAULT_THREADS);
        assert_eq!(parse_hf_threads(Some("")), HF_DEFAULT_THREADS);
        assert_eq!(parse_hf_threads(Some("not-a-number")), HF_DEFAULT_THREADS);
        assert_eq!(parse_hf_threads(Some("0")), HF_DEFAULT_THREADS);
        assert_eq!(parse_hf_threads(Some(" -4 ")), HF_DEFAULT_THREADS);
        assert_eq!(parse_hf_threads(Some(" 16 ")), 16);
        assert_eq!(parse_hf_threads(Some("64")), HF_MAX_THREADS);
        assert_eq!(parse_hf_threads(Some("65")), HF_MAX_THREADS);
        assert_eq!(
            parse_hf_threads(Some("999999999999999999999999")),
            HF_DEFAULT_THREADS
        );
    }

    #[test]
    fn hf_range_planner_covers_file_without_overlap() {
        assert!(plan_hf_ranges(0, 32).is_empty());
        assert!(plan_hf_ranges(100, 0).is_empty());

        let ranges = plan_hf_ranges(100, 32);
        assert_eq!(ranges, vec![(0, 32), (32, 64), (64, 96), (96, 100)]);
        assert_eq!(ranges.first().map(|r| r.0), Some(0));
        assert_eq!(ranges.last().map(|r| r.1), Some(100));
        for pair in ranges.windows(2) {
            assert_eq!(pair[0].1, pair[1].0, "ranges must be adjacent");
            assert!(pair[0].0 < pair[0].1, "ranges must be non-empty");
        }
        assert!(ranges.last().unwrap().0 < ranges.last().unwrap().1);
    }

    #[test]
    fn source_shard_priority_is_exact_and_stable() {
        let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::remove_var(SOURCE_SHARD_PRIORITY_ENV);
        }
        let mut shards = vec![
            "model-00001-of-00004.safetensors".to_string(),
            "model-00002-of-00004.safetensors".to_string(),
            "model-00003-of-00004.safetensors".to_string(),
            "model-00004-of-00004.safetensors".to_string(),
        ];
        apply_source_shard_priority(&mut shards)
            .expect("no priority environment should preserve the source order");
        assert_eq!(
            shards,
            vec![
                "model-00001-of-00004.safetensors",
                "model-00002-of-00004.safetensors",
                "model-00003-of-00004.safetensors",
                "model-00004-of-00004.safetensors",
            ]
        );

        unsafe {
            std::env::set_var(
                SOURCE_SHARD_PRIORITY_ENV,
                "model-00003-of-00004.safetensors,model-00001-of-00004.safetensors",
            );
        }
        apply_source_shard_priority(&mut shards).unwrap();
        assert_eq!(
            shards,
            vec![
                "model-00003-of-00004.safetensors",
                "model-00001-of-00004.safetensors",
                "model-00002-of-00004.safetensors",
                "model-00004-of-00004.safetensors",
            ]
        );

        for bad in [
            "",
            ",model-00001-of-00004.safetensors",
            "model-00001-of-00004.safetensors,",
            "model-00099-of-00004.safetensors",
            "model-00001-of-00004.safetensors,model-00001-of-00004.safetensors",
        ] {
            unsafe {
                std::env::set_var(SOURCE_SHARD_PRIORITY_ENV, bad);
            }
            let mut candidate = shards.clone();
            assert!(
                apply_source_shard_priority(&mut candidate).is_err(),
                "priority {bad:?} must fail closed"
            );
        }
        unsafe {
            std::env::remove_var(SOURCE_SHARD_PRIORITY_ENV);
        }
    }

    /// The encoders read their switches from the environment, and the test
    /// harness runs tests on threads of ONE process — so two tests steering
    /// different switches at once make each other's results meaningless.
    /// Everything that touches those variables takes this first.
    pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Pin both switches for the duration of a test, whatever ran before.
    pub(crate) fn env_guard(threads: &str, search: &str) -> std::sync::MutexGuard<'static, ()> {
        let g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::set_var("CMF_ENCODE_THREADS", threads);
            std::env::set_var("CMF_Q2TP_SEARCH", search);
        }
        g
    }
    use cortiq_core::quant::{
        dequant_q4_block, dequant_q4_tiled, dequant_q4tp, dequant_q8_2f, dequant_q8_row,
        dequant_vbit, expected_nbytes,
    };

    /// Deterministic pseudo-random weights whose per-TILE amplitude spreads
    /// over `spread` powers of two within each row — that spread is the only
    /// thing a per-row scale ladder has to cope with, so it is the axis worth
    /// parameterizing. Measured on KAT-Coder-V2.5, real rows sit at a median
    /// spread of 1.27 and a 90th percentile of 1.89; 3.7 is past the tail.
    fn synth_rows(rows: usize, cols: usize, spread: f32) -> Vec<f32> {
        let mut v = vec![0f32; rows * cols];
        let mut s = 0x2545_F491_4F6C_DD1Du64;
        let mut next = || {
            s ^= s << 13;
            s ^= s >> 7;
            s ^= s << 17;
            (s >> 40) as f32 / 8388608.0 - 1.0
        };
        for r in 0..rows {
            let amp = 10f32.powi((r % 7) as i32 - 3); // rows span 10^-3..10^3
            for g in 0..cols / GROUP_SIZE {
                let tilt = (next().abs() * spread).exp2();
                for k in 0..GROUP_SIZE {
                    v[r * cols + g * GROUP_SIZE + k] = next() * amp * tilt;
                }
            }
        }
        v
    }

    fn rel_rms(a: &[f32], b: &[f32]) -> f32 {
        let (mut num, mut den) = (0f64, 0f64);
        for (x, y) in a.iter().zip(b) {
            num += ((x - y) as f64).powi(2);
            den += (*x as f64).powi(2);
        }
        (num / den).sqrt() as f32
    }

    /// Rows spanning 10^-3..10^3 with a per-group tilt, so the row ladder
    /// has to work for the scales to come back at all.
    fn q2tp_test_matrix(rows: usize, cols: usize) -> Vec<f32> {
        let mut v = vec![0f32; rows * cols];
        let mut s = 0x2545F491_4F6CDD1Du64;
        let mut next = || {
            s ^= s << 13;
            s ^= s >> 7;
            s ^= s << 17;
            (s >> 40) as f32 / 8388608.0 - 1.0
        };
        for r in 0..rows {
            let amp = 10f32.powi((r % 7) as i32 - 3);
            for g in 0..cols / GROUP_SIZE {
                let tilt = (next().abs() * 2.0).exp2();
                for k in 0..GROUP_SIZE {
                    v[r * cols + g * GROUP_SIZE + k] = next() * amp * tilt;
                }
            }
        }
        v
    }

    fn q2tp_rel_rms(a: &[f32], b: &[f32]) -> f32 {
        let (mut num, mut den) = (0f64, 0f64);
        for (x, y) in a.iter().zip(b) {
            num += ((x - y) as f64).powi(2);
            den += (*x as f64).powi(2);
        }
        (num / den).sqrt() as f32
    }

    /// The 2-bit plane must be exactly half of q4tp's, with the params and
    /// code planes untouched — a wrong section offset reads scales out of
    /// weight bytes and still produces fluent-looking numbers, so pin the
    /// length AND the reader's own view of it.
    /// E4M3 has no infinities and one NaN; the values below are the
    /// bit patterns that pin its exponent bias and its subnormal step.
    /// DeepSeek-V4 names arrive with no `model.` wrapper and spell the
    /// blocks `attn`/`ffn`. Pin the whole map: a silent miss here means a
    /// tensor lands under a name nothing reads, and the model loads with
    /// a hole instead of failing.
    /// The 2-bit profile is worth 50 GB on a 300B MoE, and getting it wrong
    /// produces a file that is merely large — no error, no warning. These are
    /// the names it has to recognize, in the spelling `canon_name` emits.
    /// The 2-bit levels are (c−1.5)·s, so the scale decides everything, and
    /// absmax/1.5 pins the outer level to the largest weight — which
    /// minimises the WORST error, not the mean one. With four levels that
    /// difference is large. This measures both arms on weights shaped like a
    /// real expert plane and requires the search to actually win.
    #[test]
    fn two_bit_scale_search_beats_the_absmax_rule() {
        let (rows, cols) = (16usize, 512usize);
        let mut w = vec![0.0f32; rows * cols];
        for (i, v) in w.iter_mut().enumerate() {
            let x = i as f32;
            *v = ((x * 0.017).sin() + (x * 0.041).sin() + (x * 0.093).sin()) / 3.0;
            if i % 97 == 0 {
                *v *= 6.0; // an outlier every so often, as in a real plane
            }
        }
        let rel = |enc: &[u8]| {
            let mut back = vec![0.0f32; rows * cols];
            cortiq_core::quant::dequant_q2tp(enc, rows, cols, &mut back);
            let num: f32 = w.iter().zip(&back).map(|(a, b)| (a - b) * (a - b)).sum();
            let den: f32 = w.iter().map(|a| a * a).sum();
            (num / den).sqrt()
        };
        // SAFETY-of-test: read per call, and these run in sequence.
        let _g = env_guard("1", "0");
        let plain = rel(&encode_q2tp(&w, rows, cols));
        unsafe { std::env::set_var("CMF_Q2TP_SEARCH", "1") };
        let searched = rel(&encode_q2tp(&w, rows, cols));
        println!("q2tp относительная ошибка: absmax {plain:.4} → подбор {searched:.4}");
        assert!(
            searched < plain,
            "подбор ступени не улучшил: {searched:.4} против {plain:.4}"
        );
    }

    /// The same trick in the 4-bit layout. Sixteen levels forgive an outlier
    /// far more than four do, so this measures whether it is worth having
    /// there at all rather than assuming it is.
    #[test]
    fn four_bit_scale_search_measured() {
        let (rows, cols) = (16usize, 512usize);
        let mut w = vec![0.0f32; rows * cols];
        for (i, v) in w.iter_mut().enumerate() {
            let x = i as f32;
            *v = ((x * 0.017).sin() + (x * 0.041).sin() + (x * 0.093).sin()) / 3.0;
            if i % 97 == 0 {
                *v *= 6.0;
            }
        }
        let rel = |enc: &[u8]| {
            let mut back = vec![0.0f32; rows * cols];
            cortiq_core::quant::dequant_q4tp(enc, rows, cols, &mut back);
            let num: f32 = w.iter().zip(&back).map(|(a, b)| (a - b) * (a - b)).sum();
            let den: f32 = w.iter().map(|a| a * a).sum();
            (num / den).sqrt()
        };
        let _g = env_guard("1", "0");
        let plain = rel(&encode_q4tp(&w, rows, cols));
        unsafe { std::env::set_var("CMF_Q2TP_SEARCH", "1") };
        let searched = rel(&encode_q4tp(&w, rows, cols));
        println!("q4tp относительная ошибка: absmax {plain:.4} → подбор {searched:.4}");
        assert!(searched <= plain, "подбор ухудшил 4 бита");
    }

    /// The row encoders were made parallel because a 300B MoE otherwise
    /// quantizes on one core. Rows are independent, so the bytes must be
    /// identical however many threads produce them — not merely close.
    #[test]
    fn parallel_row_encoding_is_byte_identical_to_serial() {
        // Wide enough to split across threads, with a dead row and a row of
        // wildly different magnitudes so the scale ladder actually varies.
        let (rows, cols) = (97usize, 256usize);
        let mut vals = vec![0.0f32; rows * cols];
        for r in 0..rows {
            for c in 0..cols {
                vals[r * cols + c] = match r {
                    7 => 0.0, // a dead row: rung 0 everywhere
                    _ => ((r * 31 + c * 7) as f32 * 0.017).sin() * (1 << (r % 9)) as f32,
                };
            }
        }
        let _g = env_guard("1", "1");
        for (name, enc) in [
            ("q2tp", encode_q2tp as fn(&[f32], usize, usize) -> Vec<u8>),
            ("q4tp", encode_q4tp as fn(&[f32], usize, usize) -> Vec<u8>),
            ("q8_2f", encode_q8_2f as fn(&[f32], usize, usize) -> Vec<u8>),
        ] {
            let serial = enc(&vals, rows, cols);
            unsafe { std::env::set_var("CMF_ENCODE_THREADS", "8") };
            let parallel = enc(&vals, rows, cols);
            unsafe { std::env::set_var("CMF_ENCODE_THREADS", "1") };
            assert_eq!(
                serial.len(),
                parallel.len(),
                "{name}: length differs between 1 and 8 threads"
            );
            let diff = serial.iter().zip(&parallel).position(|(a, b)| a != b);
            assert!(
                diff.is_none(),
                "{name}: byte {} differs between 1 and 8 threads",
                diff.unwrap()
            );
        }
    }

    #[test]
    fn the_two_bit_profile_covers_every_experts_gate_and_up() {
        let gu = q2tp_expert_gate_or_up;
        // routed experts — the bulk of the model
        assert!(gu("model.layers.7.mlp.experts.42.gate_proj.weight"));
        assert!(gu("model.layers.7.mlp.experts.42.up_proj.weight"));
        // the shared expert, which must match the routed layout
        assert!(gu("model.layers.7.mlp.shared_expert.gate_proj.weight"));
        assert!(gu("model.layers.7.mlp.shared_expert.up_proj.weight"));
        // down stays 4-bit, and nothing outside the experts is touched
        assert!(!gu("model.layers.7.mlp.experts.42.down_proj.weight"));
        assert!(!gu("model.layers.7.mlp.shared_expert.down_proj.weight"));
        assert!(!gu("model.layers.7.mlp.gate.weight"));
        assert!(!gu("model.layers.7.self_attn.wq_b.weight"));
        assert!(!gu("model.embed_tokens.weight"));
        // DeepSeek-V4 keeps the MTP layer's own ffn/w1,w3 spelling.
        assert!(gu("model.mtp.0.ffn.experts.42.w1.weight"));
        assert!(gu("model.mtp.2.ffn.experts.42.w3.weight"));
        assert!(gu("model.mtp.1.ffn.shared_experts.w1.weight"));
        assert!(gu("model.mtp.1.ffn.shared_experts.w3.weight"));
        assert!(!gu("model.mtp.0.ffn.experts.42.w2.weight"));
    }

    #[test]
    fn deepseek_v4_names_map_onto_the_loader_layout() {
        let m = |s: &str| canon_name(s).unwrap();
        assert_eq!(m("embed.weight"), "model.embed_tokens.weight");
        assert_eq!(m("head.weight"), "lm_head.weight");
        assert_eq!(m("norm.weight"), "model.norm.weight");
        assert_eq!(m("hc_head_scale"), "model.hc_head_scale");
        assert_eq!(
            m("layers.7.attn_norm.weight"),
            "model.layers.7.input_layernorm.weight"
        );
        assert_eq!(
            m("layers.7.ffn_norm.weight"),
            "model.layers.7.post_attention_layernorm.weight"
        );
        // router + the noaux_tc bias + the hash table
        assert_eq!(
            m("layers.7.ffn.gate.weight"),
            "model.layers.7.mlp.gate.weight"
        );
        assert_eq!(
            m("layers.7.ffn.gate.bias"),
            "model.layers.7.mlp.expert_bias"
        );
        assert_eq!(m("layers.7.ffn.gate.tid2eid"), "model.layers.7.mlp.tid2eid");
        // w1 = gate, w3 = up, w2 = down — for routed AND shared experts
        assert_eq!(
            m("layers.7.ffn.experts.42.w1.weight"),
            "model.layers.7.mlp.experts.42.gate_proj.weight"
        );
        assert_eq!(
            m("layers.7.ffn.experts.42.w3.weight"),
            "model.layers.7.mlp.experts.42.up_proj.weight"
        );
        assert_eq!(
            m("layers.7.ffn.experts.42.w2.scale"),
            "model.layers.7.mlp.experts.42.down_proj.scale"
        );
        assert_eq!(
            m("layers.7.ffn.shared_experts.w1.weight"),
            "model.layers.7.mlp.shared_expert.gate_proj.weight"
        );
        // attention keeps its own spelling under self_attn — the double
        // LoRA, the compressed KV, the sink, the compressor and the
        // indexer have no equivalent in a supported arch yet
        assert_eq!(
            m("layers.7.attn.wq_a.weight"),
            "model.layers.7.self_attn.wq_a.weight"
        );
        assert_eq!(
            m("layers.7.attn.indexer.weights_proj.weight"),
            "model.layers.7.self_attn.indexer.weights_proj.weight"
        );
        assert_eq!(
            m("layers.7.attn.compressor.wkv.weight"),
            "model.layers.7.self_attn.compressor.wkv.weight"
        );
        assert_eq!(m("layers.7.hc_attn_scale"), "model.layers.7.hc_attn_scale");
    }

    #[test]
    fn deepseek_v41_keeps_full_source_config_and_native_engram_names() {
        let config = serde_json::json!({
            "model_type": "deepseek_v41",
            "quantization_config": {
                "quant_method": "fp8",
                "weight_block_size": [32, 32],
                "scale_fmt": "ue8m0"
            },
            "text_config": {
                "model_type": "deepseek_v41_text",
                "hidden_size": 8,
                "intermediate_size": 16,
                "num_hidden_layers": 1,
                "num_attention_heads": 2,
                "num_key_value_heads": 1,
                "head_dim": 4,
                "qk_rope_head_dim": 2,
                "qk_nope_head_dim": 2,
                "vocab_size": 32,
                "rms_norm_eps": 1e-6,
                "n_routed_experts": 2,
                "moe_intermediate_size": 4,
                "num_experts_per_tok": 1,
                "n_shared_experts": 1
            },
            "vision_config": {
                "model_type": "deepseek_v41_vision",
                "hidden_size": 4,
                "num_hidden_layers": 2
            }
        });
        let arch = build_arch(&config).unwrap();
        assert_eq!(arch.arch_name, "deepseek_v41");
        assert_eq!(arch.deepseek_v41.as_ref(), Some(&config));
        assert_eq!(source_fp8_block(&config), 32);
        assert_eq!(
            canon_name("layers.1.engram.embed.weight").as_deref(),
            Some("model.layers.1.engram.embed.weight")
        );
        assert_eq!(
            canon_name("layers.1.engram.embed.scale").as_deref(),
            Some("model.layers.1.engram.embed.scale")
        );
        assert_eq!(
            canon_name("layers.1.ffn.gate.bias_vl").as_deref(),
            Some("model.layers.1.mlp.expert_bias_vl")
        );
    }

    #[test]
    fn dsv41_vision_and_aligner_matrix_weights_stay_f16_in_q4tp() {
        let config = serde_json::json!({
            "model_type": "deepseek_v41",
            "text_config": {
                "model_type": "deepseek_v41_text",
                "hidden_size": 8,
                "intermediate_size": 16,
                "num_hidden_layers": 1,
                "num_attention_heads": 2,
                "num_key_value_heads": 1,
                "head_dim": 4,
                "vocab_size": 32,
                "rms_norm_eps": 1e-6
            },
            "vision_config": {"hidden_size": 8}
        });
        let arch = build_arch(&config).unwrap();
        let values = vec![0.25f32; 8 * 8];
        let mut batches = vec![Vec::new()];
        for name in [
            "vision.patch_embed.proj.weight",
            "vision.blocks.0.attn.wqkv.weight",
            "vision.blocks.0.mlp.w1.weight",
            "aligner.w1.weight",
            "aligner.w2.weight",
        ] {
            emit_profiled_tensor(
                &mut batches,
                &[Quant::Q4TiledP],
                &[true],
                &arch,
                name,
                &[8, 8],
                &values,
                EmitMode::Auto,
            );
        }
        // The pre-existing F32 route remains authoritative when a control
        // tensor is encountered in the same profile.
        emit_profiled_tensor(
            &mut batches,
            &[Quant::Q4TiledP],
            &[true],
            &arch,
            "model.layers.0.mlp.expert_bias",
            &[8],
            &values[..8],
            EmitMode::Auto,
        );
        assert_eq!(
            batches[0][..5].iter().map(|t| t.dtype).collect::<Vec<_>>(),
            vec![
                TensorDtype::F16,
                TensorDtype::F16,
                TensorDtype::F16,
                TensorDtype::F16,
                TensorDtype::F16
            ]
        );
        assert_eq!(batches[0][5].dtype, TensorDtype::F32);
    }

    #[test]
    fn local_ready_consume_reports_unlink_failure() {
        let root = std::env::temp_dir().join(format!(
            "cortiq-local-ready-unlink-test-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).unwrap();
        let missing = root.join("already-removed.safetensors");
        let err = consume_local_ready_source(&missing)
            .expect_err("local-ready consume must fail when the source unlink fails");
        assert!(
            err.to_string()
                .contains("remove consumed local-ready source")
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn fp8_e4m3_decodes_the_ocp_reference_points() {
        assert_eq!(fp8_e4m3_to_f32(0x00), 0.0);
        assert_eq!(fp8_e4m3_to_f32(0x38), 1.0); // exp 7 → 2^0
        assert_eq!(fp8_e4m3_to_f32(0xB8), -1.0);
        assert_eq!(fp8_e4m3_to_f32(0x3C), 1.5); // 1 + 4/8
        assert_eq!(fp8_e4m3_to_f32(0x40), 2.0);
        assert_eq!(fp8_e4m3_to_f32(0x01), (2f32).powi(-9)); // smallest subnormal
        assert_eq!(fp8_e4m3_to_f32(0x7E), 448.0); // largest finite
        assert!(fp8_e4m3_to_f32(0x7F).is_nan()); // E4M3FN NaN sentinel
        assert!(unpack_fp8_blocks(&[0x7F], &[127], 1, 1, 1).is_err());
    }

    /// The block plane must be indexed by TILE, not by element: a wrong
    /// stride still produces plausible numbers, which is how a silently
    /// wrong conversion happens.
    #[test]
    fn fp8_block_scales_apply_per_tile() {
        let (rows, cols, block) = (4usize, 4usize, 2usize);
        // every weight is 1.0; scales differ per 2x2 tile: 2^0, 2^1 / 2^2, 2^3
        let packed = vec![0x38u8; rows * cols];
        let scales = vec![127u8, 128, 129, 130];
        let out = unpack_fp8_blocks(&packed, &scales, rows, cols, block).unwrap();
        assert_eq!(out[0], 1.0); // tile (0,0)
        assert_eq!(out[2], 2.0); // tile (0,1)
        assert_eq!(out[2 * cols], 4.0); // tile (1,0)
        assert_eq!(out[2 * cols + 2], 8.0); // tile (1,1)
        // a NaN scale must fail rather than poison the tensor
        let bad = vec![255u8, 128, 129, 130];
        assert!(unpack_fp8_blocks(&packed, &bad, rows, cols, block).is_err());
    }

    #[test]
    fn fp8_f32_scale_inv_applies_per_block() {
        // 0x38 is exactly 1.0 in E4M3, so the output exposes the scale plane.
        let out = unpack_fp8_scale_inv(&[0x38; 4], &[1.0, 2.0, 3.0, 4.0], 2, 2, 1).unwrap();
        assert_eq!(out, vec![1.0, 2.0, 3.0, 4.0]);
        assert!(unpack_fp8_scale_inv(&[0x38; 4], &[1.0], 2, 2, 1).is_err());
        assert!(unpack_fp8_scale_inv(&[0x38; 4], &[f32::NAN; 4], 2, 2, 1).is_err());
        assert!(unpack_fp8_scale_inv(&[0x7F; 4], &[1.0; 4], 2, 2, 1).is_err());
    }

    /// Fine-grained FP8 decode is row-independent just like the output
    /// encoders. Keep a non-trivial tail row/column shape here so a future
    /// parallel rewrite cannot accidentally change block indexing or bytes
    /// while still passing a square toy case.
    #[test]
    fn fp8_scale_inv_decode_is_thread_count_invariant() {
        let (rows, cols, block) = (17usize, 130usize, 8usize);
        let sr = rows.div_ceil(block);
        let sc = cols.div_ceil(block);
        let packed: Vec<u8> = (0..rows * cols)
            .map(|i| ((i * 37 + 11) as u8) & 0x7e)
            .collect();
        let scales: Vec<f32> = (0..sr * sc)
            .map(|i| 0.125 + (i % 13) as f32 * 0.25)
            .collect();
        let _g = env_guard("1", "1");
        let serial = unpack_fp8_scale_inv(&packed, &scales, rows, cols, block).unwrap();
        unsafe { std::env::set_var("CMF_ENCODE_THREADS", "8") };
        let parallel = unpack_fp8_scale_inv(&packed, &scales, rows, cols, block).unwrap();
        assert_eq!(
            serial, parallel,
            "FP8 scale-inverse decode changed with threads"
        );
    }

    #[test]
    fn q2tp_payload_length_and_sections_match_the_reader() {
        use cortiq_core::quant::{expected_nbytes, q2tp_sections, validate_payload};
        let (rows, cols) = (7usize, 96usize);
        let v = q2tp_test_matrix(rows, cols);
        let blob = encode_q2tp(&v, rows, cols);
        let want = expected_nbytes(TensorDtype::Q2TiledP, &[rows, cols]).unwrap();
        assert_eq!(blob.len(), want, "payload length");
        let (params_off, codes_off, stride) = q2tp_sections(rows, cols);
        assert_eq!(params_off, rows * (cols / GROUP_SIZE) * 8, "weight plane");
        assert_eq!(codes_off, params_off + rows * 4, "params plane");
        assert_eq!(codes_off + rows * stride, blob.len(), "code plane");
        assert!(
            validate_payload(TensorDtype::Q2TiledP, &[rows, cols], &blob).is_ok(),
            "reader rejected its own encoder's output"
        );
    }

    /// 2 bits carry 4 levels, so the error is large by construction — what
    /// must hold is that it stays in the 2-bit BAND (a broken decode lands
    /// at ~100%) and that an all-zero row survives exactly.
    #[test]
    fn q2tp_roundtrip_stays_in_the_two_bit_error_band() {
        use cortiq_core::quant::dequant_q2tp;
        let (rows, cols) = (9usize, 128usize);
        let mut v = q2tp_test_matrix(rows, cols);
        for k in 0..cols {
            v[3 * cols + k] = 0.0;
        }
        let blob = encode_q2tp(&v, rows, cols);
        let mut back = vec![0f32; rows * cols];
        dequant_q2tp(&blob, rows, cols, &mut back);
        let e = q2tp_rel_rms(&back, &v);
        assert!(
            e < 0.55,
            "q2tp rel-RMS {e} — decode is wrong, not just coarse"
        );
        assert!(e > 0.05, "q2tp rel-RMS {e} — suspiciously exact for 2 bits");
        assert!(
            back[3 * cols..4 * cols].iter().all(|x| *x == 0.0),
            "an all-zero row must dequantize to exact zeros"
        );
    }

    #[test]
    fn q4tp_payload_length_matches_expected_nbytes() {
        for &(rows, cols) in &[(1usize, 32usize), (7, 64), (16, 2048), (2048, 512)] {
            let v = synth_rows(rows, cols, 1.27);
            let bytes = encode_q4tp(&v, rows, cols);
            assert_eq!(
                Some(bytes.len()),
                expected_nbytes(TensorDtype::Q4TiledP, &[rows, cols]),
                "shape {rows}x{cols}"
            );
        }
    }

    #[test]
    fn q4tp_codes_survive_bit_packing_at_every_offset() {
        // 5 bits per code means the byte boundary lands differently for each
        // tile mod 8; walk a full period plus change.
        let gpr = 37;
        let mut buf = vec![0u8; q4tp_code_stride(gpr)];
        let want: Vec<usize> = (0..gpr).map(|g| (g * 7 + 3) % 32).collect();
        for (g, &c) in want.iter().enumerate() {
            q4tp_put_code(&mut buf, g, c);
        }
        let got: Vec<usize> = (0..gpr)
            .map(|g| cortiq_core::quant::q4tp_code(&buf, g))
            .collect();
        assert_eq!(got, want);
    }

    #[test]
    fn q4tp_costs_almost_nothing_against_q4t_from_the_same_source() {
        // The honest comparison is BOTH codecs against the same fp32 weights.
        // Comparing q4tp against q4t's output instead measures the distance
        // between two representations, which reads far worse than the truth:
        // when the scale shifts a little the nibbles simply re-round, so the
        // total error stays pinned to the 4-bit grid either way.
        let (rows, cols) = (256usize, 2048usize);
        for &(spread, budget) in &[(0.0f32, 1.02f32), (1.27, 1.02), (1.89, 1.03), (3.70, 1.06)] {
            let v = synth_rows(rows, cols, spread);
            let mut a = vec![0f32; rows * cols];
            dequant_q4_tiled(&encode_q4_tiled(&v, rows, cols), &mut a);
            let mut b = vec![0f32; rows * cols];
            dequant_q4tp(&encode_q4tp(&v, rows, cols), rows, cols, &mut b);

            let (e_q4t, e_q4tp) = (rel_rms(&v, &a), rel_rms(&v, &b));
            assert!(
                e_q4tp <= e_q4t * budget,
                "spread {spread}: q4tp {e_q4tp:.4} over budget {budget}× of q4t {e_q4t:.4}"
            );
        }
    }

    #[test]
    fn q4tp_keeps_an_all_zero_tile_exactly_zero() {
        // A dead tile must not drag the row's ladder down (that would coarsen
        // every live tile) and must still dequantize to exact zeros.
        let (rows, cols) = (4usize, 128usize);
        let mut v = synth_rows(rows, cols, 1.27);
        for c in 0..GROUP_SIZE {
            v[cols + c] = 0.0;
        }
        let mut out = vec![0f32; rows * cols];
        dequant_q4tp(&encode_q4tp(&v, rows, cols), rows, cols, &mut out);
        assert!(out[cols..cols + GROUP_SIZE].iter().all(|&x| x == 0.0));

        let live = &v[cols + GROUP_SIZE..2 * cols];
        let got = &out[cols + GROUP_SIZE..2 * cols];
        assert!(
            rel_rms(live, got) < 0.15,
            "dead tile stretched the row's ladder"
        );
    }

    #[test]
    fn granite_42_maps_scaling_and_protects_vocabulary_edges() {
        let config = serde_json::json!({
            "architectures": ["GraniteForCausalLM"],
            "model_type": "granite",
            "hidden_size": 4096,
            "intermediate_size": 32768,
            "num_hidden_layers": 64,
            "num_attention_heads": 32,
            "num_key_value_heads": 8,
            "vocab_size": 100352,
            "max_position_embeddings": 131072,
            "rms_norm_eps": 0.00001,
            "rope_theta": 50000000.0,
            "attention_multiplier": 0.0078125,
            "embedding_multiplier": 1.0,
            "residual_multiplier": 1.0,
            "logits_scaling": 1.0,
            "hidden_act": "silu",
            "tie_word_embeddings": false
        });
        let arch = build_arch(&config).unwrap();
        assert_eq!(arch.arch_name, "granite");
        assert_eq!((arch.hidden_size, arch.head_dim), (4096, 128));
        assert_eq!(arch.rope_theta, 50_000_000.0);
        assert_eq!(arch.norm_style, NormStyle::Qwen);
        assert_eq!(arch.embed_multiplier, 1.0);
        assert_eq!(arch.logit_multiplier, None);
        assert_eq!(arch.query_pre_attn_scalar, Some(16_384.0));
        assert_eq!(
            quant_for_tensor(&arch, "model.embed_tokens.weight", Quant::Q4TiledP),
            Quant::Q8_2f
        );
        assert_eq!(
            quant_for_tensor(&arch, "lm_head.weight", Quant::Q4TiledP),
            Quant::Q8_2f
        );
        assert_eq!(
            quant_for_tensor(
                &arch,
                "model.layers.0.self_attn.q_proj.weight",
                Quant::Q4TiledP,
            ),
            Quant::Q4TiledP
        );
    }

    #[test]
    fn granite_refuses_an_unimplemented_residual_multiplier() {
        let config = serde_json::json!({
            "model_type": "granite",
            "hidden_size": 64,
            "intermediate_size": 128,
            "num_hidden_layers": 1,
            "num_attention_heads": 4,
            "num_key_value_heads": 2,
            "vocab_size": 32,
            "residual_multiplier": 0.22
        });
        let err = build_arch(&config).unwrap_err().to_string();
        assert!(err.contains("residual_multiplier=0.22"), "{err}");
    }

    #[test]
    fn laguna_config_maps_to_exact_cmf_contract() {
        let config = serde_json::json!({
            "model_type": "laguna",
            "hidden_size": 32,
            "intermediate_size": 64,
            "num_hidden_layers": 4,
            "num_attention_heads": 4,
            "num_attention_heads_per_layer": [4, 6, 6, 6],
            "num_key_value_heads": 2,
            "head_dim": 8,
            "vocab_size": 100,
            "max_position_embeddings": 1048576,
            "num_experts": 8,
            "num_experts_per_tok": 2,
            "moe_intermediate_size": 16,
            "shared_expert_intermediate_size": 16,
            "norm_topk_prob": true,
            "moe_routed_scaling_factor": 2.5,
            "sliding_window": 512,
            "layer_types": ["full_attention", "sliding_attention", "sliding_attention", "sliding_attention"],
            "rope_parameters": {
                "full_attention": {
                    "rope_type": "yarn", "rope_theta": 500000.0,
                    "factor": 128.0, "original_max_position_embeddings": 8192,
                    "beta_fast": 32.0, "beta_slow": 1.0,
                    "attention_factor": 1.485203, "partial_rotary_factor": 0.5
                },
                "sliding_attention": {
                    "rope_type": "default", "rope_theta": 10000.0,
                    "partial_rotary_factor": 1.0
                }
            }
        });
        let arch = build_arch(&config).unwrap();
        assert_eq!(arch.arch_name, "laguna");
        assert_eq!(arch.attention_heads_per_layer, Some(vec![4, 6, 6, 6]));
        assert_eq!(
            arch.layer_types,
            vec![
                LayerType::FullAttention,
                LayerType::SlidingAttention,
                LayerType::SlidingAttention,
                LayerType::SlidingAttention,
            ]
        );
        assert_eq!(arch.sliding_window, Some(512));
        assert_eq!(arch.rope_theta, 500000.0);
        assert_eq!(arch.rope_local_base_freq, Some(10000.0));
        assert_eq!(arch.partial_rotary_factor, 0.5);
        assert_eq!(arch.local_partial_rotary_factor, Some(1.0));
        let yarn = arch.yarn.unwrap();
        assert_eq!(yarn.factor, 128.0);
        let moe = arch.moe.unwrap();
        assert!(moe.router_sigmoid);
        assert_eq!(moe.routed_scaling_factor, Some(2.5));
        assert_eq!(
            canon_name("model.layers.1.mlp.experts.e_score_correction_bias").as_deref(),
            Some("model.layers.1.mlp.expert_bias")
        );
    }

    #[test]
    fn exec_order_lays_out_by_layer_then_block() {
        // Alphabetical order (the safetensors default) would put layer 10 before
        // layer 2 and the router after the experts — the exec-order key fixes both.
        let mut names: Vec<&str> = vec![
            "lm_head.weight",
            "model.layers.10.mlp.experts.1.up_proj.weight",
            "model.embed_tokens.weight",
            "model.layers.2.self_attn.q_proj.weight",
            "model.norm.weight",
            "model.layers.2.mlp.gate.weight", // MoE router
            "model.layers.2.mlp.experts.0.down_proj.weight",
            "model.layers.2.input_layernorm.weight",
            "model.layers.2.mlp.experts.0.gate_proj.weight",
            "model.layers.10.self_attn.o_proj.weight",
        ];
        names.sort_by(|a, b| {
            exec_order_key(a)
                .cmp(&exec_order_key(b))
                .then_with(|| a.cmp(b))
        });
        assert_eq!(
            names,
            vec![
                "model.embed_tokens.weight",
                "model.layers.2.input_layernorm.weight",
                "model.layers.2.self_attn.q_proj.weight",
                "model.layers.2.mlp.gate.weight",
                "model.layers.2.mlp.experts.0.gate_proj.weight",
                "model.layers.2.mlp.experts.0.down_proj.weight",
                "model.layers.10.self_attn.o_proj.weight",
                "model.layers.10.mlp.experts.1.up_proj.weight",
                "model.norm.weight",
                "lm_head.weight",
            ]
        );
    }

    #[test]
    fn vbit_roundtrip_within_quant_error() {
        // rows with distinct amplitudes → distinct bit-widths; 2 groups per row.
        let (rows, cols) = (5usize, 64usize);
        let mut vals = vec![0f32; rows * cols];
        for o in 0..rows {
            for i in 0..cols {
                vals[o * cols + i] = (o as f32 + 1.0) * 0.13 * (i as f32 * 0.27).sin();
            }
        }
        let enc = encode_vbit(&vals, rows, cols);
        // header sizes match the decoder's expectation.
        let bits = &enc[..rows];
        assert!(bits.iter().all(|&b| (3..=8).contains(&b)));
        let mut dec = vec![0f32; rows * cols];
        dequant_vbit(&enc, rows, cols, &mut dec).unwrap();
        for o in 0..rows {
            let amp = vals[o * cols..(o + 1) * cols]
                .iter()
                .fold(0f32, |m, v| m.max(v.abs()))
                .max(1e-6);
            for i in 0..cols {
                let e = (dec[o * cols + i] - vals[o * cols + i]).abs();
                assert!(
                    e <= amp * 0.2,
                    "row {o} col {i}: err {e} vs amp {amp} (bits {})",
                    bits[o]
                );
            }
        }
    }

    #[test]
    fn vbit_ro_roundtrip_and_validation() {
        use cortiq_core::TensorDtype;
        use cortiq_core::quant::{dequant_vbit_ro, validate_payload};
        let (rows, cols) = (5usize, 64usize);
        let mut vals = vec![0f32; rows * cols];
        for o in 0..rows {
            for i in 0..cols {
                vals[o * cols + i] = (o as f32 + 1.0) * 0.13 * (i as f32 * 0.27).sin();
            }
        }
        let enc = encode_vbit_ro(&vals, rows, cols);
        validate_payload(TensorDtype::VbitRo, &[rows, cols], &enc).unwrap();
        let mut dec = vec![0f32; rows * cols];
        dequant_vbit_ro(&enc, rows, cols, &mut dec).unwrap();
        // Must be BYTE-identical in reconstruction to the legacy layout.
        let legacy = encode_vbit(&vals, rows, cols);
        let mut dec_legacy = vec![0f32; rows * cols];
        dequant_vbit(&legacy, rows, cols, &mut dec_legacy).unwrap();
        assert_eq!(
            dec, dec_legacy,
            "vbit_ro must reconstruct exactly like vbit"
        );
    }

    #[test]
    fn tiktoken_roundtrip_synthetic() {
        use base64::Engine as _;
        let b64 = base64::engine::general_purpose::STANDARD;
        // Mini rank table: single bytes first, then pairs — exactly the
        // shape tiktoken ships (ranks are the merge order).
        let toks: Vec<&[u8]> = vec![
            b"h", b"e", b"l", b"o", b" ", b"w", b"r", b"d", b"he", b"ll", b"lo", b"hell", b"hello",
            b" w", b"or", b" wor", b" world",
        ];
        let model: String = toks
            .iter()
            .enumerate()
            .map(|(r, t)| format!("{} {}\n", b64.encode(t), r))
            .collect();
        let cfg = serde_json::json!({
            "added_tokens_decoder": {
                "100": {"content": "[BOS]"},
                "101": {"content": "[EOS]"}
            }
        });
        let json = tiktoken_to_tokenizer_json(&model, &cfg).unwrap();
        let tok = cortiq_engine::tokenizer::Tokenizer::from_json(&json).unwrap();
        let ids = tok.encode("hello world");
        // "hello" merges to one token (rank 12). " world"(16) is BPE-
        // UNREACHABLE with this table (merge path stops at " wor"+l+d) —
        // real tiktoken tokenizes it identically, which is exactly the
        // semantics the recovered merge list must reproduce.
        let strip: Vec<u32> = ids.iter().copied().filter(|&i| i != 100).collect(); // drop a possible auto-BOS
        assert_eq!(strip, vec![12, 15, 2, 7], "ids: {ids:?}");
        assert_eq!(tok.decode(&strip), "hello world");
    }

    #[test]
    fn qwen4_exp_arch_carries_portable_qsa_ple_geometry() {
        let cfg = serde_json::json!({
            "model_type": "qwen4_exp",
            "text_config": {
                "model_type": "qwen4_exp_text",
                "hidden_size": 2560,
                "moe_intermediate_size": 640,
                "num_hidden_layers": 48,
                "num_attention_heads": 24,
                "num_key_value_heads": 2,
                "head_dim": 256,
                "vocab_size": 248320,
                "max_position_embeddings": 262144,
                "partial_rotary_factor": 0.25,
                "rope_theta": 10000000,
                "num_experts": 512,
                "num_experts_per_tok": 10,
                "shared_expert_intermediate_size": 640,
                "linear_num_value_heads": 48,
                "linear_num_key_heads": 16,
                "linear_key_head_dim": 128,
                "linear_value_head_dim": 128,
                "linear_conv_kernel_dim": 4,
                "layer_types": ["linear_attention", "full_attention"],
                "hc_count": 4,
                "hc_lowrank": 320,
                "indexer_n_heads": 4,
                "indexer_kv_heads": 1,
                "indexer_head_dim": 128,
                "indexer_budget": 2048,
                "indexer_compress_ratio": 4,
                "ple_layer_ids": [2],
                "ple_embed_dim": 2560,
                "ple_conv_kernel_size": 4,
                "ngram_size": 3,
                "heads_per_ngram": 8,
                "ngram_vocab_size_base": 20000000,
                "make_ngram_vocab_size_divisible_by": 128,
                "split_ngram_parts": 128,
                "mtp_num_hidden_layers": 1
            }
        });
        let mut cfg = cfg;
        cfg["text_config"]["num_hidden_layers"] = 2.into();
        let mut arch = build_arch(&cfg).unwrap();
        let q = arch.qwen4_exp.as_ref().unwrap();
        assert_eq!(arch.norm_style, NormStyle::Gemma);
        assert_eq!(
            arch.layer_types,
            [LayerType::LinearAttention, LayerType::FullAttention]
        );
        assert_eq!((q.hc_count, q.hc_lowrank), (4, 320));
        assert_eq!((q.indexer_budget, q.indexer_compress_ratio), (2048, 4));
        assert_eq!(q.ple_layer_ids, [2]);
        assert_eq!(q.split_ngram_parts, 128);
        assert!(arch.moe.as_ref().unwrap().norm_topk_prob);
        assert!(arch.mtp.is_none(), "qwen4 MTP is a different stack");
        assert_eq!(
            quant_for_tensor(
                &arch,
                "model.layers.0.linear_attn.in_proj_qkv.weight",
                Quant::Q4TiledP,
            ),
            Quant::Q8_2f
        );
        assert_eq!(
            quant_for_tensor(
                &arch,
                "model.layers.0.mlp.experts.0.gate_proj.weight",
                Quant::Q4TiledP,
            ),
            Quant::Q4TiledP
        );
        assert_eq!(
            quant_for_tensor(
                &arch,
                "model.layers.1.ple.ple_embedding.ngram_embedding.shard_0.weight",
                Quant::Q4TiledP,
            ),
            Quant::Q4TiledP
        );
        assert!(force_f16(
            "model.hyper_connection_mixer.input_mix_weight_down.weight"
        ));
        arch.num_layers = 48;
        assert_eq!(
            directory_record_estimate(1, &arch),
            73_729,
            "the fixed streamed head must include packed MoE expansion"
        );
    }

    #[test]
    fn tiktoken_real_model_roundtrip() {
        // Gated: point CMF_TIKTOKEN at a real tiktoken.model (+ optional
        // CMF_TIKTOKEN_CFG tokenizer_config.json) to validate against the
        // shipped table. Skipped otherwise.
        let Ok(path) = std::env::var("CMF_TIKTOKEN") else {
            return;
        };
        let model = std::fs::read_to_string(&path).unwrap();
        let cfg: serde_json::Value = std::env::var("CMF_TIKTOKEN_CFG")
            .ok()
            .and_then(|p| std::fs::read_to_string(p).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or(serde_json::Value::Null);
        let t0 = std::time::Instant::now();
        let json = tiktoken_to_tokenizer_json(&model, &cfg).unwrap();
        eprintln!(
            "converted in {:?}, json {} MB",
            t0.elapsed(),
            json.len() / 1_000_000
        );
        let tok = cortiq_engine::tokenizer::Tokenizer::from_json(&json).unwrap();
        for text in [
            "Hello, world!",
            "Kimi Linear is a hybrid attention architecture.",
            "Пример текста на русском языке 123",
            "你好,世界!混合注意力架构。",
            "def main():\n    print(\"ok\")  # comment\n",
            "   spaces    and\ttabs\n\n",
        ] {
            let ids = tok.encode(text);
            let back = tok.decode(
                &ids.iter()
                    .copied()
                    .filter(|&i| Some(i) != tok.bos_token_id)
                    .collect::<Vec<_>>(),
            );
            assert_eq!(back, text, "roundtrip failed for {text:?} → {ids:?}");
            eprintln!("{:3} toks | {text:?}", ids.len());
        }
    }

    #[test]
    fn mxfp4_unpack_roundtrip() {
        // Values ON the E2M1 grid times power-of-two scales roundtrip
        // exactly; low nibble = even element (compressed-tensors pack).
        let grid = [0.0f32, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0];
        let rows = 2usize;
        let cols = 64usize; // two groups of 32 per row
        let scales_exp = [[127u8, 130u8], [124u8, 127u8]]; // ×1, ×8, ×0.125, ×1
        let mut want = vec![0.0f32; rows * cols];
        let mut packed = vec![0u8; rows * cols / 2];
        let mut scales = vec![0u8; rows * 2];
        for r in 0..rows {
            for g in 0..2 {
                let k = scales_exp[r][g];
                scales[r * 2 + g] = k;
                let sc = (k as f32 - 127.0).exp2();
                for i in 0..32 {
                    let nib = ((r * 31 + g * 7 + i * 3) % 16) as u8;
                    let mag = grid[(nib & 7) as usize];
                    let v = if nib & 8 != 0 { -mag } else { mag };
                    want[r * cols + g * 32 + i] = v * sc;
                    let byte = &mut packed[r * cols / 2 + g * 16 + i / 2];
                    if i % 2 == 0 {
                        *byte |= nib;
                    } else {
                        *byte |= nib << 4;
                    }
                }
            }
        }
        let got = unpack_mxfp4(&packed, &scales, rows, cols / 2).unwrap();
        assert_eq!(got, want);
        // NaN scale (E8M0 255) must refuse, not propagate.
        let mut bad = scales.clone();
        bad[0] = 255;
        assert!(unpack_mxfp4(&packed, &bad, rows, cols / 2).is_err());
    }

    #[test]
    fn minicpm3_arch_scales_and_factors() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{
            "model_type": "minicpm3",
            "hidden_size": 2560, "num_hidden_layers": 62,
            "num_attention_heads": 40, "intermediate_size": 6400,
            "vocab_size": 73448, "rms_norm_eps": 1e-5, "rope_theta": 10000.0,
            "q_lora_rank": 768, "kv_lora_rank": 256,
            "qk_rope_head_dim": 32, "qk_nope_head_dim": 64, "v_head_dim": 64,
            "scale_emb": 12, "scale_depth": 1.4, "dim_model_base": 256,
            "hidden_act": "silu",
            "max_position_embeddings": 32768,
            "rope_scaling": {
                "type": "longrope",
                "short_factor": [1.05, 1.12, 1.25, 1.53, 2.09, 3.14, 4.93, 7.52,
                                 10.47, 13.06, 14.85, 15.90, 16.46, 16.74, 16.87, 16.94],
                "long_factor":  [1.05, 1.12, 1.25, 1.53, 2.09, 3.14, 4.93, 7.52,
                                 10.47, 13.06, 14.85, 15.90, 16.46, 16.74, 16.87, 16.94],
                "original_max_position_embeddings": 32768
            }
        }"#,
        )
        .unwrap();
        let arch = build_arch(&cfg).unwrap();
        assert_eq!(arch.embed_multiplier, 12.0, "scale_emb");
        assert_eq!(arch.logit_multiplier, Some(0.1), "dim_model_base/hidden");
        let fac = arch
            .rope_freq_factors
            .as_ref()
            .expect("short factors carried");
        assert_eq!(fac.len(), 16);
        assert!((fac[15] - 16.94).abs() < 1e-9);
        assert!(arch.tie_word_embeddings, "no lm_head tensor — tied");
        let mla = arch.mla.as_ref().expect("MLA");
        assert_eq!(mla.q_lora_rank, Some(768), "compressed q");
        assert!(!mla.nope);
        assert_eq!(arch.max_position_embeddings, 32768, "native window");
    }

    #[test]
    fn kimi_canon_names() {
        let c = |s: &str| canon_name(s).unwrap();
        // K3 wrapper prefix + mixtral-style expert names → canonical MoE.
        assert_eq!(
            c("language_model.model.layers.3.block_sparse_moe.experts.5.w1.weight"),
            "model.layers.3.mlp.experts.5.gate_proj.weight"
        );
        assert_eq!(
            c("model.layers.2.block_sparse_moe.experts.0.w2.weight"),
            "model.layers.2.mlp.experts.0.down_proj.weight"
        );
        assert_eq!(
            c("model.layers.2.block_sparse_moe.experts.0.w3.weight"),
            "model.layers.2.mlp.experts.0.up_proj.weight"
        );
        assert_eq!(
            c("model.layers.2.block_sparse_moe.gate.weight"),
            "model.layers.2.mlp.gate.weight"
        );
        assert_eq!(
            c("model.layers.2.block_sparse_moe.gate.e_score_correction_bias"),
            "model.layers.2.mlp.expert_bias"
        );
        assert_eq!(
            c("model.layers.2.block_sparse_moe.shared_experts.gate_proj.weight"),
            "model.layers.2.mlp.shared_expert.gate_proj.weight"
        );
        // Vision tower dropped (text tower converts alone).
        assert_eq!(
            canon_name("vision_tower.encoder.blocks.0.wqkv.weight"),
            None
        );
        assert_eq!(canon_name("mm_projector.proj.0.weight"), None);
    }

    #[test]
    fn kimi_linear_arch_layers_and_geometry() {
        // Kimi-Linear-48B shape in miniature: 8 layers, full attention on
        // the 1-BASED layers [4, 8], KDA elsewhere; MLA NoPE; sigmoid MoE.
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{
            "model_type": "kimi_linear",
            "hidden_size": 2304, "num_hidden_layers": 8,
            "num_attention_heads": 32, "num_key_value_heads": 32,
            "intermediate_size": 9216, "vocab_size": 1000,
            "rms_norm_eps": 1e-5, "rope_theta": 10000.0,
            "kv_lora_rank": 512, "qk_rope_head_dim": 64,
            "qk_nope_head_dim": 128, "v_head_dim": 128,
            "mla_use_nope": true,
            "hidden_act": "silu",
            "num_experts": 256, "num_experts_per_token": 8,
            "moe_intermediate_size": 1024, "num_shared_experts": 1,
            "moe_renormalize": true, "moe_router_activation_func": "sigmoid",
            "first_k_dense_replace": 1,
            "linear_attn_config": {
                "full_attn_layers": [4, 8],
                "kda_layers": [1, 2, 3, 5, 6, 7],
                "head_dim": 128, "num_heads": 32,
                "short_conv_kernel_size": 4
            }
        }"#,
        )
        .unwrap();
        let arch = build_arch(&cfg).unwrap();
        assert_eq!(arch.num_layers, 8);
        // 1-based full_attn_layers [4,8] → 0-based indices 3 and 7.
        for (i, t) in arch.layer_types.iter().enumerate() {
            let want_full = i == 3 || i == 7;
            assert_eq!(
                matches!(t, cortiq_core::LayerType::FullAttention),
                want_full,
                "layer {i}"
            );
            assert_eq!(
                matches!(t, cortiq_core::LayerType::Kda),
                !want_full,
                "layer {i}"
            );
        }
        assert_eq!(arch.linear_num_key_heads, Some(32));
        assert_eq!(arch.linear_key_head_dim, Some(128));
        assert_eq!(arch.linear_value_head_dim, Some(128));
        assert_eq!(arch.linear_conv_kernel_dim, Some(4));
        let mla = arch.mla.as_ref().expect("kv_lora_rank → MLA");
        assert!(mla.nope, "mla_use_nope must carry into the header");
        assert_eq!(mla.q_lora_rank, None);
        let moe = arch.moe.as_ref().expect("num_experts → MoE");
        assert_eq!(moe.num_experts, 256);
        assert_eq!(moe.top_k, 8);
        assert!(moe.router_sigmoid, "sigmoid router");
        assert!(moe.norm_topk_prob, "moe_renormalize");
        assert_eq!(moe.shared_expert_intermediate_size, Some(1024));
        assert!(arch.kda_gate_lower_bound.is_none());
    }

    #[test]
    fn kimi_k3_unsupported_features_bail_honestly() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{
            "model_type": "kimi_k3",
            "text_config": {
                "model_type": "kimi_linear",
                "hidden_size": 7168, "num_hidden_layers": 4,
                "num_attention_heads": 96, "intermediate_size": 33792,
                "vocab_size": 1000, "rms_norm_eps": 1e-5,
                "kv_lora_rank": 512, "qk_rope_head_dim": 64,
                "qk_nope_head_dim": 128, "v_head_dim": 128,
                "attn_res_block_size": 12,
                "linear_attn_config": {
                    "full_attn_layers": [4],
                    "head_dim": 128, "num_heads": 96,
                    "short_conv_kernel_size": 4,
                    "gate_lower_bound": -5.0
                }
            }
        }"#,
        )
        .unwrap();
        let err = build_arch(&cfg).unwrap_err().to_string();
        assert!(err.contains("attn_res_block_size"), "got: {err}");
    }

    #[test]
    fn fused_gdn_split_is_correct_permutation() {
        // nk=2, dk=3, nv=4 (r=2), dv=2, hid=1. Each source row's value = its flat
        // row index, so we can trace exactly where each row lands after the split.
        let (nk, dk, nv, dv, hid) = (2usize, 3usize, 4usize, 2usize, 1usize);
        let r = nv / nk; // 2
        let gw = 2 * dk + 2 * r * dv; // 6 + 8 = 14
        let w: Vec<f32> = (0..nk * gw * hid).map(|i| i as f32).collect();
        let out =
            split_fused_gdn("m.linear_attn.in_proj_qkvz.weight", &w, hid, nk, dk, nv, dv).unwrap();
        let qkv = &out[0];
        assert_eq!(qkv.0, "m.linear_attn.in_proj_qkv.weight");
        assert_eq!(qkv.2, 2 * nk * dk + nv * dv); // 12 + 8 = 20
        // q rows: group g row rr -> source flat row g*gw+rr.
        // g=0 -> rows 0,1,2 ; g=1 -> rows 14,15,16
        assert_eq!(qkv.1[0..3], [0.0, 1.0, 2.0]);
        assert_eq!(qkv.1[3..6], [14.0, 15.0, 16.0]);
        // k rows: source g*gw + dk+rr. g=0 -> 3,4,5 ; g=1 -> 17,18,19
        assert_eq!(qkv.1[6..9], [3.0, 4.0, 5.0]);
        assert_eq!(qkv.1[9..12], [17.0, 18.0, 19.0]);
        // v rows: source g*gw + 2dk+rr (rr 0..4). g=0 -> 6,7,8,9 ; g=1 -> 20,21,22,23
        assert_eq!(qkv.1[12..16], [6.0, 7.0, 8.0, 9.0]);
        assert_eq!(qkv.1[16..20], [20.0, 21.0, 22.0, 23.0]);
        let z = &out[1];
        assert_eq!(z.0, "m.linear_attn.in_proj_z.weight");
        assert_eq!(z.2, nv * dv); // 8
        // z rows: source g*gw + 2dk+r*dv+rr. g=0 -> 10,11,12,13 ; g=1 -> 24,25,26,27
        assert_eq!(z.1, [10.0, 11.0, 12.0, 13.0, 24.0, 25.0, 26.0, 27.0]);

        // in_proj_ba: group width 2r=4. rows nk*4 = 8.
        let wb: Vec<f32> = (0..nk * 2 * r * hid).map(|i| i as f32).collect();
        let outb =
            split_fused_gdn("m.linear_attn.in_proj_ba.weight", &wb, hid, nk, dk, nv, dv).unwrap();
        // b = first r per group: g=0 -> 0,1 ; g=1 -> 4,5
        assert_eq!(outb[0].0, "m.linear_attn.in_proj_b.weight");
        assert_eq!(outb[0].1, [0.0, 1.0, 4.0, 5.0]);
        // a = next r per group: g=0 -> 2,3 ; g=1 -> 6,7
        assert_eq!(outb[1].0, "m.linear_attn.in_proj_a.weight");
        assert_eq!(outb[1].1, [2.0, 3.0, 6.0, 7.0]);
    }

    /// LFM2.5 states its mixer per layer in `layer_types`, spelling the
    /// recurrent one `conv`. The header has to carry that verbatim: a
    /// layer read as full attention would allocate a KV cache for a
    /// mixer that has none, and the short-conv ring would never advance.
    /// A VL wrapper's vision tower must not ride into the file: 333
    /// `model.visual.*` tensors under raw names is ~a gigabyte of dead
    /// weight the loader never reads (Ornith-1.5 / Qwen3.5-VL layout).
    #[test]
    fn a_vision_tower_is_skipped_whole() {
        for n in [
            "model.visual.patch_embed.proj.weight",
            "model.visual.blocks.0.attn.qkv.weight",
            "model.visual.merger.mlp.0.weight",
        ] {
            assert!(canon_name(n).is_none(), "{n} must be skipped");
        }
        // The text tower under the same wrapper still converts.
        assert_eq!(
            canon_name("model.language_model.layers.0.mlp.gate_proj.weight").as_deref(),
            Some("model.layers.0.mlp.gate_proj.weight")
        );
    }

    #[test]
    fn lfm25_layer_types_and_conv_cache_reach_the_header() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{
            "model_type": "lfm2", "architectures": ["Lfm2ForCausalLM"],
            "hidden_size": 1024, "num_hidden_layers": 6,
            "num_attention_heads": 16, "num_key_value_heads": 8,
            "intermediate_size": 2560, "vocab_size": 65536,
            "norm_eps": 1e-5, "conv_L_cache": 3, "conv_bias": false,
            "layer_types": ["conv","conv","full_attention","conv","full_attention","conv"],
            "tie_word_embeddings": true
        }"#,
        )
        .unwrap();
        let arch = build_arch(&cfg).unwrap();
        assert_eq!(arch.num_layers, 6);
        for (i, t) in arch.layer_types.iter().enumerate() {
            let want_full = i == 2 || i == 4;
            assert_eq!(
                matches!(t, cortiq_core::LayerType::FullAttention),
                want_full,
                "layer {i} attention kind"
            );
            assert_eq!(
                matches!(t, cortiq_core::LayerType::ShortConv),
                !want_full,
                "layer {i} mixer kind"
            );
        }
        // The ring is `conv_L_cache` deep; without it the conv reads
        // whatever the state buffer happened to hold.
        assert_eq!(arch.linear_conv_kernel_dim, Some(3));
        assert!(arch.moe.is_none(), "the dense build has no experts");
    }

    /// The 8B-A1B build is the same mixer schedule with a routed FFN.
    /// LFM2 routes with a sigmoid gate rather than a softmax over all
    /// experts, and reading that wrong changes which experts fire.
    #[test]
    fn lfm25_moe_routes_with_a_sigmoid_gate() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{
            "model_type": "lfm2_moe", "architectures": ["Lfm2MoeForCausalLM"],
            "hidden_size": 2048, "num_hidden_layers": 4,
            "num_attention_heads": 32, "num_key_value_heads": 8,
            "intermediate_size": 7168, "vocab_size": 128000,
            "norm_eps": 1e-5, "conv_L_cache": 3,
            "layer_types": ["conv","conv","full_attention","conv"],
            "num_experts": 32, "num_experts_per_tok": 4,
            "moe_intermediate_size": 1792, "norm_topk_prob": true,
            "routed_scaling_factor": 1.0,
            "tie_word_embeddings": true
        }"#,
        )
        .unwrap();
        let arch = build_arch(&cfg).unwrap();
        let moe = arch.moe.as_ref().expect("num_experts → MoE");
        assert_eq!(moe.num_experts, 32);
        assert_eq!(moe.top_k, 4);
        assert_eq!(moe.moe_intermediate_size, 1792);
        assert!(moe.router_sigmoid, "lfm2 routes with a sigmoid gate");
        assert!(moe.norm_topk_prob);
        // A scale of exactly 1.0 is the no-op default and must not ride
        // in the header as if it were a correction.
        assert!(moe.routed_scaling_factor.is_none());
        assert_eq!(arch.linear_conv_kernel_dim, Some(3));
    }

    #[test]
    fn lfm2_names_map_to_canonical_layout() {
        // Conv (dense) layer 0.
        let c = |s: &str| canon_name(s).unwrap();
        assert_eq!(c("model.embedding_norm.weight"), "model.norm.weight");
        assert_eq!(
            c("model.layers.0.operator_norm.weight"),
            "model.layers.0.input_layernorm.weight"
        );
        assert_eq!(
            c("model.layers.0.ffn_norm.weight"),
            "model.layers.0.post_attention_layernorm.weight"
        );
        assert_eq!(
            c("model.layers.0.conv.in_proj.weight"),
            "model.layers.0.short_conv.in_proj.weight"
        );
        assert_eq!(
            c("model.layers.0.conv.conv.weight"),
            "model.layers.0.short_conv.conv.weight"
        );
        assert_eq!(
            c("model.layers.0.conv.out_proj.weight"),
            "model.layers.0.short_conv.out_proj.weight"
        );
        // Dense FFN: w1/w3/w2 → gate/up/down.
        assert_eq!(
            c("model.layers.0.feed_forward.w1.weight"),
            "model.layers.0.mlp.gate_proj.weight"
        );
        assert_eq!(
            c("model.layers.0.feed_forward.w3.weight"),
            "model.layers.0.mlp.up_proj.weight"
        );
        assert_eq!(
            c("model.layers.0.feed_forward.w2.weight"),
            "model.layers.0.mlp.down_proj.weight"
        );
        // Attention (full_attention layer 2): out_proj → o_proj, q/k layernorm.
        assert_eq!(
            c("model.layers.2.self_attn.out_proj.weight"),
            "model.layers.2.self_attn.o_proj.weight"
        );
        assert_eq!(
            c("model.layers.2.self_attn.q_layernorm.weight"),
            "model.layers.2.self_attn.q_norm.weight"
        );
        assert_eq!(
            c("model.layers.2.self_attn.k_layernorm.weight"),
            "model.layers.2.self_attn.k_norm.weight"
        );
        // MoE router / bias / experts.
        assert_eq!(
            c("model.layers.2.feed_forward.gate.weight"),
            "model.layers.2.mlp.gate.weight"
        );
        assert_eq!(
            c("model.layers.2.feed_forward.expert_bias"),
            "model.layers.2.mlp.expert_bias"
        );
        assert_eq!(
            c("model.layers.2.feed_forward.experts.7.w1.weight"),
            "model.layers.2.mlp.experts.7.gate_proj.weight"
        );
        assert_eq!(
            c("model.layers.2.feed_forward.experts.7.w2.weight"),
            "model.layers.2.mlp.experts.7.down_proj.weight"
        );
        // Q/K/V projections already canonical — must pass through untouched.
        assert_eq!(
            c("model.layers.2.self_attn.q_proj.weight"),
            "model.layers.2.self_attn.q_proj.weight"
        );
        // A Qwen tensor must be untouched by the LFM2 rewrite.
        assert_eq!(
            c("model.layers.3.mlp.gate_proj.weight"),
            "model.layers.3.mlp.gate_proj.weight"
        );
    }

    #[test]
    fn lfm2_moe_arch_routing_and_layers() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{"model_type":"lfm2_moe","hidden_size":2048,"num_hidden_layers":4,
                "num_attention_heads":32,"num_key_value_heads":8,"intermediate_size":7168,
                "moe_intermediate_size":1792,"vocab_size":128000,"norm_eps":1e-5,
                "conv_L_cache":3,"num_experts":32,"num_experts_per_tok":4,
                "norm_topk_prob":true,"use_expert_bias":true,"routed_scaling_factor":1.0,
                "tie_word_embeddings":true,"rope_parameters":{"rope_theta":5000000},
                "layer_types":["conv","conv","full_attention","conv"]}"#,
        )
        .unwrap();
        let arch = build_arch(&cfg).unwrap();
        assert_eq!(arch.layer_types[0], LayerType::ShortConv);
        assert_eq!(arch.layer_types[2], LayerType::FullAttention);
        assert_eq!(arch.head_dim, 64);
        assert_eq!(arch.linear_conv_kernel_dim, Some(3));
        assert!((arch.rms_norm_eps - 1e-5).abs() < 1e-12);
        let moe = arch.moe.as_ref().unwrap();
        assert!(
            moe.router_sigmoid,
            "lfm2_moe must route with a sigmoid gate"
        );
        assert_eq!(moe.top_k, 4);
        assert!(moe.norm_topk_prob);
        // Scale 1.0 stores as None (no-op).
        assert_eq!(moe.routed_scaling_factor, None);
    }

    /// The safety invariant that lets `q1p` be an unconditional replacement
    /// for `q1` on models that ARE 1-bit-trained: when every group weight
    /// already sits on ±s, the carry stays zero and no sign flips, so the
    /// encoder is bit-identical to the plain sign quantizer. (For a NORMAL
    /// checkpoint the two differ — that difference is the training-free PTQ,
    /// judged by end-to-end PPL, not by any single closed-form proxy.)
    #[test]
    fn q1_ef_bit_identical_on_a_1bit_tensor() {
        let (rows, cols) = (4usize, 96usize);
        let onebit: Vec<f32> = (0..rows * cols)
            .map(|i| if (i * 7 + 3) % 5 < 2 { 0.25 } else { -0.25 })
            .collect();
        assert_eq!(
            encode_q1(&onebit, rows, cols),
            encode_q1_ef(&onebit, rows, cols),
            "error diffusion must be a no-op on a genuinely 1-bit tensor"
        );
    }

    /// Q1S roundtrip: kept outliers come back at f16 precision and the bulk
    /// decodes to the per-group ±s level. Guards the format the fold will
    /// populate.
    #[test]
    fn q1s_roundtrip_restores_outliers_and_binarizes_the_rest() {
        use cortiq_core::quant::dequant_q1s;
        let (rows, cols) = (2usize, 64usize);
        let mut vals: Vec<f32> = (0..rows * cols)
            .map(|i| (i as f32 * 0.017).sin() * 0.1)
            .collect();
        let spikes = [5usize, 40, 70, 120];
        for &i in &spikes {
            vals[i] = if i % 2 == 0 { 3.0 } else { -3.0 };
        }
        let keep = spikes.len() as f32 / (rows * cols) as f32;
        let bytes = encode_q1s(&vals, rows, cols, keep);
        let mut dec = vec![0f32; rows * cols];
        dequant_q1s(&bytes, &mut dec);
        for &i in &spikes {
            assert!(
                (dec[i] - vals[i]).abs() < 0.02,
                "outlier {i}: {} vs {}",
                dec[i],
                vals[i]
            );
        }
        for i in 0..rows * cols {
            if !spikes.contains(&i) {
                assert!(
                    dec[i].abs() < 2.0,
                    "bulk {i} should be a small ±s, got {}",
                    dec[i]
                );
            }
        }
    }

    #[test]
    fn parse_quant_variants() {
        for q in ["q8", "q8_row", "q8_2f", "q4", "q4_block", "f16"] {
            assert!(parse_quant(q).is_ok(), "{q}");
        }
        assert!(parse_quant("nope").is_err());
    }

    #[test]
    fn q8_row_roundtrips() {
        let (o, i) = (4usize, 64usize);
        let vals: Vec<f32> = (0..o * i).map(|k| (k as f32 * 0.017).sin() * 2.5).collect();
        let bytes = encode_q8_row(&vals, o, i);
        assert_eq!(bytes.len(), o * i + o * 2);
        let mut back = vec![0f32; o * i];
        dequant_q8_row(&bytes, o, i, &mut back);
        for (a, b) in vals.iter().zip(&back) {
            assert!((a - b).abs() < 0.05, "{a} vs {b}");
        }
    }

    #[test]
    fn q8_2f_roundtrips() {
        let (o, i) = (8usize, 48usize);
        let vals: Vec<f32> = (0..o * i).map(|k| (k as f32 * 0.023).cos() * 1.7).collect();
        let bytes = encode_q8_2f(&vals, o, i);
        assert_eq!(bytes.len(), o * i + o * 2 + i * 2);
        let mut back = vec![0f32; o * i];
        dequant_q8_2f(&bytes, o, i, &mut back);
        for (a, b) in vals.iter().zip(&back) {
            assert!((a - b).abs() < 0.1, "{a} vs {b}");
        }
    }

    #[test]
    fn q4_block_roundtrips() {
        let vals: Vec<f32> = (0..128).map(|k| (k as f32 * 0.05).sin()).collect();
        let bytes = encode_q4_block(&vals);
        let mut back = vec![0f32; 128];
        dequant_q4_block(&bytes, &mut back);
        for (a, b) in vals.iter().zip(&back) {
            assert!((a - b).abs() < 0.2, "{a} vs {b}");
        }
    }

    /// A raw safetensors blob from F32 tensors, for the end-to-end test.
    fn tiny_safetensors(tensors: &[(&str, Vec<usize>, Vec<f32>)]) -> Vec<u8> {
        let mut header = serde_json::Map::new();
        let mut data = Vec::new();
        for (name, shape, vals) in tensors {
            let start = data.len();
            for &v in vals {
                data.extend_from_slice(&v.to_le_bytes());
            }
            header.insert(
                name.to_string(),
                serde_json::json!({"dtype":"F32","shape":shape,"data_offsets":[start, data.len()]}),
            );
        }
        let hjson = serde_json::to_vec(&serde_json::Value::Object(header)).unwrap();
        let mut out = (hjson.len() as u64).to_le_bytes().to_vec();
        out.extend_from_slice(&hjson);
        out.extend_from_slice(&data);
        out
    }

    #[test]
    fn local_ready_rejects_partial_or_changed_source_before_mmap() {
        let root = std::env::temp_dir().join(format!(
            "cortiq-local-ready-boundary-test-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        let source_dir = root.join("hf");
        let ready_dir = root.join("ready");
        fs::create_dir_all(&source_dir).unwrap();
        fs::create_dir_all(&ready_dir).unwrap();
        let filename = "model-00001-of-00001.safetensors";
        let source = source_dir.join(filename);
        let bytes = b"complete safetensors source";
        fs::write(&source, bytes).unwrap();
        let (_, sha256) = sha256_file(&source).unwrap();
        let expected = SourceFileExpectation {
            size: bytes.len() as u64,
            sha256,
        };
        let marker = ready_marker_path(&ready_dir, filename).unwrap();
        fs::write(
            source.with_file_name(format!("{filename}.aria2")),
            b"partial",
        )
        .unwrap();
        fs::write(
            &marker,
            serde_json::to_vec(&serde_json::json!({
                "filename": filename,
                "size": expected.size,
                "sha256": expected.sha256
            }))
            .unwrap(),
        )
        .unwrap();
        let err = validate_local_ready_source(&ready_dir, &source_dir, filename, &expected)
            .expect_err("a source with .aria2 must never be mmaped");
        assert!(err.to_string().contains("aria2"), "unexpected error: {err}");
        fs::remove_file(source.with_file_name(format!("{filename}.aria2"))).unwrap();

        let mut changed = bytes.to_vec();
        changed[0] ^= 0x01;
        fs::write(&source, changed).unwrap();
        let err = validate_local_ready_source(&ready_dir, &source_dir, filename, &expected)
            .expect_err("a changed source must fail the pinned SHA256 check");
        assert!(
            err.to_string().contains("SHA256") || err.to_string().contains("validation"),
            "unexpected error: {err}"
        );

        fs::write(&source, bytes).unwrap();
        assert_eq!(
            validate_local_ready_source(&ready_dir, &source_dir, filename, &expected).unwrap(),
            source
        );
        fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn local_ready_stream_processes_certified_shards_and_preserves_source() {
        let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::set_var(LOCAL_READY_POLL_MS_ENV, "0");
            std::env::remove_var(LOCAL_READY_DIR_ENV);
            std::env::remove_var(CONSUME_SOURCE_SHARDS_ENV);
        }
        let root = std::env::temp_dir().join(format!(
            "cortiq-local-ready-stream-test-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        let source_dir = root.join("hf");
        let ready_dir = root.join("ready");
        fs::create_dir_all(&source_dir).unwrap();
        fs::create_dir_all(&ready_dir).unwrap();
        let first = "model-00001-of-00002.safetensors";
        let second = "model-00002-of-00002.safetensors";
        let shards = [
            (
                first,
                tiny_safetensors(&[("embed.weight", vec![2, 2], vec![1.0, 2.0, 3.0, 4.0])]),
            ),
            (
                second,
                tiny_safetensors(&[("norm.weight", vec![2], vec![1.0, 1.0])]),
            ),
        ];
        let mut manifest = serde_json::Map::new();
        for (name, bytes) in &shards {
            fs::write(source_dir.join(name), bytes).unwrap();
            let (size, sha256) = sha256_file(&source_dir.join(name)).unwrap();
            assert_eq!(size, bytes.len() as u64);
            manifest.insert(
                (*name).to_string(),
                serde_json::json!({"size": size, "sha256": sha256}),
            );
            fs::write(
                ready_dir.join(format!("{name}.json")),
                serde_json::json!({
                    "filename": name,
                    "size": size,
                    "sha256": sha256
                })
                .to_string(),
            )
            .unwrap();
        }
        fs::write(
            root.join("source-files.json"),
            serde_json::to_vec(&serde_json::Value::Object(manifest)).unwrap(),
        )
        .unwrap();
        fs::write(
            source_dir.join("config.json"),
            serde_json::json!({
                "model_type": "deepseek_v41",
                "text_config": {
                    "model_type": "deepseek_v41_text",
                    "hidden_size": 2,
                    "intermediate_size": 4,
                    "num_hidden_layers": 1,
                    "num_attention_heads": 1,
                    "num_key_value_heads": 1,
                    "head_dim": 2,
                    "vocab_size": 2,
                    "rms_norm_eps": 1e-6
                }
            })
            .to_string(),
        )
        .unwrap();
        fs::write(
            source_dir.join("model.safetensors.index.json"),
            serde_json::json!({
                "weight_map": {
                    "embed.weight": first,
                    "norm.weight": second
                }
            })
            .to_string(),
        )
        .unwrap();

        let output = root.join("ready.cmf");
        let mut last_progress = 0.0f32;
        unsafe {
            std::env::set_var(LOCAL_READY_DIR_ENV, &ready_dir);
        }
        run_convert_multi(
            source_dir.to_str().unwrap(),
            &[("q8".into(), output.to_str().unwrap().into())],
            None,
            None,
            None,
            false,
            |p| last_progress = p,
        )
        .unwrap();
        assert_eq!(last_progress, 1.0);
        assert!(source_dir.join(first).exists());
        assert!(source_dir.join(second).exists());
        let model = CmfModel::open(&output).unwrap();
        assert!(
            model.verify().is_empty(),
            "CMF verify: {:?}",
            model.verify()
        );
        unsafe {
            std::env::remove_var(LOCAL_READY_DIR_ENV);
            std::env::remove_var(LOCAL_READY_POLL_MS_ENV);
        }
        fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn source_shard_priority_resume_matches_default_payloads() {
        // The priority path must remain a pure scheduling change: start with
        // the second shard already written and durably marked, remove that
        // source as the consuming pod would, then resume in [second, first]
        // order.  Comparing every final tensor's bytes against an ordinary
        // [first, second] conversion catches both duplicate and missing work.
        let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::remove_var(SOURCE_SHARD_PRIORITY_ENV);
            std::env::remove_var(CONSUME_SOURCE_SHARDS_ENV);
            std::env::set_var(LOCAL_READY_POLL_MS_ENV, "0");
        }
        let root = std::env::temp_dir().join(format!(
            "cortiq-source-priority-resume-test-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        let default_dir = root.join("default");
        let default_ready = root.join("default-ready");
        let priority_dir = root.join("priority");
        let priority_ready = root.join("priority-ready");
        let first = "model-00001-of-00002.safetensors";
        let second = "model-00002-of-00002.safetensors";
        let first_values = vec![1.0f32, 2.0, 3.0, 4.0];
        let second_values = vec![1.0f32, 1.0];

        let write_fixture = |dir: &Path, ready: &Path| {
            fs::create_dir_all(dir).unwrap();
            fs::create_dir_all(ready).unwrap();
            let shards = [
                (
                    first,
                    tiny_safetensors(&[("embed.weight", vec![2, 2], first_values.clone())]),
                ),
                (
                    second,
                    tiny_safetensors(&[("norm.weight", vec![2], second_values.clone())]),
                ),
            ];
            let mut manifest = serde_json::Map::new();
            for (name, bytes) in &shards {
                let source = dir.join(name);
                fs::write(&source, bytes).unwrap();
                let (size, sha256) = sha256_file(&source).unwrap();
                manifest.insert(
                    (*name).to_string(),
                    serde_json::json!({"size": size, "sha256": sha256}),
                );
                fs::write(
                    ready.join(format!("{name}.json")),
                    serde_json::json!({
                        "filename": name,
                        "size": size,
                        "sha256": sha256
                    })
                    .to_string(),
                )
                .unwrap();
            }
            fs::write(
                ready
                    .parent()
                    .expect("ready directory has a fixture parent")
                    .join("source-files.json"),
                serde_json::to_vec(&serde_json::Value::Object(manifest)).unwrap(),
            )
            .unwrap();
            fs::write(
                dir.join("config.json"),
                serde_json::json!({
                    "model_type": "deepseek_v41",
                    "text_config": {
                        "model_type": "deepseek_v41_text",
                        "hidden_size": 2,
                        "intermediate_size": 4,
                        "num_hidden_layers": 1,
                        "num_attention_heads": 1,
                        "num_key_value_heads": 1,
                        "head_dim": 2,
                        "vocab_size": 2,
                        "rms_norm_eps": 1e-6
                    }
                })
                .to_string(),
            )
            .unwrap();
            fs::write(
                dir.join("model.safetensors.index.json"),
                serde_json::json!({
                    "weight_map": {
                        "embed.weight": first,
                        "norm.weight": second
                    }
                })
                .to_string(),
            )
            .unwrap();
        };
        write_fixture(&default_dir, &default_ready);
        write_fixture(&priority_dir, &priority_ready);

        let default_output = root.join("default.cmf");
        unsafe {
            std::env::set_var(LOCAL_READY_DIR_ENV, &default_ready);
        }
        run_convert_multi(
            default_dir.to_str().unwrap(),
            &[("f16".into(), default_output.to_str().unwrap().into())],
            None,
            None,
            None,
            false,
            |_| {},
        )
        .unwrap();

        // Seed the resumed output with the second shard's exact f16 payload.
        // Its mark is durable before the source is removed, which is the
        // checkpoint contract exercised by the production consume path.
        let priority_output = root.join("priority.cmf");
        let priority_manifest = format!("{}.manifest", priority_output.display());
        let mut writer = cortiq_core::format::CmfStreamWriter::new(
            &priority_output,
            cortiq_core::format::CmfStreamWriter::head_reserve_for(8192, 96),
        )
        .unwrap()
        .with_manifest(&priority_manifest)
        .unwrap();
        writer
            .push(
                "model.norm.weight",
                TensorDtype::F16,
                &[2],
                &encode_f16(&second_values),
            )
            .unwrap();
        writer.mark(second).unwrap();
        drop(writer);
        fs::remove_file(priority_dir.join(second)).unwrap();

        unsafe {
            std::env::set_var(LOCAL_READY_DIR_ENV, &priority_ready);
            std::env::set_var(SOURCE_SHARD_PRIORITY_ENV, format!("{second},{first}"));
        }
        run_convert_multi(
            priority_dir.to_str().unwrap(),
            &[("f16".into(), priority_output.to_str().unwrap().into())],
            None,
            None,
            None,
            true,
            |_| {},
        )
        .unwrap();

        let default_model = CmfModel::open(&default_output).unwrap();
        let priority_model = CmfModel::open(&priority_output).unwrap();
        assert!(default_model.verify().is_empty());
        assert!(priority_model.verify().is_empty());
        assert_eq!(default_model.tensors.len(), priority_model.tensors.len());
        for expected in &default_model.tensors {
            let actual = priority_model
                .tensor(&expected.name)
                .unwrap_or_else(|| panic!("resumed output lacks {}", expected.name));
            assert_eq!(actual.dtype, expected.dtype, "dtype {}", expected.name);
            assert_eq!(actual.shape, expected.shape, "shape {}", expected.name);
            assert_eq!(actual.nbytes, expected.nbytes, "size {}", expected.name);
            assert_eq!(actual.hash, expected.hash, "hash {}", expected.name);
            assert_eq!(
                default_model.tensor_bytes(&expected.name).unwrap(),
                priority_model.tensor_bytes(&expected.name).unwrap(),
                "payload {}",
                expected.name
            );
        }
        assert!(priority_dir.join(first).exists());
        assert!(!priority_dir.join(second).exists());
        unsafe {
            std::env::remove_var(LOCAL_READY_DIR_ENV);
            std::env::remove_var(LOCAL_READY_POLL_MS_ENV);
            std::env::remove_var(SOURCE_SHARD_PRIORITY_ENV);
        }
        fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn resume_skips_deleted_marked_shard_but_rejects_unmarked_missing_input() {
        // This is the failure mode of a V4.1 pod restart: the first shard was
        // durably marked and consumed before the process died, while the next
        // shard still has to be opened. The index and manifest are the only
        // files that survive source-shard consumption.
        let dir =
            std::env::temp_dir().join(format!("cortiq-resume-shard-test-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let first = "model-00001-of-00002.safetensors";
        let second = "model-00002-of-00002.safetensors";
        fs::write(
            dir.join(first),
            tiny_safetensors(&[("layers.0.weight", vec![2, 2], vec![1.0, 2.0, 3.0, 4.0])]),
        )
        .unwrap();
        fs::write(
            dir.join(second),
            tiny_safetensors(&[("layers.1.weight", vec![2, 2], vec![5.0, 6.0, 7.0, 8.0])]),
        )
        .unwrap();
        fs::write(
            dir.join("model.safetensors.index.json"),
            serde_json::to_vec(&serde_json::json!({
                "metadata": {},
                "weight_map": {
                    "layers.0.weight": first,
                    "layers.1.weight": second
                }
            }))
            .unwrap(),
        )
        .unwrap();

        let counts = source_shard_counts(&dir).unwrap();
        assert_eq!(
            counts,
            vec![(first.to_string(), 1), (second.to_string(), 1)]
        );
        let mut files = open_model(&dir).unwrap();
        assert_eq!(files.len(), 2);
        consume_source_shard(&mut files, 0, &dir).unwrap();
        assert!(!dir.join(first).exists());
        drop(files);

        let manifest = dir.join("resume.cmf.manifest");
        fs::write(
            &manifest,
            format!(
                "{{\"data_off\":4096}}\n{{\"mark\":\"{first}\",\"at\":16}}\n{{truncated\n{{\"mark\":\"{second}\",\"at\":32}}"
            ),
        )
        .unwrap();
        let marks = resume_manifest_marks(&manifest);
        assert!(marks.contains(first));
        assert!(!marks.contains(second));

        let pending = open_model_filtered(&dir, &marks).unwrap();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].name, second);
        assert_eq!(pending[0].tensors[0].name, "layers.1.weight");
        drop(pending);

        // A missing shard without a durable mark must remain a hard error;
        // silently skipping it would produce a valid-looking incomplete CMF.
        fs::remove_file(dir.join(second)).unwrap();
        assert!(open_model_filtered(&dir, &marks).is_err());
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn resume_after_checkpoint_consumes_deleted_inputs_and_finalizes_in_place() {
        // Exercise the complete local path with a partial CMF: its first
        // source shard is checkpointed, then deleted as if the pod died after
        // consumption. Resume must retain that durable payload, convert the
        // remaining shard, and finish the same output without a duplicate.
        let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::set_var(CONSUME_SOURCE_SHARDS_ENV, "1");
        }
        let dir = std::env::temp_dir().join(format!(
            "cortiq-resume-in-place-test-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let first = "model-00001-of-00002.safetensors";
        let second = "model-00002-of-00002.safetensors";
        let first_values = vec![1.0f32, 2.0, 3.0, 4.0];
        fs::write(
            dir.join(first),
            tiny_safetensors(&[("embed.weight", vec![2, 2], first_values.clone())]),
        )
        .unwrap();
        fs::write(
            dir.join(second),
            tiny_safetensors(&[("norm.weight", vec![2], vec![1.0, 1.0])]),
        )
        .unwrap();
        let config = serde_json::json!({
            "model_type": "deepseek_v41",
            "text_config": {
                "model_type": "deepseek_v41_text",
                "hidden_size": 2,
                "intermediate_size": 4,
                "num_hidden_layers": 1,
                "num_attention_heads": 1,
                "num_key_value_heads": 1,
                "head_dim": 2,
                "vocab_size": 2,
                "rms_norm_eps": 1e-6
            }
        });
        fs::write(
            dir.join("config.json"),
            serde_json::to_vec(&config).unwrap(),
        )
        .unwrap();
        fs::write(
            dir.join("model.safetensors.index.json"),
            serde_json::to_vec(&serde_json::json!({
                "weight_map": {"embed.weight": first, "norm.weight": second}
            }))
            .unwrap(),
        )
        .unwrap();

        let output = dir.join("resume.cmf");
        let manifest = format!("{}.manifest", output.display());
        let mut writer = cortiq_core::format::CmfStreamWriter::new(
            &output,
            cortiq_core::format::CmfStreamWriter::head_reserve_for(8192, 96),
        )
        .unwrap()
        .with_manifest(&manifest)
        .unwrap();
        let first_bytes: Vec<u8> = first_values.iter().flat_map(|v| v.to_le_bytes()).collect();
        writer
            .push(
                "model.embed_tokens.weight",
                TensorDtype::F32,
                &[2, 2],
                &first_bytes,
            )
            .unwrap();
        writer.mark(first).unwrap();
        drop(writer);
        fs::remove_file(dir.join(first)).unwrap();

        let mut last_progress = 0.0f32;
        run_convert_multi(
            dir.to_str().unwrap(),
            &[("q8".into(), output.to_str().unwrap().into())],
            None,
            None,
            None,
            true,
            |p| last_progress = p,
        )
        .unwrap();
        assert_eq!(last_progress, 1.0);
        assert!(!dir.join(first).exists());
        assert!(!dir.join(second).exists());
        assert!(!std::path::Path::new(&manifest).exists());
        let model = CmfModel::open(&output).unwrap();
        assert!(
            model.verify().is_empty(),
            "CMF verify: {:?}",
            model.verify()
        );
        assert_eq!(
            model.arch().deepseek_v41.as_ref(),
            Some(&config),
            "the original V4.1 config must survive resume/finalization"
        );
        assert_eq!(
            model
                .tensors
                .iter()
                .filter(|t| t.name == "model.embed_tokens.weight")
                .count(),
            1,
            "resuming must not append the checkpointed shard twice"
        );
        unsafe {
            std::env::remove_var(CONSUME_SOURCE_SHARDS_ENV);
        }
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn convert_tiny_model_end_to_end() {
        let dir = std::env::temp_dir().join(format!("cortiq-convtest-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join("config.json"),
            r#"{"model_type":"llama","hidden_size":64,"num_hidden_layers":1,"num_attention_heads":4,"num_key_value_heads":4,"intermediate_size":128,"vocab_size":32,"rms_norm_eps":0.000001,"tie_word_embeddings":true}"#,
        )
        .unwrap();
        fs::write(dir.join("tokenizer.json"), b"{}").unwrap();
        let st = tiny_safetensors(&[
            (
                "model.embed_tokens.weight",
                vec![32, 64],
                (0..32 * 64).map(|k| (k as f32 * 0.01).sin()).collect(),
            ),
            ("model.norm.weight", vec![64], vec![1.0f32; 64]),
        ]);
        fs::write(dir.join("model.safetensors"), &st).unwrap();
        let out = dir.join("m.cmf");
        run_convert(
            dir.to_str().unwrap(),
            "q8",
            out.to_str().unwrap(),
            None,
            None,
            None,
            false,
            |_| {},
        )
        .unwrap();

        let model = CmfModel::open(&out).unwrap();
        assert_eq!(model.arch().vocab_size, 32);
        assert_eq!(model.arch().num_layers, 1);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn multi_quant_emits_independent_profiles_and_matches_single_runs() {
        // This end-to-end fixture uses the ordinary local source path.  The
        // local-ready tests steer process-global environment variables while
        // they certify their temporary shards, so only this small group of
        // tests shares ENV_LOCK; the rest of the suite remains parallel.
        let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::remove_var(LOCAL_READY_DIR_ENV);
            std::env::remove_var(LOCAL_READY_POLL_MS_ENV);
            std::env::remove_var(CONSUME_SOURCE_SHARDS_ENV);
            std::env::remove_var(SOURCE_SHARD_PRIORITY_ENV);
        }
        let dir =
            std::env::temp_dir().join(format!("cortiq-multi-convtest-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join("config.json"),
            r#"{"model_type":"llama","hidden_size":64,"num_hidden_layers":1,"num_attention_heads":4,"num_key_value_heads":4,"intermediate_size":128,"vocab_size":32,"rms_norm_eps":0.000001,"tie_word_embeddings":true}"#,
        )
        .unwrap();
        fs::write(dir.join("tokenizer.json"), b"{}").unwrap();
        let vals = |n: usize| (0..n).map(|k| (k as f32 * 0.013).sin()).collect::<Vec<_>>();
        let st = tiny_safetensors(&[
            ("model.embed_tokens.weight", vec![32, 64], vals(32 * 64)),
            (
                "model.layers.0.mlp.gate_proj.weight",
                vec![128, 64],
                vals(128 * 64),
            ),
            (
                "model.layers.0.mlp.up_proj.weight",
                vec![128, 64],
                vals(128 * 64),
            ),
            (
                "model.layers.0.mlp.down_proj.weight",
                vec![64, 128],
                vals(64 * 128),
            ),
            ("model.norm.weight", vec![64], vec![1.0f32; 64]),
        ]);
        fs::write(dir.join("model.safetensors"), &st).unwrap();

        let q4 = dir.join("single-q4.cmf");
        let q2 = dir.join("single-q2.cmf");
        run_convert(
            dir.to_str().unwrap(),
            "q4tp",
            q4.to_str().unwrap(),
            None,
            None,
            None,
            false,
            |_| {},
        )
        .unwrap();
        run_convert(
            dir.to_str().unwrap(),
            "q2tp",
            q2.to_str().unwrap(),
            None,
            None,
            None,
            false,
            |_| {},
        )
        .unwrap();
        let both4 = dir.join("both-q4.cmf");
        let both2 = dir.join("both-q2.cmf");
        run_convert_multi(
            dir.to_str().unwrap(),
            &[
                ("q4tp".into(), both4.to_str().unwrap().into()),
                ("q2tp".into(), both2.to_str().unwrap().into()),
            ],
            None,
            None,
            None,
            false,
            |_| {},
        )
        .unwrap();

        let single4 = CmfModel::open(&q4).unwrap();
        let single2 = CmfModel::open(&q2).unwrap();
        let multi4 = CmfModel::open(&both4).unwrap();
        let multi2 = CmfModel::open(&both2).unwrap();
        assert_eq!(single4.tensors.len(), multi4.tensors.len());
        assert_eq!(single2.tensors.len(), multi2.tensors.len());
        for (a, b) in single4.tensors.iter().zip(&multi4.tensors) {
            assert_eq!(
                (a.name.as_str(), a.dtype, a.shape.as_slice()),
                (b.name.as_str(), b.dtype, b.shape.as_slice())
            );
            assert_eq!(single4.entry_bytes(a), multi4.entry_bytes(b));
        }
        for (a, b) in single2.tensors.iter().zip(&multi2.tensors) {
            assert_eq!(
                (a.name.as_str(), a.dtype, a.shape.as_slice()),
                (b.name.as_str(), b.dtype, b.shape.as_slice())
            );
            assert_eq!(single2.entry_bytes(a), multi2.entry_bytes(b));
        }
        let gate4 = multi4
            .tensor("model.layers.0.mlp.gate_proj.weight")
            .unwrap();
        let gate2 = multi2
            .tensor("model.layers.0.mlp.gate_proj.weight")
            .unwrap();
        assert_eq!(gate4.dtype, TensorDtype::Q4TiledP);
        assert_eq!(gate2.dtype, TensorDtype::Q2TiledP);
        assert!(!both4.with_extension("cmf.manifest").exists());
        assert!(!both2.with_extension("cmf.manifest").exists());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn multi_quant_rejects_duplicate_outputs() {
        let err = run_convert_multi(
            "missing/model",
            &[
                ("q4tp".into(), "same.cmf".into()),
                ("q2tp".into(), "same.cmf".into()),
            ],
            None,
            None,
            None,
            false,
            |_| {},
        )
        .unwrap_err();
        assert!(err.to_string().contains("repeated"));
    }

    /// Qwen3.6 ships an MTP head the converter used to drop on the floor.
    /// It must survive, and land under the names the loader reads.
    #[test]
    fn mtp_head_is_kept_and_renamed_to_the_loader_layout() {
        let m = |s: &str| canon_name(s);
        assert_eq!(
            m("mtp.fc.weight").as_deref(),
            Some("model.mtp.eh_proj.weight")
        );
        assert_eq!(
            m("mtp.pre_fc_norm_embedding.weight").as_deref(),
            Some("model.mtp.enorm.weight")
        );
        assert_eq!(
            m("mtp.pre_fc_norm_hidden.weight").as_deref(),
            Some("model.mtp.hnorm.weight")
        );
        assert_eq!(
            m("mtp.norm.weight").as_deref(),
            Some("model.mtp.norm.weight")
        );
        // The block's own tensors pass through untouched — including the MoE
        // mlp, which is what this head actually carries.
        assert_eq!(
            m("mtp.layers.0.self_attn.q_proj.weight").as_deref(),
            Some("model.mtp.layers.0.self_attn.q_proj.weight")
        );
        assert_eq!(
            m("mtp.layers.0.mlp.experts.gate_up_proj").as_deref(),
            Some("model.mtp.layers.0.mlp.experts.gate_up_proj")
        );
        assert_eq!(
            m("mtp.layers.0.mlp.shared_expert_gate.weight").as_deref(),
            Some("model.mtp.layers.0.mlp.shared_expert_gate.weight")
        );
        // Vision towers are still dropped.
        assert!(m("visual.blocks.0.attn.qkv.weight").is_none());
    }

    #[test]
    fn prism_patch_kernel_is_flattened_in_processor_channel_order() {
        // Source layout is [out, temporal, height, width, channel]; the
        // runtime's flattened patch rows are [channel, temporal, height,
        // width].  Use one output row so every source coordinate is visible.
        let shape = [1, 2, 2, 2, 3];
        let source: Vec<u16> = (0..shape.iter().product::<usize>())
            .map(|v| f32_to_f16(v as f32).to_le())
            .collect();
        let raw = source
            .iter()
            .flat_map(|v| v.to_le_bytes())
            .collect::<Vec<_>>();
        let (flat_shape, flat) = flatten_prism_patch_weight("F16", &shape, &raw).unwrap();
        assert_eq!(flat_shape, vec![1, 24]);
        let mut want = Vec::new();
        for c in 0..3 {
            for t in 0..2 {
                for y in 0..2 {
                    for x in 0..2 {
                        let src = ((((t * 2 + y) * 2 + x) * 3) + c) as f32;
                        want.push(src);
                    }
                }
            }
        }
        assert_eq!(flat, want);
    }
}

#[cfg(test)]
mod hunyuan_tests {
    use super::*;
    use cortiq_core::quant::{GROUP_SIZE, Q1T_TILE, dequant_q1t};

    #[test]
    fn hunyuan_dense_config_builds_ntk_alpha_and_late_qk_norm() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{"architectures":["HunYuanDenseV1ForCausalLM"],"model_type":"hunyuan_v1_dense",
                "hidden_size":2048,"intermediate_size":6144,"num_hidden_layers":32,
                "num_attention_heads":16,"num_key_value_heads":4,"head_dim":128,
                "attention_head_dim":128,"vocab_size":120818,"rms_norm_eps":1e-5,
                "rope_theta":10000.0,"max_position_embeddings":262144,
                "rope_scaling":{"alpha":1000.0,"beta_fast":32,"beta_slow":1,"factor":1.0,
                                "mscale":1.0,"mscale_all_dim":1.0,"type":"dynamic"},
                "tie_word_embeddings":true,"use_qk_norm":true,"use_cla":false,
                "norm_type":"rms","hidden_act":"silu","bos_token_id":120000,
                "eos_token_id":120020,"pad_token_id":120002}"#,
        )
        .unwrap();
        let arch = build_arch(&cfg).unwrap();
        assert_eq!(arch.arch_name, "hunyuan_v1_dense");
        assert!(arch.qk_norm_after_rope, "HunYuan dense norms after RoPE");
        // 10000 · 1000^(128/126) — the base llama.cpp writes as rope.freq_base.
        assert!(
            (arch.rope_theta - 11_158_840.0).abs() / 11_158_840.0 < 1e-5,
            "rope_theta {}",
            arch.rope_theta
        );
        assert_eq!(arch.max_position_embeddings, 262_144, "no window cap");
        assert_eq!((arch.head_dim, arch.num_kv_heads, arch.num_attention_heads), (128, 4, 16));
        assert!(arch.tie_word_embeddings);
        assert!(arch.moe.is_none());
        assert_eq!(arch.partial_rotary_factor, 1.0);
        assert!(arch.yarn.is_none());
    }

    #[test]
    fn hunyuan_dense_refuses_cross_layer_attention() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{"model_type":"hunyuan_v1_dense","hidden_size":64,"intermediate_size":128,
                "num_hidden_layers":2,"num_attention_heads":4,"num_key_value_heads":2,
                "head_dim":16,"vocab_size":100,"use_cla":true}"#,
        )
        .unwrap();
        let err = build_arch(&cfg).unwrap_err().to_string();
        assert!(err.contains("use_cla"), "{err}");
    }

    #[test]
    fn hy_v3_moe_config_builds_sigmoid_biased_router() {
        let cfg: serde_json::Value = serde_json::from_str(
            r#"{"architectures":["HYV3ForCausalLM"],"model_type":"hy_v3",
                "hidden_size":2048,"intermediate_size":6912,"num_hidden_layers":48,
                "num_attention_heads":32,"num_key_value_heads":4,"head_dim":128,
                "vocab_size":120832,"rms_norm_eps":1e-5,"rope_theta":11158840.0,
                "max_position_embeddings":262144,"tie_word_embeddings":false,
                "num_experts":128,"num_experts_per_tok":8,"moe_intermediate_size":768,
                "expert_hidden_dim":768,"num_shared_experts":1,"first_k_dense_replace":1,
                "moe_router_enable_expert_bias":true,"moe_router_use_sigmoid":true,
                "route_norm":true,"router_scaling_factor":2.826,"qk_norm":true,
                "hidden_act":"silu","bos_token_id":120000,"eos_token_id":120025,
                "eod_token_id":120026,"pad_token_id":120002}"#,
        )
        .unwrap();
        let arch = build_arch(&cfg).unwrap();
        assert_eq!(arch.arch_name, "hy_v3");
        assert!(!arch.qk_norm_after_rope, "hy_v3 keeps the Qwen3 order");
        assert_eq!(arch.rope_theta, 11_158_840.0);
        assert_eq!(arch.intermediate_size, 6912, "layer-0 dense FFN width");
        let moe = arch.moe.as_ref().expect("num_experts → MoE");
        assert_eq!((moe.num_experts, moe.top_k, moe.moe_intermediate_size), (128, 8, 768));
        assert!(moe.norm_topk_prob, "route_norm");
        assert!(moe.router_sigmoid, "moe_router_use_sigmoid");
        assert_eq!(moe.shared_expert_intermediate_size, Some(768));
        assert!((moe.routed_scaling_factor.unwrap() - 2.826).abs() < 1e-6);
        assert!(!moe.router_resonance);
    }

    #[test]
    fn hunyuan_tensor_names_land_on_the_canonical_layout() {
        let m = |s: &str| canon_name(s).unwrap();
        assert_eq!(
            m("model.layers.3.self_attn.query_layernorm.weight"),
            "model.layers.3.self_attn.q_norm.weight"
        );
        assert_eq!(
            m("model.layers.3.self_attn.key_layernorm.weight"),
            "model.layers.3.self_attn.k_norm.weight"
        );
        assert_eq!(
            m("model.layers.1.mlp.router.gate.weight"),
            "model.layers.1.mlp.gate.weight"
        );
        assert_eq!(
            m("model.layers.1.mlp.shared_mlp.up_proj.weight"),
            "model.layers.1.mlp.shared_expert.up_proj.weight"
        );
        assert_eq!(m("model.layers.1.mlp.expert_bias"), "model.layers.1.mlp.expert_bias");
        assert_eq!(
            m("model.layers.1.mlp.experts.17.down_proj.weight"),
            "model.layers.1.mlp.experts.17.down_proj.weight"
        );
        assert!(force_f32("model.layers.1.mlp.expert_bias"));
    }

    #[test]
    fn q1t_exact_reproduces_ternary_weights_bit_for_bit() {
        let (rows, cols) = (3usize, 96usize);
        let mut w = vec![0f32; rows * cols];
        for (g, grp) in w.chunks_mut(GROUP_SIZE).enumerate() {
            let s = f16_to_f32(f32_to_f16(0.013 * (g as f32 + 1.0)));
            for (k, v) in grp.iter_mut().enumerate() {
                *v = match (k * 7 + g) % 3 {
                    0 => 0.0,
                    1 => s,
                    _ => -s,
                };
            }
        }
        let enc = encode_q1t_exact(&w, rows, cols).unwrap();
        assert_eq!(enc.len(), (rows * cols / GROUP_SIZE) * Q1T_TILE + (rows + 1) * 4);
        let mut back = vec![0f32; rows * cols];
        dequant_q1t(&enc, rows, cols, &mut back);
        assert_eq!(back, w);
        // Non-ternary input is refused, never silently rounded.
        let mut bad = w.clone();
        bad[5] = 0.5 * bad.iter().find(|v| **v > 0.0).copied().unwrap();
        assert!(encode_q1t_exact(&bad, rows, cols).is_err());
    }
}