diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index bae24b2e..91fb0d44 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1286,15 +1286,18 @@ fn load_daemon_model( }) } -fn build_native_daemon_backend() -> Result< - ( - aien_inference_abi::NativeTransformerBackend, - String, - String, - Option, - ), +/// Loaded daemon model parts: weights, tensor compute backend, backend label, +/// model label, tokenizer. The KV manager is built from these by +/// `aien_runtime::shared_kv::build_shared_kv_runtime` (one KV for spine and backend). +type DaemonBackendParts = ( + aien_inference_abi::TransformerWeights, + std::sync::Arc, String, -> { + String, + Option, +); + +fn build_native_daemon_backend() -> Result { let policy = CheckpointPolicy::from_env(); let manifest = resolve_daemon_manifest_with(&policy); let DaemonModel { @@ -1310,9 +1313,11 @@ fn build_native_daemon_backend() -> Result< if probe.is_available() { let device = probe.device_name().to_string(); drop(probe); - let backend = aien_inference_abi::NativeTransformerBackend::new_blackwell(weights); + let tensor_backend: std::sync::Arc = + std::sync::Arc::new(aien_inference_abi::BlackwellGb10Backend::new()); Ok(( - backend, + weights, + tensor_backend, format!("NativeTransformerBackend/Blackwell ({})", device), model_label, tokenizer, @@ -1322,9 +1327,11 @@ fn build_native_daemon_backend() -> Result< "AIEN_REQUIRE_BLACKWELL is set but no Blackwell device initialized (fallback count nonzero)".to_string(), ) } else { - let backend = aien_inference_abi::NativeTransformerBackend::new_reference(weights); + let tensor_backend: std::sync::Arc = + std::sync::Arc::new(aien_inference_abi::ReferenceCpuBackend::new()); Ok(( - backend, + weights, + tensor_backend, "NativeTransformerBackend/CPU-reference (Blackwell unavailable, explicit fallback)" .to_string(), model_label, @@ -1339,7 +1346,6 @@ pub async fn run_daemon_server() { "⚡ Starting AIEN Sovereign Runtime Daemon...".cyan().bold() ); let socket_path = aien_runtime::client::AienRuntimeClient::default_socket_path(); - let kv_manager = aien_kv_cache::create_shared_kv_manager(8192, 16); let sched_cfg = aien_scheduler::SchedulerConfig { max_batch_size: 256, max_batch_tokens: 16384, @@ -1348,32 +1354,50 @@ pub async fn run_daemon_server() { chunk_prefill: true, watermark_blocks: 64, }; - let spine = aien_runtime::spine::AienRuntimeSpine::new(4096, sched_cfg, kv_manager); - let server = aien_runtime::server::AienRuntimeServer::new(spine, &socket_path); - let backend = { + let (weights, tensor_backend, backend_label, model_label, tokenizer) = match build_native_daemon_backend() { - Ok((native_backend, backend_label, model_label, tokenizer)) => { - println!(" Backend: {}", backend_label.green()); - println!(" Model: {}", model_label.yellow()); - if let Some(tokenizer) = tokenizer { - server.set_tokenizer(tokenizer); - println!(" Tokenizer: {}", "TinyLlama chat template".green()); - } else { - println!( - " Tokenizer: {}", - "not loaded; native chat will refuse turns until tokenizer.json is present" - .yellow() - ); - } - native_backend - } + Ok(parts) => parts, Err(fatal) => { eprintln!("Fatal: {}", fatal.red().bold()); std::process::exit(1); } + }; + + // One KV for runtime and backend: the spine's block tables and the + // backend's K/V writes go to the same pooled manager. + let (spine, backend) = match aien_runtime::shared_kv::build_shared_kv_runtime( + weights, + tensor_backend, + sched_cfg, + aien_runtime::shared_kv::SharedKvSizing { + arena_capacity: 4096, + total_blocks: 8192, + }, + ) { + Ok(parts) => parts, + Err(fatal) => { + eprintln!("Fatal: shared KV pool: {}", fatal.red().bold()); + std::process::exit(1); } }; + let server = aien_runtime::server::AienRuntimeServer::new(spine, &socket_path); + + println!(" Backend: {}", backend_label.green()); + println!(" Model: {}", model_label.yellow()); + println!( + " KV: {}", + "one pooled KV shared by runtime and backend".green() + ); + if let Some(tokenizer) = tokenizer { + server.set_tokenizer(tokenizer); + println!(" Tokenizer: {}", "TinyLlama chat template".green()); + } else { + println!( + " Tokenizer: {}", + "not loaded; native chat will refuse turns until tokenizer.json is present".yellow() + ); + } println!("✓ Binding socket at {}", socket_path.display()); if let Err(e) = server.run(backend).await { eprintln!("Runtime daemon error: {}", e); diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 8cf30417..0d890f86 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -1025,9 +1025,42 @@ impl NativeTransformerBackend { valid_reqs.push((req_id, last_token, pos)); } + // 1b. Reserve append slots in KV cache for this decode step. A sequence + // whose slot cannot be reserved (pool exhausted) has nowhere to put this + // step's K/V, so it is not computed and gets no token: it is ended as + // Preempted and the scheduler frees its KV. Before the backend owned + // decode K/V, the scheduler's append check did the same + // (aien-scheduler/src/lib.rs, `!backend.manages_kv_cache()` branch). + let mut slot_failures: Vec = Vec::new(); + let block_slots: Vec> = if let Some(mgr) = &self.kv_manager { + let mut write_mgr = mgr.write(); + let mut kept_reqs = Vec::with_capacity(valid_reqs.len()); + let mut kept_slots = Vec::with_capacity(valid_reqs.len()); + for req in valid_reqs.drain(..) { + match write_mgr.append_token_with_slot(req.0) { + Ok(slot) => { + kept_reqs.push(req); + kept_slots.push(Some(slot)); + } + Err(_) => { + let total_tokens = self.sequences.get(&req.0).map_or(0, |s| s.tokens.len()); + slot_failures.push(DecodeOutput::Finished { + request_id: req.0, + reason: FinishReason::Preempted, + total_tokens, + }); + } + } + } + valid_reqs = kept_reqs; + kept_slots + } else { + vec![None; valid_reqs.len()] + }; + let d = valid_reqs.len(); if d == 0 { - return Vec::new(); + return slot_failures; } // 2. Allocate batch activations @@ -1051,16 +1084,7 @@ impl NativeTransformerBackend { .embed_token(last_token, &mut x[i * hidden_dim..(i + 1) * hidden_dim]); } - // 4. Reserve append slots in KV cache for this decode step - let block_slots: Vec> = if let Some(mgr) = &self.kv_manager { - let mut write_mgr = mgr.write(); - valid_reqs - .iter() - .map(|&(seq_id, _, _)| write_mgr.append_token_with_slot(seq_id).ok()) - .collect() - } else { - vec![None; d] - }; + // 4. (Decode slots were reserved in step 1b.) // 5. Transformer layer loop for (layer_idx, layer_w) in self.weights.layers.iter().enumerate() { @@ -1295,8 +1319,9 @@ impl NativeTransformerBackend { vocab_size, ); - // 8. Sampling and output emission - let mut outputs = Vec::with_capacity(d); + // 8. Sampling and output emission (slot failures from step 1b first) + let mut outputs = slot_failures; + outputs.reserve(d); let stop_tokens = [ crate::tokenizer::TinyLlamaTokenizer::UNK_TOKEN_ID, crate::tokenizer::TinyLlamaTokenizer::BOS_TOKEN_ID, diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index 2592259e..a2642b7d 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -6,6 +6,7 @@ pub mod control; pub mod rsi; pub mod sequence; pub mod server; +pub mod shared_kv; pub mod spine; pub mod swarm; pub mod world; diff --git a/crates/aien-runtime/src/shared_kv.rs b/crates/aien-runtime/src/shared_kv.rs new file mode 100644 index 00000000..3f49ce8c --- /dev/null +++ b/crates/aien-runtime/src/shared_kv.rs @@ -0,0 +1,70 @@ +//! One KV for runtime and backend (PREFILL-E2E-0 cut C2). +//! +//! Before this module the daemon built the spine on a pool-less KV manager +//! and the backend with no KV manager at all, so block tables in the runtime +//! were bookkeeping only and the real K/V lived in the backend's private +//! dense per-request cache. `build_shared_kv_runtime` creates ONE manager with +//! a physical tensor pool sized for the loaded model and hands the same `Arc` +//! to the spine (scheduler, swarm forks, reclaim) and to the backend (which +//! writes prefill/decode K/V into the pool blocks named by the spine's block +//! tables). +//! +//! Lives in aien-runtime (not aien-cli) because this crate owns the spine and +//! already depends on aien-inference-abi and aien-kv-cache, so the assembly +//! can be exercised by integration tests next to the other spine tests. + +use std::sync::Arc; + +use aien_inference_abi::{NativeTransformerBackend, TensorBackend, TransformerWeights}; +use aien_kv_cache::{create_shared_kv_manager_with_pool, KvDType, KvPoolConfig, SharedKvManager}; +use aien_scheduler::SchedulerConfig; + +use crate::spine::AienRuntimeSpine; + +/// Sizing for the shared runtime/backend KV manager. +#[derive(Debug, Clone, Copy)] +pub struct SharedKvSizing { + /// Sequence arena capacity of the spine. + pub arena_capacity: usize, + /// Number of physical KV blocks in the pool (and in the block allocator). + pub total_blocks: usize, +} + +/// Builds the pooled KV manager for `weights.config`. The block size is the +/// model config's `block_size`, because the backend's paged writes index +/// blocks with `weights.config.block_size` +/// (aien-inference-abi/src/transformer_backend.rs, prefill paged path). +pub fn build_model_kv_manager( + weights: &TransformerWeights, + total_blocks: usize, +) -> Result { + let cfg = &weights.config; + if cfg.block_size == 0 { + return Err("shared KV: model config block_size is 0".to_string()); + } + let pool_cfg = KvPoolConfig::for_model( + total_blocks, + cfg.block_size, + cfg.num_layers, + cfg.num_kv_heads, + cfg.head_dim, + KvDType::Fp32, + ); + create_shared_kv_manager_with_pool(total_blocks, cfg.block_size, pool_cfg) +} + +/// Builds the runtime spine and the native backend over ONE pooled KV +/// manager. The returned backend's `kv_manager` is the same `Arc` as the +/// spine's `kv_manager` (`Arc::ptr_eq`). +pub fn build_shared_kv_runtime( + weights: TransformerWeights, + tensor_backend: Arc, + scheduler_config: SchedulerConfig, + sizing: SharedKvSizing, +) -> Result<(AienRuntimeSpine, NativeTransformerBackend), String> { + let kv_manager = build_model_kv_manager(&weights, sizing.total_blocks)?; + let spine = AienRuntimeSpine::new(sizing.arena_capacity, scheduler_config, kv_manager.clone()); + let backend = + NativeTransformerBackend::with_shared_kv_and_backend(weights, tensor_backend, kv_manager); + Ok((spine, backend)) +} diff --git a/crates/aien-runtime/tests/shared_kv_runtime_test.rs b/crates/aien-runtime/tests/shared_kv_runtime_test.rs new file mode 100644 index 00000000..af9d6213 --- /dev/null +++ b/crates/aien-runtime/tests/shared_kv_runtime_test.rs @@ -0,0 +1,267 @@ +//! PREFILL-E2E-0 cut C2: one KV for runtime and backend (bullets 4, 8, 10). +//! +//! Builds the spine and the native backend through the same factory the +//! daemon uses (`aien_runtime::shared_kv::build_shared_kv_runtime`), submits +//! one root prompt (<= 16 tokens, a single prefill chunk) through the real +//! swarm -> scheduler `prefill_detached` -> backend `execute_step` path up to +//! the completion fence, then reads the root's K/V back out of the SPINE's KV +//! pool and compares it with the dense K/V an unpaged backend (no KV manager) +//! computes for the same prompt with the same weights. +//! +//! Mutant (kept outside the repo, applied by the forge job): the factory gives +//! the backend its own separate pooled manager. Then the backend writes K/V +//! into a pool the spine never sees, `Arc::ptr_eq` is false and the spine's +//! pool holds only zeros for the root, so this test must fail. +//! Mutant 2 (mutant-kv.patch): the paged prefill writes K into the V slot and +//! V into the K slot, so the pool is non-zero but the K/V-equality check fails. +//! +//! Second test: with the shared KV the backend reserves decode slots itself +//! (scheduler skips its append when `manages_kv_cache()`), so a tiny pool that +//! is full after prefill must end the request as Preempted instead of +//! decoding a token whose K/V was never stored. +//! Mutant 3 (mutant-slot.patch): slot failures are kept in the batch again, +//! so the request silently continues without K/V and this test must fail. + +use std::sync::Arc; + +use aien_inference_abi::{ + DecodeOutput, FinishReason, ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, + TransformerWeights, +}; +use aien_runtime::shared_kv::{build_model_kv_manager, build_shared_kv_runtime, SharedKvSizing}; +use aien_runtime::swarm::SwarmConfig; +use aien_scheduler::SchedulerConfig; + +const TOL: f32 = 1e-6; + +fn small_config() -> ModelConfig { + ModelConfig { + model_id: "pe2e-c2-shared-kv-reference".to_string(), + max_sequence_length: 256, + // Small blocks so the 11-token prompt spans three blocks, the last one partial. + block_size: 4, + num_layers: 3, + num_heads: 4, + head_dim: 8, + num_kv_heads: 2, + hidden_dim: 32, + intermediate_dim: 64, + vocab_size: 97, + rms_norm_eps: 1e-5, + rope_theta: 10000.0, + } +} + +fn daemon_like_scheduler() -> SchedulerConfig { + // Same chunking as the daemon (aien-cli run_daemon_server): chunk 128, so + // the prompt below is one prefill chunk. + SchedulerConfig { + max_batch_size: 32, + max_batch_tokens: 2048, + max_prefill_tokens: 1024, + prefill_chunk_size: 128, + chunk_prefill: true, + watermark_blocks: 2, + } +} + +#[tokio::test] +async fn shared_kv_root_prefill_lands_in_spine_pool_and_matches_unpaged_backend() { + let config = small_config(); + let weights = TransformerWeights::reference_test_weights(&config); + let prompt: Vec = vec![5, 17, 42, 3, 88, 61, 9, 23, 70, 11, 36]; + assert!(prompt.len() <= 16); + + let (mut spine, mut backend) = build_shared_kv_runtime( + weights.clone(), + Arc::new(ReferenceCpuBackend::new()), + daemon_like_scheduler(), + SharedKvSizing { + arena_capacity: 64, + total_blocks: 64, + }, + ) + .expect("build shared KV runtime"); + + // Check 1: one KV. The backend holds the very same Arc as the spine. + let backend_kv = backend + .kv_manager + .clone() + .expect("backend must be wired to a KV manager"); + assert!( + Arc::ptr_eq(&backend_kv, &spine.kv_manager), + "SHARED_KV_VIOLATION: backend KV manager is not the spine's KV manager" + ); + assert!( + spine.kv_manager.read().tensor_pool().is_some(), + "SHARED_KV_VIOLATION: spine KV manager has no physical tensor pool" + ); + + // Submit one root prompt through the real swarm/scheduler path. + let swarm_id = spine + .launch_swarm( + SwarmConfig { + model_handle: 1, + branch_count: 0, + max_active_sequences: 1, + max_tokens_per_branch: 1, + root_world_id: 0, + priority: 1, + }, + &prompt, + ) + .expect("launch swarm"); + let root = spine + .swarm_manager + .get_swarm(swarm_id) + .expect("swarm record") + .root_sequence_id + .as_u64(); + + let before = spine + .kv_manager + .read() + .prefill_state(root) + .expect("root has a KV table after launch"); + assert!(!before.is_ready(), "root must not be ready before prefill"); + + let metrics = spine + .step(&mut backend) + .await + .expect("spine step") + .expect("step must report the root prefill"); + assert_eq!(metrics.prefill_tokens_processed, prompt.len()); + + let after = spine + .kv_manager + .read() + .prefill_state(root) + .expect("root still has a KV table after prefill"); + assert!( + after.is_ready(), + "root must be ready after the completion fence" + ); + assert!(!spine.swarm_manager.is_root_prefill_pending(swarm_id)); + + // Control: an unpaged backend (no KV manager) with the same weights. + let mut control = NativeTransformerBackend::new_reference(weights); + let control_id = 9_000_001u64; + control + .prefill_sequence(control_id, &prompt) + .expect("control prefill"); + let control_seq = control + .sequences + .get(&control_id) + .expect("control sequence state"); + + let kv_dim = config.num_kv_heads * config.head_dim; + let kv = spine.kv_manager.read(); + for layer in 0..config.num_layers { + let mut k = Vec::new(); + let mut v = Vec::new(); + kv.gather_sequence_layer_kv(root, layer, &mut k, &mut v) + .expect("gather root K/V from the spine's pool"); + + let ck = &control_seq.layers[layer].flat_k; + let cv = &control_seq.layers[layer].flat_v; + assert_eq!( + ck.len(), + prompt.len() * kv_dim, + "control K length, layer {layer}" + ); + assert_eq!(k.len(), ck.len(), "spine pool K length, layer {layer}"); + assert_eq!(v.len(), cv.len(), "spine pool V length, layer {layer}"); + + assert!( + k.iter().any(|x| *x != 0.0) && v.iter().any(|x| *x != 0.0), + "SHARED_KV_VIOLATION: spine pool K/V for root is all zero at layer {layer} \ + (prefill K/V did not land in the runtime KV)" + ); + for (i, (a, b)) in k.iter().zip(ck.iter()).enumerate() { + assert!( + (a - b).abs() <= TOL, + "K mismatch layer {layer} idx {i}: spine pool {a} vs unpaged {b}" + ); + } + for (i, (a, b)) in v.iter().zip(cv.iter()).enumerate() { + assert!( + (a - b).abs() <= TOL, + "V mismatch layer {layer} idx {i}: spine pool {a} vs unpaged {b}" + ); + } + } +} + +#[test] +fn shared_kv_decode_slot_exhaustion_preempts_instead_of_decoding_without_kv() { + let config = small_config(); + let weights = TransformerWeights::reference_test_weights(&config); + // block_size 4, two blocks: an 8-token prompt fills the whole pool. + let kv = build_model_kv_manager(&weights, 2).expect("tiny pooled KV manager"); + let mut backend = NativeTransformerBackend::with_shared_kv_and_backend( + weights, + Arc::new(ReferenceCpuBackend::new()), + kv.clone(), + ); + let id = 77u64; + let prompt: Vec = vec![5, 17, 42, 3, 88, 61, 9, 23]; + backend + .prefill_sequence(id, &prompt) + .expect("prefill fits the pool"); + assert_eq!( + kv.read().free_block_count(), + 0, + "pool must be full after prefill" + ); + let tokens_before = backend + .sequences + .get(&id) + .expect("backend sequence") + .tokens + .len(); + let kv_tokens_before = kv + .read() + .get_block_table(id) + .expect("KV table") + .total_tokens; + + let outputs = backend.forward_decode_batch(&[id]); + + assert_eq!( + outputs.len(), + 1, + "exactly one output for the one decode request" + ); + match &outputs[0] { + DecodeOutput::Finished { + request_id, reason, .. + } => { + assert_eq!(*request_id, id); + assert_eq!( + *reason, + FinishReason::Preempted, + "decode slot failure must end the request as Preempted" + ); + } + DecodeOutput::Token { token_id, .. } => panic!( + "SHARED_KV_VIOLATION: decode emitted token {token_id} although no K/V slot \ + could be reserved (request silently continued without K/V)" + ), + } + assert_eq!( + backend + .sequences + .get(&id) + .map_or(tokens_before, |s| s.tokens.len()), + tokens_before, + "SHARED_KV_VIOLATION: backend generated a token with no K/V slot" + ); + assert_eq!( + kv.read() + .get_block_table(id) + .expect("KV table") + .total_tokens, + kv_tokens_before, + "KV table must not grow when the slot reservation failed" + ); +}