diff --git a/.crumb b/.crumb index ae513c3d..d7053ee9 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-07T05:30:19Z", + "compiled_at": "2026-10-07T05:51:10Z", "compiler": "crumb-compile/1", - "digest": "sha256:3a6c25567b8a8fe62f1928014499205e0c2c6faf944e2bd09de2224f976bb35a", + "digest": "sha256:126a21c4562d45f679f00d01fc1bed1efbfc632f025ebc4419b0d7c0162f982b", "evidence_files": 155, "evidence_root": "sha256:ff6dddfecfcc02cea55f46acaccc7eaecd27557209e98c3d5616ec02bdde31db", "files": 1133, - "generated_at_commit": "bf1631593c789c24c878204e36124ee7cdae4cb1", - "source_tree": "sha256:9469cf8ea981a2f8363b740d2a8d61102e17793bb65a111c836b7ca70daecd52" + "generated_at_commit": "02e10da264f0ff8a27e559208616d6d8c14284a7", + "source_tree": "sha256:e0373fc57513028cf9323459427a1fd0c8131db9fd3d1d7f26b856faf96d7b6f" } }, "history": [], diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index 724cfb36..384b5675 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -160,6 +160,10 @@ pub trait TensorBackend: Send + Sync { /// out[i] = x[i] * weight[i] / sqrt(mean(x^2) + eps) fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32); + /// Per-head RMS normalization in place (Qwen3 q/k norm): `x` is `[heads][head_dim]` and every + /// head is normalized on its own with the same `weight` (`head_dim` values). + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32); + /// In-place Rotary Positional Embeddings (RoPE) following canonical rotate_half convention: /// rot(v) = [-v[half_dim..], v[..half_dim]] /// out = v * cos(pos * f_i) + rot(v) * sin(pos * f_i), with f_i = `rope.inv_freq(i, head_dim)` @@ -381,6 +385,10 @@ impl TensorBackend for ReferenceCpuBackend { tensor_rmsnorm(x, weight, eps, out); } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + crate::tensor::rmsnorm_heads_in_place(x, weight, head_dim, eps); + } + fn apply_rope( &self, q: &mut [f32], diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index cc9dde26..bbb3cf7d 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -33,9 +33,10 @@ pub use model_dir::{load_model_config, model_config_from_hf_json, model_id_for_d pub use moe_plan::*; pub use mojo_backend::*; pub use omega_backend::{ - omega_backend_selected, omega_model_refusal, open_gpu_session_with_retry, retry_bounded, - retry_bounded_within, OmegaGb10Backend, SessionAttemptError, GPU_BACKEND_ENV, - GPU_SESSION_OPEN_ATTEMPTS, GPU_SESSION_OPEN_DEADLINE, GPU_SESSION_RETRY_DELAY, + omega_backend_selected, omega_model_refusal, omega_model_refusal_with, + open_gpu_session_with_retry, retry_bounded, retry_bounded_within, OmegaGb10Backend, + SessionAttemptError, GB10_QWEN3_OPT_IN_ENV, GPU_BACKEND_ENV, GPU_SESSION_OPEN_ATTEMPTS, + GPU_SESSION_OPEN_DEADLINE, GPU_SESSION_RETRY_DELAY, }; pub use qwen3_coder::*; pub use qwen3_moe::*; diff --git a/crates/aien-inference-abi/src/mojo_backend.rs b/crates/aien-inference-abi/src/mojo_backend.rs index 2ec08d2b..90168900 100644 --- a/crates/aien-inference-abi/src/mojo_backend.rs +++ b/crates/aien-inference-abi/src/mojo_backend.rs @@ -262,6 +262,11 @@ impl TensorBackend for MojoGb10Backend { self.fallback.rmsnorm(out, x, weight, eps); } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + // No Mojo kernel for per-head norm: reference path, like every unbound op here. + self.fallback.rmsnorm_heads(x, weight, head_dim, eps); + } + fn apply_rope( &self, q: &mut [f32], diff --git a/crates/aien-inference-abi/src/native_ops.rs b/crates/aien-inference-abi/src/native_ops.rs index 837246e2..efb91780 100644 --- a/crates/aien-inference-abi/src/native_ops.rs +++ b/crates/aien-inference-abi/src/native_ops.rs @@ -13,7 +13,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; -/// The nine operations of `TensorBackend` (fallback_count is not an op). +/// The ten operations of `TensorBackend` (fallback_count is not an op). New ops go last so +/// existing mask bits keep their positions. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum TensorOp { @@ -26,10 +27,11 @@ pub enum TensorOp { PagedAttention, PagedAttentionBatch, ComputeLogits, + RmsnormHeads, } impl TensorOp { - pub const COUNT: usize = 9; + pub const COUNT: usize = 10; pub const ALL: [TensorOp; Self::COUNT] = [ TensorOp::Rmsnorm, TensorOp::ApplyRope, @@ -40,6 +42,7 @@ impl TensorOp { TensorOp::PagedAttention, TensorOp::PagedAttentionBatch, TensorOp::ComputeLogits, + TensorOp::RmsnormHeads, ]; fn index(self) -> usize { @@ -58,6 +61,7 @@ impl TensorOp { TensorOp::PagedAttention => "paged_attention", TensorOp::PagedAttentionBatch => "paged_attention_batch", TensorOp::ComputeLogits => "compute_logits", + TensorOp::RmsnormHeads => "rmsnorm_heads", } } } @@ -235,7 +239,16 @@ mod tests { assert_eq!(m, NativeOpMask::ALL); assert!(TensorOp::ALL.iter().all(|op| m.contains(*op))); assert!(m.reference_ops().is_empty()); - assert_eq!(m.native_ops().len(), 9); + assert_eq!(m.native_ops().len(), TensorOp::COUNT); + } + + #[test] + fn op_bits_are_stable() { + // The nine original ops keep bits 0..8; rmsnorm_heads (Qwen3 q/k norm) is bit 9. + assert_eq!(NativeOpMask::from_ops(&[TensorOp::Rmsnorm]).0, 1 << 0); + assert_eq!(NativeOpMask::from_ops(&[TensorOp::ComputeLogits]).0, 1 << 8); + assert_eq!(NativeOpMask::from_ops(&[TensorOp::RmsnormHeads]).0, 1 << 9); + assert_eq!(TensorOp::RmsnormHeads.name(), "rmsnorm_heads"); } #[test] @@ -244,7 +257,7 @@ mod tests { assert!(m.contains(TensorOp::MatmulVec)); assert!(!m.contains(TensorOp::Rmsnorm)); assert_eq!(m.native_ops().len(), 2); - assert_eq!(m.reference_ops().len(), 7); + assert_eq!(m.reference_ops().len(), TensorOp::COUNT - 2); let m2 = m.with(TensorOp::ComputeLogits).without(TensorOp::MatmulVec); assert!(m2.contains(TensorOp::ComputeLogits)); assert!(!m2.contains(TensorOp::MatmulVec)); @@ -308,7 +321,7 @@ mod tests { acct.record_reference(TensorOp::MatmulBatch); let rep = acct.report(); assert_eq!(rep.native_ops, vec!["matmul_vec", "matmul_batch"]); - assert_eq!(rep.reference_ops.len(), 7); + assert_eq!(rep.reference_ops.len(), TensorOp::COUNT - 2); assert_eq!(rep.native_fallbacks, vec![("matmul_batch".to_string(), 1)]); assert_eq!(rep.reference_runs, vec![("rmsnorm".to_string(), 1)]); let line = rep.line(); @@ -320,7 +333,7 @@ mod tests { #[test] fn default_report_is_all_native() { let rep = OpReport::all_native(); - assert_eq!(rep.native_ops.len(), 9); + assert_eq!(rep.native_ops.len(), TensorOp::COUNT); assert!(rep.reference_ops.is_empty()); assert!(rep.native_fallbacks.is_empty()); } diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index 30e9e4f5..12c97a99 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -1,14 +1,15 @@ -//! `OmegaGb10Backend` (FB-1 cuts 3b, 3c, 3d): all nine `TensorBackend` ops run on our own +//! `OmegaGb10Backend` (FB-1 cuts 3b, 3c, 3d): all ten `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`, +//! Native mask: `matmul_vec`, `matmul_batch`, `compute_logits`, `rmsnorm`, `rmsnorm_heads`, //! `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) or 128 (since omega b564bf4; -//! Qwen3 is still refused, see `omega_model_refusal`). A chip error in -//! one of those is a fallback of a claimed-native op: it is counted, goes through +//! omega attention needs head_dim 64 (TinyLlama, Llama-3.2-1B) or 128 (Qwen3-4B, since omega +//! b564bf4; Qwen3 is refused by default while omega#327 is open and at any other head_dim +//! always, see `omega_model_refusal`). 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. //! @@ -109,6 +110,7 @@ impl OmegaGb10Backend { TensorOp::MatmulBatch, TensorOp::ComputeLogits, TensorOp::Rmsnorm, + TensorOp::RmsnormHeads, TensorOp::ApplyRope, TensorOp::Swiglu, TensorOp::GqaAttention, @@ -289,6 +291,22 @@ impl OmegaGb10Backend { }) } + /// Every head is one row of omega's row-wise rmsnorm (same weight for each row), one launch. + fn chip_rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) -> bool { + if head_dim == 0 || !x.len().is_multiple_of(head_dim) || weight.len() != head_dim { + return self.fail(format!( + "rmsnorm_heads shape mismatch: x={} weight={} head_dim={head_dim}", + x.len(), + weight.len() + )); + } + let rows = x.len() / head_dim; + let input = x.to_vec(); + self.chip_elementwise(&format!("rmsnorm_heads rows={rows} dim={head_dim}"), || { + aien_omega_gpu::rmsnorm_f32(rows, head_dim, &input, weight, eps, x) + }) + } + /// q then k go to the chip as one `heads` run (the table is the same for every head). #[allow(clippy::too_many_arguments)] fn chip_rope( @@ -496,26 +514,68 @@ impl OmegaGb10Backend { } } -/// Why the GB10 engine refuses `config`, if it does: Qwen3 (`qk_norm`) needs a per-head q/k -/// norm, which has no engine op. It is host math in `TransformerLayerWeights::apply_qk_norm`, -/// outside the `TensorBackend`, so a GB10 run would compute it on the CPU without op accounting. -/// The attention kernel itself accepts `head_dim` 128 since omega b564bf4 (omega -/// `omega_gpu_attention_api.h`); opening the GB10 Qwen3 path is its own qualification. +/// Why the GB10 engine refuses `config`, if it does. Qwen3 (`qk_norm`) runs its per-head q/k +/// norm as `rmsnorm_heads`, one row per head on omega's row-wise rmsnorm, which needs +/// `head_dim % 128 == 0` (omega `omega_gpu_elementwise_api.h`); attention takes `head_dim` 64 or +/// 128 (omega `omega_gpu_attention_api.h`, since b564bf4). So a Qwen3 model runs on the engine +/// only with `head_dim` 128 (Qwen3-4B) and is refused up front otherwise, before any chip work. /// Llama-architecture models are not touched by this check. +/// +/// Qwen3 at `head_dim` 128 is also refused by default while omega#327 is open: in the +/// normal memory state (MemFree low, most memory in clean page cache) the driver's channel +/// and weight allocations fail with NV_ERR_NO_MEMORY after the f32 weight load +/// (sovereign-core #274, declared attempt 1). A declared chip attempt opts in with +/// [`GB10_QWEN3_OPT_IN_ENV`]` = 1`; see [`omega_model_refusal_with`]. pub fn omega_model_refusal(config: &ModelConfig) -> Option { - config.qk_norm.then(|| { - format!( - "OmegaGb10Backend refuses model {:?}: Qwen3 (per-head q/k norm, head_dim {}) is \ - unsupported on the GB10 engine: the per-head q/k norm runs only on the CPU, with no \ - GB10 engine op; run it on the CPU reference backend", + omega_model_refusal_with(config, gb10_qwen3_opted_in()) +} + +/// Environment switch for a declared GB10 attempt that runs Qwen3 although omega#327 is +/// open. Only the exact value `1` opts in; unset or anything else keeps the refusal. +pub const GB10_QWEN3_OPT_IN_ENV: &str = "AIEN_GB10_QWEN3_DECLARED_ATTEMPT"; + +fn gb10_qwen3_opted_in() -> bool { + std::env::var(GB10_QWEN3_OPT_IN_ENV).is_ok_and(|v| v == "1") +} + +/// [`omega_model_refusal`] with the opt-in passed explicitly instead of read from the +/// environment. +pub fn omega_model_refusal_with(config: &ModelConfig, qwen3_opted_in: bool) -> Option { + if !config.qk_norm { + return None; + } + if config.head_dim != 128 { + return Some(format!( + "OmegaGb10Backend refuses model {:?}: Qwen3 (per-head q/k norm) with head_dim {} is \ + unsupported on the GB10 engine, which runs Qwen3 only at head_dim 128 (rmsnorm_heads \ + needs head_dim % 128 == 0); run it on the CPU reference backend", config.model_id, config.head_dim + )); + } + (!qwen3_opted_in).then(|| { + format!( + "OmegaGb10Backend refuses model {:?}: the GB10 Qwen3 path is off by default while the \ + resident-weight memory issue omega#327 is open (the driver's channel and weight \ + allocations fail with NV_ERR_NO_MEMORY when MemFree is low after the f32 weight \ + load); run it on the CPU reference backend, or set {GB10_QWEN3_OPT_IN_ENV}=1 for a \ + declared chip attempt", + config.model_id ) }) } impl TensorBackend for OmegaGb10Backend { fn check_model(&self, config: &ModelConfig) -> Result<(), String> { - omega_model_refusal(config).map_or(Ok(()), Err) + omega_model_refusal(config).map_or(Ok(()), Err)?; + if config.qk_norm { + eprintln!( + "OMEGA_BACKEND WARNING: {GB10_QWEN3_OPT_IN_ENV}=1, running Qwen3 {:?} on GB10 \ + although omega#327 (NV_ERR_NO_MEMORY on low MemFree) is open; for a declared \ + chip attempt only", + config.model_id + ); + } + Ok(()) } fn name(&self) -> &'static str { @@ -545,6 +605,13 @@ impl TensorBackend for OmegaGb10Backend { } } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + if !self.chip_rmsnorm_heads(x, weight, head_dim, eps) { + self.reference_for(TensorOp::RmsnormHeads); + self.reference.rmsnorm_heads(x, weight, head_dim, eps); + } + } + fn apply_rope( &self, q: &mut [f32], @@ -960,7 +1027,7 @@ mod tests { } #[test] - fn mask_is_all_nine_ops() { + fn mask_is_all_ten_ops() { let b = OmegaGb10Backend::new(); let names: Vec<_> = b .native_ops() @@ -979,7 +1046,8 @@ mod tests { "gqa_attention", "paged_attention", "paged_attention_batch", - "compute_logits" + "compute_logits", + "rmsnorm_heads" ] ); } diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index ae0b9b43..565c8ce0 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -780,7 +780,7 @@ impl NativeTransformerBackend { backend.matmul_vec(&mut k, &x_norm, &layer_w.k_proj, kv_dim, hidden_dim); backend.matmul_vec(&mut v, &x_norm, &layer_w.v_proj, kv_dim, hidden_dim); - layer_w.apply_qk_norm(&mut q, &mut k, head_dim, eps); + layer_w.apply_qk_norm_on(backend, &mut q, &mut k, head_dim, eps); backend.apply_rope( &mut q, &mut k, @@ -1112,7 +1112,7 @@ impl NativeTransformerBackend { let v_t = &v_batch[t * kv_dim..(t + 1) * kv_dim]; let pos = offset + t; - layer_w.apply_qk_norm(q_t, k_t, head_dim, eps); + layer_w.apply_qk_norm_on(backend, q_t, k_t, head_dim, eps); backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, &rope); if let (Some((block_id, slot)), Some(mgr)) = (paged_slots[t], kv_manager) { @@ -1433,7 +1433,8 @@ impl NativeTransformerBackend { // c. RoPE across all D sequences at their respective positions for (i, &(_seq_id, _tok, pos)) in valid_reqs.iter().enumerate() { - layer_w.apply_qk_norm( + layer_w.apply_qk_norm_on( + self.tensor_backend.as_ref(), &mut q_batch[i * q_dim..(i + 1) * q_dim], &mut k_batch[i * kv_dim..(i + 1) * kv_dim], head_dim, diff --git a/crates/aien-inference-abi/src/weights.rs b/crates/aien-inference-abi/src/weights.rs index 336e13d8..8e690734 100644 --- a/crates/aien-inference-abi/src/weights.rs +++ b/crates/aien-inference-abi/src/weights.rs @@ -51,6 +51,24 @@ impl TransformerLayerWeights { rmsnorm_heads_in_place(k, w, head_dim, eps); } } + + /// [`Self::apply_qk_norm`] through `backend` (`TensorBackend::rmsnorm_heads`), so a device + /// backend runs it and accounts for it like any other op. A no-op without q_norm/k_norm. + pub fn apply_qk_norm_on( + &self, + backend: &dyn crate::backend::TensorBackend, + q: &mut [f32], + k: &mut [f32], + head_dim: usize, + eps: f32, + ) { + if let Some(w) = &self.q_norm { + backend.rmsnorm_heads(q, w, head_dim, eps); + } + if let Some(w) = &self.k_norm { + backend.rmsnorm_heads(k, w, head_dim, eps); + } + } } #[derive(Debug, Clone)] diff --git a/crates/aien-inference-abi/tests/omega_backend_parity.rs b/crates/aien-inference-abi/tests/omega_backend_parity.rs index d1d56c94..dfd7ca13 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(), 9); + assert_eq!(b.native_ops().native_ops().len(), 10); } #[test] @@ -177,6 +177,59 @@ fn chip_elementwise_parity_on_tinyllama_shapes() { println!("PARITY elementwise {}", omega.op_report().line()); } +/// Qwen3-4B shapes: `rmsnorm_heads` (32 q heads and 8 kv heads of 128, eps 1e-6, one launch each) +/// within the elementwise tolerance, and rope at head_dim 128 with theta 5000000 bit-exact, +/// against ReferenceCpuBackend. Same criteria as the TinyLlama elementwise test above. +#[test] +#[ignore = "chip test: needs a native build and the GB10; run through the heavy queue"] +fn chip_elementwise_parity_on_qwen3_shapes() { + let omega = OmegaGb10Backend::new(); + assert!(omega.is_available(), "native build required"); + let reference = ReferenceCpuBackend::new(); + let mut seed = 4242u32; + let (hd, nq, nkv) = (128usize, 32usize, 8usize); + + let mut heads_worst = 0.0f64; + for heads in [nq, nkv] { + let w: Vec = (0..hd).map(|_| lcg(&mut seed) * 4.0 + 1.0).collect(); + for trial in 0..10 { + let scale = if trial == 9 { 50.0 } else { 2.0 }; + let x: Vec = (0..heads * hd).map(|_| lcg(&mut seed) * scale).collect(); + let (mut got, mut want) = (x.clone(), x.clone()); + omega.rmsnorm_heads(&mut got, &w, hd, 1e-6); + reference.rmsnorm_heads(&mut want, &w, hd, 1e-6); + heads_worst = heads_worst.max(worst_tol_ratio(&got, &want)); + } + } + println!("PARITY rmsnorm_heads 32x128 and 8x128 worst err/tolerance = {heads_worst:.3e} (must be <= 1)"); + assert!(heads_worst <= 1.0, "rmsnorm_heads outside tolerance"); + + let theta = &aien_inference_abi::RopeParams::plain(5_000_000.0); + let mut rope_mismatch = 0usize; + for pos in [0usize, 1, 2, 37, 511, 1500, 4095] { + let q0: Vec = (0..nq * hd).map(|_| lcg(&mut seed) * 3.0).collect(); + let k0: Vec = (0..nkv * hd).map(|_| lcg(&mut seed) * 3.0).collect(); + let (mut qg, mut kg) = (q0.clone(), k0.clone()); + let (mut qw, mut kw) = (q0.clone(), k0.clone()); + omega.apply_rope(&mut qg, &mut kg, pos, hd, nq, nkv, theta); + reference.apply_rope(&mut qw, &mut kw, pos, hd, nq, nkv, theta); + rope_mismatch += qg + .iter() + .zip(&qw) + .chain(kg.iter().zip(&kw)) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + } + println!( + "PARITY rope 32+8 heads x 128 theta 5e6, 7 positions: bit mismatches = {rope_mismatch}" + ); + assert_eq!(rope_mismatch, 0, "rope must be bit-exact"); + + assert_eq!(omega.fallback_count(), 0, "{}", omega.last_error()); + assert_eq!(omega.chip_errors(), 0, "{}", omega.last_error()); + println!("PARITY qwen3 elementwise {}", omega.op_report().line()); +} + /// Diagnostic for the cut-3c finding: elementwise launches after the matmul device is /// open. Run with AIEN_DEV_FALLBACK=1 so a failure is reported instead of a strict panic. #[test] diff --git a/crates/aien-inference-abi/tests/qwen3_forward_parity.rs b/crates/aien-inference-abi/tests/qwen3_forward_parity.rs index febaafd1..b361f4a5 100644 --- a/crates/aien-inference-abi/tests/qwen3_forward_parity.rs +++ b/crates/aien-inference-abi/tests/qwen3_forward_parity.rs @@ -19,11 +19,14 @@ //! tolerance (5e-3 absolute on 36 layers) was set before the run. use aien_inference_abi::{ - load_model_config, model_config_from_hf_json, omega_model_refusal, NativeTransformerBackend, - SequenceState, TransformerWeights, + load_model_config, model_config_from_hf_json, omega_model_refusal, omega_model_refusal_with, + NativeTransformerBackend, ReferenceCpuBackend, SequenceState, TensorBackend, + TransformerWeights, GB10_QWEN3_OPT_IN_ENV, }; use serde_json::Value; use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; const ABSOLUTE_TOLERANCE: f32 = 1e-4; @@ -345,16 +348,166 @@ fn gb10_backend_refuses_qwen3_and_not_llama() { Some("{\"eos_token_id\":[151645]}"), ) .unwrap(); - let msg = omega_model_refusal(&q).expect("Qwen3 must be refused on the GB10 engine"); + // Qwen3-4B (head_dim 128): rmsnorm_heads and attention both run on the engine, but the + // path stays off by default while omega#327 (NV_ERR_NO_MEMORY on low MemFree) is open. + assert_eq!(q.head_dim, 128); + let msg = omega_model_refusal_with(&q, false) + .expect("Qwen3-4B must be refused on the GB10 engine by default"); assert!( - msg.contains("head_dim 128") - && msg.contains("Qwen3") - && msg.contains("q/k norm runs only on the CPU") - && !msg.contains("head_dim 64 only"), + msg.contains("omega#327") + && msg.contains("NV_ERR_NO_MEMORY") + && msg.contains("AIEN_GB10_QWEN3_DECLARED_ATTEMPT=1"), "{msg}" ); + assert_eq!(omega_model_refusal_with(&q, true), None); + if std::env::var(GB10_QWEN3_OPT_IN_ENV).is_err() { + assert_eq!(omega_model_refusal(&q), Some(msg)); + } + // A Qwen3 shape with head_dim 64 cannot run rmsnorm_heads (head_dim % 128): refused up front. + let q64 = model_config_from_hf_json( + "qwen3-head-dim-64", + &real_config_json().replace("\"head_dim\": 128", "\"head_dim\": 64"), + Some("{\"eos_token_id\":[151645]}"), + ) + .unwrap(); + assert_eq!(q64.head_dim, 64); + // The opt-in does not lift this one. + for opted_in in [false, true] { + let msg = omega_model_refusal_with(&q64, opted_in) + .expect("Qwen3 with head_dim 64 must be refused on the GB10 engine"); + assert!( + msg.contains("head_dim 64") + && msg.contains("Qwen3") + && msg.contains("only at head_dim 128"), + "{msg}" + ); + } let llama = aien_inference_abi::ModelConfig::tinyllama_1_1b(); assert!(omega_model_refusal(&llama).is_none()); + assert!(omega_model_refusal_with(&llama, false).is_none()); +} + +/// Delegates every op to the reference backend and counts `rmsnorm_heads` calls. +#[derive(Default)] +struct HeadsSpy { + inner: ReferenceCpuBackend, + heads_calls: AtomicU64, +} + +impl TensorBackend for HeadsSpy { + fn name(&self) -> &'static str { + "HeadsSpy" + } + fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { + self.inner.rmsnorm(out, x, weight, eps) + } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + self.heads_calls.fetch_add(1, Ordering::Relaxed); + self.inner.rmsnorm_heads(x, weight, head_dim, eps) + } + fn apply_rope( + &self, + q: &mut [f32], + k: &mut [f32], + pos: usize, + head_dim: usize, + num_q_heads: usize, + num_kv_heads: usize, + rope: &aien_inference_abi::RopeParams, + ) { + self.inner + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope) + } + fn matmul_vec( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + out_dim: usize, + in_dim: usize, + ) { + self.inner.matmul_vec(out, x, weight, out_dim, in_dim) + } + fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { + 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.inner.gqa_attention( + out, + q, + k_cache, + v_cache, + seq_len, + 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.inner + .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim) + } +} + +/// The q/k norm goes through `TensorBackend::rmsnorm_heads` on every forward path (prefill, +/// batch decode, single-token decode): two calls (q, k) per layer per token, and the logits still +/// match transformers. A device backend therefore runs and accounts for it; before this, the +/// norm was host math outside the backend. +#[test] +fn qwen3_qk_norm_runs_through_the_tensor_backend() { + let (weights, r) = tiny(); + let per_token = 2 * weights.config.num_layers as u64; + let n = r.ids.len(); + let spy = Arc::new(HeadsSpy::default()); + let calls = || spy.heads_calls.load(Ordering::Relaxed); + let mut b = NativeTransformerBackend::with_backend(weights, spy.clone()); + + b.prefill_sequence(1, &r.ids[..n - 1]).expect("prefill"); + assert_eq!(calls(), per_token * (n as u64 - 1), "prefill"); + + b.pending_prefill_token.insert(1, r.ids[n - 1]); + let (_out, logits) = b + .forward_decode_batch_with_logits(&[1]) + .expect("batch decode"); + assert_eq!(calls(), per_token * n as u64, "batch decode"); + let d = max_abs(&logits[0], &r.logits); + assert!(d <= ABSOLUTE_TOLERANCE, "batch decode max abs diff {d:e}"); + + b.prefill_sequence(2, &r.ids[..n - 1]).expect("prefill"); + let before = calls(); + let seq = b.sequences.get_mut(&2).unwrap(); + let h = NativeTransformerBackend::forward_token_impl_paged( + &b.weights, + &*b.tensor_backend, + r.ids[n - 1], + n - 1, + seq, + 2, + None, + ); + assert_eq!(calls(), before + per_token, "single-token decode"); + let d = max_abs(&b.compute_logits(&h), &r.logits); + assert!( + d <= ABSOLUTE_TOLERANCE, + "single-token decode max abs diff {d:e}" + ); } #[test] @@ -408,6 +561,74 @@ fn real_qwen3_4b_instruct_2507_matches_transformers() { assert!(d <= 5e-3, "max abs diff {d:e}"); } +/// Real Qwen3-4B-Instruct-2507 prefill on the GB10 engine (every op native, q/k norm as +/// `rmsnorm_heads`) against the same transformers reference. Bound, set before any run: the +/// project's GB10 logit bound `MAX_ABS_DLOGIT` = 0.15 (aien-inference-runtime tests/drift, from +/// the Llama cut 3d measurement 0.059) over the reference top-20, the same argmax, no fallback +/// and no chip error. Chip test: native build, AIEN_QWEN3_DIR, heavy queue / GPU hold only. +#[test] +#[ignore = "chip test: needs a native build, the GB10 and AIEN_QWEN3_DIR; run under a GPU hold"] +fn real_qwen3_4b_instruct_2507_on_gb10_matches_transformers() { + let omega = Arc::new(aien_inference_abi::OmegaGb10Backend::new()); + assert!(omega.is_available(), "native build required"); + let dir = PathBuf::from( + std::env::var("AIEN_QWEN3_DIR").expect("AIEN_QWEN3_DIR must name the model directory"), + ); + let r: Value = serde_json::from_str( + &std::fs::read_to_string( + fixture("qwen3-4b-instruct-2507-config").join("real_forward_reference.json"), + ) + .unwrap(), + ) + .unwrap(); + let ids: Vec = r["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap() as u32) + .collect(); + let top_ids: Vec = r["top_ids"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_u64().unwrap() as usize) + .collect(); + let top_logits: Vec = r["top_logits"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_f64().unwrap() as f32) + .collect(); + let config = load_model_config(&dir).expect("config"); + omega + .check_model(&config) + .expect("GB10 engine must accept Qwen3-4B (a declared attempt sets AIEN_GB10_QWEN3_DECLARED_ATTEMPT=1)"); + let weights = TransformerWeights::load_from_safetensors( + dir.join("model.safetensors.index.json"), + &config, + ) + .expect("weights"); + let mut b = NativeTransformerBackend::with_backend(weights, omega.clone()); + let got = b + .prefill_sequence(1, &ids) + .expect("prefill on the GB10 engine"); + let ours: Vec = top_ids.iter().map(|i| got[*i]).collect(); + let d = max_abs(&ours, &top_logits); + println!( + "QWEN3_GB10 max abs diff over the reference top-20 = {d:e} (bound 0.15), argmax {} vs {}, \ + chip_errors={} fallbacks={} {}", + argmax(&got), + top_ids[0], + omega.chip_errors(), + omega.fallback_count(), + omega.op_report().line() + ); + assert_eq!(omega.chip_errors(), 0, "{}", omega.last_error()); + assert_eq!(omega.fallback_count(), 0, "{}", omega.last_error()); + assert_eq!(argmax(&got), top_ids[0]); + assert!(d <= 0.15, "max abs diff {d:e}"); +} + /// Batch decode (`forward_decode_batch_with_logits`, the third q/k-norm site): two sequences /// with the reference prompt must reproduce the transformers logits, and a third, different /// sequence in the same batch must equal its own single-sequence decode. diff --git a/crates/aien-inference-runtime/tests/oracle/mod.rs b/crates/aien-inference-runtime/tests/oracle/mod.rs index 1b4d9a37..f0dc7866 100644 --- a/crates/aien-inference-runtime/tests/oracle/mod.rs +++ b/crates/aien-inference-runtime/tests/oracle/mod.rs @@ -152,6 +152,10 @@ impl TensorBackend for CountingBackend { self.hit(TensorOp::Rmsnorm); self.inner.rmsnorm(out, x, weight, eps) } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + self.hit(TensorOp::RmsnormHeads); + self.inner.rmsnorm_heads(x, weight, head_dim, eps) + } fn apply_rope( &self, q: &mut [f32], diff --git a/crates/aien-runtime/tests/prefill_e2e2.rs b/crates/aien-runtime/tests/prefill_e2e2.rs index 0dd7fc11..b4f45a4a 100644 --- a/crates/aien-runtime/tests/prefill_e2e2.rs +++ b/crates/aien-runtime/tests/prefill_e2e2.rs @@ -497,6 +497,10 @@ impl TensorBackend for CountingBackend { self.inner.rmsnorm(out, x, weight, eps); } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + self.inner.rmsnorm_heads(x, weight, head_dim, eps); + } + fn apply_rope( &self, q: &mut [f32], diff --git a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs index 79b1d1c7..8b83592b 100644 --- a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs +++ b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs @@ -168,6 +168,10 @@ impl TensorBackend for CountingBackend { self.hit(TensorOp::Rmsnorm); self.inner.rmsnorm(out, x, weight, eps) } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + self.hit(TensorOp::RmsnormHeads); + self.inner.rmsnorm_heads(x, weight, head_dim, eps) + } fn apply_rope( &self, q: &mut [f32],