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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
bytefalcon_fast60m.py

One CLI for:
  * building the byte-fallback + universal-special tokenizer,
  * initializing a deeper ~60M-parameter hybrid local-attention model from scratch,
  * atomically appending/deduplicating/shuffling new rewrite batches,
  * packing rewrite.jsonl into 4096-token byte streams,
  * training/resuming on ROCm,
  * running quick validation and generation.

Expected JSONL schema:
    {"instruction": "...", "text": "...", "output": "..."}
"""

from __future__ import annotations
from collections import Counter
import argparse
import contextlib
import gc
import hashlib
import inspect
import json
import math
import os
import random
import shutil
import sqlite3
import sys
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Iterator, Mapping, Sequence


SCRIPT_VERSION = "3.1.1-fast60m-rocm-compile-safe"
PROJECT_DIR = Path(__file__).resolve().parent
DEFAULT_INVENTORY = PROJECT_DIR / "special_tokens.json"

CONTROL_TOKENS = [
    "<pad>",
    "<bos>",
    "<eos>",
    "<unk>",
    "<instruction>",
    "<text>",
    "<output>",
    "<record>",
    "<byte_start>",
    "<byte_end>",
]

DEFAULT_ARCHITECTURE = {
    "target_parameters": 60_000_000,
    "hidden_size": 512,
    "embedding_size": 256,
    "ffn_latent_size": 256,
    "num_hidden_layers": 24,
    "num_attention_heads": 8,
    "num_key_value_heads": 2,
    "attention_every": 4,
    "window_size": 512,
    "conv_kernel_size": 4,
    "memory_size": 128,
    "memory_heads": 4,
    "attention_residual_group_size": 4,
    "mtp_loss_weight": 0.20,
    "max_position_embeddings": 4096,
}

# Runtime defaults for ROCm/PyTorch.
os.environ.setdefault("USE_HUB_KERNELS", "NO")
os.environ.setdefault("PYTORCH_ALLOC_CONF", "expandable_segments:True")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
os.environ.setdefault("USE_ROCM_CK_GEMM", "1")
os.environ.pop("PYTORCH_HIP_ALLOC_CONF", None)


# ---------------------------------------------------------------------------
# Generic utilities
# ---------------------------------------------------------------------------

def atomic_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    file_descriptor, temporary_name = tempfile.mkstemp(
        prefix=path.name + ".",
        suffix=".tmp",
        dir=path.parent,
    )
    try:
        with os.fdopen(
            file_descriptor,
            "w",
            encoding="utf-8",
        ) as handle:
            json.dump(
                value,
                handle,
                ensure_ascii=False,
                indent=2,
                sort_keys=True,
            )
            handle.write("\n")
        os.replace(temporary_name, path)
    finally:
        with contextlib.suppress(FileNotFoundError):
            os.unlink(temporary_name)


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(
            lambda: handle.read(8 * 1024 * 1024),
            b"",
        ):
            digest.update(block)
    return digest.hexdigest()


def sha256_text(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def now_iso() -> str:
    import datetime as dt

    return dt.datetime.now(dt.timezone.utc).isoformat()


def configure_torch_runtime(torch: Any) -> None:
    with contextlib.suppress(Exception):
        torch.set_float32_matmul_precision("high")
    with contextlib.suppress(Exception):
        torch.backends.cuda.matmul.allow_tf32 = True
    with contextlib.suppress(Exception):
        torch.backends.cudnn.benchmark = True
    # Prefer fused SDPA kernels on CUDA/ROCm, while retaining the math fallback.
    with contextlib.suppress(Exception):
        torch.backends.cuda.enable_flash_sdp(True)
    with contextlib.suppress(Exception):
        torch.backends.cuda.enable_mem_efficient_sdp(True)
    with contextlib.suppress(Exception):
        torch.backends.cuda.enable_math_sdp(True)
    with contextlib.suppress(Exception):
        torch._dynamo.config.cache_size_limit = 64


def clear_memory(torch: Any | None = None) -> None:
    gc.collect()
    if torch is not None and torch.cuda.is_available():
        torch.cuda.empty_cache()
        with contextlib.suppress(Exception):
            torch.cuda.ipc_collect()


# ---------------------------------------------------------------------------
# Rewrite records and atomic corpus expansion
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class RewriteRecord:
    instruction: str
    text: str
    output: str

    @property
    def digest(self) -> str:
        value = (
            self.instruction
            + "\x1f"
            + self.text
            + "\x1f"
            + self.output
        )
        return sha256_text(value)

    def to_dict(self) -> dict[str, str]:
        return {
            "instruction": self.instruction,
            "text": self.text,
            "output": self.output,
        }


def normalize_record(value: Mapping[str, Any]) -> RewriteRecord:
    missing = [
        key
        for key in ("instruction", "text", "output")
        if key not in value
    ]
    if missing:
        raise ValueError(
            "Missing rewrite keys: " + ", ".join(missing)
        )

    return RewriteRecord(
        instruction=str(value["instruction"] or ""),
        text=str(value["text"] or ""),
        output=str(value["output"] or ""),
    )


def iter_jsonl(path: Path) -> Iterator[RewriteRecord]:
    with path.open("r", encoding="utf-8-sig") as handle:
        for line_number, raw_line in enumerate(handle, start=1):
            line = raw_line.strip()
            if not line:
                continue
            try:
                value = json.loads(line)
            except json.JSONDecodeError as error:
                raise ValueError(
                    f"{path}:{line_number}: invalid JSON: {error}"
                ) from error
            if not isinstance(value, dict):
                raise ValueError(
                    f"{path}:{line_number}: expected a JSON object."
                )
            try:
                yield normalize_record(value)
            except ValueError as error:
                raise ValueError(
                    f"{path}:{line_number}: {error}"
                ) from error


def iter_json_file(path: Path) -> Iterator[RewriteRecord]:
    value = json.loads(path.read_text(encoding="utf-8-sig"))
    if isinstance(value, dict) and isinstance(value.get("data"), list):
        value = value["data"]
    if not isinstance(value, list):
        raise ValueError(
            f"{path}: expected a JSON list or a {{'data': [...]}} object."
        )
    for index, item in enumerate(value):
        if not isinstance(item, dict):
            raise ValueError(
                f"{path}: item {index} is not an object."
            )
        yield normalize_record(item)


def iter_records(path: Path) -> Iterator[RewriteRecord]:
    suffix = path.suffix.lower()
    if suffix in {".jsonl", ".ndjson"}:
        yield from iter_jsonl(path)
    elif suffix == ".json":
        yield from iter_json_file(path)
    else:
        raise ValueError(f"Unsupported batch type: {path}")


def discover_batches(
    inbox: Path,
    *,
    recursive: bool,
) -> list[Path]:
    patterns = ("*.jsonl", "*.ndjson", "*.json")
    found: set[Path] = set()
    for pattern in patterns:
        iterator = (
            inbox.rglob(pattern)
            if recursive
            else inbox.glob(pattern)
        )
        found.update(
            path.resolve()
            for path in iterator
            if path.is_file()
        )
    return sorted(found)


def deterministic_sort_key(seed: int, digest: str) -> str:
    return sha256_text(f"{seed}:{digest}")


def sync_dataset(args: argparse.Namespace) -> dict[str, Any]:
    base = args.data.resolve()
    inbox = args.inbox.resolve()
    archive = args.archive.resolve() if args.archive else None

    if not base.is_file():
        raise FileNotFoundError(f"Base dataset does not exist: {base}")
    if not inbox.is_dir():
        raise FileNotFoundError(f"Inbox directory does not exist: {inbox}")

    batches = [
        path
        for path in discover_batches(
            inbox,
            recursive=args.recursive,
        )
        if path != base
    ]

    work_dir = args.work_dir.resolve()
    work_dir.mkdir(parents=True, exist_ok=True)
    database_path = work_dir / "dataset-sync.sqlite3"
    database_path.unlink(missing_ok=True)

    connection = sqlite3.connect(database_path)
    connection.execute("PRAGMA journal_mode=WAL")
    connection.execute("PRAGMA synchronous=NORMAL")
    connection.execute("PRAGMA temp_store=FILE")
    connection.execute(
        """
        CREATE TABLE records (
            digest TEXT PRIMARY KEY,
            sort_key TEXT NOT NULL,
            instruction TEXT NOT NULL,
            text_value TEXT NOT NULL,
            output_value TEXT NOT NULL,
            source TEXT NOT NULL
        )
        """
    )

    stats = {
        "base_rows_seen": 0,
        "new_rows_seen": 0,
        "unique_rows": 0,
        "duplicates": 0,
        "invalid_files": [],
        "batch_files": [str(path) for path in batches],
    }

    def insert_record(record: RewriteRecord, source: str) -> None:
        cursor = connection.execute(
            """
            INSERT OR IGNORE INTO records
            (digest, sort_key, instruction, text_value, output_value, source)
            VALUES (?, ?, ?, ?, ?, ?)
            """,
            (
                record.digest,
                deterministic_sort_key(args.seed, record.digest),
                record.instruction,
                record.text,
                record.output,
                source,
            ),
        )
        if cursor.rowcount == 0:
            stats["duplicates"] += 1

    with connection:
        for record in iter_jsonl(base):
            stats["base_rows_seen"] += 1
            insert_record(record, str(base))

        for batch in batches:
            try:
                for record in iter_records(batch):
                    stats["new_rows_seen"] += 1
                    insert_record(record, str(batch))
            except Exception as error:
                stats["invalid_files"].append(
                    {
                        "path": str(batch),
                        "error": f"{type(error).__name__}: {error}",
                    }
                )
                if not args.skip_invalid_files:
                    connection.close()
                    database_path.unlink(missing_ok=True)
                    raise

    stats["unique_rows"] = int(
        connection.execute("SELECT COUNT(*) FROM records").fetchone()[0]
    )

    temporary = base.with_suffix(base.suffix + ".sync.tmp")
    with temporary.open("w", encoding="utf-8") as handle:
        cursor = connection.execute(
            """
            SELECT instruction, text_value, output_value
            FROM records
            ORDER BY sort_key, digest
            """
        )
        for instruction, text_value, output_value in cursor:
            handle.write(
                json.dumps(
                    {
                        "instruction": instruction,
                        "text": text_value,
                        "output": output_value,
                    },
                    ensure_ascii=False,
                    separators=(",", ":"),
                )
            )
            handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())

    connection.close()

    backup = None
    if args.backup:
        backup = base.with_name(
            f"{base.name}.before-sync-{int(time.time())}"
        )
        shutil.copy2(base, backup)

    os.replace(temporary, base)

    archived = []
    if archive is not None:
        archive.mkdir(parents=True, exist_ok=True)
        for batch in batches:
            if not batch.exists():
                continue
            destination = archive / batch.name
            if destination.exists():
                destination = archive / (
                    f"{batch.stem}-{int(time.time())}{batch.suffix}"
                )
            shutil.move(str(batch), str(destination))
            archived.append(str(destination))

    database_path.unlink(missing_ok=True)
    stats.update(
        {
            "data": str(base),
            "sha256": sha256_file(base),
            "seed": args.seed,
            "backup": str(backup) if backup else None,
            "archived": archived,
            "completed_at": now_iso(),
        }
    )

    audit = args.audit or base.with_suffix(".sync.json")
    atomic_json(audit, stats)
    print(json.dumps(stats, ensure_ascii=False, indent=2))
    return stats


# ---------------------------------------------------------------------------
# Byte-level tokenizer with universal special atoms
# ---------------------------------------------------------------------------

def bytes_to_unicode() -> dict[int, str]:
    """
    GPT-2/ByteLevel's reversible byte-to-Unicode alphabet.
    """
    byte_values = (
        list(range(ord("!"), ord("~") + 1))
        + list(range(ord("¡"), ord("¬") + 1))
        + list(range(ord("®"), ord("ÿ") + 1))
    )
    unicode_values = list(byte_values)
    extra = 0
    for byte_value in range(256):
        if byte_value not in byte_values:
            byte_values.append(byte_value)
            unicode_values.append(256 + extra)
            extra += 1
    return {
        byte_value: chr(codepoint)
        for byte_value, codepoint in zip(
            byte_values,
            unicode_values,
            strict=True,
        )
    }


def build_tokenizer(args: argparse.Namespace) -> dict[str, Any]:
    try:
        from tokenizers import AddedToken, Tokenizer, decoders, models
        from tokenizers import pre_tokenizers
        from transformers import PreTrainedTokenizerFast
    except ImportError as error:
        raise RuntimeError(
            "Tokenizer construction requires tokenizers and transformers."
        ) from error

    inventory_path = args.inventory.resolve()
    inventory = json.loads(
        inventory_path.read_text(encoding="utf-8")
    )
    output_dir = args.output.resolve()
    output_dir.mkdir(parents=True, exist_ok=True)

    byte_alphabet = bytes_to_unicode()
    vocab: dict[str, int] = {}

    for token in CONTROL_TOKENS:
        vocab[token] = len(vocab)

    byte_ids: dict[str, int] = {}
    for byte_value in range(256):
        token = byte_alphabet[byte_value]
        vocab[token] = len(vocab)
        byte_ids[f"{byte_value:02X}"] = vocab[token]

    backend = Tokenizer(
        models.BPE(
            vocab=vocab,
            merges=[],
            unk_token="<unk>",
            byte_fallback=False,
        )
    )
    backend.pre_tokenizer = pre_tokenizers.ByteLevel(
        add_prefix_space=False,
        use_regex=False,
    )
    backend.decoder = decoders.ByteLevel()

    added_tokens = []
    for entry in inventory["tokens"]:
        surface = entry["token"]
        if surface in CONTROL_TOKENS:
            continue
        added_tokens.append(
            AddedToken(
                surface,
                single_word=(entry["mode"] == "word"),
                normalized=False,
                lstrip=False,
                rstrip=False,
                special=True,
            )
        )

    backend.add_special_tokens(added_tokens)

    universal_surfaces = [
        entry["token"]
        for entry in inventory["tokens"]
        if entry["token"] not in CONTROL_TOKENS
    ]
    tokenizer = PreTrainedTokenizerFast(
        tokenizer_object=backend,
        bos_token="<bos>",
        eos_token="<eos>",
        unk_token="<unk>",
        pad_token="<pad>",
        additional_special_tokens=[
            *CONTROL_TOKENS[4:],
            *universal_surfaces,
        ],
        clean_up_tokenization_spaces=False,
        model_max_length=args.context_length,
    )
    tokenizer.padding_side = "right"
    tokenizer.truncation_side = "right"
    tokenizer.save_pretrained(output_dir)

    samples = [
        "Hello, byte world.",
        "0.003 + 15 = 15.003",
        "encode tokens and matrices",
        "😀 👍🏽 🇩🇴 👩‍💻",
        "line one\nline two\tend",
        "UTF-8: café, 日本語, العربية",
    ]
    audits = []
    for sample in samples:
        ids = tokenizer.encode(
            sample,
            add_special_tokens=False,
        )
        decoded = tokenizer.decode(
            ids,
            skip_special_tokens=False,
            clean_up_tokenization_spaces=False,
        )
        if decoded != sample:
            raise RuntimeError(
                f"Tokenizer round-trip failed: {sample!r} -> {decoded!r}"
            )
        audits.append(
            {
                "text": sample,
                "tokens": len(ids),
                "ids": ids[:64],
            }
        )

    # A string deliberately absent from the universal inventory must fall back
    # to one token per UTF-8 byte.
    fallback_sample = "qxjv"
    fallback_ids = tokenizer.encode(
        fallback_sample,
        add_special_tokens=False,
    )
    expected_bytes = len(fallback_sample.encode("utf-8"))
    if len(fallback_ids) != expected_bytes:
        raise RuntimeError(
            "Strict byte fallback audit failed for qxjv: "
            f"{len(fallback_ids)} != {expected_bytes}"
        )

    special_ids = set(tokenizer.all_special_ids)
    universal_atomic = 0
    for surface in universal_surfaces:
        ids = tokenizer.encode(
            surface,
            add_special_tokens=False,
        )
        if len(ids) == 1 and ids[0] in special_ids:
            universal_atomic += 1

    report = {
        "version": 1,
        "inventory": str(inventory_path),
        "inventory_sha256": sha256_file(inventory_path),
        "vocab_size": len(tokenizer),
        "byte_rows": 256,
        "control_tokens": CONTROL_TOKENS,
        "universal_special_surfaces": len(universal_surfaces),
        "universal_specials_atomic": universal_atomic,
        "all_special_ids_count": len(tokenizer.all_special_ids),
        "context_length": args.context_length,
        "byte_id_map": byte_ids,
        "roundtrip_audits": audits,
        "fallback_audit": {
            "text": fallback_sample,
            "utf8_bytes": expected_bytes,
            "token_count": len(fallback_ids),
        },
        "warning": (
            "Do not decode with skip_special_tokens=True: universal lexical "
            "and emoji atoms are intentionally registered as special."
        ),
        "created_at": now_iso(),
    }
    atomic_json(output_dir / "byte_tokenizer_report.json", report)

    print(json.dumps(report, ensure_ascii=False, indent=2))
    return report


def load_tokenizer(path: Path):
    from transformers import AutoTokenizer

    tokenizer = AutoTokenizer.from_pretrained(
        path,
        use_fast=True,
    )
    tokenizer.model_max_length = 4096
    return tokenizer


def control_token_id_map(tokenizer: Any) -> dict[str, int]:
    result: dict[str, int] = {}
    for token in CONTROL_TOKENS:
        token_id = tokenizer.convert_tokens_to_ids(token)
        if token_id is None:
            continue
        token_id = int(token_id)
        if token_id < 0:
            continue
        result[token] = token_id
    return result


def blocked_generation_token_ids(tokenizer: Any) -> list[int]:
    """
    Reserved control tokens are structural, not normal text-generation targets.

    EOS remains allowed. Lexical/emoji atoms are deliberately *not* blocked,
    even though the tokenizer registers them as special tokens.
    """
    allowed = {"<eos>"}
    mapping = control_token_id_map(tokenizer)
    return sorted(
        {
            token_id
            for token, token_id in mapping.items()
            if token not in allowed
        }
    )


def audit_packed_dataset(args: argparse.Namespace) -> dict[str, Any]:
    try:
        import numpy as np
    except ImportError as error:
        raise RuntimeError("Packed auditing requires NumPy.") from error

    tokenizer = load_tokenizer(args.tokenizer.resolve())
    packed_dir = args.packed.resolve()
    mapping = control_token_id_map(tokenizer)

    report: dict[str, Any] = {
        "packed": str(packed_dir),
        "tokenizer": str(args.tokenizer.resolve()),
        "vocab_size": len(tokenizer),
        "control_ids": mapping,
        "splits": {},
    }

    for split in ("train", "validation"):
        path = packed_dir / f"{split}.bin"
        if not path.is_file():
            continue

        values = np.memmap(path, mode="r", dtype=np.uint16)
        counts = {
            token: int(np.count_nonzero(values == token_id))
            for token, token_id in mapping.items()
        }
        invalid = int(np.count_nonzero(values >= len(tokenizer)))
        report["splits"][split] = {
            "path": str(path),
            "tokens": int(values.size),
            "control_token_counts": counts,
            "invalid_token_ids": invalid,
        }

    dangerous = {}
    for split, details in report["splits"].items():
        hits = {
            token: count
            for token, count in details["control_token_counts"].items()
            if token in {"<pad>", "<bos>", "<unk>"} and count > 0
        }
        if hits:
            dangerous[split] = hits

    report["dangerous_reserved_tokens"] = dangerous
    report["healthy"] = not dangerous and all(
        details["invalid_token_ids"] == 0
        for details in report["splits"].values()
    )
    print(json.dumps(report, indent=2))
    return report


# ---------------------------------------------------------------------------
# Packing
# ---------------------------------------------------------------------------

def format_rewrite(record: RewriteRecord) -> str:
    instruction = record.instruction.strip()
    quoted_text = '"' + record.text + '"'
    quoted_output = '"' + record.output + '"'
    if instruction:
        return (
            instruction
            + "\n\n"
            + quoted_text
            + "\n\n"
            + quoted_output
        )
    return quoted_text + "\n\n" + quoted_output


def stable_validation_record(
    record: RewriteRecord,
    ratio: float,
) -> bool:
    threshold = int(ratio * (2**64))
    value = int(record.digest[:16], 16)
    return value < threshold


def pack_dataset(args: argparse.Namespace) -> dict[str, Any]:
    try:
        import numpy as np
    except ImportError as error:
        raise RuntimeError("Packing requires NumPy.") from error

    data_path = args.data.resolve()
    tokenizer_dir = args.tokenizer.resolve()
    output_dir = args.output.resolve()
    output_dir.mkdir(parents=True, exist_ok=True)

    tokenizer = load_tokenizer(tokenizer_dir)
    if len(tokenizer) >= 65536:
        raise RuntimeError(
            "Tokenizer is too large for uint16 packing."
        )

    fingerprint = {
        "data_sha256": sha256_file(data_path),
        "tokenizer_sha256": sha256_file(
            tokenizer_dir / "tokenizer.json"
        ),
        "context_length": args.context_length,
        "validation_ratio": args.validation_ratio,
        "format": 'instruction\\n\\n"text"\\n\\n"output"<eos>',
        "packing_version": 2,
    }

    manifest_path = output_dir / "packed_manifest.json"
    if manifest_path.is_file() and not args.force:
        existing = json.loads(
            manifest_path.read_text(encoding="utf-8")
        )
        if existing.get("fingerprint") == fingerprint:
            print("Packed cache is current:", output_dir)
            print(json.dumps(existing, indent=2))
            return existing

    temporary_dir = Path(
        tempfile.mkdtemp(
            prefix=output_dir.name + ".packing.",
            dir=output_dir.parent,
        )
    )
    train_path = temporary_dir / "train.bin"
    validation_path = temporary_dir / "validation.bin"

    train_handle = train_path.open("wb")
    validation_handle = validation_path.open("wb")

    buffers = {
        "train": [],
        "validation": [],
    }
    token_counts = Counter()
    record_counts = Counter()
    control_token_counts = {
        "train": Counter(),
        "validation": Counter(),
    }
    control_ids = control_token_id_map(tokenizer)
    forbidden_control_tokens = {"<pad>", "<bos>", "<unk>"}
    max_buffer = 1_000_000

    def flush(split: str, force: bool = False) -> None:
        buffer = buffers[split]
        if not buffer:
            return
        if len(buffer) < max_buffer and not force:
            return
        array = np.asarray(buffer, dtype=np.uint16)
        target = (
            train_handle if split == "train" else validation_handle
        )
        array.tofile(target)
        buffer.clear()

    eos_id = int(tokenizer.eos_token_id)

    for record in iter_jsonl(data_path):
        split = (
            "validation"
            if stable_validation_record(
                record,
                args.validation_ratio,
            )
            else "train"
        )
        text = format_rewrite(record)
        ids = tokenizer.encode(
            text,
            add_special_tokens=False,
        )

        id_counts = Counter(ids)
        forbidden_hits = {}
        for control_token, control_id in control_ids.items():
            occurrences = int(id_counts.get(control_id, 0))
            if occurrences:
                control_token_counts[split][control_token] += occurrences
                if control_token in forbidden_control_tokens:
                    forbidden_hits[control_token] = occurrences

        if forbidden_hits:
            raise RuntimeError(
                "Reserved control token text was found in rewrite.jsonl. "
                f"record_digest={record.digest}, hits={forbidden_hits}. "
                "Remove or escape literal <pad>, <bos>, and <unk> strings "
                "before packing; these tokens must never become training text."
            )

        ids.append(eos_id)
        buffers[split].extend(ids)
        token_counts[split] += len(ids)
        record_counts[split] += 1
        flush(split)

    for split in ("train", "validation"):
        flush(split, force=True)

    train_handle.flush()
    validation_handle.flush()
    os.fsync(train_handle.fileno())
    os.fsync(validation_handle.fileno())
    train_handle.close()
    validation_handle.close()

    if token_counts["train"] <= args.context_length:
        raise RuntimeError("Not enough training tokens for one block.")
    if token_counts["validation"] <= args.context_length:
        print(
            "WARNING: validation split contains fewer than one full block."
        )

    manifest = {
        "fingerprint": fingerprint,
        "data": str(data_path),
        "tokenizer": str(tokenizer_dir),
        "dtype": "uint16",
        "train_records": record_counts["train"],
        "validation_records": record_counts["validation"],
        "train_tokens": token_counts["train"],
        "validation_tokens": token_counts["validation"],
        "train_blocks": max(
            0,
            (token_counts["train"] - 1) // args.context_length,
        ),
        "validation_blocks": max(
            0,
            (token_counts["validation"] - 1)
            // args.context_length,
        ),
        "control_token_counts": {
            split: dict(counts)
            for split, counts in control_token_counts.items()
        },
        "created_at": now_iso(),
    }
    atomic_json(temporary_dir / "packed_manifest.json", manifest)

    for name in ("train.bin", "validation.bin", "packed_manifest.json"):
        os.replace(temporary_dir / name, output_dir / name)
    temporary_dir.rmdir()

    print(json.dumps(manifest, indent=2))
    return manifest


# ---------------------------------------------------------------------------
# Deep speed-first hybrid language model (~60M)
# ---------------------------------------------------------------------------


def import_training_stack():
    try:
        import numpy as np
        import torch
        import torch.nn as nn
        import torch.nn.functional as F
        from torch.utils.data import DataLoader, Dataset
    except ImportError as error:
        raise RuntimeError(
            "Training requires NumPy and a ROCm-enabled PyTorch build."
        ) from error

    configure_torch_runtime(torch)
    return np, torch, nn, F, DataLoader, Dataset


@dataclass
class Fast60MConfig:
    vocab_size: int
    padded_vocab_size: int
    hidden_size: int = 512
    embedding_size: int = 256
    ffn_latent_size: int = 256
    intermediate_size: int = 1792
    num_hidden_layers: int = 24
    num_attention_heads: int = 8
    num_key_value_heads: int = 2
    attention_every: int = 4
    window_size: int = 512
    conv_kernel_size: int = 4
    memory_size: int = 128
    memory_heads: int = 4
    attention_residual_group_size: int = 4
    mtp_loss_weight: float = 0.20
    max_position_embeddings: int = 4096
    rope_theta: float = 10_000.0
    rms_norm_eps: float = 1e-5
    initializer_range: float = 0.02
    pad_token_id: int = 0
    bos_token_id: int = 1
    eos_token_id: int = 2
    model_type: str = "byte-deep-hybrid"
    architecture: str = "FastDeepHybridLM"

    @property
    def head_dim(self) -> int:
        return self.hidden_size // self.num_attention_heads

    @property
    def kv_width(self) -> int:
        return self.num_key_value_heads * self.head_dim

    @property
    def attention_layer_count(self) -> int:
        return sum(
            1
            for index in range(self.num_hidden_layers)
            if (index + 1) % self.attention_every == 0
        )

    @property
    def convolution_layer_count(self) -> int:
        return self.num_hidden_layers - self.attention_layer_count

    def to_dict(self) -> dict[str, Any]:
        return dict(self.__dict__)

    @classmethod
    def from_dict(cls, value: Mapping[str, Any]) -> "Fast60MConfig":
        fields = cls.__dataclass_fields__
        return cls(**{key: value[key] for key in fields if key in value})


def round_to_multiple(value: float, multiple: int) -> int:
    return max(multiple, int(round(value / multiple)) * multiple)


def _fixed_parameter_count(config: Fast60MConfig) -> int:
    """Count every parameter except the expandable latent FFN matrices."""
    d_model = config.hidden_size
    d_embed = config.embedding_size
    d_latent = config.ffn_latent_size
    memory = config.memory_size
    kv_width = config.kv_width

    total = config.padded_vocab_size * d_embed
    total += 2 * d_model * d_embed
    if config.mtp_loss_weight > 0:
        total += d_model * d_embed
    total += d_model  # final RMSNorm

    for index in range(config.num_hidden_layers):
        has_attention = (index + 1) % config.attention_every == 0
        total += 1  # AttnRes-lite scalar gate.
        total += d_model  # mixer RMSNorm.
        total += d_model  # FFN RMSNorm.
        total += 2 * d_model * d_latent  # FFN latent down/up projections.

        if has_attention:
            total += 2 * d_model * d_model
            total += 2 * d_model * kv_width
            total += d_model  # summary-memory RMSNorm.
            total += 2 * d_model * memory + 4 * memory * memory
        else:
            total += 3 * d_model * d_model
            total += d_model * config.conv_kernel_size

    return total


def estimate_parameter_count(config: Fast60MConfig) -> int:
    expandable = (
        config.num_hidden_layers
        * 3
        * config.ffn_latent_size
        * config.intermediate_size
    )
    return _fixed_parameter_count(config) + expandable


def build_fast_config(
    tokenizer: Any,
    *,
    target_parameters: int = 60_000_000,
    hidden_size: int = 512,
    embedding_size: int = 256,
    ffn_latent_size: int = 256,
    num_hidden_layers: int = 24,
    num_attention_heads: int = 8,
    num_key_value_heads: int = 2,
    attention_every: int = 4,
    window_size: int = 512,
    conv_kernel_size: int = 4,
    memory_size: int = 128,
    memory_heads: int = 4,
    attention_residual_group_size: int = 4,
    mtp_loss_weight: float = 0.20,
    context_length: int = 4096,
) -> Fast60MConfig:
    if hidden_size % num_attention_heads != 0:
        raise ValueError("hidden_size must be divisible by num_attention_heads.")
    if num_attention_heads % num_key_value_heads != 0:
        raise ValueError(
            "num_attention_heads must be divisible by num_key_value_heads."
        )
    if context_length % window_size != 0:
        raise ValueError("context_length must be divisible by window_size.")
    if memory_size % memory_heads != 0:
        raise ValueError("memory_size must be divisible by memory_heads.")
    if attention_every <= 0:
        raise ValueError("attention_every must be positive.")
    if ffn_latent_size <= 0 or ffn_latent_size > hidden_size:
        raise ValueError("ffn_latent_size must be in (0, hidden_size].")
    if conv_kernel_size <= 0:
        raise ValueError("conv_kernel_size must be positive.")
    if attention_residual_group_size <= 0:
        raise ValueError("attention_residual_group_size must be positive.")

    vocab_size = len(tokenizer)
    padded_vocab_size = int(math.ceil(vocab_size / 64) * 64)
    provisional = Fast60MConfig(
        vocab_size=vocab_size,
        padded_vocab_size=padded_vocab_size,
        hidden_size=hidden_size,
        embedding_size=embedding_size,
        ffn_latent_size=ffn_latent_size,
        intermediate_size=64,
        num_hidden_layers=num_hidden_layers,
        num_attention_heads=num_attention_heads,
        num_key_value_heads=num_key_value_heads,
        attention_every=attention_every,
        window_size=window_size,
        conv_kernel_size=conv_kernel_size,
        memory_size=memory_size,
        memory_heads=memory_heads,
        attention_residual_group_size=attention_residual_group_size,
        mtp_loss_weight=mtp_loss_weight,
        max_position_embeddings=context_length,
        pad_token_id=int(tokenizer.pad_token_id),
        bos_token_id=int(tokenizer.bos_token_id),
        eos_token_id=int(tokenizer.eos_token_id),
    )

    fixed = _fixed_parameter_count(provisional)
    denominator = num_hidden_layers * 3 * ffn_latent_size
    raw_intermediate = (target_parameters - fixed) / max(1, denominator)
    intermediate_size = round_to_multiple(raw_intermediate, 64)
    intermediate_size = max(512, min(4096, intermediate_size))
    provisional.intermediate_size = intermediate_size
    return provisional


def create_model_classes(torch: Any, nn: Any, F: Any):
    class RMSNorm(nn.Module):
        def __init__(self, width: int, eps: float):
            super().__init__()
            self.weight = nn.Parameter(torch.ones(width))
            self.eps = eps

        def forward(self, hidden_states):
            # ROCm's fused RMSNorm requires input and weight to share a dtype.
            # The cast remains differentiable, so FP32 master weights still
            # receive gradients while BF16 activations use the fused kernel.
            weight = self.weight
            if weight.dtype != hidden_states.dtype:
                weight = weight.to(dtype=hidden_states.dtype)
            return F.rms_norm(
                hidden_states,
                (hidden_states.shape[-1],),
                weight,
                self.eps,
            )

    def rotate_half(value):
        even = value[..., 0::2]
        odd = value[..., 1::2]
        return torch.stack((-odd, even), dim=-1).flatten(-2)

    class GroupedQueryWindowAttention(nn.Module):
        """Windowed causal attention with cheap grouped K/V projections.

        The K/V heads are repeated only inside each local window. This keeps the
        stable PyTorch SDPA path on ROCm while reducing projection parameters and
        projection FLOPs relative to full multi-head QKV.
        """

        def __init__(self, config: Fast60MConfig, shifted: bool):
            super().__init__()
            self.hidden_size = config.hidden_size
            self.num_heads = config.num_attention_heads
            self.num_kv_heads = config.num_key_value_heads
            self.kv_repeat = self.num_heads // self.num_kv_heads
            self.head_dim = config.head_dim
            self.kv_width = config.kv_width
            self.window_size = config.window_size
            self.shift_size = config.window_size // 2 if shifted else 0

            self.q_proj = nn.Linear(
                config.hidden_size,
                config.hidden_size,
                bias=False,
            )
            self.k_proj = nn.Linear(
                config.hidden_size,
                self.kv_width,
                bias=False,
            )
            self.v_proj = nn.Linear(
                config.hidden_size,
                self.kv_width,
                bias=False,
            )
            self.out_proj = nn.Linear(
                config.hidden_size,
                config.hidden_size,
                bias=False,
            )

        def _attend_segment(self, query, key, value):
            batch, query_heads, length, head_dim = query.shape
            if length == 0:
                return query

            padding = (-length) % self.window_size
            if padding:
                query = F.pad(query, (0, 0, 0, padding))
                key = F.pad(key, (0, 0, 0, padding))
                value = F.pad(value, (0, 0, 0, padding))

            padded_length = query.shape[-2]
            windows = padded_length // self.window_size

            def partition(tensor, heads):
                return (
                    tensor.reshape(
                        batch,
                        heads,
                        windows,
                        self.window_size,
                        head_dim,
                    )
                    .permute(0, 2, 1, 3, 4)
                    .reshape(
                        batch * windows,
                        heads,
                        self.window_size,
                        head_dim,
                    )
                )

            query_windows = partition(query, query_heads)
            key_windows = partition(key, self.num_kv_heads)
            value_windows = partition(value, self.num_kv_heads)
            if self.kv_repeat > 1:
                key_windows = key_windows.repeat_interleave(
                    self.kv_repeat,
                    dim=1,
                )
                value_windows = value_windows.repeat_interleave(
                    self.kv_repeat,
                    dim=1,
                )

            output = F.scaled_dot_product_attention(
                query_windows,
                key_windows,
                value_windows,
                dropout_p=0.0,
                is_causal=True,
            )
            output = (
                output.reshape(
                    batch,
                    windows,
                    query_heads,
                    self.window_size,
                    head_dim,
                )
                .permute(0, 2, 1, 3, 4)
                .reshape(batch, query_heads, padded_length, head_dim)
            )
            return output[:, :, :length, :]

        def forward(self, hidden_states, cos, sin):
            batch, length, _ = hidden_states.shape
            query = self.q_proj(hidden_states).view(
                batch,
                length,
                self.num_heads,
                self.head_dim,
            ).transpose(1, 2)
            key = self.k_proj(hidden_states).view(
                batch,
                length,
                self.num_kv_heads,
                self.head_dim,
            ).transpose(1, 2)
            value = self.v_proj(hidden_states).view(
                batch,
                length,
                self.num_kv_heads,
                self.head_dim,
            ).transpose(1, 2)

            query = query * cos + rotate_half(query) * sin
            key = key * cos + rotate_half(key) * sin

            if self.shift_size and length > self.shift_size:
                prefix = self.shift_size
                first = self._attend_segment(
                    query[:, :, :prefix],
                    key[:, :, :prefix],
                    value[:, :, :prefix],
                )
                rest = self._attend_segment(
                    query[:, :, prefix:],
                    key[:, :, prefix:],
                    value[:, :, prefix:],
                )
                output = torch.cat((first, rest), dim=-2)
            else:
                output = self._attend_segment(query, key, value)

            output = output.transpose(1, 2).contiguous().view(
                batch,
                length,
                self.hidden_size,
            )
            return self.out_proj(output)

    class CausalShortConvMixer(nn.Module):
        """KDA-inspired short causal path for non-attention layers.

        This is deliberately not a literal Kimi Delta Attention port: exact KDA
        needs custom recurrent kernels to be fast. The short depthwise convolution
        keeps local high-frequency mixing at O(sequence) cost using stock ROCm ops.
        """

        def __init__(self, config: Fast60MConfig):
            super().__init__()
            self.hidden_size = config.hidden_size
            self.kernel_size = config.conv_kernel_size
            self.in_proj = nn.Linear(
                config.hidden_size,
                2 * config.hidden_size,
                bias=False,
            )
            self.depthwise_weight = nn.Parameter(
                torch.empty(config.hidden_size, 1, self.kernel_size)
            )
            self.out_proj = nn.Linear(
                config.hidden_size,
                config.hidden_size,
                bias=False,
            )
            nn.init.normal_(
                self.depthwise_weight,
                mean=0.0,
                std=config.initializer_range,
            )

        def forward(self, hidden_states):
            length = hidden_states.shape[1]
            value, gate = self.in_proj(hidden_states).chunk(2, dim=-1)
            value = F.conv1d(
                value.transpose(1, 2),
                self.depthwise_weight,
                padding=self.kernel_size - 1,
                groups=self.hidden_size,
            )[..., :length].transpose(1, 2)
            return self.out_proj(F.silu(value) * torch.sigmoid(gate))

    class SummaryMemoryMixer(nn.Module):
        """Cheap causal communication across completed local windows."""

        def __init__(self, config: Fast60MConfig):
            super().__init__()
            self.hidden_size = config.hidden_size
            self.memory_size = config.memory_size
            self.memory_heads = config.memory_heads
            self.memory_head_dim = (
                config.memory_size // config.memory_heads
            )
            self.window_size = config.window_size
            self.down = nn.Linear(
                config.hidden_size,
                config.memory_size,
                bias=False,
            )
            self.qkv = nn.Linear(
                config.memory_size,
                3 * config.memory_size,
                bias=False,
            )
            self.out = nn.Linear(
                config.memory_size,
                config.memory_size,
                bias=False,
            )
            self.up = nn.Linear(
                config.memory_size,
                config.hidden_size,
                bias=False,
            )

        def forward(self, hidden_states):
            batch, length, width = hidden_states.shape
            padding = (-length) % self.window_size
            padded = (
                F.pad(hidden_states, (0, 0, 0, padding))
                if padding
                else hidden_states
            )
            windows = padded.view(
                batch,
                padded.shape[1] // self.window_size,
                self.window_size,
                width,
            )
            summaries = windows[:, :, -1, :]
            if padding:
                summaries = torch.cat(
                    (summaries[:, :-1], hidden_states[:, -1:, :]),
                    dim=1,
                )

            summaries = self.down(summaries)
            query, key, value = self.qkv(summaries).chunk(3, dim=-1)
            window_count = summaries.shape[1]

            def split_heads(tensor):
                return tensor.view(
                    batch,
                    window_count,
                    self.memory_heads,
                    self.memory_head_dim,
                ).transpose(1, 2)

            query = split_heads(query)
            key = split_heads(key)
            value = split_heads(value)
            memory = F.scaled_dot_product_attention(
                query,
                key,
                value,
                dropout_p=0.0,
                is_causal=True,
            )
            memory = memory.transpose(1, 2).contiguous().view(
                batch,
                window_count,
                self.memory_size,
            )
            memory = self.up(self.out(memory))

            previous_memory = torch.cat(
                (torch.zeros_like(memory[:, :1]), memory[:, :-1]),
                dim=1,
            )
            broadcast = (
                previous_memory[:, :, None, :]
                .expand(-1, -1, self.window_size, -1)
                .reshape(batch, padded.shape[1], width)
            )
            return broadcast[:, :length]

    class LatentSwiGLU(nn.Module):
        """Stable-LatentMoE-inspired dense FFN bottleneck.

        All tokens use the same dense FFN, but its expensive expansion operates
        at ffn_latent_size instead of the full residual width. This is much more
        single-GPU friendly than sparse MoE while preserving the latent-compute idea.
        """

        def __init__(self, config: Fast60MConfig):
            super().__init__()
            self.down_in = nn.Linear(
                config.hidden_size,
                config.ffn_latent_size,
                bias=False,
            )
            self.gate_up = nn.Linear(
                config.ffn_latent_size,
                2 * config.intermediate_size,
                bias=False,
            )
            self.down = nn.Linear(
                config.intermediate_size,
                config.ffn_latent_size,
                bias=False,
            )
            self.up_out = nn.Linear(
                config.ffn_latent_size,
                config.hidden_size,
                bias=False,
            )

        def forward(self, hidden_states):
            latent = self.down_in(hidden_states)
            gate, up = self.gate_up(latent).chunk(2, dim=-1)
            latent = self.down(F.silu(gate) * up)
            return self.up_out(latent)

    class FastBlock(nn.Module):
        def __init__(self, config: Fast60MConfig, index: int):
            super().__init__()
            self.index = index
            self.has_attention = (
                (index + 1) % config.attention_every == 0
            )
            attention_rank = index // config.attention_every
            self.depth_residual_gate = nn.Parameter(torch.zeros(()))
            self.mixer_norm = RMSNorm(
                config.hidden_size,
                config.rms_norm_eps,
            )
            if self.has_attention:
                self.mixer = GroupedQueryWindowAttention(
                    config,
                    shifted=(attention_rank % 2 == 1),
                )
                self.memory_norm = RMSNorm(
                    config.hidden_size,
                    config.rms_norm_eps,
                )
                self.memory_mixer = SummaryMemoryMixer(config)
            else:
                self.mixer = CausalShortConvMixer(config)
                self.memory_norm = None
                self.memory_mixer = None
            self.ffn_norm = RMSNorm(
                config.hidden_size,
                config.rms_norm_eps,
            )
            self.feed_forward = LatentSwiGLU(config)

        def forward(self, hidden_states, cos, sin, depth_anchor):
            # AttnRes-lite: each layer can retrieve its group's earlier residual
            # stream through one learned scalar, initialized as an exact no-op.
            mixer_source = hidden_states + torch.tanh(
                self.depth_residual_gate
            ) * depth_anchor
            normalized = self.mixer_norm(mixer_source)
            if self.has_attention:
                hidden_states = hidden_states + self.mixer(
                    normalized,
                    cos,
                    sin,
                )
                hidden_states = hidden_states + self.memory_mixer(
                    self.memory_norm(hidden_states)
                )
            else:
                hidden_states = hidden_states + self.mixer(normalized)
            hidden_states = hidden_states + self.feed_forward(
                self.ffn_norm(hidden_states)
            )
            return hidden_states

    @dataclass
    class FastLMOutput:
        loss: Any | None = None
        logits: Any | None = None
        main_loss: Any | None = None
        mtp_loss: Any | None = None

    class FastDeepHybridLM(nn.Module):
        def __init__(self, config: Fast60MConfig):
            super().__init__()
            self.config = config
            self.token_embedding = nn.Embedding(
                config.padded_vocab_size,
                config.embedding_size,
            )
            self.embedding_projection = nn.Linear(
                config.embedding_size,
                config.hidden_size,
                bias=False,
            )
            self.blocks = nn.ModuleList(
                FastBlock(config, index)
                for index in range(config.num_hidden_layers)
            )
            self.final_norm = RMSNorm(
                config.hidden_size,
                config.rms_norm_eps,
            )
            self.output_projection = nn.Linear(
                config.hidden_size,
                config.embedding_size,
                bias=False,
            )
            self.mtp_projection = (
                nn.Linear(
                    config.hidden_size,
                    config.embedding_size,
                    bias=False,
                )
                if config.mtp_loss_weight > 0
                else None
            )

            inverse_frequency = 1.0 / (
                config.rope_theta
                ** (
                    torch.arange(0, config.head_dim, 2).float()
                    / config.head_dim
                )
            )
            positions = torch.arange(
                config.max_position_embeddings,
                dtype=torch.float32,
            )
            frequencies = torch.outer(positions, inverse_frequency)
            embedding = torch.repeat_interleave(frequencies, 2, dim=-1)
            self.register_buffer(
                "rope_cos",
                embedding.cos()[None, None, :, :],
                persistent=False,
            )
            self.register_buffer(
                "rope_sin",
                embedding.sin()[None, None, :, :],
                persistent=False,
            )
            self.apply(self._initialize_weights)
            residual_std = config.initializer_range / math.sqrt(
                2 * config.num_hidden_layers
            )
            for block in self.blocks:
                if block.has_attention:
                    nn.init.normal_(
                        block.mixer.out_proj.weight,
                        mean=0.0,
                        std=residual_std,
                    )
                    nn.init.normal_(
                        block.memory_mixer.up.weight,
                        mean=0.0,
                        std=residual_std,
                    )
                else:
                    nn.init.normal_(
                        block.mixer.out_proj.weight,
                        mean=0.0,
                        std=residual_std,
                    )
                nn.init.normal_(
                    block.feed_forward.up_out.weight,
                    mean=0.0,
                    std=residual_std,
                )

        def _initialize_weights(self, module):
            if isinstance(module, (nn.Linear, nn.Embedding)):
                nn.init.normal_(
                    module.weight,
                    mean=0.0,
                    std=self.config.initializer_range,
                )

        def get_input_embeddings(self):
            return self.token_embedding

        def _project_logits(self, hidden_states, projection=None):
            active_projection = (
                self.output_projection if projection is None else projection
            )
            vocabulary_states = active_projection(hidden_states)
            logits = F.linear(
                vocabulary_states,
                self.token_embedding.weight,
            )
            return logits[..., : self.config.vocab_size]

        def forward(
            self,
            input_ids,
            labels=None,
            return_last_logits: bool = False,
            use_mtp: bool = True,
        ):
            if input_ids.ndim != 2:
                raise ValueError("input_ids must have shape [batch, sequence].")
            sequence_length = input_ids.shape[1]
            if sequence_length > self.config.max_position_embeddings:
                raise ValueError(
                    f"Sequence length {sequence_length} exceeds "
                    f"{self.config.max_position_embeddings}."
                )

            hidden_states = self.embedding_projection(
                self.token_embedding(input_ids)
            )
            cos = self.rope_cos[:, :, :sequence_length].to(
                dtype=hidden_states.dtype
            )
            sin = self.rope_sin[:, :, :sequence_length].to(
                dtype=hidden_states.dtype
            )
            depth_anchor = hidden_states
            group_size = self.config.attention_residual_group_size
            for index, block in enumerate(self.blocks):
                if index % group_size == 0:
                    depth_anchor = hidden_states
                hidden_states = block(
                    hidden_states,
                    cos,
                    sin,
                    depth_anchor,
                )
            hidden_states = self.final_norm(hidden_states)

            if labels is not None:
                logits = self._project_logits(hidden_states[:, :-1])
                main_loss = F.cross_entropy(
                    logits.reshape(-1, self.config.vocab_size),
                    labels[:, 1:].reshape(-1),
                )
                mtp_loss = None
                loss = main_loss
                if (
                    use_mtp
                    and self.mtp_projection is not None
                    and sequence_length > 2
                ):
                    mtp_logits = self._project_logits(
                        hidden_states[:, :-2],
                        self.mtp_projection,
                    )
                    mtp_loss = F.cross_entropy(
                        mtp_logits.reshape(-1, self.config.vocab_size),
                        labels[:, 2:].reshape(-1),
                    )
                    loss = loss + self.config.mtp_loss_weight * mtp_loss
                return FastLMOutput(
                    loss=loss,
                    logits=None,
                    main_loss=main_loss,
                    mtp_loss=mtp_loss,
                )

            if return_last_logits:
                hidden_states = hidden_states[:, -1:, :]
            logits = self._project_logits(hidden_states)
            return FastLMOutput(loss=None, logits=logits)

    return FastDeepHybridLM, FastLMOutput


def count_parameters(model: Any) -> dict[str, int]:
    total = sum(parameter.numel() for parameter in model.parameters())
    trainable = sum(
        parameter.numel()
        for parameter in model.parameters()
        if parameter.requires_grad
    )
    embedding = model.get_input_embeddings().weight.numel()
    return {
        "total": total,
        "trainable": trainable,
        "embedding": embedding,
        "non_embedding": total - embedding,
    }


def save_model_bundle(
    model: Any,
    tokenizer: Any,
    output_dir: Path,
    torch: Any,
) -> None:
    output_dir.mkdir(parents=True, exist_ok=True)
    atomic_json(output_dir / "config.json", model.config.to_dict())
    torch.save(model.state_dict(), output_dir / "model.pt")
    tokenizer.save_pretrained(output_dir)


def load_model_bundle(path: Path, torch: Any, nn: Any, F: Any):
    config = Fast60MConfig.from_dict(
        json.loads((path / "config.json").read_text(encoding="utf-8"))
    )
    model_class, _ = create_model_classes(torch, nn, F)
    model = model_class(config)
    try:
        state = torch.load(
            path / "model.pt",
            map_location="cpu",
            weights_only=True,
        )
    except TypeError:
        state = torch.load(path / "model.pt", map_location="cpu")
    try:
        model.load_state_dict(state, strict=True)
    except RuntimeError as error:
        raise RuntimeError(
            "Checkpoint is not architecture-compatible with fast60m-hybrid. "
            "Start a new run or use a checkpoint created by this script."
        ) from error
    return model


def _config_from_args(tokenizer: Any, args: argparse.Namespace, context: int):
    return build_fast_config(
        tokenizer,
        target_parameters=args.target_parameters,
        hidden_size=args.hidden_size,
        embedding_size=args.embedding_size,
        ffn_latent_size=args.ffn_latent_size,
        num_hidden_layers=args.layers,
        num_attention_heads=args.heads,
        num_key_value_heads=args.kv_heads,
        attention_every=args.attention_every,
        window_size=args.window_size,
        conv_kernel_size=args.conv_kernel_size,
        memory_size=args.memory_size,
        memory_heads=args.memory_heads,
        attention_residual_group_size=args.attention_residual_group_size,
        mtp_loss_weight=args.mtp_loss_weight,
        context_length=context,
    )


def initialize_model(args: argparse.Namespace) -> dict[str, Any]:
    np, torch, nn, F, DataLoader, Dataset = import_training_stack()
    del np, DataLoader, Dataset

    tokenizer = load_tokenizer(args.tokenizer.resolve())
    config = _config_from_args(tokenizer, args, args.context_length)
    model_class, _ = create_model_classes(torch, nn, F)
    model = model_class(config)
    parameters = count_parameters(model)

    output_dir = args.output.resolve()
    save_model_bundle(model, tokenizer, output_dir, torch)

    full_attention_projection = 4 * config.hidden_size * config.hidden_size
    gqa_projection = (
        2 * config.hidden_size * config.hidden_size
        + 2 * config.hidden_size * config.kv_width
    )
    dense_ffn = 3 * config.hidden_size * config.intermediate_size
    latent_ffn = (
        2 * config.hidden_size * config.ffn_latent_size
        + 3 * config.ffn_latent_size * config.intermediate_size
    )
    report = {
        "parameters": parameters,
        "estimated_parameters": estimate_parameter_count(config),
        "parameters_millions": parameters["total"] / 1_000_000,
        "config": config.to_dict(),
        "speed_design": {
            "depth": config.num_hidden_layers,
            "attention_layers": config.attention_layer_count,
            "linear_conv_layers": config.convolution_layer_count,
            "attention_fraction": (
                config.attention_layer_count / config.num_hidden_layers
            ),
            "attention_window": config.window_size,
            "full_context": config.max_position_embeddings,
            "attention_pair_fraction_vs_full": (
                config.window_size / config.max_position_embeddings
            ),
            "gqa_projection_fraction_vs_mha": (
                gqa_projection / full_attention_projection
            ),
            "latent_ffn_parameter_fraction_vs_full": (
                latent_ffn / dense_ffn
            ),
            "factorized_embedding_head": True,
            "causal_summary_memory_on_attention_layers_only": True,
            "attention_residuals_lite": True,
            "multi_token_prediction": config.mtp_loss_weight > 0,
            "external_custom_kernels_required": False,
        },
        "created_at": now_iso(),
    }
    atomic_json(output_dir / "initialization_report.json", report)

    lower = int(args.target_parameters * 0.90)
    upper = int(args.target_parameters * 1.10)
    if not (lower <= parameters["total"] <= upper):
        raise RuntimeError(
            f"Model is outside the requested ~{args.target_parameters / 1e6:.0f}M "
            f"range: {parameters['total']:,}. Adjust width, depth, or target."
        )

    print(json.dumps(report, indent=2))
    return report


# ---------------------------------------------------------------------------
# Training helpers
# ---------------------------------------------------------------------------


def find_latest_checkpoint(output_dir: Path) -> Path | None:
    checkpoint_root = output_dir / "checkpoints"
    if not checkpoint_root.is_dir():
        return None
    candidates = sorted(
        (
            path
            for path in checkpoint_root.glob("step-*")
            if path.is_dir()
        ),
        key=lambda path: int(path.name.split("-")[-1]),
    )
    return candidates[-1] if candidates else None


def checkpoint_step(path: Path | None) -> int:
    if path is None:
        return 0
    return int(path.name.split("-")[-1])


def prune_checkpoints(root: Path, keep: int) -> None:
    candidates = sorted(
        (
            path
            for path in root.glob("step-*")
            if path.is_dir()
        ),
        key=lambda path: int(path.name.split("-")[-1]),
    )
    for path in candidates[:-keep]:
        shutil.rmtree(path)


def load_training_state(torch: Any, path: Path) -> dict[str, Any]:
    try:
        return torch.load(
            path,
            map_location="cpu",
            weights_only=False,
        )
    except TypeError:
        return torch.load(path, map_location="cpu")


def build_adamw(torch: Any, model: Any, args: argparse.Namespace):
    common = dict(
        params=model.parameters(),
        lr=args.learning_rate,
        betas=(args.beta1, args.beta2),
        eps=args.adam_epsilon,
        weight_decay=args.weight_decay,
    )
    if args.fused_optimizer:
        try:
            optimizer = torch.optim.AdamW(**common, fused=True)
            return optimizer, "fused"
        except (TypeError, RuntimeError) as error:
            print(
                "Fused AdamW unavailable; falling back to foreach AdamW:",
                error,
            )
    try:
        return torch.optim.AdamW(**common, foreach=True), "foreach"
    except (TypeError, RuntimeError):
        return torch.optim.AdamW(**common), "single-tensor"


def make_scheduler(
    torch: Any,
    optimizer: Any,
    *,
    warmup_steps: int,
    total_steps: int,
    minimum_ratio: float,
):
    def multiplier(step: int) -> float:
        if step < warmup_steps:
            return max(1e-8, float(step + 1) / max(1, warmup_steps))
        progress = (
            float(step - warmup_steps)
            / max(1, total_steps - warmup_steps)
        )
        progress = min(1.0, max(0.0, progress))
        cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
        return minimum_ratio + (1.0 - minimum_ratio) * cosine

    return torch.optim.lr_scheduler.LambdaLR(optimizer, multiplier)


def _atomic_replace_directory(
    temporary: Path,
    destination: Path,
) -> None:
    previous = destination.with_name(
        destination.name + f".previous-{os.getpid()}"
    )
    if previous.exists():
        shutil.rmtree(previous)

    if destination.exists():
        os.replace(destination, previous)

    try:
        os.replace(temporary, destination)
    except Exception:
        if previous.exists() and not destination.exists():
            os.replace(previous, destination)
        raise
    else:
        if previous.exists():
            shutil.rmtree(previous)


def save_named_training_checkpoint(
    *,
    model: Any,
    tokenizer: Any,
    optimizer: Any,
    scheduler: Any,
    torch: Any,
    destination: Path,
    state: dict[str, Any],
    metadata: Mapping[str, Any] | None = None,
) -> Path:
    destination.parent.mkdir(parents=True, exist_ok=True)
    temporary = destination.with_name(
        destination.name + f".tmp-{os.getpid()}"
    )
    if temporary.exists():
        shutil.rmtree(temporary)
    temporary.mkdir(parents=True)

    save_model_bundle(model, tokenizer, temporary, torch)
    torch.save(
        {
            "optimizer": optimizer.state_dict(),
            "scheduler": scheduler.state_dict(),
            "state": state,
            "torch_rng": torch.get_rng_state(),
            "cuda_rng": (
                torch.cuda.get_rng_state_all()
                if torch.cuda.is_available()
                else None
            ),
            "python_rng": random.getstate(),
        },
        temporary / "training_state.pt",
    )
    atomic_json(temporary / "training_state.json", state)
    if metadata is not None:
        atomic_json(
            temporary / "checkpoint_metadata.json",
            dict(metadata),
        )

    required = (
        temporary / "config.json",
        temporary / "model.pt",
        temporary / "training_state.pt",
    )
    missing = [str(path) for path in required if not path.is_file()]
    if missing:
        shutil.rmtree(temporary, ignore_errors=True)
        raise RuntimeError(
            f"Checkpoint write was incomplete; missing={missing}"
        )

    _atomic_replace_directory(temporary, destination)
    return destination


def save_checkpoint(
    *,
    model: Any,
    tokenizer: Any,
    optimizer: Any,
    scheduler: Any,
    torch: Any,
    output_dir: Path,
    state: dict[str, Any],
    keep: int,
) -> Path:
    checkpoint_root = output_dir / "checkpoints"
    destination = checkpoint_root / f"step-{state['global_step']:08d}"
    save_named_training_checkpoint(
        model=model,
        tokenizer=tokenizer,
        optimizer=optimizer,
        scheduler=scheduler,
        torch=torch,
        destination=destination,
        state=state,
        metadata={
            "kind": "regular",
            "global_step": state["global_step"],
            "saved_at": now_iso(),
        },
    )
    prune_checkpoints(checkpoint_root, keep)
    return destination


def restore_training_checkpoint_in_place(
    *,
    checkpoint: Path,
    model: Any,
    optimizer: Any,
    scheduler: Any,
    state: dict[str, Any],
    torch: Any,
    nn: Any,
    F: Any,
) -> None:
    restored_model = load_model_bundle(
        checkpoint,
        torch,
        nn,
        F,
    )
    model.load_state_dict(
        restored_model.state_dict(),
        strict=True,
    )
    del restored_model

    saved = load_training_state(
        torch,
        checkpoint / "training_state.pt",
    )
    optimizer.load_state_dict(saved["optimizer"])
    scheduler.load_state_dict(saved["scheduler"])
    state.clear()
    state.update(saved["state"])

    if saved.get("torch_rng") is not None:
        torch.set_rng_state(saved["torch_rng"])
    if (
        torch.cuda.is_available()
        and saved.get("cuda_rng") is not None
    ):
        torch.cuda.set_rng_state_all(saved["cuda_rng"])
    if saved.get("python_rng") is not None:
        random.setstate(saved["python_rng"])


def backoff_learning_rate(
    optimizer: Any,
    scheduler: Any,
    *,
    factor: float,
    minimum: float,
) -> list[float]:
    updated = []
    for group in optimizer.param_groups:
        new_lr = max(
            minimum,
            float(group["lr"]) * factor,
        )
        group["lr"] = new_lr
        group["initial_lr"] = min(
            float(group.get("initial_lr", new_lr)),
            new_lr,
        )
        updated.append(new_lr)

    if hasattr(scheduler, "base_lrs"):
        scheduler.base_lrs = [
            max(minimum, float(value) * factor)
            for value in scheduler.base_lrs
        ]
    if hasattr(scheduler, "_last_lr"):
        scheduler._last_lr = list(updated)

    return updated


def model_parameters_are_finite(
    torch: Any,
    model: Any,
) -> bool:
    with torch.no_grad():
        for parameter in model.parameters():
            if not bool(torch.isfinite(parameter).all().item()):
                return False
    return True


def evaluate_loss(
    *,
    model: Any,
    loader: Any,
    torch: Any,
    device: Any,
    dtype_name: str,
    max_batches: int,
) -> float | None:
    """
    Evaluate with mixed precision first. If a batch becomes non-finite, retry
    that batch in FP32 before declaring the checkpoint unhealthy.
    """
    model.eval()
    total = 0.0
    count = 0
    autocast_dtype = (
        torch.bfloat16 if dtype_name == "bf16" else torch.float16
    )
    autocast_enabled = dtype_name in {"bf16", "fp16"}

    try:
        with torch.no_grad():
            for batch_index, batch in enumerate(loader):
                if batch_index >= max_batches:
                    break

                input_ids = batch.to(
                    device,
                    non_blocking=True,
                )
                with torch.autocast(
                    device_type="cuda",
                    dtype=autocast_dtype,
                    enabled=autocast_enabled,
                ):
                    output = model(
                        input_ids=input_ids,
                        labels=input_ids,
                        use_mtp=False,
                    )
                loss = output.loss.detach()

                if not bool(torch.isfinite(loss).item()):
                    print(
                        "Validation loss was non-finite under autocast; "
                        f"retrying batch {batch_index} in FP32."
                    )
                    with torch.autocast(
                        device_type="cuda",
                        enabled=False,
                    ):
                        output = model(
                            input_ids=input_ids,
                            labels=input_ids,
                            use_mtp=False,
                        )
                    loss = output.loss.detach().float()

                if not bool(torch.isfinite(loss).item()):
                    return float("nan")

                total += float(loss.item())
                count += 1
    finally:
        if torch.cuda.is_available():
            torch.cuda.synchronize()
        model.train()

    if count == 0:
        return None
    return total / count



def train_model(args: argparse.Namespace) -> dict[str, Any]:
    np, torch, nn, F, DataLoader, Dataset = import_training_stack()

    if not torch.cuda.is_available():
        raise RuntimeError(
            "ROCm PyTorch did not expose the AMD GPU through torch.cuda."
        )

    device = torch.device("cuda")
    torch.manual_seed(args.seed)
    random.seed(args.seed)
    torch.cuda.manual_seed_all(args.seed)

    tokenizer = load_tokenizer(args.tokenizer.resolve())
    packed_dir = args.packed.resolve()
    manifest = json.loads(
        (packed_dir / "packed_manifest.json").read_text(encoding="utf-8")
    )
    context_length = int(manifest["fingerprint"]["context_length"])
    if context_length != 4096:
        raise RuntimeError(
            f"This project expects 4096-token blocks, got {context_length}."
        )

    class TokenBlocks(Dataset):
        def __init__(self, path: Path, context: int):
            self.tokens = np.memmap(path, mode="r", dtype=np.uint16)
            self.context = context
            self.blocks = max(0, (len(self.tokens) - 1) // context)

        def __len__(self):
            return self.blocks

        def __getitem__(self, index):
            start = index * self.context
            values = np.asarray(
                self.tokens[start : start + self.context],
                dtype=np.int64,
            ).copy()
            return torch.from_numpy(values)

    train_dataset = TokenBlocks(
        packed_dir / "train.bin",
        context_length,
    )
    validation_dataset = TokenBlocks(
        packed_dir / "validation.bin",
        context_length,
    )
    if len(train_dataset) == 0:
        raise RuntimeError("Packed training dataset has zero blocks.")

    output_dir = args.output.resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    checkpoint = (
        find_latest_checkpoint(output_dir)
        if args.resume == "auto"
        else (
            Path(args.resume).resolve()
            if args.resume != "none"
            else None
        )
    )

    if checkpoint is not None:
        print("Resuming checkpoint:", checkpoint)
        model = load_model_bundle(checkpoint, torch, nn, F)
        if model.config.vocab_size != len(tokenizer):
            raise RuntimeError(
                "Checkpoint tokenizer size does not match --tokenizer."
            )
    else:
        config = _config_from_args(tokenizer, args, context_length)
        model_class, _ = create_model_classes(torch, nn, F)
        model = model_class(config)

    model.to(device)
    model.train()
    parameters = count_parameters(model)
    print(
        f"Architecture: {model.config.architecture}; "
        f"parameters={parameters['total']:,} "
        f"({parameters['total'] / 1e6:.3f}M); "
        f"layers={model.config.num_hidden_layers}; "
        f"attention_layers={model.config.attention_layer_count}; "
        f"conv_layers={model.config.convolution_layer_count}; "
        f"window={model.config.window_size}; "
        f"ffn_latent={model.config.ffn_latent_size}"
    )

    optimizer, optimizer_backend = build_adamw(torch, model, args)

    updates_per_epoch = math.ceil(
        len(train_dataset)
        / max(1, args.batch_size * args.gradient_accumulation)
    )
    run_target_steps = (
        args.max_steps
        if args.max_steps > 0
        else max(1, args.epochs * updates_per_epoch)
    )
    schedule_steps = (
        args.lr_decay_steps
        if args.lr_decay_steps > 0
        else run_target_steps
    )
    schedule_steps = max(schedule_steps, run_target_steps)
    warmup_steps = (
        args.warmup_steps
        if args.warmup_steps >= 0
        else int(schedule_steps * args.warmup_ratio)
    )
    scheduler = make_scheduler(
        torch,
        optimizer,
        warmup_steps=warmup_steps,
        total_steps=schedule_steps,
        minimum_ratio=args.minimum_lr_ratio,
    )

    current_packed_fingerprint = manifest["fingerprint"]
    state = {
        "global_step": 0,
        "epoch": 0,
        "batch_in_epoch": 0,
        "tokens_seen": 0,
        "best_validation_loss": None,
        "best_checkpoint": None,
        "nonfinite_events": 0,
        "last_finite_step": 0,
        "packed_fingerprint": current_packed_fingerprint,
        "lr_decay_steps": schedule_steps,
        "warmup_steps": warmup_steps,
        "started_at": now_iso(),
    }

    if checkpoint is not None:
        saved = load_training_state(
            torch,
            checkpoint / "training_state.pt",
        )
        optimizer.load_state_dict(saved["optimizer"])
        scheduler.load_state_dict(saved["scheduler"])
        saved_state = dict(saved["state"])
        previous_fingerprint = saved_state.get("packed_fingerprint")
        state.update(saved_state)

        if previous_fingerprint != current_packed_fingerprint:
            print(
                "Packed dataset changed; resetting epoch/batch cursor while "
                "preserving model, optimizer, scheduler, and global step."
            )
            state["epoch"] = 0
            state["batch_in_epoch"] = 0
            state["best_validation_loss"] = None
            state["packed_fingerprint"] = current_packed_fingerprint

        state["lr_decay_steps"] = schedule_steps
        state["warmup_steps"] = warmup_steps
        torch.set_rng_state(saved["torch_rng"])
        if saved.get("cuda_rng") is not None:
            torch.cuda.set_rng_state_all(saved["cuda_rng"])
        random.setstate(saved["python_rng"])

    def loader_for_epoch(epoch: int):
        generator = torch.Generator()
        generator.manual_seed(args.seed + epoch)
        loader_kwargs = dict(
            dataset=train_dataset,
            batch_size=args.batch_size,
            shuffle=True,
            generator=generator,
            num_workers=args.num_workers,
            pin_memory=args.pin_memory,
            drop_last=True,
            persistent_workers=(
                args.num_workers > 0 and args.persistent_workers
            ),
        )
        if args.num_workers > 0:
            loader_kwargs["prefetch_factor"] = args.prefetch_factor
        return DataLoader(**loader_kwargs)

    validation_loader = DataLoader(
        validation_dataset,
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=0,
        pin_memory=args.pin_memory,
        drop_last=False,
    )

    best_dir = output_dir / "best"
    recovery_dir = output_dir / "recovery"

    # A recovery checkpoint always exists before the first optimizer update.
    save_named_training_checkpoint(
        model=model,
        tokenizer=tokenizer,
        optimizer=optimizer,
        scheduler=scheduler,
        torch=torch,
        destination=recovery_dir,
        state=state,
        metadata={
            "kind": "recovery",
            "global_step": state["global_step"],
            "saved_at": now_iso(),
        },
    )

    # Keep a persistent best candidate even before the first finite validation.
    if not (
        (best_dir / "config.json").is_file()
        and (best_dir / "model.pt").is_file()
    ):
        save_named_training_checkpoint(
            model=model,
            tokenizer=tokenizer,
            optimizer=optimizer,
            scheduler=scheduler,
            torch=torch,
            destination=best_dir,
            state=state,
            metadata={
                "kind": "best",
                "provisional": True,
                "validation_loss": state.get("best_validation_loss"),
                "global_step": state["global_step"],
                "saved_at": now_iso(),
            },
        )
        state["best_checkpoint"] = str(best_dir)

    if (
        args.eval_at_start
        and len(validation_dataset) > 0
    ):
        starting_validation_loss = evaluate_loss(
            model=model,
            loader=validation_loader,
            torch=torch,
            device=device,
            dtype_name=args.dtype,
            max_batches=args.eval_batches,
        )
        print(
            "starting validation "
            f"step={state['global_step']:,} "
            f"loss={starting_validation_loss}"
        )
        if (
            starting_validation_loss is not None
            and math.isfinite(starting_validation_loss)
            and (
                state["best_validation_loss"] is None
                or starting_validation_loss
                < state["best_validation_loss"]
            )
        ):
            state["best_validation_loss"] = starting_validation_loss
            state["best_checkpoint"] = str(best_dir)
            save_named_training_checkpoint(
                model=model,
                tokenizer=tokenizer,
                optimizer=optimizer,
                scheduler=scheduler,
                torch=torch,
                destination=best_dir,
                state=state,
                metadata={
                    "kind": "best",
                    "provisional": False,
                    "validation_loss": starting_validation_loss,
                    "global_step": state["global_step"],
                    "saved_at": now_iso(),
                },
            )

    training_model = model
    compile_status = "disabled"
    effective_compile_mode = args.compile_mode
    compile_uses_cudagraphs = False

    if args.compile:
        is_rocm = getattr(torch.version, "hip", None) is not None

        # reduce-overhead explicitly relies on CUDA Graphs. With gradient
        # accumulation, repeated compiled forward/backward calls can overwrite
        # graph-owned outputs before autograd has finished consuming them.
        if is_rocm and effective_compile_mode == "reduce-overhead":
            effective_compile_mode = "default"
            print(
                "ROCm safety: replacing compile mode 'reduce-overhead' "
                "with 'default' to avoid CUDAGraph output reuse."
            )

        compile_options = None
        if is_rocm:
            compile_options = {"triton.cudagraphs": False}

        compile_kwargs = {
            "mode": effective_compile_mode,
            "fullgraph": args.compile_fullgraph,
            "dynamic": False,
        }
        if compile_options is not None:
            compile_kwargs["options"] = compile_options

        try:
            training_model = torch.compile(
                model,
                **compile_kwargs,
            )
            compile_status = (
                f"enabled:{effective_compile_mode}:cudagraphs-disabled"
                if is_rocm
                else f"enabled:{effective_compile_mode}"
            )
            print(
                "torch.compile enabled:",
                effective_compile_mode,
                "(CUDAGraphs disabled on ROCm)"
                if is_rocm
                else "",
            )
        except (TypeError, RuntimeError) as option_error:
            # Older builds may reject the explicit option. Retry with the
            # default mode, which does not request reduce-overhead graphs.
            if compile_options is not None:
                try:
                    training_model = torch.compile(
                        model,
                        mode="default",
                        fullgraph=args.compile_fullgraph,
                        dynamic=False,
                    )
                    effective_compile_mode = "default"
                    compile_status = (
                        "enabled:default:option-fallback"
                    )
                    print(
                        "torch.compile option fallback enabled in default "
                        "mode after:",
                        option_error,
                    )
                except Exception as error:
                    compile_status = (
                        f"setup-failed:{type(error).__name__}"
                    )
                    training_model = model
                    print(
                        "torch.compile setup failed; using eager mode:",
                        error,
                    )
            else:
                compile_status = (
                    f"setup-failed:{type(option_error).__name__}"
                )
                training_model = model
                print(
                    "torch.compile setup failed; using eager mode:",
                    option_error,
                )
        except Exception as error:
            compile_status = f"setup-failed:{type(error).__name__}"
            training_model = model
            print("torch.compile setup failed; using eager mode:", error)

    autocast_dtype = (
        torch.bfloat16 if args.dtype == "bf16" else torch.float16
    )
    autocast_enabled = args.dtype in {"bf16", "fp16"}
    scaler = None
    if args.dtype == "fp16":
        scaler = torch.amp.GradScaler("cuda")

    optimizer.zero_grad(set_to_none=True)
    accumulation = 0
    running_loss = torch.zeros((), device=device)
    running_microbatches = 0
    nonfinite_loss_seen = torch.zeros(
        (),
        device=device,
        dtype=torch.bool,
    )
    last_log_time = time.perf_counter()
    last_log_tokens = state["tokens_seen"]
    stop = False

    def recover_from_nonfinite(
        reason: str,
        batch_index: int,
    ) -> None:
        nonlocal training_model
        nonlocal compile_status
        nonlocal accumulation
        nonlocal running_microbatches
        nonlocal nonfinite_loss_seen

        event_count = int(state.get("nonfinite_events", 0)) + 1
        print(
            f"NON-FINITE TRAINING EVENT #{event_count}: {reason}"
        )

        optimizer.zero_grad(set_to_none=True)
        accumulation = 0
        running_loss.zero_()
        running_microbatches = 0
        nonfinite_loss_seen.zero_()

        if scaler is not None:
            current_scale = float(scaler.get_scale())
            with contextlib.suppress(Exception):
                scaler.update(max(1.0, current_scale * args.nan_lr_factor))

        if args.nan_action == "stop":
            raise FloatingPointError(
                f"Stopping after non-finite training state: {reason}"
            )

        if args.nan_action == "rollback":
            restore_training_checkpoint_in_place(
                checkpoint=recovery_dir,
                model=model,
                optimizer=optimizer,
                scheduler=scheduler,
                state=state,
                torch=torch,
                nn=nn,
                F=F,
            )
            training_model = model
            if compile_status.startswith("enabled"):
                compile_status = "disabled-after-nonfinite"
            print(
                "Rolled back to recovery checkpoint:",
                recovery_dir,
            )

        state["nonfinite_events"] = event_count
        state["last_nonfinite_reason"] = reason
        state["batch_in_epoch"] = batch_index + 1

        new_lrs = backoff_learning_rate(
            optimizer,
            scheduler,
            factor=args.nan_lr_factor,
            minimum=args.min_learning_rate,
        )
        print("Learning-rate fallback:", new_lrs)

        save_named_training_checkpoint(
            model=model,
            tokenizer=tokenizer,
            optimizer=optimizer,
            scheduler=scheduler,
            torch=torch,
            destination=recovery_dir,
            state=state,
            metadata={
                "kind": "recovery",
                "reason": reason,
                "nonfinite_events": event_count,
                "global_step": state["global_step"],
                "saved_at": now_iso(),
            },
        )
        clear_memory(torch)

        if event_count > args.max_nan_recoveries:
            raise FloatingPointError(
                "Exceeded --max-nan-recoveries="
                f"{args.max_nan_recoveries}."
            )

    while not stop:
        epoch = int(state["epoch"])
        if args.max_steps <= 0 and epoch >= args.epochs:
            break

        loader = loader_for_epoch(epoch)
        resume_batch = int(state["batch_in_epoch"])

        for batch_index, batch in enumerate(loader):
            if batch_index < resume_batch:
                continue

            input_ids = batch.to(device, non_blocking=True)

            def forward_backward(active_model):
                # This marker is harmless when CUDAGraphs are disabled, and
                # protects compatible compiled modes that still use graph
                # iteration tracking internally.
                if active_model is not model:
                    marker = getattr(
                        getattr(torch, "compiler", None),
                        "cudagraph_mark_step_begin",
                        None,
                    )
                    if marker is not None:
                        marker()

                with torch.autocast(
                    device_type="cuda",
                    dtype=autocast_dtype,
                    enabled=autocast_enabled,
                ):
                    output = active_model(
                        input_ids=input_ids,
                        labels=input_ids,
                    )
                    scaled_loss = output.loss / args.gradient_accumulation
                if scaler is None:
                    scaled_loss.backward()
                else:
                    scaler.scale(scaled_loss).backward()
                return output.loss.detach()

            try:
                detached_loss = forward_backward(training_model)
            except Exception as error:
                if training_model is not model:
                    print(
                        "torch.compile failed during training; discarding "
                        "the current accumulation window and continuing in "
                        "eager mode:",
                        f"{type(error).__name__}: {error}",
                    )
                    optimizer.zero_grad(set_to_none=True)
                    accumulation = 0
                    running_loss.zero_()
                    running_microbatches = 0
                    nonfinite_loss_seen.zero_()
                    training_model = model
                    compile_status = (
                        f"runtime-failed:{type(error).__name__}:eager-fallback"
                    )
                    with contextlib.suppress(Exception):
                        torch._dynamo.reset()
                    clear_memory(torch)
                    detached_loss = forward_backward(model)
                else:
                    raise

            nonfinite_loss_seen.logical_or_(
                ~torch.isfinite(detached_loss)
            )
            accumulation += 1
            running_loss += torch.nan_to_num(
                detached_loss,
                nan=0.0,
                posinf=0.0,
                neginf=0.0,
            )
            running_microbatches += 1
            state["tokens_seen"] += int(input_ids.numel())
            state["batch_in_epoch"] = batch_index + 1

            if accumulation < args.gradient_accumulation:
                continue

            if scaler is not None:
                scaler.unscale_(optimizer)

            grad_norm = torch.nn.utils.clip_grad_norm_(
                model.parameters(),
                (
                    args.max_grad_norm
                    if args.max_grad_norm > 0
                    else float("inf")
                ),
                error_if_nonfinite=False,
            )
            loss_was_nonfinite = bool(
                nonfinite_loss_seen.item()
            )
            grad_norm_value = float(
                grad_norm.detach().float().item()
            )

            if (
                loss_was_nonfinite
                or not math.isfinite(grad_norm_value)
            ):
                recover_from_nonfinite(
                    (
                        "non-finite loss"
                        if loss_was_nonfinite
                        else f"non-finite grad norm={grad_norm_value}"
                    ),
                    batch_index,
                )
                continue

            if scaler is None:
                optimizer.step()
            else:
                scaler.step(optimizer)
                scaler.update()
            scheduler.step()
            optimizer.zero_grad(set_to_none=True)
            accumulation = 0
            nonfinite_loss_seen.zero_()

            prospective_step = int(state["global_step"]) + 1
            if (
                args.finite_check_every > 0
                and prospective_step % args.finite_check_every == 0
                and not model_parameters_are_finite(torch, model)
            ):
                recover_from_nonfinite(
                    "non-finite model parameters after optimizer.step()",
                    batch_index,
                )
                continue

            state["global_step"] = prospective_step
            state["last_finite_step"] = prospective_step
            step = prospective_step
            if step % args.log_every == 0:
                torch.cuda.synchronize()
                now = time.perf_counter()
                elapsed = max(1e-9, now - last_log_time)
                delta_tokens = state["tokens_seen"] - last_log_tokens
                tokens_per_second = delta_tokens / elapsed
                mean_loss = float(
                    (running_loss / max(1, running_microbatches)).item()
                )
                memory = torch.cuda.max_memory_allocated() / (1024**3)
                print(
                    f"step={step:,} "
                    f"loss={mean_loss:.5f} "
                    f"lr={scheduler.get_last_lr()[0]:.3e} "
                    f"tok/s={tokens_per_second:,.0f} "
                    f"tokens={state['tokens_seen']:,} "
                    f"peak_gib={memory:.2f}"
                )
                running_loss.zero_()
                running_microbatches = 0
                last_log_time = now
                last_log_tokens = state["tokens_seen"]
                torch.cuda.reset_peak_memory_stats()

            if (
                args.eval_every > 0
                and step % args.eval_every == 0
                and len(validation_dataset) > 0
            ):
                validation_loss = evaluate_loss(
                    model=model,
                    loader=validation_loader,
                    torch=torch,
                    device=device,
                    dtype_name=args.dtype,
                    max_batches=args.eval_batches,
                )
                print(
                    f"validation step={step:,} loss={validation_loss}"
                )
                if (
                    validation_loss is not None
                    and not math.isfinite(validation_loss)
                ):
                    recover_from_nonfinite(
                        "validation remained non-finite after FP32 retry",
                        batch_index,
                    )
                    continue

                if (
                    validation_loss is not None
                    and math.isfinite(validation_loss)
                    and (
                        state["best_validation_loss"] is None
                        or validation_loss
                        < state["best_validation_loss"]
                    )
                ):
                    state["best_validation_loss"] = validation_loss
                    state["best_checkpoint"] = str(best_dir)
                    save_named_training_checkpoint(
                        model=model,
                        tokenizer=tokenizer,
                        optimizer=optimizer,
                        scheduler=scheduler,
                        torch=torch,
                        destination=best_dir,
                        state=state,
                        metadata={
                            "kind": "best",
                            "provisional": False,
                            "validation_loss": validation_loss,
                            "global_step": step,
                            "saved_at": now_iso(),
                        },
                    )
                    print(
                        "New best checkpoint:",
                        best_dir,
                        f"validation_loss={validation_loss}",
                    )

            if args.save_every > 0 and step % args.save_every == 0:
                destination = save_checkpoint(
                    model=model,
                    tokenizer=tokenizer,
                    optimizer=optimizer,
                    scheduler=scheduler,
                    torch=torch,
                    output_dir=output_dir,
                    state=state,
                    keep=args.keep_checkpoints,
                )
                print("Saved:", destination)
                save_named_training_checkpoint(
                    model=model,
                    tokenizer=tokenizer,
                    optimizer=optimizer,
                    scheduler=scheduler,
                    torch=torch,
                    destination=recovery_dir,
                    state=state,
                    metadata={
                        "kind": "recovery",
                        "source_checkpoint": str(destination),
                        "global_step": step,
                        "saved_at": now_iso(),
                    },
                )

            if args.max_steps > 0 and step >= args.max_steps:
                stop = True
                break

        if stop:
            break
        state["epoch"] = epoch + 1
        state["batch_in_epoch"] = 0

    final_checkpoint = save_checkpoint(
        model=model,
        tokenizer=tokenizer,
        optimizer=optimizer,
        scheduler=scheduler,
        torch=torch,
        output_dir=output_dir,
        state=state,
        keep=args.keep_checkpoints,
    )
    save_named_training_checkpoint(
        model=model,
        tokenizer=tokenizer,
        optimizer=optimizer,
        scheduler=scheduler,
        torch=torch,
        destination=recovery_dir,
        state=state,
        metadata={
            "kind": "recovery",
            "source_checkpoint": str(final_checkpoint),
            "global_step": state["global_step"],
            "saved_at": now_iso(),
        },
    )

    final_dir = output_dir / "final"
    if final_dir.exists():
        shutil.rmtree(final_dir)
    save_model_bundle(model, tokenizer, final_dir, torch)

    result = {
        "state": state,
        "parameters": parameters,
        "architecture": model.config.to_dict(),
        "optimizer_backend": optimizer_backend,
        "compile_status": compile_status,
        "final_checkpoint": str(final_checkpoint),
        "final_model": str(final_dir),
        "packed_manifest": manifest,
        "schedule": {
            "run_target_steps": run_target_steps,
            "lr_decay_steps": schedule_steps,
            "warmup_steps": warmup_steps,
            "minimum_lr_ratio": args.minimum_lr_ratio,
        },
        "completed_at": now_iso(),
    }
    atomic_json(output_dir / "training_result.json", result)
    print(json.dumps(result, indent=2))
    return result


# ---------------------------------------------------------------------------
# Generation, benchmarking, and diagnostics
# ---------------------------------------------------------------------------


def doctor(args: argparse.Namespace) -> dict[str, Any]:
    report: dict[str, Any] = {
        "python": sys.version,
        "script_version": SCRIPT_VERSION,
        "environment": {
            "PYTORCH_ALLOC_CONF": os.environ.get("PYTORCH_ALLOC_CONF"),
            "TOKENIZERS_PARALLELISM": os.environ.get(
                "TOKENIZERS_PARALLELISM"
            ),
            "USE_ROCM_CK_GEMM": os.environ.get("USE_ROCM_CK_GEMM"),
        },
    }
    try:
        np, torch, nn, F, DataLoader, Dataset = import_training_stack()
        del np, DataLoader, Dataset
        report["torch"] = {
            "version": torch.__version__,
            "hip": getattr(torch.version, "hip", None),
            "cuda_available": torch.cuda.is_available(),
            "device_count": torch.cuda.device_count(),
            "device_name": (
                torch.cuda.get_device_name(0)
                if torch.cuda.is_available()
                else None
            ),
            "bf16_supported": (
                torch.cuda.is_bf16_supported()
                if torch.cuda.is_available()
                else False
            ),
            "compile_available": hasattr(torch, "compile"),
        }
        if torch.cuda.is_available():
            query = torch.randn(
                1,
                8,
                128,
                64,
                device="cuda",
                dtype=torch.bfloat16,
            )
            with torch.no_grad():
                output = F.scaled_dot_product_attention(
                    query,
                    query,
                    query,
                    is_causal=True,
                )
            torch.cuda.synchronize()
            report["sdpa_probe"] = {
                "ok": True,
                "shape": list(output.shape),
            }
            del query, output
            clear_memory(torch)
    except Exception as error:
        report["error"] = f"{type(error).__name__}: {error}"

    print(json.dumps(report, indent=2))
    return report


def inspect_project(args: argparse.Namespace) -> dict[str, Any]:
    tokenizer = load_tokenizer(args.tokenizer.resolve())
    report = {
        "tokenizer_vocab_size": len(tokenizer),
        "special_ids": len(tokenizer.all_special_ids),
        "model_max_length": tokenizer.model_max_length,
        "default_architecture": DEFAULT_ARCHITECTURE,
    }
    model_path = args.model.resolve() if args.model else None
    if model_path and (model_path / "config.json").is_file():
        report["saved_model_config"] = json.loads(
            (model_path / "config.json").read_text(encoding="utf-8")
        )
    print(json.dumps(report, indent=2))
    return report


def benchmark_model(args: argparse.Namespace) -> dict[str, Any]:
    np, torch, nn, F, DataLoader, Dataset = import_training_stack()
    del np, DataLoader, Dataset
    if not torch.cuda.is_available():
        raise RuntimeError("ROCm GPU is unavailable.")

    device = torch.device("cuda")
    if args.model:
        model = load_model_bundle(args.model.resolve(), torch, nn, F)
    else:
        tokenizer = load_tokenizer(args.tokenizer.resolve())
        config = _config_from_args(tokenizer, args, args.context_length)
        model_class, _ = create_model_classes(torch, nn, F)
        model = model_class(config)

    model.to(device).train()
    active_model = model
    compile_status = "disabled"
    if args.compile:
        active_model = torch.compile(
            model,
            mode=args.compile_mode,
            fullgraph=args.compile_fullgraph,
            dynamic=False,
        )
        compile_status = f"enabled:{args.compile_mode}"

    input_ids = torch.randint(
        0,
        model.config.vocab_size,
        (args.batch_size, args.context_length),
        device=device,
    )
    optimizer, optimizer_backend = build_adamw(torch, model, args)
    autocast_dtype = (
        torch.bfloat16 if args.dtype == "bf16" else torch.float16
    )
    autocast_enabled = args.dtype in {"bf16", "fp16"}

    def iteration():
        optimizer.zero_grad(set_to_none=True)
        with torch.autocast(
            device_type="cuda",
            dtype=autocast_dtype,
            enabled=autocast_enabled,
        ):
            output = active_model(input_ids=input_ids, labels=input_ids)
        output.loss.backward()
        optimizer.step()
        return output.loss

    for _ in range(args.warmup):
        iteration()
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    started = time.perf_counter()
    last_loss = None
    for _ in range(args.steps):
        last_loss = iteration()
    torch.cuda.synchronize()
    elapsed = time.perf_counter() - started
    tokens = args.steps * args.batch_size * args.context_length

    result = {
        "tokens_per_second": tokens / elapsed,
        "seconds": elapsed,
        "steps": args.steps,
        "batch_size": args.batch_size,
        "context_length": args.context_length,
        "loss": (
            float(last_loss.detach().item())
            if last_loss is not None
            else None
        ),
        "peak_gib": torch.cuda.max_memory_allocated() / (1024**3),
        "parameters": count_parameters(model),
        "config": model.config.to_dict(),
        "compile_status": compile_status,
        "optimizer_backend": optimizer_backend,
    }
    print(json.dumps(result, indent=2))
    return result


def generate_text(args: argparse.Namespace) -> str:
    np, torch, nn, F, DataLoader, Dataset = import_training_stack()
    del np, DataLoader, Dataset
    if not torch.cuda.is_available():
        raise RuntimeError("ROCm GPU is unavailable.")

    model_path = args.model.resolve()
    tokenizer = load_tokenizer(model_path)
    model = load_model_bundle(model_path, torch, nn, F).to("cuda")
    model.eval()

    encoded = tokenizer(
        args.prompt,
        add_special_tokens=False,
        return_tensors="pt",
        return_token_type_ids=False,
    )
    input_ids = encoded.input_ids.to("cuda")
    prompt_length = int(input_ids.shape[1])

    blocked_ids = (
        []
        if args.allow_control_tokens
        else blocked_generation_token_ids(tokenizer)
    )
    blocked_tensor = (
        torch.tensor(
            blocked_ids,
            device="cuda",
            dtype=torch.long,
        )
        if blocked_ids
        else None
    )

    generated: list[int] = []
    with torch.no_grad():
        for generation_step in range(args.max_new_tokens):
            model_input = input_ids[
                :, -model.config.max_position_embeddings :
            ]

            with torch.autocast(
                device_type="cuda",
                dtype=torch.bfloat16,
                enabled=True,
            ):
                logits = model(
                    input_ids=model_input,
                    return_last_logits=True,
                ).logits[:, -1, :]

            if not bool(torch.isfinite(logits).all().item()):
                print(
                    "Non-finite generation logits under BF16; "
                    "retrying this token in FP32.",
                    file=sys.stderr,
                )
                with torch.autocast(
                    device_type="cuda",
                    enabled=False,
                ):
                    logits = model(
                        input_ids=model_input,
                        return_last_logits=True,
                    ).logits[:, -1, :].float()

            if not bool(torch.isfinite(logits).all().item()):
                logits = torch.nan_to_num(
                    logits,
                    nan=-float("inf"),
                    posinf=1e4,
                    neginf=-1e4,
                )

            if args.show_top_tokens > 0:
                top_values, top_indices = torch.topk(
                    logits,
                    min(args.show_top_tokens, logits.shape[-1]),
                    dim=-1,
                )
                decoded = [
                    {
                        "id": int(token_id),
                        "token": tokenizer.decode(
                            [int(token_id)],
                            skip_special_tokens=False,
                            clean_up_tokenization_spaces=False,
                        ),
                        "logit": float(value),
                    }
                    for token_id, value in zip(
                        top_indices[0].tolist(),
                        top_values[0].float().tolist(),
                    )
                ]
                print(
                    f"raw top tokens at generation step {generation_step}: "
                    + json.dumps(decoded, ensure_ascii=False),
                    file=sys.stderr,
                )

            # Structural control IDs must not compete with real text.
            # EOS remains available and ends generation normally.
            if blocked_tensor is not None:
                logits.index_fill_(
                    1,
                    blocked_tensor,
                    -float("inf"),
                )

            if args.repetition_penalty != 1.0:
                used = torch.unique(model_input)
                selected = logits[:, used]
                logits[:, used] = torch.where(
                    selected < 0,
                    selected * args.repetition_penalty,
                    selected / args.repetition_penalty,
                )

            if not bool(torch.isfinite(logits).any().item()):
                next_token = torch.tensor(
                    [[int(tokenizer.eos_token_id)]],
                    device="cuda",
                    dtype=torch.long,
                )
            elif args.temperature <= 0:
                next_token = logits.argmax(dim=-1, keepdim=True)
            else:
                logits = logits / max(args.temperature, 1e-5)
                if args.top_k > 0:
                    threshold = torch.topk(
                        logits,
                        min(args.top_k, logits.shape[-1]),
                        dim=-1,
                    ).values[:, -1:]
                    logits = logits.masked_fill(
                        logits < threshold,
                        -float("inf"),
                    )
                probabilities = torch.softmax(logits, dim=-1)
                if args.top_p < 1.0:
                    sorted_probabilities, sorted_indices = torch.sort(
                        probabilities,
                        descending=True,
                        dim=-1,
                    )
                    cumulative = sorted_probabilities.cumsum(dim=-1)
                    remove = cumulative > args.top_p
                    remove[:, 1:] = remove[:, :-1].clone()
                    remove[:, 0] = False
                    sorted_probabilities = (
                        sorted_probabilities.masked_fill(remove, 0.0)
                    )
                    denominator = sorted_probabilities.sum(
                        dim=-1,
                        keepdim=True,
                    ).clamp_min(1e-12)
                    sorted_probabilities /= denominator
                    sampled = torch.multinomial(
                        sorted_probabilities,
                        1,
                    )
                    next_token = sorted_indices.gather(-1, sampled)
                else:
                    next_token = torch.multinomial(probabilities, 1)

            token_id = int(next_token.item())
            if token_id in blocked_ids:
                raise RuntimeError(
                    "A blocked structural control token escaped masking: "
                    f"id={token_id}, token={tokenizer.decode([token_id], skip_special_tokens=False)!r}"
                )

            generated.append(token_id)
            input_ids = torch.cat((input_ids, next_token), dim=-1)
            if token_id == int(tokenizer.eos_token_id):
                break

    completion = tokenizer.decode(
        generated,
        skip_special_tokens=False,
        clean_up_tokenization_spaces=False,
    )
    print(completion)
    return completion


# ---------------------------------------------------------------------------
# Combined quick cycle
# ---------------------------------------------------------------------------


def cycle(args: argparse.Namespace) -> None:
    sync_namespace = argparse.Namespace(
        data=args.data,
        inbox=args.inbox,
        archive=args.archive,
        work_dir=args.work_dir / "sync",
        seed=args.seed,
        recursive=args.recursive,
        skip_invalid_files=False,
        backup=args.backup,
        audit=args.work_dir / "last_sync.json",
    )
    sync_dataset(sync_namespace)

    pack_namespace = argparse.Namespace(
        data=args.data,
        tokenizer=args.tokenizer,
        output=args.packed,
        context_length=4096,
        validation_ratio=args.validation_ratio,
        force=False,
    )
    pack_dataset(pack_namespace)

    latest = find_latest_checkpoint(args.output.resolve())
    current_step = checkpoint_step(latest)
    target_step = current_step + args.additional_steps

    train_namespace = argparse.Namespace(
        tokenizer=args.tokenizer,
        packed=args.packed,
        output=args.output,
        resume="auto",
        seed=args.seed,
        dtype="bf16",
        batch_size=args.batch_size,
        gradient_accumulation=args.gradient_accumulation,
        learning_rate=args.learning_rate,
        beta1=0.9,
        beta2=0.95,
        adam_epsilon=1e-8,
        weight_decay=0.1,
        max_grad_norm=1.0,
        max_steps=target_step,
        epochs=1,
        warmup_steps=-1,
        warmup_ratio=0.02,
        minimum_lr_ratio=0.1,
        lr_decay_steps=args.lr_decay_steps,
        log_every=args.log_every,
        eval_every=args.eval_every,
        eval_batches=args.eval_batches,
        save_every=args.save_every,
        keep_checkpoints=args.keep_checkpoints,
        num_workers=args.num_workers,
        pin_memory=True,
        persistent_workers=args.num_workers > 0,
        prefetch_factor=2,
        compile=args.compile,
        compile_mode=args.compile_mode,
        compile_fullgraph=args.compile_fullgraph,
        fused_optimizer=True,
        target_parameters=args.target_parameters,
        hidden_size=args.hidden_size,
        embedding_size=args.embedding_size,
        ffn_latent_size=args.ffn_latent_size,
        layers=args.layers,
        heads=args.heads,
        kv_heads=args.kv_heads,
        attention_every=args.attention_every,
        window_size=args.window_size,
        conv_kernel_size=args.conv_kernel_size,
        memory_size=args.memory_size,
        memory_heads=args.memory_heads,
        attention_residual_group_size=args.attention_residual_group_size,
        mtp_loss_weight=args.mtp_loss_weight,
        eval_at_start=True,
        nan_action="rollback",
        nan_lr_factor=0.5,
        min_learning_rate=1e-7,
        max_nan_recoveries=20,
        finite_check_every=100,
    )
    train_model(train_namespace)


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def add_architecture_arguments(parser: argparse.ArgumentParser) -> None:
    parser.add_argument(
        "--target-parameters",
        type=int,
        default=60_000_000,
    )
    parser.add_argument("--hidden-size", type=int, default=512)
    parser.add_argument("--embedding-size", type=int, default=256)
    parser.add_argument("--ffn-latent-size", type=int, default=256)
    parser.add_argument("--layers", type=int, default=24)
    parser.add_argument("--heads", type=int, default=8)
    parser.add_argument("--kv-heads", type=int, default=2)
    parser.add_argument("--attention-every", type=int, default=4)
    parser.add_argument("--window-size", type=int, default=512)
    parser.add_argument("--conv-kernel-size", type=int, default=4)
    parser.add_argument("--memory-size", type=int, default=128)
    parser.add_argument("--memory-heads", type=int, default=4)
    parser.add_argument(
        "--attention-residual-group-size",
        type=int,
        default=4,
    )
    parser.add_argument("--mtp-loss-weight", type=float, default=0.20)


def add_compile_arguments(parser: argparse.ArgumentParser) -> None:
    parser.add_argument(
        "--compile",
        action=argparse.BooleanOptionalAction,
        default=True,
    )
    parser.add_argument(
        "--compile-mode",
        choices=[
            "default",
            "reduce-overhead",
            "max-autotune",
            "max-autotune-no-cudagraphs",
        ],
        default="default",
    )
    parser.add_argument(
        "--compile-fullgraph",
        action=argparse.BooleanOptionalAction,
        default=False,
    )


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description=(
            "Train a deeper speed-first ~60M hybrid byte language model."
        ),
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    subcommands = parser.add_subparsers(dest="command", required=True)

    tokenizer_parser = subcommands.add_parser(
        "tokenizer",
        help="Build the byte + universal-special tokenizer.",
    )
    tokenizer_parser.add_argument(
        "--inventory",
        type=Path,
        default=DEFAULT_INVENTORY,
    )
    tokenizer_parser.add_argument(
        "--output",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    tokenizer_parser.add_argument(
        "--context-length",
        type=int,
        default=4096,
    )
    tokenizer_parser.set_defaults(function=build_tokenizer)

    sync_parser = subcommands.add_parser(
        "sync-data",
        help=(
            "Append, exact-dedupe, deterministically shuffle, and archive "
            "new batches from a directory."
        ),
    )
    sync_parser.add_argument("--data", type=Path, default=Path("rewrite.jsonl"))
    sync_parser.add_argument("--inbox", type=Path, required=True)
    sync_parser.add_argument("--archive", type=Path)
    sync_parser.add_argument(
        "--work-dir",
        type=Path,
        default=Path(".bytefalcon-work/sync"),
    )
    sync_parser.add_argument("--seed", type=int, default=42)
    sync_parser.add_argument("--recursive", action="store_true")
    sync_parser.add_argument("--skip-invalid-files", action="store_true")
    sync_parser.add_argument("--backup", action="store_true")
    sync_parser.add_argument("--audit", type=Path)
    sync_parser.set_defaults(function=sync_dataset)

    pack_parser = subcommands.add_parser(
        "pack",
        help="Pack rewrite.jsonl into train/validation uint16 streams.",
    )
    pack_parser.add_argument("--data", type=Path, default=Path("rewrite.jsonl"))
    pack_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    pack_parser.add_argument(
        "--output",
        type=Path,
        default=Path("artifacts/packed-4096"),
    )
    pack_parser.add_argument("--context-length", type=int, default=4096)
    pack_parser.add_argument("--validation-ratio", type=float, default=0.005)
    pack_parser.add_argument("--force", action="store_true")
    pack_parser.set_defaults(function=pack_dataset)

    audit_parser = subcommands.add_parser(
        "audit-packed",
        help="Count reserved control IDs inside packed train/validation streams.",
    )
    audit_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    audit_parser.add_argument(
        "--packed",
        type=Path,
        default=Path("artifacts/packed-4096"),
    )
    audit_parser.set_defaults(function=audit_packed_dataset)

    init_parser = subcommands.add_parser(
        "init",
        help="Initialize and save the deeper ~60M speed-first model.",
    )
    init_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    init_parser.add_argument(
        "--output",
        type=Path,
        default=Path("runs/bytefast-60m/initial"),
    )
    init_parser.add_argument("--context-length", type=int, default=4096)
    add_architecture_arguments(init_parser)
    init_parser.set_defaults(function=initialize_model)

    train_parser = subcommands.add_parser(
        "train",
        help="Train from scratch or resume a checkpoint.",
    )
    train_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    train_parser.add_argument(
        "--packed",
        type=Path,
        default=Path("artifacts/packed-4096"),
    )
    train_parser.add_argument(
        "--output",
        type=Path,
        default=Path("runs/bytefast-60m"),
    )
    train_parser.add_argument(
        "--resume",
        default="auto",
        help="'auto', 'none', or a checkpoint path.",
    )
    train_parser.add_argument("--seed", type=int, default=42)
    train_parser.add_argument(
        "--dtype",
        choices=["bf16", "fp16", "fp32"],
        default="bf16",
    )
    train_parser.add_argument("--batch-size", type=int, default=4)
    train_parser.add_argument(
        "--gradient-accumulation",
        type=int,
        default=4,
    )
    train_parser.add_argument("--learning-rate", type=float, default=2e-5)
    train_parser.add_argument("--beta1", type=float, default=0.9)
    train_parser.add_argument("--beta2", type=float, default=0.95)
    train_parser.add_argument("--adam-epsilon", type=float, default=1e-8)
    train_parser.add_argument("--weight-decay", type=float, default=0.1)
    train_parser.add_argument("--max-grad-norm", type=float, default=1.0)
    train_parser.add_argument("--max-steps", type=int, default=0)
    train_parser.add_argument("--epochs", type=int, default=1)
    train_parser.add_argument("--warmup-steps", type=int, default=-1)
    train_parser.add_argument("--warmup-ratio", type=float, default=0.02)
    train_parser.add_argument("--minimum-lr-ratio", type=float, default=0.1)
    train_parser.add_argument("--lr-decay-steps", type=int, default=100000)
    train_parser.add_argument("--log-every", type=int, default=100)
    train_parser.add_argument("--eval-every", type=int, default=500)
    train_parser.add_argument("--eval-batches", type=int, default=8)
    train_parser.add_argument("--save-every", type=int, default=1000)
    train_parser.add_argument("--keep-checkpoints", type=int, default=5)
    train_parser.add_argument(
        "--eval-at-start",
        action=argparse.BooleanOptionalAction,
        default=True,
        help="Evaluate and materialize best/ before the first optimizer update.",
    )
    train_parser.add_argument(
        "--nan-action",
        choices=["rollback", "skip", "stop"],
        default="rollback",
    )
    train_parser.add_argument("--nan-lr-factor", type=float, default=0.5)
    train_parser.add_argument("--min-learning-rate", type=float, default=1e-7)
    train_parser.add_argument("--max-nan-recoveries", type=int, default=20)
    train_parser.add_argument(
        "--finite-check-every",
        type=int,
        default=100,
        help="Scan all model parameters for NaN/Inf every N optimizer steps.",
    )
    train_parser.add_argument("--num-workers", type=int, default=2)
    train_parser.add_argument(
        "--pin-memory",
        action=argparse.BooleanOptionalAction,
        default=True,
    )
    train_parser.add_argument(
        "--persistent-workers",
        action=argparse.BooleanOptionalAction,
        default=True,
    )
    train_parser.add_argument("--prefetch-factor", type=int, default=2)
    train_parser.add_argument(
        "--fused-optimizer",
        action=argparse.BooleanOptionalAction,
        default=True,
    )
    add_compile_arguments(train_parser)
    add_architecture_arguments(train_parser)
    train_parser.set_defaults(function=train_model)

    cycle_parser = subcommands.add_parser(
        "cycle",
        help="Sync, repack if changed, and resume fast training.",
    )
    cycle_parser.add_argument("--data", type=Path, default=Path("rewrite.jsonl"))
    cycle_parser.add_argument("--inbox", type=Path, required=True)
    cycle_parser.add_argument("--archive", type=Path)
    cycle_parser.add_argument(
        "--work-dir",
        type=Path,
        default=Path(".bytefalcon-work"),
    )
    cycle_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    cycle_parser.add_argument(
        "--packed",
        type=Path,
        default=Path("artifacts/packed-4096"),
    )
    cycle_parser.add_argument(
        "--output",
        type=Path,
        default=Path("runs/bytefast-60m"),
    )
    cycle_parser.add_argument("--additional-steps", type=int, default=500)
    cycle_parser.add_argument("--seed", type=int, default=42)
    cycle_parser.add_argument("--recursive", action="store_true")
    cycle_parser.add_argument("--backup", action="store_true")
    cycle_parser.add_argument("--validation-ratio", type=float, default=0.005)
    cycle_parser.add_argument("--batch-size", type=int, default=4)
    cycle_parser.add_argument("--gradient-accumulation", type=int, default=4)
    cycle_parser.add_argument("--learning-rate", type=float, default=2e-5)
    cycle_parser.add_argument("--lr-decay-steps", type=int, default=100000)
    cycle_parser.add_argument("--log-every", type=int, default=100)
    cycle_parser.add_argument("--eval-every", type=int, default=500)
    cycle_parser.add_argument("--eval-batches", type=int, default=8)
    cycle_parser.add_argument("--save-every", type=int, default=500)
    cycle_parser.add_argument("--keep-checkpoints", type=int, default=5)
    cycle_parser.add_argument("--num-workers", type=int, default=4)
    add_compile_arguments(cycle_parser)
    add_architecture_arguments(cycle_parser)
    cycle_parser.set_defaults(function=cycle)

    doctor_parser = subcommands.add_parser(
        "doctor",
        help="Audit ROCm, bf16, torch.compile, and SDPA.",
    )
    doctor_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    doctor_parser.set_defaults(function=doctor)

    inspect_parser = subcommands.add_parser(
        "inspect",
        help="Show tokenizer and architecture details.",
    )
    inspect_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    inspect_parser.add_argument("--model", type=Path)
    inspect_parser.set_defaults(function=inspect_project)

    benchmark_parser = subcommands.add_parser(
        "benchmark",
        help="Measure steady-state training throughput on the GPU.",
    )
    benchmark_parser.add_argument("--model", type=Path)
    benchmark_parser.add_argument(
        "--tokenizer",
        type=Path,
        default=Path("artifacts/byte-tokenizer"),
    )
    benchmark_parser.add_argument("--context-length", type=int, default=4096)
    benchmark_parser.add_argument("--batch-size", type=int, default=2)
    benchmark_parser.add_argument("--warmup", type=int, default=3)
    benchmark_parser.add_argument("--steps", type=int, default=100)
    benchmark_parser.add_argument(
        "--dtype",
        choices=["bf16", "fp16", "fp32"],
        default="bf16",
    )
    benchmark_parser.add_argument("--learning-rate", type=float, default=2e-5)
    benchmark_parser.add_argument("--beta1", type=float, default=0.9)
    benchmark_parser.add_argument("--beta2", type=float, default=0.95)
    benchmark_parser.add_argument("--adam-epsilon", type=float, default=1e-8)
    benchmark_parser.add_argument("--weight-decay", type=float, default=0.1)
    benchmark_parser.add_argument(
        "--fused-optimizer",
        action=argparse.BooleanOptionalAction,
        default=True,
    )
    add_compile_arguments(benchmark_parser)
    add_architecture_arguments(benchmark_parser)
    benchmark_parser.set_defaults(function=benchmark_model)

    generate_parser = subcommands.add_parser(
        "generate",
        help="Generate from a trained checkpoint.",
    )
    generate_parser.add_argument("--model", type=Path, required=True)
    generate_parser.add_argument("--prompt", required=True)
    generate_parser.add_argument("--max-new-tokens", type=int, default=128)
    generate_parser.add_argument("--temperature", type=float, default=0.7)
    generate_parser.add_argument("--top-p", type=float, default=0.95)
    generate_parser.add_argument("--top-k", type=int, default=50)
    generate_parser.add_argument("--repetition-penalty", type=float, default=1.1)
    generate_parser.add_argument(
        "--allow-control-tokens",
        action="store_true",
        help="Allow structural IDs such as <pad>; disabled by default.",
    )
    generate_parser.add_argument(
        "--show-top-tokens",
        type=int,
        default=0,
        help="Print the raw top-N logits before reserved-token masking.",
    )
    generate_parser.set_defaults(function=generate_text)

    return parser


def validate_args(args: argparse.Namespace) -> None:
    if hasattr(args, "context_length") and args.context_length != 4096:
        raise ValueError("This project is fixed to context length 4096.")
    if hasattr(args, "validation_ratio") and not (
        0.0 <= args.validation_ratio < 0.5
    ):
        raise ValueError("--validation-ratio must be in [0, 0.5).")
    if hasattr(args, "batch_size") and args.batch_size <= 0:
        raise ValueError("--batch-size must be positive.")
    if (
        hasattr(args, "gradient_accumulation")
        and args.gradient_accumulation <= 0
    ):
        raise ValueError("--gradient-accumulation must be positive.")
    if hasattr(args, "lr_decay_steps") and args.lr_decay_steps <= 0:
        raise ValueError("--lr-decay-steps must be positive.")
    if hasattr(args, "window_size") and 4096 % args.window_size != 0:
        raise ValueError("--window-size must divide 4096 exactly.")
    if (
        hasattr(args, "hidden_size")
        and hasattr(args, "heads")
        and args.hidden_size % args.heads != 0
    ):
        raise ValueError("--hidden-size must be divisible by --heads.")
    if (
        hasattr(args, "memory_size")
        and hasattr(args, "memory_heads")
        and args.memory_size % args.memory_heads != 0
    ):
        raise ValueError(
            "--memory-size must be divisible by --memory-heads."
        )
    if (
        hasattr(args, "heads")
        and hasattr(args, "kv_heads")
        and args.heads % args.kv_heads != 0
    ):
        raise ValueError("--heads must be divisible by --kv-heads.")
    if hasattr(args, "attention_every") and args.attention_every <= 0:
        raise ValueError("--attention-every must be positive.")
    if hasattr(args, "ffn_latent_size") and (
        args.ffn_latent_size <= 0
        or args.ffn_latent_size > args.hidden_size
    ):
        raise ValueError(
            "--ffn-latent-size must be positive and no larger than hidden size."
        )
    if hasattr(args, "mtp_loss_weight") and args.mtp_loss_weight < 0:
        raise ValueError("--mtp-loss-weight must be non-negative.")
    if hasattr(args, "nan_lr_factor") and not (
        0.0 < args.nan_lr_factor < 1.0
    ):
        raise ValueError("--nan-lr-factor must be in (0, 1).")
    if hasattr(args, "min_learning_rate") and args.min_learning_rate <= 0:
        raise ValueError("--min-learning-rate must be positive.")
    if hasattr(args, "max_nan_recoveries") and args.max_nan_recoveries < 0:
        raise ValueError("--max-nan-recoveries must be non-negative.")
    if hasattr(args, "finite_check_every") and args.finite_check_every < 0:
        raise ValueError("--finite-check-every must be non-negative.")


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()
    validate_args(args)
    args.function(args)
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        print("\nInterrupted.", file=sys.stderr)
        raise SystemExit(130)