Skip to main content

dynamo_tokenizers/
hf.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::path::Path;
5
6use tokenizers::tokenizer::{AddedToken, Tokenizer as HfTokenizer};
7
8use super::{
9    Encoding, Error, Result, TokenIdType, TokenizerOptions,
10    traits::{DecodeResult, Decoder, Encoder, Tokenizer},
11};
12
13pub struct HuggingFaceTokenizer {
14    tokenizer: HfTokenizer,
15    /// Construction-time options; see [`TokenizerOptions`]. Defaults preserve
16    /// the historical behavior (e.g. `add_special_tokens: false`). Set via
17    /// [`Tokenizer::with_options`].
18    options: TokenizerOptions,
19}
20
21impl HuggingFaceTokenizer {
22    /// Load from `tokenizer.json`, merging in special tokens declared only in
23    /// a sibling `tokenizer_config.json`'s `added_tokens_decoder`. Without
24    /// this, some releases (Qwen2-VL-2B's `<|image_pad|>`) BPE-shatter and
25    /// silently break MM-aware routing. The merge is idempotent.
26    pub fn from_file(model_name: &str) -> Result<Self> {
27        let mut tokenizer = HfTokenizer::from_file(model_name)
28            .map_err(|err| Error::msg(format!("Error loading tokenizer: {}", err)))?;
29
30        if let Some(parent) = Path::new(model_name).parent() {
31            merge_special_tokens_from_config(&mut tokenizer, parent);
32        }
33
34        Ok(Self::from_tokenizer(tokenizer))
35    }
36
37    pub fn from_tokenizer(tokenizer: HfTokenizer) -> Self {
38        HuggingFaceTokenizer {
39            tokenizer,
40            options: TokenizerOptions::default(),
41        }
42    }
43
44    /// Wrap an already-loaded `HfTokenizer` and merge in the sibling
45    /// `tokenizer_config.json` special tokens; see [`Self::from_file`].
46    pub fn from_tokenizer_with_model_dir(tokenizer: HfTokenizer, model_dir: &Path) -> Self {
47        let mut tokenizer = tokenizer;
48        merge_special_tokens_from_config(&mut tokenizer, model_dir);
49        Self::from_tokenizer(tokenizer)
50    }
51}
52
53/// Promote `tokenizer_config.json`'s `special: true` `added_tokens_decoder`
54/// entries onto `tokenizer`. Missing-file / parse errors are swallowed since
55/// the file is optional. See [`HuggingFaceTokenizer::from_file`].
56///
57/// `pub` so downstream crates (e.g. `dynamo-llm`'s model_card) can apply
58/// the same promotion before extracting the special-token boundary list
59/// for the L1 prefix cache — otherwise the cache and the wrapped
60/// tokenizer would disagree on which strings are atomic specials.
61pub fn merge_special_tokens_from_config(tokenizer: &mut HfTokenizer, model_dir: &Path) {
62    let cfg_path = model_dir.join("tokenizer_config.json");
63    let Ok(raw) = std::fs::read_to_string(&cfg_path) else {
64        return;
65    };
66    let cfg: serde_json::Value = match serde_json::from_str(&raw) {
67        Ok(v) => v,
68        Err(e) => {
69            tracing::debug!(
70                target: "tokenizer",
71                path = %cfg_path.display(),
72                error = %e,
73                "tokenizer_config.json parse failed; skipping special-token merge"
74            );
75            return;
76        }
77    };
78    let Some(decoder) = cfg.get("added_tokens_decoder").and_then(|v| v.as_object()) else {
79        return;
80    };
81
82    let mut to_add: Vec<AddedToken> = Vec::new();
83    for (_id, spec) in decoder {
84        let obj = match spec.as_object() {
85            Some(o) => o,
86            None => continue,
87        };
88        // The id is informational — `add_special_tokens` reuses the existing
89        // vocab id via `Model::token_to_id` on the content string.
90        if obj.get("special").and_then(|v| v.as_bool()) != Some(true) {
91            continue;
92        }
93        let Some(content) = obj.get("content").and_then(|v| v.as_str()) else {
94            continue;
95        };
96        if content.is_empty() {
97            continue;
98        }
99        let single_word = obj
100            .get("single_word")
101            .and_then(|v| v.as_bool())
102            .unwrap_or(false);
103        let lstrip = obj.get("lstrip").and_then(|v| v.as_bool()).unwrap_or(false);
104        let rstrip = obj.get("rstrip").and_then(|v| v.as_bool()).unwrap_or(false);
105        let normalized = obj
106            .get("normalized")
107            .and_then(|v| v.as_bool())
108            .unwrap_or(false);
109        let token = AddedToken::from(content.to_string(), true)
110            .single_word(single_word)
111            .lstrip(lstrip)
112            .rstrip(rstrip)
113            .normalized(normalized);
114        to_add.push(token);
115    }
116
117    if to_add.is_empty() {
118        return;
119    }
120    // Dedups against existing added-tokens, so this is a no-op when
121    // tokenizer.json already had them. Return value = net-new count.
122    let added = tokenizer.add_special_tokens(&to_add);
123    if added > 0 {
124        // Warn (not debug) when the merge actually promotes anything —
125        // intentionally loud so accidental promotion of a previously-
126        // non-special token shows up immediately in worker logs. Lists
127        // the literal token strings so debugging doesn't require a
128        // second pass through `added_tokens_decoder`.
129        let promoted: Vec<&str> = to_add.iter().map(|t| t.content.as_str()).collect();
130        tracing::warn!(
131            target: "tokenizer",
132            path = %cfg_path.display(),
133            added,
134            candidates = to_add.len(),
135            promoted = ?promoted,
136            "merged additional special tokens from tokenizer_config.json"
137        );
138    }
139}
140
141impl Encoder for HuggingFaceTokenizer {
142    fn encode(&self, input: &str) -> Result<Encoding> {
143        // This self.tokenizer is the library
144        let encoding = self
145            .tokenizer
146            .encode(input, self.options.add_special_tokens)
147            .map_err(|err| Error::msg(format!("Error tokenizing input: {err}")))?;
148
149        Ok(Encoding::Hf(Box::new(encoding)))
150    }
151
152    fn encode_batch(&self, inputs: &[&str]) -> Result<Vec<Encoding>> {
153        let hf_encodings = self
154            .tokenizer
155            .encode_batch(inputs.to_vec(), self.options.add_special_tokens)
156            .map_err(|err| Error::msg(format!("Error batch tokenizing input: {err}")))?;
157
158        let encodings = hf_encodings
159            .into_iter()
160            .map(|enc| Encoding::Hf(Box::new(enc)))
161            .collect();
162
163        Ok(encodings)
164    }
165}
166
167impl Decoder for HuggingFaceTokenizer {
168    fn decode(&self, token_ids: &[TokenIdType], skip_special_tokens: bool) -> Result<DecodeResult> {
169        // This calls into the library
170        let text = self
171            .tokenizer
172            .decode(token_ids, skip_special_tokens)
173            .map_err(|err| Error::msg(format!("Error de-tokenizing input: {err}")))?;
174
175        Ok(text.into())
176    }
177}
178
179impl Tokenizer for HuggingFaceTokenizer {
180    /// HF honors [`TokenizerOptions::add_special_tokens`] (BOS/EOS per the
181    /// tokenizer's post-processor template).
182    fn with_options(mut self, options: TokenizerOptions) -> Self {
183        self.options = options;
184        self
185    }
186}
187
188impl From<HfTokenizer> for HuggingFaceTokenizer {
189    fn from(tokenizer: HfTokenizer) -> Self {
190        Self::from_tokenizer(tokenizer)
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    //! The existing tool-calling / reasoning parser tests inject already-
197    //! decoded text and never run `tokenizer.decode`, so they cannot
198    //! catch the class of bug where a non-special marker gets accidentally
199    //! promoted to "special" and silently disappears under
200    //! `skip_special_tokens=True`. One unit test pins both halves of the
201    //! gate (promote special:true / skip special:false) end-to-end through
202    //! the actual encode -> decode round trip — the layer above which the
203    //! parser tests cannot reach.
204    use super::*;
205    use std::fs;
206    use tempfile::TempDir;
207
208    #[test]
209    fn merge_gate_round_trips_through_decode() {
210        // Minimal WordLevel `tokenizer.json`. `<|special_kept|>` and
211        // `<|special_dropped|>` are deliberately NOT pre-declared as
212        // special in `added_tokens` here — that's exactly the shape
213        // `merge_special_tokens_from_config` is supposed to fix from
214        // tokenizer_config.json.
215        const TOKENIZER_JSON: &str = r#"{
216            "version": "1.0",
217            "truncation": null,
218            "padding": null,
219            "added_tokens": [
220                {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
221            ],
222            "normalizer": null,
223            "pre_tokenizer": null,
224            "post_processor": null,
225            "decoder": null,
226            "model": {
227                "type": "WordLevel",
228                "vocab": {"<unk>": 0, "hello": 1, "world": 2, "<|special_kept|>": 3, "<|special_dropped|>": 4},
229                "unk_token": "<unk>"
230            }
231        }"#;
232
233        // `<|special_kept|>` is `special: true` → must be promoted, and
234        // therefore stripped under skip_special_tokens=true.
235        // `<|special_dropped|>` is `special: false` → must be skipped,
236        // and therefore survive skip_special_tokens=true. The latter is
237        // the Ryan/Keiven concern: tool-call / reasoning markers are
238        // universally declared `special: false` precisely so the parser
239        // still sees them; a regression here would silently break
240        // parsing without any of the parser unit tests turning red.
241        const TOKENIZER_CONFIG_JSON: &str = r#"{
242            "added_tokens_decoder": {
243                "3": {"content": "<|special_kept|>",    "special": true,  "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
244                "4": {"content": "<|special_dropped|>", "special": false, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
245            }
246        }"#;
247
248        let dir = TempDir::new().unwrap();
249        fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
250        fs::write(
251            dir.path().join("tokenizer_config.json"),
252            TOKENIZER_CONFIG_JSON,
253        )
254        .unwrap();
255
256        let mut tokenizer = HfTokenizer::from_file(dir.path().join("tokenizer.json")).unwrap();
257        merge_special_tokens_from_config(&mut tokenizer, dir.path());
258
259        // Registry assertion: only the special:true entry was promoted.
260        let specials: Vec<String> = {
261            let mut v: Vec<String> = tokenizer
262                .get_added_tokens_decoder()
263                .values()
264                .filter(|t| t.special)
265                .map(|t| t.content.clone())
266                .collect();
267            v.sort();
268            v
269        };
270        assert_eq!(
271            specials,
272            vec!["<unk>".to_string(), "<|special_kept|>".to_string()],
273            "<|special_kept|> promoted; <|special_dropped|> stayed non-special"
274        );
275
276        // Decode round-trip assertion (the layer parser tests cannot
277        // reach): the registry mutation actually changes downstream
278        // decode behavior in the expected direction.
279        let enc_kept = tokenizer.encode("<|special_kept|>", false).unwrap();
280        let decoded_strip = tokenizer.decode(enc_kept.get_ids(), true).unwrap();
281        assert!(
282            !decoded_strip.contains("<|special_kept|>"),
283            "promoted special:true token must be stripped under skip_special_tokens=true; got {decoded_strip:?}"
284        );
285
286        let enc_drop = tokenizer.encode("<|special_dropped|>", false).unwrap();
287        let decoded_keep = tokenizer.decode(enc_drop.get_ids(), true).unwrap();
288        assert!(
289            decoded_keep.contains("<|special_dropped|>"),
290            "non-promoted special:false token must survive skip_special_tokens=true; got {decoded_keep:?}"
291        );
292    }
293
294    #[test]
295    fn add_special_tokens_flag_controls_encode() {
296        // WordLevel tokenizer with a TemplateProcessing post-processor that
297        // prepends <bos>. The post-processor only fires when encode is
298        // called with add_special_tokens=true, which is exactly the knob
299        // `TokenizerOptions`/`with_options` exposes.
300        const TOKENIZER_JSON: &str = r#"{
301            "version": "1.0",
302            "truncation": null,
303            "padding": null,
304            "added_tokens": [
305                {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
306                {"id": 3, "content": "<bos>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
307            ],
308            "normalizer": null,
309            "pre_tokenizer": null,
310            "post_processor": {
311                "type": "TemplateProcessing",
312                "single": [
313                    {"SpecialToken": {"id": "<bos>", "type_id": 0}},
314                    {"Sequence": {"id": "A", "type_id": 0}}
315                ],
316                "pair": [
317                    {"SpecialToken": {"id": "<bos>", "type_id": 0}},
318                    {"Sequence": {"id": "A", "type_id": 0}},
319                    {"Sequence": {"id": "B", "type_id": 0}}
320                ],
321                "special_tokens": {
322                    "<bos>": {"id": "<bos>", "ids": [3], "tokens": ["<bos>"]}
323                }
324            },
325            "decoder": null,
326            "model": {
327                "type": "WordLevel",
328                "vocab": {"<unk>": 0, "hello": 1, "world": 2, "<bos>": 3},
329                "unk_token": "<unk>"
330            }
331        }"#;
332
333        let dir = TempDir::new().unwrap();
334        fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
335        let path = dir.path().join("tokenizer.json");
336        let path = path.to_str().unwrap();
337
338        let ids = |enc: &Encoding| match enc {
339            Encoding::Hf(e) => e.get_ids().to_vec(),
340            _ => panic!("expected Hf encoding"),
341        };
342
343        // Default: unchanged historical behavior — no BOS.
344        let plain = HuggingFaceTokenizer::from_file(path).unwrap();
345        assert_eq!(ids(&plain.encode("hello").unwrap()), vec![1]);
346
347        let with_bos =
348            HuggingFaceTokenizer::from_file(path)
349                .unwrap()
350                .with_options(TokenizerOptions {
351                    add_special_tokens: true,
352                });
353        assert_eq!(ids(&with_bos.encode("hello").unwrap()), vec![3, 1]);
354        let batch = with_bos.encode_batch(&["hello", "world"]).unwrap();
355        assert_eq!(ids(&batch[0]), vec![3, 1]);
356        assert_eq!(ids(&batch[1]), vec![3, 2]);
357
358        // Same knob through the top-level wrapper: from_file keeps the
359        // historical default, from_file_with_options threads the flag to
360        // construction before the tokenizer goes behind the shared Arc.
361        use crate::Tokenizer as TokenizerWrapper;
362        let wrapper_plain = TokenizerWrapper::from_file(path).unwrap();
363        assert_eq!(ids(&wrapper_plain.encode("hello").unwrap()), vec![1]);
364
365        let wrapper_bos = TokenizerWrapper::from_file_with_options(
366            path,
367            TokenizerOptions {
368                add_special_tokens: true,
369            },
370        )
371        .unwrap();
372        assert_eq!(ids(&wrapper_bos.encode("hello").unwrap()), vec![3, 1]);
373    }
374}