223 lines
8.0 KiB
Rust
223 lines
8.0 KiB
Rust
//! The tokenizer value: loading from assets or a vocabulary, the segment cache and the special tokens.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
pub struct Tokenizer {
|
|
pub(super) vocab: HashMap<String, u32>,
|
|
pub(super) ranks: HashMap<String, usize>,
|
|
pub(super) pattern: Regex,
|
|
pub(super) always: Option<LiteralMatcher>,
|
|
pub(super) special: Option<LiteralMatcher>,
|
|
pub(super) marks: LiteralMarks,
|
|
pub(super) byte_chars: [char; 256],
|
|
pub(super) decode_table: DecodeTable,
|
|
/// Table-driven pre-tokenizer and BPE; `None` for a vocabulary it cannot reproduce exactly.
|
|
pub(super) fast: Option<fast::Fast>,
|
|
pub(super) segments: cache::SegmentCache,
|
|
}
|
|
|
|
impl Tokenizer {
|
|
pub fn from_assets(path: &Path) -> Result<Self> {
|
|
let config = read_config(path)?;
|
|
let tokens = read_tokens(path, &config)?;
|
|
let merge_text = fs::read_to_string(path.join("merges.txt"))?;
|
|
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"))?)?;
|
|
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());
|
|
}
|
|
Self::from_vocabulary(
|
|
&config.model,
|
|
&config.pre,
|
|
tokens,
|
|
merges.into_iter().map(str::to_owned).collect(),
|
|
token_types,
|
|
)
|
|
}
|
|
|
|
/// Construct the same tokenizer from already verified model metadata.
|
|
pub fn from_vocabulary(
|
|
model: &str,
|
|
pre: &str,
|
|
tokens: Vec<String>,
|
|
merges: Vec<String>,
|
|
token_types: Option<Vec<u32>>,
|
|
) -> Result<Self> {
|
|
if model != "gpt2" || pre != "qwen35" {
|
|
return Err("unsupported tokenizer configuration".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, special, marks) = literal_sets(&tokens, &types)?;
|
|
let pattern = Regex::new(QWEN35_PATTERN)?;
|
|
let (byte_chars, char_bytes) = byte_alphabet();
|
|
Ok(Self {
|
|
fast: fast_path(&vocab, &merges, &byte_chars),
|
|
decode_table: DecodeTable::new(&tokens, &char_bytes),
|
|
vocab,
|
|
ranks,
|
|
pattern,
|
|
always,
|
|
special,
|
|
marks,
|
|
byte_chars,
|
|
segments: cache::SegmentCache::new(segment_cache_budget()),
|
|
})
|
|
}
|
|
|
|
/// Bound the cache of segment encodings (bytes of text and ids; 0 turns it off). The default is
|
|
/// [`DEFAULT_SEGMENT_CACHE_BYTES`].
|
|
pub fn set_segment_cache_bytes(&self, budget: usize) {
|
|
self.segments.set_budget(budget);
|
|
}
|
|
|
|
/// (segments, approximate bytes) held by the segment cache.
|
|
pub fn segment_cache_stats(&self) -> (usize, usize) {
|
|
self.segments.stats()
|
|
}
|
|
|
|
/// Whether the table-driven path is in use (it is for every real vocabulary).
|
|
pub fn has_fast_path(&self) -> bool {
|
|
self.fast.is_some()
|
|
}
|
|
|
|
pub fn special_id(&self, token: &str) -> Option<u32> {
|
|
self.vocab.get(token).copied()
|
|
}
|
|
|
|
/// The marks that keep a special literal inside a message from becoming a special token (see [`LiteralMarks`]).
|
|
pub fn marks(&self) -> &LiteralMarks {
|
|
&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)
|
|
}
|
|
|
|
/// The matchers over the always-literal and the special tokens, and the marks for the literals.
|
|
fn literal_sets(
|
|
tokens: &[String],
|
|
types: &[u32],
|
|
) -> Result<(Option<LiteralMatcher>, Option<LiteralMatcher>, LiteralMarks)> {
|
|
let always = literal_matcher(tokens, types, false)?;
|
|
let special = literal_matcher(tokens, types, true)?;
|
|
Ok((always, special, marks_of(tokens, types)?))
|
|
}
|
|
|
|
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)
|
|
}
|