//! The fast path (hand-written pre-tokenizer, id-based BPE, segment cache, table decode) against the original //! implementation kept in the crate as `encode_reference` / `pre_tokenize`. //! //! * the scanner splits every Unicode scalar value, in many contexts, exactly like the regex engine; //! * fuzzed text (white space of every kind, line breaks, contractions, marks, scripts, digits, emoji) splits identically; //! * `encode` equals `encode_reference` with and without special parsing, on a cold cache, a warm cache and a cache that is //! too small to hold anything; //! * with real assets (`LELEKA_TOKENIZER_DIR`, `LELEKA_TOKENIZER_TEXTS`: a directory of UTF-8 files) the same holds on real prompts. use leleka_tokenizer::{Tokenizer, pre_tokenize, pre_tokenize_fast}; use serde_json::Value; fn golden() -> Value { serde_json::from_str(include_str!("fixtures/tokenizer_oracle.json")).unwrap() } fn strings(value: &Value) -> Vec { value .as_array() .unwrap() .iter() .map(|v| v.as_str().unwrap().to_owned()) .collect() } fn tokenizer() -> Tokenizer { let golden = golden(); let types = golden["token_types"] .as_array() .unwrap() .iter() .map(|v| v.as_u64().unwrap() as u32) .collect(); Tokenizer::from_vocabulary( "gpt2", "qwen35", strings(&golden["tokens"]), strings(&golden["merges"]), Some(types), ) .unwrap() } struct Rng(u64); impl Rng { fn next(&mut self) -> u64 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; self.0 ^= self.0 << 17; self.0 } fn below(&mut self, n: usize) -> usize { (self.next() % n as u64) as usize } } const ATOMS: &[&str] = &[ "a", "b", "e", "l", "s", "t", "x", "Z", "ll", "re", "ve", "he", "xx", "the", "Hello", " ", " ", " ", "\t", "\n", "\r", "\r\n", "\n\n", " \n", "\n ", "\u{b}", "\u{c}", "\u{85}", "\u{a0}", "\u{1680}", "\u{2003}", "\u{2028}", "\u{2029}", "\u{202f}", "\u{3000}", "\u{1c}", "\u{1f}", "'", "'s", "'S", "'t", "'T", "'re", "'RE", "'ve", "'m", "'ll", "'LL", "'d", "'x", "''", "0", "7", "42", "\u{660}", "\u{2160}", "\u{b2}", "\u{bd}", "-", ".", ",", "!", "?", "_", "(", ")", "{", "}", "[", "]", "\"", "\\", "/", "<", ">", "=", "+", "*", "#", "$", "%", "&", "@", "~", "^", "|", "`", ";", ":", "e\u{301}", "\u{301}", "\u{20dd}", "\u{200d}", "\u{200b}", "\u{feff}", "\u{ad}", "\u{e9}", "\u{df}", "\u{3b1}", "\u{4e2d}", "\u{6587}", "\u{3042}", "\u{ac00}", "\u{627}", "\u{5d0}", "\u{905}", "\u{e01}", "\u{1f600}", "\u{1f1fa}\u{1f1f8}", "\u{10000}", "\u{e000}", "\u{10ffff}", "<|im_end|>", "", ]; fn fuzz_text(rng: &mut Rng) -> String { let mut text = String::new(); for _ in 0..rng.below(14) { text.push_str(ATOMS[rng.below(ATOMS.len())]); } text } fn assert_same_split(text: &str) { let regex = pre_tokenize(text).unwrap(); let fast = pre_tokenize_fast(text); assert_eq!(regex, fast, "text {text:?}"); } #[test] fn scanner_splits_every_scalar_value_like_the_regex_in_many_contexts() { let contexts: &[(&str, &str)] = &[ ("", ""), ("a", "b"), (" ", ""), ("", " "), ("\n", ""), ("", "\n"), ("1", ""), ("'", ""), (" ", "x"), (" ", "x"), ("x", " "), ("\n ", "\n"), ("e", "\u{301}"), ]; let mut buffer = String::new(); for code in 0..=0x10FFFFu32 { let Some(c) = char::from_u32(code) else { continue; }; for (before, after) in contexts { buffer.clear(); buffer.push_str(before); buffer.push(c); buffer.push_str(after); assert_same_split(&buffer); } } } #[test] fn scanner_splits_fuzzed_text_like_the_regex() { let mut rng = Rng(0x9E3779B97F4A7C15); for _ in 0..400_000 { let text = fuzz_text(&mut rng); assert_same_split(&text); } } #[test] fn scanner_handles_the_regex_corner_cases() { for text in [ "", " ", " ", "\n", " \n", " \n x", "\n\n\n", "a b", "a \n b", "x \n\n y", "don't stop", "DON'T", "it'S fine 'RE 'vE 'Ll 'D 'M", "'", "''s", "'ss", "$100.50!", "-5", " 5", " 5", "\u{a0}word", "\t\tword", "word\t", "\u{301}\u{301}x", "e\u{301}\u{301} combining", "tail ", "tail\n ", "tail \r\n ", ] { assert_same_split(text); } } #[test] fn encode_equals_the_reference_cold_warm_and_without_a_cache() { let tokenizer = tokenizer(); assert!(tokenizer.has_fast_path()); let mut rng = Rng(0x1234_5678_9ABC_DEF1); let golden = golden(); let mut texts: Vec = golden["cases"] .as_array() .unwrap() .iter() .map(|case| case["text"].as_str().unwrap().to_owned()) .collect(); for _ in 0..3000 { // long enough that segments reach the cache threshold let mut text = String::new(); for _ in 0..rng.below(60) { text.push_str(&fuzz_text(&mut rng)); } texts.push(text); } for budget in [leleka_tokenizer::DEFAULT_SEGMENT_CACHE_BYTES, 4096, 0] { tokenizer.set_segment_cache_bytes(budget); for pass in 0..2 { for text in &texts { for special in [false, true] { assert_eq!( tokenizer.encode(text, special).unwrap(), tokenizer.encode_reference(text, special).unwrap(), "budget {budget} pass {pass} special {special} text {text:?}" ); } } } } } #[test] fn a_cache_hit_needs_the_same_text() { let tokenizer = tokenizer(); let long = "xx ".repeat(100); let other = "xx ".repeat(99) + "xy "; let first = tokenizer.encode(&long, false).unwrap(); let again = tokenizer.encode(&long, false).unwrap(); assert_eq!(first, again); assert_eq!( tokenizer.encode(&other, false).unwrap(), tokenizer.encode_reference(&other, false).unwrap() ); assert_ne!(first, tokenizer.encode(&other, false).unwrap()); let (segments, bytes) = tokenizer.segment_cache_stats(); assert!(segments >= 2 && bytes > 0); } #[test] fn decode_helpers_agree() { let tokenizer = tokenizer(); let text = "Hello, world! \u{4e2d}\u{6587} \u{1f600}<|im_end|>"; let ids = tokenizer.encode(text, true).unwrap(); assert_eq!(tokenizer.decode_bytes(&ids).unwrap(), text.as_bytes()); assert!(tokenizer.decodes_to(&ids, text.as_bytes())); assert!(!tokenizer.decodes_to(&ids, b"Hello")); assert!(!tokenizer.decodes_to(&ids[..ids.len() - 1], text.as_bytes())); assert!(!tokenizer.decodes_to(&[u32::MAX], b"")); assert!(tokenizer.decode_bytes(&[u32::MAX]).is_err()); } /// Real vocabulary and real prompts: every file of `LELEKA_TOKENIZER_TEXTS` (and the whole directory joined) encodes to the /// reference ids, cold and warm, and each prefix cut at a message boundary encodes to a prefix of the full ids' tokens /// plus the tail (the cache never changes a boundary). #[test] fn real_assets_encode_like_the_reference() { let (Some(assets), Some(texts)) = ( std::env::var_os("LELEKA_TOKENIZER_DIR"), std::env::var_os("LELEKA_TOKENIZER_TEXTS"), ) else { eprintln!("LELEKA_TOKENIZER_DIR / LELEKA_TOKENIZER_TEXTS not set: skipped"); return; }; let tokenizer = Tokenizer::from_assets(std::path::Path::new(&assets)).unwrap(); assert!(tokenizer.has_fast_path()); let mut files: Vec<_> = std::fs::read_dir(texts) .unwrap() .map(|entry| entry.unwrap().path()) .filter(|path| path.is_file()) .collect(); files.sort(); assert!(!files.is_empty()); for path in files { let text = String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into_owned(); let reference = tokenizer.encode_reference(&text, true).unwrap(); for pass in 0..2 { assert_eq!( tokenizer.encode(&text, true).unwrap(), reference, "{} pass {pass}", path.display() ); } assert!(tokenizer.decodes_to(&reference, text.as_bytes())); assert_eq!( tokenizer.encode(&text, false).unwrap(), tokenizer.encode_reference(&text, false).unwrap(), "{} plain", path.display() ); // the pre-tokenizer on the real text, piece for piece assert_eq!( pre_tokenize(&text).unwrap(), pre_tokenize_fast(&text), "{}", path.display() ); eprintln!( "{}: {} bytes -> {} tokens ok", path.display(), text.len(), reference.len() ); } }