lispm-llm / src /tokenizer.rs
Ryan.K
Add native Rust training and inference with tch-rs
fac4d07 unverified
Raw History Blame Contribute Delete
8.33 kB
//! Exact ASCII token and variable-output BLAKE2b character encoding.
use std::collections::{BTreeSet, HashMap};
use std::sync::OnceLock;
use blake2::Blake2bVar;
use blake2::digest::{Update, VariableOutput};
use regex::Regex;
use tch::Tensor;
use thiserror::Error;
use crate::config::{ConfigError, ModelConfig};
/// One unpadded clause, including the leading CLS token.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Encoded {
/// Whole-word vocabulary identifiers.
pub word_ids: Vec<i64>,
/// Fixed-length character-fragment identifiers for each token.
pub char_ids: Vec<Vec<i64>>,
}
/// Recoverable failures of encoding and batch construction.
#[derive(Debug, Error)]
pub enum TokenizerError {
/// Architecture dimensions are invalid.
#[error(transparent)]
Config(#[from] ConfigError),
/// The fixed token pattern could not compile.
#[error("token regex failed: {0}")]
Pattern(String),
/// A reserved word is missing from the vocabulary.
#[error("missing reserved vocabulary token: {0}")]
Reserved(&'static str),
/// A clause has no words or exceeds the fixed maximum.
#[error("a command must contain between 1 and {maximum} words; received {actual}")]
WordCount {
/// Number of tokenized words.
actual: usize,
/// Maximum permitted words.
maximum: usize,
},
/// Checked shape arithmetic failed.
#[error("encoded dimensions exceed supported integer ranges")]
Dimensions,
/// Hash construction or finalization failed.
#[error("BLAKE2b encoding failed")]
Hash,
/// A batch cannot be empty.
#[error("cannot collate an empty batch")]
EmptyBatch,
/// Public encoded values are inconsistent or outside token ranges.
#[error("invalid encoded row {0}")]
InvalidRow(usize),
/// LibTorch failed to construct the batch tensors.
#[error(transparent)]
Tensor(#[from] tch::TchError),
}
/// Match the Python pattern `NAME|[a-z]+(?:-[a-z]+)*` without changing case.
pub fn tokenize(phrase: &str) -> Result<Vec<String>, TokenizerError> {
static PATTERN: OnceLock<Result<Regex, regex::Error>> = OnceLock::new();
let regex = PATTERN
.get_or_init(|| Regex::new(r"NAME|[a-z]+(?:-[a-z]+)*"))
.as_ref()
.map_err(|error| TokenizerError::Pattern(error.to_string()))?;
Ok(regex
.find_iter(phrase)
.map(|matched| matched.as_str().to_owned())
.collect())
}
/// Build identifiers from sorted training words only, preserving reserved slots.
pub fn make_vocab(rows: &[(String, String)]) -> Result<HashMap<String, i64>, TokenizerError> {
let mut words = BTreeSet::new();
for (phrase, _) in rows {
words.extend(tokenize(phrase)?);
}
["<pad>", "<unk>", "<cls>"]
.into_iter()
.map(str::to_owned)
.chain(words)
.enumerate()
.map(|(index, word)| {
i64::try_from(index)
.map(|id| (word, id))
.map_err(|_| TokenizerError::Dimensions)
})
.collect()
}
/// Hash ASCII byte windows in 2/3/4 order using an eight-byte BLAKE2b digest.
/// Truncation happens before zero padding, exactly as in the Python encoder.
fn ngrams(word: &str, config: &ModelConfig) -> Result<Vec<i64>, TokenizerError> {
let maximum = usize::try_from(config.max_ngrams).map_err(|_| TokenizerError::Dimensions)?;
let buckets = u64::try_from(config.char_buckets - 1).map_err(|_| TokenizerError::Dimensions)?;
let padded = format!("<{word}>");
let mut hashes = Vec::with_capacity(maximum);
for size in [2, 3, 4] {
for piece in padded.as_bytes().windows(size) {
if hashes.len() == maximum {
break;
}
let mut hasher = Blake2bVar::new(8).map_err(|_| TokenizerError::Hash)?;
hasher.update(piece);
let mut digest = [0_u8; 8];
hasher
.finalize_variable(&mut digest)
.map_err(|_| TokenizerError::Hash)?;
let bucket = 1 + u64::from_le_bytes(digest) % buckets;
hashes.push(i64::try_from(bucket).map_err(|_| TokenizerError::Dimensions)?);
}
}
hashes.resize(maximum, 0);
Ok(hashes)
}
/// Encode all words, using character fragments even for an unknown whole word.
pub fn encode(
phrase: &str,
vocab: &HashMap<String, i64>,
config: &ModelConfig,
) -> Result<Encoded, TokenizerError> {
config.validate()?;
let words = tokenize(phrase)?;
let maximum =
usize::try_from((config.max_words - 1).min(58)).map_err(|_| TokenizerError::Dimensions)?;
if words.is_empty() || words.len() > maximum {
return Err(TokenizerError::WordCount {
actual: words.len(),
maximum,
});
}
let cls = *vocab
.get("<cls>")
.ok_or(TokenizerError::Reserved("<cls>"))?;
let unknown = *vocab
.get("<unk>")
.ok_or(TokenizerError::Reserved("<unk>"))?;
let char_width = usize::try_from(config.max_ngrams).map_err(|_| TokenizerError::Dimensions)?;
let mut word_ids = vec![cls];
let mut char_ids = vec![vec![0; char_width]];
for word in words {
word_ids.push(vocab.get(&word).copied().unwrap_or(unknown));
char_ids.push(ngrams(&word, config)?);
}
Ok(Encoded { word_ids, char_ids })
}
/// Pad CPU int64 batches with zeros without altering any unpadded encoding.
pub fn collate(
encoded: &[Encoded],
config: &ModelConfig,
) -> Result<(Tensor, Tensor), TokenizerError> {
config.validate()?;
let width = encoded
.iter()
.map(|row| row.word_ids.len())
.max()
.ok_or(TokenizerError::EmptyBatch)?;
let char_width = usize::try_from(config.max_ngrams).map_err(|_| TokenizerError::Dimensions)?;
let word_count = encoded
.len()
.checked_mul(width)
.ok_or(TokenizerError::Dimensions)?;
let char_count = word_count
.checked_mul(char_width)
.ok_or(TokenizerError::Dimensions)?;
let mut words = Vec::with_capacity(word_count);
let mut chars = Vec::with_capacity(char_count);
for (index, row) in encoded.iter().enumerate() {
let valid = !row.word_ids.is_empty()
&& row.word_ids.len() == row.char_ids.len()
&& row.word_ids.iter().all(|id| *id >= 0)
&& row.char_ids.iter().all(|ids| {
ids.len() == char_width
&& ids.iter().all(|id| (0..config.char_buckets).contains(id))
});
if !valid {
return Err(TokenizerError::InvalidRow(index));
}
words.extend(&row.word_ids);
words.resize(words.len() + width - row.word_ids.len(), 0);
chars.extend(row.char_ids.iter().flatten().copied());
let padding = (width - row.word_ids.len())
.checked_mul(char_width)
.ok_or(TokenizerError::Dimensions)?;
chars.resize(
chars
.len()
.checked_add(padding)
.ok_or(TokenizerError::Dimensions)?,
0,
);
}
let batch = i64::try_from(encoded.len()).map_err(|_| TokenizerError::Dimensions)?;
let width = i64::try_from(width).map_err(|_| TokenizerError::Dimensions)?;
Ok((
Tensor::f_from_slice(&words)?.f_reshape([batch, width])?,
Tensor::f_from_slice(&chars)?.f_reshape([batch, width, config.max_ngrams])?,
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_pattern_keeps_name_and_hyphens_but_does_not_lowercase() -> Result<(), TokenizerError> {
assert_eq!(
tokenize("NAME open-file HTTP hello123WORLD")?,
["NAME", "open-file", "hello"]
);
Ok(())
}
#[test]
fn unknown_words_retain_nonzero_character_fragments() -> Result<(), TokenizerError> {
let config = ModelConfig::default();
let vocabulary = make_vocab(&[("split right".into(), "x".into())])?;
let encoded = encode("unseen", &vocabulary, &config)?;
assert_eq!(encoded.word_ids, [2, 1]);
assert!(encoded.char_ids.iter().skip(1).flatten().any(|id| *id != 0));
assert!(matches!(
collate(&[], &config),
Err(TokenizerError::EmptyBatch)
));
Ok(())
}
}