Skip to main content

kute_bpe/
byte.rs

1//! Native byte-level BPE. Ids 0..=255 are the byte values, learned merges
2//! follow, reserved tokens come last. Lossless for arbitrary bytes.
3
4use crate::merge::{apply_merges, train_merges, Pair};
5use fancy_regex::Regex;
6use rayon::prelude::*;
7use kute_core::{check_sequence, sequence_for, CorpusFingerprint, CorpusSource, Tokenizer};
8use kute_types::{
9    CanonicalInput, KuteError, Manifest, MergeRule, Modality, Payload, PayloadKind, Provenance, Result,
10    TestVector, TokenEntry, TokenKind, TokenPayload, TokenSequence, TokenizerCapabilities, TrainingConfig,
11    Vocabulary, KUTE_VERSION, KVF_VERSION,
12};
13use rustc_hash::FxHashMap;
14use std::collections::BTreeMap;
15
16pub const ALGORITHM: &str = "bpe";
17/// Vocabularies written by the rustbpe backend use the same table layout and
18/// are read by this tokenizer too.
19pub const COMPATIBLE_ALGORITHMS: &[&str] = &["bpe", "rustbpe"];
20
21struct Loaded {
22    vocabulary: Vocabulary,
23    ranks: FxHashMap<Pair, u32>,
24    regex: Option<Splitter>,
25}
26
27/// How a pre-tokenizer pattern is executed.
28pub(crate) enum Splitter {
29    /// Any pattern, on the backtracking engine.
30    Fancy(Regex),
31    /// The GPT-4 preset on the automaton engine. The preset's possessive
32    /// quantifiers never change what it matches (each guards a character class
33    /// disjoint from what follows), so they are dropped; its one lookahead,
34    /// `\s+(?!\S)`, is applied by hand in `for_each_chunk`. The differential
35    /// test in this file holds the two engines to identical chunks.
36    Gpt4(regex::Regex),
37}
38
39const GPT4_FAST: &str = r"'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]|\s+";
40
41#[derive(Default)]
42pub struct BpeTokenizer {
43    loaded: Option<Loaded>,
44}
45
46impl BpeTokenizer {
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    pub fn boxed() -> Box<dyn Tokenizer> {
52        Box::new(Self::new())
53    }
54
55    fn loaded(&self) -> Result<&Loaded> {
56        self.loaded.as_ref().ok_or_else(|| KuteError::NotTrained("train or load a vocabulary first".into()))
57    }
58}
59
60pub(crate) fn compile(pattern: Option<&str>) -> Result<Option<Splitter>> {
61    match pattern {
62        None => Ok(None),
63        Some(p) if p == kute_types::config::GPT4_PATTERN => regex::Regex::new(GPT4_FAST)
64            .map(|re| Some(Splitter::Gpt4(re)))
65            .map_err(|e| KuteError::InvalidConfig(format!("pretokenizer pattern does not compile: {e}"))),
66        Some(p) => compile_fancy(p).map(|re| Some(Splitter::Fancy(re))),
67    }
68}
69
70fn compile_fancy(pattern: &str) -> Result<Regex> {
71    Regex::new(pattern).map_err(|e| KuteError::InvalidConfig(format!("pretokenizer pattern does not compile: {e}")))
72}
73
74/// Split `bytes` into chunks and hand each to `f`. Every byte is delivered
75/// exactly once and in order, whatever the pattern matches, so chunking can
76/// never lose information: text the pattern skips becomes its own chunk, and
77/// input that is not valid UTF-8 (or that the regex engine gives up on) is
78/// delivered whole.
79pub(crate) fn for_each_chunk<'a>(splitter: Option<&Splitter>, bytes: &'a [u8], mut f: impl FnMut(&'a [u8])) {
80    if bytes.is_empty() {
81        return;
82    }
83    let (Some(splitter), Ok(text)) = (splitter, std::str::from_utf8(bytes)) else {
84        f(bytes);
85        return;
86    };
87    let re = match splitter {
88        Splitter::Fancy(re) => re,
89        Splitter::Gpt4(re) => {
90            let mut at = 0;
91            while at < text.len() {
92                let Some(m) = re.find_at(text, at) else { break };
93                let (start, mut end) = (m.start(), m.end());
94                if end <= start {
95                    break;
96                }
97                // `\s+(?!\S)`: a whitespace run that stops before a non-space
98                // gives its last character back. Only the `\s+` branch can
99                // end in whitespace other than a line break.
100                if end < text.len() {
101                    if let Some(c) = text[start..end].chars().next_back() {
102                        if c.is_whitespace() && c != '\n' && c != '\r' && end - start > c.len_utf8() {
103                            end -= c.len_utf8();
104                        }
105                    }
106                }
107                if start > at {
108                    f(&bytes[at..start]);
109                }
110                f(&bytes[start..end]);
111                at = end;
112            }
113            if at < bytes.len() {
114                f(&bytes[at..]);
115            }
116            return;
117        }
118    };
119    let mut last = 0;
120    for m in re.find_iter(text) {
121        let Ok(m) = m else { break };
122        if m.end() <= m.start() || m.start() < last {
123            continue;
124        }
125        if m.start() > last {
126            f(&bytes[last..m.start()]);
127        }
128        f(&bytes[m.start()..m.end()]);
129        last = m.end();
130    }
131    if last < bytes.len() {
132        f(&bytes[last..]);
133    }
134}
135
136/// Inputs at least this long are encoded in pieces on several threads.
137const PARALLEL_MIN_BYTES: usize = 1 << 20;
138const PARALLEL_PIECE_BYTES: usize = 1 << 18;
139
140/// Cut points for encoding a long text in parallel under the GPT-4 preset.
141///
142/// A cut is placed only between a line feed and an ASCII letter. No branch of
143/// the preset can match across that position (line breaks only ever end a
144/// match, and the one branch that starts with an optional non-letter excludes
145/// line breaks), and the preset has no look-behind, so the pieces tokenize
146/// exactly as the whole does.
147fn parallel_cuts(bytes: &[u8]) -> Vec<usize> {
148    let mut cuts = vec![0];
149    let mut target = PARALLEL_PIECE_BYTES;
150    while target < bytes.len() {
151        match (target..bytes.len()).find(|&i| bytes[i - 1] == b'\n' && bytes[i].is_ascii_alphabetic()) {
152            Some(i) => {
153                cuts.push(i);
154                target = i + PARALLEL_PIECE_BYTES;
155            }
156            None => break,
157        }
158    }
159    cuts.push(bytes.len());
160    cuts
161}
162
163fn encode_bytes(loaded: &Loaded, bytes: &[u8]) -> Vec<u32> {
164    if bytes.len() >= PARALLEL_MIN_BYTES && matches!(loaded.regex, Some(Splitter::Gpt4(_))) && std::str::from_utf8(bytes).is_ok() {
165        let cuts = parallel_cuts(bytes);
166        if cuts.len() > 2 {
167            let pieces: Vec<Vec<u32>> = cuts.par_windows(2).map(|w| encode_piece(loaded, &bytes[w[0]..w[1]])).collect();
168            let mut out = Vec::with_capacity(pieces.iter().map(Vec::len).sum());
169            for p in &pieces {
170                out.extend_from_slice(p);
171            }
172            return out;
173        }
174    }
175    encode_piece(loaded, bytes)
176}
177
178fn encode_piece(loaded: &Loaded, bytes: &[u8]) -> Vec<u32> {
179    let mut out = Vec::with_capacity(bytes.len() / 2 + 1);
180    let mut scratch: Vec<u32> = Vec::new();
181    // Words repeat, so remember where each short chunk's ids already sit in
182    // `out`. The cache lives for one call and never changes the result.
183    const CACHE_CHUNK_MAX: usize = 48;
184    const CACHE_ENTRIES_MAX: usize = 1 << 16;
185    let cacheable = loaded.regex.is_some();
186    let mut cache: FxHashMap<&[u8], (usize, usize)> = FxHashMap::default();
187    for_each_chunk(loaded.regex.as_ref(), bytes, |chunk| {
188        let cache_this = cacheable && chunk.len() <= CACHE_CHUNK_MAX;
189        if cache_this {
190            if let Some(&(start, len)) = cache.get(chunk) {
191                out.extend_from_within(start..start + len);
192                return;
193            }
194        }
195        scratch.clear();
196        scratch.extend(chunk.iter().map(|&b| b as u32));
197        apply_merges(&mut scratch, &loaded.ranks);
198        if cache_this && cache.len() < CACHE_ENTRIES_MAX {
199            cache.insert(chunk, (out.len(), scratch.len()));
200        }
201        out.extend_from_slice(&scratch);
202    });
203    out
204}
205
206/// Assemble a byte-BPE vocabulary from learned merges. Shared with the
207/// rustbpe backend so both write identical tables.
208#[doc(hidden)]
209pub fn build_vocabulary(
210    algorithm: &str,
211    config: &TrainingConfig,
212    merges: &[(u32, u32, u32, Option<u64>)],
213    statistics: BTreeMap<String, u64>,
214    fingerprint: String,
215) -> Result<Vocabulary> {
216    let mut tokens: Vec<TokenEntry> = (0u32..256)
217        .map(|b| TokenEntry { id: b, kind: TokenKind::Byte, payload: TokenPayload::Bytes(vec![b as u8]), frequency: None })
218        .collect();
219    let mut rules = Vec::with_capacity(merges.len());
220    for &(left, right, id, count) in merges {
221        if id as usize != tokens.len() || left >= id || right >= id {
222            return Err(KuteError::Backend(format!("merge ({left}, {right}) -> {id} is out of order")));
223        }
224        let (TokenPayload::Bytes(a), TokenPayload::Bytes(b)) = (&tokens[left as usize].payload, &tokens[right as usize].payload) else {
225            return Err(KuteError::Backend("byte BPE produced a non-byte token".into()));
226        };
227        let mut bytes = a.clone();
228        bytes.extend_from_slice(b);
229        tokens.push(TokenEntry { id, kind: TokenKind::Merge, payload: TokenPayload::Bytes(bytes), frequency: count });
230        rules.push(MergeRule { left, right, id });
231    }
232    for name in &config.reserved_tokens {
233        let id = tokens.len() as u32;
234        tokens.push(TokenEntry { id, kind: TokenKind::Special, payload: TokenPayload::Bytes(name.as_bytes().to_vec()), frequency: None });
235    }
236    let modality = if config.pretokenizer.pattern().is_some() { Modality::Text } else { Modality::Binary };
237    Ok(Vocabulary {
238        manifest: Manifest {
239            kvf_version: KVF_VERSION.to_string(),
240            id: config.vocabulary_id.clone(),
241            version: config.vocabulary_version.clone(),
242            algorithm: algorithm.to_string(),
243            modality,
244            payload_kind: PayloadKind::Bytes,
245            lossless: true,
246            description: config.description.clone(),
247            created: None,
248            generator: format!("kute {KUTE_VERSION}"),
249        },
250        pretokenizer: config.pretokenizer.pattern().map(str::to_string),
251        adapter: None,
252        tokens,
253        merges: rules,
254        statistics,
255        provenance: Provenance {
256            corpus_fingerprints: vec![fingerprint],
257            license: config.license.clone(),
258            training: Some(serde_json::to_value(config)?),
259        },
260        test_vectors: Vec::new(),
261        representations: Vec::new(),
262        integrity: None,
263    })
264}
265
266impl Tokenizer for BpeTokenizer {
267    fn train(&mut self, corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Vocabulary> {
268        config.validate()?;
269        let reserved = config.reserved_tokens.len() as u32;
270        if config.vocab_size < 256 + reserved {
271            return Err(KuteError::InvalidConfig(format!(
272                "byte BPE needs vocab_size of at least {} (256 bytes plus {reserved} reserved tokens)",
273                256 + reserved
274            )));
275        }
276        let regex = compile(config.pretokenizer.pattern())?;
277        let mut fingerprint = CorpusFingerprint::new();
278        let mut chunk_counts: FxHashMap<Vec<u8>, u64> = FxHashMap::default();
279        let mut samples: Vec<Vec<u8>> = Vec::new();
280        while let Some(record) = corpus.next_record()? {
281            let Payload::Bytes(bytes) = &record.payload else {
282                return Err(KuteError::InvalidInput("the bpe algorithm takes byte payloads; use sequence-bpe for symbols".into()));
283            };
284            fingerprint.update(&record);
285            if let Some(limit) = config.max_corpus_units {
286                if fingerprint.units() > limit {
287                    return Err(KuteError::LimitExceeded(format!("corpus is larger than the max_corpus_units limit of {limit}")));
288                }
289            }
290            if samples.len() < 4 && !bytes.is_empty() {
291                samples.push(sample_prefix(bytes, 96));
292            }
293            let windowed = regex.is_none() || std::str::from_utf8(bytes).is_err();
294            if windowed {
295                for window in bytes.chunks(config.train_window) {
296                    *chunk_counts.entry(window.to_vec()).or_insert(0) += 1;
297                }
298            } else {
299                for_each_chunk(regex.as_ref(), bytes, |chunk| {
300                    // A pattern that matches nothing would hand back the whole
301                    // record; keep counting bounded either way.
302                    for window in chunk.chunks(config.train_window.max(4096)) {
303                        *chunk_counts.entry(window.to_vec()).or_insert(0) += 1;
304                    }
305                });
306            }
307        }
308
309        let mut chunks: Vec<(Vec<u8>, u64)> = chunk_counts.into_iter().collect();
310        chunks.sort_unstable();
311        let unique_chunks = chunks.len() as u64;
312        let counts: Vec<u64> = chunks.iter().map(|(_, c)| *c).collect();
313        let words: Vec<Vec<u32>> = chunks.into_iter().map(|(c, _)| c.into_iter().map(u32::from).collect()).collect();
314
315        let max_merges = config.vocab_size - 256 - reserved;
316        let mut lengths: Vec<usize> = vec![1; 256];
317        let limit = config.max_token_length;
318        let learned = train_merges(words, &counts, 256, max_merges, config.min_frequency, |l, r| {
319            let len = lengths[l as usize] + lengths[r as usize];
320            if limit.map_or(true, |m| len <= m) && len <= kute_types::vocab::MAX_TOKEN_BYTES {
321                lengths.push(len);
322                true
323            } else {
324                false
325            }
326        });
327
328        let mut statistics = BTreeMap::new();
329        statistics.insert("corpus_records".to_string(), fingerprint.records());
330        statistics.insert("corpus_bytes".to_string(), fingerprint.units());
331        statistics.insert("unique_chunks".to_string(), unique_chunks);
332        statistics.insert("merges_learned".to_string(), learned.len() as u64);
333        statistics.insert("requested_vocab_size".to_string(), config.vocab_size as u64);
334        let merges: Vec<(u32, u32, u32, Option<u64>)> = learned.iter().map(|m| (m.left, m.right, m.id, Some(m.count))).collect();
335        let vocabulary = build_vocabulary(ALGORITHM, config, &merges, statistics, fingerprint.finish())?;
336        self.finish_training(vocabulary, samples)
337    }
338
339    fn load(&mut self, mut vocabulary: Vocabulary) -> Result<()> {
340        vocabulary.validate()?;
341        if !COMPATIBLE_ALGORITHMS.contains(&vocabulary.manifest.algorithm.as_str()) {
342            return Err(KuteError::VocabularyMismatch(format!(
343                "the bpe tokenizer cannot interpret a {:?} vocabulary",
344                vocabulary.manifest.algorithm
345            )));
346        }
347        if vocabulary.manifest.payload_kind != PayloadKind::Bytes || vocabulary.tokens.len() < 256 {
348            return Err(KuteError::InvalidVocabulary("byte BPE needs the 256 byte tokens first".into()));
349        }
350        for (i, t) in vocabulary.tokens.iter().take(256).enumerate() {
351            if t.kind != TokenKind::Byte || t.payload != TokenPayload::Bytes(vec![i as u8]) {
352                return Err(KuteError::InvalidVocabulary(format!("token {i} must be the byte {i}")));
353            }
354        }
355        let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
356        for m in &vocabulary.merges {
357            if ranks.insert((m.left, m.right), m.id).is_some() {
358                return Err(KuteError::InvalidVocabulary(format!("pair ({}, {}) has two merge rules", m.left, m.right)));
359            }
360        }
361        let regex = compile(vocabulary.pretokenizer.as_deref()).map_err(|e| KuteError::InvalidVocabulary(e.to_string()))?;
362        if vocabulary.integrity.is_none() {
363            vocabulary.seal()?;
364        }
365        self.loaded = Some(Loaded { vocabulary, ranks, regex });
366        Ok(())
367    }
368
369    fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence> {
370        let loaded = self.loaded()?;
371        let Payload::Bytes(bytes) = &input.payload else {
372            return Err(KuteError::InvalidInput("the bpe algorithm takes byte payloads".into()));
373        };
374        sequence_for(&loaded.vocabulary, input.modality, encode_bytes(loaded, bytes))
375    }
376
377    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
378        let loaded = self.loaded()?;
379        check_sequence(&loaded.vocabulary, tokens)?;
380        let mut out = Vec::with_capacity(tokens.ids.len() * 3);
381        for &id in &tokens.ids {
382            match &loaded.vocabulary.token(id)?.payload {
383                TokenPayload::Bytes(b) => out.extend_from_slice(b),
384                TokenPayload::Symbols(_) => return Err(KuteError::InvalidVocabulary("symbol token in a byte vocabulary".into())),
385            }
386        }
387        Ok(CanonicalInput::bytes(tokens.modality, out))
388    }
389
390    fn vocabulary(&self) -> Option<&Vocabulary> {
391        self.loaded.as_ref().map(|l| &l.vocabulary)
392    }
393
394    fn capabilities(&self) -> TokenizerCapabilities {
395        TokenizerCapabilities {
396            algorithm: ALGORITHM.to_string(),
397            lossless: true,
398            trainable: true,
399            deterministic: true,
400            accepts: vec![PayloadKind::Bytes],
401            rejects_unknown: false,
402            notes: "Native byte-level BPE. Every byte value is a token, so any input encodes and decodes exactly.".to_string(),
403        }
404    }
405}
406
407impl BpeTokenizer {
408    /// Install the trained vocabulary, record self-test vectors, and seal it.
409    fn finish_training(&mut self, vocabulary: Vocabulary, samples: Vec<Vec<u8>>) -> Result<Vocabulary> {
410        self.load(vocabulary)?;
411        let loaded = self.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
412        let vectors: Vec<TestVector> = samples
413            .into_iter()
414            .map(|s| {
415                let ids = encode_bytes(loaded, &s);
416                TestVector { input: TokenPayload::Bytes(s), ids }
417            })
418            .collect();
419        loaded.vocabulary.test_vectors = vectors;
420        loaded.vocabulary.seal()?;
421        Ok(loaded.vocabulary.clone())
422    }
423}
424
425/// Up to `max` leading bytes, cut on a UTF-8 boundary when the data is text.
426#[doc(hidden)]
427pub fn sample_prefix(bytes: &[u8], max: usize) -> Vec<u8> {
428    if bytes.len() <= max {
429        return bytes.to_vec();
430    }
431    let mut end = max;
432    if std::str::from_utf8(bytes).is_ok() {
433        while end > 0 && (bytes[end] & 0xc0) == 0x80 {
434            end -= 1;
435        }
436    }
437    bytes[..end.max(1)].to_vec()
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443    use kute_types::config::GPT4_PATTERN;
444    use kute_types::VocabularyId;
445
446    fn chunks(splitter: &Splitter, text: &str) -> Vec<String> {
447        let mut out = Vec::new();
448        for_each_chunk(Some(splitter), text.as_bytes(), |c| out.push(String::from_utf8(c.to_vec()).unwrap()));
449        out
450    }
451
452    fn xorshift(state: &mut u64) -> u64 {
453        *state ^= *state << 13;
454        *state ^= *state >> 7;
455        *state ^= *state << 17;
456        *state
457    }
458
459    /// The automaton path for the GPT-4 preset must split exactly as the
460    /// backtracking engine does on the preset as written.
461    #[test]
462    fn fast_gpt4_splitter_matches_the_pattern() {
463        let Some(fast @ Splitter::Gpt4(_)) = compile(Some(GPT4_PATTERN)).unwrap() else { panic!("preset should take the fast path") };
464        let reference = Splitter::Fancy(compile_fancy(GPT4_PATTERN).unwrap());
465        let mut cases: Vec<String> = [
466            "", " ", "  ", "   a", "a   ", "a \n b", "a  \n\n  b", "\n\n\n", " \n", "\r\n\r\n x", "don't we'll I'VE it'S 'tis ''", "x = 12345.678e-9;",
467            "tabs\t\tand\t spaces  \t", "end with spaces   ", "naïve café 日本語 テスト", "emoji 🙂🙂 ok", "nbsp\u{a0}\u{a0}x \u{2028} y\u{3000}\u{3000}z",
468            "e\u{301}tude \u{301}\u{301}", "٣٤٥ ١٢٣٤ ⅷ", "fn main() {\n    println!(\"{}\", 1);\n}\n", "a\n\nb\n \nc \n", "!!!\n\n\nabc", " !a", "  !", "\t\n\t\nx",
469        ]
470        .iter()
471        .map(|s| s.to_string())
472        .collect();
473        let alphabet: Vec<char> = "abcXYZ 012  \t\n\r'.,!?-_(){}\u{a0}\u{2028}\u{3000}é日ß\u{301}٣🙂".chars().collect();
474        let mut state = 0x2545f4914f6cdd1du64;
475        for _ in 0..4000 {
476            let len = xorshift(&mut state) % 40;
477            cases.push((0..len).map(|_| alphabet[(xorshift(&mut state) % alphabet.len() as u64) as usize]).collect());
478        }
479        for text in &cases {
480            let (a, b) = (chunks(&fast, text), chunks(&reference, text));
481            assert_eq!(a, b, "input {text:?}");
482            assert_eq!(a.concat(), *text);
483        }
484    }
485
486    /// Encoding a long text in parallel pieces gives the ids of one serial pass.
487    #[test]
488    fn parallel_encode_matches_serial() {
489        let words = ["alpha", "beta", "gamma", "delta", "x1", "42", "naïve", "日本", "don't", "--", "\t"];
490        let mut state = 0x9e3779b97f4a7c15u64;
491        let mut text = String::new();
492        while text.len() < (PARALLEL_MIN_BYTES * 5) / 2 {
493            for _ in 0..(1 + xorshift(&mut state) % 14) {
494                text.push_str(words[(xorshift(&mut state) % words.len() as u64) as usize]);
495                text.push_str(if xorshift(&mut state) % 9 == 0 { "  " } else { " " });
496            }
497            text.push_str(match xorshift(&mut state) % 5 { 0 => "\n\n", 1 => " \n", 2 => "\r\n", _ => "\n" });
498        }
499        let mut config = TrainingConfig::new(VocabularyId::parse("test:parallel").unwrap(), 400);
500        config.pretokenizer = kute_types::Pretokenizer::Gpt4;
501        let mut tokenizer = BpeTokenizer::new();
502        let sample = CanonicalInput::bytes(Modality::Text, text.as_bytes()[..60_000].to_vec());
503        tokenizer.train(&mut kute_core::VecCorpus::new(vec![sample]), &config).unwrap();
504        let loaded = tokenizer.loaded().unwrap();
505        assert!(parallel_cuts(text.as_bytes()).len() > 3, "the text should be cut into several pieces");
506        assert_eq!(encode_bytes(loaded, text.as_bytes()), encode_piece(loaded, text.as_bytes()));
507    }
508}