diff --git a/.crumb b/.crumb
index 6cc3cb07..c7c777e6 100644
--- a/.crumb
+++ b/.crumb
@@ -64,8 +64,8 @@
"generated": {
"children": [
{
- "digest": "de59c21bf8b5819007225986edf7a75dbe93c1203686e619e72e17a6799fa127",
- "last_commit": "8a05752",
+ "digest": "14ad22b926c21034daa6cfc2108a3bcd9f5dd6256231dd5d16576951eec2d805",
+ "last_commit": "f487c4a",
"name": "scripts",
"purpose": ""
},
@@ -76,15 +76,15 @@
"purpose": ""
}
],
- "children_root": "sha256:9b69c98f2b943ef9c4a3768e892e02b1856c6bd53647de0688f375e86e964ee1",
- "compiled_at": "2026-10-11T14:52:45Z",
+ "children_root": "sha256:80534ea6daebd609b6ed1ee21d502fa008beba453f59e85a148097a322b63b4a",
+ "compiled_at": "2026-10-11T15:06:17Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:499b335b430cb6b0eba2b67e02b546f09639e1c8441bfa1e4e5d41f5063367d5",
+ "digest": "sha256:df1d06a46a68a7e07b646ef5305a06eb8aa0939aaa778de8aa04568028c5c46c",
"evidence_files": 187,
"evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280",
- "files": 3556,
- "generated_at_commit": "1d222e14f5d423bec85fd5c68bc68e31d5b66f75",
- "source_tree": "sha256:f839a1896f0c478e14324248127c5afd8970e669c2f0aa99e28fd0e1600a5ce2"
+ "files": 3566,
+ "generated_at_commit": "f487c4a95e7a012598d8befc931c45f9466f9c4a",
+ "source_tree": "sha256:2d00fbde10a457e30ed0fe70a10befe2b95334b3afc6b0dbabe8839a6e45ce96"
}
},
"history": [],
diff --git a/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/LICENSE b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/LICENSE
new file mode 100644
index 00000000..6634c8cc
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2024 Alibaba Cloud
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/PROVENANCE.md b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/PROVENANCE.md
new file mode 100644
index 00000000..a9a9cf92
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/PROVENANCE.md
@@ -0,0 +1,15 @@
+# Qwen3-8B chat template (pinned)
+
+- Source: Hugging Face `Qwen/Qwen3-8B` revision b968826d9c46dd6066d109eabc6255188de91218,
+ `tokenizer_config.json` field `chat_template`, written byte for byte (no trailing newline) to `chat_template.jinja`.
+- The upstream file was fetched at that exact revision
+ (`https://huggingface.co/Qwen/Qwen3-8B/raw/b968826d9c46dd6066d109eabc6255188de91218/tokenizer_config.json`)
+ and is byte-identical to `~/models/qwen3-8b/tokenizer_config.json` (the weights lane's download).
+- Licence: Apache-2.0, upstream `LICENSE` copied unchanged (identical to the Qwen3-8B model folder's LICENSE). Not relicensed.
+- sha256 chat_template.jinja: a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8
+- sha256 upstream tokenizer_config.json: d5d09f07b48c3086c508b30d1c9114bd1189145b74e982a265350c923acd8101
+- `render_oracle.json`: the template rendered by the reference engine, jinja2 3.1.6
+ `ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)` (the Hugging Face transformers configuration),
+ `tools=None`, `add_generation_prompt=True`, `enable_thinking=False`, 10 conversations. Produced once with a scratch
+ script outside this repository (no Python in the repository); the Rust test compares the engine's rendering to it.
+- The engine renders only the `enable_thinking=false` form (`ChatTemplate::ChatMlQwen3NoThink`); other layouts are refused.
diff --git a/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/chat_template.jinja b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/chat_template.jinja
new file mode 100644
index 00000000..01be9b30
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/chat_template.jinja
@@ -0,0 +1,89 @@
+{%- if tools %}
+ {{- '<|im_start|>system\n' }}
+ {%- if messages[0].role == 'system' %}
+ {{- messages[0].content + '\n\n' }}
+ {%- endif %}
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }}
+ {%- for tool in tools %}
+ {{- "\n" }}
+ {{- tool | tojson }}
+ {%- endfor %}
+ {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }}
+{%- else %}
+ {%- if messages[0].role == 'system' %}
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
+ {%- endif %}
+{%- endif %}
+{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
+{%- for message in messages[::-1] %}
+ {%- set index = (messages|length - 1) - loop.index0 %}
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %}
+ {%- set ns.multi_step_tool = false %}
+ {%- set ns.last_query_index = index %}
+ {%- endif %}
+{%- endfor %}
+{%- for message in messages %}
+ {%- if message.content is string %}
+ {%- set content = message.content %}
+ {%- else %}
+ {%- set content = '' %}
+ {%- endif %}
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
+ {%- elif message.role == "assistant" %}
+ {%- set reasoning_content = '' %}
+ {%- if message.reasoning_content is string %}
+ {%- set reasoning_content = message.reasoning_content %}
+ {%- else %}
+ {%- if '' in content %}
+ {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %}
+ {%- set content = content.split('')[-1].lstrip('\n') %}
+ {%- endif %}
+ {%- endif %}
+ {%- if loop.index0 > ns.last_query_index %}
+ {%- if loop.last or (not loop.last and reasoning_content) %}
+ {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }}
+ {%- else %}
+ {{- '<|im_start|>' + message.role + '\n' + content }}
+ {%- endif %}
+ {%- else %}
+ {{- '<|im_start|>' + message.role + '\n' + content }}
+ {%- endif %}
+ {%- if message.tool_calls %}
+ {%- for tool_call in message.tool_calls %}
+ {%- if (loop.first and content) or (not loop.first) %}
+ {{- '\n' }}
+ {%- endif %}
+ {%- if tool_call.function %}
+ {%- set tool_call = tool_call.function %}
+ {%- endif %}
+ {{- '\n{"name": "' }}
+ {{- tool_call.name }}
+ {{- '", "arguments": ' }}
+ {%- if tool_call.arguments is string %}
+ {{- tool_call.arguments }}
+ {%- else %}
+ {{- tool_call.arguments | tojson }}
+ {%- endif %}
+ {{- '}\n' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+ {%- elif message.role == "tool" %}
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
+ {{- '<|im_start|>user' }}
+ {%- endif %}
+ {{- '\n\n' }}
+ {{- content }}
+ {{- '\n' }}
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
+ {{- '<|im_end|>\n' }}
+ {%- endif %}
+ {%- endif %}
+{%- endfor %}
+{%- if add_generation_prompt %}
+ {{- '<|im_start|>assistant\n' }}
+ {%- if enable_thinking is defined and enable_thinking is false %}
+ {{- '\n\n\n\n' }}
+ {%- endif %}
+{%- endif %}
\ No newline at end of file
diff --git a/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/render_oracle.json b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/render_oracle.json
new file mode 100644
index 00000000..741e5c35
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-8b/render_oracle.json
@@ -0,0 +1,185 @@
+{
+ "template": "Qwen/Qwen3-8B b968826d",
+ "jinja2": "3.1.6",
+ "enable_thinking": false,
+ "cases": [
+ {
+ "turns": [
+ [
+ "user",
+ "Hi"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "system",
+ "You are AIEN."
+ ],
+ [
+ "user",
+ "List two primes."
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>system\nYou are AIEN.<|im_end|>\n<|im_start|>user\nList two primes.<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "system",
+ "S"
+ ],
+ [
+ "user",
+ "U1"
+ ],
+ [
+ "assistant",
+ "A1"
+ ],
+ [
+ "user",
+ "U2"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>system\nS<|im_end|>\n<|im_start|>user\nU1<|im_end|>\n<|im_start|>assistant\nA1<|im_end|>\n<|im_start|>user\nU2<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "user",
+ "U1"
+ ],
+ [
+ "assistant",
+ "A1"
+ ],
+ [
+ "user",
+ "U2"
+ ],
+ [
+ "assistant",
+ "A2"
+ ],
+ [
+ "user",
+ "U3"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>user\nU1<|im_end|>\n<|im_start|>assistant\nA1<|im_end|>\n<|im_start|>user\nU2<|im_end|>\n<|im_start|>assistant\nA2<|im_end|>\n<|im_start|>user\nU3<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "user",
+ " padded\n\n"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>user\n padded\n\n<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "system",
+ ""
+ ],
+ [
+ "user",
+ ""
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "user",
+ "U"
+ ],
+ [
+ "system",
+ "late system"
+ ],
+ [
+ "user",
+ "V"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>user\nU<|im_end|>\n<|im_start|>system\nlate system<|im_end|>\n<|im_start|>user\nV<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "user",
+ "U"
+ ],
+ [
+ "assistant",
+ "A"
+ ],
+ [
+ "assistant",
+ "B"
+ ],
+ [
+ "user",
+ "V"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\nA<|im_end|>\n<|im_start|>assistant\nB<|im_end|>\n<|im_start|>user\nV<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "system",
+ "S\nline two text"
+ ],
+ [
+ "user",
+ "Q with <|im_end|> inside"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>system\nS\nline two text<|im_end|>\n<|im_start|>user\nQ with <|im_end|> inside<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ },
+ {
+ "turns": [
+ [
+ "user",
+ "U"
+ ],
+ [
+ "assistant",
+ " A with spaces \n"
+ ],
+ [
+ "user",
+ "V"
+ ]
+ ],
+ "add_generation_prompt": true,
+ "enable_thinking": false,
+ "text": "<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n A with spaces \n<|im_end|>\n<|im_start|>user\nV<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/crates/aien-inference-abi/src/tokenizer.rs b/crates/aien-inference-abi/src/tokenizer.rs
index 1b235431..df7ffbf6 100644
--- a/crates/aien-inference-abi/src/tokenizer.rs
+++ b/crates/aien-inference-abi/src/tokenizer.rs
@@ -22,6 +22,10 @@ pub enum TokenizerError {
/// Role `tool` offered to the raw `ChatTurn` path; tool turns must go through
/// `tool_boundary::ToolConversation` (issue #310).
ToolTurnRefused(String),
+ /// A message combination the pinned Qwen3-8B template layout does not cover (thinking
+ /// enabled, tool turns, tool calls, reasoning content, unknown roles, an assistant turn
+ /// to continue). Refused by name, never approximated (sc#384).
+ UnsupportedChatLayout(String),
}
impl fmt::Display for TokenizerError {
@@ -32,6 +36,7 @@ impl fmt::Display for TokenizerError {
Self::EncodeError(e) => write!(f, "Tokenization encoding failed: {}", e),
Self::DecodeError(e) => write!(f, "Tokenization decoding failed: {}", e),
Self::ToolTurnRefused(e) => write!(f, "{}", e),
+ Self::UnsupportedChatLayout(e) => write!(f, "unsupported chat layout: {}", e),
Self::ContextLengthExceeded { len, max } => {
write!(
f,
@@ -74,6 +79,13 @@ pub enum ChatTemplate {
/// one user turn, `<|im_start|>user`, then per turn `\n\n{content}\n`,
/// then `<|im_end|>\n`. Selected only by the pinned template text in `QWEN3_INSTRUCT_2507`.
ChatMlQwen3,
+ /// Qwen3-8B (and any model shipping the same template text), thinking mode explicitly OFF:
+ /// the pinned template `QWEN3_8B` rendered with `enable_thinking=false`. System and user
+ /// turns are ChatML verbatim; earlier assistant turns are plain; the generation prompt is
+ /// the assistant header plus an empty think block. Everything else (thinking on, tool
+ /// turns, tool calls, reasoning content, unknown roles, a trailing assistant turn) is
+ /// refused with `TokenizerError::UnsupportedChatLayout`. Selected only by the pinned text.
+ ChatMlQwen3NoThink,
/// The model directory has no chat template at all (a base model). Plain text encode
/// and decode work; every chat render is refused (`try_render` errors with
/// "no chat template"). Chosen only when neither `tokenizer_config.json` `chat_template`
@@ -98,6 +110,12 @@ const CHATML_PLAIN: &str = "{% for message in messages %}{{'<|im_start|>' + mess
const QWEN3_INSTRUCT_2507: &str =
include_str!("../fixtures/chat-templates/qwen3-4b-instruct-2507/chat_template.jinja");
+/// The Qwen3-8B chat template, byte for byte (Hugging Face `Qwen/Qwen3-8B` revision
+/// b968826d9c46dd6066d109eabc6255188de91218, Apache-2.0; see
+/// `fixtures/chat-templates/qwen3-8b/PROVENANCE.md`). It has an `enable_thinking` switch; this
+/// engine always renders the `enable_thinking=false` form ([`ChatTemplate::ChatMlQwen3NoThink`]).
+const QWEN3_8B: &str = include_str!("../fixtures/chat-templates/qwen3-8b/chat_template.jinja");
+
/// Matches a chat template text against the ChatML layouts above. Returns the layout
/// with its default system message (None for the plain layout), or a refusal.
fn parse_chatml(template_text: &str) -> Result {
@@ -105,6 +123,9 @@ fn parse_chatml(template_text: &str) -> Result {
if text == QWEN3_INSTRUCT_2507.trim() {
return Ok(ChatTemplate::ChatMlQwen3);
}
+ if text == QWEN3_8B.trim() {
+ return Ok(ChatTemplate::ChatMlQwen3NoThink);
+ }
if text == CHATML_PLAIN {
return Ok(ChatTemplate::ChatMl {
default_system: None,
@@ -184,6 +205,78 @@ fn ends_in_assistant(turns: &[(&str, &str)]) -> bool {
})
}
+/// Oracle-checked rendering of the pinned Qwen3-8B template with `enable_thinking=false`,
+/// `tools=None`, `add_generation_prompt=true`. Branches taken (template `QWEN3_8B`):
+/// 1. `tools` falsy: the system header is `<|im_start|>system\n{content}<|im_end|>\n` only when
+/// `messages[0].role == 'system'`; in the loop that first system turn then matches no branch
+/// (the `system and not loop.first` test fails), so it is emitted exactly once.
+/// 2. user, and system after the first turn: `<|im_start|>{role}\n{content}<|im_end|>\n`.
+/// 3. assistant, `reasoning_content` undefined and no `` in content: content stays as is.
+/// At `index <= last_query_index` the turn is `<|im_start|>assistant\n{content}`; at
+/// `index > last_query_index` and not last the same text (no reasoning); the last message being
+/// an assistant turn takes the `` block branch and closes the turn, so it is refused.
+/// No `tool_calls`, so the turn ends with `<|im_end|>\n`.
+/// 4. generation prompt with `enable_thinking is false`:
+/// `<|im_start|>assistant\n\n\n\n\n`.
+///
+/// Tool turns, tool calls, reasoning, thinking-on, tool-response-shaped user text, unknown roles,
+/// and an empty conversation are refused by name.
+fn render_qwen3_nothink(turns: &[(&str, &str)]) -> Result {
+ let refuse = |why: &str| Err(TokenizerError::UnsupportedChatLayout(why.to_string()));
+ if turns.is_empty() {
+ return refuse("empty conversation");
+ }
+ let mut out = String::new();
+ for (i, (role, content)) in turns.iter().enumerate() {
+ match *role {
+ "system" | "user" => {
+ if *role == "user"
+ && content.starts_with("")
+ && content.ends_with("")
+ {
+ return refuse("user text shaped like a tool response (changes the template's last-query index)");
+ }
+ out.push_str(&format!("<|im_start|>{role}\n{content}<|im_end|>\n"));
+ }
+ "assistant" => {
+ if i + 1 == turns.len() {
+ return refuse("trailing assistant turn (the template would add a think block and close it; continuation is not supported)");
+ }
+ if content.contains("") || content.contains("") {
+ return refuse("thinking markers inside an assistant turn (reasoning content)");
+ }
+ out.push_str(&format!("<|im_start|>assistant\n{content}<|im_end|>\n"));
+ }
+ "tool" => {
+ return Err(TokenizerError::ToolTurnRefused(
+ "role tool refused: the pinned Qwen3-8B layout covers no tool turns".into(),
+ ))
+ }
+ _ => {
+ return refuse("role other than exactly system, user or assistant");
+ }
+ }
+ }
+ out.push_str("<|im_start|>assistant\n\n\n\n\n");
+ Ok(out)
+}
+
+impl ChatTemplate {
+ /// Qwen3-8B with `enable_thinking` requested explicitly. Only `false` renders; `true` is
+ /// refused (the engine does not parse or budget a thinking block).
+ pub fn try_render_thinking(
+ &self,
+ turns: &[(&str, &str)],
+ enable_thinking: bool,
+ ) -> Result {
+ if enable_thinking {
+ return Err(TokenizerError::UnsupportedChatLayout(
+ "thinking enabled is not supported".into(),
+ ));
+ }
+ self.try_render(turns)
+ }
+}
fn no_chat_template_error() -> TokenizerError {
TokenizerError::NoChatTemplate(
"no chat template: this is a plain (base) model, chat rendering is refused".to_string(),
@@ -197,6 +290,7 @@ impl ChatTemplate {
Self::Llama3 => "llama3 (Llama 3 instruct)",
Self::ChatMl { .. } => "chatml (<|im_start|> / <|im_end|>)",
Self::ChatMlQwen3 => "chatml-qwen3 (<|im_start|> / <|im_end|>, tool responses)",
+ Self::ChatMlQwen3NoThink => "chatml-qwen3-nothink (Qwen3-8B, thinking off)",
Self::None => "none (plain text model)",
}
}
@@ -248,6 +342,9 @@ impl ChatTemplate {
if let Self::ChatMlQwen3 = self {
return Ok(render_chatml(None, true, turns));
}
+ if let Self::ChatMlQwen3NoThink = self {
+ return render_qwen3_nothink(turns);
+ }
let mut out = String::new();
for (role, content) in turns {
let body = content.trim();
@@ -264,7 +361,9 @@ impl ChatTemplate {
Self::Llama3 => out.push_str(&format!(
"<|start_header_id|>{role}<|end_header_id|>\n\n{body}<|eot_id|>"
)),
- Self::ChatMl { .. } | Self::ChatMlQwen3 => unreachable!("ChatML returned above"),
+ Self::ChatMl { .. } | Self::ChatMlQwen3 | Self::ChatMlQwen3NoThink => {
+ unreachable!("ChatML returned above")
+ }
Self::None => unreachable!("plain model refused above"),
}
}
@@ -272,7 +371,9 @@ impl ChatTemplate {
out.push_str(match self {
Self::Zephyr => "<|assistant|>\n",
Self::Llama3 => "<|start_header_id|>assistant<|end_header_id|>\n\n",
- Self::ChatMl { .. } | Self::ChatMlQwen3 => unreachable!("ChatML returned above"),
+ Self::ChatMl { .. } | Self::ChatMlQwen3 | Self::ChatMlQwen3NoThink => {
+ unreachable!("ChatML returned above")
+ }
Self::None => unreachable!("plain model refused above"),
});
}
diff --git a/crates/aien-inference-abi/tests/qwen3_8b_chat_template.rs b/crates/aien-inference-abi/tests/qwen3_8b_chat_template.rs
new file mode 100644
index 00000000..343b0bfe
--- /dev/null
+++ b/crates/aien-inference-abi/tests/qwen3_8b_chat_template.rs
@@ -0,0 +1,198 @@
+//! Qwen3-8B chat template, thinking OFF (sc#384). Pinned text: Hugging Face `Qwen/Qwen3-8B`
+//! revision b968826d9c46dd6066d109eabc6255188de91218 (fixtures/chat-templates/qwen3-8b).
+//!
+//! Three independent checks of the rendered bytes:
+//! 1. HAND ORACLE (below): strings written by reading the template text branch by branch, not
+//! produced by the engine.
+//! 2. JINJA ORACLE: `render_oracle.json`, the template rendered by jinja2 3.1.6 with
+//! `enable_thinking=False` (scratch script outside the repository), for 10 conversations.
+//! 3. BYTE DIFF against the downloaded file: the ignored test extracts `chat_template` from
+//! `$AIEN_QWEN3_8B_DIR/tokenizer_config.json` and compares it to the pinned fixture byte for
+//! byte (and loads the model directory's tokenizer). Run it with
+//! `AIEN_QWEN3_8B_DIR=~/models/qwen3-8b cargo test -p aien-inference-abi --test
+//! qwen3_8b_chat_template -- --ignored`.
+//!
+//! Template branches taken (tools=None, add_generation_prompt=true, enable_thinking=false):
+//! - `{%- if tools %}` false -> `{%- else %}`: system header only if `messages[0].role=='system'`:
+//! `<|im_start|>system\n{content}<|im_end|>\n`; the loop then skips that first system turn
+//! (`message.role == "system" and not loop.first` is false), so it appears once.
+//! - user, or system after the first turn: `<|im_start|>{role}\n{content}<|im_end|>\n`, verbatim.
+//! - assistant, no reasoning_content, no `` in content, no tool_calls: `index <=
+//! last_query_index` -> `<|im_start|>assistant\n{content}`, then `<|im_end|>\n`. (An assistant
+//! turn after the last user turn that is not last takes the same plain text; one that is last
+//! takes the think-block branch and is refused by the engine.)
+//! - generation prompt: `<|im_start|>assistant\n` then, because `enable_thinking is defined and
+//! is false`, `\n\n\n\n`.
+
+use aien_inference_abi::tokenizer::{ChatTemplate, TokenizerError};
+
+const DIR: &str = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/fixtures/chat-templates/qwen3-8b"
+);
+const GEN: &str = "<|im_start|>assistant\n\n\n\n\n";
+
+fn template_text() -> String {
+ std::fs::read_to_string(format!("{DIR}/chat_template.jinja")).unwrap()
+}
+
+fn t() -> ChatTemplate {
+ ChatTemplate::detect(&template_text()).expect("Qwen3-8B template accepted")
+}
+
+#[test]
+fn pinned_template_is_selected_and_distinct_from_the_4b_layout() {
+ assert_eq!(t(), ChatTemplate::ChatMlQwen3NoThink);
+ assert_ne!(t(), ChatTemplate::ChatMlQwen3);
+}
+
+#[test]
+fn hand_oracle_from_the_template_branches() {
+ let tpl = t();
+ // Branch: no system, one user.
+ assert_eq!(
+ tpl.try_render(&[("user", "Hi")]).unwrap(),
+ format!("<|im_start|>user\nHi<|im_end|>\n{GEN}")
+ );
+ // Branch: leading system emitted once, contents verbatim (no trim).
+ assert_eq!(
+ tpl.try_render(&[("system", " S\n"), ("user", " U \n")])
+ .unwrap(),
+ format!("<|im_start|>system\n S\n<|im_end|>\n<|im_start|>user\n U \n<|im_end|>\n{GEN}")
+ );
+ // Branch: earlier assistant turn (index <= last_query_index) is plain, no think block.
+ assert_eq!(
+ tpl.try_render(&[("user", "a"), ("assistant", "b"), ("user", "c")])
+ .unwrap(),
+ format!(
+ "<|im_start|>user\na<|im_end|>\n<|im_start|>assistant\nb<|im_end|>\n<|im_start|>user\nc<|im_end|>\n{GEN}"
+ )
+ );
+}
+
+#[test]
+fn rendering_matches_the_jinja_reference_rendering() {
+ let oracle: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(format!("{DIR}/render_oracle.json")).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(oracle["enable_thinking"], false);
+ let tpl = t();
+ let cases = oracle["cases"].as_array().unwrap();
+ assert_eq!(cases.len(), 10);
+ for (i, case) in cases.iter().enumerate() {
+ assert_eq!(case["add_generation_prompt"], true);
+ assert_eq!(case["enable_thinking"], false);
+ let turns: Vec<(String, String)> = case["turns"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|p| (p[0].as_str().unwrap().into(), p[1].as_str().unwrap().into()))
+ .collect();
+ let refs: Vec<(&str, &str)> = turns
+ .iter()
+ .map(|(r, c)| (r.as_str(), c.as_str()))
+ .collect();
+ assert_eq!(
+ tpl.try_render(&refs).unwrap(),
+ case["text"].as_str().unwrap(),
+ "case {i}"
+ );
+ assert!(case["text"].as_str().unwrap().ends_with(GEN));
+ }
+}
+
+fn layout_refused(r: Result) {
+ assert!(
+ matches!(r, Err(TokenizerError::UnsupportedChatLayout(_))),
+ "{r:?}"
+ );
+}
+
+#[test]
+fn uncovered_combinations_are_refused_by_name() {
+ let tpl = t();
+ // Thinking enabled.
+ layout_refused(tpl.try_render_thinking(&[("user", "q")], true));
+ assert_eq!(
+ tpl.try_render_thinking(&[("user", "q")], false).unwrap(),
+ tpl.try_render(&[("user", "q")]).unwrap()
+ );
+ // Tool turns.
+ assert!(matches!(
+ tpl.try_render(&[("user", "q"), ("tool", "r")]),
+ Err(TokenizerError::ToolTurnRefused(_))
+ ));
+ // Reasoning content / thinking markers inside an assistant turn.
+ layout_refused(tpl.try_render(&[
+ ("user", "q"),
+ ("assistant", "xy"),
+ ("user", "z"),
+ ]));
+ // Trailing assistant turn (continuation).
+ layout_refused(tpl.try_render(&[("user", "q"), ("assistant", "partial")]));
+ layout_refused(tpl.try_render(&[("user", "q"), ("assistant", "")]));
+ // User text shaped like a tool response.
+ layout_refused(tpl.try_render(&[("user", "\nx\n")]));
+ // Unknown or differently cased roles, and an empty conversation.
+ layout_refused(tpl.try_render(&[("developer", "q")]));
+ layout_refused(tpl.try_render(&[("User", "q")]));
+ layout_refused(tpl.try_render(&[]));
+}
+
+#[test]
+fn altered_templates_are_refused() {
+ let base = template_text();
+ let altered = [
+ // Thinking-on generation prompt (no enable_thinking switch).
+ base.replace(
+ "{%- if enable_thinking is defined and enable_thinking is false %}",
+ "{%- if false %}",
+ ),
+ base.replace("\\n\\n\\n", "\\n\\n"),
+ format!("{base}{{# #}}"),
+ ];
+ for (i, text) in altered.iter().enumerate() {
+ assert_ne!(text, &base, "alteration {i} changed nothing");
+ assert!(ChatTemplate::detect(text).is_err(), "altered {i} accepted");
+ }
+}
+
+#[test]
+fn the_4b_layout_is_unchanged() {
+ let four_b = std::fs::read_to_string(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/fixtures/chat-templates/qwen3-4b-instruct-2507/chat_template.jinja"
+ ))
+ .unwrap();
+ let f = ChatTemplate::detect(&four_b).unwrap();
+ assert_eq!(f, ChatTemplate::ChatMlQwen3);
+ assert_eq!(
+ f.try_render(&[("user", "Hi")]).unwrap(),
+ "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n"
+ );
+}
+
+#[test]
+#[ignore = "needs the Qwen3-8B model directory in AIEN_QWEN3_8B_DIR"]
+fn downloaded_tokenizer_config_matches_the_pin_byte_for_byte() {
+ use aien_inference_abi::tokenizer::ChatTokenizer;
+ let dir = std::env::var("AIEN_QWEN3_8B_DIR").expect("AIEN_QWEN3_8B_DIR is not set");
+ let cfg: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(format!("{dir}/tokenizer_config.json")).unwrap(),
+ )
+ .unwrap();
+ let downloaded = cfg["chat_template"].as_str().expect("chat_template string");
+ assert_eq!(downloaded.as_bytes(), template_text().as_bytes());
+ let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).unwrap();
+ assert_eq!(tok.template(), ChatTemplate::ChatMlQwen3NoThink);
+ let im_end = tok.token_to_id("<|im_end|>").expect("<|im_end|> in vocab");
+ assert!(tok.stop_token_ids().contains(&im_end));
+ let text = tok
+ .try_format_chat(&[("system", "You are AIEN."), ("user", "List two primes.")])
+ .unwrap();
+ assert!(text.ends_with(GEN));
+ let ids = tok.encode(&text).unwrap();
+ assert_eq!(ids.first().copied(), tok.token_to_id("<|im_start|>"));
+ assert_eq!(ids.iter().filter(|&&i| i == im_end).count(), 2);
+}
diff --git a/crates/aien-inference-abi/tests/qwen3_untied_head.rs b/crates/aien-inference-abi/tests/qwen3_untied_head.rs
new file mode 100644
index 00000000..53911594
--- /dev/null
+++ b/crates/aien-inference-abi/tests/qwen3_untied_head.rs
@@ -0,0 +1,171 @@
+//! Untied output head (`tie_word_embeddings=false`), as in Qwen3-8B (hidden 4096, intermediate
+//! 12288, rope_theta 1e6, `lm_head.weight` in the last shard). CPU reference path, sc#384.
+//!
+//! Independent oracle: the tiny Qwen3 checkpoint's transformers logits (see
+//! `fixtures/qwen3-tiny/PROVENANCE.md`, tied head). The test writes a copy of that checkpoint
+//! WITH an extra `lm_head.weight` that is the embedding matrix with rows 3 and 5 swapped. The
+//! hidden state does not depend on the head, so the right untied logits are the oracle logits
+//! with entries 3 and 5 swapped. A loader that ignores `lm_head.weight` (and reuses the
+//! embeddings) returns the unswapped oracle logits and fails; the negative control asserts the
+//! swap is far outside the tolerance, so the check cannot pass vacuously. A second test shows
+//! an untied config with no `lm_head.weight` is refused, never silently tied.
+//!
+//! The real Qwen3-8B shape check (config.json values and the `lm_head.weight` index entry) is
+//! the ignored test at the bottom (`AIEN_QWEN3_8B_DIR`).
+
+use aien_inference_abi::{load_model_config, ModelConfig, SequenceState, TransformerWeights};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+
+const TOL: f32 = 1e-4;
+
+fn tiny_dir() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/qwen3-tiny")
+}
+
+fn oracle_logits() -> (Vec, Vec) {
+ let r: Value = serde_json::from_str(
+ &std::fs::read_to_string(tiny_dir().join("forward_reference.json")).unwrap(),
+ )
+ .unwrap();
+ let ids = r["ids"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_u64().unwrap() as u32)
+ .collect();
+ let logits = r["logits"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_f64().unwrap() as f32)
+ .collect();
+ (ids, logits)
+}
+
+/// The tiny checkpoint plus an `lm_head.weight` (BF16 [64, 32]) = embeddings with rows 3, 5 swapped.
+fn untied_checkpoint(dir: &Path, with_head: bool) {
+ std::fs::create_dir_all(dir).unwrap();
+ let bytes = std::fs::read(tiny_dir().join("model.safetensors")).unwrap();
+ let hlen = u64::from_le_bytes(bytes[0..8].try_into().unwrap()) as usize;
+ let mut header: Value = serde_json::from_slice(&bytes[8..8 + hlen]).unwrap();
+ let data = &bytes[8 + hlen..];
+ let emb = &header["model.embed_tokens.weight"];
+ assert_eq!(emb["dtype"], "BF16");
+ assert_eq!(emb["shape"], json!([64, 32]));
+ let start = emb["data_offsets"][0].as_u64().unwrap() as usize;
+ let end = emb["data_offsets"][1].as_u64().unwrap() as usize;
+ let row = 32 * 2;
+ assert_eq!(end - start, 64 * row);
+ let mut out = data.to_vec();
+ if with_head {
+ let mut head = data[start..end].to_vec();
+ let (a, b) = (3 * row, 5 * row);
+ for i in 0..row {
+ head.swap(a + i, b + i);
+ }
+ header["lm_head.weight"] = json!({
+ "dtype": "BF16", "shape": [64, 32],
+ "data_offsets": [out.len(), out.len() + head.len()]
+ });
+ out.extend_from_slice(&head);
+ }
+ let h = serde_json::to_vec(&header).unwrap();
+ let mut file = (h.len() as u64).to_le_bytes().to_vec();
+ file.extend_from_slice(&h);
+ file.extend_from_slice(&out);
+ std::fs::write(dir.join("model.safetensors"), file).unwrap();
+}
+
+fn untied_config() -> ModelConfig {
+ let mut c = load_model_config(&tiny_dir()).unwrap();
+ assert!(c.tie_word_embeddings, "the tiny fixture is tied");
+ c.tie_word_embeddings = false;
+ c
+}
+
+fn scratch(name: &str) -> PathBuf {
+ std::env::temp_dir().join(format!("aien-untied-head-{name}-{}", std::process::id()))
+}
+
+fn last_logits(w: &TransformerWeights, ids: &[u32]) -> Vec {
+ let mut state = SequenceState {
+ tokens: Vec::new(),
+ layers: vec![Default::default(); w.config.num_layers],
+ };
+ let mut last = Vec::new();
+ for (pos, id) in ids.iter().enumerate() {
+ last = w.forward_token(*id, pos, &mut state);
+ }
+ w.compute_logits(&last)
+}
+
+fn max_abs(a: &[f32], b: &[f32]) -> f32 {
+ assert_eq!(a.len(), b.len());
+ a.iter()
+ .zip(b)
+ .map(|(x, y)| (x - y).abs())
+ .fold(0.0, f32::max)
+}
+
+#[test]
+fn untied_head_logits_use_lm_head_not_the_embeddings() {
+ let dir = scratch("with");
+ untied_checkpoint(&dir, true);
+ let (ids, tied) = oracle_logits();
+ let mut expected = tied.clone();
+ expected.swap(3, 5);
+ // Negative control: the swapped vector is far from the tied oracle.
+ assert!(
+ max_abs(&expected, &tied) > 100.0 * TOL,
+ "rows 3 and 5 give nearly equal logits; the control would be vacuous"
+ );
+ let cfg = untied_config();
+ let w = TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &cfg)
+ .expect("untied checkpoint with lm_head.weight loads");
+ assert!(w.lm_head.is_some(), "untied load must keep lm_head");
+ let got = last_logits(&w, &ids);
+ let d = max_abs(&got, &expected);
+ eprintln!("untied head: max abs diff vs swapped oracle = {d:e}");
+ assert!(d <= TOL, "max abs diff {d:e}");
+ assert!(
+ max_abs(&got, &tied) > 100.0 * TOL,
+ "logits equal the tied (embedding) result: lm_head was ignored"
+ );
+ // Sequence path agrees with the token path.
+ let seq = w.forward_sequence_with_diagnostics(&ids).activations["last_token_logits"].clone();
+ assert!(max_abs(&seq, &expected) <= TOL);
+ let _ = std::fs::remove_dir_all(dir);
+}
+
+#[test]
+fn untied_config_without_lm_head_is_refused_not_tied() {
+ let dir = scratch("without");
+ untied_checkpoint(&dir, false);
+ let r =
+ TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &untied_config());
+ let _ = std::fs::remove_dir_all(dir);
+ let Err(e) = r else {
+ panic!("untied config without lm_head.weight must be refused");
+ };
+ assert!(e.to_string().contains("lm_head.weight"), "{e}");
+}
+
+/// Real Qwen3-8B shapes from the downloaded files: `AIEN_QWEN3_8B_DIR=~/models/qwen3-8b cargo test
+/// -p aien-inference-abi --test qwen3_untied_head -- --ignored`. Reads only config.json and the
+/// shard index (no weights), fails when the variable is unset.
+#[test]
+#[ignore = "needs the Qwen3-8B model directory in AIEN_QWEN3_8B_DIR"]
+fn real_qwen3_8b_config_is_untied_with_the_expected_shape() {
+ let dir = PathBuf::from(std::env::var("AIEN_QWEN3_8B_DIR").expect("AIEN_QWEN3_8B_DIR unset"));
+ let c = load_model_config(&dir).unwrap();
+ assert!(!c.tie_word_embeddings);
+ assert_eq!((c.hidden_dim, c.intermediate_dim), (4096, 12288));
+ assert_eq!(c.rope_theta, 1_000_000.0);
+ assert!(c.qk_norm);
+ let idx: Value = serde_json::from_str(
+ &std::fs::read_to_string(dir.join("model.safetensors.index.json")).unwrap(),
+ )
+ .unwrap();
+ assert!(idx["weight_map"]["lm_head.weight"].is_string());
+}
diff --git a/crates/aien-runtime/examples/qwen3_8b_smoke.rs b/crates/aien-runtime/examples/qwen3_8b_smoke.rs
new file mode 100644
index 00000000..16fe8f6c
--- /dev/null
+++ b/crates/aien-runtime/examples/qwen3_8b_smoke.rs
@@ -0,0 +1,190 @@
+//! Qwen3-8B correctness smoke driver (docs/campaigns/open-model-qwen3/SMOKE-8B-v1.md, sc#384).
+//! Two fixed conversations (PROMPTS), thinking off, greedy, on the daemon's path (strict
+//! safetensors load, shared-KV runtime, `ChatTokenizer::from_model_dir`, one warm-up turn).
+//! Prints ONE JSON object: prompt text and ids, output ids, finish reason, fallback_count.
+//!
+//! usage: qwen3_8b_smoke
+//! cpu = `ReferenceCpuBackend`, host f32 weights (never touches the GPU).
+//! gb10 = the daemon's GB10 construction (session open with retry, resident bf16 load through
+//! `OmegaUploader`, `OmegaGb10Backend`). Refuses by name when the engine is not linked,
+//! the build is not production-strict, or the model is refused; never falls back.
+//! UNVERIFIED: compiled but not run on the chip when this file was written.
+use aien_inference_abi::{ChatTokenizer, SamplingParams, TensorBackend};
+use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing};
+use aien_scheduler::{ChannelCompletionSink, CompletionEvent};
+use sha2::Digest;
+use std::sync::Arc;
+
+const SYSTEM: &str = "You are a careful assistant.";
+const GEN_PROMPT: &str = "<|im_start|>assistant\n\n\n\n\n";
+/// (name, user text, max new tokens). Prompt 1 is the original one-token check; prompt 2 must reply with
+/// at least 16 tokens before eos (SMOKE-8B-v1.md).
+const PROMPTS: &[(&str, &str, usize)] = &[
+ ("p1", "Reply with the single word OK.", 16),
+ (
+ "p2",
+ "List the months of the year, one per line, nothing else.",
+ 48,
+ ),
+];
+
+async fn turn(
+ spine: &mut aien_runtime::AienRuntimeSpine,
+ backend: &mut aien_inference_abi::NativeTransformerBackend,
+ ids: &[u32],
+ max_tokens: usize,
+ stop: &[u32],
+) -> Result<(Vec, String, f64), String> {
+ let (sink, mut ev) = ChannelCompletionSink::channel();
+ let sid = spine.register_completion_sink(Arc::new(sink));
+ let sampling = SamplingParams {
+ temperature: 0.0,
+ top_p: 0.95,
+ max_tokens,
+ stop_token_ids: stop.to_vec(),
+ };
+ spine.submit_work(Arc::from(ids), sampling, 2, Some(sid))?;
+ let t0 = std::time::Instant::now();
+ let mut out = Vec::new();
+ loop {
+ if spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0 {
+ spine.step(backend).await.map_err(|e| format!("{e:?}"))?;
+ }
+ while let Ok(e) = ev.try_recv() {
+ match e {
+ CompletionEvent::Token { token, .. } => out.push(token),
+ CompletionEvent::Finished { finish_reason, .. } => {
+ let label = aien_runtime::server::finish_reason_label(&finish_reason);
+ return Ok((out, label.into(), t0.elapsed().as_secs_f64() * 1e3));
+ }
+ CompletionEvent::Error { message, .. } => return Err(message),
+ }
+ }
+ }
+}
+
+fn die(code: i32, msg: &str) -> ! {
+ eprintln!("qwen3_8b_smoke: {msg}");
+ std::process::exit(code)
+}
+
+#[tokio::main]
+async fn main() {
+ let a: Vec = std::env::args().collect();
+ if a.len() != 3 || !matches!(a[2].as_str(), "cpu" | "gb10") {
+ die(2, "usage: qwen3_8b_smoke ");
+ }
+ let dir = std::path::PathBuf::from(&a[1]);
+ let gb10 = a[2] == "gb10";
+ let config = aien_inference_abi::load_model_config(&dir).expect("config.json");
+ let (weights, tb): (_, Arc) = if gb10 {
+ if !aien_inference_abi::strict::production_strict() {
+ die(
+ 3,
+ "gb10 leg needs a production-strict build (no dev fallback)",
+ );
+ }
+ let omega = aien_inference_abi::OmegaGb10Backend::new();
+ if !omega.is_available() {
+ die(3, "the Omega GB10 engine is not linked (stub build)");
+ }
+ if let Some(why) = aien_inference_abi::omega_model_refusal(&config) {
+ die(3, &why);
+ }
+ aien_inference_abi::open_gpu_session_with_retry(
+ aien_inference_abi::GPU_SESSION_OPEN_ATTEMPTS,
+ aien_inference_abi::GPU_SESSION_RETRY_DELAY,
+ aien_inference_abi::GPU_SESSION_OPEN_DEADLINE,
+ &aien_runtime::shared_kv::read_mem_available,
+ )
+ .unwrap_or_else(|e| die(3, &format!("GPU session: {e}")));
+ let weights = aien_inference_abi::load_resident_weights(
+ &dir,
+ &config,
+ &aien_inference_abi::OmegaUploader,
+ &mut |_| {},
+ )
+ .unwrap_or_else(|e| die(3, &format!("resident load: {e}")));
+ (weights, Arc::new(omega))
+ } else {
+ let weights = aien_inference_abi::TransformerWeights::load_from_safetensors(&dir, &config)
+ .expect("weights");
+ (
+ weights,
+ Arc::new(aien_inference_abi::ReferenceCpuBackend::new()),
+ )
+ };
+ let tok = ChatTokenizer::from_model_dir(&dir, None).expect("tokenizer");
+ let cfg = aien_scheduler::SchedulerConfig {
+ max_batch_size: 256,
+ max_batch_tokens: 16384,
+ max_prefill_tokens: 8192,
+ prefill_chunk_size: 128,
+ chunk_prefill: true,
+ watermark_blocks: 64,
+ };
+ let sizing = SharedKvSizing {
+ arena_capacity: 4096,
+ total_blocks: 8192,
+ };
+ let (mut spine, mut backend) =
+ build_shared_kv_runtime(weights, tb.clone(), cfg, sizing).expect("shared KV");
+ let stop = tok.stop_token_ids().to_vec();
+ let wm = vec![aien_runtime::ChatTurn {
+ role: "user".into(),
+ content: aien_runtime::WARM_UP_TEXT.into(),
+ }];
+ let wids = tok
+ .encode(&aien_runtime::format_chat(tok.template(), &wm).expect("chat"))
+ .expect("encode");
+ turn(&mut spine, &mut backend, &wids, 1, &stop)
+ .await
+ .expect("warm-up");
+ let sha = |b: &[u8]| -> String {
+ sha2::Sha256::digest(b)
+ .iter()
+ .map(|x| format!("{x:02x}"))
+ .collect()
+ };
+ let mut results = Vec::new();
+ for (name, user, max_tokens) in PROMPTS {
+ let msgs = vec![
+ aien_runtime::ChatTurn {
+ role: "system".into(),
+ content: SYSTEM.into(),
+ },
+ aien_runtime::ChatTurn {
+ role: "user".into(),
+ content: (*user).into(),
+ },
+ ];
+ let text = aien_runtime::format_chat(tok.template(), &msgs).expect("chat");
+ let expected = format!(
+ "<|im_start|>system\n{SYSTEM}<|im_end|>\n<|im_start|>user\n{user}<|im_end|>\n{GEN_PROMPT}"
+ );
+ if text != expected {
+ die(
+ 4,
+ &format!("rendered prompt {name} differs from the golden text: {text:?}"),
+ );
+ }
+ let ids = tok.encode(&text).expect("encode");
+ let (out, finish, ms) = turn(&mut spine, &mut backend, &ids, *max_tokens, &stop)
+ .await
+ .expect("turn");
+ let reply = tok.decode_opts(&out, true).expect("decode");
+ results.push(serde_json::json!({
+ "name": name, "prompt_sha256": sha(text.as_bytes()), "prompt_ids": ids,
+ "max_tokens": max_tokens, "output_ids": out, "finish": finish, "ms": ms,
+ "reply": reply,
+ }));
+ }
+ println!(
+ "{}",
+ serde_json::json!({
+ "leg": a[2], "backend": TensorBackend::name(tb.as_ref()),
+ "model_dir": dir, "model_id": config.model_id, "template": tok.template().name(),
+ "prompts": results, "fallback_count": tb.fallback_count(),
+ })
+ );
+}
diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs
index e401ced9..f80aab7f 100644
--- a/crates/aien-runtime/src/spine.rs
+++ b/crates/aien-runtime/src/spine.rs
@@ -1148,7 +1148,9 @@ pub fn compose_assistant_prefix(template: &aien_inference_abi::ChatTemplate) ->
ChatTemplate::Zephyr | ChatTemplate::Llama3 => COMPOSE_ASSISTANT_PREFIX,
// A plain model never reaches generation (chat render is refused first).
ChatTemplate::None => COMPOSE_ASSISTANT_PREFIX,
- ChatTemplate::ChatMl { .. } | ChatTemplate::ChatMlQwen3 => "filename:",
+ ChatTemplate::ChatMl { .. }
+ | ChatTemplate::ChatMlQwen3
+ | ChatTemplate::ChatMlQwen3NoThink => "filename:",
}
}
diff --git a/docs/campaigns/open-model-qwen3/SMOKE-8B-v1.golden.json b/docs/campaigns/open-model-qwen3/SMOKE-8B-v1.golden.json
new file mode 100644
index 00000000..a25a3bc7
--- /dev/null
+++ b/docs/campaigns/open-model-qwen3/SMOKE-8B-v1.golden.json
@@ -0,0 +1,115 @@
+{
+ "golden_for": "SMOKE-8B-v1",
+ "source": "CPU reference leg",
+ "prompts": [
+ {
+ "name": "p1",
+ "prompt_sha256": "258172010d5ad8cc07733bcd111c5911b8af92c9174abe3bcbe2e173f38dbb62",
+ "prompt_ids": [
+ 151644,
+ 8948,
+ 198,
+ 2610,
+ 525,
+ 264,
+ 16585,
+ 17847,
+ 13,
+ 151645,
+ 198,
+ 151644,
+ 872,
+ 198,
+ 20841,
+ 448,
+ 279,
+ 3175,
+ 3409,
+ 10402,
+ 13,
+ 151645,
+ 198,
+ 151644,
+ 77091,
+ 198,
+ 151667,
+ 271,
+ 151668,
+ 271
+ ],
+ "output_ids": [
+ 3925
+ ],
+ "reply": "OK"
+ },
+ {
+ "name": "p2",
+ "prompt_sha256": "a0673e2d48f1bf14803ed1094db20d00c3da8b2201ad1e3c36bf477deca62f79",
+ "prompt_ids": [
+ 151644,
+ 8948,
+ 198,
+ 2610,
+ 525,
+ 264,
+ 16585,
+ 17847,
+ 13,
+ 151645,
+ 198,
+ 151644,
+ 872,
+ 198,
+ 852,
+ 279,
+ 3951,
+ 315,
+ 279,
+ 1042,
+ 11,
+ 825,
+ 817,
+ 1555,
+ 11,
+ 4302,
+ 770,
+ 13,
+ 151645,
+ 198,
+ 151644,
+ 77091,
+ 198,
+ 151667,
+ 271,
+ 151668,
+ 271
+ ],
+ "output_ids": [
+ 32227,
+ 2303,
+ 32777,
+ 2303,
+ 27523,
+ 2303,
+ 28046,
+ 2303,
+ 11109,
+ 2303,
+ 27160,
+ 2303,
+ 28427,
+ 2303,
+ 31459,
+ 2303,
+ 29549,
+ 2303,
+ 30194,
+ 2303,
+ 33727,
+ 2303,
+ 32146
+ ],
+ "reply": "January \nFebruary \nMarch \nApril \nMay \nJune \nJuly \nAugust \nSeptember \nOctober \nNovember \nDecember"
+ }
+ ]
+}
diff --git a/docs/campaigns/open-model-qwen3/SMOKE-8B-v1.md b/docs/campaigns/open-model-qwen3/SMOKE-8B-v1.md
new file mode 100644
index 00000000..50a35b07
--- /dev/null
+++ b/docs/campaigns/open-model-qwen3/SMOKE-8B-v1.md
@@ -0,0 +1,44 @@
+# SMOKE-8B-v1: Qwen3-8B correctness smoke (preregistered)
+
+Status: PREREGISTERED before any 8B token was produced by this engine (2026-10-11). Lane: sc#384, authorized by Drake (sc#384 comment 6110013055). A smoke test, not a qualification and not a promotion of the 8B to a product model. Qualification of the 8B stays a separate, later decision.
+
+## Why this exists
+
+The 8B differs from the qualified 4B in ways the engine had not been shown to handle: a pinned chat template with a thinking switch (now pinned, thinking off, `ChatTemplate::ChatMlQwen3NoThink`) and an untied output head (`tie_word_embeddings=false`, separate `lm_head.weight`; CPU loader path covered by `crates/aien-inference-abi/tests/qwen3_untied_head.rs`). This smoke shows, once, that the whole path produces the same tokens on the CPU reference and on the GB10.
+
+## Fixed inputs
+
+- Model: `~/models/qwen3-8b`, Hugging Face `Qwen/Qwen3-8B` revision b968826d9c46dd6066d109eabc6255188de91218. Before any run, the script checks sha256 of `config.json` and the five shards against the values recorded in `EVAL-qwen3-8b.md` Section 1 (branch d1/qwen3-8b-eval, or main once sc#434 merges): config f7c4eadf..., shards 31d6a825..., 5991236c..., c5185c47..., b5ee7de7..., 20c2d636... A mismatch stops the run.
+- Conversations (both with system `You are a careful assistant.`, thinking off). Prompt 1: user `Reply with the single word OK.` (max 16 new tokens). Prompt 2 (added in the same PR, before any GB10 run): user `List the months of the year, one per line, nothing else.` (max 48 new tokens; chosen so the greedy reply is at least 16 tokens before eos; the first candidate, the days of the week, gave only 13 tokens and was replaced). Prompt 1 renders, byte for byte, to
+ `<|im_start|>system\nYou are a careful assistant.<|im_end|>\n<|im_start|>user\nReply with the single word OK.<|im_end|>\n<|im_start|>assistant\n\n\n\n\n`
+ and prompt 2 to the same layout with its user text (the driver exits with code 4 on any difference).
+- Decoding: greedy (temperature 0), 16 new tokens at most, stop on the model's stop set (`<|im_end|>` among them), one warm-up turn first, as the daemon does. Driver: `crates/aien-runtime/examples/qwen3_8b_smoke.rs`; runner: `scripts/smoke_qwen3_8b.sh`.
+
+## Steps and verdicts (all decided now)
+
+1. Template (already unit-tested, no model needed): the engine's rendering equals the hand oracle, the jinja2 3.1.6 rendering (`render_oracle.json`) and the publisher's file byte for byte. Test: `tests/qwen3_8b_chat_template.rs`.
+2. Untied head, CPU: `tests/qwen3_untied_head.rs` (synthetic checkpoint with a row-swapped `lm_head.weight` against the transformers oracle logits of the tiny Qwen3; an untied config without `lm_head.weight` is refused).
+3. CPU leg (`smoke_qwen3_8b.sh cpu`): `ReferenceCpuBackend`, host f32 weights. Its `prompt_ids` and `output_ids` are recorded as the golden values in `SMOKE-8B-v1.golden.json`. The CPU leg is the reference by construction; it is judged only for being well formed (non-empty output, fallback_count 0) and for the reply being sensible text, which is reported, not gated (a 16-token greedy reply of an 8B on one prompt is weak evidence of quality and is not claimed as such).
+4. GB10 leg (`smoke_qwen3_8b.sh gb10`): the daemon's GB10 construction (session open, resident bf16 load, `OmegaGb10Backend`, production-strict build, `AIEN_REQUIRE_BLACKWELL=1`). PASS if and only if all of:
+ - for BOTH prompts, `prompt_ids` equal the golden `prompt_ids`;
+ - for BOTH prompts, `output_ids` equal the golden `output_ids` token for token (parity);
+ - `fallback_count` is 0 (the backend counter covers both prompts of the run; a fallback on either fails the run).
+ Any other outcome is FAIL. A near-tie that flips a token is a FAIL and is reported with the logit margin; no tolerance is raised to accept it. A refusal by name (engine not linked, model refused, resident load or session failure) is a FAIL with the reason, never a silent CPU result.
+5. Recorded, not gated: wall time per leg, `VmHWM`, decode ms per token.
+
+## What the chip run needs (not run by this lane)
+
+- The machine free: the whole-system runs RUN-7-CPU and RUN-7-GB10 finished, `quietlock check` clear, no `whole_system_e2e` process (the script checks both).
+- About 16.4 GB of device-resident weights plus serving buffers on the GB10; the host must not hold a second f32 copy (the resident load avoids it). The 4B needed the same care (omega#327: NV_ERR_NO_MEMORY when MemFree was low).
+- The golden file from the CPU leg committed or present at `docs/campaigns/open-model-qwen3/SMOKE-8B-v1.golden.json`.
+- The pinned GPU engine build through `scripts/pins.sh --gpu` (done by the script).
+- Known limit, UNVERIFIED (confidence 60 percent that it works first time): the GB10 mode of the driver mirrors the daemon's construction by reading `crates/aien-cli/src/commands.rs` (`build_native_daemon_backend`) but has only been compiled, not run on the chip. If it fails on setup (for example a serving-buffer reservation the daemon does and the driver does not), the failure is a driver gap, to be fixed and re-run, not a model verdict.
+
+## Limits
+
+- Two prompts, at most 48 tokens: parity on these prompts, not correctness in general.
+- No Hugging Face reference token ids were produced for the 8B; the golden values come from this engine's CPU leg, whose correctness rests on the 4B/tiny-model oracle tests of the same code. EVAL Section 8 step 3 (a Hugging Face reference run, off-repo) remains open and is a stronger check; UNVERIFIED whether the CPU leg equals it.
+
+## Recorded after the CPU leg ran (2026-10-11, the only leg run so far)
+
+CPU leg on `~/models/qwen3-8b` (sha256 check passed), `ReferenceCpuBackend`, fallback_count 0, wall time 203 s for the whole script (load, warm-up, both turns). Prompt 1: 30 prompt tokens, reply `OK`, output ids `[3925]`, then eos. Prompt 2: 37 prompt tokens, 23 output tokens, reply the twelve month names one per line, then eos. Golden prompt ids, output ids and replies for both: `SMOKE-8B-v1.golden.json`. Prompt 1 ids are identical to the first recording. This does not change any verdict rule above. The GB10 leg has not been run.
diff --git a/scripts/.crumb b/scripts/.crumb
index e5364a06..6ce281c5 100644
--- a/scripts/.crumb
+++ b/scripts/.crumb
@@ -4,14 +4,14 @@
"generated": {
"children": [],
"children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- "compiled_at": "2026-10-11T14:00:48Z",
+ "compiled_at": "2026-10-11T15:06:17Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:de59c21bf8b5819007225986edf7a75dbe93c1203686e619e72e17a6799fa127",
+ "digest": "sha256:14ad22b926c21034daa6cfc2108a3bcd9f5dd6256231dd5d16576951eec2d805",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- "files": 36,
- "generated_at_commit": "5e44b0b8770528265d1d8d2ce07f7137b05a6fcf",
- "source_tree": "sha256:91af5a64bb27722da49137d357d85749a9e0b23387d00644d793ff77f61e3cd1"
+ "files": 37,
+ "generated_at_commit": "f487c4a95e7a012598d8befc931c45f9466f9c4a",
+ "source_tree": "sha256:0bf2b45e9033fde5784a0052776da3b3b1f8c842a55ed40024b0335ddabc5efd"
}
},
"parent": {
diff --git a/scripts/smoke_qwen3_8b.sh b/scripts/smoke_qwen3_8b.sh
new file mode 100755
index 00000000..e39090c1
--- /dev/null
+++ b/scripts/smoke_qwen3_8b.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+# Qwen3-8B correctness smoke (docs/campaigns/open-model-qwen3/SMOKE-8B-v1.md, sc#384).
+# smoke_qwen3_8b.sh verify sha256 of config.json and the five shards only
+# smoke_qwen3_8b.sh cpu verify, then the CPU reference leg; records the golden ids
+# (refuses to overwrite an existing golden file)
+# smoke_qwen3_8b.sh gb10 verify, then the GB10 leg against the golden ids.
+# OWNS THE CHIP: only after the whole-system runs have finished.
+# Env: MODEL_DIR (default ~/models/qwen3-8b), OUT (default $PWD/smoke-8b-out).
+set -uo pipefail
+REPO=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
+MODEL_DIR=${MODEL_DIR:-$HOME/models/qwen3-8b}
+OUT=${OUT:-$PWD/smoke-8b-out}
+GOLDEN=$REPO/docs/campaigns/open-model-qwen3/SMOKE-8B-v1.golden.json
+# Values recorded in docs/campaigns/open-model-qwen3/EVAL-qwen3-8b.md (Section 1, branch d1/qwen3-8b-eval).
+read -r -d '' SUMS <<'EOS'
+f7c4eadfbbf522470667b797a3c89be2524832d2d599797248dc304fff447c30 config.json
+31d6a825ae35f11fb85b195b4c42c146c051e446433125a215336abdf95cbf5f model-00001-of-00005.safetensors
+5991236cea6fe21f3d43cab0f0e84448734fbbe0789816202989f2ddc9d18282 model-00002-of-00005.safetensors
+c5185c4794be2d8a9784d5753c9922db38df478ce11f9ed0b415b7304d896836 model-00003-of-00005.safetensors
+b5ee7de71fbf17db3d5704e0c8f2bc7d005ca9e1d7ca2aeb19827b0cfcaa917a model-00004-of-00005.safetensors
+20c2d6366ab85c90786ccdd829cd2b9e7d30ef3b2ebbb998280e7e4014b542ff model-00005-of-00005.safetensors
+EOS
+fail() { echo "SMOKE-8B FAIL: $*" >&2; exit 1; }
+verify() {
+ [ -d "$MODEL_DIR" ] || fail "no model directory $MODEL_DIR"
+ ( cd "$MODEL_DIR" && printf '%s\n' "$SUMS" | sha256sum -c --quiet - ) || fail "sha256 mismatch in $MODEL_DIR"
+ echo "sha256 ok: config.json and 5 shards"
+}
+build() { # $1 = cpu|gb10
+ if [ "$1" = gb10 ]; then
+ # The pinned GPU engine, as scripts/whole_system_e2e.sh G1 does (env.sh: native libs required, no dev fallback).
+ local pins=$OUT/pins
+ bash "$REPO/scripts/pins.sh" --gpu "$pins" >"$OUT/pins.txt" 2>&1 || fail "pins.sh --gpu failed, see $OUT/pins.txt"
+ ( cd "$REPO" && . "$pins/env.sh" && CARGO_TARGET_DIR="$OUT/target-gb10" \
+ cargo build --release -p aien-runtime --example qwen3_8b_smoke ) >"$OUT/build-gb10.log" 2>&1 || fail "build failed, see $OUT/build-gb10.log"
+ grep -q -E "building the (CPU )?stub|developer override" "$OUT/build-gb10.log" && fail "stub engine build"
+ BIN=$OUT/target-gb10/release/examples/qwen3_8b_smoke
+ else
+ ( cd "$REPO" && CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$OUT/target-cpu}" \
+ cargo build --release -p aien-runtime --example qwen3_8b_smoke ) >"$OUT/build-cpu.log" 2>&1 || fail "build failed, see $OUT/build-cpu.log"
+ BIN=${CARGO_TARGET_DIR:-$OUT/target-cpu}/release/examples/qwen3_8b_smoke
+ fi
+ [ -x "$BIN" ] || fail "no binary at $BIN"
+}
+mkdir -p "$OUT"
+case "${1:-}" in
+ verify) verify ;;
+ cpu)
+ verify; build cpu
+ [ -e "$GOLDEN" ] && fail "golden file exists ($GOLDEN); delete it deliberately to re-record"
+ T0=$(date +%s)
+ "$BIN" "$MODEL_DIR" cpu >"$OUT/cpu.json" 2>"$OUT/cpu.err" || fail "cpu leg exit $?, see $OUT/cpu.err"
+ echo "cpu leg wall seconds: $(( $(date +%s) - T0 ))"
+ jq -e '(.leg=="cpu") and (.prompts|length==2) and (all(.prompts[]; .output_ids|length>0)) and (.prompts[1].output_ids|length>=16) and (.fallback_count==0)' "$OUT/cpu.json" >/dev/null || fail "cpu result not well formed"
+ jq '{golden_for:"SMOKE-8B-v1", source:"CPU reference leg", prompts:[.prompts[]|{name,prompt_sha256,prompt_ids,output_ids,reply}]}' "$OUT/cpu.json" >"$GOLDEN"
+ echo "golden output_ids: $(jq -c '[.prompts[].output_ids]' "$GOLDEN")"
+ echo "CPU leg done: golden recorded in $GOLDEN (not a chip verdict)"
+ ;;
+ gb10)
+ verify
+ [ -s "$GOLDEN" ] || fail "no golden file $GOLDEN (run the cpu leg first)"
+ command -v quietlock >/dev/null && { quietlock check || fail "quiet flag held: another run owns the machine"; }
+ pgrep -f whole_system_e2e.sh >/dev/null && fail "a whole-system run is live; the chip is not free"
+ build gb10
+ env -u AIEN_DEV_FALLBACK -u AIEN_OMEGA_CTA_BUDGET -u AIEN_OMEGA_SPIN_US AIEN_GPU_BACKEND=omega AIEN_REQUIRE_BLACKWELL=1 \
+ "$BIN" "$MODEL_DIR" gb10 >"$OUT/gb10.json" 2>"$OUT/gb10.err" || fail "gb10 leg exit $?, see $OUT/gb10.err"
+ jq -e '.leg=="gb10"' "$OUT/gb10.json" >/dev/null || fail "gb10 result not well formed"
+ [ "$(jq -c '[.prompts[]|[.name,.prompt_ids,.output_ids]]' "$OUT/gb10.json")" = "$(jq -c '[.prompts[]|[.name,.prompt_ids,.output_ids]]' "$GOLDEN")" ] || fail "prompt or output ids differ from the CPU golden (both prompts must be equal)"
+ [ "$(jq .fallback_count "$OUT/gb10.json")" = 0 ] || fail "fallback_count is $(jq .fallback_count "$OUT/gb10.json"), not 0"
+ echo "SMOKE-8B PASS (GB10 token ids equal the CPU golden, fallback_count 0)"
+ ;;
+ *) echo "usage: $0 verify|cpu|gb10" >&2; exit 2 ;;
+esac