interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / src / tokenizer.rs

1155 lines · 52248 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Pure Rust tokenizer and chat template formatter for the Llama model family
17//! (TinyLlama zephyr-style chat, Llama 3 instruct chat, ChatML as shipped by SmolLM2).
18//! Wraps Hugging Face tokenizers crate without Python runtime dependencies.
19
20use std::fmt;
21use std::path::Path;
22use std::sync::Arc;
23
24/// Loud error enum for tokenizer operations.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum TokenizerError {
27 LoadError(String),
28 /// Chat rendering was asked of a plain (base) model that has no chat template. Not a
29 /// load failure: the tokenizer loaded fine.
30 NoChatTemplate(String),
31 EncodeError(String),
32 DecodeError(String),
33 ContextLengthExceeded {
34 len: usize,
35 max: usize,
36 },
37 /// Role `tool` offered to the raw `ChatTurn` path; tool turns must go through
38 /// `tool_boundary::ToolConversation` (issue #310).
39 ToolTurnRefused(String),
40 /// A message combination the pinned Qwen3-8B template layout does not cover (thinking
41 /// enabled, tool turns, tool calls, reasoning content, unknown roles, an assistant turn
42 /// to continue). Refused by name, never approximated (sc#384).
43 UnsupportedChatLayout(String),
44}
45
46impl fmt::Display for TokenizerError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self {
49 Self::LoadError(e) => write!(f, "Failed to load tokenizer: {}", e),
50 Self::NoChatTemplate(e) => write!(f, "{}", e),
51 Self::EncodeError(e) => write!(f, "Tokenization encoding failed: {}", e),
52 Self::DecodeError(e) => write!(f, "Tokenization decoding failed: {}", e),
53 Self::ToolTurnRefused(e) => write!(f, "{}", e),
54 Self::UnsupportedChatLayout(e) => write!(f, "unsupported chat layout: {}", e),
55 Self::ContextLengthExceeded { len, max } => {
56 write!(
57 f,
58 "Sequence length {} exceeds maximum context length {}",
59 len, max
60 )
61 }
62 }
63 }
64}
65
66impl std::error::Error for TokenizerError {}
67
68/// The chat layout a model was fine-tuned on. Selected from the model's own chat template
69/// text (no template engine): each variant renders the one layout that template produces
70/// for plain user/system/assistant turns ending in a generation prompt.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum ChatTemplate {
73 /// TinyLlama-Chat (zephyr): `<|user|>\n{content}</s>\n<|assistant|>\n`.
74 Zephyr,
75 /// Llama 3 instruct: `<|start_header_id|>user<|end_header_id|>\n\n{content}<|eot_id|>`
76 /// then `<|start_header_id|>assistant<|end_header_id|>\n\n`. No system block is added
77 /// (the Hugging Face template's default "Cutting Knowledge Date / Today Date" block
78 /// depends on the wall clock, so it is left out).
79 Llama3,
80 /// ChatML exactly as the publisher's template renders it (SmolLM2-Instruct, and
81 /// Qwen3-4B-Instruct-2507 without tools): per turn `<|im_start|>{role}\n{content}<|im_end|>\n`,
82 /// then `<|im_start|>assistant\n`. Contents are kept verbatim and empty turns are kept
83 /// (the template neither trims nor skips).
84 /// When the template carries a default system message and the first turn is not a
85 /// system turn, that message is rendered first as a system turn, as the template does.
86 /// No BOS is part of the text; the model's tokenizer decides whether `encode` adds one
87 /// (SmolLM2's `tokenizer.json` has no post-processor, so it adds none).
88 ChatMl {
89 /// The default system message read from the model's own template, if it has one.
90 default_system: Option<Arc<str>>,
91 },
92 /// Qwen3-4B-Instruct-2507: the plain ChatML layout above (no default system message) plus
93 /// the publisher template's handling of role `tool`: a run of consecutive `tool` turns is
94 /// one user turn, `<|im_start|>user`, then per turn `\n<tool_response>\n{content}\n</tool_response>`,
95 /// then `<|im_end|>\n`. Selected only by the pinned template text in `QWEN3_INSTRUCT_2507`.
96 ChatMlQwen3,
97 /// Qwen3-8B (and any model shipping the same template text), thinking mode explicitly OFF:
98 /// the pinned template `QWEN3_8B` rendered with `enable_thinking=false`. System and user
99 /// turns are ChatML verbatim; earlier assistant turns are plain; the generation prompt is
100 /// the assistant header plus an empty think block. Everything else (thinking on, tool
101 /// turns, tool calls, reasoning content, unknown roles, a trailing assistant turn) is
102 /// refused with `TokenizerError::UnsupportedChatLayout`. Selected only by the pinned text.
103 ChatMlQwen3NoThink,
104 /// Qwen3.8-27B (the pinned template `QWEN38`): text-only system, user and assistant turns.
105 /// Thinking follows the template: ON unless [`ChatOptions::enable_thinking`] is `false`, with
106 /// the template's reasoning-effort system text (default `xhigh`; `medium` adds none). Earlier
107 /// assistant turns render with the template's empty think block (no `reasoning_content`).
108 /// Tool turns are refused. Selected only by the pinned text.
109 Qwen38,
110 /// Qwen3.6-35B-A3B (the pinned template `QWEN36`): text-only system, user and assistant turns.
111 /// Thinking follows the template: ON unless [`ChatOptions::enable_thinking`] is `false`. No
112 /// reasoning-effort text (the template has no such switch; `reasoning_effort` is ignored as the
113 /// template ignores it). A first system turn renders even when empty. Earlier assistant turns
114 /// render plain; those after the last user query, or all of them when
115 /// [`ChatOptions::preserve_thinking`] is `true`, carry the think block with the reasoning the
116 /// template splits out of a `</think>`-bearing content. Tool turns are refused. Selected only by
117 /// the pinned text.
118 Qwen36,
119 /// Qwen3.5 (the pinned template `QWEN35`, Qwen3.5-9B): the [`Self::Qwen36`] rendering without
120 /// the `preserve_thinking` switch (the template has none, so earlier assistant turns before the
121 /// last user query always render plain and the option is ignored as the template ignores it).
122 /// Selected only by the pinned text.
123 Qwen35,
124 /// The model directory has no chat template at all (a base model). Plain text encode
125 /// and decode work; every chat render is refused (`try_render` errors with
126 /// "no chat template"). Chosen only when neither `tokenizer_config.json` `chat_template`
127 /// nor `chat_template.jinja` exists; a template that exists but is unrecognized is
128 /// refused at load.
129 None,
130}
131
132/// The ChatML layouts this engine renders, as the exact Jinja text a model ships in
133/// `tokenizer_config.json` `chat_template` (the SmolLM2-Instruct template, and the same
134/// without its default system block). `{SYSTEM}` stands for the default system message
135/// (plain text: no quote, backslash, Jinja brace or ChatML marker). Any other ChatML
136/// template (tools, trimming, another generation prompt) is refused, not approximated.
137const CHATML_WITH_DEFAULT_SYSTEM: &str = "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\n{SYSTEM}<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}";
138const CHATML_PLAIN: &str = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}";
139
140/// The Qwen3-4B-Instruct-2507 chat template, byte for byte (revision cdbee75f, Apache-2.0; see
141/// `fixtures/chat-templates/qwen3-4b-instruct-2507/PROVENANCE.md`). Without tools and without
142/// assistant tool calls (this engine passes neither) it renders exactly the plain ChatML layout:
143/// no default system message, contents verbatim, generation prompt `<|im_start|>assistant\n`.
144/// Any other Qwen template text (tools in use, thinking blocks, another revision) is refused.
145const QWEN3_INSTRUCT_2507: &str =
146 include_str!("../fixtures/chat-templates/qwen3-4b-instruct-2507/chat_template.jinja");
147
148/// The Qwen3-8B chat template, byte for byte (Hugging Face `Qwen/Qwen3-8B` revision
149/// b968826d9c46dd6066d109eabc6255188de91218, Apache-2.0; see
150/// `fixtures/chat-templates/qwen3-8b/PROVENANCE.md`). It has an `enable_thinking` switch; this
151/// engine always renders the `enable_thinking=false` form ([`ChatTemplate::ChatMlQwen3NoThink`]).
152const QWEN3_8B: &str = include_str!("../fixtures/chat-templates/qwen3-8b/chat_template.jinja");
153
154/// The Qwen3.8-27B chat template, byte for byte (Hugging Face `Qwen/Qwen3.8-27B-FP8` revision
155/// 017b9c7a, Apache-2.0; see `fixtures/chat-templates/qwen3.8-27b/PROVENANCE.md`).
156const QWEN38: &str = include_str!("../fixtures/chat-templates/qwen3.8-27b/chat_template.jinja");
157
158/// The Qwen3.6-35B-A3B chat template, byte for byte (Hugging Face `Qwen/Qwen3.6-35B-A3B-FP8`
159/// revision 95a723d0, Apache-2.0; see `fixtures/chat-templates/qwen3.6-35b-a3b/PROVENANCE.md`).
160/// The 27B template without the reasoning-effort text, with `preserve_thinking` (default off:
161/// earlier assistant turns render plain) and a `</think>` split of assistant content.
162const QWEN36: &str = include_str!("../fixtures/chat-templates/qwen3.6-35b-a3b/chat_template.jinja");
163
164/// The Qwen3.5-9B chat template, byte for byte (Hugging Face `Qwen/Qwen3.5-9B` revision
165/// c202236235762e1c871ad0ccb60c8ee5ba337b9a, Apache-2.0; see
166/// `fixtures/chat-templates/qwen3.5-9b/PROVENANCE.md`). Text-only, it renders as [`QWEN36`] with
167/// `preserve_thinking` always off.
168const QWEN35: &str = include_str!("../fixtures/chat-templates/qwen3.5-9b/chat_template.jinja");
169
170/// Template switches a request may set (`chat_template_kwargs`). `None` = the template's default.
171/// Only [`ChatTemplate::Qwen38`], [`ChatTemplate::Qwen36`] and [`ChatTemplate::Qwen35`] read them;
172/// the other layouts ignore them. `reasoning_effort` is the 27B template's switch (the 35B and 9B
173/// templates ignore it); `preserve_thinking` is the 35B template's switch (the 27B renderer here
174/// keeps every think block; the 9B template has none).
175#[derive(Debug, Clone, Default, PartialEq, Eq)]
176pub struct ChatOptions {
177 pub enable_thinking: Option<bool>,
178 pub reasoning_effort: Option<String>,
179 pub preserve_thinking: Option<bool>,
180}
181
182/// The Qwen3.8-27B template's reasoning-effort system text (`QWEN38` lines 46-58).
183fn qwen38_reasoning_instructions(opts: &ChatOptions) -> Result<&'static str, TokenizerError> {
184 if opts.enable_thinking == Some(false) {
185 return Ok("");
186 }
187 match opts.reasoning_effort.as_deref().unwrap_or("xhigh") {
188 "xhigh" => Ok("Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer."),
189 "medium" => Ok(""),
190 "low" => Ok("Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration."),
191 other => Err(TokenizerError::UnsupportedChatLayout(format!(
192 "Unexpected reasoning effort {other}. Supported types are xhigh (default), medium, and low."
193 ))),
194 }
195}
196
197/// The pinned Qwen3.8-27B template without tools, text content only (oracle-checked against
198/// jinja2, `fixtures/chat-templates/qwen3.8-27b/render_oracle.json`): every content trimmed; an
199/// optional first system turn merged with the reasoning-effort text; user turns ChatML; assistant
200/// turns `<think>\n\n</think>\n\n` + content (no reasoning content is carried); generation prompt
201/// `<|im_start|>assistant\n<think>\n`, or the closed empty think block when thinking is off.
202fn render_qwen38(turns: &[(&str, &str)], opts: &ChatOptions) -> Result<String, TokenizerError> {
203 let refuse = |why: String| Err(TokenizerError::UnsupportedChatLayout(why));
204 if turns.is_empty() {
205 return refuse("No messages provided.".into());
206 }
207 let reasoning = qwen38_reasoning_instructions(opts)?;
208 let mut out = String::new();
209 let system = match turns[0] {
210 ("system", c) => Some(c.trim()),
211 _ => None,
212 };
213 match system {
214 Some(c) if !c.is_empty() => {
215 out.push_str("<|im_start|>system\n");
216 if !reasoning.is_empty() {
217 out.push_str(reasoning);
218 out.push_str("\n\n");
219 }
220 out.push_str(c);
221 out.push_str("<|im_end|>\n");
222 }
223 _ if !reasoning.is_empty() => {
224 out.push_str("<|im_start|>system\n");
225 out.push_str(reasoning);
226 out.push_str("<|im_end|>\n");
227 }
228 _ => {}
229 }
230 if !turns.iter().any(|(r, _)| *r == "user") {
231 return refuse("No user query found in messages.".into());
232 }
233 for (i, (role, content)) in turns.iter().enumerate() {
234 let content = content.trim();
235 match *role {
236 "system" if i == 0 => {}
237 "system" => return refuse("System message must be at the beginning.".into()),
238 "user" => {
239 out.push_str("<|im_start|>user\n");
240 out.push_str(content);
241 out.push_str("<|im_end|>\n");
242 }
243 "assistant" => {
244 out.push_str("<|im_start|>assistant\n<think>\n\n</think>\n\n");
245 out.push_str(content);
246 out.push_str("<|im_end|>\n");
247 }
248 other => {
249 return refuse(format!(
250 "role {other} refused: the Qwen3.8 layout here is text-only system/user/assistant"
251 ))
252 }
253 }
254 }
255 out.push_str("<|im_start|>assistant\n");
256 out.push_str(if opts.enable_thinking == Some(false) {
257 "<think>\n\n</think>\n\n"
258 } else {
259 "<think>\n"
260 });
261 Ok(out)
262}
263
264/// The pinned Qwen3.6-35B-A3B template without tools, text content only (oracle-checked against
265/// jinja2, `fixtures/chat-templates/qwen3.6-35b-a3b/render_oracle.json`): every content trimmed; a
266/// first system turn always rendered, even empty; user turns ChatML; assistant turns plain, or
267/// `<think>\n{reasoning}\n</think>\n\n` + content when `preserve_thinking` is true or the turn
268/// follows the last user query (the last user turn not shaped like a tool response), `reasoning`
269/// being what the template splits out of a `</think>`-bearing content; generation prompt
270/// `<|im_start|>assistant\n<think>\n`, or the closed empty think block when thinking is off.
271/// `reasoning_effort` is ignored: the template has no such switch.
272fn render_qwen36(turns: &[(&str, &str)], opts: &ChatOptions) -> Result<String, TokenizerError> {
273 let refuse = |why: String| Err(TokenizerError::UnsupportedChatLayout(why));
274 if turns.is_empty() {
275 return refuse("No messages provided.".into());
276 }
277 let mut out = String::new();
278 if let ("system", c) = turns[0] {
279 out.push_str("<|im_start|>system\n");
280 out.push_str(c.trim());
281 out.push_str("<|im_end|>\n");
282 }
283 // The template's `last_query_index`: the last user turn whose trimmed content is not shaped
284 // like a tool response.
285 let last_query = turns.iter().rposition(|(role, content)| {
286 let c = content.trim();
287 *role == "user" && !(c.starts_with("<tool_response>") && c.ends_with("</tool_response>"))
288 });
289 let Some(last_query) = last_query else {
290 return refuse("No user query found in messages.".into());
291 };
292 for (i, (role, content)) in turns.iter().enumerate() {
293 let content = content.trim();
294 match *role {
295 "system" if i == 0 => {}
296 "system" => return refuse("System message must be at the beginning.".into()),
297 "user" => {
298 out.push_str("<|im_start|>user\n");
299 out.push_str(content);
300 out.push_str("<|im_end|>\n");
301 }
302 "assistant" => {
303 let (reasoning, content) = qwen36_split_think(content);
304 out.push_str("<|im_start|>assistant\n");
305 if opts.preserve_thinking == Some(true) || i > last_query {
306 out.push_str("<think>\n");
307 out.push_str(reasoning);
308 out.push_str("\n</think>\n\n");
309 }
310 out.push_str(content);
311 out.push_str("<|im_end|>\n");
312 }
313 other => {
314 return refuse(format!(
315 "Unexpected message role. (role {other}: the Qwen3.6 layout here is text-only system/user/assistant)"
316 ))
317 }
318 }
319 }
320 out.push_str("<|im_start|>assistant\n");
321 out.push_str(if opts.enable_thinking == Some(false) {
322 "<think>\n\n</think>\n\n"
323 } else {
324 "<think>\n"
325 });
326 Ok(out)
327}
328
329/// The template's assistant-content split (`QWEN36`: `content.split('</think>')[0].rstrip('\n')
330/// .split('<think>')[-1].lstrip('\n')` then `|trim` for the reasoning, `content.split('</think>')
331/// [-1].lstrip('\n')` for the content). Without a `</think>` there is no reasoning.
332fn qwen36_split_think(content: &str) -> (&str, &str) {
333 let Some(first) = content.find("</think>") else {
334 return ("", content);
335 };
336 let before = content[..first].trim_end_matches('\n');
337 let reasoning = match before.rfind("<think>") {
338 Some(p) => &before[p + "<think>".len()..],
339 None => before,
340 };
341 let reasoning = reasoning.trim_start_matches('\n').trim();
342 let last = content
343 .rfind("</think>")
344 .expect("a </think> was found above");
345 let rest = content[last + "</think>".len()..].trim_start_matches('\n');
346 (reasoning, rest)
347}
348
349/// Matches a chat template text against the ChatML layouts above. Returns the layout
350/// with its default system message (None for the plain layout), or a refusal.
351fn parse_chatml(template_text: &str) -> Result<ChatTemplate, TokenizerError> {
352 let text = template_text.trim();
353 if text == QWEN3_INSTRUCT_2507.trim() {
354 return Ok(ChatTemplate::ChatMlQwen3);
355 }
356 if text == QWEN3_8B.trim() {
357 return Ok(ChatTemplate::ChatMlQwen3NoThink);
358 }
359 if text == QWEN38.trim() {
360 return Ok(ChatTemplate::Qwen38);
361 }
362 if text == QWEN36.trim() {
363 return Ok(ChatTemplate::Qwen36);
364 }
365 if text == QWEN35.trim() {
366 return Ok(ChatTemplate::Qwen35);
367 }
368 if text == CHATML_PLAIN {
369 return Ok(ChatTemplate::ChatMl {
370 default_system: None,
371 });
372 }
373 let (head, tail) = CHATML_WITH_DEFAULT_SYSTEM
374 .split_once("{SYSTEM}")
375 .expect("placeholder in the ChatML layout");
376 let system = text
377 .strip_prefix(head)
378 .and_then(|rest| rest.strip_suffix(tail))
379 .filter(|s| {
380 !s.is_empty()
381 && !s.contains(['\'', '\\', '{', '}'])
382 && !s.contains("<|im_start|>")
383 && !s.contains("<|im_end|>")
384 });
385 match system {
386 Some(system) => Ok(ChatTemplate::ChatMl {
387 default_system: Some(Arc::from(system)),
388 }),
389 None => Err(TokenizerError::LoadError(
390 "unsupported ChatML chat template: only the plain ChatML layout (each turn \
391 <|im_start|>role, newline, content, <|im_end|>, newline; generation prompt \
392 <|im_start|>assistant and a newline), optionally with one plain-text default \
393 system message, is rendered; this template differs (tools, trimming or another \
394 layout)"
395 .to_string(),
396 )),
397 }
398}
399
400/// The publisher's ChatML rendering for `(role, content)` turns ending in a generation
401/// prompt (see [`ChatTemplate::ChatMl`]). Roles are normalized as for the other layouts.
402fn render_chatml(default_system: Option<&str>, qwen_tools: bool, turns: &[(&str, &str)]) -> String {
403 let role_of = |role: &str| match role.trim().to_ascii_lowercase().as_str() {
404 "system" => "system",
405 "assistant" => "assistant",
406 "tool" if qwen_tools => "tool",
407 _ => "user",
408 };
409 let mut out = String::new();
410 if let (Some(system), Some((first_role, _))) = (default_system, turns.first()) {
411 if role_of(first_role) != "system" {
412 out.push_str(&format!("<|im_start|>system\n{system}<|im_end|>\n"));
413 }
414 }
415 for (i, (role, content)) in turns.iter().enumerate() {
416 let role = role_of(role);
417 if role == "tool" {
418 // Qwen3 template: one user turn per run of tool turns.
419 if i == 0 || role_of(turns[i - 1].0) != "tool" {
420 out.push_str("<|im_start|>user");
421 }
422 out.push_str(&format!("\n<tool_response>\n{content}\n</tool_response>"));
423 if turns
424 .get(i + 1)
425 .is_none_or(|(next, _)| role_of(next) != "tool")
426 {
427 out.push_str("<|im_end|>\n");
428 }
429 } else {
430 out.push_str(&format!("<|im_start|>{role}\n{content}<|im_end|>\n"));
431 }
432 }
433 if !ends_in_assistant(turns) {
434 out.push_str("<|im_start|>assistant\n");
435 }
436 out
437}
438
439/// True when the last turn is a non-empty assistant turn: generation then continues it
440/// instead of opening a new assistant turn.
441fn ends_in_assistant(turns: &[(&str, &str)]) -> bool {
442 turns.last().is_some_and(|(role, content)| {
443 role.trim().eq_ignore_ascii_case("assistant") && !content.trim().is_empty()
444 })
445}
446
447/// Oracle-checked rendering of the pinned Qwen3-8B template with `enable_thinking=false`,
448/// `tools=None`, `add_generation_prompt=true`. Branches taken (template `QWEN3_8B`):
449/// 1. `tools` falsy: the system header is `<|im_start|>system\n{content}<|im_end|>\n` only when
450/// `messages[0].role == 'system'`; in the loop that first system turn then matches no branch
451/// (the `system and not loop.first` test fails), so it is emitted exactly once.
452/// 2. user, and system after the first turn: `<|im_start|>{role}\n{content}<|im_end|>\n`.
453/// 3. assistant, `reasoning_content` undefined and no `</think>` in content: content stays as is.
454/// At `index <= last_query_index` the turn is `<|im_start|>assistant\n{content}`; at
455/// `index > last_query_index` and not last the same text (no reasoning); the last message being
456/// an assistant turn takes the `<think>` block branch and closes the turn, so it is refused.
457/// No `tool_calls`, so the turn ends with `<|im_end|>\n`.
458/// 4. generation prompt with `enable_thinking is false`:
459/// `<|im_start|>assistant\n<think>\n\n</think>\n\n`.
460///
461/// Tool turns, tool calls, reasoning, thinking-on, tool-response-shaped user text, unknown roles,
462/// and an empty conversation are refused by name.
463fn render_qwen3_nothink(turns: &[(&str, &str)]) -> Result<String, TokenizerError> {
464 let refuse = |why: &str| Err(TokenizerError::UnsupportedChatLayout(why.to_string()));
465 if turns.is_empty() {
466 return refuse("empty conversation");
467 }
468 let mut out = String::new();
469 for (i, (role, content)) in turns.iter().enumerate() {
470 match *role {
471 "system" | "user" => {
472 if *role == "user"
473 && content.starts_with("<tool_response>")
474 && content.ends_with("</tool_response>")
475 {
476 return refuse("user text shaped like a tool response (changes the template's last-query index)");
477 }
478 out.push_str(&format!("<|im_start|>{role}\n{content}<|im_end|>\n"));
479 }
480 "assistant" => {
481 if i + 1 == turns.len() {
482 return refuse("trailing assistant turn (the template would add a think block and close it; continuation is not supported)");
483 }
484 if content.contains("<think>") || content.contains("</think>") {
485 return refuse("thinking markers inside an assistant turn (reasoning content)");
486 }
487 out.push_str(&format!("<|im_start|>assistant\n{content}<|im_end|>\n"));
488 }
489 "tool" => {
490 return Err(TokenizerError::ToolTurnRefused(
491 "role tool refused: the pinned Qwen3-8B layout covers no tool turns".into(),
492 ))
493 }
494 _ => {
495 return refuse("role other than exactly system, user or assistant");
496 }
497 }
498 }
499 out.push_str("<|im_start|>assistant\n<think>\n\n</think>\n\n");
500 Ok(out)
501}
502
503impl ChatTemplate {
504 /// [`Self::try_render`] with template switches: only [`ChatTemplate::Qwen38`],
505 /// [`ChatTemplate::Qwen36`] and [`ChatTemplate::Qwen35`] read `opts`.
506 pub fn try_render_with(
507 &self,
508 turns: &[(&str, &str)],
509 opts: &ChatOptions,
510 ) -> Result<String, TokenizerError> {
511 match self {
512 Self::Qwen38 => render_qwen38(turns, opts),
513 Self::Qwen36 => render_qwen36(turns, opts),
514 Self::Qwen35 => render_qwen36(
515 turns,
516 &ChatOptions {
517 preserve_thinking: None,
518 ..opts.clone()
519 },
520 ),
521 _ => self.try_render(turns),
522 }
523 }
524
525 /// Qwen3-8B with `enable_thinking` requested explicitly. Only `false` renders; `true` is
526 /// refused (the engine does not parse or budget a thinking block).
527 pub fn try_render_thinking(
528 &self,
529 turns: &[(&str, &str)],
530 enable_thinking: bool,
531 ) -> Result<String, TokenizerError> {
532 if enable_thinking {
533 return Err(TokenizerError::UnsupportedChatLayout(
534 "thinking enabled is not supported".into(),
535 ));
536 }
537 self.try_render(turns)
538 }
539}
540fn no_chat_template_error() -> TokenizerError {
541 TokenizerError::NoChatTemplate(
542 "no chat template: this is a plain (base) model, chat rendering is refused".to_string(),
543 )
544}
545
546impl ChatTemplate {
547 pub fn name(&self) -> &'static str {
548 match self {
549 Self::Zephyr => "zephyr (TinyLlama chat)",
550 Self::Llama3 => "llama3 (Llama 3 instruct)",
551 Self::ChatMl { .. } => "chatml (<|im_start|> / <|im_end|>)",
552 Self::ChatMlQwen3 => "chatml-qwen3 (<|im_start|> / <|im_end|>, tool responses)",
553 Self::ChatMlQwen3NoThink => "chatml-qwen3-nothink (Qwen3-8B, thinking off)",
554 Self::Qwen38 => "qwen3.8 (Qwen3.8-27B, thinking per request, template default on)",
555 Self::Qwen36 => "qwen3.6 (Qwen3.6-35B-A3B, thinking per request, template default on)",
556 Self::Qwen35 => "qwen3.5 (Qwen3.5-9B, thinking per request, template default on)",
557 Self::None => "none (plain text model)",
558 }
559 }
560
561 /// Recognizes the layout from a Jinja chat template's text. A ChatML template must be
562 /// one of the exact layouts this engine renders (see [`ChatTemplate::ChatMl`]).
563 pub fn detect(template_text: &str) -> Result<Self, TokenizerError> {
564 if template_text.contains("<|start_header_id|>") && template_text.contains("<|eot_id|>") {
565 Ok(Self::Llama3)
566 } else if template_text.contains("<|user|>") && template_text.contains("<|assistant|>") {
567 Ok(Self::Zephyr)
568 } else if template_text.contains("<|im_start|>") && template_text.contains("<|im_end|>") {
569 parse_chatml(template_text)
570 } else {
571 Err(TokenizerError::LoadError(
572 "unsupported chat template: no zephyr (<|user|>), llama3 \
573 (<|start_header_id|>) or chatml (<|im_start|>) markers found"
574 .to_string(),
575 ))
576 }
577 }
578
579 /// The default system message the model's template adds (ChatML only).
580 pub fn default_system(&self) -> Option<&str> {
581 match self {
582 Self::ChatMl { default_system } => default_system.as_deref(),
583 _ => None,
584 }
585 }
586
587 /// Renders `(role, content)` turns; roles other than system and assistant are user
588 /// turns. Generation continues from an assistant header unless the last turn is a
589 /// non-empty assistant turn. Zephyr and Llama 3: contents are trimmed and empty turns
590 /// skipped, and the BOS token is not part of the text (`encode` adds exactly one
591 /// through the tokenizer's post-processor). ChatML: see [`ChatTemplate::ChatMl`].
592 pub fn render(&self, turns: &[(&str, &str)]) -> String {
593 self.try_render(turns).expect("no chat template")
594 }
595
596 /// Like [`ChatTemplate::render`], but a plain model (no chat template) is refused with
597 /// an error containing "no chat template" instead of a layout being invented.
598 pub fn try_render(&self, turns: &[(&str, &str)]) -> Result<String, TokenizerError> {
599 if let Self::None = self {
600 return Err(no_chat_template_error());
601 }
602 if let Self::ChatMl { default_system } = self {
603 return Ok(render_chatml(default_system.as_deref(), false, turns));
604 }
605 if let Self::ChatMlQwen3 = self {
606 return Ok(render_chatml(None, true, turns));
607 }
608 if let Self::ChatMlQwen3NoThink = self {
609 return render_qwen3_nothink(turns);
610 }
611 if let Self::Qwen38 = self {
612 return render_qwen38(turns, &ChatOptions::default());
613 }
614 if let Self::Qwen36 = self {
615 return render_qwen36(turns, &ChatOptions::default());
616 }
617 let mut out = String::new();
618 for (role, content) in turns {
619 let body = content.trim();
620 if body.is_empty() {
621 continue;
622 }
623 let role = match role.trim().to_ascii_lowercase().as_str() {
624 "system" => "system",
625 "assistant" => "assistant",
626 _ => "user",
627 };
628 match self {
629 Self::Zephyr => out.push_str(&format!("<|{role}|>\n{body}</s>\n")),
630 Self::Llama3 => out.push_str(&format!(
631 "<|start_header_id|>{role}<|end_header_id|>\n\n{body}<|eot_id|>"
632 )),
633 Self::ChatMl { .. }
634 | Self::ChatMlQwen3
635 | Self::ChatMlQwen3NoThink
636 | Self::Qwen38
637 | Self::Qwen36
638 | Self::Qwen35 => {
639 unreachable!("ChatML returned above")
640 }
641 Self::None => unreachable!("plain model refused above"),
642 }
643 }
644 if !ends_in_assistant(turns) {
645 out.push_str(match self {
646 Self::Zephyr => "<|assistant|>\n",
647 Self::Llama3 => "<|start_header_id|>assistant<|end_header_id|>\n\n",
648 Self::ChatMl { .. }
649 | Self::ChatMlQwen3
650 | Self::ChatMlQwen3NoThink
651 | Self::Qwen38
652 | Self::Qwen36
653 | Self::Qwen35 => {
654 unreachable!("ChatML returned above")
655 }
656 Self::None => unreachable!("plain model refused above"),
657 });
658 }
659 Ok(out)
660 }
661}
662
663/// Role `tool` is refused on every `ChatTokenizer` formatting path (issue #310): untrusted tool
664/// output must enter through `tool_boundary::ToolConversation`. `ChatTemplate::render` and
665/// `try_render` stay upstream-exact (the #309 oracle uses them) and are not a safe route.
666pub fn refuse_tool_role(turns: &[(&str, &str)]) -> Result<(), TokenizerError> {
667 if turns
668 .iter()
669 .any(|(r, _)| r.trim().eq_ignore_ascii_case("tool"))
670 {
671 return Err(TokenizerError::ToolTurnRefused(
672 "role tool refused: use tool_boundary::ToolConversation".into(),
673 ));
674 }
675 Ok(())
676}
677
678/// Pure Rust wrapper around Hugging Face tokenizers with the model's chat template and
679/// end-of-sequence set. `from_file`/`from_bytes` give the TinyLlama defaults;
680/// `from_model_dir` reads them from the model directory.
681#[derive(Clone)]
682pub struct ChatTokenizer {
683 inner: tokenizers::Tokenizer,
684 template: ChatTemplate,
685 stop_token_ids: Vec<u32>,
686 max_context_len: usize,
687}
688
689/// The name this tokenizer had while it served TinyLlama only.
690pub type TinyLlamaTokenizer = ChatTokenizer;
691
692fn read_json(path: &Path) -> Result<Option<serde_json::Value>, TokenizerError> {
693 match std::fs::read_to_string(path) {
694 Ok(text) => serde_json::from_str(&text).map(Some).map_err(|e| {
695 TokenizerError::LoadError(format!("{} is not valid JSON: {}", path.display(), e))
696 }),
697 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
698 Err(e) => Err(TokenizerError::LoadError(format!(
699 "Failed to read {}: {}",
700 path.display(),
701 e
702 ))),
703 }
704}
705
706/// `eos_token_id` of a Hugging Face config as a list (it is a number or an array).
707pub fn eos_token_ids_from_json(value: &serde_json::Value) -> Option<Vec<u32>> {
708 match value.get("eos_token_id")? {
709 serde_json::Value::Number(n) => n.as_u64().map(|id| vec![id as u32]),
710 serde_json::Value::Array(items) => items
711 .iter()
712 .map(|v| v.as_u64().map(|id| id as u32))
713 .collect(),
714 _ => None,
715 }
716}
717
718impl ChatTokenizer {
719 /// Beginning of Sequence token ID pinned for TinyLlama (<s>).
720 pub const BOS_TOKEN_ID: u32 = 1;
721 /// End of Sequence token ID pinned for TinyLlama (</s>).
722 pub const EOS_TOKEN_ID: u32 = 2;
723 /// Unknown / Padding token ID pinned for TinyLlama (<unk>).
724 pub const UNK_TOKEN_ID: u32 = 0;
725 /// Maximum context window supported by TinyLlama-1.1B.
726 pub const MAX_CONTEXT_LEN: usize = 2048;
727
728 /// Loads tokenizer directly from a local tokenizer.json file.
729 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, TokenizerError> {
730 let p = path.as_ref();
731 let inner = tokenizers::Tokenizer::from_file(p).map_err(|e| {
732 TokenizerError::LoadError(format!("Failed to load from {}: {}", p.display(), e))
733 })?;
734 Ok(Self::tinyllama(inner))
735 }
736
737 /// Loads tokenizer directly from a JSON byte buffer.
738 pub fn from_bytes(bytes: &[u8]) -> Result<Self, TokenizerError> {
739 let inner = tokenizers::Tokenizer::from_bytes(bytes).map_err(|e| {
740 TokenizerError::LoadError(format!("Failed to parse tokenizer bytes: {}", e))
741 })?;
742 Ok(Self::tinyllama(inner))
743 }
744
745 fn tinyllama(inner: tokenizers::Tokenizer) -> Self {
746 Self {
747 inner,
748 template: ChatTemplate::Zephyr,
749 stop_token_ids: vec![Self::EOS_TOKEN_ID],
750 max_context_len: Self::MAX_CONTEXT_LEN,
751 }
752 }
753
754 /// Loads `tokenizer_json` (default `<dir>/tokenizer.json`) with the chat template and
755 /// end-of-sequence set of the model directory `dir`:
756 /// - template: detected from `chat_template` in `tokenizer_config.json`, else from
757 /// `chat_template.jinja`;
758 /// - stop set: `eos_token_id` of `generation_config.json`; without one, `eos_token_id` of
759 /// `config.json` (or of its `text_config`), preceded by the id of `tokenizer_config.json`
760 /// `eos_token` when that is not already in it (Qwen3.5-9B ships no generation config: its
761 /// text config names `<|endoftext|>` and its tokenizer `<|im_end|>`, the chat turn end);
762 /// - context limit: `max_position_embeddings` of `config.json`, or of its `text_config`
763 /// (default 2048).
764 pub fn from_model_dir(
765 dir: &Path,
766 tokenizer_json: Option<&Path>,
767 ) -> Result<Self, TokenizerError> {
768 let default_json = dir.join("tokenizer.json");
769 let mut tokenizer = Self::from_file(tokenizer_json.unwrap_or(&default_json))?;
770 // A present `chat_template` key must be a string; any other form (the HF list
771 // form, null, an object) is an unrecognized template and never falls back to plain.
772 let tokenizer_config = read_json(&dir.join("tokenizer_config.json"))?;
773 let config_template = match tokenizer_config
774 .as_ref()
775 .and_then(|c| c.get("chat_template"))
776 {
777 None => None,
778 Some(serde_json::Value::String(text)) => Some(text.clone()),
779 Some(other) => {
780 let found = match other {
781 serde_json::Value::Array(_) => "a list",
782 serde_json::Value::Object(_) => "an object",
783 serde_json::Value::Null => "null",
784 _ => "a non-string value",
785 };
786 return Err(TokenizerError::LoadError(format!(
787 "unrecognized chat template form in {}: expected a string, found {}",
788 dir.join("tokenizer_config.json").display(),
789 found
790 )));
791 }
792 };
793 let jinja_path = dir.join("chat_template.jinja");
794 let template_text = match config_template {
795 Some(text) => Some(text),
796 None if jinja_path.exists() => {
797 Some(std::fs::read_to_string(&jinja_path).map_err(|e| {
798 TokenizerError::LoadError(format!(
799 "unreadable chat template {}: {}",
800 jinja_path.display(),
801 e
802 ))
803 })?)
804 }
805 None => None,
806 };
807 // Plain state only when neither source exists; an existing template must be recognized.
808 tokenizer.template = match template_text {
809 Some(text) => ChatTemplate::detect(&text)?,
810 None => ChatTemplate::None,
811 };
812 let config = read_json(&dir.join("config.json"))?;
813 let stop = match read_json(&dir.join("generation_config.json"))?
814 .as_ref()
815 .and_then(eos_token_ids_from_json)
816 {
817 Some(stop) => Some(stop),
818 None => config
819 .as_ref()
820 .and_then(|c| {
821 eos_token_ids_from_json(c)
822 .or_else(|| c.get("text_config").and_then(eos_token_ids_from_json))
823 })
824 .map(|mut stop| {
825 let declared = tokenizer_config
826 .as_ref()
827 .and_then(|t| t.get("eos_token")?.as_str())
828 .and_then(|tok| tokenizer.token_to_id(tok));
829 if let Some(id) = declared.filter(|id| !stop.contains(id)) {
830 stop.insert(0, id);
831 }
832 stop
833 }),
834 }
835 .ok_or_else(|| {
836 TokenizerError::LoadError(format!(
837 "no eos_token_id in {}/generation_config.json or config.json",
838 dir.display()
839 ))
840 })?;
841 if stop.is_empty() {
842 return Err(TokenizerError::LoadError(format!(
843 "empty eos_token_id in {}",
844 dir.display()
845 )));
846 }
847 tokenizer.stop_token_ids = stop;
848 // Multimodal configs (Qwen3.8 `qwen3_5`) keep the language model's limit in `text_config`.
849 if let Some(max) = config
850 .as_ref()
851 .and_then(|c| {
852 c.get("max_position_embeddings")
853 .or_else(|| c.get("text_config")?.get("max_position_embeddings"))
854 })
855 .and_then(|v| v.as_u64())
856 {
857 tokenizer.max_context_len = max as usize;
858 }
859 Ok(tokenizer)
860 }
861
862 /// The chat layout this tokenizer renders.
863 pub fn template(&self) -> ChatTemplate {
864 self.template.clone()
865 }
866
867 /// Token ids that end generation (the model's `eos_token_id` set).
868 pub fn stop_token_ids(&self) -> &[u32] {
869 &self.stop_token_ids
870 }
871
872 /// Renders `(role, content)` turns with this model's chat template.
873 pub fn format_chat(&self, turns: &[(&str, &str)]) -> String {
874 refuse_tool_role(turns).expect("tool role refused");
875 self.template.render(turns)
876 }
877
878 /// Fallible [`ChatTokenizer::format_chat`]: refuses a plain model ("no chat template").
879 pub fn try_format_chat(&self, turns: &[(&str, &str)]) -> Result<String, TokenizerError> {
880 refuse_tool_role(turns)?;
881 self.template.try_render(turns)
882 }
883
884 /// [`Self::try_format_chat`] with the request's template switches (only the Qwen3.8 layout
885 /// reads them; every other layout renders exactly as without).
886 pub fn try_format_chat_with(
887 &self,
888 turns: &[(&str, &str)],
889 opts: &ChatOptions,
890 ) -> Result<String, TokenizerError> {
891 refuse_tool_role(turns)?;
892 self.template.try_render_with(turns, opts)
893 }
894
895 /// Formats a conversation according to the canonical TinyLlama chat template:
896 /// `<|system|>\n{system}</s>\n<|user|>\n{user}</s>\n<|assistant|>\n`
897 pub fn format_chat_prompt(&self, system: Option<&str>, user: &str) -> String {
898 Self::format_prompt(system, user)
899 }
900
901 /// Static formatter for the canonical TinyLlama chat template.
902 pub fn format_prompt(system: Option<&str>, user: &str) -> String {
903 match system {
904 Some(sys) if !sys.trim().is_empty() => {
905 format!(
906 "<|system|>\n{}</s>\n<|user|>\n{}</s>\n<|assistant|>\n",
907 sys.trim(),
908 user.trim()
909 )
910 }
911 _ => {
912 format!("<|user|>\n{}</s>\n<|assistant|>\n", user.trim())
913 }
914 }
915 }
916
917 /// Encodes text into token IDs including configured special tokens.
918 pub fn encode(&self, text: &str) -> Result<Vec<u32>, TokenizerError> {
919 self.encode_with_special(text, true)
920 }
921
922 /// Encodes text with explicit control over special tokens insertion.
923 pub fn encode_with_special(
924 &self,
925 text: &str,
926 add_special_tokens: bool,
927 ) -> Result<Vec<u32>, TokenizerError> {
928 let encoding = self
929 .inner
930 .encode(text, add_special_tokens)
931 .map_err(|e| TokenizerError::EncodeError(e.to_string()))?;
932 let tokens = encoding.get_ids().to_vec();
933 if tokens.len() > self.max_context_len {
934 return Err(TokenizerError::ContextLengthExceeded {
935 len: tokens.len(),
936 max: self.max_context_len,
937 });
938 }
939 Ok(tokens)
940 }
941
942 /// Decodes a sequence of token IDs back into recognizable UTF-8 text.
943 pub fn decode(&self, tokens: &[u32]) -> Result<String, TokenizerError> {
944 self.decode_opts(tokens, false)
945 }
946
947 /// Decodes tokens with option to skip special tokens.
948 pub fn decode_opts(
949 &self,
950 tokens: &[u32],
951 skip_special_tokens: bool,
952 ) -> Result<String, TokenizerError> {
953 self.inner
954 .decode(tokens, skip_special_tokens)
955 .map_err(|e| TokenizerError::DecodeError(e.to_string()))
956 }
957
958 /// Checks if a token ID signifies generation stopping (EOS).
959 pub fn is_eos(&self, token_id: u32) -> bool {
960 self.stop_token_ids.contains(&token_id)
961 }
962
963 /// Checks if a token ID signifies sequence beginning (BOS).
964 pub fn is_bos(&self, token_id: u32) -> bool {
965 token_id == Self::BOS_TOKEN_ID
966 }
967
968 /// Checks if a token is a terminal or stop token.
969 pub fn is_stop_token(&self, token_id: u32) -> bool {
970 token_id == Self::EOS_TOKEN_ID || token_id == Self::UNK_TOKEN_ID
971 }
972
973 /// Returns the vocabulary size of the underlying model.
974 pub fn vocab_size(&self) -> usize {
975 self.inner.get_vocab_size(true)
976 }
977
978 /// Returns the token ID for a given string token if present in vocabulary.
979 pub fn token_to_id(&self, token: &str) -> Option<u32> {
980 self.inner.token_to_id(token)
981 }
982
983 /// Returns the string representation for a given token ID.
984 pub fn id_to_token(&self, id: u32) -> Option<String> {
985 self.inner.id_to_token(id)
986 }
987
988 /// Returns a reference to the underlying tokenizers::Tokenizer.
989 pub fn inner(&self) -> &tokenizers::Tokenizer {
990 &self.inner
991 }
992}
993
994#[cfg(test)]
995mod tests {
996 use super::*;
997
998 #[test]
999 fn test_pinned_special_tokens() {
1000 assert_eq!(TinyLlamaTokenizer::BOS_TOKEN_ID, 1);
1001 assert_eq!(TinyLlamaTokenizer::EOS_TOKEN_ID, 2);
1002 assert_eq!(TinyLlamaTokenizer::UNK_TOKEN_ID, 0);
1003 assert_eq!(TinyLlamaTokenizer::MAX_CONTEXT_LEN, 2048);
1004 }
1005
1006 #[test]
1007 fn test_chat_template_with_system() {
1008 let system = "You are a sovereign AI assistant.";
1009 let user = "Explain the role of an operating system in one sentence.";
1010 let formatted = TinyLlamaTokenizer::format_prompt(Some(system), user);
1011
1012 let expected = "<|system|>\nYou are a sovereign AI assistant.</s>\n<|user|>\nExplain the role of an operating system in one sentence.</s>\n<|assistant|>\n";
1013 assert_eq!(formatted, expected);
1014 }
1015
1016 #[test]
1017 fn test_chat_template_without_system() {
1018 let user = "Hello TinyLlama!";
1019 let formatted = TinyLlamaTokenizer::format_prompt(None, user);
1020
1021 let expected = "<|user|>\nHello TinyLlama!</s>\n<|assistant|>\n";
1022 assert_eq!(formatted, expected);
1023 }
1024
1025 #[test]
1026 fn test_chat_template_with_empty_system() {
1027 let user = "Hello TinyLlama!";
1028 let formatted = TinyLlamaTokenizer::format_prompt(Some(" "), user);
1029
1030 let expected = "<|user|>\nHello TinyLlama!</s>\n<|assistant|>\n";
1031 assert_eq!(formatted, expected);
1032 }
1033
1034 #[test]
1035 fn test_stop_and_eos_token_checks() {
1036 // We can construct a mock tokenizer instance or test static methods
1037 assert_eq!(TinyLlamaTokenizer::EOS_TOKEN_ID, 2);
1038 assert_eq!(TinyLlamaTokenizer::BOS_TOKEN_ID, 1);
1039 assert_eq!(TinyLlamaTokenizer::UNK_TOKEN_ID, 0);
1040 }
1041
1042 /// HuggingFaceTB/SmolLM2-1.7B-Instruct tokenizer_config.json `chat_template` at revision
1043 /// 31b70e2e869a, verbatim (the decoded JSON string; its newlines are real newlines).
1044 const SMOLLM2_TEMPLATE: &str = "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}";
1045
1046 #[test]
1047 fn smollm2_template_is_chatml_with_its_default_system_message() {
1048 let t = ChatTemplate::detect(SMOLLM2_TEMPLATE).unwrap();
1049 assert_eq!(
1050 t.default_system(),
1051 Some("You are a helpful AI assistant named SmolLM, trained by Hugging Face")
1052 );
1053 assert!(t.name().starts_with("chatml"));
1054 // Expected strings: transformers 5.17.0 apply_chat_template(add_generation_prompt=True)
1055 // on the same messages with the pinned tokenizer_config.json (scratch run, outside
1056 // the repository).
1057 assert_eq!(
1058 t.render(&[("user", "Goal: X\nAuthorized workspace: /w")]),
1059 "<|im_start|>system\nYou are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>\n\
1060 <|im_start|>user\nGoal: X\nAuthorized workspace: /w<|im_end|>\n<|im_start|>assistant\n"
1061 );
1062 assert_eq!(
1063 t.render(&[("system", "S"), ("user", "U")]),
1064 "<|im_start|>system\nS<|im_end|>\n<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n"
1065 );
1066 // Contents verbatim: the template does not trim.
1067 assert!(t
1068 .render(&[("user", " Hi \n")])
1069 .contains("<|im_start|>user\n Hi \n<|im_end|>\n"));
1070 }
1071
1072 #[test]
1073 fn chatml_without_default_system_and_refusals() {
1074 let plain = SMOLLM2_TEMPLATE.replace(
1075 "{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>\n' }}{% endif %}",
1076 "",
1077 );
1078 let t = ChatTemplate::detect(&plain).unwrap();
1079 assert_eq!(t.default_system(), None);
1080 assert_eq!(
1081 t.render(&[("user", "U")]),
1082 "<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n"
1083 );
1084 // A ChatML template with other logic (tools, trimming) is refused, not approximated.
1085 let tools = SMOLLM2_TEMPLATE.replace(
1086 "{% for message in messages %}",
1087 "{% if tools %}{{ tools | tojson }}{% endif %}{% for message in messages %}",
1088 );
1089 let err = ChatTemplate::detect(&tools).unwrap_err().to_string();
1090 assert!(err.contains("unsupported ChatML"), "{err}");
1091 let trimmed = SMOLLM2_TEMPLATE.replace("message['content']", "message['content'] | trim");
1092 assert!(ChatTemplate::detect(&trimmed).is_err());
1093 // A default system message with a quote cannot be read as plain text.
1094 let quoted = SMOLLM2_TEMPLATE.replace("named SmolLM", "named 'SmolLM'");
1095 assert!(ChatTemplate::detect(&quoted).is_err());
1096 // Zephyr and Llama 3 detection is unchanged.
1097 assert_eq!(
1098 ChatTemplate::detect("<|user|> ... <|assistant|>").unwrap(),
1099 ChatTemplate::Zephyr
1100 );
1101 assert_eq!(
1102 ChatTemplate::detect("<|start_header_id|> <|eot_id|>").unwrap(),
1103 ChatTemplate::Llama3
1104 );
1105 assert!(ChatTemplate::detect("{{ messages }}").is_err());
1106 }
1107
1108 #[test]
1109 fn test_synthetic_tokenizer_roundtrip() {
1110 // Construct a minimal BPE tokenizer JSON for testing encode and decode
1111 let minimal_json = r#"{
1112 "version": "1.0",
1113 "truncation": null,
1114 "padding": null,
1115 "added_tokens": [
1116 {"id": 0, "content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
1117 {"id": 1, "content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
1118 {"id": 2, "content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}
1119 ],
1120 "normalizer": null,
1121 "pre_tokenizer": {"type": "Whitespace"},
1122 "post_processor": null,
1123 "decoder": null,
1124 "model": {
1125 "type": "WordLevel",
1126 "unk_token": "<unk>",
1127 "vocab": {
1128 "<unk>": 0,
1129 "<s>": 1,
1130 "</s>": 2,
1131 "hello": 3,
1132 "world": 4
1133 }
1134 }
1135 }"#;
1136
1137 let tokenizer = TinyLlamaTokenizer::from_bytes(minimal_json.as_bytes()).unwrap();
1138 assert_eq!(tokenizer.vocab_size(), 5);
1139 assert_eq!(tokenizer.token_to_id("hello"), Some(3));
1140 assert_eq!(tokenizer.token_to_id("world"), Some(4));
1141 assert_eq!(tokenizer.id_to_token(1), Some("<s>".to_string()));
1142 assert_eq!(tokenizer.id_to_token(2), Some("</s>".to_string()));
1143
1144 let tokens = tokenizer.encode("hello world").unwrap();
1145 assert_eq!(tokens, vec![3, 4]);
1146
1147 let decoded = tokenizer.decode(&tokens).unwrap();
1148 assert_eq!(decoded, "hello world");
1149 assert!(tokenizer.is_eos(2));
1150 assert!(!tokenizer.is_eos(3));
1151 assert!(tokenizer.is_bos(1));
1152 assert!(tokenizer.is_stop_token(2));
1153 assert!(tokenizer.is_stop_token(0));
1154 }
1155}