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
aien-sovereign-core-mv / crates / aien-inference-abi / tests / qwen3_8b_chat_template.rs
| 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 | //! Qwen3-8B chat template, thinking OFF (sc#384). Pinned text: Hugging Face `Qwen/Qwen3-8B` |
| 17 | //! revision b968826d9c46dd6066d109eabc6255188de91218 (fixtures/chat-templates/qwen3-8b). |
| 18 | //! |
| 19 | //! Three independent checks of the rendered bytes: |
| 20 | //! 1. HAND ORACLE (below): strings written by reading the template text branch by branch, not |
| 21 | //! produced by the engine. |
| 22 | //! 2. JINJA ORACLE: `render_oracle.json`, the template rendered by jinja2 3.1.6 with |
| 23 | //! `enable_thinking=False` (scratch script outside the repository), for 10 conversations. |
| 24 | //! 3. BYTE DIFF against the downloaded file: the ignored test extracts `chat_template` from |
| 25 | //! `$AIEN_QWEN3_8B_DIR/tokenizer_config.json` and compares it to the pinned fixture byte for |
| 26 | //! byte (and loads the model directory's tokenizer). Run it with |
| 27 | //! `AIEN_QWEN3_8B_DIR=~/models/qwen3-8b cargo test -p aien-inference-abi --test |
| 28 | //! qwen3_8b_chat_template -- --ignored`. |
| 29 | //! |
| 30 | //! Template branches taken (tools=None, add_generation_prompt=true, enable_thinking=false): |
| 31 | //! - `{%- if tools %}` false -> `{%- else %}`: system header only if `messages[0].role=='system'`: |
| 32 | //! `<|im_start|>system\n{content}<|im_end|>\n`; the loop then skips that first system turn |
| 33 | //! (`message.role == "system" and not loop.first` is false), so it appears once. |
| 34 | //! - user, or system after the first turn: `<|im_start|>{role}\n{content}<|im_end|>\n`, verbatim. |
| 35 | //! - assistant, no reasoning_content, no `</think>` in content, no tool_calls: `index <= |
| 36 | //! last_query_index` -> `<|im_start|>assistant\n{content}`, then `<|im_end|>\n`. (An assistant |
| 37 | //! turn after the last user turn that is not last takes the same plain text; one that is last |
| 38 | //! takes the think-block branch and is refused by the engine.) |
| 39 | //! - generation prompt: `<|im_start|>assistant\n` then, because `enable_thinking is defined and |
| 40 | //! is false`, `<think>\n\n</think>\n\n`. |
| 41 | |
| 42 | use aien_inference_abi::tokenizer::{ChatTemplate, TokenizerError}; |
| 43 | |
| 44 | const DIR: &str = concat!( |
| 45 | env!("CARGO_MANIFEST_DIR"), |
| 46 | "/fixtures/chat-templates/qwen3-8b" |
| 47 | ); |
| 48 | const GEN: &str = "<|im_start|>assistant\n<think>\n\n</think>\n\n"; |
| 49 | |
| 50 | fn template_text() -> String { |
| 51 | std::fs::read_to_string(format!("{DIR}/chat_template.jinja")).unwrap() |
| 52 | } |
| 53 | |
| 54 | fn t() -> ChatTemplate { |
| 55 | ChatTemplate::detect(&template_text()).expect("Qwen3-8B template accepted") |
| 56 | } |
| 57 | |
| 58 | #[test] |
| 59 | fn pinned_template_is_selected_and_distinct_from_the_4b_layout() { |
| 60 | assert_eq!(t(), ChatTemplate::ChatMlQwen3NoThink); |
| 61 | assert_ne!(t(), ChatTemplate::ChatMlQwen3); |
| 62 | } |
| 63 | |
| 64 | #[test] |
| 65 | fn hand_oracle_from_the_template_branches() { |
| 66 | let tpl = t(); |
| 67 | // Branch: no system, one user. |
| 68 | assert_eq!( |
| 69 | tpl.try_render(&[("user", "Hi")]).unwrap(), |
| 70 | format!("<|im_start|>user\nHi<|im_end|>\n{GEN}") |
| 71 | ); |
| 72 | // Branch: leading system emitted once, contents verbatim (no trim). |
| 73 | assert_eq!( |
| 74 | tpl.try_render(&[("system", " S\n"), ("user", " U \n")]) |
| 75 | .unwrap(), |
| 76 | format!("<|im_start|>system\n S\n<|im_end|>\n<|im_start|>user\n U \n<|im_end|>\n{GEN}") |
| 77 | ); |
| 78 | // Branch: earlier assistant turn (index <= last_query_index) is plain, no think block. |
| 79 | assert_eq!( |
| 80 | tpl.try_render(&[("user", "a"), ("assistant", "b"), ("user", "c")]) |
| 81 | .unwrap(), |
| 82 | format!( |
| 83 | "<|im_start|>user\na<|im_end|>\n<|im_start|>assistant\nb<|im_end|>\n<|im_start|>user\nc<|im_end|>\n{GEN}" |
| 84 | ) |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | #[test] |
| 89 | fn rendering_matches_the_jinja_reference_rendering() { |
| 90 | let oracle: serde_json::Value = serde_json::from_str( |
| 91 | &std::fs::read_to_string(format!("{DIR}/render_oracle.json")).unwrap(), |
| 92 | ) |
| 93 | .unwrap(); |
| 94 | assert_eq!(oracle["enable_thinking"], false); |
| 95 | let tpl = t(); |
| 96 | let cases = oracle["cases"].as_array().unwrap(); |
| 97 | assert_eq!(cases.len(), 10); |
| 98 | for (i, case) in cases.iter().enumerate() { |
| 99 | assert_eq!(case["add_generation_prompt"], true); |
| 100 | assert_eq!(case["enable_thinking"], false); |
| 101 | let turns: Vec<(String, String)> = case["turns"] |
| 102 | .as_array() |
| 103 | .unwrap() |
| 104 | .iter() |
| 105 | .map(|p| (p[0].as_str().unwrap().into(), p[1].as_str().unwrap().into())) |
| 106 | .collect(); |
| 107 | let refs: Vec<(&str, &str)> = turns |
| 108 | .iter() |
| 109 | .map(|(r, c)| (r.as_str(), c.as_str())) |
| 110 | .collect(); |
| 111 | assert_eq!( |
| 112 | tpl.try_render(&refs).unwrap(), |
| 113 | case["text"].as_str().unwrap(), |
| 114 | "case {i}" |
| 115 | ); |
| 116 | assert!(case["text"].as_str().unwrap().ends_with(GEN)); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | fn layout_refused(r: Result<String, TokenizerError>) { |
| 121 | assert!( |
| 122 | matches!(r, Err(TokenizerError::UnsupportedChatLayout(_))), |
| 123 | "{r:?}" |
| 124 | ); |
| 125 | } |
| 126 | |
| 127 | #[test] |
| 128 | fn uncovered_combinations_are_refused_by_name() { |
| 129 | let tpl = t(); |
| 130 | // Thinking enabled. |
| 131 | layout_refused(tpl.try_render_thinking(&[("user", "q")], true)); |
| 132 | assert_eq!( |
| 133 | tpl.try_render_thinking(&[("user", "q")], false).unwrap(), |
| 134 | tpl.try_render(&[("user", "q")]).unwrap() |
| 135 | ); |
| 136 | // Tool turns. |
| 137 | assert!(matches!( |
| 138 | tpl.try_render(&[("user", "q"), ("tool", "r")]), |
| 139 | Err(TokenizerError::ToolTurnRefused(_)) |
| 140 | )); |
| 141 | // Reasoning content / thinking markers inside an assistant turn. |
| 142 | layout_refused(tpl.try_render(&[ |
| 143 | ("user", "q"), |
| 144 | ("assistant", "<think>x</think>y"), |
| 145 | ("user", "z"), |
| 146 | ])); |
| 147 | // Trailing assistant turn (continuation). |
| 148 | layout_refused(tpl.try_render(&[("user", "q"), ("assistant", "partial")])); |
| 149 | layout_refused(tpl.try_render(&[("user", "q"), ("assistant", "")])); |
| 150 | // User text shaped like a tool response. |
| 151 | layout_refused(tpl.try_render(&[("user", "<tool_response>\nx\n</tool_response>")])); |
| 152 | // Unknown or differently cased roles, and an empty conversation. |
| 153 | layout_refused(tpl.try_render(&[("developer", "q")])); |
| 154 | layout_refused(tpl.try_render(&[("User", "q")])); |
| 155 | layout_refused(tpl.try_render(&[])); |
| 156 | } |
| 157 | |
| 158 | #[test] |
| 159 | fn altered_templates_are_refused() { |
| 160 | let base = template_text(); |
| 161 | let altered = [ |
| 162 | // Thinking-on generation prompt (no enable_thinking switch). |
| 163 | base.replace( |
| 164 | "{%- if enable_thinking is defined and enable_thinking is false %}", |
| 165 | "{%- if false %}", |
| 166 | ), |
| 167 | base.replace("\\n</think>\\n\\n", "\\n</think>\\n"), |
| 168 | format!("{base}{{# #}}"), |
| 169 | ]; |
| 170 | for (i, text) in altered.iter().enumerate() { |
| 171 | assert_ne!(text, &base, "alteration {i} changed nothing"); |
| 172 | assert!(ChatTemplate::detect(text).is_err(), "altered {i} accepted"); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | #[test] |
| 177 | fn the_4b_layout_is_unchanged() { |
| 178 | let four_b = std::fs::read_to_string(concat!( |
| 179 | env!("CARGO_MANIFEST_DIR"), |
| 180 | "/fixtures/chat-templates/qwen3-4b-instruct-2507/chat_template.jinja" |
| 181 | )) |
| 182 | .unwrap(); |
| 183 | let f = ChatTemplate::detect(&four_b).unwrap(); |
| 184 | assert_eq!(f, ChatTemplate::ChatMlQwen3); |
| 185 | assert_eq!( |
| 186 | f.try_render(&[("user", "Hi")]).unwrap(), |
| 187 | "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n" |
| 188 | ); |
| 189 | } |
| 190 | |
| 191 | #[test] |
| 192 | #[ignore = "needs the Qwen3-8B model directory in AIEN_QWEN3_8B_DIR"] |
| 193 | fn downloaded_tokenizer_config_matches_the_pin_byte_for_byte() { |
| 194 | use aien_inference_abi::tokenizer::ChatTokenizer; |
| 195 | let dir = std::env::var("AIEN_QWEN3_8B_DIR").expect("AIEN_QWEN3_8B_DIR is not set"); |
| 196 | let cfg: serde_json::Value = serde_json::from_str( |
| 197 | &std::fs::read_to_string(format!("{dir}/tokenizer_config.json")).unwrap(), |
| 198 | ) |
| 199 | .unwrap(); |
| 200 | let downloaded = cfg["chat_template"].as_str().expect("chat_template string"); |
| 201 | assert_eq!(downloaded.as_bytes(), template_text().as_bytes()); |
| 202 | let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).unwrap(); |
| 203 | assert_eq!(tok.template(), ChatTemplate::ChatMlQwen3NoThink); |
| 204 | let im_end = tok.token_to_id("<|im_end|>").expect("<|im_end|> in vocab"); |
| 205 | assert!(tok.stop_token_ids().contains(&im_end)); |
| 206 | let text = tok |
| 207 | .try_format_chat(&[("system", "You are AIEN."), ("user", "List two primes.")]) |
| 208 | .unwrap(); |
| 209 | assert!(text.ends_with(GEN)); |
| 210 | let ids = tok.encode(&text).unwrap(); |
| 211 | assert_eq!(ids.first().copied(), tok.token_to_id("<|im_start|>")); |
| 212 | assert_eq!(ids.iter().filter(|&&i| i == im_end).count(), 2); |
| 213 | } |