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

GitHub aien-dev/aien-sovereign-core-mv#269 (code only)

closed derived ded1770ec2cd014a #269

Imported from GitHub aien-dev/aien-sovereign-core-mv#269 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base b5dba3b2d2c0d750d99f9ce8028ce6a50c346cc8 · Head a1b29d81087f6df21fb3efeb0877791080b74d8a

Fetch it

A git bundle of the pull request's head, 11179 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/ded1770ec2cd014a.bundle -o ded1770ec2cd014a.bundle
git fetch ded1770ec2cd014a.bundle refs/pull/269/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
269
a1b29d81087f6df21fb3efeb0877791080b74d8a
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":269,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/269","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:36Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index 77c298f2..105ba69b 100644
--- a/.crumb
+++ b/.crumb
@@ -77,14 +77,14 @@
         }
       ],
       "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1",
-      "compiled_at": "2026-10-07T04:30:07Z",
+      "compiled_at": "2026-10-07T04:44:47Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:2659adb53bc1e96c50217db037cd03ff1b0b75dc39f672260b3d3fde91f0e78f",
+      "digest": "sha256:5b22a026d2783ab0392606303128a92cd76861d0a6ce2c0e492fdb68f6cef142",
       "evidence_files": 155,
       "evidence_root": "sha256:ff6dddfecfcc02cea55f46acaccc7eaecd27557209e98c3d5616ec02bdde31db",
-      "files": 1128,
-      "generated_at_commit": "d42909b6dd1e9ead5d055b8dad9e90c8e452a25b",
-      "source_tree": "sha256:35c0f520cea5e539c54e21c24a86e37d698d211e06591111ed693d021e403553"
+      "files": 1133,
+      "generated_at_commit": "2613af0fe3e86ff632a4f355578cad2e6404d306",
+      "source_tree": "sha256:27251f9ed88c7bae15b1cf6c7ded53d0eac6f6d1ffd38c78a798dc14ca9cef29"
     }
   },
   "history": [],
diff --git a/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/LICENSE b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/LICENSE
new file mode 100644
index 00000000..6634c8cc
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/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-4b-instruct-2507/PROVENANCE.md b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/PROVENANCE.md
new file mode 100644
index 00000000..032b62d5
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/PROVENANCE.md
@@ -0,0 +1,11 @@
+# Qwen3-4B-Instruct-2507 chat template (pinned)
+
+- Source: Hugging Face `Qwen/Qwen3-4B-Instruct-2507` revision cdbee75f17c01a7cc42f958dc650907174af0554,
+  `tokenizer_config.json` field `chat_template`, written byte for byte (no trailing newline) to `chat_template.jinja`.
+- Licence: Apache-2.0, upstream `LICENSE` copied unchanged into this folder. Not relicensed.
+- sha256 chat_template.jinja: 64f85b198065d0fba2a81f37e10ed68161ce2c19a754c7100e67e0ca2ee9c326
+- sha256 upstream tokenizer_config.json: a62ff0a2472a0fa1b8eaabcb57c59b58afa42a22831dc141400b6e0cf2b65ce3
+- sha256 LICENSE: 832dd9e00a68dd83b3c3fb9f5588dad7dcf337a0db50f7d9483f310cd292e92e
+- `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`, 8 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.
diff --git a/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/chat_template.jinja b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/chat_template.jinja
new file mode 100644
index 00000000..70adff8a
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/chat_template.jinja
@@ -0,0 +1,61 @@
+{%- 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 <tools></tools> XML tags:\n<tools>" }}
+    {%- for tool in tools %}
+        {{- "\n" }}
+        {{- tool | tojson }}
+    {%- endfor %}
+    {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
+{%- else %}
+    {%- if messages[0].role == 'system' %}
+        {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
+    {%- endif %}
+{%- endif %}
+{%- 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" %}
+        {{- '<|im_start|>' + message.role + '\n' + content }}
+        {%- 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 %}
+                {{- '<tool_call>\n{"name": "' }}
+                {{- tool_call.name }}
+                {{- '", "arguments": ' }}
+                {%- if tool_call.arguments is string %}
+                    {{- tool_call.arguments }}
+                {%- else %}
+                    {{- tool_call.arguments | tojson }}
+                {%- endif %}
+                {{- '}\n</tool_call>' }}
+            {%- endfor %}
+        {%- endif %}
+        {{- '<|im_end|>\n' }}
+    {%- elif message.role == "tool" %}
+        {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
+            {{- '<|im_start|>user' }}
+        {%- endif %}
+        {{- '\n<tool_response>\n' }}
+        {{- content }}
+        {{- '\n</tool_response>' }}
+        {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
+            {{- '<|im_end|>\n' }}
+        {%- endif %}
+    {%- endif %}
+{%- endfor %}
+{%- if add_generation_prompt %}
+    {{- '<|im_start|>assistant\n' }}
+{%- endif %}
\ No newline at end of file
diff --git a/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/render_oracle.json b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/render_oracle.json
new file mode 100644
index 00000000..d2b2107e
--- /dev/null
+++ b/crates/aien-inference-abi/fixtures/chat-templates/qwen3-4b-instruct-2507/render_oracle.json
@@ -0,0 +1,113 @@
+{
+ "oracle": "jinja2 3.1.6 ImmutableSandboxedEnvironment(trim_blocks, lstrip_blocks)",
+ "cases": [
+  {
+   "turns": [
+    [
+     "user",
+     "Hello"
+    ]
+   ],
+   "add_generation_prompt": true,
+   "text": "<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n"
+  },
+  {
+   "turns": [
+    [
+     "system",
+     "You are AIEN."
+    ],
+    [
+     "user",
+     "List two primes."
+    ]
+   ],
+   "add_generation_prompt": true,
+   "text": "<|im_start|>system\nYou are AIEN.<|im_end|>\n<|im_start|>user\nList two primes.<|im_end|>\n<|im_start|>assistant\n"
+  },
+  {
+   "turns": [
+    [
+     "system",
+     "Be brief."
+    ],
+    [
+     "user",
+     "2+2?"
+    ],
+    [
+     "assistant",
+     "4."
+    ],
+    [
+     "user",
+     "And 3+3?"
+    ]
+   ],
+   "add_generation_prompt": true,
+   "text": "<|im_start|>system\nBe brief.<|im_end|>\n<|im_start|>user\n2+2?<|im_end|>\n<|im_start|>assistant\n4.<|im_end|>\n<|im_start|>user\nAnd 3+3?<|im_end|>\n<|im_start|>assistant\n"
+  },
+  {
+   "turns": [
+    [
+     "user",
+     "  padded \n"
+    ]
+   ],
+   "add_generation_prompt": true,
+   "text": "<|im_start|>user\n  padded \n<|im_end|>\n<|im_start|>assistant\n"
+  },
+  {
+   "turns": [
+    [
+     "user",
+     ""
+    ]
+   ],
+   "add_generation_prompt": true,
+   "text": "<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n"
+  },
+  {
+   "turns": [
+    [
+     "user",
+     "a"
+    ],
+    [
+     "system",
+     "b"
+    ],
+    [
+     "user",
+     "c"
+    ]
+   ],
+   "add_generation_prompt": true,
+   "text": "<|im_start|>user\na<|im_end|>\n<|im_start|>system\nb<|im_end|>\n<|im_start|>user\nc<|im_end|>\n<|im_start|>assistant\n"
+  },
+  {
+   "turns": [
+    [
+     "user",
+     "Say hi."
+    ],
+    [
+     "assistant",
+     "Hi"
+    ]
+   ],
+   "add_generation_prompt": false,
+   "text": "<|im_start|>user\nSay hi.<|im_end|>\n<|im_start|>assistant\nHi<|im_end|>\n"
+  },
+  {
+   "turns": [
+    [
+     "user",
+     "unicode: é中😀 <tag> {{x}}"
+    ]
+   ],
+   "add_generation_prompt": true,
+   "text": "<|im_start|>user\nunicode: é中😀 <tag> {{x}}<|im_end|>\n<|im_start|>assistant\n"
+  }
+ ]
+}
diff --git a/crates/aien-inference-abi/src/tokenizer.rs b/crates/aien-inference-abi/src/tokenizer.rs
index fa63e19f..4f3827a0 100644
--- a/crates/aien-inference-abi/src/tokenizer.rs
+++ b/crates/aien-inference-abi/src/tokenizer.rs
@@ -53,9 +53,10 @@ pub enum ChatTemplate {
     /// (the Hugging Face template's default "Cutting Knowledge Date / Today Date" block
     /// depends on the wall clock, so it is left out).
     Llama3,
-    /// ChatML exactly as the publisher's template renders it (SmolLM2-Instruct): per turn
-    /// `<|im_start|>{role}\n{content}<|im_end|>\n`, then `<|im_start|>assistant\n`. Contents
-    /// are kept verbatim and empty turns are kept (the template neither trims nor skips).
+    /// ChatML exactly as the publisher's template renders it (SmolLM2-Instruct, and
+    /// Qwen3-4B-Instruct-2507 without tools): per turn `<|im_start|>{role}\n{content}<|im_end|>\n`,
+    /// then `<|im_start|>assistant\n`. Contents are kept verbatim and empty turns are kept
+    /// (the template neither trims nor skips).
     /// When the template carries a default system message and the first turn is not a
     /// system turn, that message is rendered first as a system turn, as the template does.
     /// No BOS is part of the text; the model's tokenizer decides whether `encode` adds one
@@ -80,11 +81,19 @@ pub enum ChatTemplate {
 const CHATML_WITH_DEFAULT_SYSTEM: &str = "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\n{SYSTEM}<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}";
 const CHATML_PLAIN: &str = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}";
 
-/// Matches a chat template text against the two ChatML layouts above. Returns the layout
+/// The Qwen3-4B-Instruct-2507 chat template, byte for byte (revision cdbee75f, Apache-2.0; see
+/// `fixtures/chat-templates/qwen3-4b-instruct-2507/PROVENANCE.md`). Without tools and without
+/// assistant tool calls (this engine passes neither) it renders exactly the plain ChatML layout:
+/// no default system message, contents verbatim, generation prompt `<|im_start|>assistant\n`.
+/// Any other Qwen template text (tools in use, thinking blocks, another revision) is refused.
+const QWEN3_INSTRUCT_2507: &str =
+    include_str!("../fixtures/chat-templates/qwen3-4b-instruct-2507/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<ChatTemplate, TokenizerError> {
     let text = template_text.trim();
-    if text == CHATML_PLAIN {
+    if text == CHATML_PLAIN || text == QWEN3_INSTRUCT_2507.trim() {
         return Ok(ChatTemplate::ChatMl {
             default_system: None,
         });
diff --git a/crates/aien-inference-abi/tests/qwen3_chat_template.rs b/crates/aien-inference-abi/tests/qwen3_chat_template.rs
new file mode 100644
index 00000000..c2137b66
--- /dev/null
+++ b/crates/aien-inference-abi/tests/qwen3_chat_template.rs
@@ -0,0 +1,132 @@
+//! Qwen3-4B-Instruct-2507 chat template: the pinned template text is recognized, the engine's
+//! rendering equals the reference Jinja rendering (fixtures/chat-templates/.../render_oracle.json)
+//! for every recorded conversation, and any altered Qwen template is refused.
+
+use aien_inference_abi::tokenizer::ChatTemplate;
+
+const DIR: &str = concat!(
+    env!("CARGO_MANIFEST_DIR"),
+    "/fixtures/chat-templates/qwen3-4b-instruct-2507"
+);
+
+fn template() -> String {
+    std::fs::read_to_string(format!("{DIR}/chat_template.jinja")).unwrap()
+}
+
+#[test]
+fn pinned_template_is_plain_chatml_without_default_system() {
+    let t = ChatTemplate::detect(&template()).expect("Qwen3-4B-Instruct-2507 template accepted");
+    assert_eq!(
+        t,
+        ChatTemplate::ChatMl {
+            default_system: None
+        }
+    );
+    assert_eq!(t.default_system(), None);
+}
+
+#[test]
+fn rendering_matches_the_reference_jinja_rendering() {
+    let oracle: serde_json::Value = serde_json::from_str(
+        &std::fs::read_to_string(format!("{DIR}/render_oracle.json")).unwrap(),
+    )
+    .unwrap();
+    let t = ChatTemplate::detect(&template()).unwrap();
+    let cases = oracle["cases"].as_array().unwrap();
+    assert_eq!(cases.len(), 8);
+    for (i, case) in cases.iter().enumerate() {
+        let turns: Vec<(String, String)> = case["turns"]
+            .as_array()
+            .unwrap()
+            .iter()
+            .map(|p| {
+                (
+                    p[0].as_str().unwrap().to_string(),
+                    p[1].as_str().unwrap().to_string(),
+                )
+            })
+            .collect();
+        let refs: Vec<(&str, &str)> = turns
+            .iter()
+            .map(|(r, c)| (r.as_str(), c.as_str()))
+            .collect();
+        let ends_in_assistant = refs
+            .last()
+            .is_some_and(|(r, c)| *r == "assistant" && !c.trim().is_empty());
+        // The engine opens a generation prompt unless the last turn is a non-empty assistant
+        // turn; the oracle case records which of the two it rendered.
+        assert_eq!(
+            case["add_generation_prompt"].as_bool().unwrap(),
+            !ends_in_assistant,
+            "case {i}: oracle generated with the other generation-prompt setting"
+        );
+        assert_eq!(
+            t.try_render(&refs).unwrap(),
+            case["text"].as_str().unwrap(),
+            "case {i}"
+        );
+    }
+}
+
+#[test]
+fn altered_qwen_templates_are_refused() {
+    let base = template();
+    let altered = [
+        // Qwen3-4B (original) style thinking tail after the generation prompt.
+        base.replace(
+            "{{- '<|im_start|>assistant\\n' }}",
+            "{{- '<|im_start|>assistant\\n<think>\\n\\n</think>\\n\\n' }}",
+        ),
+        // Contents trimmed.
+        base.replace(
+            "{%- set content = message.content %}",
+            "{%- set content = message.content | trim %}",
+        ),
+        // A default system message added.
+        base.replacen(
+            "{%- else %}",
+            "{%- else %}\n    {{- '<|im_start|>system\\nYou are Qwen.<|im_end|>\\n' }}",
+            1,
+        ),
+        // One byte appended inside the template.
+        format!("{base}{{# #}}"),
+    ];
+    for (i, text) in altered.iter().enumerate() {
+        assert_ne!(text, &base, "alteration {i} did not change the template");
+        assert!(
+            ChatTemplate::detect(text).is_err(),
+            "altered template {i} was accepted"
+        );
+    }
+}
+
+/// The real model directory (weights not needed): `AIEN_QWEN3_DIR=<dir> cargo test -p
+/// aien-inference-abi --test qwen3_chat_template -- --ignored`. Fails, never skips, when unset.
+#[test]
+#[ignore = "needs the Qwen3-4B-Instruct-2507 model directory in AIEN_QWEN3_DIR"]
+fn real_model_dir_loads_with_the_pinned_template() {
+    use aien_inference_abi::tokenizer::ChatTokenizer;
+    let dir = std::env::var("AIEN_QWEN3_DIR").expect("AIEN_QWEN3_DIR is not set");
+    let tok = ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None).unwrap();
+    assert_eq!(
+        tok.template(),
+        ChatTemplate::ChatMl {
+            default_system: None
+        }
+    );
+    let im_end = tok.token_to_id("<|im_end|>").expect("<|im_end|> in vocab");
+    assert!(
+        tok.stop_token_ids().contains(&im_end),
+        "<|im_end|> must stop generation"
+    );
+    let text = tok
+        .try_format_chat(&[("system", "You are AIEN."), ("user", "List two primes.")])
+        .unwrap();
+    let ids = tok.encode(&text).unwrap();
+    assert_eq!(
+        ids.first().copied(),
+        tok.token_to_id("<|im_start|>"),
+        "no BOS is added"
+    );
+    assert_eq!(ids.iter().filter(|&&t| t == im_end).count(), 2);
+}