interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / infer / attention.rs

417 lines · 14836 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//! Allocation-free single-query decode attention over caller-owned KV storage.
17
18use super::gemm::{self, KernelError};
19
20/// Fixed-capacity row-major key/value cache for decode attention.
21pub struct KvCache<'a> {
22 keys: &'a mut [f32],
23 values: &'a mut [f32],
24 capacity: usize,
25 n_kv_heads: usize,
26 head_dim: usize,
27 len: usize,
28}
29
30impl<'a> KvCache<'a> {
31 /// Creates a cache backed by `keys` and `values`, each sized for capacity.
32 pub fn new(
33 keys: &'a mut [f32],
34 values: &'a mut [f32],
35 capacity: usize,
36 n_kv_heads: usize,
37 head_dim: usize,
38 ) -> Result<Self, KernelError> {
39 if n_kv_heads == 0 || head_dim == 0 {
40 return Err(KernelError::InvalidParameter);
41 }
42 let required = capacity
43 .checked_mul(n_kv_heads)
44 .and_then(|n| n.checked_mul(head_dim))
45 .ok_or(KernelError::Shape)?;
46 if keys.len() < required || values.len() < required {
47 return Err(KernelError::Shape);
48 }
49 Ok(Self {
50 keys,
51 values,
52 capacity,
53 n_kv_heads,
54 head_dim,
55 len: 0,
56 })
57 }
58
59 pub fn len(&self) -> usize {
60 self.len
61 }
62 pub fn is_empty(&self) -> bool {
63 self.len == 0
64 }
65 pub fn capacity(&self) -> usize {
66 self.capacity
67 }
68
69 /// Appends one token containing all KV heads.
70 pub fn append(&mut self, key: &[f32], value: &[f32]) -> Result<(), KernelError> {
71 let width = self.n_kv_heads * self.head_dim;
72 if key.len() != width || value.len() != width {
73 return Err(KernelError::Shape);
74 }
75 if self.len == self.capacity {
76 return Err(KernelError::Shape);
77 }
78 let start = self.len * width;
79 self.keys[start..start + width].copy_from_slice(key);
80 self.values[start..start + width].copy_from_slice(value);
81 self.len += 1;
82 Ok(())
83 }
84
85 fn key(&self, pos: usize, head: usize) -> &[f32] {
86 let start = (pos * self.n_kv_heads + head) * self.head_dim;
87 &self.keys[start..start + self.head_dim]
88 }
89
90 fn value(&self, pos: usize, head: usize) -> &[f32] {
91 let start = (pos * self.n_kv_heads + head) * self.head_dim;
92 &self.values[start..start + self.head_dim]
93 }
94}
95
96/// Computes all query heads at `position` using grouped-query attention.
97///
98/// `query` and `output` are head-major with `n_heads * head_dim` elements.
99/// Each contiguous group of `n_heads / n_kv_heads` query heads shares a KV
100/// head. `scores` is scratch space for at least `position + 1` scores.
101pub fn decode(
102 query: &[f32],
103 output: &mut [f32],
104 cache: &KvCache<'_>,
105 n_heads: usize,
106 position: usize,
107 scores: &mut [f32],
108) -> Result<(), KernelError> {
109 if n_heads == 0 || !n_heads.is_multiple_of(cache.n_kv_heads) {
110 return Err(KernelError::InvalidParameter);
111 }
112 let width = n_heads
113 .checked_mul(cache.head_dim)
114 .ok_or(KernelError::Shape)?;
115 let tokens = position.checked_add(1).ok_or(KernelError::Shape)?;
116 if query.len() != width
117 || output.len() != width
118 || position >= cache.len
119 || scores.len() < tokens
120 {
121 return Err(KernelError::Shape);
122 }
123 let group_size = n_heads / cache.n_kv_heads;
124 let scale = 1.0 / gemm::sqrt_approx(cache.head_dim as f32);
125 for head in 0..n_heads {
126 let kv_head = head / group_size;
127 let q = &query[head * cache.head_dim..(head + 1) * cache.head_dim];
128 for (token, score) in scores[..tokens].iter_mut().enumerate() {
129 *score = q
130 .iter()
131 .zip(cache.key(token, kv_head))
132 .map(|(a, b)| a * b)
133 .sum::<f32>()
134 * scale;
135 }
136 gemm::softmax(&mut scores[..tokens])?;
137 let out = &mut output[head * cache.head_dim..(head + 1) * cache.head_dim];
138 out.fill(0.0);
139 for (token, &weight) in scores[..tokens].iter().enumerate() {
140 for (dst, &v) in out.iter_mut().zip(cache.value(token, kv_head)) {
141 *dst += weight * v;
142 }
143 }
144 }
145 Ok(())
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 fn cache<'a>(
153 keys: &'a mut [f32],
154 values: &'a mut [f32],
155 capacity: usize,
156 kv_heads: usize,
157 dim: usize,
158 ) -> KvCache<'a> {
159 KvCache::new(keys, values, capacity, kv_heads, dim).unwrap()
160 }
161
162 #[test]
163 fn one_token_returns_value_exactly() {
164 let (mut keys, mut values) = ([0.0; 2], [0.0; 2]);
165 let mut kv = cache(&mut keys, &mut values, 1, 1, 2);
166 kv.append(&[1.0, 2.0], &[7.0, -3.0]).unwrap();
167 let mut out = [0.0; 2];
168 decode(&[0.5, 1.0], &mut out, &kv, 1, 0, &mut [0.0]).unwrap();
169 assert_eq!(out, [7.0, -3.0]);
170 }
171
172 #[test]
173 fn two_head_hand_computed_attention() {
174 let (mut keys, mut values) = ([1.0, 0.0, 0.0, 1.0], [2.0, 4.0, 8.0, 10.0]);
175 let mut kv = cache(&mut keys, &mut values, 2, 1, 2);
176 kv.append(&[1.0, 0.0], &[2.0, 4.0]).unwrap();
177 kv.append(&[0.0, 1.0], &[8.0, 10.0]).unwrap();
178 let query = [0.0; 4];
179 let mut out = [0.0; 4];
180 decode(&query, &mut out, &kv, 2, 1, &mut [0.0; 2]).unwrap();
181 assert_eq!(out, [5.0, 7.0, 5.0, 7.0]);
182 }
183
184 #[test]
185 fn random_inputs_match_scalar_reference() {
186 let mut seed = 0x1234_5678_u64;
187 let mut next = || {
188 seed ^= seed << 13;
189 seed ^= seed >> 7;
190 seed ^= seed << 17;
191 (seed as i32 as f32) / i32::MAX as f32
192 };
193 let (mut keys, mut values) = ([0.0; 12], [0.0; 12]);
194 let mut kv = cache(&mut keys, &mut values, 3, 1, 4);
195 let ks: std::vec::Vec<_> = (0..12).map(|_| next()).collect();
196 let vs: std::vec::Vec<_> = (0..12).map(|_| next()).collect();
197 for i in 0..3 {
198 kv.append(&ks[i * 4..i * 4 + 4], &vs[i * 4..i * 4 + 4])
199 .unwrap();
200 }
201 let query: std::vec::Vec<_> = (0..8).map(|_| next()).collect();
202 let mut out = [0.0; 8];
203 decode(&query, &mut out, &kv, 2, 2, &mut [0.0; 3]).unwrap();
204 for head in 0..2 {
205 let q = &query[head * 4..head * 4 + 4];
206 let mut logits = [0.0; 3];
207 for t in 0..3 {
208 logits[t] = q
209 .iter()
210 .zip(&ks[t * 4..t * 4 + 4])
211 .map(|(a, b)| a * b)
212 .sum::<f32>()
213 / 2.0;
214 }
215 let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
216 let weights: std::vec::Vec<_> = logits.iter().map(|x| (x - max).exp()).collect();
217 let total: f32 = weights.iter().sum();
218 for d in 0..4 {
219 let expected: f32 = (0..3).map(|t| weights[t] / total * vs[t * 4 + d]).sum();
220 assert!((out[head * 4 + d] - expected).abs() < 2e-5);
221 }
222 }
223 }
224
225 #[test]
226 fn gqa_maps_groups_of_query_heads_to_kv_heads() {
227 let (mut keys, mut values) = ([0.0; 4], [3.0, 4.0, 9.0, 10.0]);
228 let mut kv = cache(&mut keys, &mut values, 1, 2, 2);
229 kv.append(&[0.0; 4], &[3.0, 4.0, 9.0, 10.0]).unwrap();
230 let mut out = [0.0; 8];
231 decode(&[0.0; 8], &mut out, &kv, 4, 0, &mut [0.0]).unwrap();
232 assert_eq!(out, [3.0, 4.0, 3.0, 4.0, 9.0, 10.0, 9.0, 10.0]);
233 }
234
235 #[test]
236 fn append_rejects_capacity_overflow() {
237 let (mut keys, mut values) = ([0.0; 2], [0.0; 2]);
238 let mut kv = cache(&mut keys, &mut values, 1, 1, 2);
239 kv.append(&[0.0; 2], &[0.0; 2]).unwrap();
240 assert_eq!(kv.append(&[0.0; 2], &[0.0; 2]), Err(KernelError::Shape));
241 }
242
243 // ---- AO-1 (Drake.s attention hardening cut): independent oracle coverage. Values carry
244 // head-distinct bands: token t, kv head j, dim d -> 1000 (j+1) + 20 t + d, so every output
245 // value decodes back to where it came from.
246 fn banded(t: usize, j: usize, d: usize) -> f32 {
247 (1000 * (j + 1) + 20 * t + d) as f32
248 }
249 fn absf(x: f32) -> f32 {
250 if x < 0.0 {
251 -x
252 } else {
253 x
254 }
255 }
256 fn lcg(seed: &mut u64) -> f32 {
257 *seed = seed
258 .wrapping_mul(6364136223846793005)
259 .wrapping_add(1442695040888963407);
260 ((*seed >> 33) as f32 / (1u64 << 31) as f32) * 2.0 - 1.0
261 }
262
263 const D: usize = 4;
264 const KV: usize = 2;
265 const H: usize = 8;
266 const T: usize = 4;
267
268 /// Query head h points at token h % T (K is `10 e_t`, so the match scores 50 and the
269 /// rest 0); fills `out` with the decode result.
270 fn banded_decode(out: &mut [f32; H * D]) {
271 let mut keys = [0.0f32; T * KV * D];
272 let mut values = [0.0f32; T * KV * D];
273 let mut kv = cache(&mut keys, &mut values, T, KV, D);
274 for t in 0..T {
275 let mut k = [0.0f32; KV * D];
276 let mut v = [0.0f32; KV * D];
277 for j in 0..KV {
278 k[j * D + t] = 10.0;
279 for d in 0..D {
280 v[j * D + d] = banded(t, j, d);
281 }
282 }
283 kv.append(&k, &v).unwrap();
284 }
285 let mut q = [0.0f32; H * D];
286 for h in 0..H {
287 q[h * D + (h % T)] = 10.0;
288 }
289 let mut scores = [0.0f32; T];
290 decode(&q, out, &kv, H, T - 1, &mut scores).unwrap();
291 }
292
293 #[test]
294 fn query_rows_kv_groups_and_head_major_output_decode_from_bands() {
295 let mut out = [0.0f32; H * D];
296 banded_decode(&mut out);
297 let group = H / KV;
298 for h in 0..H {
299 for d in 0..D {
300 let x = out[h * D + d];
301 let want = banded(h % T, h / group, d);
302 assert!(absf(x - want) < 1e-2, "head {h} dim {d}: {x} vs {want}");
303 let n = (x + 0.5) as usize;
304 assert_eq!(n / 1000 - 1, h / group, "kv head band of head {h}");
305 assert_eq!((n % 1000) / 20, h % T, "token digit of head {h}");
306 assert_eq!(n % 20, d, "dim digit of head {h}");
307 }
308 }
309 // negatives: the h ^ 1 query row, the h ^ 1 output row and the modulo kv mapping are
310 // all different answers by at least one band step
311 for h in 0..H {
312 let j = h / group;
313 assert!(absf(out[h * D] - banded((h ^ 1) % T, j, 0)) >= 19.0);
314 assert!(absf(out[(h ^ 1) * D] - banded(h % T, j, 0)) >= 19.0);
315 if h % KV != j {
316 assert!(absf(out[h * D] - banded(h % T, h % KV, 0)) >= 999.0);
317 }
318 }
319 // dim-major reinterpretation is not the same vector
320 let mut worst = 0.0f32;
321 for h in 0..H {
322 for d in 0..D {
323 worst = worst.max(absf(out[d * H + h] - banded(h % T, h / group, d)));
324 }
325 }
326 assert!(worst >= 19.0, "a dim-major output would have passed");
327 }
328
329 #[test]
330 fn dense_output_projection_mixes_heads_and_catches_a_permutation() {
331 let mut attn = [0.0f32; H * D];
332 banded_decode(&mut attn);
333 for x in attn.iter_mut() {
334 *x /= 100.0;
335 }
336 const ROWS: usize = 6; // hidden width deliberately != H * D
337 let mut seed = 0xd0u64;
338 let mut w = [0.0f32; ROWS * H * D];
339 for x in w.iter_mut() {
340 *x = lcg(&mut seed);
341 }
342 let mut y = [0.0f32; ROWS];
343 gemm::matvec_ref(&w, &attn, &mut y, ROWS, H * D, H * D, 1, 1).unwrap();
344 for (r, yr) in y.iter().enumerate() {
345 let mut hand = 0.0f32;
346 let mut heads = 0;
347 for h in 0..H {
348 let mut part = 0.0f32;
349 for d in 0..D {
350 part += w[r * H * D + h * D + d] * attn[h * D + d];
351 }
352 if part != 0.0 {
353 heads += 1;
354 }
355 hand += part;
356 }
357 assert!(heads >= 2, "row {r} mixes one head only");
358 assert!(absf(yr - hand) < 1e-4, "row {r}: {yr} vs {hand}");
359 }
360 let mut perm = attn;
361 for d in 0..D {
362 perm.swap(d, D + d);
363 }
364 let mut y_perm = [0.0f32; ROWS];
365 gemm::matvec_ref(&w, &perm, &mut y_perm, ROWS, H * D, H * D, 1, 1).unwrap();
366 let mut worst = 0.0f32;
367 for r in 0..ROWS {
368 worst = worst.max(absf(y[r] - y_perm[r]));
369 }
370 assert!(
371 worst > 0.05,
372 "swapping two heads before W_o changed nothing"
373 );
374 }
375
376 #[test]
377 fn decode_refuses_wrong_shapes_and_head_counts() {
378 let (mut keys, mut values) = ([0.0f32; 2 * KV * D], [0.0f32; 2 * KV * D]);
379 let mut kv = cache(&mut keys, &mut values, 2, KV, D);
380 kv.append(&[0.0; KV * D], &[1.0; KV * D]).unwrap();
381 let q = [0.0f32; H * D];
382 let mut out = [0.0f32; H * D];
383 let mut scores = [0.0f32; 2];
384 assert_eq!(
385 decode(&q[..5 * D], &mut out[..5 * D], &kv, 5, 0, &mut scores),
386 Err(KernelError::InvalidParameter),
387 "5 heads over 2 kv heads"
388 );
389 assert_eq!(
390 decode(&q, &mut out, &kv, 0, 0, &mut scores),
391 Err(KernelError::InvalidParameter)
392 );
393 assert_eq!(
394 decode(&q[..H * D - 1], &mut out, &kv, H, 0, &mut scores),
395 Err(KernelError::Shape),
396 "short query"
397 );
398 assert_eq!(
399 decode(&q, &mut out[..H * D - D], &kv, H, 0, &mut scores),
400 Err(KernelError::Shape),
401 "short output"
402 );
403 assert_eq!(
404 decode(&q, &mut out, &kv, H, 1, &mut scores),
405 Err(KernelError::Shape),
406 "position past the appended tokens"
407 );
408 assert_eq!(
409 decode(&q, &mut out, &kv, H, 0, &mut scores[..0]),
410 Err(KernelError::Shape),
411 "no score scratch"
412 );
413 // and the good call still works: one token, output is exactly V per kv group
414 decode(&q, &mut out, &kv, H, 0, &mut scores).unwrap();
415 assert!(out.iter().all(|x| *x == 1.0));
416 }
417}