Skip to main content

kute_algorithms/
table.rs

1//! The three baseline tokenizers share one engine: a table of tokens matched
2//! greedily, longest first, against the input.
3
4use crate::{BYTES, CHAR, DICTIONARY};
5use kute_core::{check_sequence, sequence_for, CorpusFingerprint, CorpusSource, Tokenizer};
6use kute_types::{
7    CanonicalInput, KuteError, Manifest, Modality, Payload, PayloadKind, Provenance, Result, TestVector,
8    TokenEntry, TokenKind, TokenPayload, TokenSequence, TokenizerCapabilities, TrainingConfig, Vocabulary,
9    KUTE_VERSION, KVF_VERSION,
10};
11use rustc_hash::FxHashMap;
12use std::collections::{BTreeMap, BTreeSet};
13
14/// A loaded table vocabulary and the indexes needed to match against it.
15struct Table {
16    vocabulary: Vocabulary,
17    /// Byte entries longer than one byte, keyed by content.
18    entries: FxHashMap<Vec<u8>, u32>,
19    /// Lengths present in `entries`, longest first.
20    lengths: Vec<usize>,
21    symbols: FxHashMap<String, u32>,
22}
23
24impl Table {
25    fn build(mut vocabulary: Vocabulary, algorithm: &str) -> Result<Self> {
26        vocabulary.validate()?;
27        if vocabulary.manifest.algorithm != algorithm {
28            return Err(KuteError::VocabularyMismatch(format!(
29                "the {algorithm} tokenizer cannot interpret a {:?} vocabulary",
30                vocabulary.manifest.algorithm
31            )));
32        }
33        if !vocabulary.merges.is_empty() {
34            return Err(KuteError::InvalidVocabulary(format!("a {algorithm} vocabulary has no merge rules")));
35        }
36        let mut entries: FxHashMap<Vec<u8>, u32> = FxHashMap::default();
37        let mut symbols: FxHashMap<String, u32> = FxHashMap::default();
38        let mut lengths = BTreeSet::new();
39        match vocabulary.manifest.payload_kind {
40            PayloadKind::Bytes => {
41                if vocabulary.tokens.len() < 256 {
42                    return Err(KuteError::InvalidVocabulary("byte vocabularies start with the 256 byte tokens".into()));
43                }
44                for (i, t) in vocabulary.tokens.iter().enumerate() {
45                    let TokenPayload::Bytes(b) = &t.payload else {
46                        return Err(KuteError::InvalidVocabulary(format!("token {i} is not a byte token")));
47                    };
48                    if i < 256 {
49                        if t.kind != TokenKind::Byte || b.as_slice() != [i as u8] {
50                            return Err(KuteError::InvalidVocabulary(format!("token {i} must be the byte {i}")));
51                        }
52                    } else if t.kind != TokenKind::Special {
53                        if b.len() < 2 {
54                            return Err(KuteError::InvalidVocabulary(format!("token {i} duplicates a byte token")));
55                        }
56                        if entries.insert(b.clone(), t.id).is_some() {
57                            return Err(KuteError::InvalidVocabulary(format!("token {i} duplicates an earlier entry")));
58                        }
59                        lengths.insert(b.len());
60                    }
61                }
62            }
63            PayloadKind::Symbols => {
64                for (i, t) in vocabulary.tokens.iter().enumerate() {
65                    if t.kind == TokenKind::Special {
66                        continue;
67                    }
68                    let TokenPayload::Symbols(s) = &t.payload else {
69                        return Err(KuteError::InvalidVocabulary(format!("token {i} is not a symbol token")));
70                    };
71                    if s.len() != 1 || symbols.insert(s[0].clone(), t.id).is_some() {
72                        return Err(KuteError::InvalidVocabulary(format!("token {i} is not a single, unique symbol")));
73                    }
74                }
75            }
76        }
77        if vocabulary.integrity.is_none() {
78            vocabulary.seal()?;
79        }
80        Ok(Self { vocabulary, entries, lengths: lengths.into_iter().rev().collect(), symbols })
81    }
82
83    fn encode(&self, input: &CanonicalInput) -> Result<Vec<u32>> {
84        match (&input.payload, self.vocabulary.manifest.payload_kind) {
85            (Payload::Bytes(bytes), PayloadKind::Bytes) => {
86                let mut ids = Vec::with_capacity(bytes.len());
87                let mut i = 0;
88                'outer: while i < bytes.len() {
89                    for &len in &self.lengths {
90                        if i + len <= bytes.len() {
91                            if let Some(&id) = self.entries.get(&bytes[i..i + len]) {
92                                ids.push(id);
93                                i += len;
94                                continue 'outer;
95                            }
96                        }
97                    }
98                    ids.push(bytes[i] as u32);
99                    i += 1;
100                }
101                Ok(ids)
102            }
103            (Payload::Symbols(symbols), PayloadKind::Symbols) => symbols
104                .iter()
105                .map(|s| self.symbols.get(s).copied().ok_or_else(|| KuteError::UnknownSymbol(s.clone())))
106                .collect(),
107            (Payload::Bytes(_), PayloadKind::Symbols) => Err(KuteError::InvalidInput("this vocabulary takes symbol payloads".into())),
108            (Payload::Symbols(_), PayloadKind::Bytes) => Err(KuteError::InvalidInput("this vocabulary takes byte payloads".into())),
109        }
110    }
111
112    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
113        check_sequence(&self.vocabulary, tokens)?;
114        match self.vocabulary.manifest.payload_kind {
115            PayloadKind::Bytes => {
116                let mut out = Vec::with_capacity(tokens.ids.len());
117                for &id in &tokens.ids {
118                    if let TokenPayload::Bytes(b) = &self.vocabulary.token(id)?.payload {
119                        out.extend_from_slice(b);
120                    }
121                }
122                Ok(CanonicalInput::bytes(tokens.modality, out))
123            }
124            PayloadKind::Symbols => {
125                let mut out = Vec::with_capacity(tokens.ids.len());
126                for &id in &tokens.ids {
127                    if let TokenPayload::Symbols(s) = &self.vocabulary.token(id)?.payload {
128                        out.extend(s.iter().cloned());
129                    }
130                }
131                Ok(CanonicalInput { modality: tokens.modality, payload: Payload::Symbols(out) })
132            }
133        }
134    }
135}
136
137fn byte_tokens() -> Vec<TokenEntry> {
138    (0u32..256)
139        .map(|b| TokenEntry { id: b, kind: TokenKind::Byte, payload: TokenPayload::Bytes(vec![b as u8]), frequency: None })
140        .collect()
141}
142
143struct Draft {
144    algorithm: &'static str,
145    modality: Modality,
146    payload_kind: PayloadKind,
147    tokens: Vec<TokenEntry>,
148    statistics: BTreeMap<String, u64>,
149    fingerprint: Option<String>,
150    samples: Vec<Payload>,
151}
152
153/// Turn a draft into a sealed vocabulary with self-test vectors.
154fn finish(draft: Draft, config: &TrainingConfig) -> Result<Table> {
155    let mut tokens = draft.tokens;
156    for name in &config.reserved_tokens {
157        let id = tokens.len() as u32;
158        let payload = match draft.payload_kind {
159            PayloadKind::Bytes => TokenPayload::Bytes(name.as_bytes().to_vec()),
160            PayloadKind::Symbols => TokenPayload::Symbols(vec![name.clone()]),
161        };
162        tokens.push(TokenEntry { id, kind: TokenKind::Special, payload, frequency: None });
163    }
164    let vocabulary = Vocabulary {
165        manifest: Manifest {
166            kvf_version: KVF_VERSION.to_string(),
167            id: config.vocabulary_id.clone(),
168            version: config.vocabulary_version.clone(),
169            algorithm: draft.algorithm.to_string(),
170            modality: draft.modality,
171            payload_kind: draft.payload_kind,
172            lossless: true,
173            description: config.description.clone(),
174            created: None,
175            generator: format!("kute {KUTE_VERSION}"),
176        },
177        pretokenizer: None,
178        adapter: None,
179        tokens,
180        merges: Vec::new(),
181        statistics: draft.statistics,
182        provenance: Provenance {
183            corpus_fingerprints: draft.fingerprint.into_iter().collect(),
184            license: config.license.clone(),
185            training: Some(serde_json::to_value(config)?),
186        },
187        test_vectors: Vec::new(),
188        representations: Vec::new(),
189        integrity: None,
190    };
191    let mut table = Table::build(vocabulary, draft.algorithm)?;
192    let mut vectors = Vec::new();
193    for sample in draft.samples.into_iter().filter(|_| config.embed_test_vectors) {
194        let input = CanonicalInput { modality: draft.modality, payload: sample };
195        let ids = table.encode(&input)?;
196        let input = match input.payload {
197            Payload::Bytes(b) => TokenPayload::Bytes(b),
198            Payload::Symbols(s) => TokenPayload::Symbols(s),
199        };
200        vectors.push(TestVector { input, ids });
201    }
202    table.vocabulary.test_vectors = vectors;
203    table.vocabulary.seal()?;
204    Ok(table)
205}
206
207fn prefix(bytes: &[u8], max: usize) -> Vec<u8> {
208    let mut end = bytes.len().min(max);
209    if std::str::from_utf8(bytes).is_ok() {
210        while end > 0 && end < bytes.len() && (bytes[end] & 0xc0) == 0x80 {
211            end -= 1;
212        }
213    }
214    bytes[..end].to_vec()
215}
216
217fn check_limit(config: &TrainingConfig, fingerprint: &CorpusFingerprint) -> Result<()> {
218    match config.max_corpus_units {
219        Some(limit) if fingerprint.units() > limit => {
220            Err(KuteError::LimitExceeded(format!("corpus is larger than the max_corpus_units limit of {limit}")))
221        }
222        _ => Ok(()),
223    }
224}
225
226macro_rules! table_tokenizer {
227    ($name:ident, $algorithm:expr, $accepts:expr, $rejects:expr, $notes:expr) => {
228        #[derive(Default)]
229        pub struct $name {
230            table: Option<Table>,
231        }
232
233        impl $name {
234            fn table(&self) -> Result<&Table> {
235                self.table.as_ref().ok_or_else(|| KuteError::NotTrained("train or load a vocabulary first".into()))
236            }
237        }
238
239        impl Tokenizer for $name {
240            fn train(&mut self, corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Vocabulary> {
241                config.validate()?;
242                let table = finish(Self::draft(corpus, config)?, config)?;
243                let vocabulary = table.vocabulary.clone();
244                self.table = Some(table);
245                Ok(vocabulary)
246            }
247
248            fn load(&mut self, vocabulary: Vocabulary) -> Result<()> {
249                self.table = Some(Table::build(vocabulary, $algorithm)?);
250                Ok(())
251            }
252
253            fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence> {
254                let table = self.table()?;
255                sequence_for(&table.vocabulary, input.modality, table.encode(input)?)
256            }
257
258            fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
259                self.table()?.decode(tokens)
260            }
261
262            fn vocabulary(&self) -> Option<&Vocabulary> {
263                self.table.as_ref().map(|t| &t.vocabulary)
264            }
265
266            fn capabilities(&self) -> TokenizerCapabilities {
267                TokenizerCapabilities {
268                    algorithm: $algorithm.to_string(),
269                    lossless: true,
270                    trainable: true,
271                    deterministic: true,
272                    accepts: $accepts,
273                    rejects_unknown: $rejects,
274                    notes: $notes.to_string(),
275                }
276            }
277        }
278    };
279}
280
281table_tokenizer!(
282    ByteTokenizer,
283    BYTES,
284    vec![PayloadKind::Bytes],
285    false,
286    "One token per byte. Needs no training data; the lossless baseline."
287);
288table_tokenizer!(
289    CharTokenizer,
290    CHAR,
291    vec![PayloadKind::Bytes],
292    false,
293    "One token per Unicode character seen in training, with byte tokens as the fallback for everything else."
294);
295table_tokenizer!(
296    DictionaryTokenizer,
297    DICTIONARY,
298    vec![PayloadKind::Bytes, PayloadKind::Symbols],
299    false,
300    "Fixed entries. Over bytes: longest match with byte fallback, always lossless. Over symbols: lookup that refuses unknown symbols."
301);
302
303impl ByteTokenizer {
304    /// A ready byte tokenizer for `config`; no corpus needed.
305    pub fn with_config(config: &TrainingConfig) -> Result<Self> {
306        let mut t = Self::default();
307        t.train(&mut kute_core::VecCorpus::new(Vec::new()), config)?;
308        Ok(t)
309    }
310
311    fn draft(corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Draft> {
312        let mut fingerprint = CorpusFingerprint::new();
313        while let Some(record) = corpus.next_record()? {
314            if record.payload.kind() != PayloadKind::Bytes {
315                return Err(KuteError::InvalidInput("the bytes algorithm takes byte payloads".into()));
316            }
317            fingerprint.update(&record);
318            check_limit(config, &fingerprint)?;
319        }
320        let mut statistics = BTreeMap::new();
321        statistics.insert("corpus_records".to_string(), fingerprint.records());
322        statistics.insert("corpus_bytes".to_string(), fingerprint.units());
323        let seen = fingerprint.records() > 0;
324        Ok(Draft {
325            algorithm: BYTES,
326            modality: Modality::Binary,
327            payload_kind: PayloadKind::Bytes,
328            tokens: byte_tokens(),
329            statistics,
330            fingerprint: seen.then(|| fingerprint.finish()),
331            samples: vec![Payload::Bytes(vec![0x00, 0x7f, 0x80, 0xff, b'K'])],
332        })
333    }
334}
335
336impl CharTokenizer {
337    fn draft(corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Draft> {
338        let mut fingerprint = CorpusFingerprint::new();
339        let mut counts: BTreeMap<char, u64> = BTreeMap::new();
340        let mut samples = Vec::new();
341        while let Some(record) = corpus.next_record()? {
342            let Payload::Bytes(bytes) = &record.payload else {
343                return Err(KuteError::InvalidInput("the char algorithm takes byte payloads".into()));
344            };
345            fingerprint.update(&record);
346            check_limit(config, &fingerprint)?;
347            if samples.len() < 4 && !bytes.is_empty() {
348                samples.push(Payload::Bytes(prefix(bytes, 96)));
349            }
350            for chunk in bytes.utf8_chunks() {
351                for c in chunk.valid().chars() {
352                    if c.len_utf8() > 1 {
353                        *counts.entry(c).or_insert(0) += 1;
354                    }
355                }
356            }
357        }
358        // Most frequent first; ties by code point. Truncate to the budget.
359        let mut chars: Vec<(char, u64)> = counts.into_iter().filter(|(_, n)| *n >= config.min_frequency).collect();
360        chars.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
361        let reserved = config.reserved_tokens.len();
362        let budget = (config.vocab_size as usize).saturating_sub(256 + reserved);
363        if (config.vocab_size as usize) < 256 + reserved {
364            return Err(KuteError::InvalidConfig("the char algorithm needs vocab_size of at least 256 plus reserved tokens".into()));
365        }
366        let dropped = chars.len().saturating_sub(budget) as u64;
367        chars.truncate(budget);
368        let mut tokens = byte_tokens();
369        for (c, n) in &chars {
370            let id = tokens.len() as u32;
371            tokens.push(TokenEntry { id, kind: TokenKind::Char, payload: TokenPayload::Bytes(c.to_string().into_bytes()), frequency: Some(*n) });
372        }
373        let mut statistics = BTreeMap::new();
374        statistics.insert("corpus_records".to_string(), fingerprint.records());
375        statistics.insert("corpus_bytes".to_string(), fingerprint.units());
376        statistics.insert("characters_kept".to_string(), chars.len() as u64);
377        statistics.insert("characters_left_to_byte_fallback".to_string(), dropped);
378        Ok(Draft {
379            algorithm: CHAR,
380            modality: Modality::Text,
381            payload_kind: PayloadKind::Bytes,
382            tokens,
383            statistics,
384            fingerprint: Some(fingerprint.finish()),
385            samples,
386        })
387    }
388}
389
390impl DictionaryTokenizer {
391    /// With `config.dictionary` set, the entries are exactly that list. With it
392    /// empty and a symbol corpus, the dictionary is the corpus alphabet.
393    fn draft(corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Draft> {
394        let mut fingerprint = CorpusFingerprint::new();
395        let mut kind: Option<PayloadKind> = None;
396        let mut alphabet: BTreeMap<String, u64> = BTreeMap::new();
397        let mut samples = Vec::new();
398        while let Some(record) = corpus.next_record()? {
399            fingerprint.update(&record);
400            check_limit(config, &fingerprint)?;
401            let this = record.payload.kind();
402            if *kind.get_or_insert(this) != this {
403                return Err(KuteError::InvalidInput("a dictionary corpus must be all bytes or all symbols".into()));
404            }
405            match &record.payload {
406                Payload::Symbols(s) => {
407                    for sym in s {
408                        *alphabet.entry(sym.clone()).or_insert(0) += 1;
409                    }
410                    if samples.len() < 4 && !s.is_empty() {
411                        samples.push(Payload::Symbols(s.iter().take(32).cloned().collect()));
412                    }
413                }
414                Payload::Bytes(b) => {
415                    if samples.len() < 4 && !b.is_empty() {
416                        samples.push(Payload::Bytes(prefix(b, 96)));
417                    }
418                }
419            }
420        }
421        let mut statistics = BTreeMap::new();
422        statistics.insert("corpus_records".to_string(), fingerprint.records());
423        let seen = fingerprint.records() > 0;
424        let units = fingerprint.units();
425        let fingerprint = seen.then(|| fingerprint.finish());
426        let reserved = config.reserved_tokens.len();
427
428        if kind == Some(PayloadKind::Symbols) {
429            let entries: Vec<(String, Option<u64>)> = if config.dictionary.is_empty() {
430                alphabet.iter().filter(|(_, n)| **n >= config.min_frequency).map(|(s, n)| (s.clone(), Some(*n))).collect()
431            } else {
432                unique(&config.dictionary)?.into_iter().map(|s| { let n = alphabet.get(&s).copied(); (s, n) }).collect()
433            };
434            if entries.is_empty() {
435                return Err(KuteError::InvalidInput("no dictionary entries: the corpus is empty and no dictionary was given".into()));
436            }
437            if entries.len() + reserved > config.vocab_size as usize {
438                return Err(KuteError::InvalidConfig(format!("{} entries do not fit in vocab_size {}", entries.len(), config.vocab_size)));
439            }
440            statistics.insert("corpus_symbols".to_string(), units);
441            statistics.insert("entries".to_string(), entries.len() as u64);
442            let tokens = entries
443                .into_iter()
444                .enumerate()
445                .map(|(i, (s, n))| TokenEntry { id: i as u32, kind: TokenKind::Symbol, payload: TokenPayload::Symbols(vec![s]), frequency: n })
446                .collect();
447            return Ok(Draft { algorithm: DICTIONARY, modality: Modality::Events, payload_kind: PayloadKind::Symbols, tokens, statistics, fingerprint, samples });
448        }
449
450        if config.dictionary.is_empty() {
451            return Err(KuteError::InvalidConfig("a byte dictionary needs explicit entries (TrainingConfig.dictionary)".into()));
452        }
453        let entries = unique(&config.dictionary)?;
454        let mut tokens = byte_tokens();
455        for e in &entries {
456            if e.len() < 2 {
457                continue; // single bytes are already tokens
458            }
459            let id = tokens.len() as u32;
460            tokens.push(TokenEntry { id, kind: TokenKind::Entry, payload: TokenPayload::Bytes(e.as_bytes().to_vec()), frequency: None });
461        }
462        if tokens.len() + reserved > config.vocab_size as usize {
463            return Err(KuteError::InvalidConfig(format!("{} tokens do not fit in vocab_size {}", tokens.len() + reserved, config.vocab_size)));
464        }
465        statistics.insert("corpus_bytes".to_string(), units);
466        statistics.insert("entries".to_string(), (tokens.len() - 256) as u64);
467        Ok(Draft { algorithm: DICTIONARY, modality: Modality::Text, payload_kind: PayloadKind::Bytes, tokens, statistics, fingerprint, samples })
468    }
469}
470
471fn unique(entries: &[String]) -> Result<Vec<String>> {
472    let mut seen = BTreeSet::new();
473    for e in entries {
474        if e.is_empty() {
475            return Err(KuteError::InvalidConfig("dictionary entries must not be empty".into()));
476        }
477        if !seen.insert(e.as_str()) {
478            return Err(KuteError::InvalidConfig(format!("dictionary entry {e:?} is listed twice")));
479        }
480    }
481    Ok(entries.to_vec())
482}