aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-inference-abi / src / bitnet_tokenizer.rs
| 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 | //! Our own tokenizer for BitNet b1.58 2B-4T (stage T2): the LLaMA-3 byte-level BPE read from the |
| 17 | //! checkpoint's `tokenizer.json`, with no tokenizer library in the path. |
| 18 | //! |
| 19 | //! What it implements, and where each rule comes from (spec section 4): |
| 20 | //! - Special tokens are cut out of the text first (the 256 `added_tokens`, all `special`, |
| 21 | //! `normalized: false`), longest match at the leftmost position. |
| 22 | //! - The pre-tokenizer splits with the LLaMA-3 pattern (`tokenizer.json` pre_tokenizer, and |
| 23 | //! `REF/tokenizer.py:43`), here a hand-written scanner that follows the regex's leftmost, |
| 24 | //! first-alternative, greedy-with-backtracking semantics exactly: |
| 25 | //! `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`. |
| 26 | //! `\p{L}`, `\p{N}`, `\s` and the case folds come from the Unicode tables of `regex-syntax` |
| 27 | //! (data only; no regex engine runs). |
| 28 | //! - Each piece's UTF-8 bytes map to the GPT-2 byte alphabet; `ignore_merges: true` means a |
| 29 | //! piece that is itself a vocabulary entry is one token; otherwise BPE merges the adjacent pair |
| 30 | //! of lowest merge rank, leftmost first, until none applies. |
| 31 | //! - BOS 128000 is prepended when asked (the `TemplateProcessing` post-processor). |
| 32 | |
| 33 | use std::collections::HashMap; |
| 34 | use std::path::Path; |
| 35 | |
| 36 | use regex_syntax::hir::{Class, HirKind}; |
| 37 | |
| 38 | /// The split pattern this scanner implements; any other pattern is refused. |
| 39 | pub const LLAMA3_SPLIT_PATTERN: &str = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"; |
| 40 | |
| 41 | /// The contractions of the first alternative, in pattern order. |
| 42 | const CONTRACTIONS: [&str; 7] = ["s", "t", "re", "ve", "m", "ll", "d"]; |
| 43 | |
| 44 | /// A sorted, disjoint set of inclusive char ranges. |
| 45 | #[derive(Debug, Clone)] |
| 46 | struct CharSet(Vec<(char, char)>); |
| 47 | |
| 48 | impl CharSet { |
| 49 | fn from_class(pattern: &str) -> Result<Self, String> { |
| 50 | let hir = regex_syntax::parse(pattern).map_err(|e| format!("class {pattern}: {e}"))?; |
| 51 | match hir.kind() { |
| 52 | HirKind::Class(Class::Unicode(c)) => Ok(Self( |
| 53 | c.ranges().iter().map(|r| (r.start(), r.end())).collect(), |
| 54 | )), |
| 55 | HirKind::Literal(_) => { |
| 56 | let c = pattern |
| 57 | .chars() |
| 58 | .last() |
| 59 | .ok_or_else(|| format!("class {pattern}: empty"))?; |
| 60 | Ok(Self(vec![(c, c)])) |
| 61 | } |
| 62 | other => Err(format!( |
| 63 | "class {pattern}: not a character class ({other:?})" |
| 64 | )), |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | fn contains(&self, c: char) -> bool { |
| 69 | self.0 |
| 70 | .binary_search_by(|&(lo, hi)| { |
| 71 | if hi < c { |
| 72 | std::cmp::Ordering::Less |
| 73 | } else if lo > c { |
| 74 | std::cmp::Ordering::Greater |
| 75 | } else { |
| 76 | std::cmp::Ordering::Equal |
| 77 | } |
| 78 | }) |
| 79 | .is_ok() |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// The character classes of the split pattern. |
| 84 | #[derive(Debug, Clone)] |
| 85 | struct Classes { |
| 86 | letter: CharSet, |
| 87 | number: CharSet, |
| 88 | space: CharSet, |
| 89 | /// Case-insensitive sets for the contraction letters, keyed by the lowercase ASCII letter. |
| 90 | folds: Vec<(char, CharSet)>, |
| 91 | } |
| 92 | |
| 93 | impl Classes { |
| 94 | fn new() -> Result<Self, String> { |
| 95 | let mut folds = Vec::new(); |
| 96 | for c in "strevmld".chars() { |
| 97 | folds.push((c, CharSet::from_class(&format!("(?i:{c})"))?)); |
| 98 | } |
| 99 | Ok(Self { |
| 100 | letter: CharSet::from_class(r"\p{L}")?, |
| 101 | number: CharSet::from_class(r"\p{N}")?, |
| 102 | space: CharSet::from_class(r"\s")?, |
| 103 | folds, |
| 104 | }) |
| 105 | } |
| 106 | |
| 107 | fn l(&self, c: char) -> bool { |
| 108 | if c.is_ascii() { |
| 109 | c.is_ascii_alphabetic() |
| 110 | } else { |
| 111 | self.letter.contains(c) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn n(&self, c: char) -> bool { |
| 116 | if c.is_ascii() { |
| 117 | c.is_ascii_digit() |
| 118 | } else { |
| 119 | self.number.contains(c) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | fn s(&self, c: char) -> bool { |
| 124 | self.space.contains(c) |
| 125 | } |
| 126 | |
| 127 | /// `[^\s\p{L}\p{N}]` |
| 128 | fn other(&self, c: char) -> bool { |
| 129 | !self.s(c) && !self.l(c) && !self.n(c) |
| 130 | } |
| 131 | |
| 132 | fn folds_to(&self, c: char, lower: char) -> bool { |
| 133 | self.folds |
| 134 | .iter() |
| 135 | .find(|(k, _)| *k == lower) |
| 136 | .is_some_and(|(_, set)| set.contains(c)) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// Splits `text` into pre-tokens with the LLaMA-3 pattern; returns char-index ranges. |
| 141 | fn split_pieces(cl: &Classes, chars: &[char]) -> Vec<(usize, usize)> { |
| 142 | let n = chars.len(); |
| 143 | let at = |i: usize| chars.get(i).copied(); |
| 144 | let mut out = Vec::new(); |
| 145 | let mut i = 0; |
| 146 | while i < n { |
| 147 | let c = chars[i]; |
| 148 | let run = |from: usize, f: &dyn Fn(char) -> bool| { |
| 149 | let mut e = from; |
| 150 | while e < n && f(chars[e]) { |
| 151 | e += 1; |
| 152 | } |
| 153 | e |
| 154 | }; |
| 155 | // 1. (?i:'s|'t|'re|'ve|'m|'ll|'d) |
| 156 | let alt1 = (c == '\'') |
| 157 | .then(|| { |
| 158 | CONTRACTIONS.iter().find_map(|w| { |
| 159 | let ok = w |
| 160 | .chars() |
| 161 | .enumerate() |
| 162 | .all(|(j, lc)| at(i + 1 + j).is_some_and(|x| cl.folds_to(x, lc))); |
| 163 | ok.then_some(i + 1 + w.len()) |
| 164 | }) |
| 165 | }) |
| 166 | .flatten(); |
| 167 | // 2. [^\r\n\p{L}\p{N}]?\p{L}+ |
| 168 | let alt2 = || { |
| 169 | if cl.l(c) { |
| 170 | Some(run(i, &|x| cl.l(x))) |
| 171 | } else if c != '\r' && c != '\n' && !cl.n(c) && at(i + 1).is_some_and(|x| cl.l(x)) { |
| 172 | Some(run(i + 1, &|x| cl.l(x))) |
| 173 | } else { |
| 174 | None |
| 175 | } |
| 176 | }; |
| 177 | // 3. \p{N}{1,3} |
| 178 | let alt3 = || { |
| 179 | cl.n(c).then(|| { |
| 180 | let mut e = i; |
| 181 | while e < n && e < i + 3 && cl.n(chars[e]) { |
| 182 | e += 1; |
| 183 | } |
| 184 | e |
| 185 | }) |
| 186 | }; |
| 187 | // 4. ' ?[^\s\p{L}\p{N}]+[\r\n]*' |
| 188 | let alt4 = || { |
| 189 | let start = if c == ' ' && at(i + 1).is_some_and(|x| cl.other(x)) { |
| 190 | i + 1 |
| 191 | } else if cl.other(c) { |
| 192 | i |
| 193 | } else { |
| 194 | return None; |
| 195 | }; |
| 196 | let e = run(start, &|x| cl.other(x)); |
| 197 | Some(run(e, &|x| x == '\r' || x == '\n')) |
| 198 | }; |
| 199 | // 5-7 start on whitespace; `e` is the end of the whitespace run. |
| 200 | let ws = || { |
| 201 | if !cl.s(c) { |
| 202 | return None; |
| 203 | } |
| 204 | let e = run(i, &|x| cl.s(x)); |
| 205 | // 5. \s*[\r\n]+ : greedy \s* backs off to the last newline of the run, and the |
| 206 | // newline run from there ends at the next non-newline. |
| 207 | if let Some(last) = (i..e).rev().find(|&j| chars[j] == '\r' || chars[j] == '\n') { |
| 208 | return Some(last + 1); |
| 209 | } |
| 210 | // 6. \s+(?!\S) : the whole run at the end of text, else all but its last char. |
| 211 | if e == n { |
| 212 | return Some(e); |
| 213 | } |
| 214 | if e - i >= 2 { |
| 215 | return Some(e - 1); |
| 216 | } |
| 217 | // 7. \s+ |
| 218 | Some(e) |
| 219 | }; |
| 220 | let end = alt1 |
| 221 | .or_else(alt2) |
| 222 | .or_else(alt3) |
| 223 | .or_else(alt4) |
| 224 | .or_else(ws) |
| 225 | // Every char is a letter, number, whitespace or other, so one alternative matched. |
| 226 | .unwrap_or(i + 1); |
| 227 | out.push((i, end)); |
| 228 | i = end; |
| 229 | } |
| 230 | out |
| 231 | } |
| 232 | |
| 233 | /// GPT-2's byte-to-char alphabet: printable bytes stand for themselves, the rest move to 256+. |
| 234 | fn byte_alphabet() -> [char; 256] { |
| 235 | let mut map = ['\0'; 256]; |
| 236 | let mut next = 256u32; |
| 237 | for b in 0..256u32 { |
| 238 | let printable = |
| 239 | (33..=126).contains(&b) || (161..=172).contains(&b) || (174..=255).contains(&b); |
| 240 | let cp = if printable { |
| 241 | b |
| 242 | } else { |
| 243 | let v = next; |
| 244 | next += 1; |
| 245 | v |
| 246 | }; |
| 247 | map[b as usize] = char::from_u32(cp).expect("alphabet char"); |
| 248 | } |
| 249 | map |
| 250 | } |
| 251 | |
| 252 | /// The BitNet 2B-4T tokenizer, built from `tokenizer.json`. |
| 253 | #[derive(Debug, Clone)] |
| 254 | pub struct BitNetTokenizer { |
| 255 | classes: Classes, |
| 256 | /// Base vocabulary keyed by raw bytes. |
| 257 | vocab: HashMap<Vec<u8>, u32>, |
| 258 | /// `(left, right) -> (rank, merged)`. |
| 259 | merges: HashMap<(u32, u32), (u32, u32)>, |
| 260 | /// Every id's bytes (specials as their UTF-8 text), for decoding. |
| 261 | id_bytes: Vec<Vec<u8>>, |
| 262 | /// Special tokens by text, longest first. |
| 263 | specials: Vec<(String, u32)>, |
| 264 | byte_id: [u32; 256], |
| 265 | pub bos: u32, |
| 266 | } |
| 267 | |
| 268 | impl BitNetTokenizer { |
| 269 | pub fn from_file(path: &Path) -> Result<Self, String> { |
| 270 | let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; |
| 271 | Self::from_json(&text) |
| 272 | } |
| 273 | |
| 274 | /// Reads `tokenizer.json`; every setting this scanner does not implement is refused by name. |
| 275 | pub fn from_json(text: &str) -> Result<Self, String> { |
| 276 | let j: serde_json::Value = |
| 277 | serde_json::from_str(text).map_err(|e| format!("tokenizer.json: {e}"))?; |
| 278 | if !j["normalizer"].is_null() { |
| 279 | return Err("tokenizer.json: a normalizer is set (none is implemented)".into()); |
| 280 | } |
| 281 | let m = &j["model"]; |
| 282 | let want = |k: &str, v: serde_json::Value| -> Result<(), String> { |
| 283 | if m[k] != v { |
| 284 | return Err(format!("tokenizer.json: model.{k} is {}, need {v}", m[k])); |
| 285 | } |
| 286 | Ok(()) |
| 287 | }; |
| 288 | want("type", "BPE".into())?; |
| 289 | want("ignore_merges", true.into())?; |
| 290 | want("byte_fallback", false.into())?; |
| 291 | want("dropout", serde_json::Value::Null)?; |
| 292 | want("continuing_subword_prefix", serde_json::Value::Null)?; |
| 293 | want("end_of_word_suffix", serde_json::Value::Null)?; |
| 294 | let pre = &j["pre_tokenizer"]; |
| 295 | let parts = pre["pretokenizers"].as_array(); |
| 296 | let ok_pre = pre["type"] == "Sequence" |
| 297 | && parts.is_some_and(|p| { |
| 298 | p.len() == 2 |
| 299 | && p[0]["type"] == "Split" |
| 300 | && p[0]["pattern"]["Regex"] == LLAMA3_SPLIT_PATTERN |
| 301 | && p[0]["behavior"] == "Isolated" |
| 302 | && p[0]["invert"] == false |
| 303 | && p[1]["type"] == "ByteLevel" |
| 304 | && p[1]["add_prefix_space"] == false |
| 305 | && p[1]["use_regex"] == false |
| 306 | }); |
| 307 | if !ok_pre { |
| 308 | return Err( |
| 309 | "tokenizer.json: pre_tokenizer is not the LLaMA-3 split then ByteLevel".into(), |
| 310 | ); |
| 311 | } |
| 312 | |
| 313 | let alphabet = byte_alphabet(); |
| 314 | let mut unmap = HashMap::new(); |
| 315 | for (b, &c) in alphabet.iter().enumerate() { |
| 316 | unmap.insert(c, b as u8); |
| 317 | } |
| 318 | let to_bytes = |s: &str| -> Result<Vec<u8>, String> { |
| 319 | s.chars() |
| 320 | .map(|c| { |
| 321 | unmap.get(&c).copied().ok_or_else(|| { |
| 322 | format!("vocab entry {s:?}: char {c:?} not in the byte alphabet") |
| 323 | }) |
| 324 | }) |
| 325 | .collect() |
| 326 | }; |
| 327 | |
| 328 | let vocab_json = m["vocab"] |
| 329 | .as_object() |
| 330 | .ok_or("tokenizer.json: model.vocab is not an object")?; |
| 331 | let mut vocab = HashMap::with_capacity(vocab_json.len()); |
| 332 | let mut id_bytes: Vec<Option<Vec<u8>>> = Vec::new(); |
| 333 | for (s, id) in vocab_json { |
| 334 | let id = id |
| 335 | .as_u64() |
| 336 | .and_then(|v| u32::try_from(v).ok()) |
| 337 | .ok_or_else(|| format!("vocab entry {s:?}: id {id} is not a token id"))?; |
| 338 | let bytes = to_bytes(s)?; |
| 339 | if vocab.insert(bytes.clone(), id).is_some() { |
| 340 | return Err(format!("vocab entry {s:?}: duplicate bytes")); |
| 341 | } |
| 342 | if id_bytes.len() <= id as usize { |
| 343 | id_bytes.resize(id as usize + 1, None); |
| 344 | } |
| 345 | if id_bytes[id as usize].replace(bytes).is_some() { |
| 346 | return Err(format!("vocab id {id} used twice")); |
| 347 | } |
| 348 | } |
| 349 | let mut byte_id = [0u32; 256]; |
| 350 | for b in 0..=255u8 { |
| 351 | byte_id[b as usize] = *vocab |
| 352 | .get(&vec![b]) |
| 353 | .ok_or_else(|| format!("byte {b} has no vocabulary entry"))?; |
| 354 | } |
| 355 | |
| 356 | let mut specials = Vec::new(); |
| 357 | for t in j["added_tokens"] |
| 358 | .as_array() |
| 359 | .ok_or("tokenizer.json: added_tokens is not a list")? |
| 360 | { |
| 361 | let id = t["id"] |
| 362 | .as_u64() |
| 363 | .and_then(|v| u32::try_from(v).ok()) |
| 364 | .ok_or_else(|| format!("added token {t}: no id"))?; |
| 365 | let content = t["content"] |
| 366 | .as_str() |
| 367 | .ok_or_else(|| format!("added token {id}: no content"))?; |
| 368 | if t["special"] != true |
| 369 | || t["normalized"] != false |
| 370 | || t["lstrip"] != false |
| 371 | || t["rstrip"] != false |
| 372 | || t["single_word"] != false |
| 373 | || !content.starts_with("<|") |
| 374 | { |
| 375 | return Err(format!( |
| 376 | "added token {id} {content:?}: only plain special tokens starting with <| are implemented" |
| 377 | )); |
| 378 | } |
| 379 | if id_bytes.len() <= id as usize { |
| 380 | id_bytes.resize(id as usize + 1, None); |
| 381 | } |
| 382 | if id_bytes[id as usize] |
| 383 | .replace(content.as_bytes().to_vec()) |
| 384 | .is_some() |
| 385 | { |
| 386 | return Err(format!("added token {id} {content:?} reuses an id")); |
| 387 | } |
| 388 | specials.push((content.to_string(), id)); |
| 389 | } |
| 390 | specials.sort_by_key(|(s, _)| std::cmp::Reverse(s.len())); |
| 391 | let id_bytes = id_bytes |
| 392 | .into_iter() |
| 393 | .enumerate() |
| 394 | .map(|(i, b)| b.ok_or_else(|| format!("token id {i} is missing"))) |
| 395 | .collect::<Result<Vec<_>, _>>()?; |
| 396 | |
| 397 | let merges_json = m["merges"] |
| 398 | .as_array() |
| 399 | .ok_or("tokenizer.json: model.merges is not a list")?; |
| 400 | let mut merges = HashMap::with_capacity(merges_json.len()); |
| 401 | for (rank, mj) in merges_json.iter().enumerate() { |
| 402 | let (a, b) = match mj { |
| 403 | serde_json::Value::String(s) => s |
| 404 | .split_once(' ') |
| 405 | .ok_or_else(|| format!("merge {rank} {s:?}: no space"))?, |
| 406 | serde_json::Value::Array(p) if p.len() == 2 => ( |
| 407 | p[0].as_str() |
| 408 | .ok_or_else(|| format!("merge {rank}: not text"))?, |
| 409 | p[1].as_str() |
| 410 | .ok_or_else(|| format!("merge {rank}: not text"))?, |
| 411 | ), |
| 412 | other => return Err(format!("merge {rank}: {other} is not a pair")), |
| 413 | }; |
| 414 | let (ba, bb) = (to_bytes(a)?, to_bytes(b)?); |
| 415 | let id = |x: &Vec<u8>| { |
| 416 | vocab.get(x).copied().ok_or_else(|| { |
| 417 | format!("merge {rank} {a:?} {b:?}: a side is not in the vocabulary") |
| 418 | }) |
| 419 | }; |
| 420 | let joined = [ba.as_slice(), bb.as_slice()].concat(); |
| 421 | let key = (id(&ba)?, id(&bb)?); |
| 422 | let merged = id(&joined)?; |
| 423 | merges.entry(key).or_insert((rank as u32, merged)); |
| 424 | } |
| 425 | |
| 426 | let bos = j["post_processor"]["processors"] |
| 427 | .as_array() |
| 428 | .and_then(|ps| { |
| 429 | ps.iter() |
| 430 | .find(|p| p["type"] == "TemplateProcessing") |
| 431 | .and_then(|p| p["special_tokens"]["<|begin_of_text|>"]["ids"][0].as_u64()) |
| 432 | }) |
| 433 | .and_then(|v| u32::try_from(v).ok()) |
| 434 | .ok_or("tokenizer.json: no <|begin_of_text|> in the template post-processor")?; |
| 435 | |
| 436 | Ok(Self { |
| 437 | classes: Classes::new()?, |
| 438 | vocab, |
| 439 | merges, |
| 440 | id_bytes, |
| 441 | specials, |
| 442 | byte_id, |
| 443 | bos, |
| 444 | }) |
| 445 | } |
| 446 | |
| 447 | /// Vocabulary size including the special tokens. |
| 448 | pub fn vocab_len(&self) -> usize { |
| 449 | self.id_bytes.len() |
| 450 | } |
| 451 | |
| 452 | /// Encodes `text`, BOS first when `bos`. |
| 453 | pub fn encode(&self, text: &str, bos: bool) -> Vec<u32> { |
| 454 | let mut out = Vec::new(); |
| 455 | if bos { |
| 456 | out.push(self.bos); |
| 457 | } |
| 458 | let mut rest = text; |
| 459 | while !rest.is_empty() { |
| 460 | // Leftmost special token, longest at that position. |
| 461 | let found = rest.match_indices("<|").find_map(|(at, _)| { |
| 462 | self.specials |
| 463 | .iter() |
| 464 | .find(|(s, _)| rest[at..].starts_with(s.as_str())) |
| 465 | .map(|(s, id)| (at, s.len(), *id)) |
| 466 | }); |
| 467 | match found { |
| 468 | Some((at, len, id)) => { |
| 469 | self.encode_plain(&rest[..at], &mut out); |
| 470 | out.push(id); |
| 471 | rest = &rest[at + len..]; |
| 472 | } |
| 473 | None => { |
| 474 | self.encode_plain(rest, &mut out); |
| 475 | rest = ""; |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | out |
| 480 | } |
| 481 | |
| 482 | fn encode_plain(&self, text: &str, out: &mut Vec<u32>) { |
| 483 | let chars: Vec<char> = text.chars().collect(); |
| 484 | let mut buf = [0u8; 4]; |
| 485 | for (a, b) in split_pieces(&self.classes, &chars) { |
| 486 | let mut bytes = Vec::new(); |
| 487 | for &c in &chars[a..b] { |
| 488 | bytes.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()); |
| 489 | } |
| 490 | self.bpe(&bytes, out); |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | /// One pre-token: whole if it is a vocabulary entry (`ignore_merges`), else ranked merges. |
| 495 | fn bpe(&self, bytes: &[u8], out: &mut Vec<u32>) { |
| 496 | if let Some(&id) = self.vocab.get(bytes) { |
| 497 | out.push(id); |
| 498 | return; |
| 499 | } |
| 500 | let mut sym: Vec<u32> = bytes.iter().map(|&b| self.byte_id[b as usize]).collect(); |
| 501 | loop { |
| 502 | let best = sym |
| 503 | .windows(2) |
| 504 | .enumerate() |
| 505 | .filter_map(|(p, w)| self.merges.get(&(w[0], w[1])).map(|&(r, m)| (r, p, m))) |
| 506 | .min_by_key(|&(r, p, _)| (r, p)); |
| 507 | match best { |
| 508 | Some((_, p, m)) => { |
| 509 | sym[p] = m; |
| 510 | sym.remove(p + 1); |
| 511 | } |
| 512 | None => break, |
| 513 | } |
| 514 | } |
| 515 | out.extend_from_slice(&sym); |
| 516 | } |
| 517 | |
| 518 | /// The text of `ids` (invalid UTF-8 replaced); an unknown id is refused. |
| 519 | pub fn decode(&self, ids: &[u32]) -> Result<String, String> { |
| 520 | let mut bytes = Vec::new(); |
| 521 | for &id in ids { |
| 522 | bytes.extend_from_slice( |
| 523 | self.id_bytes |
| 524 | .get(id as usize) |
| 525 | .ok_or_else(|| format!("token id {id} outside the vocabulary"))?, |
| 526 | ); |
| 527 | } |
| 528 | Ok(String::from_utf8_lossy(&bytes).into_owned()) |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | #[cfg(test)] |
| 533 | mod tests { |
| 534 | use super::*; |
| 535 | |
| 536 | fn pieces(text: &str) -> Vec<String> { |
| 537 | let cl = Classes::new().unwrap(); |
| 538 | let chars: Vec<char> = text.chars().collect(); |
| 539 | split_pieces(&cl, &chars) |
| 540 | .into_iter() |
| 541 | .map(|(a, b)| chars[a..b].iter().collect()) |
| 542 | .collect() |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | fn split_follows_the_llama3_pattern() { |
| 547 | assert_eq!( |
| 548 | pieces("The capital of France is"), |
| 549 | ["The", " capital", " of", " France", " is"] |
| 550 | ); |
| 551 | assert_eq!( |
| 552 | pieces("Count from 6 to 10:"), |
| 553 | ["Count", " from", " ", "6", " to", " ", "10", ":"] |
| 554 | ); |
| 555 | assert_eq!(pieces("12345"), ["123", "45"]); |
| 556 | assert_eq!(pieces("I'm, they'LL"), ["I", "'m", ",", " they", "'LL"]); |
| 557 | assert_eq!(pieces("x'ſ"), ["x", "'ſ"]); |
| 558 | assert_eq!(pieces("'xy"), ["'xy"]); |
| 559 | assert_eq!(pieces("a b"), ["a", " ", " b"]); |
| 560 | assert_eq!(pieces("a \n\n b"), ["a", " \n\n", " b"]); |
| 561 | assert_eq!(pieces("a.\n\nB"), ["a", ".\n\n", "B"]); |
| 562 | assert_eq!(pieces("x "), ["x", " "]); |
| 563 | assert_eq!(pieces("x \t!"), ["x", " ", "\t", "!"]); |
| 564 | assert_eq!(pieces("x !!"), ["x", " ", " !!"]); |
| 565 | assert_eq!(pieces("\tword"), ["\tword"]); |
| 566 | assert_eq!(pieces("über 3½"), ["über", " ", "3½"]); |
| 567 | assert_eq!(pieces("a\r\n \r\nb"), ["a", "\r\n \r\n", "b"]); |
| 568 | assert_eq!( |
| 569 | pieces("it'ſ \u{3000}x; über-naïve 12345 ٣٤٥ 🙂🙂\u{200d} end "), |
| 570 | [ |
| 571 | "it", |
| 572 | "'ſ", |
| 573 | " ", |
| 574 | "\u{3000}x", |
| 575 | ";", |
| 576 | " ", |
| 577 | " über", |
| 578 | "-naïve", |
| 579 | " ", |
| 580 | "123", |
| 581 | "45", |
| 582 | " ", |
| 583 | "٣٤٥", |
| 584 | " 🙂🙂\u{200d}", |
| 585 | " end", |
| 586 | " " |
| 587 | ] |
| 588 | ); |
| 589 | } |
| 590 | |
| 591 | #[test] |
| 592 | fn byte_alphabet_is_gpt2s() { |
| 593 | let a = byte_alphabet(); |
| 594 | assert_eq!(a[b' ' as usize], 'Ġ'); |
| 595 | assert_eq!(a[b'\n' as usize], 'Ċ'); |
| 596 | assert_eq!(a[b'A' as usize], 'A'); |
| 597 | assert_eq!(a[0xAD], char::from_u32(256 + 33 + 34).unwrap()); |
| 598 | let mut seen: Vec<char> = a.to_vec(); |
| 599 | seen.sort(); |
| 600 | seen.dedup(); |
| 601 | assert_eq!(seen.len(), 256); |
| 602 | } |
| 603 | |
| 604 | /// A toy vocabulary: bytes plus "ab", "abc", "Ġab"; merges a b, ab c, Ġ ab. |
| 605 | fn toy() -> BitNetTokenizer { |
| 606 | let a = byte_alphabet(); |
| 607 | let mut vocab = serde_json::Map::new(); |
| 608 | for (b, c) in a.iter().enumerate() { |
| 609 | vocab.insert(c.to_string(), (b as u64).into()); |
| 610 | } |
| 611 | vocab.insert("ab".into(), 256.into()); |
| 612 | vocab.insert("abc".into(), 257.into()); |
| 613 | vocab.insert("Ġab".into(), 258.into()); |
| 614 | vocab.insert("bc".into(), 259.into()); |
| 615 | let j = serde_json::json!({ |
| 616 | "normalizer": null, |
| 617 | "pre_tokenizer": {"type": "Sequence", "pretokenizers": [ |
| 618 | {"type": "Split", "pattern": {"Regex": LLAMA3_SPLIT_PATTERN}, "behavior": "Isolated", "invert": false}, |
| 619 | {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true, "use_regex": false}]}, |
| 620 | "post_processor": {"type": "Sequence", "processors": [{"type": "TemplateProcessing", |
| 621 | "special_tokens": {"<|begin_of_text|>": {"ids": [260]}}}]}, |
| 622 | "added_tokens": [ |
| 623 | {"id": 260, "content": "<|begin_of_text|>", "special": true, "normalized": false, "lstrip": false, "rstrip": false, "single_word": false}, |
| 624 | {"id": 261, "content": "<|eot_id|>", "special": true, "normalized": false, "lstrip": false, "rstrip": false, "single_word": false}], |
| 625 | "model": {"type": "BPE", "ignore_merges": true, "byte_fallback": false, "dropout": null, |
| 626 | "continuing_subword_prefix": null, "end_of_word_suffix": null, |
| 627 | "vocab": vocab, "merges": ["b c", "a b", "ab c", "Ġ ab"]} |
| 628 | }); |
| 629 | BitNetTokenizer::from_json(&j.to_string()).unwrap() |
| 630 | } |
| 631 | |
| 632 | #[test] |
| 633 | fn bpe_merges_by_rank_and_specials_split_out() { |
| 634 | let t = toy(); |
| 635 | // "abc" is in the vocabulary: one token even though "b c" outranks "a b". |
| 636 | assert_eq!(t.encode("abc", false), [257]); |
| 637 | // "abd": "a b" merges; "abcc" would merge "b c" first (rank 0) then nothing joins "a". |
| 638 | assert_eq!(t.encode("abd", false), [256, b'd' as u32]); |
| 639 | assert_eq!(t.encode("abcc", false), [b'a' as u32, 259, b'c' as u32]); |
| 640 | assert_eq!(t.encode("x ab", true), [260, b'x' as u32, 258]); |
| 641 | assert_eq!( |
| 642 | t.encode("a<|eot_id|>b", false), |
| 643 | [b'a' as u32, 261, b'b' as u32] |
| 644 | ); |
| 645 | assert_eq!( |
| 646 | t.decode(&[260, 258, 261]).unwrap(), |
| 647 | "<|begin_of_text|> ab<|eot_id|>" |
| 648 | ); |
| 649 | assert!(t.decode(&[999]).is_err()); |
| 650 | } |
| 651 | |
| 652 | #[test] |
| 653 | fn unimplemented_settings_are_refused_by_name() { |
| 654 | let mut j: serde_json::Value = serde_json::json!({"normalizer": {"type": "NFC"}}); |
| 655 | assert!(BitNetTokenizer::from_json(&j.to_string()) |
| 656 | .unwrap_err() |
| 657 | .contains("normalizer")); |
| 658 | j = serde_json::json!({"normalizer": null, "model": {"type": "BPE", "ignore_merges": false}}); |
| 659 | assert!(BitNetTokenizer::from_json(&j.to_string()) |
| 660 | .unwrap_err() |
| 661 | .contains("ignore_merges")); |
| 662 | } |
| 663 | } |