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    fn validate_prefix_cache(&self) -> Result<()> {
181        if self.options.add_special_tokens {
182            return Err(Error::msg(
183                "HuggingFace tokenizers configured with add_special_tokens=true must remain uncached",
184            ));
185        }
186        Ok(())
187    }
188
189    /// HF honors [`TokenizerOptions::add_special_tokens`] (BOS/EOS per the
190    /// tokenizer's post-processor template).
191    fn with_options(mut self, options: TokenizerOptions) -> Self {
192        self.options = options;
193        self
194    }
195}
196
197impl From<HfTokenizer> for HuggingFaceTokenizer {
198    fn from(tokenizer: HfTokenizer) -> Self {
199        Self::from_tokenizer(tokenizer)
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    //! The existing tool-calling / reasoning parser tests inject already-
206    //! decoded text and never run `tokenizer.decode`, so they cannot
207    //! catch the class of bug where a non-special marker gets accidentally
208    //! promoted to "special" and silently disappears under
209    //! `skip_special_tokens=True`. One unit test pins both halves of the
210    //! gate (promote special:true / skip special:false) end-to-end through
211    //! the actual encode -> decode round trip — the layer above which the
212    //! parser tests cannot reach.
213    use super::*;
214    use std::fs;
215    use tempfile::TempDir;
216
217    #[test]
218    fn merge_gate_round_trips_through_decode() {
219        // Minimal WordLevel `tokenizer.json`. `<|special_kept|>` and
220        // `<|special_dropped|>` are deliberately NOT pre-declared as
221        // special in `added_tokens` here — that's exactly the shape
222        // `merge_special_tokens_from_config` is supposed to fix from
223        // tokenizer_config.json.
224        const TOKENIZER_JSON: &str = r#"{
225            "version": "1.0",
226            "truncation": null,
227            "padding": null,
228            "added_tokens": [
229                {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
230            ],
231            "normalizer": null,
232            "pre_tokenizer": null,
233            "post_processor": null,
234            "decoder": null,
235            "model": {
236                "type": "WordLevel",
237                "vocab": {"<unk>": 0, "hello": 1, "world": 2, "<|special_kept|>": 3, "<|special_dropped|>": 4},
238                "unk_token": "<unk>"
239            }
240        }"#;
241
242        // `<|special_kept|>` is `special: true` → must be promoted, and
243        // therefore stripped under skip_special_tokens=true.
244        // `<|special_dropped|>` is `special: false` → must be skipped,
245        // and therefore survive skip_special_tokens=true. The latter is
246        // the Ryan/Keiven concern: tool-call / reasoning markers are
247        // universally declared `special: false` precisely so the parser
248        // still sees them; a regression here would silently break
249        // parsing without any of the parser unit tests turning red.
250        const TOKENIZER_CONFIG_JSON: &str = r#"{
251            "added_tokens_decoder": {
252                "3": {"content": "<|special_kept|>",    "special": true,  "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
253                "4": {"content": "<|special_dropped|>", "special": false, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
254            }
255        }"#;
256
257        let dir = TempDir::new().unwrap();
258        fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
259        fs::write(
260            dir.path().join("tokenizer_config.json"),
261            TOKENIZER_CONFIG_JSON,
262        )
263        .unwrap();
264
265        let mut tokenizer = HfTokenizer::from_file(dir.path().join("tokenizer.json")).unwrap();
266        merge_special_tokens_from_config(&mut tokenizer, dir.path());
267
268        // Registry assertion: only the special:true entry was promoted.
269        let specials: Vec<String> = {
270            let mut v: Vec<String> = tokenizer
271                .get_added_tokens_decoder()
272                .values()
273                .filter(|t| t.special)
274                .map(|t| t.content.clone())
275                .collect();
276            v.sort();
277            v
278        };
279        assert_eq!(
280            specials,
281            vec!["<unk>".to_string(), "<|special_kept|>".to_string()],
282            "<|special_kept|> promoted; <|special_dropped|> stayed non-special"
283        );
284
285        // Decode round-trip assertion (the layer parser tests cannot
286        // reach): the registry mutation actually changes downstream
287        // decode behavior in the expected direction.
288        let enc_kept = tokenizer.encode("<|special_kept|>", false).unwrap();
289        let decoded_strip = tokenizer.decode(enc_kept.get_ids(), true).unwrap();
290        assert!(
291            !decoded_strip.contains("<|special_kept|>"),
292            "promoted special:true token must be stripped under skip_special_tokens=true; got {decoded_strip:?}"
293        );
294
295        let enc_drop = tokenizer.encode("<|special_dropped|>", false).unwrap();
296        let decoded_keep = tokenizer.decode(enc_drop.get_ids(), true).unwrap();
297        assert!(
298            decoded_keep.contains("<|special_dropped|>"),
299            "non-promoted special:false token must survive skip_special_tokens=true; got {decoded_keep:?}"
300        );
301    }
302
303    #[test]
304    fn add_special_tokens_flag_controls_encode() {
305        // WordLevel tokenizer with a TemplateProcessing post-processor that
306        // prepends <bos>. The post-processor only fires when encode is
307        // called with add_special_tokens=true, which is exactly the knob
308        // `TokenizerOptions`/`with_options` exposes.
309        const TOKENIZER_JSON: &str = r#"{
310            "version": "1.0",
311            "truncation": null,
312            "padding": null,
313            "added_tokens": [
314                {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
315                {"id": 3, "content": "<bos>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
316            ],
317            "normalizer": null,
318            "pre_tokenizer": null,
319            "post_processor": {
320                "type": "TemplateProcessing",
321                "single": [
322                    {"SpecialToken": {"id": "<bos>", "type_id": 0}},
323                    {"Sequence": {"id": "A", "type_id": 0}}
324                ],
325                "pair": [
326                    {"SpecialToken": {"id": "<bos>", "type_id": 0}},
327                    {"Sequence": {"id": "A", "type_id": 0}},
328                    {"Sequence": {"id": "B", "type_id": 0}}
329                ],
330                "special_tokens": {
331                    "<bos>": {"id": "<bos>", "ids": [3], "tokens": ["<bos>"]}
332                }
333            },
334            "decoder": null,
335            "model": {
336                "type": "WordLevel",
337                "vocab": {"<unk>": 0, "hello": 1, "world": 2, "<bos>": 3},
338                "unk_token": "<unk>"
339            }
340        }"#;
341
342        let dir = TempDir::new().unwrap();
343        fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
344        let path = dir.path().join("tokenizer.json");
345        let path = path.to_str().unwrap();
346
347        let ids = |enc: &Encoding| match enc {
348            Encoding::Hf(e) => e.get_ids().to_vec(),
349            _ => panic!("expected Hf encoding"),
350        };
351
352        // Default: unchanged historical behavior — no BOS.
353        let plain = HuggingFaceTokenizer::from_file(path).unwrap();
354        assert_eq!(ids(&plain.encode("hello").unwrap()), vec![1]);
355
356        let with_bos =
357            HuggingFaceTokenizer::from_file(path)
358                .unwrap()
359                .with_options(TokenizerOptions {
360                    add_special_tokens: true,
361                });
362        assert_eq!(ids(&with_bos.encode("hello").unwrap()), vec![3, 1]);
363        let batch = with_bos.encode_batch(&["hello", "world"]).unwrap();
364        assert_eq!(ids(&batch[0]), vec![3, 1]);
365        assert_eq!(ids(&batch[1]), vec![3, 2]);
366
367        // Same knob through the top-level wrapper: from_file keeps the
368        // historical default, from_file_with_options threads the flag to
369        // construction before the tokenizer goes behind the shared Arc.
370        use crate::Tokenizer as TokenizerWrapper;
371        let wrapper_plain = TokenizerWrapper::from_file(path).unwrap();
372        assert_eq!(ids(&wrapper_plain.encode("hello").unwrap()), vec![1]);
373
374        let wrapper_bos = TokenizerWrapper::from_file_with_options(
375            path,
376            TokenizerOptions {
377                add_special_tokens: true,
378            },
379        )
380        .unwrap();
381        assert_eq!(ids(&wrapper_bos.encode("hello").unwrap()), vec![3, 1]);
382    }
383}