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 / own30b_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-30B check: Qwen3-30B-A3B on Omega against the CPU oracle (design section 4). |
| 17 | //! |
| 18 | //! own30b_check golden <checkpoint> <golden.json> [--new N] |
| 19 | //! CPU only: loads the f32/FP8 reference model (`load_qwen3_coder`, about 35 GB host), |
| 20 | //! runs greedy continuations of the 4 fixed prompts, writes tokens and top-2 margins. |
| 21 | //! own30b_check chip <checkpoint> <golden.json> <receipt-dir> [--new N] [--layers 0,23,47] |
| 22 | //! [--max-context 8192] [--prompts 1,2,3,4] [--force-memory] |
| 23 | //! [--paged-experts SLOTS [--manifest PATH] [--read-workers W] [--read-depth D]] |
| 24 | //! [--weights bf16|fp8-experts|fp8] |
| 25 | //! [--router auto|host|device] [--lm-head auto|dense|gemv] [--router-mutants 1,2,3,4] |
| 26 | //! [--prefill auto|gemv|gemm] [--prefill-routing host|device] [--prefill-chunk N] |
| 27 | //! [--gemm-mutants 1,2,3] [--long-prompt N] [--tokens-only] |
| 28 | //! [--whole-prompt] [--prefill-device-host] |
| 29 | //! Omega: loads the resident model, per-layer parity (attention replay + exact MoE oracle) |
| 30 | //! with the routing mutant and the chip-side window-skew mutant as negative controls, |
| 31 | //! whole-model greedy tokens against the golden file, decode tok/s and load time. |
| 32 | //! Writes <receipt-dir>/run.json and a plain text log; the shell seals SHA256SUMS. |
| 33 | //! |
| 34 | //! Memory: the chip load refuses to start with less than 70 GB available (another 30 GB model |
| 35 | //! may be running) unless --force-memory. |
| 36 | |
| 37 | use std::path::{Path, PathBuf}; |
| 38 | use std::time::Instant; |
| 39 | |
| 40 | use aien_inference_abi::qwen3_coder::{ |
| 41 | compute_logits, forward_token, load_qwen3_coder, Qwen3CoderState, |
| 42 | }; |
| 43 | use aien_inference_abi::qwen3_moe::load_qwen3_fp8_moe_layer; |
| 44 | use aien_inference_abi::qwen3_moe_omega::{ |
| 45 | current_rss_bytes, load_attention_layer_f32, peak_rss_bytes, replay_attention, replay_moe, |
| 46 | AttnPath, DevicePaths, GenerateParams, LmHead, OmegaModelUploader, PathChoice, Qwen3MoeConfig, |
| 47 | Qwen3MoeOmegaEngine, StepTiming, WeightFormat, |
| 48 | }; |
| 49 | use aien_inference_abi::qwen3_moe_omega::{dgraph, ribbon}; |
| 50 | use aien_inference_abi::tokenizer::ChatTokenizer as Tokenizer; |
| 51 | |
| 52 | const PROMPT_TEXTS: [(&str, &str); 4] = [ |
| 53 | ("p1-one-token", "Hello"), |
| 54 | ("p2-short", "What is the capital of France? Answer in one sentence."), |
| 55 | ( |
| 56 | "p3-medium", |
| 57 | "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. The design trades peak bandwidth for capacity: a large mixture-of-experts model fits in memory whole, and each generated token only touches the experts the router selects. 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. Small launches add up quickly when a layer needs many of them, so grouping work per layer matters more than raw arithmetic throughput. The practical outcome is that bandwidth per token, not compute, sets the speed of decoding, and that the fastest path keeps weights in the narrowest format the kernels can read directly.", |
| 58 | ), |
| 59 | ( |
| 60 | "p4-long", |
| 61 | "You are a careful engineering assistant. Read the log below and say, in plain words, what went wrong and what to check first.\n\n[run 1] loaded 48 layers in 212 s, resident 60.4 GB\n[run 1] prompt 23 tokens, prefill 1.9 s\n[run 1] decode 16 tokens, 58 ms/token\n[run 1] parity layer 0 cosine 0.99998 p95_rel 0.0021\n[run 1] parity layer 23 cosine 0.99997 p95_rel 0.0024\n[run 1] parity layer 47 cosine 0.99995 p95_rel 0.0031\n[run 2] loaded 48 layers in 208 s, resident 60.4 GB\n[run 2] prompt 256 tokens, prefill 15.1 s\n[run 2] decode 16 tokens, 61 ms/token\n[run 2] token 9 differs from golden (margin 0.0007)\n[run 3] loaded 48 layers in 215 s\n[run 3] prompt 700 tokens, prefill 41 s\n[run 3] decode 16 tokens, 66 ms/token\n[run 3] parity layer 23 cosine 0.99996\n[run 4] mutant control: routing shifted, layer 23 cosine 0.41 (caught)\n[run 4] mutant control: window skew 1 tile, layer 23 cosine 0.12 (caught)\n[run 5] kv pool resident, attention 1.1 ms/layer at 700 context\n[run 5] experts 0.61 ms/layer, lm_head 3.2 ms\n[run 5] host ops 1.4 ms/token\n[run 6] free memory before load 101 GB, after 39 GB\n[run 6] peak host rss 64.1 GB\n[run 7] seal on: unprepared kernel refused by name\n[run 7] seal off: same tokens\n[run 8] spin window 2000 us, launch floor 6 us\n[run 8] 913 launches per token, 14 ms launch tax\n[run 9] prompt 1 token, prefill 0.07 s\n[run 9] decode 16 tokens, 57 ms/token\n[run 10] golden tokens identical on p1, p2, p3; p4 diverges at 12 (margin 0.0003)\n\nThe log repeats the same measurements across several days; treat each run as independent. Mention the numbers that matter and nothing else.", |
| 62 | ), |
| 63 | ]; |
| 64 | |
| 65 | fn chatml(user: &str) -> String { |
| 66 | format!("<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n") |
| 67 | } |
| 68 | |
| 69 | fn prompts(tok: &Tokenizer) -> Vec<(String, Vec<u32>)> { |
| 70 | PROMPT_TEXTS |
| 71 | .iter() |
| 72 | .map(|(name, text)| { |
| 73 | let ids = if *name == "p1-one-token" { |
| 74 | tok.encode_with_special(text, false).expect("encode") |
| 75 | } else { |
| 76 | tok.encode_with_special(&chatml(text), false) |
| 77 | .expect("encode") |
| 78 | }; |
| 79 | (name.to_string(), ids) |
| 80 | }) |
| 81 | .collect() |
| 82 | } |
| 83 | |
| 84 | /// One greedy run from an empty engine at a given prefill chunk: tokens, the first step's logits |
| 85 | /// (captured by the sampler), and the prefill wall time and timing. |
| 86 | struct PromptRun { |
| 87 | tokens: Vec<u32>, |
| 88 | logits0: Vec<f32>, |
| 89 | prefill_ms: u64, |
| 90 | pt: StepTiming, |
| 91 | } |
| 92 | |
| 93 | fn run_prompt( |
| 94 | engine: &mut Qwen3MoeOmegaEngine, |
| 95 | ids: &[u32], |
| 96 | chunk: usize, |
| 97 | new_tokens: usize, |
| 98 | eos: &[u32], |
| 99 | ) -> Result<PromptRun, String> { |
| 100 | engine.reset(); |
| 101 | engine.prefill_chunk = chunk; |
| 102 | let mut tokens = Vec::new(); |
| 103 | let mut logits0: Vec<f32> = Vec::new(); |
| 104 | let o = engine.generate_with( |
| 105 | ids, |
| 106 | &GenerateParams::greedy(new_tokens, eos.to_vec()), |
| 107 | &mut |logits, step| { |
| 108 | if step == 0 { |
| 109 | logits0 = logits.to_vec(); |
| 110 | } |
| 111 | aien_inference_abi::tensor::sample_argmax(logits).0 |
| 112 | }, |
| 113 | &mut |t| { |
| 114 | tokens.push(t); |
| 115 | true |
| 116 | }, |
| 117 | )?; |
| 118 | Ok(PromptRun { |
| 119 | tokens, |
| 120 | logits0, |
| 121 | prefill_ms: o.prefill_ms, |
| 122 | pt: o.prefill_timing, |
| 123 | }) |
| 124 | } |
| 125 | |
| 126 | /// Cosine and largest absolute difference between two logits vectors. |
| 127 | fn logits_agreement(a: &[f32], b: &[f32]) -> (f64, f32) { |
| 128 | let s = aien_inference_abi::qwen3_moe::parity_stats(a, b); |
| 129 | let maxd = a |
| 130 | .iter() |
| 131 | .zip(b) |
| 132 | .map(|(x, y)| (x - y).abs()) |
| 133 | .fold(0.0f32, f32::max); |
| 134 | (s.cosine, maxd) |
| 135 | } |
| 136 | |
| 137 | fn prefill_line(head: &str, n_tokens: usize, r: &PromptRun) -> String { |
| 138 | let n = n_tokens as f64; |
| 139 | let pt = &r.pt; |
| 140 | format!( |
| 141 | "{head}, {n_tokens} tokens): {:.2}s = {:.1} ms/token; per token: attention {:.1} ms experts {:.1} ms (routing {:.2} ms, sort+swiglu+combine {:.2} ms) host {:.1} ms chip-reported {:.1} ms launches {:.1}; first tokens {:?}", |
| 142 | r.prefill_ms as f64 / 1000.0, |
| 143 | r.prefill_ms as f64 / n, |
| 144 | pt.attention_ns as f64 / 1e6 / n, |
| 145 | pt.experts_ns as f64 / 1e6 / n, |
| 146 | pt.route_ns as f64 / 1e6 / n, |
| 147 | pt.moe_host_ns as f64 / 1e6 / n, |
| 148 | pt.host_ns as f64 / 1e6 / n, |
| 149 | pt.chip_ns as f64 / 1e6 / n, |
| 150 | pt.launches as f64 / n, |
| 151 | r.tokens |
| 152 | ) |
| 153 | } |
| 154 | |
| 155 | /// A chat prompt of at least `min_tokens` tokens: numbered log blocks (each block differs) and a |
| 156 | /// final question. The tokenizer refuses more than 2048 tokens per call, so the prompt is encoded |
| 157 | /// piece by piece (each piece ends on a newline) and the ids are joined. |
| 158 | fn long_prompt_ids(tok: &Tokenizer, min_tokens: usize) -> Vec<u32> { |
| 159 | let enc = |t: &str| tok.encode_with_special(t, false).expect("encode"); |
| 160 | let mut ids = enc("<|im_start|>user\nYou are a careful engineering assistant. Read the log below and say, in plain words, which block number has the largest decode time.\n\n"); |
| 161 | let tail = enc("\nAnswer with the block number only.<|im_end|>\n<|im_start|>assistant\n"); |
| 162 | let mut b = 0usize; |
| 163 | while ids.len() + tail.len() < min_tokens { |
| 164 | ids.extend(enc(&format!( |
| 165 | "[block {b}] loaded 48 layers in {} s, resident {}.{} GB\n[block {b}] prompt {} tokens, prefill {}.{} s\n[block {b}] decode 16 tokens, {} ms/token\n[block {b}] parity layer {} cosine 0.9999{}\n", |
| 166 | 200 + (b * 7) % 23, |
| 167 | 58 + b % 5, |
| 168 | (b * 3) % 10, |
| 169 | 20 + (b * 37) % 700, |
| 170 | 1 + (b * 5) % 40, |
| 171 | (b * 7) % 10, |
| 172 | 50 + (b * 11) % 37, |
| 173 | (b * 5) % 48, |
| 174 | b % 10 |
| 175 | ))); |
| 176 | b += 1; |
| 177 | } |
| 178 | ids.extend(tail); |
| 179 | ids |
| 180 | } |
| 181 | |
| 182 | fn top2_margin(logits: &[f32]) -> (u32, f32) { |
| 183 | let (mut b0, mut v0, mut v1) = (0usize, f32::NEG_INFINITY, f32::NEG_INFINITY); |
| 184 | for (i, &v) in logits.iter().enumerate() { |
| 185 | if v > v0 { |
| 186 | v1 = v0; |
| 187 | v0 = v; |
| 188 | b0 = i; |
| 189 | } else if v > v1 { |
| 190 | v1 = v; |
| 191 | } |
| 192 | } |
| 193 | (b0 as u32, v0 - v1) |
| 194 | } |
| 195 | |
| 196 | fn mem_available_gb() -> f64 { |
| 197 | std::fs::read_to_string("/proc/meminfo") |
| 198 | .ok() |
| 199 | .and_then(|t| { |
| 200 | t.lines() |
| 201 | .find(|l| l.starts_with("MemAvailable:")) |
| 202 | .and_then(|l| l.split_whitespace().nth(1)) |
| 203 | .and_then(|v| v.parse::<f64>().ok()) |
| 204 | }) |
| 205 | .map(|kb| kb / 1024.0 / 1024.0) |
| 206 | .unwrap_or(0.0) |
| 207 | } |
| 208 | |
| 209 | struct Args { |
| 210 | mode: String, |
| 211 | checkpoint: PathBuf, |
| 212 | golden: PathBuf, |
| 213 | receipt: Option<PathBuf>, |
| 214 | new_tokens: usize, |
| 215 | layers: Vec<usize>, |
| 216 | max_context: usize, |
| 217 | prompt_ids: Vec<usize>, |
| 218 | force_memory: bool, |
| 219 | format: WeightFormat, |
| 220 | attn: AttnPath, |
| 221 | /// Chip-side decode attention mutant for the attention control (omega_gpu_decode_attn_api.h). |
| 222 | attn_mutant: i32, |
| 223 | /// Prompt tokens per prefill step for the TOKENS runs (None = the engine default). |
| 224 | prefill_chunk: Option<usize>, |
| 225 | /// Router and lm_head implementations (auto = device ones when linked). |
| 226 | paths: DevicePaths, |
| 227 | /// Device router mutants run as negative controls (omega_gpu_router_api.h: 1 RMSNorm without |
| 228 | /// the weight, 2 wrong mask, 3 wrong directory entry, 4 weights not normalised). |
| 229 | router_mutants: Vec<i32>, |
| 230 | /// Skip parity, controls and the prefill check: tokens against the golden and timing only. |
| 231 | tokens_only: bool, |
| 232 | /// Whole-prompt prefill (W-RC: the RC server default) and its device router/combine. |
| 233 | whole_prompt: bool, |
| 234 | wp_device_host: bool, |
| 235 | /// Batched prefill kernel: auto (GEMM when linked), gemv (the grouped GEMV) or gemm (required). |
| 236 | prefill: PathChoice, |
| 237 | /// Batched prefill routing: false = host (default), true = the device router per token. |
| 238 | prefill_device_routing: bool, |
| 239 | /// Prefill GEMM mutants run as negative controls through the real prefill path (omega_gpu_fp8gemm_api.h: |
| 240 | /// 1 scale dropped, 2 scale pointer never advances, 3 neighbour row's x). |
| 241 | gemm_mutants: Vec<i32>, |
| 242 | /// Also run a prompt of at least this many tokens: chunk 1 against the batched chunk, tokens and hidden state. |
| 243 | long_prompt: usize, |
| 244 | /// Expert Ribbon: page the experts into this many GPU slots (0 = all resident). |
| 245 | paged_slots: usize, |
| 246 | ribbon_manifest: PathBuf, |
| 247 | read_workers: usize, |
| 248 | read_depth: usize, |
| 249 | } |
| 250 | |
| 251 | fn parse_choice(v: &str, host_word: &str, flag: &str) -> PathChoice { |
| 252 | match v { |
| 253 | "auto" => PathChoice::Auto, |
| 254 | w if w == host_word => PathChoice::Host, |
| 255 | "device" | "gemv" => PathChoice::Device, |
| 256 | other => panic!("{flag} {other}: auto, {host_word} or device"), |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | fn parse_args() -> Args { |
| 261 | let mut it = std::env::args().skip(1); |
| 262 | let mode = it.next().unwrap_or_default(); |
| 263 | let mut pos: Vec<String> = Vec::new(); |
| 264 | let mut a = Args { |
| 265 | mode: mode.clone(), |
| 266 | checkpoint: PathBuf::new(), |
| 267 | golden: PathBuf::new(), |
| 268 | receipt: None, |
| 269 | new_tokens: 16, |
| 270 | layers: vec![0, 23, 47], |
| 271 | max_context: 8192, |
| 272 | prompt_ids: vec![1, 2, 3, 4], |
| 273 | force_memory: false, |
| 274 | format: WeightFormat::Bf16, |
| 275 | attn: AttnPath::Auto, |
| 276 | attn_mutant: 1, |
| 277 | prefill_chunk: None, |
| 278 | paths: DevicePaths::default(), |
| 279 | router_mutants: vec![1, 2, 3, 4], |
| 280 | tokens_only: false, |
| 281 | whole_prompt: false, |
| 282 | wp_device_host: false, |
| 283 | prefill: PathChoice::Auto, |
| 284 | prefill_device_routing: false, |
| 285 | gemm_mutants: vec![1, 2, 3], |
| 286 | long_prompt: 0, |
| 287 | paged_slots: 0, |
| 288 | ribbon_manifest: std::env::temp_dir().join("aien-ribbon-manifest.json"), |
| 289 | read_workers: 16, |
| 290 | read_depth: 32, |
| 291 | }; |
| 292 | while let Some(arg) = it.next() { |
| 293 | match arg.as_str() { |
| 294 | "--new" => a.new_tokens = it.next().expect("--new N").parse().expect("number"), |
| 295 | "--max-context" => { |
| 296 | a.max_context = it.next().expect("--max-context N").parse().expect("number") |
| 297 | } |
| 298 | "--layers" => { |
| 299 | a.layers = it |
| 300 | .next() |
| 301 | .expect("--layers a,b") |
| 302 | .split(',') |
| 303 | .map(|s| s.parse().expect("layer")) |
| 304 | .collect() |
| 305 | } |
| 306 | "--prompts" => { |
| 307 | a.prompt_ids = it |
| 308 | .next() |
| 309 | .expect("--prompts a,b") |
| 310 | .split(',') |
| 311 | .map(|s| s.parse().expect("prompt")) |
| 312 | .collect() |
| 313 | } |
| 314 | "--force-memory" => a.force_memory = true, |
| 315 | "--weights" => { |
| 316 | a.format = match it.next().expect("--weights bf16|fp8-experts|fp8").as_str() { |
| 317 | "bf16" => WeightFormat::Bf16, |
| 318 | "fp8-experts" => WeightFormat::Fp8Experts, |
| 319 | "fp8" => WeightFormat::Fp8All, |
| 320 | other => panic!("--weights {other}: bf16, fp8-experts or fp8"), |
| 321 | } |
| 322 | } |
| 323 | "--attn" => { |
| 324 | a.attn = match it.next().expect("--attn auto|split|fused").as_str() { |
| 325 | "auto" => AttnPath::Auto, |
| 326 | "split" => AttnPath::Split, |
| 327 | "fused" => AttnPath::Fused, |
| 328 | other => panic!("--attn {other}: auto, split or fused"), |
| 329 | } |
| 330 | } |
| 331 | "--attn-mutant" => { |
| 332 | a.attn_mutant = it.next().expect("--attn-mutant N").parse().expect("number") |
| 333 | } |
| 334 | "--prefill-chunk" => { |
| 335 | a.prefill_chunk = Some( |
| 336 | it.next() |
| 337 | .expect("--prefill-chunk N") |
| 338 | .parse() |
| 339 | .expect("number"), |
| 340 | ) |
| 341 | } |
| 342 | "--router" => { |
| 343 | a.paths.router = parse_choice( |
| 344 | &it.next().expect("--router auto|host|device"), |
| 345 | "host", |
| 346 | "--router", |
| 347 | ) |
| 348 | } |
| 349 | "--lm-head" => { |
| 350 | a.paths.lm_head = parse_choice( |
| 351 | &it.next().expect("--lm-head auto|dense|gemv"), |
| 352 | "dense", |
| 353 | "--lm-head", |
| 354 | ) |
| 355 | } |
| 356 | "--tokens-only" => a.tokens_only = true, |
| 357 | "--paged-experts" => { |
| 358 | a.paged_slots = it |
| 359 | .next() |
| 360 | .expect("--paged-experts SLOTS") |
| 361 | .parse() |
| 362 | .expect("number") |
| 363 | } |
| 364 | "--manifest" => a.ribbon_manifest = PathBuf::from(it.next().expect("--manifest PATH")), |
| 365 | "--read-workers" => { |
| 366 | a.read_workers = it |
| 367 | .next() |
| 368 | .expect("--read-workers N") |
| 369 | .parse() |
| 370 | .expect("number") |
| 371 | } |
| 372 | "--read-depth" => { |
| 373 | a.read_depth = it.next().expect("--read-depth N").parse().expect("number") |
| 374 | } |
| 375 | "--whole-prompt" => a.whole_prompt = true, |
| 376 | "--prefill-device-host" => a.wp_device_host = true, |
| 377 | "--prefill" => { |
| 378 | a.prefill = parse_choice( |
| 379 | &it.next().expect("--prefill auto|gemv|gemm"), |
| 380 | "gemv", |
| 381 | "--prefill", |
| 382 | ) |
| 383 | } |
| 384 | "--prefill-routing" => { |
| 385 | a.prefill_device_routing = |
| 386 | match it.next().expect("--prefill-routing host|device").as_str() { |
| 387 | "host" => false, |
| 388 | "device" => true, |
| 389 | other => panic!("--prefill-routing {other}: host or device"), |
| 390 | } |
| 391 | } |
| 392 | "--gemm-mutants" => { |
| 393 | let v = it.next().expect("--gemm-mutants a,b (empty for none)"); |
| 394 | a.gemm_mutants = v |
| 395 | .split(',') |
| 396 | .filter(|s| !s.is_empty()) |
| 397 | .map(|s| s.parse().expect("mutant")) |
| 398 | .collect(); |
| 399 | } |
| 400 | "--long-prompt" => { |
| 401 | a.long_prompt = it.next().expect("--long-prompt N").parse().expect("number") |
| 402 | } |
| 403 | "--router-mutants" => { |
| 404 | let v = it.next().expect("--router-mutants a,b (empty for none)"); |
| 405 | a.router_mutants = v |
| 406 | .split(',') |
| 407 | .filter(|s| !s.is_empty()) |
| 408 | .map(|s| s.parse().expect("mutant")) |
| 409 | .collect(); |
| 410 | } |
| 411 | other => pos.push(other.to_string()), |
| 412 | } |
| 413 | } |
| 414 | if mode != "golden" && mode != "chip" || pos.len() < 2 { |
| 415 | eprintln!("usage: own30b_check golden <checkpoint> <golden.json> | chip <checkpoint> <golden.json> <receipt-dir>"); |
| 416 | std::process::exit(2); |
| 417 | } |
| 418 | a.checkpoint = PathBuf::from(&pos[0]); |
| 419 | a.golden = PathBuf::from(&pos[1]); |
| 420 | a.receipt = pos.get(2).map(PathBuf::from); |
| 421 | a |
| 422 | } |
| 423 | |
| 424 | fn golden(a: &Args) { |
| 425 | let tok = Tokenizer::from_file(a.checkpoint.join("tokenizer.json")).expect("tokenizer"); |
| 426 | let config = Qwen3MoeConfig::from_checkpoint(&a.checkpoint).expect("config"); |
| 427 | let t0 = Instant::now(); |
| 428 | let weights = load_qwen3_coder(&a.checkpoint).expect("load CPU reference"); |
| 429 | eprintln!( |
| 430 | "cpu reference loaded in {:.0}s, rss {:.1} GB", |
| 431 | t0.elapsed().as_secs_f64(), |
| 432 | current_rss_bytes().unwrap_or(0) as f64 / 1e9 |
| 433 | ); |
| 434 | let mut out = Vec::new(); |
| 435 | for (idx, (name, ids)) in prompts(&tok).into_iter().enumerate() { |
| 436 | if !a.prompt_ids.contains(&(idx + 1)) { |
| 437 | continue; |
| 438 | } |
| 439 | let t1 = Instant::now(); |
| 440 | let mut state = Qwen3CoderState::new(); |
| 441 | let mut hidden = Vec::new(); |
| 442 | for (pos, &t) in ids.iter().enumerate() { |
| 443 | hidden = forward_token(&weights, t, pos, &mut state); |
| 444 | } |
| 445 | let mut tokens = Vec::new(); |
| 446 | let mut margins = Vec::new(); |
| 447 | for pos in (ids.len()..).take(a.new_tokens) { |
| 448 | let logits = compute_logits(&weights, &hidden); |
| 449 | let (next, margin) = top2_margin(&logits); |
| 450 | tokens.push(next); |
| 451 | margins.push(margin); |
| 452 | if config.eos_token_ids.contains(&next) { |
| 453 | break; |
| 454 | } |
| 455 | hidden = forward_token(&weights, next, pos, &mut state); |
| 456 | } |
| 457 | let secs = t1.elapsed().as_secs_f64(); |
| 458 | let text = tok.decode(&tokens).unwrap_or_default(); |
| 459 | eprintln!( |
| 460 | "{name}: {} prompt tokens, {} new in {secs:.0}s: {text:?}", |
| 461 | ids.len(), |
| 462 | tokens.len() |
| 463 | ); |
| 464 | out.push(serde_json::json!({ |
| 465 | "name": name, "prompt_tokens": ids, "golden": tokens, "margins": margins, |
| 466 | "text": text, "cpu_seconds": secs, |
| 467 | })); |
| 468 | } |
| 469 | let doc = serde_json::json!({ |
| 470 | "checkpoint": a.checkpoint.display().to_string(), "max_new": a.new_tokens, |
| 471 | "oracle": "qwen3_coder::forward_token (f32 attention, exact FP8 MoE) + compute_logits, greedy", |
| 472 | "prompts": out, |
| 473 | }); |
| 474 | std::fs::write(&a.golden, serde_json::to_string_pretty(&doc).unwrap()).expect("write golden"); |
| 475 | eprintln!("wrote {}", a.golden.display()); |
| 476 | } |
| 477 | |
| 478 | fn chip(a: &Args) { |
| 479 | let receipt = a.receipt.clone().expect("receipt dir"); |
| 480 | std::fs::create_dir_all(&receipt).expect("receipt dir"); |
| 481 | let mut log: Vec<String> = Vec::new(); |
| 482 | let mut say = |s: String| { |
| 483 | println!("{s}"); |
| 484 | log.push(s); |
| 485 | }; |
| 486 | let avail = mem_available_gb(); |
| 487 | say(format!("mem available before load: {avail:.1} GB")); |
| 488 | let config0 = Qwen3MoeConfig::from_checkpoint(&a.checkpoint).expect("config.json"); |
| 489 | // Paged experts: the slot pools (exact) plus a fixed 6 GB for attention, lm_head, KV and scratch. |
| 490 | let (h0, i0) = (config0.hidden, config0.moe_intermediate); |
| 491 | let pool_bytes = a.paged_slots * (3 * h0 * i0 + 4 * 3 * (h0 / 128) * (i0 / 128)); |
| 492 | let need_gb = if a.paged_slots > 0 { |
| 493 | pool_bytes as f64 / 1e9 + 6.0 |
| 494 | } else { |
| 495 | 70.0 |
| 496 | }; |
| 497 | if a.paged_slots > 0 { |
| 498 | say(format!( |
| 499 | "RIBBON: {} slots, pools {:.2} GB; memory gate {need_gb:.1} GB", |
| 500 | a.paged_slots, |
| 501 | pool_bytes as f64 / 1e9 |
| 502 | )); |
| 503 | } |
| 504 | if avail < need_gb && !a.force_memory { |
| 505 | say(format!("REFUSED: less than {need_gb:.1} GB available (another model may be loaded); --force-memory to override")); |
| 506 | std::process::exit(3); |
| 507 | } |
| 508 | let golden: serde_json::Value = |
| 509 | serde_json::from_slice(&std::fs::read(&a.golden).expect("golden file")) |
| 510 | .expect("golden json"); |
| 511 | let tok = Tokenizer::from_file(a.checkpoint.join("tokenizer.json")).expect("tokenizer"); |
| 512 | // Spin window: honour AIEN_OMEGA_SPIN_US (one knob, one variable per run); unset keeps |
| 513 | // whatever the session default is, and the value actually in force is printed below. |
| 514 | if let Some(us) = |
| 515 | aien_omega_gpu::parse_spin_us(std::env::var(aien_omega_gpu::SPIN_US_ENV).ok().as_deref()) |
| 516 | .expect("spin env") |
| 517 | { |
| 518 | aien_omega_gpu::set_spin_us(us).expect("set spin window"); |
| 519 | } |
| 520 | let config = Qwen3MoeConfig::from_checkpoint(&a.checkpoint).expect("config"); |
| 521 | say(format!( |
| 522 | "engine native={} window_api={} fp8_api={} dattn_api={} weights={:?} attn={:?} spin_us={:?} cta_budget={:?}", |
| 523 | aien_omega_gpu::is_native(), |
| 524 | OmegaModelUploader::uses_window_api(), |
| 525 | OmegaModelUploader::uses_fp8_api(), |
| 526 | OmegaModelUploader::uses_dattn_api(), |
| 527 | a.format, |
| 528 | a.attn, |
| 529 | aien_omega_gpu::spin_us(), |
| 530 | aien_omega_gpu::cta_budget() |
| 531 | )); |
| 532 | |
| 533 | // ---- load ---- |
| 534 | let t0 = Instant::now(); |
| 535 | let mut n = 0usize; |
| 536 | let paged = (a.paged_slots > 0).then(|| { |
| 537 | ribbon::open_omega( |
| 538 | &a.checkpoint, |
| 539 | h0, |
| 540 | i0, |
| 541 | &ribbon::RibbonOptions { |
| 542 | manifest: a.ribbon_manifest.clone(), |
| 543 | slots: a.paged_slots, |
| 544 | read: aien_heartbeat::ReadConfig { |
| 545 | workers: a.read_workers, |
| 546 | queue_depth: a.read_depth, |
| 547 | }, |
| 548 | direct: true, |
| 549 | read_deadline: std::time::Duration::from_secs(30), |
| 550 | }, |
| 551 | &mut |s| eprintln!(" {s}"), |
| 552 | ) |
| 553 | .expect("expert ribbon") |
| 554 | }); |
| 555 | let (mut engine, report) = Qwen3MoeOmegaEngine::load_omega_experts( |
| 556 | &a.checkpoint, |
| 557 | a.max_context, |
| 558 | a.format, |
| 559 | a.attn, |
| 560 | a.paths, |
| 561 | paged.clone(), |
| 562 | &mut |s| { |
| 563 | n += 1; |
| 564 | if n.is_multiple_of(20) || s.starts_with("kv") || s == "lm_head" { |
| 565 | eprintln!(" [{:.0}s] {s}", t0.elapsed().as_secs_f64()); |
| 566 | } |
| 567 | }, |
| 568 | ) |
| 569 | .expect("load on Omega"); |
| 570 | match a.prefill { |
| 571 | PathChoice::Host => engine.prefill_gemm = false, |
| 572 | PathChoice::Device => assert!( |
| 573 | engine.prefill_gemm, |
| 574 | "--prefill gemm: the prefill GEMM is not linked or not offered for every projection" |
| 575 | ), |
| 576 | PathChoice::Auto => {} |
| 577 | } |
| 578 | engine.prefill_device_routing = a.prefill_device_routing; |
| 579 | if !engine.prefill_gemm { |
| 580 | engine.prefill_chunk = aien_inference_abi::qwen3_moe_omega::PREFILL_CHUNK; |
| 581 | } |
| 582 | if let Some(chunk) = a.prefill_chunk { |
| 583 | engine.prefill_chunk = chunk; |
| 584 | } |
| 585 | say(format!( |
| 586 | "prefill path {} routing {} (gemm_api={})", |
| 587 | if engine.prefill_gemm { "gemm" } else { "gemv" }, |
| 588 | if engine.prefill_device_routing { |
| 589 | "device" |
| 590 | } else { |
| 591 | "host" |
| 592 | }, |
| 593 | aien_omega_fp8::has_gemm() |
| 594 | )); |
| 595 | say(format!( |
| 596 | "attention path {} prefill_chunk {} batched_prefill_possible {}", |
| 597 | engine.attention_path(), |
| 598 | engine.prefill_chunk, |
| 599 | engine.batched_prefill_possible() |
| 600 | )); |
| 601 | let router_path = if engine.device_routing { |
| 602 | "device" |
| 603 | } else { |
| 604 | "host" |
| 605 | }; |
| 606 | let lm_head_path = if matches!(engine.weights().lm_head, LmHead::Gemv(_)) { |
| 607 | "gemv" |
| 608 | } else { |
| 609 | "dense" |
| 610 | }; |
| 611 | say(format!( |
| 612 | "router path {router_path} lm_head path {lm_head_path} (router_api={} bf16_api={})", |
| 613 | OmegaModelUploader::uses_router_api(), |
| 614 | OmegaModelUploader::uses_bf16_api() |
| 615 | )); |
| 616 | // One command list per decode token (OWN30B_DECODE_GRAPH=1): built now so a load that cannot |
| 617 | // run it is refused before any generation, never run on the old path in its place. |
| 618 | if dgraph::stamps_requested() && !engine.decode_graph_on() { |
| 619 | say(format!( |
| 620 | "REFUSED: {}=1 measures the one-list decode; it needs {}=1 as well", |
| 621 | dgraph::STAMPS_ENV, |
| 622 | dgraph::ENV |
| 623 | )); |
| 624 | std::process::exit(4); |
| 625 | } |
| 626 | if engine.decode_graph_on() { |
| 627 | if let Err(e) = engine.prepare_decode_graph() { |
| 628 | say(format!("REFUSED: {e}")); |
| 629 | std::process::exit(4); |
| 630 | } |
| 631 | } |
| 632 | say(format!( |
| 633 | "decode graph {} (dgraph_api={}, {}=1 to turn on) mutant {}", |
| 634 | if engine.decode_graph_on() { |
| 635 | "ON" |
| 636 | } else { |
| 637 | "OFF" |
| 638 | }, |
| 639 | aien_omega_dgraph::is_native(), |
| 640 | aien_inference_abi::qwen3_moe_omega::dgraph::ENV, |
| 641 | engine.decode_graph_mutant() |
| 642 | )); |
| 643 | // Whole-prompt prefill (W-RC): the release-candidate server turns both on. The per-layer |
| 644 | // parity replays set trace layers, which the whole-prompt path declines (chunked there). |
| 645 | if a.whole_prompt { |
| 646 | if let Err(e) = engine.set_whole_prompt(true) { |
| 647 | say(format!("REFUSED: whole-prompt prefill: {e}")); |
| 648 | std::process::exit(4); |
| 649 | } |
| 650 | if a.wp_device_host { |
| 651 | if let Err(e) = engine.set_whole_prompt_device_host(true) { |
| 652 | say(format!("REFUSED: whole-prompt device router/combine: {e}")); |
| 653 | std::process::exit(4); |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | say(format!( |
| 658 | "whole-prompt prefill {} device router/combine {}", |
| 659 | if engine.whole_prompt_on() { |
| 660 | "ON" |
| 661 | } else { |
| 662 | "OFF" |
| 663 | }, |
| 664 | if engine.whole_prompt_device_host_on() { |
| 665 | "ON" |
| 666 | } else { |
| 667 | "OFF" |
| 668 | } |
| 669 | )); |
| 670 | let peak = report.peak_rss_bytes.unwrap_or(0) as f64 / 1e9; |
| 671 | say(format!( |
| 672 | "LOAD: {:.1}s resident {:.2} GB host {:.2} GB peak_rss {:.2} GB (before {:.2} GB) kv_resident={} mem_available_after {:.1} GB", |
| 673 | report.seconds, |
| 674 | report.resident_bytes as f64 / 1e9, |
| 675 | report.host_bytes as f64 / 1e9, |
| 676 | peak, |
| 677 | report.peak_rss_before_bytes.unwrap_or(0) as f64 / 1e9, |
| 678 | engine.kv_resident(), |
| 679 | mem_available_gb() |
| 680 | )); |
| 681 | // Transient budget: whatever the resident mapping counts, the extra over resident + host must |
| 682 | // stay within one layer's transients plus slack (design: peak near the 60 GB resident size). |
| 683 | let transient = peak - (report.resident_bytes + report.host_bytes) as f64 / 1e9; |
| 684 | say(format!( |
| 685 | "LOAD peak over resident+host: {transient:.2} GB (budget 6 GB) -> {}", |
| 686 | if transient <= 6.0 { "PASS" } else { "FAIL" } |
| 687 | )); |
| 688 | |
| 689 | let ps = prompts(&tok); |
| 690 | let mut results = Vec::new(); |
| 691 | |
| 692 | let mut parity_json = Vec::new(); |
| 693 | let mut parity_pass = true; |
| 694 | let mut controls = Vec::new(); |
| 695 | let mut tokens_pass_prefill = true; |
| 696 | // --tokens-only skips parity, controls and the prefill check (speed and token runs only). |
| 697 | if !a.tokens_only { |
| 698 | // ---- layer parity on the short prompt (prompt 2), chip traces replayed on the host ---- |
| 699 | let (pname, pids) = &ps[1]; |
| 700 | engine.trace_layers = a.layers.clone(); |
| 701 | engine.reset(); |
| 702 | for &t in pids { |
| 703 | engine.step(t).expect("step"); |
| 704 | } |
| 705 | let traces = std::mem::take(&mut engine.traces); |
| 706 | for &l in &a.layers { |
| 707 | let lt: Vec<_> = traces.iter().filter(|t| t.layer == l).cloned().collect(); |
| 708 | let attn = |
| 709 | load_attention_layer_f32(&a.checkpoint, &config, l).expect("attention weights"); |
| 710 | let host = replay_attention(&config, &attn, <); |
| 711 | let capsule = load_qwen3_fp8_moe_layer(&a.checkpoint, l).expect("capsule"); |
| 712 | let mut worst_attn = 1.0f64; |
| 713 | let mut worst_moe = 1.0f64; |
| 714 | let mut worst_p95 = 0.0f32; |
| 715 | let mut routing_ok = true; |
| 716 | let mut worst_wt = 0.0f32; |
| 717 | let mut worst_xprime = 0.0f32; |
| 718 | for (t, h) in lt.iter().zip(&host) { |
| 719 | // The device router's own x' against the host RMSNorm of the same residual row. |
| 720 | if !t.post_device.is_empty() { |
| 721 | worst_xprime = t |
| 722 | .post_device |
| 723 | .iter() |
| 724 | .zip(&t.post) |
| 725 | .map(|(d, p)| (d - p).abs() / (1.0 + p.abs())) |
| 726 | .fold(worst_xprime, f32::max); |
| 727 | } |
| 728 | let s = aien_inference_abi::qwen3_moe::parity_stats(&t.attn_proj, h); |
| 729 | worst_attn = worst_attn.min(s.cosine); |
| 730 | let m = replay_moe(&capsule, t, config.top_k); |
| 731 | worst_moe = worst_moe.min(m.stats.cosine); |
| 732 | worst_p95 = worst_p95.max(m.stats.p95_rel); |
| 733 | routing_ok &= m.routing_agrees; |
| 734 | worst_wt = worst_wt.max(m.max_weight_err); |
| 735 | } |
| 736 | let pass = worst_attn >= 0.999 |
| 737 | && worst_moe >= 0.999 |
| 738 | && routing_ok |
| 739 | && worst_wt <= 1e-4 |
| 740 | && worst_xprime <= 1e-4; |
| 741 | parity_pass &= pass; |
| 742 | say(format!( |
| 743 | "PARITY layer {l} over {} positions ({pname}): attention cosine(min) {worst_attn:.6} moe cosine(min) {worst_moe:.6} moe p95_rel(max) {worst_p95:.4} routing_agrees={routing_ok} routing weights err(max) {worst_wt:.2e} router x' rel(max) {worst_xprime:.2e} -> {}", |
| 744 | lt.len(), |
| 745 | if pass { "PASS" } else { "FAIL" } |
| 746 | )); |
| 747 | parity_json.push(serde_json::json!({"layer": l, "positions": lt.len(), "attn_cosine_min": worst_attn, "moe_cosine_min": worst_moe, "moe_p95_rel_max": worst_p95, "routing_agrees": routing_ok, "routing_weight_err_max": worst_wt, "router_xprime_rel_max": worst_xprime, "pass": pass})); |
| 748 | } |
| 749 | // Negative controls on the first traced layer: host routing mutant, then the chip-side mutant |
| 750 | // of the expert kernel in use (bf16: window skew of one tile; FP8: scales dropped, kernel |
| 751 | // mutant 1 of omega_gpu_fp8_api.h). |
| 752 | let l0 = a.layers[0]; |
| 753 | let capsule = load_qwen3_fp8_moe_layer(&a.checkpoint, l0).expect("capsule"); |
| 754 | let fp8 = a.format.fp8_experts(); |
| 755 | let chip_control = if fp8 { |
| 756 | "fp8-scales-dropped" |
| 757 | } else { |
| 758 | "window-skew-1-tile" |
| 759 | }; |
| 760 | for (name, set) in [("routing-mutant", 0), (chip_control, 1)] { |
| 761 | engine.reset(); |
| 762 | engine.trace_layers = vec![l0]; |
| 763 | engine.routing_mutant = set == 0; |
| 764 | if set == 1 && fp8 { |
| 765 | aien_omega_fp8::test_set_mutant(1); |
| 766 | } else if set == 1 { |
| 767 | aien_omega_moe::test_set_window_skew(1); |
| 768 | } |
| 769 | let stepped: Result<Vec<_>, _> = pids[..pids.len().min(4)] |
| 770 | .iter() |
| 771 | .map(|&t| engine.step(t)) |
| 772 | .collect(); |
| 773 | aien_omega_fp8::test_set_mutant(0); |
| 774 | aien_omega_moe::test_set_window_skew(0); |
| 775 | engine.routing_mutant = false; |
| 776 | if let Err(e) = stepped { |
| 777 | // A mutant kernel the chip refuses (poison survived) is also caught, by name. |
| 778 | say(format!( |
| 779 | "CONTROL {name}: layer {l0} step refused: {e} -> CAUGHT (refused)" |
| 780 | )); |
| 781 | controls.push(serde_json::json!({"control": name, "refused": e, "caught": true})); |
| 782 | engine.traces.clear(); |
| 783 | continue; |
| 784 | } |
| 785 | let worst = engine |
| 786 | .traces |
| 787 | .iter() |
| 788 | .map(|t| replay_moe(&capsule, t, config.top_k).stats.cosine) |
| 789 | .fold(1.0f64, f64::min); |
| 790 | let not_applicable = set == 1 && !fp8 && !OmegaModelUploader::uses_window_api(); |
| 791 | let caught = worst < 0.99 || not_applicable; |
| 792 | let note = if not_applicable { |
| 793 | " (window API not linked: control not applicable)" |
| 794 | } else { |
| 795 | "" |
| 796 | }; |
| 797 | say(format!( |
| 798 | "CONTROL {name}: layer {l0} moe cosine(min) {worst:.4} -> {}{note}", |
| 799 | if caught { |
| 800 | "CAUGHT" |
| 801 | } else { |
| 802 | "NOT CAUGHT (FAIL)" |
| 803 | } |
| 804 | )); |
| 805 | controls.push( |
| 806 | serde_json::json!({"control": name, "moe_cosine_min": worst, "caught": caught}), |
| 807 | ); |
| 808 | parity_pass &= caught; |
| 809 | engine.traces.clear(); |
| 810 | } |
| 811 | // Third control on the fused path: the chip-side decode attention mutant (default 1 = no |
| 812 | // RoPE on q and k; omega_gpu_decode_attn_api.h) over the parity prompt; the host attention |
| 813 | // replay of the first traced layer must then disagree. |
| 814 | if engine.attention_path() == "fused" { |
| 815 | let name = format!("attention-mutant-{}", a.attn_mutant); |
| 816 | engine.reset(); |
| 817 | engine.trace_layers = vec![l0]; |
| 818 | aien_omega_dattn::test_set_mutant(a.attn_mutant); |
| 819 | let stepped: Result<Vec<_>, _> = pids.iter().map(|&t| engine.step(t)).collect(); |
| 820 | aien_omega_dattn::test_set_mutant(0); |
| 821 | match stepped { |
| 822 | Err(e) => { |
| 823 | say(format!( |
| 824 | "CONTROL {name}: layer {l0} step refused: {e} -> CAUGHT (refused)" |
| 825 | )); |
| 826 | controls |
| 827 | .push(serde_json::json!({"control": name, "refused": e, "caught": true})); |
| 828 | } |
| 829 | Ok(_) => { |
| 830 | let attn = load_attention_layer_f32(&a.checkpoint, &config, l0) |
| 831 | .expect("attention weights"); |
| 832 | let host = replay_attention(&config, &attn, &engine.traces); |
| 833 | let worst = engine |
| 834 | .traces |
| 835 | .iter() |
| 836 | .zip(&host) |
| 837 | .map(|(t, h)| { |
| 838 | aien_inference_abi::qwen3_moe::parity_stats(&t.attn_proj, h).cosine |
| 839 | }) |
| 840 | .fold(1.0f64, f64::min); |
| 841 | let caught = worst < 0.99; |
| 842 | say(format!( |
| 843 | "CONTROL {name}: layer {l0} attention cosine(min) {worst:.4} over {} positions -> {}", |
| 844 | engine.traces.len(), |
| 845 | if caught { "CAUGHT" } else { "NOT CAUGHT (FAIL)" } |
| 846 | )); |
| 847 | controls.push(serde_json::json!({"control": name, "attn_cosine_min": worst, "caught": caught})); |
| 848 | parity_pass &= caught; |
| 849 | } |
| 850 | } |
| 851 | engine.traces.clear(); |
| 852 | } |
| 853 | // Router controls on the device path: each deliberately wrong router kernel (omega_gpu_router_api.h) |
| 854 | // over the parity prompt must make the first traced layer disagree with the host oracle: the |
| 855 | // oracle input is the host's own RMSNorm of the same residual row, the chip's choice and MoE |
| 856 | // output come from the wrong router. |
| 857 | if engine.device_routing { |
| 858 | for &m in &a.router_mutants { |
| 859 | let name = format!("router-mutant-{m}"); |
| 860 | engine.reset(); |
| 861 | engine.trace_layers = vec![l0]; |
| 862 | aien_omega_router::test_set_mutant(m); |
| 863 | let stepped: Result<Vec<_>, _> = pids[..pids.len().min(4)] |
| 864 | .iter() |
| 865 | .map(|&t| engine.step(t)) |
| 866 | .collect(); |
| 867 | aien_omega_router::test_set_mutant(0); |
| 868 | match stepped { |
| 869 | Err(e) => { |
| 870 | say(format!( |
| 871 | "CONTROL {name}: layer {l0} step refused: {e} -> CAUGHT (refused)" |
| 872 | )); |
| 873 | controls.push( |
| 874 | serde_json::json!({"control": name, "refused": e, "caught": true}), |
| 875 | ); |
| 876 | } |
| 877 | Ok(_) => { |
| 878 | let mut worst = 1.0f64; |
| 879 | let mut routing_ok = true; |
| 880 | let mut xprime = 0.0f32; |
| 881 | let mut wt_err = 0.0f32; |
| 882 | for t in &engine.traces { |
| 883 | let r = replay_moe(&capsule, t, config.top_k); |
| 884 | worst = worst.min(r.stats.cosine); |
| 885 | routing_ok &= r.routing_agrees; |
| 886 | wt_err = wt_err.max(r.max_weight_err); |
| 887 | xprime = t |
| 888 | .post_device |
| 889 | .iter() |
| 890 | .zip(&t.post) |
| 891 | .map(|(d, p)| (d - p).abs() / (1.0 + p.abs())) |
| 892 | .fold(xprime, f32::max); |
| 893 | } |
| 894 | let caught = worst < 0.99 || !routing_ok || wt_err > 1e-3 || xprime > 1e-4; |
| 895 | say(format!( |
| 896 | "CONTROL {name}: layer {l0} moe cosine(min) {worst:.4} routing_agrees={routing_ok} routing weights err(max) {wt_err:.2e} router x' rel(max) {xprime:.2e} over {} positions -> {}", |
| 897 | engine.traces.len(), |
| 898 | if caught { "CAUGHT" } else { "NOT CAUGHT (FAIL)" } |
| 899 | )); |
| 900 | controls.push(serde_json::json!({"control": name, "moe_cosine_min": worst, "routing_agrees": routing_ok, "routing_weight_err_max": wt_err, "router_xprime_rel_max": xprime, "caught": caught})); |
| 901 | parity_pass &= caught; |
| 902 | } |
| 903 | } |
| 904 | engine.traces.clear(); |
| 905 | } |
| 906 | } |
| 907 | engine.trace_layers.clear(); |
| 908 | } |
| 909 | |
| 910 | // ---- batched prefill against token-at-a-time on the 204-token prompt: same logits, same tokens ---- |
| 911 | let mut prefill_json = serde_json::Value::Null; |
| 912 | if !a.tokens_only && engine.batched_prefill_possible() && engine.prefill_chunk > 1 { |
| 913 | let (pname, pids) = &ps[2]; |
| 914 | let chunk = engine.prefill_chunk; |
| 915 | let mut outs = Vec::new(); |
| 916 | for c in [1usize, chunk] { |
| 917 | let r = run_prompt(&mut engine, pids, c, 8, &config.eos_token_ids).expect("generate"); |
| 918 | say(prefill_line( |
| 919 | &format!("PREFILL chunk {c} ({pname}"), |
| 920 | pids.len(), |
| 921 | &r, |
| 922 | )); |
| 923 | outs.push(r); |
| 924 | } |
| 925 | engine.prefill_chunk = chunk; |
| 926 | let same = outs[0].tokens == outs[1].tokens; |
| 927 | let (cos, maxd) = logits_agreement(&outs[1].logits0, &outs[0].logits0); |
| 928 | let ok = same && cos > 0.99999; |
| 929 | say(format!( |
| 930 | "PREFILL chunk {chunk} vs 1: tokens {} ; first-step logits cosine {cos:.7} max abs diff {maxd:.2e} ; {:.1} -> {:.1} ms/token -> {}", |
| 931 | if same { "IDENTICAL" } else { "DIFFER (FAIL)" }, |
| 932 | outs[0].prefill_ms as f64 / pids.len() as f64, |
| 933 | outs[1].prefill_ms as f64 / pids.len() as f64, |
| 934 | if ok { "PASS" } else { "FAIL" } |
| 935 | )); |
| 936 | tokens_pass_prefill = ok; |
| 937 | prefill_json = serde_json::json!({"prompt": pname, "prompt_tokens": pids.len(), "chunk": chunk, |
| 938 | "prefill_ms_chunk1": outs[0].prefill_ms, "prefill_ms_chunk": outs[1].prefill_ms, |
| 939 | "launches_per_token_chunk1": outs[0].pt.launches as f64 / pids.len() as f64, "launches_per_token_chunk": outs[1].pt.launches as f64 / pids.len() as f64, |
| 940 | "tokens_identical": same, "logits_cosine": cos, "logits_max_abs_diff": maxd}); |
| 941 | } |
| 942 | |
| 943 | // ---- prefill GEMM negative controls through the real batched path ---- |
| 944 | // Each deliberately wrong GEMM kernel (omega_gpu_fp8gemm_api.h) runs a whole chunked prefill; the |
| 945 | // first-step logits must then disagree with the clean chunked prefill of the same prompt. |
| 946 | let mut gemm_controls = Vec::new(); |
| 947 | if !a.tokens_only |
| 948 | && engine.prefill_gemm |
| 949 | && engine.batched_prefill_possible() |
| 950 | && !a.gemm_mutants.is_empty() |
| 951 | { |
| 952 | let (pname, pids) = &ps[2]; |
| 953 | let ids = &pids[..pids.len().min(80)]; |
| 954 | let chunk = engine.prefill_chunk.max(2); |
| 955 | let clean = run_prompt(&mut engine, ids, chunk, 1, &config.eos_token_ids) |
| 956 | .expect("clean gemm prefill"); |
| 957 | for &m in &a.gemm_mutants { |
| 958 | let name = format!("gemm-mutant-{m}"); |
| 959 | aien_omega_fp8::gemm_test_set_mutant(m); |
| 960 | let r = run_prompt(&mut engine, ids, chunk, 1, &config.eos_token_ids); |
| 961 | aien_omega_fp8::gemm_test_set_mutant(0); |
| 962 | match r { |
| 963 | Err(e) => { |
| 964 | say(format!("CONTROL {name}: prefill of {} tokens ({pname}) refused: {e} -> CAUGHT (refused)", ids.len())); |
| 965 | gemm_controls |
| 966 | .push(serde_json::json!({"control": name, "refused": e, "caught": true})); |
| 967 | } |
| 968 | Ok(r) => { |
| 969 | let (cos, maxd) = logits_agreement(&r.logits0, &clean.logits0); |
| 970 | let caught = !cos.is_finite() || cos < 0.999 || r.tokens != clean.tokens; |
| 971 | say(format!( |
| 972 | "CONTROL {name}: prefill of {} tokens ({pname}, chunk {chunk}) first-step logits cosine {cos:.4} max abs diff {maxd:.2e} tokens {:?} vs clean {:?} -> {}", |
| 973 | ids.len(), r.tokens, clean.tokens, if caught { "CAUGHT" } else { "NOT CAUGHT (FAIL)" } |
| 974 | )); |
| 975 | gemm_controls.push(serde_json::json!({"control": name, "logits_cosine": cos, "max_abs_diff": maxd, "caught": caught})); |
| 976 | parity_pass &= caught; |
| 977 | } |
| 978 | } |
| 979 | } |
| 980 | // The kernel cache is back to the clean kernel: the same prefill again is bit-identical. |
| 981 | let again = run_prompt(&mut engine, ids, chunk, 1, &config.eos_token_ids) |
| 982 | .expect("clean gemm prefill again"); |
| 983 | let restored = again.logits0 == clean.logits0; |
| 984 | say(format!("CONTROL gemm-mutants-off: the clean prefill after the mutants is bit-identical to before -> {}", if restored { "PASS" } else { "FAIL" })); |
| 985 | parity_pass &= restored; |
| 986 | controls.extend(gemm_controls.iter().cloned()); |
| 987 | engine.prefill_chunk = chunk; |
| 988 | } |
| 989 | |
| 990 | // ---- whole-model greedy tokens vs golden, with timing ---- |
| 991 | let mut tokens_pass = tokens_pass_prefill; |
| 992 | for (idx, (name, ids)) in ps.iter().enumerate() { |
| 993 | if !a.prompt_ids.contains(&(idx + 1)) { |
| 994 | continue; |
| 995 | } |
| 996 | let g = golden["prompts"] |
| 997 | .as_array() |
| 998 | .and_then(|arr| arr.iter().find(|p| p["name"] == *name)); |
| 999 | let Some(g) = g else { |
| 1000 | say(format!("{name}: no golden entry, skipped")); |
| 1001 | continue; |
| 1002 | }; |
| 1003 | let want: Vec<u32> = g["golden"] |
| 1004 | .as_array() |
| 1005 | .unwrap() |
| 1006 | .iter() |
| 1007 | .map(|v| v.as_u64().unwrap() as u32) |
| 1008 | .collect(); |
| 1009 | let margins: Vec<f32> = g["margins"] |
| 1010 | .as_array() |
| 1011 | .unwrap() |
| 1012 | .iter() |
| 1013 | .map(|v| v.as_f64().unwrap() as f32) |
| 1014 | .collect(); |
| 1015 | let golden_prompt: Vec<u32> = g["prompt_tokens"] |
| 1016 | .as_array() |
| 1017 | .unwrap() |
| 1018 | .iter() |
| 1019 | .map(|v| v.as_u64().unwrap() as u32) |
| 1020 | .collect(); |
| 1021 | if golden_prompt != *ids { |
| 1022 | say(format!( |
| 1023 | "{name}: prompt tokens differ from the golden file's ({} vs {}), FAIL", |
| 1024 | ids.len(), |
| 1025 | golden_prompt.len() |
| 1026 | )); |
| 1027 | tokens_pass = false; |
| 1028 | continue; |
| 1029 | } |
| 1030 | let mut got = Vec::new(); |
| 1031 | let params = GenerateParams::greedy(a.new_tokens, config.eos_token_ids.clone()); |
| 1032 | // Start this prompt's timeline from zero (earlier sections also ran graph tokens). |
| 1033 | let _ = engine.take_decode_timeline(); |
| 1034 | let rb0 = paged.as_ref().map(|p| (p.stats(), p.read_stats())); |
| 1035 | let generation_start = Instant::now(); |
| 1036 | let mut token_elapsed_ms = Vec::new(); |
| 1037 | let o = engine |
| 1038 | .generate(ids, ¶ms, &mut |t| { |
| 1039 | token_elapsed_ms.push(generation_start.elapsed().as_secs_f64() * 1000.0); |
| 1040 | got.push(t); |
| 1041 | true |
| 1042 | }) |
| 1043 | .expect("generate"); |
| 1044 | let generation_wall_ms = generation_start.elapsed().as_secs_f64() * 1000.0; |
| 1045 | // The golden list includes a final stop id when the CPU stopped; ours consumed it. |
| 1046 | let want_cmp: Vec<u32> = want |
| 1047 | .iter() |
| 1048 | .copied() |
| 1049 | .filter(|t| !config.eos_token_ids.contains(t)) |
| 1050 | .collect(); |
| 1051 | let first_diff = got.iter().zip(&want_cmp).position(|(x, y)| x != y).or( |
| 1052 | if got.len() != want_cmp.len() { |
| 1053 | Some(got.len().min(want_cmp.len())) |
| 1054 | } else { |
| 1055 | None |
| 1056 | }, |
| 1057 | ); |
| 1058 | let verdict = match first_diff { |
| 1059 | None => "IDENTICAL".to_string(), |
| 1060 | Some(i) => { |
| 1061 | let m = margins.get(i).copied().unwrap_or(f32::NAN); |
| 1062 | format!( |
| 1063 | "DIVERGES at {i} (cpu top-2 margin {m:.4}; {})", |
| 1064 | if m < 1e-3 { |
| 1065 | "below the 1e-3 floor: recorded, not waved" |
| 1066 | } else { |
| 1067 | "FAIL" |
| 1068 | } |
| 1069 | ) |
| 1070 | } |
| 1071 | }; |
| 1072 | if let Some(i) = first_diff { |
| 1073 | if margins.get(i).copied().unwrap_or(0.0) >= 1e-3 { |
| 1074 | tokens_pass = false; |
| 1075 | } |
| 1076 | } |
| 1077 | let dt = &o.decode_timing; |
| 1078 | let steps = o.emitted_tokens.max(1) as f64; |
| 1079 | let tok_s = if o.decode_ms > 0 { |
| 1080 | o.emitted_tokens as f64 * 1000.0 / o.decode_ms as f64 |
| 1081 | } else { |
| 1082 | 0.0 |
| 1083 | }; |
| 1084 | let pt = &o.prefill_timing; |
| 1085 | say(format!( |
| 1086 | "TOKENS {name}: {} prompt tokens, prefill {:.2}s ({:.1} ms/token; chunk {}, per token attention {:.1} ms experts {:.1} ms host {:.1} ms launches {:.1}), decode {} tokens in {} ms = {:.1} ms/token = {tok_s:.1} tok/s; per step: attention {:.1} ms experts {:.1} ms lm_head {:.1} ms host {:.1} ms chip-reported {:.1} ms launches {}; {verdict}", |
| 1087 | ids.len(), |
| 1088 | o.prefill_ms as f64 / 1000.0, |
| 1089 | o.prefill_ms as f64 / ids.len() as f64, |
| 1090 | engine.prefill_chunk, |
| 1091 | pt.attention_ns as f64 / 1e6 / ids.len() as f64, |
| 1092 | pt.experts_ns as f64 / 1e6 / ids.len() as f64, |
| 1093 | pt.host_ns as f64 / 1e6 / ids.len() as f64, |
| 1094 | pt.launches as f64 / ids.len() as f64, |
| 1095 | o.emitted_tokens, |
| 1096 | o.decode_ms, |
| 1097 | o.decode_ms as f64 / steps, |
| 1098 | dt.attention_ns as f64 / 1e6 / steps, |
| 1099 | dt.experts_ns as f64 / 1e6 / steps, |
| 1100 | dt.lm_head_ns as f64 / 1e6 / steps, |
| 1101 | dt.host_ns as f64 / 1e6 / steps, |
| 1102 | dt.chip_ns as f64 / 1e6 / steps, |
| 1103 | dt.launches as f64 / steps, |
| 1104 | )); |
| 1105 | // Every old-path launch is its own synchronous submission; a one-list token is one |
| 1106 | // submission for all its launches. |
| 1107 | let submits = dt.launches - dt.graph_launches + dt.graph_submits; |
| 1108 | let per_graph = |v: u64| { |
| 1109 | if dt.graph_tokens > 0 { |
| 1110 | v as f64 / dt.graph_tokens as f64 |
| 1111 | } else { |
| 1112 | 0.0 |
| 1113 | } |
| 1114 | }; |
| 1115 | say(format!( |
| 1116 | " DECODE GRAPH {}: {} of {} decode steps as one list (the first step is the prefill's lm_head); per step launches {:.1} submits {:.1}; per graph token launches {:.1} submits {:.1} record {:.1} us", |
| 1117 | if engine.decode_graph_on() { "ON" } else { "OFF" }, |
| 1118 | dt.graph_tokens, |
| 1119 | o.emitted_tokens, |
| 1120 | dt.launches as f64 / steps, |
| 1121 | submits as f64 / steps, |
| 1122 | per_graph(dt.graph_launches), |
| 1123 | per_graph(dt.graph_submits), |
| 1124 | per_graph(dt.graph_record_ns) / 1e3, |
| 1125 | )); |
| 1126 | let mut ribbon_json = serde_json::Value::Null; |
| 1127 | if let (Some(p), Some((s0, r0))) = (&paged, &rb0) { |
| 1128 | let (s, r) = (p.stats(), p.read_stats()); |
| 1129 | let hit = s.experts_hit - s0.experts_hit; |
| 1130 | let miss = s.experts_missed - s0.experts_missed; |
| 1131 | let bytes = s.bytes_loaded - s0.bytes_loaded; |
| 1132 | let slot_ns = s.slot_load_ns - s0.slot_load_ns; |
| 1133 | let read_ns = s.read_wait_ns - s0.read_wait_ns; |
| 1134 | let miss_wall = s.miss_wall_ns - s0.miss_wall_ns; |
| 1135 | let dev_bytes = r.device_bytes - r0.device_bytes; |
| 1136 | say(format!( |
| 1137 | " RIBBON {} slots: experts hit {hit} miss {miss} (hit rate {:.4}); loaded {bytes} B; miss wall {:.1} ms; per decode step page {:.2} ms; prefill page {:.1} ms; summed read wait {:.1} ms; summed slot load {:.1} ms; device read {dev_bytes} B; resident {}", |
| 1138 | p.capacity(), |
| 1139 | hit as f64 / (hit + miss).max(1) as f64, |
| 1140 | miss_wall as f64 / 1e6, |
| 1141 | dt.page_ns as f64 / steps / 1e6, |
| 1142 | pt.page_ns as f64 / 1e6, |
| 1143 | read_ns as f64 / 1e6, |
| 1144 | slot_ns as f64 / 1e6, |
| 1145 | p.resident(), |
| 1146 | )); |
| 1147 | ribbon_json = serde_json::json!({"slots": p.capacity(), "hit": hit, "miss": miss, |
| 1148 | "bytes_loaded": bytes, "miss_wall_ns": miss_wall, "read_wait_ns": read_ns, |
| 1149 | "read_syscall_ns": r.read_ns - r0.read_ns, "verify_ns": r.digest_ns - r0.digest_ns, |
| 1150 | "reads_submitted": r.reads_submitted - r0.reads_submitted, |
| 1151 | "slot_load_ns": slot_ns, "device_read_bytes": dev_bytes, "decode_page_ns": dt.page_ns, |
| 1152 | "prefill_page_ns": pt.page_ns, "decode_steps": o.emitted_tokens}); |
| 1153 | } |
| 1154 | let mut timeline_json = serde_json::Value::Null; |
| 1155 | if let Some(t) = engine.take_decode_timeline() { |
| 1156 | let lines = timeline_table(&t, &config); |
| 1157 | for l in &lines { |
| 1158 | say(format!(" {l}")); |
| 1159 | } |
| 1160 | timeline_json = serde_json::json!({"steps": t.steps, "launches": t.launches, "ns": t.ns, "span_ns": t.span_ns, "chip_ns": t.chip_ns, "table": lines}); |
| 1161 | } |
| 1162 | say(format!( |
| 1163 | " chip text: {:?}", |
| 1164 | tok.decode(&got).unwrap_or_default() |
| 1165 | )); |
| 1166 | say(format!( |
| 1167 | " cpu text: {:?}", |
| 1168 | g["text"].as_str().unwrap_or("") |
| 1169 | )); |
| 1170 | results.push(serde_json::json!({ |
| 1171 | "name": name, "prompt_tokens": ids.len(), "chip": got, "golden": want, "first_diff": first_diff, |
| 1172 | "prefill_ms": o.prefill_ms, "decode_ms": o.decode_ms, "emitted": o.emitted_tokens, "tok_s": tok_s, "ribbon": ribbon_json, |
| 1173 | "first_visible_token_ms": token_elapsed_ms.first(), "token_elapsed_ms": token_elapsed_ms, |
| 1174 | "generation_wall_ms": generation_wall_ms, "peak_rss_after_generation_bytes": peak_rss_bytes(), |
| 1175 | "per_step_ms": {"attention": dt.attention_ns as f64 / 1e6 / steps, "experts": dt.experts_ns as f64 / 1e6 / steps, |
| 1176 | "lm_head": dt.lm_head_ns as f64 / 1e6 / steps, "host": dt.host_ns as f64 / 1e6 / steps, "chip_reported": dt.chip_ns as f64 / 1e6 / steps, |
| 1177 | "launches": dt.launches as f64 / steps}, |
| 1178 | "decode_graph": {"on": engine.decode_graph_on(), "graph_tokens": dt.graph_tokens, "graph_launches": dt.graph_launches, |
| 1179 | "graph_submits": dt.graph_submits, "graph_record_ns": dt.graph_record_ns, "submits": submits, "mutant": engine.decode_graph_mutant(), "timeline": timeline_json}, |
| 1180 | })); |
| 1181 | } |
| 1182 | // ---- a long prompt (new territory past 673 tokens): chunk 1 against the batched chunk ---- |
| 1183 | let mut long_json = serde_json::Value::Null; |
| 1184 | if a.long_prompt > 0 && engine.batched_prefill_possible() { |
| 1185 | let ids = long_prompt_ids(&tok, a.long_prompt); |
| 1186 | let chunk = engine.prefill_chunk.max(2); |
| 1187 | let mut outs = Vec::new(); |
| 1188 | for c in [chunk, 1usize] { |
| 1189 | let r = run_prompt(&mut engine, &ids, c, a.new_tokens, &config.eos_token_ids) |
| 1190 | .expect("long prompt generate"); |
| 1191 | say(prefill_line(&format!("LONG chunk {c}"), ids.len(), &r)); |
| 1192 | outs.push(r); |
| 1193 | } |
| 1194 | engine.prefill_chunk = chunk; |
| 1195 | let same = outs[0].tokens == outs[1].tokens; |
| 1196 | let (cos, maxd) = logits_agreement(&outs[0].logits0, &outs[1].logits0); |
| 1197 | let (_, margin) = top2_margin(&outs[1].logits0); |
| 1198 | // The batched path routes on the host and chunk 1 on the device, so their logits drift a little |
| 1199 | // with context (tokens must still agree); the GEMM itself must equal the grouped GEMV bit for bit. |
| 1200 | let mut gemm_eq_gemv = true; |
| 1201 | if engine.prefill_gemm { |
| 1202 | engine.prefill_gemm = false; |
| 1203 | let g = run_prompt( |
| 1204 | &mut engine, |
| 1205 | &ids, |
| 1206 | aien_inference_abi::qwen3_moe_omega::PREFILL_CHUNK, |
| 1207 | a.new_tokens, |
| 1208 | &config.eos_token_ids, |
| 1209 | ) |
| 1210 | .expect("long prompt gemv"); |
| 1211 | engine.prefill_gemm = true; |
| 1212 | say(prefill_line("LONG gemv chunk 8", ids.len(), &g)); |
| 1213 | gemm_eq_gemv = g.logits0 == outs[0].logits0 && g.tokens == outs[0].tokens; |
| 1214 | say(format!("LONG GEMM chunk {chunk} vs GEMV chunk 8: first-step logits and tokens bit-identical -> {}", if gemm_eq_gemv { "PASS" } else { "FAIL" })); |
| 1215 | } |
| 1216 | let ok = same && cos > 0.999 && gemm_eq_gemv; |
| 1217 | say(format!( |
| 1218 | "LONG chunk {chunk} vs 1 ({} tokens): tokens {} ; first-step logits cosine {cos:.7} max abs diff {maxd:.2e} (chunk-1 top-2 margin {margin:.4}) ; {:.1} -> {:.1} ms/token -> {}", |
| 1219 | ids.len(), |
| 1220 | if same { "IDENTICAL" } else { "DIFFER (FAIL)" }, |
| 1221 | outs[1].prefill_ms as f64 / ids.len() as f64, |
| 1222 | outs[0].prefill_ms as f64 / ids.len() as f64, |
| 1223 | if ok { "PASS" } else { "FAIL" } |
| 1224 | )); |
| 1225 | say(format!( |
| 1226 | " long chip text: {:?}", |
| 1227 | tok.decode(&outs[0].tokens).unwrap_or_default() |
| 1228 | )); |
| 1229 | tokens_pass &= ok; |
| 1230 | long_json = serde_json::json!({"prompt_tokens": ids.len(), "chunk": chunk, "tokens_identical": same, "logits_cosine": cos, "logits_max_abs_diff": maxd, |
| 1231 | "prefill_ms_chunk": outs[0].prefill_ms, "prefill_ms_chunk1": outs[1].prefill_ms, "top2_margin_chunk1": margin}); |
| 1232 | } |
| 1233 | say(format!( |
| 1234 | "SUMMARY parity={} tokens={} peak_rss={:.2} GB", |
| 1235 | if parity_pass { "PASS" } else { "FAIL" }, |
| 1236 | if tokens_pass { "PASS" } else { "FAIL" }, |
| 1237 | peak_rss_bytes().unwrap_or(0) as f64 / 1e9 |
| 1238 | )); |
| 1239 | let doc = serde_json::json!({ |
| 1240 | "checkpoint": a.checkpoint.display().to_string(), |
| 1241 | "golden": a.golden.display().to_string(), |
| 1242 | "native_identity": serde_json::from_str::<serde_json::Value>(&aien_omega_gpu::native_identity().to_json()).expect("native identity JSON"), |
| 1243 | "engine": {"native": aien_omega_gpu::is_native(), "window_api": OmegaModelUploader::uses_window_api(), |
| 1244 | "fp8_api": OmegaModelUploader::uses_fp8_api(), "router_api": OmegaModelUploader::uses_router_api(), "bf16_api": OmegaModelUploader::uses_bf16_api(), "dattn_api": OmegaModelUploader::uses_dattn_api(), |
| 1245 | "weights": format!("{:?}", a.format), "attention": engine.attention_path(), "router": router_path, "lm_head": lm_head_path, "prefill_chunk": engine.prefill_chunk, "prefill_path": if engine.prefill_gemm { "gemm" } else { "gemv" }, "prefill_routing": if engine.prefill_device_routing { "device" } else { "host" }, |
| 1246 | "spin_us": aien_omega_gpu::spin_us(), "cta_budget": aien_omega_gpu::cta_budget(), "kv_resident": engine.kv_resident(), |
| 1247 | "max_context": engine.max_context_tokens()}, |
| 1248 | "prefill": prefill_json, "long_prompt": long_json, |
| 1249 | "load": {"seconds": report.seconds, "resident_bytes": report.resident_bytes, "host_bytes": report.host_bytes, |
| 1250 | "peak_rss_bytes": report.peak_rss_bytes, "peak_rss_before_bytes": report.peak_rss_before_bytes, "transient_gb": transient}, |
| 1251 | "parity": parity_json, "controls": controls, "prompts": results, |
| 1252 | "pass": parity_pass && tokens_pass, |
| 1253 | }); |
| 1254 | std::fs::write( |
| 1255 | receipt.join("run.json"), |
| 1256 | serde_json::to_string_pretty(&doc).unwrap(), |
| 1257 | ) |
| 1258 | .expect("write run.json"); |
| 1259 | std::fs::write(receipt.join("run.log"), log.join("\n") + "\n").expect("write run.log"); |
| 1260 | println!("receipt: {}", receipt.display()); |
| 1261 | if !(parity_pass && tokens_pass) { |
| 1262 | std::process::exit(1); |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | fn main() { |
| 1267 | let a = parse_args(); |
| 1268 | if !Path::new(&a.checkpoint).join("config.json").is_file() { |
| 1269 | eprintln!("no config.json in {}", a.checkpoint.display()); |
| 1270 | std::process::exit(2); |
| 1271 | } |
| 1272 | match a.mode.as_str() { |
| 1273 | "golden" => golden(&a), |
| 1274 | _ => chip(&a), |
| 1275 | } |
| 1276 | } |
| 1277 | |
| 1278 | /// The one-list decode's per-kind timeline as table lines: kind, launches/step, us/step, FP8 (or |
| 1279 | /// bf16 for the lm_head) weight bytes/step and the achieved GB/s. Router, attention and the glue |
| 1280 | /// kernels get "-" for bytes (their traffic is not a fixed weight read; KV bytes are not guessed). |
| 1281 | fn timeline_table(t: &dgraph::Timeline, c: &Qwen3MoeConfig) -> Vec<String> { |
| 1282 | let steps = t.steps.max(1) as f64; |
| 1283 | let l = c.layers as f64; |
| 1284 | let bytes = |kind: &str| -> Option<f64> { |
| 1285 | match kind { |
| 1286 | "qkv" => Some(5120.0 * 2048.0 * l), |
| 1287 | "o_proj" => Some(2048.0 * 4096.0 * l), |
| 1288 | "gate_up" => Some(8.0 * 1536.0 * 2048.0 * l), |
| 1289 | "down" => Some(8.0 * 2048.0 * 768.0 * l), |
| 1290 | "lm_head" => Some(151936.0 * 2048.0 * 2.0), |
| 1291 | _ => None, |
| 1292 | } |
| 1293 | }; |
| 1294 | let mut out = vec![format!( |
| 1295 | "TIMELINE over {} graph tokens: {:<12} {:>9} {:>10} {:>14} {:>9}", |
| 1296 | t.steps, "kind", "launches", "us/step", "bytes/step", "GB/s" |
| 1297 | )]; |
| 1298 | let mut sum_ns = 0u64; |
| 1299 | for k in 0..12 { |
| 1300 | let name = aien_omega_dgraph::kind_name(k as u8); |
| 1301 | sum_ns += t.ns[k]; |
| 1302 | let us = t.ns[k] as f64 / 1e3 / steps; |
| 1303 | let (b, gbs) = match bytes(&name) { |
| 1304 | // bytes per ns = GB/s |
| 1305 | Some(b) if t.ns[k] > 0 => ( |
| 1306 | format!("{b:.0}"), |
| 1307 | format!("{:.1}", b * steps / t.ns[k] as f64), |
| 1308 | ), |
| 1309 | Some(b) => (format!("{b:.0}"), "-".into()), |
| 1310 | None => ("-".into(), "-".into()), |
| 1311 | }; |
| 1312 | out.push(format!( |
| 1313 | "TIMELINE {:<12} {:>9.1} {:>10.1} {:>14} {:>9}", |
| 1314 | name, |
| 1315 | t.launches[k] as f64 / steps, |
| 1316 | us, |
| 1317 | b, |
| 1318 | gbs |
| 1319 | )); |
| 1320 | } |
| 1321 | out.push(format!( |
| 1322 | "TIMELINE span {:.1} us/step (sum of kinds {:.1}) vs graph chip_ns {:.1} us/step", |
| 1323 | t.span_ns as f64 / 1e3 / steps, |
| 1324 | sum_ns as f64 / 1e3 / steps, |
| 1325 | t.chip_ns as f64 / 1e3 / steps |
| 1326 | )); |
| 1327 | out |
| 1328 | } |