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
aien-sovereign-core-mv / crates / aien-inference-abi / src / generation / echo_chain.rs
| 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 | //! The host fake forward pass `EchoChainModel` (ADR 0004 section 4), behind `host-test-engine`. |
| 17 | //! |
| 18 | //! No weights, vocabulary 64, the tiny KV geometry (2 layers, 1 KV head of 128), on a real |
| 19 | //! [`HostPoolKv`], so export, restore and park move real `HostPagedPoolV1` bytes. For token `t` at |
| 20 | //! position `p` and layer `l` it appends K and V rows of small integers (exact in bf16), then |
| 21 | //! attends with a fixed query over `0..=p` at every layer and folds every layer's attention |
| 22 | //! output into one hash `h` together with `p`; `logits[i] = ((h + 37 i) % 64) / 64`, a |
| 23 | //! permutation, so the argmax is unique. It keeps no history of its own: every logit depends on |
| 24 | //! every stored row in every layer, so a stale, missing or wrong row changes the tokens. |
| 25 | |
| 26 | use std::sync::{Arc, Mutex}; |
| 27 | |
| 28 | use super::{gather_rows, ForwardPass, KvIdentityInputs, Next, Want}; |
| 29 | use crate::qwen3_moe::{bf16_to_f32, f32_to_bf16}; |
| 30 | use crate::qwen3_moe_omega::{ |
| 31 | HostPoolKv, KvAttention, KvGeometry, KvStore, StepTiming, KV_BLOCK_SIZE, |
| 32 | }; |
| 33 | use crate::tensor::sample_argmax; |
| 34 | |
| 35 | /// The fake's vocabulary. |
| 36 | pub const ECHO_VOCAB: usize = 64; |
| 37 | const LAYERS: usize = 2; |
| 38 | const HEAD_DIM: usize = 128; |
| 39 | |
| 40 | /// The fake's KV geometry: 2 layers, 1 query head, 1 KV head of 128. |
| 41 | pub fn echo_geometry() -> KvGeometry { |
| 42 | KvGeometry { |
| 43 | layers: LAYERS, |
| 44 | q_heads: 1, |
| 45 | kv_heads: 1, |
| 46 | head_dim: HEAD_DIM, |
| 47 | rope_theta: 1_000_000.0, |
| 48 | block_size: KV_BLOCK_SIZE, |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// One entry of the fake's call log. |
| 53 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 54 | pub enum Call { |
| 55 | Prefill { |
| 56 | pos: usize, |
| 57 | len: usize, |
| 58 | }, |
| 59 | Decode { |
| 60 | pos: usize, |
| 61 | tokens: Vec<u32>, |
| 62 | }, |
| 63 | /// Pushed by a test's `on_token` through [`EchoChainModel::log_handle`], to check ordering. |
| 64 | Emitted(u32), |
| 65 | } |
| 66 | |
| 67 | /// The fake's cache: a [`KvAttention`] whose every layer can be inspected. |
| 68 | pub trait EchoKv: KvAttention { |
| 69 | /// Positions held in `layer` alone. |
| 70 | fn layer_len(&self, layer: usize) -> usize; |
| 71 | /// `Some(reason)` when this cache deliberately damages K/V (a negative control). |
| 72 | fn mutant(&self) -> Option<&'static str> { |
| 73 | None |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | impl EchoKv for HostPoolKv { |
| 78 | fn layer_len(&self, layer: usize) -> usize { |
| 79 | HostPoolKv::layer_len(self, layer) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// Negative control 1 (ADR 0004 section 4): a [`HostPoolKv`] that, on the first truncate that |
| 84 | /// keeps position `pos` (a rewind), overwrites the V row of (`pos`, `layer`) with different |
| 85 | /// bytes. A warm run that reuses that row must then differ from a cold run. |
| 86 | pub struct CorruptRowKv { |
| 87 | inner: HostPoolKv, |
| 88 | pos: usize, |
| 89 | layer: usize, |
| 90 | fired: bool, |
| 91 | } |
| 92 | |
| 93 | impl CorruptRowKv { |
| 94 | pub fn new(max_context: usize, pos: usize, layer: usize) -> Result<Self, String> { |
| 95 | Ok(Self { |
| 96 | inner: HostPoolKv::new(&echo_geometry(), max_context)?, |
| 97 | pos, |
| 98 | layer, |
| 99 | fired: false, |
| 100 | }) |
| 101 | } |
| 102 | |
| 103 | /// Whether the row has been overwritten. |
| 104 | pub fn fired(&self) -> bool { |
| 105 | self.fired |
| 106 | } |
| 107 | |
| 108 | /// Rewrites positions `0..len` through export and import with one V row changed (every |
| 109 | /// element plus 7, exact in bf16). `append` refuses out-of-order writes, so the payload is |
| 110 | /// the only door to a surviving row. |
| 111 | fn corrupt(&mut self, len: usize) { |
| 112 | let mut bytes = match self.inner.export_blocks(0, len) { |
| 113 | Some(Ok(b)) => b, |
| 114 | other => panic!("corrupt row: export of {len} positions failed: {other:?}"), |
| 115 | }; |
| 116 | let g = self.inner.geometry().pool_block(); |
| 117 | let off = g.row_offset(self.pos, self.layer, true, 0); |
| 118 | for e in bytes[off..off + g.token_stride()].chunks_exact_mut(2) { |
| 119 | let v = bf16_to_f32(u16::from_le_bytes([e[0], e[1]])) + 7.0; |
| 120 | e.copy_from_slice(&f32_to_bf16(v).to_le_bytes()); |
| 121 | } |
| 122 | self.inner.truncate(0); |
| 123 | match self.inner.import_blocks(0, len, &bytes) { |
| 124 | Some(Ok(())) => {} |
| 125 | other => panic!("corrupt row: import of {len} positions failed: {other:?}"), |
| 126 | } |
| 127 | self.fired = true; |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | impl KvStore for CorruptRowKv { |
| 132 | fn geometry(&self) -> KvGeometry { |
| 133 | self.inner.geometry() |
| 134 | } |
| 135 | fn capacity(&self) -> usize { |
| 136 | self.inner.capacity() |
| 137 | } |
| 138 | fn len(&self) -> usize { |
| 139 | self.inner.len() |
| 140 | } |
| 141 | fn path_name(&self) -> &'static str { |
| 142 | self.inner.path_name() |
| 143 | } |
| 144 | fn truncate(&mut self, len: usize) { |
| 145 | self.inner.truncate(len); |
| 146 | if !self.fired && self.pos < len && self.inner.len() == len { |
| 147 | self.corrupt(len); |
| 148 | } |
| 149 | } |
| 150 | fn export_blocks(&mut self, start: usize, len: usize) -> Option<Result<Vec<u8>, String>> { |
| 151 | self.inner.export_blocks(start, len) |
| 152 | } |
| 153 | fn import_blocks( |
| 154 | &mut self, |
| 155 | start: usize, |
| 156 | len: usize, |
| 157 | bytes: &[u8], |
| 158 | ) -> Option<Result<(), String>> { |
| 159 | self.inner.import_blocks(start, len, bytes) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | impl KvAttention for CorruptRowKv { |
| 164 | fn append(&mut self, layer: usize, pos: usize, k: &[f32], v: &[f32]) -> Result<(), String> { |
| 165 | self.inner.append(layer, pos, k, v) |
| 166 | } |
| 167 | fn attend( |
| 168 | &mut self, |
| 169 | layer: usize, |
| 170 | q: &[f32], |
| 171 | context_len: usize, |
| 172 | out: &mut [f32], |
| 173 | ) -> Result<u64, String> { |
| 174 | self.inner.attend(layer, q, context_len, out) |
| 175 | } |
| 176 | fn resident(&self) -> bool { |
| 177 | false |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | impl EchoKv for CorruptRowKv { |
| 182 | fn layer_len(&self, layer: usize) -> usize { |
| 183 | self.inner.layer_len(layer) |
| 184 | } |
| 185 | fn mutant(&self) -> Option<&'static str> { |
| 186 | Some("the corrupt-row negative control damages a stored K/V row") |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// The cache as the fake lends it through `kv()`. Lending forgets nothing: pending heads stay |
| 191 | /// pending until `clear_pending`, `prefill` or `decode` replaces them (like the 30B's held graph |
| 192 | /// token), so a test sees every `clear_pending` the controller makes. A head is still refused |
| 193 | /// after the cache changed under it (I2): a truncate that drops a row or an import moves `epoch`. |
| 194 | struct Lent { |
| 195 | inner: Box<dyn EchoKv>, |
| 196 | epoch: u64, |
| 197 | } |
| 198 | |
| 199 | impl KvStore for Lent { |
| 200 | fn geometry(&self) -> KvGeometry { |
| 201 | self.inner.geometry() |
| 202 | } |
| 203 | fn capacity(&self) -> usize { |
| 204 | self.inner.capacity() |
| 205 | } |
| 206 | fn len(&self) -> usize { |
| 207 | self.inner.len() |
| 208 | } |
| 209 | fn path_name(&self) -> &'static str { |
| 210 | self.inner.path_name() |
| 211 | } |
| 212 | fn truncate(&mut self, len: usize) { |
| 213 | if (0..LAYERS).any(|l| self.inner.layer_len(l) > len) { |
| 214 | self.epoch += 1; |
| 215 | } |
| 216 | self.inner.truncate(len); |
| 217 | } |
| 218 | fn export_blocks(&mut self, start: usize, len: usize) -> Option<Result<Vec<u8>, String>> { |
| 219 | self.inner.export_blocks(start, len) |
| 220 | } |
| 221 | fn import_blocks( |
| 222 | &mut self, |
| 223 | start: usize, |
| 224 | len: usize, |
| 225 | bytes: &[u8], |
| 226 | ) -> Option<Result<(), String>> { |
| 227 | self.epoch += 1; |
| 228 | self.inner.import_blocks(start, len, bytes) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// One pending output. |
| 233 | struct Head { |
| 234 | h: u64, |
| 235 | /// The cache epoch it was made in: a truncate that drops a row, or an import, makes it stale. |
| 236 | epoch: u64, |
| 237 | /// Graph mode: the argmax taken at `decode` and held, like the 30B's one-list graph. |
| 238 | chip_token: Option<u32>, |
| 239 | } |
| 240 | |
| 241 | /// The host fake forward pass. Switches and instruments are public fields. |
| 242 | pub struct EchoChainModel { |
| 243 | kv: Lent, |
| 244 | heads: Vec<Option<Head>>, |
| 245 | logits: Vec<f32>, |
| 246 | log: Arc<Mutex<Vec<Call>>>, |
| 247 | /// Full-logits read-backs of a graph head (the 30B's `dgraph_take_logits`). |
| 248 | pub chip_reads: usize, |
| 249 | /// Host output heads (the 30B's `logits()`): every prefill head, every decode head off the graph. |
| 250 | pub lm_heads: usize, |
| 251 | /// `next_rows` calls. |
| 252 | pub rows_reads: usize, |
| 253 | /// Decode heads hold the argmax, taken eagerly, and answer `Want::Greedy` with no read. |
| 254 | pub graph_mode: bool, |
| 255 | /// Writing this position fails after layer 0 (a deliberate half-write). |
| 256 | pub fail_at: Option<usize>, |
| 257 | /// Added to every K/V element: an identity entry. |
| 258 | pub salt: u32, |
| 259 | /// What `max_decode_batch()` reports. |
| 260 | pub max_decode_batch: usize, |
| 261 | } |
| 262 | |
| 263 | impl EchoChainModel { |
| 264 | /// The fake on a [`HostPoolKv`] of `max_context` tokens (rounded up to whole blocks). |
| 265 | pub fn new(max_context: usize) -> Self { |
| 266 | let kv = HostPoolKv::new(&echo_geometry(), max_context).expect("echo-chain host pool"); |
| 267 | Self::with_kv(Box::new(kv)) |
| 268 | } |
| 269 | |
| 270 | /// The fake on any inspectable cache built for [`echo_geometry`] (a negative control). |
| 271 | pub fn with_kv(kv: Box<dyn EchoKv>) -> Self { |
| 272 | Self { |
| 273 | kv: Lent { |
| 274 | inner: kv, |
| 275 | epoch: 0, |
| 276 | }, |
| 277 | heads: Vec::new(), |
| 278 | logits: vec![0.0; ECHO_VOCAB], |
| 279 | log: Arc::new(Mutex::new(Vec::new())), |
| 280 | chip_reads: 0, |
| 281 | lm_heads: 0, |
| 282 | rows_reads: 0, |
| 283 | graph_mode: false, |
| 284 | fail_at: None, |
| 285 | salt: 0, |
| 286 | max_decode_batch: 1, |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | /// The call log so far. |
| 291 | pub fn calls(&self) -> Vec<Call> { |
| 292 | self.log.lock().expect("echo-chain log").clone() |
| 293 | } |
| 294 | |
| 295 | /// The shared call log, for a test's `on_token` to push [`Call::Emitted`] into. |
| 296 | pub fn log_handle(&self) -> Arc<Mutex<Vec<Call>>> { |
| 297 | Arc::clone(&self.log) |
| 298 | } |
| 299 | |
| 300 | /// Positions held by each layer. |
| 301 | pub fn layer_lens(&self) -> Vec<usize> { |
| 302 | (0..LAYERS).map(|l| self.kv.inner.layer_len(l)).collect() |
| 303 | } |
| 304 | |
| 305 | /// The cache's mutant reason, if any. |
| 306 | pub fn kv_mutant(&self) -> Option<&'static str> { |
| 307 | self.kv.inner.mutant() |
| 308 | } |
| 309 | |
| 310 | /// The `d`th element of the K (`s` 0) or V (`s` 1) row of token `t` at (`p`, `l`). |
| 311 | fn element(&self, t: u32, p: usize, l: usize, d: usize, s: usize) -> f32 { |
| 312 | let n = t as usize * 131 + p * 17 + l * 7 + d + 3 * s + self.salt as usize; |
| 313 | (n % 61) as f32 - 30.0 |
| 314 | } |
| 315 | |
| 316 | /// Writes `tokens` from `pos` in every layer; the hash of each position's attention outputs. |
| 317 | fn run(&mut self, pos: usize, tokens: &[u32]) -> Result<Vec<u64>, String> { |
| 318 | self.heads.clear(); |
| 319 | if tokens.is_empty() { |
| 320 | return Err("echo-chain: no tokens".into()); |
| 321 | } |
| 322 | if let Some(t) = tokens.iter().find(|&&t| t as usize >= ECHO_VOCAB) { |
| 323 | return Err(format!("echo-chain: token {t} outside the vocabulary")); |
| 324 | } |
| 325 | // I1: the ledger's position must be what every layer holds. |
| 326 | if self.kv.inner.len() != pos { |
| 327 | return Err(format!( |
| 328 | "echo-chain: asked to write at {pos}, the cache holds {}", |
| 329 | self.kv.inner.len() |
| 330 | )); |
| 331 | } |
| 332 | let query: Vec<f32> = (0..HEAD_DIM) |
| 333 | .map(|d| ((d * 5) % 7) as f32 / 1024.0 - 3.0 / 1024.0) |
| 334 | .collect(); |
| 335 | let mut out = vec![0.0f32; HEAD_DIM]; |
| 336 | let mut hashes = Vec::with_capacity(tokens.len()); |
| 337 | for (i, &t) in tokens.iter().enumerate() { |
| 338 | let p = pos + i; |
| 339 | let mut h = mix(0xcbf2_9ce4_8422_2325, p as u64); |
| 340 | for l in 0..LAYERS { |
| 341 | if l > 0 && self.fail_at == Some(p) { |
| 342 | return Err(format!( |
| 343 | "echo-chain: injected failure at position {p} after layer 0" |
| 344 | )); |
| 345 | } |
| 346 | let k: Vec<f32> = (0..HEAD_DIM).map(|d| self.element(t, p, l, d, 0)).collect(); |
| 347 | let v: Vec<f32> = (0..HEAD_DIM).map(|d| self.element(t, p, l, d, 1)).collect(); |
| 348 | self.kv.inner.append(l, p, &k, &v)?; |
| 349 | self.kv.inner.attend(l, &query, p + 1, &mut out)?; |
| 350 | for x in &out { |
| 351 | h = mix(h, u64::from(x.to_bits())); |
| 352 | } |
| 353 | } |
| 354 | hashes.push(h); |
| 355 | } |
| 356 | Ok(hashes) |
| 357 | } |
| 358 | |
| 359 | fn fill_logits(&mut self, h: u64) { |
| 360 | for (i, l) in self.logits.iter_mut().enumerate() { |
| 361 | *l = (h.wrapping_add(37 * i as u64) % ECHO_VOCAB as u64) as f32 / ECHO_VOCAB as f32; |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | fn push(&self, call: Call) { |
| 366 | self.log.lock().expect("echo-chain log").push(call); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | /// FNV-1a step over one 64-bit word. |
| 371 | fn mix(h: u64, x: u64) -> u64 { |
| 372 | (h ^ x).wrapping_mul(0x0000_0100_0000_01b3) |
| 373 | } |
| 374 | |
| 375 | impl ForwardPass for EchoChainModel { |
| 376 | fn kind(&self) -> &'static str { |
| 377 | "echo-chain" |
| 378 | } |
| 379 | fn vocab(&self) -> usize { |
| 380 | ECHO_VOCAB |
| 381 | } |
| 382 | fn kv(&mut self) -> &mut dyn KvStore { |
| 383 | &mut self.kv |
| 384 | } |
| 385 | fn max_decode_batch(&self) -> usize { |
| 386 | self.max_decode_batch |
| 387 | } |
| 388 | fn prefill( |
| 389 | &mut self, |
| 390 | pos: usize, |
| 391 | tokens: &[u32], |
| 392 | timing: &mut StepTiming, |
| 393 | ) -> Result<(), String> { |
| 394 | self.push(Call::Prefill { |
| 395 | pos, |
| 396 | len: tokens.len(), |
| 397 | }); |
| 398 | let hashes = self.run(pos, tokens)?; |
| 399 | timing.launches += tokens.len() as u64; |
| 400 | let h = *hashes.last().expect("non-empty prefill"); |
| 401 | self.heads = vec![Some(Head { |
| 402 | h, |
| 403 | epoch: self.kv.epoch, |
| 404 | chip_token: None, |
| 405 | })]; |
| 406 | Ok(()) |
| 407 | } |
| 408 | fn decode( |
| 409 | &mut self, |
| 410 | pos: usize, |
| 411 | tokens: &[u32], |
| 412 | timing: &mut StepTiming, |
| 413 | ) -> Result<(), String> { |
| 414 | self.push(Call::Decode { |
| 415 | pos, |
| 416 | tokens: tokens.to_vec(), |
| 417 | }); |
| 418 | if tokens.len() > self.max_decode_batch { |
| 419 | return Err(format!( |
| 420 | "echo-chain: decode of {} tokens, batch is {}", |
| 421 | tokens.len(), |
| 422 | self.max_decode_batch |
| 423 | )); |
| 424 | } |
| 425 | let hashes = self.run(pos, tokens)?; |
| 426 | timing.launches += tokens.len() as u64; |
| 427 | if self.graph_mode { |
| 428 | timing.graph_tokens += tokens.len() as u64; |
| 429 | timing.graph_submits += 1; |
| 430 | } |
| 431 | let mut heads = Vec::with_capacity(hashes.len()); |
| 432 | for h in hashes { |
| 433 | let chip_token = if self.graph_mode { |
| 434 | self.fill_logits(h); |
| 435 | Some(sample_argmax(&self.logits).0) |
| 436 | } else { |
| 437 | None |
| 438 | }; |
| 439 | heads.push(Some(Head { |
| 440 | h, |
| 441 | epoch: self.kv.epoch, |
| 442 | chip_token, |
| 443 | })); |
| 444 | } |
| 445 | self.heads = heads; |
| 446 | Ok(()) |
| 447 | } |
| 448 | fn next( |
| 449 | &mut self, |
| 450 | head: usize, |
| 451 | want: Want, |
| 452 | timing: &mut StepTiming, |
| 453 | ) -> Result<Next<'_>, String> { |
| 454 | let hd = self |
| 455 | .heads |
| 456 | .get_mut(head) |
| 457 | .and_then(Option::take) |
| 458 | .ok_or_else(|| format!("echo-chain: head {head} is not pending"))?; |
| 459 | if hd.epoch != self.kv.epoch { |
| 460 | return Err(format!( |
| 461 | "echo-chain: head {head} is stale: the cache changed under it" |
| 462 | )); |
| 463 | } |
| 464 | match (hd.chip_token, want) { |
| 465 | (Some(t), Want::Greedy) => return Ok(Next::Token(t)), |
| 466 | (Some(_), Want::Logits) => self.chip_reads += 1, |
| 467 | (None, _) => { |
| 468 | self.lm_heads += 1; |
| 469 | timing.launches += 1; |
| 470 | } |
| 471 | } |
| 472 | self.fill_logits(hd.h); |
| 473 | Ok(Next::Logits(&self.logits)) |
| 474 | } |
| 475 | fn next_rows( |
| 476 | &mut self, |
| 477 | head: usize, |
| 478 | rows: &[u32], |
| 479 | out: &mut [f32], |
| 480 | timing: &mut StepTiming, |
| 481 | ) -> Result<(), String> { |
| 482 | self.rows_reads += 1; |
| 483 | gather_rows(self, head, rows, out, timing) |
| 484 | } |
| 485 | fn clear_pending(&mut self) { |
| 486 | self.heads.clear(); |
| 487 | } |
| 488 | fn kv_identity(&self) -> Result<KvIdentityInputs, String> { |
| 489 | if let Some(why) = self.kv.inner.mutant() { |
| 490 | return Err(why.into()); |
| 491 | } |
| 492 | // The fake's K/V bytes depend on the cache path and the salt only (graph_mode, the |
| 493 | // instruments and the decode batch change no byte). |
| 494 | Ok(KvIdentityInputs { |
| 495 | kind: self.kind(), |
| 496 | entries: vec![ |
| 497 | ("attention_path", self.kv.inner.path_name().to_string()), |
| 498 | ("salt", self.salt.to_string()), |
| 499 | ], |
| 500 | }) |
| 501 | } |
| 502 | } |