interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / tests / swarm_prefill_gate_test.rs

1035 lines · 37435 bytes Raw Blame History
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-GATE end to end: a launched swarm must run the root prompt through
17//! the model before any branch decodes.
18//!
19//! Uses only APIs that already exist on main (cfd9982), so this file also runs
20//! against main, where it must FAIL (see scripts/prefill-gate/fails-on-main.sh):
21//! on main SwarmManager::launch_swarm forks branches from allocated-but-zeroed
22//! root blocks (crates/aien-runtime/src/swarm.rs:95-111 at cfd9982) and the
23//! scheduler decodes them with no prefill at all.
24//!
25//! The stock MockInferenceBackend ignores prompt content, so this test uses a
26//! recording backend that logs every prefill span and every decode, in order.
27//!
28//! PREFILL-E2E C4 (bullets 6, 7, 8) extends it: the recording backend also
29//! logs the backend fork hook (`fork_sequence`) together with the parent's
30//! KV prefill state at that moment, and refuses a fork whose parent is not
31//! ready. The swarm test asserts the order prefill fence -> fork_sequence per
32//! branch -> first decode. Further tests drive the real
33//! NativeTransformerBackend (reference weights, CPU) through spine +
34//! scheduler + one pooled KV: a fork before the fence is refused, a decode
35//! of an unknown id is an error, and each branch's first decode logits equal
36//! the root's own continuation logits (abs 1e-5).
37//!
38//! Mutant (outside the repo, ~/workspace/hive/PE2E-C4/mutant.patch): the
39//! spine no longer calls `fork_sequence` and `forward_decode_batch` again
40//! creates an empty state (`or_insert_with`) for an unknown id. Then no Fork
41//! events are recorded, the unknown-id decode is accepted, and branches decode
42//! from token 1 at position 0, so the tests below fail.
43//!
44//! PREFILL-E2E C6 (bullet 11, "no branch can observe another branch's
45//! suffix"): branches now decode with their own sampling params (handed over
46//! by `fork_sequence_with_sampling`) and a per-request seed, so they diverge.
47//! `sampled_branches_diverge_and_each_matches_its_own_teacher_forced_control`
48//! checks that two or more branches produce different tokens, and that every
49//! decode step of each branch has the same logits (abs 1e-5) as a fresh
50//! unpaged backend fed the root prompt + root token + that branch's own
51//! generated tokens. Mutants (outside the repo): ~/workspace/hive/PE2E-C6/
52//! mutant.patch makes each decode row write its K/V into its sibling's slot
53//! (parity fails: BRANCH_ISOLATION_VIOLATION); mutant_a.patch seeds every
54//! branch identically (divergence fails: BRANCH_DIVERGENCE_VIOLATION).
55
56use std::collections::HashMap;
57
58use std::sync::Arc;
59
60use aien_inference_abi::{
61 AienInferenceBackend, DecodeOutput, ModelConfig, NativeTransformerBackend, ReferenceCpuBackend,
62 SamplingParams, ScheduledBatch, SequenceRequest, StepMetrics, TransformerWeights,
63};
64use aien_kv_cache::{create_shared_kv_manager, SharedKvManager};
65use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing};
66use aien_runtime::spine::AienRuntimeSpine;
67use aien_runtime::swarm::SwarmConfig;
68use aien_scheduler::SchedulerConfig;
69use async_trait::async_trait;
70
71#[derive(Debug, Clone)]
72enum Event {
73 Prefill {
74 id: u64,
75 tokens: Vec<u32>,
76 },
77 Decode {
78 id: u64,
79 },
80 Fork {
81 parent: u64,
82 child: u64,
83 parent_ready: bool,
84 },
85}
86
87#[derive(Default)]
88struct RecordingBackend {
89 events: Vec<Event>,
90 /// The spine's KV manager, read in `fork_sequence` to record (and gate on)
91 /// whether the parent passed the prefill completion fence.
92 kv: Option<SharedKvManager>,
93}
94
95#[async_trait]
96impl AienInferenceBackend for RecordingBackend {
97 async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> {
98 Ok(())
99 }
100
101 async fn execute_step(
102 &mut self,
103 batch: &ScheduledBatch,
104 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
105 let mut outputs = Vec::new();
106 let mut prefill_tokens = 0;
107 for req in &batch.prefill_requests {
108 prefill_tokens += req.prompt_tokens.len();
109 self.events.push(Event::Prefill {
110 id: req.request_id,
111 tokens: req.prompt_tokens.clone(),
112 });
113 outputs.push(DecodeOutput::Token {
114 request_id: req.request_id,
115 token_id: 100,
116 logprob: None,
117 });
118 }
119 for &id in &batch.decode_requests {
120 self.events.push(Event::Decode { id });
121 outputs.push(DecodeOutput::Token {
122 request_id: id,
123 token_id: 101,
124 logprob: None,
125 });
126 }
127 let metrics = StepMetrics {
128 prefill_tokens_processed: prefill_tokens,
129 decode_tokens_emitted: batch.decode_requests.len() + batch.prefill_requests.len(),
130 step_latency_us: 0,
131 active_kv_blocks: batch.block_tables.values().map(|v| v.len()).sum(),
132 };
133 Ok((outputs, metrics))
134 }
135
136 fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> {
137 let parent_ready = self
138 .kv
139 .as_ref()
140 .and_then(|kv| kv.read().prefill_state(parent_id))
141 .map(|s| s.is_ready())
142 .unwrap_or(false);
143 self.events.push(Event::Fork {
144 parent: parent_id,
145 child: child_id,
146 parent_ready,
147 });
148 if parent_ready {
149 Ok(())
150 } else {
151 Err(format!(
152 "recording backend: fork {} -> {} refused, parent not PrefillReady",
153 parent_id, child_id
154 ))
155 }
156 }
157}
158
159#[tokio::test]
160async fn prefill_gate_swarm_branches_never_decode_before_root_prompt_prefill() {
161 let kv_manager = create_shared_kv_manager(256, 16);
162 let sched_cfg = SchedulerConfig {
163 max_batch_size: 32,
164 max_batch_tokens: 2048,
165 max_prefill_tokens: 1024,
166 prefill_chunk_size: 16,
167 chunk_prefill: true,
168 watermark_blocks: 4,
169 };
170 let mut spine = AienRuntimeSpine::new(64, sched_cfg, kv_manager.clone());
171 let mut backend = RecordingBackend {
172 kv: Some(kv_manager.clone()),
173 ..RecordingBackend::default()
174 };
175
176 let prompt: Vec<u32> = (500..540).collect();
177 let branch_count = 4usize;
178 let config = SwarmConfig {
179 model_handle: 1,
180 branch_count,
181 max_active_sequences: branch_count,
182 max_tokens_per_branch: 3,
183 root_world_id: 0,
184 priority: 1,
185 };
186 let swarm_id = spine.launch_swarm(config, &prompt).expect("launch");
187 let swarm = spine
188 .swarm_manager
189 .get_swarm(swarm_id)
190 .expect("swarm record")
191 .clone();
192 let root = swarm.root_sequence_id.as_u64();
193 let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect();
194
195 let mut steps = 0;
196 while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0)
197 && steps < 100
198 {
199 steps += 1;
200 spine.step(&mut backend).await.expect("step");
201 }
202
203 // Replay the backend log in order. Every branch decode must come after
204 // the full prompt was run through the model, for the shared root or for
205 // that branch itself.
206 let mut prefilled: HashMap<u64, Vec<u32>> = HashMap::new();
207 let mut branch_decodes = 0usize;
208 let covers_prompt = |seen: Option<&Vec<u32>>| {
209 seen.map(|s| s.len() >= prompt.len() && s[..prompt.len()] == prompt[..])
210 .unwrap_or(false)
211 };
212 for event in &backend.events {
213 match event {
214 Event::Prefill { id, tokens } => {
215 prefilled.entry(*id).or_default().extend_from_slice(tokens);
216 }
217 Event::Decode { id } => {
218 if branches.contains(id) {
219 branch_decodes += 1;
220 assert!(
221 covers_prompt(prefilled.get(&root)) || covers_prompt(prefilled.get(id)),
222 "PREFILL_GATE_VIOLATION: branch {} decoded before its prompt was prefilled \
223 (root prefilled {:?} tokens, branch prefilled {:?} tokens, prompt {} tokens)",
224 id,
225 prefilled.get(&root).map(|v| v.len()),
226 prefilled.get(id).map(|v| v.len()),
227 prompt.len()
228 );
229 }
230 }
231 Event::Fork { .. } => {}
232 }
233 }
234
235 // PREFILL-E2E C4 order: prefill fence -> fork_sequence per branch -> first decode.
236 let last_root_prefill = backend
237 .events
238 .iter()
239 .rposition(|e| matches!(e, Event::Prefill { id, .. } if *id == root))
240 .expect("root prompt must be prefilled");
241 for &b in &branches {
242 let forks: Vec<usize> = backend
243 .events
244 .iter()
245 .enumerate()
246 .filter(|(_, e)| matches!(e, Event::Fork { child, .. } if *child == b))
247 .map(|(i, _)| i)
248 .collect();
249 assert_eq!(
250 forks.len(),
251 1,
252 "BACKEND_FORK_VIOLATION: branch {} must be forked in the backend exactly once, got {}",
253 b,
254 forks.len()
255 );
256 let fork_at = forks[0];
257 match &backend.events[fork_at] {
258 Event::Fork {
259 parent,
260 parent_ready,
261 ..
262 } => {
263 assert_eq!(
264 *parent, root,
265 "branch {} forked from {} not root",
266 b, parent
267 );
268 assert!(
269 *parent_ready,
270 "BACKEND_FORK_VIOLATION: branch {} forked before the root prefill fence",
271 b
272 );
273 }
274 _ => unreachable!(),
275 }
276 assert!(
277 fork_at > last_root_prefill,
278 "BACKEND_FORK_VIOLATION: branch {} forked (event {}) before the last root prefill chunk (event {})",
279 b,
280 fork_at,
281 last_root_prefill
282 );
283 let first_decode = backend
284 .events
285 .iter()
286 .position(|e| matches!(e, Event::Decode { id } if *id == b))
287 .expect("every branch decodes");
288 assert!(
289 fork_at < first_decode,
290 "BACKEND_FORK_VIOLATION: branch {} decoded (event {}) before its backend fork (event {})",
291 b,
292 first_decode,
293 fork_at
294 );
295 }
296
297 assert!(
298 branch_decodes > 0,
299 "branches must decode once the root prompt is prefilled"
300 );
301 assert_eq!(
302 spine.scheduler.metrics().finished_requests as usize,
303 branch_count,
304 "every branch must finish"
305 );
306}
307
308// ---------------------------------------------------------------------------
309// PREFILL-E2E C4: real NativeTransformerBackend (reference weights, CPU)
310// through spine + scheduler + one pooled KV.
311// ---------------------------------------------------------------------------
312
313/// Branch and root decode through the shared KV pool, which stores K/V as `SHARED_KV_DTYPE` (bf16 since
314/// the Qwen3-8B decode-speed lane, sc#464), while the teacher-forced controls below keep f32 K/V. The
315/// rounding shows as about 7e-5 on this test model's logits; a real fork or isolation bug shows as O(1).
316const POOL_VS_F32_TOL: f32 = 5e-4;
317
318fn c4_config() -> ModelConfig {
319 ModelConfig {
320 model_id: "pe2e-c4-fork-hooks-reference".to_string(),
321 max_sequence_length: 256,
322 // 6-token prompt over 4-token blocks: the root's tail block is partial
323 // and shared, so each branch's first decode copies it (COW).
324 block_size: 4,
325 num_layers: 3,
326 num_heads: 4,
327 head_dim: 8,
328 num_kv_heads: 2,
329 hidden_dim: 32,
330 intermediate_dim: 64,
331 vocab_size: 97,
332 rms_norm_eps: 1e-5,
333 rope_theta: 10000.0,
334 rope_scaling: None,
335 tie_word_embeddings: false,
336 eos_token_ids: Vec::new(),
337 qk_norm: false,
338 }
339}
340
341fn c4_scheduler() -> SchedulerConfig {
342 SchedulerConfig {
343 max_batch_size: 32,
344 max_batch_tokens: 2048,
345 max_prefill_tokens: 1024,
346 prefill_chunk_size: 128,
347 chunk_prefill: true,
348 watermark_blocks: 2,
349 }
350}
351
352const C4_PROMPT: [u32; 6] = [5, 17, 42, 3, 88, 61];
353
354/// Delegates to the native backend and records each sequence's decode logits.
355struct LogitsTap {
356 inner: NativeTransformerBackend,
357 decode_logits: HashMap<u64, Vec<Vec<f32>>>,
358 /// Token each decode step sampled, per sequence (C6).
359 decode_tokens: HashMap<u64, Vec<u32>>,
360 /// Per decode batch: (id, last token fed) for every row (C6).
361 decode_batches: Vec<Vec<(u64, u32)>>,
362 /// Each sequence's backend token stream as it was just before its first decode.
363 first_decode_tokens: HashMap<u64, Vec<u32>>,
364}
365
366#[async_trait]
367impl AienInferenceBackend for LogitsTap {
368 async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> {
369 Ok(())
370 }
371
372 async fn execute_step(
373 &mut self,
374 batch: &ScheduledBatch,
375 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
376 let mut outputs = Vec::new();
377 let mut metrics = StepMetrics::default();
378 if !batch.prefill_requests.is_empty() {
379 let prefill_only = ScheduledBatch {
380 decode_requests: Vec::new(),
381 ..batch.clone()
382 };
383 let (o, m) = self.inner.execute_step(&prefill_only).await?;
384 outputs.extend(o);
385 metrics = m;
386 }
387 if !batch.decode_requests.is_empty() {
388 let fed: Vec<(u64, u32)> = batch
389 .decode_requests
390 .iter()
391 .map(|id| {
392 let last = self
393 .inner
394 .sequences
395 .get(id)
396 .and_then(|s| s.tokens.last().copied())
397 .unwrap_or(u32::MAX);
398 (*id, last)
399 })
400 .collect();
401 self.decode_batches.push(fed);
402 for id in &batch.decode_requests {
403 if let Some(seq) = self.inner.sequences.get(id) {
404 self.first_decode_tokens
405 .entry(*id)
406 .or_insert_with(|| seq.tokens.clone());
407 }
408 }
409 let (o, logits) = self
410 .inner
411 .forward_decode_batch_with_logits(&batch.decode_requests)?;
412 for (id, row) in batch.decode_requests.iter().zip(logits) {
413 self.decode_logits.entry(*id).or_default().push(row);
414 if let Some(tok) = self.inner.sequences.get(id).and_then(|s| s.tokens.last()) {
415 self.decode_tokens.entry(*id).or_default().push(*tok);
416 }
417 }
418 outputs.extend(o);
419 metrics.decode_tokens_emitted += batch.decode_requests.len();
420 }
421 Ok((outputs, metrics))
422 }
423
424 fn manages_kv_cache(&self) -> bool {
425 self.inner.manages_kv_cache()
426 }
427
428 fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> {
429 self.inner.fork_sequence(parent_id, child_id)
430 }
431
432 fn fork_sequence_with_sampling(
433 &mut self,
434 parent_id: u64,
435 child_id: u64,
436 sampling: &SamplingParams,
437 ) -> Result<(), String> {
438 self.inner
439 .fork_sequence_with_sampling(parent_id, child_id, sampling)
440 }
441}
442
443fn c4_swarm_config(branch_count: usize, max_tokens: usize) -> SwarmConfig {
444 SwarmConfig {
445 model_handle: 1,
446 branch_count,
447 max_active_sequences: branch_count,
448 max_tokens_per_branch: max_tokens,
449 root_world_id: 0,
450 priority: 1,
451 }
452}
453
454#[tokio::test]
455async fn backend_fork_before_prefill_fence_is_refused() {
456 let config = c4_config();
457 let weights = TransformerWeights::reference_test_weights(&config);
458 let (mut spine, mut backend) = build_shared_kv_runtime(
459 weights,
460 Arc::new(ReferenceCpuBackend::new()),
461 c4_scheduler(),
462 SharedKvSizing {
463 arena_capacity: 64,
464 total_blocks: 64,
465 },
466 )
467 .expect("build shared KV runtime");
468
469 let swarm_id = spine
470 .launch_swarm(c4_swarm_config(2, 2), &C4_PROMPT)
471 .expect("launch swarm");
472 let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone();
473 let root = swarm.root_sequence_id.as_u64();
474 let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect();
475
476 // Run the model over the root prompt WITHOUT the completion fence: the
477 // backend now knows the root, but the KV manager has not marked it ready.
478 let mut block_tables = HashMap::new();
479 block_tables.insert(
480 root,
481 spine
482 .kv_manager
483 .read()
484 .get_block_table(root)
485 .unwrap()
486 .block_ids
487 .clone(),
488 );
489 let unfenced = ScheduledBatch {
490 prefill_requests: vec![SequenceRequest {
491 request_id: root,
492 prompt_tokens: C4_PROMPT.to_vec(),
493 sampling_params: SamplingParams::default(),
494 arrival_time_ns: 0,
495 priority: 1,
496 }],
497 decode_requests: Vec::new(),
498 block_tables,
499 step_id: 1,
500 };
501 backend
502 .execute_step(&unfenced)
503 .await
504 .expect("unfenced prefill");
505 assert!(backend.sequences.contains_key(&root));
506 let state = spine.kv_manager.read().prefill_state(root).unwrap();
507 assert!(
508 !state.is_ready(),
509 "root must not be ready without the fence"
510 );
511
512 let err = backend
513 .fork_sequence(root, branches[0])
514 .expect_err("BACKEND_FORK_VIOLATION: fork before the prefill fence must be refused");
515 assert!(
516 err.contains("not ready"),
517 "unexpected refusal reason: {err}"
518 );
519 assert!(
520 !backend.sequences.contains_key(&branches[0]),
521 "a refused fork must not create backend state"
522 );
523
524 // Parent unknown to the KV manager is refused too.
525 assert!(backend.fork_sequence(9_999_999, 9_999_998).is_err());
526}
527
528#[tokio::test]
529async fn backend_decode_of_unknown_request_id_is_an_error() {
530 let config = c4_config();
531 let weights = TransformerWeights::reference_test_weights(&config);
532 let (_spine, mut backend) = build_shared_kv_runtime(
533 weights,
534 Arc::new(ReferenceCpuBackend::new()),
535 c4_scheduler(),
536 SharedKvSizing {
537 arena_capacity: 64,
538 total_blocks: 64,
539 },
540 )
541 .expect("build shared KV runtime");
542
543 let unknown = 4_242_424u64;
544 let direct = backend.forward_decode_batch(&[unknown]);
545 assert!(
546 direct.is_err(),
547 "DECODE_STATE_VIOLATION: decoding an unknown request id must be an error, got {:?}",
548 direct.ok()
549 );
550 assert!(
551 !backend.sequences.contains_key(&unknown),
552 "DECODE_STATE_VIOLATION: a refused decode must not create an empty sequence state"
553 );
554
555 let batch = ScheduledBatch {
556 prefill_requests: Vec::new(),
557 decode_requests: vec![unknown],
558 block_tables: HashMap::new(),
559 step_id: 1,
560 };
561 assert!(
562 backend.execute_step(&batch).await.is_err(),
563 "DECODE_STATE_VIOLATION: execute_step must refuse a decode of an unknown request id"
564 );
565 assert!(!backend.sequences.contains_key(&unknown));
566}
567
568#[tokio::test]
569async fn branch_first_decode_logits_equal_root_continuation_logits() {
570 let config = c4_config();
571 let weights = TransformerWeights::reference_test_weights(&config);
572 let (mut spine, backend) = build_shared_kv_runtime(
573 weights.clone(),
574 Arc::new(ReferenceCpuBackend::new()),
575 c4_scheduler(),
576 SharedKvSizing {
577 arena_capacity: 64,
578 total_blocks: 64,
579 },
580 )
581 .expect("build shared KV runtime");
582 let mut tap = LogitsTap {
583 inner: backend,
584 decode_logits: HashMap::new(),
585 decode_tokens: HashMap::new(),
586 decode_batches: Vec::new(),
587 first_decode_tokens: HashMap::new(),
588 };
589
590 let branch_count = 3usize;
591 let swarm_id = spine
592 .launch_swarm(c4_swarm_config(branch_count, 2), &C4_PROMPT)
593 .expect("launch swarm");
594 let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone();
595 let root = swarm.root_sequence_id.as_u64();
596 let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect();
597
598 let mut steps = 0;
599 while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) && steps < 50
600 {
601 steps += 1;
602 spine.step(&mut tap).await.expect("spine step");
603 }
604 assert_eq!(
605 spine.scheduler.metrics().finished_requests as usize,
606 branch_count,
607 "every branch must finish"
608 );
609
610 // Root's own continuation, computed independently: a fresh backend with
611 // its own pooled KV prefills the same prompt under the same request id
612 // (prefill sampling is seeded by request id) and decodes one step.
613 let mut control = NativeTransformerBackend::with_paged_kv(weights, 64, config.block_size)
614 .expect("control backend");
615 let control_batch = ScheduledBatch {
616 prefill_requests: vec![SequenceRequest {
617 request_id: root,
618 prompt_tokens: C4_PROMPT.to_vec(),
619 sampling_params: SamplingParams::default(),
620 arrival_time_ns: 0,
621 priority: 1,
622 }],
623 decode_requests: Vec::new(),
624 block_tables: HashMap::new(),
625 step_id: 1,
626 };
627 control
628 .execute_step(&control_batch)
629 .await
630 .expect("control prefill");
631 assert_eq!(
632 control.sequences.get(&root).map(|s| s.tokens.clone()),
633 tap.inner.sequences.get(&root).map(|s| s.tokens.clone()),
634 "control root must hold the same tokens as the spine root after prefill"
635 );
636 let (_out, control_logits) = control
637 .forward_decode_batch_with_logits(&[root])
638 .expect("control root continuation");
639 let root_logits = &control_logits[0];
640 assert!(root_logits.iter().any(|x| *x != 0.0));
641
642 for &b in &branches {
643 let first = tap
644 .decode_logits
645 .get(&b)
646 .and_then(|v| v.first())
647 .unwrap_or_else(|| panic!("branch {} never decoded", b));
648 assert_eq!(first.len(), root_logits.len());
649 let max_diff = first
650 .iter()
651 .zip(root_logits.iter())
652 .map(|(a, c)| (a - c).abs())
653 .fold(0.0f32, f32::max);
654 assert!(
655 max_diff <= POOL_VS_F32_TOL,
656 "BACKEND_FORK_VIOLATION: branch {} step-1 logits differ from the root's own \
657 continuation by {} (> {})",
658 b,
659 max_diff,
660 POOL_VS_F32_TOL
661 );
662 }
663}
664
665/// C4c: the token prefill sampled but did not append (`pending_prefill_token`)
666/// belongs to the root's stream. `fork_sequence` must give each child that token
667/// appended to its own copy of the parent's tokens WITHOUT mutating the parent, so every
668/// branch's first decode feeds that token at
669/// position `prompt_len`, exactly like the root's own continuation.
670#[tokio::test]
671async fn backend_fork_carries_parent_pending_prefill_token() {
672 let config = c4_config();
673 let weights = TransformerWeights::reference_test_weights(&config);
674 let (mut spine, backend) = build_shared_kv_runtime(
675 weights,
676 Arc::new(ReferenceCpuBackend::new()),
677 c4_scheduler(),
678 SharedKvSizing {
679 arena_capacity: 64,
680 total_blocks: 64,
681 },
682 )
683 .expect("build shared KV runtime");
684 let mut tap = LogitsTap {
685 inner: backend,
686 decode_logits: HashMap::new(),
687 decode_tokens: HashMap::new(),
688 decode_batches: Vec::new(),
689 first_decode_tokens: HashMap::new(),
690 };
691
692 let branch_count = 3usize;
693 let swarm_id = spine
694 .launch_swarm(c4_swarm_config(branch_count, 2), &C4_PROMPT)
695 .expect("launch swarm");
696 let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone();
697 let root = swarm.root_sequence_id.as_u64();
698 let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect();
699
700 let mut steps = 0;
701 while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) && steps < 50
702 {
703 steps += 1;
704 spine.step(&mut tap).await.expect("spine step");
705 }
706
707 let root_tokens = tap
708 .inner
709 .sequences
710 .get(&root)
711 .expect("root state")
712 .tokens
713 .clone();
714 assert_eq!(
715 root_tokens,
716 C4_PROMPT.to_vec(),
717 "fork must not mutate the parent: root tokens stay the prompt only"
718 );
719 let pending = *tap
720 .inner
721 .pending_prefill_token
722 .get(&root)
723 .expect("fork must leave the parent's pending prefill token untouched");
724 let mut expected_child = root_tokens.clone();
725 expected_child.push(pending);
726 for &b in &branches {
727 let first = tap
728 .first_decode_tokens
729 .get(&b)
730 .unwrap_or_else(|| panic!("branch {} never decoded", b));
731 assert_eq!(
732 first, &expected_child,
733 "PENDING_TOKEN_VIOLATION: branch {} must start its first decode from the root's \
734 prompt plus the sampled token",
735 b
736 );
737 }
738}
739
740/// PREFILL-E2E C6, bullet 11: sampled branches diverge, and no branch sees
741/// another branch's suffix. Reference weights, CPU, spine + scheduler + one
742/// pooled KV (`build_shared_kv_runtime`).
743#[tokio::test]
744async fn sampled_branches_diverge_and_each_matches_its_own_teacher_forced_control() {
745 let config = c4_config();
746 let weights = TransformerWeights::reference_test_weights(&config);
747 let (mut spine, backend) = build_shared_kv_runtime(
748 weights.clone(),
749 Arc::new(ReferenceCpuBackend::new()),
750 c4_scheduler(),
751 SharedKvSizing {
752 arena_capacity: 64,
753 total_blocks: 64,
754 },
755 )
756 .expect("build shared KV runtime");
757 let mut tap = LogitsTap {
758 inner: backend,
759 decode_logits: HashMap::new(),
760 decode_tokens: HashMap::new(),
761 decode_batches: Vec::new(),
762 first_decode_tokens: HashMap::new(),
763 };
764
765 let branch_count = 3usize;
766 let max_tokens = 8usize;
767 let swarm_id = spine
768 .launch_swarm(c4_swarm_config(branch_count, max_tokens), &C4_PROMPT)
769 .expect("launch swarm");
770 let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone();
771 let root = swarm.root_sequence_id.as_u64();
772 let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect();
773
774 let mut steps = 0;
775 while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0)
776 && steps < 100
777 {
778 steps += 1;
779 spine.step(&mut tap).await.expect("spine step");
780 }
781 assert_eq!(
782 spine.scheduler.metrics().finished_requests as usize,
783 branch_count,
784 "every branch must finish"
785 );
786
787 // The fork hook carried each branch's own sampling params.
788 for &b in &branches {
789 let params = tap.inner.sampling_params(b).unwrap_or_else(|| {
790 panic!(
791 "BRANCH_SAMPLING_VIOLATION: branch {} has no sampling params (fork hook did not carry them)",
792 b
793 )
794 });
795 assert!(
796 params.temperature > 0.001,
797 "branch {} must sample (temperature {})",
798 b,
799 params.temperature
800 );
801 }
802
803 let generated: Vec<Vec<u32>> = branches
804 .iter()
805 .map(|b| tap.decode_tokens.get(b).cloned().unwrap_or_default())
806 .collect();
807 for (b, g) in branches.iter().zip(&generated) {
808 assert!(!g.is_empty(), "branch {} never decoded", b);
809 }
810
811 // 1. Divergence: with temperature > 0 and per-branch seeds the branches
812 // must not all generate the same tokens.
813 assert!(
814 generated.iter().any(|g| *g != generated[0]),
815 "BRANCH_DIVERGENCE_VIOLATION: all {} branches generated identical tokens {:?}",
816 branch_count,
817 generated
818 );
819
820 // Precondition for 2: some decode batch held two or more branches fed
821 // different tokens, so a cross-branch K/V mixup would change logits.
822 assert!(
823 tap.decode_batches.iter().any(|rows| {
824 let fed: Vec<u32> = rows
825 .iter()
826 .filter(|(id, _)| branches.contains(id))
827 .map(|(_, t)| *t)
828 .collect();
829 fed.len() >= 2 && fed.iter().any(|t| *t != fed[0])
830 }),
831 "C6 precondition: no decode batch held two branches with different inputs ({:?})",
832 tap.decode_batches
833 );
834
835 // 2. Isolation: each branch's per-step logits equal a teacher-forced,
836 // independent control (fresh unpaged backend, dense private K/V) fed
837 // the root prompt, the root's sampled token and only that branch's own
838 // generated tokens.
839 let root_tokens = tap
840 .inner
841 .sequences
842 .get(&root)
843 .expect("root backend state")
844 .tokens
845 .clone();
846 // C4 semantics: the root keeps prompt-only tokens; the sampled prefill token
847 // stays pending and each fork child carries it.
848 assert_eq!(root_tokens, C4_PROMPT.to_vec());
849 let root_token = *tap
850 .inner
851 .pending_prefill_token
852 .get(&root)
853 .expect("root pending prefill token");
854
855 for (b, gen) in branches.iter().zip(&generated) {
856 let branch_logits = tap.decode_logits.get(b).expect("branch logits");
857 assert_eq!(branch_logits.len(), gen.len());
858
859 let ctl_id = 1u64;
860 let mut control = NativeTransformerBackend::new(weights.clone());
861 assert!(control.kv_manager.is_none(), "control must be unpaged");
862 control
863 .prefill_sequence(ctl_id, &C4_PROMPT)
864 .expect("control prefill");
865 control
866 .sequences
867 .get_mut(&ctl_id)
868 .unwrap()
869 .tokens
870 .push(root_token);
871
872 for (k, row) in branch_logits.iter().enumerate() {
873 let (_out, ctl_logits) = control
874 .forward_decode_batch_with_logits(&[ctl_id])
875 .expect("control decode");
876 let ctl_row = &ctl_logits[0];
877 assert_eq!(row.len(), ctl_row.len());
878 assert!(ctl_row.iter().any(|x| *x != 0.0));
879 let max_diff = row
880 .iter()
881 .zip(ctl_row.iter())
882 .map(|(a, c)| (a - c).abs())
883 .fold(0.0f32, f32::max);
884 assert!(
885 max_diff <= POOL_VS_F32_TOL,
886 "BRANCH_ISOLATION_VIOLATION: branch {} step {} logits differ from its own \
887 teacher-forced control by {} (> {})",
888 b,
889 k + 1,
890 max_diff,
891 POOL_VS_F32_TOL
892 );
893 // Teacher forcing: replace the control's own pick with the token
894 // this branch actually generated at this step.
895 let seq = control.sequences.get_mut(&ctl_id).unwrap();
896 seq.tokens.pop();
897 seq.tokens.push(gen[k]);
898 }
899 }
900}
901
902/// One branch of a sampled swarm run: id, sampling params, backend tokens just
903/// before its first decode, per-step decode logits, per-step sampled tokens.
904type BranchRun = (u64, SamplingParams, Vec<u32>, Vec<Vec<f32>>, Vec<u32>);
905
906/// Runs the C6 sampled swarm (reference weights, CPU, spine + scheduler + one
907/// pooled KV) in a fresh runtime to completion.
908async fn sampled_swarm_run(branch_count: usize, max_tokens: usize) -> Vec<BranchRun> {
909 let config = c4_config();
910 let weights = TransformerWeights::reference_test_weights(&config);
911 let (mut spine, backend) = build_shared_kv_runtime(
912 weights,
913 Arc::new(ReferenceCpuBackend::new()),
914 c4_scheduler(),
915 SharedKvSizing {
916 arena_capacity: 64,
917 total_blocks: 64,
918 },
919 )
920 .expect("build shared KV runtime");
921 let mut tap = LogitsTap {
922 inner: backend,
923 decode_logits: HashMap::new(),
924 decode_tokens: HashMap::new(),
925 decode_batches: Vec::new(),
926 first_decode_tokens: HashMap::new(),
927 };
928 let swarm_id = spine
929 .launch_swarm(c4_swarm_config(branch_count, max_tokens), &C4_PROMPT)
930 .expect("launch swarm");
931 let swarm = spine.swarm_manager.get_swarm(swarm_id).unwrap().clone();
932 let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect();
933 let mut steps = 0;
934 while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0)
935 && steps < 100
936 {
937 steps += 1;
938 spine.step(&mut tap).await.expect("spine step");
939 }
940 assert_eq!(
941 spine.scheduler.metrics().finished_requests as usize,
942 branch_count,
943 "every branch must finish"
944 );
945 branches
946 .iter()
947 .map(|&b| {
948 (
949 b,
950 tap.inner
951 .sampling_params(b)
952 .cloned()
953 .expect("branch sampling params"),
954 tap.first_decode_tokens
955 .get(&b)
956 .cloned()
957 .expect("branch decoded"),
958 tap.decode_logits.get(&b).cloned().unwrap_or_default(),
959 tap.decode_tokens.get(&b).cloned().unwrap_or_default(),
960 )
961 })
962 .collect()
963}
964
965/// Branch-specific sampling follows the reproducibility contract in
966/// crates/aien-inference-abi/src/transformer_backend.rs `decode_sampling_seed`
967/// (PREFILL-E2E C6): each decode token is `sample_with_params(logits, the
968/// branch's own params, decode_sampling_seed(request id, token count before the
969/// new token))`; sibling branches draw from different seed streams; and "the
970/// same request replays the same stream": the same swarm in a fresh runtime
971/// gives the same ids, logits and tokens bit for bit. Marker SEED_CONTRACT_VIOLATION.
972#[tokio::test]
973async fn sampled_branches_follow_the_seed_contract_and_replay_bit_identically() {
974 let first = sampled_swarm_run(3, 8).await;
975 for (b, params, before, logits, gen) in &first {
976 assert!(params.temperature > 0.001, "branch {} must sample", b);
977 assert!(!gen.is_empty(), "branch {} never decoded", b);
978 assert_eq!(logits.len(), gen.len());
979 for (k, row) in logits.iter().enumerate() {
980 let seed = aien_inference_abi::decode_sampling_seed(*b, before.len() + k);
981 let (tok, _) = aien_inference_abi::sample_with_params(row, params, seed);
982 assert_eq!(
983 tok, gen[k],
984 "SEED_CONTRACT_VIOLATION: branch {} step {} sampled {} but the contract seed gives {}",
985 b, k + 1, gen[k], tok
986 );
987 }
988 }
989 // sibling branches use different seed streams at every position they share
990 for i in 0..first.len() {
991 for j in (i + 1)..first.len() {
992 let (bi, _, pi, _, gi) = &first[i];
993 let (bj, _, _, _, _) = &first[j];
994 assert_ne!(bi, bj);
995 for pos in pi.len()..pi.len() + gi.len() {
996 assert_ne!(
997 aien_inference_abi::decode_sampling_seed(*bi, pos),
998 aien_inference_abi::decode_sampling_seed(*bj, pos),
999 "SEED_CONTRACT_VIOLATION: branches {} and {} share the seed for position {}",
1000 bi,
1001 bj,
1002 pos
1003 );
1004 }
1005 }
1006 }
1007 // replay in a fresh runtime: identical ids, logits (bitwise) and tokens
1008 let second = sampled_swarm_run(3, 8).await;
1009 assert_eq!(first.len(), second.len());
1010 for (a, b) in first.iter().zip(&second) {
1011 assert_eq!(
1012 a.0, b.0,
1013 "SEED_CONTRACT_VIOLATION: replay assigned different branch ids"
1014 );
1015 assert_eq!(
1016 a.2, b.2,
1017 "SEED_CONTRACT_VIOLATION: branch {} context differs on replay",
1018 a.0
1019 );
1020 assert_eq!(
1021 a.4, b.4,
1022 "SEED_CONTRACT_VIOLATION: branch {} tokens differ on replay",
1023 a.0
1024 );
1025 let bits = |rows: &Vec<Vec<f32>>| -> Vec<u32> {
1026 rows.iter().flatten().map(|x| x.to_bits()).collect()
1027 };
1028 assert_eq!(
1029 bits(&a.3),
1030 bits(&b.3),
1031 "SEED_CONTRACT_VIOLATION: branch {} logits differ on replay",
1032 a.0
1033 );
1034 }
1035}