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 / tests / qwen3_chat_template.rs

159 lines · 6057 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//! Qwen3-4B-Instruct-2507 chat template: the pinned template text is recognized, the engine's
17//! rendering equals the reference Jinja rendering (fixtures/chat-templates/.../render_oracle.json)
18//! for every recorded conversation, and any altered Qwen template is refused.
19
20use aien_inference_abi::tokenizer::ChatTemplate;
21
22const DIR: &str = concat!(
23 env!("CARGO_MANIFEST_DIR"),
24 "/fixtures/chat-templates/qwen3-4b-instruct-2507"
25);
26
27fn template() -> String {
28 std::fs::read_to_string(format!("{DIR}/chat_template.jinja")).unwrap()
29}
30
31#[test]
32fn pinned_template_is_qwen3_chatml_without_default_system() {
33 let t = ChatTemplate::detect(&template()).expect("Qwen3-4B-Instruct-2507 template accepted");
34 assert_eq!(t, ChatTemplate::ChatMlQwen3);
35 assert_eq!(t.default_system(), None);
36}
37
38#[test]
39fn rendering_matches_the_reference_jinja_rendering() {
40 let oracle: serde_json::Value = serde_json::from_str(
41 &std::fs::read_to_string(format!("{DIR}/render_oracle.json")).unwrap(),
42 )
43 .unwrap();
44 let t = ChatTemplate::detect(&template()).unwrap();
45 let cases = oracle["cases"].as_array().unwrap();
46 assert_eq!(cases.len(), 12);
47 for (i, case) in cases.iter().enumerate() {
48 let turns: Vec<(String, String)> = case["turns"]
49 .as_array()
50 .unwrap()
51 .iter()
52 .map(|p| {
53 (
54 p[0].as_str().unwrap().to_string(),
55 p[1].as_str().unwrap().to_string(),
56 )
57 })
58 .collect();
59 let refs: Vec<(&str, &str)> = turns
60 .iter()
61 .map(|(r, c)| (r.as_str(), c.as_str()))
62 .collect();
63 let ends_in_assistant = refs
64 .last()
65 .is_some_and(|(r, c)| *r == "assistant" && !c.trim().is_empty());
66 // The engine opens a generation prompt unless the last turn is a non-empty assistant
67 // turn; the oracle case records which of the two it rendered.
68 assert_eq!(
69 case["add_generation_prompt"].as_bool().unwrap(),
70 !ends_in_assistant,
71 "case {i}: oracle generated with the other generation-prompt setting"
72 );
73 assert_eq!(
74 t.try_render(&refs).unwrap(),
75 case["text"].as_str().unwrap(),
76 "case {i}"
77 );
78 }
79}
80
81#[test]
82fn altered_qwen_templates_are_refused() {
83 let base = template();
84 let altered = [
85 // Qwen3-4B (original) style thinking tail after the generation prompt.
86 base.replace(
87 "{{- '<|im_start|>assistant\\n' }}",
88 "{{- '<|im_start|>assistant\\n<think>\\n\\n</think>\\n\\n' }}",
89 ),
90 // Contents trimmed.
91 base.replace(
92 "{%- set content = message.content %}",
93 "{%- set content = message.content | trim %}",
94 ),
95 // A default system message added.
96 base.replacen(
97 "{%- else %}",
98 "{%- else %}\n {{- '<|im_start|>system\\nYou are Qwen.<|im_end|>\\n' }}",
99 1,
100 ),
101 // One byte appended inside the template.
102 format!("{base}{{# #}}"),
103 ];
104 for (i, text) in altered.iter().enumerate() {
105 assert_ne!(text, &base, "alteration {i} did not change the template");
106 assert!(
107 ChatTemplate::detect(text).is_err(),
108 "altered template {i} was accepted"
109 );
110 }
111}
112
113/// The real model directory (weights not needed): `AIEN_QWEN3_DIR=<dir> cargo test -p
114/// aien-inference-abi --test qwen3_chat_template -- --ignored`. Fails, never skips, when unset.
115#[test]
116#[ignore = "needs the Qwen3-4B-Instruct-2507 model directory in AIEN_QWEN3_DIR"]
117fn real_model_dir_loads_with_the_pinned_template() {
118 use aien_inference_abi::tokenizer::ChatTokenizer;
119 let dir = std::env::var("AIEN_QWEN3_DIR").expect("AIEN_QWEN3_DIR is not set");
120 let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).unwrap();
121 assert_eq!(tok.template(), ChatTemplate::ChatMlQwen3);
122 let im_end = tok.token_to_id("<|im_end|>").expect("<|im_end|> in vocab");
123 assert!(
124 tok.stop_token_ids().contains(&im_end),
125 "<|im_end|> must stop generation"
126 );
127 let text = tok
128 .try_format_chat(&[("system", "You are AIEN."), ("user", "List two primes.")])
129 .unwrap();
130 let ids = tok.encode(&text).unwrap();
131 assert_eq!(
132 ids.first().copied(),
133 tok.token_to_id("<|im_start|>"),
134 "no BOS is added"
135 );
136 assert_eq!(ids.iter().filter(|&&t| t == im_end).count(), 2);
137}
138
139/// Other ChatML models (SmolLM2, plain ChatML) keep their layout: role `tool` is still a plain
140/// user turn there, and the non-tool roles render the same as for Qwen3.
141#[test]
142fn plain_chatml_is_unchanged_and_shares_non_tool_roles_with_qwen3() {
143 let plain = ChatTemplate::ChatMl {
144 default_system: None,
145 };
146 let turns = [("user", "q"), ("tool", "r"), ("tool", "s")];
147 assert_eq!(
148 plain.try_render(&turns).unwrap(),
149 "<|im_start|>user\nq<|im_end|>\n<|im_start|>user\nr<|im_end|>\n<|im_start|>user\ns<|im_end|>\n<|im_start|>assistant\n"
150 );
151 let qwen = ChatTemplate::detect(&template()).unwrap();
152 let no_tool = [
153 ("system", "S"),
154 ("user", "U"),
155 ("assistant", "A"),
156 ("user", "V"),
157 ];
158 assert_eq!(plain.try_render(&no_tool), qwen.try_render(&no_tool));
159}