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
aien-sovereign-core-mv / crates / aien-inference-abi / tests / qwen3_untied_head.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Untied output head (`tie_word_embeddings=false`), as in Qwen3-8B (hidden 4096, intermediate |
| 17 | //! 12288, rope_theta 1e6, `lm_head.weight` in the last shard). CPU reference path, sc#384. |
| 18 | //! |
| 19 | //! Independent oracle: the tiny Qwen3 checkpoint's transformers logits (see |
| 20 | //! `fixtures/qwen3-tiny/PROVENANCE.md`, tied head). The test writes a copy of that checkpoint |
| 21 | //! WITH an extra `lm_head.weight` that is the embedding matrix with rows 3 and 5 swapped. The |
| 22 | //! hidden state does not depend on the head, so the right untied logits are the oracle logits |
| 23 | //! with entries 3 and 5 swapped. A loader that ignores `lm_head.weight` (and reuses the |
| 24 | //! embeddings) returns the unswapped oracle logits and fails; the negative control asserts the |
| 25 | //! swap is far outside the tolerance, so the check cannot pass vacuously. A second test shows |
| 26 | //! an untied config with no `lm_head.weight` is refused, never silently tied. |
| 27 | //! |
| 28 | //! The real Qwen3-8B shape check (config.json values and the `lm_head.weight` index entry) is |
| 29 | //! the ignored test at the bottom (`AIEN_QWEN3_8B_DIR`). |
| 30 | |
| 31 | use aien_inference_abi::{load_model_config, ModelConfig, SequenceState, TransformerWeights}; |
| 32 | use serde_json::{json, Value}; |
| 33 | use std::path::{Path, PathBuf}; |
| 34 | |
| 35 | const TOL: f32 = 1e-4; |
| 36 | |
| 37 | fn tiny_dir() -> PathBuf { |
| 38 | PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/qwen3-tiny") |
| 39 | } |
| 40 | |
| 41 | fn oracle_logits() -> (Vec<u32>, Vec<f32>) { |
| 42 | let r: Value = serde_json::from_str( |
| 43 | &std::fs::read_to_string(tiny_dir().join("forward_reference.json")).unwrap(), |
| 44 | ) |
| 45 | .unwrap(); |
| 46 | let ids = r["ids"] |
| 47 | .as_array() |
| 48 | .unwrap() |
| 49 | .iter() |
| 50 | .map(|v| v.as_u64().unwrap() as u32) |
| 51 | .collect(); |
| 52 | let logits = r["logits"] |
| 53 | .as_array() |
| 54 | .unwrap() |
| 55 | .iter() |
| 56 | .map(|v| v.as_f64().unwrap() as f32) |
| 57 | .collect(); |
| 58 | (ids, logits) |
| 59 | } |
| 60 | |
| 61 | /// The tiny checkpoint plus an `lm_head.weight` (BF16 [64, 32]) = embeddings with rows 3, 5 swapped. |
| 62 | fn untied_checkpoint(dir: &Path, with_head: bool) { |
| 63 | std::fs::create_dir_all(dir).unwrap(); |
| 64 | let bytes = std::fs::read(tiny_dir().join("model.safetensors")).unwrap(); |
| 65 | let hlen = u64::from_le_bytes(bytes[0..8].try_into().unwrap()) as usize; |
| 66 | let mut header: Value = serde_json::from_slice(&bytes[8..8 + hlen]).unwrap(); |
| 67 | let data = &bytes[8 + hlen..]; |
| 68 | let emb = &header["model.embed_tokens.weight"]; |
| 69 | assert_eq!(emb["dtype"], "BF16"); |
| 70 | assert_eq!(emb["shape"], json!([64, 32])); |
| 71 | let start = emb["data_offsets"][0].as_u64().unwrap() as usize; |
| 72 | let end = emb["data_offsets"][1].as_u64().unwrap() as usize; |
| 73 | let row = 32 * 2; |
| 74 | assert_eq!(end - start, 64 * row); |
| 75 | let mut out = data.to_vec(); |
| 76 | if with_head { |
| 77 | let mut head = data[start..end].to_vec(); |
| 78 | let (a, b) = (3 * row, 5 * row); |
| 79 | for i in 0..row { |
| 80 | head.swap(a + i, b + i); |
| 81 | } |
| 82 | header["lm_head.weight"] = json!({ |
| 83 | "dtype": "BF16", "shape": [64, 32], |
| 84 | "data_offsets": [out.len(), out.len() + head.len()] |
| 85 | }); |
| 86 | out.extend_from_slice(&head); |
| 87 | } |
| 88 | let h = serde_json::to_vec(&header).unwrap(); |
| 89 | let mut file = (h.len() as u64).to_le_bytes().to_vec(); |
| 90 | file.extend_from_slice(&h); |
| 91 | file.extend_from_slice(&out); |
| 92 | std::fs::write(dir.join("model.safetensors"), file).unwrap(); |
| 93 | } |
| 94 | |
| 95 | fn untied_config() -> ModelConfig { |
| 96 | let mut c = load_model_config(&tiny_dir()).unwrap(); |
| 97 | assert!(c.tie_word_embeddings, "the tiny fixture is tied"); |
| 98 | c.tie_word_embeddings = false; |
| 99 | c |
| 100 | } |
| 101 | |
| 102 | fn scratch(name: &str) -> PathBuf { |
| 103 | std::env::temp_dir().join(format!("aien-untied-head-{name}-{}", std::process::id())) |
| 104 | } |
| 105 | |
| 106 | fn last_logits(w: &TransformerWeights, ids: &[u32]) -> Vec<f32> { |
| 107 | let mut state = SequenceState { |
| 108 | tokens: Vec::new(), |
| 109 | layers: vec![Default::default(); w.config.num_layers], |
| 110 | kv_dtype: Default::default(), |
| 111 | }; |
| 112 | let mut last = Vec::new(); |
| 113 | for (pos, id) in ids.iter().enumerate() { |
| 114 | last = w.forward_token(*id, pos, &mut state); |
| 115 | } |
| 116 | w.compute_logits(&last) |
| 117 | } |
| 118 | |
| 119 | fn max_abs(a: &[f32], b: &[f32]) -> f32 { |
| 120 | assert_eq!(a.len(), b.len()); |
| 121 | a.iter() |
| 122 | .zip(b) |
| 123 | .map(|(x, y)| (x - y).abs()) |
| 124 | .fold(0.0, f32::max) |
| 125 | } |
| 126 | |
| 127 | #[test] |
| 128 | fn untied_head_logits_use_lm_head_not_the_embeddings() { |
| 129 | let dir = scratch("with"); |
| 130 | untied_checkpoint(&dir, true); |
| 131 | let (ids, tied) = oracle_logits(); |
| 132 | let mut expected = tied.clone(); |
| 133 | expected.swap(3, 5); |
| 134 | // Negative control: the swapped vector is far from the tied oracle. |
| 135 | assert!( |
| 136 | max_abs(&expected, &tied) > 100.0 * TOL, |
| 137 | "rows 3 and 5 give nearly equal logits; the control would be vacuous" |
| 138 | ); |
| 139 | let cfg = untied_config(); |
| 140 | let w = TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &cfg) |
| 141 | .expect("untied checkpoint with lm_head.weight loads"); |
| 142 | assert!(w.lm_head.is_some(), "untied load must keep lm_head"); |
| 143 | let got = last_logits(&w, &ids); |
| 144 | let d = max_abs(&got, &expected); |
| 145 | eprintln!("untied head: max abs diff vs swapped oracle = {d:e}"); |
| 146 | assert!(d <= TOL, "max abs diff {d:e}"); |
| 147 | assert!( |
| 148 | max_abs(&got, &tied) > 100.0 * TOL, |
| 149 | "logits equal the tied (embedding) result: lm_head was ignored" |
| 150 | ); |
| 151 | // Sequence path agrees with the token path. |
| 152 | let seq = w.forward_sequence_with_diagnostics(&ids).activations["last_token_logits"].clone(); |
| 153 | assert!(max_abs(&seq, &expected) <= TOL); |
| 154 | let _ = std::fs::remove_dir_all(dir); |
| 155 | } |
| 156 | |
| 157 | #[test] |
| 158 | fn untied_config_without_lm_head_is_refused_not_tied() { |
| 159 | let dir = scratch("without"); |
| 160 | untied_checkpoint(&dir, false); |
| 161 | let r = |
| 162 | TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &untied_config()); |
| 163 | let _ = std::fs::remove_dir_all(dir); |
| 164 | let Err(e) = r else { |
| 165 | panic!("untied config without lm_head.weight must be refused"); |
| 166 | }; |
| 167 | assert!(e.to_string().contains("lm_head.weight"), "{e}"); |
| 168 | } |
| 169 | |
| 170 | /// Real Qwen3-8B shapes from the downloaded files: `AIEN_QWEN3_8B_DIR=~/models/qwen3-8b cargo test |
| 171 | /// -p aien-inference-abi --test qwen3_untied_head -- --ignored`. Reads only config.json and the |
| 172 | /// shard index (no weights), fails when the variable is unset. |
| 173 | #[test] |
| 174 | #[ignore = "needs the Qwen3-8B model directory in AIEN_QWEN3_8B_DIR"] |
| 175 | fn real_qwen3_8b_config_is_untied_with_the_expected_shape() { |
| 176 | let dir = PathBuf::from(std::env::var("AIEN_QWEN3_8B_DIR").expect("AIEN_QWEN3_8B_DIR unset")); |
| 177 | let c = load_model_config(&dir).unwrap(); |
| 178 | assert!(!c.tie_word_embeddings); |
| 179 | assert_eq!((c.hidden_dim, c.intermediate_dim), (4096, 12288)); |
| 180 | assert_eq!(c.rope_theta, 1_000_000.0); |
| 181 | assert!(c.qk_norm); |
| 182 | let idx: Value = serde_json::from_str( |
| 183 | &std::fs::read_to_string(dir.join("model.safetensors.index.json")).unwrap(), |
| 184 | ) |
| 185 | .unwrap(); |
| 186 | assert!(idx["weight_map"]["lm_head.weight"].is_string()); |
| 187 | } |