kute-bpe 0.9.1

Byte Pair Encoding for KUTE: native byte-level BPE and BPE over symbol sequences
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Native byte-level BPE. Ids 0..=255 are the byte values, learned merges
//! follow, reserved tokens come last. Lossless for arbitrary bytes.

use crate::merge::{apply_merges, resumable_merges, train_merges, LearnedMerge, Pair};
use fancy_regex::Regex;
use rayon::prelude::*;
use kute_core::{check_sequence, sequence_for, CorpusFingerprint, CorpusSource, Tokenizer};
use kute_types::{
    CanonicalInput, KuteError, Manifest, MergeRule, Modality, Payload, PayloadKind, Provenance, Result,
    TestVector, TokenEntry, TokenKind, TokenPayload, TokenSequence, TokenizerCapabilities, TrainingConfig,
    Vocabulary, KUTE_VERSION, KVF_VERSION,
};
use rustc_hash::FxHashMap;
use std::collections::BTreeMap;

pub const ALGORITHM: &str = "bpe";
/// Vocabularies written by the rustbpe backend use the same table layout and
/// are read by this tokenizer too.
pub const COMPATIBLE_ALGORITHMS: &[&str] = &["bpe", "rustbpe"];

struct Loaded {
    vocabulary: Vocabulary,
    ranks: FxHashMap<Pair, u32>,
    regex: Option<Splitter>,
}

/// How a pre-tokenizer pattern is executed.
pub(crate) enum Splitter {
    /// Any pattern, on the backtracking engine.
    Fancy(Regex),
    /// The GPT-4 preset on the automaton engine. The preset's possessive
    /// quantifiers never change what it matches (each guards a character class
    /// disjoint from what follows), so they are dropped; its one lookahead,
    /// `\s+(?!\S)`, is applied by hand in `for_each_chunk`. The differential
    /// test in this file holds the two engines to identical chunks.
    Gpt4(regex::Regex),
}

const 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+";

#[derive(Default)]
pub struct BpeTokenizer {
    loaded: Option<Loaded>,
}

impl BpeTokenizer {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn boxed() -> Box<dyn Tokenizer> {
        Box::new(Self::new())
    }

    fn loaded(&self) -> Result<&Loaded> {
        self.loaded.as_ref().ok_or_else(|| KuteError::NotTrained("train or load a vocabulary first".into()))
    }
}

pub(crate) fn compile(pattern: Option<&str>) -> Result<Option<Splitter>> {
    match pattern {
        None => Ok(None),
        Some(p) if p == kute_types::config::GPT4_PATTERN => regex::Regex::new(GPT4_FAST)
            .map(|re| Some(Splitter::Gpt4(re)))
            .map_err(|e| KuteError::InvalidConfig(format!("pretokenizer pattern does not compile: {e}"))),
        Some(p) => compile_fancy(p).map(|re| Some(Splitter::Fancy(re))),
    }
}

fn compile_fancy(pattern: &str) -> Result<Regex> {
    Regex::new(pattern).map_err(|e| KuteError::InvalidConfig(format!("pretokenizer pattern does not compile: {e}")))
}

/// Split `bytes` into chunks and hand each to `f`. Every byte is delivered
/// exactly once and in order, whatever the pattern matches, so chunking can
/// never lose information: text the pattern skips becomes its own chunk, and
/// input that is not valid UTF-8 (or that the regex engine gives up on) is
/// delivered whole.
pub(crate) fn for_each_chunk<'a>(splitter: Option<&Splitter>, bytes: &'a [u8], mut f: impl FnMut(&'a [u8])) {
    if bytes.is_empty() {
        return;
    }
    let (Some(splitter), Ok(text)) = (splitter, std::str::from_utf8(bytes)) else {
        f(bytes);
        return;
    };
    let re = match splitter {
        Splitter::Fancy(re) => re,
        Splitter::Gpt4(re) => {
            let mut at = 0;
            while at < text.len() {
                let Some(m) = re.find_at(text, at) else { break };
                let (start, mut end) = (m.start(), m.end());
                if end <= start {
                    break;
                }
                // `\s+(?!\S)`: a whitespace run that stops before a non-space
                // gives its last character back. Only the `\s+` branch can
                // end in whitespace other than a line break.
                if end < text.len() {
                    if let Some(c) = text[start..end].chars().next_back() {
                        if c.is_whitespace() && c != '\n' && c != '\r' && end - start > c.len_utf8() {
                            end -= c.len_utf8();
                        }
                    }
                }
                if start > at {
                    f(&bytes[at..start]);
                }
                f(&bytes[start..end]);
                at = end;
            }
            if at < bytes.len() {
                f(&bytes[at..]);
            }
            return;
        }
    };
    let mut last = 0;
    for m in re.find_iter(text) {
        let Ok(m) = m else { break };
        if m.end() <= m.start() || m.start() < last {
            continue;
        }
        if m.start() > last {
            f(&bytes[last..m.start()]);
        }
        f(&bytes[m.start()..m.end()]);
        last = m.end();
    }
    if last < bytes.len() {
        f(&bytes[last..]);
    }
}

/// Inputs at least this long are encoded in pieces on several threads.
const PARALLEL_MIN_BYTES: usize = 1 << 20;
const PARALLEL_PIECE_BYTES: usize = 1 << 18;

/// Cut points for encoding a long text in parallel under the GPT-4 preset.
///
/// A cut is placed only between a line feed and an ASCII letter. No branch of
/// the preset can match across that position (line breaks only ever end a
/// match, and the one branch that starts with an optional non-letter excludes
/// line breaks), and the preset has no look-behind, so the pieces tokenize
/// exactly as the whole does.
fn parallel_cuts(bytes: &[u8]) -> Vec<usize> {
    let mut cuts = vec![0];
    let mut target = PARALLEL_PIECE_BYTES;
    while target < bytes.len() {
        match (target..bytes.len()).find(|&i| bytes[i - 1] == b'\n' && bytes[i].is_ascii_alphabetic()) {
            Some(i) => {
                cuts.push(i);
                target = i + PARALLEL_PIECE_BYTES;
            }
            None => break,
        }
    }
    cuts.push(bytes.len());
    cuts
}

fn encode_bytes(loaded: &Loaded, bytes: &[u8]) -> Vec<u32> {
    if bytes.len() >= PARALLEL_MIN_BYTES && matches!(loaded.regex, Some(Splitter::Gpt4(_))) && std::str::from_utf8(bytes).is_ok() {
        let cuts = parallel_cuts(bytes);
        if cuts.len() > 2 {
            let pieces: Vec<Vec<u32>> = cuts.par_windows(2).map(|w| encode_piece(loaded, &bytes[w[0]..w[1]])).collect();
            let mut out = Vec::with_capacity(pieces.iter().map(Vec::len).sum());
            for p in &pieces {
                out.extend_from_slice(p);
            }
            return out;
        }
    }
    encode_piece(loaded, bytes)
}

fn encode_piece(loaded: &Loaded, bytes: &[u8]) -> Vec<u32> {
    let mut out = Vec::with_capacity(bytes.len() / 2 + 1);
    let mut scratch: Vec<u32> = Vec::new();
    // Words repeat, so remember where each short chunk's ids already sit in
    // `out`. The cache lives for one call and never changes the result.
    const CACHE_CHUNK_MAX: usize = 48;
    const CACHE_ENTRIES_MAX: usize = 1 << 16;
    let cacheable = loaded.regex.is_some();
    let mut cache: FxHashMap<&[u8], (usize, usize)> = FxHashMap::default();
    for_each_chunk(loaded.regex.as_ref(), bytes, |chunk| {
        let cache_this = cacheable && chunk.len() <= CACHE_CHUNK_MAX;
        if cache_this {
            if let Some(&(start, len)) = cache.get(chunk) {
                out.extend_from_within(start..start + len);
                return;
            }
        }
        scratch.clear();
        scratch.extend(chunk.iter().map(|&b| b as u32));
        apply_merges(&mut scratch, &loaded.ranks);
        if cache_this && cache.len() < CACHE_ENTRIES_MAX {
            cache.insert(chunk, (out.len(), scratch.len()));
        }
        out.extend_from_slice(&scratch);
    });
    out
}

/// Assemble a byte-BPE vocabulary from learned merges. Shared with the
/// rustbpe backend so both write identical tables.
#[doc(hidden)]
pub fn build_vocabulary(
    algorithm: &str,
    config: &TrainingConfig,
    merges: &[(u32, u32, u32, Option<u64>)],
    statistics: BTreeMap<String, u64>,
    fingerprint: String,
) -> Result<Vocabulary> {
    let mut tokens: Vec<TokenEntry> = (0u32..256)
        .map(|b| TokenEntry { id: b, kind: TokenKind::Byte, payload: TokenPayload::Bytes(vec![b as u8]), frequency: None })
        .collect();
    let mut rules = Vec::with_capacity(merges.len());
    for &(left, right, id, count) in merges {
        if id as usize != tokens.len() || left >= id || right >= id {
            return Err(KuteError::Backend(format!("merge ({left}, {right}) -> {id} is out of order")));
        }
        let (TokenPayload::Bytes(a), TokenPayload::Bytes(b)) = (&tokens[left as usize].payload, &tokens[right as usize].payload) else {
            return Err(KuteError::Backend("byte BPE produced a non-byte token".into()));
        };
        let mut bytes = a.clone();
        bytes.extend_from_slice(b);
        tokens.push(TokenEntry { id, kind: TokenKind::Merge, payload: TokenPayload::Bytes(bytes), frequency: count });
        rules.push(MergeRule { left, right, id });
    }
    for name in &config.reserved_tokens {
        let id = tokens.len() as u32;
        tokens.push(TokenEntry { id, kind: TokenKind::Special, payload: TokenPayload::Bytes(name.as_bytes().to_vec()), frequency: None });
    }
    let modality = if config.pretokenizer.pattern().is_some() { Modality::Text } else { Modality::Binary };
    Ok(Vocabulary {
        manifest: Manifest {
            kvf_version: KVF_VERSION.to_string(),
            id: config.vocabulary_id.clone(),
            version: config.vocabulary_version.clone(),
            algorithm: algorithm.to_string(),
            modality,
            payload_kind: PayloadKind::Bytes,
            lossless: true,
            description: config.description.clone(),
            created: None,
            generator: format!("kute {KUTE_VERSION}"),
        },
        pretokenizer: config.pretokenizer.pattern().map(str::to_string),
        adapter: None,
        tokens,
        merges: rules,
        statistics,
        provenance: Provenance {
            corpus_fingerprints: vec![fingerprint],
            license: config.license.clone(),
            training: Some(serde_json::to_value(config)?),
        },
        test_vectors: Vec::new(),
        representations: Vec::new(),
        integrity: None,
    })
}

impl Tokenizer for BpeTokenizer {
    fn train(&mut self, corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Vocabulary> {
        config.validate()?;
        let reserved = config.reserved_tokens.len() as u32;
        if config.vocab_size < 256 + reserved {
            return Err(KuteError::InvalidConfig(format!(
                "byte BPE needs vocab_size of at least {} (256 bytes plus {reserved} reserved tokens)",
                256 + reserved
            )));
        }
        let regex = compile(config.pretokenizer.pattern())?;
        let mut fingerprint = CorpusFingerprint::new();
        let mut chunk_counts: FxHashMap<Vec<u8>, u64> = FxHashMap::default();
        let mut samples: Vec<Vec<u8>> = Vec::new();
        while let Some(record) = corpus.next_record()? {
            let Payload::Bytes(bytes) = &record.payload else {
                return Err(KuteError::InvalidInput("the bpe algorithm takes byte payloads; use sequence-bpe for symbols".into()));
            };
            fingerprint.update(&record);
            if let Some(limit) = config.max_corpus_units {
                if fingerprint.units() > limit {
                    return Err(KuteError::LimitExceeded(format!("corpus is larger than the max_corpus_units limit of {limit}")));
                }
            }
            if samples.len() < 4 && !bytes.is_empty() {
                samples.push(sample_prefix(bytes, 96));
            }
            let windowed = regex.is_none() || std::str::from_utf8(bytes).is_err();
            if windowed {
                for window in bytes.chunks(config.train_window) {
                    *chunk_counts.entry(window.to_vec()).or_insert(0) += 1;
                }
            } else if bytes.len() >= PARALLEL_MIN_BYTES && matches!(regex, Some(Splitter::Gpt4(_))) {
                // A long text under the preset is cut where no match can
                // cross (see `parallel_cuts`), the pieces are counted on
                // every core, and the counts are added up. The chunks, and
                // so the vocabulary, are the same as for the whole text.
                let cuts = parallel_cuts(bytes);
                let window = config.train_window.max(4096);
                let parts: Vec<FxHashMap<&[u8], u64>> = cuts
                    .par_windows(2)
                    .map(|c| {
                        let mut local: FxHashMap<&[u8], u64> = FxHashMap::default();
                        for_each_chunk(regex.as_ref(), &bytes[c[0]..c[1]], |chunk| {
                            for w in chunk.chunks(window) {
                                *local.entry(w).or_insert(0) += 1;
                            }
                        });
                        local
                    })
                    .collect();
                for part in parts {
                    for (chunk, n) in part {
                        match chunk_counts.get_mut(chunk) {
                            Some(total) => *total += n,
                            None => {
                                chunk_counts.insert(chunk.to_vec(), n);
                            }
                        }
                    }
                }
            } else {
                for_each_chunk(regex.as_ref(), bytes, |chunk| {
                    // A pattern that matches nothing would hand back the whole
                    // record; keep counting bounded either way.
                    for window in chunk.chunks(config.train_window.max(4096)) {
                        *chunk_counts.entry(window.to_vec()).or_insert(0) += 1;
                    }
                });
            }
        }

        let mut chunks: Vec<(Vec<u8>, u64)> = chunk_counts.into_iter().collect();
        chunks.sort_unstable();
        let unique_chunks = chunks.len() as u64;
        let counts: Vec<u64> = chunks.iter().map(|(_, c)| *c).collect();
        let mut words: Vec<Vec<u32>> = chunks.into_iter().map(|(c, _)| c.into_iter().map(u32::from).collect()).collect();

        let max_merges = config.vocab_size - 256 - reserved;
        let mut lengths: Vec<usize> = vec![1; 256];
        let limit = config.max_token_length;
        let corpus_records = fingerprint.records();
        let corpus_units = fingerprint.units();
        let corpus_fingerprint = fingerprint.finish();

        // Resuming: bring the words to the state the earlier run left them
        // in. Which pair is merged next depends only on that state, so
        // learning continues exactly as it would have.
        let mut kept: Vec<LearnedMerge> = Vec::new();
        if let Some(prior) = &config.resume_from {
            kept = resumable_merges(prior, ALGORITHM, config, &corpus_fingerprint, 256, max_merges)?;
            let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
            for m in &kept {
                ranks.insert((m.left, m.right), m.id);
                lengths.push(lengths[m.left as usize] + lengths[m.right as usize]);
            }
            words.par_iter_mut().for_each(|w| apply_merges(w, &ranks));
        }
        let resumed = kept.len() as u32;
        let more = train_merges(words, &counts, 256 + resumed, max_merges - resumed, config.min_frequency, |l, r| {
            let len = lengths[l as usize] + lengths[r as usize];
            if limit.is_none_or(|m| len <= m) && len <= kute_types::vocab::MAX_TOKEN_BYTES {
                lengths.push(len);
                true
            } else {
                false
            }
        });

        let mut learned = kept;
        learned.extend(more);

        let mut statistics = BTreeMap::new();
        statistics.insert("corpus_records".to_string(), corpus_records);
        statistics.insert("corpus_bytes".to_string(), corpus_units);
        statistics.insert("unique_chunks".to_string(), unique_chunks);
        statistics.insert("merges_learned".to_string(), learned.len() as u64);
        statistics.insert("requested_vocab_size".to_string(), config.vocab_size as u64);
        let merges: Vec<(u32, u32, u32, Option<u64>)> = learned.iter().map(|m| (m.left, m.right, m.id, Some(m.count))).collect();
        let vocabulary = build_vocabulary(ALGORITHM, config, &merges, statistics, corpus_fingerprint)?;
        self.finish_training(vocabulary, samples, config.embed_test_vectors)
    }

    fn load(&mut self, mut vocabulary: Vocabulary) -> Result<()> {
        vocabulary.validate()?;
        if !COMPATIBLE_ALGORITHMS.contains(&vocabulary.manifest.algorithm.as_str()) {
            return Err(KuteError::VocabularyMismatch(format!(
                "the bpe tokenizer cannot interpret a {:?} vocabulary",
                vocabulary.manifest.algorithm
            )));
        }
        if vocabulary.manifest.payload_kind != PayloadKind::Bytes || vocabulary.tokens.len() < 256 {
            return Err(KuteError::InvalidVocabulary("byte BPE needs the 256 byte tokens first".into()));
        }
        for (i, t) in vocabulary.tokens.iter().take(256).enumerate() {
            if t.kind != TokenKind::Byte || t.payload != TokenPayload::Bytes(vec![i as u8]) {
                return Err(KuteError::InvalidVocabulary(format!("token {i} must be the byte {i}")));
            }
        }
        let mut ranks: FxHashMap<Pair, u32> = FxHashMap::default();
        for m in &vocabulary.merges {
            if ranks.insert((m.left, m.right), m.id).is_some() {
                return Err(KuteError::InvalidVocabulary(format!("pair ({}, {}) has two merge rules", m.left, m.right)));
            }
        }
        let regex = compile(vocabulary.pretokenizer.as_deref()).map_err(|e| KuteError::InvalidVocabulary(e.to_string()))?;
        if vocabulary.integrity.is_none() {
            vocabulary.seal()?;
        }
        self.loaded = Some(Loaded { vocabulary, ranks, regex });
        Ok(())
    }

    fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence> {
        let loaded = self.loaded()?;
        let Payload::Bytes(bytes) = &input.payload else {
            return Err(KuteError::InvalidInput("the bpe algorithm takes byte payloads".into()));
        };
        sequence_for(&loaded.vocabulary, input.modality, encode_bytes(loaded, bytes))
    }

    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput> {
        let loaded = self.loaded()?;
        check_sequence(&loaded.vocabulary, tokens)?;
        let mut out = Vec::with_capacity(tokens.ids.len() * 3);
        for &id in &tokens.ids {
            match &loaded.vocabulary.token(id)?.payload {
                TokenPayload::Bytes(b) => out.extend_from_slice(b),
                TokenPayload::Symbols(_) => return Err(KuteError::InvalidVocabulary("symbol token in a byte vocabulary".into())),
            }
        }
        Ok(CanonicalInput::bytes(tokens.modality, out))
    }

    fn vocabulary(&self) -> Option<&Vocabulary> {
        self.loaded.as_ref().map(|l| &l.vocabulary)
    }

    fn capabilities(&self) -> TokenizerCapabilities {
        TokenizerCapabilities {
            algorithm: ALGORITHM.to_string(),
            lossless: true,
            trainable: true,
            deterministic: true,
            accepts: vec![PayloadKind::Bytes],
            rejects_unknown: false,
            notes: "Native byte-level BPE. Every byte value is a token, so any input encodes and decodes exactly.".to_string(),
        }
    }
}

impl BpeTokenizer {
    /// Install the trained vocabulary, record self-test vectors, and seal it.
    fn finish_training(&mut self, vocabulary: Vocabulary, samples: Vec<Vec<u8>>, embed: bool) -> Result<Vocabulary> {
        self.load(vocabulary)?;
        let loaded = self.loaded.as_mut().ok_or_else(|| KuteError::NotTrained("load failed".into()))?;
        let vectors: Vec<TestVector> = samples
            .into_iter()
            .filter(|_| embed)
            .map(|s| {
                let ids = encode_bytes(loaded, &s);
                TestVector { input: TokenPayload::Bytes(s), ids }
            })
            .collect();
        loaded.vocabulary.test_vectors = vectors;
        loaded.vocabulary.seal()?;
        Ok(loaded.vocabulary.clone())
    }
}

/// Up to `max` leading bytes, cut on a UTF-8 boundary when the data is text.
#[doc(hidden)]
pub fn sample_prefix(bytes: &[u8], max: usize) -> Vec<u8> {
    if bytes.len() <= max {
        return bytes.to_vec();
    }
    let mut end = max;
    if std::str::from_utf8(bytes).is_ok() {
        while end > 0 && (bytes[end] & 0xc0) == 0x80 {
            end -= 1;
        }
    }
    bytes[..end.max(1)].to_vec()
}

#[cfg(test)]
mod tests {
    use super::*;
    use kute_types::config::GPT4_PATTERN;
    use kute_types::VocabularyId;

    fn chunks(splitter: &Splitter, text: &str) -> Vec<String> {
        let mut out = Vec::new();
        for_each_chunk(Some(splitter), text.as_bytes(), |c| out.push(String::from_utf8(c.to_vec()).unwrap()));
        out
    }

    fn xorshift(state: &mut u64) -> u64 {
        *state ^= *state << 13;
        *state ^= *state >> 7;
        *state ^= *state << 17;
        *state
    }

    /// The automaton path for the GPT-4 preset must split exactly as the
    /// backtracking engine does on the preset as written.
    #[test]
    fn fast_gpt4_splitter_matches_the_pattern() {
        let Some(fast @ Splitter::Gpt4(_)) = compile(Some(GPT4_PATTERN)).unwrap() else { panic!("preset should take the fast path") };
        let reference = Splitter::Fancy(compile_fancy(GPT4_PATTERN).unwrap());
        let mut cases: Vec<String> = [
            "", " ", "  ", "   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;",
            "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",
            "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",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let alphabet: Vec<char> = "abcXYZ 012  \t\n\r'.,!?-_(){}\u{a0}\u{2028}\u{3000}é日ß\u{301}٣🙂".chars().collect();
        let mut state = 0x2545f4914f6cdd1du64;
        for _ in 0..4000 {
            let len = xorshift(&mut state) % 40;
            cases.push((0..len).map(|_| alphabet[(xorshift(&mut state) % alphabet.len() as u64) as usize]).collect());
        }
        for text in &cases {
            let (a, b) = (chunks(&fast, text), chunks(&reference, text));
            assert_eq!(a, b, "input {text:?}");
            assert_eq!(a.concat(), *text);
        }
    }

    /// Encoding a long text in parallel pieces gives the ids of one serial pass.
    #[test]
    fn parallel_encode_matches_serial() {
        let words = ["alpha", "beta", "gamma", "delta", "x1", "42", "naïve", "日本", "don't", "--", "\t"];
        let mut state = 0x9e3779b97f4a7c15u64;
        let mut text = String::new();
        while text.len() < (PARALLEL_MIN_BYTES * 5) / 2 {
            for _ in 0..(1 + xorshift(&mut state) % 14) {
                text.push_str(words[(xorshift(&mut state) % words.len() as u64) as usize]);
                text.push_str(if xorshift(&mut state) % 9 == 0 { "  " } else { " " });
            }
            text.push_str(match xorshift(&mut state) % 5 { 0 => "\n\n", 1 => " \n", 2 => "\r\n", _ => "\n" });
        }
        let mut config = TrainingConfig::new(VocabularyId::parse("test:parallel").unwrap(), 400);
        config.pretokenizer = kute_types::Pretokenizer::Gpt4;
        let mut tokenizer = BpeTokenizer::new();
        let sample = CanonicalInput::bytes(Modality::Text, text.as_bytes()[..60_000].to_vec());
        tokenizer.train(&mut kute_core::VecCorpus::new(vec![sample]), &config).unwrap();
        let loaded = tokenizer.loaded().unwrap();
        assert!(parallel_cuts(text.as_bytes()).len() > 3, "the text should be cut into several pieces");
        assert_eq!(encode_bytes(loaded, text.as_bytes()), encode_piece(loaded, text.as_bytes()));
    }

    /// Counting a long text on several cores gives the vocabulary that
    /// counting its pieces one after another gives.
    #[test]
    fn parallel_training_matches_serial() {
        let words = ["alpha", "beta", "gamma", "delta", "x1", "42", "naïve", "日本", "don't", "--", "\t", "Ab", "aB"];
        let mut state = 0x243f6a8885a308d3u64;
        let mut text = String::new();
        while text.len() < (PARALLEL_MIN_BYTES * 7) / 2 {
            for _ in 0..(1 + xorshift(&mut state) % 14) {
                text.push_str(words[(xorshift(&mut state) % words.len() as u64) as usize]);
                text.push_str(if xorshift(&mut state) % 9 == 0 { "  " } else { " " });
            }
            text.push_str(match xorshift(&mut state) % 5 { 0 => "\n\n", 1 => " \n", 2 => "\r\n", _ => "\n" });
        }
        let bytes = text.as_bytes();
        let cuts = parallel_cuts(bytes);
        assert!(cuts.len() > 8);
        let mut config = TrainingConfig::new(VocabularyId::parse("test:parallel-train").unwrap(), 700);
        config.pretokenizer = kute_types::Pretokenizer::Gpt4;
        let whole = BpeTokenizer::new().train(&mut kute_core::VecCorpus::new(vec![CanonicalInput::bytes(Modality::Text, bytes.to_vec())]), &config).unwrap();
        // every piece is below the size at which counting goes parallel
        let pieces: Vec<CanonicalInput> = cuts.windows(2).map(|c| CanonicalInput::bytes(Modality::Text, bytes[c[0]..c[1]].to_vec())).collect();
        assert!(cuts.windows(2).all(|c| c[1] - c[0] < PARALLEL_MIN_BYTES));
        let apart = BpeTokenizer::new().train(&mut kute_core::VecCorpus::new(pieces), &config).unwrap();
        assert_eq!(whole.tokens, apart.tokens);
        assert_eq!(whole.merges, apart.merges);
        assert_eq!(whole.statistics.get("unique_chunks"), apart.statistics.get("unique_chunks"));
        assert!(whole.merges.len() > 20, "{}", whole.merges.len());
    }

    /// The pieces between cut points split into the chunks the whole text
    /// splits into, in the same order, for text built to put every kind of
    /// boundary next to a line feed, and for lengths just under, at and just
    /// over the size at which counting goes parallel.
    #[test]
    fn cut_pieces_chunk_as_the_whole_does() {
        let regex = compile(kute_types::Pretokenizer::Gpt4.pattern()).unwrap();
        let parts = [
            "alpha", "Beta", "x", "don't", "'s", "'ll", "42", "1234567", "naïve", "日本", "é", "--", "...", "!", "'", "\"", " ", "  ", "\t",
            "\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",
        ];
        let mut state = 0x9e3779b97f4a7c15u64;
        for round in 0..6 {
            let target = match round {
                0 => PARALLEL_MIN_BYTES - 1,
                1 => PARALLEL_MIN_BYTES,
                2 => PARALLEL_MIN_BYTES + 1,
                _ => PARALLEL_MIN_BYTES * 2 + (xorshift(&mut state) % 4096) as usize,
            };
            let mut text = String::new();
            while text.len() < target {
                text.push_str(parts[(xorshift(&mut state) % parts.len() as u64) as usize]);
            }
            // Trim to the exact length on a character boundary, then pad with letters.
            while text.len() > target {
                text.pop();
            }
            while text.len() < target {
                text.push('a');
            }
            let bytes = text.as_bytes();
            let mut whole: Vec<&[u8]> = Vec::new();
            for_each_chunk(regex.as_ref(), bytes, |c| whole.push(c));
            let cuts = parallel_cuts(bytes);
            assert!(cuts.len() > 3, "round {round}: the text should be cut");
            let mut apart: Vec<&[u8]> = Vec::new();
            for c in cuts.windows(2) {
                for_each_chunk(regex.as_ref(), &bytes[c[0]..c[1]], |c| apart.push(c));
            }
            if let Some(i) = (0..whole.len().min(apart.len())).find(|&i| whole[i] != apart[i]) {
                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]));
            }
            assert_eq!(whole.len(), apart.len(), "round {round}");
        }
    }
}