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, train_merges, 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 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 learned = train_merges(words, &counts, base, config.vocab_size - base - reserved, config.min_frequency, |l, r| {
169            let len = lengths[l as usize] + lengths[r as usize];
170            if limit.is_none_or(|m| len <= m) && len <= kute_types::vocab::MAX_TOKEN_SYMBOLS {
171                lengths.push(len);
172                true
173            } else {
174                false
175            }
176        });
177
178        let mut tokens: Vec<TokenEntry> = alphabet_set
179            .iter()
180            .enumerate()
181            .map(|(i, s)| TokenEntry { id: i as u32, kind: TokenKind::Symbol, payload: TokenPayload::Symbols(vec![s.to_string()]), frequency: None })
182            .collect();
183        let mut rules = Vec::with_capacity(learned.len());
184        for m in &learned {
185            let mut seq = match &tokens[m.left as usize].payload {
186                TokenPayload::Symbols(s) => s.clone(),
187                TokenPayload::Bytes(_) => unreachable!("sequence vocabularies hold symbols only"),
188            };
189            if let TokenPayload::Symbols(s) = &tokens[m.right as usize].payload {
190                seq.extend(s.iter().cloned());
191            }
192            tokens.push(TokenEntry { id: m.id, kind: TokenKind::Merge, payload: TokenPayload::Symbols(seq), frequency: Some(m.count) });
193            rules.push(MergeRule { left: m.left, right: m.right, id: m.id });
194        }
195        for name in &config.reserved_tokens {
196            let id = tokens.len() as u32;
197            tokens.push(TokenEntry { id, kind: TokenKind::Special, payload: TokenPayload::Symbols(vec![name.clone()]), frequency: None });
198        }
199
200        let mut statistics = BTreeMap::new();
201        statistics.insert("corpus_records".to_string(), fingerprint.records());
202        statistics.insert("corpus_symbols".to_string(), fingerprint.units());
203        statistics.insert("alphabet_size".to_string(), base as u64);
204        statistics.insert("unique_windows".to_string(), unique_windows);
205        statistics.insert("merges_learned".to_string(), learned.len() as u64);
206        statistics.insert("requested_vocab_size".to_string(), config.vocab_size as u64);
207
208        let vocabulary = Vocabulary {
209            manifest: Manifest {
210                kvf_version: KVF_VERSION.to_string(),
211                id: config.vocabulary_id.clone(),
212                version: config.vocabulary_version.clone(),
213                algorithm: ALGORITHM.to_string(),
214                modality,
215                payload_kind: PayloadKind::Symbols,
216                lossless: true,
217                description: config.description.clone(),
218                created: None,
219                generator: format!("kute {KUTE_VERSION}"),
220            },
221            pretokenizer: None,
222            adapter: None,
223            tokens,
224            merges: rules,
225            statistics,
226            provenance: Provenance {
227                corpus_fingerprints: vec![fingerprint.finish()],
228                license: config.license.clone(),
229                training: Some(serde_json::to_value(config)?),
230            },
231            test_vectors: Vec::new(),
232            representations: Vec::new(),
233            integrity: None,
234        };
235        self.load(vocabulary)?;
236        let loaded = self.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
237        let mut vectors = Vec::new();
238        for sample in samples.into_iter().filter(|_| config.embed_test_vectors) {
239            let ids = encode_symbols(loaded, &sample)?;
240            vectors.push(TestVector { input: TokenPayload::Symbols(sample), ids });
241        }
242        loaded.vocabulary.test_vectors = vectors;
243        loaded.vocabulary.seal()?;
244        Ok(loaded.vocabulary.clone())
245    }
246
247    fn load(&mut self, mut vocabulary: Vocabulary) -> Result<()> {
248        vocabulary.validate()?;
249        if vocabulary.manifest.algorithm != ALGORITHM {
250            return Err(KuteError::VocabularyMismatch(format!(
251                "the sequence-bpe tokenizer cannot interpret a {:?} vocabulary",
252                vocabulary.manifest.algorithm
253            )));
254        }
255        let mut alphabet: FxHashMap<String, u32> = FxHashMap::default();
256        for t in &vocabulary.tokens {
257            if t.kind == TokenKind::Symbol {
258                let TokenPayload::Symbols(s) = &t.payload else {
259                    return Err(KuteError::InvalidVocabulary(format!("symbol token {} has a byte payload", t.id)));
260                };
261                if s.len() != 1 || alphabet.insert(s[0].clone(), t.id).is_some() {
262                    return Err(KuteError::InvalidVocabulary(format!("symbol token {} is not a single, unique symbol", t.id)));
263                }
264            }
265        }
266        let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
267        for m in &vocabulary.merges {
268            if ranks.insert((m.left, m.right), m.id).is_some() {
269                return Err(KuteError::InvalidVocabulary(format!("pair ({}, {}) has two merge rules", m.left, m.right)));
270            }
271        }
272        if vocabulary.integrity.is_none() {
273            vocabulary.seal()?;
274        }
275        self.loaded = Some(Loaded { vocabulary, alphabet, ranks });
276        Ok(())
277    }
278
279    fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence> {
280        let loaded = self.loaded()?;
281        let Payload::Symbols(symbols) = &input.payload else {
282            return Err(KuteError::InvalidInput("sequence-bpe takes symbol payloads".into()));
283        };
284        sequence_for(&loaded.vocabulary, input.modality, encode_symbols(loaded, symbols)?)
285    }
286
287    fn encode_open(&self, input: &CanonicalInput, policy: UnknownPolicy) -> Result<TokenSequence> {
288        if policy == UnknownPolicy::Strict {
289            return self.encode(input);
290        }
291        let loaded = self.loaded()?;
292        let Payload::Symbols(symbols) = &input.payload else {
293            return Err(KuteError::InvalidInput("sequence-bpe takes symbol payloads".into()));
294        };
295        let (ids, escapes) = encode_symbols_open(loaded, symbols)?;
296        let mut sequence = sequence_for(&loaded.vocabulary, input.modality, ids)?;
297        sequence.escapes = escapes;
298        Ok(sequence)
299    }
300
301    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
302        let loaded = self.loaded()?;
303        check_sequence(&loaded.vocabulary, tokens)?;
304        let mut out = Vec::with_capacity(tokens.ids.len() * 2);
305        let table = loaded.vocabulary.tokens.len();
306        for &id in &tokens.ids {
307            if id as usize >= table {
308                let escaped = tokens.escapes.get(id as usize - table).ok_or(KuteError::UnknownToken(id))?;
309                out.push(escaped.clone());
310                continue;
311            }
312            match &loaded.vocabulary.token(id)?.payload {
313                TokenPayload::Symbols(s) => out.extend(s.iter().cloned()),
314                TokenPayload::Bytes(_) => return Err(KuteError::InvalidVocabulary("byte token in a symbol vocabulary".into())),
315            }
316        }
317        Ok(CanonicalInput { modality: tokens.modality, payload: Payload::Symbols(out) })
318    }
319
320    fn vocabulary(&self) -> Option<&Vocabulary> {
321        self.loaded.as_ref().map(|l| &l.vocabulary)
322    }
323
324    fn capabilities(&self) -> TokenizerCapabilities {
325        TokenizerCapabilities {
326            algorithm: ALGORITHM.to_string(),
327            lossless: true,
328            trainable: true,
329            deterministic: true,
330            accepts: vec![PayloadKind::Symbols],
331            rejects_unknown: false,
332            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(),
333        }
334    }
335}
336
337/// Most additions one evolution step accepts.
338pub const MAX_ADDITIONS: usize = 65_536;
339
340/// Derive the next version of a sequence vocabulary by adding symbols and
341/// symbol sequences (development directive v0.2, vocabulary evolution).
342///
343/// The parent is not modified. Every token of the parent keeps its id and
344/// payload, so the child's table extends the parent's. New single symbols
345/// are appended as symbol tokens; a sequence is appended as a chain of merge
346/// tokens, reusing any merge the parent already has. The result is a pure
347/// function of the parent, `additions` and `version`: two parties that
348/// apply the same step hold the same digest.
349///
350/// Encoding can differ between parent and child, since the child knows more
351/// merges. A sequence encoded under the parent still names the parent's
352/// digest; re-encode it to move it to the child.
353pub fn evolve(parent: &Vocabulary, additions: &[Vec<String>], version: kute_types::Version) -> Result<Vocabulary> {
354    parent.validate()?;
355    if parent.manifest.algorithm != ALGORITHM {
356        return Err(KuteError::Unsupported(format!("evolution is defined for {ALGORITHM} vocabularies, not {:?}", parent.manifest.algorithm)));
357    }
358    if version <= parent.manifest.version {
359        return Err(KuteError::InvalidConfig(format!("the new version {version} must be greater than {}", parent.manifest.version)));
360    }
361    if additions.is_empty() || additions.len() > MAX_ADDITIONS {
362        return Err(KuteError::InvalidConfig(format!("an evolution step takes 1 to {MAX_ADDITIONS} additions")));
363    }
364    let mut child = parent.clone();
365    child.integrity = None;
366    child.manifest.version = version;
367    child.manifest.generator = format!("kute {KUTE_VERSION}");
368    let mut by_symbol: FxHashMap<String, u32> = FxHashMap::default();
369    let mut by_pair: FxHashMap<Pair, u32> = FxHashMap::default();
370    for t in &child.tokens {
371        if let (TokenKind::Symbol, TokenPayload::Symbols(s)) = (t.kind, &t.payload) {
372            by_symbol.insert(s[0].clone(), t.id);
373        }
374    }
375    for m in &child.merges {
376        by_pair.insert((m.left, m.right), m.id);
377    }
378    // Reserved tokens are not symbols of the alphabet; a symbol of the same
379    // name would be ambiguous to a reader.
380    let reserved: BTreeSet<&str> = parent
381        .tokens
382        .iter()
383        .filter(|t| t.kind == TokenKind::Special)
384        .filter_map(|t| match &t.payload {
385            TokenPayload::Symbols(s) => Some(s[0].as_str()),
386            TokenPayload::Bytes(_) => None,
387        })
388        .collect();
389    let before = child.tokens.len();
390    for addition in additions {
391        if addition.is_empty() || addition.len() > kute_types::vocab::MAX_TOKEN_SYMBOLS {
392            return Err(KuteError::InvalidInput(format!("an addition must hold 1 to {} symbols", kute_types::vocab::MAX_TOKEN_SYMBOLS)));
393        }
394        let mut ids = Vec::with_capacity(addition.len());
395        for symbol in addition {
396            if symbol.is_empty() || symbol.len() > kute_types::vocab::MAX_SYMBOL_BYTES {
397                return Err(KuteError::InvalidInput("symbols must be 1 to 1024 bytes".into()));
398            }
399            if reserved.contains(symbol.as_str()) {
400                return Err(KuteError::InvalidInput(format!("{symbol:?} is a reserved token of this vocabulary")));
401            }
402            let id = match by_symbol.get(symbol) {
403                Some(&id) => id,
404                None => {
405                    let id = child.tokens.len() as u32;
406                    child.tokens.push(TokenEntry { id, kind: TokenKind::Symbol, payload: TokenPayload::Symbols(vec![symbol.clone()]), frequency: None });
407                    by_symbol.insert(symbol.clone(), id);
408                    id
409                }
410            };
411            ids.push(id);
412        }
413        let mut left = ids[0];
414        let mut payload = vec![addition[0].clone()];
415        for (i, &right) in ids.iter().enumerate().skip(1) {
416            payload.push(addition[i].clone());
417            left = match by_pair.get(&(left, right)) {
418                Some(&id) => id,
419                None => {
420                    let id = child.tokens.len() as u32;
421                    child.tokens.push(TokenEntry { id, kind: TokenKind::Merge, payload: TokenPayload::Symbols(payload.clone()), frequency: None });
422                    child.merges.push(MergeRule { left, right, id });
423                    by_pair.insert((left, right), id);
424                    id
425                }
426            };
427        }
428    }
429    let added = child.tokens.len() - before;
430    if added == 0 {
431        return Err(KuteError::InvalidInput("every addition is already in the vocabulary".into()));
432    }
433    if child.tokens.len() > kute_types::vocab::MAX_TOKENS {
434        return Err(KuteError::LimitExceeded("the evolved vocabulary would exceed the token limit".into()));
435    }
436    child.statistics.insert("evolved_tokens".to_string(), added as u64);
437    child.provenance.training = Some(serde_json::json!({
438        "evolved_from": { "version": parent.manifest.version.to_string(), "digest": parent.digest()? },
439        "additions": additions,
440        "parent_training": parent.provenance.training,
441    }));
442    // Expected ids of the parent's test vectors may change under the new
443    // merges; recompute them against the child.
444    let inputs: Vec<TokenPayload> = std::mem::take(&mut child.test_vectors).into_iter().map(|v| v.input).collect();
445    let mut tokenizer = SequenceBpeTokenizer::new();
446    tokenizer.load(child)?;
447    let loaded = tokenizer.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
448    let mut vectors = Vec::with_capacity(inputs.len());
449    for input in inputs {
450        if let TokenPayload::Symbols(symbols) = &input {
451            let ids = encode_symbols(loaded, symbols)?;
452            vectors.push(TestVector { input, ids });
453        }
454    }
455    loaded.vocabulary.test_vectors = vectors;
456    loaded.vocabulary.seal()?;
457    Ok(loaded.vocabulary.clone())
458}