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 = HbHashMap; type TopHeap = BinaryHeap)>>; type TailHeap = BinaryHeap<(u64, String, u64)>; type StatsSender = SyncSender, String>>; fn fast_map() -> FastMap { 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, #[arg(long)] tok_max_chars: Option, #[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, #[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, #[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, remaining_chars: Option, } 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> { 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> { 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::>() .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, 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 { let mut words = Vec::new(); let mut current = String::new(); let mut current_kind: Option = 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( 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) -> 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, 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>> creates a new generic instantiation. let nested_reader: Box = 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 = 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( source: &str, mut reader: R, cfg: &WorkerConfig, budget: &mut LimitBudget, tx: &StatsSender, ) -> Result<(u64, u64, u64)> { let mut line = Vec::::with_capacity(64 * 1024); let mut tools: Option = 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 { 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> { 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, rx: Receiver>, 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>, writers: Vec>>, handles: Vec>>, 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 { 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::>(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) -> 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> = (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 = 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, estimated_bytes: usize, memory_limit_bytes: usize, total_occurrences: u128, spill: Option, 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 { 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) -> 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) { 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, 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 = 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::, 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 = 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, handle: Option>, } 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 { 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 { 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 { let mut bytes: Vec = (33u8..=126).chain(161..=172).chain(174..=255).collect(); let mut chars: Vec = 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 { 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, Vec) = 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 = 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::>()) .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 = pairs .iter() .enumerate() .map(|(id, (token, _))| (token.clone(), id as u32)) .collect(); let vocab_json: Vec = 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 = 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 = 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()); } } }