File size: 8,326 Bytes
fac4d07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | //! 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(())
}
}
|