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/blob/main/crates/aien-inference-abi/src/backend.rs # 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 branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-inference-abi / src / backend.rs` 823 lines ยท 29521 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Decoupled TensorBackend trait and ReferenceCpuBackend correctness oracle. 17 //! Provides hardware-neutral abstraction for transformer mathematical operations. 18 19 use crate::tensor::{ 20 apply_rope_params as tensor_rope, matmul_vec as tensor_matmul, rmsnorm as tensor_rmsnorm, 21 }; 22 use aien_abi_core::{AttentionGeometry, ModelConfig, RopeParams}; 23 24 /// The trait's attention methods return `()`, so a wrong head layout cannot be reported as an 25 /// error value; it must never turn into numbers either. These helpers refuse loudly (panic with 26 /// the exact geometry) before any element is read. Callers that can report errors check the 27 /// geometry up front (`ModelConfig::attention_geometry`), so a panic here means a caller bypassed 28 /// that check. 29 pub(crate) fn checked_geometry( 30 num_q_heads: usize, 31 num_kv_heads: usize, 32 head_dim: usize, 33 op: &str, 34 ) -> AttentionGeometry { 35 match AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim) { 36 Ok(g) => g, 37 Err(e) => panic!("{op} refused: {e}"), 38 } 39 } 40 41 /// q and out must be exactly one flattened `[num_q_heads][head_dim]` row each. 42 pub(crate) fn check_q_out(geom: &AttentionGeometry, q_len: usize, out_len: usize, op: &str) { 43 let want = geom.q_dim(); 44 assert!( 45 q_len == want, 46 "{op} refused: q has {q_len} values, geometry {}x{} needs {want}", 47 geom.num_q_heads(), 48 geom.head_dim() 49 ); 50 assert!( 51 out_len == want, 52 "{op} refused: out has {out_len} values, geometry {}x{} needs {want}", 53 geom.num_q_heads(), 54 geom.head_dim() 55 ); 56 } 57 58 /// The pool must be laid out for this geometry's kv heads and head width. 59 pub(crate) fn check_pool( 60 geom: &AttentionGeometry, 61 pool: &aien_kv_cache::UnifiedKvTensorPool, 62 op: &str, 63 ) { 64 let c = pool.config(); 65 if let Err(e) = geom.check_kv_pool(c.num_kv_heads, c.head_dim) { 66 panic!("{op} refused: {e}"); 67 } 68 } 69 70 /// Reads one KV head from the pool using the pool's dtype. Bf16 bytes are decoded. 71 /// A short or unknown dtype returns zeros instead of reading past the allocation. 72 pub(crate) fn read_kv_head( 73 pool: &aien_kv_cache::UnifiedKvTensorPool, 74 block_id: usize, 75 layer_idx: usize, 76 is_value: bool, 77 token_in_block: usize, 78 kv_head: usize, 79 head_dim: usize, 80 ) -> Vec { 81 let dtype = pool.config().dtype; 82 let element_bytes = match dtype { 83 aien_kv_cache::KvDType::Fp32 => 4, 84 aien_kv_cache::KvDType::Bf16 | aien_kv_cache::KvDType::Fp16 => 2, 85 aien_kv_cache::KvDType::Fp8 => 1, 86 aien_kv_cache::KvDType::Fp4 => return vec![0.0; head_dim], 87 }; 88 let offset = pool.element_offset(block_id, layer_idx, is_value, token_in_block) 89 + kv_head * head_dim * element_bytes; 90 let nbytes = head_dim * element_bytes; 91 if offset.saturating_add(nbytes) > pool.layout().total_bytes { 92 return vec![0.0; head_dim]; 93 } 94 let ptr = unsafe { pool.base_ptr().add(offset) }; 95 match dtype { 96 aien_kv_cache::KvDType::Fp32 => unsafe { 97 std::slice::from_raw_parts(ptr as *const f32, head_dim).to_vec() 98 }, 99 aien_kv_cache::KvDType::Bf16 => { 100 let bits = unsafe { std::slice::from_raw_parts(ptr as *const u16, head_dim) }; 101 bits.iter() 102 .copied() 103 .map(aien_kv_cache::bf16_bits_to_f32) 104 .collect() 105 } 106 aien_kv_cache::KvDType::Fp16 => { 107 let bits = unsafe { std::slice::from_raw_parts(ptr as *const u16, head_dim) }; 108 bits.iter().copied().map(fp16_bits_to_f32).collect() 109 } 110 aien_kv_cache::KvDType::Fp8 => { 111 let bytes = unsafe { std::slice::from_raw_parts(ptr, head_dim) }; 112 bytes.iter().map(|byte| *byte as f32).collect() 113 } 114 aien_kv_cache::KvDType::Fp4 => vec![0.0; head_dim], 115 } 116 } 117 118 fn fp16_bits_to_f32(bits: u16) -> f32 { 119 let sign = (bits as u32) & 0x8000; 120 let exp = ((bits >> 10) & 0x1f) as i32; 121 let frac = (bits & 0x3ff) as u32; 122 let out_bits = if exp == 0 { 123 if frac == 0 { 124 sign << 16 125 } else { 126 let mut mantissa = frac; 127 let mut exponent = -14; 128 while mantissa & 0x400 == 0 { 129 mantissa <<= 1; 130 exponent -= 1; 131 } 132 mantissa &= 0x3ff; 133 (sign << 16) | (((exponent + 127) as u32) << 23) | (mantissa << 13) 134 } 135 } else if exp == 31 { 136 (sign << 16) | (0xff << 23) | (frac << 13) 137 } else { 138 (sign << 16) | (((exp as u32) + (127 - 15)) << 23) | (frac << 13) 139 }; 140 f32::from_bits(out_bits) 141 } 142 143 /// Decoupled mathematical abstraction for transformer tensor operations. 144 pub trait TensorBackend: Send + Sync { 145 /// Human-readable name of the backend implementation. 146 fn name(&self) -> &'static str; 147 148 /// Refuses a model this backend cannot run correctly, before any forward pass. Default: 149 /// accepts everything. Called at the start of every forward pass. 150 fn check_model(&self, _config: &ModelConfig) -> Result<(), String> { 151 Ok(()) 152 } 153 154 /// Memory for the shared paged KV pool, when this backend can read KV in place from an 155 /// allocation of its own (omega: a GPU-uncached, host-visible pool; the paged attention then 156 /// stages nothing per call). `None`, the default: the caller maps ordinary host memory and 157 /// the backend copies the referenced slices for every call. 158 fn alloc_kv_pool(&self, _bytes: usize) -> Option { 159 None 160 } 161 162 /// How many operations this backend ran on a software fallback instead of 163 /// the device it was bound to. Zero for pure CPU backends; a production 164 /// build treats a non-zero count as a strict real-model violation. 165 fn fallback_count(&self) -> u64 { 166 0 167 } 168 169 /// Operations this backend claims to run natively on its device. Strict mode 170 /// fails only on fallbacks of ops in this mask; ops outside it run on the 171 /// reference CPU path by design. Default: all ops native (original semantics). 172 fn native_ops(&self) -> crate::native_ops::NativeOpMask { 173 crate::native_ops::NativeOpMask::ALL 174 } 175 176 /// Native-versus-reference listing and per-op counters for receipts. 177 /// Default: all native, no counters. 178 fn op_report(&self) -> crate::native_ops::OpReport { 179 crate::native_ops::OpReport::all_native() 180 } 181 182 /// Operations this backend has run on its chip so far (process total), for 183 /// receipts (sc#402). Default: None, for a backend with no chip or that does 184 /// not count chip calls: an absent claim, never zero. 185 fn gpu_executions(&self) -> Option { 186 None 187 } 188 189 /// Per-operation wall and chip time since the last reset, one line per kind 190 /// ("key calls=N wall_ms=W chip_ms=C", sorted by wall time), for timing receipts. 191 /// Default: None, for a backend that does not keep the table. 192 fn op_timing_report(&self) -> Option { 193 None 194 } 195 196 /// Clear the per-operation timing table (no-op without one). 197 fn reset_op_timing(&self) {} 198 199 /// In-place Root Mean Square Normalization: 200 /// out[i] = x[i] * weight[i] / sqrt(mean(x^2) + eps) 201 fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32); 202 203 /// `rows` rows of `weight.len()` values normalized independently with the same `weight` 204 /// (`x` and `out` are `[rows][dim]`). The prompt read calls this once per chunk and layer 205 /// instead of `rmsnorm` once per token; the default is that per-row loop, a chip backend 206 /// makes it one launch. `rows == 0` is a no-op. 207 fn rmsnorm_rows(&self, out: &mut [f32], x: &[f32], weight: &[f32], rows: usize, eps: f32) { 208 let dim = weight.len(); 209 for r in 0..rows { 210 let (lo, hi) = (r * dim, (r + 1) * dim); 211 self.rmsnorm(&mut out[lo..hi], &x[lo..hi], weight, eps); 212 } 213 } 214 215 /// Per-head RMS normalization in place (Qwen3 q/k norm): `x` is `[heads][head_dim]` and every 216 /// head is normalized on its own with the same `weight` (`head_dim` values). 217 fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32); 218 219 /// In-place Rotary Positional Embeddings (RoPE) following canonical rotate_half convention: 220 /// rot(v) = [-v[half_dim..], v[..half_dim]] 221 /// out = v * cos(pos * f_i) + rot(v) * sin(pos * f_i), with f_i = `rope.inv_freq(i, head_dim)` 222 /// (theta^(-2i/d), smoothed by the llama3 scaling when the model has one). 223 #[allow(clippy::too_many_arguments)] 224 fn apply_rope( 225 &self, 226 q: &mut [f32], 227 k: &mut [f32], 228 pos: usize, 229 head_dim: usize, 230 num_q_heads: usize, 231 num_kv_heads: usize, 232 rope: &RopeParams, 233 ); 234 235 /// Vector-matrix multiplication for row-major weights: out = x * W^T 236 /// where x is [in_dim], weight is [out_dim, in_dim], and out is [out_dim]. 237 fn matmul_vec(&self, out: &mut [f32], x: &[f32], weight: &[f32], out_dim: usize, in_dim: usize); 238 239 /// Batched vector-matrix multiplication for row-major weights: out = X * W^T 240 /// where X is [batch_size, in_dim], weight is [out_dim, in_dim], and out is [batch_size, out_dim]. 241 fn matmul_batch( 242 &self, 243 out: &mut [f32], 244 x: &[f32], 245 weight: &[f32], 246 batch_size: usize, 247 in_dim: usize, 248 out_dim: usize, 249 ) { 250 for b in 0..batch_size { 251 let x_b = &x[b * in_dim..(b + 1) * in_dim]; 252 let out_b = &mut out[b * out_dim..(b + 1) * out_dim]; 253 self.matmul_vec(out_b, x_b, weight, out_dim, in_dim); 254 } 255 } 256 257 /// SwiGLU activation: out = (gate * silu) * up = silu(gate) * up 258 fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]); 259 260 /// Grouped-Query Attention (GQA) with multi-head queries and shared key-value heads. 261 /// Grouped-Query Attention (GQA) with multi-head queries and shared key-value heads. 262 /// Operates over flattened key and value cache slices with causal history. 263 fn gqa_attention( 264 &self, 265 out: &mut [f32], 266 q: &[f32], 267 k_cache: &[f32], 268 v_cache: &[f32], 269 seq_len: usize, 270 num_q_heads: usize, 271 num_kv_heads: usize, 272 head_dim: usize, 273 ); 274 275 /// Prompt-read attention: `num_rows` query rows in one call over a contiguous cache that 276 /// holds `base_len + num_rows` tokens. Row `i` (`q[i * q_dim..]`) attends over the first 277 /// `base_len + i + 1` tokens, which is causal prefill. Default: one `gqa_attention` per 278 /// row. The omega backend sends the whole chunk to the chip in a few launches (omega#406). 279 #[allow(clippy::too_many_arguments)] 280 fn gqa_attention_rows( 281 &self, 282 out: &mut [f32], 283 q: &[f32], 284 k_cache: &[f32], 285 v_cache: &[f32], 286 base_len: usize, 287 num_rows: usize, 288 num_q_heads: usize, 289 num_kv_heads: usize, 290 head_dim: usize, 291 ) { 292 let q_dim = num_q_heads * head_dim; 293 for i in 0..num_rows { 294 let (lo, hi) = (i * q_dim, (i + 1) * q_dim); 295 self.gqa_attention( 296 &mut out[lo..hi], 297 &q[lo..hi], 298 k_cache, 299 v_cache, 300 base_len + i + 1, 301 num_q_heads, 302 num_kv_heads, 303 head_dim, 304 ); 305 } 306 } 307 308 /// Grouped-Query Paged Attention directly over a physical Copy-on-Write page pool. 309 /// Default implementation evaluates online softmax token-by-token across physical blocks 310 /// with zero intermediate array allocation or contiguous gathering. 311 fn paged_attention( 312 &self, 313 out: &mut [f32], 314 q: &[f32], 315 pool: &aien_kv_cache::UnifiedKvTensorPool, 316 block_ids: &[usize], 317 context_len: usize, 318 layer_idx: usize, 319 num_q_heads: usize, 320 num_kv_heads: usize, 321 head_dim: usize, 322 ) { 323 let geom = checked_geometry(num_q_heads, num_kv_heads, head_dim, "paged_attention"); 324 check_q_out(&geom, q.len(), out.len(), "paged_attention"); 325 check_pool(&geom, pool, "paged_attention"); 326 if context_len == 0 || block_ids.is_empty() { 327 out.fill(0.0); 328 return; 329 } 330 331 let gqa_ratio = geom.gqa_ratio(); 332 let inv_sqrt_d = 1.0 / (head_dim as f64).sqrt(); 333 let block_size = pool.config().block_size; 334 335 for h in 0..num_q_heads { 336 let kv_head = h / gqa_ratio; 337 let q_head = &q[h * head_dim..(h + 1) * head_dim]; 338 339 let mut m_prev = f64::NEG_INFINITY; 340 let mut l_prev = 0.0f64; 341 let mut acc = vec![0.0f64; head_dim]; 342 343 for t in 0..context_len { 344 let blk_idx = t / block_size; 345 if blk_idx >= block_ids.len() { 346 break; 347 } 348 let blk_id = block_ids[blk_idx]; 349 let slot = t % block_size; 350 351 let k_head = read_kv_head(pool, blk_id, layer_idx, false, slot, kv_head, head_dim); 352 let v_head = read_kv_head(pool, blk_id, layer_idx, true, slot, kv_head, head_dim); 353 354 let mut dot = 0.0f64; 355 for d in 0..head_dim { 356 dot += (q_head[d] as f64) * (k_head[d] as f64); 357 } 358 let score = dot * inv_sqrt_d; 359 360 let m_new = m_prev.max(score); 361 let alpha = (m_prev - m_new).exp(); 362 let beta = (score - m_new).exp(); 363 let l_new = l_prev * alpha + beta; 364 365 for d in 0..head_dim { 366 acc[d] = acc[d] * alpha + beta * (v_head[d] as f64); 367 } 368 369 m_prev = m_new; 370 l_prev = l_new; 371 } 372 373 let inv_l = if l_prev > 0.0 { 1.0 / l_prev } else { 0.0 }; 374 let out_head = &mut out[h * head_dim..(h + 1) * head_dim]; 375 for d in 0..head_dim { 376 out_head[d] = (acc[d] * inv_l) as f32; 377 } 378 } 379 } 380 381 /// Batched Grouped-Query Paged Attention across multiple sequences concurrently. 382 /// Default implementation evaluates each sequence sequentially via paged_attention. 383 fn paged_attention_batch( 384 &self, 385 out: &mut [f32], 386 q: &[f32], 387 pool: &aien_kv_cache::UnifiedKvTensorPool, 388 block_tables: &[i32], 389 context_lens: &[i32], 390 max_blocks_per_seq: usize, 391 num_seqs: usize, 392 layer_idx: usize, 393 num_q_heads: usize, 394 num_kv_heads: usize, 395 head_dim: usize, 396 ) { 397 let geom = checked_geometry(num_q_heads, num_kv_heads, head_dim, "paged_attention_batch"); 398 check_pool(&geom, pool, "paged_attention_batch"); 399 let q_stride = geom.q_dim(); 400 assert!( 401 q.len() == num_seqs * q_stride && out.len() == num_seqs * q_stride, 402 "paged_attention_batch refused: q has {} and out has {} values, {num_seqs} sequences x q_dim {q_stride} need {}", 403 q.len(), 404 out.len(), 405 num_seqs * q_stride 406 ); 407 for s in 0..num_seqs { 408 let q_s = &q[s * q_stride..(s + 1) * q_stride]; 409 let out_s = &mut out[s * q_stride..(s + 1) * q_stride]; 410 let ctx_len = if s < context_lens.len() && context_lens[s] > 0 { 411 context_lens[s] as usize 412 } else { 413 0 414 }; 415 let bt_start = s * max_blocks_per_seq; 416 let bt_end = bt_start + max_blocks_per_seq; 417 let bt_slice = if bt_end <= block_tables.len() { 418 &block_tables[bt_start..bt_end] 419 } else { 420 &[] 421 }; 422 let usize_blocks: Vec = bt_slice 423 .iter() 424 .filter(|&&b| b >= 0) 425 .map(|&b| b as usize) 426 .collect(); 427 428 self.paged_attention( 429 out_s, 430 q_s, 431 pool, 432 &usize_blocks, 433 ctx_len, 434 layer_idx, 435 num_q_heads, 436 num_kv_heads, 437 head_dim, 438 ); 439 } 440 } 441 442 /// Projects hidden states to vocabulary logits: logits = hidden * W^T 443 fn compute_logits( 444 &self, 445 logits: &mut [f32], 446 hidden: &[f32], 447 embed_weight: &[f32], 448 vocab_size: usize, 449 hidden_dim: usize, 450 ); 451 452 /// [`Self::matmul_vec`] for a weight that may be device-resident. Host weights go to 453 /// `matmul_vec`; a resident weight is refused by name unless the backend overrides this (only 454 /// the Omega GB10 backend can use one). Never a silent CPU fallback. 455 fn matmul_vec_w( 456 &self, 457 out: &mut [f32], 458 x: &[f32], 459 weight: crate::resident::MatrixRef<'_>, 460 out_dim: usize, 461 in_dim: usize, 462 ) { 463 let w = self.resident_refusal_or_host(weight, "matmul_vec"); 464 self.matmul_vec(out, x, w, out_dim, in_dim); 465 } 466 467 /// [`Self::matmul_batch`] for a weight that may be device-resident (see [`Self::matmul_vec_w`]). 468 fn matmul_batch_w( 469 &self, 470 out: &mut [f32], 471 x: &[f32], 472 weight: crate::resident::MatrixRef<'_>, 473 batch_size: usize, 474 in_dim: usize, 475 out_dim: usize, 476 ) { 477 let w = self.resident_refusal_or_host(weight, "matmul_batch"); 478 self.matmul_batch(out, x, w, batch_size, in_dim, out_dim); 479 } 480 481 /// [`Self::compute_logits`] for a head that may be device-resident (see [`Self::matmul_vec_w`]). 482 fn compute_logits_w( 483 &self, 484 logits: &mut [f32], 485 hidden: &[f32], 486 head: crate::resident::MatrixRef<'_>, 487 vocab_size: usize, 488 hidden_dim: usize, 489 ) { 490 let w = self.resident_refusal_or_host(head, "compute_logits"); 491 self.compute_logits(logits, hidden, w, vocab_size, hidden_dim); 492 } 493 494 /// Host values of `weight`, or the named refusal when it is resident and this backend 495 /// cannot use a device copy. 496 #[doc(hidden)] 497 fn resident_refusal_or_host<'a>( 498 &self, 499 weight: crate::resident::MatrixRef<'a>, 500 op: &str, 501 ) -> &'a [f32] { 502 match weight { 503 crate::resident::MatrixRef::Host(v) => v, 504 crate::resident::MatrixRef::Resident(_) => crate::resident::refuse_resident(&format!( 505 "backend {} cannot run {op} on a device-resident weight", 506 self.name() 507 )), 508 } 509 } 510 } 511 512 /// Pure Rust FP32 reference implementation satisfying TensorBackend. 513 /// Serves as the golden correctness oracle on both development workstations and CI runners. 514 #[derive(Debug, Clone, Default)] 515 pub struct ReferenceCpuBackend; 516 517 impl ReferenceCpuBackend { 518 pub fn new() -> Self { 519 Self 520 } 521 } 522 523 impl TensorBackend for ReferenceCpuBackend { 524 fn name(&self) -> &'static str { 525 "ReferenceCpuBackend" 526 } 527 528 fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { 529 tensor_rmsnorm(x, weight, eps, out); 530 } 531 532 fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { 533 crate::tensor::rmsnorm_heads_in_place(x, weight, head_dim, eps); 534 } 535 536 fn apply_rope( 537 &self, 538 q: &mut [f32], 539 k: &mut [f32], 540 pos: usize, 541 head_dim: usize, 542 num_q_heads: usize, 543 num_kv_heads: usize, 544 rope: &RopeParams, 545 ) { 546 tensor_rope(q, k, pos, num_q_heads, num_kv_heads, head_dim, rope); 547 } 548 549 fn matmul_vec( 550 &self, 551 out: &mut [f32], 552 x: &[f32], 553 weight: &[f32], 554 out_dim: usize, 555 in_dim: usize, 556 ) { 557 tensor_matmul(x, weight, out, in_dim, out_dim); 558 } 559 560 fn matmul_batch( 561 &self, 562 out: &mut [f32], 563 x: &[f32], 564 weight: &[f32], 565 batch_size: usize, 566 in_dim: usize, 567 out_dim: usize, 568 ) { 569 crate::tensor::matmul_batch(x, weight, out, batch_size, in_dim, out_dim); 570 } 571 572 fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { 573 let n = gate.len().min(up.len()).min(out.len()); 574 for i in 0..n { 575 let g = gate[i] as f64; 576 let silu = g / (1.0 + (-g).exp()); 577 out[i] = (silu * (up[i] as f64)) as f32; 578 } 579 } 580 581 fn gqa_attention( 582 &self, 583 out: &mut [f32], 584 q: &[f32], 585 k_cache: &[f32], 586 v_cache: &[f32], 587 seq_len: usize, 588 num_q_heads: usize, 589 num_kv_heads: usize, 590 head_dim: usize, 591 ) { 592 let geom = checked_geometry(num_q_heads, num_kv_heads, head_dim, "gqa_attention"); 593 check_q_out(&geom, q.len(), out.len(), "gqa_attention"); 594 let need = seq_len * geom.kv_dim(); 595 assert!( 596 k_cache.len() >= need && v_cache.len() >= need, 597 "gqa_attention refused: k/v caches hold {}/{} values, {seq_len} tokens x kv_dim {} need {need}", 598 k_cache.len(), 599 v_cache.len(), 600 geom.kv_dim() 601 ); 602 if seq_len == 0 { 603 out.fill(0.0); 604 return; 605 } 606 607 let gqa_ratio = geom.gqa_ratio(); 608 let inv_sqrt_d = 1.0 / (head_dim as f64).sqrt(); 609 let mut scores = vec![0.0f64; seq_len]; 610 611 for h in 0..num_q_heads { 612 let kv_head = h / gqa_ratio; 613 let q_head = &q[h * head_dim..(h + 1) * head_dim]; 614 615 for t in 0..seq_len { 616 let k_offset = (t * num_kv_heads + kv_head) * head_dim; 617 let k_t = &k_cache[k_offset..k_offset + head_dim]; 618 let mut dot = 0.0f64; 619 for d in 0..head_dim { 620 dot += (q_head[d] as f64) * (k_t[d] as f64); 621 } 622 scores[t] = dot * inv_sqrt_d; 623 } 624 625 let max_score = scores.iter().cloned().fold(f64::NEG_INFINITY, f64::max); 626 let mut sum_exp = 0.0f64; 627 for s in scores.iter_mut() { 628 *s = (*s - max_score).exp(); 629 sum_exp += *s; 630 } 631 let inv_sum = 1.0 / sum_exp.max(1e-12); 632 for s in scores.iter_mut() { 633 *s *= inv_sum; 634 } 635 636 let out_head = &mut out[h * head_dim..(h + 1) * head_dim]; 637 for d in 0..head_dim { 638 let mut sum = 0.0f64; 639 for t in 0..seq_len { 640 let v_offset = (t * num_kv_heads + kv_head) * head_dim; 641 sum += scores[t] * (v_cache[v_offset + d] as f64); 642 } 643 out_head[d] = sum as f32; 644 } 645 } 646 } 647 648 fn compute_logits( 649 &self, 650 logits: &mut [f32], 651 hidden: &[f32], 652 embed_weight: &[f32], 653 vocab_size: usize, 654 hidden_dim: usize, 655 ) { 656 self.matmul_vec(logits, hidden, embed_weight, vocab_size, hidden_dim); 657 } 658 } 659 660 #[cfg(test)] 661 mod tests { 662 use super::*; 663 664 /// The default `rmsnorm_rows` is the per-row loop: 3 rows in one call equal 3 single calls, 665 /// and 0 rows touches nothing. 666 #[test] 667 fn test_rmsnorm_rows_default_equals_per_row() { 668 let b = ReferenceCpuBackend::new(); 669 let dim = 8; 670 let w: Vec = (0..dim).map(|i| 1.0 + i as f32 * 0.25).collect(); 671 let x: Vec = (0..3 * dim) 672 .map(|i| (i as f32 * 0.37).sin() * 3.0) 673 .collect(); 674 let mut got = vec![0.0f32; 3 * dim]; 675 b.rmsnorm_rows(&mut got, &x, &w, 3, 1e-5); 676 for r in 0..3 { 677 let mut want = vec![0.0f32; dim]; 678 b.rmsnorm(&mut want, &x[r * dim..(r + 1) * dim], &w, 1e-5); 679 assert_eq!(&got[r * dim..(r + 1) * dim], &want[..], "row {r}"); 680 } 681 let mut untouched = vec![7.0f32; dim]; 682 b.rmsnorm_rows(&mut untouched, &x, &w, 0, 1e-5); 683 assert!(untouched.iter().all(|&v| v == 7.0)); 684 } 685 686 /// The default `gqa_attention_rows` is causal prefill: row i of a 4-row call over a cache 687 /// of 2 + 4 tokens equals `gqa_attention` with seq_len 2 + i + 1; 0 rows touches nothing. 688 #[test] 689 fn test_gqa_attention_rows_default_is_causal_per_row() { 690 let b = ReferenceCpuBackend::new(); 691 let (nq, nkv, hd, base, rows) = (4usize, 2usize, 8usize, 2usize, 4usize); 692 let (q_dim, kv_dim) = (nq * hd, nkv * hd); 693 let q: Vec = (0..rows * q_dim).map(|i| (i as f32 * 0.31).sin()).collect(); 694 let k: Vec = (0..(base + rows) * kv_dim) 695 .map(|i| (i as f32 * 0.17).cos()) 696 .collect(); 697 let v: Vec = (0..(base + rows) * kv_dim) 698 .map(|i| (i as f32 * 0.23).sin()) 699 .collect(); 700 let mut got = vec![0.0f32; rows * q_dim]; 701 b.gqa_attention_rows(&mut got, &q, &k, &v, base, rows, nq, nkv, hd); 702 for i in 0..rows { 703 let mut want = vec![0.0f32; q_dim]; 704 b.gqa_attention( 705 &mut want, 706 &q[i * q_dim..(i + 1) * q_dim], 707 &k, 708 &v, 709 base + i + 1, 710 nq, 711 nkv, 712 hd, 713 ); 714 assert_eq!(&got[i * q_dim..(i + 1) * q_dim], &want[..], "row {i}"); 715 } 716 // the last row must differ from a non-causal read over the whole cache of the first row 717 let mut whole = vec![0.0f32; q_dim]; 718 b.gqa_attention(&mut whole, &q[..q_dim], &k, &v, base + rows, nq, nkv, hd); 719 assert_ne!(&got[..q_dim], &whole[..], "row 0 must not see later tokens"); 720 let mut untouched = vec![7.0f32; q_dim]; 721 b.gqa_attention_rows(&mut untouched, &q, &k, &v, base, 0, nq, nkv, hd); 722 assert!(untouched.iter().all(|&x| x == 7.0)); 723 } 724 #[test] 725 fn test_reference_backend_name() { 726 let backend = ReferenceCpuBackend::new(); 727 assert_eq!(backend.name(), "ReferenceCpuBackend"); 728 } 729 730 #[test] 731 fn test_reference_rmsnorm_matches_tensor() { 732 let backend = ReferenceCpuBackend::new(); 733 let x = vec![1.0f32, 2.0, 3.0, 4.0]; 734 let w = vec![1.0f32, 1.0, 1.0, 1.0]; 735 let mut out = vec![0.0f32; 4]; 736 backend.rmsnorm(&mut out, &x, &w, 1e-5); 737 738 let mut expected = vec![0.0f32; 4]; 739 tensor_rmsnorm(&x, &w, 1e-5, &mut expected); 740 741 assert_eq!(out, expected); 742 } 743 744 #[test] 745 fn test_reference_rope_matches_tensor() { 746 let backend = ReferenceCpuBackend::new(); 747 let mut q1 = vec![1.0f32; 128]; 748 let mut k1 = vec![1.0f32; 64]; 749 let mut q2 = q1.clone(); 750 let mut k2 = k1.clone(); 751 752 backend.apply_rope(&mut q1, &mut k1, 5, 64, 2, 1, &RopeParams::plain(10000.0)); 753 crate::tensor::apply_rope(&mut q2, &mut k2, 5, 2, 1, 64, 10000.0); 754 755 assert_eq!(q1, q2); 756 assert_eq!(k1, k2); 757 } 758 759 #[test] 760 fn test_reference_matmul_matches_tensor() { 761 let backend = ReferenceCpuBackend::new(); 762 let x = vec![1.0f32, 2.0, 3.0]; 763 let w = vec![1.0f32, 0.0, 0.0, 0.0, 1.0, 0.0]; 764 let mut out = vec![0.0f32; 2]; 765 backend.matmul_vec(&mut out, &x, &w, 2, 3); 766 assert_eq!(out, vec![1.0, 2.0]); 767 } 768 769 #[test] 770 fn test_reference_swiglu() { 771 let backend = ReferenceCpuBackend::new(); 772 let gate = vec![0.0f32, 2.0]; 773 let up = vec![1.0f32, 3.0]; 774 let mut out = vec![0.0f32; 2]; 775 backend.swiglu(&mut out, &gate, &up); 776 777 // silu(0) = 0 * 0.5 = 0, so out[0] = 0 778 assert_eq!(out[0], 0.0); 779 // silu(2) = 2 / (1 + exp(-2)) ~= 1.761594, out[1] = 1.761594 * 3 ~= 5.28478 780 assert!((out[1] - 5.28478).abs() < 1e-4); 781 } 782 783 #[test] 784 fn test_reference_gqa_attention() { 785 let backend = ReferenceCpuBackend::new(); 786 let head_dim = 4; 787 let num_q_heads = 2; 788 let num_kv_heads = 1; 789 let seq_len = 2; 790 791 let q = vec![1.0f32; num_q_heads * head_dim]; 792 let k_cache = vec![1.0f32; seq_len * num_kv_heads * head_dim]; 793 let v_cache = vec![2.0f32; seq_len * num_kv_heads * head_dim]; 794 let mut out = vec![0.0f32; num_q_heads * head_dim]; 795 796 backend.gqa_attention( 797 &mut out, 798 &q, 799 &k_cache, 800 &v_cache, 801 seq_len, 802 num_q_heads, 803 num_kv_heads, 804 head_dim, 805 ); 806 807 // All values are 2.0, so weighted sum should be 2.0 for all outputs 808 for v in &out { 809 assert!((v - 2.0).abs() < 1e-5); 810 } 811 } 812 813 #[test] 814 fn test_reference_compute_logits() { 815 let backend = ReferenceCpuBackend::new(); 816 let hidden = vec![1.0f32, 0.5]; 817 let embed = vec![2.0f32, 0.0, 0.0, 4.0, 1.0, 1.0]; 818 let mut logits = vec![0.0f32; 3]; 819 backend.compute_logits(&mut logits, &hidden, &embed, 3, 2); 820 821 assert_eq!(logits, vec![2.0, 2.0, 1.5]); 822 } 823 }