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-runtime / tests / shared_kv_runtime_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 | //! PREFILL-E2E-0 cut C2: one KV for runtime and backend (bullets 4, 8, 10). |
| 17 | //! |
| 18 | //! Builds the spine and the native backend through the same factory the |
| 19 | //! daemon uses (`aien_runtime::shared_kv::build_shared_kv_runtime`), submits |
| 20 | //! one root prompt (<= 16 tokens, a single prefill chunk) through the real |
| 21 | //! swarm -> scheduler `prefill_detached` -> backend `execute_step` path up to |
| 22 | //! the completion fence, then reads the root's K/V back out of the SPINE's KV |
| 23 | //! pool and compares it with the dense K/V an unpaged backend (no KV manager) |
| 24 | //! computes for the same prompt with the same weights. |
| 25 | //! |
| 26 | //! Mutant (kept outside the repo, applied by the forge job): the factory gives |
| 27 | //! the backend its own separate pooled manager. Then the backend writes K/V |
| 28 | //! into a pool the spine never sees, `Arc::ptr_eq` is false and the spine's |
| 29 | //! pool holds only zeros for the root, so this test must fail. |
| 30 | //! Mutant 2 (mutant-kv.patch): the paged prefill writes K into the V slot and |
| 31 | //! V into the K slot, so the pool is non-zero but the K/V-equality check fails. |
| 32 | //! |
| 33 | //! Second test: with the shared KV the backend reserves decode slots itself |
| 34 | //! (scheduler skips its append when `manages_kv_cache()`), so a tiny pool that |
| 35 | //! is full after prefill must end the request as Preempted instead of |
| 36 | //! decoding a token whose K/V was never stored. |
| 37 | //! Mutant 3 (mutant-slot.patch): slot failures are kept in the batch again, |
| 38 | //! so the request silently continues without K/V and this test must fail. |
| 39 | |
| 40 | use std::sync::Arc; |
| 41 | |
| 42 | use aien_inference_abi::{ |
| 43 | DecodeOutput, FinishReason, ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, |
| 44 | TransformerWeights, |
| 45 | }; |
| 46 | use aien_kv_cache::{bf16_bits_to_f32, f32_to_bf16_bits, KvDType}; |
| 47 | use aien_runtime::shared_kv::SHARED_KV_DTYPE; |
| 48 | use aien_runtime::shared_kv::{build_model_kv_manager, build_shared_kv_runtime, SharedKvSizing}; |
| 49 | use aien_runtime::swarm::SwarmConfig; |
| 50 | use aien_scheduler::SchedulerConfig; |
| 51 | |
| 52 | const TOL: f32 = 1e-6; |
| 53 | |
| 54 | /// The spine pool stores `SHARED_KV_DTYPE`, and since the birth-rounding fix (KV_ARITH_EPOCH 2) |
| 55 | /// every backend rounds K/V to its storage dtype the moment they are produced, so attention sees |
| 56 | /// the same bits the pool keeps. The control below therefore runs with `kv_dtype = SHARED_KV_DTYPE` |
| 57 | /// and must match the pool value exactly (bf16 round-to-nearest-even); `pool_rounded` is then the |
| 58 | /// identity on the control value and only guards against a pool that stored something other than |
| 59 | /// the rounded f32. |
| 60 | fn pool_rounded(x: f32) -> f32 { |
| 61 | match SHARED_KV_DTYPE { |
| 62 | KvDType::Bf16 => bf16_bits_to_f32(f32_to_bf16_bits(x)), |
| 63 | _ => x, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | fn small_config() -> ModelConfig { |
| 68 | ModelConfig { |
| 69 | model_id: "pe2e-c2-shared-kv-reference".to_string(), |
| 70 | max_sequence_length: 256, |
| 71 | // Small blocks so the 11-token prompt spans three blocks, the last one partial. |
| 72 | block_size: 4, |
| 73 | num_layers: 3, |
| 74 | num_heads: 4, |
| 75 | head_dim: 8, |
| 76 | num_kv_heads: 2, |
| 77 | hidden_dim: 32, |
| 78 | intermediate_dim: 64, |
| 79 | vocab_size: 97, |
| 80 | rms_norm_eps: 1e-5, |
| 81 | rope_theta: 10000.0, |
| 82 | rope_scaling: None, |
| 83 | tie_word_embeddings: false, |
| 84 | eos_token_ids: Vec::new(), |
| 85 | qk_norm: false, |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fn daemon_like_scheduler() -> SchedulerConfig { |
| 90 | // Same chunking as the daemon (aien-cli run_daemon_server): chunk 128, so |
| 91 | // the prompt below is one prefill chunk. |
| 92 | SchedulerConfig { |
| 93 | max_batch_size: 32, |
| 94 | max_batch_tokens: 2048, |
| 95 | max_prefill_tokens: 1024, |
| 96 | prefill_chunk_size: 128, |
| 97 | chunk_prefill: true, |
| 98 | watermark_blocks: 2, |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | #[tokio::test] |
| 103 | async fn shared_kv_root_prefill_lands_in_spine_pool_and_matches_unpaged_backend() { |
| 104 | let config = small_config(); |
| 105 | let weights = TransformerWeights::reference_test_weights(&config); |
| 106 | let prompt: Vec<u32> = vec![5, 17, 42, 3, 88, 61, 9, 23, 70, 11, 36]; |
| 107 | assert!(prompt.len() <= 16); |
| 108 | |
| 109 | let (mut spine, mut backend) = build_shared_kv_runtime( |
| 110 | weights.clone(), |
| 111 | Arc::new(ReferenceCpuBackend::new()), |
| 112 | daemon_like_scheduler(), |
| 113 | SharedKvSizing { |
| 114 | arena_capacity: 64, |
| 115 | total_blocks: 64, |
| 116 | }, |
| 117 | ) |
| 118 | .expect("build shared KV runtime"); |
| 119 | |
| 120 | // Check 1: one KV. The backend holds the very same Arc as the spine. |
| 121 | let backend_kv = backend |
| 122 | .kv_manager |
| 123 | .clone() |
| 124 | .expect("backend must be wired to a KV manager"); |
| 125 | assert!( |
| 126 | Arc::ptr_eq(&backend_kv, &spine.kv_manager), |
| 127 | "SHARED_KV_VIOLATION: backend KV manager is not the spine's KV manager" |
| 128 | ); |
| 129 | assert!( |
| 130 | spine.kv_manager.read().tensor_pool().is_some(), |
| 131 | "SHARED_KV_VIOLATION: spine KV manager has no physical tensor pool" |
| 132 | ); |
| 133 | |
| 134 | // Submit one root prompt through the real swarm/scheduler path. |
| 135 | let swarm_id = spine |
| 136 | .launch_swarm( |
| 137 | SwarmConfig { |
| 138 | model_handle: 1, |
| 139 | branch_count: 0, |
| 140 | max_active_sequences: 1, |
| 141 | max_tokens_per_branch: 1, |
| 142 | root_world_id: 0, |
| 143 | priority: 1, |
| 144 | }, |
| 145 | &prompt, |
| 146 | ) |
| 147 | .expect("launch swarm"); |
| 148 | let root = spine |
| 149 | .swarm_manager |
| 150 | .get_swarm(swarm_id) |
| 151 | .expect("swarm record") |
| 152 | .root_sequence_id |
| 153 | .as_u64(); |
| 154 | |
| 155 | let before = spine |
| 156 | .kv_manager |
| 157 | .read() |
| 158 | .prefill_state(root) |
| 159 | .expect("root has a KV table after launch"); |
| 160 | assert!(!before.is_ready(), "root must not be ready before prefill"); |
| 161 | |
| 162 | let metrics = spine |
| 163 | .step(&mut backend) |
| 164 | .await |
| 165 | .expect("spine step") |
| 166 | .expect("step must report the root prefill"); |
| 167 | assert_eq!(metrics.prefill_tokens_processed, prompt.len()); |
| 168 | |
| 169 | let after = spine |
| 170 | .kv_manager |
| 171 | .read() |
| 172 | .prefill_state(root) |
| 173 | .expect("root still has a KV table after prefill"); |
| 174 | assert!( |
| 175 | after.is_ready(), |
| 176 | "root must be ready after the completion fence" |
| 177 | ); |
| 178 | assert!(!spine.swarm_manager.is_root_prefill_pending(swarm_id)); |
| 179 | |
| 180 | // Control: an unpaged backend (no KV manager) with the same weights. |
| 181 | // Same storage dtype as the pool: both sides round at birth, so the hidden states that feed |
| 182 | // later layers agree bit for bit (an f32 control diverges from layer 1 on, see #589). |
| 183 | let mut control = NativeTransformerBackend::new_reference(weights); |
| 184 | control.kv_dtype = SHARED_KV_DTYPE; |
| 185 | let control_id = 9_000_001u64; |
| 186 | control |
| 187 | .prefill_sequence(control_id, &prompt) |
| 188 | .expect("control prefill"); |
| 189 | let control_seq = control |
| 190 | .sequences |
| 191 | .get(&control_id) |
| 192 | .expect("control sequence state"); |
| 193 | |
| 194 | let kv_dim = config.num_kv_heads * config.head_dim; |
| 195 | let kv = spine.kv_manager.read(); |
| 196 | for layer in 0..config.num_layers { |
| 197 | let mut k = Vec::new(); |
| 198 | let mut v = Vec::new(); |
| 199 | kv.gather_sequence_layer_kv(root, layer, &mut k, &mut v) |
| 200 | .expect("gather root K/V from the spine's pool"); |
| 201 | |
| 202 | let ck = &control_seq.layers[layer].flat_k; |
| 203 | let cv = &control_seq.layers[layer].flat_v; |
| 204 | assert_eq!( |
| 205 | ck.len(), |
| 206 | prompt.len() * kv_dim, |
| 207 | "control K length, layer {layer}" |
| 208 | ); |
| 209 | assert_eq!(k.len(), ck.len(), "spine pool K length, layer {layer}"); |
| 210 | assert_eq!(v.len(), cv.len(), "spine pool V length, layer {layer}"); |
| 211 | |
| 212 | assert!( |
| 213 | k.iter().any(|x| *x != 0.0) && v.iter().any(|x| *x != 0.0), |
| 214 | "SHARED_KV_VIOLATION: spine pool K/V for root is all zero at layer {layer} \ |
| 215 | (prefill K/V did not land in the runtime KV)" |
| 216 | ); |
| 217 | for (i, (a, b)) in k.iter().zip(ck.iter()).enumerate() { |
| 218 | assert!( |
| 219 | (a - pool_rounded(*b)).abs() <= TOL, |
| 220 | "K mismatch layer {layer} idx {i}: spine pool {a} vs unpaged {b} (rounded {})", |
| 221 | pool_rounded(*b) |
| 222 | ); |
| 223 | } |
| 224 | for (i, (a, b)) in v.iter().zip(cv.iter()).enumerate() { |
| 225 | assert!( |
| 226 | (a - pool_rounded(*b)).abs() <= TOL, |
| 227 | "V mismatch layer {layer} idx {i}: spine pool {a} vs unpaged {b} (rounded {})", |
| 228 | pool_rounded(*b) |
| 229 | ); |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn shared_kv_decode_slot_exhaustion_preempts_instead_of_decoding_without_kv() { |
| 236 | let config = small_config(); |
| 237 | let weights = TransformerWeights::reference_test_weights(&config); |
| 238 | // block_size 4, two blocks: an 8-token prompt fills the whole pool. |
| 239 | let kv = build_model_kv_manager(&weights, 2).expect("tiny pooled KV manager"); |
| 240 | let mut backend = NativeTransformerBackend::with_shared_kv_and_backend( |
| 241 | weights, |
| 242 | Arc::new(ReferenceCpuBackend::new()), |
| 243 | kv.clone(), |
| 244 | ); |
| 245 | let id = 77u64; |
| 246 | let prompt: Vec<u32> = vec![5, 17, 42, 3, 88, 61, 9, 23]; |
| 247 | backend |
| 248 | .prefill_sequence(id, &prompt) |
| 249 | .expect("prefill fits the pool"); |
| 250 | assert_eq!( |
| 251 | kv.read().free_block_count(), |
| 252 | 0, |
| 253 | "pool must be full after prefill" |
| 254 | ); |
| 255 | let tokens_before = backend |
| 256 | .sequences |
| 257 | .get(&id) |
| 258 | .expect("backend sequence") |
| 259 | .tokens |
| 260 | .len(); |
| 261 | let kv_tokens_before = kv |
| 262 | .read() |
| 263 | .get_block_table(id) |
| 264 | .expect("KV table") |
| 265 | .total_tokens; |
| 266 | |
| 267 | let outputs = backend |
| 268 | .forward_decode_batch(&[id]) |
| 269 | .expect("known, prefilled id: slot failure is an output, not an error"); |
| 270 | |
| 271 | assert_eq!( |
| 272 | outputs.len(), |
| 273 | 1, |
| 274 | "exactly one output for the one decode request" |
| 275 | ); |
| 276 | match &outputs[0] { |
| 277 | DecodeOutput::Finished { |
| 278 | request_id, reason, .. |
| 279 | } => { |
| 280 | assert_eq!(*request_id, id); |
| 281 | assert_eq!( |
| 282 | *reason, |
| 283 | FinishReason::Preempted, |
| 284 | "decode slot failure must end the request as Preempted" |
| 285 | ); |
| 286 | } |
| 287 | DecodeOutput::Token { token_id, .. } => panic!( |
| 288 | "SHARED_KV_VIOLATION: decode emitted token {token_id} although no K/V slot \ |
| 289 | could be reserved (request silently continued without K/V)" |
| 290 | ), |
| 291 | } |
| 292 | assert_eq!( |
| 293 | backend |
| 294 | .sequences |
| 295 | .get(&id) |
| 296 | .map_or(tokens_before, |s| s.tokens.len()), |
| 297 | tokens_before, |
| 298 | "SHARED_KV_VIOLATION: backend generated a token with no K/V slot" |
| 299 | ); |
| 300 | assert_eq!( |
| 301 | kv.read() |
| 302 | .get_block_table(id) |
| 303 | .expect("KV table") |
| 304 | .total_tokens, |
| 305 | kv_tokens_before, |
| 306 | "KV table must not grow when the slot reservation failed" |
| 307 | ); |
| 308 | } |