File size: 83,870 Bytes
d517dc9 | 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 | use ahash::{AHashSet, RandomState};
use anyhow::{anyhow, bail, Context, Result};
use clap::{Parser, ValueEnum};
use hashbrown::HashMap as HbHashMap;
use rocksdb::{DBCompressionType, DB, IteratorMode, Options, WriteBatch, WriteOptions};
use sonic_rs::{JsonContainerTrait, JsonValueTrait, Value};
use std::collections::HashMap;
use std::{
cmp::Reverse,
collections::{BinaryHeap, HashSet},
fs::{self, File},
io::{BufRead, BufReader, BufWriter, Read, Write},
mem,
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
mpsc::{sync_channel, Receiver, SyncSender},
Arc,
},
thread::{self, JoinHandle},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokenizers::{
models::{
bpe::{BPE, BpeConfig},
unigram::Unigram,
wordpiece::WordPieceConfig,
},
pipeline::EncodeOptions,
vocab::bucket_added_vocabulary::AddedToken,
};
use tk_train::{BpeTrainer, Trainer, UnigramTrainer, WordPieceTrainer};
use walkdir::WalkDir;
use xxhash_rust::xxh3::xxh3_64;
const SPECIAL: &[&str] = &[
"<|pad|>",
"<|system|>",
"<|user|>",
"<|assistant|>",
"<|tool|>",
"<|think|>",
"<|tool_call|>",
"<|end|>",
];
const UNK: &str = "<|unk|>";
const DB_COUNT_BYTES: usize = 8;
static STATS_MESSAGES: AtomicU64 = AtomicU64::new(0);
static STATS_CHARS: AtomicU64 = AtomicU64::new(0);
type FastMap<K, V> = HbHashMap<K, V, RandomState>;
type TopHeap = BinaryHeap<Reverse<(u64, Reverse<String>)>>;
type TailHeap = BinaryHeap<(u64, String, u64)>;
type StatsSender = SyncSender<std::result::Result<FastMap<String, u64>, String>>;
fn fast_map<K, V>() -> FastMap<K, V> {
FastMap::with_hasher(RandomState::new())
}
#[derive(Clone, Copy, Debug, ValueEnum)]
enum Algorithm {
Bpe,
Unigram,
Wordpiece,
}
#[derive(Parser, Debug, Clone)]
#[command(
version,
about = "Rust tokenizer-training stage for STS JSONL corpora",
rename_all = "verbatim"
)]
struct Args {
/// Input folder or a single .jsonl/.jsonl.zst/.tar/.tar.zst file.
#[arg(long, default_value = "./traces")]
data_dir: PathBuf,
/// Output directory; tokenizer.json and pretokenization artifacts are written here.
#[arg(long, default_value = "./out")]
out_dir: PathBuf,
#[arg(long, value_enum, default_value_t = Algorithm::Bpe)]
tokenizer: Algorithm,
#[arg(long, default_value_t = 16_000)]
vocab_size: usize,
/// Maximum nested tar archive depth.
#[arg(long, default_value_t = 3)]
max_archive_depth: usize,
#[arg(long)]
tok_max_messages: Option<u64>,
#[arg(long)]
tok_max_chars: Option<usize>,
#[arg(long)]
no_reasoning: bool,
#[arg(long, default_value_t = 16)]
unigram_max_piece_length: usize,
#[arg(long, default_value_t = 4096)]
unigram_max_unique_words: usize,
#[arg(long, default_value_t = 500_000)]
unigram_train_words: usize,
/// Statistics-map RAM budget in MiB. Default: 8192 MiB. The old name remains accepted.
#[arg(
long = "stats_memory_mb",
aliases = ["stats-memory-mb", "unigram_memory_total_mb", "unigram-memory-total-mb"],
default_value_t = 8192
)]
stats_memory_mb: usize,
/// Overrides --stats_memory_mb. This is a spill threshold, not a preallocation request.
#[arg(long, alias = "stats-memory-gb")]
stats_memory_gb: Option<usize>,
#[arg(long, default_value_t = 32_768)]
unigram_stats_batch: usize,
#[arg(long, default_value_t = 64)]
unigram_max_word_chars: usize,
#[arg(long, default_value_t = 50_000)]
bpe_max_unique_words: usize,
#[arg(long, default_value_t = 1_000_000)]
bpe_train_words: usize,
#[arg(long, default_value_t = 128)]
bpe_max_word_chars: usize,
#[arg(long, default_value_t = 64)]
bpe_max_token_length: usize,
#[arg(long, default_value_t = 2)]
bpe_min_frequency: u64,
#[arg(long, default_value_t = 10_000)]
wordpiece_max_unique_words: usize,
#[arg(long, default_value_t = 200_000)]
wordpiece_train_words: usize,
#[arg(long, default_value_t = 64)]
wordpiece_max_word_chars: usize,
#[arg(long, default_value_t = 8)]
tok_batch_mb: usize,
#[arg(long, default_value_t = 64)]
tok_queue_mb: usize,
#[arg(long, default_value_t = 8)]
input_chunk_mb: usize,
#[arg(long, default_value_t = 100)]
zstd_read_mb: usize,
#[arg(long, default_value_t = 64)]
max_json_line_mb: usize,
#[arg(long)]
tok_stats_dir: Option<PathBuf>,
#[arg(long, default_value_t = 0)]
rayon_threads: usize,
/// Concurrent source workers. 0 selects an automatic count.
#[arg(long, alias = "workers", default_value_t = 0)]
tok_workers: usize,
/// Upper bound on concurrent source readers. 0 selects an automatic count.
#[arg(long, default_value_t = 0)]
input_workers: usize,
#[arg(long, default_value_t = 512)]
tok_batch_size: usize,
/// Number of concurrent RocksDB writer threads. 0 selects an automatic count.
#[arg(long, default_value_t = 0)]
db_writer_threads: usize,
/// Number of queued maps per RocksDB writer.
#[arg(long, default_value_t = 4)]
db_writer_queue: usize,
/// Maximum merge operations per RocksDB WriteBatch.
#[arg(long, default_value_t = 16_384)]
db_write_batch_size: usize,
/// Size of each RocksDB memtable in MiB.
#[arg(long, default_value_t = 512)]
db_write_buffer_mb: usize,
/// Number of RocksDB memtables per database.
#[arg(long, default_value_t = 4)]
db_max_write_buffers: usize,
/// Resolve long merge chains after this many successive merge operands per key.
#[arg(long, default_value_t = 64)]
db_max_successive_merges: usize,
/// RocksDB background jobs. 0 selects an automatic count.
#[arg(long, default_value_t = 0)]
db_background_jobs: usize,
/// Compress RocksDB SST files with Zstandard. Off by default for ingestion speed.
#[arg(long)]
db_zstd: bool,
/// Save the bounded ByteLevel word-frequency sample and stop before training.
#[arg(long, alias = "pretokenize-only")]
pretokenize_only: bool,
/// Accepted for CLI compatibility: this program always stops after tokenizer creation.
#[arg(long, alias = "tokenize-only", alias = "tokenize-from-existing")]
tokenize_only: bool,
/// Tokenize the corpus with the trained/loaded tokenizer and write token ids to disk.
#[arg(long)]
tokenize: bool,
/// Maximum tokens per output shard. 0 writes a single tokens.bin.
#[arg(long, default_value_t = 0)]
shard_tokens: usize,
}
#[derive(Clone)]
struct WorkerConfig {
include_reasoning: bool,
max_line_bytes: usize,
input_buffer_bytes: usize,
zstd_buffer_bytes: usize,
raw_batch_messages: usize,
max_word_chars: usize,
overlap_chars: usize,
batch_occurrences: usize,
batch_bytes: usize,
}
#[derive(Clone, Copy)]
struct LimitBudget {
remaining_messages: Option<u64>,
remaining_chars: Option<usize>,
}
impl LimitBudget {
fn from_args(args: &Args) -> Self {
Self {
remaining_messages: args.tok_max_messages,
remaining_chars: args.tok_max_chars,
}
}
fn exhausted(&self) -> bool {
self.remaining_messages == Some(0) || self.remaining_chars == Some(0)
}
fn consume(&mut self, chars: usize) {
if let Some(messages) = &mut self.remaining_messages {
*messages = messages.saturating_sub(1);
}
if let Some(remaining) = &mut self.remaining_chars {
*remaining = remaining.saturating_sub(chars);
}
}
}
fn lower_name(path: &Path) -> String {
path.to_string_lossy().to_ascii_lowercase()
}
fn is_archive(path: &Path) -> bool {
is_archive_name(&lower_name(path))
}
fn is_archive_name(name: &str) -> bool {
name.ends_with(".tar") || name.ends_with(".tar.zst") || name.ends_with(".tar.zstd")
}
fn is_jsonl_name(name: &str) -> bool {
name.ends_with(".jsonl") || name.ends_with(".jsonl.zst")
}
fn is_jsonl(path: &Path) -> bool {
is_jsonl_name(&lower_name(path))
}
fn collect_inputs(input: &Path) -> Result<Vec<PathBuf>> {
if !input.exists() {
bail!("Input does not exist: {}", input.display());
}
let mut files = Vec::new();
if input.is_file() {
if !(is_jsonl(input) || is_archive(input)) {
bail!(
"Expected .jsonl, .jsonl.zst, .tar, .tar.zst, or .tar.zstd: {}",
input.display()
);
}
files.push(input.to_path_buf());
} else {
for entry in WalkDir::new(input).follow_links(false) {
let entry = entry?;
if entry.file_type().is_file() && (is_jsonl(entry.path()) || is_archive(entry.path())) {
files.push(entry.path().to_path_buf());
}
}
}
files.sort();
files.dedup();
if files.is_empty() {
bail!(
"No .jsonl, .jsonl.zst, or tar archive inputs found under {}",
input.display()
);
}
Ok(files)
}
fn open_reader(path: &Path, capacity: usize) -> Result<Box<dyn BufRead + Send>> {
let file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
if lower_name(path).ends_with(".zst") {
let decoder = zstd::stream::read::Decoder::new(file)
.with_context(|| format!("creating Zstandard decoder for {}", path.display()))?;
Ok(Box::new(BufReader::with_capacity(capacity, decoder)))
} else {
Ok(Box::new(BufReader::with_capacity(capacity, file)))
}
}
fn canonical_json(value: &Value) -> String {
if let Some(object) = value.as_object() {
// serde_json's default Map is key-sorted. Sonic-RS preserves source order,
// so sort recursively to keep the existing rendered-corpus format stable.
let mut entries = std::collections::BTreeMap::<&str, &Value>::new();
for (key, child) in object.iter() {
entries.insert(key, child);
}
let mut out = String::from("{");
for (index, (key, child)) in entries.into_iter().enumerate() {
if index != 0 {
out.push(',');
}
out.push_str(&sonic_rs::to_string(key).unwrap_or_else(|_| "\"\"".to_owned()));
out.push(':');
out.push_str(&canonical_json(child));
}
out.push('}');
out
} else if let Some(array) = value.as_array() {
let mut out = String::from("[");
for (index, child) in array.iter().enumerate() {
if index != 0 {
out.push(',');
}
out.push_str(&canonical_json(child));
}
out.push(']');
out
} else {
sonic_rs::to_string(value).unwrap_or_default()
}
}
fn content_text(value: Option<&Value>) -> String {
let Some(value) = value else {
return String::new();
};
if value.is_null() {
String::new()
} else if let Some(text) = value.as_str() {
text.to_owned()
} else if let Some(boolean) = value.as_bool() {
boolean.to_string()
} else if value.is_number() {
sonic_rs::to_string(value).unwrap_or_default()
} else if let Some(items) = value.as_array() {
let mut out = String::new();
for item in items {
if let Some(text) = item.as_str() {
out.push_str(text);
} else if let Some(text) = item.get(&"text").and_then(|v| v.as_str()) {
out.push_str(text);
} else {
out.push_str(&canonical_json(item));
}
}
out
} else {
canonical_json(value)
}
}
fn render_message(message: &Value, tools: Option<&str>, include_reasoning: bool) -> String {
let mut out = String::new();
if let Some(tools) = tools {
out.push_str("<|system|>Available tools (OpenAI API schema):\n");
out.push_str(tools);
out.push_str("<|end|>");
}
// Responses API items carry their kind in `type` instead of `role`.
let item_type = message
.get(&"type")
.and_then(|value| value.as_str())
.unwrap_or("");
if item_type == "function_call" {
let name = content_text(message.get(&"name"));
let arguments = content_text(message.get(&"arguments"));
let call_id = content_text(message.get(&"call_id").or_else(|| message.get(&"id")));
let mut out = String::new();
if let Some(tools) = tools {
out.push_str("<|system|>Available tools (OpenAI API schema):\n");
out.push_str(tools);
out.push_str("|");
}
out.push_str("<|assistant|><|tool_call|>");
out.push_str(&call_id);
out.push('\n');
out.push_str("function\n");
out.push_str(&name);
out.push('\n');
out.push_str(&arguments);
out.push_str("|");
return out;
}
if item_type == "function_call_output" {
let call_id = content_text(message.get(&"call_id"));
let output = content_text(message.get(&"output"));
let mut out = String::new();
if let Some(tools) = tools {
out.push_str("<|system|>Available tools (OpenAI API schema):\n");
out.push_str(tools);
out.push_str("|");
}
out.push_str("<|tool|>");
out.push_str(&call_id);
out.push('\n');
out.push_str(&output);
out.push_str("|\n");
out.push_str(&output);
out.push_str("|");
return out;
}
if item_type == "reasoning" {
let mut out = String::new();
if let Some(tools) = tools {
out.push_str("<|system|>Available tools (OpenAI API schema):\n");
out.push_str(tools);
out.push_str("|");
}
out.push_str("<|assistant|>");
if include_reasoning {
let summary = message
.get(&"summary")
.and_then(|value| value.as_array())
.map(|items| {
items
.iter()
.map(|item| content_text(item.get(&"text").or(Some(item))))
.collect::<Vec<_>>()
.join(" ")
})
.unwrap_or_default();
if !summary.is_empty() {
out.push_str("<|think|>");
out.push_str(&summary);
out.push_str("|");
}
}
out.push_str("|");
return out;
}
let role = message
.get(&"role")
.and_then(|value| value.as_str())
.unwrap_or(if item_type == "message" { "user" } else { "user" });
let content = content_text(message.get(&"content"));
match role {
"assistant" => {
out.push_str("<|assistant|>");
let reasoning = content_text(message.get(&"reasoningContent"));
if include_reasoning && !reasoning.is_empty() {
out.push_str("<|think|>");
out.push_str(&reasoning);
out.push_str("<|end|>");
}
out.push_str(&content);
let calls = message.get(&"tool_calls").or_else(|| message.get(&"toolCalls"));
if let Some(calls) = calls.and_then(|value| value.as_array()) {
for call in calls {
let Some(obj) = call.as_object() else {
continue;
};
let custom = obj.get(&"custom").and_then(|value| value.as_object());
out.push_str("<|tool_call|>");
out.push_str(&content_text(obj.get(&"id")));
out.push('\n');
if let Some(custom) = custom {
out.push_str("custom\n");
out.push_str(&content_text(custom.get(&"name")));
out.push('\n');
out.push_str(&content_text(custom.get(&"input")));
} else {
let function = obj.get(&"function").and_then(|value| value.as_object());
out.push_str(
obj.get(&"type")
.and_then(|value| value.as_str())
.unwrap_or("function"),
);
out.push('\n');
out.push_str(&content_text(
function.and_then(|function| function.get(&"name")),
));
out.push('\n');
out.push_str(&content_text(
function.and_then(|function| function.get(&"arguments")),
));
}
}
}
out.push_str("<|end|>");
}
"tool" | "function" => {
out.push_str("<|tool|>");
out.push_str(&content_text(message.get(&"tool_call_id")));
out.push('\n');
out.push_str(&content_text(message.get(&"name")));
out.push('\n');
out.push_str(&content);
out.push_str("<|end|>");
}
"system" | "developer" => {
out.push_str("<|system|>");
out.push_str(&content);
out.push_str("<|end|>");
}
_ => {
out.push_str("<|user|>");
out.push_str(&content);
out.push_str("<|end|>");
}
}
out
}
fn grouped(value: impl ToString) -> String {
let digits = value.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (index, ch) in digits.chars().enumerate() {
if index > 0 && (digits.len() - index) % 3 == 0 {
out.push(',');
}
out.push(ch);
}
out
}
fn stable_hash(text: &str) -> u64 {
// XXH3 is deterministic across runs; AHash remains randomized for in-memory tables.
xxh3_64(text.as_bytes())
}
fn add_count(map: &mut FastMap<String, u64>, word: String, n: u64) -> Result<()> {
let entry = map.entry(word).or_insert(0);
*entry = entry
.checked_add(n)
.ok_or_else(|| anyhow!("word frequency overflow (u64)"))?;
Ok(())
}
fn estimate_entry_bytes(word: &str) -> usize {
// Conservative estimate for a hash-table bucket, control byte, String allocation,
// and allocator metadata. This is a spill heuristic, not an allocator measurement.
mem::size_of::<(String, u64)>()
.saturating_mul(2)
.saturating_add(word.len())
.saturating_add(48)
}
fn pretokenize_words(text: &str) -> Vec<String> {
let mut words = Vec::new();
let mut current = String::new();
let mut current_kind: Option<u8> = None;
for ch in text.chars() {
let kind = if ch.is_whitespace() {
0
} else if ch.is_alphanumeric() || ch == '_' {
1
} else {
2
};
if kind == 0 {
if !current.is_empty() {
words.push(std::mem::take(&mut current));
current_kind = None;
}
continue;
}
if current_kind.is_some_and(|k| k != kind) && !current.is_empty() {
words.push(std::mem::take(&mut current));
}
current_kind = Some(kind);
current.push(ch);
}
if !current.is_empty() {
words.push(current);
}
words
}
fn visit_bounded_windows<F>(
word: &str,
max_chars: usize,
overlap: usize,
mut visit: F,
) -> Result<()>
where
F: FnMut(&str) -> Result<()>,
{
if word.is_empty() {
return Ok(());
}
let max_chars = max_chars.max(1);
let step_chars = max_chars.saturating_sub(overlap).max(1);
let mut start = 0usize;
loop {
let remaining = &word[start..];
let end = match remaining.char_indices().nth(max_chars) {
Some((byte_offset, _)) => start + byte_offset,
None => word.len(),
};
visit(&word[start..end])?;
if end == word.len() {
break;
}
let step = remaining
.char_indices()
.nth(step_chars)
.map(|(byte_offset, _)| byte_offset)
.unwrap_or(remaining.len());
start = start.saturating_add(step);
}
Ok(())
}
fn emit_batch(tx: &StatsSender, batch: &mut FastMap<String, u64>) -> Result<()> {
if batch.is_empty() {
return Ok(());
}
let ready = mem::replace(batch, fast_map());
tx.send(Ok(ready))
.map_err(|_| anyhow!("statistics consumer stopped"))
}
fn add_file_counts(
total: &mut (u64, u64, u64),
current: (u64, u64, u64),
) -> Result<()> {
total.0 = total
.0
.checked_add(current.0)
.ok_or_else(|| anyhow!("message counter overflow"))?;
total.1 = total
.1
.checked_add(current.1)
.ok_or_else(|| anyhow!("character counter overflow"))?;
total.2 = total
.2
.checked_add(current.2)
.ok_or_else(|| anyhow!("malformed-record counter overflow"))?;
Ok(())
}
fn process_tar_archive<'a>(
source: &str,
reader: Box<dyn Read + 'a>,
depth: usize,
max_depth: usize,
cfg: &WorkerConfig,
budget: &mut LimitBudget,
tx: &StatsSender,
) -> Result<(u64, u64, u64)> {
let mut archive = tar::Archive::new(reader);
let mut totals = (0u64, 0u64, 0u64);
for entry_result in archive.entries().context("opening tar entries")? {
if budget.exhausted() {
break;
}
let entry = entry_result.context("reading tar entry")?;
let path = entry
.path()
.with_context(|| format!("reading entry path in {source}"))?
.to_string_lossy()
.into_owned();
let lower = path.to_ascii_lowercase();
if entry.header().entry_type().is_dir() {
continue;
}
if is_jsonl_name(&lower) {
let current = if lower.ends_with(".zst") {
let decoder = zstd::stream::read::Decoder::new(entry)
.with_context(|| format!("decompressing archive member {path}"))?;
let reader = BufReader::with_capacity(cfg.zstd_buffer_bytes, decoder);
process_reader(&path, reader, cfg, budget, tx)?
} else {
let reader = BufReader::with_capacity(cfg.input_buffer_bytes, entry);
process_reader(&path, reader, cfg, budget, tx)?
};
add_file_counts(&mut totals, current)?;
} else if is_archive_name(&lower) && depth < max_depth {
// Erase the nested reader type before recursion. Otherwise each nested
// Entry<Decoder<Entry<...>>> creates a new generic instantiation.
let nested_reader: Box<dyn Read + '_> =
if lower.ends_with(".zst") || lower.ends_with(".zstd") {
let decoder = zstd::stream::read::Decoder::new(entry)
.with_context(|| format!("decompressing nested archive {path}"))?;
Box::new(BufReader::with_capacity(cfg.zstd_buffer_bytes, decoder))
} else {
Box::new(BufReader::with_capacity(cfg.input_buffer_bytes, entry))
};
let current = process_tar_archive(
&path,
nested_reader,
depth + 1,
max_depth,
cfg,
budget,
tx,
)?;
add_file_counts(&mut totals, current)?;
}
}
Ok(totals)
}
fn process_file(
path: &Path,
max_depth: usize,
cfg: &WorkerConfig,
args: &Args,
tx: &StatsSender,
) -> Result<(u64, u64, u64)> {
let mut budget = LimitBudget::from_args(args);
if budget.exhausted() {
return Ok((0, 0, 0));
}
if is_archive(path) {
let file = File::open(path).with_context(|| format!("opening archive {}", path.display()))?;
let name = lower_name(path);
let reader: Box<dyn Read> = if name.ends_with(".tar.zst") || name.ends_with(".tar.zstd") {
let decoder = zstd::stream::read::Decoder::new(file)
.with_context(|| format!("decompressing archive {}", path.display()))?;
Box::new(BufReader::with_capacity(cfg.zstd_buffer_bytes, decoder))
} else {
Box::new(BufReader::with_capacity(cfg.input_buffer_bytes, file))
};
process_tar_archive(
&path.display().to_string(),
reader,
0,
max_depth,
cfg,
&mut budget,
tx,
)
} else {
let name = lower_name(path);
let capacity = if name.ends_with(".zst") {
cfg.zstd_buffer_bytes
} else {
cfg.input_buffer_bytes
};
let reader = open_reader(path, capacity)?;
process_reader(
&path.display().to_string(),
reader,
cfg,
&mut budget,
tx,
)
}
}
fn process_reader<R: BufRead>(
source: &str,
mut reader: R,
cfg: &WorkerConfig,
budget: &mut LimitBudget,
tx: &StatsSender,
) -> Result<(u64, u64, u64)> {
let mut line = Vec::<u8>::with_capacity(64 * 1024);
let mut tools: Option<String> = None;
let mut messages = 0u64;
let mut chars = 0u64;
let mut malformed = 0u64;
let mut batch = fast_map();
let mut batch_occurrences = 0usize;
let mut batch_estimate = 0usize;
let mut messages_since_batch = 0usize;
loop {
if budget.exhausted() {
break;
}
line.clear();
let n = reader.read_until(b'\n', &mut line)?;
if n == 0 {
break;
}
if cfg.max_line_bytes > 0 && n > cfg.max_line_bytes {
bail!(
"JSONL record in {source} exceeds --max_json_line_mb ({} bytes)",
cfg.max_line_bytes
);
}
let record: Value = match sonic_rs::from_slice(&line) {
Ok(value) => value,
Err(_) => {
malformed = malformed.saturating_add(1);
continue;
}
};
match record.get(&"type").and_then(|value| value.as_str()) {
Some("session") => {
tools = record
.get(&"tools")
.filter(|value| {
value
.as_array()
.is_some_and(|array| !array.is_empty())
})
.map(canonical_json);
}
Some("message") => {
let Some(message) = record.get(&"message") else {
continue;
};
if !message.is_object() {
continue;
}
let rendered = render_message(message, tools.as_deref(), cfg.include_reasoning);
tools = None;
if rendered.is_empty() {
continue;
}
let mut rendered = rendered;
let mut rendered_chars = rendered.chars().count();
if let Some(remaining) = budget.remaining_chars {
if remaining == 0 {
break;
}
if rendered_chars > remaining {
let byte_end = rendered
.char_indices()
.nth(remaining)
.map(|(byte_index, _)| byte_index)
.unwrap_or(rendered.len());
rendered.truncate(byte_end);
rendered_chars = remaining;
}
}
if rendered.is_empty() {
break;
}
messages = messages
.checked_add(1)
.ok_or_else(|| anyhow!("message counter overflow in {source}"))?;
chars = chars
.checked_add(rendered_chars as u64)
.ok_or_else(|| anyhow!("character counter overflow in {source}"))?;
budget.consume(rendered_chars);
STATS_MESSAGES.fetch_add(1, Ordering::Relaxed);
STATS_CHARS.fetch_add(rendered_chars as u64, Ordering::Relaxed);
messages_since_batch += 1;
for word in pretokenize_words(&rendered) {
visit_bounded_windows(&word, cfg.max_word_chars, cfg.overlap_chars, |window| {
add_count(&mut batch, window.to_owned(), 1)?;
batch_occurrences += 1;
batch_estimate = batch_estimate
.saturating_add(256usize.saturating_add(4 * window.len()));
if batch_occurrences >= cfg.batch_occurrences
|| batch_estimate >= cfg.batch_bytes
{
emit_batch(tx, &mut batch)?;
batch_occurrences = 0;
batch_estimate = 0;
}
Ok(())
})?;
}
if messages_since_batch >= cfg.raw_batch_messages {
emit_batch(tx, &mut batch)?;
batch_occurrences = 0;
batch_estimate = 0;
messages_since_batch = 0;
}
}
_ => {}
}
}
emit_batch(tx, &mut batch)?;
Ok((messages, chars, malformed))
}
fn decode_db_count(bytes: &[u8]) -> Option<u64> {
let array: [u8; DB_COUNT_BYTES] = bytes.try_into().ok()?;
Some(u64::from_le_bytes(array))
}
fn merge_u64_counts(
_key: &[u8],
existing_value: Option<&[u8]>,
operands: &rocksdb::MergeOperands,
) -> Option<Vec<u8>> {
let mut total = match existing_value {
Some(bytes) => decode_db_count(bytes)?,
None => 0,
};
for operand in operands {
// Returning None rejects the merge instead of allowing a frequency to wrap.
total = total.checked_add(decode_db_count(operand)?)?;
}
Some(total.to_le_bytes().to_vec())
}
fn rocksdb_writer(
db: Arc<DB>,
rx: Receiver<FastMap<String, u64>>,
write_batch_size: usize,
) -> Result<()> {
let write_options = {
let mut options = WriteOptions::default();
options.set_sync(false);
options.disable_wal(true);
options
};
let batch_capacity = write_batch_size.saturating_mul(48).max(1024);
for words in rx {
let mut batch = WriteBatch::with_capacity_bytes(batch_capacity);
let mut count = 0usize;
for (word, frequency) in words {
let encoded = frequency.to_le_bytes();
batch.merge(word.as_bytes(), encoded);
count += 1;
if count >= write_batch_size {
db.write_opt(batch, &write_options)
.context("writing RocksDB statistics batch")?;
batch = WriteBatch::with_capacity_bytes(batch_capacity);
count = 0;
}
}
if !batch.is_empty() {
db.write_opt(batch, &write_options)
.context("writing final RocksDB statistics batch")?;
}
}
Ok(())
}
struct RocksSpill {
path: PathBuf,
db: Option<Arc<DB>>,
writers: Vec<SyncSender<FastMap<String, u64>>>,
handles: Vec<JoinHandle<Result<()>>>,
dispatch_chunk_entries: usize,
finished: bool,
}
impl RocksSpill {
#[allow(clippy::too_many_arguments)]
fn new(
spill_dir: &Path,
writer_threads: usize,
writer_queue: usize,
write_batch_size: usize,
write_buffer_mb: usize,
max_write_buffers: usize,
max_successive_merges: usize,
background_jobs: usize,
zstd_compression: bool,
) -> Result<Self> {
fs::create_dir_all(spill_dir)
.with_context(|| format!("creating statistics directory {}", spill_dir.display()))?;
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("system clock is before UNIX epoch")?
.as_nanos();
let path = spill_dir.join(format!(
".sts_tokenizer_stats_{}_{}",
std::process::id(),
stamp
));
let mut options = Options::default();
options.create_if_missing(true);
options.set_merge_operator_associative("u64-frequency-sum-v1", merge_u64_counts);
options.set_write_buffer_size(write_buffer_mb.saturating_mul(1024 * 1024));
options.set_max_write_buffer_number(max_write_buffers.min(i32::MAX as usize) as i32);
options.set_min_write_buffer_number_to_merge(2);
// Merge operands are compacted into concrete values before their chains grow
// without bound for high-frequency tokens.
options.set_max_successive_merges(max_successive_merges.max(1));
options.set_max_background_jobs(background_jobs.min(i32::MAX as usize) as i32);
options.set_allow_concurrent_memtable_write(true);
options.set_enable_write_thread_adaptive_yield(true);
if zstd_compression {
options.set_compression_type(DBCompressionType::Zstd);
} else {
options.set_compression_type(DBCompressionType::None);
}
let db = Arc::new(
DB::open(&options, &path)
.with_context(|| format!("opening RocksDB statistics store {}", path.display()))?,
);
let writer_threads = writer_threads.max(1);
let mut writers = Vec::with_capacity(writer_threads);
let mut handles = Vec::with_capacity(writer_threads);
for _ in 0..writer_threads {
let (tx, rx) = sync_channel::<FastMap<String, u64>>(writer_queue.max(1));
let writer_db = Arc::clone(&db);
handles.push(thread::spawn(move || {
rocksdb_writer(writer_db, rx, write_batch_size.max(1))
}));
writers.push(tx);
}
Ok(Self {
path,
db: Some(db),
writers,
handles,
dispatch_chunk_entries: write_batch_size.max(1024),
finished: false,
})
}
fn dispatch_map(&self, words: FastMap<String, u64>) -> Result<()> {
if words.is_empty() {
return Ok(());
}
if self.writers.is_empty() {
bail!("RocksDB writers are already stopped");
}
let writer_count = self.writers.len();
let chunk_limit = self.dispatch_chunk_entries;
let mut shards: Vec<FastMap<String, u64>> =
(0..writer_count).map(|_| fast_map()).collect();
for (word, frequency) in words {
let shard = (stable_hash(&word) as usize) % writer_count;
let shard_map = &mut shards[shard];
shard_map.insert(word, frequency);
if shard_map.len() >= chunk_limit {
let ready = mem::replace(shard_map, fast_map());
self.writers[shard]
.send(ready)
.map_err(|_| anyhow!("RocksDB writer {shard} stopped"))?;
}
}
for (shard, remaining) in shards.into_iter().enumerate() {
if !remaining.is_empty() {
self.writers[shard]
.send(remaining)
.map_err(|_| anyhow!("RocksDB writer {shard} stopped"))?;
}
}
Ok(())
}
fn finish_writers(&mut self) -> Result<()> {
if self.finished {
return Ok(());
}
self.writers.clear();
let mut first_error: Option<anyhow::Error> = None;
for handle in self.handles.drain(..) {
match handle.join() {
Ok(Ok(())) => {}
Ok(Err(error)) => {
if first_error.is_none() {
first_error = Some(error);
}
}
Err(_) => {
if first_error.is_none() {
first_error = Some(anyhow!("RocksDB writer thread panicked"));
}
}
}
}
self.finished = true;
if let Some(error) = first_error {
Err(error)
} else {
Ok(())
}
}
fn select(&mut self, max_unique: usize) -> Result<(Vec<(String, u64)>, u64, u64, u64)> {
self.finish_writers()?;
let db = self
.db
.as_ref()
.ok_or_else(|| anyhow!("RocksDB statistics database is unavailable"))?;
select_database(db, max_unique)
}
}
impl Drop for RocksSpill {
fn drop(&mut self) {
self.writers.clear();
for handle in self.handles.drain(..) {
let _ = handle.join();
}
self.db.take();
if self.path.exists() {
let options = Options::default();
let _ = DB::destroy(&options, &self.path);
}
}
}
struct WordStats {
map: FastMap<String, u64>,
estimated_bytes: usize,
memory_limit_bytes: usize,
total_occurrences: u128,
spill: Option<RocksSpill>,
spill_dir: PathBuf,
db_writer_threads: usize,
db_writer_queue: usize,
db_write_batch_size: usize,
db_write_buffer_mb: usize,
db_max_write_buffers: usize,
db_max_successive_merges: usize,
db_background_jobs: usize,
db_zstd: bool,
}
impl WordStats {
#[allow(clippy::too_many_arguments)]
fn new(
memory_limit_bytes: usize,
spill_dir: &Path,
db_writer_threads: usize,
db_writer_queue: usize,
db_write_batch_size: usize,
db_write_buffer_mb: usize,
db_max_write_buffers: usize,
db_max_successive_merges: usize,
db_background_jobs: usize,
db_zstd: bool,
) -> Result<Self> {
fs::create_dir_all(spill_dir)?;
Ok(Self {
map: fast_map(),
estimated_bytes: 0,
memory_limit_bytes: memory_limit_bytes.max(1),
total_occurrences: 0,
spill: None,
spill_dir: spill_dir.to_path_buf(),
db_writer_threads,
db_writer_queue,
db_write_batch_size,
db_write_buffer_mb,
db_max_write_buffers,
db_max_successive_merges,
db_background_jobs,
db_zstd,
})
}
fn start_spill(&mut self) -> Result<()> {
if self.spill.is_some() {
return Ok(());
}
let spill = RocksSpill::new(
&self.spill_dir,
self.db_writer_threads,
self.db_writer_queue,
self.db_write_batch_size,
self.db_write_buffer_mb,
self.db_max_write_buffers,
self.db_max_successive_merges,
self.db_background_jobs,
self.db_zstd,
)?;
let existing = mem::replace(&mut self.map, fast_map());
self.estimated_bytes = 0;
spill.dispatch_map(existing)?;
self.spill = Some(spill);
eprintln!(" statistics map reached its RAM budget; switched to concurrent RocksDB spill");
Ok(())
}
fn merge(&mut self, batch: FastMap<String, u64>) -> Result<()> {
if batch.is_empty() {
return Ok(());
}
let batch_total = batch.values().try_fold(0u128, |total, frequency| {
total
.checked_add(*frequency as u128)
.ok_or_else(|| anyhow!("total word occurrence counter overflow (u128)"))
})?;
self.total_occurrences = self
.total_occurrences
.checked_add(batch_total)
.ok_or_else(|| anyhow!("total word occurrence counter overflow (u128)"))?;
if self.spill.is_none() {
let added_bytes = batch
.iter()
.filter(|(word, _)| !self.map.contains_key(*word))
.fold(0usize, |total, (word, _)| {
total.saturating_add(estimate_entry_bytes(word))
});
let threshold = self.memory_limit_bytes.saturating_mul(85) / 100;
if self.estimated_bytes.saturating_add(added_bytes) >= threshold {
self.start_spill()?;
}
}
if let Some(spill) = &self.spill {
spill.dispatch_map(batch)?;
} else {
for (word, frequency) in batch {
if !self.map.contains_key(&word) {
self.estimated_bytes = self
.estimated_bytes
.saturating_add(estimate_entry_bytes(&word));
}
add_count(&mut self.map, word, frequency)?;
}
}
Ok(())
}
fn select(
mut self,
max_unique: usize,
) -> Result<(Vec<(String, u64)>, u128, u64, u64, u64)> {
if self.total_occurrences == 0 {
bail!("No text was available for tokenizer training");
}
let (items, total_unique, frequent, tail) = if let Some(mut spill) = self.spill.take() {
let (items, total_unique, frequent, tail) = spill.select(max_unique)?;
(items, total_unique, frequent, tail)
} else {
select_map(&self.map, max_unique)?
};
Ok((
items,
self.total_occurrences,
total_unique,
frequent,
tail,
))
}
}
fn consider_frequent(heap: &mut TopHeap, word: &str, frequency: u64, limit: usize) {
if limit == 0 {
return;
}
// The heap root is the worst selected entry: lowest frequency, then the
// lexicographically greatest word. Avoid allocating a String unless this
// candidate actually enters the bounded heap.
if heap.len() < limit {
heap.push(Reverse((frequency, Reverse(word.to_owned()))));
return;
}
let should_insert = match heap.peek() {
Some(Reverse((worst_frequency, Reverse(worst_word)))) => {
frequency > *worst_frequency
|| (frequency == *worst_frequency && word < worst_word.as_str())
}
None => true,
};
if should_insert {
heap.pop();
heap.push(Reverse((frequency, Reverse(word.to_owned()))));
}
}
fn frequent_items_from_heap(heap: TopHeap) -> Vec<(String, u64)> {
let mut frequent: Vec<(String, u64)> = heap
.into_iter()
.map(|Reverse((frequency, Reverse(word)))| (word, frequency))
.collect();
frequent.sort_by(|left, right| {
right
.1
.cmp(&left.1)
.then_with(|| left.0.cmp(&right.0))
});
frequent
}
fn finish_frequent_heap(heap: TopHeap) -> (Vec<(String, u64)>, AHashSet<String>) {
let frequent = frequent_items_from_heap(heap);
let frequent_set = frequent.iter().map(|(word, _)| word.clone()).collect();
(frequent, frequent_set)
}
fn consider_tail(heap: &mut TailHeap, word: &str, frequency: u64, limit: usize) {
if limit == 0 {
return;
}
let hash = stable_hash(word);
let should_insert = match heap.peek() {
None => true,
Some((worst_hash, worst_word, _)) => (hash, word) < (*worst_hash, worst_word.as_str()),
};
if heap.len() < limit {
heap.push((hash, word.to_owned(), frequency));
} else if should_insert {
heap.pop();
heap.push((hash, word.to_owned(), frequency));
}
}
fn finish_selection(
mut frequent: Vec<(String, u64)>,
mut tail_heap: TailHeap,
total_unique: u64,
selected: usize,
frequent_n: usize,
) -> (Vec<(String, u64)>, u64, u64, u64) {
let mut tail_items: Vec<(String, u64)> = tail_heap
.drain()
.map(|(_, word, frequency)| (word, frequency))
.collect();
tail_items.sort_by(|left, right| left.0.cmp(&right.0));
frequent.append(&mut tail_items);
(
frequent,
total_unique,
frequent_n as u64,
(selected - frequent_n) as u64,
)
}
fn selection_sizes(total_unique: u64, max_unique: usize) -> (usize, usize) {
let selected = total_unique.min(max_unique as u64) as usize;
let frequent_n = if selected == 0 {
0
} else {
selected.min(((selected as f64 * 0.8) as usize).max(1))
};
(selected, frequent_n)
}
fn select_map(
map: &FastMap<String, u64>,
max_unique: usize,
) -> Result<(Vec<(String, u64)>, u64, u64, u64)> {
let total_unique = u64::try_from(map.len()).context("unique-word count exceeds u64")?;
let (selected, frequent_n) = selection_sizes(total_unique, max_unique);
let mut frequent_heap = TopHeap::with_capacity(frequent_n.saturating_add(1));
for (word, frequency) in map {
consider_frequent(&mut frequent_heap, word, *frequency, frequent_n);
}
let (frequent_items, frequent_set) = finish_frequent_heap(frequent_heap);
let tail_n = selected - frequent_n;
let mut tail_heap = TailHeap::with_capacity(tail_n.saturating_add(1));
if tail_n > 0 {
for (word, frequency) in map {
if !frequent_set.contains(word) {
consider_tail(&mut tail_heap, word, *frequency, tail_n);
}
}
}
Ok(finish_selection(
frequent_items,
tail_heap,
total_unique,
selected,
frequent_n,
))
}
fn select_database(
db: &DB,
max_unique: usize,
) -> Result<(Vec<(String, u64)>, u64, u64, u64)> {
let mut frequent_heap = TopHeap::new();
let mut total_unique = 0u64;
// Keep only enough candidates to produce the final 80% frequent subset.
// When the corpus has fewer than max_unique entries, this cap is still at
// least as large as the eventual frequent_n and is trimmed after counting.
let frequent_candidate_cap = if max_unique == 0 {
0
} else {
((max_unique as f64 * 0.8) as usize).max(1).min(max_unique)
};
// First pass: exact unique count and the most frequent words.
for entry in db.iterator(IteratorMode::Start) {
let (key, value) = entry.context("iterating RocksDB statistics (top-frequency pass)")?;
let word = std::str::from_utf8(&key).context("RocksDB word key is not UTF-8")?;
let frequency = decode_db_count(&value)
.ok_or_else(|| anyhow!("invalid or overflowing RocksDB frequency value"))?;
total_unique = total_unique
.checked_add(1)
.ok_or_else(|| anyhow!("unique-word counter overflow (u64)"))?;
// The exact frequent_n is unknown until the first pass completes, but
// this cap is sufficient in both the truncated and untruncated cases.
consider_frequent(&mut frequent_heap, word, frequency, frequent_candidate_cap);
}
let (selected, frequent_n) = selection_sizes(total_unique, max_unique);
let mut frequent_items = frequent_items_from_heap(frequent_heap);
if frequent_items.len() > frequent_n {
frequent_items.truncate(frequent_n);
}
let frequent_set: AHashSet<String> =
frequent_items.iter().map(|(word, _)| word.clone()).collect();
let tail_n = selected - frequent_n;
let mut tail_heap = TailHeap::with_capacity(tail_n.saturating_add(1));
if tail_n > 0 {
// Second pass: deterministic XXH3 sample from the non-frequent tail.
for entry in db.iterator(IteratorMode::Start) {
let (key, value) = entry.context("iterating RocksDB statistics (tail-sampling pass)")?;
let word = std::str::from_utf8(&key).context("RocksDB word key is not UTF-8")?;
if frequent_set.contains(word) {
continue;
}
let frequency = decode_db_count(&value)
.ok_or_else(|| anyhow!("invalid or overflowing RocksDB frequency value"))?;
consider_tail(&mut tail_heap, word, frequency, tail_n);
}
}
Ok(finish_selection(
frequent_items,
tail_heap,
total_unique,
selected,
frequent_n,
))
}
fn collect_stats(
files: &[PathBuf],
args: &Args,
cfg: &WorkerConfig,
source_workers: usize,
spill_dir: &Path,
memory_limit_bytes: usize,
db_writer_threads: usize,
db_background_jobs: usize,
) -> Result<(Vec<(String, u64)>, u128, u64, u64, u64)> {
let queue_slots = (args.tok_queue_mb / args.tok_batch_mb.max(1)).max(1);
let (tx, rx) = sync_channel::<std::result::Result<FastMap<String, u64>, String>>(queue_slots);
let next_file = Arc::new(AtomicUsize::new(0));
let files = Arc::new(files.to_vec());
let mut stats = WordStats::new(
memory_limit_bytes,
spill_dir,
db_writer_threads,
args.db_writer_queue,
args.db_write_batch_size,
args.db_write_buffer_mb,
args.db_max_write_buffers,
args.db_max_successive_merges,
db_background_jobs,
args.db_zstd,
)?;
let mut handles = Vec::with_capacity(source_workers);
for _ in 0..source_workers {
let tx = tx.clone();
let next_file = Arc::clone(&next_file);
let files = Arc::clone(&files);
let cfg = cfg.clone();
let args = args.clone();
handles.push(thread::spawn(move || -> Result<()> {
loop {
let index = next_file.fetch_add(1, Ordering::Relaxed);
if index >= files.len() {
break;
}
let path = &files[index];
let file_cfg = cfg.clone();
let mut file_args = args.clone();
if let Some(limit) = args.tok_max_messages {
let file_count = files.len() as u64;
let base = limit / file_count;
let extra = if (index as u64) < (limit % file_count) { 1u64 } else { 0 };
file_args.tok_max_messages = Some(base + extra);
}
if let Some(limit) = args.tok_max_chars {
let file_count = files.len();
let base = limit / file_count;
let extra = if index < (limit % file_count) { 1usize } else { 0 };
file_args.tok_max_chars = Some(base + extra);
}
match process_file(path, args.max_archive_depth, &file_cfg, &file_args, &tx) {
Ok((_messages, _chars, _malformed)) => {}
Err(error) => {
let _ = tx.send(Err(format!("{}: {error:#}", path.display())));
return Err(error);
}
}
}
Ok(())
}));
}
drop(tx);
let mut receive_error: Option<anyhow::Error> = None;
while let Ok(item) = rx.recv() {
match item {
Ok(batch) => {
if let Err(error) = stats.merge(batch) {
receive_error = Some(error);
break;
}
}
Err(error) => {
receive_error = Some(anyhow!(error));
break;
}
}
}
if let Some(error) = receive_error {
drop(rx);
for handle in handles {
let _ = handle.join();
}
return Err(error);
}
for handle in handles {
handle
.join()
.map_err(|_| anyhow!("tokenizer input worker panicked"))??;
}
stats.select(match args.tokenizer {
Algorithm::Bpe => args.bpe_max_unique_words,
Algorithm::Unigram => args.unigram_max_unique_words,
Algorithm::Wordpiece => args.wordpiece_max_unique_words,
})
}
// Kept separate so the heartbeat thread is always stopped, including on early errors.
struct Heartbeat {
done: Arc<AtomicBool>,
handle: Option<JoinHandle<()>>,
}
impl Heartbeat {
fn start(started: Instant) -> Self {
let done = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&done);
let handle = thread::spawn(move || {
let mut next_report = 60u64;
while !flag.load(Ordering::Relaxed) {
thread::sleep(Duration::from_secs(1));
let elapsed = started.elapsed().as_secs();
if elapsed >= next_report && !flag.load(Ordering::Relaxed) {
eprintln!(
" [heartbeat] elapsed {:.0}s; messages={}, chars={}",
started.elapsed().as_secs_f64(),
STATS_MESSAGES.load(Ordering::Relaxed),
STATS_CHARS.load(Ordering::Relaxed)
);
next_report = next_report.saturating_add(60);
}
}
});
Self {
done,
handle: Some(handle),
}
}
fn stop(&mut self) {
self.done.store(true, Ordering::Relaxed);
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
impl Drop for Heartbeat {
fn drop(&mut self) {
self.stop();
}
}
struct WeightedWords {
words: Vec<(String, u64)>,
index: usize,
remaining: u64,
scale: f64,
}
impl WeightedWords {
fn new(words: Vec<(String, u64)>, max_examples: usize) -> Self {
let total: u128 = words.iter().map(|(_, frequency)| *frequency as u128).sum();
let scale = if total == 0 {
1.0
} else {
(max_examples as f64).min(total as f64) / total as f64
};
Self {
words,
index: 0,
remaining: 0,
scale,
}
}
}
impl Iterator for WeightedWords {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.remaining > 0 {
self.remaining -= 1;
return Some(self.words[self.index - 1].0.clone());
}
if self.index >= self.words.len() {
return None;
}
let frequency = self.words[self.index].1;
self.remaining = ((frequency as f64 * self.scale + 0.5).floor() as u64).max(1);
self.index += 1;
}
}
}
fn special_tokens(include_unk: bool) -> Vec<AddedToken> {
let mut tokens = Vec::new();
if include_unk {
tokens.push(AddedToken::from(UNK.to_owned(), true));
}
tokens.extend(SPECIAL.iter().map(|token| AddedToken::from((*token).to_owned(), true)));
tokens
}
fn byte_level_alphabet() -> HashSet<char> {
let mut bytes: Vec<u8> = (33u8..=126).chain(161..=172).chain(174..=255).collect();
let mut chars: Vec<u32> = bytes.iter().map(|&b| b as u32).collect();
let mut n = 0u32;
for b in 0u8..=255 {
if !bytes.contains(&b) {
bytes.push(b);
chars.push(256 + n);
n += 1;
}
}
chars.into_iter().filter_map(char::from_u32).collect()
}
fn added_token_json(id: u32, content: &str) -> serde_json::Value {
serde_json::json!({
"id": id,
"content": content,
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true,
"control": false,
})
}
fn build_tokenizer(args: &Args, words: Vec<(String, u64)>) -> Result<serde_json::Value> {
let alphabet = byte_level_alphabet();
let weighted = WeightedWords::new(
words,
match args.tokenizer {
Algorithm::Bpe => args.bpe_train_words,
Algorithm::Unigram => args.unigram_train_words,
Algorithm::Wordpiece => args.wordpiece_train_words,
},
);
let (model_json, vocab, added): (serde_json::Value, HashMap<String, u32>, Vec<serde_json::Value>) =
match args.tokenizer {
Algorithm::Bpe => {
let mut model = BPE::from_config(BpeConfig::default())
.map_err(|error| anyhow!("creating BPE model: {error}"))?;
let mut trainer = BpeTrainer::builder()
.vocab_size(args.vocab_size)
.min_frequency(args.bpe_min_frequency)
.special_tokens(special_tokens(false))
.initial_alphabet(alphabet)
.max_token_length(Some(args.bpe_max_token_length))
.show_progress(true)
.build();
trainer
.feed(weighted, |word| Ok(vec![word.to_owned()]))
.map_err(|error| anyhow!("feeding BPE trainer: {error}"))?;
trainer
.train(&mut model)
.map_err(|error| anyhow!("training BPE: {error}"))?;
let config = model
.to_config()
.map_err(|error| anyhow!("reading trained BPE: {error}"))?;
let vocab: HashMap<String, u32> =
config.vocab.iter().map(|(k, v)| (k.clone(), *v)).collect();
let merges: Vec<[String; 2]> = config
.merges
.into_iter()
.map(|(a, b)| [a, b])
.collect();
let model_json = serde_json::json!({
"type": "BPE",
"dropout": null,
"unk_token": config.unk_token,
"continuing_subword_prefix": config.continuing_subword_prefix,
"end_of_word_suffix": config.end_of_word_suffix,
"fuse_unk": config.fuse_unk,
"byte_fallback": true,
"byte_level": true,
"vocab": config.vocab,
"merges": merges,
});
let added = SPECIAL
.iter()
.filter_map(|token| vocab.get(*token).map(|id| added_token_json(*id, token)))
.collect();
(model_json, vocab, added)
}
Algorithm::Unigram => {
let mut model = Unigram::from(vec![(UNK.to_owned(), 0.0)], Some(0), true)
.map_err(|error| anyhow!("creating byte-fallback Unigram model: {error}"))?;
let mut builder = UnigramTrainer::builder();
builder
.vocab_size(
args.vocab_size
.try_into()
.map_err(|_| anyhow!("Unigram vocab_size exceeds u32::MAX"))?,
)
.special_tokens(special_tokens(true))
.unk_token(Some(UNK.to_owned()))
.initial_alphabet(alphabet.into_iter().collect::<AHashSet<char>>())
.max_piece_length(args.unigram_max_piece_length)
.show_progress(true);
let mut trainer = builder
.build()
.map_err(|error| anyhow!("building Unigram trainer: {error}"))?;
trainer
.feed(weighted, |word| Ok(vec![word.to_owned()]))
.map_err(|error| anyhow!("feeding Unigram trainer: {error}"))?;
trainer
.train(&mut model)
.map_err(|error| anyhow!("training Unigram: {error}"))?;
let pairs: Vec<(String, f64)> = model.vocab().to_vec();
let vocab: HashMap<String, u32> = pairs
.iter()
.enumerate()
.map(|(id, (token, _))| (token.clone(), id as u32))
.collect();
let vocab_json: Vec<serde_json::Value> = pairs
.iter()
.map(|(token, score)| serde_json::json!([token, score]))
.collect();
let model_json = serde_json::json!({
"type": "Unigram",
"unk_id": model.unk_id(),
"byte_fallback": true,
"vocab": vocab_json,
});
let added = SPECIAL
.iter()
.chain(std::iter::once(&UNK))
.filter_map(|token| vocab.get(*token).map(|id| added_token_json(*id, token)))
.collect();
(model_json, vocab, added)
}
Algorithm::Wordpiece => {
let mut model = WordPieceConfig::default();
model.unk_token = UNK.to_owned();
let mut trainer = WordPieceTrainer::builder()
.vocab_size(args.vocab_size)
.special_tokens(special_tokens(true))
.show_progress(true)
.build();
trainer
.feed(weighted, |word| Ok(vec![word.to_owned()]))
.map_err(|error| anyhow!("feeding WordPiece trainer: {error}"))?;
trainer
.train(&mut model)
.map_err(|error| anyhow!("training WordPiece: {error}"))?;
let vocab: HashMap<String, u32> = model.vocab.into_iter().collect();
let model_json = serde_json::json!({
"type": "WordPiece",
"unk_token": model.unk_token,
"continuing_subword_prefix": model.continuing_subword_prefix,
"max_input_chars_per_word": model.max_input_chars_per_word,
"vocab": vocab,
});
let added = SPECIAL
.iter()
.chain(std::iter::once(&UNK))
.filter_map(|token| vocab.get(*token).map(|id| added_token_json(*id, token)))
.collect();
(model_json, vocab, added)
}
};
let operator_pattern = r"\?\?[=/()'<>!]|<%|%>|<:|:>|%:|%:%:|and_eq|or_eq|not_eq|bitand|bitor|xor_eq|==|!=|<=|>=|->|::|\*\*|\+\+|--|&&|\|\||<<=|>>=|<<|>>|\+=|-=|\*=|/=|%=|&=|\|=|\^=|[<>]=?|[+\-*/%&|^]=?|~";
let mut pretokenizers = vec![
serde_json::json!({
"type": "ByteLevel",
"add_prefix_space": false,
"trim_offsets": true,
"use_regex": true
}),
serde_json::json!({
"type": "Split",
"pattern": {"Regex": operator_pattern},
"behavior": "Isolated",
"invert": false
})
];
let pre_tokenizer = serde_json::json!({
"type": "Sequence",
"pretokenizers": pretokenizers
});
let decoder = match args.tokenizer {
Algorithm::Bpe => serde_json::json!({
"type": "ByteLevel",
"add_prefix_space": true,
"trim_offsets": true,
"use_regex": true,
}),
Algorithm::Unigram => serde_json::json!({
"type": "Sequence",
"decoders": [
{"type": "ByteFallback"},
{"type": "ByteLevel", "add_prefix_space": true, "trim_offsets": true, "use_regex": true},
],
}),
Algorithm::Wordpiece => serde_json::json!({
"type": "Sequence",
"decoders": [
{"type": "WordPiece", "prefix": "##", "cleanup": false},
{"type": "ByteLevel", "add_prefix_space": true, "trim_offsets": true, "use_regex": true},
],
}),
};
if vocab.is_empty() {
bail!("training produced an empty vocabulary");
}
Ok(serde_json::json!({
"version": "1.0",
"truncation": null,
"padding": null,
"added_tokens": added,
"normalizer": null,
"pre_tokenizer": pre_tokenizer,
"post_processor": null,
"decoder": decoder,
"model": model_json,
}))
}
#[derive(serde::Serialize)]
struct PretokenizedWord<'a> {
text: &'a str,
frequency: u64,
}
#[derive(serde::Serialize)]
struct PretokenizedMeta<'a> {
format_version: u8,
stage: &'static str,
algorithm: String,
include_reasoning: bool,
vocab_size: usize,
total_occurrences: u128,
total_unique_words: u64,
saved_unique_words: usize,
frequent_words: u64,
sampled_tail_words: u64,
frequency_count_error: f64,
data_file: &'a str,
}
fn write_pretokenized(
path: &Path,
words: &[(String, u64)],
args: &Args,
occurrences: u128,
unique: u64,
frequent: u64,
tail: u64,
) -> Result<()> {
let tmp = path.with_extension("jsonl.tmp");
let file = File::create(&tmp)?;
let mut writer = BufWriter::new(file);
for (word, frequency) in words {
serde_json::to_writer(
&mut writer,
&PretokenizedWord {
text: word,
frequency: *frequency,
},
)?;
writer.write_all(b"\n")?;
}
writer.flush()?;
writer.get_ref().sync_all()?;
if path.exists() {
fs::remove_file(path)?;
}
fs::rename(&tmp, path)?;
let data_file = path.file_name().unwrap_or_default().to_string_lossy();
let meta = PretokenizedMeta {
format_version: 1,
stage: "bytelevel_pretokenized_word_frequencies",
algorithm: format!("{:?}", args.tokenizer).to_lowercase(),
include_reasoning: !args.no_reasoning,
vocab_size: args.vocab_size,
total_occurrences: occurrences,
total_unique_words: unique,
saved_unique_words: words.len(),
frequent_words: frequent,
sampled_tail_words: tail,
frequency_count_error: 0.0,
data_file: &data_file,
};
let meta_path = path.with_file_name("pretokenized_meta.json");
let meta_tmp = meta_path.with_extension("json.tmp");
let mut meta_writer = BufWriter::new(File::create(&meta_tmp)?);
serde_json::to_writer_pretty(&mut meta_writer, &meta)?;
meta_writer.flush()?;
meta_writer.get_ref().sync_all()?;
if meta_path.exists() {
fs::remove_file(&meta_path)?;
}
fs::rename(&meta_tmp, &meta_path)?;
Ok(())
}
fn tokenize_corpus(args: &Args) -> Result<()> {
let tokenizer_path = args.out_dir.join("tokenizer.json");
let raw = fs::read_to_string(&tokenizer_path)
.with_context(|| format!("reading {}", tokenizer_path.display()))?;
// Rust's v1 reader cannot load a `ByteLevel` pre-tokenizer on non-BPE models, so build a
// Rust-compatible view by dropping `ByteLevel` members from any `Sequence` pre-tokenizer.
let value: serde_json::Value = serde_json::from_str(&raw)?;
let mut rust_value = value.clone();
if let Some(version) = rust_value.get_mut(&"version") {
*version = serde_json::json!("2.0");
}
if let Some(pre) = rust_value.get_mut(&"pre_tokenizer") {
if pre.get(&"type").and_then(serde_json::Value::as_str) == Some("Sequence") {
if let Some(members) = pre.get_mut(&"pretokenizers").and_then(serde_json::Value::as_array_mut) {
members.retain(|member| member.get(&"type").and_then(serde_json::Value::as_str) != Some("ByteLevel"));
if members.is_empty() {
*pre = serde_json::Value::Null;
}
}
} else if pre.get(&"type").and_then(serde_json::Value::as_str) == Some("ByteLevel") {
*pre = serde_json::Value::Null;
}
}
let canonical = serde_json::to_string(&rust_value)?;
let tokenizer = tokenizers::from_json(&canonical)
.map_err(|error| anyhow!("loading {}: {error}", tokenizer_path.display()))?;
let files = collect_inputs(&args.data_dir)?;
let shard_limit = args.shard_tokens;
let mut shard_index = 0usize;
let mut shard_tokens = 0usize;
let mut writer = if shard_limit == 0 {
std::io::BufWriter::new(File::create(args.out_dir.join("tokens.bin"))?)
} else {
std::io::BufWriter::new(File::create(args.out_dir.join(format!("tokens_{shard_index:04}.bin")))?)
};
let mut label_writer = if shard_limit == 0 {
std::io::BufWriter::new(File::create(args.out_dir.join("labels.bin"))?)
} else {
std::io::BufWriter::new(File::create(args.out_dir.join(format!("labels_{shard_index:04}.bin")))?)
};
let mut total_tokens = 0u64;
let mut total_messages = 0u64;
for path in &files {
let capacity = if path.to_string_lossy().to_ascii_lowercase().ends_with(".zst") {
args.input_chunk_mb.saturating_mul(1024 * 1024).max(1024 * 1024)
} else {
args.input_chunk_mb.saturating_mul(1024 * 1024).max(1024 * 1024)
};
let mut reader = open_reader(path, capacity)?;
let mut line = String::new();
let mut tools: Option<Value> = None;
let include_reasoning = !args.no_reasoning;
loop {
line.clear();
let n = reader.read_line(&mut line)?;
if n == 0 {
break;
}
let record: Value = match serde_json::from_str(&line) {
Ok(value) => value,
Err(_) => continue,
};
match record.get(&"type").and_then(Value::as_str) {
Some("session") => {
tools = record
.get(&"tools")
.filter(|value| value.as_array().is_some_and(|array| !array.is_empty()))
.cloned();
}
Some("message") => {
let Some(message) = record.get(&"message") else {
continue;
};
if !message.is_object() {
continue;
}
let is_target = message
.get(&"role")
.and_then(Value::as_str)
.map(|role| role == "assistant")
.unwrap_or_else(|| {
message
.get(&"type")
.and_then(Value::as_str)
.map(|kind| kind == "function_call")
.unwrap_or(false)
});
let rendered = render_message(message, tools.as_ref().map(|value| value.to_string()).as_deref(), include_reasoning);
tools = None;
if rendered.is_empty() {
continue;
}
let encoded = tokenizer
.encode(rendered.as_str(), &EncodeOptions::default())
.wait()
.map_err(|error| anyhow!("encoding message: {error}"))?;
for encoding in &encoded {
for token in encoding.ids() {
writer.write_all(&token.id().to_le_bytes())?;
label_writer.write_all(&[if is_target { 1u8 } else { 0u8 }])?;
total_tokens += 1;
shard_tokens += 1;
if shard_limit > 0 && shard_tokens >= shard_limit {
writer.flush()?;
label_writer.flush()?;
shard_index += 1;
shard_tokens = 0;
writer = std::io::BufWriter::new(File::create(
args.out_dir.join(format!("tokens_{shard_index:04}.bin")),
)?);
label_writer = std::io::BufWriter::new(File::create(
args.out_dir.join(format!("labels_{shard_index:04}.bin")),
)?);
}
}
}
total_messages += 1;
}
_ => {}
}
}
}
writer.flush()?;
eprintln!(
"Tokenized {} messages into {} tokens (shards: {})",
total_messages,
total_tokens,
shard_index + 1
);
Ok(())
}
fn main() -> Result<()> {
let args = Args::parse();
if args.tokenize_only && args.pretokenize_only {
bail!("--tokenize-only and --pretokenize-only are mutually exclusive");
}
if args.tok_max_messages == Some(0) || args.tok_max_chars == Some(0) {
bail!("tokenizer corpus limits must be >= 1");
}
if args.max_archive_depth > 64 {
bail!("--max_archive_depth must be <= 64");
}
if args.vocab_size == 0 || args.unigram_max_piece_length == 0 || args.bpe_max_token_length < 2 {
bail!("invalid vocabulary or token-length setting");
}
if args.bpe_max_unique_words == 0
|| args.bpe_train_words == 0
|| args.bpe_max_word_chars < args.bpe_max_token_length
{
bail!("require positive BPE limits and --bpe_max_word_chars >= --bpe_max_token_length");
}
if args.unigram_max_unique_words == 0
|| args.unigram_train_words == 0
|| args.unigram_max_word_chars < args.unigram_max_piece_length
{
bail!("invalid Unigram memory/training limits");
}
if args.wordpiece_max_unique_words == 0
|| args.wordpiece_train_words == 0
|| args.wordpiece_max_word_chars == 0
{
bail!("WordPiece memory/training limits must be positive");
}
if args.bpe_min_frequency == 0
|| args.tok_batch_size == 0
|| args.tok_batch_mb == 0
|| args.tok_queue_mb < args.tok_batch_mb
|| args.unigram_stats_batch == 0
{
bail!("invalid frequency or tokenizer batch/queue limits");
}
if args.stats_memory_gb == Some(0)
|| (args.stats_memory_gb.is_none() && args.stats_memory_mb == 0)
{
bail!("statistics memory budget must be positive");
}
if args.db_writer_queue == 0
|| args.db_write_batch_size == 0
|| args.db_write_buffer_mb == 0
|| args.db_max_write_buffers < 2
|| args.db_max_successive_merges == 0
{
bail!("invalid RocksDB writer, batch, or memory settings");
}
if args.zstd_read_mb == 0 || args.input_chunk_mb == 0 {
bail!("input and Zstandard buffer limits must be positive");
}
let min_vocab = match args.tokenizer {
Algorithm::Bpe => SPECIAL.len() + 256,
Algorithm::Unigram => SPECIAL.len() + 257,
Algorithm::Wordpiece => SPECIAL.len() + 1,
};
if args.vocab_size < min_vocab {
bail!("--vocab_size must be at least {min_vocab} for {:?}", args.tokenizer);
}
if args.rayon_threads > 0 {
std::env::set_var("RAYON_RS_NUM_THREADS", args.rayon_threads.to_string());
}
fs::create_dir_all(&args.out_dir)?;
let files = collect_inputs(&args.data_dir)?;
eprintln!(
"Tokenizer: {:?}; {} source(s); vocab_size={}",
args.tokenizer,
files.len(),
args.vocab_size
);
let cpus = thread::available_parallelism()
.map(|count| count.get())
.unwrap_or(1);
let tok_workers = if args.tok_workers == 0 {
cpus
} else {
args.tok_workers
};
let input_workers = if args.input_workers == 0 {
tok_workers.saturating_mul(2).min(16)
} else {
args.input_workers
};
let source_workers = tok_workers
.min(input_workers)
.max(1)
.min(files.len());
// Capped runs stay single-worker so the corpus limits are deterministic.
let source_workers = if args.tok_max_messages.is_some() || args.tok_max_chars.is_some() {
1
} else {
source_workers
};
let db_writer_threads = if args.db_writer_threads == 0 {
cpus.min(8).max(1)
} else {
args.db_writer_threads
};
let db_background_jobs = if args.db_background_jobs == 0 {
cpus.clamp(2, 16)
} else {
args.db_background_jobs
};
let (max_word_chars, overlap_chars) = match args.tokenizer {
Algorithm::Bpe => (args.bpe_max_word_chars, args.bpe_max_token_length - 1),
Algorithm::Unigram => (args.unigram_max_word_chars, args.unigram_max_piece_length - 1),
Algorithm::Wordpiece => (args.wordpiece_max_word_chars, 0),
};
let cfg = WorkerConfig {
include_reasoning: !args.no_reasoning,
max_line_bytes: args.max_json_line_mb.saturating_mul(1024 * 1024),
input_buffer_bytes: args.input_chunk_mb.saturating_mul(1024 * 1024).max(1024 * 1024),
zstd_buffer_bytes: (args.zstd_read_mb.saturating_mul(1024 * 1024)
/ source_workers.max(1))
.max(1024 * 1024),
raw_batch_messages: args.tok_batch_size,
max_word_chars,
overlap_chars,
batch_occurrences: args.unigram_stats_batch,
batch_bytes: args.tok_batch_mb.saturating_mul(1024 * 1024),
};
let memory_limit_mb = args
.stats_memory_gb
.map(|gb| gb.saturating_mul(1024))
.unwrap_or(args.stats_memory_mb);
let memory_limit_bytes = memory_limit_mb.saturating_mul(1024 * 1024).max(1);
let spill_dir = args.tok_stats_dir.as_deref().unwrap_or(&args.out_dir);
eprintln!(
"Workers: sources={source_workers}, RocksDB writers={db_writer_threads}; statistics spill threshold={:.2} GiB",
memory_limit_bytes as f64 / (1024.0 * 1024.0 * 1024.0)
);
if args.tokenize_only {
tokenize_corpus(&args)?;
return Ok(());
}
let started = Instant::now();
let mut heartbeat = Heartbeat::start(started);
let (words, occurrences, unique, frequent, tail) = collect_stats(
&files,
&args,
&cfg,
source_workers,
spill_dir,
memory_limit_bytes,
db_writer_threads,
db_background_jobs,
)?;
heartbeat.stop();
let feed_examples: u64 = {
let total: u128 = words.iter().map(|(_, frequency)| *frequency as u128).sum();
let cap = match args.tokenizer {
Algorithm::Bpe => args.bpe_train_words,
Algorithm::Unigram => args.unigram_train_words,
Algorithm::Wordpiece => args.wordpiece_train_words,
} as u128;
let scale = if total == 0 {
1.0
} else {
(cap.min(total) as f64) / total as f64
};
words
.iter()
.map(|(_, frequency)| ((*frequency as f64 * scale + 0.5).floor() as u64).max(1))
.sum()
};
eprintln!(
"Tokenizer stats: {} word windows, {} unique words; selected {} ({} frequent + {} deterministic tail); {} weighted examples; {:.1}s",
grouped(occurrences),
grouped(unique),
grouped(words.len()),
grouped(frequent),
grouped(tail),
grouped(feed_examples),
started.elapsed().as_secs_f64()
);
let pretokenized_path = args.out_dir.join("pretokenized_words.jsonl");
if args.pretokenize_only {
write_pretokenized(
&pretokenized_path,
&words,
&args,
occurrences,
unique,
frequent,
tail,
)?;
eprintln!("Pre-tokenization complete: {}", pretokenized_path.display());
return Ok(());
}
if matches!(args.tokenizer, Algorithm::Wordpiece) {
eprintln!(
"WARNING: WordPiece + ByteLevel is not byte-safe; unseen bytes may become <|unk|> and decoding can be lossy."
);
}
let tokenizer = build_tokenizer(&args, words)?;
let tokenizer_path = args.out_dir.join("tokenizer.json");
let vocab_size = tokenizer
.get("model")
.and_then(|model| model.get("vocab"))
.and_then(|vocab| vocab.as_object().map(|map| map.len()).or_else(|| vocab.as_array().map(|array| array.len())))
.unwrap_or(0);
let encoded = serde_json::to_vec_pretty(&tokenizer)?;
fs::write(&tokenizer_path, encoded)?;
eprintln!(
"Saved {} tokens to {} ({:.1}s total)",
vocab_size,
tokenizer_path.display(),
started.elapsed().as_secs_f64()
);
tokenize_corpus(&args)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn emitted_tokenizer_json_uses_023_schema() {
let mut args = Args::parse_from(["rust-sts-tokenizer", "--vocab_size", "300"]);
let words = [
("hello".to_owned(), 4),
("world".to_owned(), 3),
("tokenizer".to_owned(), 2),
];
for algorithm in [Algorithm::Bpe, Algorithm::Unigram, Algorithm::Wordpiece] {
args.tokenizer = algorithm;
let tokenizer = build_tokenizer(&args, words.to_vec()).unwrap();
assert_eq!(tokenizer["version"], "1.0");
assert_eq!(tokenizer["pre_tokenizer"]["type"], "Sequence");
if matches!(algorithm, Algorithm::Bpe) {
assert_eq!(tokenizer["model"]["byte_level"], true);
}
assert!(tokenizer["added_tokens"][0].get("control").is_some());
}
}
}
|