interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / evidence / qwen38-omega-full-20261018T1641Z-INVALID-oom / qwen38_omega_full.rs

243 lines · 11014 bytes Raw Blame History
1//! The whole Qwen3.8-27B (all 64 layers) on the Omega engine against the host reference, one
2//! layer window at a time (sc #642, omega-mv #559).
3//!
4//! qwen38_omega_full <checkpoint-dir> <window-layers> <golden.json> <out.json>
5//!
6//! `golden.json` is a `qwen38_check generate` record (`prompt_ids`, `generated_ids`: the host
7//! reference's greedy continuation). The sequence is the prompt plus every generated token but the
8//! last, fed one decode step at a time (teacher forcing with the reference's own tokens: if the chip
9//! picks the reference's token at every step, free-running greedy decoding produces the same text).
10//!
11//! The device holds one window of `window-layers` layers (plus lm_head) at a time, because the
12//! resident 30B server leaves less free memory than the whole 27B needs. Window 0 takes the token
13//! embeddings; window w takes window w - 1's residual stream as the CHIP computed it (never the
14//! reference's), so the last window's logits are a full 64-layer chip forward pass. Each window's
15//! output residual is also held to the reference's residual at that layer boundary.
16//!
17//! PASS when every generated position's chip token equals the golden token, the logits' cosine is
18//! >= 0.9999 at every step, the greedy token agrees wherever the reference's top-two margin is at
19//! least 0.1, and both controls are caught: (1) each step against the reference's NEXT position,
20//! (2) the final residual against the reference's residual one window earlier (the last window
21//! must matter). A check that cannot fail proves nothing.
22
23use std::path::Path;
24use std::time::Instant;
25
26use aien_inference_abi::qwen38::{argmax, Logits, Qwen38Config, Qwen38Reference};
27use aien_inference_abi::qwen38_omega::Qwen38Omega;
28use aien_inference_abi::qwen3_moe::parity_stats;
29use aien_inference_abi::qwen3_moe_omega::ShardSource;
30use serde_json::{json, Value};
31
32const COSINE_MIN: f64 = 0.9999;
33const MARGIN_MIN: f32 = 0.1;
34
35fn margin(logits: &[f32]) -> f32 {
36 let top = argmax(logits);
37 let second = logits
38 .iter()
39 .enumerate()
40 .filter(|&(i, _)| i != top)
41 .map(|(_, &v)| v)
42 .fold(f32::NEG_INFINITY, f32::max);
43 logits[top] - second
44}
45
46fn ids(v: &Value, key: &str) -> Result<Vec<u32>, String> {
47 v[key]
48 .as_array()
49 .ok_or_else(|| format!("golden: no {key}"))?
50 .iter()
51 .map(|x| {
52 x.as_u64()
53 .and_then(|n| u32::try_from(n).ok())
54 .ok_or_else(|| format!("golden: {key} holds a non-id"))
55 })
56 .collect()
57}
58
59fn run() -> Result<bool, String> {
60 let args: Vec<String> = std::env::args().collect();
61 let usage = "usage: qwen38_omega_full <checkpoint-dir> <window-layers> <golden.json> <out.json>";
62 if args.len() != 5 {
63 return Err(usage.into());
64 }
65 let dir = Path::new(&args[1]);
66 let wl: usize = args[2].parse().map_err(|_| usage.to_string())?;
67 let out_path = &args[4];
68 let golden: Value = serde_json::from_str(
69 &std::fs::read_to_string(&args[3]).map_err(|e| format!("{}: {e}", args[3]))?,
70 )
71 .map_err(|e| format!("{}: {e}", args[3]))?;
72 let prompt = ids(&golden, "prompt_ids")?;
73 let generated = ids(&golden, "generated_ids")?;
74 if prompt.is_empty() || generated.is_empty() {
75 return Err("golden: empty prompt or continuation".into());
76 }
77 let mut seq = prompt.clone();
78 seq.extend_from_slice(&generated[..generated.len() - 1]);
79 let (t, first_gen) = (seq.len(), prompt.len() - 1);
80
81 let config = Qwen38Config::from_checkpoint(dir)?;
82 let layers = config.layers;
83 if wl == 0 || layers % wl != 0 {
84 return Err(format!("window {wl} does not divide {layers} layers"));
85 }
86 let windows = layers / wl;
87 let (h, vocab) = (config.hidden, config.vocab);
88 eprintln!("model: {layers} layers in {windows} windows of {wl}; {t} positions ({} generated)", generated.len());
89
90 // The reference: logits at every position plus the residual at every window boundary.
91 let t0 = Instant::now();
92 let bounds: Vec<usize> = (1..=windows).map(|w| w * wl).collect();
93 let mut taps = Vec::new();
94 let reference = {
95 let mut r = Qwen38Reference::new(config.clone(), ShardSource::open(dir)?)?;
96 let mut state = r.new_state();
97 r.forward_tapped(&mut state, &seq, Logits::All, &bounds, &mut taps)?
98 };
99 let ref_s = t0.elapsed().as_secs_f64();
100 let ref_matches_golden = (0..generated.len())
101 .all(|i| argmax(&reference[(first_gen + i) * vocab..(first_gen + i + 1) * vocab]) == generated[i] as usize);
102 eprintln!(
103 "reference: {t} positions in {ref_s:.1} s; its greedy tokens {} the golden record",
104 if ref_matches_golden { "equal" } else { "DIFFER FROM" }
105 );
106
107 // The chip, window by window, each fed the previous window's chip residual.
108 let mut x_in: Vec<Vec<f32>> = Vec::new();
109 let mut gpu_logits: Vec<Vec<f32>> = Vec::new();
110 let mut tokens = vec![0u32; t];
111 let mut chip_ns = vec![0u64; t];
112 let mut win_report = Vec::new();
113 let mut upload_s = 0.0;
114 let mut weight_bytes = 0usize;
115 for w in 0..windows {
116 let first = w * wl;
117 let t1 = Instant::now();
118 let mut engine = Qwen38Omega::open_window(dir, first, wl, t.max(256))?;
119 let ls = t1.elapsed().as_secs_f64();
120 upload_s += ls;
121 weight_bytes += engine.weight_bytes();
122 eprintln!(
123 "window {w} (layers {first}..{}): uploaded in {ls:.1} s, weights {} MB, KV {} MB",
124 first + wl - 1,
125 engine.weight_bytes() >> 20,
126 engine.kv_bytes() >> 20
127 );
128 let last = w + 1 == windows;
129 let mut x_out = Vec::with_capacity(t);
130 for p in 0..t {
131 let (tok, st) = if w == 0 {
132 engine.step(seq[p])?
133 } else {
134 engine.step_residual(&x_in[p])?
135 };
136 chip_ns[p] += st.chip_ns;
137 x_out.push(engine.residual()?);
138 if last {
139 tokens[p] = tok;
140 gpu_logits.push(engine.logits()?);
141 }
142 }
143 let tap = &taps[w];
144 let (mut cos_min, mut p95_max) = (f64::INFINITY, 0f32);
145 for (p, x) in x_out.iter().enumerate() {
146 let s = parity_stats(x, &tap[p * h..(p + 1) * h]);
147 cos_min = cos_min.min(if s.non_finite > 0 { f64::NEG_INFINITY } else { s.cosine });
148 p95_max = p95_max.max(s.p95_rel);
149 }
150 println!("window {w} layers {first}..{}: residual cosine(min) {cos_min:.6} p95_rel(max) {p95_max:.4}", first + wl - 1);
151 win_report.push(json!({"window": w, "first_layer": first, "layers": wl, "upload_s": ls,
152 "weight_bytes": engine.weight_bytes(), "residual_cosine_min": cos_min, "residual_p95_rel_max": p95_max}));
153 x_in = x_out;
154 drop(engine);
155 }
156
157 let mut steps = Vec::with_capacity(t);
158 let (mut cos_min, mut p95_max, mut greedy_ok, mut golden_ok) = (f64::INFINITY, 0f32, true, true);
159 let mut gen_tokens = Vec::new();
160 for p in 0..t {
161 let logits = &gpu_logits[p];
162 let expected = &reference[p * vocab..(p + 1) * vocab];
163 let s = parity_stats(logits, expected);
164 let (ref_tok, m) = (argmax(expected), margin(expected));
165 let tok = tokens[p] as usize;
166 let agree = tok == ref_tok && argmax(logits) == tok;
167 if m >= MARGIN_MIN && !agree {
168 greedy_ok = false;
169 }
170 let gold = (p >= first_gen).then(|| generated[p - first_gen] as usize);
171 if let Some(g) = gold {
172 gen_tokens.push(tok);
173 if tok != g {
174 golden_ok = false;
175 }
176 }
177 cos_min = cos_min.min(if s.non_finite > 0 { f64::NEG_INFINITY } else { s.cosine });
178 p95_max = p95_max.max(s.p95_rel);
179 println!(
180 "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{}",
181 gold.map_or(String::new(), |g| format!(" golden {g:6}")),
182 s.cosine,
183 s.p95_rel,
184 s.max_abs,
185 chip_ns[p] as f64 / 1e6,
186 if gold.is_some_and(|g| g != tok) { " GOLDEN DIFFERS" } else if agree { "" } else { " (differs)" }
187 );
188 steps.push(json!({"pos": p, "token": tok, "ref_token": ref_tok, "golden": gold, "ref_margin": m,
189 "cosine": s.cosine, "p95_rel": s.p95_rel, "max_abs": s.max_abs, "non_finite": s.non_finite,
190 "chip_ns_all_windows": chip_ns[p]}));
191 }
192
193 // Controls.
194 let shift_cos = (0..t - 1)
195 .map(|p| parity_stats(&gpu_logits[p], &reference[(p + 1) * vocab..(p + 2) * vocab]).cosine)
196 .fold(f64::NEG_INFINITY, f64::max);
197 let short_cos = (windows >= 2).then(|| {
198 let tap = &taps[windows - 2];
199 (0..t)
200 .map(|p| parity_stats(&x_in[p], &tap[p * h..(p + 1) * h]).cosine)
201 .fold(f64::NEG_INFINITY, f64::max)
202 });
203 let caught = shift_cos < COSINE_MIN && short_cos.is_none_or(|c| c < COSINE_MIN);
204 println!(
205 "CONTROL shifted-by-one: best cosine {shift_cos:.6}; one window short: best cosine {} -> {}",
206 short_cos.map_or("n/a".to_string(), |c| format!("{c:.6}")),
207 if caught { "caught" } else { "NOT CAUGHT" }
208 );
209 let text_ok = gen_tokens.len() == generated.len();
210 let pass = cos_min >= COSINE_MIN && greedy_ok && golden_ok && text_ok && caught && ref_matches_golden;
211 println!(
212 "QWEN38_OMEGA_FULL layers {layers} windows {windows} positions {t}: generated {}/{} identical to golden, cosine(min) {cos_min:.6} p95_rel(max) {p95_max:.4} greedy {} control {} -> {}",
213 gen_tokens.iter().zip(&generated).filter(|(a, b)| **a == **b as usize).count(),
214 generated.len(),
215 if greedy_ok { "agrees" } else { "DIFFERS" },
216 if caught { "caught" } else { "NOT CAUGHT" },
217 if pass { "PASS" } else { "FAIL" }
218 );
219 let report = json!({
220 "checkpoint": dir.display().to_string(), "layers": layers, "window_layers": wl, "windows": win_report,
221 "positions": t, "prompt_ids": prompt, "golden_ids": generated, "chip_ids": gen_tokens,
222 "reference_s": ref_s, "reference_matches_golden": ref_matches_golden, "upload_s": upload_s,
223 "weight_bytes": weight_bytes, "cosine_min": cos_min, "p95_rel_max": p95_max,
224 "greedy_agrees": greedy_ok, "golden_identical": golden_ok,
225 "control_shift_best_cosine": shift_cos, "control_window_short_best_cosine": short_cos,
226 "control_caught": caught, "thresholds": {"cosine_min": COSINE_MIN, "margin_min": MARGIN_MIN},
227 "steps": steps, "pass": pass,
228 });
229 std::fs::write(out_path, serde_json::to_string_pretty(&report).unwrap())
230 .map_err(|e| format!("{out_path}: {e}"))?;
231 Ok(pass)
232}
233
234fn main() {
235 match run() {
236 Ok(true) => {}
237 Ok(false) => std::process::exit(1),
238 Err(e) => {
239 eprintln!("qwen38_omega_full: {e}");
240 std::process::exit(2);
241 }
242 }
243}