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 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 use super::*;
205 use std::fs;
206 use tempfile::TempDir;
207
208 #[test]
209 fn merge_gate_round_trips_through_decode() {
210 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 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 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 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 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 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 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}