1use std::path::Path;
5
6use tokenizers::tokenizer::{AddedToken, PostProcessor as _, 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 options: TokenizerOptions,
19}
20
21impl HuggingFaceTokenizer {
22 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 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
53pub 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 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 let added = tokenizer.add_special_tokens(&to_add);
123 if added > 0 {
124 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 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 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 fn with_options(mut self, options: TokenizerOptions) -> Self {
192 self.options = options;
193 self
194 }
195
196 fn vocab_size(&self) -> Option<usize> {
197 Some(self.tokenizer.get_vocab_size(true))
198 }
199
200 fn token_to_id(&self, token: &str) -> Result<Option<TokenIdType>> {
201 Ok(self.tokenizer.token_to_id(token))
202 }
203
204 fn special_token_ids(&self) -> Result<Vec<TokenIdType>> {
205 let mut ids: Vec<TokenIdType> = self
206 .tokenizer
207 .get_added_tokens_decoder()
208 .into_iter()
209 .filter_map(|(id, token)| token.special.then_some(id))
210 .collect();
211 ids.sort_unstable();
212 Ok(ids)
213 }
214
215 fn num_special_tokens_added(&self) -> Result<usize> {
216 Ok(self
217 .tokenizer
218 .get_post_processor()
219 .map_or(0, |processor| processor.added_tokens(false)))
220 }
221}
222
223impl From<HfTokenizer> for HuggingFaceTokenizer {
224 fn from(tokenizer: HfTokenizer) -> Self {
225 Self::from_tokenizer(tokenizer)
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
240 use std::fs;
241 use tempfile::TempDir;
242
243 #[test]
244 fn merge_gate_round_trips_through_decode() {
245 const TOKENIZER_JSON: &str = r#"{
251 "version": "1.0",
252 "truncation": null,
253 "padding": null,
254 "added_tokens": [
255 {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
256 ],
257 "normalizer": null,
258 "pre_tokenizer": null,
259 "post_processor": null,
260 "decoder": null,
261 "model": {
262 "type": "WordLevel",
263 "vocab": {"<unk>": 0, "hello": 1, "world": 2, "<|special_kept|>": 3, "<|special_dropped|>": 4},
264 "unk_token": "<unk>"
265 }
266 }"#;
267
268 const TOKENIZER_CONFIG_JSON: &str = r#"{
277 "added_tokens_decoder": {
278 "3": {"content": "<|special_kept|>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
279 "4": {"content": "<|special_dropped|>", "special": false, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
280 }
281 }"#;
282
283 let dir = TempDir::new().unwrap();
284 fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
285 fs::write(
286 dir.path().join("tokenizer_config.json"),
287 TOKENIZER_CONFIG_JSON,
288 )
289 .unwrap();
290
291 let mut tokenizer = HfTokenizer::from_file(dir.path().join("tokenizer.json")).unwrap();
292 merge_special_tokens_from_config(&mut tokenizer, dir.path());
293
294 let specials: Vec<String> = {
296 let mut v: Vec<String> = tokenizer
297 .get_added_tokens_decoder()
298 .values()
299 .filter(|t| t.special)
300 .map(|t| t.content.clone())
301 .collect();
302 v.sort();
303 v
304 };
305 assert_eq!(
306 specials,
307 vec!["<unk>".to_string(), "<|special_kept|>".to_string()],
308 "<|special_kept|> promoted; <|special_dropped|> stayed non-special"
309 );
310
311 let enc_kept = tokenizer.encode("<|special_kept|>", false).unwrap();
315 let decoded_strip = tokenizer.decode(enc_kept.get_ids(), true).unwrap();
316 assert!(
317 !decoded_strip.contains("<|special_kept|>"),
318 "promoted special:true token must be stripped under skip_special_tokens=true; got {decoded_strip:?}"
319 );
320
321 let enc_drop = tokenizer.encode("<|special_dropped|>", false).unwrap();
322 let decoded_keep = tokenizer.decode(enc_drop.get_ids(), true).unwrap();
323 assert!(
324 decoded_keep.contains("<|special_dropped|>"),
325 "non-promoted special:false token must survive skip_special_tokens=true; got {decoded_keep:?}"
326 );
327 }
328
329 #[test]
330 fn add_special_tokens_flag_controls_encode() {
331 const TOKENIZER_JSON: &str = r#"{
336 "version": "1.0",
337 "truncation": null,
338 "padding": null,
339 "added_tokens": [
340 {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
341 {"id": 3, "content": "<bos>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
342 ],
343 "normalizer": null,
344 "pre_tokenizer": null,
345 "post_processor": {
346 "type": "TemplateProcessing",
347 "single": [
348 {"SpecialToken": {"id": "<bos>", "type_id": 0}},
349 {"Sequence": {"id": "A", "type_id": 0}}
350 ],
351 "pair": [
352 {"SpecialToken": {"id": "<bos>", "type_id": 0}},
353 {"Sequence": {"id": "A", "type_id": 0}},
354 {"Sequence": {"id": "B", "type_id": 0}}
355 ],
356 "special_tokens": {
357 "<bos>": {"id": "<bos>", "ids": [3], "tokens": ["<bos>"]}
358 }
359 },
360 "decoder": null,
361 "model": {
362 "type": "WordLevel",
363 "vocab": {"<unk>": 0, "hello": 1, "world": 2, "<bos>": 3},
364 "unk_token": "<unk>"
365 }
366 }"#;
367
368 let dir = TempDir::new().unwrap();
369 fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
370 let path = dir.path().join("tokenizer.json");
371 let path = path.to_str().unwrap();
372
373 let ids = |enc: &Encoding| match enc {
374 Encoding::Hf(e) => e.get_ids().to_vec(),
375 _ => panic!("expected Hf encoding"),
376 };
377
378 let plain = HuggingFaceTokenizer::from_file(path).unwrap();
380 assert_eq!(ids(&plain.encode("hello").unwrap()), vec![1]);
381
382 let with_bos =
383 HuggingFaceTokenizer::from_file(path)
384 .unwrap()
385 .with_options(TokenizerOptions {
386 add_special_tokens: true,
387 });
388 assert_eq!(ids(&with_bos.encode("hello").unwrap()), vec![3, 1]);
389 let batch = with_bos.encode_batch(&["hello", "world"]).unwrap();
390 assert_eq!(ids(&batch[0]), vec![3, 1]);
391 assert_eq!(ids(&batch[1]), vec![3, 2]);
392
393 use crate::Tokenizer as TokenizerWrapper;
397 let wrapper_plain = TokenizerWrapper::from_file(path).unwrap();
398 assert_eq!(ids(&wrapper_plain.encode("hello").unwrap()), vec![1]);
399
400 let wrapper_bos = TokenizerWrapper::from_file_with_options(
401 path,
402 TokenizerOptions {
403 add_special_tokens: true,
404 },
405 )
406 .unwrap();
407 assert_eq!(ids(&wrapper_bos.encode("hello").unwrap()), vec![3, 1]);
408 }
409
410 #[test]
411 fn vocab_introspection_accessors() {
412 const TOKENIZER_JSON: &str = r#"{
413 "version": "1.0",
414 "truncation": null,
415 "padding": null,
416 "added_tokens": [
417 {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
418 ],
419 "normalizer": null,
420 "pre_tokenizer": null,
421 "post_processor": null,
422 "decoder": null,
423 "model": {
424 "type": "WordLevel",
425 "vocab": {"<unk>": 0, "hello": 1, "world": 2},
426 "unk_token": "<unk>"
427 }
428 }"#;
429
430 let dir = TempDir::new().unwrap();
431 fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
432 let path = dir.path().join("tokenizer.json");
433
434 let tokenizer = HuggingFaceTokenizer::from_file(path.to_str().unwrap()).unwrap();
435 assert_eq!(tokenizer.vocab_size(), Some(3));
436 assert_eq!(tokenizer.token_to_id("hello").unwrap(), Some(1));
437 assert_eq!(tokenizer.special_token_ids().unwrap(), vec![0]);
438 assert_eq!(tokenizer.num_special_tokens_added().unwrap(), 0);
439 }
440
441 #[test]
442 fn num_special_tokens_added_reflects_post_processor_additions() {
443 const TOKENIZER_JSON: &str = r#"{
444 "version": "1.0",
445 "truncation": null,
446 "padding": null,
447 "added_tokens": [
448 {"id": 0, "content": "<unk>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false},
449 {"id": 3, "content": "<bos>", "special": true, "single_word": false, "lstrip": false, "rstrip": false, "normalized": false}
450 ],
451 "normalizer": null,
452 "pre_tokenizer": null,
453 "post_processor": {
454 "type": "TemplateProcessing",
455 "single": [
456 {"SpecialToken": {"id": "<bos>", "type_id": 0}},
457 {"Sequence": {"id": "A", "type_id": 0}}
458 ],
459 "pair": [
460 {"SpecialToken": {"id": "<bos>", "type_id": 0}},
461 {"Sequence": {"id": "A", "type_id": 0}},
462 {"Sequence": {"id": "B", "type_id": 0}}
463 ],
464 "special_tokens": {
465 "<bos>": {"id": "<bos>", "ids": [3], "tokens": ["<bos>"]}
466 }
467 },
468 "decoder": null,
469 "model": {
470 "type": "WordLevel",
471 "vocab": {"<unk>": 0, "hello": 1, "world": 2, "<bos>": 3},
472 "unk_token": "<unk>"
473 }
474 }"#;
475
476 let dir = TempDir::new().unwrap();
477 fs::write(dir.path().join("tokenizer.json"), TOKENIZER_JSON).unwrap();
478 let path = dir.path().join("tokenizer.json");
479
480 let tokenizer = HuggingFaceTokenizer::from_file(path.to_str().unwrap()).unwrap();
481 assert_eq!(tokenizer.num_special_tokens_added().unwrap(), 1);
482 }
483}