STRA-338 size-fn: tokenizer: GgufBpe::from_parts split into vocabulary stages (fn>30 prod 1 fewer)
This commit is contained in:
@@ -66,6 +66,7 @@ pub struct Utf8Stream {
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
mod build;
|
||||
mod impl_fmt_display_for;
|
||||
#[allow(unused_imports)]
|
||||
pub use impl_fmt_display_for::*;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The stages of `GgufBpe::from_parts`, each checking one part of the vocabulary.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Token text to id; a repeated token is an error.
|
||||
pub(super) fn token_ids(tokens: &[&str]) -> Result<HashMap<String, u32>, TokenizerError> {
|
||||
let mut ids = HashMap::with_capacity(tokens.len());
|
||||
for (id, token) in tokens.iter().enumerate() {
|
||||
if ids.insert((*token).to_owned(), id as u32).is_some() {
|
||||
return Err(TokenizerError::Invalid(format!("duplicate token {token:?}")));
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The id of the token of every byte's character.
|
||||
pub(super) fn byte_ids(ids: &HashMap<String, u32>, byte_char: &[char; 256]) -> Result<[u32; 256], TokenizerError> {
|
||||
let mut byte_id = [u32::MAX; 256];
|
||||
for (b, c) in byte_char.iter().enumerate() {
|
||||
let mut buf = [0u8; 4];
|
||||
byte_id[b] = *ids.get(c.encode_utf8(&mut buf) as &str).ok_or_else(|| {
|
||||
TokenizerError::Invalid(format!("vocabulary lacks the token for byte {b}"))
|
||||
})?;
|
||||
}
|
||||
Ok(byte_id)
|
||||
}
|
||||
|
||||
/// `(left id, right id)` to `(rank, merged id)`.
|
||||
type MergeMap = HashMap<(u32, u32), (u32, u32)>;
|
||||
|
||||
pub(super) fn merge_ranks(merges: &[&str], ids: &HashMap<String, u32>) -> Result<MergeMap, TokenizerError> {
|
||||
let mut merge_map = HashMap::with_capacity(merges.len());
|
||||
for (rank, merge) in merges.iter().enumerate() {
|
||||
let (left, right) = merge
|
||||
.split_once(' ')
|
||||
.ok_or_else(|| TokenizerError::Invalid(format!("merge {merge:?}")))?;
|
||||
let (Some(l), Some(r)) = (ids.get(left), ids.get(right)) else {
|
||||
return Err(TokenizerError::Invalid(format!("merge {merge:?} names an unknown token")));
|
||||
};
|
||||
let Some(merged) = ids.get(&format!("{left}{right}")) else {
|
||||
continue; // a merge whose result is not a token can never apply
|
||||
};
|
||||
merge_map.entry((*l, *r)).or_insert((rank as u32, *merged));
|
||||
}
|
||||
Ok(merge_map)
|
||||
}
|
||||
|
||||
/// The literal matcher over the control and user-defined tokens.
|
||||
pub(super) fn special_matcher(tokens: &[&str], types: &[i64]) -> Result<Matcher, TokenizerError> {
|
||||
let ids: Vec<u32> = (0..tokens.len() as u32)
|
||||
.filter(|i| {
|
||||
let t = types[*i as usize];
|
||||
(t == TYPE_CONTROL || t == TYPE_USER_DEFINED) && !tokens[*i as usize].is_empty()
|
||||
})
|
||||
.collect();
|
||||
if ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let literals: Vec<&str> = ids.iter().map(|i| tokens[*i as usize]).collect();
|
||||
let search = AhoCorasickBuilder::new()
|
||||
.match_kind(MatchKind::LeftmostLongest)
|
||||
.build(&literals)
|
||||
.map_err(|e| TokenizerError::Invalid(format!("special tokens: {e}")))?;
|
||||
Ok(Some((search, ids)))
|
||||
}
|
||||
|
||||
/// The bos, eos and pad ids must name tokens.
|
||||
pub(super) fn check_special_ids(n_tokens: usize, specials: [Option<u32>; 3]) -> Result<(), TokenizerError> {
|
||||
for id in specials.into_iter().flatten() {
|
||||
if id as usize >= n_tokens {
|
||||
return Err(TokenizerError::Invalid(format!("special id {id}")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl GgufBpe.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use super::{build, *};
|
||||
|
||||
impl GgufBpe {
|
||||
/// Read the tokenizer from the metadata of a GGUF file.
|
||||
@@ -63,72 +63,18 @@ impl GgufBpe {
|
||||
pad: Option<u32>,
|
||||
) -> Result<Self, TokenizerError> {
|
||||
if tokens.is_empty() || types.len() != tokens.len() {
|
||||
return Err(TokenizerError::Invalid(
|
||||
"token and type counts differ or are zero".into(),
|
||||
));
|
||||
}
|
||||
let mut ids = HashMap::with_capacity(tokens.len());
|
||||
for (id, token) in tokens.iter().enumerate() {
|
||||
if ids.insert((*token).to_owned(), id as u32).is_some() {
|
||||
return Err(TokenizerError::Invalid(format!(
|
||||
"duplicate token {token:?}"
|
||||
)));
|
||||
}
|
||||
return Err(TokenizerError::Invalid("token and type counts differ or are zero".into()));
|
||||
}
|
||||
let ids = build::token_ids(tokens)?;
|
||||
let byte_char = byte_chars();
|
||||
let char_byte: HashMap<char, u8> = byte_char
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(b, c)| (*c, b as u8))
|
||||
.collect();
|
||||
let mut byte_id = [u32::MAX; 256];
|
||||
for (b, c) in byte_char.iter().enumerate() {
|
||||
let mut buf = [0u8; 4];
|
||||
byte_id[b] = *ids.get(c.encode_utf8(&mut buf) as &str).ok_or_else(|| {
|
||||
TokenizerError::Invalid(format!("vocabulary lacks the token for byte {b}"))
|
||||
})?;
|
||||
}
|
||||
let mut merge_map = HashMap::with_capacity(merges.len());
|
||||
for (rank, merge) in merges.iter().enumerate() {
|
||||
let (left, right) = merge
|
||||
.split_once(' ')
|
||||
.ok_or_else(|| TokenizerError::Invalid(format!("merge {merge:?}")))?;
|
||||
let (Some(l), Some(r)) = (ids.get(left), ids.get(right)) else {
|
||||
return Err(TokenizerError::Invalid(format!(
|
||||
"merge {merge:?} names an unknown token"
|
||||
)));
|
||||
};
|
||||
let Some(merged) = ids.get(&format!("{left}{right}")) else {
|
||||
continue; // a merge whose result is not a token can never apply
|
||||
};
|
||||
merge_map.entry((*l, *r)).or_insert((rank as u32, *merged));
|
||||
}
|
||||
let is_special: Vec<bool> = types
|
||||
.iter()
|
||||
.map(|t| *t == TYPE_CONTROL || *t == TYPE_USER_DEFINED)
|
||||
.collect();
|
||||
let matcher = |wanted: &dyn Fn(i64) -> bool| -> Result<Matcher, TokenizerError> {
|
||||
let ids: Vec<u32> = (0..tokens.len() as u32)
|
||||
.filter(|i| wanted(types[*i as usize]) && !tokens[*i as usize].is_empty())
|
||||
.collect();
|
||||
if ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let literals: Vec<&str> = ids.iter().map(|i| tokens[*i as usize]).collect();
|
||||
let search = AhoCorasickBuilder::new()
|
||||
.match_kind(MatchKind::LeftmostLongest)
|
||||
.build(&literals)
|
||||
.map_err(|e| TokenizerError::Invalid(format!("special tokens: {e}")))?;
|
||||
Ok(Some((search, ids)))
|
||||
};
|
||||
let specials = matcher(&|t| t == TYPE_CONTROL || t == TYPE_USER_DEFINED)?;
|
||||
let char_byte: HashMap<char, u8> = byte_char.iter().enumerate().map(|(b, c)| (*c, b as u8)).collect();
|
||||
let byte_id = build::byte_ids(&ids, &byte_char)?;
|
||||
let merge_map = build::merge_ranks(merges, &ids)?;
|
||||
let is_special: Vec<bool> = types.iter().map(|t| *t == TYPE_CONTROL || *t == TYPE_USER_DEFINED).collect();
|
||||
let specials = build::special_matcher(tokens, types)?;
|
||||
let pattern = Regex::new(GPT4O_PATTERN)
|
||||
.map_err(|e| TokenizerError::Invalid(format!("pre-tokenizer expression: {e}")))?;
|
||||
for id in [bos, eos, pad].into_iter().flatten() {
|
||||
if id as usize >= tokens.len() {
|
||||
return Err(TokenizerError::Invalid(format!("special id {id}")));
|
||||
}
|
||||
}
|
||||
build::check_special_ids(tokens.len(), [bos, eos, pad])?;
|
||||
Ok(Self {
|
||||
tokens: tokens.iter().map(|t| (*t).to_owned()).collect(),
|
||||
ids,
|
||||
|
||||
Reference in New Issue
Block a user