pub struct Tokenizer {
pub bos_token_id: Option<u32>,
pub eos_token_id: Option<u32>,
pub pad_token_id: Option<u32>,
pub im_start_id: Option<u32>,
pub im_end_id: Option<u32>,
pub chat_template: Option<String>,
pub extra_eos: HashSet<u32>,
pub add_bos: bool,
/* private fields */
}Expand description
A loaded BPE tokenizer.
Fields§
§bos_token_id: Option<u32>Special tokens
eos_token_id: Option<u32>§pad_token_id: Option<u32>§im_start_id: Option<u32>Chat template special tokens
im_end_id: Option<u32>§chat_template: Option<String>Jinja chat template carried by the container (spec §6.1); None → hardcoded ChatML fallback.
extra_eos: HashSet<u32>Extra stop ids from the container’s generation config.
add_bos: boolGeneration prepends BOS (llama post_processor semantics).
Implementations§
Source§impl Tokenizer
impl Tokenizer
Sourcepub fn from_file(path: impl AsRef<Path>) -> Result<Self, TokenizerError>
pub fn from_file(path: impl AsRef<Path>) -> Result<Self, TokenizerError>
Load tokenizer from HuggingFace tokenizer.json file.
Sourcepub fn from_bytes(bytes: &[u8]) -> Result<Self, TokenizerError>
pub fn from_bytes(bytes: &[u8]) -> Result<Self, TokenizerError>
Load tokenizer from raw tokenizer.json bytes (CMF VOCAB section).
Sourcepub fn from_json(json: &str) -> Result<Self, TokenizerError>
pub fn from_json(json: &str) -> Result<Self, TokenizerError>
Load tokenizer from JSON string.
Sourcepub fn byte_level() -> Self
pub fn byte_level() -> Self
Create a minimal tokenizer for testing (byte tokens, no merges).
Sourcepub fn encode(&self, text: &str) -> Vec<u32>
pub fn encode(&self, text: &str) -> Vec<u32>
Encode text to token IDs.
Examples found in repository?
18fn main() {
19 let args: Vec<String> = std::env::args().collect();
20 if args.len() < 4 {
21 eprintln!("usage: decode_flat <model.cmf> <ctx> <tokens> [o1spec|off]");
22 std::process::exit(2);
23 }
24 let path = &args[1];
25 let ctx: usize = args[2].parse().expect("ctx");
26 let tokens: usize = args[3].parse().expect("tokens");
27 let o1spec = args.get(4).cloned().unwrap_or_else(|| "off".to_string());
28
29 let model = Arc::new(CmfModel::open_sharded(path).expect("open model"));
30 let mut pipeline = Pipeline::from_model(&model, SamplerConfig::default()).expect("pipeline");
31 pipeline.set_o1(cortiq_engine::nystrom::O1Cfg::from_spec(
32 &o1spec, None, None, None, None,
33 ));
34 eprintln!("o1_active = {}", pipeline.o1_active());
35
36 // Same synthetic prompt shape as `cortiq bench --ctx`.
37 let prompt = "The quick brown fox jumps over the lazy dog. ".repeat(ctx / 8 + 2);
38 let mut ids = pipeline.tokenizer.encode(&prompt);
39 ids.truncate(ctx);
40 assert_eq!(ids.len(), ctx, "prompt too short for ctx");
41
42 // Warm the mmap so the first token is not billed for page faults.
43 let _ = pipeline.forward_ids(&ids[..2], None).expect("warm");
44
45 let stamps: Arc<std::sync::Mutex<Vec<Instant>>> = Arc::default();
46 let st = stamps.clone();
47 let cb: cortiq_engine::TokenCallback = Box::new(move |_t| {
48 st.lock().unwrap().push(Instant::now());
49 true
50 });
51 let t0 = Instant::now();
52 let _ = pipeline
53 .generate_from_ids(&ids, tokens, None, Some(cb))
54 .expect("generate");
55
56 let stamps = stamps.lock().unwrap();
57 // stamps[0] fires after generation's prefill + the one-off o1 seal:
58 // that gap is TTFT, not a decode step.
59 println!("ctx={ctx} o1={o1spec} ttft_s={:.3}", stamps[0].duration_since(t0).as_secs_f64());
60 println!("# idx ms");
61 for i in 1..stamps.len() {
62 println!("{:4} {:7.2}", i, (stamps[i] - stamps[i - 1]).as_secs_f64() * 1e3);
63 }
64 // Mean of the last half — past any startup transient.
65 let half = stamps.len() / 2;
66 if stamps.len() > 2 && half >= 1 {
67 let dt = (stamps[stamps.len() - 1] - stamps[half]).as_secs_f64();
68 let n = (stamps.len() - 1 - half) as f64;
69 println!("last-half: {:.2} ms/tok = {:.2} tok/s", dt / n * 1e3, n / dt);
70 }
71}Sourcepub fn decode(&self, ids: &[u32]) -> String
pub fn decode(&self, ids: &[u32]) -> String
Decode token IDs back to text. Special tokens are skipped; added tokens are raw text; everything else reverses the byte-level map.
Sourcepub fn decode_token(&self, id: u32) -> String
pub fn decode_token(&self, id: u32) -> String
Streaming decode of ONE token: no sequence-level Strip — a per-token strip would eat the ▁-spaces of every SP word.
Sourcepub fn apply_chat_template(&self, messages: &[(String, String)]) -> Vec<u32>
pub fn apply_chat_template(&self, messages: &[(String, String)]) -> Vec<u32>
Render the container’s Jinja chat template (HF semantics: trim_blocks + lstrip_blocks + loop controls) and encode it. Falls back to hardcoded ChatML when the file carries none.
Sourcepub fn apply_chat_template_opts(
&self,
messages: &[(String, String)],
enable_thinking: Option<bool>,
) -> Vec<u32>
pub fn apply_chat_template_opts( &self, messages: &[(String, String)], enable_thinking: Option<bool>, ) -> Vec<u32>
Like apply_chat_template, with an explicit enable_thinking value for
reasoning-model templates (Qwen3/3.5 emit an empty None leaves the variable
undefined — the template’s own default applies.
Sourcepub fn with_bos(&self, ids: Vec<u32>) -> Vec<u32>
pub fn with_bos(&self, ids: Vec<u32>) -> Vec<u32>
Prepend BOS when the tokenizer declares it (llama family).
Sourcepub fn render_chat(&self, messages: &[(String, String)]) -> Option<String>
pub fn render_chat(&self, messages: &[(String, String)]) -> Option<String>
Render the carried template to text (parity-testable surface).
Sourcepub fn vocab_size(&self) -> usize
pub fn vocab_size(&self) -> usize
Vocabulary size.