Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/8e5d1143b7b4b860 # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#265 (code only) closed derived `8e5d1143b7b4b860` #265 Imported from GitHub aien-dev/aien-sovereign-core-mv#265 (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 `4f4ca68840a163b9fbc6b0253cb45a9504f03a0d` · Head `80c44da26b98ef5e0fe99f8d2f9957057bf27b3b` ### Fetch it A git bundle of the pull request's head, 64375 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/8e5d1143b7b4b860.bundle -o 8e5d1143b7b4b860.bundle git fetch 8e5d1143b7b4b860.bundle refs/pull/265/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 265 80c44da26b98ef5e0fe99f8d2f9957057bf27b3b ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":265,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/265","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:35Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 20b16d43..a196cd3c 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:4ff1a56b7c8ac606ad5709f2ba1141f16055c34f5f242ac491233dca20d5153e", - "compiled_at": "2026-10-07T03:12:39Z", + "compiled_at": "2026-10-07T03:37:34Z", "compiler": "crumb-compile/1", - "digest": "sha256:e7fad4dcac6c621181a7cb2d6dacbea9d7fd217cf5b23eb6171b8a7a42917b4d", + "digest": "sha256:9c94e6a0360e0904f07fd35e6dd1ae960c62f62b9d5043e6242d7cc08e3dca86", "evidence_files": 155, "evidence_root": "sha256:ff6dddfecfcc02cea55f46acaccc7eaecd27557209e98c3d5616ec02bdde31db", - "files": 1106, - "generated_at_commit": "ec1891165204a5114781513c04b24a284e6eb404", - "source_tree": "sha256:3e4d3a33a5e90481eeb10be72b8e24893eed8a3273b692a0d67a288947492265" + "files": 1119, + "generated_at_commit": "a914490eb8ae8f9582ec31b498497eb4483ac400", + "source_tree": "sha256:116073775100d240cef5d339050b961d09e8538c2f141d89bf888ead349fdf69" } }, "history": [], diff --git a/crates/aien-abi-core/src/lib.rs b/crates/aien-abi-core/src/lib.rs index 8fa6ecfa..ff67dd75 100644 --- a/crates/aien-abi-core/src/lib.rs +++ b/crates/aien-abi-core/src/lib.rs @@ -150,6 +150,13 @@ pub struct ModelConfig { /// Empty means the legacy TinyLlama set, see [`ModelConfig::stop_token_ids`]. #[serde(default)] pub eos_token_ids: Vec, + /// True for Qwen3 (`Qwen3ForCausalLM`): every attention layer carries per-head RMSNorm + /// weights `self_attn.q_norm.weight` and `self_attn.k_norm.weight` (length `head_dim`), + /// applied to Q and K per head before RoPE. `head_dim` is then read from `config.json` + /// and `num_heads * head_dim` may differ from `hidden_dim`. Not serialized when false, so + /// every other model's serialized config is unchanged. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub qk_norm: bool, } /// Why an [`AttentionGeometry`] was refused. Every variant names the offending numbers so a @@ -364,6 +371,7 @@ impl ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } @@ -438,6 +446,7 @@ impl Default for ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } } diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 9bac57ff..9bcb974e 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "1c1e7ea90bd280ec2616a754131b2315453b0a51a2d8cc8e3c2954e6e9b5f6e7", - "last_commit": "56ed257", + "digest": "6a6cc7468724c1e39da5894f241e7624a1e06cb1ba64aa1a57b11c8561cffcb2", + "last_commit": "a914490", "name": "src", "purpose": "" } ], - "children_root": "sha256:8b286db0ae4f814fa398b7f3ffc0a487227759a0137797f3203c733ce88edf03", - "compiled_at": "2026-10-07T02:28:51Z", + "children_root": "sha256:ece32049063166417cb3a3776ce48142e7d8508419ca2137329b429105347b01", + "compiled_at": "2026-10-07T03:37:34Z", "compiler": "crumb-compile/1", - "digest": "sha256:5c4ce8cc01bf96f38d988d9a09da42d86876cf40968a5cabcda3b69aa4a52b6a", + "digest": "sha256:49c03271c3d397db12777d39f844007b87ae1e684a0c1a522c3341f024391d0a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 28, - "generated_at_commit": "9119485e6358f70ba463997290e0f3be51aecb24", - "source_tree": "sha256:1c5b12e7c0e143ec1e1533e0f3e2e7306b6c7ab121e2fee412e6ce86cefe526f" + "generated_at_commit": "a914490eb8ae8f9582ec31b498497eb4483ac400", + "source_tree": "sha256:1a0913028dd44628b2524bd46371813d7e17182776a4ae4cfe79339ce426ca03" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index f7b4e8b6..48649b52 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-07T02:28:51Z", + "compiled_at": "2026-10-07T03:37:34Z", "compiler": "crumb-compile/1", - "digest": "sha256:1c1e7ea90bd280ec2616a754131b2315453b0a51a2d8cc8e3c2954e6e9b5f6e7", + "digest": "sha256:6a6cc7468724c1e39da5894f241e7624a1e06cb1ba64aa1a57b11c8561cffcb2", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 25, - "generated_at_commit": "9119485e6358f70ba463997290e0f3be51aecb24", - "source_tree": "sha256:63cc47424618d8c2adf61f08f6d8de6a50d09e2552e6392a8f93fe48de6886b4" + "generated_at_commit": "a914490eb8ae8f9582ec31b498497eb4483ac400", + "source_tree": "sha256:a229666f3c0ca085e00955867c49c65e30aaf99cff891f64aff548c808d8d118" } }, "history": [ diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 5926e5ec..389befb9 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1111,6 +1111,7 @@ fn reference_config() -> aien_inference_abi::ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } diff --git a/crates/aien-inference-abi/examples/profile_ops.rs b/crates/aien-inference-abi/examples/profile_ops.rs index 411d05bc..7551316d 100644 --- a/crates/aien-inference-abi/examples/profile_ops.rs +++ b/crates/aien-inference-abi/examples/profile_ops.rs @@ -22,6 +22,7 @@ fn main() { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, }; let safetensors_path = "/home/drakestapleton/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6/model.safetensors"; diff --git a/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/LICENSE b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/LICENSE new file mode 100644 index 00000000..6634c8cc --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/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/qwen3-4b-instruct-2507-config/PROVENANCE.md b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/PROVENANCE.md new file mode 100644 index 00000000..b8460686 --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/PROVENANCE.md @@ -0,0 +1,7 @@ +config.json, generation_config.json and LICENSE are unmodified copies from +https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507 at revision +cdbee75f17c01a7cc42f958dc650907174af0554 (Apache License 2.0, copyright Alibaba Cloud / Qwen team, +see LICENSE in this directory). No weights are committed. +real_forward_reference.json: top-20 last-position logits for the ids of "The capital of France is" +(Qwen tokenizer, no special tokens), transformers 5.17.0 + torch 2.14.0, CPU, float32, loaded from +the bf16 checkpoint of that revision by a scratch script outside the repository. diff --git a/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/config.json b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/config.json new file mode 100644 index 00000000..6988f134 --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/config.json @@ -0,0 +1,30 @@ +{ + "architectures": [ + "Qwen3ForCausalLM" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bos_token_id": 151643, + "eos_token_id": 151645, + "head_dim": 128, + "hidden_act": "silu", + "hidden_size": 2560, + "initializer_range": 0.02, + "intermediate_size": 9728, + "max_position_embeddings": 262144, + "max_window_layers": 36, + "model_type": "qwen3", + "num_attention_heads": 32, + "num_hidden_layers": 36, + "num_key_value_heads": 8, + "rms_norm_eps": 1e-06, + "rope_scaling": null, + "rope_theta": 5000000, + "sliding_window": null, + "tie_word_embeddings": true, + "torch_dtype": "bfloat16", + "transformers_version": "4.51.0", + "use_cache": true, + "use_sliding_window": false, + "vocab_size": 151936 +} \ No newline at end of file diff --git a/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/generation_config.json b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/generation_config.json new file mode 100644 index 00000000..432531a0 --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/generation_config.json @@ -0,0 +1,13 @@ +{ + "bos_token_id": 151643, + "do_sample": true, + "eos_token_id": [ + 151645, + 151643 + ], + "pad_token_id": 151643, + "temperature": 0.7, + "top_k": 20, + "top_p": 0.8, + "transformers_version": "4.51.0" +} \ No newline at end of file diff --git a/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/real_forward_reference.json b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/real_forward_reference.json new file mode 100644 index 00000000..d4238539 --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config/real_forward_reference.json @@ -0,0 +1,58 @@ +{ + "tool": "transformers 5.17.0 torch 2.14.0+cu130 (CPU, float32 loaded from the bf16 checkpoint)", + "model": "Qwen/Qwen3-4B-Instruct-2507 rev cdbee75f17c01a7cc42f958dc650907174af0554", + "prompt": "The capital of France is (no chat template, no special tokens)", + "ids": [ + 785, + 6722, + 315, + 9625, + 374 + ], + "argmax": 12095, + "top_ids": [ + 12095, + 7407, + 32671, + 304, + 30743, + 1304, + 1128, + 264, + 510, + 537, + 1447, + 5267, + 3881, + 1939, + 279, + 7148, + 65892, + 30, + 892, + 198 + ], + "top_logits": [ + 16.569156646728516, + 13.840231895446777, + 13.586695671081543, + 13.18361759185791, + 13.038496971130371, + 12.952102661132812, + 12.822670936584473, + 12.635554313659668, + 12.42106819152832, + 12.337651252746582, + 12.2235746383667, + 12.109580039978027, + 12.070366859436035, + 12.070148468017578, + 11.967041015625, + 11.862318992614746, + 11.730515480041504, + 11.441274642944336, + 11.338995933532715, + 11.102069854736328 + ], + "vocab": 151936 +} \ No newline at end of file diff --git a/crates/aien-inference-abi/fixtures/qwen3-tiny/PROVENANCE.md b/crates/aien-inference-abi/fixtures/qwen3-tiny/PROVENANCE.md new file mode 100644 index 00000000..930d5648 --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-tiny/PROVENANCE.md @@ -0,0 +1,9 @@ +Tiny random Qwen3ForCausalLM (seed 20261007; 2 layers, hidden 32, 4 heads, 2 KV heads, head_dim 16, +tied embeddings, q/k norm weights randomised) generated by a scratch script outside the repository +with transformers 5.17.0 + torch 2.14.0 (CPU), saved as bf16 safetensors. config.json is the +saved config rewritten in the Hugging Face 4.51 layout of the real Qwen3 checkpoints (rope_theta +and rope_scaling null instead of transformers 5's rope_parameters). forward_reference.json holds +last-position logits for ids [0, 5, 17, 42, 9, 33] computed in float32 from the bf16 weights. +The reference model is reloaded from the saved bf16 files in float32 (a bf16 round trip of the live +model also rounds the rotary inv_freq buffer and shifts logits by about 1e-4). float32 versus +float64 of the same model differ by 6.5e-7, so the oracle itself is accurate to that level. diff --git a/crates/aien-inference-abi/fixtures/qwen3-tiny/config.json b/crates/aien-inference-abi/fixtures/qwen3-tiny/config.json new file mode 100644 index 00000000..c278127c --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-tiny/config.json @@ -0,0 +1,35 @@ +{ + "architectures": [ + "Qwen3ForCausalLM" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bos_token_id": 0, + "eos_token_id": 1, + "head_dim": 16, + "hidden_act": "silu", + "hidden_size": 32, + "initializer_range": 0.02, + "intermediate_size": 48, + "layer_types": [ + "full_attention", + "full_attention" + ], + "max_position_embeddings": 128, + "max_window_layers": 28, + "model_type": "qwen3", + "num_attention_heads": 4, + "num_hidden_layers": 2, + "num_key_value_heads": 2, + "pad_token_id": 0, + "rms_norm_eps": 0.000001, + "sliding_window": null, + "tie_word_embeddings": true, + "transformers_version": "4.51.0", + "use_cache": true, + "use_sliding_window": false, + "vocab_size": 64, + "rope_theta": 1000000, + "rope_scaling": null, + "torch_dtype": "bfloat16" +} diff --git a/crates/aien-inference-abi/fixtures/qwen3-tiny/forward_reference.json b/crates/aien-inference-abi/fixtures/qwen3-tiny/forward_reference.json new file mode 100644 index 00000000..3827ae51 --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-tiny/forward_reference.json @@ -0,0 +1 @@ +{"tool": "transformers 5.17.0 torch 2.14.0+cu130 (CPU, float32 after upcasting the bf16 weights)", "model": "tiny random Qwen3ForCausalLM, seed 20261007, 2 layers, hidden 32, 4 heads, 2 kv heads, head_dim 16, tied, norms randomised", "ids": [0, 5, 17, 42, 9, 33], "argmax": 38, "logits": [-0.43972060084342957, -0.8615236282348633, 0.7856644988059998, -0.5695605874061584, -0.26251330971717834, 0.43897300958633423, -0.6595174670219421, -0.3013143539428711, -0.8841713070869446, -0.5845550298690796, -0.13791656494140625, -0.22891409695148468, 0.2053021788597107, -0.25369906425476074, 0.9904226660728455, -0.6887377500534058, -1.0605151653289795, 0.8110088109970093, -0.15679602324962616, -0.6564469933509827, 0.27932700514793396, 0.36428695917129517, 0.03732987493276596, -0.02165655419230461, -0.48203378915786743, 0.7794568538665771, 0.09148486703634262, -1.1038419008255005, 0.22095604240894318, -0.836110532283783, 0.7729686498641968, -1.0997055768966675, 0.5189003348350525, -0.20644450187683105, 0.6058120131492615, 0.44640621542930603, -0.24257118999958038, 1.1544275283813477, 1.190962791442871, 0.5008851289749146, 0.07899382710456848, -0.10305533558130264, 0.4617588222026825, -0.3543776869773865, -0.2719959616661072, -0.22959710657596588, -0.37634485960006714, 0.0417044572532177, -0.5611942410469055, -0.09111856669187546, 0.6225908994674683, -0.5858741998672485, 0.8129835724830627, 0.15753836929798126, 0.5058656334877014, 0.28459569811820984, 0.320931077003479, -0.15769094228744507, -0.17418505251407623, -0.018768038600683212, 1.0287829637527466, -0.48321667313575745, 0.14080524444580078, 1.1559228897094727]} \ No newline at end of file diff --git a/crates/aien-inference-abi/fixtures/qwen3-tiny/generation_config.json b/crates/aien-inference-abi/fixtures/qwen3-tiny/generation_config.json new file mode 100644 index 00000000..2ea16d14 --- /dev/null +++ b/crates/aien-inference-abi/fixtures/qwen3-tiny/generation_config.json @@ -0,0 +1,10 @@ +{ + "_from_model_config": true, + "bos_token_id": 0, + "eos_token_id": 1, + "output_attentions": false, + "output_hidden_states": false, + "pad_token_id": 0, + "transformers_version": "5.17.0", + "use_cache": true +} diff --git a/crates/aien-inference-abi/fixtures/qwen3-tiny/model.safetensors b/crates/aien-inference-abi/fixtures/qwen3-tiny/model.safetensors new file mode 100644 index 00000000..e197ceb9 Binary files /dev/null and b/crates/aien-inference-abi/fixtures/qwen3-tiny/model.safetensors differ diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index 96d71e50..724cfb36 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -4,7 +4,7 @@ use crate::tensor::{ apply_rope_params as tensor_rope, matmul_vec as tensor_matmul, rmsnorm as tensor_rmsnorm, }; -use aien_abi_core::{AttentionGeometry, RopeParams}; +use aien_abi_core::{AttentionGeometry, ModelConfig, RopeParams}; /// The trait's attention methods return `()`, so a wrong head layout cannot be reported as an /// error value; it must never turn into numbers either. These helpers refuse loudly (panic with @@ -130,6 +130,12 @@ pub trait TensorBackend: Send + Sync { /// Human-readable name of the backend implementation. fn name(&self) -> &'static str; + /// Refuses a model this backend cannot run correctly, before any forward pass. Default: + /// accepts everything. Called at the start of every forward pass. + fn check_model(&self, _config: &ModelConfig) -> Result<(), String> { + Ok(()) + } + /// How many operations this backend ran on a software fallback instead of /// the device it was bound to. Zero for pure CPU backends; a production /// build treats a non-zero count as a strict real-model violation. diff --git a/crates/aien-inference-abi/src/checkpoint.rs b/crates/aien-inference-abi/src/checkpoint.rs index 4a362489..b782ac33 100644 --- a/crates/aien-inference-abi/src/checkpoint.rs +++ b/crates/aien-inference-abi/src/checkpoint.rs @@ -228,7 +228,8 @@ pub fn tinyllama_catalog() -> Vec<(String, Vec)> { catalog } -/// The tensor catalog of a Llama-architecture checkpoint (`LlamaForCausalLM`) described by +/// The tensor catalog of a Llama-architecture checkpoint (`LlamaForCausalLM`, or Qwen3 with +/// per-layer `q_norm`/`k_norm` when `config.qk_norm`) described by /// `config`: names and shapes of every tensor the forward pass reads. `lm_head.weight` is /// left out when the model ties its output projection to `model.embed_tokens.weight`. /// For `ModelConfig::tinyllama_1_1b()` this is exactly [`tinyllama_catalog`]. @@ -238,7 +239,7 @@ pub fn llama_catalog(config: &aien_abi_core::ModelConfig) -> Vec<(String, Vec Vec<(String, Vec Result<(), String> { + let obj = raw.as_object().ok_or("config.json is not an object")?; + if let Some(key) = obj.keys().find(|k| !QWEN3_KNOWN_KEYS.contains(&k.as_str())) { + return Err(format!("unsupported Qwen3 config field {key:?}")); + } + match obj.get("model_type").and_then(|v| v.as_str()) { + Some("qwen3") => {} + other => { + return Err(format!( + "unsupported model_type {other:?} for Qwen3ForCausalLM (expected \"qwen3\")" + )) + } + } + if !obj.get("head_dim").is_some_and(|v| v.is_u64()) { + return Err( + "Qwen3 config.json must set head_dim (it is not hidden_size / num_attention_heads)" + .to_string(), + ); + } + if obj + .get("use_sliding_window") + .is_some_and(|v| v != &serde_json::Value::Bool(false)) + { + return Err("unsupported use_sliding_window (supported: false)".to_string()); + } + if obj.get("sliding_window").is_some_and(|v| !v.is_null()) { + return Err("unsupported sliding_window (supported: null)".to_string()); + } + if let Some(types) = obj.get("layer_types") { + let all_full = types + .as_array() + .is_some_and(|a| a.iter().all(|t| t.as_str() == Some("full_attention"))); + if !all_full { + return Err( + "unsupported layer_types (supported: every layer full_attention)".to_string(), + ); + } + } + Ok(()) +} + /// KV page size used for every model loaded from a directory. const BLOCK_SIZE: usize = 16; @@ -89,7 +171,7 @@ fn parse_rope_scaling( } } -/// Builds the [`ModelConfig`] of a `LlamaForCausalLM` checkpoint from the text of its +/// Builds the [`ModelConfig`] of a `LlamaForCausalLM` or `Qwen3ForCausalLM` checkpoint from the text of its /// `config.json` and, when present, its `generation_config.json` (stop set: its /// `eos_token_id`, else the one in `config.json`). pub fn model_config_from_hf_json( @@ -101,12 +183,18 @@ pub fn model_config_from_hf_json( serde_json::from_str(config_json).map_err(|e| format!("config.json: {e}"))?; let hf: HfLlamaConfig = serde_json::from_value(raw.clone()).map_err(|e| format!("config.json: {e}"))?; - if hf.architectures.as_slice() != [LLAMA_ARCHITECTURE] { - return Err(format!( - "unsupported architectures {:?}: this engine runs [\"{LLAMA_ARCHITECTURE}\"] only", - hf.architectures - )); - } + let qk_norm = match hf.architectures.as_slice() { + [a] if a == LLAMA_ARCHITECTURE => false, + [a] if a == QWEN3_ARCHITECTURE => { + check_qwen3_fields(&raw)?; + true + } + other => { + return Err(format!( + "unsupported architectures {other:?}: this engine runs [\"{LLAMA_ARCHITECTURE}\"] or [\"{QWEN3_ARCHITECTURE}\"] only" + )) + } + }; if let Some(act) = hf.hidden_act.as_deref().filter(|a| *a != "silu") { return Err(format!("unsupported hidden_act {act:?} (supported: silu)")); } @@ -114,14 +202,14 @@ pub fn model_config_from_hf_json( return Err("unsupported attention_bias/mlp_bias = true (no bias tensors)".to_string()); } let num_heads = hf.num_attention_heads; - if num_heads == 0 || !hf.hidden_size.is_multiple_of(num_heads) { + if num_heads == 0 || (!qk_norm && !hf.hidden_size.is_multiple_of(num_heads)) { return Err(format!( "hidden_size {} is not a multiple of num_attention_heads {num_heads}", hf.hidden_size )); } - let head_dim = hf.head_dim.unwrap_or(hf.hidden_size / num_heads); - if head_dim * num_heads != hf.hidden_size { + let head_dim = hf.head_dim.unwrap_or(hf.hidden_size / num_heads.max(1)); + if !qk_norm && head_dim * num_heads != hf.hidden_size { return Err(format!( "unsupported head_dim {head_dim}: num_attention_heads * head_dim must equal hidden_size {}", hf.hidden_size @@ -153,6 +241,7 @@ pub fn model_config_from_hf_json( rope_scaling, tie_word_embeddings: hf.tie_word_embeddings, eos_token_ids, + qk_norm, }; config .attention_geometry() @@ -247,6 +336,7 @@ mod tests { assert_eq!( ModelConfig { eos_token_ids: Vec::new(), + qk_norm: false, ..from_json.clone() }, wired diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index b743f9bd..f21380cd 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -28,7 +28,7 @@ //! [`OmegaGb10Backend::clear_resident`] after changing weights. use crate::backend::{ReferenceCpuBackend, TensorBackend}; use crate::native_ops::{NativeOpMask, OpAccounting, OpReport, TensorOp}; -use aien_abi_core::RopeParams; +use aien_abi_core::{ModelConfig, RopeParams}; use aien_omega_gpu::ResidentTensor; use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; @@ -495,7 +495,26 @@ impl OmegaGb10Backend { } } +/// Why the GB10 engine refuses `config`, if it does: Qwen3 (`qk_norm`) has `head_dim` 128 and +/// the omega attention kernel is fixed at `head_dim` 64 (omega `omega_gpu_attention_api.h`), +/// and the per-head q/k norm runs only on the CPU reference path. Llama-architecture models +/// are not touched by this check. +pub fn omega_model_refusal(config: &ModelConfig) -> Option { + config.qk_norm.then(|| { + format!( + "OmegaGb10Backend refuses model {:?}: Qwen3 (per-head q/k norm, head_dim {}) is \ + unsupported on the GB10 engine, whose attention kernel supports head_dim 64 only; \ + run it on the CPU reference backend", + config.model_id, config.head_dim + ) + }) +} + impl TensorBackend for OmegaGb10Backend { + fn check_model(&self, config: &ModelConfig) -> Result<(), String> { + omega_model_refusal(config).map_or(Ok(()), Err) + } + fn name(&self) -> &'static str { if self.is_available() { "OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" diff --git a/crates/aien-inference-abi/src/tensor.rs b/crates/aien-inference-abi/src/tensor.rs index 1e35297e..a66b2a8e 100644 --- a/crates/aien-inference-abi/src/tensor.rs +++ b/crates/aien-inference-abi/src/tensor.rs @@ -94,6 +94,17 @@ pub fn rmsnorm(x: &[f32], weight: &[f32], eps: f32, out: &mut [f32]) { } } +/// Qwen3 per-head RMSNorm in place: `x` is `[heads][head_dim]`, every head is normalised over +/// its own `head_dim` values with the shared `weight` (`[head_dim]`), same maths as [`rmsnorm`]. +pub fn rmsnorm_heads_in_place(x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + assert!(head_dim > 0 && x.len().is_multiple_of(head_dim) && weight.len() == head_dim); + let mut scratch = vec![0.0f32; head_dim]; + for head in x.chunks_exact_mut(head_dim) { + rmsnorm(head, weight, eps, &mut scratch); + head.copy_from_slice(&scratch); + } +} + /// Applies Rotary Positional Embeddings (RoPE) to query and key head slices. /// Follows canonical Hugging Face LLaMA rotate_half pairing coordinate i with coordinate i + half_dim: /// out[i] = q[i] * cos - q[i + half_dim] * sin diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 97a98456..ae0b9b43 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -718,6 +718,7 @@ impl NativeTransformerBackend { .config .attention_geometry() .map_err(|e| e.to_string())?; + backend.check_model(&weights.config)?; let num_heads = geom.num_q_heads(); let num_kv_heads = geom.num_kv_heads(); let head_dim = geom.head_dim(); @@ -779,6 +780,7 @@ impl NativeTransformerBackend { backend.matmul_vec(&mut k, &x_norm, &layer_w.k_proj, kv_dim, hidden_dim); backend.matmul_vec(&mut v, &x_norm, &layer_w.v_proj, kv_dim, hidden_dim); + layer_w.apply_qk_norm(&mut q, &mut k, head_dim, eps); backend.apply_rope( &mut q, &mut k, @@ -971,6 +973,7 @@ impl NativeTransformerBackend { .config .attention_geometry() .map_err(|e| e.to_string())?; + backend.check_model(&weights.config)?; let num_heads = geom.num_q_heads(); let num_kv_heads = geom.num_kv_heads(); let head_dim = geom.head_dim(); @@ -1109,6 +1112,7 @@ impl NativeTransformerBackend { let v_t = &v_batch[t * kv_dim..(t + 1) * kv_dim]; let pos = offset + t; + layer_w.apply_qk_norm(q_t, k_t, head_dim, eps); backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, &rope); if let (Some((block_id, slot)), Some(mgr)) = (paged_slots[t], kv_manager) { @@ -1295,6 +1299,7 @@ impl NativeTransformerBackend { .config .attention_geometry() .map_err(|e| e.to_string())?; + self.tensor_backend.check_model(&self.weights.config)?; let num_heads = geom.num_q_heads(); let num_kv_heads = geom.num_kv_heads(); let head_dim = geom.head_dim(); @@ -1428,6 +1433,12 @@ impl NativeTransformerBackend { // c. RoPE across all D sequences at their respective positions for (i, &(_seq_id, _tok, pos)) in valid_reqs.iter().enumerate() { + layer_w.apply_qk_norm( + &mut q_batch[i * q_dim..(i + 1) * q_dim], + &mut k_batch[i * kv_dim..(i + 1) * kv_dim], + head_dim, + eps, + ); self.tensor_backend.apply_rope( &mut q_batch[i * q_dim..(i + 1) * q_dim], &mut k_batch[i * kv_dim..(i + 1) * kv_dim], diff --git a/crates/aien-inference-abi/src/weights.rs b/crates/aien-inference-abi/src/weights.rs index c4403e4f..336e13d8 100644 --- a/crates/aien-inference-abi/src/weights.rs +++ b/crates/aien-inference-abi/src/weights.rs @@ -1,7 +1,8 @@ //! Native weight data structures and zero-dependency loaders for transformer models. use crate::tensor::{ - apply_rope_params, matmul_vec, rmsnorm, scaled_dot_product_attention_single, swiglu, + apply_rope_params, matmul_vec, rmsnorm, rmsnorm_heads_in_place, + scaled_dot_product_attention_single, swiglu, }; use crate::ModelConfig; use serde_json::Value; @@ -31,6 +32,25 @@ pub struct TransformerLayerWeights { pub gate_proj: Vec, pub up_proj: Vec, pub down_proj: Vec, + /// Qwen3 per-head RMSNorm weights `[head_dim]` for Q and K (`config.qk_norm`); `None` for + /// Llama-architecture models. + pub q_norm: Option>, + pub k_norm: Option>, +} + +impl TransformerLayerWeights { + /// Qwen3: RMSNorm each query head and each key head over `head_dim`, in place, right + /// after the projections and before RoPE (Hugging Face `modeling_qwen3.py` + /// `Qwen3Attention.forward`: `q_norm(q_proj(x).view(.., head_dim))`, then rotary). + /// A no-op for models without q_norm/k_norm. + pub fn apply_qk_norm(&self, q: &mut [f32], k: &mut [f32], head_dim: usize, eps: f32) { + if let Some(w) = &self.q_norm { + rmsnorm_heads_in_place(q, w, head_dim, eps); + } + if let Some(w) = &self.k_norm { + rmsnorm_heads_in_place(k, w, head_dim, eps); + } + } } #[derive(Debug, Clone)] @@ -162,6 +182,8 @@ impl TransformerWeights { gate_proj, up_proj, down_proj, + q_norm: config.qk_norm.then(|| vec![1.0f32; config.head_dim]), + k_norm: config.qk_norm.then(|| vec![1.0f32; config.head_dim]), }); } @@ -226,6 +248,8 @@ impl TransformerWeights { matmul_vec(&x_norm, &layer_w.k_proj, &mut k, hidden_dim, kv_dim); matmul_vec(&x_norm, &layer_w.v_proj, &mut v, hidden_dim, kv_dim); + layer_w.apply_qk_norm(&mut q, &mut k, head_dim, eps); + // 2c. Rotary Positional Embeddings (RoPE) apply_rope_params( &mut q, @@ -414,6 +438,8 @@ impl TransformerWeights { matmul_vec(&x_norm, &layer_w.k_proj, &mut k, hidden_dim, kv_dim); matmul_vec(&x_norm, &layer_w.v_proj, &mut v, hidden_dim, kv_dim); + layer_w.apply_qk_norm(&mut q, &mut k, head_dim, eps); + // 2c. Rotary Positional Embeddings (RoPE) apply_rope_params( &mut q, @@ -692,6 +718,10 @@ impl TransformerWeights { if let Some(t) = extract_tensor(&format!("{}.mlp.down_proj.weight", prefix)) { layer.down_proj = t; } + if config.qk_norm { + layer.q_norm = extract_tensor(&format!("{}.self_attn.q_norm.weight", prefix)); + layer.k_norm = extract_tensor(&format!("{}.self_attn.k_norm.weight", prefix)); + } } if let Some(t) = extract_tensor("model.norm.weight") { @@ -738,6 +768,14 @@ impl TransformerWeights { let gate_proj = decode(&format!("{}.mlp.gate_proj.weight", prefix))?; let up_proj = decode(&format!("{}.mlp.up_proj.weight", prefix))?; let down_proj = decode(&format!("{}.mlp.down_proj.weight", prefix))?; + let (q_norm, k_norm) = if config.qk_norm { + ( + Some(decode(&format!("{}.self_attn.q_norm.weight", prefix))?), + Some(decode(&format!("{}.self_attn.k_norm.weight", prefix))?), + ) + } else { + (None, None) + }; layers.push(TransformerLayerWeights { input_layernorm, @@ -749,6 +787,8 @@ impl TransformerWeights { gate_proj, up_proj, down_proj, + q_norm, + k_norm, }); } @@ -832,6 +872,7 @@ mod tests { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, }; let weights = TransformerWeights::reference_test_weights(&config); @@ -864,6 +905,7 @@ mod tests { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, }; // 1. Missing tensor fails loudly with CheckpointError::MissingTensor diff --git a/crates/aien-inference-abi/tests/llama32_pin.rs b/crates/aien-inference-abi/tests/llama32_pin.rs new file mode 100644 index 00000000..ea900884 --- /dev/null +++ b/crates/aien-inference-abi/tests/llama32_pin.rs @@ -0,0 +1,62 @@ +//! Pins unsloth/Llama-3.2-1B-Instruct (the CAND-4 model, snapshot +//! 5a8abab4a5d6f164389b1079fb721cfab8d7126c) on the CPU reference path so the Qwen3 loader change +//! cannot alter a Llama-architecture model: composed prompt ids, and the exact last-position +//! logits (FNV-1a over every f32 bit pattern, plus the top-5 ids). Values were computed on +//! origin/main 845f58f (before the Qwen3 change). Set `AIEN_LLAMA3_DIR` to that snapshot +//! directory to run; skipped otherwise. + +use aien_inference_abi::tokenizer::ChatTokenizer; +use aien_inference_abi::{load_model_config, TransformerWeights}; +use std::path::Path; + +const TURNS: &[(&str, &str)] = &[("system", "You are terse."), ("user", " What is 2+2?\n")]; + +fn fnv1a(logits: &[f32]) -> u64 { + let mut h: u64 = 0xcbf29ce484222325; + for v in logits { + for b in v.to_bits().to_le_bytes() { + h ^= b as u64; + h = h.wrapping_mul(0x100000001b3); + } + } + h +} + +#[test] +fn llama32_prompt_ids_and_forward_logits_are_pinned() { + let Ok(dir) = std::env::var("AIEN_LLAMA3_DIR") else { + eprintln!("AIEN_LLAMA3_DIR not set: Llama 3.2 pin skipped"); + return; + }; + let dir = Path::new(&dir); + let tok = ChatTokenizer::from_model_dir(dir, None).expect("tokenizer"); + let text = tok.template().render(TURNS); + let ids = tok.encode(&text).expect("encode"); + println!("PIN llama32 ids={ids:?}"); + assert_eq!(ids, PIN_IDS); + + let config = load_model_config(dir).expect("config"); + let weights = TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config) + .expect("weights"); + let logits = + weights.forward_sequence_with_diagnostics(&ids).activations["last_token_logits"].clone(); + let mut order: Vec = (0..logits.len()).collect(); + order.sort_by(|a, b| logits[*b].total_cmp(&logits[*a])); + let top5: Vec = order[..5].to_vec(); + println!( + "PIN llama32 len={} fnv={:#018x} top5={top5:?}", + logits.len(), + fnv1a(&logits) + ); + assert_eq!(logits.len(), PIN_LEN); + assert_eq!(top5, PIN_TOP5); + assert_eq!(fnv1a(&logits), PIN_FNV); +} + +const PIN_IDS: &[u32] = &[ + 128000, 128006, 9125, 128007, 271, 2675, 527, 51637, 13, 128009, 128006, 882, 128007, 271, + 3923, 374, 220, 17, 10, 17, 30, 128009, 128006, 78191, 128007, 271, +]; +const PIN_LEN: usize = 128256; +const PIN_TOP5: [usize; 5] = [18, 19, 40, 17, 16]; +const PIN_FNV: u64 = 0x00d44eba4b6ca94b; diff --git a/crates/aien-inference-abi/tests/qwen3_forward_parity.rs b/crates/aien-inference-abi/tests/qwen3_forward_parity.rs new file mode 100644 index 00000000..cee07af7 --- /dev/null +++ b/crates/aien-inference-abi/tests/qwen3_forward_parity.rs @@ -0,0 +1,459 @@ +//! Qwen3 (`Qwen3ForCausalLM`) on the CPU reference path. +//! +//! Oracle: transformers 5.17.0 / torch 2.14.0 on CPU, float32 after upcasting the bf16 +//! weights, run by a scratch script outside the repository (provenance in +//! `fixtures/qwen3-tiny/PROVENANCE.md` and `forward_reference.json`). Our code is never its own +//! oracle. Tolerance: absolute 1e-4, the ABSOLUTE_TOLERANCE of tinyllama_parity.rs (set before +//! the first comparison, not tuned). +//! +//! The tiny model has `num_heads * head_dim = 64` against `hidden_size = 32`, per-layer +//! q_norm/k_norm weights that are not 1, tied embeddings, and head_dim read from config.json. +//! The negative test removes the q/k norm and shows the logits move far outside the tolerance, +//! so the comparison is not vacuous. +//! +//! `AIEN_QWEN3_DIR` (a Qwen3-4B-Instruct-2507 model directory) also runs the real model against +//! `fixtures/qwen3-4b-instruct-2507-config/real_forward_reference.json` (top-20 logits of the +//! prompt "The capital of France is", transformers 5.17.0 CPU float32); skipped when unset. Its +//! tolerance (5e-3 absolute on 36 layers) was set before the run. + +use aien_inference_abi::{ + load_model_config, model_config_from_hf_json, omega_model_refusal, NativeTransformerBackend, + SequenceState, TransformerWeights, +}; +use serde_json::Value; +use std::path::PathBuf; + +const ABSOLUTE_TOLERANCE: f32 = 1e-4; + +fn fixture(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join(name) +} + +struct Reference { + ids: Vec, + logits: Vec, + argmax: usize, +} + +fn reference(path: PathBuf) -> Reference { + let r: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + Reference { + ids: r["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap() as u32) + .collect(), + logits: r["logits"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_f64().unwrap() as f32) + .collect(), + argmax: r["argmax"].as_u64().unwrap() as usize, + } +} + +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) +} + +fn argmax(v: &[f32]) -> usize { + v.iter() + .enumerate() + .max_by(|a, b| a.1.total_cmp(b.1)) + .unwrap() + .0 +} + +fn tiny() -> (TransformerWeights, Reference) { + let dir = fixture("qwen3-tiny"); + let config = load_model_config(&dir).expect("config.json"); + assert!(config.qk_norm); + assert_eq!( + (config.head_dim, config.num_heads, config.hidden_dim), + (16, 4, 32) + ); + let weights = TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config) + .expect("weights"); + (weights, reference(dir.join("forward_reference.json"))) +} + +#[test] +fn qwen3_tiny_sequence_logits_match_transformers() { + let (weights, r) = tiny(); + let got = weights + .forward_sequence_with_diagnostics(&r.ids) + .activations["last_token_logits"] + .clone(); + let d = max_abs(&got, &r.logits); + eprintln!("sequence path max abs diff = {d:e}"); + assert!(d <= ABSOLUTE_TOLERANCE, "max abs diff {d:e}"); + assert_eq!(argmax(&got), r.argmax); +} + +#[test] +fn qwen3_tiny_token_by_token_logits_match_transformers() { + let (weights, r) = tiny(); + let mut state = SequenceState { + tokens: Vec::new(), + layers: vec![Default::default(); weights.config.num_layers], + }; + let mut last = Vec::new(); + for (pos, id) in r.ids.iter().enumerate() { + last = weights.forward_token(*id, pos, &mut state); + } + let got = weights.compute_logits(&last); + let d = max_abs(&got, &r.logits); + eprintln!("forward_token path max abs diff = {d:e}"); + assert!(d <= ABSOLUTE_TOLERANCE, "max abs diff {d:e}"); +} + +#[test] +fn qwen3_tiny_backend_prefill_and_decode_match_transformers() { + let (weights, r) = tiny(); + let mut backend = NativeTransformerBackend::new_reference(weights); + let got = backend.prefill_sequence(1, &r.ids).expect("prefill"); + let d = max_abs(&got, &r.logits); + eprintln!("backend prefill max abs diff = {d:e}"); + assert!(d <= ABSOLUTE_TOLERANCE, "prefill max abs diff {d:e}"); + + // Prefill all but the last id, then decode the last id: same logits. + let mut backend2 = NativeTransformerBackend::new_reference(tiny().0); + backend2 + .prefill_sequence(2, &r.ids[..r.ids.len() - 1]) + .expect("prefill"); + let seq = backend2.sequences.get_mut(&2).unwrap(); + let h = NativeTransformerBackend::forward_token_impl_paged( + &backend2.weights, + &*backend2.tensor_backend, + *r.ids.last().unwrap(), + r.ids.len() - 1, + seq, + 2, + None, + ); + let got2 = backend2.compute_logits(&h); + let d2 = max_abs(&got2, &r.logits); + eprintln!("backend decode max abs diff = {d2:e}"); + assert!(d2 <= ABSOLUTE_TOLERANCE, "decode max abs diff {d2:e}"); +} + +/// Negative control: without q_norm/k_norm the logits are far from the reference, so the +/// parity tests above do exercise the norm. +#[test] +fn qwen3_without_qk_norm_is_far_from_reference() { + let (mut weights, r) = tiny(); + for layer in &mut weights.layers { + layer.q_norm = None; + layer.k_norm = None; + } + let got = weights + .forward_sequence_with_diagnostics(&r.ids) + .activations["last_token_logits"] + .clone(); + let d = max_abs(&got, &r.logits); + eprintln!("no-norm max abs diff = {d:e}"); + assert!( + d > 100.0 * ABSOLUTE_TOLERANCE, + "norm removal changed logits by only {d:e}" + ); +} + +#[test] +fn qwen3_checkpoint_missing_q_norm_is_refused() { + let dir = fixture("qwen3-tiny"); + let mut config = load_model_config(&dir).unwrap(); + config.qk_norm = false; // catalog without norms: file has extra tensors, still loads as Llama-style + let llama_style = + TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config); + // The Qwen3 catalog is a strict superset: a Llama-style config must not silently load a + // Qwen3 file as correct, so the weights it builds carry no norms. + if let Ok(w) = llama_style { + assert!(w + .layers + .iter() + .all(|l| l.q_norm.is_none() && l.k_norm.is_none())); + } + let cat = aien_inference_abi::llama_catalog(&load_model_config(&dir).unwrap()); + assert!(cat + .iter() + .any(|(n, s)| n == "model.layers.1.self_attn.q_norm.weight" && s == &vec![16])); + assert!(cat + .iter() + .any(|(n, s)| n == "model.layers.0.self_attn.k_norm.weight" && s == &vec![16])); + assert!(cat + .iter() + .any(|(n, s)| n == "model.layers.0.self_attn.q_proj.weight" && s == &vec![64, 32])); +} + +fn real_config_json() -> String { + std::fs::read_to_string(fixture("qwen3-4b-instruct-2507-config").join("config.json")).unwrap() +} + +#[test] +fn real_qwen3_4b_instruct_2507_config_is_accepted() { + let c = model_config_from_hf_json( + "Qwen/Qwen3-4B-Instruct-2507", + &real_config_json(), + Some( + &std::fs::read_to_string( + fixture("qwen3-4b-instruct-2507-config").join("generation_config.json"), + ) + .unwrap(), + ), + ) + .expect("accepted"); + assert!(c.qk_norm && c.tie_word_embeddings); + assert_eq!( + (c.num_layers, c.num_heads, c.num_kv_heads, c.head_dim), + (36, 32, 8, 128) + ); + assert_eq!( + (c.hidden_dim, c.intermediate_dim, c.vocab_size), + (2560, 9728, 151936) + ); + assert_eq!(c.rope_theta, 5_000_000.0); + assert_eq!(c.max_sequence_length, 262144); + assert_eq!(c.eos_token_ids, vec![151645, 151643]); + let cat = aien_inference_abi::llama_catalog(&c); + // embed + 36 * (norms 2 + qkvo 4 + qk_norm 2 + mlp 3) + final norm, no lm_head (tied). + assert_eq!(cat.len(), 1 + 36 * 11 + 1); + assert!(cat + .iter() + .any(|(n, s)| n == "model.layers.35.self_attn.q_proj.weight" && s == &vec![4096, 2560])); + assert!(cat + .iter() + .any(|(n, s)| n == "model.layers.35.self_attn.o_proj.weight" && s == &vec![2560, 4096])); + assert!(cat + .iter() + .any(|(n, s)| n == "model.layers.0.self_attn.q_norm.weight" && s == &vec![128])); +} + +#[test] +fn qwen3_unsupported_config_fields_are_refused_by_name() { + let base: Value = serde_json::from_str(&real_config_json()).unwrap(); + let refuse = |edit: &dyn Fn(&mut serde_json::Map), needle: &str| { + let mut v = base.clone(); + edit(v.as_object_mut().unwrap()); + let err = model_config_from_hf_json("m", &v.to_string(), None).unwrap_err(); + assert!(err.contains(needle), "error {err:?} should name {needle:?}"); + }; + refuse( + &|m| { + m.remove("head_dim"); + }, + "head_dim", + ); + refuse( + &|m| { + m.insert( + "rope_parameters".into(), + serde_json::json!({"rope_type": "default"}), + ); + }, + "rope_parameters", + ); + refuse( + &|m| { + m.insert("some_new_field".into(), Value::Bool(true)); + }, + "some_new_field", + ); + refuse( + &|m| { + m.insert("use_sliding_window".into(), Value::Bool(true)); + }, + "use_sliding_window", + ); + refuse( + &|m| { + m.insert("sliding_window".into(), Value::from(4096)); + }, + "sliding_window", + ); + refuse( + &|m| { + m.insert( + "layer_types".into(), + serde_json::json!(["linear_attention"]), + ); + }, + "layer_types", + ); + refuse( + &|m| { + m.insert("attention_bias".into(), Value::Bool(true)); + }, + "attention_bias", + ); + refuse( + &|m| { + m.insert("hidden_act".into(), Value::from("gelu")); + }, + "hidden_act", + ); + refuse( + &|m| { + m.insert("model_type".into(), Value::from("qwen2")); + }, + "model_type", + ); + refuse( + &|m| { + m.insert( + "rope_scaling".into(), + serde_json::json!({"rope_type": "yarn", "factor": 4.0}), + ); + }, + "rope_scaling", + ); + refuse( + &|m| { + m.insert( + "architectures".into(), + serde_json::json!(["Qwen3MoeForCausalLM"]), + ); + }, + "architectures", + ); +} + +#[test] +fn llama_head_dim_rule_is_unchanged() { + // A Llama-architecture config whose heads * head_dim != hidden is still refused. + let json = r#"{"architectures":["LlamaForCausalLM"],"hidden_size":32,"intermediate_size":64, + "num_hidden_layers":1,"num_attention_heads":4,"num_key_value_heads":2,"head_dim":16, + "vocab_size":10,"rms_norm_eps":1e-5,"max_position_embeddings":16,"eos_token_id":2}"#; + let err = model_config_from_hf_json("m", json, None).unwrap_err(); + assert!(err.contains("must equal hidden_size"), "{err}"); +} + +#[test] +fn gb10_backend_refuses_qwen3_and_not_llama() { + let q = model_config_from_hf_json( + "Qwen/Qwen3-4B-Instruct-2507", + &real_config_json(), + Some("{\"eos_token_id\":[151645]}"), + ) + .unwrap(); + let msg = omega_model_refusal(&q).expect("Qwen3 must be refused on the GB10 engine"); + assert!( + msg.contains("head_dim 128") && msg.contains("Qwen3"), + "{msg}" + ); + let llama = aien_inference_abi::ModelConfig::tinyllama_1_1b(); + assert!(omega_model_refusal(&llama).is_none()); +} + +#[test] +fn real_qwen3_4b_instruct_2507_matches_transformers() { + let Ok(dir) = std::env::var("AIEN_QWEN3_DIR") else { + eprintln!("AIEN_QWEN3_DIR not set: real Qwen3-4B-Instruct-2507 comparison skipped"); + return; + }; + let dir = PathBuf::from(dir); + let r: Value = serde_json::from_str( + &std::fs::read_to_string( + fixture("qwen3-4b-instruct-2507-config").join("real_forward_reference.json"), + ) + .unwrap(), + ) + .unwrap(); + let ids: Vec = r["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap() as u32) + .collect(); + let top_ids: Vec = r["top_ids"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap() as usize) + .collect(); + let top_logits: Vec = r["top_logits"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_f64().unwrap() as f32) + .collect(); + let config = load_model_config(&dir).expect("config"); + let weights = TransformerWeights::load_from_safetensors( + dir.join("model.safetensors.index.json"), + &config, + ) + .expect("weights"); + let got = + weights.forward_sequence_with_diagnostics(&ids).activations["last_token_logits"].clone(); + assert_eq!(got.len(), r["vocab"].as_u64().unwrap() as usize); + let ours: Vec = top_ids.iter().map(|i| got[*i]).collect(); + let d = max_abs(&ours, &top_logits); + eprintln!( + "real model: max abs diff over the reference top-20 = {d:e}, argmax {} vs {}", + argmax(&got), + top_ids[0] + ); + assert_eq!(argmax(&got), top_ids[0]); + assert!(d <= 5e-3, "max abs diff {d:e}"); +} + +/// Batch decode (`forward_decode_batch_with_logits`, the third q/k-norm site): two sequences +/// with the reference prompt must reproduce the transformers logits, and a third, different +/// sequence in the same batch must equal its own single-sequence decode. +#[test] +fn qwen3_tiny_batch_decode_matches_transformers_and_single_sequence() { + let (weights, r) = tiny(); + let n = r.ids.len(); + let other: Vec = r.ids.iter().rev().copied().collect(); + + let mut batch = NativeTransformerBackend::new_reference(weights.clone()); + for (id, prompt) in [(1u64, &r.ids), (2, &r.ids), (3, &other)] { + batch + .prefill_sequence(id, &prompt[..n - 1]) + .expect("prefill"); + // The decode step consumes the pending token at position n - 1. + batch.pending_prefill_token.insert(id, prompt[n - 1]); + } + let (_out, logits) = batch + .forward_decode_batch_with_logits(&[1, 2, 3]) + .expect("batch decode"); + assert_eq!(logits.len(), 3); + for row in &logits[..2] { + let d = max_abs(row, &r.logits); + eprintln!("batch decode vs transformers max abs diff = {d:e}"); + assert!(d <= ABSOLUTE_TOLERANCE, "batch max abs diff {d:e}"); + } + + let mut single = NativeTransformerBackend::new_reference(weights); + single + .prefill_sequence(9, &other[..n - 1]) + .expect("prefill"); + let seq = single.sequences.get_mut(&9).unwrap(); + let h = NativeTransformerBackend::forward_token_impl_paged( + &single.weights, + &*single.tensor_backend, + other[n - 1], + n - 1, + seq, + 9, + None, + ); + let want = single.compute_logits(&h); + let d = max_abs(&logits[2], &want); + eprintln!("batch row 3 vs single-sequence max abs diff = {d:e}"); + assert!( + d <= ABSOLUTE_TOLERANCE, + "batch vs single max abs diff {d:e}" + ); + assert!( + max_abs(&logits[2], &logits[0]) > 1e-3, + "third sequence must differ from the first" + ); +} diff --git a/crates/aien-inference-abi/tests/smollm2_pin.rs b/crates/aien-inference-abi/tests/smollm2_pin.rs new file mode 100644 index 00000000..fac1364f --- /dev/null +++ b/crates/aien-inference-abi/tests/smollm2_pin.rs @@ -0,0 +1,61 @@ +//! Pins SmolLM2-1.7B-Instruct on the CPU reference path so the Qwen3 loader change cannot +//! alter a Llama-architecture model: composed prompt ids, and the exact last-position +//! logits (FNV-1a over every f32 bit pattern, plus the top-5 ids). Values were computed on +//! origin/main 845f58f (before the Qwen3 change) with the model directory +//! `SmolLM2-1.7B-Instruct-31b70e2e869a`. Set `AIEN_SMOLLM2_DIR` to run; skipped otherwise. + +use aien_inference_abi::tokenizer::ChatTokenizer; +use aien_inference_abi::{load_model_config, TransformerWeights}; +use std::path::Path; + +const TURNS: &[(&str, &str)] = &[("system", "You are terse."), ("user", " What is 2+2?\n")]; + +fn fnv1a(logits: &[f32]) -> u64 { + let mut h: u64 = 0xcbf29ce484222325; + for v in logits { + for b in v.to_bits().to_le_bytes() { + h ^= b as u64; + h = h.wrapping_mul(0x100000001b3); + } + } + h +} + +#[test] +fn smollm2_prompt_ids_and_forward_logits_are_pinned() { + let Ok(dir) = std::env::var("AIEN_SMOLLM2_DIR") else { + eprintln!("AIEN_SMOLLM2_DIR not set: SmolLM2 pin skipped"); + return; + }; + let dir = Path::new(&dir); + let tok = ChatTokenizer::from_model_dir(dir, None).expect("tokenizer"); + let text = tok.template().render(TURNS); + let ids = tok.encode(&text).expect("encode"); + println!("PIN smollm2 ids={ids:?}"); + assert_eq!(ids, PIN_IDS); + + let config = load_model_config(dir).expect("config"); + let weights = TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config) + .expect("weights"); + let logits = + weights.forward_sequence_with_diagnostics(&ids).activations["last_token_logits"].clone(); + let mut order: Vec = (0..logits.len()).collect(); + order.sort_by(|a, b| logits[*b].total_cmp(&logits[*a])); + let top5: Vec = order[..5].to_vec(); + println!( + "PIN smollm2 len={} fnv={:#018x} top5={top5:?}", + logits.len(), + fnv1a(&logits) + ); + assert_eq!(logits.len(), PIN_LEN); + assert_eq!(top5, PIN_TOP5); + assert_eq!(fnv1a(&logits), PIN_FNV); +} + +const PIN_IDS: &[u32] = &[ + 1, 9690, 198, 2683, 359, 1733, 313, 30, 2, 198, 1, 4093, 3805, 1812, 314, 216, 34, 27, 34, 47, + 198, 2, 198, 1, 520, 9531, 198, +]; +const PIN_LEN: usize = 49152; +const PIN_TOP5: [usize; 5] = [36, 34, 19622, 504, 10345]; +const PIN_FNV: u64 = 0x6862d0b2920753e4; diff --git a/crates/aien-inference-abi/tests/tinyllama_parity.rs b/crates/aien-inference-abi/tests/tinyllama_parity.rs index 9b0661fd..432afdd7 100644 --- a/crates/aien-inference-abi/tests/tinyllama_parity.rs +++ b/crates/aien-inference-abi/tests/tinyllama_parity.rs @@ -37,6 +37,7 @@ fn tinyllama_config() -> ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } diff --git a/crates/aien-inference-abi/tests/transformer_parity.rs b/crates/aien-inference-abi/tests/transformer_parity.rs index ada61454..7afc7126 100644 --- a/crates/aien-inference-abi/tests/transformer_parity.rs +++ b/crates/aien-inference-abi/tests/transformer_parity.rs @@ -24,6 +24,7 @@ fn test_model_config() -> ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } diff --git a/crates/aien-runtime/src/shared_kv.rs b/crates/aien-runtime/src/shared_kv.rs index f0fbbaae..7540466c 100644 --- a/crates/aien-runtime/src/shared_kv.rs +++ b/crates/aien-runtime/src/shared_kv.rs @@ -477,6 +477,7 @@ mod tests { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } diff --git a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs index 56d2c20a..6b3f4b24 100644 --- a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs +++ b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs @@ -81,6 +81,7 @@ fn test_micro_model_config() -> ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } @@ -106,6 +107,7 @@ fn gb10_micro_model_config() -> ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } diff --git a/crates/aien-runtime/tests/shared_kv_runtime_test.rs b/crates/aien-runtime/tests/shared_kv_runtime_test.rs index 125616ba..7de1f9ca 100644 --- a/crates/aien-runtime/tests/shared_kv_runtime_test.rs +++ b/crates/aien-runtime/tests/shared_kv_runtime_test.rs @@ -52,6 +52,7 @@ fn small_config() -> ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } diff --git a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs index 2538bde2..7088a577 100644 --- a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs +++ b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs @@ -316,6 +316,7 @@ fn c4_config() -> ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } diff --git a/crates/aien-runtime/tests/swarm_reclaim_test.rs b/crates/aien-runtime/tests/swarm_reclaim_test.rs index 26bf490e..8404c1b3 100644 --- a/crates/aien-runtime/tests/swarm_reclaim_test.rs +++ b/crates/aien-runtime/tests/swarm_reclaim_test.rs @@ -65,6 +65,7 @@ fn c5_config() -> ModelConfig { rope_scaling: None, tie_word_embeddings: false, eos_token_ids: Vec::new(), + qk_norm: false, } } ```