snaptokens 0.2.2

Fast BPE tokenization from local Hugging Face tokenizer.json files
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
use memchr::{memchr_iter, memmem};
use serde::Deserialize;
use serde_json::Value;

use crate::pre_tokenized::{PreTokenizedString, Split as PtSplit};

use super::{Error, scanner::PatternId};

/// A pattern for a Split pre-tokenizer: either a literal string or a recognized tokenizer regex.
#[derive(Clone, Debug, Deserialize)]
pub enum Pattern {
    /// Literal string matched byte-for-byte.
    String(std::string::String),
    /// Fixed tokenizer grammar selected by its exact source string.
    Regex(std::string::String),
}

/// The direct matcher stored by a compiled Split pre-tokenizer.
#[derive(Clone, Debug)]
enum Matcher {
    Literal(Box<str>),
    Fixed(PatternId),
}

impl Matcher {
    /// Compile a config pattern into either literal search or a fixed scanner.
    fn from_pattern(pattern: Pattern) -> Result<Self, Error> {
        match pattern {
            Pattern::String(literal) => Ok(Self::Literal(literal.into_boxed_str())),
            Pattern::Regex(source) => PatternId::from_source(&source)
                .map(Self::Fixed)
                .ok_or_else(|| Error::Unsupported(format!("Split regex pattern: {source}"))),
        }
    }

    /// Visit each non-empty, non-overlapping match in ascending byte order.
    fn for_each_match(&self, input: &str, mut emit: impl FnMut(usize, usize)) {
        match self {
            Self::Fixed(pattern) => pattern.for_each_match(input, emit),
            Self::Literal(literal) => {
                let needle = literal.as_bytes();
                if needle.is_empty() {
                    return;
                }
                if needle.len() == 1 {
                    for start in memchr_iter(needle[0], input.as_bytes()) {
                        emit(start, start + 1);
                    }
                    return;
                }
                for start in memmem::find_iter(input.as_bytes(), needle) {
                    emit(start, start + needle.len());
                }
            }
        }
    }
}

/// How matched delimiters are handled in the output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
pub enum SplitBehavior {
    /// Discard matched segments entirely.
    Removed,
    /// Each matched segment becomes its own token.
    #[default]
    Isolated,
    /// Matched segments attach to the preceding token.
    MergedWithPrevious,
    /// Matched segments attach to the following token.
    MergedWithNext,
    /// Adjacent segments of the same kind are grouped into one token.
    Contiguous,
}

/// Raw deserialization helper for [`Split`].
#[derive(Deserialize)]
struct SplitRaw {
    pattern: Pattern,
    #[serde(default)]
    behavior: SplitBehavior,
    #[serde(default)]
    invert: bool,
}

/// A compiled fixed-pattern Split pre-tokenizer.
#[derive(Clone, Debug, Deserialize)]
#[serde(try_from = "SplitRaw")]
pub struct Split {
    matcher: Matcher,
    behavior: SplitBehavior,
    invert: bool,
}

impl TryFrom<SplitRaw> for Split {
    type Error = Error;

    /// Build a Split while rejecting regex sources outside the fixed tokenizer catalog.
    fn try_from(raw: SplitRaw) -> Result<Self, Error> {
        Self::from_parts(raw.pattern, raw.behavior, raw.invert)
    }
}

impl Split {
    /// Build a Split from already-deserialized fields.
    fn from_parts(pattern: Pattern, behavior: SplitBehavior, invert: bool) -> Result<Self, Error> {
        Ok(Self {
            matcher: Matcher::from_pattern(pattern)?,
            behavior,
            invert,
        })
    }

    /// Build a [`Split`] from raw tokenizer JSON fields.
    pub fn from_config(pattern: &Value, behavior: &str, invert: bool) -> Result<Self, Error> {
        let pattern = serde_json::from_value(pattern.clone())?;
        let behavior = serde_json::from_value(Value::String(behavior.to_string()))?;
        Self::from_parts(pattern, behavior, invert)
    }

    /// Return whether this Split can fuse its scan with an ASCII NFC proof.
    pub(crate) fn supports_ascii_nfc_fusion(&self) -> bool {
        self.behavior == SplitBehavior::Isolated
            && !self.invert
            && matches!(
                self.matcher,
                Matcher::Fixed(PatternId::Qwen | PatternId::QwenMark)
            )
    }

    /// Return whether this Split can stream its retained ranges without materialization.
    pub(crate) fn supports_fused_stream(&self) -> bool {
        if !self.invert {
            return self.behavior == SplitBehavior::Isolated;
        }
        self.behavior == SplitBehavior::Removed
            && matches!(
                self.matcher,
                Matcher::Fixed(PatternId::Llama | PatternId::LlamaContraction)
            )
    }

    /// Return the fixed scanner identity used by this Split, if any.
    pub(crate) fn pattern_id(&self) -> Option<PatternId> {
        match &self.matcher {
            Matcher::Fixed(pattern) => Some(*pattern),
            Matcher::Literal(_) => None,
        }
    }

    /// Visit the isolated matches and gaps that this Split would materialize.
    pub(crate) fn for_each_fused_piece(
        &self,
        input: &str,
        mut emit: impl FnMut(&str, usize, usize),
    ) {
        debug_assert!(self.supports_fused_stream());
        if let Matcher::Fixed(pattern @ (PatternId::Llama | PatternId::LlamaContraction)) =
            &self.matcher
        {
            let mut previous = 0;
            (*pattern).for_each_match(input, |start, end| {
                debug_assert_eq!(start, previous);
                emit(input, start, end);
                previous = end;
            });
            debug_assert_eq!(previous, input.len());
            return;
        }
        let mut previous = 0;
        self.matcher.for_each_match(input, |start, end| {
            if start > previous {
                emit(input, previous, start);
            }
            emit(input, start, end);
            previous = end;
        });
        if previous < input.len() {
            emit(input, previous, input.len());
        }
    }

    /// Refine the splits of a [`PreTokenizedString`] without changing its buffer.
    pub fn pre_tokenize(&self, pts: &mut PreTokenizedString) -> Result<(), Error> {
        if self.behavior == SplitBehavior::Isolated && !self.invert {
            self.pre_tokenize_isolated(pts);
            return Ok(());
        }
        if self.behavior == SplitBehavior::Removed && self.invert {
            self.pre_tokenize_removed_inverted(pts);
            return Ok(());
        }

        let mut new_splits = Vec::with_capacity(pts.splits().len().saturating_mul(2));
        for split in pts.splits() {
            if split.token_id.is_some() {
                new_splits.push(split.clone());
                continue;
            }

            let text = pts.split_text(split);
            if text.is_empty() {
                continue;
            }

            let base = split.range.start;
            let segments = self.find_segments(text);
            let ranges = self.apply_behavior(&segments);
            for (start, end) in ranges {
                if start < end {
                    new_splits.push(PtSplit {
                        range: (base + start)..(base + end),
                        token_id: None,
                    });
                }
            }
        }

        pts.refine_splits(new_splits);
        Ok(())
    }

    /// Append borrowed-input split ranges while simultaneously proving the text is ASCII.
    pub(crate) fn append_ascii_splits(
        &self,
        input: &str,
        base: usize,
        output: &mut Vec<PtSplit>,
    ) -> bool {
        debug_assert!(self.supports_ascii_nfc_fusion());
        if input.is_empty() {
            return true;
        }

        let Matcher::Fixed(pattern) = &self.matcher else {
            unreachable!("eligible ASCII fusion requires a fixed scanner");
        };
        let mut previous = 0;
        let complete = pattern.for_each_ascii_match(input, |start, end| {
            if start > previous {
                output.push(PtSplit {
                    range: (base + previous)..(base + start),
                    token_id: None,
                });
            }
            output.push(PtSplit {
                range: (base + start)..(base + end),
                token_id: None,
            });
            previous = end;
        });
        if !complete {
            return false;
        }
        if previous < input.len() {
            output.push(PtSplit {
                range: (base + previous)..(base + input.len()),
                token_id: None,
            });
        }
        true
    }

    /// Emit isolated matches and gaps directly without segment intermediates.
    fn pre_tokenize_isolated(&self, pts: &mut PreTokenizedString) {
        // Real tokenizer pieces average four to five source bytes, so this
        // avoids repeated growth without reserving for the one-byte worst case.
        let capacity = pts.buffer().len().div_ceil(4).max(pts.splits().len());
        let mut new_splits = Vec::with_capacity(capacity);
        for split in pts.splits() {
            if split.token_id.is_some() {
                new_splits.push(split.clone());
                continue;
            }

            let text = pts.split_text(split);
            if text.is_empty() {
                continue;
            }
            let base = split.range.start;
            self.for_each_fused_piece(text, |_, start, end| {
                new_splits.push(PtSplit {
                    range: (base + start)..(base + end),
                    token_id: None,
                });
            });
        }

        pts.refine_splits(new_splits);
    }

    /// Emit matcher spans directly for the Removed-and-inverted behavior.
    fn pre_tokenize_removed_inverted(&self, pts: &mut PreTokenizedString) {
        // Inversion marks original matches as gaps, which Removed retains.
        let capacity = pts.buffer().len().div_ceil(4).max(pts.splits().len());
        let mut new_splits = Vec::with_capacity(capacity);
        for split in pts.splits() {
            if split.token_id.is_some() {
                new_splits.push(split.clone());
                continue;
            }

            let text = pts.split_text(split);
            let base = split.range.start;
            self.matcher.for_each_match(text, |start, end| {
                new_splits.push(PtSplit {
                    range: (base + start)..(base + end),
                    token_id: None,
                });
            });
        }

        pts.refine_splits(new_splits);
    }

    /// Return split text slices for focused behavior tests.
    #[cfg(test)]
    fn split<'a>(&self, input: &'a str) -> Vec<&'a str> {
        let segments = self.find_segments(input);
        self.apply_behavior(&segments)
            .into_iter()
            .filter(|&(start, end)| start < end)
            .map(|(start, end)| &input[start..end])
            .collect()
    }

    /// Build the alternating match/gap segments consumed by split behaviors.
    fn find_segments(&self, input: &str) -> Vec<(usize, usize, bool)> {
        let mut segments = Vec::new();
        let mut previous = 0;
        self.matcher.for_each_match(input, |start, end| {
            if start > previous {
                segments.push((previous, start, false));
            }
            segments.push((start, end, true));
            previous = end;
        });
        if previous < input.len() {
            segments.push((previous, input.len(), false));
        }

        if self.invert {
            for segment in &mut segments {
                segment.2 = !segment.2;
            }
        }
        segments
    }

    /// Apply Hugging Face delimiter behavior to alternating match/gap segments.
    fn apply_behavior(&self, segments: &[(usize, usize, bool)]) -> Vec<(usize, usize)> {
        match self.behavior {
            SplitBehavior::Removed => segments
                .iter()
                .filter(|&&(_, _, is_match)| !is_match)
                .map(|&(start, end, _)| (start, end))
                .collect(),
            SplitBehavior::Isolated => segments
                .iter()
                .map(|&(start, end, _)| (start, end))
                .collect(),
            SplitBehavior::Contiguous => {
                let mut result: Vec<(usize, usize)> = Vec::new();
                let mut previous_match = None;
                for &(start, end, is_match) in segments {
                    if previous_match == Some(is_match) {
                        if let Some(last) = result.last_mut() {
                            last.1 = end;
                        }
                    } else {
                        result.push((start, end));
                    }
                    previous_match = Some(is_match);
                }
                result
            }
            SplitBehavior::MergedWithPrevious => {
                let mut result: Vec<(usize, usize)> = Vec::new();
                let mut previous_was_match = false;
                for &(start, end, is_match) in segments {
                    if is_match && !previous_was_match {
                        if let Some(last) = result.last_mut() {
                            last.1 = end;
                        } else {
                            result.push((start, end));
                        }
                    } else {
                        result.push((start, end));
                    }
                    previous_was_match = is_match;
                }
                result
            }
            SplitBehavior::MergedWithNext => {
                let mut result: Vec<(usize, usize)> = Vec::new();
                let mut previous_was_match = false;
                for &(start, end, is_match) in segments.iter().rev() {
                    if is_match && !previous_was_match {
                        if let Some(last) = result.last_mut() {
                            last.0 = start;
                        } else {
                            result.push((start, end));
                        }
                    } else {
                        result.push((start, end));
                    }
                    previous_was_match = is_match;
                }
                result.reverse();
                result
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;
    use tokenizers::{
        OffsetReferential, OffsetType, PreTokenizedString as HfPreTokenizedString, PreTokenizer,
        SplitDelimiterBehavior,
        pre_tokenizers::split::{Split as HfSplit, SplitPattern},
    };

    use super::*;
    use crate::pre_tokenizers::scanner::{
        DEEPSEEK_CJK_PATTERN, DEEPSEEK_MAIN_PATTERN, DEEPSEEK_NUMBER_PATTERN,
        GPT2_CASE_INSENSITIVE_PATTERN, GPT2_PATTERN, KIMI_PATTERN, LLAMA_CONTRACTION_PATTERN,
        LLAMA_PATTERN, PHI_GLM_PATTERN, QWEN_MARK_PATTERN, QWEN_PATTERN,
    };

    /// Convert a behavior name to the Hugging Face reference enum.
    fn hf_behavior(behavior: &str) -> SplitDelimiterBehavior {
        match behavior {
            "Removed" => SplitDelimiterBehavior::Removed,
            "Isolated" => SplitDelimiterBehavior::Isolated,
            "MergedWithPrevious" => SplitDelimiterBehavior::MergedWithPrevious,
            "MergedWithNext" => SplitDelimiterBehavior::MergedWithNext,
            "Contiguous" => SplitDelimiterBehavior::Contiguous,
            _ => panic!("unknown behavior"),
        }
    }

    /// Run the Hugging Face Split implementation and collect its byte-preserving pieces.
    fn hf_pieces(source: &str, behavior: &str, invert: bool, input: &str) -> Vec<String> {
        let split = HfSplit::new(
            SplitPattern::Regex(source.to_string()),
            hf_behavior(behavior),
            invert,
        )
        .unwrap();
        let mut pts = HfPreTokenizedString::from(input);
        split.pre_tokenize(&mut pts).unwrap();
        pts.get_splits(OffsetReferential::Original, OffsetType::Byte)
            .into_iter()
            .map(|(piece, _, _)| piece.to_string())
            .collect()
    }

    #[test]
    fn literal_behaviors_match_expected_boundaries() {
        let cases = [
            ("Removed", vec!["the", "final", "countdown"]),
            ("Isolated", vec!["the", "-", "final", "-", "-", "countdown"]),
            (
                "MergedWithPrevious",
                vec!["the-", "final-", "-", "countdown"],
            ),
            ("MergedWithNext", vec!["the", "-final", "-", "-countdown"]),
            ("Contiguous", vec!["the", "-", "final", "--", "countdown"]),
        ];
        for (behavior, expected) in cases {
            let split = Split::from_config(&json!({"String": "-"}), behavior, false).unwrap();
            assert_eq!(split.split("the-final--countdown"), expected);
        }

        let literal = Split::from_config(&json!({"String": "[a]"}), "Isolated", false).unwrap();
        assert_eq!(literal.split("a[a]b"), vec!["a", "[a]", "b"]);
    }

    #[test]
    fn fixed_scanners_match_hugging_face_on_semantic_edges() {
        let patterns = [
            (LLAMA_PATTERN, "Isolated", false),
            (LLAMA_CONTRACTION_PATTERN, "Isolated", false),
            (LLAMA_CONTRACTION_PATTERN, "Removed", true),
            (KIMI_PATTERN, "Isolated", false),
            (QWEN_PATTERN, "Isolated", false),
            (QWEN_MARK_PATTERN, "Isolated", false),
            (PHI_GLM_PATTERN, "Isolated", false),
            (PHI_GLM_PATTERN, "Removed", true),
            (DEEPSEEK_NUMBER_PATTERN, "Isolated", false),
            (DEEPSEEK_CJK_PATTERN, "Isolated", false),
            (DEEPSEEK_MAIN_PATTERN, "Isolated", false),
            (GPT2_PATTERN, "Isolated", false),
            (GPT2_CASE_INSENSITIVE_PATTERN, "Isolated", false),
        ];
        let inputs = [
            "I'm DON'T we're HTTPServer camelCase 12345",
            " café\u{301} \u{01c5}uro 你好世界! \t\n  trailing  ",
            "a.\n\nx",
            "$True foo\tbar\r\n/baz 🚀",
            "\u{216b}\u{b2} numbers\u{85}\u{a0}space\u{2028}line",
            "\u{300}\u{301}\u{302}",
            "汉字𠀀かなカナ mixedHan字word",
            "\u{3}\u{b}BASKETBALL",
        ];

        for (source, behavior, invert) in patterns {
            let scanner = Split::from_config(&json!({"Regex": source}), behavior, invert).unwrap();
            for input in inputs {
                let actual: Vec<String> = if behavior == "Removed" && invert {
                    let mut pts = PreTokenizedString::from_text(input);
                    scanner.pre_tokenize(&mut pts).unwrap();
                    pts.splits()
                        .iter()
                        .map(|split| pts.split_text(split).to_string())
                        .collect()
                } else {
                    scanner
                        .split(input)
                        .into_iter()
                        .map(str::to_string)
                        .collect()
                };
                let expected = hf_pieces(source, behavior, invert, input);
                assert_eq!(actual, expected, "pattern={source:?}, input={input:?}");
            }
        }
    }

    #[test]
    fn unsupported_regex_is_rejected_without_fallback() {
        let error = Split::from_config(&json!({"Regex": "\\d+"}), "Isolated", false).unwrap_err();
        assert!(matches!(error, Error::Unsupported(_)));
    }

    #[test]
    fn pre_tokenize_preserves_added_tokens() {
        let split = Split::from_config(&json!({"String": " "}), "Removed", false).unwrap();
        let mut pts = PreTokenizedString::new(
            "hello world".to_string(),
            vec![
                PtSplit {
                    range: 0..5,
                    token_id: None,
                },
                PtSplit {
                    range: 5..5,
                    token_id: Some(42),
                },
                PtSplit {
                    range: 5..11,
                    token_id: None,
                },
            ],
        );
        split.pre_tokenize(&mut pts).unwrap();
        assert!(pts.splits().iter().any(|piece| piece.token_id == Some(42)));
    }
}