Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-infer/src/tokenizer.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-infer / src / tokenizer.rs` 510 lines · 16549 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Llama-3 byte-level BPE tokenizer built from the GGUF `tokenizer.ggml.*` 17 //! arrays (pre-tokenizer `llama-bpe`). 18 //! 19 //! Adapted in structure from `crates/aienos-kernel/src/infer/tokenizer.rs` 20 //! (that one reads a custom text vocabulary; this one reads GGUF tokens and 21 //! merges and adds the llama-bpe pre-tokenizer split and the GPT-2 byte map). 22 //! No regex engine: the llama-bpe split is a hand-written matcher with the 23 //! same alternatives and backtracking as llama.cpp's regex 24 //! (`llama-vocab.cpp`, `LLAMA_VOCAB_PRE_TYPE_LLAMA3`). 25 26 use alloc::string::String; 27 use alloc::vec::Vec; 28 29 use crate::gguf::TokenizerData; 30 31 /// Why a tokenizer could not be built or a text could not be encoded. 32 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 33 pub enum TokenizerError { 34 /// `tokenizer.ggml.tokens` is empty or too large for u32 ids. 35 BadVocab, 36 /// A byte-level symbol is missing from the vocabulary. 37 MissingSymbol, 38 /// A token id is outside the vocabulary. 39 BadId(u32), 40 } 41 42 /// Longest pre-token fed to the BPE merge loop (keeps it bounded). 43 const MAX_WORD_BYTES: usize = 1024; 44 /// Longest `<|...|>` special token string recognised in text. 45 const MAX_SPECIAL_BYTES: usize = 64; 46 47 const TYPE_CONTROL: i32 = 3; 48 const TYPE_USER_DEFINED: i32 = 4; 49 50 /// GPT-2 `bytes_to_unicode`: printable bytes map to themselves, the rest to 51 /// U+0100 upward in byte order. 52 fn byte_to_char(b: u8) -> char { 53 let keep = (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b); 54 if keep { 55 return b as char; 56 } 57 // Rank of this byte among the non-kept bytes. 58 let mut n = 0u32; 59 for x in 0..b { 60 let k = (33..=126).contains(&x) || (161..=172).contains(&x) || (174..=255).contains(&x); 61 if !k { 62 n += 1; 63 } 64 } 65 char::from_u32(256 + n).expect("valid scalar") 66 } 67 68 fn char_to_byte(c: char) -> Option { 69 let cp = c as u32; 70 if cp < 256 { 71 let b = cp as u8; 72 let keep = (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b); 73 return if keep { Some(b) } else { None }; 74 } 75 if cp >= 256 { 76 let n = cp - 256; 77 let mut seen = 0u32; 78 for b in 0..=255u8 { 79 let keep = 80 (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b); 81 if !keep { 82 if seen == n { 83 return Some(b); 84 } 85 seen += 1; 86 } 87 } 88 } 89 None 90 } 91 92 /// Byte-level BPE tokenizer borrowing the GGUF strings. 93 pub struct Tokenizer<'a> { 94 tokens: Vec<&'a str>, 95 types: Vec, 96 /// `(token text, id)` sorted by text. 97 by_text: Vec<(&'a str, u32)>, 98 /// `(merge "left right", rank)` sorted by text. 99 merges: Vec<(&'a str, u32)>, 100 pub bos_id: Option, 101 pub eos_id: Option, 102 /// `<|eot_id|>` if present. 103 pub eot_id: Option, 104 /// Dense table: GPT-2 mapped char of every byte. 105 byte_chars: [char; 256], 106 } 107 108 impl<'a> Tokenizer<'a> { 109 pub fn new(data: &TokenizerData<'a>) -> Result { 110 let tokens: Vec<&'a str> = data.tokens.strings().collect(); 111 if tokens.is_empty() 112 || tokens.len() != data.tokens.len() 113 || tokens.len() > u32::MAX as usize 114 { 115 return Err(TokenizerError::BadVocab); 116 } 117 let types: Vec = match data.token_type { 118 Some(a) => a.i32s().collect(), 119 None => Vec::new(), 120 }; 121 let mut by_text: Vec<(&'a str, u32)> = tokens 122 .iter() 123 .enumerate() 124 .map(|(i, t)| (*t, i as u32)) 125 .collect(); 126 // Duplicate texts: keep the lowest id (stable sort + dedup below). 127 by_text.sort_by(|a, b| a.0.cmp(b.0).then(a.1.cmp(&b.1))); 128 by_text.dedup_by(|b, a| a.0 == b.0); 129 let mut merges: Vec<(&'a str, u32)> = match data.merges { 130 Some(m) => m 131 .strings() 132 .enumerate() 133 .map(|(i, s)| (s, i as u32)) 134 .collect(), 135 None => Vec::new(), 136 }; 137 merges.sort_by(|a, b| a.0.cmp(b.0).then(a.1.cmp(&b.1))); 138 merges.dedup_by(|b, a| a.0 == b.0); 139 let mut byte_chars = ['\0'; 256]; 140 for b in 0..=255u8 { 141 byte_chars[b as usize] = byte_to_char(b); 142 } 143 let mut t = Tokenizer { 144 tokens, 145 types, 146 by_text, 147 merges, 148 bos_id: data.bos_id, 149 eos_id: data.eos_id, 150 eot_id: None, 151 byte_chars, 152 }; 153 t.eot_id = t.lookup("<|eot_id|>"); 154 Ok(t) 155 } 156 157 pub fn vocab_size(&self) -> usize { 158 self.tokens.len() 159 } 160 161 /// Token text as stored (GPT-2 mapped). 162 pub fn token_text(&self, id: u32) -> Option<&'a str> { 163 self.tokens.get(id as usize).copied() 164 } 165 166 /// Id of an exact token text. 167 pub fn lookup(&self, text: &str) -> Option { 168 self.by_text 169 .binary_search_by(|p| p.0.cmp(text)) 170 .ok() 171 .map(|i| self.by_text[i].1) 172 } 173 174 fn merge_rank(&self, buf: &mut String, left: &str, right: &str) -> Option { 175 buf.clear(); 176 buf.push_str(left); 177 buf.push(' '); 178 buf.push_str(right); 179 self.merges 180 .binary_search_by(|p| p.0.cmp(buf.as_str())) 181 .ok() 182 .map(|i| self.merges[i].1) 183 } 184 185 fn is_special(&self, id: u32) -> bool { 186 matches!( 187 self.types.get(id as usize), 188 Some(&TYPE_CONTROL) | Some(&TYPE_USER_DEFINED) 189 ) 190 } 191 192 /// True for control tokens (printed as nothing). 193 pub fn is_control(&self, id: u32) -> bool { 194 self.types.get(id as usize) == Some(&TYPE_CONTROL) 195 } 196 197 /// Encode `text`. With `parse_special`, `<|name|>` strings that are 198 /// control or user-defined tokens become their single id. No BOS is 199 /// added (the chat template carries it). 200 pub fn encode(&self, text: &str, parse_special: bool) -> Result, TokenizerError> { 201 let mut out = Vec::new(); 202 let mut rest = text; 203 loop { 204 let hit = if parse_special { 205 self.find_special(rest) 206 } else { 207 None 208 }; 209 match hit { 210 Some((at, len, id)) => { 211 self.encode_plain(&rest[..at], &mut out)?; 212 out.push(id); 213 rest = &rest[at + len..]; 214 } 215 None => { 216 self.encode_plain(rest, &mut out)?; 217 return Ok(out); 218 } 219 } 220 } 221 } 222 223 /// First special token string in `s`: (byte offset, byte length, id). 224 fn find_special(&self, s: &str) -> Option<(usize, usize, u32)> { 225 let b = s.as_bytes(); 226 let mut i = 0; 227 while i + 1 < b.len() { 228 if b[i] == b'<' && b[i + 1] == b'|' { 229 let end = (i + MAX_SPECIAL_BYTES).min(b.len()); 230 let mut j = i + 2; 231 while j + 1 < end + 1 && j + 1 < b.len() { 232 if b[j] == b'|' && b[j + 1] == b'>' { 233 let cand = &s[i..j + 2]; 234 if let Some(id) = self.lookup(cand) { 235 if self.is_special(id) { 236 return Some((i, cand.len(), id)); 237 } 238 } 239 break; 240 } 241 j += 1; 242 } 243 } 244 i += 1; 245 } 246 None 247 } 248 249 fn encode_plain(&self, text: &str, out: &mut Vec) -> Result<(), TokenizerError> { 250 let mut mapped = String::new(); 251 let mut buf = String::new(); 252 for word in pretokenize(text) { 253 for chunk in word.as_bytes().chunks(MAX_WORD_BYTES) { 254 mapped.clear(); 255 for &b in chunk { 256 mapped.push(self.byte_chars[b as usize]); 257 } 258 self.bpe_word(&mapped, &mut buf, out)?; 259 } 260 } 261 Ok(()) 262 } 263 264 fn bpe_word( 265 &self, 266 word: &str, 267 buf: &mut String, 268 out: &mut Vec, 269 ) -> Result<(), TokenizerError> { 270 // llama-bpe sets ignore_merges: a whole pre-token in the vocab wins. 271 if let Some(id) = self.lookup(word) { 272 out.push(id); 273 return Ok(()); 274 } 275 // Symbols as (start, end) byte ranges of `word`. 276 let mut syms: Vec<(usize, usize)> = word 277 .char_indices() 278 .map(|(i, c)| (i, i + c.len_utf8())) 279 .collect(); 280 loop { 281 let mut best: Option<(u32, usize)> = None; 282 for i in 0..syms.len().saturating_sub(1) { 283 let l = &word[syms[i].0..syms[i].1]; 284 let r = &word[syms[i + 1].0..syms[i + 1].1]; 285 if let Some(rank) = self.merge_rank(buf, l, r) { 286 if best.is_none_or(|(br, _)| rank < br) { 287 best = Some((rank, i)); 288 } 289 } 290 } 291 match best { 292 Some((_, i)) => { 293 syms[i].1 = syms[i + 1].1; 294 syms.remove(i + 1); 295 } 296 None => break, 297 } 298 } 299 for (s, e) in syms { 300 out.push( 301 self.lookup(&word[s..e]) 302 .ok_or(TokenizerError::MissingSymbol)?, 303 ); 304 } 305 Ok(()) 306 } 307 308 /// Append the raw bytes of token `id` (control tokens add nothing). 309 pub fn decode_token(&self, id: u32, out: &mut Vec) -> Result<(), TokenizerError> { 310 let t = self.token_text(id).ok_or(TokenizerError::BadId(id))?; 311 if self.is_control(id) { 312 return Ok(()); 313 } 314 for c in t.chars() { 315 match char_to_byte(c) { 316 Some(b) => out.push(b), 317 None => { 318 let mut tmp = [0u8; 4]; 319 out.extend_from_slice(c.encode_utf8(&mut tmp).as_bytes()); 320 } 321 } 322 } 323 Ok(()) 324 } 325 326 /// Bytes for a whole id sequence. 327 pub fn decode(&self, ids: &[u32]) -> Result, TokenizerError> { 328 let mut out = Vec::new(); 329 for &id in ids { 330 self.decode_token(id, &mut out)?; 331 } 332 Ok(out) 333 } 334 335 /// Llama-3 instruct chat template for one user turn, ending at the 336 /// assistant header so generation starts the reply. 337 pub fn encode_chat(&self, user: &str) -> Result, TokenizerError> { 338 let mut s = String::from("<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"); 339 s.push_str(user); 340 s.push_str("<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"); 341 self.encode(&s, true) 342 } 343 } 344 345 fn is_letter(c: char) -> bool { 346 c.is_alphabetic() 347 } 348 fn is_number(c: char) -> bool { 349 c.is_numeric() 350 } 351 fn is_nl(c: char) -> bool { 352 c == '\r' || c == '\n' 353 } 354 355 /// Split `text` like the llama-bpe regex: 356 /// `(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD]) 357 /// |[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]* 358 /// |\s*[\r\n]+|\s+(?!\S)|\s+` 359 /// `\p{L}` is approximated by `char::is_alphabetic` (a superset: also 360 /// letter-numbers and a few combining marks), `\p{N}` by `char::is_numeric`. 361 pub fn pretokenize(text: &str) -> Vec<&str> { 362 let mut parts = Vec::new(); 363 let mut i = 0; 364 while i < text.len() { 365 let end = i + match_one(&text[i..]); 366 parts.push(&text[i..end]); 367 i = end; 368 } 369 parts 370 } 371 372 /// Length in bytes of the first match at the start of `s` (always >= 1). 373 fn match_one(s: &str) -> usize { 374 let mut it = s.chars(); 375 let c0 = it.next().expect("non-empty"); 376 // 1: contractions 377 if c0 == '\'' { 378 let rest = &s[1..]; 379 let low = |n: usize| -> Option<[u8; 2]> { 380 let b = rest.as_bytes(); 381 if b.len() < n { 382 return None; 383 } 384 Some([ 385 b[0].to_ascii_lowercase(), 386 if n > 1 { b[1].to_ascii_lowercase() } else { 0 }, 387 ]) 388 }; 389 if let Some([a, b]) = low(2) { 390 if (a == b'r' && b == b'e') || (a == b'v' && b == b'e') || (a == b'l' && b == b'l') { 391 return 3; 392 } 393 } 394 if let Some([a, _]) = low(1) { 395 if matches!(a, b's' | b't' | b'm' | b'd') { 396 return 2; 397 } 398 } 399 } 400 // 2: optional one char, then letters 401 if is_letter(c0) { 402 return c0.len_utf8() + run(&s[c0.len_utf8()..], is_letter); 403 } 404 if !is_nl(c0) && !is_number(c0) { 405 let l0 = c0.len_utf8(); 406 if s[l0..].chars().next().is_some_and(is_letter) { 407 return l0 + run(&s[l0..], is_letter); 408 } 409 } 410 // 3: 1..=3 digits 411 if is_number(c0) { 412 let mut len = 0; 413 for (n, c) in s.chars().enumerate() { 414 if n == 3 || !is_number(c) { 415 break; 416 } 417 len += c.len_utf8(); 418 } 419 return len; 420 } 421 // 4: optional space, symbols, trailing newlines 422 let sym = |c: char| !c.is_whitespace() && !is_letter(c) && !is_number(c); 423 { 424 let skip = if c0 == ' ' { 1 } else { 0 }; 425 let body = run(&s[skip..], sym); 426 if body > 0 { 427 let tail = run(&s[skip + body..], is_nl); 428 return skip + body + tail; 429 } 430 } 431 // 5-7: whitespace handling (c0 is whitespace here) 432 let ws = run(s, char::is_whitespace); 433 let w = &s[..ws]; 434 // 5: \s*[\r\n]+ -> through the last newline of the run 435 if let Some(p) = w.rfind(is_nl) { 436 return p + 1; // \r and \n are one byte 437 } 438 // 6: \s+(?!\S) 439 if ws == s.len() { 440 return ws; 441 } 442 let n_chars = w.chars().count(); 443 if n_chars > 1 { 444 let last = w.chars().next_back().expect("non-empty").len_utf8(); 445 return ws - last; 446 } 447 // 7: \s+ 448 ws 449 } 450 451 /// Byte length of the longest prefix whose chars all satisfy `f`. 452 fn run(s: &str, f: impl Fn(char) -> bool) -> usize { 453 let mut len = 0; 454 for c in s.chars() { 455 if !f(c) { 456 break; 457 } 458 len += c.len_utf8(); 459 } 460 len 461 } 462 463 #[cfg(test)] 464 mod tests { 465 use super::*; 466 467 #[test] 468 fn byte_map_is_gpt2() { 469 assert_eq!(byte_to_char(b'A'), 'A'); 470 assert_eq!(byte_to_char(b' '), 'Ġ'); 471 assert_eq!(byte_to_char(b'\n'), 'Ċ'); 472 assert_eq!(byte_to_char(0), 'Ā'); 473 assert_eq!(byte_to_char(127), 'ġ'); 474 assert_eq!(byte_to_char(173), 'Ń'); 475 for b in 0..=255u8 { 476 assert_eq!(char_to_byte(byte_to_char(b)), Some(b)); 477 } 478 } 479 480 fn split(s: &str) -> Vec<&str> { 481 pretokenize(s) 482 } 483 484 #[test] 485 fn pretokenize_cases() { 486 assert_eq!(split("Hello world"), ["Hello", " world"]); 487 assert_eq!( 488 split("it's I'M we'LL"), 489 ["it", "'s", " I", "'M", " we", "'LL"] 490 ); 491 assert_eq!(split("a1234b"), ["a", "123", "4", "b"]); 492 assert_eq!(split("x y"), ["x", " ", " y"]); 493 assert_eq!(split("end.\n\nnext"), ["end", ".\n\n", "next"]); 494 assert_eq!(split("a \n b"), ["a", " \n", " b"]); 495 assert_eq!(split("a "), ["a", " "]); 496 assert_eq!(split(" ,x"), [" ,", "x"]); 497 assert_eq!(split("(abc"), ["(abc"]); 498 assert_eq!(split("\n\n"), ["\n\n"]); 499 assert_eq!(split("é à"), ["é", " à"]); 500 assert_eq!(split("don't"), ["don", "'t"]); 501 assert_eq!(split("'x"), ["'x"]); 502 assert_eq!(split("1 2"), ["1", " ", "2"]); 503 } 504 505 #[test] 506 fn pretokenize_covers_input() { 507 let s = "Mixed: 12345, \t tabs\r\n\r\n and ünïcode… ok'd 99 \u{3000} end "; 508 assert_eq!(split(s).concat(), s); 509 } 510 }