Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/cf3843569de71662 # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#188 (code only) closed derived `cf3843569de71662` #188 Imported from GitHub aien-dev/aien-sovereign-core-mv#188 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `1d1bb57d5cd918a18a60c3e9a397463dd66c1ad6` · Head `e319ee018fe6e6b626c7b5ff9a7e714c9be14c2e` ### Apply it ``` git checkout -b patch-cf3843569de71662 1d1bb57d5cd918a18a60c3e9a397463dd66c1ad6 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/cf3843569de71662.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 188 e319ee018fe6e6b626c7b5ff9a7e714c9be14c2e ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":188,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/188","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:14Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index aa8ce8f9..ac38c2fa 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -7,7 +7,7 @@ use crate::tensor::{ /// Reads one KV head from the pool using the pool's dtype. Bf16 bytes are decoded. /// A short or unknown dtype returns zeros instead of reading past the allocation. -fn read_kv_head( +pub(crate) fn read_kv_head( pool: &aien_kv_cache::UnifiedKvTensorPool, block_id: usize, layer_idx: usize, diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index e7224f24..7e5c2106 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -1,10 +1,12 @@ -//! `OmegaGb10Backend` (FB-1 cuts 3b and 3c): the three matrix-multiply ops, rmsnorm, -//! rope and swiglu of `TensorBackend` run on our own native GPU engine -//! (`libomega_gpu.a`, no CUDA) through the `aien-omega-gpu` crate; the attention ops -//! run on the reference CPU path by design and are counted by `OpAccounting`. +//! `OmegaGb10Backend` (FB-1 cuts 3b, 3c, 3d): all nine `TensorBackend` ops run on our own +//! native GPU engine (`libomega_gpu.a`, no CUDA) through the `aien-omega-gpu` crate. //! //! Native mask: `matmul_vec`, `matmul_batch`, `compute_logits`, `rmsnorm`, -//! `apply_rope`, `swiglu`. A chip error in +//! `apply_rope`, `swiglu`, `gqa_attention`, `paged_attention`, `paged_attention_batch`. +//! Paged attention over a bf16 pool uses omega's paged kernel; over any other pool dtype +//! (the model builds Fp32 pools) the sequence's K/V are gathered on the host into +//! contiguous f32 exactly as the reference reads them, then run on the f32 gqa kernel. +//! omega attention needs head_dim 64 (TinyLlama, Llama-3.2-1B). A chip error in //! one of those is a fallback of a claimed-native op: it is counted, goes through //! `OpAccounting::reference_path` (fatal in a production build, see `strict.rs`) //! and, in a dev build only, the reference result is computed so the run goes on. @@ -104,6 +106,9 @@ impl OmegaGb10Backend { TensorOp::Rmsnorm, TensorOp::ApplyRope, TensorOp::Swiglu, + TensorOp::GqaAttention, + TensorOp::PagedAttention, + TensorOp::PagedAttentionBatch, ])), chip: Mutex::new(HashMap::new()), rope_tables: Mutex::new(HashMap::new()), @@ -330,6 +335,115 @@ impl OmegaGb10Backend { }) } + fn chip_attention( + &self, + what: &str, + call: impl FnOnce() -> Result, + ) -> bool { + let guard = match self.chip.lock() { + Ok(g) => g, + Err(_) => return self.fail("chip lock poisoned".into()), + }; + let res = call(); + drop(guard); + match res { + Ok(info) => { + self.chip_calls.fetch_add(1, Ordering::Relaxed); + self.chip_ns.fetch_add(info.elapsed_ns, Ordering::Relaxed); + true + } + Err(e) => self.fail(format!("{what}: {e}")), + } + } + + /// One sequence of paged attention on the chip. A bf16 pool goes straight to the + /// paged kernel; any other dtype (the model builds Fp32 pools) is gathered on the host + /// into contiguous `[t][kv_head][head_dim]` f32 K and V exactly as the reference reads + /// them (tokens past the block table are dropped), then runs the f32 gqa kernel. + #[allow(clippy::too_many_arguments)] + fn chip_paged_one( + &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, + ) -> bool { + if context_len == 0 || block_ids.is_empty() { + out.fill(0.0); + return true; + } + if pool.config().dtype == aien_kv_cache::KvDType::Bf16 { + let ids: Option> = block_ids.iter().map(|&b| u32::try_from(b).ok()).collect(); + let Some(ids) = ids else { + return self.fail("paged_attention: block id past u32".into()); + }; + let d = pool.layout_desc(); + let layout = aien_omega_gpu::OmegaGpuKvLayout { + block_stride_bytes: d.block_stride_bytes, + layer_stride_bytes: d.layer_stride_bytes, + kv_plane_stride_bytes: d.kv_plane_stride_bytes, + token_stride_bytes: d.token_stride_bytes, + head_stride_bytes: d.head_stride_bytes, + pool_bytes: d.pool_bytes, + num_blocks: d.num_blocks, + num_layers: d.num_layers, + block_size: d.block_size, + }; + // SAFETY: the pool owns total_bytes() readable bytes at base_ptr() for its lifetime, + // and we hold &pool for the whole call. + let bytes = unsafe { std::slice::from_raw_parts(pool.base_ptr(), pool.total_bytes()) }; + return self.chip_attention(&format!("paged_attention_bf16 ctx={context_len}"), || { + aien_omega_gpu::paged_attention_bf16( + q, + bytes, + &layout, + &ids, + context_len, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + out, + ) + }); + } + let block_size = pool.config().block_size; + let n = context_len.min(block_ids.len().saturating_mul(block_size)); + let row = num_kv_heads * head_dim; + let mut k = vec![0.0f32; n * row]; + let mut v = vec![0.0f32; n * row]; + for t in 0..n { + let blk = block_ids[t / block_size]; + let slot = t % block_size; + for kh in 0..num_kv_heads { + let at = t * row + kh * head_dim; + k[at..at + head_dim].copy_from_slice(&crate::backend::read_kv_head( + pool, blk, layer_idx, false, slot, kh, head_dim, + )); + v[at..at + head_dim].copy_from_slice(&crate::backend::read_kv_head( + pool, blk, layer_idx, true, slot, kh, head_dim, + )); + } + } + self.chip_attention(&format!("paged_attention(gathered) ctx={n}"), || { + aien_omega_gpu::gqa_attention_f32( + q, + &k, + &v, + n, + num_q_heads, + num_kv_heads, + head_dim, + out, + ) + }) + } + fn fail(&self, msg: String) -> bool { self.chip_errors.fetch_add(1, Ordering::Relaxed); let stage = aien_omega_gpu::last_error(); @@ -443,6 +557,26 @@ impl TensorBackend for OmegaGb10Backend { num_kv_heads: usize, head_dim: usize, ) { + // The reference reads only the first seq_len rows; causal prefill passes the whole + // prompt's cache with a shorter seq_len, so hand omega exactly those rows. + let need = seq_len * num_kv_heads * head_dim; + let k_rows = &k_cache[..need.min(k_cache.len())]; + let v_rows = &v_cache[..need.min(v_cache.len())]; + let native = self.chip_attention(&format!("gqa_attention seq={seq_len}"), || { + aien_omega_gpu::gqa_attention_f32( + q, + k_rows, + v_rows, + seq_len, + num_q_heads, + num_kv_heads, + head_dim, + out, + ) + }); + if native { + return; + } self.reference_for(TensorOp::GqaAttention); self.reference.gqa_attention( out, @@ -468,6 +602,19 @@ impl TensorBackend for OmegaGb10Backend { num_kv_heads: usize, head_dim: usize, ) { + if self.chip_paged_one( + out, + q, + pool, + block_ids, + context_len, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + ) { + return; + } self.reference_for(TensorOp::PagedAttention); self.reference.paged_attention( out, @@ -496,8 +643,46 @@ impl TensorBackend for OmegaGb10Backend { num_kv_heads: usize, head_dim: usize, ) { - // Counted once as a batch op; the reference batch calls the reference - // single-sequence path, not ours, so there is no double count. + // Per sequence, the same row handling as the TensorBackend default (context_lens <= 0 + // means 0, a row past the array is empty, negative entries are removed), each row on + // the chip. Any failed row sends the whole batch to the reference, counted once as a + // batch op (the reference batch calls the reference single path, not ours). + let q_stride = num_q_heads * head_dim; + let mut all_native = q.len() >= num_seqs * q_stride && out.len() >= num_seqs * q_stride; + for s in 0..num_seqs { + if !all_native { + break; + } + let ctx = context_lens + .get(s) + .copied() + .filter(|&c| c > 0) + .map_or(0, |c| c as usize); + let (b0, b1) = (s * max_blocks_per_seq, (s + 1) * max_blocks_per_seq); + let row: Vec = if b1 <= block_tables.len() { + block_tables[b0..b1] + .iter() + .filter(|&&b| b >= 0) + .map(|&b| b as usize) + .collect() + } else { + Vec::new() + }; + all_native = self.chip_paged_one( + &mut out[s * q_stride..(s + 1) * q_stride], + &q[s * q_stride..(s + 1) * q_stride], + pool, + &row, + ctx, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + ); + } + if all_native { + return; + } self.reference_for(TensorOp::PagedAttentionBatch); self.reference.paged_attention_batch( out, @@ -540,7 +725,7 @@ mod tests { } #[test] - fn mask_is_exactly_the_six_native_ops() { + fn mask_is_all_nine_ops() { let b = OmegaGb10Backend::new(); let names: Vec<_> = b .native_ops() @@ -556,18 +741,35 @@ mod tests { "matmul_vec", "matmul_batch", "swiglu", + "gqa_attention", + "paged_attention", + "paged_attention_batch", "compute_logits" ] ); } #[test] - fn reference_ops_are_counted_by_design_and_never_trip() { + fn attention_chip_error_is_a_counted_fallback() { + if aien_omega_gpu::is_native() || !crate::strict::dev_fallback_active() { + return; // native: nothing fails here; production: it would (correctly) panic + } let b = OmegaGb10Backend::new(); - let mut out = [0.0f32; 2]; - b.gqa_attention(&mut out, &[1.0; 2], &[1.0; 2], &[1.0; 2], 1, 1, 1, 2); - assert_eq!(b.fallback_count(), 0); - assert!(b.op_report().line().contains("gqa_attention:1")); + let (q, k, v) = ( + [0.5f32, -1.0], + [1.0f32, 2.0, -1.0, 0.25], + [3.0f32, 4.0, 5.0, 6.0], + ); + let mut got = [0.0f32; 2]; + let mut want = [0.0f32; 2]; + b.gqa_attention(&mut got, &q, &k, &v, 2, 1, 1, 2); + ReferenceCpuBackend::new().gqa_attention(&mut want, &q, &k, &v, 2, 1, 1, 2); + assert_eq!(got, want); + assert_eq!(b.fallback_count(), 1); + assert!(b + .op_report() + .line() + .contains("native_fallbacks=[gqa_attention:1]")); } /// Stub build only: a chip error on a claimed-native op is a counted fallback diff --git a/crates/aien-inference-abi/tests/omega_backend_parity.rs b/crates/aien-inference-abi/tests/omega_backend_parity.rs index 6fb1467f..a1ab2991 100644 --- a/crates/aien-inference-abi/tests/omega_backend_parity.rs +++ b/crates/aien-inference-abi/tests/omega_backend_parity.rs @@ -45,7 +45,7 @@ fn worst_ratio( fn stub_backend_reports_unavailable() { let b = OmegaGb10Backend::new(); assert_eq!(b.is_available(), aien_omega_gpu::is_native()); - assert_eq!(b.native_ops().native_ops().len(), 6); + assert_eq!(b.native_ops().native_ops().len(), 9); } #[test] @@ -204,3 +204,122 @@ fn chip_mixed_matmul_then_elementwise() { omega.last_error() ); } + +fn worst_attn_ratio(got: &[f32], want: &[f32]) -> f64 { + // omega tests/gpu_attention_test.c tolerances (FB-1 cut 5): rel 2e-4, abs 2e-5. + assert_eq!(got.len(), want.len()); + got.iter() + .zip(want) + .map(|(g, w)| (*g as f64 - *w as f64).abs() / (2e-5 + 2e-4 * (*w as f64).abs())) + .fold(0.0, f64::max) +} + +/// Fill `n_tokens` tokens of `layer` into a fresh TinyLlama-shaped pool (block_size 16), +/// blocks used in a scrambled order so the block table is not the identity. +fn filled_pool( + dtype: aien_kv_cache::KvDType, + n_tokens: usize, + layer: usize, + seed: &mut u32, +) -> (aien_kv_cache::UnifiedKvTensorPool, Vec) { + let (num_blocks, bs) = (160usize, 16usize); + let cfg = aien_kv_cache::KvPoolConfig::for_tinyllama(num_blocks, bs, dtype); + let mut pool = aien_kv_cache::UnifiedKvTensorPool::allocate(cfg).expect("pool"); + let need = n_tokens.div_ceil(bs); + let blocks: Vec = (0..need).map(|i| (i * 37 + 11) % num_blocks).collect(); + let kv_dim = 4 * 64; + for t in 0..n_tokens { + let k: Vec = (0..kv_dim).map(|_| lcg(seed) * 2.0).collect(); + let v: Vec = (0..kv_dim).map(|_| lcg(seed) * 2.0).collect(); + pool.write_token_kv(blocks[t / bs], layer, t % bs, &k, &v); + } + (pool, blocks) +} + +/// FB-1 cut 3d: the three attention ops on the chip at TinyLlama shapes (32 q heads, +/// 4 kv heads, head_dim 64) against ReferenceCpuBackend: contiguous gqa, paged over an +/// Fp32 pool (the model's pool; host gather + f32 kernel), paged over a bf16 pool (omega's +/// paged kernel), and the batch op with ragged rows, a negative entry and an empty row. +#[test] +#[ignore = "chip test: needs a native build and the GB10; run through the heavy queue"] +fn chip_attention_parity_on_tinyllama_shapes() { + let omega = OmegaGb10Backend::new(); + assert!(omega.is_available(), "native build required"); + let reference = ReferenceCpuBackend::new(); + let mut seed = 4242u32; + let (nq, nkv, hd) = (32usize, 4usize, 64usize); + + let mut gqa_worst = 0.0f64; + for seq in [1usize, 7, 64, 300, 2048] { + let q: Vec = (0..nq * hd).map(|_| lcg(&mut seed) * 2.0).collect(); + let k: Vec = (0..seq * nkv * hd).map(|_| lcg(&mut seed) * 2.0).collect(); + let v: Vec = (0..seq * nkv * hd).map(|_| lcg(&mut seed) * 2.0).collect(); + let (mut got, mut want) = (vec![0.0f32; nq * hd], vec![0.0f32; nq * hd]); + omega.gqa_attention(&mut got, &q, &k, &v, seq, nq, nkv, hd); + reference.gqa_attention(&mut want, &q, &k, &v, seq, nq, nkv, hd); + let r = worst_attn_ratio(&got, &want); + let at = got + .iter() + .zip(&want) + .map(|(g, w)| (*g as f64 - *w as f64).abs()) + .enumerate() + .fold( + (0usize, 0.0f64), + |m, (i, d)| if d > m.1 { (i, d) } else { m }, + ); + println!( + "PARITY gqa seq={seq} err/tol={r:.3e} worst at {} got={} want={}", + at.0, got[at.0], want[at.0] + ); + gqa_worst = gqa_worst.max(r); + } + println!( + "PARITY gqa_attention seq 1..2048 worst err/tolerance = {gqa_worst:.3e} (must be <= 1)" + ); + assert!(gqa_worst <= 1.0, "gqa_attention outside tolerance"); + + for dtype in [aien_kv_cache::KvDType::Fp32, aien_kv_cache::KvDType::Bf16] { + let mut worst = 0.0f64; + for (ctx, layer) in [(1usize, 0usize), (17, 3), (250, 21), (1000, 9)] { + let (pool, blocks) = filled_pool(dtype, ctx, layer, &mut seed); + let q: Vec = (0..nq * hd).map(|_| lcg(&mut seed) * 2.0).collect(); + let (mut got, mut want) = (vec![0.0f32; nq * hd], vec![0.0f32; nq * hd]); + omega.paged_attention(&mut got, &q, &pool, &blocks, ctx, layer, nq, nkv, hd); + reference.paged_attention(&mut want, &q, &pool, &blocks, ctx, layer, nq, nkv, hd); + worst = worst.max(worst_attn_ratio(&got, &want)); + } + println!( + "PARITY paged_attention {dtype:?} worst err/tolerance = {worst:.3e} (must be <= 1)" + ); + assert!(worst <= 1.0, "paged_attention {dtype:?} outside tolerance"); + + // batch: 3 rows (ctx 40, 0 = empty, 90 with a trailing -1), max_blocks 8. + let (pool, blocks) = filled_pool(dtype, 90, 5, &mut seed); + let mb = 8usize; + let mut tables = vec![-1i32; 3 * mb]; + for (i, b) in blocks.iter().take(3).enumerate() { + tables[i] = *b as i32; + } + for (i, b) in blocks.iter().enumerate() { + tables[2 * mb + i] = *b as i32; + } + let lens = [40i32, 0, 90]; + let q: Vec = (0..3 * nq * hd).map(|_| lcg(&mut seed) * 2.0).collect(); + let (mut got, mut want) = (vec![0.0f32; 3 * nq * hd], vec![0.0f32; 3 * nq * hd]); + omega.paged_attention_batch(&mut got, &q, &pool, &tables, &lens, mb, 3, 5, nq, nkv, hd); + reference + .paged_attention_batch(&mut want, &q, &pool, &tables, &lens, mb, 3, 5, nq, nkv, hd); + let bw = worst_attn_ratio(&got, &want); + println!( + "PARITY paged_attention_batch {dtype:?} worst err/tolerance = {bw:.3e} (must be <= 1)" + ); + assert!( + bw <= 1.0, + "paged_attention_batch {dtype:?} outside tolerance" + ); + } + + assert_eq!(omega.fallback_count(), 0, "{}", omega.last_error()); + assert_eq!(omega.chip_errors(), 0, "{}", omega.last_error()); + println!("PARITY attention {}", omega.op_report().line()); +} diff --git a/crates/aien-inference-runtime/tests/drift/mod.rs b/crates/aien-inference-runtime/tests/drift/mod.rs new file mode 100644 index 00000000..44cb9e97 --- /dev/null +++ b/crates/aien-inference-runtime/tests/drift/mod.rs @@ -0,0 +1,133 @@ +//! Teacher-forced logit comparison shared by the strict gate and the drift diagnostic. +//! +//! Both backends are fed the reference's own greedy tokens, so every step compares +//! logits for the same context. A greedy text comparison cannot tell a wrong backend +//! from a near-tie: TinyLlama on the gate prompt has a step where "processing" leads +//! "memory" by 0.0005 logits while the f32 backends differ by ~0.03 everywhere +//! (evidence-out/FB1-CUT3D-02dfa2e-drift, 2026-10-04). +#![allow(dead_code)] +use aien_inference_abi::transformer_backend::NativeTransformerBackend; +use aien_inference_abi::SequenceState; + +/// Largest allowed |logit difference| at any step. The cut 3d run measured 0.059 worst +/// over 32 steps (32000 logits each); the bound leaves 2.5x headroom. +pub const MAX_ABS_DLOGIT: f32 = 0.15; + +pub fn top2(l: &[f32]) -> (usize, f32, usize, f32) { + let (mut i1, mut v1, mut i2, mut v2) = (0usize, f32::NEG_INFINITY, 0usize, f32::NEG_INFINITY); + for (i, &v) in l.iter().enumerate() { + if v > v1 { + (i2, v2) = (i1, v1); + (i1, v1) = (i, v); + } else if v > v2 { + (i2, v2) = (i, v); + } + } + (i1, v1, i2, v2) +} + +/// Logits for every step: step 0 from prefill, step s from decoding `forced[s-1]`. +/// With `forced` empty the model's own argmax is fed back; the fed tokens are returned. +pub fn logits_per_step( + t: &mut NativeTransformerBackend, + prompt: &[u32], + steps: usize, + forced: &[u32], +) -> (Vec>, Vec) { + let seq_id = 0x10_9175_u64; + let mut out = vec![t.prefill_sequence(seq_id, prompt).expect("prefill")]; + let mut toks = Vec::new(); + for s in 0..steps { + let tok = if forced.is_empty() { + top2(&out[s]).0 as u32 + } else { + forced[s] + }; + toks.push(tok); + if s + 1 == steps { + break; + } + let seq: &mut SequenceState = t.sequences.get_mut(&seq_id).expect("sequence"); + seq.tokens.push(tok); + let pos = seq.tokens.len() - 1; + let hidden = NativeTransformerBackend::try_forward_token_impl_paged( + &t.weights, + &*t.tensor_backend, + tok, + pos, + seq, + seq_id, + t.kv_manager.as_ref(), + ) + .expect("decode"); + out.push(NativeTransformerBackend::compute_logits_impl( + &t.weights, + &*t.tensor_backend, + &hidden, + )); + } + t.release_sequence(seq_id); + (out, toks) +} + +pub struct StepCmp { + pub step: usize, + pub ref_tok: usize, + pub ref_margin: f32, + pub cand_tok: usize, + pub max_abs_dlogit: f32, +} + +pub fn compare(reference: &[Vec], candidate: &[Vec]) -> Vec { + reference + .iter() + .zip(candidate) + .enumerate() + .map(|(step, (r, c))| { + let (r1, rv1, _, rv2) = top2(r); + let d = r + .iter() + .zip(c) + .map(|(a, b)| (a - b).abs()) + .fold(0.0f32, |m, x| { + if m.is_nan() || x.is_nan() { + f32::NAN + } else { + m.max(x) + } + }); // a NaN logit must fail the judge, f32::max would drop it + StepCmp { + step, + ref_tok: r1, + ref_margin: rv1 - rv2, + cand_tok: top2(c).0, + max_abs_dlogit: d, + } + }) + .collect() +} + +/// Pass when every step stays within `MAX_ABS_DLOGIT` and every argmax disagreement is a +/// near-tie the measured difference can explain: a flip needs the top-two gap to move by +/// at least the reference margin, and that gap moves by at most 2 * max_abs_dlogit. +pub fn judge(steps: &[StepCmp]) -> Result { + let mut flips = 0; + for s in steps { + if s.max_abs_dlogit.is_nan() || s.max_abs_dlogit > MAX_ABS_DLOGIT { + return Err(format!( + "step {}: max |dlogit| {} exceeds {MAX_ABS_DLOGIT}", + s.step, s.max_abs_dlogit + )); + } + if s.cand_tok != s.ref_tok { + if s.ref_margin > 2.0 * s.max_abs_dlogit { + return Err(format!( + "step {}: argmax {} vs reference {} with reference margin {} > 2 * max |dlogit| {}", + s.step, s.cand_tok, s.ref_tok, s.ref_margin, s.max_abs_dlogit + )); + } + flips += 1; + } + } + Ok(flips) +} diff --git a/crates/aien-inference-runtime/tests/logit_drift.rs b/crates/aien-inference-runtime/tests/logit_drift.rs new file mode 100644 index 00000000..29ed311a --- /dev/null +++ b/crates/aien-inference-runtime/tests/logit_drift.rs @@ -0,0 +1,102 @@ +//! Teacher-forced logit drift between the CPU reference and the Omega backend, printed +//! per step (diagnostic), plus host tests proving the drift judge used by the strict gate +//! rejects what it must. +//! AIEN_E2E_CHECKPOINT=~/models/TinyLlama-1.1B-Chat-v1.0 \ +//! cargo test -p aien-inference-runtime --release --test logit_drift -- --ignored --nocapture +mod drift; + +use aien_inference_runtime::model::EmbeddedModel; +use drift::{compare, judge, logits_per_step, top2, StepCmp, MAX_ABS_DLOGIT}; +use std::path::{Path, PathBuf}; + +fn step(ref_tok: usize, ref_margin: f32, cand_tok: usize, d: f32) -> StepCmp { + StepCmp { + step: 0, + ref_tok, + ref_margin, + cand_tok, + max_abs_dlogit: d, + } +} + +#[test] +fn judge_accepts_agreement_and_explained_near_tie() { + assert_eq!(judge(&[step(5, 0.3, 5, 0.04)]), Ok(0)); + // the measured cut 3d case: margin 0.0005, difference 0.0314 + assert_eq!(judge(&[step(9068, 0.0005, 3370, 0.0314)]), Ok(1)); +} + +#[test] +fn judge_rejects_unexplained_flip_and_large_drift() { + // negative controls: a flip the measured difference cannot explain, and drift over the bound + assert!(judge(&[step(9068, 1.0, 3370, 0.03)]).is_err()); + assert!(judge(&[step(5, 0.3, 5, MAX_ABS_DLOGIT * 2.0)]).is_err()); + assert!(judge(&[step(5, 0.3, 5, f32::NAN)]).is_err()); +} + +#[test] +fn compare_finds_flip_margin_and_difference() { + let r = vec![vec![0.0, 2.0, 1.9]]; + let c = vec![vec![0.0, 1.9, 2.0]]; + let s = &compare(&r, &c)[0]; + assert_eq!((s.ref_tok, s.cand_tok), (1, 2)); + assert!((s.ref_margin - 0.1).abs() < 1e-6 && (s.max_abs_dlogit - 0.1).abs() < 1e-6); +} + +#[test] +#[ignore = "needs the real checkpoint and the GB10 with a native Omega build; heavy queue only"] +fn teacher_forced_logit_drift() { + let ckpt = PathBuf::from(std::env::var("AIEN_E2E_CHECKPOINT").expect("AIEN_E2E_CHECKPOINT")); + let dir = if ckpt.is_dir() { + ckpt.clone() + } else { + ckpt.parent().map(Path::to_path_buf).unwrap_or_default() + }; + let (model_path, tokenizer_path) = (dir.join("model.safetensors"), dir.join("tokenizer.json")); + let prompt = "The DGX Spark is a small computer with a large"; + let steps = 32usize; + + let mut cpu = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, false, true) + .expect("reference load"); + let ptoks = cpu.tokenizer.encode(prompt).expect("encode"); + let (ref_logits, ref_toks) = logits_per_step(&mut cpu.transformer, &ptoks, steps, &[]); + let tok = cpu.tokenizer; + drop(cpu.transformer); + + std::env::set_var(aien_inference_abi::GPU_BACKEND_ENV, "omega"); + let mut om = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true) + .expect("omega load"); + println!( + "DRIFT omega backend: {}", + om.transformer.tensor_backend.name() + ); + let (om_logits, _) = logits_per_step(&mut om.transformer, &ptoks, steps, &ref_toks); + println!("DRIFT {}", om.transformer.tensor_backend.op_report().line()); + + let cmp = compare(&ref_logits, &om_logits); + for (s, c) in cmp.iter().enumerate() { + let (_, _, r2, _) = top2(&ref_logits[s]); + println!( + "DRIFT step={s:2} ref_tok={:5} {:?} ref_margin={:.4} omega_tok={:5} max_abs_dlogit={:.4} ref2={r2} {:?}{}", + c.ref_tok, + tok.decode(&[c.ref_tok as u32]).unwrap_or_default(), + c.ref_margin, + c.cand_tok, + c.max_abs_dlogit, + tok.decode(&[r2 as u32]).unwrap_or_default(), + if c.ref_tok != c.cand_tok { " <-- FLIP" } else { "" } + ); + } + let worst = cmp.iter().map(|c| c.max_abs_dlogit).fold(0.0f32, f32::max); + println!( + "DRIFT summary steps={steps} worst_max_abs_dlogit={worst:.4} judge={:?}", + judge(&cmp) + ); +} + +#[test] +fn compare_keeps_nan_so_the_judge_fails_it() { + let s = compare(&[vec![1.0, 0.0]], &[vec![f32::NAN, 0.0]]); + assert!(s[0].max_abs_dlogit.is_nan()); + assert!(judge(&s).is_err()); +} diff --git a/crates/aien-inference-runtime/tests/strict_real_model.rs b/crates/aien-inference-runtime/tests/strict_real_model.rs index ecd5717f..7fbb0fa4 100644 --- a/crates/aien-inference-runtime/tests/strict_real_model.rs +++ b/crates/aien-inference-runtime/tests/strict_real_model.rs @@ -9,6 +9,8 @@ //! AIEN_STRICT_RECEIPT=/path/receipt.json \ //! cargo test -p aien-inference-runtime --release --test strict_real_model -- --ignored --nocapture +mod drift; + use aien_inference_abi::strict::{self, StrictModelReceipt}; use aien_inference_abi::ExecutionSurface; use aien_inference_runtime::model::EmbeddedModel; @@ -151,7 +153,10 @@ fn strict_real_model_gate() { /// FB-1 cut 3b gate: the same greedy generation on the CPU reference backend and on /// the Omega backend (AIEN_GPU_BACKEND=omega), same checkpoint. Records tok/s for -/// both, asserts identical text and zero fallbacks of the claimed-native matmul ops. +/// both, checks zero fallbacks and all nine ops native, and judges the backend by teacher- +/// forced logits (tests/drift): greedy text alone cannot tell a wrong backend from a +/// near-tie flip (cut 3d: "processing" led "memory" by 0.0005 logits). Text equality is +/// printed (tokens_match) but no longer asserted. /// AIEN_E2E_CHECKPOINT=~/models/TinyLlama-1.1B-Chat-v1.0 AIEN_STRICT_RECEIPT=/path/receipt.json \ /// cargo test -p aien-inference-runtime --release --test strict_real_model \ /// omega_vs_reference_real_model -- --ignored --nocapture @@ -199,6 +204,9 @@ fn omega_vs_reference_real_model() { "OMEGA_GATE ref tokens={cpu_n} secs={cpu_s:.3} tok/s={:.3} text={cpu_text:?}", cpu_n as f64 / cpu_s ); + let ptoks = cpu.tokenizer.encode(prompt).expect("encode"); + let (ref_logits, ref_toks) = + drift::logits_per_step(&mut cpu.transformer, &ptoks, max_tokens, &[]); drop(cpu); // Omega leg. The env var is read inside load_checkpoint; set before loading. @@ -215,6 +223,21 @@ fn omega_vs_reference_real_model() { t.elapsed().as_secs_f64() ); let (om_text, om_n, om_s) = run(&mut om); + let (om_logits, _) = drift::logits_per_step(&mut om.transformer, &ptoks, max_tokens, &ref_toks); + let cmp = drift::compare(&ref_logits, &om_logits); + for c in cmp.iter().filter(|c| c.ref_tok != c.cand_tok) { + println!( + "OMEGA_GATE flip step={} ref_tok={} omega_tok={} ref_margin={:.4} max_abs_dlogit={:.4}", + c.step, c.ref_tok, c.cand_tok, c.ref_margin, c.max_abs_dlogit + ); + } + let worst = cmp.iter().map(|c| c.max_abs_dlogit).fold(0.0f32, f32::max); + let drift_verdict = drift::judge(&cmp); + println!( + "OMEGA_GATE teacher_forced steps={} worst_max_abs_dlogit={worst:.4} bound={} judge={drift_verdict:?}", + cmp.len(), + drift::MAX_ABS_DLOGIT + ); println!( "OMEGA_GATE omega tokens={om_n} secs={om_s:.3} tok/s={:.3} text={om_text:?}", om_n as f64 / om_s @@ -230,6 +253,9 @@ fn omega_vs_reference_real_model() { "rmsnorm", "apply_rope", "swiglu", + "gqa_attention", + "paged_attention", + "paged_attention_batch", ] { assert!( report.native_ops.iter().any(|n| n == op), @@ -268,6 +294,8 @@ fn omega_vs_reference_real_model() { receipt.verdict, receipt_path.display() ); - assert_eq!(cpu_text, om_text, "Omega backend changed the greedy output"); + if let Err(e) = drift_verdict { + panic!("Omega backend logits disagree with the reference: {e}"); + } verdict.unwrap_or_else(|e| panic!("{e}")); } diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs index 7abdb5df..77ae458b 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -1,5 +1,5 @@ //! Raw declarations, written by hand from omega `src/omega_gpu_matmul_api.h` -//! at the commit pinned in `omega.lock` (2636409). Nothing generated. +//! at the commit pinned in `omega.lock` (3d4648c; headers unchanged since 6b940fa). Nothing generated. //! Includes the resident-weights handles added by omega FB-1 cut 1b. use std::os::raw::{c_char, c_int}; @@ -210,3 +210,110 @@ extern "C" { ) -> c_int; pub fn omega_gpu_elementwise_rc_name(rc: c_int) -> *const c_char; } + +// ---- omega `src/omega_gpu_attention_api.h` (FB-1 cut 5 + 4b, pinned 3d4648c) ---- +pub const OMEGA_GPU_ATTN_OK: c_int = 0; +pub const OMEGA_GPU_ATTN_BAD_ARGS: c_int = -1; +pub const OMEGA_GPU_ATTN_TOO_LARGE: c_int = -2; +pub const OMEGA_GPU_ATTN_CODEGEN_FAIL: c_int = -3; +pub const OMEGA_GPU_ATTN_CHIP_FAIL: c_int = -4; +pub const OMEGA_GPU_ATTN_UNWRITTEN: c_int = -5; + +/// Mirrors `OmegaGpuAttnInfo` field for field, same order (note `call_ns` is third). +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct OmegaGpuAttnInfo { + pub chip_calls: u32, + pub elapsed_ns: u64, + pub call_ns: u64, + pub completion_marker: u32, + pub unwritten_words: u32, + pub gpr_count: u32, + pub insn_count: u32, + pub kernel_cache_hit: bool, + pub ctas_last_launch: u32, + pub threads_per_cta: u32, + pub target_chip: [c_char; 64], + pub sm_architecture: u32, +} + +impl OmegaGpuAttnInfo { + pub fn zeroed() -> Self { + Self { + chip_calls: 0, + elapsed_ns: 0, + call_ns: 0, + completion_marker: 0, + unwritten_words: 0, + gpr_count: 0, + insn_count: 0, + kernel_cache_hit: false, + ctas_last_launch: 0, + threads_per_cta: 0, + target_chip: [0; 64], + sm_architecture: 0, + } + } +} + +/// Mirrors `OmegaGpuKvLayout` (itself a mirror of aien-kv-cache `KvLayoutDesc`), +/// field for field, strides in bytes. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OmegaGpuKvLayout { + pub block_stride_bytes: u64, + pub layer_stride_bytes: u64, + pub kv_plane_stride_bytes: u64, + pub token_stride_bytes: u64, + pub head_stride_bytes: u64, + pub pool_bytes: u64, + pub num_blocks: u32, + pub num_layers: u32, + pub block_size: u32, +} + +#[cfg(has_omega_gpu)] +extern "C" { + pub fn omega_gpu_gqa_attention_f32( + q: *const f32, + k_cache: *const f32, + v_cache: *const f32, + seq_len: u32, + num_q_heads: u32, + num_kv_heads: u32, + head_dim: u32, + out: *mut f32, + info: *mut OmegaGpuAttnInfo, + ) -> c_int; + pub fn omega_gpu_paged_attention_bf16( + q: *const f32, + pool: *const u8, + layout: *const OmegaGpuKvLayout, + block_ids: *const u32, + num_block_ids: u32, + context_len: u32, + layer_idx: u32, + num_q_heads: u32, + num_kv_heads: u32, + head_dim: u32, + out: *mut f32, + info: *mut OmegaGpuAttnInfo, + ) -> c_int; + pub fn omega_gpu_paged_attention_batch_bf16( + q: *const f32, + pool: *const u8, + layout: *const OmegaGpuKvLayout, + block_tables: *const i32, + context_lens: *const i32, + max_blocks_per_seq: u32, + num_seqs: u32, + layer_idx: u32, + num_q_heads: u32, + num_kv_heads: u32, + head_dim: u32, + out: *mut f32, + info: *mut OmegaGpuAttnInfo, + ) -> c_int; + pub fn omega_gpu_attention_rc_name(rc: c_int) -> *const c_char; + pub fn omega_gpu_attention_last_error() -> *const c_char; +} diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 382ec8c2..f621f1cc 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -496,3 +496,234 @@ pub fn swiglu_f32( Err(OmegaGpuError::Unavailable) } } + +// ---- native decode attention (omega FB-1 cut 5, persistent session cut 4b) ---- + +pub use ffi::{OmegaGpuAttnInfo, OmegaGpuKvLayout}; + +/// Name of an attention return code (omega's table when native). +pub fn attn_rc_name(rc: i32) -> String { + #[cfg(has_omega_gpu)] + { + // SAFETY: returns a pointer to a static NUL-terminated string. + let p = unsafe { ffi::omega_gpu_attention_rc_name(rc) }; + if !p.is_null() { + // SAFETY: non-null, static, NUL-terminated. + return unsafe { std::ffi::CStr::from_ptr(p) } + .to_string_lossy() + .into_owned(); + } + } + match rc { + ffi::OMEGA_GPU_ATTN_OK => "OK", + ffi::OMEGA_GPU_ATTN_BAD_ARGS => "BAD_ARGS", + ffi::OMEGA_GPU_ATTN_TOO_LARGE => "TOO_LARGE", + ffi::OMEGA_GPU_ATTN_CODEGEN_FAIL => "CODEGEN_FAIL", + ffi::OMEGA_GPU_ATTN_CHIP_FAIL => "CHIP_FAIL", + ffi::OMEGA_GPU_ATTN_UNWRITTEN => "UNWRITTEN", + _ => "UNKNOWN", + } + .to_string() +} + +#[cfg(has_omega_gpu)] +fn attn_finish(rc: i32, info: OmegaGpuAttnInfo) -> Result { + if rc == ffi::OMEGA_GPU_ATTN_OK { + Ok(info) + } else { + Err(OmegaGpuError::Rc { + rc, + name: attn_rc_name(rc), + }) + } +} + +fn attn_dim(v: usize) -> Result { + u32::try_from(v).map_err(|_| OmegaGpuError::Rc { + rc: ffi::OMEGA_GPU_ATTN_TOO_LARGE, + name: attn_rc_name(ffi::OMEGA_GPU_ATTN_TOO_LARGE), + }) +} + +/// Decode attention over contiguous f32 KV (`TensorBackend::gqa_attention`). +/// `q`, `out`: `[num_q_heads][head_dim]`; `k_cache`, `v_cache`: `[seq_len][num_kv_heads][head_dim]`. +/// omega requires `head_dim == 64` and `num_q_heads <= 64`; otherwise `Rc { rc: -1 | -2 }`. +#[allow(clippy::too_many_arguments)] +pub fn gqa_attention_f32( + q: &[f32], + k_cache: &[f32], + v_cache: &[f32], + seq_len: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + out: &mut [f32], +) -> Result { + check_len("q", num_q_heads * head_dim, q.len())?; + check_len("k_cache", seq_len * num_kv_heads * head_dim, k_cache.len())?; + check_len("v_cache", seq_len * num_kv_heads * head_dim, v_cache.len())?; + check_len("out", num_q_heads * head_dim, out.len())?; + let (su, qh, kh, hd) = ( + attn_dim(seq_len)?, + attn_dim(num_q_heads)?, + attn_dim(num_kv_heads)?, + attn_dim(head_dim)?, + ); + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuAttnInfo::zeroed(); + // SAFETY: lengths checked above; pointers valid for the call; info is an out-pointer. + let rc = unsafe { + ffi::omega_gpu_gqa_attention_f32( + q.as_ptr(), + k_cache.as_ptr(), + v_cache.as_ptr(), + su, + qh, + kh, + hd, + out.as_mut_ptr(), + &mut info, + ) + }; + attn_finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (su, qh, kh, hd); + Err(OmegaGpuError::Unavailable) + } +} + +/// Decode attention over the bf16 paged KV pool (`TensorBackend::paged_attention`). +/// `pool` is the whole pool (at least `layout.pool_bytes` bytes); `block_ids` lists the +/// sequence's blocks in token order. `q`, `out`: `[num_q_heads][head_dim]`. +#[allow(clippy::too_many_arguments)] +pub fn paged_attention_bf16( + q: &[f32], + pool: &[u8], + layout: &OmegaGpuKvLayout, + block_ids: &[u32], + context_len: usize, + layer_idx: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + out: &mut [f32], +) -> Result { + check_len("q", num_q_heads * head_dim, q.len())?; + check_len("out", num_q_heads * head_dim, out.len())?; + check_pool(pool, layout)?; + let (nb, cl, li, qh, kh, hd) = ( + attn_dim(block_ids.len())?, + attn_dim(context_len)?, + attn_dim(layer_idx)?, + attn_dim(num_q_heads)?, + attn_dim(num_kv_heads)?, + attn_dim(head_dim)?, + ); + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuAttnInfo::zeroed(); + // SAFETY: q/out lengths checked; pool covers layout.pool_bytes; block_ids has nb entries. + let rc = unsafe { + ffi::omega_gpu_paged_attention_bf16( + q.as_ptr(), + pool.as_ptr(), + layout, + block_ids.as_ptr(), + nb, + cl, + li, + qh, + kh, + hd, + out.as_mut_ptr(), + &mut info, + ) + }; + attn_finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (nb, cl, li, qh, kh, hd); + Err(OmegaGpuError::Unavailable) + } +} + +/// Batched decode attention (`TensorBackend::paged_attention_batch`). +/// `block_tables`: `[num_seqs][max_blocks_per_seq]` (negative = none), `context_lens`: `[num_seqs]`. +/// `q`, `out`: `[num_seqs][num_q_heads][head_dim]`. +#[allow(clippy::too_many_arguments)] +pub fn paged_attention_batch_bf16( + q: &[f32], + pool: &[u8], + layout: &OmegaGpuKvLayout, + 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, + out: &mut [f32], +) -> Result { + check_len("q", num_seqs * num_q_heads * head_dim, q.len())?; + check_len("out", num_seqs * num_q_heads * head_dim, out.len())?; + check_len("context_lens", num_seqs, context_lens.len())?; + check_len( + "block_tables", + num_seqs * max_blocks_per_seq, + block_tables.len(), + )?; + check_pool(pool, layout)?; + let (mb, ns, li, qh, kh, hd) = ( + attn_dim(max_blocks_per_seq)?, + attn_dim(num_seqs)?, + attn_dim(layer_idx)?, + attn_dim(num_q_heads)?, + attn_dim(num_kv_heads)?, + attn_dim(head_dim)?, + ); + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuAttnInfo::zeroed(); + // SAFETY: every slice length checked against the stated shape; pool covers the layout. + let rc = unsafe { + ffi::omega_gpu_paged_attention_batch_bf16( + q.as_ptr(), + pool.as_ptr(), + layout, + block_tables.as_ptr(), + context_lens.as_ptr(), + mb, + ns, + li, + qh, + kh, + hd, + out.as_mut_ptr(), + &mut info, + ) + }; + attn_finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (mb, ns, li, qh, kh, hd); + Err(OmegaGpuError::Unavailable) + } +} + +fn check_pool(pool: &[u8], layout: &OmegaGpuKvLayout) -> Result<(), OmegaGpuError> { + let need = usize::try_from(layout.pool_bytes).unwrap_or(usize::MAX); + if pool.len() < need { + return Err(OmegaGpuError::ShapeMismatch { + what: "pool", + expected: need, + got: pool.len(), + }); + } + Ok(()) +} diff --git a/omega.lock b/omega.lock index 49c20dca..1d632393 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -6b940faa9df2baffa7d38ec3cafdf4a55fd91289 +3d4648c7ee767e18066d1a82b9f0cffb6bac9255 ```