From 0607182837efbdfa18c584ee1b60d48d058860fa Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 14:31:58 -0500 Subject: [PATCH 1/2] abi: typed AttentionGeometry contract; attention paths check heads, widths and pool layout SC-1 of Drake's attention hardening cut. - aien-abi-core: `AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim)` is the only constructor; it refuses zero heads or width, non-divisible head counts and a q_dim/kv_dim that overflows usize, and names the numbers in the error. Accessors q_dim, kv_dim, gqa_ratio, kv_head_of(q_head), check_kv_pool(kv_heads, head_dim). Deliberately no power-of-two ratio, no q_dim == hidden_dim (Qwen3-Coder: 4096 vs 2048) and no Q == KV requirement. Serde re-runs the checks on deserialise. `ModelConfig::attention_geometry()` exposes it. - aien-inference-abi reference/trait defaults (gqa_attention, paged_attention, paged_attention_batch): geometry, q/out widths and pool kv_heads/head_dim are checked before any element is read; a mismatch panics with the exact geometry (the trait returns (), so a wrong layout must never turn into numbers). - OmegaGb10Backend: chip_paged_one and gqa_attention refuse geometry, q/out width and pool-layout mismatches before any native code runs (counted via fail()). - TransformerBackend: the three forward paths derive q_dim/kv_dim from the checked geometry and return Err on a bad config instead of slicing wrongly. Tests: crates/aien-abi-core/tests/attention_geometry.rs (10 cases incl. Qwen3-Coder q_dim != hidden_dim, ratio 3 and 5 accepted, zero/non-divisible/overflow refused, pool mismatch named, serde recheck). fmt + clippy (-D warnings, 4 crates, all targets) clean; AIEN_DEV_FALLBACK=1 AIEN_FORCE_CPU_STUB=1 cargo test on the 4 crates: all PASS (0 failed). Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- .crumb | 10 +- Cargo.lock | 1 + crates/aien-abi-core/Cargo.toml | 3 + crates/aien-abi-core/src/lib.rs | 200 ++++++++++++++++++ .../aien-abi-core/tests/attention_geometry.rs | 151 +++++++++++++ crates/aien-inference-abi/src/backend.rs | 75 ++++++- .../aien-inference-abi/src/omega_backend.rs | 56 +++-- .../src/transformer_backend.rs | 49 +++-- 8 files changed, 509 insertions(+), 36 deletions(-) create mode 100644 crates/aien-abi-core/tests/attention_geometry.rs diff --git a/.crumb b/.crumb index 0503c299..69b7e0b9 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:dfcfd805db0c30c667bc5682364bd3acb3383d494967dcae39f2420739723d7d", - "compiled_at": "2026-10-04T19:07:25Z", + "compiled_at": "2026-10-04T19:57:23Z", "compiler": "crumb-compile/1", - "digest": "sha256:c96cedd67ca67fa0d0dc9fa9a2eff7f7bdfe480ff8725ba72b1c387e5ef6a5e4", + "digest": "sha256:57acab1c0a88266597b4b6c2f37a9d5d99b72049e7f5c3dfd7bffe151f16c70f", "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", - "files": 675, - "generated_at_commit": "2f9570a04f137de59afda33d29d3994993ab56c9", - "source_tree": "sha256:f958c571fffbecd3c2b0bea616aedad59a58c39063d50017eec51b80c4e02ca0" + "files": 676, + "generated_at_commit": "75800398eb53646444d4c12e5a27fdc26cd14e04", + "source_tree": "sha256:8c5cd62485332468eab8185a24cd6a2ed9936353094a09b5eb44f2f66e6e9109" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 3ef9ad1e..034bfdd6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -31,6 +31,7 @@ version = "0.1.0" dependencies = [ "async-trait", "serde", + "serde_json", ] [[package]] diff --git a/crates/aien-abi-core/Cargo.toml b/crates/aien-abi-core/Cargo.toml index fbf98449..ef8361fa 100644 --- a/crates/aien-abi-core/Cargo.toml +++ b/crates/aien-abi-core/Cargo.toml @@ -9,3 +9,6 @@ license.workspace = true [dependencies] async-trait = "0.1" serde = { version = "1.0", features = ["derive"] } + +[dev-dependencies] +serde_json = "1.0" diff --git a/crates/aien-abi-core/src/lib.rs b/crates/aien-abi-core/src/lib.rs index 92539c20..aaafcc75 100644 --- a/crates/aien-abi-core/src/lib.rs +++ b/crates/aien-abi-core/src/lib.rs @@ -59,6 +59,200 @@ pub struct ModelConfig { pub rope_theta: f32, } +/// Why an [`AttentionGeometry`] was refused. Every variant names the offending numbers so a +/// refusal in a log says what to fix. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum AttentionGeometryError { + ZeroQueryHeads, + ZeroKvHeads, + ZeroHeadDim, + /// `num_q_heads` is not a whole multiple of `num_kv_heads` (every kv head must serve the + /// same number of query heads). + QueryHeadsNotDivisible { + num_q_heads: usize, + num_kv_heads: usize, + }, + /// `num_q_heads * head_dim` or `num_kv_heads * head_dim` does not fit in `usize`. + Overflow { + heads: usize, + head_dim: usize, + }, + /// A KV pool (or any KV buffer) is laid out for a different kv-head count or head width + /// than this geometry. + KvPoolMismatch { + geometry_kv_heads: usize, + geometry_head_dim: usize, + pool_kv_heads: usize, + pool_head_dim: usize, + }, +} + +impl std::fmt::Display for AttentionGeometryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::ZeroQueryHeads => write!(f, "attention geometry: num_q_heads is 0"), + Self::ZeroKvHeads => write!(f, "attention geometry: num_kv_heads is 0"), + Self::ZeroHeadDim => write!(f, "attention geometry: head_dim is 0"), + Self::QueryHeadsNotDivisible { + num_q_heads, + num_kv_heads, + } => write!( + f, + "attention geometry: num_q_heads {num_q_heads} is not a multiple of num_kv_heads {num_kv_heads}" + ), + Self::Overflow { heads, head_dim } => write!( + f, + "attention geometry: {heads} heads x head_dim {head_dim} overflows usize" + ), + Self::KvPoolMismatch { + geometry_kv_heads, + geometry_head_dim, + pool_kv_heads, + pool_head_dim, + } => write!( + f, + "attention geometry: model has {geometry_kv_heads} kv heads x head_dim {geometry_head_dim} but the KV pool is laid out for {pool_kv_heads} kv heads x head_dim {pool_head_dim}" + ), + } + } +} + +impl std::error::Error for AttentionGeometryError {} + +/// The checked head geometry of one attention layer: `num_q_heads` query heads sharing +/// `num_kv_heads` key/value heads, every head `head_dim` wide. +/// +/// Construction is the only way to get a value, so a geometry in hand always satisfies: +/// no zero count, `num_q_heads` divisible by `num_kv_heads`, and both `q_dim` and `kv_dim` +/// fit in `usize`. The contract deliberately does NOT require a power-of-two GQA ratio, +/// `q_dim == hidden_dim` (Qwen3-Coder: q_dim 4096, hidden 2048) or `num_q_heads == +/// num_kv_heads`; a kernel with a narrower envelope refuses on its own and says so. +/// +/// Flattened layouts the geometry describes: +/// - q and attention output: `[num_q_heads][head_dim]` (`q_dim` values), head h at +/// `h * head_dim`; +/// - one token of K or V: `[num_kv_heads][head_dim]` (`kv_dim` values); +/// - query head h reads kv head `h / gqa_ratio` ([`Self::kv_head_of`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(try_from = "AttentionGeometryRaw", into = "AttentionGeometryRaw")] +pub struct AttentionGeometry { + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, +} + +/// Serde shape of [`AttentionGeometry`]; deserialising re-runs the checks. +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub struct AttentionGeometryRaw { + pub num_q_heads: usize, + pub num_kv_heads: usize, + pub head_dim: usize, +} + +impl TryFrom for AttentionGeometry { + type Error = AttentionGeometryError; + fn try_from(r: AttentionGeometryRaw) -> Result { + Self::new(r.num_q_heads, r.num_kv_heads, r.head_dim) + } +} + +impl From for AttentionGeometryRaw { + fn from(g: AttentionGeometry) -> Self { + Self { + num_q_heads: g.num_q_heads, + num_kv_heads: g.num_kv_heads, + head_dim: g.head_dim, + } + } +} + +impl AttentionGeometry { + /// Checks and builds the geometry. See the type docs for the exact rules. + pub fn new( + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) -> Result { + if num_q_heads == 0 { + return Err(AttentionGeometryError::ZeroQueryHeads); + } + if num_kv_heads == 0 { + return Err(AttentionGeometryError::ZeroKvHeads); + } + if head_dim == 0 { + return Err(AttentionGeometryError::ZeroHeadDim); + } + if !num_q_heads.is_multiple_of(num_kv_heads) { + return Err(AttentionGeometryError::QueryHeadsNotDivisible { + num_q_heads, + num_kv_heads, + }); + } + if num_q_heads.checked_mul(head_dim).is_none() { + return Err(AttentionGeometryError::Overflow { + heads: num_q_heads, + head_dim, + }); + } + // num_kv_heads <= num_q_heads here, so kv_dim fits whenever q_dim does. + Ok(Self { + num_q_heads, + num_kv_heads, + head_dim, + }) + } + + pub fn num_q_heads(&self) -> usize { + self.num_q_heads + } + + pub fn num_kv_heads(&self) -> usize { + self.num_kv_heads + } + + pub fn head_dim(&self) -> usize { + self.head_dim + } + + /// Width of one flattened query (and of one attention output): `num_q_heads * head_dim`. + pub fn q_dim(&self) -> usize { + self.num_q_heads * self.head_dim + } + + /// Width of one token's K (or V) row: `num_kv_heads * head_dim`. + pub fn kv_dim(&self) -> usize { + self.num_kv_heads * self.head_dim + } + + /// Query heads per kv head (1 for multi-head attention). + pub fn gqa_ratio(&self) -> usize { + self.num_q_heads / self.num_kv_heads + } + + /// The kv head query head `q_head` reads. `None` when `q_head >= num_q_heads`. + pub fn kv_head_of(&self, q_head: usize) -> Option { + (q_head < self.num_q_heads).then(|| q_head / self.gqa_ratio()) + } + + /// Refuses a KV pool or buffer laid out for a different kv-head count or head width. + /// Call it before any native (chip) code reads the pool with this geometry. + pub fn check_kv_pool( + &self, + pool_kv_heads: usize, + pool_head_dim: usize, + ) -> Result<(), AttentionGeometryError> { + if pool_kv_heads != self.num_kv_heads || pool_head_dim != self.head_dim { + return Err(AttentionGeometryError::KvPoolMismatch { + geometry_kv_heads: self.num_kv_heads, + geometry_head_dim: self.head_dim, + pool_kv_heads, + pool_head_dim, + }); + } + Ok(()) + } +} + impl ModelConfig { pub fn tinyllama_1_1b() -> Self { Self { @@ -77,6 +271,12 @@ impl ModelConfig { } } + /// The checked head geometry of this model's attention layers + /// (`num_heads` query heads, `num_kv_heads` kv heads, `head_dim`). + pub fn attention_geometry(&self) -> Result { + AttentionGeometry::new(self.num_heads, self.num_kv_heads, self.head_dim) + } + pub fn hidden_dim(&self) -> usize { if self.hidden_dim > 0 { self.hidden_dim diff --git a/crates/aien-abi-core/tests/attention_geometry.rs b/crates/aien-abi-core/tests/attention_geometry.rs new file mode 100644 index 00000000..2c1989f4 --- /dev/null +++ b/crates/aien-abi-core/tests/attention_geometry.rs @@ -0,0 +1,151 @@ +//! Contract tests for `AttentionGeometry` (Drake's attention hardening cut, phase 1). +//! Numbers come from the model configs in this repo, not from guesses. + +use aien_abi_core::{AttentionGeometry, AttentionGeometryError, ModelConfig}; + +#[test] +fn qwen3_coder_q_dim_differs_from_hidden_dim() { + // crates/aien-inference-abi/src/qwen3_coder.rs: 32 q heads, 4 kv heads, head_dim 128, + // hidden 2048. q_dim (4096) is NOT hidden_dim and the contract must not care. + let g = AttentionGeometry::new(32, 4, 128).expect("Qwen3-Coder geometry"); + assert_eq!(g.q_dim(), 4096); + assert_eq!(g.kv_dim(), 512); + assert_eq!(g.gqa_ratio(), 8); + assert_ne!( + g.q_dim(), + 2048, + "q_dim must be allowed to differ from hidden_dim" + ); + assert_eq!(g.kv_head_of(0), Some(0)); + assert_eq!(g.kv_head_of(7), Some(0)); + assert_eq!(g.kv_head_of(8), Some(1)); + assert_eq!(g.kv_head_of(31), Some(3)); + assert_eq!(g.kv_head_of(32), None); +} + +#[test] +fn tinyllama_and_default_configs_build() { + let t = ModelConfig::tinyllama_1_1b() + .attention_geometry() + .expect("TinyLlama geometry"); + assert_eq!( + (t.num_q_heads(), t.num_kv_heads(), t.head_dim()), + (32, 4, 64) + ); + assert_eq!(t.q_dim(), 2048); + assert_eq!(t.kv_dim(), 256); + let d = ModelConfig::default() + .attention_geometry() + .expect("default geometry"); + assert_eq!((d.q_dim(), d.kv_dim(), d.gqa_ratio()), (4096, 1024, 4)); +} + +#[test] +fn multi_head_attention_is_ratio_one() { + let g = AttentionGeometry::new(16, 16, 64).unwrap(); + assert_eq!(g.gqa_ratio(), 1); + for h in 0..16 { + assert_eq!(g.kv_head_of(h), Some(h)); + } + assert_eq!(g.q_dim(), g.kv_dim()); +} + +#[test] +fn non_power_of_two_ratio_is_accepted() { + // The contract describes the model, not one kernel's envelope. + let g = AttentionGeometry::new(24, 8, 64).unwrap(); + assert_eq!(g.gqa_ratio(), 3); + assert_eq!(g.kv_head_of(5), Some(1)); + let g = AttentionGeometry::new(40, 8, 128).unwrap(); + assert_eq!(g.gqa_ratio(), 5); + assert_eq!(g.kv_head_of(39), Some(7)); +} + +#[test] +fn zero_counts_are_refused() { + assert_eq!( + AttentionGeometry::new(0, 4, 64), + Err(AttentionGeometryError::ZeroQueryHeads) + ); + assert_eq!( + AttentionGeometry::new(32, 0, 64), + Err(AttentionGeometryError::ZeroKvHeads) + ); + assert_eq!( + AttentionGeometry::new(32, 4, 0), + Err(AttentionGeometryError::ZeroHeadDim) + ); +} + +#[test] +fn non_divisible_heads_are_refused() { + assert_eq!( + AttentionGeometry::new(10, 4, 64), + Err(AttentionGeometryError::QueryHeadsNotDivisible { + num_q_heads: 10, + num_kv_heads: 4 + }) + ); + // more kv heads than query heads is also not a whole ratio + assert_eq!( + AttentionGeometry::new(4, 8, 64), + Err(AttentionGeometryError::QueryHeadsNotDivisible { + num_q_heads: 4, + num_kv_heads: 8 + }) + ); +} + +#[test] +fn overflow_is_refused_not_wrapped() { + let heads = usize::MAX / 2 + 1; + assert_eq!( + AttentionGeometry::new(heads, 1, 4), + Err(AttentionGeometryError::Overflow { heads, head_dim: 4 }) + ); + // largest product that still fits is accepted + let g = AttentionGeometry::new(usize::MAX / 64, 1, 64).unwrap(); + assert_eq!(g.q_dim(), (usize::MAX / 64) * 64); +} + +#[test] +fn kv_pool_mismatch_is_named() { + let g = AttentionGeometry::new(32, 4, 64).unwrap(); + assert_eq!(g.check_kv_pool(4, 64), Ok(())); + assert_eq!( + g.check_kv_pool(8, 64), + Err(AttentionGeometryError::KvPoolMismatch { + geometry_kv_heads: 4, + geometry_head_dim: 64, + pool_kv_heads: 8, + pool_head_dim: 64, + }) + ); + let msg = g.check_kv_pool(4, 128).unwrap_err().to_string(); + assert!(msg.contains("4 kv heads x head_dim 64") && msg.contains("4 kv heads x head_dim 128")); +} + +#[test] +fn model_config_with_bad_heads_is_refused() { + let mut c = ModelConfig::tinyllama_1_1b(); + c.num_kv_heads = 6; + assert_eq!( + c.attention_geometry(), + Err(AttentionGeometryError::QueryHeadsNotDivisible { + num_q_heads: 32, + num_kv_heads: 6 + }) + ); +} + +#[test] +fn serde_round_trip_rechecks() { + let g = AttentionGeometry::new(32, 4, 128).unwrap(); + let json = serde_json::to_string(&g).unwrap(); + let back: AttentionGeometry = serde_json::from_str(&json).unwrap(); + assert_eq!(back, g); + let bad = serde_json::from_str::( + r#"{"num_q_heads":10,"num_kv_heads":4,"head_dim":64}"#, + ); + assert!(bad.is_err(), "deserialising must re-run the checks"); +} diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index ac38c2fa..ed359587 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -4,6 +4,53 @@ use crate::tensor::{ apply_rope as tensor_rope, matmul_vec as tensor_matmul, rmsnorm as tensor_rmsnorm, }; +use aien_abi_core::AttentionGeometry; + +/// The trait's attention methods return `()`, so a wrong head layout cannot be reported as an +/// error value; it must never turn into numbers either. These helpers refuse loudly (panic with +/// the exact geometry) before any element is read. Callers that can report errors check the +/// geometry up front (`ModelConfig::attention_geometry`), so a panic here means a caller bypassed +/// that check. +pub(crate) fn checked_geometry( + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + op: &str, +) -> AttentionGeometry { + match AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim) { + Ok(g) => g, + Err(e) => panic!("{op} refused: {e}"), + } +} + +/// q and out must be exactly one flattened `[num_q_heads][head_dim]` row each. +pub(crate) fn check_q_out(geom: &AttentionGeometry, q_len: usize, out_len: usize, op: &str) { + let want = geom.q_dim(); + assert!( + q_len == want, + "{op} refused: q has {q_len} values, geometry {}x{} needs {want}", + geom.num_q_heads(), + geom.head_dim() + ); + assert!( + out_len == want, + "{op} refused: out has {out_len} values, geometry {}x{} needs {want}", + geom.num_q_heads(), + geom.head_dim() + ); +} + +/// The pool must be laid out for this geometry's kv heads and head width. +pub(crate) fn check_pool( + geom: &AttentionGeometry, + pool: &aien_kv_cache::UnifiedKvTensorPool, + op: &str, +) { + let c = pool.config(); + if let Err(e) = geom.check_kv_pool(c.num_kv_heads, c.head_dim) { + panic!("{op} refused: {e}"); + } +} /// 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. @@ -176,12 +223,15 @@ pub trait TensorBackend: Send + Sync { num_kv_heads: usize, head_dim: usize, ) { + let geom = checked_geometry(num_q_heads, num_kv_heads, head_dim, "paged_attention"); + check_q_out(&geom, q.len(), out.len(), "paged_attention"); + check_pool(&geom, pool, "paged_attention"); if context_len == 0 || block_ids.is_empty() { out.fill(0.0); return; } - let gqa_ratio = num_q_heads / num_kv_heads; + let gqa_ratio = geom.gqa_ratio(); let inv_sqrt_d = 1.0 / (head_dim as f64).sqrt(); let block_size = pool.config().block_size; @@ -247,7 +297,16 @@ pub trait TensorBackend: Send + Sync { num_kv_heads: usize, head_dim: usize, ) { - let q_stride = num_q_heads * head_dim; + let geom = checked_geometry(num_q_heads, num_kv_heads, head_dim, "paged_attention_batch"); + check_pool(&geom, pool, "paged_attention_batch"); + let q_stride = geom.q_dim(); + assert!( + q.len() == num_seqs * q_stride && out.len() == num_seqs * q_stride, + "paged_attention_batch refused: q has {} and out has {} values, {num_seqs} sequences x q_dim {q_stride} need {}", + q.len(), + out.len(), + num_seqs * q_stride + ); for s in 0..num_seqs { let q_s = &q[s * q_stride..(s + 1) * q_stride]; let out_s = &mut out[s * q_stride..(s + 1) * q_stride]; @@ -370,12 +429,22 @@ impl TensorBackend for ReferenceCpuBackend { num_kv_heads: usize, head_dim: usize, ) { + let geom = checked_geometry(num_q_heads, num_kv_heads, head_dim, "gqa_attention"); + check_q_out(&geom, q.len(), out.len(), "gqa_attention"); + let need = seq_len * geom.kv_dim(); + assert!( + k_cache.len() >= need && v_cache.len() >= need, + "gqa_attention refused: k/v caches hold {}/{} values, {seq_len} tokens x kv_dim {} need {need}", + k_cache.len(), + v_cache.len(), + geom.kv_dim() + ); if seq_len == 0 { out.fill(0.0); return; } - let gqa_ratio = num_q_heads / num_kv_heads; + let gqa_ratio = geom.gqa_ratio(); let inv_sqrt_d = 1.0 / (head_dim as f64).sqrt(); let mut scores = vec![0.0f64; seq_len]; diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index 8285b21d..98a9a12a 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -373,6 +373,25 @@ impl OmegaGb10Backend { num_kv_heads: usize, head_dim: usize, ) -> bool { + // Geometry and pool layout are checked before any native code sees the pool. A refusal + // is counted like a chip error and the reference then refuses the same call loudly. + let geom = match aien_abi_core::AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim) + { + Ok(g) => g, + Err(e) => return self.fail(format!("paged_attention geometry refused: {e}")), + }; + let cfg = pool.config(); + if let Err(e) = geom.check_kv_pool(cfg.num_kv_heads, cfg.head_dim) { + return self.fail(format!("paged_attention refused: {e}")); + } + if q.len() != geom.q_dim() || out.len() != geom.q_dim() { + return self.fail(format!( + "paged_attention refused: q={} out={} values, geometry needs {}", + q.len(), + out.len(), + geom.q_dim() + )); + } if context_len == 0 || block_ids.is_empty() { out.fill(0.0); return true; @@ -559,21 +578,32 @@ impl TensorBackend for OmegaGb10Backend { ) { // 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 geom = aien_abi_core::AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim); + let need = geom.as_ref().map_or(0, |g| seq_len * g.kv_dim()); + let shapes_ok = match &geom { + Ok(g) => { + q.len() == g.q_dim() + && out.len() == g.q_dim() + && k_cache.len() >= need + && v_cache.len() >= need + } + Err(e) => self.fail(format!("gqa_attention geometry refused: {e}")), + }; 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, - ) - }); + let native = shapes_ok + && 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; } diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 83bab82a..54b82fcb 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -712,11 +712,17 @@ impl NativeTransformerBackend { kv_manager: Option<&SharedKvManager>, ) -> Result, String> { let hidden_dim = weights.config.hidden_dim(); - let num_heads = weights.config.num_heads; - let num_kv_heads = weights.config.num_kv_heads; - let head_dim = weights.config.head_dim; - let q_dim = num_heads * head_dim; - let kv_dim = num_kv_heads * head_dim; + // Checked once per forward: zero heads, non-divisible heads or an overflowing width + // are refused here instead of becoming a wrong slice later. + let geom = weights + .config + .attention_geometry() + .map_err(|e| e.to_string())?; + let num_heads = geom.num_q_heads(); + let num_kv_heads = geom.num_kv_heads(); + let head_dim = geom.head_dim(); + let q_dim = geom.q_dim(); + let kv_dim = geom.kv_dim(); let intermediate_dim = weights.config.intermediate_dim(); let eps = weights.config.rms_norm_eps; let theta = weights.config.rope_theta; @@ -959,11 +965,17 @@ impl NativeTransformerBackend { } let hidden_dim = weights.config.hidden_dim(); - let num_heads = weights.config.num_heads; - let num_kv_heads = weights.config.num_kv_heads; - let head_dim = weights.config.head_dim; - let q_dim = num_heads * head_dim; - let kv_dim = num_kv_heads * head_dim; + // Checked once per forward: zero heads, non-divisible heads or an overflowing width + // are refused here instead of becoming a wrong slice later. + let geom = weights + .config + .attention_geometry() + .map_err(|e| e.to_string())?; + let num_heads = geom.num_q_heads(); + let num_kv_heads = geom.num_kv_heads(); + let head_dim = geom.head_dim(); + let q_dim = geom.q_dim(); + let kv_dim = geom.kv_dim(); let intermediate_dim = weights.config.intermediate_dim(); let eps = weights.config.rms_norm_eps; let theta = weights.config.rope_theta; @@ -1276,11 +1288,18 @@ impl NativeTransformerBackend { } let hidden_dim = self.weights.config.hidden_dim(); - let num_heads = self.weights.config.num_heads; - let num_kv_heads = self.weights.config.num_kv_heads; - let head_dim = self.weights.config.head_dim; - let q_dim = num_heads * head_dim; - let kv_dim = num_kv_heads * head_dim; + // Checked once per forward: zero heads, non-divisible heads or an overflowing width + // are refused here instead of becoming a wrong slice later. + let geom = self + .weights + .config + .attention_geometry() + .map_err(|e| e.to_string())?; + let num_heads = geom.num_q_heads(); + let num_kv_heads = geom.num_kv_heads(); + let head_dim = geom.head_dim(); + let q_dim = geom.q_dim(); + let kv_dim = geom.kv_dim(); let intermediate_dim = self.weights.config.intermediate_dim(); let eps = self.weights.config.rms_norm_eps; let theta = self.weights.config.rope_theta; From 4c5f5b02c4d015b417162a1c9e6e83b617782f49 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 14:32:13 -0500 Subject: [PATCH 2/2] crumb: recompile for SC-1 head Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- .crumb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.crumb b/.crumb index 69b7e0b9..4e0be52a 100644 --- a/.crumb +++ b/.crumb @@ -83,7 +83,7 @@ "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", "files": 676, - "generated_at_commit": "75800398eb53646444d4c12e5a27fdc26cd14e04", + "generated_at_commit": "0607182837efbdfa18c584ee1b60d48d058860fa", "source_tree": "sha256:8c5cd62485332468eab8185a24cd6a2ed9936353094a09b5eb44f2f66e6e9109" } },