Skip to main content

cortiq_engine/
tokenizer.rs

1//! Byte-level BPE tokenizer — HF tokenizer.json parity.
2//!
3//! Faithful pipeline (matches `tokenizers` for Qwen-style files):
4//!   added-token split (raw text) → NFC → pre-tokenizer regex
5//!   (GPT-2 style, needs lookahead) → byte-level mapping → ranked BPE
6//!   merges → vocab ids. Decode reverses through the byte-level map,
7//!   assembling UTF-8 across token boundaries.
8//!
9//! No silent corruption: a symbol that cannot be encoded is reported
10//! (tracing::error), never dropped without a trace.
11
12use serde::Deserialize;
13use std::collections::{HashMap, HashSet};
14use std::path::Path;
15use std::sync::OnceLock;
16use unicode_normalization::UnicodeNormalization;
17
18/// GPT-2 pre-tokenizer pattern — used when tokenizer.json carries no
19/// explicit Split regex (Qwen files carry their own; see `from_json`).
20const DEFAULT_SPLIT: &str = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+";
21
22/// Tool-call grammar tokens that decode as TEXT even when the vocabulary
23/// marks them special.
24///
25/// `decode` drops special tokens, which is right for control tokens
26/// (`<|im_end|>`, `</s>` …) and wrong for these: they ARE the tool call.
27/// MiniCPM5's tokenizer marks `<function`, `</function>`, `<param`,
28/// `</param>` (and `<tool_call>` …) special, so a call came out as
29/// ` name="get_weather">…Paris` — nothing a parser can find. Qwen's
30/// tokenizer marks its `<tool_call>` non-special for the same reason;
31/// this list gives every vocabulary that behaviour. Only exact tool
32/// markup is listed, so no chat control token can leak into content.
33pub const TOOL_MARKUP_TOKENS: &[&str] = &[
34    "<tool_call>",
35    "</tool_call>",
36    "<function",
37    "</function>",
38    "<param",
39    "</param>",
40];
41
42/// Inkling 2's turn markers: a model turn is `<|message_model|>` (a tool
43/// call's name after it), then `<|content_thinking|>`, `<|content_text|>` or
44/// `<|content_invoke_tool_json|>`, the part, `<|end_message|>`.
45#[derive(Clone, Copy, Debug)]
46struct InkMarks {
47    model: u32,
48    think: u32,
49    text: u32,
50    end: u32,
51    tool: u32,
52}
53
54/// A loaded BPE tokenizer.
55pub struct Tokenizer {
56    /// Inkling 2's turn markers, when the vocabulary has them (`ink_marks`).
57    ink: OnceLock<Option<InkMarks>>,
58    /// `decode_token`'s place in an Inkling turn (0 none, 1 thinking, 2 text,
59    /// 3 a tool call, 4 a turn's header).
60    ink_state: std::sync::atomic::AtomicU8,
61    /// Token string → ID
62    vocab: HashMap<String, u32>,
63    /// ID → Token string
64    id_to_token: Vec<String>,
65    /// BPE merge ranks: (left, right) → rank (lower merges first)
66    ranks: HashMap<(String, String), u32>,
67    /// The SentencePiece merges over token ids (built on first use; `None`
68    /// when a merge names a string outside the vocabulary — the string
69    /// path then runs)
70    sp_ids: OnceLock<Option<SpMerges>>,
71    /// All added tokens (split during encode; emitted raw at decode)
72    added: Vec<(String, u32)>,
73    /// IDs of added tokens (decode: emit content raw, no byte-map)
74    added_ids: HashSet<u32>,
75    /// IDs of special tokens (skipped by `decode`)
76    special_ids: HashSet<u32>,
77    /// Pre-tokenizer split pattern (None = whitespace fallback for the
78    /// synthetic `byte_level()` tokenizer)
79    /// Applied in order; each subdivides the previous stage's pieces.
80    split_res: Vec<fancy_regex::Regex>,
81    /// Per-stage gap policy, parallel to `split_res`: `true` when the
82    /// stage's Split declares `behavior: Removed, invert: true`, so the
83    /// NON-matching spans (whitespace) are dropped instead of kept as
84    /// pieces. The CLIP family isolates words that way — keeping the
85    /// gaps would hand BPE a stray `Ġ` piece per space.
86    split_drop_gap: Vec<bool>,
87    /// `model.ignore_merges`: a whole pre-token in the vocabulary is one token.
88    ignore_merges: bool,
89    /// `model.end_of_word_suffix` (CLIP: `</w>`), appended to a piece's
90    /// LAST symbol before the merges run — the merges themselves carry
91    /// the suffix (`["th", "e</w>"]`), so plain words resolve to their
92    /// `…</w>` ids, never to the mid-word spelling.
93    eow_suffix: Option<String>,
94    /// Normalizer `Lowercase` (CLIP): lower-case the segment before the
95    /// pre-tokenizer runs.
96    lowercase: bool,
97    /// Normalizer `Replace(\s+ → " ")` (CLIP): collapse whitespace runs
98    /// to a single space, before lowercasing.
99    collapse_ws: bool,
100    /// SentencePiece Prepend("▁") normalizer present (llama family).
101    /// Gemma replaces spaces with ▁ but does NOT prepend one.
102    sp_prepend: bool,
103    /// Metaspace `prepend_scheme: "first"` in the PRE-tokenizer (no
104    /// Prepend normalizer): the ▁ goes on the very first section of the
105    /// input only, so text after an added token gets none. Nanbeige 4.2
106    /// is this shape — reading only the normalizer left every raw prompt
107    /// short one leading ▁ ("Hello" instead of "▁Hello").
108    sp_prepend_first: bool,
109    /// SentencePiece family (TinyLlama/Llama-2/Mistral): metaspace ▁
110    /// normalization + byte_fallback, no byte-level alphabet.
111    metaspace: bool,
112    /// NFC only when the file's normalizer declares it (Qwen does,
113    /// TinyLlama does not — forcing it broke combining-accent parity).
114    nfc: bool,
115    /// byte → byte-level char (GPT-2 visible-alphabet mapping)
116    byte_to_char: [char; 256],
117    /// byte-level char → byte
118    char_to_byte: HashMap<char, u8>,
119    /// Special tokens
120    pub bos_token_id: Option<u32>,
121    pub eos_token_id: Option<u32>,
122    pub pad_token_id: Option<u32>,
123    /// Chat template special tokens
124    pub im_start_id: Option<u32>,
125    pub im_end_id: Option<u32>,
126    /// Jinja chat template carried by the container (spec §6.1);
127    /// None → hardcoded ChatML fallback.
128    pub chat_template: Option<String>,
129    /// Extra stop ids from the container's generation config.
130    pub extra_eos: HashSet<u32>,
131    /// Generation prepends BOS (llama post_processor semantics).
132    pub add_bos: bool,
133}
134
135impl std::fmt::Debug for Tokenizer {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        f.debug_struct("Tokenizer")
138            .field("vocab", &self.vocab.len())
139            .field("merges", &self.ranks.len())
140            .field("added", &self.added.len())
141            .finish()
142    }
143}
144
145/// GPT-2 byte↔unicode bijection: printable bytes map to themselves,
146/// the rest get consecutive codepoints from U+0100 up.
147fn bytes_to_unicode() -> ([char; 256], HashMap<char, u8>) {
148    let mut b2c = ['\0'; 256];
149    let mut c2b = HashMap::with_capacity(256);
150    let mut n = 0u32;
151    for b in 0..=255u16 {
152        let printable =
153            (0x21..=0x7E).contains(&b) || (0xA1..=0xAC).contains(&b) || (0xAE..=0xFF).contains(&b);
154        let c = if printable {
155            char::from_u32(b as u32).unwrap()
156        } else {
157            let c = char::from_u32(256 + n).unwrap();
158            n += 1;
159            c
160        };
161        b2c[b as usize] = c;
162        c2b.insert(c, b as u8);
163    }
164    (b2c, c2b)
165}
166
167/// HuggingFace tokenizer.json schema (the parts we execute).
168#[derive(Deserialize)]
169struct HfTokenizerJson {
170    model: HfModel,
171    #[serde(default)]
172    added_tokens: Vec<HfAddedToken>,
173    #[serde(default)]
174    pre_tokenizer: Option<serde_json::Value>,
175    #[serde(default)]
176    normalizer: Option<serde_json::Value>,
177    #[serde(default)]
178    post_processor: Option<serde_json::Value>,
179}
180
181#[derive(Deserialize)]
182struct HfModel {
183    vocab: HashMap<String, u32>,
184    #[serde(default)]
185    merges: Vec<HfMerge>,
186    #[serde(default)]
187    byte_fallback: bool,
188    /// CLIP's `</w>`: the BPE model appends it to a word's last symbol.
189    #[serde(default)]
190    end_of_word_suffix: Option<String>,
191    /// o200k-style BPE (Inkling 2): a pre-token that is a vocabulary entry
192    /// as a whole is that token, the merges never run on it.
193    #[serde(default)]
194    ignore_merges: bool,
195}
196
197/// Merge rules come in two HF flavours: legacy `"a b"` strings and
198/// modern `["a", "b"]` pairs (Qwen3.5 tokenizer.json uses pairs).
199#[derive(Deserialize)]
200#[serde(untagged)]
201enum HfMerge {
202    Pair([String; 2]),
203    Text(String),
204}
205
206#[derive(Deserialize)]
207struct HfAddedToken {
208    id: u32,
209    content: String,
210    special: bool,
211}
212
213/// Collect EVERY Split regex from a pre_tokenizer subtree, in order.
214///
215/// A Sequence applies its splits one after another, each subdividing what
216/// the previous one produced — taking only the first is not an
217/// approximation, it is a different tokenizer. DeepSeek-V4 puts the digit
218/// rule first and the word rule third, so reading one pattern sent whole
219/// sentences into BPE as a single piece and produced ids the model has
220/// never seen.
221fn collect_split_patterns(pt: &serde_json::Value, out: &mut Vec<String>) {
222    if pt.get("type").and_then(|t| t.as_str()) == Some("Split") {
223        if let Some(r) = pt
224            .get("pattern")
225            .and_then(|p| p.get("Regex"))
226            .and_then(|r| r.as_str())
227        {
228            out.push(r.to_string());
229        }
230        return;
231    }
232    if let Some(list) = pt.get("pretokenizers").and_then(|l| l.as_array()) {
233        for p in list {
234            collect_split_patterns(p, out);
235        }
236    }
237}
238
239/// The gap policy of every Split stage, in the SAME traversal order as
240/// [`collect_split_patterns`]: `true` = `behavior: Removed` with
241/// `invert: true` (non-matching spans dropped — CLIP's word isolation).
242fn collect_split_drop_gaps(pt: &serde_json::Value, out: &mut Vec<bool>) {
243    if pt.get("type").and_then(|t| t.as_str()) == Some("Split") {
244        let behavior = pt.get("behavior").and_then(|b| b.as_str()).unwrap_or("");
245        let invert = pt.get("invert").and_then(|i| i.as_bool()).unwrap_or(false);
246        out.push(behavior == "Removed" && invert);
247        return;
248    }
249    if let Some(list) = pt.get("pretokenizers").and_then(|l| l.as_array()) {
250        for p in list {
251            collect_split_drop_gaps(p, out);
252        }
253    }
254}
255
256/// `prepend_scheme` of a Metaspace pre-tokenizer ("always" | "first" |
257/// "never"), searched through a Sequence.
258fn find_prepend_scheme(pt: &serde_json::Value) -> Option<String> {
259    if pt.get("type").and_then(|t| t.as_str()) == Some("Metaspace") {
260        return pt
261            .get("prepend_scheme")
262            .and_then(|p| p.as_str())
263            .map(String::from);
264    }
265    if let Some(list) = pt.get("pretokenizers").and_then(|l| l.as_array()) {
266        return list.iter().find_map(find_prepend_scheme);
267    }
268    None
269}
270
271/// Neutralise `{% generation %}` / `{% endgeneration %}`.
272///
273/// Transformers uses that pair to mark which span of the render is the
274/// assistant's own tokens, so a trainer can build a loss mask. For
275/// INFERENCE it is transparent — the body renders either way — but
276/// minijinja does not know the statement and fails the whole template,
277/// after which the caller quietly serves a ChatML approximation and the
278/// model answers a differently-shaped prompt than the one it was tuned
279/// on. LiquidAI's LFM2.5 templates use it.
280///
281/// Deleting the tag is not enough: `{%- generation -%}` also carries
282/// whitespace control, and dropping it would leave the newline and the
283/// indentation around it in the output. Each tag becomes an assignment
284/// that does nothing, carrying the SAME dashes, so minijinja trims
285/// exactly what the original would have.
286pub(crate) fn strip_generation_tags(tpl: &str) -> std::borrow::Cow<'_, str> {
287    if !tpl.contains("generation") {
288        return std::borrow::Cow::Borrowed(tpl);
289    }
290    let mut out = String::with_capacity(tpl.len());
291    let mut rest = tpl;
292    let mut touched = false;
293    while let Some(open) = rest.find("{%") {
294        let Some(close_rel) = rest[open..].find("%}") else {
295            break;
296        };
297        let close = open + close_rel + 2;
298        let tag = &rest[open..close];
299        let inner = tag[2..tag.len() - 2].trim();
300        let lead = inner.starts_with('-');
301        let trail = inner.ends_with('-');
302        let name = inner.trim_matches('-').trim();
303        out.push_str(&rest[..open]);
304        if name == "generation" || name == "endgeneration" {
305            out.push_str(if lead { "{%-" } else { "{%" });
306            out.push_str(" set _generation_span = true ");
307            out.push_str(if trail { "-%}" } else { "%}" });
308            touched = true;
309        } else {
310            out.push_str(tag);
311        }
312        rest = &rest[close..];
313    }
314    if !touched {
315        return std::borrow::Cow::Borrowed(tpl);
316    }
317    out.push_str(rest);
318    std::borrow::Cow::Owned(out)
319}
320
321/// Whether a chat template consumes a `reasoning_effort` variable (Minico-M1's
322/// off/low/medium/high/max dial, GLM-5, gpt-oss): only such templates are
323/// handed a caller's effort, verbatim, by `run --reasoning-effort` and the
324/// server's `reasoning_effort` field.
325pub fn template_reads_reasoning_effort(tpl: &str) -> bool {
326    tpl.contains("reasoning_effort")
327}
328
329/// Close a template's generation-time `<think>` marker for direct answers.
330///
331/// GLM-5's template ends in `<|assistant|><think>` and controls the reasoning
332/// budget with `reasoning_effort`; unlike Qwen templates it does not inspect
333/// `enable_thinking`.  The marker must be closed after rendering without
334/// splitting the complete `<|assistant|>` special token.  Keep this helper
335/// shared by pair- and JSON-shaped chat rendering so both APIs use identical
336/// token sequences.
337fn close_direct_think(rendered: String, enable_thinking: Option<bool>) -> String {
338    if enable_thinking != Some(false) || rendered.contains("</think>") {
339        return rendered;
340    }
341    if let Some(pos) = rendered.rfind("<|assistant|>") {
342        let marker_end = pos + "<|assistant|>".len();
343        let after = &rendered[marker_end..];
344        let mut out = String::with_capacity(rendered.len() + 24);
345        out.push_str(&rendered[..marker_end]);
346        if let Some(rest) = after.strip_prefix("<think>") {
347            out.push_str("<think></think>\n\n");
348            out.push_str(rest);
349        } else {
350            out.push_str(after);
351            if !out.ends_with('\n') {
352                out.push('\n');
353            }
354            out.push_str("<think>\n\n</think>\n\n");
355        }
356        return out;
357    }
358    // ChatML templates that take no `enable_thinking` (Ripple) end in
359    // `<|im_start|>assistant\n`; the empty think block goes after that line.
360    if let Some(pos) = rendered.rfind("<|im_start|>assistant") {
361        let mut insert_at = pos + "<|im_start|>assistant".len();
362        if let Some(idx) = rendered[insert_at..].find('\n') {
363            insert_at += idx + 1;
364        }
365        let mut out = String::with_capacity(rendered.len() + 24);
366        out.push_str(&rendered[..insert_at]);
367        if !out.ends_with('\n') {
368            out.push('\n');
369        }
370        out.push_str("<think>\n\n</think>\n\n");
371        out.push_str(&rendered[insert_at..]);
372        return out;
373    }
374    // Templates without the angle-bracket assistant marker use a
375    // line-oriented role prefix.  Keep that marker intact and append the
376    // empty think block after its newline.
377    if let Some(pos) = rendered.rfind("\nassistant") {
378        let mut insert_at = pos + 1 + "assistant".len();
379        if let Some(idx) = rendered[insert_at..].find('\n') {
380            insert_at += idx + 1;
381        }
382        let mut out = String::with_capacity(rendered.len() + 24);
383        out.push_str(&rendered[..insert_at]);
384        if !out.ends_with('\n') {
385            out.push('\n');
386        }
387        out.push_str("<think>\n\n</think>\n\n");
388        out.push_str(&rendered[insert_at..]);
389        return out;
390    }
391    rendered
392}
393
394/// An Inkling tool call `{"name": …, "args": {…}}` as the Hermes spelling the
395/// server's parser reads; a body that is not that JSON goes through as it is.
396fn ink_tool_call(body: &str) -> String {
397    let fixed = serde_json::from_str::<serde_json::Value>(body.trim()).ok().and_then(|v| {
398        let name = v.get("name")?.clone();
399        let args = v.get("args").or_else(|| v.get("arguments")).cloned().unwrap_or_else(|| serde_json::json!({}));
400        Some(serde_json::json!({ "name": name, "arguments": args }).to_string())
401    });
402    format!("<tool_call>{}</tool_call>", fixed.unwrap_or_else(|| body.to_string()))
403}
404
405impl Tokenizer {
406    /// Load tokenizer from HuggingFace tokenizer.json file.
407    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, TokenizerError> {
408        let data = std::fs::read_to_string(path.as_ref())
409            .map_err(|e| TokenizerError::Io(e.to_string()))?;
410        Self::from_json(&data)
411    }
412
413    /// Load tokenizer from raw tokenizer.json bytes (CMF VOCAB section).
414    pub fn from_bytes(bytes: &[u8]) -> Result<Self, TokenizerError> {
415        let s = std::str::from_utf8(bytes)
416            .map_err(|e| TokenizerError::Parse(format!("vocab is not UTF-8: {e}")))?;
417        Self::from_json(s)
418    }
419
420    /// Load tokenizer from JSON string.
421    pub fn from_json(json: &str) -> Result<Self, TokenizerError> {
422        let hf: HfTokenizerJson =
423            serde_json::from_str(json).map_err(|e| TokenizerError::Parse(e.to_string()))?;
424
425        let mut vocab = hf.model.vocab;
426        let mut ranks = HashMap::new();
427        for (rank, m) in hf.model.merges.into_iter().enumerate() {
428            let (a, b) = match m {
429                HfMerge::Pair([a, b]) => (a, b),
430                HfMerge::Text(s) => {
431                    let mut it = s.splitn(2, ' ');
432                    match (it.next(), it.next()) {
433                        (Some(a), Some(b)) => (a.to_string(), b.to_string()),
434                        _ => continue,
435                    }
436                }
437            };
438            ranks.insert((a, b), rank as u32);
439        }
440
441        // Family detection: SentencePiece carries byte_fallback and/or a
442        // Prepend("▁") normalizer; byte-level BPE carries a Split regex.
443        // Llama-family post_processor prepends <s> at add_special_tokens
444        // time; generation must honor it (word salad without BOS).
445        let mut saw_gemma_bos = false;
446        let add_bos_detected = hf
447            .post_processor
448            .as_ref()
449            .map(|p| {
450                let pp = p.to_string();
451                pp.contains("\"<s>\"") || pp.contains("\"<bos>\"")
452            })
453            .unwrap_or(false);
454        let nfc = hf
455            .normalizer
456            .as_ref()
457            .map(|n| n.to_string().contains("NFC"))
458            .unwrap_or(false);
459        let metaspace = hf.model.byte_fallback
460            || hf
461                .normalizer
462                .as_ref()
463                .map(|n| n.to_string().contains("\u{2581}") || n.to_string().contains("▁"))
464                .unwrap_or(false);
465        let sp_prepend = hf
466            .normalizer
467            .as_ref()
468            .map(|n| n.to_string().contains("Prepend"))
469            .unwrap_or(false);
470        // Metaspace can also live in the pre-tokenizer, carrying its own
471        // prepend_scheme: "always" behaves like the llama normalizer,
472        // "first" only marks the head of the input (see `sp_prepend_first`).
473        let (sp_prepend, sp_prepend_first) = if sp_prepend {
474            (true, false)
475        } else {
476            match hf.pre_tokenizer.as_ref().and_then(find_prepend_scheme) {
477                Some(s) if s == "always" => (true, false),
478                Some(s) if s == "first" => (false, true),
479                _ => (false, false),
480            }
481        };
482        let (split_res, split_drop_gap) = if metaspace {
483            (Vec::new(), Vec::new())
484        } else {
485            let mut pats = Vec::new();
486            if let Some(pt) = hf.pre_tokenizer.as_ref() {
487                collect_split_patterns(pt, &mut pats);
488            }
489            if pats.is_empty() {
490                pats.push(DEFAULT_SPLIT.to_string());
491            }
492            let mut split_drop_gap = Vec::new();
493            if let Some(pt) = hf.pre_tokenizer.as_ref() {
494                collect_split_drop_gaps(pt, &mut split_drop_gap);
495            }
496            while split_drop_gap.len() < pats.len() {
497                split_drop_gap.push(false);
498            }
499            split_drop_gap.truncate(pats.len());
500            (
501                pats.iter()
502                    .map(|p| {
503                        fancy_regex::Regex::new(p)
504                            .map_err(|e| TokenizerError::Parse(format!("pre-tokenizer regex: {e}")))
505                    })
506                    .collect::<Result<Vec<_>, _>>()?,
507                split_drop_gap,
508            )
509        };
510        // CLIP's normalizer: NFC → Replace(\s+ → " ") → Lowercase.
511        let norm_s = hf
512            .normalizer
513            .as_ref()
514            .map(|n| n.to_string())
515            .unwrap_or_default();
516        let collapse_ws = norm_s.contains("\"Replace\"") && norm_s.contains("\\\\s+");
517        let lowercase = norm_s.contains("\"Lowercase\"");
518
519        // Added tokens: longest-first so overlapping contents match right.
520        let mut bos_token_id = None;
521        let mut eos_token_id = None;
522        let mut pad_token_id = None;
523        let mut im_start_id = None;
524        let mut im_end_id = None;
525        let mut special_ids = HashSet::new();
526        let mut added_ids = HashSet::new();
527        let mut added = Vec::new();
528
529        for at in &hf.added_tokens {
530            vocab.insert(at.content.clone(), at.id);
531            added.push((at.content.clone(), at.id));
532            added_ids.insert(at.id);
533            if at.special && !TOOL_MARKUP_TOKENS.contains(&at.content.as_str()) {
534                special_ids.insert(at.id);
535            }
536            match at.content.as_str() {
537                "<|endoftext|>" | "</s>" | "[EOS]" => eos_token_id = Some(at.id),
538                "<|im_start|>" => im_start_id = Some(at.id),
539                "<|im_end|>" => im_end_id = Some(at.id),
540                "<s>" | "[BOS]" | "<|startoftext|>" => bos_token_id = Some(at.id),
541                // Gemma spells BOS as literal "<bos>" — the family
542                // REQUIRES it on every sequence, and newer tokenizers
543                // (gemma-4) no longer say so in a post_processor.
544                "<bos>" => {
545                    bos_token_id = Some(at.id);
546                    saw_gemma_bos = true;
547                }
548                "<pad>" => pad_token_id = Some(at.id),
549                _ => {}
550            }
551        }
552
553        // DeepSeek-V4.1 keeps harmony/DSML markers in the ordinary vocabulary
554        // on some tokenizer revisions and in `added_tokens` on others. Treat
555        // either spelling as atomic so image placeholders cannot split into
556        // byte-BPE pieces, and make the configured BOS/EOS ids discoverable.
557        const DSV41_SPECIALS: &[&str] = &[
558            "<|begin▁of▁sentence|>",
559            "<|end▁of▁sentence|>",
560            "<|User|>",
561            "<|Assistant|>",
562            "<|System|>",
563            "<|latest_reminder|>",
564            "<|deepseek_image|>",
565            "<|action|>",
566            "<|query|>",
567            "<|authority|>",
568            "<|domain|>",
569            "<|title|>",
570            "<|read_url|>",
571            "<think>",
572            "</think>",
573            "|DSML|",
574        ];
575        for token in DSV41_SPECIALS {
576            if let Some(&id) = vocab.get(*token) {
577                if !added.iter().any(|(content, _)| content.as_str() == *token) {
578                    added.push(((*token).to_string(), id));
579                }
580                added_ids.insert(id);
581                match *token {
582                    "<|begin▁of▁sentence|>" => bos_token_id = Some(id),
583                    "<|end▁of▁sentence|>" => eos_token_id = Some(id),
584                    _ => {}
585                }
586            }
587        }
588        added.sort_by_key(|(c, _)| std::cmp::Reverse(c.len()));
589
590        // Gemma REQUIRES a leading <bos> on every sequence, but newer
591        // tokenizers (gemma-4, 262k vocab) no longer spell it in a
592        // post_processor template — the family marker <start_of_turn>
593        // is the reliable tell. Without this, raw-text scoring runs
594        // unanchored and the first ~30 positions read worse than
595        // uniform (the chat path masked it: the template carries <bos>).
596        let gemma_family = saw_gemma_bos
597            || vocab.contains_key("<start_of_turn>")
598            || added.iter().any(|(c, _)| c == "<start_of_turn>");
599
600        // The post_processor template names the exact BOS content
601        // (llama "<s>", gemma "<bos>" — gemma's vocab carries BOTH, so
602        // added-token scan order must not decide).
603        if let Some(pp) = hf.post_processor.as_ref() {
604            let pp = pp.to_string();
605            for name in ["<bos>", "<s>"] {
606                if pp.contains(&format!("\"{name}\"")) {
607                    if let Some(&id) = vocab.get(name) {
608                        bos_token_id = Some(id);
609                    }
610                    break;
611                }
612            }
613        }
614
615        // Build reverse map
616        let max_id = vocab.values().copied().max().unwrap_or(0) as usize;
617        let mut id_to_token = vec![String::new(); max_id + 1];
618        for (token, &id) in &vocab {
619            if (id as usize) < id_to_token.len() {
620                id_to_token[id as usize] = token.clone();
621            }
622        }
623
624        let (byte_to_char, char_to_byte) = bytes_to_unicode();
625
626        tracing::info!(
627            "Tokenizer loaded: {} vocab, {} merges, {} added, eos={:?}",
628            vocab.len(),
629            ranks.len(),
630            added.len(),
631            eos_token_id
632        );
633
634        Ok(Self {
635            ink: OnceLock::new(),
636            ink_state: std::sync::atomic::AtomicU8::new(0),
637            vocab,
638            id_to_token,
639            ranks,
640            sp_ids: OnceLock::new(),
641            added,
642            added_ids,
643            special_ids,
644            split_res,
645            split_drop_gap,
646            ignore_merges: hf.model.ignore_merges,
647            eow_suffix: hf.model.end_of_word_suffix,
648            lowercase,
649            collapse_ws,
650            metaspace,
651            sp_prepend,
652            sp_prepend_first,
653            nfc,
654            byte_to_char,
655            char_to_byte,
656            bos_token_id,
657            eos_token_id,
658            pad_token_id,
659            im_start_id,
660            im_end_id,
661            chat_template: None,
662            extra_eos: HashSet::new(),
663            add_bos: add_bos_detected || gemma_family,
664        })
665    }
666
667    /// Create a minimal tokenizer for testing (byte tokens, no merges).
668    pub fn byte_level() -> Self {
669        let mut vocab = HashMap::new();
670        let mut id_to_token = Vec::with_capacity(256);
671        for i in 0..256u32 {
672            let tok = format!("<0x{:02X}>", i);
673            vocab.insert(tok.clone(), i);
674            id_to_token.push(tok);
675        }
676        let (byte_to_char, char_to_byte) = bytes_to_unicode();
677        Self {
678            ink: OnceLock::new(),
679            ink_state: std::sync::atomic::AtomicU8::new(0),
680            vocab,
681            id_to_token,
682            ranks: HashMap::new(),
683            sp_ids: OnceLock::new(),
684            added: Vec::new(),
685            added_ids: HashSet::new(),
686            special_ids: HashSet::new(),
687            split_res: Vec::new(),
688            split_drop_gap: Vec::new(),
689            ignore_merges: false,
690            eow_suffix: None,
691            lowercase: false,
692            collapse_ws: false,
693            metaspace: false,
694            sp_prepend: false,
695            sp_prepend_first: false,
696            nfc: false,
697            byte_to_char,
698            char_to_byte,
699            bos_token_id: None,
700            eos_token_id: None,
701            pad_token_id: None,
702            im_start_id: None,
703            im_end_id: None,
704            chat_template: None,
705            extra_eos: HashSet::new(),
706            add_bos: false,
707        }
708    }
709
710    /// Encode text to token IDs.
711    pub fn encode(&self, text: &str) -> Vec<u32> {
712        let mut ids = Vec::new();
713        // Added tokens match on raw text (normalized: false), longest first.
714        let mut at = 0;
715        // Next occurrence of each added token at or after `at`. A token is
716        // searched again only once `at` has passed it, so one that never
717        // occurs costs a single scan: rescanning the rest of the text per
718        // token and per match made long chat-format text quadratic.
719        let mut next: Vec<Option<usize>> =
720            self.added.iter().map(|(content, _)| text.find(content.as_str())).collect();
721        // `prepend_scheme: "first"` marks only the section that starts at
722        // offset 0 — HF drops the ▁ for everything after an added token,
723        // which is why a chat prompt opening with <|im_start|> tokenizes
724        // the same either way and only raw prompts were wrong.
725        let mut head = true;
726        'outer: while at < text.len() {
727            let mut best: Option<(usize, usize, u32)> = None; // (pos, len, id)
728            for (i, (content, id)) in self.added.iter().enumerate() {
729                if next[i].is_some_and(|p| p < at) {
730                    next[i] = text[at..].find(content.as_str()).map(|p| at + p);
731                }
732                if let Some(pos) = next[i] {
733                    let better = match best {
734                        None => true,
735                        Some((bp, bl, _)) => pos < bp || (pos == bp && content.len() > bl),
736                    };
737                    if better {
738                        best = Some((pos, content.len(), *id));
739                    }
740                    if pos == at {
741                        break; // earliest possible; added is longest-first
742                    }
743                }
744            }
745            match best {
746                Some((pos, len, id)) => {
747                    self.encode_segment_at(&text[at..pos], head, &mut ids);
748                    ids.push(id);
749                    at = pos + len;
750                    head = false;
751                }
752                None => {
753                    self.encode_segment_at(&text[at..], head, &mut ids);
754                    break 'outer;
755                }
756            }
757        }
758        ids
759    }
760
761    /// Encode text as PLAIN text: the whole input is one added-token-free
762    /// segment (NFC → split → byte-map → BPE), so a literal `<|im_end|>`
763    /// in it stays bytes instead of becoming the special id. This is the
764    /// trainer's `Bpe::encode` (user text, never the template frame) —
765    /// router v2 tokenizes the user message with it (spec §9.4).
766    pub fn encode_plain(&self, text: &str) -> Vec<u32> {
767        let mut ids = Vec::new();
768        self.encode_segment_at(text, true, &mut ids);
769        ids
770    }
771
772    /// Encode one added-token-free segment: NFC → whitespace collapse →
773    /// lowercase (the CLIP normalizer chain) → split → byte-map → BPE.
774    /// `head` says whether this section starts at offset 0 of the
775    /// input — only that one takes a `prepend_scheme: "first"` ▁.
776    fn encode_segment_at(&self, segment: &str, head: bool, out: &mut Vec<u32>) {
777        if segment.is_empty() {
778            return;
779        }
780        let mut norm: String = if self.nfc {
781            segment.nfc().collect()
782        } else {
783            segment.to_string()
784        };
785        if self.collapse_ws {
786            // Replace(\s+ → " "): every whitespace RUN becomes one space.
787            let mut collapsed = String::with_capacity(norm.len());
788            let mut in_ws = false;
789            for ch in norm.chars() {
790                if ch.is_whitespace() {
791                    if !in_ws {
792                        collapsed.push(' ');
793                        in_ws = true;
794                    }
795                } else {
796                    collapsed.push(ch);
797                    in_ws = false;
798                }
799            }
800            norm = collapsed;
801        }
802        if self.lowercase {
803            norm = norm.to_lowercase();
804        }
805        if self.metaspace {
806            // SentencePiece: [Prepend("▁") +] Replace(" "→"▁"), BPE over
807            // chars of the whole span (no pre-tokenizer, no byte map).
808            // Gemma's normalizer replaces only — no dummy prefix.
809            let sp = if self.sp_prepend {
810                // Normalizer order: Prepend THEN Replace, unguarded — so
811                // " hello" really does become ▁▁hello on llama.
812                format!("\u{2581}{}", norm).replace(' ', "\u{2581}")
813            } else {
814                // Pre-tokenizer Metaspace: Replace, then prepend only if
815                // the span does not already start with ▁ (HF's guard, so
816                // " hello" stays one ▁, not two).
817                let replaced = norm.replace(' ', "\u{2581}");
818                if self.sp_prepend_first && head && !replaced.starts_with('\u{2581}') {
819                    format!("\u{2581}{replaced}")
820                } else {
821                    replaced
822                }
823            };
824            self.bpe_piece_sp(&sp, out);
825            return;
826        }
827        if !self.split_res.is_empty() {
828            // Each stage subdivides the pieces the previous one left, with
829            // Isolated behaviour: both the matches and the gaps survive.
830            // A stage declaring `behavior: Removed, invert: true` keeps
831            // only the matches — its gaps (whitespace) are dropped.
832            let mut pieces: Vec<(usize, usize)> = vec![(0, norm.len())];
833            for (stage, re) in self.split_res.iter().enumerate() {
834                let drop = self.split_drop_gap.get(stage).copied().unwrap_or(false);
835                let mut next: Vec<(usize, usize)> = Vec::with_capacity(pieces.len() * 2);
836                for (ps, pe) in pieces {
837                    let seg = &norm[ps..pe];
838                    let mut last = 0usize;
839                    for m in re.find_iter(seg) {
840                        let m = match m {
841                            Ok(m) => m,
842                            Err(e) => {
843                                tracing::error!("pre-tokenizer regex failed: {e}");
844                                break;
845                            }
846                        };
847                        if m.start() > last && !drop {
848                            next.push((ps + last, ps + m.start()));
849                        }
850                        if m.end() > m.start() {
851                            next.push((ps + m.start(), ps + m.end()));
852                        }
853                        last = m.end();
854                    }
855                    if last < seg.len() && !drop {
856                        next.push((ps + last, pe));
857                    }
858                }
859                pieces = next;
860            }
861            for (ps, pe) in pieces {
862                self.bpe_piece(&norm[ps..pe], out);
863            }
864        } else {
865            {
866                // Synthetic byte_level() tokenizer: raw byte tokens.
867                for b in norm.bytes() {
868                    let tok = format!("<0x{:02X}>", b);
869                    if let Some(&id) = self.vocab.get(&tok) {
870                        out.push(id);
871                    }
872                }
873            }
874        }
875    }
876
877    /// The id-level merge table of a SentencePiece vocabulary.
878    fn sp_merges(&self) -> Option<&SpMerges> {
879        self.sp_ids
880            .get_or_init(|| SpMerges::build(&self.vocab, &self.ranks))
881            .as_ref()
882    }
883
884    /// SentencePiece BPE: symbols are chars (no byte-level alphabet);
885    /// unknown symbols fall back to <0xNN> tokens per UTF-8 byte.
886    ///
887    /// The rule is "merge every occurrence of the lowest-ranked adjacent
888    /// pair, left to right, until none is left". [`SpMerges::encode`] runs
889    /// it over ids with a heap (O(n log n)); this string form (O(n²) with a
890    /// clone per pair) remains for vocabularies whose merges leave the
891    /// vocabulary and as the reference the fast form is tested against.
892    fn bpe_piece_sp(&self, piece: &str, out: &mut Vec<u32>) {
893        if piece.is_empty() {
894            return;
895        }
896        if !SP_STRINGS.with(|f| f.get()) {
897            if let Some(m) = self.sp_merges() {
898                m.encode(&self.vocab, piece, out);
899                return;
900            }
901        }
902        self.bpe_piece_sp_strings(piece, out);
903    }
904
905    /// [`encode`](Self::encode) with the SentencePiece string form forced:
906    /// the reference the id-level BPE is checked against.
907    #[doc(hidden)]
908    pub fn encode_reference(&self, text: &str) -> Vec<u32> {
909        SP_STRINGS.with(|f| f.set(true));
910        let ids = self.encode(text);
911        SP_STRINGS.with(|f| f.set(false));
912        ids
913    }
914
915    fn bpe_piece_sp_strings(&self, piece: &str, out: &mut Vec<u32>) {
916        let mut sym: Vec<String> = piece.chars().map(|c| c.to_string()).collect();
917        loop {
918            let mut best: Option<(u32, usize)> = None;
919            for i in 0..sym.len().saturating_sub(1) {
920                if let Some(&r) = self.ranks.get(&(sym[i].clone(), sym[i + 1].clone())) {
921                    if best.map(|(br, _)| r < br).unwrap_or(true) {
922                        best = Some((r, i));
923                    }
924                }
925            }
926            let Some((_, i)) = best else { break };
927            let merged = format!("{}{}", sym[i], sym[i + 1]);
928            let (left, right) = (sym[i].clone(), sym[i + 1].clone());
929            let mut j = 0;
930            while j + 1 < sym.len() {
931                if sym[j] == left && sym[j + 1] == right {
932                    sym[j] = merged.clone();
933                    sym.remove(j + 1);
934                }
935                j += 1;
936            }
937        }
938        for t in &sym {
939            if let Some(&id) = self.vocab.get(t) {
940                out.push(id);
941            } else {
942                let mut ok = true;
943                for byte in t.bytes() {
944                    let tok = format!("<0x{:02X}>", byte);
945                    match self.vocab.get(&tok) {
946                        Some(&id) => out.push(id),
947                        None => {
948                            ok = false;
949                            break;
950                        }
951                    }
952                }
953                if !ok {
954                    tracing::error!("tokenizer: no id for SP symbol {t:?} — dropped");
955                }
956            }
957        }
958    }
959
960    /// Byte-level map one pre-token piece, then ranked BPE merges.
961    fn bpe_piece(&self, piece: &str, out: &mut Vec<u32>) {
962        if piece.is_empty() {
963            return;
964        }
965        let mapped: Vec<String> = piece
966            .bytes()
967            .map(|b| self.byte_to_char[b as usize].to_string())
968            .collect();
969        if self.ignore_merges {
970            let whole: String = mapped.concat();
971            if let Some(&id) = self.vocab.get(&whole) {
972                out.push(id);
973                return;
974            }
975        }
976        let mut sym = mapped;
977        // CLIP's `end_of_word_suffix`: the last symbol of the word wears
978        // it before any merge runs, so the suffixed merges ("th",
979        // "e</w>") can form and the word resolves to its `…</w>` id.
980        if let Some(sfx) = &self.eow_suffix {
981            if let Some(last) = sym.last_mut() {
982                last.push_str(sfx);
983            }
984        }
985
986        // Classic BPE: repeatedly merge the lowest-rank adjacent pair.
987        loop {
988            let mut best: Option<(u32, usize)> = None;
989            for i in 0..sym.len().saturating_sub(1) {
990                if let Some(&r) = self.ranks.get(&(sym[i].clone(), sym[i + 1].clone())) {
991                    if best.map(|(br, _)| r < br).unwrap_or(true) {
992                        best = Some((r, i));
993                    }
994                }
995            }
996            let Some((_, i)) = best else { break };
997            let merged = format!("{}{}", sym[i], sym[i + 1]);
998            // Merge ALL occurrences of this exact pair, left to right.
999            let (left, right) = (sym[i].clone(), sym[i + 1].clone());
1000            let mut j = 0;
1001            while j + 1 < sym.len() {
1002                if sym[j] == left && sym[j + 1] == right {
1003                    sym[j] = merged.clone();
1004                    sym.remove(j + 1);
1005                }
1006                j += 1;
1007            }
1008        }
1009
1010        for s in &sym {
1011            if let Some(&id) = self.vocab.get(s) {
1012                out.push(id);
1013            } else {
1014                // Byte-fallback (synthetic vocabs); never drop silently.
1015                let mut ok = true;
1016                for ch in s.chars() {
1017                    let Some(&b) = self.char_to_byte.get(&ch) else {
1018                        ok = false;
1019                        break;
1020                    };
1021                    let tok = format!("<0x{:02X}>", b);
1022                    if let Some(&id) = self.vocab.get(&tok) {
1023                        out.push(id);
1024                    } else {
1025                        ok = false;
1026                        break;
1027                    }
1028                }
1029                if !ok {
1030                    tracing::error!("tokenizer: no id for symbol {s:?} — dropped");
1031                }
1032            }
1033        }
1034    }
1035
1036    /// Decode token IDs back to text. Special tokens are skipped; added
1037    /// tokens are raw text; everything else reverses the byte-level map.
1038    /// Inkling 2's markers, when this vocabulary has them.
1039    fn ink_marks(&self) -> Option<InkMarks> {
1040        *self.ink.get_or_init(|| {
1041            let id = |t: &str| self.vocab.get(t).copied().or_else(|| self.added.iter().find(|(s, _)| s == t).map(|&(_, i)| i));
1042            id("<|content_model_end_sampling|>")?;
1043            Some(InkMarks {
1044                model: id("<|message_model|>")?,
1045                think: id("<|content_thinking|>")?,
1046                text: id("<|content_text|>")?,
1047                end: id("<|end_message|>")?,
1048                tool: id("<|content_invoke_tool_json|>")?,
1049            })
1050        })
1051    }
1052
1053    /// An Inkling turn in the `<think>` / `<tool_call>` spelling the rest of
1054    /// the engine reads: a thinking part becomes `<think>…</think>`, a tool
1055    /// call `<tool_call>{"name", "arguments"}</tool_call>`, a text part its
1056    /// text; the headers and other markers go.
1057    fn ink_decode(&self, m: InkMarks, ids: &[u32]) -> String {
1058        let mut out = String::new();
1059        let mut run: Vec<u32> = Vec::new();
1060        // 0 none, 1 thinking, 2 text, 3 tool call, 4 header
1061        let mut state = 0u8;
1062        let flush = |run: &mut Vec<u32>, out: &mut String| {
1063            if !run.is_empty() {
1064                out.push_str(&self.decode_plain(run));
1065                run.clear();
1066            }
1067        };
1068        let mut tool = String::new();
1069        for &id in ids {
1070            if id == m.model {
1071                flush(&mut run, &mut out);
1072                state = 4;
1073            } else if id == m.think {
1074                run.clear();
1075                out.push_str("<think>");
1076                state = 1;
1077            } else if id == m.text {
1078                run.clear();
1079                state = 2;
1080            } else if id == m.tool {
1081                run.clear();
1082                state = 3;
1083            } else if id == m.end {
1084                if state == 3 {
1085                    tool.push_str(&self.decode_plain(&run));
1086                    run.clear();
1087                    out.push_str(&ink_tool_call(&tool));
1088                    tool.clear();
1089                } else {
1090                    flush(&mut run, &mut out);
1091                    if state == 1 {
1092                        out.push_str("</think>\n\n");
1093                    }
1094                }
1095                state = 0;
1096            } else if state == 4 || self.special_ids.contains(&id) {
1097                // a header's name, or another marker
1098            } else {
1099                run.push(id);
1100            }
1101        }
1102        if state == 3 {
1103            tool.push_str(&self.decode_plain(&run));
1104            out.push_str("<tool_call>");
1105            out.push_str(&tool);
1106        } else {
1107            flush(&mut run, &mut out);
1108        }
1109        out
1110    }
1111
1112    pub fn decode(&self, ids: &[u32]) -> String {
1113        if let Some(m) = self.ink_marks()
1114            && ids.iter().any(|&i| i == m.model || i == m.think || i == m.text || i == m.end || i == m.tool)
1115        {
1116            return self.ink_decode(m, ids);
1117        }
1118        self.decode_plain(ids)
1119    }
1120
1121    fn decode_plain(&self, ids: &[u32]) -> String {
1122        let mut bytes: Vec<u8> = Vec::new();
1123        for &id in ids {
1124            if self.special_ids.contains(&id) {
1125                continue;
1126            }
1127            let idx = id as usize;
1128            if idx >= self.id_to_token.len() {
1129                continue;
1130            }
1131            let tok = &self.id_to_token[idx];
1132            if self.added_ids.contains(&id) {
1133                // Gemma-3n declares its multi-space ▁-runs as ADDED
1134                // tokens — verbatim passthrough leaked ▁ into output.
1135                if self.metaspace && tok.contains('\u{2581}') {
1136                    bytes.extend_from_slice(tok.replace('\u{2581}', " ").as_bytes());
1137                } else {
1138                    bytes.extend_from_slice(tok.as_bytes());
1139                }
1140                continue;
1141            }
1142            // Byte-fallback / legacy byte tokens
1143            if tok.starts_with("<0x") && tok.ends_with('>') && tok.len() == 6 {
1144                if let Ok(b) = u8::from_str_radix(&tok[3..5], 16) {
1145                    bytes.push(b);
1146                    continue;
1147                }
1148            }
1149            if self.metaspace {
1150                // SP decoder: Replace(▁→" "); UTF-8 chars pass through.
1151                for ch in tok.chars() {
1152                    if ch == '\u{2581}' {
1153                        bytes.push(b' ');
1154                    } else {
1155                        let mut buf = [0u8; 4];
1156                        bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
1157                    }
1158                }
1159                continue;
1160            }
1161            for ch in tok.chars() {
1162                match self.char_to_byte.get(&ch) {
1163                    Some(&b) => bytes.push(b),
1164                    // Not a byte-level char (shouldn't happen for real
1165                    // vocabs) — pass the char through as UTF-8.
1166                    None => {
1167                        let mut buf = [0u8; 4];
1168                        bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
1169                    }
1170                }
1171            }
1172        }
1173        let text = String::from_utf8_lossy(&bytes).into_owned();
1174        if self.metaspace && (self.sp_prepend || self.sp_prepend_first) {
1175            // SP decoder Strip(start=1): one leading space from Prepend.
1176            if let Some(stripped) = text.strip_prefix(' ') {
1177                return stripped.to_string();
1178            }
1179        }
1180        text
1181    }
1182
1183    /// Streaming decode of ONE token: no sequence-level Strip — a
1184    /// per-token strip would eat the ▁-spaces of every SP word.
1185    /// An Inkling turn marker one token at a time (`decode_token` and the
1186    /// stream): `Some` of its spelling (the thinking part's `<think>` …
1187    /// `</think>`, a tool call's `<tool_call>` … `</tool_call>`, nothing for the
1188    /// others and for a turn header's name), `None` for a token of a part.
1189    fn ink_token(&self, id: u32) -> Option<String> {
1190        let m = self.ink_marks()?;
1191        use std::sync::atomic::Ordering::Relaxed;
1192        let st = &self.ink_state;
1193        if id == m.model {
1194            st.store(4, Relaxed);
1195            return Some(String::new());
1196        }
1197        if id == m.think {
1198            st.store(1, Relaxed);
1199            return Some("<think>".into());
1200        }
1201        if id == m.text {
1202            st.store(2, Relaxed);
1203            return Some(String::new());
1204        }
1205        if id == m.tool {
1206            st.store(3, Relaxed);
1207            return Some("<tool_call>".into());
1208        }
1209        if id == m.end {
1210            return Some(match st.swap(0, Relaxed) {
1211                1 => "</think>\n\n".into(),
1212                3 => "</tool_call>".into(),
1213                _ => String::new(),
1214            });
1215        }
1216        (st.load(Relaxed) == 4).then(String::new)
1217    }
1218
1219    pub fn decode_token(&self, id: u32) -> String {
1220        if let Some(t) = self.ink_token(id) {
1221            return t;
1222        }
1223        if self.special_ids.contains(&id) {
1224            return String::new();
1225        }
1226        let idx = id as usize;
1227        if idx >= self.id_to_token.len() {
1228            return String::new();
1229        }
1230        let tok = &self.id_to_token[idx];
1231        if self.added_ids.contains(&id) {
1232            if self.metaspace && tok.contains('\u{2581}') {
1233                return tok.replace('\u{2581}', " ");
1234            }
1235            return tok.clone();
1236        }
1237        if tok.starts_with("<0x") && tok.ends_with('>') && tok.len() == 6 {
1238            if let Ok(b) = u8::from_str_radix(&tok[3..5], 16) {
1239                return String::from_utf8_lossy(&[b]).into_owned();
1240            }
1241        }
1242        if self.metaspace {
1243            return tok.replace('\u{2581}', " ");
1244        }
1245        let mut bytes = Vec::new();
1246        for ch in tok.chars() {
1247            match self.char_to_byte.get(&ch) {
1248                Some(&b) => bytes.push(b),
1249                None => {
1250                    let mut buf = [0u8; 4];
1251                    bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
1252                }
1253            }
1254        }
1255        String::from_utf8_lossy(&bytes).into_owned()
1256    }
1257
1258    /// Streaming decode of ONE token that never splits a character. A
1259    /// byte-level (or `<0xNN>`) token may end inside a multi-byte UTF-8
1260    /// sequence — a CJK character or a subscript digit spread over two
1261    /// tokens of a small vocabulary — and decoding it alone gives U+FFFD.
1262    /// The incomplete tail waits in `pending` (one per stream) and comes out
1263    /// with the token that completes it; invalid bytes still decode lossily.
1264    pub fn decode_token_stream(&self, id: u32, pending: &mut Vec<u8>) -> String {
1265        if let Some(t) = self.ink_token(id) {
1266            return t;
1267        }
1268        if self.special_ids.contains(&id) {
1269            return String::new();
1270        }
1271        if self.added_ids.contains(&id) {
1272            pending.extend_from_slice(self.decode_token(id).as_bytes());
1273        } else {
1274            pending.extend_from_slice(&self.token_bytes(id));
1275        }
1276        match std::str::from_utf8(pending) {
1277            Ok(s) => {
1278                let out = s.to_string();
1279                pending.clear();
1280                out
1281            }
1282            // Only an unfinished last character: emit what is complete.
1283            Err(e) if e.error_len().is_none() => {
1284                let valid = e.valid_up_to();
1285                let out = std::str::from_utf8(&pending[..valid]).unwrap_or_default().to_string();
1286                pending.drain(..valid);
1287                out
1288            }
1289            Err(_) => {
1290                let out = String::from_utf8_lossy(pending).into_owned();
1291                pending.clear();
1292                out
1293            }
1294        }
1295    }
1296
1297    /// The raw bytes token `id` stands for (an added token: its content), so
1298    /// a caller can map an encoded text's tokens back to its characters.
1299    pub fn token_bytes(&self, id: u32) -> Vec<u8> {
1300        let idx = id as usize;
1301        let Some(tok) = self.id_to_token.get(idx) else {
1302            return Vec::new();
1303        };
1304        if self.added_ids.contains(&id) {
1305            return tok.as_bytes().to_vec();
1306        }
1307        if tok.starts_with("<0x") && tok.ends_with('>') && tok.len() == 6 {
1308            if let Ok(b) = u8::from_str_radix(&tok[3..5], 16) {
1309                return vec![b];
1310            }
1311        }
1312        if self.metaspace {
1313            return tok.replace('\u{2581}', " ").into_bytes();
1314        }
1315        let mut bytes = Vec::new();
1316        for ch in tok.chars() {
1317            match self.char_to_byte.get(&ch) {
1318                Some(&b) => bytes.push(b),
1319                None => {
1320                    let mut buf = [0u8; 4];
1321                    bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
1322                }
1323            }
1324        }
1325        bytes
1326    }
1327
1328    /// The text of every special added token (what `decode` skips).
1329    pub fn special_texts(&self) -> Vec<String> {
1330        self.added
1331            .iter()
1332            .filter(|(_, id)| self.special_ids.contains(id))
1333            .map(|(text, _)| text.clone())
1334            .collect()
1335    }
1336
1337    /// Decode one vocabulary entry for Engram's compressed token map while
1338    /// retaining special tokens.
1339    pub fn decode_token_for_hash(&self, id: u32) -> String {
1340        let idx = id as usize;
1341        if idx >= self.id_to_token.len() {
1342            return String::new();
1343        }
1344        if self.special_ids.contains(&id) {
1345            return self.id_to_token[idx].clone();
1346        }
1347        self.decode_token(id)
1348    }
1349
1350    /// Decode generated protocol text while retaining special markers. The
1351    /// V4.1 harmony parser needs `<think>`, EOS, and spaced DSML tags.
1352    pub fn decode_for_protocol(&self, ids: &[u32]) -> String {
1353        if self.ink_marks().is_some() {
1354            return self.decode(ids);
1355        }
1356        let mut out = String::new();
1357        for &id in ids {
1358            let idx = id as usize;
1359            if self.special_ids.contains(&id) {
1360                if let Some(token) = self.id_to_token.get(idx) {
1361                    out.push_str(token);
1362                }
1363            } else {
1364                out.push_str(&self.decode_token(id));
1365            }
1366        }
1367        out
1368    }
1369
1370    /// Return the backend vocabulary spelling for an Engram map entry.
1371    pub fn raw_token_for_hash(&self, id: u32) -> String {
1372        self.id_to_token
1373            .get(id as usize)
1374            .cloned()
1375            .unwrap_or_default()
1376    }
1377
1378    /// Render the container's Jinja chat template (HF semantics:
1379    /// trim_blocks + lstrip_blocks + loop controls) and encode it.
1380    /// Falls back to hardcoded ChatML when the file carries none.
1381    pub fn apply_chat_template(&self, messages: &[(String, String)]) -> Vec<u32> {
1382        self.apply_chat_template_opts(messages, None)
1383    }
1384
1385    /// Like `apply_chat_template`, with an explicit `enable_thinking` value for
1386    /// reasoning-model templates (Qwen3/3.5 emit an empty <think> block when it
1387    /// is false, so the model answers directly). `None` leaves the variable
1388    /// undefined — the template's own default applies.
1389
1390    /// Chat template with the FULL message shape and a tool list.
1391    ///
1392    /// The pair-based API below flattens every message to (role, text),
1393    /// which silently drops exactly what agentic use needs: the `tools`
1394    /// array, `role: "tool"` results, and `tool_calls` on assistant
1395    /// turns. The templates this format embeds — Qwen-family, Nanbeige —
1396    /// have carried a `{%- if tools %}` branch all along; this is the
1397    /// call that finally feeds it. Messages arrive as JSON objects in
1398    /// the OpenAI shape and pass through to minijinja unflattened, so a
1399    /// template sees the same fields a Python `apply_chat_template`
1400    /// would.
1401    pub fn apply_chat_template_json(
1402        &self,
1403        messages: &[serde_json::Value],
1404        tools: Option<&[serde_json::Value]>,
1405        enable_thinking: Option<bool>,
1406    ) -> Vec<u32> {
1407        self.apply_chat_template_json_with_reasoning_effort(messages, tools, enable_thinking, None)
1408    }
1409
1410    /// JSON chat template rendering with an optional template-native reasoning
1411    /// effort. An explicit value is passed through to Jinja unchanged.
1412    pub fn apply_chat_template_json_with_reasoning_effort(
1413        &self,
1414        messages: &[serde_json::Value],
1415        tools: Option<&[serde_json::Value]>,
1416        enable_thinking: Option<bool>,
1417        reasoning_effort: Option<&str>,
1418    ) -> Vec<u32> {
1419        match self.try_apply_chat_template_json_with_reasoning_effort(
1420            messages,
1421            tools,
1422            enable_thinking,
1423            reasoning_effort,
1424        ) {
1425            Ok(ids) => ids,
1426            Err(e) => {
1427                tracing::error!("chat template render failed ({e}); ChatML fallback");
1428                self.chatml_json_fallback(messages, enable_thinking)
1429            }
1430        }
1431    }
1432
1433    /// Like [`Self::apply_chat_template_json`], but a template that fails
1434    /// to render is an ERROR instead of a quiet ChatML approximation.
1435    ///
1436    /// The fallback flattens every message to (role, text): it has no
1437    /// place for `tools`, `tool_calls` or `role: "tool"`. For a plain chat
1438    /// that is a tolerable degradation; for a request with tools it means
1439    /// the model never sees the functions and answers as if none were
1440    /// offered — a failure no client can detect. The server calls this
1441    /// variant when tools are present and reports the error instead.
1442    /// Files without a template still take the ChatML path (Ok).
1443    pub fn try_apply_chat_template_json(
1444        &self,
1445        messages: &[serde_json::Value],
1446        tools: Option<&[serde_json::Value]>,
1447        enable_thinking: Option<bool>,
1448    ) -> Result<Vec<u32>, String> {
1449        self.try_apply_chat_template_json_with_reasoning_effort(
1450            messages,
1451            tools,
1452            enable_thinking,
1453            None,
1454        )
1455    }
1456
1457    /// Fallible JSON template rendering with a native reasoning-effort
1458    /// variable. MiniMax M3's upstream template is adaptive and consumes
1459    /// `<effort>` from this variable instead of a generic `<think>` injection.
1460    pub fn try_apply_chat_template_json_with_reasoning_effort(
1461        &self,
1462        messages: &[serde_json::Value],
1463        tools: Option<&[serde_json::Value]>,
1464        enable_thinking: Option<bool>,
1465        reasoning_effort: Option<&str>,
1466    ) -> Result<Vec<u32>, String> {
1467        if let Some(tpl) = &self.chat_template {
1468            return self
1469                .render_template_json(tpl, messages, tools, enable_thinking, reasoning_effort)
1470                .map(|text| self.with_bos(self.encode(&text)))
1471                .map_err(|e| format!("{e:#}"));
1472        }
1473        Ok(self.chatml_json_fallback(messages, enable_thinking))
1474    }
1475
1476    fn chatml_json_fallback(
1477        &self,
1478        messages: &[serde_json::Value],
1479        enable_thinking: Option<bool>,
1480    ) -> Vec<u32> {
1481        let pairs: Vec<(String, String)> = messages
1482            .iter()
1483            .map(|m| {
1484                (
1485                    m.get("role")
1486                        .and_then(|v| v.as_str())
1487                        .unwrap_or("user")
1488                        .to_string(),
1489                    m.get("content")
1490                        .and_then(|v| v.as_str())
1491                        .unwrap_or("")
1492                        .to_string(),
1493                )
1494            })
1495            .collect();
1496        self.with_bos(self.chatml_fallback_opts(&pairs, enable_thinking))
1497    }
1498
1499    /// Render the template against JSON-shaped messages (parity surface).
1500    pub fn render_chat_json(
1501        &self,
1502        messages: &[serde_json::Value],
1503        tools: Option<&[serde_json::Value]>,
1504        enable_thinking: Option<bool>,
1505    ) -> Option<String> {
1506        self.render_chat_json_with_reasoning_effort(messages, tools, enable_thinking, None)
1507    }
1508
1509    /// Render a JSON chat template with an optional native reasoning effort.
1510    /// Kept public for exact-template parity tests and protocol adapters.
1511    pub fn render_chat_json_with_reasoning_effort(
1512        &self,
1513        messages: &[serde_json::Value],
1514        tools: Option<&[serde_json::Value]>,
1515        enable_thinking: Option<bool>,
1516        reasoning_effort: Option<&str>,
1517    ) -> Option<String> {
1518        let tpl = self.chat_template.as_ref()?;
1519        match self.render_template_json(tpl, messages, tools, enable_thinking, reasoning_effort) {
1520            Ok(t) => Some(t),
1521            Err(e) => {
1522                tracing::error!("chat template render (json): {e:#}");
1523                eprintln!("chat template render (json): {e:#}");
1524                None
1525            }
1526        }
1527    }
1528
1529    /// Whether the chat template writes a system prompt of its own when the
1530    /// conversation has none (CherryPit's identity prompt, Qwen2.5's "You
1531    /// are Qwen…"): a user turn alone renders LONGER than the same turn
1532    /// behind an empty system message. A caller that would add a system
1533    /// message of its own must not, or that prompt is lost. False when the
1534    /// file has no template or it fails to render.
1535    pub fn template_has_default_system(&self) -> bool {
1536        let Some(tpl) = self.chat_template.as_ref() else {
1537            return false;
1538        };
1539        let user = serde_json::json!({"role": "user", "content": "x"});
1540        let system = serde_json::json!({"role": "system", "content": ""});
1541        let alone = self.render_template_json(tpl, std::slice::from_ref(&user), None, None, None);
1542        let behind = self.render_template_json(tpl, &[system, user], None, None, None);
1543        matches!((alone, behind), (Ok(a), Ok(b)) if a.len() > b.len())
1544    }
1545
1546    fn render_template_json(
1547        &self,
1548        tpl: &str,
1549        messages: &[serde_json::Value],
1550        tools: Option<&[serde_json::Value]>,
1551        enable_thinking: Option<bool>,
1552        reasoning_effort: Option<&str>,
1553    ) -> Result<String, minijinja::Error> {
1554        let mut env = crate::chat_template::environment();
1555        self.add_special_globals(&mut env);
1556        let tpl_src = strip_generation_tags(tpl);
1557        // a direct answer's reasoning budget: GLM-5's templates take `low`,
1558        // Hy4-flash's only `no_think` / `high` / `max` (it raises on `low`)
1559        // Inkling 2's dial is a number (`none` = 0, a direct answer) and its turn
1560        // has no think block to close
1561        let inkling = tpl_src.contains("<|content_model_end_sampling|>") && tpl_src.contains("Thinking effort level");
1562        let off_effort: &'static str = if tpl_src.contains("no_think") {
1563            "no_think"
1564        } else if inkling {
1565            "none"
1566        } else {
1567            "low"
1568        };
1569        env.add_template("chat", &tpl_src)?;
1570        let msgs: Vec<minijinja::Value> = messages
1571            .iter()
1572            .map(minijinja::Value::from_serialize)
1573            .collect();
1574        let tools_v: Option<Vec<minijinja::Value>> =
1575            tools.map(|ts| ts.iter().map(minijinja::Value::from_serialize).collect());
1576        let tpl = env.get_template("chat")?;
1577        // Three axes, each present only when meaningful: templates guard
1578        // with `is defined`, and an explicit null flips those guards.
1579        // `tool_call_format` picks the grammar in two-mode templates
1580        // (Nanbeige): undefined falls into their XML branch. The JSON
1581        // grammar is the one every parser downstream speaks, so choose
1582        // it explicitly; templates without the knob never read it.
1583        let rendered = match (tools_v, enable_thinking, reasoning_effort) {
1584            (Some(ts), Some(v), Some(effort)) => tpl.render(minijinja::context! {
1585                messages => msgs, tools => ts, add_generation_prompt => true, enable_thinking => v,
1586                reasoning_effort => effort,
1587                tool_call_format => "json",
1588            })?,
1589            (Some(ts), Some(v), None) => tpl.render(minijinja::context! {
1590                messages => msgs, tools => ts, add_generation_prompt => true, enable_thinking => v,
1591                // GLM-5's template controls its reasoning budget with
1592                // `reasoning_effort` rather than `enable_thinking`.  A direct
1593                // answer therefore needs the low budget when thinking is
1594                // disabled; otherwise the template defaults to `max`.
1595                reasoning_effort => if !v { Some(off_effort) } else { None::<&str> },
1596                tool_call_format => "json",
1597            })?,
1598            (Some(ts), None, Some(effort)) => tpl.render(minijinja::context! {
1599                messages => msgs, tools => ts, add_generation_prompt => true,
1600                reasoning_effort => effort,
1601                tool_call_format => "json",
1602            })?,
1603            (Some(ts), None, None) => tpl.render(minijinja::context! {
1604                messages => msgs, tools => ts, add_generation_prompt => true,
1605                tool_call_format => "json",
1606            })?,
1607            (None, Some(v), Some(effort)) => tpl.render(minijinja::context! {
1608                messages => msgs, add_generation_prompt => true, enable_thinking => v,
1609                reasoning_effort => effort,
1610                tool_call_format => "json",
1611            })?,
1612            (None, Some(v), None) => tpl.render(minijinja::context! {
1613                messages => msgs, add_generation_prompt => true, enable_thinking => v,
1614                // See the tool-bearing branch above.
1615                reasoning_effort => if !v { Some(off_effort) } else { None::<&str> },
1616                tool_call_format => "json",
1617            })?,
1618            (None, None, Some(effort)) => tpl.render(minijinja::context! {
1619                messages => msgs, add_generation_prompt => true,
1620                reasoning_effort => effort,
1621                tool_call_format => "json",
1622            })?,
1623            (None, None, None) => tpl.render(minijinja::context! {
1624                messages => msgs, add_generation_prompt => true,
1625                tool_call_format => "json",
1626            })?,
1627        };
1628        if inkling {
1629            return Ok(rendered);
1630        }
1631        Ok(close_direct_think(rendered, enable_thinking))
1632    }
1633
1634    pub fn apply_chat_template_opts(
1635        &self,
1636        messages: &[(String, String)],
1637        enable_thinking: Option<bool>,
1638    ) -> Vec<u32> {
1639        if let Some(tpl) = &self.chat_template {
1640            match self.render_template(tpl, messages, enable_thinking) {
1641                Ok(text) => return self.with_bos(self.encode(&text)),
1642                Err(e) => {
1643                    tracing::error!("chat template render failed ({e}); ChatML fallback");
1644                }
1645            }
1646        }
1647        self.with_bos(self.chatml_fallback_opts(messages, enable_thinking))
1648    }
1649
1650    /// Prepend BOS when the tokenizer declares it (llama family).
1651    pub fn with_bos(&self, mut ids: Vec<u32>) -> Vec<u32> {
1652        if self.add_bos {
1653            if let Some(b) = self.bos_token_id {
1654                if ids.first() != Some(&b) {
1655                    ids.insert(0, b);
1656                }
1657            }
1658        }
1659        ids
1660    }
1661
1662    /// Render the carried template to text (parity-testable surface).
1663    pub fn render_chat(&self, messages: &[(String, String)]) -> Option<String> {
1664        self.render_chat_opts(messages, None)
1665    }
1666
1667    /// Render the carried template to text with explicit thinking mode.
1668    pub fn render_chat_opts(
1669        &self,
1670        messages: &[(String, String)],
1671        enable_thinking: Option<bool>,
1672    ) -> Option<String> {
1673        let tpl = self.chat_template.as_ref()?;
1674        match self.render_template(tpl, messages, enable_thinking) {
1675            Ok(t) => Some(t),
1676            Err(e) => {
1677                tracing::error!("chat template render: {e:#}");
1678                None
1679            }
1680        }
1681    }
1682
1683    fn render_template(
1684        &self,
1685        tpl: &str,
1686        messages: &[(String, String)],
1687        enable_thinking: Option<bool>,
1688    ) -> Result<String, minijinja::Error> {
1689        let mut env = crate::chat_template::environment();
1690        self.add_special_globals(&mut env);
1691        let tpl_src = strip_generation_tags(tpl);
1692        // a direct answer's reasoning budget: GLM-5's templates take `low`,
1693        // Hy4-flash's only `no_think` / `high` / `max` (it raises on `low`),
1694        // Inkling 2 a number (`none` = 0)
1695        let inkling = tpl_src.contains("<|content_model_end_sampling|>") && tpl_src.contains("Thinking effort level");
1696        let off_effort: &'static str = if tpl_src.contains("no_think") {
1697            "no_think"
1698        } else if inkling {
1699            "none"
1700        } else {
1701            "low"
1702        };
1703        env.add_template("chat", &tpl_src)?;
1704        let msgs: Vec<minijinja::Value> = messages
1705            .iter()
1706            .map(|(role, content)| {
1707                minijinja::context! { role => role, content => content }
1708            })
1709            .collect();
1710        // `enable_thinking` stays UNDEFINED when None — reasoning templates
1711        // check `enable_thinking is defined` and fall back to their default.
1712        let rendered = match enable_thinking {
1713            Some(v) => env.get_template("chat")?.render(minijinja::context! {
1714                messages => msgs,
1715                add_generation_prompt => true,
1716                enable_thinking => v,
1717                // GLM-5 uses this variable (not `enable_thinking`) to select
1718                // its reasoning budget and defaults to max when omitted.
1719                reasoning_effort => if !v { Some(off_effort) } else { None::<&str> },
1720            })?,
1721            None => env.get_template("chat")?.render(minijinja::context! {
1722                messages => msgs,
1723                add_generation_prompt => true,
1724            })?,
1725        };
1726        if inkling {
1727            return Ok(rendered);
1728        }
1729        Ok(close_direct_think(rendered, enable_thinking))
1730    }
1731
1732    /// The BOS text Transformers hands every chat template as `bos_token`.
1733    /// LFM2/LFM3 templates open with `{{- bos_token -}}` while their
1734    /// tokenizers add no BOS of their own, so an undefined variable dropped
1735    /// the BOS from every chat prompt. A tokenizer that also prepends BOS
1736    /// (`add_bos`) sees it already in place (`with_bos`), so nothing doubles.
1737    fn add_special_globals(&self, env: &mut minijinja::Environment<'_>) {
1738        let bos = self.bos_token_id.and_then(|id| {
1739            self.added
1740                .iter()
1741                .find(|(_, i)| *i == id)
1742                .map(|(text, _)| text.clone())
1743        });
1744        if let Some(text) = bos {
1745            env.add_global("bos_token", text);
1746        }
1747    }
1748
1749    /// Hardcoded Qwen ChatML (pre-§6.1 files).
1750    fn chatml_fallback(&self, messages: &[(String, String)]) -> Vec<u32> {
1751        self.chatml_fallback_opts(messages, None)
1752    }
1753
1754    /// Hardcoded Qwen ChatML (pre-§6.1 files) with optional thinking suppression.
1755    fn chatml_fallback_opts(
1756        &self,
1757        messages: &[(String, String)],
1758        enable_thinking: Option<bool>,
1759    ) -> Vec<u32> {
1760        let mut tokens = Vec::new();
1761
1762        for (role, content) in messages {
1763            // <|im_start|>role\ncontent<|im_end|>\n
1764            if let Some(start_id) = self.im_start_id {
1765                tokens.push(start_id);
1766            }
1767            tokens.extend(self.encode(&format!("{}\n{}", role, content)));
1768            if let Some(end_id) = self.im_end_id {
1769                tokens.push(end_id);
1770            }
1771            tokens.extend(self.encode("\n"));
1772        }
1773
1774        // Add assistant prefix
1775        if let Some(start_id) = self.im_start_id {
1776            tokens.push(start_id);
1777        }
1778        tokens.extend(self.encode("assistant\n"));
1779        if enable_thinking == Some(false) {
1780            tokens.extend(self.encode("<think>\n\n</think>\n\n"));
1781        }
1782
1783        tokens
1784    }
1785
1786    /// Vocabulary size.
1787    pub fn vocab_size(&self) -> usize {
1788        self.id_to_token.len()
1789    }
1790
1791    /// Return the ID for an exact token spelling, including added/special
1792    /// tokens. Multimodal prompt preparation uses this to validate the image
1793    /// placeholder against the model configuration.
1794    pub fn token_to_id(&self, token: &str) -> Option<u32> {
1795        self.vocab.get(token).copied()
1796    }
1797
1798    /// Alias matching the HuggingFace tokenizer API used by the official
1799    /// DeepSeek image processor.
1800    pub fn convert_tokens_to_ids(&self, token: &str) -> Option<u32> {
1801        self.token_to_id(token)
1802    }
1803
1804    /// Check if token ID is EOS.
1805    pub fn is_eos(&self, id: u32) -> bool {
1806        self.eos_token_id == Some(id) || self.im_end_id == Some(id) || self.extra_eos.contains(&id)
1807    }
1808}
1809
1810#[derive(Debug, thiserror::Error)]
1811pub enum TokenizerError {
1812    #[error("IO error: {0}")]
1813    Io(String),
1814    #[error("Parse error: {0}")]
1815    Parse(String),
1816}
1817
1818/// SentencePiece merges over token ids: `(left, right)` → `(rank, merged)`.
1819struct SpMerges {
1820    pairs: HashMap<u64, (u32, u32)>,
1821    /// `<0xNN>` ids for the byte fallback (`u32::MAX` = absent)
1822    bytes: [u32; 256],
1823}
1824
1825const SP_NONE: u32 = u32::MAX;
1826
1827thread_local! {
1828    /// [`Tokenizer::encode_reference`] in progress on this thread.
1829    static SP_STRINGS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1830}
1831
1832impl SpMerges {
1833    fn build(vocab: &HashMap<String, u32>, ranks: &HashMap<(String, String), u32>) -> Option<Self> {
1834        if ranks.is_empty() {
1835            return None;
1836        }
1837        let mut pairs = HashMap::with_capacity(ranks.len());
1838        let mut cat = String::new();
1839        for ((a, b), &r) in ranks {
1840            let (&ia, &ib) = (vocab.get(a)?, vocab.get(b)?);
1841            cat.clear();
1842            cat.push_str(a);
1843            cat.push_str(b);
1844            let &m = vocab.get(&cat)?;
1845            pairs.insert(((ia as u64) << 32) | ib as u64, (r, m));
1846        }
1847        let mut bytes = [SP_NONE; 256];
1848        for (b, slot) in bytes.iter_mut().enumerate() {
1849            if let Some(&id) = vocab.get(&format!("<0x{b:02X}>")) {
1850                *slot = id;
1851            }
1852        }
1853        Some(SpMerges { pairs, bytes })
1854    }
1855
1856    #[inline]
1857    fn rank(&self, a: u32, b: u32) -> Option<(u32, u32)> {
1858        if a == SP_NONE || b == SP_NONE {
1859            return None;
1860        }
1861        self.pairs.get(&(((a as u64) << 32) | b as u64)).copied()
1862    }
1863
1864    /// The string form's rule over ids: take the lowest rank among the
1865    /// adjacent pairs, merge every live occurrence of that pair left to
1866    /// right (non-overlapping), and only then admit the pairs the merges
1867    /// formed — exactly the order of `bpe_piece_sp_strings`.
1868    fn encode(&self, vocab: &HashMap<String, u32>, piece: &str, out: &mut Vec<u32>) {
1869        use std::cmp::Reverse;
1870        use std::collections::BinaryHeap;
1871        let spans: Vec<(usize, usize)> = piece
1872            .char_indices()
1873            .map(|(i, c)| (i, i + c.len_utf8()))
1874            .collect();
1875        let n = spans.len();
1876        let mut buf = [0u8; 4];
1877        let mut id: Vec<u32> = piece
1878            .chars()
1879            .map(|c| *vocab.get(c.encode_utf8(&mut buf) as &str).unwrap_or(&SP_NONE))
1880            .collect();
1881        let mut next: Vec<usize> = (1..=n).collect();
1882        let mut prev: Vec<usize> = (0..n).map(|i| i.wrapping_sub(1)).collect();
1883        let mut alive = vec![true; n];
1884        let mut heap: BinaryHeap<Reverse<(u32, usize)>> = BinaryHeap::with_capacity(n);
1885        for i in 0..n.saturating_sub(1) {
1886            if let Some((r, _)) = self.rank(id[i], id[i + 1]) {
1887                heap.push(Reverse((r, i)));
1888            }
1889        }
1890        let mut batch: Vec<usize> = Vec::new();
1891        let mut merged: Vec<usize> = Vec::new();
1892        while let Some(&Reverse((r, _))) = heap.peek() {
1893            batch.clear();
1894            while let Some(&Reverse((r2, pos))) = heap.peek() {
1895                if r2 != r {
1896                    break;
1897                }
1898                heap.pop();
1899                batch.push(pos);
1900            }
1901            batch.sort_unstable();
1902            batch.dedup();
1903            merged.clear();
1904            for &pos in &batch {
1905                if !alive[pos] || next[pos] >= n {
1906                    continue;
1907                }
1908                let j = next[pos];
1909                match self.rank(id[pos], id[j]) {
1910                    Some((rr, m)) if rr == r => {
1911                        id[pos] = m;
1912                        alive[j] = false;
1913                        next[pos] = next[j];
1914                        if next[j] < n {
1915                            prev[next[j]] = pos;
1916                        }
1917                        merged.push(pos);
1918                    }
1919                    _ => {}
1920                }
1921            }
1922            for &pos in &merged {
1923                if !alive[pos] {
1924                    continue;
1925                }
1926                let pv = prev[pos];
1927                if pv < n && alive[pv] {
1928                    if let Some((r2, _)) = self.rank(id[pv], id[pos]) {
1929                        heap.push(Reverse((r2, pv)));
1930                    }
1931                }
1932                let nx = next[pos];
1933                if nx < n {
1934                    if let Some((r2, _)) = self.rank(id[pos], id[nx]) {
1935                        heap.push(Reverse((r2, pos)));
1936                    }
1937                }
1938            }
1939        }
1940        let mut i = 0usize;
1941        while i < n {
1942            if id[i] != SP_NONE {
1943                out.push(id[i]);
1944            } else {
1945                // a character outside the vocabulary: its UTF-8 bytes
1946                let (a, b) = spans[i];
1947                let mut ok = true;
1948                for &byte in piece[a..b].as_bytes() {
1949                    match self.bytes[byte as usize] {
1950                        SP_NONE => {
1951                            ok = false;
1952                            break;
1953                        }
1954                        t => out.push(t),
1955                    }
1956                }
1957                if !ok {
1958                    tracing::error!("tokenizer: no id for SP symbol {:?} — dropped", &piece[a..b]);
1959                }
1960            }
1961            i = next[i];
1962        }
1963    }
1964}
1965
1966#[cfg(test)]
1967mod tests {
1968    use super::*;
1969
1970    #[test]
1971    fn direct_answer_closes_think_after_a_chatml_assistant_line() {
1972        let r = "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n".to_string();
1973        assert_eq!(
1974            close_direct_think(r.clone(), Some(false)),
1975            "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
1976        );
1977        assert_eq!(close_direct_think(r.clone(), None), r);
1978        // A template that closed the block itself is left alone.
1979        let done = format!("{r}<think>\n\n</think>\n\n");
1980        assert_eq!(close_direct_think(done.clone(), Some(false)), done);
1981    }
1982
1983    #[test]
1984    fn byte_unicode_bijection() {
1985        let (b2c, c2b) = bytes_to_unicode();
1986        for b in 0..=255u8 {
1987            assert_eq!(c2b[&b2c[b as usize]], b);
1988        }
1989        // GPT-2 well-known mappings: space → Ġ, newline → Ċ
1990        assert_eq!(b2c[b' ' as usize], 'Ġ');
1991        assert_eq!(b2c[b'\n' as usize], 'Ċ');
1992    }
1993
1994    #[test]
1995    fn byte_level_roundtrip_utf8() {
1996        let tok = Tokenizer::byte_level();
1997        let text = "hello 🌍 hi\n";
1998        let ids = tok.encode(text);
1999        assert_eq!(ids.len(), text.len()); // one id per byte
2000        assert_eq!(tok.decode(&ids), text);
2001    }
2002
2003    /// A tiny real-format tokenizer.json exercising the full pipeline:
2004    /// GPT-2 regex, byte-level alphabet, one merge, an added token.
2005    fn mini_json() -> String {
2006        // vocab: byte-level chars for h,e,l,o,Ġ,w,r,d + merged "he"
2007        let vocab: Vec<(&str, u32)> = vec![
2008            ("h", 0),
2009            ("e", 1),
2010            ("l", 2),
2011            ("o", 3),
2012            ("Ġ", 4),
2013            ("w", 5),
2014            ("r", 6),
2015            ("d", 7),
2016            ("he", 8),
2017            ("Ġw", 9),
2018        ];
2019        let vocab_json: String = vocab
2020            .iter()
2021            .map(|(t, i)| format!("\"{t}\": {i}"))
2022            .collect::<Vec<_>>()
2023            .join(", ");
2024        format!(
2025            r#"{{
2026              "model": {{
2027                "type": "BPE",
2028                "vocab": {{ {vocab_json} }},
2029                "merges": [["h", "e"], ["Ġ", "w"]]
2030              }},
2031              "added_tokens": [
2032                {{"id": 10, "content": "<|eot|>", "special": true}}
2033              ]
2034            }}"#
2035        )
2036    }
2037
2038    /// The id-level SentencePiece BPE gives the string form's ids on every
2039    /// input, including merges whose products rank below the merge that
2040    /// made them, overlapping runs ("aaa"), two merges producing one
2041    /// string, and characters outside the vocabulary (byte fallback, with
2042    /// one byte missing).
2043    #[test]
2044    fn sp_heap_bpe_matches_the_string_form() {
2045        let toks = [
2046            "a", "b", "c", "▁", "bc", "abc", "ab", "aa", "aab", "ca", "▁a", "aabc",
2047            "aaa", "<0x64>", "<0xC3>", "▁▁",
2048        ];
2049        let vocab: Vec<String> = toks
2050            .iter()
2051            .enumerate()
2052            .map(|(i, t)| format!("\"{t}\": {i}"))
2053            .collect();
2054        let merges = [
2055            ("aab", "c"),
2056            ("b", "c"),
2057            ("a", "bc"),
2058            ("a", "b"),
2059            ("ab", "c"),
2060            ("a", "a"),
2061            ("aa", "b"),
2062            ("c", "a"),
2063            ("▁", "a"),
2064            ("aa", "a"),
2065            ("▁", "▁"),
2066        ];
2067        let merges: Vec<String> = merges
2068            .iter()
2069            .map(|(a, b)| format!("[\"{a}\", \"{b}\"]"))
2070            .collect();
2071        let json = format!(
2072            r#"{{"model": {{"type": "BPE", "byte_fallback": true, "vocab": {{ {} }}, "merges": [{}]}},
2073               "normalizer": {{"type": "Replace", "pattern": {{"String": " "}}, "content": "\u2581"}},
2074               "added_tokens": []}}"#,
2075            vocab.join(", "),
2076            merges.join(", ")
2077        );
2078        let t = Tokenizer::from_json(&json).unwrap();
2079        assert!(t.metaspace, "a byte_fallback vocabulary takes the SentencePiece path");
2080        assert!(t.sp_merges().is_some());
2081        let alphabet = ['a', 'b', 'c', '\u{2581}', 'd', 'é', 'a', 'a', 'b'];
2082        let mut state = 0x2545_f491_4f6c_dd1du64;
2083        for len in 0..40 {
2084            for _ in 0..60 {
2085                let piece: String = (0..len)
2086                    .map(|_| {
2087                        state ^= state << 13;
2088                        state ^= state >> 7;
2089                        state ^= state << 17;
2090                        alphabet[(state % alphabet.len() as u64) as usize]
2091                    })
2092                    .collect();
2093                let (mut fast, mut slow) = (Vec::new(), Vec::new());
2094                t.sp_merges().unwrap().encode(&t.vocab, &piece, &mut fast);
2095                t.bpe_piece_sp_strings(&piece, &mut slow);
2096                assert_eq!(fast, slow, "{piece:?}");
2097            }
2098        }
2099    }
2100
2101    /// A small byte-level vocabulary splits a CJK character over two tokens
2102    /// (MNN-Pocket's 65k vocab: "地" = E5 9C | B0). Streaming must print the
2103    /// character once it is complete, never two U+FFFD.
2104    #[test]
2105    fn streaming_keeps_a_character_split_over_tokens() {
2106        let (b2u, _) = bytes_to_unicode();
2107        let piece = |bytes: &[u8]| bytes.iter().map(|&b| b2u[b as usize]).collect::<String>();
2108        let vocab = serde_json::json!({
2109            piece(" ".as_bytes()): 0,
2110            piece(&[0xE5, 0x9C]): 1,
2111            piece(&[0xB0]): 2,
2112            piece("球".as_bytes()): 3,
2113        });
2114        let json = serde_json::json!({
2115            "model": {"type": "BPE", "vocab": vocab, "merges": []},
2116            "pre_tokenizer": {"type": "ByteLevel"},
2117            "decoder": {"type": "ByteLevel"},
2118            "added_tokens": [{"id": 4, "content": "<|im_end|>", "special": true}],
2119        })
2120        .to_string();
2121        let t = Tokenizer::from_json(&json).unwrap();
2122        let ids = [0u32, 1, 2, 3, 4];
2123        assert_eq!(t.decode(&ids), " 地球");
2124        let mut pending = Vec::new();
2125        let pieces: Vec<String> = ids.iter().map(|&i| t.decode_token_stream(i, &mut pending)).collect();
2126        assert_eq!(pieces, [" ", "", "地", "球", ""]);
2127        assert!(pending.is_empty());
2128        // Invalid bytes still come out (lossily) instead of waiting forever.
2129        assert_eq!(t.decode_token_stream(2, &mut pending), "\u{FFFD}");
2130        assert!(pending.is_empty());
2131    }
2132
2133    /// MiniCPM5 marks its tool grammar special. Decoding must keep the
2134    /// markup (the call IS that text) and still drop the chat control
2135    /// tokens around it.
2136    #[test]
2137    fn tool_markup_decodes_even_when_special() {
2138        let json = r#"{
2139          "model": {"type": "BPE", "vocab": {"h": 0, "e": 1, "l": 2, "o": 3}, "merges": []},
2140          "added_tokens": [
2141            {"id": 10, "content": "<|im_end|>", "special": true},
2142            {"id": 11, "content": "<function", "special": true},
2143            {"id": 12, "content": "</function>", "special": true},
2144            {"id": 13, "content": "<param", "special": true},
2145            {"id": 14, "content": "</param>", "special": true},
2146            {"id": 15, "content": "<tool_call>", "special": true}
2147          ]
2148        }"#;
2149        let t = Tokenizer::from_json(json).unwrap();
2150        let ids = [11, 0, 1, 13, 2, 14, 12, 15, 10];
2151        assert_eq!(
2152            t.decode(&ids),
2153            "<functionhe<paraml</param></function><tool_call>"
2154        );
2155        let streamed: String = ids.iter().map(|&i| t.decode_token(i)).collect();
2156        assert_eq!(streamed, t.decode(&ids), "streaming must agree with decode");
2157        assert!(
2158            !t.decode(&[10]).contains("im_end"),
2159            "control tokens stay hidden"
2160        );
2161    }
2162
2163    /// Parity against HuggingFace on a real tokenizer, run only when the
2164    /// file is present (CMF_TOK_PARITY=/path/to/tokenizer.json).
2165    #[test]
2166    fn real_tokenizer_parity_when_available() {
2167        let Ok(path) = std::env::var("CMF_TOK_PARITY") else {
2168            return;
2169        };
2170        let t = Tokenizer::from_file(&path).expect("load");
2171        for (text, want) in [
2172            (
2173                "The capital of France is",
2174                vec![671u32, 6102, 294, 8760, 344],
2175            ),
2176            ("2 + 2 =", vec![20, 940, 223, 20, 438]),
2177        ] {
2178            let got = t.encode(text);
2179            assert_eq!(got, want, "«{text}»");
2180        }
2181    }
2182
2183    /// Granite 4.2 ships its prompt grammar as a sidecar
2184    /// `chat_template.jinja` (not tokenizer_config.chat_template).  Exercise
2185    /// the exact upstream file when supplied so macro/namespace support and
2186    /// both reasoning prefixes cannot silently fall back to generic ChatML.
2187    #[test]
2188    fn granite_42_chat_template_when_available() {
2189        let Ok(path) = std::env::var("CMF_GRANITE_CHAT_TEMPLATE") else {
2190            return;
2191        };
2192        let mut tok = Tokenizer::byte_level();
2193        tok.chat_template = Some(std::fs::read_to_string(path).expect("read Granite template"));
2194        let messages = vec![("user".to_string(), "Hello".to_string())];
2195
2196        let thinking = tok
2197            .render_chat_opts(&messages, Some(true))
2198            .expect("render Granite thinking prompt");
2199        assert_eq!(
2200            thinking,
2201            "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>\n"
2202        );
2203
2204        let direct = tok
2205            .render_chat_opts(&messages, Some(false))
2206            .expect("render Granite direct prompt");
2207        assert_eq!(
2208            direct,
2209            "<|im_start|>system\n<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think></think>"
2210        );
2211    }
2212
2213    #[test]
2214    fn json_template_passes_explicit_reasoning_effort_without_overriding_it() {
2215        let mut tok = Tokenizer::byte_level();
2216        tok.chat_template = Some(
2217            "{% if reasoning_effort is defined %}<effort>{{ reasoning_effort }}</effort>{% else %}<default-effort>{% endif %}|{{ enable_thinking }}|{{ messages[0].reasoning_content }}"
2218                .to_string(),
2219        );
2220        let messages = vec![serde_json::json!({
2221            "role": "assistant",
2222            "content": "answer",
2223            "reasoning_content": "prior chain"
2224        })];
2225        let explicit = tok
2226            .render_chat_json_with_reasoning_effort(&messages, None, Some(false), Some("high"))
2227            .expect("render explicit effort");
2228        assert_eq!(explicit, "<effort>high</effort>|False|prior chain");
2229
2230        let native_default = tok
2231            .render_chat_json_with_reasoning_effort(&messages, None, None, None)
2232            .expect("render native default");
2233        assert_eq!(native_default, "<default-effort>||prior chain");
2234    }
2235
2236    /// Minico-M1-1105's five-step dial, its resolution block verbatim: the
2237    /// lax `default`, case folding, aliases, the unknown-value fallback and
2238    /// `enable_thinking=false` as the hard off switch must behave in
2239    /// minijinja as they do in Transformers.
2240    #[test]
2241    fn minico_effort_dial_resolves_like_transformers() {
2242        let mut tok = Tokenizer::byte_level();
2243        tok.chat_template = Some(
2244            r#"{%- set effort = (reasoning_effort | default("medium", true) | string | lower | trim) -%}
2245{%- set effort_aliases = {"none": "off", "xhigh": "max", "med": "medium"} -%}
2246{%- if effort in effort_aliases -%}
2247    {%- set effort = effort_aliases[effort] -%}
2248{%- endif -%}
2249{%- if effort not in ["off", "low", "medium", "high", "max"] -%}
2250    {%- set effort = "medium" -%}
2251{%- endif -%}
2252{%- if enable_thinking is defined and enable_thinking is not none and not enable_thinking -%}
2253    {%- set effort = "off" -%}
2254{%- endif -%}
2255{{- "Reasoning effort: " + effort -}}
2256{%- if effort == "off" -%}{{- "<think>\n\n</think>" -}}{%- endif -%}"#
2257                .to_string(),
2258        );
2259        let msgs = vec![serde_json::json!({"role": "user", "content": "hi"})];
2260        let render = |thinking: Option<bool>, effort: Option<&str>| {
2261            tok.render_chat_json_with_reasoning_effort(&msgs, None, thinking, effort)
2262                .expect("render the effort dial")
2263        };
2264        assert_eq!(render(None, None), "Reasoning effort: medium");
2265        assert_eq!(render(Some(true), None), "Reasoning effort: medium");
2266        assert_eq!(render(None, Some("high")), "Reasoning effort: high");
2267        assert_eq!(render(None, Some(" XHigh ")), "Reasoning effort: max");
2268        assert_eq!(render(None, Some("bogus")), "Reasoning effort: medium");
2269        assert_eq!(render(None, Some("off")), "Reasoning effort: off<think>\n\n</think>");
2270        assert_eq!(render(Some(false), None), "Reasoning effort: off<think>\n\n</think>");
2271        assert_eq!(render(Some(false), Some("max")), "Reasoning effort: off<think>\n\n</think>");
2272        assert!(template_reads_reasoning_effort(tok.chat_template.as_deref().unwrap()));
2273    }
2274
2275    #[test]
2276    fn template_default_system_is_detected() {
2277        let mut tok = Tokenizer::byte_level();
2278        tok.chat_template = Some(
2279            "{% if messages[0].role != 'system' %}<|im_start|>system\nYou are CherryPit.<|im_end|>\n{% endif %}\
2280             {% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}"
2281                .to_string(),
2282        );
2283        assert!(tok.template_has_default_system());
2284
2285        tok.chat_template = Some(
2286            "{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}"
2287                .to_string(),
2288        );
2289        assert!(!tok.template_has_default_system());
2290
2291        tok.chat_template = Some("{% for message in messages %}".to_string());
2292        assert!(!tok.template_has_default_system());
2293        tok.chat_template = None;
2294        assert!(!tok.template_has_default_system());
2295    }
2296
2297    #[test]
2298    fn fallible_json_template_render_does_not_use_chatml_on_jinja_error() {
2299        let mut tok = Tokenizer::byte_level();
2300        tok.chat_template = Some("{% for message in messages %}".to_string());
2301        let messages = vec![serde_json::json!({"role": "user", "content": "hello"})];
2302        let error = tok
2303            .try_apply_chat_template_json_with_reasoning_effort(
2304                &messages,
2305                None,
2306                None,
2307                Some("high"),
2308            )
2309            .expect_err("unclosed Jinja must fail instead of producing ChatML");
2310        assert!(!error.is_empty());
2311    }
2312
2313    /// MiniMax M3.1 carries an unusually featureful sidecar template: macros,
2314    /// `namespace`, Python-style mapping access, custom `tojson` keywords,
2315    /// a namespaced XML tool grammar and M3-specific reasoning markers.  Run
2316    /// its *actual* upstream template when supplied rather than accepting a
2317    /// synthetic toy template that would miss a minijinja compatibility gap.
2318    #[test]
2319    fn minimax_m3_chat_template_when_available() {
2320        let Ok(path) = std::env::var("CMF_MINIMAX_M3_CHAT_TEMPLATE") else {
2321            return;
2322        };
2323        let mut tok = Tokenizer::byte_level();
2324        tok.chat_template = Some(std::fs::read_to_string(path).expect("read MiniMax M3 template"));
2325        let messages = vec![
2326            serde_json::json!({"role": "system", "content": "Keep answers concise."}),
2327            serde_json::json!({"role": "user", "content": "What is 2 + 2?"}),
2328        ];
2329        let tools = vec![serde_json::json!({
2330            "type": "function",
2331            "function": {
2332                "name": "get_weather",
2333                "description": "Return the weather for a city.",
2334                "parameters": {
2335                    "type": "object",
2336                    "properties": {"city": {"type": "string"}},
2337                    "required": ["city"]
2338                }
2339            }
2340        })];
2341        let rendered = tok
2342            .render_chat_json(&messages, Some(&tools), Some(false))
2343            .expect("render MiniMax M3 native prompt");
2344        assert!(rendered.starts_with("]~!b[]~b]system\n"), "{rendered:?}");
2345        assert!(rendered.contains("<effort>low</effort>"), "{rendered:?}");
2346        assert!(
2347            rendered.contains("]<]minimax[>[<tool_call>"),
2348            "{rendered:?}"
2349        );
2350        assert!(rendered.contains("get_weather"), "{rendered:?}");
2351        assert!(rendered.ends_with("]~b]ai\n"), "{rendered:?}");
2352    }
2353
2354    /// GLM-5's generation suffix is `<|assistant|><think>`.  The direct-answer
2355    /// path must close that marker without splitting the `<|assistant|>` token
2356    /// (a bare `rfind("assistant")` inserts bytes in the middle of the marker).
2357    #[test]
2358    fn glm_direct_template_keeps_assistant_special_token_intact() {
2359        let mut tok = Tokenizer::byte_level();
2360        tok.chat_template = Some(
2361            "[gMASK]<sop>{%- set effort = reasoning_effort if reasoning_effort is defined and reasoning_effort in ['low', 'high'] else 'max' -%}<|system|>Reasoning Effort: {{ effort | capitalize }}{%- for m in messages -%}<|user|>{{ m.content }}{%- endfor -%}<|assistant|><think>"
2362                .to_string(),
2363        );
2364        let messages = vec![("user".to_string(), "2+2?".to_string())];
2365        let rendered = tok
2366            .render_chat_opts(&messages, Some(false))
2367            .expect("render GLM direct prompt");
2368        assert!(rendered.contains("Reasoning Effort: Low"));
2369        assert!(rendered.contains("<|assistant|><think></think>"));
2370        assert!(!rendered.contains("<|assistant\n"));
2371
2372        // Leaving thinking enabled must preserve GLM's template default
2373        // (`max`) rather than serializing our direct-answer hint.
2374        let thinking = tok
2375            .render_chat_opts(&messages, Some(true))
2376            .expect("render GLM thinking prompt");
2377        assert!(thinking.contains("Reasoning Effort: Max"));
2378
2379        let json_messages = vec![serde_json::json!({
2380            "role": "user",
2381            "content": "2+2?"
2382        })];
2383        let rendered_json = tok
2384            .render_chat_json(&json_messages, None, Some(false))
2385            .expect("render GLM JSON direct prompt");
2386        assert!(rendered_json.contains("Reasoning Effort: Low"));
2387        assert!(rendered_json.contains("<|assistant|><think></think>"));
2388        assert!(!rendered_json.contains("<|assistant\n"));
2389    }
2390
2391    /// A Sequence of Splits applies ALL of them, in order. Reading only the
2392    /// first is not a near-miss: DeepSeek-V4 puts a digit rule first and the
2393    /// word rule third, so one-pattern behaviour hands BPE a whole sentence
2394    /// as a single piece and the ids that come back are ones the model was
2395    /// never trained on.
2396    #[test]
2397    fn every_split_in_a_sequence_is_applied() {
2398        let pt = serde_json::json!({
2399            "type": "Sequence",
2400            "pretokenizers": [
2401                {"type": "Split", "behavior": "Isolated",
2402                 "pattern": {"Regex": r"\p{N}{1,3}"}},
2403                {"type": "Split", "behavior": "Isolated",
2404                 "pattern": {"Regex": r" ?[\p{L}]+"}},
2405                {"type": "ByteLevel", "add_prefix_space": false, "use_regex": false}
2406            ]
2407        });
2408        let mut pats = Vec::new();
2409        collect_split_patterns(&pt, &mut pats);
2410        assert_eq!(
2411            pats.len(),
2412            2,
2413            "both Split stages must be collected: {pats:?}"
2414        );
2415        assert!(pats[0].contains("p{N}"), "digit rule first");
2416        assert!(pats[1].contains("p{L}"), "word rule second");
2417
2418        // And the staged subdivision reaches the word boundaries. Building a
2419        // byte-level tokenizer over this pre_tokenizer, "ab cd" has to become
2420        // two pieces rather than one.
2421        let re: Vec<fancy_regex::Regex> = pats
2422            .iter()
2423            .map(|p| fancy_regex::Regex::new(p).unwrap())
2424            .collect();
2425        let norm = "ab cd12";
2426        let mut pieces: Vec<(usize, usize)> = vec![(0, norm.len())];
2427        for r in &re {
2428            let mut next = Vec::new();
2429            for (ps, pe) in pieces {
2430                let seg = &norm[ps..pe];
2431                let mut last = 0;
2432                for m in r.find_iter(seg).flatten() {
2433                    if m.start() > last {
2434                        next.push((ps + last, ps + m.start()));
2435                    }
2436                    if m.end() > m.start() {
2437                        next.push((ps + m.start(), ps + m.end()));
2438                    }
2439                    last = m.end();
2440                }
2441                if last < seg.len() {
2442                    next.push((ps + last, pe));
2443                }
2444            }
2445            pieces = next;
2446        }
2447        let got: Vec<&str> = pieces.iter().map(|(a, b)| &norm[*a..*b]).collect();
2448        assert_eq!(
2449            got,
2450            vec!["ab", " cd", "12"],
2451            "staged split produced {got:?}"
2452        );
2453    }
2454
2455    #[test]
2456    fn full_pipeline_merges_and_added_tokens() {
2457        let tok = Tokenizer::from_json(&mini_json()).unwrap();
2458        // "hello world" → [he,l,l,o, Ġw,o,r,l,d]
2459        let ids = tok.encode("hello world");
2460        assert_eq!(ids, vec![8, 2, 2, 3, 9, 3, 6, 2, 7]);
2461        assert_eq!(tok.decode(&ids), "hello world");
2462        // Added token splits and is skipped at decode (special).
2463        let ids2 = tok.encode("he<|eot|>he");
2464        assert_eq!(ids2, vec![8, 10, 8]);
2465        assert_eq!(tok.decode(&ids2), "hehe");
2466    }
2467
2468    /// `encode` keeps each added token's next position: the result must equal
2469    /// a fresh search of the remaining text at every match.
2470    #[test]
2471    fn added_token_scan_matches_a_fresh_search() {
2472        let mut tok = Tokenizer::from_json(&mini_json()).unwrap();
2473        // overlapping contents, longest first; "absent!" never occurs
2474        tok.added = vec![
2475            ("<|eot|>".to_string(), 10),
2476            ("absent!".to_string(), 11),
2477            ("<|".to_string(), 12),
2478            ("he".to_string(), 13),
2479        ];
2480        let fresh = |text: &str| {
2481            let (mut ids, mut rest, mut head) = (Vec::new(), text, true);
2482            while !rest.is_empty() {
2483                let mut best: Option<(usize, usize, u32)> = None;
2484                for (content, id) in &tok.added {
2485                    if let Some(pos) = rest.find(content.as_str()) {
2486                        if best.is_none_or(|(bp, bl, _)| pos < bp || (pos == bp && content.len() > bl)) {
2487                            best = Some((pos, content.len(), *id));
2488                        }
2489                    }
2490                }
2491                let Some((pos, len, id)) = best else {
2492                    tok.encode_segment_at(rest, head, &mut ids);
2493                    break;
2494                };
2495                tok.encode_segment_at(&rest[..pos], head, &mut ids);
2496                ids.push(id);
2497                rest = &rest[pos + len..];
2498                head = false;
2499            }
2500            ids
2501        };
2502        for text in [
2503            "",
2504            "he",
2505            "world",
2506            "<|",
2507            "<|eot|>",
2508            "<|eot|><|eot|>he<|",
2509            "hello <|eot|> world <| he <|eot|>he",
2510            "<|<|eot|<|eot|>hehe wor<|ld",
2511            "world he<|eot|> hello he he <|",
2512        ] {
2513            assert_eq!(tok.encode(text), fresh(text), "{text:?}");
2514        }
2515    }
2516
2517    /// LFM2/LFM3 templates open with `{{- bos_token -}}` and their tokenizers
2518    /// add no BOS themselves: the template must see the BOS text, as under
2519    /// transformers' `apply_chat_template`, and a tokenizer that also
2520    /// prepends BOS must not get two.
2521    #[test]
2522    fn chat_template_sees_bos_token_once() {
2523        let mut tok = Tokenizer::from_json(&mini_json()).unwrap();
2524        tok.bos_token_id = Some(10);
2525        tok.chat_template = Some(
2526            "{{- bos_token -}}{%- for m in messages -%}{{ m.content }}{%- endfor -%}".to_string(),
2527        );
2528        let messages = vec![("user".to_string(), "he".to_string())];
2529        assert_eq!(tok.apply_chat_template(&messages), vec![10, 8]);
2530        let json = vec![serde_json::json!({"role": "user", "content": "he"})];
2531        assert_eq!(tok.apply_chat_template_json(&json, None, None), vec![10, 8]);
2532        tok.add_bos = true;
2533        assert_eq!(tok.apply_chat_template(&messages), vec![10, 8]);
2534    }
2535
2536    #[test]
2537    fn non_ascii_is_never_silently_dropped() {
2538        let tok = Tokenizer::from_json(&mini_json()).unwrap();
2539        // A non-ASCII char is not encodable by the mini vocab (no byte tokens either):
2540        // the id list may be empty, but ASCII around it must survive.
2541        let ids = tok.encode("hello");
2542        assert!(!ids.is_empty());
2543    }
2544}
2545
2546#[cfg(test)]
2547mod generation_tag_tests {
2548    use super::strip_generation_tags;
2549
2550    /// LFM2.5's template wraps the assistant branch in `{%- generation -%}`.
2551    /// minijinja does not know the statement, the whole template failed,
2552    /// and the caller served a ChatML approximation instead — the model
2553    /// then answers a differently-shaped prompt than it was tuned on.
2554    #[test]
2555    fn a_generation_block_becomes_a_no_op_keeping_its_whitespace_control() {
2556        let tpl = "a{%- generation -%}b{%- endgeneration -%}c";
2557        let out = strip_generation_tags(tpl);
2558        assert!(!out.contains("{%- generation"));
2559        assert!(!out.contains("endgeneration"));
2560        // Both dashes survive on both tags: the trimming must not change.
2561        assert_eq!(out.matches("{%-").count(), 2);
2562        assert_eq!(out.matches("-%}").count(), 2);
2563        assert!(out.starts_with('a') && out.ends_with('c'));
2564    }
2565
2566    /// Whitespace control is per-side, and a tag without dashes must not
2567    /// grow any.
2568    #[test]
2569    fn each_side_keeps_its_own_dash() {
2570        let out = strip_generation_tags("{% generation %}x{%- endgeneration %}");
2571        assert!(out.starts_with("{% set"), "no dash added on the left");
2572        assert!(out.contains("{%- set"), "the right tag keeps its dash");
2573        assert!(!out.contains("-%}"), "no trailing dash invented");
2574    }
2575
2576    /// Templates that never use it are returned untouched, and other
2577    /// statements are never rewritten.
2578    #[test]
2579    fn everything_else_is_left_alone() {
2580        let plain = "{%- if x -%}{{ y }}{%- endif -%}";
2581        assert_eq!(strip_generation_tags(plain), plain);
2582        // The word appearing in TEXT is not a statement.
2583        let prose = "{{ 'the generation of tokens' }}";
2584        assert_eq!(strip_generation_tags(prose), prose);
2585    }
2586}
2587
2588#[cfg(test)]
2589mod ink_tests {
2590    use super::Tokenizer;
2591
2592    /// A byte-level BPE whose merges would split "abc" as "a" + "bc"; with
2593    /// `ignore_merges` the whole word is its own entry.
2594    fn tok(ignore: bool) -> Tokenizer {
2595        let json = format!(
2596            r#"{{"model": {{"type": "BPE", "ignore_merges": {ignore}, "vocab": {{"a": 0, "b": 1, "c": 2, "bc": 3, "abc": 4}}, "merges": [["b", "c"]]}},
2597               "pre_tokenizer": {{"type": "ByteLevel", "add_prefix_space": false, "use_regex": false}},
2598               "added_tokens": []}}"#
2599        );
2600        Tokenizer::from_json(&json).unwrap()
2601    }
2602
2603    #[test]
2604    fn ignore_merges_takes_a_whole_word_from_the_vocabulary() {
2605        assert_eq!(tok(false).encode("abc"), vec![0, 3]);
2606        assert_eq!(tok(true).encode("abc"), vec![4]);
2607        // a word that is not an entry still merges
2608        assert_eq!(tok(true).encode("bc"), vec![3]);
2609        assert_eq!(tok(true).encode("cbc"), vec![2, 3]);
2610    }
2611
2612    #[test]
2613    fn an_inkling_turn_decodes_as_think_and_text() {
2614        let json = r#"{"model": {"type": "BPE", "vocab": {"a": 0, "b": 1}, "merges": []},
2615               "pre_tokenizer": {"type": "ByteLevel", "add_prefix_space": false, "use_regex": false},
2616               "added_tokens": [
2617                 {"id": 2, "content": "<|message_model|>", "special": true},
2618                 {"id": 3, "content": "<|content_thinking|>", "special": true},
2619                 {"id": 4, "content": "<|content_text|>", "special": true},
2620                 {"id": 5, "content": "<|end_message|>", "special": true},
2621                 {"id": 6, "content": "<|content_invoke_tool_json|>", "special": true},
2622                 {"id": 7, "content": "<|content_model_end_sampling|>", "special": true}]}"#;
2623        let t = Tokenizer::from_json(json).unwrap();
2624        assert_eq!(t.decode(&[2, 3, 0, 5, 2, 4, 1, 5, 7]), "<think>a</think>\n\nb");
2625        assert_eq!(t.decode(&[2, 4, 1, 1, 5]), "bb");
2626        let streamed: String = [2u32, 3, 0, 5, 2, 4, 1, 5, 7].iter().map(|&i| t.decode_token(i)).collect();
2627        assert_eq!(streamed, "<think>a</think>\n\nb");
2628        // the UTF-8-safe stream `run` prints with marks the parts the same way
2629        let mut pending = Vec::new();
2630        let streamed: String = [2u32, 3, 0, 5, 2, 4, 1, 5, 7].iter().map(|&i| t.decode_token_stream(i, &mut pending)).collect();
2631        assert_eq!(streamed, "<think>a</think>\n\nb");
2632    }
2633}
2634
2635#[cfg(test)]
2636mod ink_parity {
2637    /// `CMF_TOK_PARITY=<tokenizer.json>,<text file>,<out ids file>`: the ids of the
2638    /// text, one a line, for a comparison against the reference tokenizer.
2639    #[test]
2640    #[ignore]
2641    fn dump_ids() {
2642        let Ok(spec) = std::env::var("CMF_TOK_PARITY") else { return };
2643        let mut it = spec.split(',');
2644        let (tj, txt, out) = (it.next().unwrap(), it.next().unwrap(), it.next().unwrap());
2645        let t = super::Tokenizer::from_file(tj).unwrap();
2646        let ids = t.encode(&std::fs::read_to_string(txt).unwrap());
2647        std::fs::write(out, ids.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("\n")).unwrap();
2648    }
2649}