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, resumable_merges, train_merges, LearnedMerge, 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 if bytes.len() >= PARALLEL_MIN_BYTES && matches!(regex, Some(Splitter::Gpt4(_))) {
299                // A long text under the preset is cut where no match can
300                // cross (see `parallel_cuts`), the pieces are counted on
301                // every core, and the counts are added up. The chunks, and
302                // so the vocabulary, are the same as for the whole text.
303                let cuts = parallel_cuts(bytes);
304                let window = config.train_window.max(4096);
305                let parts: Vec<FxHashMap<&[u8], u64>> = cuts
306                    .par_windows(2)
307                    .map(|c| {
308                        let mut local: FxHashMap<&[u8], u64> = FxHashMap::default();
309                        for_each_chunk(regex.as_ref(), &bytes[c[0]..c[1]], |chunk| {
310                            for w in chunk.chunks(window) {
311                                *local.entry(w).or_insert(0) += 1;
312                            }
313                        });
314                        local
315                    })
316                    .collect();
317                for part in parts {
318                    for (chunk, n) in part {
319                        match chunk_counts.get_mut(chunk) {
320                            Some(total) => *total += n,
321                            None => {
322                                chunk_counts.insert(chunk.to_vec(), n);
323                            }
324                        }
325                    }
326                }
327            } else {
328                for_each_chunk(regex.as_ref(), bytes, |chunk| {
329                    // A pattern that matches nothing would hand back the whole
330                    // record; keep counting bounded either way.
331                    for window in chunk.chunks(config.train_window.max(4096)) {
332                        *chunk_counts.entry(window.to_vec()).or_insert(0) += 1;
333                    }
334                });
335            }
336        }
337
338        let mut chunks: Vec<(Vec<u8>, u64)> = chunk_counts.into_iter().collect();
339        chunks.sort_unstable();
340        let unique_chunks = chunks.len() as u64;
341        let counts: Vec<u64> = chunks.iter().map(|(_, c)| *c).collect();
342        let mut words: Vec<Vec<u32>> = chunks.into_iter().map(|(c, _)| c.into_iter().map(u32::from).collect()).collect();
343
344        let max_merges = config.vocab_size - 256 - reserved;
345        let mut lengths: Vec<usize> = vec![1; 256];
346        let limit = config.max_token_length;
347        let corpus_records = fingerprint.records();
348        let corpus_units = fingerprint.units();
349        let corpus_fingerprint = fingerprint.finish();
350
351        // Resuming: bring the words to the state the earlier run left them
352        // in. Which pair is merged next depends only on that state, so
353        // learning continues exactly as it would have.
354        let mut kept: Vec<LearnedMerge> = Vec::new();
355        if let Some(prior) = &config.resume_from {
356            kept = resumable_merges(prior, ALGORITHM, config, &corpus_fingerprint, 256, max_merges)?;
357            let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
358            for m in &kept {
359                ranks.insert((m.left, m.right), m.id);
360                lengths.push(lengths[m.left as usize] + lengths[m.right as usize]);
361            }
362            words.par_iter_mut().for_each(|w| apply_merges(w, &ranks));
363        }
364        let resumed = kept.len() as u32;
365        let more = train_merges(words, &counts, 256 + resumed, max_merges - resumed, config.min_frequency, |l, r| {
366            let len = lengths[l as usize] + lengths[r as usize];
367            if limit.is_none_or(|m| len <= m) && len <= kute_types::vocab::MAX_TOKEN_BYTES {
368                lengths.push(len);
369                true
370            } else {
371                false
372            }
373        });
374
375        let mut learned = kept;
376        learned.extend(more);
377
378        let mut statistics = BTreeMap::new();
379        statistics.insert("corpus_records".to_string(), corpus_records);
380        statistics.insert("corpus_bytes".to_string(), corpus_units);
381        statistics.insert("unique_chunks".to_string(), unique_chunks);
382        statistics.insert("merges_learned".to_string(), learned.len() as u64);
383        statistics.insert("requested_vocab_size".to_string(), config.vocab_size as u64);
384        let merges: Vec<(u32, u32, u32, Option<u64>)> = learned.iter().map(|m| (m.left, m.right, m.id, Some(m.count))).collect();
385        let vocabulary = build_vocabulary(ALGORITHM, config, &merges, statistics, corpus_fingerprint)?;
386        self.finish_training(vocabulary, samples, config.embed_test_vectors)
387    }
388
389    fn load(&mut self, mut vocabulary: Vocabulary) -> Result<()> {
390        vocabulary.validate()?;
391        if !COMPATIBLE_ALGORITHMS.contains(&vocabulary.manifest.algorithm.as_str()) {
392            return Err(KuteError::VocabularyMismatch(format!(
393                "the bpe tokenizer cannot interpret a {:?} vocabulary",
394                vocabulary.manifest.algorithm
395            )));
396        }
397        if vocabulary.manifest.payload_kind != PayloadKind::Bytes || vocabulary.tokens.len() < 256 {
398            return Err(KuteError::InvalidVocabulary("byte BPE needs the 256 byte tokens first".into()));
399        }
400        for (i, t) in vocabulary.tokens.iter().take(256).enumerate() {
401            if t.kind != TokenKind::Byte || t.payload != TokenPayload::Bytes(vec![i as u8]) {
402                return Err(KuteError::InvalidVocabulary(format!("token {i} must be the byte {i}")));
403            }
404        }
405        let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
406        for m in &vocabulary.merges {
407            if ranks.insert((m.left, m.right), m.id).is_some() {
408                return Err(KuteError::InvalidVocabulary(format!("pair ({}, {}) has two merge rules", m.left, m.right)));
409            }
410        }
411        let regex = compile(vocabulary.pretokenizer.as_deref()).map_err(|e| KuteError::InvalidVocabulary(e.to_string()))?;
412        if vocabulary.integrity.is_none() {
413            vocabulary.seal()?;
414        }
415        self.loaded = Some(Loaded { vocabulary, ranks, regex });
416        Ok(())
417    }
418
419    fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence> {
420        let loaded = self.loaded()?;
421        let Payload::Bytes(bytes) = &input.payload else {
422            return Err(KuteError::InvalidInput("the bpe algorithm takes byte payloads".into()));
423        };
424        sequence_for(&loaded.vocabulary, input.modality, encode_bytes(loaded, bytes))
425    }
426
427    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
428        let loaded = self.loaded()?;
429        check_sequence(&loaded.vocabulary, tokens)?;
430        let mut out = Vec::with_capacity(tokens.ids.len() * 3);
431        for &id in &tokens.ids {
432            match &loaded.vocabulary.token(id)?.payload {
433                TokenPayload::Bytes(b) => out.extend_from_slice(b),
434                TokenPayload::Symbols(_) => return Err(KuteError::InvalidVocabulary("symbol token in a byte vocabulary".into())),
435            }
436        }
437        Ok(CanonicalInput::bytes(tokens.modality, out))
438    }
439
440    fn vocabulary(&self) -> Option<&Vocabulary> {
441        self.loaded.as_ref().map(|l| &l.vocabulary)
442    }
443
444    fn capabilities(&self) -> TokenizerCapabilities {
445        TokenizerCapabilities {
446            algorithm: ALGORITHM.to_string(),
447            lossless: true,
448            trainable: true,
449            deterministic: true,
450            accepts: vec![PayloadKind::Bytes],
451            rejects_unknown: false,
452            notes: "Native byte-level BPE. Every byte value is a token, so any input encodes and decodes exactly.".to_string(),
453        }
454    }
455}
456
457impl BpeTokenizer {
458    /// Install the trained vocabulary, record self-test vectors, and seal it.
459    fn finish_training(&mut self, vocabulary: Vocabulary, samples: Vec<Vec<u8>>, embed: bool) -> Result<Vocabulary> {
460        self.load(vocabulary)?;
461        let loaded = self.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
462        let vectors: Vec<TestVector> = samples
463            .into_iter()
464            .filter(|_| embed)
465            .map(|s| {
466                let ids = encode_bytes(loaded, &s);
467                TestVector { input: TokenPayload::Bytes(s), ids }
468            })
469            .collect();
470        loaded.vocabulary.test_vectors = vectors;
471        loaded.vocabulary.seal()?;
472        Ok(loaded.vocabulary.clone())
473    }
474}
475
476/// Up to `max` leading bytes, cut on a UTF-8 boundary when the data is text.
477#[doc(hidden)]
478pub fn sample_prefix(bytes: &[u8], max: usize) -> Vec<u8> {
479    if bytes.len() <= max {
480        return bytes.to_vec();
481    }
482    let mut end = max;
483    if std::str::from_utf8(bytes).is_ok() {
484        while end > 0 && (bytes[end] & 0xc0) == 0x80 {
485            end -= 1;
486        }
487    }
488    bytes[..end.max(1)].to_vec()
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use kute_types::config::GPT4_PATTERN;
495    use kute_types::VocabularyId;
496
497    fn chunks(splitter: &Splitter, text: &str) -> Vec<String> {
498        let mut out = Vec::new();
499        for_each_chunk(Some(splitter), text.as_bytes(), |c| out.push(String::from_utf8(c.to_vec()).unwrap()));
500        out
501    }
502
503    fn xorshift(state: &mut u64) -> u64 {
504        *state ^= *state << 13;
505        *state ^= *state >> 7;
506        *state ^= *state << 17;
507        *state
508    }
509
510    /// The automaton path for the GPT-4 preset must split exactly as the
511    /// backtracking engine does on the preset as written.
512    #[test]
513    fn fast_gpt4_splitter_matches_the_pattern() {
514        let Some(fast @ Splitter::Gpt4(_)) = compile(Some(GPT4_PATTERN)).unwrap() else { panic!("preset should take the fast path") };
515        let reference = Splitter::Fancy(compile_fancy(GPT4_PATTERN).unwrap());
516        let mut cases: Vec<String> = [
517            "", " ", "  ", "   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;",
518            "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",
519            "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",
520        ]
521        .iter()
522        .map(|s| s.to_string())
523        .collect();
524        let alphabet: Vec<char> = "abcXYZ 012  \t\n\r'.,!?-_(){}\u{a0}\u{2028}\u{3000}é日ß\u{301}٣🙂".chars().collect();
525        let mut state = 0x2545f4914f6cdd1du64;
526        for _ in 0..4000 {
527            let len = xorshift(&mut state) % 40;
528            cases.push((0..len).map(|_| alphabet[(xorshift(&mut state) % alphabet.len() as u64) as usize]).collect());
529        }
530        for text in &cases {
531            let (a, b) = (chunks(&fast, text), chunks(&reference, text));
532            assert_eq!(a, b, "input {text:?}");
533            assert_eq!(a.concat(), *text);
534        }
535    }
536
537    /// Encoding a long text in parallel pieces gives the ids of one serial pass.
538    #[test]
539    fn parallel_encode_matches_serial() {
540        let words = ["alpha", "beta", "gamma", "delta", "x1", "42", "naïve", "日本", "don't", "--", "\t"];
541        let mut state = 0x9e3779b97f4a7c15u64;
542        let mut text = String::new();
543        while text.len() < (PARALLEL_MIN_BYTES * 5) / 2 {
544            for _ in 0..(1 + xorshift(&mut state) % 14) {
545                text.push_str(words[(xorshift(&mut state) % words.len() as u64) as usize]);
546                text.push_str(if xorshift(&mut state) % 9 == 0 { "  " } else { " " });
547            }
548            text.push_str(match xorshift(&mut state) % 5 { 0 => "\n\n", 1 => " \n", 2 => "\r\n", _ => "\n" });
549        }
550        let mut config = TrainingConfig::new(VocabularyId::parse("test:parallel").unwrap(), 400);
551        config.pretokenizer = kute_types::Pretokenizer::Gpt4;
552        let mut tokenizer = BpeTokenizer::new();
553        let sample = CanonicalInput::bytes(Modality::Text, text.as_bytes()[..60_000].to_vec());
554        tokenizer.train(&mut kute_core::VecCorpus::new(vec![sample]), &config).unwrap();
555        let loaded = tokenizer.loaded().unwrap();
556        assert!(parallel_cuts(text.as_bytes()).len() > 3, "the text should be cut into several pieces");
557        assert_eq!(encode_bytes(loaded, text.as_bytes()), encode_piece(loaded, text.as_bytes()));
558    }
559
560    /// Counting a long text on several cores gives the vocabulary that
561    /// counting its pieces one after another gives.
562    #[test]
563    fn parallel_training_matches_serial() {
564        let words = ["alpha", "beta", "gamma", "delta", "x1", "42", "naïve", "日本", "don't", "--", "\t", "Ab", "aB"];
565        let mut state = 0x243f6a8885a308d3u64;
566        let mut text = String::new();
567        while text.len() < (PARALLEL_MIN_BYTES * 7) / 2 {
568            for _ in 0..(1 + xorshift(&mut state) % 14) {
569                text.push_str(words[(xorshift(&mut state) % words.len() as u64) as usize]);
570                text.push_str(if xorshift(&mut state) % 9 == 0 { "  " } else { " " });
571            }
572            text.push_str(match xorshift(&mut state) % 5 { 0 => "\n\n", 1 => " \n", 2 => "\r\n", _ => "\n" });
573        }
574        let bytes = text.as_bytes();
575        let cuts = parallel_cuts(bytes);
576        assert!(cuts.len() > 8);
577        let mut config = TrainingConfig::new(VocabularyId::parse("test:parallel-train").unwrap(), 700);
578        config.pretokenizer = kute_types::Pretokenizer::Gpt4;
579        let whole = BpeTokenizer::new().train(&mut kute_core::VecCorpus::new(vec![CanonicalInput::bytes(Modality::Text, bytes.to_vec())]), &config).unwrap();
580        // every piece is below the size at which counting goes parallel
581        let pieces: Vec<CanonicalInput> = cuts.windows(2).map(|c| CanonicalInput::bytes(Modality::Text, bytes[c[0]..c[1]].to_vec())).collect();
582        assert!(cuts.windows(2).all(|c| c[1] - c[0] < PARALLEL_MIN_BYTES));
583        let apart = BpeTokenizer::new().train(&mut kute_core::VecCorpus::new(pieces), &config).unwrap();
584        assert_eq!(whole.tokens, apart.tokens);
585        assert_eq!(whole.merges, apart.merges);
586        assert_eq!(whole.statistics.get("unique_chunks"), apart.statistics.get("unique_chunks"));
587        assert!(whole.merges.len() > 20, "{}", whole.merges.len());
588    }
589
590    /// The pieces between cut points split into the chunks the whole text
591    /// splits into, in the same order, for text built to put every kind of
592    /// boundary next to a line feed, and for lengths just under, at and just
593    /// over the size at which counting goes parallel.
594    #[test]
595    fn cut_pieces_chunk_as_the_whole_does() {
596        let regex = compile(kute_types::Pretokenizer::Gpt4.pattern()).unwrap();
597        let parts = [
598            "alpha", "Beta", "x", "don't", "'s", "'ll", "42", "1234567", "naïve", "日本", "é", "--", "...", "!", "'", "\"", " ", "  ", "\t",
599            "\u{a0}", "\u{2028}", "\u{85}", "\n", "\n\n", "\r\n", "\r", " \n", "\n ", "\t\n", ".\n", "!\n\n", "'\n", "9\n", "é\n", " \r\n",
600        ];
601        let mut state = 0x9e3779b97f4a7c15u64;
602        for round in 0..6 {
603            let target = match round {
604                0 => PARALLEL_MIN_BYTES - 1,
605                1 => PARALLEL_MIN_BYTES,
606                2 => PARALLEL_MIN_BYTES + 1,
607                _ => PARALLEL_MIN_BYTES * 2 + (xorshift(&mut state) % 4096) as usize,
608            };
609            let mut text = String::new();
610            while text.len() < target {
611                text.push_str(parts[(xorshift(&mut state) % parts.len() as u64) as usize]);
612            }
613            // Trim to the exact length on a character boundary, then pad with letters.
614            while text.len() > target {
615                text.pop();
616            }
617            while text.len() < target {
618                text.push('a');
619            }
620            let bytes = text.as_bytes();
621            let mut whole: Vec<&[u8]> = Vec::new();
622            for_each_chunk(regex.as_ref(), bytes, |c| whole.push(c));
623            let cuts = parallel_cuts(bytes);
624            assert!(cuts.len() > 3, "round {round}: the text should be cut");
625            let mut apart: Vec<&[u8]> = Vec::new();
626            for c in cuts.windows(2) {
627                for_each_chunk(regex.as_ref(), &bytes[c[0]..c[1]], |c| apart.push(c));
628            }
629            if let Some(i) = (0..whole.len().min(apart.len())).find(|&i| whole[i] != apart[i]) {
630                panic!("round {round}: chunk {i} is {:?} in the whole text and {:?} in the pieces", String::from_utf8_lossy(whole[i]), String::from_utf8_lossy(apart[i]));
631            }
632            assert_eq!(whole.len(), apart.len(), "round {round}");
633        }
634    }
635}