Files
leleka/crates/tokenizer/src/lib.rs
T

81 lines
2.3 KiB
Rust

//! Native qwen35 byte-level BPE, matching the pinned Strata tokenizer oracle.
pub mod gguf_bpe;
use std::{
cmp::Reverse,
collections::{BinaryHeap, HashMap},
error::Error,
fs,
path::Path,
};
use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
use fancy_regex::Regex;
use serde::Deserialize;
mod cache;
mod fast;
mod marks;
pub use cache::{DEFAULT_BUDGET as DEFAULT_SEGMENT_CACHE_BYTES, MIN_SEGMENT_BYTES};
pub use marks::LiteralMarks;
/// Pre-tokenization expression pinned to the Qwen35 GGUF vocabulary oracle.
pub const QWEN35_PATTERN: &str = concat!(
r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])",
r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+",
r"|\p{N}",
r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*",
r"|\s*[\r\n]+",
r"|\s+(?!\S)",
r"|\s+",
);
type Result<T> = std::result::Result<T, Box<dyn Error>>;
/// The `qwen35` pre-tokenizer alone: the pieces `text` is split into before byte-level BPE. Exposed so the split can
/// be compared with Python's `regex` for every Unicode scalar value (scripts/offline/diff_tokenizer.py).
pub fn pre_tokenize(text: &str) -> Result<Vec<&str>> {
static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
let pattern = match PATTERN.get() {
Some(pattern) => pattern,
None => PATTERN.get_or_init(|| Regex::new(QWEN35_PATTERN).expect("pinned qwen35 pattern")),
};
let mut pieces = Vec::new();
for found in pattern.find_iter(text) {
pieces.push(found?.as_str());
}
Ok(pieces)
}
/// [`pre_tokenize`] by the hand-written scanner the tokenizer's fast path uses (same pieces; exposed for the
/// differential tests).
#[doc(hidden)]
pub fn pre_tokenize_fast(text: &str) -> Vec<&str> {
static CLASSES: std::sync::OnceLock<fast::Classes> = std::sync::OnceLock::new();
let classes = CLASSES.get_or_init(|| fast::Classes::new().expect("unicode classes"));
let mut pieces = Vec::new();
let mut at = 0;
while at < text.len() {
let end = classes.piece_end(text, at);
pieces.push(&text[at..end]);
at = end;
}
pieces
}
#[cfg(test)]
mod tests;
mod construction;
pub use construction::Tokenizer;
mod encoding;
mod decoding;
use decoding::DecodeTable;
mod bpe_merge;
use bpe_merge::pair_key;
mod vocabulary;
use vocabulary::{Config, LiteralMatcher, literal_matcher};
pub use vocabulary::byte_alphabet;