1pub mod chat;
11mod json;
12mod unicode;
13mod unicode_data;
14
15pub use chat::apply_chat_template_str;
16
17use memra_gguf::{GgufFile, MetaValue};
18use std::cmp::Ordering;
19use std::collections::{BinaryHeap, HashMap};
20
21const TT_UNKNOWN: i64 = 2;
23const TT_CONTROL: i64 = 3;
24const TT_USER_DEFINED: i64 = 4;
25const TT_BYTE: i64 = 6;
26const QWEN35_PRETOKENIZE_REGEX: &str = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+";
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29enum TokAttr {
30 Normal,
31 Unknown,
32 Control,
33 UserDefined,
34 Byte,
35 Other,
36}
37
38impl TokAttr {
39 fn from_toktype(t: i64) -> Self {
40 match t {
41 TT_UNKNOWN => TokAttr::Unknown,
42 TT_CONTROL => TokAttr::Control,
43 TT_USER_DEFINED => TokAttr::UserDefined,
44 TT_BYTE => TokAttr::Byte,
45 1 => TokAttr::Normal,
46 _ => TokAttr::Other,
47 }
48 }
49 fn is_special(self) -> bool {
52 matches!(
53 self,
54 TokAttr::Control | TokAttr::UserDefined | TokAttr::Unknown
55 )
56 }
57}
58
59pub struct Tokenizer {
60 id_to_token: Vec<String>,
62 token_to_id: HashMap<String, u32>,
64 attrs: Vec<TokAttr>,
66 bpe_ranks: HashMap<(String, String), i32>,
68 special_tokens: Vec<u32>,
70 eos_id: u32,
71 bos_id: Option<u32>,
72 add_bos: bool,
73 pre: String,
74 chat_template: Option<String>,
75 spm_style: bool,
77}
78
79#[derive(Clone, Eq, PartialEq)]
84struct Bigram {
85 left: i32,
86 right: i32,
87 rank: i32,
88 text: String,
89}
90
91impl Ord for Bigram {
92 fn cmp(&self, other: &Self) -> Ordering {
93 match other.rank.cmp(&self.rank) {
96 Ordering::Equal => other.left.cmp(&self.left),
97 o => o,
98 }
99 }
100}
101impl PartialOrd for Bigram {
102 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
103 Some(self.cmp(other))
104 }
105}
106
107struct Symbol {
109 text: String,
110 prev: i32,
111 next: i32,
112 n: usize, }
114
115impl Tokenizer {
116 pub fn from_gguf(g: &GgufFile) -> Result<Self, String> {
118 let model = g
119 .metadata
120 .get("tokenizer.ggml.model")
121 .and_then(|v| v.as_str())
122 .ok_or("missing tokenizer.ggml.model")?;
123 if model != "gpt2" && model != "gemma4" {
124 return Err(format!(
125 "unsupported tokenizer model '{model}' (only gpt2/gemma4)"
126 ));
127 }
128 let spm_style = model == "gemma4";
132 let pre = g
133 .metadata
134 .get("tokenizer.ggml.pre")
135 .and_then(|v| v.as_str())
136 .unwrap_or(if spm_style { "gemma4" } else { "default" })
137 .to_string();
138
139 let tokens = match g.metadata.get("tokenizer.ggml.tokens") {
141 Some(MetaValue::Array(a)) => a,
142 _ => return Err("missing tokenizer.ggml.tokens array".into()),
143 };
144 let n = tokens.len();
145 let mut id_to_token = Vec::with_capacity(n);
146 let mut token_to_id = HashMap::with_capacity(n);
147 for (i, t) in tokens.iter().enumerate() {
148 let s = t.as_str().ok_or("non-string in tokens[]")?.to_string();
149 token_to_id.entry(s.clone()).or_insert(i as u32);
151 id_to_token.push(s);
152 }
153
154 let mut attrs = vec![TokAttr::Normal; n];
156 if let Some(MetaValue::Array(a)) = g.metadata.get("tokenizer.ggml.token_type") {
157 for (i, v) in a.iter().enumerate().take(n) {
158 if let Some(t) = v.as_u64() {
159 attrs[i] = TokAttr::from_toktype(t as i64);
160 } else if let MetaValue::I32(t) = v {
161 attrs[i] = TokAttr::from_toktype(*t as i64);
162 }
163 }
164 }
165
166 let mut bpe_ranks = HashMap::new();
168 if let Some(MetaValue::Array(a)) = g.metadata.get("tokenizer.ggml.merges") {
169 for (i, v) in a.iter().enumerate() {
170 let word = v.as_str().ok_or("non-string in merges[]")?;
171 let bytes = word.as_bytes();
175 if let Some(pos) = bytes.iter().skip(1).position(|&b| b == b' ').map(|p| p + 1) {
176 let first = word[..pos].to_string();
177 let second = word[pos + 1..].to_string();
178 bpe_ranks.insert((first, second), i as i32);
179 }
180 }
181 } else {
182 return Err("missing tokenizer.ggml.merges array".into());
183 }
184
185 let mut special_tokens: Vec<u32> = (0..n as u32)
187 .filter(|&id| attrs[id as usize].is_special())
188 .collect();
189 special_tokens.sort_by(|&a, &b| {
190 id_to_token[b as usize]
191 .len()
192 .cmp(&id_to_token[a as usize].len())
193 });
194
195 let eos_id = g
196 .metadata
197 .get("tokenizer.ggml.eos_token_id")
198 .and_then(|v| v.as_u64())
199 .map(|v| v as u32)
200 .ok_or("missing tokenizer.ggml.eos_token_id")?;
201 let bos_id = g
202 .metadata
203 .get("tokenizer.ggml.bos_token_id")
204 .and_then(|v| v.as_u64())
205 .map(|v| v as u32);
206 let add_bos = g
207 .metadata
208 .get("tokenizer.ggml.add_bos_token")
209 .and_then(|v| match v {
210 MetaValue::Bool(b) => Some(*b),
211 _ => v.as_u64().map(|x| x != 0),
212 })
213 .unwrap_or(false);
214 let add_bos = add_bos || spm_style;
215
216 let chat_template = g
217 .metadata
218 .get("tokenizer.chat_template")
219 .and_then(|v| v.as_str())
220 .map(|s| s.to_string());
221
222 Ok(Tokenizer {
223 id_to_token,
224 token_to_id,
225 attrs,
226 bpe_ranks,
227 special_tokens,
228 eos_id,
229 bos_id,
230 add_bos,
231 pre,
232 chat_template,
233 spm_style,
234 })
235 }
236
237 pub fn from_hf_dir(dir: &std::path::Path) -> Result<Self, String> {
254 let tj_path = dir.join("tokenizer.json");
255 let text = std::fs::read_to_string(&tj_path)
256 .map_err(|e| format!("read {}: {e}", tj_path.display()))?;
257 let tj = json::parse(&text).map_err(|e| format!("{}: {e}", tj_path.display()))?;
258
259 let model = tj.get("model").ok_or("tokenizer.json: missing model")?;
260 if let Some(t) = model.get("type").and_then(|v| v.as_str()) {
261 if t != "BPE" {
262 return Err(format!(
263 "unsupported tokenizer.json model type '{t}' (only BPE)"
264 ));
265 }
266 }
267 let pre_tok = tj
269 .get("pre_tokenizer")
270 .ok_or("tokenizer.json: missing pre_tokenizer")?;
271 if !pre_tokenizer_is_byte_level(pre_tok) {
272 return Err(
273 "tokenizer.json: pre_tokenizer is not ByteLevel — only byte-level \
274 BPE is supported"
275 .into(),
276 );
277 }
278
279 let vocab = model
281 .get("vocab")
282 .and_then(|v| v.as_obj())
283 .ok_or("tokenizer.json: missing model.vocab")?;
284 let empty: Vec<json::Value> = Vec::new();
285 let added = tj
286 .get("added_tokens")
287 .and_then(|v| v.as_arr())
288 .unwrap_or(&empty);
289 let mut max_id = 0u32;
290 for v in vocab.values() {
291 let id =
292 v.as_u64()
293 .ok_or("tokenizer.json: non-integer id in model.vocab")? as u32;
294 max_id = max_id.max(id);
295 }
296 for a in added {
297 if let Some(id) = a.get("id").and_then(|v| v.as_u64()) {
298 max_id = max_id.max(id as u32);
299 }
300 }
301 let n = max_id as usize + 1;
302 let mut id_to_token = vec![String::new(); n];
303 let mut token_to_id: HashMap<String, u32> = HashMap::with_capacity(n);
304 let mut attrs = vec![TokAttr::Normal; n];
305 for (tok, v) in vocab {
306 let id = v.as_u64().unwrap() as u32;
307 id_to_token[id as usize] = tok.clone();
308 token_to_id.entry(tok.clone()).or_insert(id);
309 }
310 for a in added {
313 let id =
314 a.get("id")
315 .and_then(|v| v.as_u64())
316 .ok_or("tokenizer.json: added_tokens entry missing id")? as u32;
317 let content = a
318 .get("content")
319 .and_then(|v| v.as_str())
320 .ok_or("tokenizer.json: added_tokens entry missing content")?;
321 if id_to_token[id as usize].is_empty() {
322 id_to_token[id as usize] = content.to_string();
323 }
324 token_to_id.entry(content.to_string()).or_insert(id);
325 if a.get("special").and_then(|v| v.as_bool()).unwrap_or(false) {
326 attrs[id as usize] = TokAttr::Control;
327 } else {
328 attrs[id as usize] = TokAttr::UserDefined;
334 }
335 }
336
337 let merges = model
339 .get("merges")
340 .and_then(|v| v.as_arr())
341 .ok_or("tokenizer.json: missing model.merges")?;
342 let mut bpe_ranks = HashMap::with_capacity(merges.len());
343 for (i, m) in merges.iter().enumerate() {
344 let (first, second) = match m {
345 json::Value::Str(s) => {
346 let bytes = s.as_bytes();
349 let pos = bytes
350 .iter()
351 .skip(1)
352 .position(|&b| b == b' ')
353 .map(|p| p + 1)
354 .ok_or_else(|| format!("tokenizer.json: merges[{i}] has no space"))?;
355 (s[..pos].to_string(), s[pos + 1..].to_string())
356 }
357 json::Value::Arr(a) if a.len() == 2 => {
358 let f = a[0]
359 .as_str()
360 .ok_or_else(|| format!("tokenizer.json: merges[{i}] non-string pair"))?;
361 let s2 = a[1]
362 .as_str()
363 .ok_or_else(|| format!("tokenizer.json: merges[{i}] non-string pair"))?;
364 (f.to_string(), s2.to_string())
365 }
366 _ => {
367 return Err(format!(
368 "tokenizer.json: merges[{i}] is neither \"a b\" string nor [a, b] pair"
369 ));
370 }
371 };
372 bpe_ranks.insert((first, second), i as i32);
373 }
374
375 let mut special_tokens: Vec<u32> = (0..n as u32)
377 .filter(|&id| attrs[id as usize].is_special())
378 .collect();
379 special_tokens.sort_by(|&a, &b| {
380 id_to_token[b as usize]
381 .len()
382 .cmp(&id_to_token[a as usize].len())
383 });
384
385 let tc = std::fs::read_to_string(dir.join("tokenizer_config.json"))
387 .ok()
388 .and_then(|t| json::parse(&t).ok());
389 let gc = std::fs::read_to_string(dir.join("generation_config.json"))
390 .ok()
391 .and_then(|t| json::parse(&t).ok());
392
393 let tok_content = |v: &json::Value| -> Option<String> {
395 v.as_str().map(|s| s.to_string()).or_else(|| {
396 v.get("content")
397 .and_then(|c| c.as_str())
398 .map(|s| s.to_string())
399 })
400 };
401 let eos_from_cfg = tc
402 .as_ref()
403 .and_then(|c| c.get("eos_token"))
404 .and_then(&tok_content)
405 .and_then(|s| token_to_id.get(&s).copied());
406 let eos_from_gen = gc
408 .as_ref()
409 .and_then(|c| c.get("eos_token_id"))
410 .and_then(|v| match v {
411 json::Value::Num(_) => v.as_u64(),
412 json::Value::Arr(a) => a.first().and_then(|x| x.as_u64()),
413 _ => None,
414 })
415 .map(|v| v as u32);
416 let eos_id = eos_from_cfg.or(eos_from_gen).ok_or(
417 "no eos token: need tokenizer_config.json eos_token or \
418 generation_config.json eos_token_id",
419 )?;
420 let bos_id = tc
421 .as_ref()
422 .and_then(|c| c.get("bos_token"))
423 .and_then(&tok_content)
424 .and_then(|s| token_to_id.get(&s).copied());
425 let add_bos = tc
426 .as_ref()
427 .and_then(|c| c.get("add_bos_token"))
428 .and_then(|v| v.as_bool())
429 .unwrap_or(false);
430
431 let chat_template = tc
433 .as_ref()
434 .and_then(|c| c.get("chat_template"))
435 .and_then(|v| v.as_str())
436 .map(|s| s.to_string())
437 .or_else(|| std::fs::read_to_string(dir.join("chat_template.jinja")).ok());
438 let pre = tc
439 .as_ref()
440 .and_then(|c| c.get("pretokenize_regex"))
441 .and_then(|v| v.as_str())
442 .filter(|regex| *regex == QWEN35_PRETOKENIZE_REGEX)
443 .map_or("default", |_| "qwen35");
444
445 Ok(Tokenizer {
446 id_to_token,
447 token_to_id,
448 attrs,
449 bpe_ranks,
450 special_tokens,
451 eos_id,
452 bos_id,
453 add_bos,
454 pre: pre.to_string(),
455 chat_template,
456 spm_style: false,
457 })
458 }
459
460 pub fn eos_id(&self) -> u32 {
461 self.eos_id
462 }
463 pub fn eog_ids(&self) -> Vec<u32> {
466 let mut ids = vec![self.eos_id];
467 for t in ["<|im_end|>", "<turn|>", "<end_of_turn>"] {
468 if let Some(&id) = self.token_to_id.get(t) {
469 if !ids.contains(&id) {
470 ids.push(id);
471 }
472 }
473 }
474 ids
475 }
476 pub fn bos_id(&self) -> Option<u32> {
477 self.bos_id
478 }
479 pub fn vocab_size(&self) -> usize {
480 self.id_to_token.len()
481 }
482 pub fn pre(&self) -> &str {
483 &self.pre
484 }
485 pub fn chat_template(&self) -> Option<&str> {
486 self.chat_template.as_deref()
487 }
488
489 #[inline]
490 fn text_to_token(&self, s: &str) -> Option<u32> {
491 self.token_to_id.get(s).copied()
492 }
493
494 fn find_bpe_rank(&self, left: &str, right: &str) -> i32 {
495 self.bpe_ranks
496 .get(&(left.to_string(), right.to_string()))
497 .copied()
498 .unwrap_or(-1)
499 }
500
501 pub fn encode(&self, text: &str, add_special: bool) -> Vec<u32> {
507 self.encode_special(text, add_special, true)
508 }
509
510 pub fn encode_special(&self, text: &str, add_special: bool, parse_special: bool) -> Vec<u32> {
511 let mut output: Vec<u32> = Vec::new();
512 if add_special && self.add_bos {
513 if let Some(b) = self.bos_id {
514 output.push(b);
515 }
516 }
517 if text.is_empty() {
518 return output;
519 }
520
521 for frag in self.st_partition(text, parse_special) {
523 match frag {
524 Fragment::Token(id) => output.push(id),
525 Fragment::Text(span) => self.bpe_tokenize(&span, &mut output),
526 }
527 }
528 output
529 }
530
531 fn st_partition(&self, text: &str, parse_special: bool) -> Vec<Fragment> {
533 let mut frags = vec![Fragment::Text(text.to_string())];
534 for &sid in &self.special_tokens {
535 let attr = self.attrs[sid as usize];
536 if !parse_special && matches!(attr, TokAttr::Control | TokAttr::Unknown) {
538 continue;
539 }
540 let needle = &self.id_to_token[sid as usize];
541 if needle.is_empty() {
542 continue;
543 }
544 let mut next: Vec<Fragment> = Vec::with_capacity(frags.len());
545 for f in frags.drain(..) {
546 match f {
547 Fragment::Token(id) => next.push(Fragment::Token(id)),
548 Fragment::Text(s) => {
549 let mut rest: &str = &s;
550 let mut acc = String::new();
551 while let Some(m) = rest.find(needle.as_str()) {
552 acc.push_str(&rest[..m]);
553 if !acc.is_empty() {
554 next.push(Fragment::Text(std::mem::take(&mut acc)));
555 }
556 next.push(Fragment::Token(sid));
557 rest = &rest[m + needle.len()..];
558 }
559 acc.push_str(rest);
560 if !acc.is_empty() {
561 next.push(Fragment::Text(acc));
562 }
563 }
564 }
565 }
566 frags = next;
567 }
568 frags
569 }
570
571 fn warn_unsupported_pre(pre: &str) {
575 use std::sync::OnceLock;
576 static WARNED: OnceLock<()> = OnceLock::new();
577 let pre = pre.to_string();
578 WARNED.get_or_init(move || {
579 eprintln!(
580 "memra-tokenizer: WARNING unsupported tokenizer.ggml.pre '{pre}' — falling back \
581 to the qwen35 pre-tokenizer split. Token ids will NOT be exact for this model."
582 );
583 });
584 }
585
586 fn bpe_tokenize(&self, text: &str, output: &mut Vec<u32>) {
588 if self.spm_style {
589 let escaped: String = text
592 .chars()
593 .map(|c| if c == ' ' { '\u{2581}' } else { c })
594 .collect();
595 let mut words: Vec<String> = Vec::new();
596 let mut cur = String::new();
597 let mut cur_nl: Option<bool> = None;
598 for c in escaped.chars() {
599 let nl = c == '\n';
600 if cur_nl != Some(nl) && !cur.is_empty() {
601 words.push(std::mem::take(&mut cur));
602 }
603 cur_nl = Some(nl);
604 cur.push(c);
605 }
606 if !cur.is_empty() {
607 words.push(cur);
608 }
609 for word in &words {
610 if word.chars().all(|c| c == '\n') {
612 if let Some(tok) = self.text_to_token(word) {
613 output.push(tok);
614 continue;
615 }
616 }
617 self.bpe_merge_word(word, output);
618 }
619 return;
620 }
621 let words: Vec<String> = match self.pre.as_str() {
623 "qwen35" => unicode::split_qwen35(text),
624 "deepseek-v3" => unicode::split_deepseek_v3(text),
628 "qwen2" => unicode::split_qwen35(text),
631 other => {
634 Self::warn_unsupported_pre(other);
635 unicode::split_qwen35(text)
636 }
637 };
638
639 for word in &words {
640 let word = unicode::byte_encode(word);
641 self.bpe_merge_word(&word, output);
642 }
643 }
644
645 fn bpe_merge_word(&self, word: &str, output: &mut Vec<u32>) {
648 {
649 let word = word.to_string();
650
651 let chars: Vec<char> = word.chars().collect();
653 let mut symbols: Vec<Symbol> = Vec::with_capacity(chars.len());
654 for (i, &c) in chars.iter().enumerate() {
655 symbols.push(Symbol {
656 text: c.to_string(),
657 prev: i as i32 - 1,
658 next: if i + 1 == chars.len() {
659 -1
660 } else {
661 i as i32 + 1
662 },
663 n: 1,
664 });
665 }
666
667 let mut queue: BinaryHeap<Bigram> = BinaryHeap::new();
669 for i in 1..symbols.len() {
670 self.add_bigram(&symbols, i as i32 - 1, i as i32, &mut queue);
671 }
672
673 while let Some(bigram) = queue.pop() {
675 let li = bigram.left as usize;
676 let ri = bigram.right as usize;
677 if symbols[li].n == 0 || symbols[ri].n == 0 {
678 continue;
679 }
680 let combined = format!("{}{}", symbols[li].text, symbols[ri].text);
681 if combined != bigram.text {
682 continue; }
684 symbols[li].text = combined;
686 symbols[li].n += symbols[ri].n;
687 symbols[ri].n = 0;
688 let r_next = symbols[ri].next;
689 symbols[li].next = r_next;
690 if r_next >= 0 {
691 symbols[r_next as usize].prev = bigram.left;
692 }
693 let l_prev = symbols[li].prev;
694 let l_next = symbols[li].next;
695 self.add_bigram(&symbols, l_prev, bigram.left, &mut queue);
696 self.add_bigram(&symbols, bigram.left, l_next, &mut queue);
697 }
698
699 for sym in &symbols {
701 if sym.n == 0 {
702 continue;
703 }
704 match self.text_to_token(&sym.text) {
705 Some(tok) => output.push(tok),
706 None => {
707 for b in sym.text.bytes() {
709 let bs = if self.spm_style {
710 format!("<0x{b:02X}>") } else {
712 (b as char).to_string()
713 };
714 if let Some(t) = self.text_to_token(&bs) {
715 output.push(t);
716 }
717 }
718 }
719 }
720 }
721 }
722 }
723
724 fn add_bigram(
725 &self,
726 symbols: &[Symbol],
727 left: i32,
728 right: i32,
729 queue: &mut BinaryHeap<Bigram>,
730 ) {
731 if left == -1 || right == -1 {
732 return;
733 }
734 let lt = &symbols[left as usize].text;
735 let rt = &symbols[right as usize].text;
736 let rank = self.find_bpe_rank(lt, rt);
737 if rank < 0 {
738 return;
739 }
740 queue.push(Bigram {
741 left,
742 right,
743 rank,
744 text: format!("{lt}{rt}"),
745 });
746 }
747
748 pub fn decode(&self, ids: &[u32]) -> String {
751 self.decode_special(ids, true)
752 }
753
754 pub fn token_is_control(&self, id: u32) -> bool {
759 match self.attrs.get(id as usize) {
760 Some(TokAttr::Control) | Some(TokAttr::Unknown) => true,
761 _ => false,
762 }
763 }
764
765 pub fn decode_special(&self, ids: &[u32], special: bool) -> String {
766 String::from_utf8_lossy(&self.decode_bytes_special(ids, special)).into_owned()
767 }
768
769 pub fn decode_bytes_special(&self, ids: &[u32], special: bool) -> Vec<u8> {
772 let mut bytes: Vec<u8> = Vec::new();
773 for &id in ids {
774 let i = id as usize;
775 if i >= self.id_to_token.len() {
776 continue;
777 }
778 let attr = self.attrs[i];
779 let piece = &self.id_to_token[i];
780 match attr {
781 TokAttr::Normal | TokAttr::Byte => {
782 if self.spm_style {
783 if matches!(attr, TokAttr::Byte)
785 || (piece.len() == 6
786 && piece.starts_with("<0x")
787 && piece.ends_with('>'))
788 {
789 if let Ok(b) = u8::from_str_radix(&piece[3..5], 16) {
790 bytes.push(b);
791 continue;
792 }
793 }
794 for c in piece.chars() {
795 if c == '\u{2581}' {
796 bytes.push(b' ');
797 } else {
798 let mut buf = [0u8; 4];
799 bytes.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
800 }
801 }
802 } else {
803 self.piece_to_bytes(piece, &mut bytes);
805 }
806 }
807 TokAttr::UserDefined => {
808 bytes.extend_from_slice(piece.as_bytes());
810 }
811 TokAttr::Control | TokAttr::Unknown => {
812 if special {
813 bytes.extend_from_slice(piece.as_bytes());
814 }
815 }
817 TokAttr::Other => {}
818 }
819 }
820 bytes
821 }
822
823 fn piece_to_bytes(&self, piece: &str, out: &mut Vec<u8>) {
824 for c in piece.chars() {
825 match unicode::unicode_to_byte(c) {
826 Some(b) => out.push(b),
827 None => {
828 let mut buf = [0u8; 4];
830 out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
831 }
832 }
833 }
834 }
835
836 pub fn apply_chat_template(
839 &self,
840 messages: &[(&str, &str)],
841 add_generation_prompt: bool,
842 ) -> String {
843 chat::apply_chat_template_str(
844 self.chat_template.as_deref(),
845 messages,
846 add_generation_prompt,
847 )
848 }
849
850 pub fn apply_chat_template_tools(
854 &self,
855 turns: &[chat::Turn],
856 add_generation_prompt: bool,
857 tools_json: &[String],
858 think: chat::ThinkMode,
859 reasoning_effort: Option<&str>,
860 ) -> Result<String, String> {
861 chat::apply_chat_template_tools(
862 self.chat_template.as_deref(),
863 turns,
864 add_generation_prompt,
865 tools_json,
866 think,
867 reasoning_effort,
868 )
869 }
870}
871
872enum Fragment {
873 Text(String),
874 Token(u32),
875}
876
877fn pre_tokenizer_is_byte_level(pt: &json::Value) -> bool {
880 match pt.get("type").and_then(|v| v.as_str()) {
881 Some("ByteLevel") => true,
882 Some("Sequence") => pt
883 .get("pretokenizers")
884 .and_then(|v| v.as_arr())
885 .map(|arr| arr.iter().any(pre_tokenizer_is_byte_level))
886 .unwrap_or(false),
887 _ => false,
888 }
889}
890
891#[cfg(test)]
892mod hf_tests {
893 use super::*;
894
895 const TOKENIZER_JSON: &str = r#"{
899 "version": "1.0",
900 "added_tokens": [
901 {"id": 15, "content": "<|end|>", "special": true},
902 {"id": 16, "content": "<think>", "special": false}
903 ],
904 "pre_tokenizer": {
905 "type": "Sequence",
906 "pretokenizers": [
907 {"type": "Split", "pattern": {"Regex": ""}, "behavior": "Isolated"},
908 {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": false}
909 ]
910 },
911 "model": {
912 "type": "BPE",
913 "vocab": {
914 "h": 0, "e": 1, "l": 2, "o": 3, "Ġ": 4, "w": 5, "r": 6, "d": 7,
915 "he": 8, "ll": 9, "hell": 10, "hello": 11, "Ġw": 12, "or": 13, "!": 14
916 },
917 "merges": [
918 "h e",
919 ["l", "l"],
920 "he ll",
921 ["hell", "o"],
922 ["Ġ", "w"],
923 "o r"
924 ]
925 }
926 }"#;
927
928 fn write_fixture(
929 name: &str,
930 tokenizer_config: Option<&str>,
931 generation_config: Option<&str>,
932 jinja: Option<&str>,
933 ) -> std::path::PathBuf {
934 let dir = std::env::temp_dir().join(format!("memra-tok-hf-{name}-{}", std::process::id()));
935 let _ = std::fs::remove_dir_all(&dir);
936 std::fs::create_dir_all(&dir).unwrap();
937 std::fs::write(dir.join("tokenizer.json"), TOKENIZER_JSON).unwrap();
938 if let Some(tc) = tokenizer_config {
939 std::fs::write(dir.join("tokenizer_config.json"), tc).unwrap();
940 }
941 if let Some(gc) = generation_config {
942 std::fs::write(dir.join("generation_config.json"), gc).unwrap();
943 }
944 if let Some(j) = jinja {
945 std::fs::write(dir.join("chat_template.jinja"), j).unwrap();
946 }
947 dir
948 }
949
950 #[test]
951 fn hf_dir_encode_decode_roundtrip_and_specials() {
952 let tc = r#"{
954 "eos_token": {"content": "<|end|>", "lstrip": false},
955 "add_bos_token": false,
956 "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
957 "chat_template": "{{ messages }}<|end|>"
958 }"#;
959 let dir = write_fixture("full", Some(tc), None, None);
960 let tok = Tokenizer::from_hf_dir(&dir).expect("from_hf_dir");
961
962 assert_eq!(tok.eos_id(), 15);
963 assert_eq!(tok.bos_id(), None);
964 assert_eq!(tok.pre(), "qwen35");
965 assert_eq!(tok.vocab_size(), 17); assert_eq!(tok.chat_template(), Some("{{ messages }}<|end|>"));
967
968 let ids = tok.encode("hello world", true);
972 assert_eq!(ids, vec![11, 12, 13, 2, 7]);
973 assert_eq!(tok.decode(&ids), "hello world");
974
975 let ids = tok.encode("hello<|end|> world", true);
977 assert_eq!(ids, vec![11, 15, 12, 13, 2, 7]);
978 assert_eq!(tok.decode_special(&ids, true), "hello<|end|> world");
980 assert_eq!(tok.decode_special(&ids, false), "hello world");
981
982 assert_eq!(tok.decode(&[16]), "<think>");
984 let _ = std::fs::remove_dir_all(&dir);
985 }
986
987 #[test]
988 fn hf_dir_generation_config_eos_fallback_and_jinja() {
989 let gc = r#"{"eos_token_id": [15, 14]}"#;
992 let dir = write_fixture("genconf", None, Some(gc), Some("JINJA {{ messages }}"));
993 let tok = Tokenizer::from_hf_dir(&dir).expect("from_hf_dir");
994 assert_eq!(tok.eos_id(), 15);
995 assert!(!tok.encode("hello", true).is_empty());
996 assert_eq!(tok.chat_template(), Some("JINJA {{ messages }}"));
997 let _ = std::fs::remove_dir_all(&dir);
998 }
999
1000 #[test]
1001 fn hf_dir_rejects_non_byte_level() {
1002 let dir = std::env::temp_dir().join(format!("memra-tok-hf-nonbl-{}", std::process::id()));
1003 let _ = std::fs::remove_dir_all(&dir);
1004 std::fs::create_dir_all(&dir).unwrap();
1005 let bad = TOKENIZER_JSON.replace("\"ByteLevel\"", "\"Metaspace\"");
1006 std::fs::write(dir.join("tokenizer.json"), bad).unwrap();
1007 assert!(Tokenizer::from_hf_dir(&dir).is_err());
1008 let _ = std::fs::remove_dir_all(&dir);
1009 }
1010}