diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 4eb3f610..8fc134c6 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -243,6 +243,25 @@ pub trait AienInferenceBackend: Send + Sync { fn manages_kv_cache(&self) -> bool { false } + + /// PREFILL-E2E-0 bullets 6-8: forks the backend's per-sequence state + /// (tokens, position, last token) from a prefilled parent into a child. + /// Called by the runtime spine once per branch AFTER the root passed the + /// prefill completion fence and the KV manager shared the root blocks + /// (`fork_branches_from_ready_root`), and BEFORE any branch is decoded. + /// Must never copy or re-fork K/V: the physical KV fork is already done. + /// Default: no-op, for backends that keep no per-sequence state. + fn fork_sequence(&mut self, _parent_id: u64, _child_id: u64) -> Result<(), String> { + Ok(()) + } + + /// Drops the backend's per-sequence state for `seq_id`. Reclaim wiring + /// (calling this when a sequence finishes or a swarm is cancelled) is + /// PREFILL-E2E cut C5; it is not called by the runtime yet. + /// Default: no-op. + fn release_sequence(&mut self, _seq_id: u64) -> Result<(), String> { + Ok(()) + } } /// High-throughput simulated backend for benchmarking scheduler and KV manager overhead diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 0d890f86..af289e1e 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -236,6 +236,14 @@ impl NativeTransformerBackend { } /// Forks an existing context into an independently decoding branch with zero KV copying. + /// + /// Handle-API helper for library tests (`paged_transformer_parity.rs`, + /// `branch_client_harness.rs`, the unit tests below). It is NOT on the + /// runtime path: the spine forks backend state only through the trait hook + /// `AienInferenceBackend::fork_sequence`, which is gated on PrefillReady and + /// never copies K/V. This method is ungated and, without a KV manager, + /// copies the parent's dense K/V per branch; no code in aien-runtime or + /// aien-cli calls it (grep `fork_context`, PREFILL-E2E C4). pub fn fork_context(&mut self, parent: ContextHandle) -> Result { self.commit_pending_prefill_token(parent.0); let parent_seq = self @@ -992,12 +1000,46 @@ impl NativeTransformerBackend { /// Forward pass executing one token decode step across a batch of D sequences concurrently. /// Employs batched GEMM (M=D) for all linear projections and batched paged attention. - pub fn forward_decode_batch(&mut self, decode_req_ids: &[u64]) -> Vec { + /// + /// Every id must already have backend state (from a prefill or from + /// `fork_sequence`). An unknown id, or one with no tokens, is an error and + /// nothing is computed: decoding it would start from token 1 at position 0 + /// over an empty cache (PREFILL-E2E C4). + pub fn forward_decode_batch( + &mut self, + decode_req_ids: &[u64], + ) -> Result, String> { + self.forward_decode_batch_impl(decode_req_ids) + .map(|(outputs, _logits, _vocab)| outputs) + } + + /// Same as `forward_decode_batch`, also returning each sequence's logits + /// (in `decode_req_ids` order, minus any sequence ended as Preempted for + /// lack of a KV slot, which gets no logits) for parity checks. + pub fn forward_decode_batch_with_logits( + &mut self, + decode_req_ids: &[u64], + ) -> Result<(Vec, Vec>), String> { + let (outputs, logits_batch, vocab_size) = self.forward_decode_batch_impl(decode_req_ids)?; + let logits = if vocab_size == 0 { + Vec::new() + } else { + logits_batch + .chunks(vocab_size) + .map(|row| row.to_vec()) + .collect() + }; + Ok((outputs, logits)) + } + + fn forward_decode_batch_impl( + &mut self, + decode_req_ids: &[u64], + ) -> Result<(Vec, Vec, usize), String> { if decode_req_ids.is_empty() { - return Vec::new(); + return Ok((Vec::new(), Vec::new(), 0)); } - let num_layers = self.weights.config.num_layers; let hidden_dim = self.weights.config.hidden_dim(); let num_heads = self.weights.config.num_heads; let num_kv_heads = self.weights.config.num_kv_heads; @@ -1010,18 +1052,24 @@ impl NativeTransformerBackend { let vocab_size = self.weights.config.vocab_size(); // 1. Gather active sequence requests and their current positions / last tokens + // Validated before anything is written, so a refused batch leaves no state behind. let mut valid_reqs = Vec::with_capacity(decode_req_ids.len()); for &req_id in decode_req_ids { self.commit_pending_prefill_token(req_id); - let seq = self - .sequences - .entry(req_id) - .or_insert_with(|| SequenceState { - tokens: Vec::new(), - layers: vec![LayerKvCache::default(); num_layers], - }); - let pos = seq.tokens.len().saturating_sub(1); - let last_token = *seq.tokens.last().unwrap_or(&1); + let seq = self.sequences.get(&req_id).ok_or_else(|| { + format!( + "decode refused: request {} has no backend sequence state \ + (never prefilled and never forked via fork_sequence)", + req_id + ) + })?; + let last_token = *seq.tokens.last().ok_or_else(|| { + format!( + "decode refused: request {} has no tokens (no prefilled prompt)", + req_id + ) + })?; + let pos = seq.tokens.len() - 1; valid_reqs.push((req_id, last_token, pos)); } @@ -1060,7 +1108,7 @@ impl NativeTransformerBackend { let d = valid_reqs.len(); if d == 0 { - return slot_failures; + return Ok((slot_failures, Vec::new(), 0)); } // 2. Allocate batch activations @@ -1351,7 +1399,7 @@ impl NativeTransformerBackend { } } - outputs + Ok((outputs, logits_batch, vocab_size)) } } @@ -1368,6 +1416,92 @@ impl AienInferenceBackend for NativeTransformerBackend { self.kv_manager.is_some() } + /// Forks per-sequence backend state (tokens, hence position and last + /// token) from a prefilled parent into a child whose physical KV the + /// shared KV manager has already forked (`fork_prefilled`). Never copies + /// or re-forks K/V. Refuses when: + /// - there is no KV manager, or it has no physical tensor pool: the K/V + /// would live in the backend's dense per-sequence cache and a fork + /// would have to copy it per branch (bullet 10); + /// - the parent is not PrefillReady/SharedFrozen in the KV manager + /// (bullet 6: no fork before the completion fence); + /// - the child has no KV block table yet (the KV fork must come first); + /// - the parent is unknown to the backend, or the child already exists. + fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> { + let kv_mgr = self.kv_manager.as_ref().ok_or_else(|| { + format!( + "fork_sequence {} -> {} refused: backend has no shared KV manager \ + (unpaged fork would copy dense K/V)", + parent_id, child_id + ) + })?; + { + let kv = kv_mgr.read(); + if kv.tensor_pool().is_none() { + return Err(format!( + "fork_sequence {} -> {} refused: KV manager has no physical tensor pool", + parent_id, child_id + )); + } + match kv.prefill_state(parent_id) { + Some(state) if state.is_ready() => {} + Some(state) => { + return Err(format!( + "fork_sequence {} -> {} refused: parent prefill state {:?} is not ready \ + (completion fence not passed)", + parent_id, child_id, state + )) + } + None => { + return Err(format!( + "fork_sequence {} -> {} refused: parent has no KV block table", + parent_id, child_id + )) + } + } + if kv.get_block_table(child_id).is_none() { + return Err(format!( + "fork_sequence {} -> {} refused: child has no KV block table \ + (physical KV fork must precede the backend fork)", + parent_id, child_id + )); + } + } + if self.sequences.contains_key(&child_id) { + return Err(format!( + "fork_sequence {} -> {} refused: child already has backend state", + parent_id, child_id + )); + } + // The token prefill sampled but did not append yet (`pending_prefill_token`) + // belongs to the parent's stream. The child gets it appended to its own copy + // of the tokens; the parent is NOT mutated (its tokens stay prompt-only and + // its pending token stays pending, so the parent's own next decode commits it). + let mut parent_tokens = self + .sequences + .get(&parent_id) + .ok_or_else(|| { + format!( + "fork_sequence {} -> {} refused: parent unknown to the backend", + parent_id, child_id + ) + })? + .tokens + .clone(); + if let Some(&pending) = self.pending_prefill_token.get(&parent_id) { + parent_tokens.push(pending); + } + self.sequences.insert( + child_id, + SequenceState { + tokens: parent_tokens, + // Paged mode: K/V lives in the shared pool, never in per-sequence layers. + layers: Vec::new(), + }, + ); + Ok(()) + } + async fn execute_step( &mut self, batch: &ScheduledBatch, @@ -1431,7 +1565,7 @@ impl AienInferenceBackend for NativeTransformerBackend { // 2. Decode Requests (Batched across D active sequences) if !batch.decode_requests.is_empty() { - let decode_outputs = self.forward_decode_batch(&batch.decode_requests); + let decode_outputs = self.forward_decode_batch(&batch.decode_requests)?; outputs.extend(decode_outputs); } diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 1d58b84b..7ed33bc3 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -27,6 +27,10 @@ pub struct AienRuntimeSpine { pub swarm_manager: SwarmManager, pub controller: RuntimeController, pub step_counter: u64, + /// Subagent forks whose KV is already forked but whose backend state is + /// not yet: (parent, child) KV ids, applied via the backend's + /// `fork_sequence` at the start of the next `step`, before any decode. + pending_backend_forks: Vec<(u64, u64)>, } impl AienRuntimeSpine { @@ -45,6 +49,7 @@ impl AienRuntimeSpine { swarm_manager: SwarmManager::new(), controller: RuntimeController::new(), step_counter: 0, + pending_backend_forks: Vec::new(), } } @@ -104,8 +109,13 @@ impl AienRuntimeSpine { child_id: u64, sink_id: Option, ) -> Result<(), String> { - self.scheduler - .fork_subagent_with_sink(parent_id, child_id, sink_id) + let ids = self + .scheduler + .fork_subagent_with_sink_ids(parent_id, child_id, sink_id)?; + // The backend is not reachable here; its state is forked at the start + // of the next step, before the child can be decoded. + self.pending_backend_forks.push(ids); + Ok(()) } /// Executes runtime steps in a closed loop until all active requests complete or max_steps is reached. @@ -136,6 +146,12 @@ impl AienRuntimeSpine { ) -> Result, String> { self.step_counter += 1; + // PREFILL-E2E C4: backend state for subagent forks made since the + // last step, before the scheduler can decode the children. + for (parent, child) in std::mem::take(&mut self.pending_backend_forks) { + backend.fork_sequence(parent, child)?; + } + // PREFILL-GATE: run the model prefill over each pending swarm root // prompt BEFORE any branch can be scheduled, then share the computed // root blocks with the branches. Branches never see root blocks that @@ -210,9 +226,27 @@ impl AienRuntimeSpine { { prefilled += m.prefill_tokens_processed; } - let mut kv = self.kv_manager.write(); - self.swarm_manager - .fork_branches_from_ready_root(swarm_id, &mut self.arena, &mut kv)?; + { + let mut kv = self.kv_manager.write(); + self.swarm_manager.fork_branches_from_ready_root( + swarm_id, + &mut self.arena, + &mut kv, + )?; + } + // PREFILL-E2E C4 (bullets 6-8): fork the backend's per-sequence + // state (tokens, position, last token) for each branch right after + // the physical KV fork and before any branch can be scheduled for + // decode. The KV lock is released first: the backend reads the + // same shared KV manager to check the parent is PrefillReady. + let branches: Vec = self + .swarm_manager + .get_swarm(swarm_id) + .map(|s| s.branch_sequences.iter().map(|b| b.as_u64()).collect()) + .unwrap_or_default(); + for child in branches { + backend.fork_sequence(root_kv_id, child)?; + } } Ok(prefilled) } diff --git a/crates/aien-runtime/tests/shared_kv_runtime_test.rs b/crates/aien-runtime/tests/shared_kv_runtime_test.rs index af9d6213..cf2d9652 100644 --- a/crates/aien-runtime/tests/shared_kv_runtime_test.rs +++ b/crates/aien-runtime/tests/shared_kv_runtime_test.rs @@ -225,7 +225,9 @@ fn shared_kv_decode_slot_exhaustion_preempts_instead_of_decoding_without_kv() { .expect("KV table") .total_tokens; - let outputs = backend.forward_decode_batch(&[id]); + let outputs = backend + .forward_decode_batch(&[id]) + .expect("known, prefilled id: slot failure is an output, not an error"); assert_eq!( outputs.len(), diff --git a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs index be953371..7ef0a3bb 100644 --- a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs +++ b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs @@ -9,13 +9,33 @@ //! //! The stock MockInferenceBackend ignores prompt content, so this test uses a //! recording backend that logs every prefill span and every decode, in order. +//! +//! PREFILL-E2E C4 (bullets 6, 7, 8) extends it: the recording backend also +//! logs the backend fork hook (`fork_sequence`) together with the parent's +//! KV prefill state at that moment, and refuses a fork whose parent is not +//! ready. The swarm test asserts the order prefill fence -> fork_sequence per +//! branch -> first decode. Further tests drive the real +//! NativeTransformerBackend (reference weights, CPU) through spine + +//! scheduler + one pooled KV: a fork before the fence is refused, a decode +//! of an unknown id is an error, and each branch's first decode logits equal +//! the root's own continuation logits (abs 1e-5). +//! +//! Mutant (outside the repo, ~/workspace/hive/PE2E-C4/mutant.patch): the +//! spine no longer calls `fork_sequence` and `forward_decode_batch` again +//! creates an empty state (`or_insert_with`) for an unknown id. Then no Fork +//! events are recorded, the unknown-id decode is accepted, and branches decode +//! from token 1 at position 0, so the tests below fail. use std::collections::HashMap; +use std::sync::Arc; + use aien_inference_abi::{ - AienInferenceBackend, DecodeOutput, ModelConfig, ScheduledBatch, StepMetrics, + AienInferenceBackend, DecodeOutput, ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, + SamplingParams, ScheduledBatch, SequenceRequest, StepMetrics, TransformerWeights, }; -use aien_kv_cache::create_shared_kv_manager; +use aien_kv_cache::{create_shared_kv_manager, SharedKvManager}; +use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; use aien_runtime::spine::AienRuntimeSpine; use aien_runtime::swarm::SwarmConfig; use aien_scheduler::SchedulerConfig; @@ -23,13 +43,26 @@ use async_trait::async_trait; #[derive(Debug, Clone)] enum Event { - Prefill { id: u64, tokens: Vec }, - Decode { id: u64 }, + Prefill { + id: u64, + tokens: Vec, + }, + Decode { + id: u64, + }, + Fork { + parent: u64, + child: u64, + parent_ready: bool, + }, } #[derive(Default)] struct RecordingBackend { events: Vec, + /// The spine's KV manager, read in `fork_sequence` to record (and gate on) + /// whether the parent passed the prefill completion fence. + kv: Option, } #[async_trait] @@ -72,6 +105,28 @@ impl AienInferenceBackend for RecordingBackend { }; Ok((outputs, metrics)) } + + fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> { + let parent_ready = self + .kv + .as_ref() + .and_then(|kv| kv.read().prefill_state(parent_id)) + .map(|s| s.is_ready()) + .unwrap_or(false); + self.events.push(Event::Fork { + parent: parent_id, + child: child_id, + parent_ready, + }); + if parent_ready { + Ok(()) + } else { + Err(format!( + "recording backend: fork {} -> {} refused, parent not PrefillReady", + parent_id, child_id + )) + } + } } #[tokio::test] @@ -86,7 +141,10 @@ async fn prefill_gate_swarm_branches_never_decode_before_root_prompt_prefill() { watermark_blocks: 4, }; let mut spine = AienRuntimeSpine::new(64, sched_cfg, kv_manager.clone()); - let mut backend = RecordingBackend::default(); + let mut backend = RecordingBackend { + kv: Some(kv_manager.clone()), + ..RecordingBackend::default() + }; let prompt: Vec = (500..540).collect(); let branch_count = 4usize; @@ -143,7 +201,70 @@ async fn prefill_gate_swarm_branches_never_decode_before_root_prompt_prefill() { ); } } + Event::Fork { .. } => {} + } + } + + // PREFILL-E2E C4 order: prefill fence -> fork_sequence per branch -> first decode. + let last_root_prefill = backend + .events + .iter() + .rposition(|e| matches!(e, Event::Prefill { id, .. } if *id == root)) + .expect("root prompt must be prefilled"); + for &b in &branches { + let forks: Vec = backend + .events + .iter() + .enumerate() + .filter(|(_, e)| matches!(e, Event::Fork { child, .. } if *child == b)) + .map(|(i, _)| i) + .collect(); + assert_eq!( + forks.len(), + 1, + "BACKEND_FORK_VIOLATION: branch {} must be forked in the backend exactly once, got {}", + b, + forks.len() + ); + let fork_at = forks[0]; + match &backend.events[fork_at] { + Event::Fork { + parent, + parent_ready, + .. + } => { + assert_eq!( + *parent, root, + "branch {} forked from {} not root", + b, parent + ); + assert!( + *parent_ready, + "BACKEND_FORK_VIOLATION: branch {} forked before the root prefill fence", + b + ); + } + _ => unreachable!(), } + assert!( + fork_at > last_root_prefill, + "BACKEND_FORK_VIOLATION: branch {} forked (event {}) before the last root prefill chunk (event {})", + b, + fork_at, + last_root_prefill + ); + let first_decode = backend + .events + .iter() + .position(|e| matches!(e, Event::Decode { id } if *id == b)) + .expect("every branch decodes"); + assert!( + fork_at < first_decode, + "BACKEND_FORK_VIOLATION: branch {} decoded (event {}) before its backend fork (event {})", + b, + first_decode, + fork_at + ); } assert!( @@ -156,3 +277,393 @@ async fn prefill_gate_swarm_branches_never_decode_before_root_prompt_prefill() { "every branch must finish" ); } + +// --------------------------------------------------------------------------- +// PREFILL-E2E C4: real NativeTransformerBackend (reference weights, CPU) +// through spine + scheduler + one pooled KV. +// --------------------------------------------------------------------------- + +const PARITY_TOL: f32 = 1e-5; + +fn c4_config() -> ModelConfig { + ModelConfig { + model_id: "pe2e-c4-fork-hooks-reference".to_string(), + max_sequence_length: 256, + // 6-token prompt over 4-token blocks: the root's tail block is partial + // and shared, so each branch's first decode copies it (COW). + 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 c4_scheduler() -> SchedulerConfig { + SchedulerConfig { + max_batch_size: 32, + max_batch_tokens: 2048, + max_prefill_tokens: 1024, + prefill_chunk_size: 128, + chunk_prefill: true, + watermark_blocks: 2, + } +} + +const C4_PROMPT: [u32; 6] = [5, 17, 42, 3, 88, 61]; + +/// Delegates to the native backend and records each sequence's decode logits. +struct LogitsTap { + inner: NativeTransformerBackend, + decode_logits: HashMap>>, + /// Each sequence's backend token stream as it was just before its first decode. + first_decode_tokens: HashMap>, +} + +#[async_trait] +impl AienInferenceBackend for LogitsTap { + async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> { + Ok(()) + } + + async fn execute_step( + &mut self, + batch: &ScheduledBatch, + ) -> Result<(Vec, StepMetrics), String> { + let mut outputs = Vec::new(); + let mut metrics = StepMetrics::default(); + if !batch.prefill_requests.is_empty() { + let prefill_only = ScheduledBatch { + decode_requests: Vec::new(), + ..batch.clone() + }; + let (o, m) = self.inner.execute_step(&prefill_only).await?; + outputs.extend(o); + metrics = m; + } + if !batch.decode_requests.is_empty() { + for id in &batch.decode_requests { + if let Some(seq) = self.inner.sequences.get(id) { + self.first_decode_tokens + .entry(*id) + .or_insert_with(|| seq.tokens.clone()); + } + } + let (o, logits) = self + .inner + .forward_decode_batch_with_logits(&batch.decode_requests)?; + for (id, row) in batch.decode_requests.iter().zip(logits) { + self.decode_logits.entry(*id).or_default().push(row); + } + outputs.extend(o); + metrics.decode_tokens_emitted += batch.decode_requests.len(); + } + Ok((outputs, metrics)) + } + + fn manages_kv_cache(&self) -> bool { + self.inner.manages_kv_cache() + } + + fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> { + self.inner.fork_sequence(parent_id, child_id) + } +} + +fn c4_swarm_config(branch_count: usize, max_tokens: usize) -> SwarmConfig { + SwarmConfig { + model_handle: 1, + branch_count, + max_active_sequences: branch_count, + max_tokens_per_branch: max_tokens, + root_world_id: 0, + priority: 1, + } +} + +#[tokio::test] +async fn backend_fork_before_prefill_fence_is_refused() { + let config = c4_config(); + let weights = TransformerWeights::reference_test_weights(&config); + let (mut spine, mut backend) = build_shared_kv_runtime( + weights, + Arc::new(ReferenceCpuBackend::new()), + c4_scheduler(), + SharedKvSizing { + arena_capacity: 64, + total_blocks: 64, + }, + ) + .expect("build shared KV runtime"); + + let swarm_id = spine + .launch_swarm(c4_swarm_config(2, 2), &C4_PROMPT) + .expect("launch swarm"); + let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone(); + let root = swarm.root_sequence_id.as_u64(); + let branches: Vec = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect(); + + // Run the model over the root prompt WITHOUT the completion fence: the + // backend now knows the root, but the KV manager has not marked it ready. + let mut block_tables = HashMap::new(); + block_tables.insert( + root, + spine + .kv_manager + .read() + .get_block_table(root) + .unwrap() + .block_ids + .clone(), + ); + let unfenced = ScheduledBatch { + prefill_requests: vec![SequenceRequest { + request_id: root, + prompt_tokens: C4_PROMPT.to_vec(), + sampling_params: SamplingParams::default(), + arrival_time_ns: 0, + priority: 1, + }], + decode_requests: Vec::new(), + block_tables, + step_id: 1, + }; + backend + .execute_step(&unfenced) + .await + .expect("unfenced prefill"); + assert!(backend.sequences.contains_key(&root)); + let state = spine.kv_manager.read().prefill_state(root).unwrap(); + assert!( + !state.is_ready(), + "root must not be ready without the fence" + ); + + let err = backend + .fork_sequence(root, branches[0]) + .expect_err("BACKEND_FORK_VIOLATION: fork before the prefill fence must be refused"); + assert!( + err.contains("not ready"), + "unexpected refusal reason: {err}" + ); + assert!( + !backend.sequences.contains_key(&branches[0]), + "a refused fork must not create backend state" + ); + + // Parent unknown to the KV manager is refused too. + assert!(backend.fork_sequence(9_999_999, 9_999_998).is_err()); +} + +#[tokio::test] +async fn backend_decode_of_unknown_request_id_is_an_error() { + let config = c4_config(); + let weights = TransformerWeights::reference_test_weights(&config); + let (_spine, mut backend) = build_shared_kv_runtime( + weights, + Arc::new(ReferenceCpuBackend::new()), + c4_scheduler(), + SharedKvSizing { + arena_capacity: 64, + total_blocks: 64, + }, + ) + .expect("build shared KV runtime"); + + let unknown = 4_242_424u64; + let direct = backend.forward_decode_batch(&[unknown]); + assert!( + direct.is_err(), + "DECODE_STATE_VIOLATION: decoding an unknown request id must be an error, got {:?}", + direct.ok() + ); + assert!( + !backend.sequences.contains_key(&unknown), + "DECODE_STATE_VIOLATION: a refused decode must not create an empty sequence state" + ); + + let batch = ScheduledBatch { + prefill_requests: Vec::new(), + decode_requests: vec![unknown], + block_tables: HashMap::new(), + step_id: 1, + }; + assert!( + backend.execute_step(&batch).await.is_err(), + "DECODE_STATE_VIOLATION: execute_step must refuse a decode of an unknown request id" + ); + assert!(!backend.sequences.contains_key(&unknown)); +} + +#[tokio::test] +async fn branch_first_decode_logits_equal_root_continuation_logits() { + let config = c4_config(); + let weights = TransformerWeights::reference_test_weights(&config); + let (mut spine, backend) = build_shared_kv_runtime( + weights.clone(), + Arc::new(ReferenceCpuBackend::new()), + c4_scheduler(), + SharedKvSizing { + arena_capacity: 64, + total_blocks: 64, + }, + ) + .expect("build shared KV runtime"); + let mut tap = LogitsTap { + inner: backend, + decode_logits: HashMap::new(), + first_decode_tokens: HashMap::new(), + }; + + let branch_count = 3usize; + let swarm_id = spine + .launch_swarm(c4_swarm_config(branch_count, 2), &C4_PROMPT) + .expect("launch swarm"); + let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone(); + let root = swarm.root_sequence_id.as_u64(); + let branches: Vec = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect(); + + let mut steps = 0; + while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) && steps < 50 + { + steps += 1; + spine.step(&mut tap).await.expect("spine step"); + } + assert_eq!( + spine.scheduler.metrics().finished_requests as usize, + branch_count, + "every branch must finish" + ); + + // Root's own continuation, computed independently: a fresh backend with + // its own pooled KV prefills the same prompt under the same request id + // (prefill sampling is seeded by request id) and decodes one step. + let mut control = NativeTransformerBackend::with_paged_kv(weights, 64, config.block_size) + .expect("control backend"); + let control_batch = ScheduledBatch { + prefill_requests: vec![SequenceRequest { + request_id: root, + prompt_tokens: C4_PROMPT.to_vec(), + sampling_params: SamplingParams::default(), + arrival_time_ns: 0, + priority: 1, + }], + decode_requests: Vec::new(), + block_tables: HashMap::new(), + step_id: 1, + }; + control + .execute_step(&control_batch) + .await + .expect("control prefill"); + assert_eq!( + control.sequences.get(&root).map(|s| s.tokens.clone()), + tap.inner.sequences.get(&root).map(|s| s.tokens.clone()), + "control root must hold the same tokens as the spine root after prefill" + ); + let (_out, control_logits) = control + .forward_decode_batch_with_logits(&[root]) + .expect("control root continuation"); + let root_logits = &control_logits[0]; + assert!(root_logits.iter().any(|x| *x != 0.0)); + + for &b in &branches { + let first = tap + .decode_logits + .get(&b) + .and_then(|v| v.first()) + .unwrap_or_else(|| panic!("branch {} never decoded", b)); + assert_eq!(first.len(), root_logits.len()); + let max_diff = first + .iter() + .zip(root_logits.iter()) + .map(|(a, c)| (a - c).abs()) + .fold(0.0f32, f32::max); + assert!( + max_diff <= PARITY_TOL, + "BACKEND_FORK_VIOLATION: branch {} step-1 logits differ from the root's own \ + continuation by {} (> {})", + b, + max_diff, + PARITY_TOL + ); + } +} + +/// C4c: the token prefill sampled but did not append (`pending_prefill_token`) +/// belongs to the root's stream. `fork_sequence` must give each child that token +/// appended to its own copy of the parent's tokens WITHOUT mutating the parent, so every +/// branch's first decode feeds that token at +/// position `prompt_len`, exactly like the root's own continuation. +#[tokio::test] +async fn backend_fork_carries_parent_pending_prefill_token() { + let config = c4_config(); + let weights = TransformerWeights::reference_test_weights(&config); + let (mut spine, backend) = build_shared_kv_runtime( + weights, + Arc::new(ReferenceCpuBackend::new()), + c4_scheduler(), + SharedKvSizing { + arena_capacity: 64, + total_blocks: 64, + }, + ) + .expect("build shared KV runtime"); + let mut tap = LogitsTap { + inner: backend, + decode_logits: HashMap::new(), + first_decode_tokens: HashMap::new(), + }; + + let branch_count = 3usize; + let swarm_id = spine + .launch_swarm(c4_swarm_config(branch_count, 2), &C4_PROMPT) + .expect("launch swarm"); + let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone(); + let root = swarm.root_sequence_id.as_u64(); + let branches: Vec = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect(); + + let mut steps = 0; + while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) && steps < 50 + { + steps += 1; + spine.step(&mut tap).await.expect("spine step"); + } + + let root_tokens = tap + .inner + .sequences + .get(&root) + .expect("root state") + .tokens + .clone(); + assert_eq!( + root_tokens, + C4_PROMPT.to_vec(), + "fork must not mutate the parent: root tokens stay the prompt only" + ); + let pending = *tap + .inner + .pending_prefill_token + .get(&root) + .expect("fork must leave the parent's pending prefill token untouched"); + let mut expected_child = root_tokens.clone(); + expected_child.push(pending); + for &b in &branches { + let first = tap + .first_decode_tokens + .get(&b) + .unwrap_or_else(|| panic!("branch {} never decoded", b)); + assert_eq!( + first, &expected_child, + "PENDING_TOKEN_VIOLATION: branch {} must start its first decode from the root's \ + prompt plus the sampled token", + b + ); + } +} diff --git a/crates/aien-scheduler/src/lib.rs b/crates/aien-scheduler/src/lib.rs index c39464e7..bab2695d 100644 --- a/crates/aien-scheduler/src/lib.rs +++ b/crates/aien-scheduler/src/lib.rs @@ -272,6 +272,19 @@ impl AienScheduler { child_raw: u64, sink_id: Option, ) -> Result<(), String> { + self.fork_subagent_with_sink_ids(parent_raw, child_raw, sink_id) + .map(|_| ()) + } + + /// Same as `fork_subagent_with_sink`, returning the (parent, child) KV + /// sequence ids the fork was recorded under, so the runtime can fork the + /// backend's per-sequence state under the same ids (PREFILL-E2E C4). + pub fn fork_subagent_with_sink_ids( + &mut self, + parent_raw: u64, + child_raw: u64, + sink_id: Option, + ) -> Result<(u64, u64), String> { let parent_id = self .running_sequences .iter() @@ -286,14 +299,19 @@ impl AienScheduler { let child_id = self.arena.fork(parent_id, sink_id)?; - { + let kv_ids = { let mut kv = self.kv_manager.write(); - kv.fork_sequence(parent_id.to_u64(), child_id.to_u64()) - .or_else(|_| kv.fork_sequence(parent_raw, child_raw))?; - } + match kv.fork_sequence(parent_id.to_u64(), child_id.to_u64()) { + Ok(_) => (parent_id.to_u64(), child_id.to_u64()), + Err(_) => { + kv.fork_sequence(parent_raw, child_raw)?; + (parent_raw, child_raw) + } + } + }; self.running_sequences.push(child_id); - Ok(()) + Ok(kv_ids) } /// Discards stale items from queue heads and internal lists without panics.