STRA-338 size-fn: tokenizer: from_assets, from_vocabulary, piece_end, merge_long, encode_piece, merge_piece, from_gguf, from_parts, bpe_heap, encode_plain, encode_segment, unmark, Classes::new and the examples within limits (fn>30 prod 12 -> 0)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 18:39:09 +01:00
parent 0abeca4871
commit 25c73e6ade
15 changed files with 765 additions and 527 deletions
+29 -15
View File
@@ -2,7 +2,12 @@
//!
//! `cargo run --release -p leleka-tokenizer --example bench_encode -- TOKENIZER_DIR PROMPTS.txt [REPEAT]`
use std::{env, fs, path::Path, process::ExitCode, time::Instant};
use std::{
env, fs,
path::Path,
process::ExitCode,
time::{Duration, Instant},
};
use leleka_tokenizer::Tokenizer;
@@ -24,20 +29,29 @@ fn main() -> ExitCode {
let ids = tokenizer.encode(&text, true).expect("encode");
let encode = started.elapsed();
let started = Instant::now();
let mut bytes = 0usize;
for &id in &ids {
bytes += tokenizer.decode_bytes(&[id]).expect("decode").len();
}
let decode = started.elapsed();
eprintln!(
"text {} bytes -> {} tokens: encode {:.1} ms ({:.2} Mtok/s); decode_bytes one id at a time {:.2} us/token ({} bytes)",
text.len(),
ids.len(),
encode.as_secs_f64() * 1e3,
ids.len() as f64 / encode.as_secs_f64() / 1e6,
decode.as_secs_f64() * 1e6 / ids.len() as f64,
bytes
);
let bytes = decoded_bytes(&tokenizer, &ids);
report(&text, &ids, (encode, started.elapsed()), bytes);
}
ExitCode::SUCCESS
}
/// Decode one id at a time and total the bytes.
fn decoded_bytes(tokenizer: &Tokenizer, ids: &[u32]) -> usize {
let mut bytes = 0usize;
for &id in ids {
bytes += tokenizer.decode_bytes(&[id]).expect("decode").len();
}
bytes
}
fn report(text: &str, ids: &[u32], (encode, decode): (Duration, Duration), bytes: usize) {
eprintln!(
"text {} bytes -> {} tokens: encode {:.1} ms ({:.2} Mtok/s); decode_bytes one id at a time {:.2} us/token ({} bytes)",
text.len(),
ids.len(),
encode.as_secs_f64() * 1e3,
ids.len() as f64 / encode.as_secs_f64() / 1e6,
decode.as_secs_f64() * 1e6 / ids.len() as f64,
bytes
);
}
+24 -12
View File
@@ -18,6 +18,28 @@ fn best<T>(repeat: usize, mut work: impl FnMut() -> T) -> (f64, T) {
(best, last.unwrap())
}
/// The next turn: the same history plus a new tail.
fn next_turn(text: &str) -> String {
let tail = concat!(
"<|im_start|>user\n<tool_response>\nsome new tool output that has not been seen before\n",
"</tool_response><|im_end|>\n<|im_start|>assistant\n<think>\n"
);
format!("{text}{tail}")
}
/// The report: sizes, then one line per mode.
fn report(text: &str, reference: &[u32], ms: [f64; 7]) {
let [reference_ms, fast_ms, first_ms, warm_ms, next_ms, decode_ms, matches_ms] = ms;
let mtok = |ms: f64| reference.len() as f64 / ms / 1e3;
println!(
"{} bytes, {} tokens\n reference (regex + string BPE) {reference_ms:8.2} ms {:6.2} Mtok/s\n fast path, no cache {fast_ms:8.2} ms {:6.2} Mtok/s\n fast path, cache cold {first_ms:8.2} ms\n cache warm (same text) {warm_ms:8.2} ms\n cache warm + new tail {next_ms:8.2} ms\n decode_bytes {decode_ms:8.2} ms\n decodes_to {matches_ms:8.2} ms",
text.len(),
reference.len(),
mtok(reference_ms),
mtok(fast_ms),
);
}
fn main() -> ExitCode {
let args: Vec<String> = env::args().collect();
if args.len() < 3 {
@@ -45,20 +67,10 @@ fn main() -> ExitCode {
assert_eq!(first, reference);
let (warm_ms, warm) = best(repeat, || tokenizer.encode(&text, true).unwrap());
assert_eq!(warm, reference);
// the next turn: the same history plus a new tail
let tail = "<|im_start|>user\n<tool_response>\nsome new tool output that has not been seen before\n</tool_response><|im_end|>\n<|im_start|>assistant\n<think>\n";
let next = format!("{text}{tail}");
let (next_ms, _) = best(1, || tokenizer.encode(&next, true).unwrap());
let (next_ms, _) = best(1, || tokenizer.encode(&next_turn(&text), true).unwrap());
let (decode_ms, bytes) = best(repeat, || tokenizer.decode_bytes(&reference).unwrap());
let (matches_ms, ok) = best(repeat, || tokenizer.decodes_to(&reference, text.as_bytes()));
assert!(ok && bytes == text.as_bytes());
let mtok = |ms: f64| reference.len() as f64 / ms / 1e3;
println!(
"{} bytes, {} tokens\n reference (regex + string BPE) {reference_ms:8.2} ms {:6.2} Mtok/s\n fast path, no cache {fast_ms:8.2} ms {:6.2} Mtok/s\n fast path, cache cold {first_ms:8.2} ms\n cache warm (same text) {warm_ms:8.2} ms\n cache warm + new tail {next_ms:8.2} ms\n decode_bytes {decode_ms:8.2} ms\n decodes_to {matches_ms:8.2} ms",
text.len(),
reference.len(),
mtok(reference_ms),
mtok(fast_ms),
);
report(&text, &reference, [reference_ms, fast_ms, first_ms, warm_ms, next_ms, decode_ms, matches_ms]);
ExitCode::SUCCESS
}
+16 -23
View File
@@ -16,20 +16,18 @@ fn main() -> ExitCode {
eprintln!("usage: chat_tokens TOKENIZER_DIR PROMPTS.txt");
return ExitCode::from(2);
}
let tokenizer = match Tokenizer::from_assets(Path::new(&args[1])) {
Ok(t) => t,
match run(&args) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("chat_tokens: tokenizer: {e}");
return ExitCode::FAILURE;
eprintln!("chat_tokens: {e}");
ExitCode::FAILURE
}
};
let text = match fs::read_to_string(&args[2]) {
Ok(t) => t,
Err(e) => {
eprintln!("chat_tokens: {}: {e}", args[2]);
return ExitCode::FAILURE;
}
};
}
}
fn run(args: &[String]) -> Result<(), String> {
let tokenizer = Tokenizer::from_assets(Path::new(&args[1])).map_err(|e| format!("tokenizer: {e}"))?;
let text = fs::read_to_string(&args[2]).map_err(|e| format!("{}: {e}", args[2]))?;
for line in text.lines().map(str::trim) {
if line.is_empty() || line.starts_with('#') {
continue;
@@ -37,16 +35,11 @@ fn main() -> ExitCode {
let turn = format!(
"<|im_start|>user\n{line}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
);
match tokenizer.encode(&turn, true) {
Ok(ids) => {
let ids: Vec<String> = ids.iter().map(u32::to_string).collect();
println!("{}", ids.join(","));
}
Err(e) => {
eprintln!("chat_tokens: encode: {e}");
return ExitCode::FAILURE;
}
}
let ids = tokenizer
.encode(&turn, true)
.map_err(|e| format!("encode: {e}"))?;
let ids: Vec<String> = ids.iter().map(u32::to_string).collect();
println!("{}", ids.join(","));
}
ExitCode::SUCCESS
Ok(())
}
+51 -39
View File
@@ -19,19 +19,38 @@ fn main() {
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 (gguf, tok) = load(&path);
if info {
print_specials(&gguf, &tok);
return;
}
let run = |text: &str| print_ids(&tok, text, special, json);
if args.is_empty() {
for line in std::io::stdin().lock().lines() {
run(&line.expect("stdin"));
}
} else {
for text in &args {
run(text);
}
}
}
fn flag(args: &mut Vec<String>, name: &str) -> bool {
let before = args.len();
args.retain(|a| a != name);
args.len() != before
}
fn load(path: &str) -> (Gguf, GgufBpe) {
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")),
BufReader::with_capacity(1 << 20, File::open(Path::new(path)).expect("open")),
size,
)
.expect("valid GGUF");
@@ -44,40 +63,33 @@ fn main() {
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 {
(gguf, tok)
}
fn print_specials(gguf: &Gguf, tok: &GgufBpe) {
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!(
"[{}]",
ids.iter().map(u32::to_string).collect::<Vec<_>>().join(",")
"{id}\t{:?}\t{}",
types[id as usize],
tok.token_text(id).unwrap_or("")
);
} 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);
}
}
}
fn print_ids(tok: &GgufBpe, text: &str, special: bool, json: bool) {
let ids = tok.encode(text, special);
if json {
println!(
"[{}]",
ids.iter().map(u32::to_string).collect::<Vec<_>>().join(",")
);
} else {
println!("{ids:?} -> {:?}", tok.decode(&ids));
}
}
+50 -58
View File
@@ -21,64 +21,7 @@ fn main() -> ExitCode {
eprintln!("usage: long_prompts TOKENIZER_DIR CORPUS.txt OUT_DIR TOKENS...");
return ExitCode::from(2);
}
let tokenizer = match Tokenizer::from_assets(Path::new(&args[1])) {
Ok(t) => t,
Err(e) => {
eprintln!("long_prompts: tokenizer: {e}");
return ExitCode::FAILURE;
}
};
let corpus = match fs::read_to_string(&args[2]) {
Ok(t) => t,
Err(e) => {
eprintln!("long_prompts: {}: {e}", args[2]);
return ExitCode::FAILURE;
}
};
let out_dir = Path::new(&args[3]);
if let Err(e) = fs::create_dir_all(out_dir) {
eprintln!("long_prompts: {}: {e}", args[3]);
return ExitCode::FAILURE;
}
let encode = |text: &str, special: bool| {
tokenizer
.encode(text, special)
.map_err(|e| format!("encode: {e}"))
};
let run = || -> Result<(), String> {
let head = encode(PREAMBLE, true)?;
let tail = encode(QUESTION, true)?;
let body = encode(&corpus, false)?;
eprintln!(
"long_prompts: corpus {} bytes = {} tokens",
corpus.len(),
body.len()
);
for size in &args[4..] {
let size: usize = size.parse().map_err(|_| format!("bad size {size}"))?;
let room = size
.checked_sub(head.len() + tail.len())
.ok_or("size below the fixed parts")?;
if room > body.len() {
return Err(format!(
"corpus has {} tokens, {size} needs {room}",
body.len()
));
}
let ids: Vec<String> = head
.iter()
.chain(&body[..room])
.chain(&tail)
.map(u32::to_string)
.collect();
let path = out_dir.join(format!("prompt-{size}.ids"));
fs::write(&path, ids.join(",") + "\n")
.map_err(|e| format!("{}: {e}", path.display()))?;
eprintln!("long_prompts: {} ({} tokens)", path.display(), ids.len());
}
Ok(())
};
match run() {
match run(&args) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("long_prompts: {e}");
@@ -86,3 +29,52 @@ fn main() -> ExitCode {
}
}
}
fn encode(tokenizer: &Tokenizer, text: &str, special: bool) -> Result<Vec<u32>, String> {
tokenizer
.encode(text, special)
.map_err(|e| format!("encode: {e}"))
}
fn run(args: &[String]) -> Result<(), String> {
let tokenizer = Tokenizer::from_assets(Path::new(&args[1])).map_err(|e| format!("tokenizer: {e}"))?;
let corpus = fs::read_to_string(&args[2]).map_err(|e| format!("{}: {e}", args[2]))?;
let out_dir = Path::new(&args[3]);
fs::create_dir_all(out_dir).map_err(|e| format!("{}: {e}", args[3]))?;
let head = encode(&tokenizer, PREAMBLE, true)?;
let tail = encode(&tokenizer, QUESTION, true)?;
let body = encode(&tokenizer, &corpus, false)?;
eprintln!(
"long_prompts: corpus {} bytes = {} tokens",
corpus.len(),
body.len()
);
for size in &args[4..] {
write_prompt(out_dir, size, [&head, &body, &tail])?;
}
Ok(())
}
/// One prompt of exactly `size` tokens: the head, as much of the body as fits, the tail.
fn write_prompt(out_dir: &Path, size: &str, [head, body, tail]: [&[u32]; 3]) -> Result<(), String> {
let size: usize = size.parse().map_err(|_| format!("bad size {size}"))?;
let room = size
.checked_sub(head.len() + tail.len())
.ok_or("size below the fixed parts")?;
if room > body.len() {
return Err(format!(
"corpus has {} tokens, {size} needs {room}",
body.len()
));
}
let ids: Vec<String> = head
.iter()
.chain(&body[..room])
.chain(tail)
.map(u32::to_string)
.collect();
let path = out_dir.join(format!("prompt-{size}.ids"));
fs::write(&path, ids.join(",") + "\n").map_err(|e| format!("{}: {e}", path.display()))?;
eprintln!("long_prompts: {} ({} tokens)", path.display(), ids.len());
Ok(())
}
+68 -44
View File
@@ -23,14 +23,7 @@ impl Tokenizer {
} else {
self.bpe_scan(&mapped)
};
for token in parts {
ids.push(
*self
.vocab
.get(&token)
.ok_or("BPE produced a token outside the vocabulary")?,
);
}
self.push_ids(parts, &mut ids)?;
offset = piece.end();
}
if offset != text.len() {
@@ -39,6 +32,18 @@ impl Tokenizer {
Ok(ids)
}
fn push_ids(&self, parts: Vec<String>, ids: &mut Vec<u32>) -> Result<()> {
for token in parts {
ids.push(
*self
.vocab
.get(&token)
.ok_or("BPE produced a token outside the vocabulary")?,
);
}
Ok(())
}
pub(super) fn rank(&self, left: &str, right: &str) -> Option<usize> {
self.ranks.get(&pair_key(left, right)).copied()
}
@@ -62,54 +67,22 @@ impl Tokenizer {
}
pub(super) fn bpe_heap(&self, word: &str) -> Vec<String> {
let mut nodes: Vec<Node> = word
.chars()
.enumerate()
.map(|(index, ch)| Node {
text: ch.to_string(),
prev: index.checked_sub(1),
next: Some(index + 1),
version: 0,
alive: true,
})
.collect();
if let Some(last) = nodes.last_mut() {
last.next = None;
}
let mut nodes = char_nodes(word);
let mut heap = BinaryHeap::new();
for left in 0..nodes.len().saturating_sub(1) {
self.push_pair(&nodes, left, &mut heap);
}
while let Some(Reverse((_, left, right, left_version, right_version))) = heap.pop() {
if !nodes[left].alive
|| !nodes[right].alive
|| nodes[left].next != Some(right)
|| nodes[left].version != left_version
|| nodes[right].version != right_version
{
if is_stale(&nodes, (left, right), (left_version, right_version)) {
continue;
}
let successor = nodes[right].next;
let merged = std::mem::take(&mut nodes[right].text);
nodes[left].text.push_str(&merged);
nodes[left].next = successor;
nodes[left].version += 1;
nodes[right].alive = false;
if let Some(next) = successor {
nodes[next].prev = Some(left);
}
join_nodes(&mut nodes, left, right);
self.push_pair(&nodes, left, &mut heap);
if let Some(prev) = nodes[left].prev {
self.push_pair(&nodes, prev, &mut heap);
}
}
let mut parts = Vec::new();
let mut current = (!nodes.is_empty()).then_some(0);
while let Some(index) = current {
parts.push(std::mem::take(&mut nodes[index].text));
current = nodes[index].next;
}
parts
take_parts(&mut nodes)
}
pub(super) fn push_pair(&self, nodes: &[Node], left: usize, heap: &mut BinaryHeap<Reverse<HeapEntry>>) {
@@ -138,3 +111,54 @@ pub(super) fn pair_key(left: &str, right: &str) -> String {
key.push_str(right);
key
}
/// One node per character, linked in order.
fn char_nodes(word: &str) -> Vec<Node> {
let mut nodes: Vec<Node> = word
.chars()
.enumerate()
.map(|(index, ch)| Node {
text: ch.to_string(),
prev: index.checked_sub(1),
next: Some(index + 1),
version: 0,
alive: true,
})
.collect();
if let Some(last) = nodes.last_mut() {
last.next = None;
}
nodes
}
/// A queued merge is stale when a neighbour was joined or removed after it was queued.
fn is_stale(nodes: &[Node], (left, right): (usize, usize), (left_version, right_version): (u64, u64)) -> bool {
!nodes[left].alive
|| !nodes[right].alive
|| nodes[left].next != Some(right)
|| nodes[left].version != left_version
|| nodes[right].version != right_version
}
/// Join `right` into `left`.
fn join_nodes(nodes: &mut [Node], left: usize, right: usize) {
let successor = nodes[right].next;
let merged = std::mem::take(&mut nodes[right].text);
nodes[left].text.push_str(&merged);
nodes[left].next = successor;
nodes[left].version += 1;
nodes[right].alive = false;
if let Some(next) = successor {
nodes[next].prev = Some(left);
}
}
fn take_parts(nodes: &mut [Node]) -> Vec<String> {
let mut parts = Vec::new();
let mut current = (!nodes.is_empty()).then_some(0);
while let Some(index) = current {
parts.push(std::mem::take(&mut nodes[index].text));
current = nodes[index].next;
}
parts
}
+129 -95
View File
@@ -19,49 +19,15 @@ pub struct Tokenizer {
impl Tokenizer {
pub fn from_assets(path: &Path) -> Result<Self> {
let config: Config = serde_json::from_slice(&fs::read(path.join("tokenizer.json"))?)?;
if config.model != "gpt2" || config.pre != "qwen35" || config.pre_pattern != QWEN35_PATTERN {
return Err("unsupported tokenizer model, pre-tokenizer, or pattern".into());
}
let vocab: HashMap<String, u32> = serde_json::from_slice(&fs::read(path.join("vocab.json"))?)?;
if vocab.len() != config.vocab_size || vocab.is_empty() {
return Err("tokenizer vocabulary size mismatch".into());
}
let mut ordered = vec![None; vocab.len()];
for (token, &id) in &vocab {
let slot = ordered
.get_mut(id as usize)
.ok_or("tokenizer ID exceeds vocabulary length")?;
if slot.replace(token.clone()).is_some() {
return Err("duplicate tokenizer ID".into());
}
}
let tokens = ordered
.into_iter()
.collect::<Option<Vec<_>>>()
.ok_or("tokenizer IDs are not contiguous")?;
if tokens.iter().any(|token| token.contains('\0')) {
return Err("tokenizer vocabulary contains a NUL character".into());
}
let config = read_config(path)?;
let tokens = read_tokens(path, &config)?;
let merge_text = fs::read_to_string(path.join("merges.txt"))?;
let merges: Vec<&str> = if merge_text.is_empty() {
Vec::new()
} else {
merge_text.split('\n').collect()
};
if merges.len() != config.n_merges {
return Err("tokenizer merge count mismatch".into());
}
let merges = split_merges(&merge_text, config.n_merges)?;
let token_types: Option<Vec<u32>> = serde_json::from_slice(&fs::read(path.join("token_type.json"))?)?;
if token_types.as_ref().is_some_and(|types| types.len() != tokens.len()) {
return Err("token type count mismatch".into());
check_type_count(&token_types, tokens.len())?;
if config.special_ids.values().any(|&id| id as usize >= tokens.len()) {
return Err("special token ID exceeds vocabulary".into());
}
for &id in config.special_ids.values() {
if id as usize >= tokens.len() {
return Err("special token ID exceeds vocabulary".into());
}
}
drop(vocab);
Self::from_vocabulary(
&config.model,
&config.pre,
@@ -82,64 +48,18 @@ impl Tokenizer {
if model != "gpt2" || pre != "qwen35" {
return Err("unsupported tokenizer configuration".into());
}
if tokens.is_empty() || tokens.len() > u32::MAX as usize {
return Err("vocabulary size mismatch".into());
}
let mut vocab = HashMap::with_capacity(tokens.len());
for (id, token) in tokens.iter().enumerate() {
if token.is_empty() || token.contains('\0') || vocab.insert(token.clone(), id as u32).is_some() {
return Err("vocabulary contains NUL or duplicate tokens".into());
}
}
if token_types.as_ref().is_some_and(|types| types.len() != tokens.len()) {
return Err("token type count mismatch".into());
}
let mut ranks = HashMap::with_capacity(merges.len());
for (rank, merge) in merges.iter().enumerate() {
let Some((left, right)) = merge.split_once(' ') else {
return Err("BPE merge is not a pair".into());
};
if left.is_empty()
|| right.is_empty()
|| right.contains(' ')
|| !vocab.contains_key(left)
|| !vocab.contains_key(right)
|| ranks.insert(pair_key(left, right), rank).is_some()
{
return Err("BPE merge is invalid or duplicated".into());
}
}
let vocab = vocab_of(&tokens)?;
check_type_count(&token_types, tokens.len())?;
let ranks = ranks_of(&merges, &vocab)?;
let types = token_types.unwrap_or_default();
let always = literal_matcher(&tokens, &types, false)?;
let special = literal_matcher(&tokens, &types, true)?;
let marks = LiteralMarks::new(
types
.iter()
.enumerate()
.filter(|(_, kind)| matches!(**kind, 3 | 4))
.map(|(id, _)| tokens[id].as_str()),
)?;
let marks = marks_of(&tokens, &types)?;
let pattern = Regex::new(QWEN35_PATTERN)?;
let (byte_chars, char_bytes) = byte_alphabet();
let pairs: Vec<(String, String)> = merges
.iter()
.filter_map(|merge| merge.split_once(' '))
.map(|(left, right)| (left.to_owned(), right.to_owned()))
.collect();
// Kill switches for an operator who suspects the fast path: `LELEKA_TOKENIZER_REFERENCE=1` runs the original
// implementation only; `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB=n` sizes the segment cache (0 turns it off).
let reference_only = std::env::var_os("LELEKA_TOKENIZER_REFERENCE").is_some_and(|v| v == "1");
let fast = if reference_only {
None
} else {
fast::Fast::build(&vocab, &pairs, &byte_chars)
};
let cache_budget = std::env::var("LELEKA_TOKENIZER_SEGMENT_CACHE_MIB")
.ok()
.and_then(|value| value.parse::<usize>().ok())
.map_or(cache::DEFAULT_BUDGET, |mib| mib << 20);
let decode_table = DecodeTable::new(&tokens, &char_bytes);
Ok(Self {
fast: fast_path(&vocab, &merges, &byte_chars),
decode_table: DecodeTable::new(&tokens, &char_bytes),
vocab,
ranks,
pattern,
@@ -147,9 +67,7 @@ impl Tokenizer {
special,
marks,
byte_chars,
decode_table,
fast,
segments: cache::SegmentCache::new(cache_budget),
segments: cache::SegmentCache::new(segment_cache_budget()),
})
}
@@ -178,3 +96,119 @@ impl Tokenizer {
&self.marks
}
}
fn read_config(path: &Path) -> Result<Config> {
let config: Config = serde_json::from_slice(&fs::read(path.join("tokenizer.json"))?)?;
if config.model != "gpt2" || config.pre != "qwen35" || config.pre_pattern != QWEN35_PATTERN {
return Err("unsupported tokenizer model, pre-tokenizer, or pattern".into());
}
Ok(config)
}
/// The vocabulary of `vocab.json` as a list indexed by token ID.
fn read_tokens(path: &Path, config: &Config) -> Result<Vec<String>> {
let vocab: HashMap<String, u32> = serde_json::from_slice(&fs::read(path.join("vocab.json"))?)?;
if vocab.len() != config.vocab_size || vocab.is_empty() {
return Err("tokenizer vocabulary size mismatch".into());
}
let mut ordered = vec![None; vocab.len()];
for (token, &id) in &vocab {
let slot = ordered
.get_mut(id as usize)
.ok_or("tokenizer ID exceeds vocabulary length")?;
if slot.replace(token.clone()).is_some() {
return Err("duplicate tokenizer ID".into());
}
}
let tokens = ordered
.into_iter()
.collect::<Option<Vec<_>>>()
.ok_or("tokenizer IDs are not contiguous")?;
if tokens.iter().any(|token| token.contains('\0')) {
return Err("tokenizer vocabulary contains a NUL character".into());
}
Ok(tokens)
}
fn split_merges(merge_text: &str, n_merges: usize) -> Result<Vec<&str>> {
let merges: Vec<&str> = if merge_text.is_empty() {
Vec::new()
} else {
merge_text.split('\n').collect()
};
if merges.len() != n_merges {
return Err("tokenizer merge count mismatch".into());
}
Ok(merges)
}
fn check_type_count(token_types: &Option<Vec<u32>>, tokens: usize) -> Result<()> {
if token_types.as_ref().is_some_and(|types| types.len() != tokens) {
return Err("token type count mismatch".into());
}
Ok(())
}
fn vocab_of(tokens: &[String]) -> Result<HashMap<String, u32>> {
if tokens.is_empty() || tokens.len() > u32::MAX as usize {
return Err("vocabulary size mismatch".into());
}
let mut vocab = HashMap::with_capacity(tokens.len());
for (id, token) in tokens.iter().enumerate() {
if token.is_empty() || token.contains('\0') || vocab.insert(token.clone(), id as u32).is_some() {
return Err("vocabulary contains NUL or duplicate tokens".into());
}
}
Ok(vocab)
}
fn ranks_of(merges: &[String], vocab: &HashMap<String, u32>) -> Result<HashMap<String, usize>> {
let mut ranks = HashMap::with_capacity(merges.len());
for (rank, merge) in merges.iter().enumerate() {
let Some((left, right)) = merge.split_once(' ') else {
return Err("BPE merge is not a pair".into());
};
if left.is_empty()
|| right.is_empty()
|| right.contains(' ')
|| !vocab.contains_key(left)
|| !vocab.contains_key(right)
|| ranks.insert(pair_key(left, right), rank).is_some()
{
return Err("BPE merge is invalid or duplicated".into());
}
}
Ok(ranks)
}
fn marks_of(tokens: &[String], types: &[u32]) -> Result<LiteralMarks> {
Ok(LiteralMarks::new(
types
.iter()
.enumerate()
.filter(|(_, kind)| matches!(**kind, 3 | 4))
.map(|(id, _)| tokens[id].as_str()),
)?)
}
/// Kill switch for an operator who suspects the fast path: `LELEKA_TOKENIZER_REFERENCE=1` runs the original
/// implementation only.
fn fast_path(vocab: &HashMap<String, u32>, merges: &[String], byte_chars: &[char; 256]) -> Option<fast::Fast> {
if std::env::var_os("LELEKA_TOKENIZER_REFERENCE").is_some_and(|v| v == "1") {
return None;
}
let pairs: Vec<(String, String)> = merges
.iter()
.filter_map(|merge| merge.split_once(' '))
.map(|(left, right)| (left.to_owned(), right.to_owned()))
.collect();
fast::Fast::build(vocab, &pairs, byte_chars)
}
/// `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB=n` sizes the segment cache (0 turns it off).
fn segment_cache_budget() -> usize {
std::env::var("LELEKA_TOKENIZER_SEGMENT_CACHE_MIB")
.ok()
.and_then(|value| value.parse::<usize>().ok())
.map_or(cache::DEFAULT_BUDGET, |mib| mib << 20)
}
+14 -7
View File
@@ -4,7 +4,8 @@
use super::*;
impl Tokenizer {
/// Token ids of a rendered prompt whose message text went through [`LiteralMarks::mark`] before the chat template ran:
/// Token ids of a rendered prompt whose message text went through [`LiteralMarks::mark`] before the chat template
/// ran:
/// the literals the template wrote parse as special tokens, exactly as `encode(prompt, true)` does, and every mark
/// is turned back into its literal and encoded as ordinary text. For a prompt without marks this is
/// `encode(prompt, true)`. The token count of a prompt is the length of this, never of `encode(.., true)` on the
@@ -86,12 +87,7 @@ impl Tokenizer {
None
};
let mark = ids.len();
let mut at = 0;
while at < text.len() {
let end = fast.classes.piece_end(text, at);
fast.encode_piece(&text.as_bytes()[at..end], ids, scratch);
at = end;
}
encode_pieces(fast, text, ids, scratch);
if let Some(key) = key {
self.segments.insert(key, text, &ids[mark..]);
}
@@ -116,3 +112,14 @@ impl Tokenizer {
Ok(ids)
}
}
/// Pre-tokenize `text` with the table-driven scanner and merge each piece.
#[inline]
fn encode_pieces(fast: &fast::Fast, text: &str, ids: &mut Vec<u32>, scratch: &mut fast::Scratch) {
let mut at = 0;
while at < text.len() {
let end = fast.classes.piece_end(text, at);
fast.encode_piece(&text.as_bytes()[at..end], ids, scratch);
at = end;
}
}
+114 -80
View File
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use std::{cmp::Reverse, collections::BinaryHeap};
impl Fast {
/// `None` when the vocabulary is not one the id-based merge reproduces exactly (see the module notes).
@@ -53,86 +54,47 @@ impl Fast {
}
ranks.clear();
for pair in parts.windows(2) {
ranks.push(
self.pairs
.get(pair[0], pair[1])
.map_or(NO_RANK, |(rank, _)| rank),
);
ranks.push(self.rank_of(pair[0], pair[1]));
}
loop {
let mut best = NO_RANK;
let mut at = 0;
for (index, &rank) in ranks.iter().enumerate() {
if rank < best {
best = rank;
at = index;
}
}
if best == NO_RANK {
break;
}
let (_, merged) = self
.pairs
.get(parts[at], parts[at + 1])
.expect("ranked pair is in the table");
parts[at] = merged;
parts.remove(at + 1);
ranks.remove(at);
if at > 0 {
ranks[at - 1] = self
.pairs
.get(parts[at - 1], parts[at])
.map_or(NO_RANK, |(rank, _)| rank);
}
if at + 1 < parts.len() {
ranks[at] = self
.pairs
.get(parts[at], parts[at + 1])
.map_or(NO_RANK, |(rank, _)| rank);
}
while let Some(at) = lowest_rank(ranks) {
self.merge_at(parts, ranks, at);
}
out.extend_from_slice(parts);
}
#[inline]
fn rank_of(&self, left: u32, right: u32) -> u32 {
self.pairs.get(left, right).map_or(NO_RANK, |(rank, _)| rank)
}
/// Join the pair at `at` and refresh the ranks of its two new neighbours.
#[inline]
fn merge_at(&self, parts: &mut Vec<u32>, ranks: &mut Vec<u32>, at: usize) {
let (_, merged) = self
.pairs
.get(parts[at], parts[at + 1])
.expect("ranked pair is in the table");
parts[at] = merged;
parts.remove(at + 1);
ranks.remove(at);
if at > 0 {
ranks[at - 1] = self.rank_of(parts[at - 1], parts[at]);
}
if at + 1 < parts.len() {
ranks[at] = self.rank_of(parts[at], parts[at + 1]);
}
}
/// The linked-list and heap form for long pieces (the same merge order: lowest rank first, leftmost on ties).
pub(super) fn merge_long(&self, parts: &mut Vec<u32>) {
use std::{cmp::Reverse, collections::BinaryHeap};
type MergeQueue = BinaryHeap<Reverse<(u32, u32, u32, u32, u32)>>;
let n = parts.len();
let mut next: Vec<usize> = (1..=n).collect();
let mut prev: Vec<isize> = (0..n as isize).map(|i| i - 1).collect();
let mut alive = vec![true; n];
let mut version = vec![0u32; n];
let mut queue: MergeQueue = BinaryHeap::new();
let push = |queue: &mut MergeQueue,
parts: &[u32],
next: &[usize],
version: &[u32],
left: usize| {
let right = next[left];
if right < n
&& let Some((rank, _)) = self.pairs.get(parts[left], parts[right])
{
queue.push(Reverse((
rank,
left as u32,
right as u32,
version[left],
version[right],
)));
}
};
let mut links = Links::new(n);
for left in 0..n.saturating_sub(1) {
push(&mut queue, parts, &next, &version, left);
self.queue_pair(&mut links, parts, left);
}
while let Some(Reverse((_, left, right, left_version, right_version))) = queue.pop() {
while let Some(Reverse((_, left, right, left_version, right_version))) = links.queue.pop() {
let (left, right) = (left as usize, right as usize);
if !alive[left]
|| !alive[right]
|| next[left] != right
|| version[left] != left_version
|| version[right] != right_version
{
if links.is_stale(left, right, left_version, right_version) {
continue;
}
let (_, merged) = self
@@ -140,23 +102,95 @@ impl Fast {
.get(parts[left], parts[right])
.expect("queued pair is in the table");
parts[left] = merged;
alive[right] = false;
next[left] = next[right];
version[left] += 1;
if next[left] < n {
prev[next[left]] = left as isize;
}
push(&mut queue, parts, &next, &version, left);
if prev[left] >= 0 {
push(&mut queue, parts, &next, &version, prev[left] as usize);
links.absorb(left, right);
self.queue_pair(&mut links, parts, left);
let before = links.prev[left];
if before >= 0 {
self.queue_pair(&mut links, parts, before as usize);
}
}
*parts = links.chain(parts);
}
fn queue_pair(&self, links: &mut Links, parts: &[u32], left: usize) {
let right = links.next[left];
if right < links.next.len()
&& let Some((rank, _)) = self.pairs.get(parts[left], parts[right])
{
links.queue.push(Reverse((
rank,
left as u32,
right as u32,
links.version[left],
links.version[right],
)));
}
}
}
/// The first position holding the lowest rank, `None` when no pair can merge.
#[inline]
fn lowest_rank(ranks: &[u32]) -> Option<usize> {
let mut best = NO_RANK;
let mut at = 0;
for (index, &rank) in ranks.iter().enumerate() {
if rank < best {
best = rank;
at = index;
}
}
(best != NO_RANK).then_some(at)
}
type MergeQueue = BinaryHeap<Reverse<(u32, u32, u32, u32, u32)>>;
/// The doubly linked list of pieces and the heap of candidate merges behind [`Fast::merge_long`].
struct Links {
next: Vec<usize>,
prev: Vec<isize>,
alive: Vec<bool>,
version: Vec<u32>,
queue: MergeQueue,
}
impl Links {
fn new(n: usize) -> Self {
Self {
next: (1..=n).collect(),
prev: (0..n as isize).map(|i| i - 1).collect(),
alive: vec![true; n],
version: vec![0u32; n],
queue: BinaryHeap::new(),
}
}
/// A queued merge is stale when a neighbour was joined or removed after it was queued.
fn is_stale(&self, left: usize, right: usize, left_version: u32, right_version: u32) -> bool {
!self.alive[left]
|| !self.alive[right]
|| self.next[left] != right
|| self.version[left] != left_version
|| self.version[right] != right_version
}
/// Remove `right` from the list; `left` takes its place.
fn absorb(&mut self, left: usize, right: usize) {
self.alive[right] = false;
self.next[left] = self.next[right];
self.version[left] += 1;
if self.next[left] < self.next.len() {
self.prev[self.next[left]] = left as isize;
}
}
fn chain(&self, parts: &[u32]) -> Vec<u32> {
let n = parts.len();
let mut result = Vec::with_capacity(n);
let mut current = 0usize;
while current < n {
result.push(parts[current]);
current = next[current];
current = self.next[current];
}
*parts = result;
result
}
}
+88 -57
View File
@@ -22,34 +22,43 @@ pub(super) fn contains(ranges: &[(u32, u32)], code: u32) -> bool {
at > 0 && ranges[at - 1].1 >= code
}
type ClassSets = [(u8, Vec<(u32, u32)>); 4];
fn class_flags(sets: &ClassSets, code: u32) -> u8 {
sets.iter()
.filter(|(_, ranges)| contains(ranges, code))
.fold(0u8, |bits, (flag, _)| bits | flag)
}
/// Every code point where the class flags may change, sorted and without duplicates.
fn class_bounds(sets: &ClassSets) -> Vec<u32> {
let mut bounds = vec![0u32];
for (_, ranges) in sets {
for &(start, end) in ranges {
bounds.push(start);
bounds.push(end + 1);
}
}
bounds.sort_unstable();
bounds.dedup();
bounds.retain(|&b| b <= 0x10FFFF);
bounds
}
impl Classes {
pub fn new() -> Result<Self, String> {
let sets = [
let sets: ClassSets = [
(LETTER, unicode_ranges(r"\p{L}")?),
(MARK, unicode_ranges(r"\p{M}")?),
(NUMBER, unicode_ranges(r"\p{N}")?),
(SPACE, unicode_ranges(r"\s")?),
];
let flags_of = |code: u32| {
sets.iter()
.filter(|(_, ranges)| contains(ranges, code))
.fold(0u8, |bits, (flag, _)| bits | flag)
};
let mut ascii = [0u8; 128];
for (code, slot) in ascii.iter_mut().enumerate() {
*slot = flags_of(code as u32);
*slot = class_flags(&sets, code as u32);
}
let mut bounds = vec![0u32];
for (_, ranges) in &sets {
for &(start, end) in ranges {
bounds.push(start);
bounds.push(end + 1);
}
}
bounds.sort_unstable();
bounds.dedup();
bounds.retain(|&b| b <= 0x10FFFF);
let flags = bounds.iter().map(|&start| flags_of(start)).collect();
let bounds = class_bounds(&sets);
let flags = bounds.iter().map(|&start| class_flags(&sets, start)).collect();
Ok(Self {
ascii,
starts: bounds,
@@ -103,26 +112,32 @@ impl Classes {
/// |\s+
/// ```
///
/// with leftmost-first alternation and backtracking quantifiers. Every scalar value falls in exactly one of letter/mark,
/// number, symbol (none of the three and not white space) or white space, so some alternative always matches.
/// with leftmost-first alternation and backtracking quantifiers. Every scalar value falls in exactly one of
/// letter/mark, number, symbol (none of the three and not white space) or white space, so some alternative always matches.
pub fn piece_end(&self, text: &str, i: usize) -> usize {
let bytes = text.as_bytes();
let (flags, c, len) = self.at(text, i).expect("piece_end past the end");
// 1: contractions
if c == '\'' {
let at = |k: usize| bytes.get(i + k).copied();
match at(1) {
Some(b's' | b'S' | b't' | b'T' | b'm' | b'M' | b'd' | b'D') => return i + 2,
Some(b'r' | b'R' | b'v' | b'V') if matches!(at(2), Some(b'e' | b'E')) => {
return i + 3;
}
Some(b'l' | b'L') if matches!(at(2), Some(b'l' | b'L')) => return i + 3,
_ => {}
}
if c == '\'' && let Some(end) = contraction_end(text.as_bytes(), i) {
return end;
}
// 2: [^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+ (a mark is both a possible prefix and a letter; either reading ends in the same place)
if let Some(end) = self.prefixed_letters_end(text, i, (flags, c, len)) {
return end;
}
if flags & NUMBER != 0 {
return i + len;
}
if let Some(end) = self.symbols_end(text, i, c) {
return end;
}
debug_assert!(flags & SPACE != 0);
self.white_space_end(text, i)
}
/// 2: `[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+` (a mark is both a possible prefix and a letter; either reading ends in the
/// same place).
#[inline]
fn prefixed_letters_end(&self, text: &str, i: usize, (flags, c, len): (u8, char, usize)) -> Option<usize> {
if flags & LETTER_OR_MARK != 0 {
return self.letters_end(text, i + len);
return Some(self.letters_end(text, i + len));
}
if c != '\r'
&& c != '\n'
@@ -130,32 +145,36 @@ impl Classes {
&& let Some((next, _, _)) = self.at(text, i + len)
&& next & LETTER_OR_MARK != 0
{
return self.letters_end(text, i + len);
return Some(self.letters_end(text, i + len));
}
// 3: \p{N}
if flags & NUMBER != 0 {
return i + len;
}
// 4: ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*
None
}
/// 4: ` ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*`
#[inline]
fn symbols_end(&self, text: &str, i: usize, c: char) -> Option<usize> {
let start = if c == ' ' { i + 1 } else { i };
if let Some((first, _, _)) = self.at(text, start)
&& first & (SPACE | LETTER | MARK | NUMBER) == 0
{
let mut end = start;
while let Some((f, _, l)) = self.at(text, end) {
if f & (SPACE | LETTER | MARK | NUMBER) != 0 {
break;
}
end += l;
}
while matches!(bytes.get(end), Some(b'\r' | b'\n')) {
end += 1;
}
return end;
let (first, _, _) = self.at(text, start)?;
if first & (SPACE | LETTER | MARK | NUMBER) != 0 {
return None;
}
// 5-7: white space. \s*[\r\n]+ ends at the last line break of the run; \s+(?!\S) gives the run back one character
// unless the text ends; \s+ takes a lone character.
debug_assert!(flags & SPACE != 0);
let mut end = start;
while let Some((f, _, l)) = self.at(text, end) {
if f & (SPACE | LETTER | MARK | NUMBER) != 0 {
break;
}
end += l;
}
while matches!(text.as_bytes().get(end), Some(b'\r' | b'\n')) {
end += 1;
}
Some(end)
}
/// 5-7: white space. `\s*[\r\n]+` ends at the last line break of the run; `\s+(?!\S)` gives the run back one
/// character unless the text ends; `\s+` takes a lone character.
#[inline]
fn white_space_end(&self, text: &str, i: usize) -> usize {
let mut end = i;
let mut last_break = 0;
let mut last_len = 0;
@@ -181,6 +200,18 @@ impl Classes {
}
}
/// 1: contractions
#[inline]
fn contraction_end(bytes: &[u8], i: usize) -> Option<usize> {
let at = |k: usize| bytes.get(i + k).copied();
match at(1) {
Some(b's' | b'S' | b't' | b'T' | b'm' | b'M' | b'd' | b'D') => Some(i + 2),
Some(b'r' | b'R' | b'v' | b'V') if matches!(at(2), Some(b'e' | b'E')) => Some(i + 3),
Some(b'l' | b'L') if matches!(at(2), Some(b'l' | b'L')) => Some(i + 3),
_ => None,
}
}
impl PairTable {
pub(super) fn with_capacity(entries: usize) -> Self {
let slots = (entries * 2).max(16).next_power_of_two();
+1
View File
@@ -74,5 +74,6 @@ mod impl_ggufbpe;
#[allow(unused_imports)]
pub use impl_ggufbpe::*;
mod impl_utf8stream;
mod symbols;
#[allow(unused_imports)]
pub use impl_utf8stream::*;
+80 -1
View File
@@ -26,7 +26,7 @@ pub(super) fn byte_ids(ids: &HashMap<String, u32>, byte_char: &[char; 256]) -> R
}
/// `(left id, right id)` to `(rank, merged id)`.
type MergeMap = HashMap<(u32, u32), (u32, u32)>;
pub(super) type MergeMap = HashMap<(u32, u32), (u32, u32)>;
pub(super) fn merge_ranks(merges: &[&str], ids: &HashMap<String, u32>) -> Result<MergeMap, TokenizerError> {
let mut merge_map = HashMap::with_capacity(merges.len());
@@ -73,3 +73,82 @@ pub(super) fn check_special_ids(n_tokens: usize, specials: [Option<u32>; 3]) ->
}
Ok(())
}
/// The tokenizer must be the GPT-2 model with the GPT-4o pre-tokenizer.
pub(super) fn check_model(g: &Gguf) -> Result<(), TokenizerError> {
match g.get_str("tokenizer.ggml.model") {
Some("gpt2") => {}
other => return Err(TokenizerError::Unsupported(format!("model {other:?}"))),
}
match g.get_str("tokenizer.ggml.pre") {
Some("gpt-4o") => {}
other => {
return Err(TokenizerError::Unsupported(format!("pre-tokenizer {other:?}")));
}
}
Ok(())
}
/// The strings of the array under `key`.
pub(super) fn string_list<'a>(g: &'a Gguf, key: &str) -> Result<Vec<&'a str>, TokenizerError> {
g.get(key)
.and_then(Value::as_array)
.ok_or_else(|| TokenizerError::Missing(key.into()))?
.iter()
.map(|v| {
v.as_str()
.ok_or_else(|| TokenizerError::Invalid(format!("{key}: not a string")))
})
.collect()
}
/// The token types; every token is normal when the file has none.
pub(super) fn token_types(g: &Gguf, n_tokens: usize) -> Result<Vec<i64>, TokenizerError> {
match g.get("tokenizer.ggml.token_type") {
Some(Value::Array(a)) => a
.iter()
.map(|v| match v {
Value::I32(t) => Ok(i64::from(*t)),
Value::U32(t) => Ok(i64::from(*t)),
_ => Err(TokenizerError::Invalid("token_type: not an integer".into())),
})
.collect::<Result<_, _>>(),
_ => Ok(vec![1; n_tokens]),
}
}
/// What `from_parts` derives from the pieces before the special tokens and the pre-tokenizer.
pub(super) struct Vocabulary {
pub(super) ids: HashMap<String, u32>,
pub(super) byte_char: [char; 256],
pub(super) char_byte: HashMap<char, u8>,
pub(super) byte_id: [u32; 256],
pub(super) merges: MergeMap,
}
pub(super) fn vocabulary(tokens: &[&str], types: &[i64], merges: &[&str]) -> Result<Vocabulary, TokenizerError> {
if tokens.is_empty() || types.len() != tokens.len() {
return Err(TokenizerError::Invalid("token and type counts differ or are zero".into()));
}
let ids = token_ids(tokens)?;
let byte_char = byte_chars();
let char_byte: HashMap<char, u8> = byte_char.iter().enumerate().map(|(b, c)| (*c, b as u8)).collect();
let byte_id = byte_ids(&ids, &byte_char)?;
let merges = merge_ranks(merges, &ids)?;
Ok(Vocabulary {
ids,
byte_char,
char_byte,
byte_id,
merges,
})
}
/// Whether each token is a control or user-defined (special) token.
pub(super) fn special_flags(types: &[i64]) -> Vec<bool> {
types.iter().map(|t| *t == TYPE_CONTROL || *t == TYPE_USER_DEFINED).collect()
}
pub(super) fn pre_tokenizer() -> Result<Regex, TokenizerError> {
Regex::new(GPT4O_PATTERN).map_err(|e| TokenizerError::Invalid(format!("pre-tokenizer expression: {e}")))
}
+40 -83
View File
@@ -1,47 +1,15 @@
//! Moved out of the parent module by STRA-338: impl GgufBpe.
#[allow(unused_imports)]
use super::{build, *};
use super::{build, symbols::Symbols, *};
impl GgufBpe {
/// Read the tokenizer from the metadata of a GGUF file.
pub fn from_gguf(g: &Gguf) -> Result<Self, TokenizerError> {
match g.get_str("tokenizer.ggml.model") {
Some("gpt2") => {}
other => return Err(TokenizerError::Unsupported(format!("model {other:?}"))),
}
match g.get_str("tokenizer.ggml.pre") {
Some("gpt-4o") => {}
other => {
return Err(TokenizerError::Unsupported(format!(
"pre-tokenizer {other:?}"
)));
}
}
let strings = |key: &str| -> Result<Vec<&str>, TokenizerError> {
g.get(key)
.and_then(Value::as_array)
.ok_or_else(|| TokenizerError::Missing(key.into()))?
.iter()
.map(|v| {
v.as_str()
.ok_or_else(|| TokenizerError::Invalid(format!("{key}: not a string")))
})
.collect()
};
let tokens = strings("tokenizer.ggml.tokens")?;
let merges = strings("tokenizer.ggml.merges")?;
let types: Vec<i64> = match g.get("tokenizer.ggml.token_type") {
Some(Value::Array(a)) => a
.iter()
.map(|v| match v {
Value::I32(t) => Ok(i64::from(*t)),
Value::U32(t) => Ok(i64::from(*t)),
_ => Err(TokenizerError::Invalid("token_type: not an integer".into())),
})
.collect::<Result<_, _>>()?,
_ => vec![1; tokens.len()],
};
build::check_model(g)?;
let tokens = build::string_list(g, "tokenizer.ggml.tokens")?;
let merges = build::string_list(g, "tokenizer.ggml.merges")?;
let types = build::token_types(g, tokens.len())?;
let special_id = |key: &str| g.get_u64(key).and_then(|v| u32::try_from(v).ok());
Self::from_parts(
&tokens,
@@ -62,29 +30,21 @@ impl GgufBpe {
eos: Option<u32>,
pad: Option<u32>,
) -> Result<Self, TokenizerError> {
if tokens.is_empty() || types.len() != tokens.len() {
return Err(TokenizerError::Invalid("token and type counts differ or are zero".into()));
}
let ids = build::token_ids(tokens)?;
let byte_char = byte_chars();
let char_byte: HashMap<char, u8> = byte_char.iter().enumerate().map(|(b, c)| (*c, b as u8)).collect();
let byte_id = build::byte_ids(&ids, &byte_char)?;
let merge_map = build::merge_ranks(merges, &ids)?;
let is_special: Vec<bool> = types.iter().map(|t| *t == TYPE_CONTROL || *t == TYPE_USER_DEFINED).collect();
let vocabulary = build::vocabulary(tokens, types, merges)?;
let is_special = build::special_flags(types);
let specials = build::special_matcher(tokens, types)?;
let pattern = Regex::new(GPT4O_PATTERN)
.map_err(|e| TokenizerError::Invalid(format!("pre-tokenizer expression: {e}")))?;
let pattern = build::pre_tokenizer()?;
build::check_special_ids(tokens.len(), [bos, eos, pad])?;
Ok(Self {
tokens: tokens.iter().map(|t| (*t).to_owned()).collect(),
ids,
merges: merge_map,
ids: vocabulary.ids,
merges: vocabulary.merges,
pattern,
specials,
is_special,
byte_char,
char_byte,
byte_id,
byte_char: vocabulary.byte_char,
char_byte: vocabulary.char_byte,
byte_id: vocabulary.byte_id,
bos,
eos,
pad,
@@ -159,48 +119,45 @@ impl GgufBpe {
out.extend(ids);
return;
}
let mut prev: Vec<usize> = (0..n).map(|i| i.wrapping_sub(1)).collect();
let mut next: Vec<usize> = (1..=n).collect(); // n marks the end
let mut alive = vec![true; n];
let mut symbols = Symbols::new(n);
self.merge_by_rank(&mut ids, &mut symbols);
symbols.collect_into(&ids, out);
}
/// Join the lowest-ranked pair until none is left.
fn merge_by_rank(&self, ids: &mut [u32], symbols: &mut Symbols) {
let n = ids.len();
let mut heap = BinaryHeap::new();
let push = |heap: &mut BinaryHeap<Reverse<(u32, usize, u32, u32)>>,
left: usize,
right: usize,
ids: &[u32]| {
if let Some((rank, _)) = self.merges.get(&(ids[left], ids[right])) {
heap.push(Reverse((*rank, left, ids[left], ids[right])));
}
};
for i in 0..n - 1 {
push(&mut heap, i, i + 1, &ids);
self.queue_merge(&mut heap, i, i + 1, ids);
}
while let Some(Reverse((_, left, left_id, right_id))) = heap.pop() {
let right = next[left];
let right = symbols.next[left];
// stale entries: a symbol changed or died since the pair was queued
if !alive[left] || right >= n || !alive[right] {
continue;
}
if ids[left] != left_id || ids[right] != right_id {
if symbols.is_stale(left, right) || ids[left] != left_id || ids[right] != right_id {
continue;
}
let (_, merged) = self.merges[&(left_id, right_id)];
ids[left] = merged;
alive[right] = false;
next[left] = next[right];
if next[right] < n {
prev[next[right]] = left;
symbols.absorb(left, right);
if symbols.prev[left] != usize::MAX {
self.queue_merge(&mut heap, symbols.prev[left], left, ids);
}
if prev[left] != usize::MAX {
push(&mut heap, prev[left], left, &ids);
}
if next[left] < n {
push(&mut heap, left, next[left], &ids);
if symbols.next[left] < n {
self.queue_merge(&mut heap, left, symbols.next[left], ids);
}
}
let mut i = 0;
while i < n {
out.push(ids[i]);
i = next[i];
}
fn queue_merge(
&self,
heap: &mut BinaryHeap<Reverse<(u32, usize, u32, u32)>>,
left: usize,
right: usize,
ids: &[u32],
) {
if let Some((rank, _)) = self.merges.get(&(ids[left], ids[right])) {
heap.push(Reverse((*rank, left, ids[left], ids[right])));
}
}
+39
View File
@@ -0,0 +1,39 @@
//! The doubly linked list of symbols behind `GgufBpe::merge_piece`.
pub(super) struct Symbols {
pub(super) prev: Vec<usize>,
pub(super) next: Vec<usize>, // n marks the end
alive: Vec<bool>,
}
impl Symbols {
pub(super) fn new(n: usize) -> Self {
Self {
prev: (0..n).map(|i| i.wrapping_sub(1)).collect(),
next: (1..=n).collect(),
alive: vec![true; n],
}
}
/// Whether the pair starting at `left` is gone: a symbol died since the pair was queued.
pub(super) fn is_stale(&self, left: usize, right: usize) -> bool {
!self.alive[left] || right >= self.next.len() || !self.alive[right]
}
/// Join `right` into `left`.
pub(super) fn absorb(&mut self, left: usize, right: usize) {
self.alive[right] = false;
self.next[left] = self.next[right];
if self.next[right] < self.next.len() {
self.prev[self.next[right]] = left;
}
}
pub(super) fn collect_into(&self, ids: &[u32], out: &mut Vec<u32>) {
let mut i = 0;
while i < ids.len() {
out.push(ids[i]);
i = self.next[i];
}
}
}
+22 -13
View File
@@ -9,8 +9,8 @@
//!
//! 1. **before the template renders**, [`LiteralMarks::mark`] swaps each special literal in a message's text for one
//! private-use character (plane 15, `U+F0E01` upward). The template then prints the mark like any other text.
//! 2. **when the rendered prompt is encoded**, [`crate::Tokenizer::encode_marked`] parses the template's own literals as
//! special tokens as before, and turns each mark back into its literal text and encodes that as ordinary text.
//! 2. **when the rendered prompt is encoded**, [`crate::Tokenizer::encode_marked`] parses the template's own literals
//! as special tokens as before, and turns each mark back into its literal text and encodes that as ordinary text.
//!
//! Text that already contains one of the mark characters is escaped with `U+F0E00` by `mark`, so a round trip
//! (`unmark(mark(text)) == text`) holds for every string and a client cannot forge a mark.
@@ -135,17 +135,7 @@ impl LiteralMarks {
let mut changed = false;
while let Some(c) = chars.next() {
if c == ESCAPE {
match chars.next() {
Some(next) if self.owns(next) => {
out.push(next);
changed = true;
}
Some(next) => {
out.push(c);
out.push(next);
}
None => out.push(c),
}
changed |= self.unescape(&mut chars, &mut out);
} else if let Some(literal) = self.literal_of(c) {
out.push_str(literal);
changed = true;
@@ -160,6 +150,25 @@ impl LiteralMarks {
}
}
/// Resolve the character after an escape into `out`; whether it dropped the escape.
fn unescape(&self, chars: &mut std::str::Chars, out: &mut String) -> bool {
match chars.next() {
Some(next) if self.owns(next) => {
out.push(next);
true
}
Some(next) => {
out.push(ESCAPE);
out.push(next);
false
}
None => {
out.push(ESCAPE);
false
}
}
}
/// Whether `text` holds a mark (a literal that is to be encoded as ordinary text).
pub fn has_marks(&self, text: &str) -> bool {
if !text.as_bytes().contains(&PLANE_15_LEAD) {