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
GitHub aien-dev/aien-sovereign-core-mv#883 (code only)
Apply it
git checkout -b patch-630ec847ae0acbdf 9818d6b47364a94a8e45ea81001b8f2f7413ab4b curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/630ec847ae0acbdf.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
883
b129e1eae4be82e220b7f305fa327bca36a66714
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":883,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/883","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:11Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aien-inference-abi/src/bin/qwen36_prefill_bench.rs b/crates/aien-inference-abi/src/bin/qwen36_prefill_bench.rs new file mode 100644 index 00000000..0b7263c6 --- /dev/null +++ b/crates/aien-inference-abi/src/bin/qwen36_prefill_bench.rs @@ -0,0 +1,504 @@ +//! Prefill bench for the 35B (P-DRA-4 Lane P, gates G1-G3): one prefill arm per process, so the +//! arm is the environment (path A: the legacy fp8 GEMV prefill, chunk 128; path B: the tensor-core +//! prefill, `AIEN_OMEGA_Q36_PF_QMMA=1` on a library that has it). The logits it writes are judged +//! offline by `om/prefill-logits` (A against B, same prompt). +//! +//! ```text +//! qwen36_prefill_bench [--plan] <checkpoint-dir> <arm> <out-dir> <reps> <prompt>... +//! prompt: NAME=corpus:FILE.txt:LEN the first LEN tokens of FILE (tokenized as the L369 gate does) +//! NAME=text:FILE.txt every token of FILE +//! NAME=ids:FILE.json token ids: a JSON array, or an object with "prompt_ids" / "ids" +//! ``` +//! +//! Chunk: `AIEN_Q36_PREFILL_CHUNK` read by [`q36_prefill_chunk`] (the server's knob, default the +//! graph's most rows); 0 = token by token through the decode graph (the GEMV reference). The bench +//! hands the prefill one chunk per call, so every chunk gets its own clock, byte count and timeline. +//! +//! Per prompt, `reps` timed passes (stamps off), then one pass with the launch timestamps on. +//! Written to `<out-dir>/<arm>/`: `NAME.logits.f32` (the last prompt token's logits, 248320 LE f32, +//! no header), `NAME.json`, and `bench.json` (every prompt). Clocks, never mixed: +//! - `ttft_inproc_host_ms`: host clock around the whole prompt (embedding, submit, wait, the last +//! token's head and argmax) in this process. No HTTP, no tokenizer, no queue. +//! - `chip_only_ms`: the GPU timestamps, last minus first stamp of each chunk, summed over chunks. +//! The first launch of each command list carries the host gap before it, so this is the device +//! span, not busy time; `classes` sums the same per-launch spans by launch kind. +//! `GraphStats::chip_ns` is not used: it is host clock from submit to the marker. +//! - `streamed_bytes`: the graph's fp8 GEMM weight byte count, per chunk. +//! +//! `AIEN_BENCH_LAYERS=N`: a model prefix (small load). `AIEN_BENCH_STAMPS=0`: no timestamp pass. +//! `--plan`: tokenize, write `NAME.ids.json` with the chunk plan, load nothing (host check). +//! Exit 0 done, 1 a rep's logits differ bit for bit from rep 0 (non-determinism), 2 error. +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use aien_inference_abi::qwen38_omega::{q36_prefill_chunk, Qwen38Omega}; +use aien_inference_abi::tokenizer::ChatTokenizer; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +const TOKENIZE_PIECE: usize = 2000; +const TOP_K: usize = 16; +/// The knobs a record carries: everything that picks a prefill or decode path in this process. +const KNOBS: &[&str] = &[ + "AIEN_Q36_PREFILL_CHUNK", + "AIEN_OMEGA_Q36_PF_CHUNK", + "AIEN_OMEGA_Q36_PF_QMMA", + "AIEN_OMEGA_Q36_PF_MUTANT", + "AIEN_OMEGA_PFQ_MUTANT", + "AIEN_OMEGA_PFQ_WAIT", + "AIEN_OMEGA_Q36_PF_GDN", + "AIEN_OMEGA_Q36_PF_ATTN", + "AIEN_OMEGA_FP8_GROUPED_WAVE", + "AIEN_Q36_EXACT_HEAD", + "AIEN_STROKE_IN_WINDOW", + "AIEN_BENCH_LAYERS", + "AIEN_BENCH_STAMPS", +]; + +struct Prompt { + name: String, + source: String, + ids: Vec<u32>, +} + +enum Spec { + Corpus(PathBuf, usize), + Text(PathBuf), + Ids(PathBuf), +} + +fn parse_spec(s: &str) -> Result<(String, Spec), String> { + let (name, rest) = s + .split_once('=') + .ok_or_else(|| format!("prompt {s}: NAME=corpus:FILE:LEN | NAME=text:FILE | NAME=ids:FILE"))?; + if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { + return Err(format!("prompt {s}: NAME must be [A-Za-z0-9_-]+")); + } + let (kind, arg) = rest + .split_once(':') + .ok_or_else(|| format!("prompt {s}: no kind"))?; + let spec = match kind { + "corpus" => { + let (file, len) = arg + .rsplit_once(':') + .ok_or_else(|| format!("prompt {s}: corpus:FILE:LEN"))?; + let len: usize = len.parse().map_err(|e| format!("prompt {s}: len: {e}"))?; + if len == 0 { + return Err(format!("prompt {s}: len 0")); + } + Spec::Corpus(file.into(), len) + } + "text" => Spec::Text(arg.into()), + "ids" => Spec::Ids(arg.into()), + k => return Err(format!("prompt {s}: kind {k} (corpus | text | ids)")), + }; + Ok((name.to_string(), spec)) +} + +/// The L369 gate's tokenization: pieces of at most [`TOKENIZE_PIECE`] bytes, cut on char boundaries. +fn tokenize(tk: &ChatTokenizer, text: &str, want: Option<usize>) -> Result<Vec<u32>, String> { + let mut out = Vec::new(); + let mut rest = text; + while want.is_none_or(|w| out.len() < w) && !rest.is_empty() { + let mut cut = rest.len().min(TOKENIZE_PIECE); + while !rest.is_char_boundary(cut) { + cut -= 1; + } + out.extend(tk.encode(&rest[..cut]).map_err(|e| e.to_string())?); + rest = &rest[cut..]; + } + if let Some(w) = want { + if out.len() < w { + return Err(format!("{} tokens, {w} wanted", out.len())); + } + out.truncate(w); + } + Ok(out) +} + +fn ids_from_json(v: &Value) -> Result<Vec<u32>, String> { + let arr = match v { + Value::Array(a) => a, + Value::Object(o) => o + .get("prompt_ids") + .or_else(|| o.get("ids")) + .and_then(Value::as_array) + .ok_or("no \"prompt_ids\" or \"ids\" array")?, + _ => return Err("not an array or object".into()), + }; + let ids = arr + .iter() + .map(|x| { + x.as_u64() + .and_then(|n| u32::try_from(n).ok()) + .ok_or_else(|| format!("id {x} is not a u32")) + }) + .collect::<Result<Vec<_>, _>>()?; + if ids.is_empty() { + return Err("no ids".into()); + } + Ok(ids) +} + +fn tokenizer<'a>(tk: &'a mut Option<ChatTokenizer>, dir: &Path) -> Result<&'a ChatTokenizer, String> { + if tk.is_none() { + *tk = Some(ChatTokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| e.to_string())?); + } + Ok(tk.as_ref().expect("set above")) +} + +fn load_prompt(tk: &mut Option<ChatTokenizer>, dir: &Path, spec: &str) -> Result<Prompt, String> { + let (name, s) = parse_spec(spec)?; + let read = |p: &Path| std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display())); + let ids = match &s { + Spec::Corpus(f, len) => tokenize(tokenizer(tk, dir)?, &read(f)?, Some(*len)), + Spec::Text(f) => tokenize(tokenizer(tk, dir)?, &read(f)?, None), + Spec::Ids(f) => serde_json::from_str::<Value>(&read(f)?) + .map_err(|e| e.to_string()) + .and_then(|v| ids_from_json(&v)), + } + .map_err(|e| format!("prompt {name}: {e}"))?; + Ok(Prompt { name, source: spec.to_string(), ids }) +} + +fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +fn ids_sha256(ids: &[u32]) -> String { + let b: Vec<u8> = ids.iter().flat_map(|t| t.to_le_bytes()).collect(); + sha256_hex(&b) +} + +fn logits_bytes(l: &[f32]) -> Vec<u8> { + l.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +/// The `k` largest finite logits, descending; a tie keeps the lower id first (the judge's order). +fn top_k(l: &[f32], k: usize) -> Vec<(u32, f32)> { + let mut t: Vec<(u32, f32)> = Vec::with_capacity(k + 1); + for (i, &x) in l.iter().enumerate() { + if !x.is_finite() || (t.len() == k && x <= t[k - 1].1) { + continue; + } + let p = t.iter().position(|e| x > e.1).unwrap_or(t.len()); + t.insert(p, (i as u32, x)); + t.truncate(k); + } + t +} + +/// Chunk sizes the bench hands the prefill: `chunk` each, the last one shorter; chunk 0 = one +/// token per step. +fn chunk_plan(n: usize, chunk: usize) -> Vec<usize> { + let c = chunk.max(1); + (0..n.div_ceil(c)).map(|i| c.min(n - i * c)).collect() +} + +/// The attention cache holds whole score passes of 256 positions (as the L369 gate). +fn max_pos_for(longest: usize) -> usize { + (longest + 1).next_multiple_of(256) +} + +struct Pass { + host_ms: f64, + chunk_host_ms: Vec<f64>, + streamed: Vec<u64>, + /// Per chunk: the device span (ns) or the timeline error. + chip_ns: Vec<Result<u64, String>>, + classes: BTreeMap<String, (u64, u64)>, + next: u32, + logits: Vec<f32>, +} + +fn one_pass(m: &mut Qwen38Omega, ids: &[u32], chunk: usize, stamps: bool) -> Result<Pass, String> { + m.reset_head(0)?; + m.set_stamps(stamps)?; + let plan = chunk_plan(ids.len(), chunk); + let mut p = Pass { + host_ms: 0.0, + chunk_host_ms: Vec::with_capacity(plan.len()), + streamed: Vec::with_capacity(plan.len()), + chip_ns: Vec::new(), + classes: BTreeMap::new(), + next: 0, + logits: Vec::new(), + }; + let t_all = Instant::now(); + let mut at = 0; + for (i, &len) in plan.iter().enumerate() { + let c = &ids[at..at + len]; + at += len; + let last = i + 1 == plan.len(); + let s0 = m.q36_prefill_streamed(); + let t = Instant::now(); + let r = if chunk == 0 { + m.step(c[0]).map(|(tok, _)| Some(tok)) + } else { + m.prefill_moe_head(0, c, chunk, last).map(|(tok, _)| tok) + }; + let ms = t.elapsed().as_secs_f64() * 1e3; + let tok = match r { + Ok(t) => t, + Err(e) => { + let _ = m.set_stamps(false); + return Err(e); + } + }; + p.chunk_host_ms.push(ms); + p.streamed.push(m.q36_prefill_streamed() - s0); + if stamps { + p.chip_ns.push(m.timeline().map(|tl| { + for (name, ns) in &tl { + let e = p.classes.entry(name.clone()).or_default(); + e.0 += ns; + e.1 += 1; + } + tl.iter().map(|e| e.1).sum() + })); + } + if last { + p.next = tok.ok_or("prefill gave no token")?; + } + } + p.host_ms = t_all.elapsed().as_secs_f64() * 1e3; + m.set_stamps(false)?; + p.logits = m.logits_head(0)?; + Ok(p) +} + +fn knobs() -> Value { + let mut o = serde_json::Map::new(); + for k in KNOBS { + o.insert((*k).into(), std::env::var(k).map(Value::from).unwrap_or(Value::Null)); + } + Value::Object(o) +} + +fn plan_record(p: &Prompt, chunk: usize) -> Value { + let plan = chunk_plan(p.ids.len(), chunk); + json!({ + "name": p.name, "source": p.source, "tokens": p.ids.len(), "ids_sha256": ids_sha256(&p.ids), + "chunk": chunk, "chunks": plan.len(), "chunk_sizes_first_last": [plan[0], plan[plan.len() - 1]], + "prompt_ids": p.ids, + }) +} + +fn bench_one(m: &mut Qwen38Omega, p: &Prompt, chunk: usize, reps: usize, dir: &Path) -> Result<Value, String> { + let n = p.ids.len(); + let mut passes = Vec::with_capacity(reps); + for r in 0..reps { + let ps = one_pass(m, &p.ids, chunk, false)?; + eprintln!("{} rep {r}: {:.1} ms host ({:.1} tok/s), next {}", p.name, ps.host_ms, n as f64 / (ps.host_ms / 1e3), ps.next); + passes.push(ps); + } + let stamped = if std::env::var("AIEN_BENCH_STAMPS").is_ok_and(|v| v == "0") { + None + } else { + Some(one_pass(m, &p.ids, chunk, true)?) + }; + let ref0 = &passes[0]; + let bits = |l: &[f32]| l.iter().map(|x| x.to_bits()).collect::<Vec<_>>(); + let b0 = bits(&ref0.logits); + let mut diff_reps: Vec<usize> = passes.iter().enumerate().skip(1).filter(|(_, q)| bits(&q.logits) != b0).map(|(i, _)| i).collect(); + if let Some(s) = &stamped { + if bits(&s.logits) != b0 { + diff_reps.push(reps); + } + } + let lb = logits_bytes(&ref0.logits); + let lpath = dir.join(format!("{}.logits.f32", p.name)); + std::fs::write(&lpath, &lb).map_err(|e| format!("{}: {e}", lpath.display()))?; + let host: Vec<f64> = passes.iter().map(|q| q.host_ms).collect(); + let mut sorted = host.clone(); + sorted.sort_by(f64::total_cmp); + let median = sorted[sorted.len() / 2]; + let streamed_total: u64 = ref0.streamed.iter().sum(); + let chip = stamped.as_ref().map(|s| { + let ok: Vec<u64> = s.chip_ns.iter().filter_map(|r| r.as_ref().ok().copied()).collect(); + let errs: Vec<String> = s.chip_ns.iter().filter_map(|r| r.as_ref().err().cloned()).collect(); + let complete = errs.is_empty(); + let ms: f64 = ok.iter().sum::<u64>() as f64 / 1e6; + let classes: BTreeMap<&String, Value> = s + .classes + .iter() + .map(|(k, (ns, c))| (k, json!({"ms": *ns as f64 / 1e6, "launches": c}))) + .collect(); + json!({ + "label": "CHIP_ONLY (GPU timestamps: device span per chunk incl. inter-list host gaps; not HTTP)", + "complete": complete, + "chip_only_ms": if complete { json!(ms) } else { Value::Null }, + "chip_only_tok_s": if complete { json!(n as f64 / (ms / 1e3)) } else { Value::Null }, + "chunk_chip_ms": s.chip_ns.iter().map(|r| r.as_ref().ok().map(|ns| *ns as f64 / 1e6)).collect::<Vec<_>>(), + "timeline_errors": errs.iter().take(4).collect::<Vec<_>>(), + "timeline_error_count": errs.len(), + "classes_ms": classes, + "stamped_host_ms": s.host_ms, + }) + }); + let top: Vec<Value> = top_k(&ref0.logits, TOP_K).iter().map(|(i, x)| json!([i, x])).collect(); + let rec = json!({ + "name": p.name, "source": p.source, "tokens": n, "ids_sha256": ids_sha256(&p.ids), + "chunk": chunk, "chunks": ref0.chunk_host_ms.len(), "reps": reps, + "next": ref0.next, "top_k": top, + "logits_file": lpath.file_name().map(|s| s.to_string_lossy().into_owned()), + "logits_sha256": sha256_hex(&lb), + "reps_bit_identical": diff_reps.is_empty(), "reps_differing": diff_reps, + "ttft_inproc_host": { + "label": "TTFT_INPROC_HOST (host clock around the whole prompt in this process; not HTTP, not chip-only)", + "ms": host, "median_ms": median, "median_tok_s": n as f64 / (median / 1e3), + "chunk_ms_rep0": ref0.chunk_host_ms, + }, + "streamed": { + "label": "fp8 GEMM weight bytes (omega_gpu_q36_graph_prefill_streamed deltas), rep 0", + "total_bytes": streamed_total, "bytes_per_token": streamed_total as f64 / n as f64, + "per_chunk_bytes": ref0.streamed, + }, + "chip": chip, + }); + std::fs::write(dir.join(format!("{}.json", p.name)), serde_json::to_string_pretty(&rec).map_err(|e| e.to_string())? + "\n") + .map_err(|e| format!("{}: {e}", p.name))?; + Ok(rec) +} + +fn run(args: &[String]) -> Result<bool, String> { + let plan_only = args.get(1).is_some_and(|a| a == "--plan"); + let a = &args[if plan_only { 2 } else { 1 }..]; + if a.len() < 5 { + return Err("usage: qwen36_prefill_bench [--plan] <checkpoint-dir> <arm> <out-dir> <reps> <prompt>...".into()); + } + let dir = Path::new(&a[0]); + let arm = &a[1]; + if arm.is_empty() || !arm.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { + return Err(format!("arm {arm}: [A-Za-z0-9_-]+")); + } + let out = Path::new(&a[2]).join(arm); + let reps: usize = a[3].parse().map_err(|e| format!("reps: {e}"))?; + if reps == 0 { + return Err("reps: at least 1".into()); + } + let chunk = q36_prefill_chunk()?; + let mut tk = None; + let prompts = a[4..].iter().map(|s| load_prompt(&mut tk, dir, s)).collect::<Result<Vec<_>, _>>()?; + let mut names: Vec<&str> = prompts.iter().map(|p| p.name.as_str()).collect(); + names.sort_unstable(); + if names.windows(2).any(|w| w[0] == w[1]) { + return Err("two prompts with one NAME".into()); + } + std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; + let longest = prompts.iter().map(|p| p.ids.len()).max().ok_or("no prompts")?; + let max_pos = max_pos_for(longest); + if plan_only { + for p in &prompts { + let r = plan_record(p, chunk); + eprintln!("plan {}: {} tokens, ids {}, chunk {chunk}, {} chunks", p.name, p.ids.len(), r["ids_sha256"], r["chunks"]); + std::fs::write(out.join(format!("{}.ids.json", p.name)), serde_json::to_string(&r).map_err(|e| e.to_string())? + "\n") + .map_err(|e| format!("{}: {e}", p.name))?; + } + eprintln!("plan: arm {arm}, max_pos {max_pos}, knobs {}", knobs()); + return Ok(true); + } + let full = aien_inference_abi::qwen38::Qwen38Config::from_checkpoint(dir)?; + let count = match std::env::var("AIEN_BENCH_LAYERS") { + Ok(l) => l.parse::<usize>().map_err(|e| format!("AIEN_BENCH_LAYERS: {e}"))?, + Err(_) => full.layers, + }; + let t = Instant::now(); + let mut m = Qwen38Omega::open_window(dir, 0, count, max_pos)?; + let load_s = t.elapsed().as_secs_f64(); + eprintln!("arm {arm}: loaded {count} layers in {load_s:.1} s, max_pos {max_pos}, chunk {chunk}"); + let mut runs = Vec::new(); + let mut all = true; + for p in &prompts { + let r = bench_one(&mut m, p, chunk, reps, &out)?; + all &= r["reps_bit_identical"].as_bool() == Some(true); + runs.push(r); + } + let rec = json!({ + "bench": "qwen36_prefill_bench", "arm": arm, "layers": count, "chunk": chunk, "max_pos": max_pos, + "load_s": load_s, "knobs": knobs(), "deterministic": all, "runs": runs, + }); + let path = out.join("bench.json"); + std::fs::write(&path, serde_json::to_string_pretty(&rec).map_err(|e| e.to_string())? + "\n") + .map_err(|e| format!("{}: {e}", path.display()))?; + eprintln!("BENCH {} arm {arm}", if all { "DONE" } else { "NONDETERMINISTIC" }); + Ok(all) +} + +fn main() { + let args: Vec<String> = std::env::args().collect(); + match run(&args) { + Ok(true) => {} + Ok(false) => std::process::exit(1), + Err(e) => { + eprintln!("qwen36_prefill_bench: {e}"); + std::process::exit(2); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chunk_plan_covers_the_prompt() { + assert_eq!(chunk_plan(300, 128), vec![128, 128, 44]); + assert_eq!(chunk_plan(256, 128), vec![128, 128]); + assert_eq!(chunk_plan(5, 0), vec![1; 5]); + assert_eq!(chunk_plan(8192, 8192), vec![8192]); + for n in 1..600 { + for c in [0, 1, 7, 128, 512] { + let p = chunk_plan(n, c); + assert_eq!(p.iter().sum::<usize>(), n); + assert!(p.iter().all(|&x| x >= 1 && x <= c.max(1))); + } + } + } + + #[test] + fn max_pos_rounds_to_score_passes() { + assert_eq!(max_pos_for(255), 256); + assert_eq!(max_pos_for(256), 512); + assert_eq!(max_pos_for(32768), 33024); + } + + #[test] + fn top_k_is_descending_lower_id_first_and_skips_nonfinite() { + let l = [1.0, 3.0, f32::NAN, 3.0, f32::INFINITY, 2.0, -1.0]; + assert_eq!(top_k(&l, 3), vec![(1, 3.0), (3, 3.0), (5, 2.0)]); + assert_eq!(top_k(&l, 16).len(), 5); + } + + #[test] + fn specs_parse_and_refuse() { + assert!(matches!(parse_spec("c2k=corpus:/a/b.txt:2048"), Ok((n, Spec::Corpus(_, 2048))) if n == "c2k")); + assert!(matches!(parse_spec("x=text:/a.txt"), Ok((_, Spec::Text(_))))); + assert!(matches!(parse_spec("x=ids:/a.json"), Ok((_, Spec::Ids(_))))); + for bad in ["x", "=corpus:a:1", "a/b=text:x", "x=corpus:a:0", "x=corpus:a", "x=pdf:a"] { + assert!(parse_spec(bad).is_err(), "{bad}"); + } + } + + #[test] + fn ids_json_forms() { + assert_eq!(ids_from_json(&json!([1, 2, 3])).unwrap(), vec![1, 2, 3]); + assert_eq!(ids_from_json(&json!({"prompt_ids": [7]})).unwrap(), vec![7]); + assert_eq!(ids_from_json(&json!({"ids": [8, 9]})).unwrap(), vec![8, 9]); + assert!(ids_from_json(&json!([])).is_err()); + assert!(ids_from_json(&json!([-1])).is_err()); + assert!(ids_from_json(&json!([4294967296u64])).is_err()); + assert!(ids_from_json(&json!({"x": [1]})).is_err()); + } + + #[test] + fn ids_sha_is_le_u32() { + // sha256 of the 4 bytes 01 00 00 00 + assert_eq!(ids_sha256(&[1]), sha256_hex(&[1, 0, 0, 0])); + assert_ne!(ids_sha256(&[1, 2]), ids_sha256(&[2, 1])); + } +} diff --git a/crates/aien-inference-abi/src/qwen38_omega.rs b/crates/aien-inference-abi/src/qwen38_omega.rs index 28ee17d8..650da74b 100644 --- a/crates/aien-inference-abi/src/qwen38_omega.rs +++ b/crates/aien-inference-abi/src/qwen38_omega.rs @@ -49,7 +49,7 @@ mod prefill; mod rows; pub use rows::{RowFeed, RowOut, RowTest}; mod session; -pub use prefill::PrefillStats; +pub use prefill::{q36_prefill_chunk, PrefillStats}; pub use session::{plan_reuse, FeedStats, Qwen38Session, Reuse, IM_START}; use crate::qwen38::{read_bf16_words, read_matrix, read_vec, text_prefix, Matrix, Qwen38Config}; diff --git a/om/prefill-logits/TOLERANCE.md b/om/prefill-logits/TOLERANCE.md new file mode 100644 index 00000000..b4f381d1 --- /dev/null +++ b/om/prefill-logits/TOLERANCE.md @@ -0,0 +1,52 @@ +# SC-PREFILL-LOGITS tolerance (P-DRA-4 Lane P G1, #877) + +Status: PROPOSED. TAU = 1.0 is enforced by `prefill-logits.om`, but it stays PROPOSED until two things +happen: the chip A/A arm (path A run twice: `A1`/`A2` in chip/PREFILLGATE/s01-g1-ab.sh) measures the +noise floor, and Drake approves the value (Hive is asking him). Until then a G1 PASS reads "PASS under +the PROPOSED tolerance". Chip runs are NOT_RUN. + +## What is compared +- Arm A is the legacy GEMV prefill (f32 activations, chunk 128). +- Arm B is the path under test, for example DRA-82 `AIEN_OMEGA_Q36_PF_QMMA=1`. +- Both arms read the same prompt ids. Each writes the last prompt token's logits as 248,320 LE f32 + (`qwen36_prefill_bench`, `NAME.logits.f32`). + +## Rule +PASS requires all three of: +1. Every value is finite in both files. +2. Top-1 agrees. B's top-1 equals A's top-1 (a tie goes to the lowest id), or A's own logit gap between + its top-1 and B's top-1 is below BAND = 0.1. BAND is the house `MARGIN_MIN`, written 2026-10-21 in + `qwen38_omega_full.rs` / `qwen36_stroke_gate.rs`, and is never derived from a run. +3. max |A − B| ≤ TAU = 1.0 logit, inclusive. + +The judge always reports these alongside the verdict: A's top-two margin, max |Δ| and its id, rms Δ, +top-16 overlap, nonfinite counts, TAU, and the flip gap. + +## Why these numbers (Wolfram, quoted) +- B quantizes GEMM input activations to e4m3 with one power-of-two scale per row per 128-column block. + The e4m3 unit roundoff is 2^-4: `N[2^-4, 6]` → 0.0625. The rms relative error of uniform rounding is + 2^-4/√6: `N[2^-4/Sqrt[6], 6]` → 0.0255155. +- That predicted 0.0255 agrees with Prefill's host measurement on a synthetic single GEMM (k 384): + rms|Δy|/rms|y| = 0.0261, and worst |y_B − y_A| = 0.053 of Σ|terms|. +- The maximum of 248,320 Gaussian deviations sits near √(2 ln V) σ: `N[Sqrt[2 Log[248320]], 6]` → + 4.98447. So TAU = 1.0 allows a per-logit noise σ up to about `N[1.0/Sqrt[2 Log[248320]], 6]` → 0.200623 + logit before the max alone trips it. +- A 1.0 logit shift changes a token's probability ratio by at most `N[Exp[2*1.0], 6]` → 7.38906 (both + ends move). TAU is therefore a numerical-fault screen, not a sampling-equivalence claim. +- File size check: `248320*4` → 993280. + +## Path B numerics (from Prefill, DRA-82, CUDApp 721826bd) +- e4m3 quantization uses RNE and saturates. The scale is `2^(ceil(log2 amax)-8)` per row per 128-column + block. +- QMMA accumulates in fp32 per 128-k block, then multiplies by act_scale·w_scale. +- This applies to the GDN/attention mix, o (multi-token only), and expert gate_up/down. A keeps f32 + activations. + +## Risks / open +- Logit-level B-vs-A error through 40 layers is unmeasured (NOT_RUN). The single-GEMM 2.6 % may grow + with depth. If the G1 chip slice shows max |Δ| > 1.0 together with a stable top-1, revisit TAU with + the A/A and A/B distributions. Do not adjust TAU after looking at the results. +- The A/A noise floor (two A runs) is a required arm of the G1 slice. A is expected to be bit-identical + run to run (`reps_bit_identical` in bench.json). If it is not, record that as a finding. +- One prompt checks only the last token. Mid-prompt errors show up only through state carried into + later chunks (GDN state, KV). diff --git a/om/prefill-logits/gate.sh b/om/prefill-logits/gate.sh new file mode 100755 index 00000000..ce1e17dc --- /dev/null +++ b/om/prefill-logits/gate.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# om/prefill-logits/gate.sh: SC-PREFILL-LOGITS, the G1 logits judge of P-DRA-4 Lane P +# (aien-dev/aien-sovereign-core-mv#877, Linear P-DRA-4 Lane P G1; DRA-82/DRA-83). Builds om/prefill-logits/prefill-logits.om +# with the pinned seeded omc and runs it on synthetic fixtures (om/prefill-logits/mkfix.py, test equipment): +# 1. same identical pair must exit 0, verdict PASS, max_abs_d_u 0; +# 2. noise ref + N(0, 0.05) must exit 0, verdict PASS (bound not over-strict); +# 3. edge one logit |d| = 1.0 exactly = TAU must exit 0, verdict PASS (TAU inclusive); +# 4. over one logit |d| = 1.0 + 2^-23 must exit 1, verdict FAIL (red mutant, top-1 kept); +# 5. flip top-1 flips, A gap 0.2 > BAND 0.1 must exit 1, verdict FAIL; +# 5b. tie top-1 flips, A gap 0.05 < BAND 0.1 must exit 0, verdict PASS (written near-tie band); +# 6. nan one NaN in B must exit 1, verdict FAIL, nonfinite_b 1; +# 7. other a different prompt's logits must exit 1, verdict FAIL (negative control); +# 8. short 993276-byte file must exit 3 (io); +# 9. tau0 judge rebuilt with TAU 0.0 (source mutant): noise must turn FAIL, same must stay PASS; +# 10. band0 judge rebuilt with BAND 0.0 (source mutant): tie must turn FAIL. +# With two arguments (gate.sh A.f32 B.f32) the self-test runs first and must pass; then the real pair is +# judged and its verdict is the gate's verdict. +# The shell only sequences; every judgment about the logits is made by the .om program. +# Compiler: AIEN_OMC (OMC and OMEGA_OMC are accepted too) must hash to omega.pin, else NOT_RUN; +# python3 (fixtures only) missing is NOT_RUN. +# Exit 0 PASS, 1 FAIL, 77 NOT_RUN (with an AIEN-OBS not_run_reason line). +set -u +here=$(cd "$(dirname "$0")" && pwd) +obs() { printf 'AIEN-OBS %s %s\n' "$1" "$2"; } +not_run() { echo "prefill-logits gate: NOT_RUN $1: $2" >&2; obs not_run_reason "\"$1\""; exit 77; } + +[ $# = 0 ] || [ $# = 2 ] || { echo "usage: gate.sh [A.f32 B.f32]" >&2; exit 2; } +omc=${AIEN_OMC:-${OMC:-${OMEGA_OMC:-}}} +[ -n "$omc" ] || not_run omc_missing "set AIEN_OMC to omega-mv seed/out/omc at the commit in om/prefill-logits/omega.pin" +[ -x "$omc" ] || not_run omc_missing "$omc is not executable" +pin=$(sed -n 's/^omc_sha256: //p' "$here/omega.pin") +got=$(sha256sum < "$omc" | cut -d' ' -f1) +[ "$got" = "$pin" ] || not_run omc_unpinned "omc sha256 $got, pinned $pin" +command -v python3 > /dev/null || not_run python3_missing "fixtures need python3" + +b=$(mktemp -d) +trap 'rm -rf "$b"' EXIT +build() { # source out + { printf 'om2\n'; cat "$1"; } | "$omc" > "$2" 2> "$2.err" || { echo "FAIL compile $1: $(cat "$2.err")"; exit 1; } + chmod 700 "$2" +} +build "$here/prefill-logits.om" "$b/pl" +sed 's/^ret 1\.0f64$/ret 0.0f64/' "$here/prefill-logits.om" > "$b/tau0.om" +cmp -s "$here/prefill-logits.om" "$b/tau0.om" && { echo "FAIL tau0: source mutant did not apply"; exit 1; } +build "$b/tau0.om" "$b/pl0" +sed 's/^ret 0\.1f64$/ret 0.0f64/' "$here/prefill-logits.om" > "$b/band0.om" +cmp -s "$here/prefill-logits.om" "$b/band0.om" && { echo "FAIL band0: source mutant did not apply"; exit 1; } +build "$b/band0.om" "$b/plb0" +obs omc_sha256 "\"$got\"" +obs check_sha256 "\"$(sha256sum < "$b/pl" | cut -d' ' -f1)\"" +python3 "$here/mkfix.py" "$b" || { echo "FAIL fixtures"; exit 1; } + +fail=0 +line= +arm() { # name judge A B want_rc want_verdict [required substring] + line=$(timeout 120 "$2" "$3" "$4" 2>&1 < /dev/null) + rc=$? + echo "$line" + if [ "$rc" = "$5" ] && { [ "$6" = - ] || [[ $line == "prefill-logits verdict $6 "* ]]; } \ + && { [ -z "${7:-}" ] || [[ "$line " == *" $7 "* ]]; }; then + echo "ok $1: exit $rc, verdict $6${7:+, $7}" + return 0 + fi + echo "FAIL $1: exit $rc, want $5 and verdict $6${7:+ and $7}" + fail=1 + return 1 +} +f=$b +arm same "$b/pl" "$f/ref.f32" "$f/same.f32" 0 PASS "max_abs_d_u 0" +arm noise "$b/pl" "$f/ref.f32" "$f/noise.f32" 0 PASS "top1_b 1234" +arm edge "$b/pl" "$f/ref.f32" "$f/edge.f32" 0 PASS "max_abs_d_u 1000000" +arm over "$b/pl" "$f/ref.f32" "$f/over.f32" 1 FAIL "max_at 5000" +arm flip "$b/pl" "$f/refc.f32" "$f/flipc.f32" 1 FAIL "top1_b 77" +arm tie "$b/pl" "$f/refn.f32" "$f/flipn.f32" 0 PASS "flip_gap_a_u 62500" +arm nan "$b/pl" "$f/ref.f32" "$f/nan.f32" 1 FAIL "nonfinite_b 1" +arm other "$b/pl" "$f/ref.f32" "$f/other.f32" 1 FAIL "top1_b 42" +arm short "$b/pl" "$f/ref.f32" "$f/short.f32" 3 - +arm tau0-noise "$b/pl0" "$f/ref.f32" "$f/noise.f32" 1 FAIL "tau_u 0" +arm tau0-same "$b/pl0" "$f/ref.f32" "$f/same.f32" 0 PASS "tau_u 0" +arm band0-tie "$b/plb0" "$f/refn.f32" "$f/flipn.f32" 1 FAIL "top1_b 77" +if [ "$fail" != 0 ]; then obs verdict '"FAIL"'; echo "SC-PREFILL-LOGITS FAIL (self-test)"; exit 1; fi +echo "SC-PREFILL-LOGITS self-test PASS (12 arms)" + +if [ $# = 2 ]; then + obs a_sha256 "\"$(sha256sum < "$1" | cut -d' ' -f1)\"" + obs b_sha256 "\"$(sha256sum < "$2" | cut -d' ' -f1)\"" + line=$(timeout 120 "$b/pl" "$1" "$2" 2>&1 < /dev/null) + rc=$? + echo "$line" + obs judge_rc "$rc" + if [ "$rc" = 0 ]; then obs verdict '"PASS"'; echo "SC-PREFILL-LOGITS PASS"; exit 0; fi + obs verdict '"FAIL"' + echo "SC-PREFILL-LOGITS FAIL (judge exit $rc)" + exit 1 +fi +obs verdict '"PASS"' +echo "SC-PREFILL-LOGITS PASS" +exit 0 diff --git a/om/prefill-logits/mkfix.py b/om/prefill-logits/mkfix.py new file mode 100755 index 00000000..823d5d26 --- /dev/null +++ b/om/prefill-logits/mkfix.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Test equipment for om/prefill-logits/gate.sh: writes the synthetic logits fixtures. + +Every file is 248320 little-endian binary32 values (993280 bytes), the layout qwen36_prefill_bench +writes for the last prompt token. Deterministic (fixed seeds); the judgment itself is made by +prefill-logits.om, never here. + + ref.f32 A: N(0, 2) background, top-1 id 1234 = 25.0, top-2 id 77 = 22.0, id 5000 = 0.5 + same.f32 copy of ref -> PASS, max 0 + noise.f32 ref + N(0, 0.05) on every id -> PASS (green: the bound is not over-strict) + edge.f32 ref with id 5000 = 1.5 (|d| = 1.0 exactly = TAU) -> PASS (TAU is inclusive) + over.f32 ref with id 5000 = nextafter(1.5, +inf) -> FAIL (red mutant: one logit past TAU) + refc.f32 ref with id 77 = 24.8 (close margin 0.2) + flipc.f32 refc with id 1234 = 24.7, id 77 = 24.9 -> FAIL vs refc (top-1 flips, max |d| 0.3) + refn.f32 ref with id 77 = 24.9375 (near tie, gap 1/16 below the 0.1 band) + flipn.f32 refn with id 1234 = 24.9375, id 77 = 25.0 -> PASS vs refn (flip inside the band) + nan.f32 ref with id 9 = NaN -> FAIL (nonfinite) + other.f32 independent N(0, 2), top-1 id 42 = 25.0 -> FAIL (different prompt) + short.f32 ref minus its last value (993276 bytes) -> exit 3 (size) +""" +import random +import struct +import sys + +NV = 248320 + + +def background(seed): + rng = random.Random(seed) + return [rng.gauss(0.0, 2.0) for _ in range(NV)] + + +def f32(x): + return struct.unpack("<f", struct.pack("<f", x))[0] + + +def write(path, vals, drop_last=False): + if drop_last: + vals = vals[:-1] + with open(path, "wb") as f: + f.write(struct.pack("<%df" % len(vals), *vals)) + + +def main(out): + ref = background(1) + ref[1234] = 25.0 + ref[77] = 22.0 + ref[5000] = 0.5 + ref = [f32(v) for v in ref] + write(f"{out}/ref.f32", ref) + write(f"{out}/same.f32", ref) + + rng = random.Random(3) + write(f"{out}/noise.f32", [v + rng.gauss(0.0, 0.05) for v in ref]) + + edge = list(ref) + edge[5000] = 1.5 + write(f"{out}/edge.f32", edge) + over = list(ref) + over[5000] = struct.unpack("<f", struct.pack("<I", struct.unpack("<I", struct.pack("<f", 1.5))[0] + 1))[0] + write(f"{out}/over.f32", over) + + refc = list(ref) + refc[77] = 24.8 + write(f"{out}/refc.f32", refc) + flipc = list(refc) + flipc[1234] = 24.7 + flipc[77] = 24.9 + write(f"{out}/flipc.f32", flipc) + refn = list(ref) + refn[77] = 24.9375 + write(f"{out}/refn.f32", refn) + flipn = list(refn) + flipn[1234] = 24.9375 + flipn[77] = 25.0 + write(f"{out}/flipn.f32", flipn) + + nan = list(ref) + nan[9] = float("nan") + write(f"{out}/nan.f32", nan) + + other = background(2) + other[42] = 25.0 + write(f"{out}/other.f32", other) + + write(f"{out}/short.f32", ref, drop_last=True) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/om/prefill-logits/omega.pin b/om/prefill-logits/omega.pin new file mode 100644 index 00000000..f8cca0fc --- /dev/null +++ b/om/prefill-logits/omega.pin @@ -0,0 +1,5 @@ +repo: aien-dev/omega-mv +commit: 0b77e6ea294aa3d69ccbdb86b9c14d133abea689 +omc_sha256: 2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f +seed0_hex_sha256: baaf081fe6055a768485c5d25d7435681ce00b04cfa80b26c48169f78944e14d +omc_om_sha256: 7703da00055fc0c7a91fcae43071df76a3f277dbe867cb284a3bdff3bedb7e1b diff --git a/om/prefill-logits/prefill-logits.om b/om/prefill-logits/prefill-logits.om new file mode 100644 index 00000000..06c4c577 --- /dev/null +++ b/om/prefill-logits/prefill-logits.om @@ -0,0 +1,369 @@ +note om/prefill-logits/prefill-logits.om: G1 last-token logits judge for Qwen3.6-35B prefill (P-DRA-4). +note Usage: prefill-logits A.f32 B.f32. Each file is the last prompt token's logits as written by +note qwen36_prefill_bench: 248320 little-endian IEEE binary32 values, exactly 993280 bytes. +note A is the reference arm (legacy GEMV prefill, chunk 128), B the candidate arm (env-gated new path). +note Written tolerance (om/prefill-logits/TOLERANCE.md): PASS iff +note every value of A and B is finite, and +note top-1 of A equals top-1 of B (lowest id wins a tie), and +note max over the vocabulary of |A[i] - B[i]| (computed in binary64) is at most TAU = 1.0 logit. +note Reported, not judged: A's top-1 minus top-2 margin, the RMS difference, the top-16 id overlap. +note Values printed with suffix _u are micro-logits (value * 1e6, truncated, capped at 1e12). +note Exit 0 PASS, 1 FAIL, 2 usage, 3 io (missing file, not regular, size not 993280, short read). +note Build: { printf 'om2\n'; cat om/prefill-logits/prefill-logits.om; } | "$AIEN_OMC" > prefill-logits + +const nv ulong 248320 +const nbyte ulong 993280 +const kop ulong 0 +const knfa ulong 1 +const knfb ulong 2 +const kmi ulong 3 +const kmx ulong 4 +const kss ulong 5 +const kca ulong 6 + +global ga uchar 8192 +global gas ulong 4 +global gal ulong 4 +global gpth uchar 4352 +global gstb uchar 128 +global la uchar 993280 +global lb uchar 993280 +global tk ulong 32 +global gst ulong 16 +global gob uchar 2048 +global gdg uchar 32 + +text tref "prefill-logits error " +text tusage "usage: prefill-logits A.f32 B.f32" +text tio "io" +text tnreg "not a regular file" +text tsize "size is not 993280 bytes" +text thead "prefill-logits verdict " +text tpass "PASS" +text tfail "FAIL" +text o1 "top1_a" +text o2 "top1_b" +text o3 "margin_a_u" +text o4 "max_abs_d_u" +text o5 "max_at" +text o6 "rms_d_u" +text o7 "top16_overlap" +text o8 "nonfinite_a" +text o9 "nonfinite_b" +text o10 "tau_u" +text o11 "flip_gap_a_u" + +note TAU in logits; the justification and the Wolfram figures are in TOLERANCE.md +fn pl_tau to f64 +ret 1.0f64 +end + +note BAND in logits: a top-1 flip is allowed when A's own logit gap between its top-1 and B's top-1 is +note below it (the house MARGIN_MIN, qwen38_omega_full.rs, written 2026-10-21, never from the run) +fn pl_band to f64 +ret 0.1f64 +end + +note ======== output ======== + +fn pl_dec v ulong to ulong +n = ulong 0 +x = v +while true bound 25 +put gdg n add 48 uchar rem x 10 +n = add n 1 +x = div x 10 +if eq x 0 +break +end +end +ret n +end + +fn pl_ob c uchar to void +p = get gst kop +if lt p len gob +put gob p c +put gst kop add p 1 +end +end + +fn pl_otx t view uchar * to void +for i ulong len t +pl_ob get t i +end +end + +fn pl_ou v ulong to void +n = pl_dec v +for i ulong n +pl_ob get gdg sub sub n i 1 +end +end + +fn pl_kv t view uchar * v ulong to void +pl_ob 32 +pl_otx t +pl_ob 32 +pl_ou v +end + +note pl_mu: |v| as micro-logits, truncated toward zero, capped at 1e12; NaN prints the cap +fn pl_mu v f64 to ulong +x = fabs v +if not le x 1000000.0f64 +ret 1000000000000 +end +ret ulong mul x 1000000.0f64 +end + +fn pl_oflush fd int to void +o = ulong 0 +m = get gst kop +while lt o m bound 4096 +w = write fd gob o sub m o +if le w 0 +exit 3 +end +o = add o ulong w +end +put gst kop 0 +end + +fn pl_die c ulong t view uchar * to void +put gst kop 0 +pl_otx tref +pl_ou c +pl_ob 32 +pl_otx t +pl_ob 10 +pl_oflush 2 +exit int c +end + +note ======== files ======== + +fn pl_le64 o ulong to ulong +v = ulong 0 +for i ulong 8 +v = or v shl ulong get gstb add o i mul 8 i +end +ret v +end + +note pl_argp: copy argument a into gpth; its length +fn pl_argp a ulong to ulong +n = get gal a +if or eq n 0 gt n 4000 +pl_die 2 tusage +end +o = get gas a +for i ulong n +put gpth i get ga add o i +end +ret n +end + +note pl_open: open argument a with O_RDONLY | O_CLOEXEC | O_NOFOLLOW (arm64 557056), require a regular +note file (st_mode & S_IFMT 61440 == S_IFREG 32768) of exactly nbyte bytes +fn pl_open a ulong to long +n = pl_argp a +fd = fopen gpth 0 n 557056 0 +if lt fd 0 +if eq fd -40 +pl_die 3 tnreg +end +pl_die 3 tio +end +r = fstat int fd gstb 0 128 +if ne r 0 +pl_die 3 tio +end +md = or ulong get gstb 16 shl ulong get gstb 17 8 +if ne and md 61440 32768 +pl_die 3 tnreg +end +if ne pl_le64 48 nbyte +pl_die 3 tsize +end +ret fd +end + +fn pl_close fd long to void +r = fclose int fd +if ne r 0 +pl_die 3 tio +end +end + +note pl_load: argument 1 into la, argument 2 into lb; every pass adds at least one byte (r > 0), so +note at most nbyte passes, below the 999999 bound +fn pl_load w ulong to void +fd = pl_open add w 1 +o = ulong 0 +while lt o nbyte bound 999999 +r = long 0 +if eq w 0 +r = pread int fd la o sub nbyte o long o +else +r = pread int fd lb o sub nbyte o long o +end +if le r 0 +pl_die 3 tio +end +o = add o ulong r +end +pl_close fd +end + +note ======== values ======== + +note pl_bits: raw binary32 bits of value i of arm w (0 = A, 1 = B) +fn pl_bits w ulong i ulong to uint +o = mul i 4 +u = uint 0 +if eq w 0 +u = or uint get la o shl uint get la add o 1 8 +u = or u shl uint get la add o 2 16 +u = or u shl uint get la add o 3 24 +else +u = or uint get lb o shl uint get lb add o 1 8 +u = or u shl uint get lb add o 2 16 +u = or u shl uint get lb add o 3 24 +end +ret u +end + +fn pl_val w ulong i ulong to f64 +ret f64 bitcast f32 pl_bits w i +end + +note pl_fin: exponent field not all ones (not Inf, not NaN) +fn pl_fin w ulong i ulong to bool +ret ne and shr pl_bits w i 23 255 255 +end + +note pl_ins: insert id i into arm w's descending top-16 list tk[16w .. 16w+16) holding n ids; +note strict greater-than keeps the lower id ahead on a tie +fn pl_ins w ulong i ulong n ulong to void +x = pl_val w i +b = mul w 16 +p = n +if ge n 16 +if not gt x pl_val w get tk add b 15 +ret +end +p = ulong 15 +end +while gt p 0 bound 16 +q = sub p 1 +if not gt x pl_val w get tk add b q +break +end +put tk add b p get tk add b q +p = q +end +put tk add b p i +end + +note pl_take: count a nonfinite value of arm w, or insert a finite one into its top-16 list; a NaN never +note enters the list (it compares false and would pin the ids below it) +fn pl_take w ulong i ulong to void +if not pl_fin w i +put gst add knfa w add get gst add knfa w 1 +ret +end +n = get gst add kca w +pl_ins w i n +if lt n 16 +put gst add kca w add n 1 +end +end + +note ======== judge ======== + +note pl_args: argv[0 .. 3) into ga +fn pl_args to void +c = argcnt +if ne c 3 +pl_die 2 tusage +end +o = ulong 0 +for i ulong 3 +r = argread i ga o sub len ga o +if lt r 0 +pl_die 2 tusage +end +put gas i o +put gal i ulong r +o = add o ulong r +end +end + +note pl_scan: one pass over the vocabulary; leaves the max |A - B| bits in gst kmx, its id in kmi, +note the sum of squared differences bits in kss, nonfinite counts in knfa / knfb, top-16 lists in tk +fn pl_scan to void +mx = 0.0f64 +ss = 0.0f64 +for i ulong nv +pl_take 0 i +pl_take 1 i +d = fabs sub pl_val 0 i pl_val 1 i +if gt d mx +mx = d +put gst kmi i +end +ss = add ss mul d d +end +put gst kmx bitcast ulong mx +put gst kss bitcast ulong ss +end + +fn pl_ovl to ulong +ov = ulong 0 +for j ulong 16 +for k ulong 16 +if eq get tk j get tk add 16 k +ov = add ov 1 +end +end +end +ret ov +end + +fn main to int +pl_args +pl_load 0 +pl_load 1 +pl_scan +mx = bitcast f64 get gst kmx +a1 = get tk 0 +b1 = get tk 16 +gap = sub pl_val 0 a1 pl_val 0 b1 +agree = or eq a1 b1 lt gap pl_band +ok = and and eq get gst knfa 0 eq get gst knfb 0 and agree le mx pl_tau +put gst kop 0 +pl_otx thead +if ok +pl_otx tpass +else +pl_otx tfail +end +pl_kv o1 a1 +pl_kv o2 b1 +pl_kv o3 pl_mu sub pl_val 0 a1 pl_val 0 get tk 1 +pl_kv o4 pl_mu mx +pl_kv o5 get gst kmi +pl_kv o6 pl_mu fsqrt div bitcast f64 get gst kss f64 nv +pl_kv o7 pl_ovl +pl_kv o8 get gst knfa +pl_kv o9 get gst knfb +pl_kv o10 pl_mu pl_tau +pl_kv o11 pl_mu gap +pl_ob 10 +pl_oflush 1 +if ok +ret 0 +end +ret 1 +end diff --git a/scripts/prefill-ttft-http.py b/scripts/prefill-ttft-http.py new file mode 100755 index 00000000..29de0747 --- /dev/null +++ b/scripts/prefill-ttft-http.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""HTTP TTFT / ITL client for the door (P-DRA-4 Lane P, #877). Test equipment, not product code. + +Every number this prints is labelled HTTP: wall clock at the client, measured from just before the request +is sent. That clock includes the door, the tokenizer, queueing and the network. Never put it next to the +bench's CHIP_ONLY or TTFT_INPROC_HOST clocks. + + prefill-ttft-http.py ttft URL MODEL PROMPT_FILE [--runs N] [--max-tokens K] [--out J] + prefill-ttft-http.py probe URL MODEL LONG_FILE SHORT_FILE [--max-tokens K] [--out J] + +ttft streams /v1/chat/completions (stream, temperature 0, enable_thinking false) N times. Per run it +reports the time to the first content delta, the time to the first byte, the gaps between later content +deltas (ITL), and the server's usage when it is sent. +probe first starts a short decode stream (SHORT_FILE). Once that stream's first content arrives it sends +the long prompt (LONG_FILE) on a second connection. It then reports the short stream's ITL before the +long request was sent, during the long request's prefill (send to first content), and after that. This +measures how much a long read stalls a concurrent decode. +Exit 0 ok, 2 usage/error. +""" +import argparse, json, statistics, sys, threading, time, urllib.request + +LABEL = "HTTP" + + +def stream(url, model, prompt, max_tokens, t0=None, on_first=None): + """Return dict with t_send, first_byte_s, content times (s since t0), text, usage; on_first() fires at the first content.""" + body = json.dumps({ + "model": model, "stream": True, "temperature": 0, "max_tokens": max_tokens, + "messages": [{"role": "user", "content": prompt}], + "chat_template_kwargs": {"enable_thinking": False}, + "stream_options": {"include_usage": True}, + }).encode() + req = urllib.request.Request(url.rstrip("/") + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + t0 = time.monotonic() if t0 is None else t0 + out = {"t_send": time.monotonic() - t0, "first_byte_s": None, "content_t": [], "text": "", "usage": None} + with urllib.request.urlopen(req, timeout=3600) as r: + for raw in r: + now = time.monotonic() - t0 + if out["first_byte_s"] is None: + out["first_byte_s"] = now + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + break + ev = json.loads(data) + if ev.get("usage"): + out["usage"] = ev["usage"] + for ch in ev.get("choices") or []: + piece = (ch.get("delta") or {}).get("content") + if piece: + if not out["content_t"] and on_first: + on_first() + out["content_t"].append(now) + out["text"] += piece + return out + + +def gaps(ts): + return [b - a for a, b in zip(ts, ts[1:])] + + +def summ(xs): + if not xs: + return {"n": 0} + return {"n": len(xs), "median_ms": statistics.median(xs) * 1e3, "max_ms": max(xs) * 1e3, + "mean_ms": statistics.fmean(xs) * 1e3} + + +def cmd_ttft(a): + prompt = open(a.prompt, encoding="utf-8").read() + runs = [] + for i in range(a.runs): + s = stream(a.url, a.model, prompt, a.max_tokens) + if not s["content_t"]: + raise SystemExit(f"run {i}: no content delta") + ttft = s["content_t"][0] - s["t_send"] + runs.append({"ttft_ms": ttft * 1e3, "first_byte_ms": (s["first_byte_s"] - s["t_send"]) * 1e3, + "itl": summ(gaps(s["content_t"])), "usage": s["usage"], "text_head": s["text"][:80]}) + print(f"{LABEL} run {i}: ttft_ms {ttft * 1e3:.1f} itl_median_ms {runs[-1]['itl'].get('median_ms', 0):.2f}" + f" prompt_tokens {(s['usage'] or {}).get('prompt_tokens', '-')}") + t = [r["ttft_ms"] for r in runs] + res = {"label": LABEL, "clock": "client wall, send to first content delta", "url": a.url, + "prompt_file": a.prompt, "runs": runs, "ttft_median_ms": statistics.median(t)} + print(f"{LABEL} ttft_median_ms {res['ttft_median_ms']:.1f} over {len(t)} runs") + return res + + +def cmd_probe(a): + long_p = open(a.long, encoding="utf-8").read() + short_p = open(a.short, encoding="utf-8").read() + t0 = time.monotonic() + box, err = {}, [] + started = threading.Event() + + def short_run(): + try: + box["short"] = stream(a.url, a.model, short_p, a.max_tokens, t0, started.set) + except Exception as e: # reported below + err.append(repr(e)) + finally: + started.set() + + th = threading.Thread(target=short_run) + th.start() + started.wait() + time.sleep(a.lead_s) # a few decode gaps before the long request, for the "before" phase + lng = stream(a.url, a.model, long_p, 1, t0) + th.join() + if err or "short" not in box: + raise SystemExit(f"short stream failed: {err}") + s = box["short"] + send, first = lng["t_send"], (lng["content_t"] or [lng["first_byte_s"]])[0] + ct = s["content_t"] + phase = {"before": [], "during": [], "after": []} + for a_t, b_t in zip(ct, ct[1:]): + key = "before" if b_t <= send else ("during" if a_t < first else "after") + phase[key].append(b_t - a_t) + res = {"label": LABEL, "clock": "client wall", "long_send_s": send, "long_first_content_s": first, + "long_ttft_ms": (first - send) * 1e3, "short_itl": {k: summ(v) for k, v in phase.items()}, + "short_tokens": len(ct)} + print(f"{LABEL} probe long_ttft_ms {res['long_ttft_ms']:.1f} short_itl_median_ms before " + f"{res['short_itl']['before'].get('median_ms', float('nan')):.2f} during " + f"{res['short_itl']['during'].get('median_ms', float('nan')):.2f} max_during " + f"{res['short_itl']['during'].get('max_ms', float('nan')):.2f}") + return res + + +def main(): + p = argparse.ArgumentParser() + sp = p.add_subparsers(dest="cmd", required=True) + t = sp.add_parser("ttft") + t.add_argument("url"); t.add_argument("model"); t.add_argument("prompt") + t.add_argument("--runs", type=int, default=3); t.add_argument("--max-tokens", type=int, default=16) + t.add_argument("--out") + q = sp.add_parser("probe") + q.add_argument("url"); q.add_argument("model"); q.add_argument("long"); q.add_argument("short") + q.add_argument("--max-tokens", type=int, default=256); q.add_argument("--lead-s", type=float, default=1.0) + q.add_argument("--out") + a = p.parse_args() + try: + res = cmd_ttft(a) if a.cmd == "ttft" else cmd_probe(a) + except (OSError, ValueError, SystemExit) as e: + print(f"prefill-ttft-http: error {e}", file=sys.stderr) + return 2 + if a.out: + with open(a.out, "w") as f: + json.dump(res, f, indent=1) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gates/run.sh b/tests/gates/run.sh index 2b78d219..0e2847db 100755 --- a/tests/gates/run.sh +++ b/tests/gates/run.sh @@ -178,6 +178,9 @@ case "$step" in # No hosted mirror (the checkpoint is host-only). SC-EXPERT-BYTES (DRA-63, #855): per-expert bytes of the # Qwen3.6-35B-A3B-FP8 headers, layers 0-39, by seeded Omega; width 768 and FP32 scales must go red. expert-bytes) bash om/expert-bytes/gate.sh ;; + # SC-PREFILL-LOGITS (#877, P-DRA-4 Lane P G1): the seeded-Omega last-token logits judge, self-test arms plus + # TAU-0 and BAND-0 source mutants on synthetic fixtures; a real A/B pair is judged by gate.sh A.f32 B.f32. + prefill-logits) bash om/prefill-logits/gate.sh ;; # hardening.yml kv-props) cargo fetch --manifest-path crates/aien-replay/Cargo.toml diff --git a/tests/gates/sc-prefill-logits.gate b/tests/gates/sc-prefill-logits.gate new file mode 100644 index 00000000..1dacf3e4 --- /dev/null +++ b/tests/gates/sc-prefill-logits.gate @@ -0,0 +1,24 @@ +# tests/gates/sc-prefill-logits.gate +# No hosted mirror: the pinned omc lives on the host. P-DRA-4 Lane P G1 (aien-dev/aien-sovereign-core-mv#877): +# om/prefill-logits/prefill-logits.om, built with the omc pinned in om/prefill-logits/omega.pin, judges two +# last-token logit files (248320 LE f32 = 993,280 B): PASS iff all finite, top-1 identical (or a flip whose +# reference gap is below the 0.1 MARGIN_MIN band) and max |dlogit| <= TAU 1.0 (PROPOSED; om/prefill-logits/TOLERANCE.md). +# The self-test runs 12 arms on synthetic fixtures, including a different-prompt negative control and the TAU 0 +# and BAND 0 source mutants, which must go red. AIEN_OMC unset or not the pinned omc is NOT_RUN (exit 77). +gate: SC-PREFILL-LOGITS +manifest_version: 2 +owner: aien-sovereign-core +requires: + - host +inputs: + - om/prefill-logits/ + - tests/gates/ +run: + exec: tests/gates/run.sh + args: ["prefill-logits"] +expects: + exit: 0 + verdict: PASS +timeout: 5m +exactness: EXACT +cache_scope: machine