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 / qwen3_moe_omega_kvio.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 | //! Persistent KV export and import for the Omega engine (sc#505). New file. |
| 17 | //! |
| 18 | //! The payload is the persistent KV store's `HostPagedPoolV1` format (ADR 0003 section 2.2): for |
| 19 | //! positions `start..start + len`, `ceil(len / KV_BLOCK_SIZE)` blocks, each exactly |
| 20 | //! [`PoolBlockGeometry::block_stride`] bytes, laid out `[layer][K plane | V plane][token][kv |
| 21 | //! head][dim]` with every element a little-endian bf16 bit pattern. Rows at or past `len` in the |
| 22 | //! last block are zero. This is byte for byte the layout of `aien_kv_cache::UnifiedKvTensorPool` |
| 23 | //! with dtype bf16 and block size [`KV_BLOCK_SIZE`](super::KV_BLOCK_SIZE) (the pool |
| 24 | //! [`super::OmegaPagedKv`] attends over), so the split path copies its blocks as they are. |
| 25 | //! |
| 26 | //! The fused path ([`crate::qwen3_moe_omega_dattn::OmegaFusedKv`], what the live server runs) keeps |
| 27 | //! its K/V differently on the chip: per layer one K plane and one V plane of bf16 rows, row |
| 28 | //! `(kv_head, pos)` at `(kv_head * max_pos + pos) * head_dim * 2` bytes. [`rows_to_blocks`] and |
| 29 | //! [`blocks_to_rows`] move whole bf16 rows between that layout and the payload without touching a |
| 30 | //! value (no rounding, no conversion), so the payload is the same `HostPagedPoolV1` bytes either |
| 31 | //! way. Which attention path computed them is part of the engine identity the namespace binds |
| 32 | //! (aien-serve-http `kv_persist.rs`), so a fused payload is never offered to the split path or |
| 33 | //! the other way round. |
| 34 | //! |
| 35 | //! Both rows of a position are the cached K (after the k norm and RoPE) and V, exactly what the |
| 36 | //! attention reads; positions are absolute, so a restored prefix lines up with the next step. |
| 37 | |
| 38 | use super::{KvGeometry, Qwen3MoeConfig}; |
| 39 | |
| 40 | /// The byte geometry of one `HostPagedPoolV1` block for a model (bf16 elements). |
| 41 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 42 | pub struct PoolBlockGeometry { |
| 43 | pub layers: usize, |
| 44 | pub kv_heads: usize, |
| 45 | pub head_dim: usize, |
| 46 | pub block_size: usize, |
| 47 | } |
| 48 | |
| 49 | /// Bytes of one bf16 element. |
| 50 | pub const ELEMENT_BYTES: usize = 2; |
| 51 | |
| 52 | impl PoolBlockGeometry { |
| 53 | pub fn for_geometry(g: &KvGeometry) -> Self { |
| 54 | Self { |
| 55 | layers: g.layers, |
| 56 | kv_heads: g.kv_heads, |
| 57 | head_dim: g.head_dim, |
| 58 | block_size: g.block_size, |
| 59 | } |
| 60 | } |
| 61 | /// Shim until ADR 0004 step 5: the geometry of a 30B-family config. |
| 62 | pub fn for_config(c: &Qwen3MoeConfig) -> Self { |
| 63 | Self::for_geometry(&KvGeometry::from(c)) |
| 64 | } |
| 65 | pub fn head_stride(&self) -> usize { |
| 66 | self.head_dim * ELEMENT_BYTES |
| 67 | } |
| 68 | pub fn token_stride(&self) -> usize { |
| 69 | self.kv_heads * self.head_stride() |
| 70 | } |
| 71 | pub fn kv_plane_stride(&self) -> usize { |
| 72 | self.block_size * self.token_stride() |
| 73 | } |
| 74 | pub fn layer_stride(&self) -> usize { |
| 75 | 2 * self.kv_plane_stride() |
| 76 | } |
| 77 | pub fn block_stride(&self) -> usize { |
| 78 | self.layers * self.layer_stride() |
| 79 | } |
| 80 | /// Payload bytes for `len` positions. |
| 81 | pub fn payload_len(&self, len: usize) -> usize { |
| 82 | len.div_ceil(self.block_size) * self.block_stride() |
| 83 | } |
| 84 | /// Offset of the row of (`pos` relative to the payload start, `layer`, K or V, `head`). |
| 85 | pub fn row_offset(&self, rel_pos: usize, layer: usize, value: bool, head: usize) -> usize { |
| 86 | (rel_pos / self.block_size) * self.block_stride() |
| 87 | + layer * self.layer_stride() |
| 88 | + usize::from(value) * self.kv_plane_stride() |
| 89 | + (rel_pos % self.block_size) * self.token_stride() |
| 90 | + head * self.head_stride() |
| 91 | } |
| 92 | fn check(&self, start: usize, len: usize) -> Result<(), String> { |
| 93 | if self.layers == 0 || self.kv_heads == 0 || self.head_dim == 0 || self.block_size == 0 { |
| 94 | return Err(format!("kv export geometry {self:?} has a zero dimension")); |
| 95 | } |
| 96 | if len == 0 { |
| 97 | return Err("kv export of zero positions".into()); |
| 98 | } |
| 99 | if !start.is_multiple_of(self.block_size) { |
| 100 | return Err(format!( |
| 101 | "kv export start {start} is not a multiple of the block size {}", |
| 102 | self.block_size |
| 103 | )); |
| 104 | } |
| 105 | Ok(()) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// Builds the payload for positions `start..start + len` from a row reader: |
| 110 | /// `read_row(layer, kv_head, pos, k, v)` fills `head_dim` bf16 bit patterns of K and of V. |
| 111 | pub fn rows_to_blocks( |
| 112 | g: &PoolBlockGeometry, |
| 113 | start: usize, |
| 114 | len: usize, |
| 115 | mut read_row: impl FnMut(usize, usize, usize, &mut [u16], &mut [u16]) -> Result<(), String>, |
| 116 | ) -> Result<Vec<u8>, String> { |
| 117 | g.check(start, len)?; |
| 118 | let mut out = vec![0u8; g.payload_len(len)]; |
| 119 | let (mut k, mut v) = (vec![0u16; g.head_dim], vec![0u16; g.head_dim]); |
| 120 | for layer in 0..g.layers { |
| 121 | for head in 0..g.kv_heads { |
| 122 | for rel in 0..len { |
| 123 | read_row(layer, head, start + rel, &mut k, &mut v)?; |
| 124 | put_row(&mut out, g.row_offset(rel, layer, false, head), &k); |
| 125 | put_row(&mut out, g.row_offset(rel, layer, true, head), &v); |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | Ok(out) |
| 130 | } |
| 131 | |
| 132 | /// Splits a payload of `len` positions into contiguous per-(layer, kv head) rows and hands them |
| 133 | /// to `write_rows(layer, kv_head, k_rows, v_rows)` (`len * head_dim` bf16 bit patterns each, |
| 134 | /// position order). Refuses a payload of the wrong size, or with a non-zero byte in the padding |
| 135 | /// rows of its last block, before writing anything. |
| 136 | pub fn blocks_to_rows( |
| 137 | g: &PoolBlockGeometry, |
| 138 | start: usize, |
| 139 | len: usize, |
| 140 | bytes: &[u8], |
| 141 | mut write_rows: impl FnMut(usize, usize, &[u16], &[u16]) -> Result<(), String>, |
| 142 | ) -> Result<(), String> { |
| 143 | g.check(start, len)?; |
| 144 | check_payload(g, len, bytes)?; |
| 145 | let (mut k, mut v) = (vec![0u16; len * g.head_dim], vec![0u16; len * g.head_dim]); |
| 146 | for layer in 0..g.layers { |
| 147 | for head in 0..g.kv_heads { |
| 148 | for rel in 0..len { |
| 149 | let row = rel * g.head_dim..(rel + 1) * g.head_dim; |
| 150 | get_row( |
| 151 | bytes, |
| 152 | g.row_offset(rel, layer, false, head), |
| 153 | &mut k[row.clone()], |
| 154 | ); |
| 155 | get_row(bytes, g.row_offset(rel, layer, true, head), &mut v[row]); |
| 156 | } |
| 157 | write_rows(layer, head, &k, &v)?; |
| 158 | } |
| 159 | } |
| 160 | Ok(()) |
| 161 | } |
| 162 | |
| 163 | /// The payload must be exactly `payload_len(len)` bytes, and every row past `len` in the last |
| 164 | /// block must be zero (ADR 0003 section 2.2: the writer zeroes them, so anything else is damage). |
| 165 | pub fn check_payload(g: &PoolBlockGeometry, len: usize, bytes: &[u8]) -> Result<(), String> { |
| 166 | if bytes.len() != g.payload_len(len) { |
| 167 | return Err(format!( |
| 168 | "kv payload of {} bytes, {len} positions need {}", |
| 169 | bytes.len(), |
| 170 | g.payload_len(len) |
| 171 | )); |
| 172 | } |
| 173 | let tail = len % g.block_size; |
| 174 | if tail != 0 { |
| 175 | let last = len - tail; |
| 176 | for layer in 0..g.layers { |
| 177 | for value in [false, true] { |
| 178 | let from = g.row_offset(last + tail, layer, value, 0); |
| 179 | let to = g.row_offset(last, layer, value, 0) + g.kv_plane_stride(); |
| 180 | if bytes[from..to].iter().any(|&b| b != 0) { |
| 181 | return Err(format!("kv payload: padding rows past position {len} of layer {layer} are not zero")); |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | Ok(()) |
| 187 | } |
| 188 | |
| 189 | /// Zeroes the rows at or past `len` in the last block of a payload (in place). |
| 190 | pub fn zero_padding(g: &PoolBlockGeometry, len: usize, bytes: &mut [u8]) { |
| 191 | let tail = len % g.block_size; |
| 192 | if tail == 0 { |
| 193 | return; |
| 194 | } |
| 195 | let last = len - tail; |
| 196 | for layer in 0..g.layers { |
| 197 | for value in [false, true] { |
| 198 | let from = g.row_offset(last + tail, layer, value, 0); |
| 199 | let to = g.row_offset(last, layer, value, 0) + g.kv_plane_stride(); |
| 200 | bytes[from..to].fill(0); |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | fn put_row(out: &mut [u8], at: usize, row: &[u16]) { |
| 206 | for (i, w) in row.iter().enumerate() { |
| 207 | out[at + 2 * i..at + 2 * i + 2].copy_from_slice(&w.to_le_bytes()); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | fn get_row(bytes: &[u8], at: usize, row: &mut [u16]) { |
| 212 | for (i, w) in row.iter_mut().enumerate() { |
| 213 | *w = u16::from_le_bytes([bytes[at + 2 * i], bytes[at + 2 * i + 1]]); |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | #[cfg(test)] |
| 218 | mod tests { |
| 219 | use super::*; |
| 220 | |
| 221 | fn geom() -> PoolBlockGeometry { |
| 222 | PoolBlockGeometry { |
| 223 | layers: 3, |
| 224 | kv_heads: 2, |
| 225 | head_dim: 4, |
| 226 | block_size: 16, |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /// A fake fused cache: rows keyed by (layer, head, pos, value). |
| 231 | fn row_word(layer: usize, head: usize, pos: usize, value: bool, i: usize) -> u16 { |
| 232 | (((layer * 7 + head * 3 + pos * 11 + usize::from(value) * 5 + i) % 65_521) as u16) | 1 |
| 233 | } |
| 234 | |
| 235 | #[test] |
| 236 | fn geometry_equals_the_kv_cache_pool_layout() { |
| 237 | // The payload must be the aien_kv_cache pool layout (HostPagedPoolV1), not a look-alike. |
| 238 | let g = geom(); |
| 239 | let cfg = aien_kv_cache::KvPoolConfig::for_model( |
| 240 | 4, |
| 241 | g.block_size, |
| 242 | g.layers, |
| 243 | g.kv_heads, |
| 244 | g.head_dim, |
| 245 | aien_kv_cache::KvDType::Bf16, |
| 246 | ); |
| 247 | let d = aien_kv_cache::UnifiedKvTensorPool::allocate(cfg) |
| 248 | .unwrap() |
| 249 | .layout_desc(); |
| 250 | assert_eq!(d.block_stride_bytes as usize, g.block_stride()); |
| 251 | assert_eq!(d.layer_stride_bytes as usize, g.layer_stride()); |
| 252 | assert_eq!(d.kv_plane_stride_bytes as usize, g.kv_plane_stride()); |
| 253 | assert_eq!(d.token_stride_bytes as usize, g.token_stride()); |
| 254 | assert_eq!(d.head_stride_bytes as usize, g.head_stride()); |
| 255 | } |
| 256 | |
| 257 | #[test] |
| 258 | fn fused_rows_round_trip_through_the_payload_byte_for_byte() { |
| 259 | let g = geom(); |
| 260 | for (start, len) in [(0usize, 1usize), (0, 16), (0, 37), (32, 5), (48, 48)] { |
| 261 | let bytes = rows_to_blocks(&g, start, len, |l, h, p, k, v| { |
| 262 | for i in 0..g.head_dim { |
| 263 | k[i] = row_word(l, h, p, false, i); |
| 264 | v[i] = row_word(l, h, p, true, i); |
| 265 | } |
| 266 | Ok(()) |
| 267 | }) |
| 268 | .unwrap(); |
| 269 | assert_eq!(bytes.len(), g.payload_len(len)); |
| 270 | check_payload(&g, len, &bytes).unwrap(); |
| 271 | let mut seen = 0usize; |
| 272 | blocks_to_rows(&g, start, len, &bytes, |l, h, k, v| { |
| 273 | for rel in 0..len { |
| 274 | for i in 0..g.head_dim { |
| 275 | assert_eq!( |
| 276 | k[rel * g.head_dim + i], |
| 277 | row_word(l, h, start + rel, false, i) |
| 278 | ); |
| 279 | assert_eq!( |
| 280 | v[rel * g.head_dim + i], |
| 281 | row_word(l, h, start + rel, true, i) |
| 282 | ); |
| 283 | } |
| 284 | } |
| 285 | seen += 1; |
| 286 | Ok(()) |
| 287 | }) |
| 288 | .unwrap(); |
| 289 | assert_eq!(seen, g.layers * g.kv_heads); |
| 290 | // Export again from what was imported: identical bytes. |
| 291 | let again = rows_to_blocks(&g, start, len, |l, h, p, k, v| { |
| 292 | let rel = p - start; |
| 293 | get_row(&bytes, g.row_offset(rel, l, false, h), k); |
| 294 | get_row(&bytes, g.row_offset(rel, l, true, h), v); |
| 295 | Ok(()) |
| 296 | }) |
| 297 | .unwrap(); |
| 298 | assert_eq!(again, bytes); |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn damaged_payloads_are_refused_before_any_write() { |
| 304 | let g = geom(); |
| 305 | let mut bytes = rows_to_blocks(&g, 0, 20, |_, _, _, k, v| { |
| 306 | k.fill(0x3f80); |
| 307 | v.fill(0x4000); |
| 308 | Ok(()) |
| 309 | }) |
| 310 | .unwrap(); |
| 311 | let mut writes = 0; |
| 312 | // Wrong size. |
| 313 | assert!( |
| 314 | blocks_to_rows(&g, 0, 20, &bytes[..bytes.len() - 1], |_, _, _, _| { |
| 315 | writes += 1; |
| 316 | Ok(()) |
| 317 | }) |
| 318 | .is_err() |
| 319 | ); |
| 320 | // A non-zero padding byte (position 20 of layer 1, V plane). |
| 321 | let at = g.row_offset(20, 1, true, 1) + 3; |
| 322 | bytes[at] = 9; |
| 323 | assert!(blocks_to_rows(&g, 0, 20, &bytes, |_, _, _, _| { |
| 324 | writes += 1; |
| 325 | Ok(()) |
| 326 | }) |
| 327 | .is_err()); |
| 328 | assert_eq!(writes, 0); |
| 329 | zero_padding(&g, 20, &mut bytes); |
| 330 | assert!(check_payload(&g, 20, &bytes).is_ok()); |
| 331 | // Unaligned start and zero length are refused. |
| 332 | assert!(rows_to_blocks(&g, 3, 4, |_, _, _, _, _| Ok(())).is_err()); |
| 333 | assert!(rows_to_blocks(&g, 0, 0, |_, _, _, _, _| Ok(())).is_err()); |
| 334 | } |
| 335 | } |