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/aienux/blob/main/crates/aienos-infer/src/decode.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. 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 `aienux / crates / aienos-infer / src / decode.rs` 541 lines ยท 17893 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 //! Forward pass, KV cache and greedy decode (aienos#34 lanes 2 and 3). 17 //! 18 //! Scalar f32, one token at a time. Graph per layer (llama.cpp 19 //! `src/models/llama.cpp`): RMSNorm, Q/K/V, RoPE (adjacent pairs, base 20 //! `rope_freq_base`, per-pair divisor from `rope_freqs.weight`), causal 21 //! grouped-query attention over the cache (scale `1/sqrt(head_dim)`), output 22 //! projection, residual, RMSNorm, SwiGLU (`silu(gate) * up -> down`), residual. 23 24 use alloc::vec; 25 use alloc::vec::Vec; 26 27 use crate::dotprod::{cpu_dotprod, DotProd, Q8Act}; 28 use crate::math; 29 use crate::model::{InferError, Model, Weight}; 30 31 /// KV cache plus scratch buffers for one sequence. 32 pub struct DecodeState { 33 capacity: usize, 34 pos: usize, 35 kv_dim: usize, 36 /// `[layer][pos][kv_dim]` 37 k: Vec, 38 v: Vec, 39 x: Vec, 40 h: Vec, 41 q: Vec, 42 kk: Vec, 43 vv: Vec, 44 att: Vec, 45 scores: Vec, 46 gate: Vec, 47 up: Vec, 48 tmp: Vec, 49 scr: Vec, 50 rope_cos: Vec, 51 rope_sin: Vec, 52 /// Logits of the last position that asked for them. 53 pub logits: Vec, 54 /// Round matvec inputs to the Q8_K grid like ggml does (default off). 55 pub emulate_q8k: bool, 56 /// SDOT int8-activation path for the K-quant matvecs (Q8_K activations, 57 /// integer dots; see `dotprod`). `Some` only with a capability token; a 58 /// new state takes it from `set_cpu_dotprod` (kernel boot decode), never 59 /// assumed. `None` runs the scalar f32 path unchanged. Takes over the 60 /// Q8_K rounding of `emulate_q8k` (the quantizer does it). 61 pub dotprod: Option, 62 q8: Q8Act, 63 } 64 65 impl DecodeState { 66 /// Cache for up to `capacity` positions of `model`. 67 pub fn new(model: &Model<'_>, capacity: usize) -> Self { 68 let p = &model.params; 69 let (e, ff) = (p.embedding_length as usize, p.feed_forward_length as usize); 70 let n_layer = p.block_count as usize; 71 let kv = n_layer * capacity * model.kv_dim; 72 Self { 73 capacity, 74 pos: 0, 75 kv_dim: model.kv_dim, 76 k: vec![0.0; kv], 77 v: vec![0.0; kv], 78 x: vec![0.0; e], 79 h: vec![0.0; e], 80 q: vec![0.0; e], 81 kk: vec![0.0; model.kv_dim], 82 vv: vec![0.0; model.kv_dim], 83 att: vec![0.0; e], 84 scores: vec![0.0; capacity], 85 gate: vec![0.0; ff], 86 up: vec![0.0; ff], 87 tmp: vec![0.0; e.max(ff)], 88 scr: vec![0.0; e.max(ff)], 89 rope_cos: vec![0.0; model.head_dim / 2], 90 rope_sin: vec![0.0; model.head_dim / 2], 91 logits: vec![0.0; p.vocab_size as usize], 92 emulate_q8k: false, 93 dotprod: cpu_dotprod(), 94 q8: Q8Act::with_capacity(e.max(ff)), 95 } 96 } 97 98 /// Positions already in the cache. 99 pub fn len(&self) -> usize { 100 self.pos 101 } 102 pub fn is_empty(&self) -> bool { 103 self.pos == 0 104 } 105 pub fn capacity(&self) -> usize { 106 self.capacity 107 } 108 /// Forget the sequence (buffers are kept). 109 pub fn reset(&mut self) { 110 self.pos = 0; 111 } 112 } 113 114 /// `x * w / sqrt(mean(x^2) + eps)` into `out`. 115 pub fn rms_norm(x: &[f32], w: &[f32], eps: f32, out: &mut [f32]) { 116 let ss: f32 = x.iter().map(|v| v * v).sum::() / x.len() as f32; 117 let scale = 1.0 / math::sqrt(ss + eps); 118 for ((o, v), g) in out.iter_mut().zip(x).zip(w) { 119 *o = v * scale * g; 120 } 121 } 122 123 /// In-place softmax with max subtraction. 124 pub fn softmax(x: &mut [f32]) { 125 let max = x.iter().copied().fold(f32::NEG_INFINITY, f32::max); 126 let mut sum = 0.0; 127 for v in x.iter_mut() { 128 *v = math::exp(*v - max); 129 sum += *v; 130 } 131 for v in x.iter_mut() { 132 *v /= sum; 133 } 134 } 135 136 /// Fill cos/sin for one position as ggml's `ggml_rope_cache_init` does: 137 /// `theta` starts at `pos`, is multiplied by `base^(-2/n_rot)` each pair and 138 /// divided by that pair's factor. 139 pub fn rope_cache(pos: usize, base: f32, factors: &[f32], cos: &mut [f32], sin: &mut [f32]) { 140 let n_rot = cos.len() * 2; 141 let theta_scale = math::powf(base, -2.0 / n_rot as f32); 142 let mut theta = pos as f32; 143 for i in 0..cos.len() { 144 let ff = factors.get(i).copied().unwrap_or(1.0); 145 let (s, c) = math::sin_cos(theta / ff); 146 cos[i] = c; 147 sin[i] = s; 148 theta *= theta_scale; 149 } 150 } 151 152 /// Rotate adjacent pairs of every head of `x` in place. 153 pub fn rope_apply(x: &mut [f32], head_dim: usize, cos: &[f32], sin: &[f32]) { 154 for head in x.chunks_exact_mut(head_dim) { 155 for i in 0..head_dim / 2 { 156 let (a, b) = (head[2 * i], head[2 * i + 1]); 157 head[2 * i] = a * cos[i] - b * sin[i]; 158 head[2 * i + 1] = a * sin[i] + b * cos[i]; 159 } 160 } 161 } 162 163 impl DecodeState { 164 /// Run one token through the model at the next position, appending to 165 /// the cache. Logits are computed (into `self.logits`) only when 166 /// `want_logits`, since they cost as much as several layers. 167 pub fn forward( 168 &mut self, 169 m: &Model<'_>, 170 token: u32, 171 want_logits: bool, 172 ) -> Result<(), InferError> { 173 let p = &m.params; 174 if token >= p.vocab_size { 175 return Err(InferError::BadToken(token)); 176 } 177 if self.pos >= self.capacity { 178 return Err(InferError::ContextFull); 179 } 180 let pos = self.pos; 181 let hd = m.head_dim; 182 let n_head = p.head_count as usize; 183 let group = n_head / p.head_count_kv as usize; 184 let eps = p.rms_norm_eps; 185 let scale = 1.0 / math::sqrt(hd as f32); 186 let (dp, emu) = (self.dotprod, self.emulate_q8k); 187 188 m.tok_embd.row_into(token as usize, &mut self.x)?; 189 rope_cache( 190 pos, 191 p.rope_freq_base, 192 &m.rope_factors, 193 &mut self.rope_cos, 194 &mut self.rope_sin, 195 ); 196 197 for (l, layer) in m.layers.iter().enumerate() { 198 rms_norm(&self.x, &layer.attn_norm, eps, &mut self.h); 199 prep(dp, emu, &mut self.q8, &mut self.h)?; 200 mv(dp, &layer.wq, &self.h, &self.q8, &mut self.q, &mut self.scr)?; 201 mv( 202 dp, 203 &layer.wk, 204 &self.h, 205 &self.q8, 206 &mut self.kk, 207 &mut self.scr, 208 )?; 209 mv( 210 dp, 211 &layer.wv, 212 &self.h, 213 &self.q8, 214 &mut self.vv, 215 &mut self.scr, 216 )?; 217 rope_apply(&mut self.q, hd, &self.rope_cos, &self.rope_sin); 218 rope_apply(&mut self.kk, hd, &self.rope_cos, &self.rope_sin); 219 220 let base = l * self.capacity * self.kv_dim; 221 let at = base + pos * self.kv_dim; 222 self.k[at..at + self.kv_dim].copy_from_slice(&self.kk); 223 self.v[at..at + self.kv_dim].copy_from_slice(&self.vv); 224 225 for h in 0..n_head { 226 let kvh = (h / group) * hd; 227 let q = &self.q[h * hd..(h + 1) * hd]; 228 let sc = &mut self.scores[..=pos]; 229 for (t, s) in sc.iter_mut().enumerate() { 230 let kt = &self.k[base + t * self.kv_dim + kvh..][..hd]; 231 *s = q.iter().zip(kt).map(|(a, b)| a * b).sum::() * scale; 232 } 233 softmax(sc); 234 let out = &mut self.att[h * hd..(h + 1) * hd]; 235 out.fill(0.0); 236 for (t, &w) in sc.iter().enumerate() { 237 let vt = &self.v[base + t * self.kv_dim + kvh..][..hd]; 238 for (o, v) in out.iter_mut().zip(vt) { 239 *o += w * v; 240 } 241 } 242 } 243 let e = self.x.len(); 244 prep(dp, emu, &mut self.q8, &mut self.att)?; 245 mv( 246 dp, 247 &layer.wo, 248 &self.att, 249 &self.q8, 250 &mut self.tmp[..e], 251 &mut self.scr, 252 )?; 253 for (x, d) in self.x.iter_mut().zip(&self.tmp[..e]) { 254 *x += d; 255 } 256 257 rms_norm(&self.x, &layer.ffn_norm, eps, &mut self.h); 258 prep(dp, emu, &mut self.q8, &mut self.h)?; 259 mv( 260 dp, 261 &layer.w_gate, 262 &self.h, 263 &self.q8, 264 &mut self.gate, 265 &mut self.scr, 266 )?; 267 mv( 268 dp, 269 &layer.w_up, 270 &self.h, 271 &self.q8, 272 &mut self.up, 273 &mut self.scr, 274 )?; 275 for (g, u) in self.gate.iter_mut().zip(&self.up) { 276 *g = *g / (1.0 + math::exp(-*g)) * u; 277 } 278 prep(dp, emu, &mut self.q8, &mut self.gate)?; 279 mv( 280 dp, 281 &layer.w_down, 282 &self.gate, 283 &self.q8, 284 &mut self.tmp[..e], 285 &mut self.scr, 286 )?; 287 for (x, d) in self.x.iter_mut().zip(&self.tmp[..e]) { 288 *x += d; 289 } 290 } 291 self.pos += 1; 292 if want_logits { 293 rms_norm(&self.x, &m.output_norm, eps, &mut self.h); 294 prep(dp, emu, &mut self.q8, &mut self.h)?; 295 mv( 296 dp, 297 &m.output, 298 &self.h, 299 &self.q8, 300 &mut self.logits, 301 &mut self.scr, 302 )?; 303 } 304 Ok(()) 305 } 306 307 /// Feed `ids` in order (prefill); logits are computed for the last one. 308 pub fn prefill(&mut self, m: &Model<'_>, ids: &[u32]) -> Result<(), InferError> { 309 for (i, &t) in ids.iter().enumerate() { 310 self.forward(m, t, i + 1 == ids.len())?; 311 } 312 Ok(()) 313 } 314 } 315 316 /// Prepare an activation vector for the quantized matvecs that follow: the 317 /// SDOT path quantizes it into `q8`; otherwise the optional Q8_K rounding 318 /// emulation rounds it in place. 319 fn prep(dp: Option, emu: bool, q8: &mut Q8Act, x: &mut [f32]) -> Result<(), InferError> { 320 if dp.is_some() { 321 q8.quantize(x)?; 322 } else if emu { 323 q8k_round(x); 324 } 325 Ok(()) 326 } 327 328 /// One matvec: SDOT on `q8` for K-quant weights when `dp` is set, else the 329 /// scalar f32 path on `x`. 330 fn mv( 331 dp: Option, 332 w: &Weight<'_>, 333 x: &[f32], 334 q8: &Q8Act, 335 out: &mut [f32], 336 scr: &mut [f32], 337 ) -> Result<(), InferError> { 338 match dp { 339 Some(t) if w.is_kquant() => w.matvec_q8(t, q8, out), 340 _ => w.matvec(x, out, scr), 341 } 342 } 343 344 /// Index of the largest logit (first on ties, like llama.cpp's greedy). 345 pub fn argmax(logits: &[f32]) -> u32 { 346 let mut best = 0usize; 347 for (i, &v) in logits.iter().enumerate() { 348 if v > logits[best] { 349 best = i; 350 } 351 } 352 best as u32 353 } 354 355 /// Greedy generation: prefill `prompt`, then up to `max_new` tokens, stopping 356 /// after any id in `stop` (that id is included in the result). 357 pub fn generate_greedy( 358 m: &Model<'_>, 359 st: &mut DecodeState, 360 prompt: &[u32], 361 max_new: usize, 362 stop: &[u32], 363 ) -> Result, InferError> { 364 let mut out = Vec::new(); 365 st.prefill(m, prompt)?; 366 for i in 0..max_new { 367 let t = argmax(&st.logits); 368 out.push(t); 369 if stop.contains(&t) || i + 1 == max_new { 370 break; 371 } 372 st.forward(m, t, true)?; 373 } 374 Ok(out) 375 } 376 377 /// Round activations to ggml's Q8_K grid in place (per 256-block: scale 378 /// `d = max/-127` where `max` is the signed value of largest magnitude, 379 /// `q = round-half-even(x / d)` clamped to 127, value `q * d`). ggml quantizes 380 /// the activations this way before every quantized dot; applying it makes 381 /// results track llama.cpp more closely (see `DecodeState::emulate_q8k`). 382 pub fn q8k_round(x: &mut [f32]) { 383 for blk in x.chunks_exact_mut(256) { 384 let mut amax = 0f32; 385 let mut max = 0f32; 386 for &v in blk.iter() { 387 if v.abs() > amax { 388 amax = v.abs(); 389 max = v; 390 } 391 } 392 if amax == 0.0 { 393 continue; 394 } 395 let iscale = -127.0 / max; 396 let d = 1.0 / iscale; 397 for v in blk.iter_mut() { 398 let t = *v * iscale; 399 // nearest_int: magic-number rounding (ties to even), as ggml. 400 let q = ((t + 12_582_912.0) - 12_582_912.0).min(127.0); 401 *v = q * d; 402 } 403 } 404 } 405 406 #[cfg(test)] 407 mod rope_tests { 408 //! AO-1 (Drake's attention hardening cut): RoPE relative-position qualification through 409 //! this crate's own `rope_cache` + `rope_apply` (ggml adjacent-pair convention), with no 410 //! dependency on any other repo's implementation. 411 use super::*; 412 413 const HD: usize = 8; 414 const BASE: f32 = 10000.0; 415 416 fn absf(x: f32) -> f32 { 417 if x < 0.0 { 418 -x 419 } else { 420 x 421 } 422 } 423 424 fn lcg(seed: &mut u64) -> f32 { 425 *seed = seed 426 .wrapping_mul(`6364136223846793005`) 427 .wrapping_add(`1442695040888963407`); 428 ((*seed >> 33) as f32 / (1u64 << 31) as f32) * 2.0 - 1.0 429 } 430 431 fn rot(x: &[f32; HD], pos: usize) -> [f32; HD] { 432 let (mut c, mut s) = ([0.0f32; HD / 2], [0.0f32; HD / 2]); 433 rope_cache(pos, BASE, &[], &mut c, &mut s); 434 let mut y = *x; 435 rope_apply(&mut y, HD, &c, &s); 436 y 437 } 438 439 fn dot(a: &[f32], b: &[f32]) -> f32 { 440 a.iter().zip(b).map(|(x, y)| x * y).sum() 441 } 442 443 #[test] 444 fn pair_zero_rotates_by_the_position_angle() { 445 // pair 0 has theta = pos exactly (ggml: theta starts at pos), so e_0 -> (cos pos, sin pos) 446 let mut x = [0.0f32; HD]; 447 x[0] = 1.0; 448 let y = rot(&x, 1); 449 let (s, c) = math::sin_cos(1.0); 450 assert!(absf(y[0] - c) < 1e-6 && absf(y[1] - s) < 1e-6, "{y:?}"); 451 assert!(y[2..].iter().all(|v| *v == 0.0), "other pairs untouched"); 452 assert_eq!(rot(&x, 0), x, "position 0 is the identity"); 453 } 454 455 #[test] 456 fn score_depends_on_relative_position_only() { 457 let mut seed = 0x5eed_u64; 458 let mut q = [0.0f32; HD]; 459 let mut k = [0.0f32; HD]; 460 for v in q.iter_mut().chain(k.iter_mut()) { 461 *v = lcg(&mut seed); 462 } 463 let same = dot(&rot(&q, 11), &rot(&k, 11)); 464 assert!(absf(same - dot(&q, &k)) < 1e-5, "same position must cancel"); 465 let a = dot(&rot(&q, 5), &rot(&k, 2)); 466 let b = dot(&rot(&q, 13), &rot(&k, 10)); 467 let c = dot(&rot(&q, 5), &rot(&k, 3)); 468 assert!(absf(a - b) < 1e-4, "offset 3 at two bases: {a} vs {b}"); 469 assert!( 470 absf(a - c) > 1e-3, 471 "offsets 3 and 2 must differ: {a} vs {c}" 472 ); 473 // the rotation is a rotation: norms are preserved 474 assert!(absf(dot(&rot(&q, 97), &rot(&q, 97)) - dot(&q, &q)) < 1e-4); 475 } 476 477 #[test] 478 fn every_head_is_rotated_independently_with_the_same_table() { 479 let mut seed = 7u64; 480 let mut x = [0.0f32; 3 * HD]; 481 for v in x.iter_mut() { 482 *v = lcg(&mut seed); 483 } 484 // head 1 copies head 0, head 2 differs 485 for d in 0..HD { 486 x[HD + d] = x[d]; 487 } 488 let (mut c, mut s) = ([0.0f32; HD / 2], [0.0f32; HD / 2]); 489 rope_cache(9, BASE, &[], &mut c, &mut s); 490 let before = x; 491 rope_apply(&mut x, HD, &c, &s); 492 assert_eq!(x[..HD], x[HD..2 * HD], "equal heads must rotate equally"); 493 assert!(x[..HD] != before[..HD], "position 9 must change the head"); 494 let mut diff = false; 495 for d in 0..HD { 496 diff |= absf(x[2 * HD + d] - x[d]) > 1e-3; 497 } 498 assert!(diff, "a different head must come out different"); 499 } 500 501 #[test] 502 fn softmax_weights_are_shift_invariant_and_position_sensitive() { 503 const T: usize = 5; 504 let mut seed = 99u64; 505 let mut q = [0.0f32; HD]; 506 let mut k0 = [0.0f32; HD]; 507 for v in q.iter_mut().chain(k0.iter_mut()) { 508 *v = lcg(&mut seed) * 3.0; 509 } 510 // K for token t is k0 shifted by t so tokens are distinguishable before rope 511 let weights = |base: usize, q_pos: usize| -> [f32; T] { 512 let mut w = [0.0f32; T]; 513 let rq = rot(&q, base + q_pos); 514 for (t, wt) in w.iter_mut().enumerate() { 515 let mut kt = k0; 516 kt[t % HD] += 1.0; 517 *wt = dot(&rq, &rot(&kt, base + t)) / math::sqrt(HD as f32); 518 } 519 softmax(&mut w); 520 w 521 }; 522 let w0 = weights(0, T - 1); 523 let w23 = weights(23, T - 1); 524 let sum: f32 = w0.iter().sum(); 525 assert!(absf(sum - 1.0) < 1e-5); 526 for t in 0..T { 527 assert!( 528 absf(w0[t] - w23[t]) < 1e-4, 529 "token {t}: {} vs {}", 530 w0[t], 531 w23[t] 532 ); 533 } 534 let w_moved = weights(0, T + 4); 535 let mut changed = false; 536 for t in 0..T { 537 changed |= absf(w0[t] - w_moved[t]) > 1e-3; 538 } 539 assert!(changed, "moving q relative to K must change the weights"); 540 } 541 }