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 / own8b_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 | //! OWN-8B stage 2 check: a dense Qwen3 checkpoint (Qwen3-8B FP8, Qwen3-4B bf16 tied) on Omega |
| 17 | //! against the host reference path (design `~/handoffs/2026-10-15-own8b-design.md`, section 2.4). |
| 18 | //! |
| 19 | //! own8b_check golden <checkpoint> <golden.json> [--new N] [--prompts 1,2,3,4,5] |
| 20 | //! Host only: the same engine code with host GEMVs and the host bf16 KV pool (oracle A), |
| 21 | //! greedy continuations of the 5 fixed prompts (4 chat prompts + a 512-token prompt), |
| 22 | //! top-2 margins, the shard SHA256s. Recorded once, then sealed. |
| 23 | //! own8b_check chip <checkpoint> <golden.json> <receipt-dir> [--new N] [--prompts 1,2,3,4,5] |
| 24 | //! [--layers 0,17,35] [--parity-prompts 1,2,3,4] [--max-context 4096] |
| 25 | //! [--speed-tokens 128] [--upload-mutant swap-kv|transpose-scales] |
| 26 | //! [--kernel-mutant N] [--attention-mutant] [--no-host] [--force-memory] |
| 27 | //! Omega: loads the resident model; oracle A per layer (chip traces against the host |
| 28 | //! engine teacher-forced on the golden tokens). Design 2.4 A, kept 2026-11-01: cosine |
| 29 | //! >= 0.99999 on x_out, attention, and mlp_out, and x_out p95_rel <= 2e-3, per traced |
| 30 | //! layer. The default `--layers` set is every layer (a subset still works). Greedy tokens |
| 31 | //! against the golden exactly; prefill (multi-row) against decode |
| 32 | //! (row by row) on the chip; decode tok/s and prefill tok/s. Mutant flags turn a run |
| 33 | //! into a negative control: it must FAIL. |
| 34 | //! Writes <receipt-dir>/run.json and log.txt; the shell seals SHA256SUMS. |
| 35 | //! own8b_check oracle-b <checkpoint> <golden.json> [<out.json>] [--prompts 1,2,3,4,5] |
| 36 | //! Host only, oracle B teacher-forced leg (design section 2.4 B): feeds the golden tokens of |
| 37 | //! another checkpoint (the bf16 golden) to this checkpoint's host engine and counts the |
| 38 | //! positions where this checkpoint's top-1 equals the golden token. Prior-guess thresholds: |
| 39 | //! >= 0.95 over all scored positions and no prompt below 0.90 (MISS goes to Drake as a |
| 40 | //! finding about the checkpoint, not as an engine verdict). |
| 41 | //! |
| 42 | //! Exit: 0 PASS, 1 FAIL (oracle-b: MISS), 2 usage, 3 refused (memory). |
| 43 | |
| 44 | use std::path::{Path, PathBuf}; |
| 45 | use std::time::Instant; |
| 46 | |
| 47 | use aien_inference_abi::qwen3_dense_omega::engine::{ |
| 48 | DenseLayerTrace, DenseUploadMutant, HostDenseUploader, MutantUploader, OmegaDenseUploader, |
| 49 | Qwen3DenseOmegaEngine, |
| 50 | }; |
| 51 | use aien_inference_abi::qwen3_dense_omega::{DenseUploader, DenseWeightFormat, Qwen3DenseConfig}; |
| 52 | use aien_inference_abi::qwen3_moe::parity_stats; |
| 53 | use aien_inference_abi::qwen3_moe_omega::GenerateParams; |
| 54 | use aien_inference_abi::tokenizer::ChatTokenizer as Tokenizer; |
| 55 | use sha2::{Digest, Sha256}; |
| 56 | |
| 57 | /// Oracle A thresholds, design `~/handoffs/2026-10-15-own8b-design.md` section 2.4 A. |
| 58 | /// Kept 2026-11-01 (merge desk on PR 636): cosine >= 0.99999, x_out p95_rel <= 2e-3. |
| 59 | /// A miss does not move either constant. |
| 60 | const COSINE_MIN: f64 = 0.99999; |
| 61 | const P95_REL_MAX: f32 = 2e-3; |
| 62 | |
| 63 | const PROMPT_TEXTS: [(&str, &str); 4] = [ |
| 64 | ("p1-one-token", "Hello"), |
| 65 | ("p2-short", "What is the capital of France? Answer in one sentence."), |
| 66 | ( |
| 67 | "p3-medium", |
| 68 | "Summarise the following in three bullet points.\n\nThe DGX Spark is a compact workstation built around the GB10 Grace Blackwell superchip. It pairs an Arm CPU with a Blackwell GPU over a coherent link, sharing one pool of unified memory, so a model that is loaded once can be read by both sides without copies. Engineers who write their own kernels for this chip have to think about launch overhead, about which memory is cached on the GPU side, and about how the host polls for completion. The practical outcome is that bandwidth per token, not compute, sets the speed of decoding.", |
| 69 | ), |
| 70 | ( |
| 71 | "p4-code", |
| 72 | "Write a Rust function `fn is_prime(n: u64) -> bool` that uses trial division up to the square root, with a short doc comment. Then explain in two sentences why checking up to the square root is enough.", |
| 73 | ), |
| 74 | ]; |
| 75 | /// The fifth prompt: the first 512 ids of a long text (prefill at width, design 2.4 B). |
| 76 | const LONG_PROMPT_TOKENS: usize = 512; |
| 77 | |
| 78 | fn chatml(user: &str) -> String { |
| 79 | format!("<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n") |
| 80 | } |
| 81 | |
| 82 | fn prompts(tok: &Tokenizer) -> Vec<(String, Vec<u32>)> { |
| 83 | let mut out: Vec<(String, Vec<u32>)> = PROMPT_TEXTS |
| 84 | .iter() |
| 85 | .map(|(name, text)| { |
| 86 | let ids = if *name == "p1-one-token" { |
| 87 | tok.encode_with_special(text, false).expect("encode") |
| 88 | } else { |
| 89 | tok.encode_with_special(&chatml(text), false) |
| 90 | .expect("encode") |
| 91 | }; |
| 92 | (name.to_string(), ids) |
| 93 | }) |
| 94 | .collect(); |
| 95 | let long: String = (0..12) |
| 96 | .map(|i| format!("Section {i}. {}\n", PROMPT_TEXTS[2].1)) |
| 97 | .collect(); |
| 98 | let mut ids = tok.encode_with_special(&long, false).expect("encode"); |
| 99 | assert!( |
| 100 | ids.len() >= LONG_PROMPT_TOKENS, |
| 101 | "long prompt has {} ids", |
| 102 | ids.len() |
| 103 | ); |
| 104 | ids.truncate(LONG_PROMPT_TOKENS); |
| 105 | out.push(("p5-512".into(), ids)); |
| 106 | out |
| 107 | } |
| 108 | |
| 109 | #[derive(Debug, Clone)] |
| 110 | struct Args { |
| 111 | mode: String, |
| 112 | checkpoint: PathBuf, |
| 113 | golden: PathBuf, |
| 114 | receipt: Option<PathBuf>, |
| 115 | new_tokens: usize, |
| 116 | prompt_ids: Vec<usize>, |
| 117 | parity_prompts: Vec<usize>, |
| 118 | layers: Option<Vec<usize>>, |
| 119 | max_context: usize, |
| 120 | speed_tokens: usize, |
| 121 | upload_mutant: Option<DenseUploadMutant>, |
| 122 | kernel_mutant: i32, |
| 123 | attention_mutant: bool, |
| 124 | no_host: bool, |
| 125 | force_memory: bool, |
| 126 | } |
| 127 | |
| 128 | fn usage() -> ! { |
| 129 | eprintln!("{}", USAGE); |
| 130 | std::process::exit(2) |
| 131 | } |
| 132 | |
| 133 | const USAGE: &str = "usage: own8b_check golden <checkpoint> <golden.json> [--new N] [--prompts 1,2,..]\n own8b_check chip <checkpoint> <golden.json> <receipt-dir> [flags, see the source header]\n own8b_check oracle-b <checkpoint> <golden.json> [<out.json>] [--prompts 1,2,..]"; |
| 134 | |
| 135 | fn list(s: &str) -> Vec<usize> { |
| 136 | s.split(',') |
| 137 | .map(|x| x.trim().parse().unwrap_or_else(|_| usage())) |
| 138 | .collect() |
| 139 | } |
| 140 | |
| 141 | fn parse() -> Args { |
| 142 | let argv: Vec<String> = std::env::args().skip(1).collect(); |
| 143 | let mut a = Args { |
| 144 | mode: argv.first().cloned().unwrap_or_else(|| usage()), |
| 145 | checkpoint: PathBuf::new(), |
| 146 | golden: PathBuf::new(), |
| 147 | receipt: None, |
| 148 | new_tokens: 32, |
| 149 | prompt_ids: vec![1, 2, 3, 4, 5], |
| 150 | parity_prompts: vec![1, 2, 3, 4], |
| 151 | layers: None, |
| 152 | max_context: 4096, |
| 153 | speed_tokens: 128, |
| 154 | upload_mutant: None, |
| 155 | kernel_mutant: 0, |
| 156 | attention_mutant: false, |
| 157 | no_host: false, |
| 158 | force_memory: false, |
| 159 | }; |
| 160 | let mut pos = Vec::new(); |
| 161 | let mut i = 1; |
| 162 | while i < argv.len() { |
| 163 | let v = || argv.get(i + 1).cloned().unwrap_or_else(|| usage()); |
| 164 | match argv[i].as_str() { |
| 165 | "--new" => a.new_tokens = v().parse().unwrap_or_else(|_| usage()), |
| 166 | "--prompts" => a.prompt_ids = list(&v()), |
| 167 | "--parity-prompts" => a.parity_prompts = list(&v()), |
| 168 | "--layers" => a.layers = Some(list(&v())), |
| 169 | "--max-context" => a.max_context = v().parse().unwrap_or_else(|_| usage()), |
| 170 | "--speed-tokens" => a.speed_tokens = v().parse().unwrap_or_else(|_| usage()), |
| 171 | "--upload-mutant" => { |
| 172 | a.upload_mutant = Some(DenseUploadMutant::parse(&v()).unwrap_or_else(|e| { |
| 173 | eprintln!("{e}"); |
| 174 | usage() |
| 175 | })) |
| 176 | } |
| 177 | "--kernel-mutant" => a.kernel_mutant = v().parse().unwrap_or_else(|_| usage()), |
| 178 | "--attention-mutant" => { |
| 179 | a.attention_mutant = true; |
| 180 | i += 1; |
| 181 | continue; |
| 182 | } |
| 183 | "--no-host" => { |
| 184 | a.no_host = true; |
| 185 | i += 1; |
| 186 | continue; |
| 187 | } |
| 188 | "--force-memory" => { |
| 189 | a.force_memory = true; |
| 190 | i += 1; |
| 191 | continue; |
| 192 | } |
| 193 | f if f.starts_with("--") => usage(), |
| 194 | p => { |
| 195 | pos.push(p.to_string()); |
| 196 | i += 1; |
| 197 | continue; |
| 198 | } |
| 199 | } |
| 200 | i += 2; |
| 201 | } |
| 202 | if pos.len() < 2 { |
| 203 | usage(); |
| 204 | } |
| 205 | a.checkpoint = PathBuf::from(&pos[0]); |
| 206 | a.golden = PathBuf::from(&pos[1]); |
| 207 | a.receipt = pos.get(2).map(PathBuf::from); |
| 208 | a |
| 209 | } |
| 210 | |
| 211 | fn top2_margin(logits: &[f32]) -> (u32, f32) { |
| 212 | let (mut b1, mut b2) = ((0usize, f32::NEG_INFINITY), f32::NEG_INFINITY); |
| 213 | for (i, &v) in logits.iter().enumerate() { |
| 214 | if v > b1.1 { |
| 215 | b2 = b1.1; |
| 216 | b1 = (i, v); |
| 217 | } else if v > b2 { |
| 218 | b2 = v; |
| 219 | } |
| 220 | } |
| 221 | (b1.0 as u32, b1.1 - b2) |
| 222 | } |
| 223 | |
| 224 | fn shard_digests(dir: &Path) -> Vec<serde_json::Value> { |
| 225 | let mut names: Vec<_> = std::fs::read_dir(dir) |
| 226 | .expect("checkpoint dir") |
| 227 | .filter_map(|e| e.ok()) |
| 228 | .map(|e| e.file_name().to_string_lossy().into_owned()) |
| 229 | .filter(|n| n.ends_with(".safetensors")) |
| 230 | .collect(); |
| 231 | names.sort(); |
| 232 | names |
| 233 | .into_iter() |
| 234 | .map(|n| { |
| 235 | let mut f = std::fs::File::open(dir.join(&n)).expect("shard"); |
| 236 | let mut h = Sha256::new(); |
| 237 | std::io::copy(&mut f, &mut h).expect("hash shard"); |
| 238 | serde_json::json!({"file": n, "sha256": format!("{:x}", h.finalize())}) |
| 239 | }) |
| 240 | .collect() |
| 241 | } |
| 242 | |
| 243 | fn mem_available_gb() -> f64 { |
| 244 | std::fs::read_to_string("/proc/meminfo") |
| 245 | .ok() |
| 246 | .and_then(|s| { |
| 247 | s.lines() |
| 248 | .find(|l| l.starts_with("MemAvailable:")) |
| 249 | .and_then(|l| l.split_whitespace().nth(1)) |
| 250 | .and_then(|kb| kb.parse::<f64>().ok()) |
| 251 | }) |
| 252 | .map_or(0.0, |kb| kb / 1e6) |
| 253 | } |
| 254 | |
| 255 | fn config_json(c: &Qwen3DenseConfig) -> serde_json::Value { |
| 256 | serde_json::json!({ |
| 257 | "format": format!("{:?}", c.format), "layers": c.layers, "hidden": c.hidden, |
| 258 | "q_heads": c.q_heads, "kv_heads": c.kv_heads, "head_dim": c.head_dim, |
| 259 | "intermediate": c.intermediate, "vocab": c.vocab, "rope_theta": c.rope_theta, |
| 260 | "tie_word_embeddings": c.tie_word_embeddings, "eos": c.eos_token_ids, |
| 261 | "resident_bytes": c.model_resident_bytes(), |
| 262 | }) |
| 263 | } |
| 264 | |
| 265 | fn golden(a: &Args) { |
| 266 | let tok = Tokenizer::from_file(a.checkpoint.join("tokenizer.json")).expect("tokenizer"); |
| 267 | let t0 = Instant::now(); |
| 268 | let (mut e, report) = Qwen3DenseOmegaEngine::load_host( |
| 269 | &a.checkpoint, |
| 270 | &HostDenseUploader, |
| 271 | a.max_context, |
| 272 | &mut |_| {}, |
| 273 | ) |
| 274 | .expect("host load"); |
| 275 | let config = e.config().clone(); |
| 276 | eprintln!( |
| 277 | "host reference loaded in {:.0}s ({:.2} GB)", |
| 278 | t0.elapsed().as_secs_f64(), |
| 279 | report.resident_bytes as f64 / 1e9 |
| 280 | ); |
| 281 | let mut out = Vec::new(); |
| 282 | for (idx, (name, ids)) in prompts(&tok).into_iter().enumerate() { |
| 283 | if !a.prompt_ids.contains(&(idx + 1)) { |
| 284 | continue; |
| 285 | } |
| 286 | let t1 = Instant::now(); |
| 287 | e.reset(); |
| 288 | let mut hidden = e.step_batch(&ids).expect("prefill"); |
| 289 | let (mut tokens, mut margins) = (Vec::new(), Vec::new()); |
| 290 | for _ in 0..a.new_tokens { |
| 291 | let (next, margin) = top2_margin(&e.logits(&hidden).expect("logits")); |
| 292 | tokens.push(next); |
| 293 | margins.push(margin); |
| 294 | if config.eos_token_ids.contains(&next) { |
| 295 | break; |
| 296 | } |
| 297 | hidden = e.step(next).expect("step"); |
| 298 | } |
| 299 | let secs = t1.elapsed().as_secs_f64(); |
| 300 | let text = tok.decode(&tokens).unwrap_or_default(); |
| 301 | eprintln!( |
| 302 | "{name}: {} prompt tokens, {} new in {secs:.0}s: {text:?}", |
| 303 | ids.len(), |
| 304 | tokens.len() |
| 305 | ); |
| 306 | out.push(serde_json::json!({ |
| 307 | "name": name, "prompt_tokens": ids, "golden": tokens, "margins": margins, |
| 308 | "text": text, "host_seconds": secs, |
| 309 | })); |
| 310 | } |
| 311 | let doc = serde_json::json!({ |
| 312 | "checkpoint": a.checkpoint.display().to_string(), |
| 313 | "shards": shard_digests(&a.checkpoint), |
| 314 | "config": config_json(&config), |
| 315 | "max_new": a.new_tokens, |
| 316 | "oracle": "Qwen3DenseOmegaEngine on the host (HostDenseUploader: HostFp8Gemv / HostBf16Gemv, f32 sums in column order; HostPoolKv bf16 KV), greedy, stop on eos", |
| 317 | "prompts": out, |
| 318 | }); |
| 319 | std::fs::write(&a.golden, serde_json::to_string_pretty(&doc).unwrap()).expect("write golden"); |
| 320 | eprintln!("wrote {}", a.golden.display()); |
| 321 | } |
| 322 | |
| 323 | /// Oracle B, teacher-forced: this checkpoint's host top-1 against another checkpoint's golden tokens. |
| 324 | fn oracle_b(a: &Args) { |
| 325 | let golden: serde_json::Value = |
| 326 | serde_json::from_slice(&std::fs::read(&a.golden).expect("golden file")) |
| 327 | .expect("golden json"); |
| 328 | let t0 = Instant::now(); |
| 329 | let (mut e, _) = Qwen3DenseOmegaEngine::load_host( |
| 330 | &a.checkpoint, |
| 331 | &HostDenseUploader, |
| 332 | a.max_context, |
| 333 | &mut |_| {}, |
| 334 | ) |
| 335 | .expect("host load"); |
| 336 | eprintln!( |
| 337 | "host reference loaded in {:.0}s", |
| 338 | t0.elapsed().as_secs_f64() |
| 339 | ); |
| 340 | let (mut agree_all, mut scored_all, mut worst) = (0usize, 0usize, f64::INFINITY); |
| 341 | let mut rows = Vec::new(); |
| 342 | let gprompts = golden["prompts"].as_array().expect("golden prompts"); |
| 343 | for (idx, gp) in gprompts.iter().enumerate() { |
| 344 | if !a.prompt_ids.contains(&(idx + 1)) { |
| 345 | continue; |
| 346 | } |
| 347 | let ids: Vec<u32> = serde_json::from_value(gp["prompt_tokens"].clone()).unwrap(); |
| 348 | let gold: Vec<u32> = serde_json::from_value(gp["golden"].clone()).unwrap(); |
| 349 | e.reset(); |
| 350 | let mut hidden = e.step_batch(&ids).expect("prefill"); |
| 351 | let (mut agree, mut first_miss) = (0usize, None); |
| 352 | for (i, &t) in gold.iter().enumerate() { |
| 353 | let (top, _) = top2_margin(&e.logits(&hidden).expect("logits")); |
| 354 | if top == t { |
| 355 | agree += 1; |
| 356 | } else if first_miss.is_none() { |
| 357 | first_miss = Some(i); |
| 358 | } |
| 359 | if i + 1 < gold.len() { |
| 360 | hidden = e.step(t).expect("step"); |
| 361 | } |
| 362 | } |
| 363 | let rate = agree as f64 / gold.len().max(1) as f64; |
| 364 | worst = worst.min(rate); |
| 365 | agree_all += agree; |
| 366 | scored_all += gold.len(); |
| 367 | let name = gp["name"].as_str().unwrap_or("?"); |
| 368 | println!( |
| 369 | "ORACLE_B {name}: {agree} of {} teacher-forced positions agree ({rate:.4}), first disagreement {}", |
| 370 | gold.len(), |
| 371 | first_miss.map_or("none".to_string(), |p| p.to_string()) |
| 372 | ); |
| 373 | rows.push(serde_json::json!({"name": name, "scored": gold.len(), "agree": agree, "rate": rate, "first_disagreement": first_miss})); |
| 374 | } |
| 375 | let overall = agree_all as f64 / scored_all.max(1) as f64; |
| 376 | let pass = overall >= 0.95 && worst >= 0.90; |
| 377 | let verdict = if pass { "PASS" } else { "MISS" }; |
| 378 | println!( |
| 379 | "SUMMARY oracle-b teacher-forced {agree_all} of {scored_all} ({overall:.4}), worst prompt {worst:.4}, prior guesses >= 0.95 overall and >= 0.90 per prompt -> {verdict}" |
| 380 | ); |
| 381 | if let Some(out) = &a.receipt { |
| 382 | let doc = serde_json::json!({ |
| 383 | "checkpoint": a.checkpoint.display().to_string(), |
| 384 | "golden": a.golden.display().to_string(), |
| 385 | "prompts": rows, "agree": agree_all, "scored": scored_all, |
| 386 | "overall": overall, "worst_prompt": worst, "verdict": verdict, |
| 387 | }); |
| 388 | std::fs::write(out, serde_json::to_string_pretty(&doc).unwrap()).expect("oracle-b json"); |
| 389 | } |
| 390 | std::process::exit(if pass { 0 } else { 1 }); |
| 391 | } |
| 392 | |
| 393 | /// Per traced layer: worst cosine and p95_rel of x_out, and worst cosine of the |
| 394 | /// attention output and of mlp_out. [`layer_meets_bound`] gates all three cosines |
| 395 | /// and the x_out p95_rel. |
| 396 | #[derive(Debug, Default, Clone, Copy)] |
| 397 | struct LayerWorst { |
| 398 | positions: usize, |
| 399 | x_cos: f64, |
| 400 | x_p95: f32, |
| 401 | attn_cos: f64, |
| 402 | mlp_cos: f64, |
| 403 | } |
| 404 | |
| 405 | /// Design 2.4 A. Cosine applies to x_out, attention, and mlp_out. p95_rel applies |
| 406 | /// to x_out, the only relative-error statistic this check computes. |
| 407 | fn layer_meets_bound(w: &LayerWorst) -> bool { |
| 408 | w.x_cos >= COSINE_MIN |
| 409 | && w.attn_cos >= COSINE_MIN |
| 410 | && w.mlp_cos >= COSINE_MIN |
| 411 | && w.x_p95 <= P95_REL_MAX |
| 412 | } |
| 413 | |
| 414 | fn compare_traces(chip: &[DenseLayerTrace], host: &[DenseLayerTrace], layer: usize) -> LayerWorst { |
| 415 | let mut w = LayerWorst { |
| 416 | positions: 0, |
| 417 | x_cos: 1.0, |
| 418 | x_p95: 0.0, |
| 419 | attn_cos: 1.0, |
| 420 | mlp_cos: 1.0, |
| 421 | }; |
| 422 | for c in chip.iter().filter(|t| t.layer == layer) { |
| 423 | let Some(h) = host.iter().find(|t| t.layer == layer && t.pos == c.pos) else { |
| 424 | continue; |
| 425 | }; |
| 426 | let x = parity_stats(&c.x_out, &h.x_out); |
| 427 | w.positions += 1; |
| 428 | w.x_cos = w |
| 429 | .x_cos |
| 430 | .min(if x.non_finite > 0 { f64::NAN } else { x.cosine }); |
| 431 | w.x_p95 = w.x_p95.max(x.p95_rel); |
| 432 | w.attn_cos = w.attn_cos.min(parity_stats(&c.attn, &h.attn).cosine); |
| 433 | w.mlp_cos = w.mlp_cos.min(parity_stats(&c.mlp_out, &h.mlp_out).cosine); |
| 434 | } |
| 435 | w |
| 436 | } |
| 437 | |
| 438 | fn chip(a: &Args) { |
| 439 | let receipt = a.receipt.clone().unwrap_or_else(|| usage()); |
| 440 | std::fs::create_dir_all(&receipt).expect("receipt dir"); |
| 441 | let mut log: Vec<String> = Vec::new(); |
| 442 | let mut say = |s: String| { |
| 443 | println!("{s}"); |
| 444 | log.push(s); |
| 445 | }; |
| 446 | let config = Qwen3DenseConfig::from_checkpoint(&a.checkpoint).expect("config"); |
| 447 | let need_gb = |
| 448 | config.model_resident_bytes() as f64 / 1e9 * if a.no_host { 1.2 } else { 2.4 } + 4.0; |
| 449 | let avail = mem_available_gb(); |
| 450 | say(format!( |
| 451 | "mem available before load: {avail:.1} GB, this run needs about {need_gb:.1} GB" |
| 452 | )); |
| 453 | if avail < need_gb && !a.force_memory { |
| 454 | say("REFUSED: not enough memory available; --force-memory to override".into()); |
| 455 | std::process::exit(3); |
| 456 | } |
| 457 | let golden: serde_json::Value = |
| 458 | serde_json::from_slice(&std::fs::read(&a.golden).expect("golden file")) |
| 459 | .expect("golden json"); |
| 460 | let gprompts = golden["prompts"] |
| 461 | .as_array() |
| 462 | .expect("golden prompts") |
| 463 | .clone(); |
| 464 | let tok = Tokenizer::from_file(a.checkpoint.join("tokenizer.json")).expect("tokenizer"); |
| 465 | let ours = prompts(&tok); |
| 466 | for (i, gp) in gprompts.iter().enumerate() { |
| 467 | let ids: Vec<u32> = serde_json::from_value(gp["prompt_tokens"].clone()).unwrap(); |
| 468 | let name = gp["name"].as_str().unwrap_or(""); |
| 469 | let mine = ours.iter().find(|p| p.0 == name).map(|p| &p.1); |
| 470 | assert_eq!( |
| 471 | mine, |
| 472 | Some(&ids), |
| 473 | "golden prompt {i} ({name}) is not this binary's prompt" |
| 474 | ); |
| 475 | } |
| 476 | let (bf16_native, fp8_native) = OmegaDenseUploader::native(); |
| 477 | say(format!( |
| 478 | "omega native: bf16 GEMV {bf16_native}, FP8 GEMV {fp8_native}, FP8 GEMM {}", |
| 479 | aien_omega_fp8::has_gemm() |
| 480 | )); |
| 481 | // Every layer, so a receipt is the full error-growth profile. `--layers` still selects a subset. |
| 482 | let layers = a |
| 483 | .layers |
| 484 | .clone() |
| 485 | .unwrap_or_else(|| (0..config.layers).collect()); |
| 486 | |
| 487 | // --- load (chip) --- |
| 488 | let t0 = Instant::now(); |
| 489 | let omega = OmegaDenseUploader; |
| 490 | let mutant_up; |
| 491 | let up: &dyn DenseUploader = match a.upload_mutant { |
| 492 | Some(m) => { |
| 493 | mutant_up = MutantUploader::new(&omega, m, &config); |
| 494 | &mutant_up |
| 495 | } |
| 496 | None => &omega, |
| 497 | }; |
| 498 | let (mut e, report) = |
| 499 | Qwen3DenseOmegaEngine::load_omega(&a.checkpoint, up, a.max_context, &mut |_| {}) |
| 500 | .unwrap_or_else(|err| { |
| 501 | println!("LOAD FAIL {err}"); |
| 502 | std::process::exit(1) |
| 503 | }); |
| 504 | let load_s = t0.elapsed().as_secs_f64(); |
| 505 | e.attention_mutant = a.attention_mutant; |
| 506 | if a.kernel_mutant != 0 { |
| 507 | if config.format == DenseWeightFormat::Fp8Block128 { |
| 508 | aien_omega_fp8::test_set_mutant(a.kernel_mutant); |
| 509 | aien_omega_fp8::gemm_test_set_mutant(a.kernel_mutant); |
| 510 | } else { |
| 511 | aien_omega_bf16::test_set_mutant(a.kernel_mutant); |
| 512 | } |
| 513 | } |
| 514 | say(format!( |
| 515 | "LOAD {} format {:?} tied {} layers {} resident {:.3} GB uploads {} in {load_s:.1}s, kv {} resident {} context {}, controls: upload_mutant {:?} kernel_mutant {} attention_mutant {}", |
| 516 | a.checkpoint.display(), |
| 517 | config.format, |
| 518 | config.tie_word_embeddings, |
| 519 | config.layers, |
| 520 | report.resident_bytes as f64 / 1e9, |
| 521 | report.uploads, |
| 522 | e.attention_path(), |
| 523 | e.kv_resident(), |
| 524 | e.max_context_tokens(), |
| 525 | a.upload_mutant, |
| 526 | a.kernel_mutant, |
| 527 | a.attention_mutant, |
| 528 | )); |
| 529 | let mut pass = true; |
| 530 | let mut parity_json = Vec::new(); |
| 531 | |
| 532 | // --- oracle A: per-layer parity against the host engine, teacher-forced --- |
| 533 | if !a.no_host { |
| 534 | let t1 = Instant::now(); |
| 535 | let (mut host, _) = Qwen3DenseOmegaEngine::load_host( |
| 536 | &a.checkpoint, |
| 537 | &HostDenseUploader, |
| 538 | a.max_context, |
| 539 | &mut |_| {}, |
| 540 | ) |
| 541 | .expect("host load"); |
| 542 | say(format!( |
| 543 | "host reference loaded in {:.1}s", |
| 544 | t1.elapsed().as_secs_f64() |
| 545 | )); |
| 546 | e.trace_layers = layers.clone(); |
| 547 | host.trace_layers = layers.clone(); |
| 548 | let mut worst: Vec<LayerWorst> = Vec::new(); |
| 549 | for (idx, gp) in gprompts.iter().enumerate() { |
| 550 | if !a.parity_prompts.contains(&(idx + 1)) { |
| 551 | continue; |
| 552 | } |
| 553 | let ids: Vec<u32> = serde_json::from_value(gp["prompt_tokens"].clone()).unwrap(); |
| 554 | let gold: Vec<u32> = serde_json::from_value(gp["golden"].clone()).unwrap(); |
| 555 | let steps = &gold[..gold.len().saturating_sub(1).min(16)]; |
| 556 | for eng in [&mut e, &mut host] { |
| 557 | eng.reset(); |
| 558 | eng.step_batch(&ids).expect("prefill"); |
| 559 | for &t in steps { |
| 560 | eng.step(t).expect("step"); |
| 561 | } |
| 562 | } |
| 563 | for (li, &l) in layers.iter().enumerate() { |
| 564 | let w = compare_traces(&e.traces, &host.traces, l); |
| 565 | if worst.len() <= li { |
| 566 | worst.push(w); |
| 567 | } else { |
| 568 | let o = &mut worst[li]; |
| 569 | o.positions += w.positions; |
| 570 | o.x_cos = o.x_cos.min(w.x_cos); |
| 571 | o.x_p95 = o.x_p95.max(w.x_p95); |
| 572 | o.attn_cos = o.attn_cos.min(w.attn_cos); |
| 573 | o.mlp_cos = o.mlp_cos.min(w.mlp_cos); |
| 574 | } |
| 575 | } |
| 576 | e.traces.clear(); |
| 577 | host.traces.clear(); |
| 578 | } |
| 579 | for (li, &l) in layers.iter().enumerate() { |
| 580 | let w = worst[li]; |
| 581 | let ok = layer_meets_bound(&w); |
| 582 | pass &= ok; |
| 583 | say(format!( |
| 584 | "PARITY layer {l} over {} positions: x_out cosine(min) {:.6} p95_rel(max) {:.2e}, attention cosine(min) {:.6}, mlp cosine(min) {:.6} -> {}", |
| 585 | w.positions, w.x_cos, w.x_p95, w.attn_cos, w.mlp_cos, |
| 586 | if ok { "PASS" } else { "FAIL" } |
| 587 | )); |
| 588 | parity_json.push(serde_json::json!({"layer": l, "positions": w.positions, "x_cosine_min": w.x_cos, "x_p95_rel_max": w.x_p95, "attn_cosine_min": w.attn_cos, "mlp_cosine_min": w.mlp_cos, "pass": ok})); |
| 589 | } |
| 590 | e.trace_layers.clear(); |
| 591 | drop(host); |
| 592 | } |
| 593 | |
| 594 | // --- prefill (multi-row) against decode (row by row) on the chip --- |
| 595 | let long = gprompts |
| 596 | .iter() |
| 597 | .find(|p| p["name"] == "p5-512") |
| 598 | .or_else(|| gprompts.last()) |
| 599 | .expect("a golden prompt"); |
| 600 | let long_ids: Vec<u32> = serde_json::from_value(long["prompt_tokens"].clone()).unwrap(); |
| 601 | e.reset(); |
| 602 | let tp = Instant::now(); |
| 603 | let h_batch = e.step_batch(&long_ids).expect("prefill"); |
| 604 | let prefill_s = tp.elapsed().as_secs_f64(); |
| 605 | let prefill_timing = e.last_timing; |
| 606 | e.reset(); |
| 607 | let mut h_rows = Vec::new(); |
| 608 | for &t in &long_ids { |
| 609 | h_rows = e.step(t).expect("step"); |
| 610 | } |
| 611 | let exact = h_batch |
| 612 | .iter() |
| 613 | .zip(&h_rows) |
| 614 | .all(|(x, y)| x.to_bits() == y.to_bits()); |
| 615 | let ps = parity_stats(&h_batch, &h_rows); |
| 616 | say(format!( |
| 617 | "PREFILL {} tokens in {prefill_s:.3}s ({} launches, chip {:.1} ms), last hidden vs token-at-a-time: bit-equal {exact}, cosine {:.9}", |
| 618 | long_ids.len(), |
| 619 | prefill_timing.launches, |
| 620 | prefill_timing.chip_ns as f64 / 1e6, |
| 621 | ps.cosine |
| 622 | )); |
| 623 | |
| 624 | // --- greedy tokens against the golden --- |
| 625 | let mut tokens_json = Vec::new(); |
| 626 | let mut tokens_all = true; |
| 627 | for (idx, gp) in gprompts.iter().enumerate() { |
| 628 | if !a.prompt_ids.contains(&(idx + 1)) { |
| 629 | continue; |
| 630 | } |
| 631 | let name = gp["name"].as_str().unwrap_or("?"); |
| 632 | let ids: Vec<u32> = serde_json::from_value(gp["prompt_tokens"].clone()).unwrap(); |
| 633 | let gold: Vec<u32> = serde_json::from_value(gp["golden"].clone()).unwrap(); |
| 634 | let margins: Vec<f32> = serde_json::from_value(gp["margins"].clone()).unwrap_or_default(); |
| 635 | e.reset(); |
| 636 | let mut got = Vec::new(); |
| 637 | let params = GenerateParams::greedy(gold.len(), Vec::new()); |
| 638 | e.generate(&ids, ¶ms, &mut |t| { |
| 639 | got.push(t); |
| 640 | true |
| 641 | }) |
| 642 | .expect("generate"); |
| 643 | let first_diff = got.iter().zip(&gold).position(|(x, y)| x != y); |
| 644 | let same = first_diff.is_none() && got.len() == gold.len(); |
| 645 | tokens_all &= same; |
| 646 | let detail = match first_diff { |
| 647 | None => "identical".to_string(), |
| 648 | Some(p) => format!( |
| 649 | "first divergence at {p} (golden margin there {:.4})", |
| 650 | margins.get(p).copied().unwrap_or(f32::NAN) |
| 651 | ), |
| 652 | }; |
| 653 | say(format!( |
| 654 | "TOKENS {name}: {} of {} golden tokens, {detail} -> {}", |
| 655 | got.iter().zip(&gold).take_while(|(x, y)| x == y).count(), |
| 656 | gold.len(), |
| 657 | if same { "PASS" } else { "FAIL" } |
| 658 | )); |
| 659 | tokens_json.push(serde_json::json!({"name": name, "golden": gold, "chip": got, "first_divergence": first_diff, "pass": same})); |
| 660 | } |
| 661 | pass &= tokens_all; |
| 662 | |
| 663 | // --- decode speed --- |
| 664 | let p4 = gprompts |
| 665 | .iter() |
| 666 | .find(|p| p["name"] == "p4-code") |
| 667 | .unwrap_or(&gprompts[0]); |
| 668 | let ids: Vec<u32> = serde_json::from_value(p4["prompt_tokens"].clone()).unwrap(); |
| 669 | e.reset(); |
| 670 | let mut n = 0usize; |
| 671 | let o = e |
| 672 | .generate( |
| 673 | &ids, |
| 674 | &GenerateParams::greedy(a.speed_tokens, Vec::new()), |
| 675 | &mut |_| { |
| 676 | n += 1; |
| 677 | true |
| 678 | }, |
| 679 | ) |
| 680 | .expect("speed run"); |
| 681 | let dt = o.decode_timing; |
| 682 | let steps = o.emitted_tokens.max(1) as f64; |
| 683 | let tok_s = o.emitted_tokens as f64 / (o.decode_ms as f64 / 1e3); |
| 684 | say(format!( |
| 685 | "SPEED decode {} tokens in {} ms = {tok_s:.2} tok/s; per token: chip {:.2} ms, host {:.2} ms, attention {:.2} ms, mlp {:.2} ms, lm_head {:.2} ms, {:.0} launches; prefill {} tokens in {} ms", |
| 686 | o.emitted_tokens, |
| 687 | o.decode_ms, |
| 688 | dt.chip_ns as f64 / 1e6 / steps, |
| 689 | dt.host_ns as f64 / 1e6 / steps, |
| 690 | dt.attention_ns as f64 / 1e6 / steps, |
| 691 | dt.experts_ns as f64 / 1e6 / steps, |
| 692 | dt.lm_head_ns as f64 / 1e6 / steps, |
| 693 | dt.launches as f64 / steps, |
| 694 | o.prompt_tokens, |
| 695 | o.prefill_ms, |
| 696 | )); |
| 697 | |
| 698 | let verdict = if pass { "PASS" } else { "FAIL" }; |
| 699 | say(format!( |
| 700 | "SUMMARY {verdict} (parity {} layers, tokens {}, prefill bit-equal {exact})", |
| 701 | parity_json.len(), |
| 702 | if tokens_all { "identical" } else { "differ" } |
| 703 | )); |
| 704 | let doc = serde_json::json!({ |
| 705 | "checkpoint": a.checkpoint.display().to_string(), |
| 706 | "golden": a.golden.display().to_string(), |
| 707 | "config": config_json(&config), |
| 708 | "controls": {"upload_mutant": format!("{:?}", a.upload_mutant), "kernel_mutant": a.kernel_mutant, "attention_mutant": a.attention_mutant}, |
| 709 | "thresholds": {"cosine_min": COSINE_MIN, "p95_rel_max": P95_REL_MAX}, |
| 710 | "load_seconds": load_s, "resident_bytes": report.resident_bytes, |
| 711 | "parity": parity_json, "tokens": tokens_json, |
| 712 | "prefill": {"tokens": long_ids.len(), "seconds": prefill_s, "launches": prefill_timing.launches, "chip_ns": prefill_timing.chip_ns, "bit_equal_to_decode": exact, "cosine": ps.cosine}, |
| 713 | "speed": {"tokens": o.emitted_tokens, "decode_ms": o.decode_ms, "tok_s": tok_s, "chip_ns": dt.chip_ns, "host_ns": dt.host_ns, "attention_ns": dt.attention_ns, "mlp_ns": dt.experts_ns, "lm_head_ns": dt.lm_head_ns, "launches": dt.launches, "prefill_ms": o.prefill_ms, "prompt_tokens": o.prompt_tokens}, |
| 714 | "verdict": verdict, |
| 715 | }); |
| 716 | std::fs::write( |
| 717 | receipt.join("run.json"), |
| 718 | serde_json::to_string_pretty(&doc).unwrap(), |
| 719 | ) |
| 720 | .expect("run.json"); |
| 721 | std::fs::write(receipt.join("log.txt"), log.join("\n") + "\n").expect("log"); |
| 722 | std::process::exit(if pass { 0 } else { 1 }); |
| 723 | } |
| 724 | |
| 725 | fn main() { |
| 726 | let a = parse(); |
| 727 | match a.mode.as_str() { |
| 728 | "golden" => golden(&a), |
| 729 | "chip" => chip(&a), |
| 730 | "oracle-b" => oracle_b(&a), |
| 731 | _ => usage(), |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | #[cfg(test)] |
| 736 | mod tests { |
| 737 | use super::{layer_meets_bound, LayerWorst, COSINE_MIN, P95_REL_MAX}; |
| 738 | |
| 739 | fn on_bound() -> LayerWorst { |
| 740 | LayerWorst { |
| 741 | positions: 1, |
| 742 | x_cos: COSINE_MIN, |
| 743 | x_p95: P95_REL_MAX, |
| 744 | attn_cos: COSINE_MIN, |
| 745 | mlp_cos: COSINE_MIN, |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | #[test] |
| 750 | fn design_bound_is_cosine_0_99999_and_p95_rel_2e_3() { |
| 751 | assert_eq!(COSINE_MIN, 0.99999); |
| 752 | assert_eq!(P95_REL_MAX, 2e-3); |
| 753 | assert!(layer_meets_bound(&on_bound())); |
| 754 | } |
| 755 | |
| 756 | /// x_out, attention, and p95_rel all meet design 2.4. Only mlp_out cosine misses, |
| 757 | /// and it still clears the retired 0.9999 constant. |
| 758 | #[test] |
| 759 | fn mlp_cosine_under_the_design_bound_fails_the_layer() { |
| 760 | let mut w = on_bound(); |
| 761 | w.mlp_cos = 0.99998; |
| 762 | assert!(w.mlp_cos > 0.9999); |
| 763 | assert!(w.mlp_cos < COSINE_MIN); |
| 764 | assert!(!layer_meets_bound(&w)); |
| 765 | } |
| 766 | |
| 767 | #[test] |
| 768 | fn x_p95_over_2e_3_fails_while_cosines_hold() { |
| 769 | let mut w = on_bound(); |
| 770 | w.x_p95 = 2.1e-3; |
| 771 | assert!(w.x_p95 > P95_REL_MAX); |
| 772 | assert!(!layer_meets_bound(&w)); |
| 773 | } |
| 774 | } |