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 / tests / kv_seam_backend_test.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 | //! C6a (sc#484, ADR 0003 sections 6.2 and 6.3): the backend side of the |
| 17 | //! persistent-KV seam. |
| 18 | //! |
| 19 | //! - `computed_prefix` names only the tokens whose K/V is written in the pool |
| 20 | //! (review finding 3): never the last token after a decode step, never the |
| 21 | //! token prefill sampled but did not run. |
| 22 | //! - `restore_sequence` gives a sequence backend state for a prefix whose K/V a |
| 23 | //! restore already put in its block table, with the same refusals as |
| 24 | //! `fork_sequence`, so the next prefill chunk lines up at the restored |
| 25 | //! position. |
| 26 | //! |
| 27 | //! Reference CPU backend with synthetic reference weights and a small paged |
| 28 | //! pool: no checkpoint, no GPU, runs in seconds. |
| 29 | |
| 30 | use aien_inference_abi::{ |
| 31 | AienInferenceBackend, DecodeOutput, ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, |
| 32 | SamplingParams, ScheduledBatch, SequenceRequest, TransformerWeights, |
| 33 | }; |
| 34 | use aien_kv_cache::{ |
| 35 | create_shared_kv_manager, create_shared_kv_manager_with_pool, holder_id, KvDType, KvPoolConfig, |
| 36 | SharedKvManager, SuffixPolicy, |
| 37 | }; |
| 38 | use std::collections::HashMap; |
| 39 | use std::sync::Arc; |
| 40 | |
| 41 | const BLOCK: usize = 16; |
| 42 | const POOL_BLOCKS: usize = 64; |
| 43 | |
| 44 | fn config() -> ModelConfig { |
| 45 | ModelConfig { |
| 46 | num_layers: 2, |
| 47 | num_heads: 4, |
| 48 | num_kv_heads: 2, |
| 49 | head_dim: 16, |
| 50 | hidden_dim: 64, |
| 51 | intermediate_dim: 128, |
| 52 | vocab_size: 256, |
| 53 | block_size: BLOCK, |
| 54 | ..Default::default() |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fn weights() -> TransformerWeights { |
| 59 | TransformerWeights::reference_test_weights(&config()) |
| 60 | } |
| 61 | |
| 62 | fn shared_pool() -> SharedKvManager { |
| 63 | let c = config(); |
| 64 | let pool = KvPoolConfig::for_model( |
| 65 | POOL_BLOCKS, |
| 66 | BLOCK, |
| 67 | c.num_layers, |
| 68 | c.num_kv_heads, |
| 69 | c.head_dim, |
| 70 | KvDType::Fp32, |
| 71 | ); |
| 72 | create_shared_kv_manager_with_pool(POOL_BLOCKS, BLOCK, pool).expect("pool") |
| 73 | } |
| 74 | |
| 75 | fn backend_on(kv: &SharedKvManager) -> NativeTransformerBackend { |
| 76 | NativeTransformerBackend::with_shared_kv_and_backend( |
| 77 | weights(), |
| 78 | Arc::new(ReferenceCpuBackend::new()), |
| 79 | kv.clone(), |
| 80 | ) |
| 81 | } |
| 82 | |
| 83 | /// Deterministic prompt avoiding token ids 0..=2. |
| 84 | fn prompt(n: usize) -> Vec<u32> { |
| 85 | (0..n).map(|i| ((i * 37 + 11) % 253 + 3) as u32).collect() |
| 86 | } |
| 87 | |
| 88 | fn greedy() -> SamplingParams { |
| 89 | SamplingParams { |
| 90 | temperature: 0.0, |
| 91 | top_p: 1.0, |
| 92 | max_tokens: 64, |
| 93 | stop_token_ids: vec![], |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn prefill_batch(id: u64, tokens: &[u32]) -> ScheduledBatch { |
| 98 | ScheduledBatch { |
| 99 | prefill_requests: vec![SequenceRequest { |
| 100 | request_id: id, |
| 101 | prompt_tokens: tokens.to_vec(), |
| 102 | sampling_params: greedy(), |
| 103 | arrival_time_ns: 0, |
| 104 | priority: 1, |
| 105 | }], |
| 106 | decode_requests: Vec::new(), |
| 107 | block_tables: HashMap::new(), |
| 108 | step_id: 1, |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | fn decode_batch(id: u64) -> ScheduledBatch { |
| 113 | ScheduledBatch { |
| 114 | prefill_requests: Vec::new(), |
| 115 | decode_requests: vec![id], |
| 116 | block_tables: HashMap::new(), |
| 117 | step_id: 2, |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | fn token_of(outputs: &[DecodeOutput], id: u64) -> u32 { |
| 122 | outputs |
| 123 | .iter() |
| 124 | .find_map(|o| match o { |
| 125 | DecodeOutput::Token { |
| 126 | request_id, |
| 127 | token_id, |
| 128 | .. |
| 129 | } if *request_id == id => Some(*token_id), |
| 130 | _ => None, |
| 131 | }) |
| 132 | .expect("a token for the request") |
| 133 | } |
| 134 | |
| 135 | /// Sum of |K| and |V| at one position, layer 0, read straight from the pool. |
| 136 | fn kv_magnitude(kv: &SharedKvManager, seq: u64, pos: usize) -> f32 { |
| 137 | let r = kv.read(); |
| 138 | let table = r.get_block_table(seq).expect("table"); |
| 139 | let pool = r.tensor_pool().expect("pool"); |
| 140 | let kv_dim = config().num_kv_heads * config().head_dim; |
| 141 | let (mut k, mut v) = (vec![0.0f32; kv_dim], vec![0.0f32; kv_dim]); |
| 142 | let (blk, slot) = (table.block_ids[pos / BLOCK], pos % BLOCK); |
| 143 | pool.read_token_kv(blk, 0, slot, &mut k, &mut v); |
| 144 | k.iter().chain(v.iter()).map(|x| x.abs()).sum() |
| 145 | } |
| 146 | |
| 147 | #[tokio::test] |
| 148 | async fn computed_prefix_excludes_uncomputed_last_token() { |
| 149 | let kv = shared_pool(); |
| 150 | let mut b = backend_on(&kv); |
| 151 | let id = 0x1_0000_0001u64; |
| 152 | let p = prompt(20); |
| 153 | |
| 154 | // After prefill: the sampled token is held apart, every prompt token has K/V. |
| 155 | let (out, _) = b.execute_step(&prefill_batch(id, &p)).await.unwrap(); |
| 156 | let tok1 = token_of(&out, id); |
| 157 | assert_eq!(b.sequences[&id].tokens.len(), 20); |
| 158 | assert_eq!( |
| 159 | b.computed_prefix(id).expect("prefilled sequence"), |
| 160 | p, |
| 161 | "prefill: computed = the prompt; the sampled token is not in it" |
| 162 | ); |
| 163 | assert_eq!(kv.read().total_tokens(id), Some(20)); |
| 164 | assert!(kv_magnitude(&kv, id, 19) > 0.0, "position 19 holds K/V"); |
| 165 | |
| 166 | // After one decode step: the token fed (tok1) now has K/V, the newly |
| 167 | // sampled one (tok2) is the last entry of `tokens` and has none. |
| 168 | let (out, _) = b.execute_step(&decode_batch(id)).await.unwrap(); |
| 169 | let tok2 = token_of(&out, id); |
| 170 | assert_eq!( |
| 171 | b.sequences[&id].tokens.len(), |
| 172 | 22, |
| 173 | "the naive token list is one longer than the computed prefix" |
| 174 | ); |
| 175 | let mut expected = p.clone(); |
| 176 | expected.push(tok1); |
| 177 | let computed = b.computed_prefix(id).expect("decoding sequence"); |
| 178 | assert_eq!(computed, expected, "decode: the last token is excluded"); |
| 179 | assert_ne!(computed.last(), Some(&tok2)); |
| 180 | assert_eq!(kv.read().total_tokens(id), Some(21)); |
| 181 | assert!( |
| 182 | kv_magnitude(&kv, id, 20) > 0.0, |
| 183 | "the last computed position (20) is written" |
| 184 | ); |
| 185 | // Position 21 is the uncomputed last token: its slot in the pool is zero. |
| 186 | // The table stops at 21 tokens but the block has room, so read the raw slot. |
| 187 | let blk = kv.read().get_block_table(id).unwrap().block_ids[21 / BLOCK]; |
| 188 | let mut k = vec![0.0f32; 32]; |
| 189 | let mut v = vec![0.0f32; 32]; |
| 190 | kv.read() |
| 191 | .tensor_pool() |
| 192 | .unwrap() |
| 193 | .read_token_kv(blk, 0, 21 % BLOCK, &mut k, &mut v); |
| 194 | assert!( |
| 195 | k.iter().chain(v.iter()).all(|x| *x == 0.0), |
| 196 | "position `computed` (21) is unwritten in the pool" |
| 197 | ); |
| 198 | |
| 199 | // A second decode step moves the boundary by exactly one. |
| 200 | b.execute_step(&decode_batch(id)).await.unwrap(); |
| 201 | assert_eq!(b.computed_prefix(id).unwrap().len(), 22); |
| 202 | assert_eq!(b.sequences[&id].tokens.len(), 23); |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn computed_prefix_is_none_for_unknown_sequence_and_unpaged_backend() { |
| 207 | let kv = shared_pool(); |
| 208 | let b = backend_on(&kv); |
| 209 | assert_eq!(b.computed_prefix(0x1_0000_0009), None, "unknown sequence"); |
| 210 | |
| 211 | // No shared pool: K/V lives in the backend's dense per-sequence cache, not |
| 212 | // in blocks a holder could pin, so there is nothing to park. |
| 213 | let mut dense = NativeTransformerBackend::new(weights()); |
| 214 | dense.prefill_sequence(0x1_0000_0001, &prompt(8)).unwrap(); |
| 215 | assert_eq!(dense.computed_prefix(0x1_0000_0001), None); |
| 216 | } |
| 217 | |
| 218 | fn pending_table(kv: &SharedKvManager, seq: u64, tokens: &[u32]) { |
| 219 | let mut w = kv.write(); |
| 220 | w.allocate_sequence(seq, tokens).unwrap(); |
| 221 | w.mark_prefill_pending(seq).unwrap(); |
| 222 | } |
| 223 | |
| 224 | #[test] |
| 225 | fn restore_sequence_refuses_like_fork_sequence() { |
| 226 | let seq = 0x2_0000_0001u64; |
| 227 | let p = prompt(32); |
| 228 | |
| 229 | // No KV manager at all. |
| 230 | let mut no_kv = NativeTransformerBackend::new(weights()); |
| 231 | let e = no_kv.restore_sequence(seq, &p).unwrap_err(); |
| 232 | assert!(e.contains("no shared KV manager"), "{e}"); |
| 233 | |
| 234 | // A manager with no physical pool. |
| 235 | let bare = create_shared_kv_manager(POOL_BLOCKS, BLOCK); |
| 236 | let mut no_pool = backend_on(&bare); |
| 237 | pending_table(&bare, seq, &p); |
| 238 | let e = no_pool.restore_sequence(seq, &p).unwrap_err(); |
| 239 | assert!(e.contains("no physical tensor pool"), "{e}"); |
| 240 | |
| 241 | let kv = shared_pool(); |
| 242 | let mut b = backend_on(&kv); |
| 243 | |
| 244 | // No block table for the sequence. |
| 245 | let e = b.restore_sequence(seq, &p).unwrap_err(); |
| 246 | assert!(e.contains("no KV block table"), "{e}"); |
| 247 | |
| 248 | // Table exists but was never marked pending: allocation is not restoration. |
| 249 | kv.write().allocate_sequence(seq, &p).unwrap(); |
| 250 | let e = b.restore_sequence(seq, &p).unwrap_err(); |
| 251 | assert!(e.contains("prefill state"), "{e}"); |
| 252 | |
| 253 | // A ready table could enter decode: refused. |
| 254 | kv.write().mark_prefill_pending(seq).unwrap(); |
| 255 | kv.write().complete_prefill(seq).unwrap(); |
| 256 | let e = b.restore_sequence(seq, &p).unwrap_err(); |
| 257 | assert!(e.contains("prefill state"), "{e}"); |
| 258 | assert!( |
| 259 | b.sequences.is_empty(), |
| 260 | "every refusal leaves no backend state" |
| 261 | ); |
| 262 | } |
| 263 | |
| 264 | #[test] |
| 265 | fn restore_sequence_refuses_wrong_token_counts_and_double_restore() { |
| 266 | let kv = shared_pool(); |
| 267 | let mut b = backend_on(&kv); |
| 268 | let seq = 0x2_0000_0001u64; |
| 269 | let p = prompt(32); |
| 270 | pending_table(&kv, seq, &p); |
| 271 | |
| 272 | let e = b.restore_sequence(seq, &[]).unwrap_err(); |
| 273 | assert!(e.contains("empty"), "{e}"); |
| 274 | let e = b.restore_sequence(seq, &p[..31]).unwrap_err(); |
| 275 | assert!( |
| 276 | e.contains("covers 32"), |
| 277 | "token count must equal the table: {e}" |
| 278 | ); |
| 279 | assert!(b.sequences.is_empty()); |
| 280 | |
| 281 | b.restore_sequence(seq, &p).expect("matching restore"); |
| 282 | assert_eq!(b.sequences[&seq].tokens, p); |
| 283 | assert!( |
| 284 | !b.pending_prefill_token.contains_key(&seq), |
| 285 | "a restored prefix has no pending sampled token" |
| 286 | ); |
| 287 | let e = b.restore_sequence(seq, &p).unwrap_err(); |
| 288 | assert!(e.contains("already has backend state"), "{e}"); |
| 289 | assert_eq!( |
| 290 | b.sequences[&seq].tokens, p, |
| 291 | "second attempt changed nothing" |
| 292 | ); |
| 293 | } |
| 294 | |
| 295 | /// The A2 prerequisite at the backend: a prefix parked behind a holder and |
| 296 | /// restored into a new sequence continues exactly like an uninterrupted prefill. |
| 297 | /// `restored` is the parked prefix length; a value inside a block exercises the |
| 298 | /// partial tail, which the first suffix append copies on write. |
| 299 | async fn restore_and_continue(restored: usize, policy: SuffixPolicy) { |
| 300 | let p = prompt(40); |
| 301 | |
| 302 | // Control: one backend, one pool, the whole prompt in one chunk. |
| 303 | let control_kv = shared_pool(); |
| 304 | let mut control = backend_on(&control_kv); |
| 305 | let cid = 0x3_0000_0001u64; |
| 306 | let (out, _) = control.execute_step(&prefill_batch(cid, &p)).await.unwrap(); |
| 307 | let control_token = token_of(&out, cid); |
| 308 | |
| 309 | // Cold run of the first two blocks, then park behind a holder and free. |
| 310 | let kv = shared_pool(); |
| 311 | let mut cold = backend_on(&kv); |
| 312 | let pid = 0x4_0000_0001u64; |
| 313 | cold.execute_step(&prefill_batch(pid, &p[..restored])) |
| 314 | .await |
| 315 | .unwrap(); |
| 316 | let holder = holder_id(1).unwrap(); |
| 317 | { |
| 318 | let mut w = kv.write(); |
| 319 | w.mark_prefill_pending(pid).unwrap(); |
| 320 | w.complete_prefill(pid).unwrap(); |
| 321 | w.fork_range(pid, 0, restored.div_ceil(BLOCK), holder) |
| 322 | .unwrap(); |
| 323 | w.free_sequence(pid).unwrap(); |
| 324 | } |
| 325 | AienInferenceBackend::release_sequence(&mut cold, pid).unwrap(); |
| 326 | |
| 327 | // Restore: assemble the request's own table from the holder, give the |
| 328 | // backend the restored tokens, prefill only the suffix. |
| 329 | let rid = 0x5_0000_0001u64; |
| 330 | kv.write().assemble_table(rid, &[holder], policy).unwrap(); |
| 331 | let mut warm = backend_on(&kv); |
| 332 | warm.restore_sequence(rid, &p[..restored]).unwrap(); |
| 333 | let (out, _) = warm |
| 334 | .execute_step(&prefill_batch(rid, &p[restored..])) |
| 335 | .await |
| 336 | .unwrap(); |
| 337 | assert_eq!( |
| 338 | token_of(&out, rid), |
| 339 | control_token, |
| 340 | "greedy token after restore equals the uninterrupted run" |
| 341 | ); |
| 342 | assert_eq!(kv.read().total_tokens(rid), Some(40)); |
| 343 | if !restored.is_multiple_of(BLOCK) { |
| 344 | assert!( |
| 345 | kv.read().cow_faults() >= 1, |
| 346 | "the shared partial tail was copied on write, not mutated in place" |
| 347 | ); |
| 348 | } |
| 349 | |
| 350 | // K/V of every position matches the control within the chunking tolerance. |
| 351 | for layer in 0..2 { |
| 352 | let (rk, rv) = kv.read().gather_layer_kv(rid, layer).unwrap(); |
| 353 | let (ck, cv) = control_kv.read().gather_layer_kv(cid, layer).unwrap(); |
| 354 | assert_eq!(rk.len(), ck.len()); |
| 355 | let worst = rk |
| 356 | .iter() |
| 357 | .zip(&ck) |
| 358 | .chain(rv.iter().zip(&cv)) |
| 359 | .map(|(a, b)| (a - b).abs()) |
| 360 | .fold(0.0f32, f32::max); |
| 361 | assert!(worst <= 1e-4, "layer {layer}: K/V differs by {worst}"); |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | #[tokio::test] |
| 366 | async fn restored_prefix_continues_like_uninterrupted_prefill() { |
| 367 | restore_and_continue(32, SuffixPolicy::FullBlocksOnly).await; |
| 368 | } |
| 369 | |
| 370 | #[tokio::test] |
| 371 | async fn restored_partial_tail_continues_like_uninterrupted_prefill() { |
| 372 | restore_and_continue(20, SuffixPolicy::AllowPartialTail).await; |
| 373 | } |