interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / tests / attention_wiring.rs

743 lines · 27781 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//! SC-2: deterministic wiring qualification of the attention reference paths (Drake's attention
17//! hardening cut). Every case uses head-distinct magnitude bands so a wrong kv-head mapping, a
18//! wrong query-head row, a wrong output row or a transposed output cannot pass by accident, and
19//! every negative is a concrete wrong wiring whose answer is shown to differ.
20//!
21//! Values: V for token t, kv head j, dim d is `1000 (j+1) + 20 t + d` (bands never overlap for
22//! t < 16, d < 16), so a value decodes back to (kv head, token, dim). K for token t is
23//! `BIG * e_t` in every kv head and q for query head h is `BIG * e_target(h)`, so head h attends
24//! to token target(h) with weight 1 - O(e^-25).
25
26use aien_abi_core::AttentionGeometry;
27use aien_inference_abi::backend::{ReferenceCpuBackend, TensorBackend};
28use aien_inference_abi::omega_backend::OmegaGb10Backend;
29use aien_inference_abi::tensor;
30use aien_kv_cache::{
31 bf16_bits_to_f32, f32_to_bf16_bits, KvDType, KvPoolConfig, UnifiedKvTensorPool,
32};
33use std::panic::{catch_unwind, AssertUnwindSafe};
34
35const HD: usize = 16;
36const BIG: f32 = 10.0;
37const THETA: f32 = 10000.0;
38const ROPE: aien_inference_abi::RopeParams = aien_inference_abi::RopeParams::plain(THETA);
39
40fn v_val(t: usize, j: usize, d: usize) -> f32 {
41 assert!(t < 16 && d < 16);
42 (1000 * (j + 1) + 20 * t + d) as f32
43}
44fn band_head(x: f32) -> usize {
45 x.round() as usize / 1000 - 1
46}
47fn band_token(x: f32) -> usize {
48 (x.round() as usize % 1000) / 20
49}
50fn band_dim(x: f32) -> usize {
51 x.round() as usize % 20
52}
53
54/// Contiguous `[t][j][d]` K and V for `t_count` tokens and `nkv` kv heads.
55fn banded_kv(t_count: usize, nkv: usize) -> (Vec<f32>, Vec<f32>) {
56 let mut k = vec![0.0f32; t_count * nkv * HD];
57 let mut v = vec![0.0f32; t_count * nkv * HD];
58 for t in 0..t_count {
59 for j in 0..nkv {
60 let base = (t * nkv + j) * HD;
61 k[base + t] = BIG;
62 for d in 0..HD {
63 v[base + d] = v_val(t, j, d);
64 }
65 }
66 }
67 (k, v)
68}
69
70/// q with head h pointing at token `target(h)`.
71fn pointed_q(nq: usize, target: impl Fn(usize) -> usize) -> Vec<f32> {
72 let mut q = vec![0.0f32; nq * HD];
73 for h in 0..nq {
74 q[h * HD + target(h)] = BIG;
75 }
76 q
77}
78
79fn pool_with(
80 cfg: KvPoolConfig,
81 block_ids: &[usize],
82 layer: usize,
83 k: &[f32],
84 v: &[f32],
85 t_count: usize,
86) -> UnifiedKvTensorPool {
87 let mut pool = UnifiedKvTensorPool::allocate(cfg.clone()).unwrap();
88 let kv_dim = cfg.num_kv_heads * cfg.head_dim;
89 for t in 0..t_count {
90 let (b, s) = (t / cfg.block_size, t % cfg.block_size);
91 if b >= block_ids.len() {
92 break;
93 }
94 pool.write_token_kv(
95 block_ids[b],
96 layer,
97 s,
98 &k[t * kv_dim..(t + 1) * kv_dim],
99 &v[t * kv_dim..(t + 1) * kv_dim],
100 );
101 }
102 pool
103}
104
105fn assert_close(got: &[f32], want: &[f32], tol: f32, what: &str) {
106 assert_eq!(got.len(), want.len(), "{what}: length");
107 for (i, (g, w)) in got.iter().zip(want).enumerate() {
108 assert!(
109 (g - w).abs() <= tol,
110 "{what}: index {i} got {g} want {w} (tol {tol})"
111 );
112 }
113}
114
115fn max_abs_diff(a: &[f32], b: &[f32]) -> f32 {
116 a.iter()
117 .zip(b)
118 .map(|(x, y)| (x - y).abs())
119 .fold(0.0, f32::max)
120}
121
122fn panic_message(r: Result<(), Box<dyn std::any::Any + Send>>) -> String {
123 let e = r.expect_err("expected a refusal (panic)");
124 if let Some(s) = e.downcast_ref::<String>() {
125 s.clone()
126 } else if let Some(s) = e.downcast_ref::<&str>() {
127 s.to_string()
128 } else {
129 String::from("<non-string panic payload>")
130 }
131}
132
133// ---------------------------------------------------------------- A: GQA mapping
134
135#[test]
136fn a_gqa_mapping_mha_ratio2_ratio4_ratio8() {
137 let be = ReferenceCpuBackend::new();
138 for (nq, nkv) in [(4, 4), (8, 4), (8, 2), (16, 2), (8, 1)] {
139 let geom = AttentionGeometry::new(nq, nkv, HD).unwrap();
140 // one token: softmax weight is exactly 1, out[h] is V[0][kv_head_of(h)] exactly
141 let (k, v) = banded_kv(1, nkv);
142 let q = vec![1.0f32; nq * HD];
143 let mut out = vec![f32::NAN; nq * HD];
144 be.gqa_attention(&mut out, &q, &k, &v, 1, nq, nkv, HD);
145 let mut wrong_rows = 0;
146 for h in 0..nq {
147 let j = geom.kv_head_of(h).unwrap();
148 assert_eq!(j, h / (nq / nkv));
149 for d in 0..HD {
150 assert_eq!(
151 out[h * HD + d],
152 v_val(0, j, d),
153 "gqa {nq}q/{nkv}kv head {h} dim {d}"
154 );
155 assert_eq!(band_head(out[h * HD + d]), j);
156 }
157 // the modulo mapping h % nkv is the classic wrong wiring; it must give a different
158 // row for some head whenever ratio > 1
159 if h % nkv != j {
160 wrong_rows += 1;
161 assert_ne!(out[h * HD], v_val(0, h % nkv, 0));
162 }
163 }
164 if nq / nkv > 1 && nkv > 1 {
165 assert!(wrong_rows > 0, "{nq}q/{nkv}kv: negative not exercised");
166 }
167 // same through the paged path (one block, Fp32)
168 let cfg = KvPoolConfig {
169 num_blocks: 3,
170 block_size: 4,
171 num_layers: 2,
172 num_kv_heads: nkv,
173 head_dim: HD,
174 dtype: KvDType::Fp32,
175 };
176 let pool = pool_with(cfg, &[2], 1, &k, &v, 1);
177 let mut pout = vec![f32::NAN; nq * HD];
178 be.paged_attention(&mut pout, &q, &pool, &[2], 1, 1, nq, nkv, HD);
179 assert_eq!(pout, out, "paged {nq}q/{nkv}kv differs from gqa");
180 }
181}
182
183// ---------------------------------------------------------------- B + C: q rows, out rows
184
185#[test]
186fn b_query_head_rows_and_c_head_major_output() {
187 let be = ReferenceCpuBackend::new();
188 let (nq, nkv, t_count) = (8usize, 2usize, 4usize);
189 let geom = AttentionGeometry::new(nq, nkv, HD).unwrap();
190 let target = |h: usize| h % t_count;
191 let (k, v) = banded_kv(t_count, nkv);
192 let q = pointed_q(nq, target);
193 let mut out = vec![f32::NAN; nq * HD];
194 be.gqa_attention(&mut out, &q, &k, &v, t_count, nq, nkv, HD);
195
196 let mut want = vec![0.0f32; nq * HD];
197 let mut want_swapped_q = vec![0.0f32; nq * HD]; // q row read from head h ^ 1
198 let mut want_swapped_out = vec![0.0f32; nq * HD]; // head h's answer stored in row h ^ 1
199 for h in 0..nq {
200 let j = geom.kv_head_of(h).unwrap();
201 for d in 0..HD {
202 want[h * HD + d] = v_val(target(h), j, d);
203 want_swapped_q[h * HD + d] = v_val(target(h ^ 1), j, d);
204 want_swapped_out[(h ^ 1) * HD + d] = v_val(target(h), j, d);
205 }
206 }
207 // B: every head read its own q row (token digit) and its own kv head (band)
208 assert_close(&out, &want, 1e-2, "B/C wiring");
209 for h in 0..nq {
210 for d in 0..HD {
211 let x = out[h * HD + d];
212 assert_eq!(band_head(x), geom.kv_head_of(h).unwrap(), "head {h} band");
213 assert_eq!(band_token(x), target(h), "head {h} token digit");
214 assert_eq!(band_dim(x), d, "head {h} dim digit");
215 }
216 }
217 // negatives are real alternatives with different answers
218 assert!(
219 max_abs_diff(&want, &want_swapped_q) >= 10.0,
220 "swapped q rows must differ"
221 );
222 assert!(
223 max_abs_diff(&want, &want_swapped_out) >= 10.0,
224 "swapped out rows must differ"
225 );
226 assert!(max_abs_diff(&out, &want_swapped_q) >= 9.0);
227 assert!(max_abs_diff(&out, &want_swapped_out) >= 9.0);
228 // C: head-major flattening; the dim-major reinterpretation is a different vector
229 let mut dim_major = vec![0.0f32; nq * HD];
230 for h in 0..nq {
231 for d in 0..HD {
232 dim_major[d * nq + h] = want[h * HD + d];
233 }
234 }
235 assert!(
236 max_abs_diff(&out, &dim_major) >= 9.0,
237 "dim-major layout must not match"
238 );
239}
240
241// ---------------------------------------------------------------- D: dense W_o mixing
242
243#[test]
244fn d_dense_wo_mixes_every_head_and_catches_a_permutation() {
245 let be = ReferenceCpuBackend::new();
246 let (nq, nkv, hidden) = (8usize, 2usize, 24usize);
247 let geom = AttentionGeometry::new(nq, nkv, HD).unwrap();
248 let q_dim = geom.q_dim();
249 assert_ne!(
250 q_dim, hidden,
251 "this case deliberately has q_dim != hidden_dim"
252 );
253 // attention output with distinct bands per head (from case B's wiring)
254 let mut attn = vec![0.0f32; q_dim];
255 for h in 0..nq {
256 for d in 0..HD {
257 attn[h * HD + d] = v_val(h % 4, geom.kv_head_of(h).unwrap(), d) / 1000.0;
258 }
259 }
260 // dense W_o [hidden][q_dim]: deterministic pseudo-random entries in [-1, 1], so every
261 // (row, head) pair contributes and no head permutation is a symmetry
262 let mut seed = 0xd0_u64;
263 let w: Vec<f32> = (0..hidden * q_dim).map(|_| lcg(&mut seed)).collect();
264 let mut y = vec![f32::NAN; hidden];
265 be.matmul_vec(&mut y, &attn, &w, hidden, q_dim);
266 // hand sum over every head
267 let mut y_ref = vec![0.0f32; hidden];
268 for r in 0..hidden {
269 let mut heads_contributing = 0;
270 for h in 0..nq {
271 let mut part = 0.0f64;
272 for d in 0..HD {
273 part += (w[r * q_dim + h * HD + d] as f64) * (attn[h * HD + d] as f64);
274 }
275 if part != 0.0 {
276 heads_contributing += 1;
277 }
278 y_ref[r] += part as f32;
279 }
280 assert!(
281 heads_contributing >= 2,
282 "row {r}: W_o must mix several heads"
283 );
284 }
285 assert_close(&y, &y_ref, 1e-3, "W_o dense product");
286 // permutation negative: swapping two heads of the attention output changes y
287 let mut attn_perm = attn.clone();
288 for d in 0..HD {
289 attn_perm.swap(d, HD + d);
290 }
291 let mut y_perm = vec![0.0f32; hidden];
292 be.matmul_vec(&mut y_perm, &attn_perm, &w, hidden, q_dim);
293 assert!(
294 max_abs_diff(&y, &y_perm) > 0.05,
295 "a head permutation before W_o must change the output"
296 );
297 // full h -> h ^ 1 permutation (the Q_ROW / OUT_ROW shape of error) also caught
298 let mut attn_x = vec![0.0f32; q_dim];
299 for h in 0..nq {
300 attn_x[(h ^ 1) * HD..(h ^ 1) * HD + HD].copy_from_slice(&attn[h * HD..h * HD + HD]);
301 }
302 let mut y_x = vec![0.0f32; hidden];
303 be.matmul_vec(&mut y_x, &attn_x, &w, hidden, q_dim);
304 assert!(max_abs_diff(&y, &y_x) > 0.05);
305}
306
307// ---------------------------------------------------------------- E: RoPE
308
309fn lcg(seed: &mut u64) -> f32 {
310 *seed = seed
311 .wrapping_mul(6364136223846793005)
312 .wrapping_add(1442695040888963407);
313 ((*seed >> 33) as f32 / (1u64 << 31) as f32) * 2.0 - 1.0
314}
315
316fn rope_q(be: &dyn TensorBackend, q0: &[f32], pos: usize, nq: usize, nkv: usize) -> Vec<f32> {
317 let mut q = q0.to_vec();
318 let mut k = vec![0.0f32; nkv * HD];
319 be.apply_rope(&mut q, &mut k, pos, HD, nq, nkv, &ROPE);
320 q
321}
322
323fn rope_k(be: &dyn TensorBackend, k0: &[f32], pos: usize, nq: usize, nkv: usize) -> Vec<f32> {
324 let mut q = vec![0.0f32; nq * HD];
325 let mut k = k0.to_vec();
326 be.apply_rope(&mut q, &mut k, pos, HD, nq, nkv, &ROPE);
327 k
328}
329
330fn dot(a: &[f32], b: &[f32]) -> f64 {
331 a.iter()
332 .zip(b)
333 .map(|(x, y)| (*x as f64) * (*y as f64))
334 .sum()
335}
336
337#[test]
338fn e_rope_depends_on_relative_position_only() {
339 let be = ReferenceCpuBackend::new();
340 let (nq, nkv) = (4usize, 2usize);
341 let mut seed = 0x5eed_u64;
342 let q0: Vec<f32> = (0..nq * HD).map(|_| lcg(&mut seed)).collect();
343 let k0: Vec<f32> = (0..nkv * HD).map(|_| lcg(&mut seed)).collect();
344 // the trait's argument order (head_dim, num_q_heads, num_kv_heads) must reach the
345 // implementation (num_heads, num_kv_heads, head_dim) correctly: compare bitwise
346 let (mut tq, mut tk) = (q0.clone(), k0.clone());
347 tensor::apply_rope(&mut tq, &mut tk, 7, nq, nkv, HD, THETA);
348 assert_eq!(
349 rope_q(&be, &q0, 7, nq, nkv),
350 tq,
351 "trait rope q != tensor rope q"
352 );
353 assert_eq!(
354 rope_k(&be, &k0, 7, nq, nkv),
355 tk,
356 "trait rope k != tensor rope k"
357 );
358 assert_ne!(tq, q0, "rope at pos 7 must change q");
359 // same position on both sides cancels: dot unchanged
360 for h in 0..nq {
361 let j = h / (nq / nkv);
362 let d0 = dot(&q0[h * HD..(h + 1) * HD], &k0[j * HD..(j + 1) * HD]);
363 let d1 = dot(
364 &rope_q(&be, &q0, 11, nq, nkv)[h * HD..(h + 1) * HD],
365 &rope_k(&be, &k0, 11, nq, nkv)[j * HD..(j + 1) * HD],
366 );
367 assert!(
368 (d0 - d1).abs() < 1e-4,
369 "head {h}: same-position rope changed the dot"
370 );
371 }
372 // (5,2) and (13,10) share the offset 3; (5,3) has offset 2
373 for h in 0..nq {
374 let j = h / (nq / nkv);
375 let at = |pq: usize, pk: usize| {
376 dot(
377 &rope_q(&be, &q0, pq, nq, nkv)[h * HD..(h + 1) * HD],
378 &rope_k(&be, &k0, pk, nq, nkv)[j * HD..(j + 1) * HD],
379 )
380 };
381 let (a, b, c) = (at(5, 2), at(13, 10), at(5, 3));
382 assert!(
383 (a - b).abs() < 1e-4,
384 "head {h}: offset 3 at two bases differs: {a} vs {b}"
385 );
386 assert!(
387 (a - c).abs() > 1e-3,
388 "head {h}: offsets 3 and 2 must differ: {a} vs {c}"
389 );
390 }
391 // through attention: V one-hot per token so the output IS the softmax weight vector
392 let t_count = 6usize;
393 let weights = |base: usize, q_pos: usize| -> Vec<f32> {
394 let mut k = vec![0.0f32; t_count * nkv * HD];
395 let mut v = vec![0.0f32; t_count * nkv * HD];
396 for t in 0..t_count {
397 let kt = rope_k(&be, &k0, base + t, nq, nkv);
398 for j in 0..nkv {
399 let b = (t * nkv + j) * HD;
400 k[b..b + HD].copy_from_slice(&kt[j * HD..(j + 1) * HD]);
401 v[b + t] = 1.0;
402 }
403 }
404 let q = rope_q(
405 &be,
406 &q0.iter().map(|x| x * 4.0).collect::<Vec<_>>(),
407 base + q_pos,
408 nq,
409 nkv,
410 );
411 let mut out = vec![f32::NAN; nq * HD];
412 be.gqa_attention(&mut out, &q, &k, &v, t_count, nq, nkv, HD);
413 out
414 };
415 let w0 = weights(0, t_count - 1);
416 let w37 = weights(37, t_count - 1);
417 assert_close(&w0, &w37, 1e-4, "softmax weights must be shift invariant");
418 for h in 0..nq {
419 let s: f32 = w0[h * HD..h * HD + t_count].iter().sum();
420 assert!((s - 1.0).abs() < 1e-4, "head {h} weights sum {s}");
421 assert!(w0[h * HD + t_count..(h + 1) * HD]
422 .iter()
423 .all(|x| x.abs() < 1e-6));
424 }
425 let w_shifted_q = weights(0, t_count + 4); // q five positions later than the last token
426 assert!(
427 max_abs_diff(&w0, &w_shifted_q) > 1e-3,
428 "moving q relative to K must change the weights"
429 );
430}
431
432// ---------------------------------------------------------------- F: boundaries
433
434fn cfg(nkv: usize, block_size: usize, num_blocks: usize, dtype: KvDType) -> KvPoolConfig {
435 KvPoolConfig {
436 num_blocks,
437 block_size,
438 num_layers: 3,
439 num_kv_heads: nkv,
440 head_dim: HD,
441 dtype,
442 }
443}
444
445#[test]
446fn f_empty_context_and_no_blocks_write_zeros() {
447 let be = ReferenceCpuBackend::new();
448 let (nq, nkv) = (8usize, 2usize);
449 let (k, v) = banded_kv(3, nkv);
450 let pool = pool_with(cfg(nkv, 4, 4, KvDType::Fp32), &[1], 2, &k, &v, 3);
451 let q = pointed_q(nq, |h| h % 3);
452 let mut out = vec![f32::NAN; nq * HD];
453 be.paged_attention(&mut out, &q, &pool, &[1], 0, 2, nq, nkv, HD);
454 assert!(out.iter().all(|x| *x == 0.0), "context 0 must write zeros");
455 out.fill(f32::NAN);
456 be.paged_attention(&mut out, &q, &pool, &[], 3, 2, nq, nkv, HD);
457 assert!(out.iter().all(|x| *x == 0.0), "no blocks must write zeros");
458 out.fill(f32::NAN);
459 be.gqa_attention(&mut out, &q, &k, &v, 0, nq, nkv, HD);
460 assert!(out.iter().all(|x| *x == 0.0), "seq_len 0 must write zeros");
461}
462
463#[test]
464fn f_one_token_is_exactly_v() {
465 let be = ReferenceCpuBackend::new();
466 let (nq, nkv) = (8usize, 4usize);
467 let (k, v) = banded_kv(1, nkv);
468 let pool = pool_with(cfg(nkv, 16, 2, KvDType::Fp32), &[1], 0, &k, &v, 1);
469 let q: Vec<f32> = (0..nq * HD).map(|i| (i % 7) as f32 - 3.0).collect();
470 let mut out = vec![f32::NAN; nq * HD];
471 be.paged_attention(&mut out, &q, &pool, &[1], 1, 0, nq, nkv, HD);
472 for h in 0..nq {
473 for d in 0..HD {
474 assert_eq!(out[h * HD + d], v_val(0, h / 2, d));
475 }
476 }
477}
478
479/// Partial last block, several blocks, scattered ids, Fp32 and Bf16, against the contiguous
480/// reference over the test's own arrays (not the pool's gather).
481#[test]
482fn f_partial_block_multiple_scattered_blocks_fp32_and_bf16() {
483 let be = ReferenceCpuBackend::new();
484 let (nq, nkv, bs) = (8usize, 2usize, 4usize);
485 let ids = [7usize, 2, 11, 29];
486 let ctx = 14; // 3 full blocks + 2 tokens of the 4th
487 let mut seed = 99u64;
488 let kv_dim = nkv * HD;
489 let k: Vec<f32> = (0..ctx * kv_dim).map(|_| lcg(&mut seed)).collect();
490 let v: Vec<f32> = (0..ctx * kv_dim).map(|_| lcg(&mut seed) * 50.0).collect();
491 let q: Vec<f32> = (0..nq * HD).map(|_| lcg(&mut seed) * 3.0).collect();
492 for dtype in [KvDType::Fp32, KvDType::Bf16] {
493 let pool = pool_with(cfg(nkv, bs, 32, dtype), &ids, 1, &k, &v, ctx);
494 // what the pool holds after its own rounding
495 let round = |x: f32| match dtype {
496 KvDType::Bf16 => bf16_bits_to_f32(f32_to_bf16_bits(x)),
497 _ => x,
498 };
499 let kr: Vec<f32> = k.iter().map(|x| round(*x)).collect();
500 let vr: Vec<f32> = v.iter().map(|x| round(*x)).collect();
501 let mut want = vec![0.0f32; nq * HD];
502 be.gqa_attention(&mut want, &q, &kr, &vr, ctx, nq, nkv, HD);
503 let mut got = vec![f32::NAN; nq * HD];
504 be.paged_attention(&mut got, &q, &pool, &ids, ctx, 1, nq, nkv, HD);
505 assert_close(&got, &want, 1e-4, &format!("paged vs contiguous {dtype:?}"));
506 // the other layers of the same blocks were never written: layer 0 must not see this data
507 let mut other = vec![f32::NAN; nq * HD];
508 be.paged_attention(&mut other, &q, &pool, &ids, ctx, 0, nq, nkv, HD);
509 assert!(
510 max_abs_diff(&other, &want) > 1.0,
511 "layer 0 read layer 1's data"
512 );
513 // tokens past the block table are dropped (documented oracle behaviour): the first two
514 // blocks only
515 let mut want8 = vec![0.0f32; nq * HD];
516 be.gqa_attention(&mut want8, &q, &kr, &vr, 2 * bs, nq, nkv, HD);
517 let mut got8 = vec![f32::NAN; nq * HD];
518 be.paged_attention(&mut got8, &q, &pool, &ids[..2], ctx, 1, nq, nkv, HD);
519 assert_close(&got8, &want8, 1e-4, "tokens past the table dropped");
520 assert!(
521 max_abs_diff(&got8, &want) > 1e-3,
522 "8 and 14 tokens must differ"
523 );
524 }
525}
526
527#[test]
528fn f_wrong_q_length_is_refused() {
529 let be = ReferenceCpuBackend::new();
530 let (nq, nkv) = (8usize, 2usize);
531 let (k, v) = banded_kv(2, nkv);
532 let pool = pool_with(cfg(nkv, 4, 4, KvDType::Fp32), &[0], 0, &k, &v, 2);
533 let q = vec![1.0f32; nq * HD + HD]; // one head too many
534 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
535 let mut out = vec![0.0f32; nq * HD];
536 be.paged_attention(&mut out, &q, &pool, &[0], 2, 0, nq, nkv, HD);
537 })));
538 assert!(
539 msg.contains("refused") && msg.contains("q has 144"),
540 "{msg}"
541 );
542 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
543 let mut out = vec![0.0f32; nq * HD];
544 be.gqa_attention(&mut out, &q[..nq * HD - 1], &k, &v, 2, nq, nkv, HD);
545 })));
546 assert!(
547 msg.contains("gqa_attention refused") && msg.contains("q has 127"),
548 "{msg}"
549 );
550}
551
552#[test]
553fn f_wrong_out_length_is_refused() {
554 let be = ReferenceCpuBackend::new();
555 let (nq, nkv) = (8usize, 2usize);
556 let (k, v) = banded_kv(2, nkv);
557 let pool = pool_with(cfg(nkv, 4, 4, KvDType::Fp32), &[0], 0, &k, &v, 2);
558 let q = vec![1.0f32; nq * HD];
559 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
560 let mut out = vec![0.0f32; nq * HD - HD]; // one head short
561 be.paged_attention(&mut out, &q, &pool, &[0], 2, 0, nq, nkv, HD);
562 })));
563 assert!(
564 msg.contains("refused") && msg.contains("out has 112"),
565 "{msg}"
566 );
567 // batch: 2 sequences need 2 x q_dim
568 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
569 let mut out = vec![0.0f32; nq * HD];
570 let q2 = vec![1.0f32; 2 * nq * HD];
571 be.paged_attention_batch(&mut out, &q2, &pool, &[0, 0], &[2, 2], 1, 2, 0, nq, nkv, HD);
572 })));
573 assert!(msg.contains("paged_attention_batch refused"), "{msg}");
574}
575
576#[test]
577fn f_incompatible_kv_geometry_is_refused_before_reading() {
578 let be = ReferenceCpuBackend::new();
579 let (nq, nkv) = (8usize, 2usize);
580 let (k, v) = banded_kv(2, nkv);
581 // pool laid out for 2 kv heads, caller claims 4
582 let pool = pool_with(cfg(nkv, 4, 4, KvDType::Fp32), &[0], 0, &k, &v, 2);
583 let q = vec![1.0f32; nq * HD];
584 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
585 let mut out = vec![0.0f32; nq * HD];
586 be.paged_attention(&mut out, &q, &pool, &[0], 2, 0, nq, 4, HD);
587 })));
588 assert!(
589 msg.contains("4 kv heads x head_dim 16") && msg.contains("pool is laid out for 2 kv heads"),
590 "{msg}"
591 );
592 // head_dim mismatch (caller says 8), even with an empty context
593 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
594 let mut out = vec![0.0f32; nq * 8];
595 be.paged_attention(&mut out, &q[..nq * 8], &pool, &[0], 0, 0, nq, nkv, 8);
596 })));
597 assert!(msg.contains("head_dim 16"), "{msg}");
598 // non-divisible heads
599 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
600 let mut out = vec![0.0f32; 6 * HD];
601 be.gqa_attention(&mut out, &q[..6 * HD], &k, &v, 2, 6, 4, HD);
602 })));
603 assert!(
604 msg.contains("6 is not a multiple of num_kv_heads 4"),
605 "{msg}"
606 );
607 // a short K cache for the claimed seq_len
608 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
609 let mut out = vec![0.0f32; nq * HD];
610 be.gqa_attention(&mut out, &q, &k, &v, 5, nq, nkv, HD);
611 })));
612 assert!(
613 msg.contains("k/v caches hold 64/64 values") && msg.contains("need 160"),
614 "{msg}"
615 );
616}
617
618/// The chip backend refuses the same mismatches before any native call; in the CPU-stub build
619/// this is the only path that runs, and the refusal is counted as a chip error. In a strict
620/// process the refusal surfaces as the strict violation for the op (the fallback itself is
621/// fatal); in a dev process the reference path then refuses with the geometry message.
622#[test]
623fn f_omega_backend_refuses_pool_mismatch_before_native_code() {
624 let strict = aien_inference_abi::strict::production_strict();
625 let refused = |msg: &str, op: &str, dev_text: &[&str]| {
626 if strict {
627 assert!(
628 msg.contains(aien_inference_abi::strict::STRICT_VIOLATION_PREFIX)
629 && msg.contains(op),
630 "{msg}"
631 );
632 } else {
633 assert!(dev_text.iter().all(|t| msg.contains(t)), "{msg}");
634 }
635 };
636 let be = OmegaGb10Backend::new();
637 let (nq, nkv) = (8usize, 2usize);
638 let (k, v) = banded_kv(2, nkv);
639 let pool = pool_with(cfg(nkv, 4, 4, KvDType::Fp32), &[0], 0, &k, &v, 2);
640 let q = vec![1.0f32; nq * HD];
641 let before = be.chip_errors();
642 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
643 let mut out = vec![0.0f32; nq * HD];
644 be.paged_attention(&mut out, &q, &pool, &[0], 2, 0, nq, 4, HD);
645 })));
646 refused(
647 &msg,
648 "paged_attention",
649 &["pool is laid out for 2 kv heads"],
650 );
651 assert!(be.chip_errors() > before, "the refusal must be counted");
652 let msg = panic_message(catch_unwind(AssertUnwindSafe(|| {
653 let mut out = vec![0.0f32; 6 * HD];
654 be.gqa_attention(&mut out, &q[..6 * HD], &k, &v, 2, 6, 4, HD);
655 })));
656 refused(
657 &msg,
658 "gqa_attention",
659 &["6 is not a multiple of num_kv_heads 4"],
660 );
661}
662
663/// Batched call with a shared prefix and negative (padding) table entries equals the
664/// per-sequence calls; a sequence whose private tail differs gets a different answer.
665#[test]
666fn f_batch_shared_prefix_scattered_ids_matches_single_calls() {
667 let be = ReferenceCpuBackend::new();
668 let (nq, nkv, bs) = (8usize, 2usize, 4usize);
669 let kv_dim = nkv * HD;
670 let mut seed = 7u64;
671 let mut pool = UnifiedKvTensorPool::allocate(cfg(nkv, bs, 32, KvDType::Fp32)).unwrap();
672 // shared prefix blocks 9 and 3 (8 tokens), private tails: seq0 block 20 (3 tokens),
673 // seq1 block 5 (2 tokens), seq2 no tail (prefix only)
674 let mut fill = |block: usize, tokens: usize| {
675 for s in 0..tokens {
676 let k: Vec<f32> = (0..kv_dim).map(|_| lcg(&mut seed)).collect();
677 let v: Vec<f32> = (0..kv_dim).map(|_| lcg(&mut seed) * 20.0).collect();
678 pool.write_token_kv(block, 0, s, &k, &v);
679 }
680 };
681 fill(9, bs);
682 fill(3, bs);
683 fill(20, 3);
684 fill(5, 2);
685 let tables: [&[i32]; 3] = [&[9, 3, 20], &[9, 3, 5], &[9, 3, -1]];
686 let ctx = [11i32, 10, 8];
687 let maxb = 3;
688 let q: Vec<f32> = (0..3 * nq * HD).map(|_| lcg(&mut seed) * 2.0).collect();
689 let flat: Vec<i32> = tables.concat();
690 let mut batch = vec![f32::NAN; 3 * nq * HD];
691 be.paged_attention_batch(&mut batch, &q, &pool, &flat, &ctx, maxb, 3, 0, nq, nkv, HD);
692 for s in 0..3 {
693 let ids: Vec<usize> = tables[s]
694 .iter()
695 .filter(|b| **b >= 0)
696 .map(|b| *b as usize)
697 .collect();
698 let mut single = vec![f32::NAN; nq * HD];
699 be.paged_attention(
700 &mut single,
701 &q[s * nq * HD..(s + 1) * nq * HD],
702 &pool,
703 &ids,
704 ctx[s] as usize,
705 0,
706 nq,
707 nkv,
708 HD,
709 );
710 assert_close(
711 &batch[s * nq * HD..(s + 1) * nq * HD],
712 &single,
713 1e-6,
714 &format!("seq {s}"),
715 );
716 }
717 // the three sequences see different histories, so with the same q they must differ
718 let q0 = &q[..nq * HD];
719 let mut same_q = vec![0.0f32; 3 * nq * HD];
720 for s in 0..3 {
721 same_q[s * nq * HD..(s + 1) * nq * HD].copy_from_slice(q0);
722 }
723 be.paged_attention_batch(
724 &mut batch, &same_q, &pool, &flat, &ctx, maxb, 3, 0, nq, nkv, HD,
725 );
726 assert!(max_abs_diff(&batch[..nq * HD], &batch[nq * HD..2 * nq * HD]) > 1e-3);
727 assert!(max_abs_diff(&batch[..nq * HD], &batch[2 * nq * HD..]) > 1e-3);
728 // context_len <= 0 rows are zero
729 be.paged_attention_batch(
730 &mut batch,
731 &same_q,
732 &pool,
733 &flat,
734 &[11, 0, -4],
735 maxb,
736 3,
737 0,
738 nq,
739 nkv,
740 HD,
741 );
742 assert!(batch[nq * HD..].iter().all(|x| *x == 0.0));
743}