diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index a8aed47b..0ab9b5f2 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -255,6 +255,21 @@ pub trait AienInferenceBackend: Send + Sync { Ok(()) } + /// PREFILL-E2E C6 (bullet 11): `fork_sequence` that also hands the + /// backend the child's own sampling params, so a branch decodes with its + /// request's temperature/top_p instead of argmax. Decode batches carry + /// only request ids (`ScheduledBatch::decode_requests`), so the fork hook + /// is where a branch's params reach the backend. + /// Default: plain `fork_sequence` (params ignored). + fn fork_sequence_with_sampling( + &mut self, + parent_id: u64, + child_id: u64, + _sampling: &SamplingParams, + ) -> Result<(), String> { + self.fork_sequence(parent_id, child_id) + } + /// Drops the backend's per-sequence state for `seq_id` (PREFILL-E2E /// bullet 12). The runtime spine calls it for every finished branch, for /// the swarm root once its last branch finished, and for every sequence of diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 355158a1..0ea923dd 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -8,7 +8,7 @@ use crate::tensor::{sample_argmax, sample_temperature}; use crate::weights::{LayerKvCache, SequenceState, TransformerWeights}; use crate::{ AienInferenceBackend, AienUsageReceipt, BranchHandle, ContextHandle, DecodeOutput, - FinishReason, ModelConfig, ScheduledBatch, StepMetrics, + FinishReason, ModelConfig, SamplingParams, ScheduledBatch, StepMetrics, }; use aien_kv_cache::{create_shared_kv_manager_with_pool, KvDType, KvPoolConfig, SharedKvManager}; use async_trait::async_trait; @@ -18,6 +18,85 @@ use std::sync::Arc; static NEXT_HANDLE_ID: AtomicU64 = AtomicU64::new(1); +/// splitmix64 mixing step (the generator behind java.util.SplittableRandom): +/// a bijective 64-bit mixer, in-house, no outside crate. +fn splitmix64(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Deterministic seed for sampling the token at `position` (the sequence's +/// token count before the new token) of request `request_id` (PREFILL-E2E +/// C6). Swarm branches get distinct request ids from the runtime arena +/// (`AienRuntimeSpine::launch_swarm` submits each branch with +/// `request_id: child_seq.as_u64()`), so sibling branches forked from one +/// root draw different streams; the same request replays the same stream. +pub fn decode_sampling_seed(request_id: u64, position: usize) -> u64 { + splitmix64(request_id ^ splitmix64(position as u64)) +} + +/// Samples one token from `logits` under `params` with the given seed. +/// - `temperature <= 0.001`: argmax (unchanged greedy path). +/// - otherwise softmax(logits / temperature) in f64; if `0 < top_p < 1` +/// only the smallest highest-probability set whose mass reaches `top_p` +/// is kept (ties broken by lower token id); one uniform draw from the +/// seed picks a token from the kept mass. (`SamplingParams` has no top-k +/// field, so there is no top-k.) +/// +/// Returns the token and its log-probability under the kept distribution. +pub fn sample_with_params(logits: &[f32], params: &SamplingParams, seed: u64) -> (u32, f32) { + if params.temperature <= 0.001 { + return sample_argmax(logits); + } + assert!(!logits.is_empty(), "Logits cannot be empty"); + let inv_t = 1.0f64 / params.temperature as f64; + let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v)) as f64; + let mut probs: Vec = logits + .iter() + .map(|&v| ((v as f64 - max) * inv_t).exp()) + .collect(); + let sum: f64 = probs.iter().sum(); + for p in probs.iter_mut() { + *p /= sum; + } + + let mut kept: Vec = (0..probs.len()).collect(); + let top_p = params.top_p as f64; + if top_p > 0.0 && top_p < 1.0 { + kept.sort_by(|&a, &b| { + probs[b] + .partial_cmp(&probs[a]) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.cmp(&b)) + }); + let mut cum = 0.0f64; + let mut keep = 0usize; + for &i in &kept { + cum += probs[i]; + keep += 1; + if cum >= top_p { + break; + } + } + kept.truncate(keep); + } + + let mass: f64 = kept.iter().map(|&i| probs[i]).sum(); + // 53 random bits -> uniform in [0, 1), scaled to the kept mass. + let r = ((seed >> 11) as f64 / (1u64 << 53) as f64) * mass; + let mut cum = 0.0f64; + for &i in &kept { + cum += probs[i]; + if r < cum { + return (i as u32, (probs[i] / mass).max(1e-300).ln() as f32); + } + } + let last = *kept.last().expect("kept set is never empty"); + (last as u32, (probs[last] / mass).max(1e-300).ln() as f32) +} + /// Fully native Rust transformer backend executing real tensor forward computation. /// Decouples execution orchestration from compute hardware via the TensorBackend trait. pub struct NativeTransformerBackend { @@ -25,6 +104,11 @@ pub struct NativeTransformerBackend { pub sequences: HashMap, pub tensor_backend: Arc, pub kv_manager: Option, + /// Per-request sampling params used by decode (PREFILL-E2E C6). Recorded + /// from the prefill request (`execute_step`) and from the fork hook + /// (`fork_sequence_with_sampling`; a plain `fork_sequence` child inherits + /// its parent's entry). A request with no entry decodes with argmax. + sampling: HashMap, /// Token sampled after the most recent `execute_step` prefill chunk of a request, /// not yet appended to `sequences[id].tokens`. A prefill request does not say /// whether it is the final chunk of its prompt, so the sample is held here: @@ -40,6 +124,7 @@ impl NativeTransformerBackend { Self { weights, sequences: HashMap::new(), + sampling: HashMap::new(), tensor_backend: Arc::new(ReferenceCpuBackend::new()), kv_manager: None, pending_prefill_token: HashMap::new(), @@ -54,6 +139,7 @@ impl NativeTransformerBackend { Self { weights, sequences: HashMap::new(), + sampling: HashMap::new(), tensor_backend, kv_manager: None, pending_prefill_token: HashMap::new(), @@ -111,6 +197,7 @@ impl NativeTransformerBackend { Ok(Self { weights, sequences: HashMap::new(), + sampling: HashMap::new(), tensor_backend: Arc::new(ReferenceCpuBackend::new()), kv_manager: Some(kv_mgr), pending_prefill_token: HashMap::new(), @@ -136,6 +223,7 @@ impl NativeTransformerBackend { Ok(Self { weights, sequences: HashMap::new(), + sampling: HashMap::new(), tensor_backend, kv_manager: Some(kv_mgr), pending_prefill_token: HashMap::new(), @@ -151,12 +239,19 @@ impl NativeTransformerBackend { Self { weights, sequences: HashMap::new(), + sampling: HashMap::new(), tensor_backend, kv_manager: Some(kv_manager), pending_prefill_token: HashMap::new(), } } + /// Sampling params decode will use for `request_id`, if any were recorded + /// (PREFILL-E2E C6). `None` means decode takes the argmax. + pub fn sampling_params(&self, request_id: u64) -> Option<&SamplingParams> { + self.sampling.get(&request_id) + } + /// Creates a new immutable root context from prompt tokens. pub fn prefill_sequence( &mut self, @@ -1376,9 +1471,18 @@ impl NativeTransformerBackend { crate::tokenizer::TinyLlamaTokenizer::EOS_TOKEN_ID, ]; - for (i, &(seq_id, _, _)) in valid_reqs.iter().enumerate() { + for (i, &(seq_id, _, pos)) in valid_reqs.iter().enumerate() { let logits = &logits_batch[i * vocab_size..(i + 1) * vocab_size]; - let (sampled_tok, logprob) = sample_argmax(logits); + // PREFILL-E2E C6: the request's own sampling params (recorded at + // prefill or by the fork hook), seeded per request and position. + // No params, or temperature 0: argmax as before. + let (sampled_tok, logprob) = match self.sampling.get(&seq_id) { + Some(params) => { + let seed = decode_sampling_seed(seq_id, pos + 1); + sample_with_params(logits, params, seed) + } + None => sample_argmax(logits), + }; if let Some(seq) = self.sequences.get_mut(&seq_id) { seq.tokens.push(sampled_tok); @@ -1408,6 +1512,7 @@ impl AienInferenceBackend for NativeTransformerBackend { async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> { self.weights = TransformerWeights::reference_test_weights(config); self.sequences.clear(); + self.sampling.clear(); self.pending_prefill_token.clear(); Ok(()) } @@ -1499,6 +1604,24 @@ impl AienInferenceBackend for NativeTransformerBackend { layers: Vec::new(), }, ); + // PREFILL-E2E C6: a plain fork inherits the parent's sampling params + // (seeded by the child's own id at decode, so streams still differ). + if let Some(params) = self.sampling.get(&parent_id).cloned() { + self.sampling.insert(child_id, params); + } + Ok(()) + } + + /// PREFILL-E2E C6: same checks and state fork as `fork_sequence`, then + /// records the branch's own sampling params for decode. + fn fork_sequence_with_sampling( + &mut self, + parent_id: u64, + child_id: u64, + sampling: &SamplingParams, + ) -> Result<(), String> { + self.fork_sequence(parent_id, child_id)?; + self.sampling.insert(child_id, sampling.clone()); Ok(()) } @@ -1513,6 +1636,8 @@ impl AienInferenceBackend for NativeTransformerBackend { fn release_sequence(&mut self, seq_id: u64) -> Result<(), String> { self.sequences.remove(&seq_id); self.pending_prefill_token.remove(&seq_id); + // PREFILL-E2E C6: the per-request sampling params entry goes too. + self.sampling.remove(&seq_id); Ok(()) } @@ -1528,6 +1653,9 @@ impl AienInferenceBackend for NativeTransformerBackend { // 1. Prefill Requests for req in &batch.prefill_requests { prefill_tokens += req.prompt_tokens.len(); + // PREFILL-E2E C6: decode of this request uses its sampling params. + self.sampling + .insert(req.request_id, req.sampling_params.clone()); // A further prefill chunk: the sample held from the previous chunk was // mid-prompt and is discarded. self.pending_prefill_token.remove(&req.request_id); diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 5b0b930e..4caf2e30 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -283,13 +283,22 @@ impl AienRuntimeSpine { // 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 + // PREFILL-E2E C6 (bullet 11): the fork hook also hands each + // branch its own sampling params (the same ones its scheduler + // request carries), so branches decode with temperature and a + // per-branch seed instead of all taking the argmax. + let (branches, sampling): (Vec, SamplingParams) = self .swarm_manager .get_swarm(swarm_id) - .map(|s| s.branch_sequences.iter().map(|b| b.as_u64()).collect()) - .unwrap_or_default(); + .map(|s| { + ( + s.branch_sequences.iter().map(|b| b.as_u64()).collect(), + branch_sampling_params(&s.config), + ) + }) + .unwrap_or_else(|| (Vec::new(), SamplingParams::default())); for child in branches { - backend.fork_sequence(root_kv_id, child)?; + backend.fork_sequence_with_sampling(root_kv_id, child, &sampling)?; } } Ok(prefilled) @@ -319,12 +328,7 @@ impl AienRuntimeSpine { let req = aien_inference_abi::SequenceRequest { request_id: child_seq.as_u64(), prompt_tokens: prompt_tokens.to_vec(), - sampling_params: aien_inference_abi::SamplingParams { - temperature: 0.7, - top_p: 0.95, - max_tokens: swarm.config.max_tokens_per_branch, - stop_token_ids: vec![2], - }, + sampling_params: branch_sampling_params(&swarm.config), arrival_time_ns: self.step_counter, priority: swarm.config.priority, }; @@ -458,3 +462,15 @@ impl AienRuntimeSpine { } } } + +/// Sampling params of every swarm branch: submitted with the branch's +/// scheduler request (`launch_swarm`) and handed to the backend by the fork +/// hook (`prefill_pending_swarm_roots`), so both sides agree. +fn branch_sampling_params(config: &SwarmConfig) -> SamplingParams { + SamplingParams { + temperature: 0.7, + top_p: 0.95, + max_tokens: config.max_tokens_per_branch, + stop_token_ids: vec![2], + } +} diff --git a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs index 7ef0a3bb..152c1195 100644 --- a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs +++ b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs @@ -25,6 +25,18 @@ //! 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. +//! +//! PREFILL-E2E C6 (bullet 11, "no branch can observe another branch's +//! suffix"): branches now decode with their own sampling params (handed over +//! by `fork_sequence_with_sampling`) and a per-request seed, so they diverge. +//! `sampled_branches_diverge_and_each_matches_its_own_teacher_forced_control` +//! checks that two or more branches produce different tokens, and that every +//! decode step of each branch has the same logits (abs 1e-5) as a fresh +//! unpaged backend fed the root prompt + root token + that branch's own +//! generated tokens. Mutants (outside the repo): ~/workspace/hive/PE2E-C6/ +//! mutant.patch makes each decode row write its K/V into its sibling's slot +//! (parity fails: BRANCH_ISOLATION_VIOLATION); mutant_a.patch seeds every +//! branch identically (divergence fails: BRANCH_DIVERGENCE_VIOLATION). use std::collections::HashMap; @@ -321,6 +333,10 @@ const C4_PROMPT: [u32; 6] = [5, 17, 42, 3, 88, 61]; struct LogitsTap { inner: NativeTransformerBackend, decode_logits: HashMap>>, + /// Token each decode step sampled, per sequence (C6). + decode_tokens: HashMap>, + /// Per decode batch: (id, last token fed) for every row (C6). + decode_batches: Vec>, /// Each sequence's backend token stream as it was just before its first decode. first_decode_tokens: HashMap>, } @@ -347,6 +363,20 @@ impl AienInferenceBackend for LogitsTap { metrics = m; } if !batch.decode_requests.is_empty() { + let fed: Vec<(u64, u32)> = batch + .decode_requests + .iter() + .map(|id| { + let last = self + .inner + .sequences + .get(id) + .and_then(|s| s.tokens.last().copied()) + .unwrap_or(u32::MAX); + (*id, last) + }) + .collect(); + self.decode_batches.push(fed); for id in &batch.decode_requests { if let Some(seq) = self.inner.sequences.get(id) { self.first_decode_tokens @@ -359,6 +389,9 @@ impl AienInferenceBackend for LogitsTap { .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); + if let Some(tok) = self.inner.sequences.get(id).and_then(|s| s.tokens.last()) { + self.decode_tokens.entry(*id).or_default().push(*tok); + } } outputs.extend(o); metrics.decode_tokens_emitted += batch.decode_requests.len(); @@ -373,6 +406,16 @@ impl AienInferenceBackend for LogitsTap { fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> { self.inner.fork_sequence(parent_id, child_id) } + + fn fork_sequence_with_sampling( + &mut self, + parent_id: u64, + child_id: u64, + sampling: &SamplingParams, + ) -> Result<(), String> { + self.inner + .fork_sequence_with_sampling(parent_id, child_id, sampling) + } } fn c4_swarm_config(branch_count: usize, max_tokens: usize) -> SwarmConfig { @@ -517,6 +560,8 @@ async fn branch_first_decode_logits_equal_root_continuation_logits() { let mut tap = LogitsTap { inner: backend, decode_logits: HashMap::new(), + decode_tokens: HashMap::new(), + decode_batches: Vec::new(), first_decode_tokens: HashMap::new(), }; @@ -617,6 +662,8 @@ async fn backend_fork_carries_parent_pending_prefill_token() { let mut tap = LogitsTap { inner: backend, decode_logits: HashMap::new(), + decode_tokens: HashMap::new(), + decode_batches: Vec::new(), first_decode_tokens: HashMap::new(), }; @@ -667,3 +714,165 @@ async fn backend_fork_carries_parent_pending_prefill_token() { ); } } + +/// PREFILL-E2E C6, bullet 11: sampled branches diverge, and no branch sees +/// another branch's suffix. Reference weights, CPU, spine + scheduler + one +/// pooled KV (`build_shared_kv_runtime`). +#[tokio::test] +async fn sampled_branches_diverge_and_each_matches_its_own_teacher_forced_control() { + 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(), + decode_tokens: HashMap::new(), + decode_batches: Vec::new(), + first_decode_tokens: HashMap::new(), + }; + + let branch_count = 3usize; + let max_tokens = 8usize; + let swarm_id = spine + .launch_swarm(c4_swarm_config(branch_count, max_tokens), &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 < 100 + { + 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" + ); + + // The fork hook carried each branch's own sampling params. + for &b in &branches { + let params = tap.inner.sampling_params(b).unwrap_or_else(|| { + panic!( + "BRANCH_SAMPLING_VIOLATION: branch {} has no sampling params (fork hook did not carry them)", + b + ) + }); + assert!( + params.temperature > 0.001, + "branch {} must sample (temperature {})", + b, + params.temperature + ); + } + + let generated: Vec> = branches + .iter() + .map(|b| tap.decode_tokens.get(b).cloned().unwrap_or_default()) + .collect(); + for (b, g) in branches.iter().zip(&generated) { + assert!(!g.is_empty(), "branch {} never decoded", b); + } + + // 1. Divergence: with temperature > 0 and per-branch seeds the branches + // must not all generate the same tokens. + assert!( + generated.iter().any(|g| *g != generated[0]), + "BRANCH_DIVERGENCE_VIOLATION: all {} branches generated identical tokens {:?}", + branch_count, + generated + ); + + // Precondition for 2: some decode batch held two or more branches fed + // different tokens, so a cross-branch K/V mixup would change logits. + assert!( + tap.decode_batches.iter().any(|rows| { + let fed: Vec = rows + .iter() + .filter(|(id, _)| branches.contains(id)) + .map(|(_, t)| *t) + .collect(); + fed.len() >= 2 && fed.iter().any(|t| *t != fed[0]) + }), + "C6 precondition: no decode batch held two branches with different inputs ({:?})", + tap.decode_batches + ); + + // 2. Isolation: each branch's per-step logits equal a teacher-forced, + // independent control (fresh unpaged backend, dense private K/V) fed + // the root prompt, the root's sampled token and only that branch's own + // generated tokens. + let root_tokens = tap + .inner + .sequences + .get(&root) + .expect("root backend state") + .tokens + .clone(); + // C4 semantics: the root keeps prompt-only tokens; the sampled prefill token + // stays pending and each fork child carries it. + assert_eq!(root_tokens, C4_PROMPT.to_vec()); + let root_token = *tap + .inner + .pending_prefill_token + .get(&root) + .expect("root pending prefill token"); + + for (b, gen) in branches.iter().zip(&generated) { + let branch_logits = tap.decode_logits.get(b).expect("branch logits"); + assert_eq!(branch_logits.len(), gen.len()); + + let ctl_id = 1u64; + let mut control = NativeTransformerBackend::new(weights.clone()); + assert!(control.kv_manager.is_none(), "control must be unpaged"); + control + .prefill_sequence(ctl_id, &C4_PROMPT) + .expect("control prefill"); + control + .sequences + .get_mut(&ctl_id) + .unwrap() + .tokens + .push(root_token); + + for (k, row) in branch_logits.iter().enumerate() { + let (_out, ctl_logits) = control + .forward_decode_batch_with_logits(&[ctl_id]) + .expect("control decode"); + let ctl_row = &ctl_logits[0]; + assert_eq!(row.len(), ctl_row.len()); + assert!(ctl_row.iter().any(|x| *x != 0.0)); + let max_diff = row + .iter() + .zip(ctl_row.iter()) + .map(|(a, c)| (a - c).abs()) + .fold(0.0f32, f32::max); + assert!( + max_diff <= PARITY_TOL, + "BRANCH_ISOLATION_VIOLATION: branch {} step {} logits differ from its own \ + teacher-forced control by {} (> {})", + b, + k + 1, + max_diff, + PARITY_TOL + ); + // Teacher forcing: replace the control's own pick with the token + // this branch actually generated at this step. + let seq = control.sequences.get_mut(&ctl_id).unwrap(); + seq.tokens.pop(); + seq.tokens.push(gen[k]); + } + } +} diff --git a/crates/aien-runtime/tests/swarm_reclaim_test.rs b/crates/aien-runtime/tests/swarm_reclaim_test.rs index 0c7731a5..64d09436 100644 --- a/crates/aien-runtime/tests/swarm_reclaim_test.rs +++ b/crates/aien-runtime/tests/swarm_reclaim_test.rs @@ -152,6 +152,15 @@ fn assert_fully_reclaimed( .map(|b| b.as_u64()) .collect::>() ); + // C6 x C5: the sampling map entry is dropped with the sequence. + assert!( + backend.sampling_params(swarm.root_sequence_id.as_u64()).is_none() + && swarm + .branch_sequences + .iter() + .all(|b| backend.sampling_params(b.as_u64()).is_none()), + "RECLAIM_VIOLATION: RECLAIM_SAMPLING_LEAK backend still holds sampling params for a released sequence" + ); let kv = spine.kv_manager.read(); assert_eq!( kv.allocated_block_count(),