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 / q36_levers.rs
| 1 | //! Speed levers on the served Qwen3.6-35B-A3B decode graph (sc L356): identity and timing in one run. |
| 2 | //! |
| 3 | //! q36_levers <checkpoint-dir> <out.json> <golden.json>... |
| 4 | //! |
| 5 | //! 1. Identity: every golden (`qwen38_check generate` record: `prompt_ids`, `generated_ids`) is fed |
| 6 | //! token by token through the decode graph and decoded greedily for as many tokens as it holds. |
| 7 | //! The chip's ids must equal the golden's; every decoded step's logits are also hashed (FNV-1a |
| 8 | //! over the raw f32 bits) so two builds can be held to bit-identical logits, not only ids. |
| 9 | //! 2. Timing: the first golden's prompt, then greedy decoding up to `Q36_LEVERS_POS` (default 1100) |
| 10 | //! with no logits read. Chip and host time per token, averaged per position band. Tokens at the |
| 11 | //! positions in `Q36_LEVERS_STAMPS` (default 40,300,1000) run with the GPU timeline on and are |
| 12 | //! left out of the averages: their launches are summed per kind and set against the bytes each |
| 13 | //! kind moves at `BW` (the 228 GB/s stream rate), the gap a lever can close. |
| 14 | //! |
| 15 | //! Exit 0 when every golden is identical, 1 otherwise. |
| 16 | use std::path::Path; |
| 17 | use std::time::Instant; |
| 18 | |
| 19 | use aien_inference_abi::qwen38::Qwen38Config; |
| 20 | use aien_inference_abi::qwen38_omega::{need_bytes, Qwen38Omega}; |
| 21 | use aien_omega_q38::q36; |
| 22 | use serde_json::{json, Value}; |
| 23 | |
| 24 | const KEEP_FREE: u64 = 12 << 30; |
| 25 | /// Stream rate the byte times are taken at (GB/s, MACHINE_CEILING). |
| 26 | const BW: f64 = 228e9; |
| 27 | |
| 28 | fn mem_available() -> Result<u64, String> { |
| 29 | let text = std::fs::read_to_string("/proc/meminfo").map_err(|e| e.to_string())?; |
| 30 | text.lines() |
| 31 | .find_map(|l| l.strip_prefix("MemAvailable:")) |
| 32 | .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::<u64>().ok()) |
| 33 | .map(|kb| kb * 1024) |
| 34 | .ok_or_else(|| "/proc/meminfo: no MemAvailable".into()) |
| 35 | } |
| 36 | |
| 37 | fn fnv(l: &[f32]) -> u64 { |
| 38 | let mut h: u64 = 0xcbf2_9ce4_8422_2325; |
| 39 | for v in l { |
| 40 | for b in v.to_bits().to_le_bytes() { |
| 41 | h ^= b as u64; |
| 42 | h = h.wrapping_mul(0x0100_0000_01b3); |
| 43 | } |
| 44 | } |
| 45 | h |
| 46 | } |
| 47 | |
| 48 | fn ids(v: &Value, k: &str) -> Result<Vec<u32>, String> { |
| 49 | v[k].as_array() |
| 50 | .ok_or(format!("golden: no {k}"))? |
| 51 | .iter() |
| 52 | .map(|x| { |
| 53 | x.as_u64() |
| 54 | .map(|x| x as u32) |
| 55 | .ok_or(format!("golden: bad {k}")) |
| 56 | }) |
| 57 | .collect() |
| 58 | } |
| 59 | |
| 60 | /// What the lm_head byte count assumes, printed on the lm_head line of every report. |
| 61 | fn lm_head_basis(exact_head: bool) -> &'static str { |
| 62 | if exact_head { |
| 63 | "exact two-pass head: fp8b screen 1 B/weight + bf16 block scales, 5 f32 vocab vectors; candidate rows not counted" |
| 64 | } else { |
| 65 | "plain head: bf16 2 B/weight" |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// Bytes the lm_head launches read per token. The 35B uploads lm_head as bf16 (qwen38_omega/moe.rs). |
| 70 | /// With the exact two-pass head on (HUM L314, the default unless `AIEN_Q36_EXACT_HEAD=0`) the final |
| 71 | /// step reads the fp8b screen (1 B per weight plus one bf16 scale per 128 x 128 block), its XBOUND |
| 72 | /// glue reads s and c and writes lo and hi (f32 [vocab] each), and the bf16 MASK gemv reads hi[r] |
| 73 | /// for every row (f32 [vocab]) and runs the K loop only on the candidate rows (hi[r] >= tau; data |
| 74 | /// dependent, a few rows of 4 KiB, not counted). Off, the plain gemv reads the whole bf16 head |
| 75 | /// (2 B per weight). The logits write (f32 [vocab]) is left out on both branches, as for every |
| 76 | /// gemv here. From omega_gpu_q36_graph.c record_head_final and omega_blackwell_codegen_bf16.h (MASK). |
| 77 | fn lm_head_bytes(vocab: usize, hidden: usize, exact_head: bool) -> f64 { |
| 78 | let (v, h) = (vocab as f64, hidden as f64); |
| 79 | if exact_head { |
| 80 | v * h + (v / 128.0).ceil() * (h / 128.0).ceil() * 2.0 + 5.0 * v * 4.0 |
| 81 | } else { |
| 82 | v * h * 2.0 |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Bytes one launch kind moves per token at position `pos` (weights, state, KV; glue kernels |
| 87 | /// counted as their inputs plus outputs in f32). From the shapes in omega_gpu_q36_graph.h. |
| 88 | fn kind_bytes(c: &Qwen38Config, kind: &str, pos: usize, exact_head: bool) -> f64 { |
| 89 | let h = c.hidden as f64; |
| 90 | let gdn = c.full_attention.iter().filter(|a| !**a).count() as f64; |
| 91 | let attn = c.layers as f64 - gdn; |
| 92 | let mixer = q36::MIXER_OUT as f64; |
| 93 | match kind { |
| 94 | "mix" => gdn * q36::GDN_MIX as f64 * h + attn * q36::ATT_MIX as f64 * h, |
| 95 | "ab" => gdn * q36::AB as f64 * h * 2.0, |
| 96 | // DeltaNet state f32 [32 v heads][128][128], read and written. |
| 97 | "gdn" => gdn * 2.0 * 32.0 * 128.0 * 128.0 * 4.0, |
| 98 | // K and V, bf16, 2 kv heads x 256, positions 0..=pos. |
| 99 | "attn" => attn * 2.0 * q36::KV_HEADS as f64 * 256.0 * 2.0 * (pos + 1) as f64, |
| 100 | "o_proj" => c.layers as f64 * h * mixer, |
| 101 | "router" => c.layers as f64 * q36::EXPERT_ROWS as f64 * h * 2.0, |
| 102 | "gate_up" => c.layers as f64 * q36::GROUPS as f64 * 2.0 * q36::EXPERT_INTER as f64 * h, |
| 103 | "down" => c.layers as f64 * q36::GROUPS as f64 * h * q36::EXPERT_INTER as f64, |
| 104 | "lm_head" => lm_head_bytes(c.vocab, c.hidden, exact_head), |
| 105 | _ => 0.0, |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// One stamped kind's bytes and its JSON row (`bytes_basis` on the lm_head row), both from the |
| 110 | /// one exact-head flag. |
| 111 | fn kind_row( |
| 112 | c: &Qwen38Config, |
| 113 | name: &str, |
| 114 | launches: u32, |
| 115 | ns: u64, |
| 116 | pos: usize, |
| 117 | exact_head: bool, |
| 118 | ) -> (f64, Value) { |
| 119 | let b = kind_bytes(c, name, pos, exact_head); |
| 120 | let mut row = |
| 121 | json!({"kind": name, "launches": launches, "ns": ns, "bytes": b, "byte_ns": b / BW * 1e9}); |
| 122 | if name == "lm_head" { |
| 123 | row["bytes_basis"] = json!(lm_head_basis(exact_head)); |
| 124 | } |
| 125 | (b, row) |
| 126 | } |
| 127 | |
| 128 | fn run() -> Result<bool, String> { |
| 129 | let a: Vec<String> = std::env::args().collect(); |
| 130 | if a.len() < 4 { |
| 131 | return Err("usage: q36_levers <checkpoint-dir> <out.json> <golden.json>...".into()); |
| 132 | } |
| 133 | let dir = Path::new(&a[1]); |
| 134 | let env_list = |k: &str, d: &str| -> Vec<usize> { |
| 135 | std::env::var(k) |
| 136 | .unwrap_or_else(|_| d.into()) |
| 137 | .split(',') |
| 138 | .filter_map(|s| s.trim().parse().ok()) |
| 139 | .collect() |
| 140 | }; |
| 141 | let end_pos = env_list("Q36_LEVERS_POS", "1100")[0]; |
| 142 | let stamp_at = env_list("Q36_LEVERS_STAMPS", "40,300,1000"); |
| 143 | let max_pos = 2048.max(end_pos + 1); |
| 144 | let c = Qwen38Config::from_checkpoint(dir)?; |
| 145 | let need = need_bytes(&c, max_pos, 4096); |
| 146 | let avail = mem_available()?; |
| 147 | if avail < need + KEEP_FREE { |
| 148 | return Err(format!( |
| 149 | "needs {} MiB + {} MiB free, MemAvailable {} MiB; refusing", |
| 150 | need >> 20, |
| 151 | KEEP_FREE >> 20, |
| 152 | avail >> 20 |
| 153 | )); |
| 154 | } |
| 155 | let env: Vec<(String, String)> = std::env::vars() |
| 156 | .filter(|(k, _)| k.starts_with("AIEN_") || k.starts_with("OMEGA") || k.starts_with("Q36_")) |
| 157 | .collect(); |
| 158 | eprintln!( |
| 159 | "upload: need {} MiB, MemAvailable {} MiB, env {env:?}", |
| 160 | need >> 20, |
| 161 | avail >> 20 |
| 162 | ); |
| 163 | let t = Instant::now(); |
| 164 | let mut m = Qwen38Omega::open(dir, None, max_pos)?; |
| 165 | let open_s = t.elapsed().as_secs_f64(); |
| 166 | if !m.is_moe() { |
| 167 | return Err("not the 35B (sparse) model".into()); |
| 168 | } |
| 169 | |
| 170 | // 1. identity |
| 171 | let mut all_ok = true; |
| 172 | let mut goldens = Vec::new(); |
| 173 | let mut first_prompt = Vec::new(); |
| 174 | for gpath in &a[3..] { |
| 175 | let g: Value = serde_json::from_str( |
| 176 | &std::fs::read_to_string(gpath).map_err(|e| format!("{gpath}: {e}"))?, |
| 177 | ) |
| 178 | .map_err(|e| format!("{gpath}: {e}"))?; |
| 179 | let (prompt, want) = (ids(&g, "prompt_ids")?, ids(&g, "generated_ids")?); |
| 180 | if first_prompt.is_empty() { |
| 181 | first_prompt = prompt.clone(); |
| 182 | } |
| 183 | m.reset()?; |
| 184 | let mut tok = 0; |
| 185 | for &p in &prompt { |
| 186 | tok = m.step(p)?.0; |
| 187 | } |
| 188 | let mut got = vec![tok]; |
| 189 | let mut hashes = vec![format!("{:016x}", fnv(&m.logits()?))]; |
| 190 | while got.len() < want.len() { |
| 191 | tok = m.step(tok)?.0; |
| 192 | got.push(tok); |
| 193 | hashes.push(format!("{:016x}", fnv(&m.logits()?))); |
| 194 | } |
| 195 | let ok = got == want; |
| 196 | all_ok &= ok; |
| 197 | let first_diff = got.iter().zip(&want).position(|(x, y)| x != y); |
| 198 | eprintln!( |
| 199 | "identity {gpath}: {} ({} tokens)", |
| 200 | if ok { "IDENTICAL" } else { "DIFFER" }, |
| 201 | want.len() |
| 202 | ); |
| 203 | goldens.push(json!({"golden": gpath, "identical": ok, "first_diff": first_diff, "got": got, "logits_fnv": hashes})); |
| 204 | } |
| 205 | |
| 206 | // 2. timing |
| 207 | m.reset()?; |
| 208 | let mut tok = 0; |
| 209 | for &p in &first_prompt { |
| 210 | tok = m.step(p)?.0; |
| 211 | } |
| 212 | let bands: [(usize, usize); 4] = [(0, 64), (64, 288), (288, 800), (800, usize::MAX)]; |
| 213 | let mut sums = vec![(0u64, 0u64, 0u64, 0usize); bands.len()]; // chip, host total, wall, n |
| 214 | let mut stamped = Vec::new(); |
| 215 | let mut pos = first_prompt.len(); |
| 216 | while pos < end_pos { |
| 217 | let stamp = stamp_at.contains(&pos); |
| 218 | if stamp { |
| 219 | m.q36_graph_mut().ok_or("no q36 graph")?.set_stamps(true); |
| 220 | } |
| 221 | let t = Instant::now(); |
| 222 | let (next, st) = m.step(tok)?; |
| 223 | let wall = t.elapsed().as_nanos() as u64; |
| 224 | if stamp { |
| 225 | let g = m.q36_graph_mut().ok_or("no q36 graph")?; |
| 226 | let tl = g.timeline().map_err(|rc| format!("stamps: rc {rc}"))?; |
| 227 | g.set_stamps(false); |
| 228 | let mut per: Vec<(String, u64, u32)> = Vec::new(); |
| 229 | for &(kind, d) in &tl { |
| 230 | let name = q36::Q36Graph::kind_name(kind); |
| 231 | match per.iter_mut().find(|e| e.0 == name) { |
| 232 | Some(e) => { |
| 233 | e.1 += d; |
| 234 | e.2 += 1 |
| 235 | } |
| 236 | None => per.push((name, d, 1)), |
| 237 | } |
| 238 | } |
| 239 | let span: u64 = tl.iter().map(|e| e.1).sum(); |
| 240 | let mut rows = Vec::new(); |
| 241 | let mut byte_total = 0.0; |
| 242 | eprintln!( |
| 243 | "timeline pos {pos}: {} launches, span {:.1} us, chip {:.1} us", |
| 244 | tl.len(), |
| 245 | span as f64 / 1e3, |
| 246 | st.chip_ns as f64 / 1e3 |
| 247 | ); |
| 248 | let exact_head = m.exact_head_active(); |
| 249 | for (name, ns, n) in &per { |
| 250 | let (b, row) = kind_row(&c, name, *n, *ns, pos, exact_head); |
| 251 | byte_total += b; |
| 252 | let byte_us = b / BW * 1e6; |
| 253 | let basis = row["bytes_basis"] |
| 254 | .as_str() |
| 255 | .map_or(String::new(), |s| format!(" [{s}]")); |
| 256 | eprintln!( |
| 257 | " {name:>8}: {n:4} launches {:9.1} us ({:5.1}%), {:8.2} MB, byte time {:8.1} us, gap {:8.1} us, {:6.2} us/launch{basis}", |
| 258 | *ns as f64 / 1e3, |
| 259 | *ns as f64 * 100.0 / span as f64, |
| 260 | b / 1e6, |
| 261 | byte_us, |
| 262 | *ns as f64 / 1e3 - byte_us, |
| 263 | *ns as f64 / 1e3 / *n as f64 |
| 264 | ); |
| 265 | rows.push(row); |
| 266 | } |
| 267 | eprintln!( |
| 268 | " total bytes {:.1} MB, byte time {:.1} us", |
| 269 | byte_total / 1e6, |
| 270 | byte_total / BW * 1e6 |
| 271 | ); |
| 272 | stamped.push(json!({"pos": pos, "launches": tl.len(), "span_ns": span, "chip_ns": st.chip_ns, "wall_ns": wall, |
| 273 | "bytes": byte_total, "byte_ns": byte_total / BW * 1e9, "kinds": rows})); |
| 274 | } else { |
| 275 | let b = bands |
| 276 | .iter() |
| 277 | .position(|&(lo, hi)| pos >= lo && pos < hi) |
| 278 | .unwrap_or(0); |
| 279 | let e = &mut sums[b]; |
| 280 | e.0 += st.chip_ns; |
| 281 | e.1 += st.total_ns; |
| 282 | e.2 += wall; |
| 283 | e.3 += 1; |
| 284 | } |
| 285 | tok = next; |
| 286 | pos += 1; |
| 287 | } |
| 288 | let band_rows: Vec<Value> = bands |
| 289 | .iter() |
| 290 | .zip(&sums) |
| 291 | .filter(|(_, s)| s.3 > 0) |
| 292 | .map(|(&(lo, hi), &(chip, tot, wall, n))| { |
| 293 | let n64 = n as f64; |
| 294 | eprintln!( |
| 295 | "band pos [{lo}, {}): {n} tokens, chip {:.3} ms, graph total {:.3} ms, wall {:.3} ms, {:.2} tok/s (wall)", |
| 296 | if hi == usize::MAX { end_pos } else { hi }, |
| 297 | chip as f64 / n64 / 1e6, |
| 298 | tot as f64 / n64 / 1e6, |
| 299 | wall as f64 / n64 / 1e6, |
| 300 | n64 * 1e9 / wall as f64 |
| 301 | ); |
| 302 | json!({"lo": lo, "hi": hi.min(end_pos), "tokens": n, "chip_ms": chip as f64 / n64 / 1e6, |
| 303 | "graph_total_ms": tot as f64 / n64 / 1e6, "wall_ms": wall as f64 / n64 / 1e6, "tok_s": n64 * 1e9 / wall as f64}) |
| 304 | }) |
| 305 | .collect(); |
| 306 | let out = json!({ |
| 307 | "tool": "q36_levers", "model": a[1], "open_s": open_s, "env": env.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>(), |
| 308 | "all_identical": all_ok, "goldens": goldens, "bands": band_rows, "timelines": stamped, |
| 309 | }); |
| 310 | std::fs::write( |
| 311 | &a[2], |
| 312 | serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?, |
| 313 | ) |
| 314 | .map_err(|e| e.to_string())?; |
| 315 | eprintln!( |
| 316 | "identity: {}", |
| 317 | if all_ok { "ALL IDENTICAL" } else { "DIFFER" } |
| 318 | ); |
| 319 | Ok(all_ok) |
| 320 | } |
| 321 | |
| 322 | fn main() { |
| 323 | match run() { |
| 324 | Ok(true) => {} |
| 325 | Ok(false) => std::process::exit(1), |
| 326 | Err(e) => { |
| 327 | eprintln!("q36_levers: {e}"); |
| 328 | std::process::exit(2); |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | #[cfg(test)] |
| 334 | mod tests { |
| 335 | use super::{kind_row, lm_head_bytes}; |
| 336 | use aien_inference_abi::qwen38::Qwen38Config; |
| 337 | |
| 338 | /// The 35B's shape as far as kind_bytes reads it (config.json of qwen3.6-35b-a3b-fp8). |
| 339 | fn q36() -> Qwen38Config { |
| 340 | Qwen38Config { |
| 341 | hidden: 2048, |
| 342 | layers: 40, |
| 343 | vocab: 248_320, |
| 344 | intermediate: 0, |
| 345 | full_attention: (0..40).map(|l| l % 4 == 3).collect(), |
| 346 | heads: 16, |
| 347 | kv_heads: 2, |
| 348 | head_dim: 256, |
| 349 | rotary_dim: 64, |
| 350 | rope_theta: 1e7, |
| 351 | lin_k_heads: 16, |
| 352 | lin_v_heads: 32, |
| 353 | lin_k_dim: 128, |
| 354 | lin_v_dim: 128, |
| 355 | conv_kernel: 4, |
| 356 | eps: 1e-6, |
| 357 | eos_token_ids: vec![], |
| 358 | moe: None, |
| 359 | fp8: true, |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | // Qwen3.6-35B-A3B: vocab 248,320, hidden 2048 (config.json); lm_head.weight BF16 [248320, 2048], |
| 364 | // 1,017,118,720 B in outside.safetensors. |
| 365 | #[test] |
| 366 | fn lm_head_counts_the_fp8b_screen_with_the_exact_head() { |
| 367 | // 248320 * 2048 weights at 1 B + (248320/128) x (2048/128) = 1940 x 16 blocks at 2 B |
| 368 | // + s, c, lo, hi (XBOUND) and hi again (MASK), f32 [248320]. |
| 369 | let exact = 248_320.0 * 2048.0 + 1940.0 * 16.0 * 2.0 + 5.0 * 248_320.0 * 4.0; |
| 370 | assert_eq!(lm_head_bytes(248_320, 2048, true), exact); |
| 371 | assert_eq!(exact, 508_559_360.0 + 62_080.0 + 4_966_400.0); |
| 372 | assert_eq!(exact, 513_587_840.0); |
| 373 | } |
| 374 | |
| 375 | #[test] |
| 376 | fn lm_head_counts_the_bf16_head_without_the_exact_head() { |
| 377 | // The checkpoint tensor's size: data_offsets [0, 1017118720]. |
| 378 | assert_eq!(lm_head_bytes(248_320, 2048, false), 1_017_118_720.0); |
| 379 | assert_ne!( |
| 380 | lm_head_bytes(248_320, 2048, false), |
| 381 | lm_head_bytes(248_320, 2048, true) |
| 382 | ); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn the_stamped_lm_head_row_takes_bytes_and_basis_from_one_flag() { |
| 387 | let c = q36(); |
| 388 | let (b, row) = kind_row(&c, "lm_head", 1, 0, 40, true); |
| 389 | assert_eq!(b, 513_587_840.0); |
| 390 | assert_eq!(row["bytes"], 513_587_840.0); |
| 391 | assert!(row["bytes_basis"] |
| 392 | .as_str() |
| 393 | .unwrap() |
| 394 | .starts_with("exact two-pass head")); |
| 395 | let (b, row) = kind_row(&c, "lm_head", 1, 0, 40, false); |
| 396 | assert_eq!(b, 1_017_118_720.0); |
| 397 | assert_eq!(row["bytes"], 1_017_118_720.0); |
| 398 | assert_eq!(row["bytes_basis"], "plain head: bf16 2 B/weight"); |
| 399 | // Other kinds carry no basis and do not depend on the flag. |
| 400 | let (t, row) = kind_row(&c, "down", 40, 0, 40, true); |
| 401 | assert_eq!(t, kind_row(&c, "down", 40, 0, 40, false).0); |
| 402 | assert!(row.get("bytes_basis").is_none()); |
| 403 | } |
| 404 | } |