aien-dev has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
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#211 (code only)
Apply it
git checkout -b patch-d43da96cb9d8baea 28b047a6b66843a795649d1221402c6736989bc1 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/d43da96cb9d8baea.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
211
fd47ffa51097a281ee7247d4901f2c9ad371a23b
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":211,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/211","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:19Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 9e40a9cb..da0b5ca6 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:10d81c6270915316b54eee21734bb8e8f2716ffdc567100fb347a5f22ed95e24", - "compiled_at": "2026-10-05T04:36:19Z", + "compiled_at": "2026-10-05T05:02:22Z", "compiler": "crumb-compile/1", - "digest": "sha256:d793b5a5a403590e612f709eb322486735e403c1755a3c93ac163a66ec2029c3", + "digest": "sha256:7714b9bdd20b3f93c0bf33526dff84fcfb18b051966dd0e1a9ae93a3c481dbd4", "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", - "files": 685, - "generated_at_commit": "4f97cadc8f661c40858815d4cd6a956a540ac196", - "source_tree": "sha256:3342460d0f8adc9e041a77fc43a1af9f31c6383ae3ab0cbbd412175d20548900" + "files": 686, + "generated_at_commit": "151319dc4113e110ffeae129dce9aa20cc8000b2", + "source_tree": "sha256:be5a847713c2d044b78674f68eaf505f5fb1c3707f6201f10086244379693db9" } }, "history": [], diff --git a/crates/aien-inference-abi/tests/omega_backend_parity.rs b/crates/aien-inference-abi/tests/omega_backend_parity.rs index a1ab2991..9f0e7bfb 100644 --- a/crates/aien-inference-abi/tests/omega_backend_parity.rs +++ b/crates/aien-inference-abi/tests/omega_backend_parity.rs @@ -323,3 +323,50 @@ fn chip_attention_parity_on_tinyllama_shapes() { assert_eq!(omega.chip_errors(), 0, "{}", omega.last_error()); println!("PARITY attention {}", omega.op_report().line()); } + +/// Negative control on the chip build: an attention geometry the native engine does not +/// support (head_dim 32; omega refuses head_dim != 64 with OMEGA_GPU_ATTN_TOO_LARGE in +/// src/omega_gpu_attention_api.c before any launch) goes through the native library, is +/// refused there, and in a strict process the refusal is fatal: no CPU answer appears behind +/// the GPU backend. In a dev process it is a counted fallback. This is a library refusal, not +/// an injected device fault; a device fault takes the same `fail` -> `reference_path` route. +#[test] +#[ignore = "chip test: needs a native build and the GB10; run through the heavy queue"] +fn chip_unsupported_attention_is_refused() { + let omega = OmegaGb10Backend::new(); + assert!(omega.is_available(), "native build required"); + let (nq, nkv, hd, seq) = (4usize, 2usize, 32usize, 3usize); + let mut seed = 99u32; + let q: Vec<f32> = (0..nq * hd).map(|_| lcg(&mut seed)).collect(); + let k: Vec<f32> = (0..seq * nkv * hd).map(|_| lcg(&mut seed)).collect(); + let v: Vec<f32> = (0..seq * nkv * hd).map(|_| lcg(&mut seed)).collect(); + let mut out = vec![0.0f32; nq * hd]; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + omega.gqa_attention(&mut out, &q, &k, &v, seq, nq, nkv, hd) + })); + println!( + "NEGATIVE unsupported head_dim={hd}: chip_errors={} fallback_count={} last_error={:?} strict={}", + omega.chip_errors(), + omega.fallback_count(), + omega.last_error(), + aien_inference_abi::strict::production_strict() + ); + assert_eq!(omega.chip_errors(), 1, "the native library must refuse"); + assert_eq!(omega.fallback_count(), 1); + if aien_inference_abi::strict::production_strict() { + let err = r.expect_err("strict: an unsupported native op must be fatal"); + let msg = err + .downcast_ref::<String>() + .cloned() + .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string())) + .unwrap_or_default(); + assert!( + msg.contains(aien_inference_abi::strict::STRICT_VIOLATION_PREFIX) + && msg.contains("gqa_attention"), + "{msg}" + ); + println!("NEGATIVE strict refusal: {msg}"); + } else { + r.expect("dev: counted fallback, run continues"); + } +} diff --git a/crates/aien-inference-runtime/tests/oracle/mod.rs b/crates/aien-inference-runtime/tests/oracle/mod.rs new file mode 100644 index 00000000..eec9b155 --- /dev/null +++ b/crates/aien-inference-runtime/tests/oracle/mod.rs @@ -0,0 +1,286 @@ +//! Independent reference and per-op native accounting for the GB10 strict gate. +//! +//! The independent reference is the Hugging Face FP32 oracle fixture checked into +//! `aien-inference-abi/fixtures` (tinyllama_oracle_manifest.json + tinyllama_oracle.safetensors): +//! TinyLlama-1.1B-Chat-v1.0 logits for a 46-token prompt and its 16-step greedy decode, +//! produced outside this codebase. The CPU reference backend is our own code, so comparing +//! Omega only against it cannot catch a bug both share. +//! +//! [`CountingBackend`] wraps the backend the production path selected and counts calls per +//! op, so a receipt can show every op that ran and that none of them fell back. +#![allow(dead_code)] +use aien_inference_abi::backend::TensorBackend; +use aien_inference_abi::native_ops::{NativeOpMask, OpReport, TensorOp}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +pub fn fixtures_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../aien-inference-abi/fixtures") +} + +pub struct Oracle { + pub model_sha256: String, + pub tokenizer_sha256: String, + pub safetensors_sha256: String, + pub prompt_text: String, + pub prompt_tokens: Vec<u32>, + pub greedy_tokens: Vec<u32>, + pub greedy_text: String, + /// Oracle logits for the token after the prompt (32000 values). + pub last_token_logits: Vec<f32>, +} + +fn str_field(v: &serde_json::Value, k: &str) -> String { + v[k].as_str() + .unwrap_or_else(|| panic!("oracle manifest: missing {k}")) + .to_string() +} + +fn u32_list(v: &serde_json::Value) -> Vec<u32> { + v.as_array() + .expect("oracle manifest: expected an array") + .iter() + .map(|t| t.as_u64().expect("oracle manifest: token id") as u32) + .collect() +} + +/// One f32 tensor from a safetensors file (header JSON, then raw little-endian data). +fn read_f32_tensor(path: &Path, name: &str) -> Vec<f32> { + let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); + let hlen = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize; + let header: serde_json::Value = + serde_json::from_slice(&bytes[8..8 + hlen]).expect("oracle safetensors header"); + let t = &header[name]; + assert_eq!(t["dtype"].as_str(), Some("F32"), "{name} dtype: {t}"); + let off = t["data_offsets"].as_array().expect("data_offsets"); + let (a, b) = ( + off[0].as_u64().unwrap() as usize, + off[1].as_u64().unwrap() as usize, + ); + let (words, rest) = bytes[8 + hlen + a..8 + hlen + b].as_chunks::<4>(); + assert!(rest.is_empty(), "{name}: byte length not a multiple of 4"); + words.iter().map(|w| f32::from_le_bytes(*w)).collect() +} + +pub fn load() -> Oracle { + let dir = fixtures_dir(); + let manifest: serde_json::Value = serde_json::from_slice( + &std::fs::read(dir.join("tinyllama_oracle_manifest.json")).expect("oracle manifest"), + ) + .expect("oracle manifest JSON"); + let st = dir.join(str_field(&manifest, "safetensors_file")); + let last_token_logits = read_f32_tensor(&st, "last_token_logits"); + assert_eq!(last_token_logits.len(), 32000, "oracle last_token_logits"); + Oracle { + model_sha256: str_field(&manifest, "model_sha256"), + tokenizer_sha256: str_field(&manifest, "tokenizer_sha256"), + safetensors_sha256: str_field(&manifest, "safetensors_sha256"), + prompt_text: str_field(&manifest, "prompt_text"), + prompt_tokens: u32_list(&manifest["prompt_tokens"]), + greedy_tokens: u32_list(&manifest["decoded_16_steps"]["token_ids"]), + greedy_text: str_field(&manifest["decoded_16_steps"], "text"), + last_token_logits, + } +} + +/// Delegates every op to the backend the production path chose and counts calls per op. +pub struct CountingBackend { + inner: Arc<dyn TensorBackend>, + calls: [AtomicU64; TensorOp::COUNT], +} + +impl CountingBackend { + pub fn new(inner: Arc<dyn TensorBackend>) -> Self { + Self { + inner, + calls: Default::default(), + } + } + + fn hit(&self, op: TensorOp) { + self.calls[TensorOp::ALL.iter().position(|o| *o == op).unwrap()] + .fetch_add(1, Ordering::Relaxed); + } + + pub fn calls(&self, op: TensorOp) -> u64 { + self.calls[TensorOp::ALL.iter().position(|o| *o == op).unwrap()].load(Ordering::Relaxed) + } + + /// Calls per op minus reference runs and fallbacks of that op: the native executions. + pub fn native_calls(&self) -> Vec<(TensorOp, u64, u64)> { + let rep = self.inner.op_report(); + let count = |v: &[(String, u64)], op: TensorOp| { + v.iter() + .find(|(n, _)| n == op.name()) + .map_or(0, |(_, c)| *c) + }; + TensorOp::ALL + .into_iter() + .map(|op| { + let off = count(&rep.native_fallbacks, op) + count(&rep.reference_runs, op); + (op, self.calls(op), self.calls(op).saturating_sub(off)) + }) + .collect() + } + + /// `NATIVE_CALLS op:calls/native,...` for the run log. + pub fn line(&self) -> String { + let parts: Vec<String> = self + .native_calls() + .into_iter() + .map(|(op, c, n)| format!("{}:{c}/{n}", op.name())) + .collect(); + format!("NATIVE_CALLS {}", parts.join(",")) + } +} + +impl TensorBackend for CountingBackend { + fn name(&self) -> &'static str { + self.inner.name() + } + fn fallback_count(&self) -> u64 { + self.inner.fallback_count() + } + fn native_ops(&self) -> NativeOpMask { + self.inner.native_ops() + } + fn op_report(&self) -> OpReport { + self.inner.op_report() + } + fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { + self.hit(TensorOp::Rmsnorm); + self.inner.rmsnorm(out, x, weight, eps) + } + fn apply_rope( + &self, + q: &mut [f32], + k: &mut [f32], + pos: usize, + head_dim: usize, + num_q_heads: usize, + num_kv_heads: usize, + theta: f32, + ) { + self.hit(TensorOp::ApplyRope); + self.inner + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta) + } + fn matmul_vec( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + out_dim: usize, + in_dim: usize, + ) { + self.hit(TensorOp::MatmulVec); + self.inner.matmul_vec(out, x, weight, out_dim, in_dim) + } + fn matmul_batch( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + batch_size: usize, + in_dim: usize, + out_dim: usize, + ) { + self.hit(TensorOp::MatmulBatch); + self.inner + .matmul_batch(out, x, weight, batch_size, in_dim, out_dim) + } + fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { + self.hit(TensorOp::Swiglu); + self.inner.swiglu(out, gate, up) + } + fn gqa_attention( + &self, + out: &mut [f32], + q: &[f32], + k_cache: &[f32], + v_cache: &[f32], + seq_len: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) { + self.hit(TensorOp::GqaAttention); + self.inner.gqa_attention( + out, + q, + k_cache, + v_cache, + seq_len, + num_q_heads, + num_kv_heads, + head_dim, + ) + } + fn paged_attention( + &self, + out: &mut [f32], + q: &[f32], + pool: &aien_kv_cache::UnifiedKvTensorPool, + block_ids: &[usize], + context_len: usize, + layer_idx: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) { + self.hit(TensorOp::PagedAttention); + self.inner.paged_attention( + out, + q, + pool, + block_ids, + context_len, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + ) + } + fn paged_attention_batch( + &self, + out: &mut [f32], + q: &[f32], + pool: &aien_kv_cache::UnifiedKvTensorPool, + block_tables: &[i32], + context_lens: &[i32], + max_blocks_per_seq: usize, + num_seqs: usize, + layer_idx: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) { + self.hit(TensorOp::PagedAttentionBatch); + self.inner.paged_attention_batch( + out, + q, + pool, + block_tables, + context_lens, + max_blocks_per_seq, + num_seqs, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + ) + } + fn compute_logits( + &self, + logits: &mut [f32], + hidden: &[f32], + embed_weight: &[f32], + vocab_size: usize, + hidden_dim: usize, + ) { + self.hit(TensorOp::ComputeLogits); + self.inner + .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim) + } +} diff --git a/crates/aien-inference-runtime/tests/strict_real_model.rs b/crates/aien-inference-runtime/tests/strict_real_model.rs index 21dfcafe..5e702a8d 100644 --- a/crates/aien-inference-runtime/tests/strict_real_model.rs +++ b/crates/aien-inference-runtime/tests/strict_real_model.rs @@ -10,7 +10,9 @@ //! cargo test -p aien-inference-runtime --release --test strict_real_model -- --ignored --nocapture mod drift; +mod oracle; +use aien_inference_abi::backend::TensorBackend; use aien_inference_abi::strict::{self, StrictModelReceipt}; use aien_inference_abi::ExecutionSurface; use aien_inference_runtime::model::EmbeddedModel; @@ -299,3 +301,202 @@ fn omega_vs_reference_real_model() { } verdict.unwrap_or_else(|e| panic!("{e}")); } + +/// The oracle fixture is self-consistent: its recorded sha256 matches the file, the prompt is +/// 46 tokens, the greedy decode is 16 tokens and starts with the oracle's argmax. Host test. +#[test] +fn oracle_fixture_is_intact() { + let o = oracle::load(); + assert_eq!( + sha256_file_hex(&oracle::fixtures_dir().join("tinyllama_oracle.safetensors")), + o.safetensors_sha256 + ); + assert_eq!(o.prompt_tokens.len(), 46); + assert_eq!(o.greedy_tokens.len(), 16); + assert_eq!( + drift::top2(&o.last_token_logits).0 as u32, + o.greedy_tokens[0] + ); +} + +/// GB10 strict gate against the INDEPENDENT reference (Hugging Face FP32 oracle fixture), not +/// our own CPU backend. The backend is chosen by the production runtime path +/// (`EmbeddedModel::load_checkpoint`, use_gpu), then wrapped only to count calls per op. +/// Judged with the frozen drift rule (`drift::MAX_ABS_DLOGIT`, near-tie flips only): +/// step 0 compares all 32000 logits with the oracle's; steps 0..15 are teacher-forced with the +/// oracle's greedy tokens and every argmax must equal the oracle token unless the oracle token +/// is within 2 * MAX_ABS_DLOGIT of the Omega top logit (the same near-tie bound `drift::judge` +/// uses). Every op that ran must have run natively (zero fallbacks, zero reference runs). +/// AIEN_E2E_CHECKPOINT=<TinyLlama dir with model.safetensors + tokenizer.json> \ +/// AIEN_STRICT_RECEIPT=/path/receipt.json cargo test -p aien-inference-runtime --release \ +/// --test strict_real_model omega_vs_hf_oracle -- --ignored --nocapture +#[test] +#[ignore = "needs the real checkpoint and the GB10 with a native Omega build; heavy queue only"] +fn omega_vs_hf_oracle() { + use aien_inference_abi::native_ops::TensorOp; + use std::sync::Arc; + + let o = oracle::load(); + let ckpt = PathBuf::from(std::env::var("AIEN_E2E_CHECKPOINT").expect("AIEN_E2E_CHECKPOINT")); + let receipt_path = + PathBuf::from(std::env::var("AIEN_STRICT_RECEIPT").expect("AIEN_STRICT_RECEIPT")); + let model_path = ckpt.join("model.safetensors"); + let tokenizer_path = ckpt.join("tokenizer.json"); + let model_sha = sha256_file_hex(&model_path); + let tokenizer_sha = sha256_file_hex(&tokenizer_path); + println!( + "ORACLE_GATE checkpoint {} sha256={model_sha}", + model_path.display() + ); + println!( + "ORACLE_GATE tokenizer {} sha256={tokenizer_sha}", + tokenizer_path.display() + ); + assert_eq!( + model_sha, o.model_sha256, + "checkpoint is not the oracle's model" + ); + assert_eq!( + tokenizer_sha, o.tokenizer_sha256, + "tokenizer is not the oracle's" + ); + + let mut model = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true) + .unwrap_or_else(|e| panic!("STRICT: omega bind refused: {e}")); + let backend_identity = model.transformer.tensor_backend.name().to_string(); + println!("ORACLE_GATE backend: {backend_identity}"); + println!( + "ORACLE_GATE dev_fallback_active={}", + strict::dev_fallback_active() + ); + let counting = Arc::new(oracle::CountingBackend::new( + model.transformer.tensor_backend.clone(), + )); + model.transformer.tensor_backend = counting.clone(); + + let steps = o.greedy_tokens.len(); + let (logits, fed) = drift::logits_per_step( + &mut model.transformer, + &o.prompt_tokens, + steps, + &o.greedy_tokens, + ); + assert_eq!(fed, o.greedy_tokens); + assert_eq!(logits.len(), steps); + + // Step 0: the full logit vector against the oracle. + let cmp0 = drift::compare(std::slice::from_ref(&o.last_token_logits), &logits[..1]); + println!( + "ORACLE_GATE step0 max_abs_dlogit={:.4} oracle_tok={} omega_tok={} oracle_margin={:.4} bound={}", + cmp0[0].max_abs_dlogit, + cmp0[0].ref_tok, + cmp0[0].cand_tok, + cmp0[0].ref_margin, + drift::MAX_ABS_DLOGIT + ); + let step0 = drift::judge(&cmp0); + + // Steps 0..15: argmax against the oracle's greedy tokens, near-tie rule from the frozen bound. + let mut bad = Vec::new(); + let mut flips = 0usize; + for (s, (l, &want)) in logits.iter().zip(&o.greedy_tokens).enumerate() { + let (top, top_v, _, _) = drift::top2(l); + let gap = top_v - l[want as usize]; + if top as u32 != want { + println!("ORACLE_GATE flip step={s} oracle_tok={want} omega_tok={top} gap={gap:.4}"); + if gap.is_nan() || gap > 2.0 * drift::MAX_ABS_DLOGIT { + bad.push(format!("step {s}: omega {top} vs oracle {want}, gap {gap}")); + } + flips += 1; + } + } + let text = model.tokenizer.decode(&fed).unwrap_or_default(); + println!( + "ORACLE_GATE teacher_forced steps={steps} flips={flips} oracle_text={:?} fed_text={text:?}", + o.greedy_text + ); + + // Per-op accounting: every op that ran ran natively. "native" below is calls minus the + // backend's counted fallbacks and reference runs, so it only means native on a backend that + // counts them (OmegaGb10Backend); a CPU backend reports none and is refused by the receipt. + let native_engine = backend_identity.contains("native Omega engine"); + println!( + "ORACLE_GATE {} native_engine={native_engine}", + counting.line() + ); + let report = counting.op_report(); + println!("ORACLE_GATE {}", report.line()); + let mut op_problems = Vec::new(); + if !native_engine { + op_problems.push(format!( + "backend is not the native Omega engine: {backend_identity}" + )); + } + for (op, calls, native) in counting.native_calls() { + if calls != native { + op_problems.push(format!("{}: {calls} calls, {native} native", op.name())); + } + } + if !report.native_fallbacks.is_empty() || !report.reference_runs.is_empty() { + op_problems.push(report.line()); + } + for op in [ + TensorOp::Rmsnorm, + TensorOp::ApplyRope, + TensorOp::Swiglu, + TensorOp::ComputeLogits, + ] { + if counting.calls(op) == 0 { + op_problems.push(format!("{} never ran", op.name())); + } + } + if counting.calls(TensorOp::MatmulVec) + counting.calls(TensorOp::MatmulBatch) == 0 { + op_problems.push("no matmul ran".into()); + } + if counting.calls(TensorOp::GqaAttention) + + counting.calls(TensorOp::PagedAttention) + + counting.calls(TensorOp::PagedAttentionBatch) + == 0 + { + op_problems.push("no attention ran".into()); + } + + let mut receipt = StrictModelReceipt { + checkpoint_path: model_path.display().to_string(), + checkpoint_sha256: model_sha, + tokenizer_path: tokenizer_path.display().to_string(), + tokenizer_sha256: tokenizer_sha, + backend_identity, + model_id: model.config.model_id.clone(), + model_config: serde_json::to_value(&model.config) + .unwrap_or(serde_json::json!({"model_id": model.config.model_id})), + fallback_count: counting.fallback_count(), + op_report: Some(report), + dev_fallback_build: strict::dev_fallback_active(), + verdict: String::new(), + }; + let verdict = receipt.verify(); + std::fs::write( + &receipt_path, + serde_json::to_string_pretty(&receipt).unwrap(), + ) + .expect("write receipt"); + println!( + "ORACLE_GATE receipt verdict: {} (receipt {})", + receipt.verdict, + receipt_path.display() + ); + if let Err(e) = step0 { + panic!("Omega step-0 logits disagree with the HF oracle: {e}"); + } + assert!( + bad.is_empty(), + "argmax disagreements beyond the near-tie bound: {bad:?}" + ); + assert!( + op_problems.is_empty(), + "per-op native accounting: {op_problems:?}" + ); + verdict.unwrap_or_else(|e| panic!("{e}")); + println!("ORACLE_GATE verdict: PASS"); +}