Skip to main content

kute_cli/
lib.rs

1//! `kute`: train, encode, decode, inspect, validate, compare, export, benchmark.
2//!
3//! Results go to stdout as JSON (or raw bytes for `decode`), messages to
4//! stderr. Exit status is 0 on success and 1 on any error.
5
6use clap::{Parser, Subcommand, ValueEnum};
7use kute::{vocab, AdapterConfig, Engine, KuteError, Pretokenizer, TokenSequence, TrainingConfig, Version, VocabularyId};
8use serde_json::json;
9use std::io::Write;
10use std::path::PathBuf;
11use std::process::ExitCode;
12
13#[derive(Parser)]
14#[command(name = "kute", version, about = "Kannaka Universal Tokenization Engine", long_about = None)]
15struct Cli {
16    #[command(subcommand)]
17    command: Command,
18}
19
20#[derive(Subcommand)]
21enum Command {
22    /// Learn a vocabulary from files and write it as KVF.
23    Train(Box<TrainArgs>),
24    /// Encode a file to a .kute token sequence.
25    Encode {
26        #[arg(long)]
27        vocab: PathBuf,
28        #[arg(long)]
29        input: PathBuf,
30        /// Where to write the .kute container. Without it, token ids are printed as JSON.
31        #[arg(long)]
32        output: Option<PathBuf>,
33        /// Write the compressed container (format 2) instead of plain varint ids.
34        #[arg(long, requires = "output")]
35        compress: bool,
36    },
37    /// Decode a .kute token sequence back to bytes.
38    Decode {
39        #[arg(long)]
40        vocab: PathBuf,
41        #[arg(long)]
42        input: PathBuf,
43        /// Where to write the decoded bytes. Without it, they go to stdout.
44        #[arg(long)]
45        output: Option<PathBuf>,
46    },
47    /// Summarize a vocabulary, or show tokens from it.
48    Inspect {
49        vocab: PathBuf,
50        /// Show the full envelope of one token id.
51        #[arg(long)]
52        token: Option<u32>,
53        /// Show the N longest learned tokens.
54        #[arg(long, default_value_t = 0)]
55        longest: usize,
56    },
57    /// Check structure, integrity and the embedded test vectors.
58    Validate { vocab: PathBuf },
59    /// Compare two vocabularies by token content.
60    Compare { a: PathBuf, b: PathBuf },
61    /// Convert a vocabulary to another tool's format.
62    Export {
63        #[arg(long)]
64        vocab: PathBuf,
65        #[arg(long, value_enum, default_value_t = ExportFormat::Tiktoken)]
66        format: ExportFormat,
67        /// Output file, e.g. general.tiktoken. A `.json` sidecar with the
68        /// pattern and special tokens is written next to it.
69        #[arg(long)]
70        output: PathBuf,
71    },
72    /// Measure a vocabulary on a dataset, or run the benchmark suite.
73    Benchmark {
74        #[arg(long, required_unless_present = "suite")]
75        vocab: Option<PathBuf>,
76        /// File or directory to evaluate on. Keep it separate from training data.
77        #[arg(long, required_unless_present = "suite")]
78        dataset: Option<PathBuf>,
79        /// Run the built-in benchmark program instead.
80        #[arg(long, conflicts_with_all = ["vocab", "dataset"])]
81        suite: bool,
82        /// Repository root for the suite's in-repo corpora.
83        #[arg(long)]
84        repo_root: Option<PathBuf>,
85        /// A large UTF-8 text file for the suite's real-data case (for example enwik8).
86        /// The first 90% trains a 32K vocabulary; the rest is the evaluation set.
87        #[arg(long, requires = "suite")]
88        large_text: Option<PathBuf>,
89        #[arg(long, default_value_t = 5)]
90        iterations: usize,
91        /// Also write the JSON report to this file.
92        #[arg(long)]
93        output: Option<PathBuf>,
94    },
95    /// List registered algorithms and adapters and what each declares.
96    Capabilities,
97    /// Write the seeded example datasets used by the documentation.
98    SampleData {
99        /// Directory to create the files in.
100        #[arg(long)]
101        output: PathBuf,
102    },
103}
104
105#[derive(Clone, Copy, ValueEnum)]
106enum ExportFormat {
107    Tiktoken,
108}
109
110#[derive(clap::Args)]
111struct TrainArgs {
112    /// Files or directories to train on. Directories are read recursively.
113    #[arg(long, required = true, num_args = 1..)]
114    input: Vec<PathBuf>,
115    /// Vocabulary identifier, e.g. kute:industrial:events.
116    #[arg(long)]
117    id: String,
118    /// Vocabulary version (semantic versioning).
119    #[arg(long, default_value = "0.1.0")]
120    vocab_version: String,
121    #[arg(long, default_value = "bpe")]
122    algorithm: String,
123    #[arg(long, default_value = "text")]
124    adapter: String,
125    /// Adapter option as key=value. Repeatable.
126    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
127    adapter_options: Vec<String>,
128    #[arg(long, default_value_t = 4096)]
129    vocab_size: u32,
130    /// none, gpt4, or regex:<pattern>. Default: gpt4 for the text adapter, none otherwise.
131    #[arg(long)]
132    pretokenizer: Option<String>,
133    #[arg(long, default_value_t = 1)]
134    min_frequency: u64,
135    #[arg(long)]
136    max_token_length: Option<usize>,
137    /// Reserved (special) token. Repeatable.
138    #[arg(long = "reserved")]
139    reserved: Vec<String>,
140    /// File with one dictionary entry per line, for the dictionary algorithm.
141    #[arg(long)]
142    dictionary_file: Option<PathBuf>,
143    #[arg(long)]
144    description: Option<String>,
145    /// License of the vocabulary, e.g. an SPDX identifier.
146    #[arg(long)]
147    license: Option<String>,
148    #[arg(long)]
149    output: PathBuf,
150    /// Replace an existing output file even if its content differs.
151    #[arg(long)]
152    force: bool,
153}
154
155fn print(value: &impl serde::Serialize) -> kute::Result<()> {
156    let text = serde_json::to_string_pretty(value)?;
157    let mut out = std::io::stdout().lock();
158    writeln!(out, "{text}")?;
159    Ok(())
160}
161
162fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
163    match spec {
164        None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
165        Some("none") => Ok(Pretokenizer::None),
166        Some("gpt4") => Ok(Pretokenizer::Gpt4),
167        Some(s) => match s.strip_prefix("regex:") {
168            Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
169            _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
170        },
171    }
172}
173
174fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
175    let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
176    config.vocabulary_version = Version::parse(&args.vocab_version)
177        .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
178    let symbol_algorithm = args.algorithm == "sequence-bpe";
179    config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
180        Pretokenizer::None
181    } else {
182        parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
183    };
184    config.min_frequency = args.min_frequency;
185    config.max_token_length = args.max_token_length;
186    config.reserved_tokens = args.reserved;
187    config.description = args.description;
188    config.license = args.license;
189    if let Some(path) = &args.dictionary_file {
190        let text = std::fs::read_to_string(path)?;
191        config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
192    }
193    let mut adapter_config = AdapterConfig::default();
194    for option in &args.adapter_options {
195        let (key, value) = option
196            .split_once('=')
197            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
198        adapter_config = adapter_config.with(key, value);
199    }
200    let start = std::time::Instant::now();
201    let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
202    let seconds = start.elapsed().as_secs_f64();
203    vocab::save(&vocabulary, &args.output, args.force)?;
204    eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
205    print(&json!({
206        "output": args.output,
207        "train_seconds": seconds,
208        "summary": vocab::summarize(&vocabulary)?,
209    }))
210}
211
212fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
213    match cli.command {
214        Command::Train(args) => train(&engine, *args),
215        Command::Encode { vocab: vocab_path, input, output, compress } => {
216            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
217            let raw = std::fs::read(&input)?;
218            let sequence = engine.encode_raw(tokenizer.as_ref(), &raw)?;
219            match output {
220                Some(path) => {
221                    let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
222                    std::fs::write(&path, &bytes)?;
223                    print(&json!({
224                        "output": path,
225                        "input_bytes": raw.len(),
226                        "tokens": sequence.ids.len(),
227                        "serialized_bytes": bytes.len(),
228                        "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
229                    }))
230                }
231                None => print(&sequence),
232            }
233        }
234        Command::Decode { vocab: vocab_path, input, output } => {
235            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
236            let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
237            let bytes = engine.decode_raw(tokenizer.as_ref(), &sequence)?;
238            match output {
239                Some(path) => {
240                    std::fs::write(&path, &bytes)?;
241                    print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
242                }
243                None => {
244                    let mut out = std::io::stdout().lock();
245                    out.write_all(&bytes)?;
246                    out.flush()?;
247                    Ok(())
248                }
249            }
250        }
251        Command::Inspect { vocab: vocab_path, token, longest } => {
252            let vocabulary = vocab::load(&vocab_path)?;
253            if let Some(id) = token {
254                return print(&vocabulary.record(id)?);
255            }
256            let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
257            if longest > 0 {
258                let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
259                learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
260                let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
261                report["longest_learned_tokens"] = serde_json::to_value(rows)?;
262            }
263            print(&report)
264        }
265        Command::Validate { vocab: vocab_path } => {
266            let vocabulary = vocab::load(&vocab_path)?;
267            let report = engine.verify(&vocabulary)?;
268            print(&report)?;
269            if report.ok() {
270                Ok(())
271            } else {
272                Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
273            }
274        }
275        Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
276        Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
277            let vocabulary = vocab::load(&vocab_path)?;
278            let export = vocab::export_tiktoken(&vocabulary)?;
279            std::fs::write(&output, &export.bpe_file)?;
280            let mut sidecar = output.clone().into_os_string();
281            sidecar.push(".json");
282            let sidecar = PathBuf::from(sidecar);
283            let meta = json!({
284                "name": vocabulary.id().as_str().replace(':', "_"),
285                "pat_str": export.pat_str,
286                "special_tokens": export.special_tokens,
287                "explicit_n_vocab": export.n_vocab,
288                "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
289                "source_digest": vocabulary.digest()?,
290            });
291            std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
292            print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
293        }
294        Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
295            let report = if suite {
296                serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
297            } else {
298                let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
299                    return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
300                };
301                let vocabulary = vocab::load(&vocab_path)?;
302                let documents = kute_bench::read_dataset(&dataset)?;
303                json!({
304                    "environment": kute_bench::Environment::detect(),
305                    "dataset": dataset,
306                    "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
307                })
308            };
309            if let Some(path) = output {
310                let mut text = serde_json::to_string_pretty(&report)?;
311                text.push('\n');
312                std::fs::write(&path, text)?;
313                eprintln!("report written to {}", path.display());
314            }
315            print(&report)
316        }
317        Command::SampleData { output } => {
318            use kute_bench::data;
319            std::fs::create_dir_all(&output)?;
320            let files: Vec<(&str, Vec<u8>, &str)> = vec![
321                ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
322                ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
323                ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
324                ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
325                ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
326                ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
327                ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
328                ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
329            ];
330            let mut written = Vec::new();
331            for (name, bytes, what) in files {
332                std::fs::write(output.join(name), &bytes)?;
333                written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
334            }
335            print(&json!({ "output": output, "synthetic": true, "files": written }))
336        }
337        Command::Capabilities => {
338            let registry = engine.registry();
339            let algorithms: Vec<kute::TokenizerCapabilities> =
340                registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
341            let adapters: Vec<serde_json::Value> = registry
342                .adapter_names()
343                .iter()
344                .map(|n| {
345                    registry.adapter(n).map(|a| {
346                        let c = a.capabilities();
347                        json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
348                    })
349                })
350                .collect::<kute::Result<_>>()?;
351            print(&json!({
352                "kute_version": kute::KUTE_VERSION,
353                "kvf_version": kute::KVF_VERSION,
354                "algorithms": algorithms,
355                "adapters": adapters,
356            }))
357        }
358    }
359}
360
361/// Parse the command line and run it on `engine`. The `kute` binary passes
362/// the default engine; other front ends can register more algorithms first.
363pub fn main_with(engine: Engine) -> ExitCode {
364    match run(engine, Cli::parse()) {
365        Ok(()) => ExitCode::SUCCESS,
366        Err(e) => {
367            eprintln!("kute: {e}");
368            ExitCode::FAILURE
369        }
370    }
371}