Files
leleka/crates/tokenizer/examples/gguf_tokenize.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 d661812b09 feat: add the gpt-oss tokenizer and the Harmony prompt renderer and parser (STRA-213)
leleka-tokenizer gains gguf_bpe: a byte-level BPE tokenizer built from the vocabulary in the GGUF file
(gpt2 model, gpt-4o pre-tokenizer), with special-token parsing that is off by default so user text cannot
forge markers, and a UTF-8-safe streaming decoder. Checked against llama.cpp's /tokenize on 67 strings: same
ids except the two documented differences (llama.cpp forges some Harmony markers from text; it splits
words at combining marks, which the o200k expression keeps together).

New leleka-harmony crate: render() reproduces the gpt-oss chat template (including its whitespace) and is
byte-identical to llama.cpp's /apply-template on ten conversations with many tool-schema shapes;
HarmonyParser turns generated tokens into reasoning, answer and tool-call events.

The oracle fixtures are test strings, token ids and rendered prompts only. The tokenizer oracle test needs
LELEKA_GPTOSS_GGUF and reports "skipped" without it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 19:08:24 +02:00

84 lines
2.7 KiB
Rust

//! Tokenize text with the vocabulary of a GGUF file and print the ids.
//!
//! Run: `cargo run --release -p leleka-tokenizer --example gguf_tokenize -- <model.gguf> [--special] [--json] [text...]`
//! With no text arguments, every line of standard input is tokenized. `--json` prints one JSON array of
//! ids per line (for comparing with llama.cpp's `/tokenize`); `--special` parses special-token text.
//! `--info` prints the special tokens of the vocabulary and exits.
use leleka_gguf::Gguf;
use leleka_tokenizer::gguf_bpe::GgufBpe;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
fn main() {
let mut args: Vec<String> = std::env::args().skip(1).collect();
if args.is_empty() {
eprintln!("usage: gguf_tokenize <model.gguf> [--special] [--json] [--info] [text...]");
std::process::exit(2);
}
let path = args.remove(0);
let flag = |args: &mut Vec<String>, name: &str| {
let before = args.len();
args.retain(|a| a != name);
args.len() != before
};
let special = flag(&mut args, "--special");
let json = flag(&mut args, "--json");
let info = flag(&mut args, "--info");
let size = std::fs::metadata(&path).expect("model file").len();
let t = Instant::now();
let gguf = Gguf::read(
BufReader::with_capacity(1 << 20, File::open(Path::new(&path)).expect("open")),
size,
)
.expect("valid GGUF");
let tok = GgufBpe::from_gguf(&gguf).expect("tokenizer");
eprintln!(
"tokenizer: {} tokens, loaded in {:.2} s (bos {:?}, eos {:?}, pad {:?})",
tok.vocab_size(),
t.elapsed().as_secs_f64(),
tok.bos,
tok.eos,
tok.pad
);
if info {
let types = gguf
.get("tokenizer.ggml.token_type")
.and_then(leleka_gguf::Value::as_array)
.expect("token types");
for id in 0..tok.vocab_size() as u32 {
if tok.is_special(id) {
println!(
"{id}\t{:?}\t{}",
types[id as usize],
tok.token_text(id).unwrap_or("")
);
}
}
return;
}
let run = |text: &str| {
let ids = tok.encode(text, special);
if json {
println!(
"[{}]",
ids.iter().map(u32::to_string).collect::<Vec<_>>().join(",")
);
} else {
println!("{ids:?} -> {:?}", tok.decode(&ids));
}
};
if args.is_empty() {
for line in std::io::stdin().lock().lines() {
run(&line.expect("stdin"));
}
} else {
for text in &args {
run(text);
}
}
}