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_check.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 | //! Qwen3.8-27B on the Omega engine against the host reference, over a model prefix (sc #642). |
| 17 | //! |
| 18 | //! qwen38_omega_check <checkpoint-dir> <layers> <prompt.txt> <tokens> <out.json> |
| 19 | //! |
| 20 | //! Uploads the first `layers` layers (final norm and lm_head on top), feeds the prompt's first |
| 21 | //! `tokens` ids one decode step at a time through the one-list graph, and holds each step's |
| 22 | //! logits to the reference's (same prefix, one host pass, `Logits::All`): cosine, p95 relative |
| 23 | //! error and the greedy token. The negative control compares each step with the reference's NEXT |
| 24 | //! position, and with the reference ONE LAYER SHORTER (the last layer must matter); both must |
| 25 | //! disagree: a check that cannot fail proves nothing. |
| 26 | //! |
| 27 | //! PASS when every step has cosine >= 0.9999, the greedy tokens agree wherever the reference's |
| 28 | //! top-two margin is at least 0.1, and the control is caught. |
| 29 | |
| 30 | use std::path::Path; |
| 31 | use std::time::Instant; |
| 32 | |
| 33 | use aien_inference_abi::qwen38::{argmax, Logits, Qwen38Config, Qwen38Reference}; |
| 34 | use aien_inference_abi::qwen38_omega::Qwen38Omega; |
| 35 | use aien_inference_abi::qwen3_moe::parity_stats; |
| 36 | use aien_inference_abi::qwen3_moe_omega::ShardSource; |
| 37 | use aien_inference_abi::tokenizer::ChatTokenizer; |
| 38 | use serde_json::json; |
| 39 | |
| 40 | const COSINE_MIN: f64 = 0.9999; |
| 41 | const MARGIN_MIN: f32 = 0.1; |
| 42 | |
| 43 | fn margin(logits: &[f32]) -> f32 { |
| 44 | let top = argmax(logits); |
| 45 | let second = logits |
| 46 | .iter() |
| 47 | .enumerate() |
| 48 | .filter(|&(i, _)| i != top) |
| 49 | .map(|(_, &v)| v) |
| 50 | .fold(f32::NEG_INFINITY, f32::max); |
| 51 | logits[top] - second |
| 52 | } |
| 53 | |
| 54 | fn run() -> Result<bool, String> { |
| 55 | let args: Vec<String> = std::env::args().collect(); |
| 56 | let usage = |
| 57 | "usage: qwen38_omega_check <checkpoint-dir> <layers> <prompt.txt> <tokens> <out.json>"; |
| 58 | if args.len() != 6 { |
| 59 | return Err(usage.into()); |
| 60 | } |
| 61 | let dir = Path::new(&args[1]); |
| 62 | let layers: usize = args[2].parse().map_err(|_| usage.to_string())?; |
| 63 | let count: usize = args[4].parse().map_err(|_| usage.to_string())?; |
| 64 | let out_path = &args[5]; |
| 65 | let text = std::fs::read_to_string(&args[3]).map_err(|e| format!("{}: {e}", args[3]))?; |
| 66 | let tokenizer = |
| 67 | ChatTokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| e.to_string())?; |
| 68 | let mut ids = tokenizer.encode(&text).map_err(|e| e.to_string())?; |
| 69 | ids.truncate(count); |
| 70 | if ids.len() < 2 { |
| 71 | return Err("the prompt needs at least two tokens".into()); |
| 72 | } |
| 73 | let t = ids.len(); |
| 74 | let config = Qwen38Config::from_checkpoint(dir)? |
| 75 | .prefix(layers) |
| 76 | .ok_or_else(|| format!("layers {layers} outside the model"))?; |
| 77 | let attn_layers = config.full_attention.iter().filter(|&&a| a).count(); |
| 78 | eprintln!( |
| 79 | "prefix: {layers} layers ({} DeltaNet, {attn_layers} attention), {t} tokens", |
| 80 | layers - attn_layers |
| 81 | ); |
| 82 | |
| 83 | let t0 = Instant::now(); |
| 84 | let reference = { |
| 85 | let mut r = Qwen38Reference::new(config.clone(), ShardSource::open(dir)?)?; |
| 86 | let mut state = r.new_state(); |
| 87 | r.forward(&mut state, &ids, Logits::All)? |
| 88 | }; |
| 89 | let short = match config.prefix(layers - 1) { |
| 90 | Some(c) => { |
| 91 | let mut r = Qwen38Reference::new(c, ShardSource::open(dir)?)?; |
| 92 | let mut state = r.new_state(); |
| 93 | Some(r.forward(&mut state, &ids, Logits::All)?) |
| 94 | } |
| 95 | None => None, |
| 96 | }; |
| 97 | let ref_s = t0.elapsed().as_secs_f64(); |
| 98 | eprintln!("reference: {t} positions in {ref_s:.1} s"); |
| 99 | let vocab = config.vocab; |
| 100 | |
| 101 | let t1 = Instant::now(); |
| 102 | let mut engine = Qwen38Omega::load(config, &mut ShardSource::open(dir)?, t.max(256))?; |
| 103 | let load_s = t1.elapsed().as_secs_f64(); |
| 104 | eprintln!( |
| 105 | "engine: uploaded in {load_s:.1} s, weights {} MB, KV {} MB", |
| 106 | engine.weight_bytes() >> 20, |
| 107 | engine.kv_bytes() >> 20 |
| 108 | ); |
| 109 | |
| 110 | let mut steps = Vec::with_capacity(t); |
| 111 | let mut gpu_logits = Vec::with_capacity(t); |
| 112 | let (mut cos_min, mut p95_max, mut greedy_ok) = (f64::INFINITY, 0f32, true); |
| 113 | let mut chip_ns = Vec::with_capacity(t); |
| 114 | for (p, &id) in ids.iter().enumerate() { |
| 115 | let (token, st) = engine.step(id)?; |
| 116 | let logits = engine.logits()?; |
| 117 | let expected = &reference[p * vocab..(p + 1) * vocab]; |
| 118 | let s = parity_stats(&logits, expected); |
| 119 | let (ref_tok, m) = (argmax(expected), margin(expected)); |
| 120 | let agree = token as usize == ref_tok; |
| 121 | let counts = m >= MARGIN_MIN; |
| 122 | if counts && !agree { |
| 123 | greedy_ok = false; |
| 124 | } |
| 125 | if s.non_finite > 0 { |
| 126 | cos_min = f64::NEG_INFINITY; |
| 127 | } |
| 128 | cos_min = cos_min.min(s.cosine); |
| 129 | p95_max = p95_max.max(s.p95_rel); |
| 130 | chip_ns.push(st.chip_ns); |
| 131 | println!( |
| 132 | "step {p:3}: token {token:6} ref {ref_tok:6} margin {m:7.3} cosine {:.6} p95_rel {:.4} max_abs {:.4} chip {:.2} ms launches {} submits {}{}", |
| 133 | s.cosine, |
| 134 | s.p95_rel, |
| 135 | s.max_abs, |
| 136 | st.chip_ns as f64 / 1e6, |
| 137 | st.launches, |
| 138 | st.submits, |
| 139 | if agree { "" } else if counts { " GREEDY DIFFERS" } else { " (differs, below margin)" } |
| 140 | ); |
| 141 | steps.push(json!({"pos": p, "token": token, "ref_token": ref_tok, "ref_margin": m, |
| 142 | "cosine": s.cosine, "p95_rel": s.p95_rel, "max_abs": s.max_abs, "non_finite": s.non_finite, |
| 143 | "chip_ns": st.chip_ns, "launches": st.launches, "submits": st.submits})); |
| 144 | gpu_logits.push(logits); |
| 145 | } |
| 146 | |
| 147 | // Negative control: step p against the reference's position p + 1. |
| 148 | let control_cos = (0..t - 1) |
| 149 | .map(|p| parity_stats(&gpu_logits[p], &reference[(p + 1) * vocab..(p + 2) * vocab]).cosine) |
| 150 | .fold(f64::NEG_INFINITY, f64::max); |
| 151 | let short_cos = short.as_ref().map(|s| { |
| 152 | (0..t) |
| 153 | .map(|p| parity_stats(&gpu_logits[p], &s[p * vocab..(p + 1) * vocab]).cosine) |
| 154 | .fold(f64::NEG_INFINITY, f64::max) |
| 155 | }); |
| 156 | let caught = control_cos < COSINE_MIN && short_cos.is_none_or(|c| c < COSINE_MIN); |
| 157 | println!( |
| 158 | "CONTROL shifted-by-one: best cosine {control_cos:.6}; one layer short: best cosine {} -> {}", |
| 159 | short_cos.map_or("n/a (1 layer)".to_string(), |c| format!("{c:.6}")), |
| 160 | if caught { "caught" } else { "NOT CAUGHT" } |
| 161 | ); |
| 162 | |
| 163 | let mut sorted = chip_ns.clone(); |
| 164 | sorted.sort_unstable(); |
| 165 | let median_ms = sorted[sorted.len() / 2] as f64 / 1e6; |
| 166 | let pass = cos_min >= COSINE_MIN && greedy_ok && caught; |
| 167 | println!( |
| 168 | "QWEN38_OMEGA_PARITY layers {layers} tokens {t}: cosine(min) {cos_min:.6} p95_rel(max) {p95_max:.4} greedy {} control {} chip median {median_ms:.2} ms/token -> {}", |
| 169 | if greedy_ok { "agrees" } else { "DIFFERS" }, |
| 170 | if caught { "caught" } else { "NOT CAUGHT" }, |
| 171 | if pass { "PASS" } else { "FAIL" } |
| 172 | ); |
| 173 | let report = json!({ |
| 174 | "checkpoint": dir.display().to_string(), "layers": layers, "attention_layers": attn_layers, |
| 175 | "tokens": t, "ids": ids, "reference_s": ref_s, "upload_s": load_s, |
| 176 | "weight_bytes": engine.weight_bytes(), "kv_bytes": engine.kv_bytes(), |
| 177 | "cosine_min": cos_min, "p95_rel_max": p95_max, "greedy_agrees": greedy_ok, |
| 178 | "control_best_cosine": control_cos, "control_short_best_cosine": short_cos, "control_caught": caught, |
| 179 | "chip_median_ms": median_ms, "thresholds": {"cosine_min": COSINE_MIN, "margin_min": MARGIN_MIN}, |
| 180 | "steps": steps, "pass": pass, |
| 181 | }); |
| 182 | std::fs::write(out_path, serde_json::to_string_pretty(&report).unwrap()) |
| 183 | .map_err(|e| format!("{out_path}: {e}"))?; |
| 184 | Ok(pass) |
| 185 | } |
| 186 | |
| 187 | fn main() { |
| 188 | match run() { |
| 189 | Ok(true) => {} |
| 190 | Ok(false) => std::process::exit(1), |
| 191 | Err(e) => { |
| 192 | eprintln!("qwen38_omega_check: {e}"); |
| 193 | std::process::exit(2); |
| 194 | } |
| 195 | } |
| 196 | } |