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

299 lines · 12869 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//! NEXT-PHASE-1 v3: the proposal request goes through the model's own chat
17//! template. Source: TinyLlama-1.1B-Chat-v1.0 tokenizer_config.json
18//! (sha256 7b41ba7d0eb91e77914ca3dafde559ea3e19878769b7e68409e89bed5222e77a),
19//! field `chat_template`, rendered with the Hugging Face settings
20//! (trim_blocks, lstrip_blocks): per message `'<|' + role + '|>\n' + content
21//! + eos_token` followed by the newline after the expression, then
22//! `'<|assistant|>'` and its newline when a generation prompt is asked for.
23
24use aien_inference_abi::TinyLlamaTokenizer;
25use aien_runtime::control::{format_tinyllama_chat, ChatTurn};
26
27fn turn(role: &str, content: &str) -> ChatTurn {
28 ChatTurn {
29 role: role.into(),
30 content: content.into(),
31 }
32}
33
34/// The template as the tokenizer_config.json jinja renders it, by hand.
35fn rendered_by_template(messages: &[(&str, &str)]) -> String {
36 let mut out = String::new();
37 for (role, content) in messages {
38 out.push_str(&format!("<|{role}|>\n{content}</s>\n"));
39 }
40 out.push_str("<|assistant|>\n");
41 out
42}
43
44const V2_PROMPT: &str = "Goal: Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.\nAuthorized workspace: /tmp/ws\nTop-level entries: README.md, docs\nPropose exactly one file change inside the workspace.\nAnswer in exactly this format and nothing else:\nfilename: <relative path>\n<the complete new file content>";
45
46#[test]
47fn streamturn_formatting_matches_the_model_template() {
48 let ours = format_tinyllama_chat(&[turn("user", V2_PROMPT)]).expect("chat");
49 assert_eq!(ours, rendered_by_template(&[("user", V2_PROMPT)]));
50 let with_system =
51 format_tinyllama_chat(&[turn("system", "S"), turn("user", "U")]).expect("chat");
52 assert_eq!(
53 with_system,
54 rendered_by_template(&[("system", "S"), ("user", "U")])
55 );
56}
57
58/// With the real tokenizer (AIEN_TOKENIZER_PATH): BOS first, and `</s>` in the
59/// rendered text becomes the single EOS token id 2, not the characters.
60#[test]
61fn template_encodes_bos_and_one_eos_token() {
62 let Ok(path) = std::env::var("AIEN_TOKENIZER_PATH") else {
63 eprintln!("AIEN_TOKENIZER_PATH not set: token check skipped");
64 return;
65 };
66 let tok = TinyLlamaTokenizer::from_file(path).expect("tokenizer");
67 let ids = tok
68 .encode(&format_tinyllama_chat(&[turn("user", V2_PROMPT)]).expect("chat"))
69 .expect("encode");
70 eprintln!("template ids ({}): {:?}", ids.len(), ids);
71 assert_eq!(ids[0], TinyLlamaTokenizer::BOS_TOKEN_ID);
72 let eos: Vec<usize> = ids
73 .iter()
74 .enumerate()
75 .filter(|(_, &t)| t == TinyLlamaTokenizer::EOS_TOKEN_ID)
76 .map(|(i, _)| i)
77 .collect();
78 assert_eq!(eos.len(), 1, "exactly one EOS (the user turn end)");
79}
80
81/// Prompt sizes behind the ACCEPTANCE-v3 budget arithmetic (printed; the
82/// assertion only guards the 2-chunk assumption: at most 256 prompt tokens).
83#[test]
84fn proposal_prompt_token_counts() {
85 let Ok(path) = std::env::var("AIEN_TOKENIZER_PATH") else {
86 eprintln!("AIEN_TOKENIZER_PATH not set: token count skipped");
87 return;
88 };
89 let tok = TinyLlamaTokenizer::from_file(path).expect("tokenizer");
90 let goal = "Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.";
91 let base = aien_runtime::compose::rederive::proposal_prompt(goal);
92 let retry = aien_runtime::compose::rederive::retry_prompt(
93 &base,
94 "no filename line: the first line must be 'filename: <relative path>'",
95 );
96 for (name, p) in [("base", &base), ("retry", &retry)] {
97 let n = tok
98 .encode(&format_tinyllama_chat(&[turn("user", p)]).expect("chat"))
99 .expect("encode")
100 .len();
101 eprintln!("{name} prompt tokens: {n}");
102 assert!(n <= 256);
103 }
104}
105
106/// ACCEPTANCE-v4 2(1): the bytes sent end with the assistant marker, its
107/// newline and the literal prefix "filename:" (no trailing space since the v5
108/// engine cut); nothing follows the colon.
109#[test]
110fn assistant_prefix_follows_the_assistant_marker() {
111 use aien_inference_abi::ChatTemplate;
112 use aien_runtime::check_file_proposal;
113 use aien_runtime::compose::rederive::{compose_assistant_prefix, COMPOSE_ASSISTANT_PREFIX};
114 assert_eq!(COMPOSE_ASSISTANT_PREFIX, "filename:");
115 // The per-template seam keeps Zephyr and Llama 3 byte-identical to the v5 value.
116 assert_eq!(
117 compose_assistant_prefix(&ChatTemplate::Zephyr).as_bytes(),
118 b"filename:"
119 );
120 assert_eq!(
121 compose_assistant_prefix(&ChatTemplate::Llama3).as_bytes(),
122 b"filename:"
123 );
124 let sent = format!(
125 "{}{}",
126 format_tinyllama_chat(&[turn("user", V2_PROMPT)]).expect("chat"),
127 COMPOSE_ASSISTANT_PREFIX
128 );
129 assert!(sent.starts_with("<|user|>\nGoal: "));
130 assert!(sent.ends_with("</s>\n<|assistant|>\nfilename:"));
131 // parser unchanged: it reads prefix + generated text
132 let read = |generated: &str| format!("{COMPOSE_ASSISTANT_PREFIX}{generated}");
133 let ok = check_file_proposal(&read(
134 " NOTES.md\nEvery change stays inside the workspace.\n",
135 ))
136 .expect("path + content parses");
137 assert_eq!(ok.path, "NOTES.md");
138 assert!(check_file_proposal(&read("NOTES.md\n"))
139 .unwrap_err()
140 .contains("empty content"));
141 assert!(check_file_proposal(&read("../x\ny\n"))
142 .unwrap_err()
143 .contains("outside the workspace"));
144 if let Ok(path) = std::env::var("AIEN_TOKENIZER_PATH") {
145 let tok = TinyLlamaTokenizer::from_file(path).expect("tokenizer");
146 let ids = tok.encode(&sent).expect("encode");
147 eprintln!(
148 "prefixed prompt tokens: {} tail {:?}",
149 ids.len(),
150 &ids[ids.len() - 6..]
151 );
152 assert_eq!(&ids[ids.len() - 3..], &[13, 9507, 29901]);
153 }
154}
155
156/// ACCEPTANCE-v4 2(2): the warm-up prompt spans more than one 128-token
157/// prefill chunk.
158#[test]
159fn warm_up_prompt_spans_two_prefill_chunks() {
160 let Ok(path) = std::env::var("AIEN_TOKENIZER_PATH") else {
161 eprintln!("AIEN_TOKENIZER_PATH not set: warm-up length check skipped");
162 return;
163 };
164 let tok = TinyLlamaTokenizer::from_file(path).expect("tokenizer");
165 let n = tok
166 .encode(
167 &format_tinyllama_chat(&[turn("user", aien_runtime::server::WARM_UP_TEXT)])
168 .expect("chat"),
169 )
170 .expect("encode")
171 .len();
172 eprintln!("warm-up prompt tokens: {n}");
173 assert!(n > 128 && n <= 256, "{n}");
174}
175
176/// Llama 3 instruct layout (v5 engine cut): header, blank line, content, `<|eot_id|>`, then
177/// the assistant header; no system block, no BOS in the text.
178#[test]
179fn llama3_template_renders_the_instruct_layout() {
180 use aien_inference_abi::ChatTemplate;
181 use aien_runtime::control::format_chat;
182 let text = format_chat(ChatTemplate::Llama3, &[turn("user", " Hi there \n")]).expect("chat");
183 assert_eq!(
184 text,
185 "<|start_header_id|>user<|end_header_id|>\n\nHi there<|eot_id|>\
186 <|start_header_id|>assistant<|end_header_id|>\n\n"
187 );
188 // TinyLlama keeps the zephyr layout, byte for byte.
189 assert_eq!(
190 format_chat(ChatTemplate::Zephyr, &[turn("user", V2_PROMPT)]).expect("chat"),
191 format_tinyllama_chat(&[turn("user", V2_PROMPT)]).expect("chat")
192 );
193}
194
195/// With a Llama 3 model directory (`AIEN_LLAMA3_DIR`): the template is detected from the
196/// model's own files, encoding adds exactly one `<|begin_of_text|>` (128000), the stop set
197/// is the generation_config eos list, and the compose prefix is the last two tokens.
198#[test]
199fn llama3_model_dir_tokenizer_has_one_bos_and_eos_list() {
200 let Ok(dir) = std::env::var("AIEN_LLAMA3_DIR") else {
201 eprintln!("AIEN_LLAMA3_DIR not set: Llama 3 tokenizer check skipped");
202 return;
203 };
204 use aien_inference_abi::{ChatTemplate, ChatTokenizer};
205 use aien_runtime::compose::rederive::COMPOSE_ASSISTANT_PREFIX;
206 use aien_runtime::control::format_chat;
207 let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).expect("tokenizer");
208 assert_eq!(tok.template(), ChatTemplate::Llama3);
209 assert_eq!(tok.stop_token_ids(), &[128001, 128008, 128009]);
210 let text = format!(
211 "{}{COMPOSE_ASSISTANT_PREFIX}",
212 format_chat(tok.template(), &[turn("user", V2_PROMPT)]).expect("chat")
213 );
214 let ids = tok.encode(&text).expect("encode");
215 assert_eq!(ids[0], 128000);
216 assert_eq!(ids.iter().filter(|&&t| t == 128000).count(), 1);
217 // "<|start_header_id|>user<|end_header_id|>\n\n" after the BOS
218 assert_eq!(&ids[1..5], &[128006, 882, 128007, 271]);
219 // "<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\nfilename:"
220 let tail = &ids[ids.len() - 7..];
221 assert_eq!(&tail[..5], &[128009, 128006, 78191, 128007, 271]);
222 assert_eq!(tok.decode(&tail[5..]).unwrap(), "filename:");
223}
224
225/// ChatML (SmolLM2-Instruct): the compose prefix for the ChatML template, and the bytes sent
226/// end with the publisher's generation prompt followed directly by it.
227#[test]
228fn chatml_compose_prefix_follows_the_im_start_assistant_marker() {
229 use aien_inference_abi::ChatTemplate;
230 use aien_runtime::compose::rederive::compose_assistant_prefix;
231 use aien_runtime::control::format_chat;
232 let chatml = ChatTemplate::ChatMl {
233 default_system: Some(
234 "You are a helpful AI assistant named SmolLM, trained by Hugging Face".into(),
235 ),
236 };
237 assert_eq!(compose_assistant_prefix(&chatml).as_bytes(), b"filename:");
238 assert_eq!(
239 compose_assistant_prefix(&ChatTemplate::ChatMl {
240 default_system: None
241 })
242 .as_bytes(),
243 b"filename:"
244 );
245 let sent = format!(
246 "{}{}",
247 format_chat(chatml, &[turn("user", V2_PROMPT)]).expect("chat"),
248 compose_assistant_prefix(&ChatTemplate::ChatMl {
249 default_system: None
250 })
251 );
252 assert!(sent.starts_with("<|im_start|>system\nYou are a helpful AI assistant named SmolLM"));
253 assert!(sent.ends_with("<|im_end|>\n<|im_start|>assistant\nfilename:"));
254}
255
256/// With the pinned SmolLM2-1.7B-Instruct directory (`AIEN_SMOLLM2_DIR`, revision
257/// 31b70e2e869a): the template is detected from the model's own files, the stop set is
258/// `<|im_end|>` (2), encoding adds no BOS, and the prompt ids equal the ids of transformers
259/// 5.17.0 `apply_chat_template(tokenize=True, add_generation_prompt=True)` on the same message.
260#[test]
261fn smollm2_model_dir_tokenizer_matches_the_publisher_template_ids() {
262 let Ok(dir) = std::env::var("AIEN_SMOLLM2_DIR") else {
263 eprintln!("AIEN_SMOLLM2_DIR not set: SmolLM2 tokenizer check skipped");
264 return;
265 };
266 use aien_inference_abi::ChatTokenizer;
267 use aien_runtime::compose::rederive::compose_assistant_prefix;
268 use aien_runtime::control::format_chat;
269 let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).expect("tokenizer");
270 assert!(tok.template().name().starts_with("chatml"));
271 assert_eq!(
272 tok.template().default_system(),
273 Some("You are a helpful AI assistant named SmolLM, trained by Hugging Face")
274 );
275 assert_eq!(tok.stop_token_ids(), &[2]);
276 assert_eq!(tok.token_to_id("<|im_start|>"), Some(1));
277 assert_eq!(tok.token_to_id("<|im_end|>"), Some(2));
278 let text = format_chat(
279 tok.template(),
280 &[turn("user", "Goal: X\nAuthorized workspace: /w")],
281 )
282 .expect("chat");
283 let ids = tok.encode(&text).expect("encode");
284 let hf: [u32; 40] = [
285 1, 9690, 198, 2683, 359, 253, 5356, 5646, 11173, 3365, 3511, 308, 34519, 28, 7018, 411,
286 407, 19712, 8182, 2, 198, 1, 4093, 198, 44474, 42, 2273, 198, 15051, 1005, 26344, 42, 2272,
287 103, 2, 198, 1, 520, 9531, 198,
288 ];
289 assert_eq!(ids, hf);
290 // "filename:" is two tokens and ends on the colon.
291 let with_prefix = tok
292 .encode(&format!(
293 "{text}{}",
294 compose_assistant_prefix(&tok.template())
295 ))
296 .expect("encode");
297 assert_eq!(&with_prefix[..40], &hf);
298 assert_eq!(&with_prefix[40..], &[5805, 42]);
299}