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-20261018T1646Z-INVALID-mixed-physics / qwen38_omega_full.rs

286 lines · 12974 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;
33/// Free memory kept for everything else on the box (the resident 30B server shares this pool:
34/// 2026-10-18 16:43:58Z a 32-layer window pushed the kernel into the OOM killer, which took the
35/// server). A window is uploaded only when MemAvailable covers it plus this margin.
36const KEEP_FREE: u64 = 12 << 30;
37
38/// Device bytes a window takes: its FP8 weights (1 byte each; the 128x128 block scales add 1/4096),
39/// the bf16 a|b rows of its DeltaNet layers, and the bf16 lm_head; from the config, not measured.
40fn window_bytes(c: &Qwen38Config, first: usize, count: usize) -> u64 {
41 let h = c.hidden as u64;
42 let mlp = 3 * c.intermediate as u64 * h;
43 let o = h * (c.heads * c.head_dim) as u64;
44 let layers: u64 = c.full_attention[first..first + count]
45 .iter()
46 .map(|&attn| {
47 if attn {
48 (2 * c.heads * c.head_dim + 2 * c.kv_dim()) as u64 * h + o + mlp
49 } else {
50 (c.conv_dim() + c.lin_value_dim()) as u64 * h + o + mlp + 2 * 2 * c.lin_v_heads as u64 * h
51 }
52 })
53 .sum();
54 layers + layers / 4096 + 2 * c.vocab as u64 * h
55}
56
57/// MemAvailable from /proc/meminfo, in bytes.
58fn mem_available() -> Result<u64, String> {
59 let m = std::fs::read_to_string("/proc/meminfo").map_err(|e| format!("/proc/meminfo: {e}"))?;
60 m.lines()
61 .find_map(|l| l.strip_prefix("MemAvailable:"))
62 .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::<u64>().ok())
63 .map(|kb| kb << 10)
64 .ok_or_else(|| "/proc/meminfo: no MemAvailable".into())
65}
66const MARGIN_MIN: f32 = 0.1;
67
68fn margin(logits: &[f32]) -> f32 {
69 let top = argmax(logits);
70 let second = logits
71 .iter()
72 .enumerate()
73 .filter(|&(i, _)| i != top)
74 .map(|(_, &v)| v)
75 .fold(f32::NEG_INFINITY, f32::max);
76 logits[top] - second
77}
78
79fn ids(v: &Value, key: &str) -> Result<Vec<u32>, String> {
80 v[key]
81 .as_array()
82 .ok_or_else(|| format!("golden: no {key}"))?
83 .iter()
84 .map(|x| {
85 x.as_u64()
86 .and_then(|n| u32::try_from(n).ok())
87 .ok_or_else(|| format!("golden: {key} holds a non-id"))
88 })
89 .collect()
90}
91
92fn run() -> Result<bool, String> {
93 let args: Vec<String> = std::env::args().collect();
94 let usage = "usage: qwen38_omega_full <checkpoint-dir> <window-layers> <golden.json> <out.json>";
95 if args.len() != 5 {
96 return Err(usage.into());
97 }
98 let dir = Path::new(&args[1]);
99 let wl: usize = args[2].parse().map_err(|_| usage.to_string())?;
100 let out_path = &args[4];
101 let golden: Value = serde_json::from_str(
102 &std::fs::read_to_string(&args[3]).map_err(|e| format!("{}: {e}", args[3]))?,
103 )
104 .map_err(|e| format!("{}: {e}", args[3]))?;
105 let prompt = ids(&golden, "prompt_ids")?;
106 let generated = ids(&golden, "generated_ids")?;
107 if prompt.is_empty() || generated.is_empty() {
108 return Err("golden: empty prompt or continuation".into());
109 }
110 let mut seq = prompt.clone();
111 seq.extend_from_slice(&generated[..generated.len() - 1]);
112 let (t, first_gen) = (seq.len(), prompt.len() - 1);
113
114 let config = Qwen38Config::from_checkpoint(dir)?;
115 let layers = config.layers;
116 if wl == 0 || layers % wl != 0 {
117 return Err(format!("window {wl} does not divide {layers} layers"));
118 }
119 let windows = layers / wl;
120 let (h, vocab) = (config.hidden, config.vocab);
121 eprintln!("model: {layers} layers in {windows} windows of {wl}; {t} positions ({} generated)", generated.len());
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())
134 .all(|i| argmax(&reference[(first_gen + i) * vocab..(first_gen + i + 1) * vocab]) == generated[i] as usize);
135 eprintln!(
136 "reference: {t} positions in {ref_s:.1} s; its greedy tokens {} the golden record",
137 if ref_matches_golden { "equal" } else { "DIFFER FROM" }
138 );
139
140 // The chip, window by window, each fed the previous window's chip residual.
141 let mut x_in: Vec<Vec<f32>> = Vec::new();
142 let mut gpu_logits: Vec<Vec<f32>> = Vec::new();
143 let mut tokens = vec![0u32; t];
144 let mut chip_ns = vec![0u64; t];
145 let mut win_report = Vec::new();
146 let mut upload_s = 0.0;
147 let mut weight_bytes = 0usize;
148 for w in 0..windows {
149 let first = w * wl;
150 let need = window_bytes(&config, first, wl);
151 let avail = mem_available()?;
152 if avail < need + KEEP_FREE {
153 return Err(format!(
154 "window {w}: needs {} MiB with {} MiB kept free, MemAvailable {} MiB; refusing (use a smaller window)",
155 need >> 20,
156 KEEP_FREE >> 20,
157 avail >> 20
158 ));
159 }
160 let t1 = Instant::now();
161 let mut engine = Qwen38Omega::open_window(dir, first, wl, t.max(256))?;
162 let ls = t1.elapsed().as_secs_f64();
163 upload_s += ls;
164 weight_bytes += engine.weight_bytes();
165 eprintln!(
166 "window {w} (layers {first}..{}): uploaded in {ls:.1} s, weights {} MB, KV {} MB",
167 first + wl - 1,
168 engine.weight_bytes() >> 20,
169 engine.kv_bytes() >> 20
170 );
171 let last = w + 1 == windows;
172 let mut x_out = Vec::with_capacity(t);
173 for p in 0..t {
174 let (tok, st) = if w == 0 {
175 engine.step(seq[p])?
176 } else {
177 engine.step_residual(&x_in[p])?
178 };
179 chip_ns[p] += st.chip_ns;
180 x_out.push(engine.residual()?);
181 if last {
182 tokens[p] = tok;
183 gpu_logits.push(engine.logits()?);
184 }
185 }
186 let tap = &taps[w];
187 let (mut cos_min, mut p95_max) = (f64::INFINITY, 0f32);
188 for (p, x) in x_out.iter().enumerate() {
189 let s = parity_stats(x, &tap[p * h..(p + 1) * h]);
190 cos_min = cos_min.min(if s.non_finite > 0 { f64::NEG_INFINITY } else { s.cosine });
191 p95_max = p95_max.max(s.p95_rel);
192 }
193 println!("window {w} layers {first}..{}: residual cosine(min) {cos_min:.6} p95_rel(max) {p95_max:.4}", first + wl - 1);
194 win_report.push(json!({"window": w, "first_layer": first, "layers": wl, "upload_s": ls,
195 "weight_bytes": engine.weight_bytes(), "residual_cosine_min": cos_min, "residual_p95_rel_max": p95_max}));
196 x_in = x_out;
197 drop(engine);
198 }
199
200 let mut steps = Vec::with_capacity(t);
201 let (mut cos_min, mut p95_max, mut greedy_ok, mut golden_ok) = (f64::INFINITY, 0f32, true, true);
202 let mut gen_tokens = Vec::new();
203 for p in 0..t {
204 let logits = &gpu_logits[p];
205 let expected = &reference[p * vocab..(p + 1) * vocab];
206 let s = parity_stats(logits, expected);
207 let (ref_tok, m) = (argmax(expected), margin(expected));
208 let tok = tokens[p] as usize;
209 let agree = tok == ref_tok && argmax(logits) == tok;
210 if m >= MARGIN_MIN && !agree {
211 greedy_ok = false;
212 }
213 let gold = (p >= first_gen).then(|| generated[p - first_gen] as usize);
214 if let Some(g) = gold {
215 gen_tokens.push(tok);
216 if tok != g {
217 golden_ok = false;
218 }
219 }
220 cos_min = cos_min.min(if s.non_finite > 0 { f64::NEG_INFINITY } else { s.cosine });
221 p95_max = p95_max.max(s.p95_rel);
222 println!(
223 "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{}",
224 gold.map_or(String::new(), |g| format!(" golden {g:6}")),
225 s.cosine,
226 s.p95_rel,
227 s.max_abs,
228 chip_ns[p] as f64 / 1e6,
229 if gold.is_some_and(|g| g != tok) { " GOLDEN DIFFERS" } else if agree { "" } else { " (differs)" }
230 );
231 steps.push(json!({"pos": p, "token": tok, "ref_token": ref_tok, "golden": gold, "ref_margin": m,
232 "cosine": s.cosine, "p95_rel": s.p95_rel, "max_abs": s.max_abs, "non_finite": s.non_finite,
233 "chip_ns_all_windows": chip_ns[p]}));
234 }
235
236 // Controls.
237 let shift_cos = (0..t - 1)
238 .map(|p| parity_stats(&gpu_logits[p], &reference[(p + 1) * vocab..(p + 2) * vocab]).cosine)
239 .fold(f64::NEG_INFINITY, f64::max);
240 let short_cos = (windows >= 2).then(|| {
241 let tap = &taps[windows - 2];
242 (0..t)
243 .map(|p| parity_stats(&x_in[p], &tap[p * h..(p + 1) * h]).cosine)
244 .fold(f64::NEG_INFINITY, f64::max)
245 });
246 let caught = shift_cos < COSINE_MIN && short_cos.is_none_or(|c| c < COSINE_MIN);
247 println!(
248 "CONTROL shifted-by-one: best cosine {shift_cos:.6}; one window short: best cosine {} -> {}",
249 short_cos.map_or("n/a".to_string(), |c| format!("{c:.6}")),
250 if caught { "caught" } else { "NOT CAUGHT" }
251 );
252 let text_ok = gen_tokens.len() == generated.len();
253 let pass = cos_min >= COSINE_MIN && greedy_ok && golden_ok && text_ok && caught && ref_matches_golden;
254 println!(
255 "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 {} -> {}",
256 gen_tokens.iter().zip(&generated).filter(|(a, b)| **a == **b as usize).count(),
257 generated.len(),
258 if greedy_ok { "agrees" } else { "DIFFERS" },
259 if caught { "caught" } else { "NOT CAUGHT" },
260 if pass { "PASS" } else { "FAIL" }
261 );
262 let report = json!({
263 "checkpoint": dir.display().to_string(), "layers": layers, "window_layers": wl, "windows": win_report,
264 "positions": t, "prompt_ids": prompt, "golden_ids": generated, "chip_ids": gen_tokens,
265 "reference_s": ref_s, "reference_matches_golden": ref_matches_golden, "upload_s": upload_s,
266 "weight_bytes": weight_bytes, "cosine_min": cos_min, "p95_rel_max": p95_max,
267 "greedy_agrees": greedy_ok, "golden_identical": golden_ok,
268 "control_shift_best_cosine": shift_cos, "control_window_short_best_cosine": short_cos,
269 "control_caught": caught, "thresholds": {"cosine_min": COSINE_MIN, "margin_min": MARGIN_MIN},
270 "steps": steps, "pass": pass,
271 });
272 std::fs::write(out_path, serde_json::to_string_pretty(&report).unwrap())
273 .map_err(|e| format!("{out_path}: {e}"))?;
274 Ok(pass)
275}
276
277fn main() {
278 match run() {
279 Ok(true) => {}
280 Ok(false) => std::process::exit(1),
281 Err(e) => {
282 eprintln!("qwen38_omega_full: {e}");
283 std::process::exit(2);
284 }
285 }
286}