Skip to main content

kute_bpe/
sequence.rs

1//! BPE over sequences of named symbols instead of bytes: events, opcodes,
2//! gates. The base alphabet is whatever symbols the corpus contains; merges
3//! become composite tokens such as `[MOTOR_START, CURRENT_HIGH, MOTOR_TRIP]`.
4//!
5//! This is KUTE's own capability, not a rustbpe feature.
6//!
7//! A vocabulary is frozen, but the world is not: new event names appear. A
8//! symbol outside the alphabet is never approximated. Under the strict
9//! policy it is refused; under the escape policy it travels literally in
10//! the sequence's escape table, the vocabulary stays as it was, and decoding
11//! returns the input exactly. Merges never span an escaped symbol.
12
13use crate::merge::{apply_merges, resumable_merges, train_merges, LearnedMerge, Pair};
14use kute_core::{check_sequence, sequence_for, CorpusFingerprint, CorpusSource, Tokenizer};
15use kute_types::{
16    CanonicalInput, KuteError, Manifest, MergeRule, Modality, Payload, PayloadKind, Provenance, Result,
17    TestVector, TokenEntry, TokenKind, TokenPayload, TokenSequence, TokenizerCapabilities, TrainingConfig,
18    UnknownPolicy, Vocabulary, KUTE_VERSION, KVF_VERSION, MAX_ESCAPES,
19};
20use rustc_hash::FxHashMap;
21use std::collections::{BTreeMap, BTreeSet};
22
23pub const ALGORITHM: &str = "sequence-bpe";
24
25struct Loaded {
26    vocabulary: Vocabulary,
27    alphabet: FxHashMap<String, u32>,
28    ranks: FxHashMap<Pair, u32>,
29}
30
31#[derive(Default)]
32pub struct SequenceBpeTokenizer {
33    loaded: Option<Loaded>,
34}
35
36impl SequenceBpeTokenizer {
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    pub fn boxed() -> Box<dyn Tokenizer> {
42        Box::new(Self::new())
43    }
44
45    fn loaded(&self) -> Result<&Loaded> {
46        self.loaded.as_ref().ok_or_else(|| KuteError::NotTrained("train or load a vocabulary first".into()))
47    }
48}
49
50fn encode_symbols(loaded: &Loaded, symbols: &[String]) -> Result<Vec<u32>> {
51    let mut ids = Vec::with_capacity(symbols.len());
52    for s in symbols {
53        ids.push(*loaded.alphabet.get(s).ok_or_else(|| KuteError::UnknownSymbol(s.clone()))?);
54    }
55    apply_merges(&mut ids, &loaded.ranks);
56    Ok(ids)
57}
58
59/// Encode with unknown symbols escaped. Returns the ids and the escape
60/// table; an escaped symbol gets the id `table length + its index`, and the
61/// same symbol always reuses one entry.
62fn encode_symbols_open(loaded: &Loaded, symbols: &[String]) -> Result<(Vec<u32>, Vec<String>)> {
63    let table = loaded.vocabulary.tokens.len() as u32;
64    let mut out = Vec::with_capacity(symbols.len());
65    let mut run: Vec<u32> = Vec::new();
66    let mut escapes: Vec<String> = Vec::new();
67    let mut escape_index: FxHashMap<&str, u32> = FxHashMap::default();
68    for s in symbols {
69        match loaded.alphabet.get(s) {
70            Some(&id) => run.push(id),
71            None => {
72                if s.is_empty() || s.len() > kute_types::vocab::MAX_SYMBOL_BYTES {
73                    return Err(KuteError::InvalidInput("symbols must be 1 to 1024 bytes".into()));
74                }
75                apply_merges(&mut run, &loaded.ranks);
76                out.append(&mut run);
77                let index = match escape_index.get(s.as_str()) {
78                    Some(&i) => i,
79                    None => {
80                        if escapes.len() >= MAX_ESCAPES {
81                            return Err(KuteError::LimitExceeded(format!("more than {MAX_ESCAPES} distinct unknown symbols in one sequence")));
82                        }
83                        escapes.push(s.clone());
84                        escape_index.insert(s.as_str(), escapes.len() as u32 - 1);
85                        escapes.len() as u32 - 1
86                    }
87                };
88                out.push(table + index);
89            }
90        }
91    }
92    apply_merges(&mut run, &loaded.ranks);
93    out.append(&mut run);
94    Ok((out, escapes))
95}
96
97impl Tokenizer for SequenceBpeTokenizer {
98    fn train(&mut self, corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Vocabulary> {
99        config.validate()?;
100        // One pass. Only the window counts, the alphabet and a few sample
101        // records are kept, so memory follows the number of distinct
102        // windows, not the size of the corpus. Symbols get provisional ids
103        // in order of first appearance and are renumbered in sorted order
104        // afterwards, which keeps the result independent of that order.
105        let mut fingerprint = CorpusFingerprint::new();
106        let mut modality = Modality::Events;
107        let mut seen: FxHashMap<String, u32> = FxHashMap::default();
108        let mut provisional: FxHashMap<Vec<u32>, u64> = FxHashMap::default();
109        let mut samples: Vec<Vec<String>> = Vec::new();
110        let mut ids: Vec<u32> = Vec::new();
111        while let Some(record) = corpus.next_record()? {
112            fingerprint.update(&record);
113            if let Some(limit) = config.max_corpus_units {
114                if fingerprint.units() > limit {
115                    return Err(KuteError::LimitExceeded(format!("corpus is larger than the max_corpus_units limit of {limit}")));
116                }
117            }
118            modality = record.modality;
119            let Payload::Symbols(symbols) = record.payload else {
120                return Err(KuteError::InvalidInput("sequence-bpe takes symbol payloads; use bpe for bytes".into()));
121            };
122            if samples.len() < 4 && !symbols.is_empty() {
123                samples.push(symbols.iter().take(32).cloned().collect());
124            }
125            ids.clear();
126            for s in symbols {
127                if s.is_empty() || s.len() > kute_types::vocab::MAX_SYMBOL_BYTES {
128                    return Err(KuteError::InvalidInput("symbols must be 1 to 1024 bytes".into()));
129                }
130                let next = seen.len() as u32;
131                ids.push(*seen.entry(s).or_insert(next));
132            }
133            for window in ids.chunks(config.train_window) {
134                match provisional.get_mut(window) {
135                    Some(count) => *count += 1,
136                    None => {
137                        provisional.insert(window.to_vec(), 1);
138                    }
139                }
140            }
141        }
142        let alphabet_set: BTreeSet<&str> = seen.keys().map(String::as_str).collect();
143        if alphabet_set.is_empty() {
144            return Err(KuteError::InvalidInput("the corpus contains no symbols".into()));
145        }
146        let base = alphabet_set.len() as u32;
147        let reserved = config.reserved_tokens.len() as u32;
148        if config.vocab_size < base + reserved {
149            return Err(KuteError::InvalidConfig(format!(
150                "the corpus has {base} distinct symbols; vocab_size must be at least {}",
151                base + reserved
152            )));
153        }
154        let index: FxHashMap<&str, u32> = alphabet_set.iter().enumerate().map(|(i, s)| (*s, i as u32)).collect();
155        let mut renumber = vec![0u32; seen.len()];
156        for (symbol, &first) in &seen {
157            renumber[first as usize] = index[symbol.as_str()];
158        }
159        let mut windows: Vec<(Vec<u32>, u64)> =
160            provisional.into_iter().map(|(w, c)| (w.into_iter().map(|id| renumber[id as usize]).collect(), c)).collect();
161        windows.sort_unstable();
162        let counts: Vec<u64> = windows.iter().map(|(_, c)| *c).collect();
163        let mut words: Vec<Vec<u32>> = windows.into_iter().map(|(w, _)| w).collect();
164        let unique_windows = words.len() as u64;
165
166        let mut lengths: Vec<usize> = vec![1; base as usize];
167        let limit = config.max_token_length;
168        let max_merges = config.vocab_size - base - reserved;
169        let corpus_records = fingerprint.records();
170        let corpus_units = fingerprint.units();
171        let corpus_fingerprint = fingerprint.finish();
172
173        // Resuming, as in byte BPE: replay the earlier merges, then go on.
174        let mut kept: Vec<LearnedMerge> = Vec::new();
175        if let Some(prior) = &config.resume_from {
176            // An evolved vocabulary keeps its parent's fingerprint but may
177            // have symbols after its merges; its ids would not line up.
178            let same_alphabet = prior.tokens.len() >= base as usize
179                && alphabet_set.iter().zip(&prior.tokens).all(|(s, t)| t.kind == TokenKind::Symbol && t.payload == TokenPayload::Symbols(vec![s.to_string()]));
180            if !same_alphabet {
181                return Err(KuteError::VocabularyMismatch(format!(
182                    "cannot resume from {} {}: its base symbols are not this corpus's",
183                    prior.id(),
184                    prior.version()
185                )));
186            }
187            kept = resumable_merges(prior, ALGORITHM, config, &corpus_fingerprint, base, max_merges)?;
188            let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
189            for m in &kept {
190                ranks.insert((m.left, m.right), m.id);
191                lengths.push(lengths[m.left as usize] + lengths[m.right as usize]);
192            }
193            for w in &mut words {
194                apply_merges(w, &ranks);
195            }
196        }
197        let resumed = kept.len() as u32;
198        let more = train_merges(words, &counts, base + resumed, max_merges - resumed, config.min_frequency, |l, r| {
199            let len = lengths[l as usize] + lengths[r as usize];
200            if limit.is_none_or(|m| len <= m) && len <= kute_types::vocab::MAX_TOKEN_SYMBOLS {
201                lengths.push(len);
202                true
203            } else {
204                false
205            }
206        });
207
208        let mut learned = kept;
209        learned.extend(more);
210
211        let mut tokens: Vec<TokenEntry> = alphabet_set
212            .iter()
213            .enumerate()
214            .map(|(i, s)| TokenEntry { id: i as u32, kind: TokenKind::Symbol, payload: TokenPayload::Symbols(vec![s.to_string()]), frequency: None })
215            .collect();
216        let mut rules = Vec::with_capacity(learned.len());
217        for m in &learned {
218            let mut seq = match &tokens[m.left as usize].payload {
219                TokenPayload::Symbols(s) => s.clone(),
220                TokenPayload::Bytes(_) => unreachable!("sequence vocabularies hold symbols only"),
221            };
222            if let TokenPayload::Symbols(s) = &tokens[m.right as usize].payload {
223                seq.extend(s.iter().cloned());
224            }
225            tokens.push(TokenEntry { id: m.id, kind: TokenKind::Merge, payload: TokenPayload::Symbols(seq), frequency: Some(m.count) });
226            rules.push(MergeRule { left: m.left, right: m.right, id: m.id });
227        }
228        for name in &config.reserved_tokens {
229            let id = tokens.len() as u32;
230            tokens.push(TokenEntry { id, kind: TokenKind::Special, payload: TokenPayload::Symbols(vec![name.clone()]), frequency: None });
231        }
232
233        let mut statistics = BTreeMap::new();
234        statistics.insert("corpus_records".to_string(), corpus_records);
235        statistics.insert("corpus_symbols".to_string(), corpus_units);
236        statistics.insert("alphabet_size".to_string(), base as u64);
237        statistics.insert("unique_windows".to_string(), unique_windows);
238        statistics.insert("merges_learned".to_string(), learned.len() as u64);
239        statistics.insert("requested_vocab_size".to_string(), config.vocab_size as u64);
240
241        let vocabulary = Vocabulary {
242            manifest: Manifest {
243                kvf_version: KVF_VERSION.to_string(),
244                id: config.vocabulary_id.clone(),
245                version: config.vocabulary_version.clone(),
246                algorithm: ALGORITHM.to_string(),
247                modality,
248                payload_kind: PayloadKind::Symbols,
249                lossless: true,
250                description: config.description.clone(),
251                created: None,
252                generator: format!("kute {KUTE_VERSION}"),
253            },
254            pretokenizer: None,
255            adapter: None,
256            tokens,
257            merges: rules,
258            statistics,
259            provenance: Provenance {
260                corpus_fingerprints: vec![corpus_fingerprint],
261                license: config.license.clone(),
262                training: Some(serde_json::to_value(config)?),
263            },
264            test_vectors: Vec::new(),
265            representations: Vec::new(),
266            integrity: None,
267        };
268        self.load(vocabulary)?;
269        let loaded = self.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
270        let mut vectors = Vec::new();
271        for sample in samples.into_iter().filter(|_| config.embed_test_vectors) {
272            let ids = encode_symbols(loaded, &sample)?;
273            vectors.push(TestVector { input: TokenPayload::Symbols(sample), ids });
274        }
275        loaded.vocabulary.test_vectors = vectors;
276        loaded.vocabulary.seal()?;
277        Ok(loaded.vocabulary.clone())
278    }
279
280    fn load(&mut self, mut vocabulary: Vocabulary) -> Result<()> {
281        vocabulary.validate()?;
282        if vocabulary.manifest.algorithm != ALGORITHM {
283            return Err(KuteError::VocabularyMismatch(format!(
284                "the sequence-bpe tokenizer cannot interpret a {:?} vocabulary",
285                vocabulary.manifest.algorithm
286            )));
287        }
288        let mut alphabet: FxHashMap<String, u32> = FxHashMap::default();
289        for t in &vocabulary.tokens {
290            if t.kind == TokenKind::Symbol {
291                let TokenPayload::Symbols(s) = &t.payload else {
292                    return Err(KuteError::InvalidVocabulary(format!("symbol token {} has a byte payload", t.id)));
293                };
294                if s.len() != 1 || alphabet.insert(s[0].clone(), t.id).is_some() {
295                    return Err(KuteError::InvalidVocabulary(format!("symbol token {} is not a single, unique symbol", t.id)));
296                }
297            }
298        }
299        let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
300        for m in &vocabulary.merges {
301            if ranks.insert((m.left, m.right), m.id).is_some() {
302                return Err(KuteError::InvalidVocabulary(format!("pair ({}, {}) has two merge rules", m.left, m.right)));
303            }
304        }
305        if vocabulary.integrity.is_none() {
306            vocabulary.seal()?;
307        }
308        self.loaded = Some(Loaded { vocabulary, alphabet, ranks });
309        Ok(())
310    }
311
312    fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence> {
313        let loaded = self.loaded()?;
314        let Payload::Symbols(symbols) = &input.payload else {
315            return Err(KuteError::InvalidInput("sequence-bpe takes symbol payloads".into()));
316        };
317        sequence_for(&loaded.vocabulary, input.modality, encode_symbols(loaded, symbols)?)
318    }
319
320    fn encode_open(&self, input: &CanonicalInput, policy: UnknownPolicy) -> Result<TokenSequence> {
321        if policy == UnknownPolicy::Strict {
322            return self.encode(input);
323        }
324        let loaded = self.loaded()?;
325        let Payload::Symbols(symbols) = &input.payload else {
326            return Err(KuteError::InvalidInput("sequence-bpe takes symbol payloads".into()));
327        };
328        let (ids, escapes) = encode_symbols_open(loaded, symbols)?;
329        let mut sequence = sequence_for(&loaded.vocabulary, input.modality, ids)?;
330        sequence.escapes = escapes;
331        Ok(sequence)
332    }
333
334    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
335        let loaded = self.loaded()?;
336        check_sequence(&loaded.vocabulary, tokens)?;
337        let mut out = Vec::with_capacity(tokens.ids.len() * 2);
338        let table = loaded.vocabulary.tokens.len();
339        for &id in &tokens.ids {
340            if id as usize >= table {
341                let escaped = tokens.escapes.get(id as usize - table).ok_or(KuteError::UnknownToken(id))?;
342                out.push(escaped.clone());
343                continue;
344            }
345            match &loaded.vocabulary.token(id)?.payload {
346                TokenPayload::Symbols(s) => out.extend(s.iter().cloned()),
347                TokenPayload::Bytes(_) => return Err(KuteError::InvalidVocabulary("byte token in a symbol vocabulary".into())),
348            }
349        }
350        Ok(CanonicalInput { modality: tokens.modality, payload: Payload::Symbols(out) })
351    }
352
353    fn vocabulary(&self) -> Option<&Vocabulary> {
354        self.loaded.as_ref().map(|l| &l.vocabulary)
355    }
356
357    fn capabilities(&self) -> TokenizerCapabilities {
358        TokenizerCapabilities {
359            algorithm: ALGORITHM.to_string(),
360            lossless: true,
361            trainable: true,
362            deterministic: true,
363            accepts: vec![PayloadKind::Symbols],
364            rejects_unknown: false,
365            notes: "BPE over named symbols. Lossless for the trained alphabet. A symbol outside it is refused under the strict policy and carried literally, without changing the vocabulary, under the escape policy.".to_string(),
366        }
367    }
368}
369
370/// The `generator` an evolved vocabulary carries. The generator is part of
371/// the digest, so it names the rule of the evolution step and not the
372/// release that ran it: two releases that implement the same rule give the
373/// same child and the same digest. It changes only when the rule does.
374/// Rule 1 (v0.3.0 to v0.5.0) wrote `kute <release>` here. Rule 2 (v0.6.0)
375/// derived the same tokens as rule 3 but copied the parent's whole training
376/// record into the child, so each generation carried all earlier ones; rule
377/// 3 records the parent by digest only. Provenance is part of the digest,
378/// so the two rules give different children and have different names.
379pub const EVOLVE_GENERATOR: &str = "kute evolve-3";
380
381/// Most additions one evolution step accepts.
382pub const MAX_ADDITIONS: usize = 65_536;
383
384/// Derive the next version of a sequence vocabulary by adding symbols and
385/// symbol sequences (development directive v0.2, vocabulary evolution).
386///
387/// The parent is not modified. Every token of the parent keeps its id and
388/// payload, so the child's table extends the parent's. New single symbols
389/// are appended as symbol tokens; a sequence is first tokenized by the merges
390/// already present and the tokens that remain are joined by new merges, each
391/// applied to the whole sequence before the next is chosen, so the sequence
392/// on its own encodes as one token under the child. The result is a pure
393/// function of the parent, `additions` and `version`: two parties that
394/// apply the same step hold the same digest.
395///
396/// Encoding can differ between parent and child, since the child knows more
397/// merges. A sequence encoded under the parent still names the parent's
398/// digest; re-encode it to move it to the child.
399pub fn evolve(parent: &Vocabulary, additions: &[Vec<String>], version: kute_types::Version) -> Result<Vocabulary> {
400    parent.validate()?;
401    if parent.manifest.algorithm != ALGORITHM {
402        return Err(KuteError::Unsupported(format!("evolution is defined for {ALGORITHM} vocabularies, not {:?}", parent.manifest.algorithm)));
403    }
404    if version <= parent.manifest.version {
405        return Err(KuteError::InvalidConfig(format!("the new version {version} must be greater than {}", parent.manifest.version)));
406    }
407    if additions.is_empty() || additions.len() > MAX_ADDITIONS {
408        return Err(KuteError::InvalidConfig(format!("an evolution step takes 1 to {MAX_ADDITIONS} additions")));
409    }
410    let mut child = parent.clone();
411    child.integrity = None;
412    child.manifest.version = version;
413    child.manifest.generator = EVOLVE_GENERATOR.to_string();
414    let mut by_symbol: FxHashMap<String, u32> = FxHashMap::default();
415    let mut by_pair: FxHashMap<Pair, u32> = FxHashMap::default();
416    for t in &child.tokens {
417        if let (TokenKind::Symbol, TokenPayload::Symbols(s)) = (t.kind, &t.payload) {
418            by_symbol.insert(s[0].clone(), t.id);
419        }
420    }
421    for m in &child.merges {
422        by_pair.insert((m.left, m.right), m.id);
423    }
424    // Reserved tokens are not symbols of the alphabet; a symbol of the same
425    // name would be ambiguous to a reader.
426    let reserved: BTreeSet<&str> = parent
427        .tokens
428        .iter()
429        .filter(|t| t.kind == TokenKind::Special)
430        .filter_map(|t| match &t.payload {
431            TokenPayload::Symbols(s) => Some(s[0].as_str()),
432            TokenPayload::Bytes(_) => None,
433        })
434        .collect();
435    let before = child.tokens.len();
436    for addition in additions {
437        if addition.is_empty() || addition.len() > kute_types::vocab::MAX_TOKEN_SYMBOLS {
438            return Err(KuteError::InvalidInput(format!("an addition must hold 1 to {} symbols", kute_types::vocab::MAX_TOKEN_SYMBOLS)));
439        }
440        let mut ids = Vec::with_capacity(addition.len());
441        for symbol in addition {
442            if symbol.is_empty() || symbol.len() > kute_types::vocab::MAX_SYMBOL_BYTES {
443                return Err(KuteError::InvalidInput("symbols must be 1 to 1024 bytes".into()));
444            }
445            if reserved.contains(symbol.as_str()) {
446                return Err(KuteError::InvalidInput(format!("{symbol:?} is a reserved token of this vocabulary")));
447            }
448            let id = match by_symbol.get(symbol) {
449                Some(&id) => id,
450                None => {
451                    let id = child.tokens.len() as u32;
452                    child.tokens.push(TokenEntry { id, kind: TokenKind::Symbol, payload: TokenPayload::Symbols(vec![symbol.clone()]), frequency: None });
453                    by_symbol.insert(symbol.clone(), id);
454                    id
455                }
456            };
457            ids.push(id);
458        }
459        // Tokenize the addition as the vocabulary so far would, then join
460        // what is left, one new merge at a time. A chain built over the bare
461        // symbols would seldom apply: the encoder runs the earlier merges
462        // first, and they have already joined those symbols into other
463        // tokens. Each new merge is applied to the whole addition before the
464        // next is chosen, because the encoder will apply it that way too:
465        // in A A A A the merge of A A leaves two tokens, not three.
466        apply_merges(&mut ids, &by_pair);
467        let symbols_of = |tokens: &[TokenEntry], id: u32| match &tokens[id as usize].payload {
468            TokenPayload::Symbols(s) => s.clone(),
469            TokenPayload::Bytes(_) => Vec::new(),
470        };
471        while ids.len() > 1 {
472            // No pair left in `ids` is a known merge, so this one is new.
473            let (left, right) = (ids[0], ids[1]);
474            let mut payload = symbols_of(&child.tokens, left);
475            payload.extend(symbols_of(&child.tokens, right));
476            let id = child.tokens.len() as u32;
477            child.tokens.push(TokenEntry { id, kind: TokenKind::Merge, payload: TokenPayload::Symbols(payload), frequency: None });
478            child.merges.push(MergeRule { left, right, id });
479            by_pair.insert((left, right), id);
480            apply_merges(&mut ids, &by_pair);
481        }
482    }
483    let added = child.tokens.len() - before;
484    if added == 0 {
485        return Err(KuteError::InvalidInput("every addition is already in the vocabulary".into()));
486    }
487    if child.tokens.len() > kute_types::vocab::MAX_TOKENS {
488        return Err(KuteError::LimitExceeded("the evolved vocabulary would exceed the token limit".into()));
489    }
490    child.statistics.insert("evolved_tokens".to_string(), added as u64);
491    child.provenance.training = Some(serde_json::json!({
492        // Computed from the parent's content, not read from its file, so
493        // the link is true whatever the parent claims about itself.
494        "evolved_from": { "version": parent.manifest.version.to_string(), "digest": parent.compute_digest()? },
495        "additions": additions,
496    }));
497    // Expected ids of the parent's test vectors may change under the new
498    // merges; recompute them against the child.
499    let inputs: Vec<TokenPayload> = std::mem::take(&mut child.test_vectors).into_iter().map(|v| v.input).collect();
500    let mut tokenizer = SequenceBpeTokenizer::new();
501    tokenizer.load(child)?;
502    let loaded = tokenizer.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
503    let mut vectors = Vec::with_capacity(inputs.len());
504    for input in inputs {
505        if let TokenPayload::Symbols(symbols) = &input {
506            let ids = encode_symbols(loaded, symbols)?;
507            vectors.push(TestVector { input, ids });
508        }
509    }
510    loaded.vocabulary.test_vectors = vectors;
511    loaded.vocabulary.seal()?;
512    Ok(loaded.vocabulary.clone())
513}