1use 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 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
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 use super::*;
214 use std::fs;
215 use tempfile::TempDir;
216
217 #[test]
218 fn merge_gate_round_trips_through_decode() {
219 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 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 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 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 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 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 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}