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 / src / bin / qwen38_omega_full.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 | //! The whole Qwen3.8-27B (all 64 layers) on the Omega engine against the host reference, one |
| 17 | //! layer window at a time (sc #642, omega-mv #559). |
| 18 | //! |
| 19 | //! qwen38_omega_full <checkpoint-dir> <window-layers> <golden.json> <out.json> |
| 20 | //! |
| 21 | //! `golden.json` is a `qwen38_check generate` record (`prompt_ids`, `generated_ids`: the host |
| 22 | //! reference's greedy continuation). The sequence is the prompt plus every generated token but the |
| 23 | //! last, fed one decode step at a time (teacher forcing with the reference's own tokens: if the chip |
| 24 | //! picks the reference's token at every step, free-running greedy decoding produces the same text). |
| 25 | //! |
| 26 | //! The device holds one window of `window-layers` layers (plus lm_head) at a time, because the |
| 27 | //! resident 30B server leaves less free memory than the whole 27B needs. Window 0 takes the token |
| 28 | //! embeddings; window w takes window w - 1's residual stream as the CHIP computed it (never the |
| 29 | //! reference's), so the last window's logits are a full 64-layer chip forward pass. Each window's |
| 30 | //! output residual is also held to the reference's residual at that layer boundary. |
| 31 | //! |
| 32 | //! PASS (the identity gate Drake set for the motor, 2026-10-21, L312) when every generated |
| 33 | //! position's chip token equals the golden token, except where the reference's own top-two margin |
| 34 | //! is below a band WRITTEN IN ADVANCE (`MARGIN_MIN`, 0.1 logit): two float orders cannot be asked |
| 35 | //! to agree on a decision the reference itself made by less than that, so such a flip is reported |
| 36 | //! as allowed, while a flip at a wider margin is a wrong kernel and fails. The band is never taken |
| 37 | //! from the run under test (2026-10-21 01:58Z: a band equal to the run's own max logit error let |
| 38 | //! the shared-expert mutant through with 22 flips at max error 23.8: a broken run excused itself). |
| 39 | //! The same band gates the chip's greedy choice at every position, prompt included. The logits' |
| 40 | //! cosine and max error are recorded at every step (the earlier 0.9999 cosine floor is an open |
| 41 | //! precision item, not a gate), and both controls must be caught: (1) each step against the |
| 42 | //! reference's NEXT position, (2) the final residual against the reference's residual one window |
| 43 | //! earlier (the last window must matter; n/a with one window). A check that cannot fail proves |
| 44 | //! nothing: the negative control (`AIEN_Q36_TEST_MUTANT`) must fail this rule. |
| 45 | |
| 46 | use std::path::Path; |
| 47 | use std::time::Instant; |
| 48 | |
| 49 | use aien_inference_abi::qwen38::{argmax, Logits, Qwen38Config, Qwen38Reference}; |
| 50 | use aien_inference_abi::qwen38_omega::{mem_available, window_bytes, Qwen38Omega, KEEP_FREE}; |
| 51 | use aien_inference_abi::qwen3_moe::parity_stats; |
| 52 | use aien_inference_abi::qwen3_moe_omega::ShardSource; |
| 53 | use serde_json::{json, Value}; |
| 54 | |
| 55 | const COSINE_MIN: f64 = 0.9999; |
| 56 | |
| 57 | /// The written band: the reference's top-two logit margin below which two float orders may |
| 58 | /// legitimately disagree. Fixed in advance, never taken from the run under test. Every correct run |
| 59 | /// held it (2026-10-21 p1..p4: 127/128 words identical, the one flip at margin 0.0096) and the |
| 60 | /// shared-expert mutant broke it (22 flips, smallest margin 0.214, 10 of them wider than even the |
| 61 | /// correct runs' largest vocabulary-wide logit error 2.425). |
| 62 | const MARGIN_MIN: f32 = 0.1; |
| 63 | |
| 64 | fn margin(logits: &[f32]) -> f32 { |
| 65 | let top = argmax(logits); |
| 66 | let second = logits |
| 67 | .iter() |
| 68 | .enumerate() |
| 69 | .filter(|&(i, _)| i != top) |
| 70 | .map(|(_, &v)| v) |
| 71 | .fold(f32::NEG_INFINITY, f32::max); |
| 72 | logits[top] - second |
| 73 | } |
| 74 | |
| 75 | fn ids(v: &Value, key: &str) -> Result<Vec<u32>, String> { |
| 76 | v[key] |
| 77 | .as_array() |
| 78 | .ok_or_else(|| format!("golden: no {key}"))? |
| 79 | .iter() |
| 80 | .map(|x| { |
| 81 | x.as_u64() |
| 82 | .and_then(|n| u32::try_from(n).ok()) |
| 83 | .ok_or_else(|| format!("golden: {key} holds a non-id")) |
| 84 | }) |
| 85 | .collect() |
| 86 | } |
| 87 | |
| 88 | fn run() -> Result<bool, String> { |
| 89 | let args: Vec<String> = std::env::args().collect(); |
| 90 | let usage = |
| 91 | "usage: qwen38_omega_full <checkpoint-dir> <window-layers> <golden.json> <out.json>"; |
| 92 | if args.len() != 5 { |
| 93 | return Err(usage.into()); |
| 94 | } |
| 95 | let dir = Path::new(&args[1]); |
| 96 | let wl: usize = args[2].parse().map_err(|_| usage.to_string())?; |
| 97 | let out_path = &args[4]; |
| 98 | let golden: Value = serde_json::from_str( |
| 99 | &std::fs::read_to_string(&args[3]).map_err(|e| format!("{}: {e}", args[3]))?, |
| 100 | ) |
| 101 | .map_err(|e| format!("{}: {e}", args[3]))?; |
| 102 | let prompt = ids(&golden, "prompt_ids")?; |
| 103 | let generated = ids(&golden, "generated_ids")?; |
| 104 | if prompt.is_empty() || generated.is_empty() { |
| 105 | return Err("golden: empty prompt or continuation".into()); |
| 106 | } |
| 107 | let mut seq = prompt.clone(); |
| 108 | seq.extend_from_slice(&generated[..generated.len() - 1]); |
| 109 | let (t, first_gen) = (seq.len(), prompt.len() - 1); |
| 110 | |
| 111 | let config = Qwen38Config::from_checkpoint(dir)?; |
| 112 | let layers = config.layers; |
| 113 | if wl == 0 || layers % wl != 0 { |
| 114 | return Err(format!("window {wl} does not divide {layers} layers")); |
| 115 | } |
| 116 | let windows = layers / wl; |
| 117 | let (h, vocab) = (config.hidden, config.vocab); |
| 118 | eprintln!( |
| 119 | "model: {layers} layers in {windows} windows of {wl}; {t} positions ({} generated)", |
| 120 | generated.len() |
| 121 | ); |
| 122 | |
| 123 | // The reference: logits at every position plus the residual at every window boundary. |
| 124 | let t0 = Instant::now(); |
| 125 | let bounds: Vec<usize> = (1..=windows).map(|w| w * wl).collect(); |
| 126 | let mut taps = Vec::new(); |
| 127 | let reference = { |
| 128 | let mut r = Qwen38Reference::new(config.clone(), ShardSource::open(dir)?)?; |
| 129 | let mut state = r.new_state(); |
| 130 | r.forward_tapped(&mut state, &seq, Logits::All, &bounds, &mut taps)? |
| 131 | }; |
| 132 | let ref_s = t0.elapsed().as_secs_f64(); |
| 133 | let ref_matches_golden = (0..generated.len()).all(|i| { |
| 134 | argmax(&reference[(first_gen + i) * vocab..(first_gen + i + 1) * vocab]) |
| 135 | == generated[i] as usize |
| 136 | }); |
| 137 | eprintln!( |
| 138 | "reference: {t} positions in {ref_s:.1} s; its greedy tokens {} the golden record", |
| 139 | if ref_matches_golden { |
| 140 | "equal" |
| 141 | } else { |
| 142 | "DIFFER FROM" |
| 143 | } |
| 144 | ); |
| 145 | |
| 146 | // The chip, window by window, each fed the previous window's chip residual. |
| 147 | let mut x_in: Vec<Vec<f32>> = Vec::new(); |
| 148 | let mut gpu_logits: Vec<Vec<f32>> = Vec::new(); |
| 149 | let mut tokens = vec![0u32; t]; |
| 150 | let mut chip_ns = vec![0u64; t]; |
| 151 | let mut win_report = Vec::new(); |
| 152 | let mut upload_s = 0.0; |
| 153 | let mut weight_bytes = 0usize; |
| 154 | for (w, tap) in taps.iter().enumerate().take(windows) { |
| 155 | let first = w * wl; |
| 156 | let need = window_bytes(&config, first, wl); |
| 157 | let avail = mem_available()?; |
| 158 | if avail < need + KEEP_FREE { |
| 159 | return Err(format!( |
| 160 | "window {w}: needs {} MiB with {} MiB kept free, MemAvailable {} MiB; refusing (use a smaller window)", |
| 161 | need >> 20, |
| 162 | KEEP_FREE >> 20, |
| 163 | avail >> 20 |
| 164 | )); |
| 165 | } |
| 166 | let t1 = Instant::now(); |
| 167 | let mut engine = Qwen38Omega::open_window(dir, first, wl, t.max(256))?; |
| 168 | let ls = t1.elapsed().as_secs_f64(); |
| 169 | upload_s += ls; |
| 170 | weight_bytes += engine.weight_bytes(); |
| 171 | eprintln!( |
| 172 | "window {w} (layers {first}..{}): uploaded in {ls:.1} s, weights {} MB, KV {} MB", |
| 173 | first + wl - 1, |
| 174 | engine.weight_bytes() >> 20, |
| 175 | engine.kv_bytes() >> 20 |
| 176 | ); |
| 177 | let last = w + 1 == windows; |
| 178 | let mut x_out = Vec::with_capacity(t); |
| 179 | for p in 0..t { |
| 180 | let (tok, st) = if w == 0 { |
| 181 | engine.step(seq[p])? |
| 182 | } else { |
| 183 | engine.step_residual(&x_in[p])? |
| 184 | }; |
| 185 | chip_ns[p] += st.chip_ns; |
| 186 | x_out.push(engine.residual()?); |
| 187 | if last { |
| 188 | tokens[p] = tok; |
| 189 | gpu_logits.push(engine.logits()?); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | let (mut cos_min, mut p95_max) = (f64::INFINITY, 0f32); |
| 194 | for (p, x) in x_out.iter().enumerate() { |
| 195 | let s = parity_stats(x, &tap[p * h..(p + 1) * h]); |
| 196 | cos_min = cos_min.min(if s.non_finite > 0 { |
| 197 | f64::NEG_INFINITY |
| 198 | } else { |
| 199 | s.cosine |
| 200 | }); |
| 201 | p95_max = p95_max.max(s.p95_rel); |
| 202 | } |
| 203 | println!("window {w} layers {first}..{}: residual cosine(min) {cos_min:.6} p95_rel(max) {p95_max:.4}", first + wl - 1); |
| 204 | win_report.push(json!({"window": w, "first_layer": first, "layers": wl, "upload_s": ls, |
| 205 | "weight_bytes": engine.weight_bytes(), "residual_cosine_min": cos_min, "residual_p95_rel_max": p95_max})); |
| 206 | x_in = x_out; |
| 207 | drop(engine); |
| 208 | } |
| 209 | |
| 210 | let mut steps = Vec::with_capacity(t); |
| 211 | let (mut cos_min, mut p95_max, mut greedy_ok, mut golden_ok) = |
| 212 | (f64::INFINITY, 0f32, true, true); |
| 213 | let mut gen_tokens = Vec::new(); |
| 214 | // Golden flips inside the written margin band (allowed, reported) and beyond it (wrong kernel). |
| 215 | let (mut flips_allowed, mut flips_beyond) = (Vec::new(), Vec::new()); |
| 216 | for p in 0..t { |
| 217 | let logits = &gpu_logits[p]; |
| 218 | let expected = &reference[p * vocab..(p + 1) * vocab]; |
| 219 | let s = parity_stats(logits, expected); |
| 220 | let (ref_tok, m) = (argmax(expected), margin(expected)); |
| 221 | let tok = tokens[p] as usize; |
| 222 | let agree = tok == ref_tok && argmax(logits) == tok; |
| 223 | if m >= MARGIN_MIN && !agree { |
| 224 | greedy_ok = false; |
| 225 | } |
| 226 | let gold = (p >= first_gen).then(|| generated[p - first_gen] as usize); |
| 227 | if let Some(g) = gold { |
| 228 | gen_tokens.push(tok); |
| 229 | if tok != g { |
| 230 | golden_ok = false; |
| 231 | let flip = json!({"pos": p, "token": tok, "golden": g, "ref_margin": m, "max_abs": s.max_abs}); |
| 232 | if m < MARGIN_MIN { |
| 233 | flips_allowed.push(flip); |
| 234 | } else { |
| 235 | flips_beyond.push(flip); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | cos_min = cos_min.min(if s.non_finite > 0 { |
| 240 | f64::NEG_INFINITY |
| 241 | } else { |
| 242 | s.cosine |
| 243 | }); |
| 244 | p95_max = p95_max.max(s.p95_rel); |
| 245 | println!( |
| 246 | "step {p:3}: token {tok:6} ref {ref_tok:6}{} margin {m:7.3} cosine {:.6} p95_rel {:.4} max_abs {:.4} chip {:.2} ms{}", |
| 247 | gold.map_or(String::new(), |g| format!(" golden {g:6}")), |
| 248 | s.cosine, |
| 249 | s.p95_rel, |
| 250 | s.max_abs, |
| 251 | chip_ns[p] as f64 / 1e6, |
| 252 | if gold.is_some_and(|g| g != tok) { " GOLDEN DIFFERS" } else if agree { "" } else { " (differs)" } |
| 253 | ); |
| 254 | steps.push(json!({"pos": p, "token": tok, "ref_token": ref_tok, "golden": gold, "ref_margin": m, |
| 255 | "cosine": s.cosine, "p95_rel": s.p95_rel, "max_abs": s.max_abs, "non_finite": s.non_finite, |
| 256 | "chip_ns_all_windows": chip_ns[p]})); |
| 257 | } |
| 258 | |
| 259 | // Controls. |
| 260 | let shift_cos = (0..t - 1) |
| 261 | .map(|p| parity_stats(&gpu_logits[p], &reference[(p + 1) * vocab..(p + 2) * vocab]).cosine) |
| 262 | .fold(f64::NEG_INFINITY, f64::max); |
| 263 | let short_cos = (windows >= 2).then(|| { |
| 264 | let tap = &taps[windows - 2]; |
| 265 | (0..t) |
| 266 | .map(|p| parity_stats(&x_in[p], &tap[p * h..(p + 1) * h]).cosine) |
| 267 | .fold(f64::NEG_INFINITY, f64::max) |
| 268 | }); |
| 269 | let caught = shift_cos < COSINE_MIN && short_cos.is_none_or(|c| c < COSINE_MIN); |
| 270 | println!( |
| 271 | "CONTROL shifted-by-one: best cosine {shift_cos:.6}; one window short: best cosine {} -> {}", |
| 272 | short_cos.map_or("n/a".to_string(), |c| format!("{c:.6}")), |
| 273 | if caught { "caught" } else { "NOT CAUGHT" } |
| 274 | ); |
| 275 | let text_ok = gen_tokens.len() == generated.len(); |
| 276 | let words_ok = flips_beyond.is_empty(); |
| 277 | let cosine_floor_held = cos_min >= COSINE_MIN; |
| 278 | let pass = words_ok && greedy_ok && text_ok && caught && ref_matches_golden; |
| 279 | println!( |
| 280 | "QWEN38_OMEGA_FULL layers {layers} windows {windows} positions {t}: generated {}/{} identical to golden ({} flips inside the written margin band {MARGIN_MIN}, {} beyond it), cosine(min) {cos_min:.6} (floor {COSINE_MIN} {}, recorded not gated) p95_rel(max) {p95_max:.4} greedy {} control {} -> {}", |
| 281 | gen_tokens.iter().zip(&generated).filter(|(a, b)| **a == **b as usize).count(), |
| 282 | generated.len(), |
| 283 | flips_allowed.len(), |
| 284 | flips_beyond.len(), |
| 285 | if cosine_floor_held { "held" } else { "NOT held: open precision item" }, |
| 286 | if greedy_ok { "agrees" } else { "DIFFERS" }, |
| 287 | if caught { "caught" } else { "NOT CAUGHT" }, |
| 288 | if pass { "PASS" } else { "FAIL" } |
| 289 | ); |
| 290 | let report = json!({ |
| 291 | "checkpoint": dir.display().to_string(), "layers": layers, "window_layers": wl, "windows": win_report, |
| 292 | "positions": t, "prompt_ids": prompt, "golden_ids": generated, "chip_ids": gen_tokens, |
| 293 | "reference_s": ref_s, "reference_matches_golden": ref_matches_golden, "upload_s": upload_s, |
| 294 | "weight_bytes": weight_bytes, "cosine_min": cos_min, "p95_rel_max": p95_max, |
| 295 | "greedy_agrees": greedy_ok, "golden_identical": golden_ok, |
| 296 | "words_identical_outside_margin_band": words_ok, |
| 297 | "flips_allowed": flips_allowed, "flips_beyond_error": flips_beyond, |
| 298 | "cosine_floor_held": cosine_floor_held, "cosine_floor_gated": false, |
| 299 | "control_shift_best_cosine": shift_cos, "control_window_short_best_cosine": short_cos, |
| 300 | "control_caught": caught, "thresholds": {"cosine_min_recorded": COSINE_MIN, "margin_band_logits": MARGIN_MIN}, |
| 301 | "gate": "words identical to the golden except where the reference's top-two margin is below the written band (0.1 logit, fixed in advance, never from the run under test); chip greedy agrees at every position outside the band; controls caught; reference equals golden (Drake 2026-10-21, L312; band fixed 02:10Z after a self-measured band let mutant 4 through)", |
| 302 | "steps": steps, "pass": pass, |
| 303 | }); |
| 304 | std::fs::write(out_path, serde_json::to_string_pretty(&report).unwrap()) |
| 305 | .map_err(|e| format!("{out_path}: {e}"))?; |
| 306 | Ok(pass) |
| 307 | } |
| 308 | |
| 309 | fn main() { |
| 310 | match run() { |
| 311 | Ok(true) => {} |
| 312 | Ok(false) => std::process::exit(1), |
| 313 | Err(e) => { |
| 314 | eprintln!("qwen38_omega_full: {e}"); |
| 315 | std::process::exit(2); |
| 316 | } |
| 317 | } |
| 318 | } |