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 / prefill_e2e1.rs

1503 lines · 59049 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-E2E-1: the E2E-0 end-to-end gate at N = 1, 2, 8, 32, 128 and 500
17//! branches from ONE shared root prompt (TinyLlama, CPU, strict checkpoint).
18//!
19//! `#[ignore]`d for normal CI. Run with `--ignored`; it FAILS (never skips)
20//! when `AIEN_E2E_CHECKPOINT` or `AIEN_E2E1_RECEIPT` is unset.
21//!
22//! - `AIEN_E2E_CHECKPOINT`: TinyLlama-1.1B-Chat-v1.0 directory (holding
23//! `model.safetensors` and `tokenizer.json`) or the `.safetensors` file.
24//! - `AIEN_E2E1_RECEIPT`: path of the JSON receipt (an array, one object per N).
25//!
26//! The helpers (strict load, tolerance reader, recording backend, parity,
27//! receipt helpers) are copied from `prefill_e2e0.rs` (not edited) with two
28//! changes: the recording backend keeps every step's logits only for the
29//! branches that get a control run (all branches keep step 1), and the gate
30//! body is a loop over N with per-N pool sizing and per-N checks.
31//!
32//! Per N the checks are: (a) allocated is not ready, prefill executed in >= 2
33//! chunks, the fence made the root ready before any fork, a fork before the
34//! fence is refused; (b) every branch's step 1 equals the root continuation,
35//! and a documented sample of branches (at least 8, first and last included,
36//! all of them for N <= 8) equals an independent control at every step, at the
37//! frozen tolerance 0.0 (docs/campaigns/c1/acceptance.toml
38//! [numerics.noise_floor.tinyllama]); (c) the prefix is held once, and the
39//! physical KV peak stays within prefix blocks + N x per-branch suffix blocks
40//! and below the logical bytes for N > 1; (d) branches diverge (distinct
41//! request ids give distinct sampling seeds, crates/aien-inference-abi/src/
42//! transformer_backend.rs `decode_sampling_seed`) and a decode batch mixed
43//! different branch inputs; (e) backend sequences, KV blocks, arena, worlds and
44//! scheduler all empty after each N.
45//!
46//! Scheduler admission (GB10-2): `build_scheduled_batch` step 3 asks
47//! `AienKvManager::incremental_blocks_needed` for the NEW blocks a sequence
48//! needs, so a fork child that shares the root blocks needs only its
49//! copy-on-write block. The pool is sized to the true requirement (prefix + N x
50//! private suffix + watermark, see `pool_plan`) and records the pool size and
51//! the reason. A step-guard hit, an idle-while-waiting step (starved branch) or
52//! a scheduler/spine error is FAIL.
53//!
54//! The run stops at the first N that fails (later counts are listed in the
55//! receipt as `not_run_after_failure`), so a failing gate stays failing and
56//! mutants die fast. All checks of an N are evaluated and the receipt for the
57//! whole run is written before any assert fires.
58
59#![recursion_limit = "256"]
60
61use std::collections::HashMap;
62use std::io::{Read, Seek, SeekFrom};
63use std::path::{Path, PathBuf};
64use std::sync::Arc;
65use std::time::{Duration, Instant};
66
67use aien_inference_abi::{
68 AienInferenceBackend, DecodeOutput, FinishReason, ModelConfig, NativeTransformerBackend,
69 PrefillState, ReferenceCpuBackend, SamplingParams, ScheduledBatch, StepMetrics,
70 TinyLlamaTokenizer, TransformerWeights,
71};
72use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing};
73use aien_runtime::swarm::SwarmConfig;
74use aien_scheduler::SchedulerConfig;
75use async_trait::async_trait;
76use sha2::{Digest, Sha256};
77
78/// Branch counts of the gate, run in this order.
79const BRANCH_COUNTS: [usize; 6] = [1, 2, 8, 32, 128, 500];
80/// Branch count from which (d) requires distinct outputs and a mixed decode
81/// batch; below it the counts are recorded only (sampling coincidence).
82const DIVERGENCE_MIN_N: usize = 8;
83/// Decode budget per branch. 4 tokens keep N = 500 finishable on CPU: the run
84/// does N x 4 batched decode rows plus one full control (217-token prefill + 4
85/// decodes) per sampled branch, and 4 tokens still cover a partial-block
86/// copy-on-write, a mixed decode batch and per-step parity.
87const MAX_TOKENS_PER_BRANCH: usize = 4;
88/// Branches that get a full per-step control run (N <= 8: all of them).
89const SAMPLED_CONTROLS: usize = 8;
90/// The daemon's prefill chunk size (crates/aien-cli/src/commands.rs,
91/// `run_daemon_server` scheduler config). The root prompt must exceed it.
92const PREFILL_CHUNK: usize = 128;
93/// Control sequence id inside each fresh control backend.
94const CONTROL_ID: u64 = 1;
95
96const SYSTEM_PROMPT: &str = "You are a careful engineering assistant. You answer in plain \
97English, you show the steps of your reasoning, and you never invent numbers you were not given.";
98
99const USER_PROMPT: &str = "A small workshop builds wooden chairs. Each chair needs four legs, \
100one seat, two side rails, one back rest and twelve screws. The workshop has ninety legs, \
101twenty seats, forty side rails, eighteen back rests and two hundred screws in stock. Two of \
102the seats are cracked and cannot be used, and one box of twenty screws turned out to be the \
103wrong size. The carpenter wants to know how many complete chairs can be built today, which \
104part runs out first, and how many of every other part will be left over afterwards. After \
105that, suggest the smallest order of extra parts that would let the workshop build exactly \
106twenty five chairs tomorrow, and explain briefly why that order is the smallest one.";
107
108// ---------------------------------------------------------------------------
109// Environment, strict checkpoint, acceptance tolerance
110// ---------------------------------------------------------------------------
111
112struct CheckpointPaths {
113 model: PathBuf,
114 tokenizer: PathBuf,
115}
116
117fn required_env(name: &str) -> String {
118 match std::env::var(name) {
119 Ok(v) if !v.trim().is_empty() => v.trim().to_string(),
120 _ => panic!(
121 "PREFILL_E2E1_ENV: {name} is unset; this gate never skips (set it and rerun with \
122 --ignored)"
123 ),
124 }
125}
126
127fn checkpoint_paths(raw: &str) -> CheckpointPaths {
128 let p = PathBuf::from(raw);
129 let (model, dir) = if p.is_dir() {
130 (p.join("model.safetensors"), p.clone())
131 } else {
132 let dir = p.parent().map(Path::to_path_buf).unwrap_or_default();
133 (p.clone(), dir)
134 };
135 let tokenizer = dir.join("tokenizer.json");
136 assert!(
137 model.is_file(),
138 "STRICT_CHECKPOINT_VIOLATION: checkpoint {} does not exist; refusing to fall back \
139 (AIEN_REQUIRE_CHECKPOINT=1 semantics)",
140 model.display()
141 );
142 assert!(
143 tokenizer.is_file(),
144 "STRICT_CHECKPOINT_VIOLATION: tokenizer {} does not exist; refusing to fall back",
145 tokenizer.display()
146 );
147 CheckpointPaths { model, tokenizer }
148}
149
150fn sha256_file_hex(path: &Path) -> String {
151 let mut file = std::fs::File::open(path)
152 .unwrap_or_else(|e| panic!("STRICT_CHECKPOINT_VIOLATION: open {}: {e}", path.display()));
153 let mut hasher = Sha256::new();
154 let mut buf = vec![0u8; 1 << 20];
155 loop {
156 let n = file
157 .read(&mut buf)
158 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
159 if n == 0 {
160 break;
161 }
162 hasher.update(&buf[..n]);
163 }
164 hex(&hasher.finalize())
165}
166
167fn hex(bytes: &[u8]) -> String {
168 bytes.iter().map(|b| format!("{b:02x}")).collect()
169}
170
171fn f16_to_f32(bits: u16) -> f32 {
172 let sign = ((bits >> 15) & 1) as u32;
173 let exp = ((bits >> 10) & 0x1f) as u32;
174 let frac = (bits & 0x3ff) as u32;
175 let out = if exp == 0 {
176 if frac == 0 {
177 sign << 31
178 } else {
179 // Subnormal: renormalize.
180 let mut e: i32 = 0;
181 let mut f = frac;
182 while f & 0x400 == 0 {
183 f <<= 1;
184 e -= 1;
185 }
186 let exp32 = (127 - 15 + 1 + e) as u32;
187 (sign << 31) | (exp32 << 23) | ((f & 0x3ff) << 13)
188 }
189 } else if exp == 31 {
190 (sign << 31) | (0xff << 23) | (frac << 13)
191 } else {
192 (sign << 31) | ((exp + 127 - 15) << 23) | (frac << 13)
193 };
194 f32::from_bits(out)
195}
196
197/// Reads `count` values starting at element `first` of tensor `name` straight
198/// from the safetensors file (8-byte header length, JSON header, data), with
199/// no aien code involved.
200fn read_tensor_values(path: &Path, name: &str, first: usize, count: usize) -> Vec<f32> {
201 let mut file = std::fs::File::open(path).expect("open checkpoint");
202 let mut len_buf = [0u8; 8];
203 file.read_exact(&mut len_buf)
204 .expect("safetensors header length");
205 let header_len = u64::from_le_bytes(len_buf) as usize;
206 let mut header = vec![0u8; header_len];
207 file.read_exact(&mut header).expect("safetensors header");
208 let header: serde_json::Value = serde_json::from_slice(&header).expect("header JSON");
209 let info = header
210 .get(name)
211 .unwrap_or_else(|| panic!("STRICT_CHECKPOINT_VIOLATION: tensor {name} not in checkpoint"));
212 let dtype = info["dtype"].as_str().expect("dtype").to_string();
213 let start = info["data_offsets"][0].as_u64().expect("data_offsets") as usize;
214 let width = match dtype.as_str() {
215 "F32" => 4,
216 "BF16" | "F16" => 2,
217 other => panic!("unsupported checkpoint dtype {other}"),
218 };
219 let mut raw = vec![0u8; count * width];
220 file.seek(SeekFrom::Start(
221 (8 + header_len + start + first * width) as u64,
222 ))
223 .expect("seek tensor");
224 file.read_exact(&mut raw).expect("read tensor bytes");
225 raw.chunks_exact(width)
226 .map(|c| match dtype.as_str() {
227 "F32" => f32::from_le_bytes([c[0], c[1], c[2], c[3]]),
228 "BF16" => f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16),
229 _ => f16_to_f32(u16::from_le_bytes([c[0], c[1]])),
230 })
231 .collect()
232}
233
234/// Loads TinyLlama with no fallback and proves the weights came from the file.
235fn strict_load(paths: &CheckpointPaths) -> TransformerWeights {
236 let config = ModelConfig::tinyllama_1_1b();
237 let weights =
238 TransformerWeights::load_from_safetensors(&paths.model, &config).unwrap_or_else(|e| {
239 panic!(
240 "STRICT_CHECKPOINT_VIOLATION: {} failed to load against the {} config: {e:?}; \
241 refusing to fall back (AIEN_REQUIRE_CHECKPOINT=1 semantics)",
242 paths.model.display(),
243 config.model_id
244 )
245 });
246 let hidden = config.hidden_dim;
247 let vocab = config.vocab_size;
248 assert_eq!(
249 weights.embed_tokens.len(),
250 vocab * hidden,
251 "STRICT_CHECKPOINT_VIOLATION: embedding shape does not match the TinyLlama config"
252 );
253 for row in [0usize, vocab - 1] {
254 let from_file = read_tensor_values(
255 &paths.model,
256 "model.embed_tokens.weight",
257 row * hidden,
258 hidden,
259 );
260 let loaded = &weights.embed_tokens[row * hidden..(row + 1) * hidden];
261 assert!(
262 loaded
263 .iter()
264 .zip(&from_file)
265 .all(|(a, b)| a.to_bits() == b.to_bits()),
266 "STRICT_CHECKPOINT_VIOLATION: loaded embedding row {row} differs from the bytes in \
267 {} (weights did not come from the checkpoint; reference fallback?)",
268 paths.model.display()
269 );
270 }
271 weights
272}
273
274struct Tolerance {
275 abs: f64,
276 rel: f64,
277 rel_eps: f64,
278 floor_status: String,
279 floor_model_sha256: String,
280}
281
282/// Minimal reader for `key = value` lines of one TOML table (no new crate).
283fn toml_table(text: &str, table: &str) -> HashMap<String, String> {
284 let header = format!("[{table}]");
285 let mut out = HashMap::new();
286 let mut inside = false;
287 for line in text.lines() {
288 let line = line.trim();
289 if line.starts_with('[') {
290 inside = line == header;
291 continue;
292 }
293 if !inside || line.is_empty() || line.starts_with('#') {
294 continue;
295 }
296 if let Some((k, v)) = line.split_once('=') {
297 let v = v.split('#').next().unwrap_or("").trim().trim_matches('"');
298 out.insert(k.trim().to_string(), v.to_string());
299 }
300 }
301 out
302}
303
304fn acceptance_tolerance() -> Tolerance {
305 let path =
306 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/campaigns/c1/acceptance.toml");
307 let text = std::fs::read_to_string(&path)
308 .unwrap_or_else(|e| panic!("PARITY_TOLERANCE: cannot read {}: {e}", path.display()));
309 let floor = toml_table(&text, "numerics.noise_floor.tinyllama");
310 let numerics = toml_table(&text, "numerics");
311 let num = |t: &HashMap<String, String>, k: &str| -> f64 {
312 t.get(k)
313 .unwrap_or_else(|| panic!("PARITY_TOLERANCE: {k} missing in {}", path.display()))
314 .parse::<f64>()
315 .unwrap_or_else(|e| panic!("PARITY_TOLERANCE: {k} not a number: {e}"))
316 };
317 Tolerance {
318 abs: num(&floor, "tolerance_abs"),
319 rel: num(&floor, "tolerance_rel"),
320 rel_eps: num(&numerics, "relative_error_epsilon"),
321 floor_status: floor.get("status").cloned().unwrap_or_default(),
322 floor_model_sha256: floor.get("model_sha256").cloned().unwrap_or_default(),
323 }
324}
325
326// ---------------------------------------------------------------------------
327// Recording backend
328// ---------------------------------------------------------------------------
329
330struct PrefillChunk {
331 id: u64,
332 len: usize,
333 state_before: Option<PrefillState>,
334}
335
336struct ForkRecord {
337 parent: u64,
338 child: u64,
339 parent_ready: bool,
340 ok: bool,
341 child_tokens_ok: bool,
342 temperature: f32,
343}
344
345/// State at the first fork hook call (right after the fence).
346struct ForkSnapshot {
347 root_state: Option<PrefillState>,
348 root_backend_tokens: usize,
349 root_pending_token: Option<u32>,
350 root_kv_values: usize,
351 root_kv_nonzero: usize,
352}
353
354/// KV state at the first decode batch (all branches forked, nothing decoded).
355struct PrefixSnapshot {
356 root_blocks: Vec<usize>,
357 branches_share_root_blocks: bool,
358 physical_pages: usize,
359 logical_pages: usize,
360 shared_pages: usize,
361 allocated_blocks: usize,
362 block_bytes: usize,
363}
364
365/// Delegates to the real backend and records what the gate needs.
366struct E2eTap {
367 inner: NativeTransformerBackend,
368 root: u64,
369 branches: Vec<u64>,
370 prompt: Vec<u32>,
371 launch_at: Instant,
372 prefill_chunks: Vec<PrefillChunk>,
373 prefill_wall: Duration,
374 forks: Vec<ForkRecord>,
375 fork_snapshot: Option<ForkSnapshot>,
376 prefix_snapshot: Option<PrefixSnapshot>,
377 decode_logits: HashMap<u64, Vec<Vec<f32>>>,
378 decode_tokens: HashMap<u64, Vec<u32>>,
379 decode_batches: Vec<Vec<(u64, u32)>>,
380 first_branch_token: Option<Duration>,
381 peak_physical_pages: usize,
382 /// Branches whose every step keeps its logits (the others keep step 1 only).
383 keep_all: std::collections::HashSet<u64>,
384}
385
386impl E2eTap {
387 fn kv_state(&self, id: u64) -> Option<PrefillState> {
388 self.inner
389 .kv_manager
390 .as_ref()
391 .and_then(|kv| kv.read().prefill_state(id))
392 }
393
394 fn take_fork_snapshot(&mut self) {
395 let root = self.root;
396 let (values, nonzero) = match self.inner.kv_manager.as_ref() {
397 Some(kv) => {
398 let kv = kv.read();
399 let mut values = 0usize;
400 let mut nonzero = 0usize;
401 for layer in 0..self.inner.weights.config.num_layers {
402 if let Ok((k, v)) = kv.gather_layer_kv(root, layer) {
403 values += k.len() + v.len();
404 nonzero += k.iter().chain(v.iter()).filter(|x| **x != 0.0).count();
405 }
406 }
407 (values, nonzero)
408 }
409 None => (0, 0),
410 };
411 self.fork_snapshot = Some(ForkSnapshot {
412 root_state: self.kv_state(root),
413 root_backend_tokens: self
414 .inner
415 .sequences
416 .get(&root)
417 .map_or(0, |s| s.tokens.len()),
418 root_pending_token: self.inner.pending_prefill_token.get(&root).copied(),
419 root_kv_values: values,
420 root_kv_nonzero: nonzero,
421 });
422 }
423
424 fn take_prefix_snapshot(&mut self) {
425 let Some(kv) = self.inner.kv_manager.as_ref() else {
426 return;
427 };
428 let kv = kv.read();
429 let root_blocks = kv
430 .get_block_table(self.root)
431 .map(|t| t.block_ids.clone())
432 .unwrap_or_default();
433 let branches_share_root_blocks = self.branches.iter().all(|b| {
434 kv.get_block_table(*b)
435 .is_some_and(|t| !root_blocks.is_empty() && t.block_ids == root_blocks)
436 });
437 let m = kv.metrics();
438 self.prefix_snapshot = Some(PrefixSnapshot {
439 root_blocks,
440 branches_share_root_blocks,
441 physical_pages: m.physical_pages,
442 logical_pages: m.logical_pages,
443 shared_pages: m.shared_pages,
444 allocated_blocks: kv.allocated_block_count(),
445 block_bytes: kv.tensor_pool().map_or(0, |p| p.block_bytes()),
446 });
447 }
448
449 fn record_fork(&mut self, parent: u64, child: u64, temperature: f32, ok: bool) {
450 let child_tokens_ok = ok
451 && match (
452 self.inner.sequences.get(&child),
453 self.fork_snapshot
454 .as_ref()
455 .and_then(|s| s.root_pending_token),
456 ) {
457 (Some(seq), Some(pending)) => {
458 seq.tokens.len() == self.prompt.len() + 1
459 && seq.tokens[..self.prompt.len()] == self.prompt[..]
460 && seq.tokens[self.prompt.len()] == pending
461 }
462 _ => false,
463 };
464 let parent_ready = self.kv_state(parent).is_some_and(|s| s.is_ready());
465 self.forks.push(ForkRecord {
466 parent,
467 child,
468 parent_ready,
469 ok,
470 child_tokens_ok,
471 temperature,
472 });
473 }
474}
475
476#[async_trait]
477impl AienInferenceBackend for E2eTap {
478 async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> {
479 Ok(())
480 }
481
482 async fn execute_step(
483 &mut self,
484 batch: &ScheduledBatch,
485 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
486 let mut outputs = Vec::new();
487 let mut metrics = StepMetrics::default();
488 if !batch.prefill_requests.is_empty() {
489 for req in &batch.prefill_requests {
490 let state_before = self.kv_state(req.request_id);
491 self.prefill_chunks.push(PrefillChunk {
492 id: req.request_id,
493 len: req.prompt_tokens.len(),
494 state_before,
495 });
496 }
497 let prefill_only = ScheduledBatch {
498 decode_requests: Vec::new(),
499 ..batch.clone()
500 };
501 let t0 = Instant::now();
502 let (o, m) = self.inner.execute_step(&prefill_only).await?;
503 self.prefill_wall += t0.elapsed();
504 outputs.extend(o);
505 metrics = m;
506 }
507 if !batch.decode_requests.is_empty() {
508 // Normally taken at the first fork hook call. If the spine never
509 // called the hook, take it here so b4/b5 still judge the prefill
510 // and b7 reports the missing fork.
511 if self.fork_snapshot.is_none() {
512 self.take_fork_snapshot();
513 }
514 if self.prefix_snapshot.is_none() {
515 self.take_prefix_snapshot();
516 }
517 let fed: Vec<(u64, u32)> = batch
518 .decode_requests
519 .iter()
520 .map(|id| {
521 let last = self
522 .inner
523 .pending_prefill_token
524 .get(id)
525 .copied()
526 .or_else(|| {
527 self.inner
528 .sequences
529 .get(id)
530 .and_then(|s| s.tokens.last().copied())
531 });
532 (*id, last.unwrap_or(u32::MAX))
533 })
534 .collect();
535 self.decode_batches.push(fed);
536 let (o, logits) = self
537 .inner
538 .forward_decode_batch_with_logits(&batch.decode_requests)?;
539 // Rows ended as Preempted (no KV slot) get no logits.
540 let preempted: Vec<u64> = o
541 .iter()
542 .filter_map(|out| match out {
543 DecodeOutput::Finished {
544 request_id,
545 reason: FinishReason::Preempted,
546 ..
547 } => Some(*request_id),
548 _ => None,
549 })
550 .collect();
551 let computed = batch
552 .decode_requests
553 .iter()
554 .filter(|id| !preempted.contains(*id));
555 for (id, row) in computed.zip(logits) {
556 let rows = self.decode_logits.entry(*id).or_default();
557 if rows.is_empty() || self.keep_all.contains(id) {
558 rows.push(row);
559 }
560 if let Some(tok) = self.inner.sequences.get(id).and_then(|s| s.tokens.last()) {
561 self.decode_tokens.entry(*id).or_default().push(*tok);
562 }
563 }
564 if self.first_branch_token.is_none()
565 && o.iter().any(|out| {
566 matches!(out, DecodeOutput::Token { request_id, .. }
567 if self.branches.contains(request_id))
568 })
569 {
570 self.first_branch_token = Some(self.launch_at.elapsed());
571 }
572 if let Some(kv) = self.inner.kv_manager.as_ref() {
573 let pages = kv.read().metrics().physical_pages;
574 self.peak_physical_pages = self.peak_physical_pages.max(pages);
575 }
576 outputs.extend(o);
577 metrics.decode_tokens_emitted += batch.decode_requests.len();
578 }
579 Ok((outputs, metrics))
580 }
581
582 fn manages_kv_cache(&self) -> bool {
583 self.inner.manages_kv_cache()
584 }
585
586 fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<(), String> {
587 if self.fork_snapshot.is_none() {
588 self.take_fork_snapshot();
589 }
590 let result = self.inner.fork_sequence(parent_id, child_id);
591 self.record_fork(parent_id, child_id, 0.0, result.is_ok());
592 result
593 }
594
595 fn fork_sequence_with_sampling(
596 &mut self,
597 parent_id: u64,
598 child_id: u64,
599 sampling: &SamplingParams,
600 ) -> Result<(), String> {
601 if self.fork_snapshot.is_none() {
602 self.take_fork_snapshot();
603 }
604 let result = self
605 .inner
606 .fork_sequence_with_sampling(parent_id, child_id, sampling);
607 self.record_fork(parent_id, child_id, sampling.temperature, result.is_ok());
608 result
609 }
610
611 fn release_sequence(&mut self, seq_id: u64) -> Result<(), String> {
612 // The trait hook (runtime reclaim), not the inherent method of the same
613 // name, which also frees KV.
614 AienInferenceBackend::release_sequence(&mut self.inner, seq_id)
615 }
616}
617
618// ---------------------------------------------------------------------------
619// Parity
620// ---------------------------------------------------------------------------
621
622#[derive(Default)]
623struct Parity {
624 max_abs: f64,
625 max_rel: f64,
626 compared_values: usize,
627 violations: usize,
628 first_violation: Option<String>,
629}
630
631impl Parity {
632 /// Element passes iff |a-c| <= tolerance_abs or |a-c| / max(|c|, eps) <=
633 /// tolerance_rel (acceptance.toml [numerics] relative error definition).
634 /// NaN never passes.
635 fn compare(&mut self, what: &str, row: &[f32], control: &[f32], tol: &Tolerance) {
636 if row.len() != control.len() {
637 self.violations += 1;
638 if self.first_violation.is_none() {
639 self.first_violation = Some(format!(
640 "{what}: length {} vs control {}",
641 row.len(),
642 control.len()
643 ));
644 }
645 return;
646 }
647 for (i, (a, c)) in row.iter().zip(control).enumerate() {
648 let abs = (f64::from(*a) - f64::from(*c)).abs();
649 let rel = abs / f64::from(c.abs()).max(tol.rel_eps);
650 self.compared_values += 1;
651 if abs.is_nan() || abs > self.max_abs {
652 self.max_abs = if abs.is_nan() { f64::INFINITY } else { abs };
653 }
654 if rel.is_nan() || rel > self.max_rel {
655 self.max_rel = if rel.is_nan() { f64::INFINITY } else { rel };
656 }
657 let ok = abs <= tol.abs || rel <= tol.rel;
658 if !ok {
659 self.violations += 1;
660 if self.first_violation.is_none() {
661 self.first_violation = Some(format!(
662 "{what}: logit {i} = {a} vs control {c} (abs {abs:e}, rel {rel:e})"
663 ));
664 }
665 }
666 }
667 }
668
669 fn pass(&self) -> bool {
670 self.violations == 0 && self.compared_values > 0
671 }
672}
673
674/// Fresh unpaged backend (own dense K/V, no KV manager), one-shot prefill of
675/// the root prompt, then the root's sampled token. Returns the backend.
676fn control_after_prompt(
677 weights: &TransformerWeights,
678 prompt: &[u32],
679 root_token: u32,
680) -> NativeTransformerBackend {
681 let mut control = NativeTransformerBackend::new(weights.clone());
682 assert!(control.kv_manager.is_none(), "control must be unpaged");
683 control
684 .prefill_sequence(CONTROL_ID, prompt)
685 .expect("control one-shot prefill");
686 control
687 .sequences
688 .get_mut(&CONTROL_ID)
689 .expect("control sequence")
690 .tokens
691 .push(root_token);
692 control
693}
694
695// ---------------------------------------------------------------------------
696// Receipt helpers
697// ---------------------------------------------------------------------------
698
699fn hardware() -> serde_json::Value {
700 let cpuinfo = std::fs::read_to_string("/proc/cpuinfo").unwrap_or_default();
701 let processors = cpuinfo
702 .lines()
703 .filter(|l| l.starts_with("processor"))
704 .count();
705 let mut fields: HashMap<String, Vec<String>> = HashMap::new();
706 for line in cpuinfo.lines() {
707 if let Some((k, v)) = line.split_once(':') {
708 let k = k.trim();
709 if matches!(
710 k,
711 "model name" | "Hardware" | "CPU implementer" | "CPU part" | "CPU architecture"
712 ) {
713 let entry = fields.entry(k.to_string()).or_default();
714 let v = v.trim().to_string();
715 if !entry.contains(&v) {
716 entry.push(v);
717 }
718 }
719 }
720 }
721 let uname = std::process::Command::new("uname")
722 .arg("-a")
723 .output()
724 .ok()
725 .filter(|o| o.status.success())
726 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
727 serde_json::json!({
728 "source": "/proc/cpuinfo + uname -a, read at runtime",
729 "processors": processors,
730 "cpuinfo": fields,
731 "uname": uname,
732 })
733}
734
735/// `git rev-parse HEAD` in this crate's directory, at runtime.
736fn commit_sha() -> Option<String> {
737 std::process::Command::new("git")
738 .args(["-C", env!("CARGO_MANIFEST_DIR"), "rev-parse", "HEAD"])
739 .output()
740 .ok()
741 .filter(|o| o.status.success())
742 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
743}
744
745struct Check {
746 name: &'static str,
747 pass: bool,
748 message: String,
749}
750
751fn check(name: &'static str, pass: bool, message: String) -> Check {
752 Check {
753 name,
754 pass,
755 message,
756 }
757}
758
759// ---------------------------------------------------------------------------
760// Pool sizing and branch sampling
761// ---------------------------------------------------------------------------
762
763/// Extra free blocks on top of the exact need (prefix + N x private suffix +
764/// watermark). Zero: the scheduler admits by the KV manager's incremental
765/// need (GB10-2), so the pool is sized to the true requirement.
766const POOL_SLACK_BLOCKS: usize = 0;
767
768struct PoolPlan {
769 prefix_blocks: usize,
770 per_branch_suffix_blocks: usize,
771 watermark_blocks: usize,
772 total_blocks: usize,
773}
774
775/// Blocks the pool needs for `n` branches over a `prompt_len`-token root.
776///
777/// - prefix: the root's blocks, held once.
778/// - per branch: a branch appends at most MAX_TOKENS_PER_BRANCH + 1 tokens
779/// (the sampled root token plus its decodes). A shared partial last block is
780/// copied on the first append (copy-on-write, crates/aien-kv-cache/src/
781/// lib.rs `append_token_with_slot`), so the private blocks a branch owns are
782/// ceil((prompt_len % block_size + appends) / block_size).
783/// - watermark: the scheduler preempts when free blocks fall below it, so the
784/// pool keeps that many free on top. Admission itself needs only the
785/// incremental blocks (GB10-2: `AienKvManager::incremental_blocks_needed`),
786/// not a whole prompt per branch.
787fn pool_plan(prompt_len: usize, block_size: usize, n: usize, watermark: usize) -> PoolPlan {
788 let prefix_blocks = prompt_len.div_ceil(block_size);
789 let appends = MAX_TOKENS_PER_BRANCH + 1;
790 let per_branch_suffix_blocks = (prompt_len % block_size + appends).div_ceil(block_size);
791 PoolPlan {
792 prefix_blocks,
793 per_branch_suffix_blocks,
794 watermark_blocks: watermark,
795 total_blocks: prefix_blocks + n * per_branch_suffix_blocks + watermark + POOL_SLACK_BLOCKS,
796 }
797}
798
799/// Indices of the branches that get a full per-step control: all of them for
800/// n <= SAMPLED_CONTROLS, otherwise SAMPLED_CONTROLS evenly spaced indices
801/// from 0 to n - 1 (first and last always included).
802fn sampled_indices(n: usize) -> Vec<usize> {
803 if n <= SAMPLED_CONTROLS {
804 return (0..n).collect();
805 }
806 (0..SAMPLED_CONTROLS)
807 .map(|i| i * (n - 1) / (SAMPLED_CONTROLS - 1))
808 .collect()
809}
810
811fn mem_total_bytes() -> Option<u64> {
812 std::fs::read_to_string("/proc/meminfo")
813 .ok()?
814 .lines()
815 .find_map(|l| l.strip_prefix("MemTotal:"))
816 .and_then(|rest| rest.split_whitespace().next()?.parse::<u64>().ok())
817 .map(|kib| kib * 1024)
818}
819
820// ---------------------------------------------------------------------------
821// One run at one N
822// ---------------------------------------------------------------------------
823
824struct Shared<'a> {
825 weights: &'a TransformerWeights,
826 prompt: &'a [u32],
827 tol: &'a Tolerance,
828 common: &'a serde_json::Value,
829}
830
831struct RunResult {
832 receipt: serde_json::Value,
833 checks: Vec<Check>,
834 pass: bool,
835}
836
837async fn run_one(n: usize, sh: &Shared<'_>) -> RunResult {
838 let prompt = sh.prompt;
839 let prompt_len = prompt.len();
840 let tol = sh.tol;
841
842 // Fresh controller state per N (RuntimeController persists operation ids).
843 let state_dir = tempfile::tempdir().expect("state dir");
844 std::env::set_var("AIEN_RUNTIME_STATE_DIR", state_dir.path());
845
846 let block_size = sh.weights.config.block_size;
847 let watermark = 2usize;
848 let plan = pool_plan(prompt_len, block_size, n, watermark);
849 let max_batch = 32usize.max(n + 2);
850 let scheduler = SchedulerConfig {
851 max_batch_size: max_batch,
852 max_batch_tokens: 4096,
853 max_prefill_tokens: 8192,
854 prefill_chunk_size: PREFILL_CHUNK,
855 chunk_prefill: true,
856 watermark_blocks: watermark,
857 };
858 let (mut spine, backend) = build_shared_kv_runtime(
859 sh.weights.clone(),
860 Arc::new(ReferenceCpuBackend::new()),
861 scheduler,
862 SharedKvSizing {
863 arena_capacity: n + 16,
864 total_blocks: plan.total_blocks,
865 },
866 )
867 .expect("build shared KV runtime");
868 let kv = spine.kv_manager.clone();
869 let backend_name = format!(
870 "NativeTransformerBackend/{} (paged, pooled shared KV)",
871 backend.tensor_backend.name()
872 );
873
874 let mut checks: Vec<Check> = Vec::new();
875
876 // (a) one root submitted via the spine swarm API.
877 let launch_at = Instant::now();
878 let swarm_id = spine
879 .launch_swarm(
880 SwarmConfig {
881 model_handle: 1,
882 branch_count: n,
883 max_active_sequences: n,
884 max_tokens_per_branch: MAX_TOKENS_PER_BRANCH,
885 root_world_id: 0,
886 priority: 1,
887 },
888 prompt,
889 )
890 .expect("launch swarm");
891 let swarm = spine
892 .swarm_manager
893 .get_swarm(swarm_id)
894 .expect("swarm record")
895 .clone();
896 let root = swarm.root_sequence_id.as_u64();
897 let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect();
898 let pending = spine.swarm_manager.pending_root_prefills();
899 checks.push(check(
900 "a_one_root",
901 pending.len() == 1
902 && pending[0].1 == root
903 && pending[0].2 == prompt
904 && spine.swarm_manager.active_swarm_count() == 1
905 && branches.len() == n,
906 format!(
907 "(a) ONE_ROOT_VIOLATION: N={n}: expected exactly one pending root ({root}) with the \
908 submitted prompt and {n} branches; pending roots {:?}, swarms {}, branches {}",
909 pending.iter().map(|p| p.1).collect::<Vec<_>>(),
910 spine.swarm_manager.active_swarm_count(),
911 branches.len()
912 ),
913 ));
914
915 // (a) allocating the root's KV does not make it ready.
916 let root_state = kv.read().prefill_state(root);
917 checks.push(check(
918 "a_allocated_not_ready",
919 root_state == Some(PrefillState::Allocated),
920 format!(
921 "(a) ALLOCATED_IS_NOT_READY_VIOLATION: N={n}: root KV state right after launch is \
922 {root_state:?}, expected Allocated (not ready)"
923 ),
924 ));
925
926 let sampled_idx = sampled_indices(n);
927 let sampled_ids: Vec<u64> = sampled_idx.iter().map(|i| branches[*i]).collect();
928 let mut tap = E2eTap {
929 inner: backend,
930 root,
931 branches: branches.clone(),
932 prompt: prompt.to_vec(),
933 launch_at,
934 prefill_chunks: Vec::new(),
935 prefill_wall: Duration::ZERO,
936 forks: Vec::new(),
937 fork_snapshot: None,
938 prefix_snapshot: None,
939 decode_logits: HashMap::new(),
940 decode_tokens: HashMap::new(),
941 decode_batches: Vec::new(),
942 first_branch_token: None,
943 peak_physical_pages: 0,
944 keep_all: sampled_ids.iter().copied().collect(),
945 };
946
947 // (a) no fork before the fence: neither the KV fork nor the backend fork.
948 let kv_fork = {
949 let mut guard = kv.write();
950 spine
951 .swarm_manager
952 .fork_branches_from_ready_root(swarm_id, &mut spine.arena, &mut guard)
953 };
954 let backend_fork = tap.inner.fork_sequence(root, branches[0]);
955 let any_branch_table = branches
956 .iter()
957 .any(|b| kv.read().get_block_table(*b).is_some());
958 checks.push(check(
959 "a_no_fork_before_ready",
960 kv_fork.is_err()
961 && backend_fork.is_err()
962 && !any_branch_table
963 && !tap.inner.sequences.contains_key(&branches[0]),
964 format!(
965 "(a) FORK_BEFORE_FENCE_VIOLATION: N={n}: before the fence the KV fork returned \
966 {kv_fork:?}, the backend fork returned {backend_fork:?}, branch KV tables exist: \
967 {any_branch_table}"
968 ),
969 ));
970
971 // Run spine steps until every branch finished. A step-guard hit, an idle
972 // step while work is waiting (starved branch) and a step error are FAILs.
973 let step_guard = 100 + 2 * n;
974 let mut run_error: Option<String> = None;
975 let mut steps = 0usize;
976 let mut idle = 0usize;
977 let mut guard_hit = false;
978 let mut starved = false;
979 while spine.scheduler.running_count() > 0
980 || spine.scheduler.waiting_count() > 0
981 || spine.swarm_manager.is_root_prefill_pending(swarm_id)
982 {
983 if steps >= step_guard {
984 guard_hit = true;
985 break;
986 }
987 steps += 1;
988 match spine.step(&mut tap).await {
989 Err(e) => {
990 run_error = Some(e);
991 break;
992 }
993 Ok(Some(_)) => idle = 0,
994 Ok(None) => {
995 idle += 1;
996 if idle >= 3 {
997 starved = true;
998 break;
999 }
1000 }
1001 }
1002 }
1003 let run_note = format!(
1004 "; spine steps {steps}/{step_guard}, step guard hit {guard_hit}, starved {starved}, \
1005 step error {run_error:?}"
1006 );
1007 let run_ok = run_error.is_none() && !guard_hit && !starved;
1008 checks.push(check(
1009 "run_completed",
1010 run_ok,
1011 format!(
1012 "(a) RUN_INCOMPLETE_VIOLATION: N={n}: the run did not finish cleanly (a step-guard \
1013 hit or a starved branch is a FAIL, never silent; pool {} blocks){run_note}",
1014 plan.total_blocks
1015 ),
1016 ));
1017
1018 // (a) model prefill executed.
1019 let root_chunks: Vec<&PrefillChunk> =
1020 tap.prefill_chunks.iter().filter(|c| c.id == root).collect();
1021 let root_prefilled: usize = root_chunks.iter().map(|c| c.len).sum();
1022 let other_prefills = tap.prefill_chunks.len() - root_chunks.len();
1023 let snap = tap.fork_snapshot.as_ref();
1024 let prefill_ok = root_prefilled == prompt_len
1025 && root_chunks.len() >= 2
1026 && other_prefills == 0
1027 && snap.is_some_and(|s| {
1028 s.root_backend_tokens == prompt_len && s.root_kv_values > 0 && s.root_kv_nonzero > 0
1029 });
1030 checks.push(check(
1031 "a_prefill_executed",
1032 prefill_ok,
1033 format!(
1034 "(a) PREFILL_EXECUTED_VIOLATION: N={n}: backend prefilled {root_prefilled}/{prompt_len} \
1035 root tokens in {} chunks, {other_prefills} non-root prefills; at the fence the backend \
1036 held {:?} root tokens and the pool held {:?} non-zero of {:?} root K/V values{run_note}",
1037 root_chunks.len(),
1038 snap.map(|s| s.root_backend_tokens),
1039 snap.map(|s| s.root_kv_nonzero),
1040 snap.map(|s| s.root_kv_values),
1041 ),
1042 ));
1043
1044 // (a) the completion fence made the root ready, and only after the prefill.
1045 let chunks_not_ready = root_chunks
1046 .iter()
1047 .all(|c| !matches!(c.state_before, Some(s) if s.is_ready()));
1048 checks.push(check(
1049 "a_fence_made_ready",
1050 chunks_not_ready && snap.is_some_and(|s| s.root_state.is_some_and(|st| st.is_ready())),
1051 format!(
1052 "(a) FENCE_VIOLATION: N={n}: root states before each prefill chunk {:?}; at the first \
1053 fork {:?}{run_note}",
1054 root_chunks
1055 .iter()
1056 .map(|c| c.state_before)
1057 .collect::<Vec<_>>(),
1058 snap.map(|s| s.root_state),
1059 ),
1060 ));
1061
1062 // N branches forked from the ready root, backend state included.
1063 let good_forks: Vec<&ForkRecord> = tap
1064 .forks
1065 .iter()
1066 .filter(|f| f.ok && f.parent == root && f.parent_ready && f.child_tokens_ok)
1067 .collect();
1068 let forked_children: Vec<u64> = good_forks.iter().map(|f| f.child).collect();
1069 let all_forked = branches.iter().all(|b| forked_children.contains(b))
1070 && good_forks.len() == n
1071 && tap.forks.len() == n
1072 && good_forks.iter().all(|f| f.temperature > 0.001);
1073 let root_token = snap.and_then(|s| s.root_pending_token);
1074 // Root continuation: fresh unpaged control, prompt + root token, one decode.
1075 // EVERY branch's step 1 is compared against it.
1076 let mut step1 = Parity::default();
1077 let mut step1_detail = String::new();
1078 if let (true, Some(root_token)) = (all_forked, root_token) {
1079 let mut control = control_after_prompt(&tap.inner.weights, prompt, root_token);
1080 let (_o, ctl) = control
1081 .forward_decode_batch_with_logits(&[CONTROL_ID])
1082 .expect("root continuation control decode");
1083 let root_continuation = ctl.into_iter().next().expect("control logits");
1084 for b in &branches {
1085 match tap.decode_logits.get(b).and_then(|v| v.first()) {
1086 Some(first) => step1.compare(
1087 &format!("branch {b} step 1"),
1088 first,
1089 &root_continuation,
1090 tol,
1091 ),
1092 None => {
1093 step1.violations += 1;
1094 step1_detail.push_str(&format!(" branch {b} never decoded;"));
1095 }
1096 }
1097 }
1098 }
1099 checks.push(check(
1100 "b_forks_and_step1",
1101 all_forked && root_token.is_some() && step1.pass(),
1102 format!(
1103 "(a/b) BRANCH_FORK_VIOLATION: N={n}: {} fork hook calls, {} valid (parent ready, child \
1104 = prompt + root token, sampling params); root token {root_token:?}; step-1 of all {n} \
1105 branches vs root continuation: max_abs {:e}, violations {}{}{step1_detail}{run_note}",
1106 tap.forks.len(),
1107 good_forks.len(),
1108 step1.max_abs,
1109 step1.violations,
1110 step1
1111 .first_violation
1112 .as_deref()
1113 .map_or(String::new(), |v| format!(", first: {v}")),
1114 ),
1115 ));
1116
1117 // (b) sampled branches, every step, vs independent controls.
1118 let mut parity = Parity::default();
1119 let mut b9_detail = String::new();
1120 let generated: Vec<Vec<u32>> = branches
1121 .iter()
1122 .map(|b| tap.decode_tokens.get(b).cloned().unwrap_or_default())
1123 .collect();
1124 match root_token {
1125 Some(root_token) if run_ok => {
1126 for (idx, b) in sampled_idx.iter().zip(&sampled_ids) {
1127 let gen = &generated[*idx];
1128 let rows = tap.decode_logits.get(b).cloned().unwrap_or_default();
1129 if rows.is_empty() || rows.len() != gen.len() {
1130 parity.violations += 1;
1131 b9_detail.push_str(&format!(
1132 " branch {b}: {} logit rows for {} tokens;",
1133 rows.len(),
1134 gen.len()
1135 ));
1136 continue;
1137 }
1138 let mut control = control_after_prompt(&tap.inner.weights, prompt, root_token);
1139 for (k, row) in rows.iter().enumerate() {
1140 let (_o, ctl) = control
1141 .forward_decode_batch_with_logits(&[CONTROL_ID])
1142 .expect("control decode");
1143 let ctl_row = ctl.into_iter().next().expect("control logits");
1144 parity.compare(&format!("branch {b} step {}", k + 1), row, &ctl_row, tol);
1145 // Teacher forcing with this branch's own token only.
1146 let seq = control.sequences.get_mut(&CONTROL_ID).expect("control seq");
1147 seq.tokens.pop();
1148 seq.tokens.push(gen[k]);
1149 }
1150 }
1151 }
1152 _ => {
1153 parity.violations += 1;
1154 b9_detail.push_str(" no root token / run failed;");
1155 }
1156 }
1157 let parity_pass = parity.pass() && step1.pass() && sampled_ids.len() >= n.min(SAMPLED_CONTROLS);
1158 checks.push(check(
1159 "b_parity_vs_controls",
1160 parity_pass,
1161 format!(
1162 "(b) BRANCH_PARITY_VIOLATION: N={n}: {} sampled controls; max_abs {:e}, max_rel {:e} \
1163 over {} values vs tolerance abs {:e} rel {:e} (acceptance.toml); {} violations{}{b9_detail}{run_note}",
1164 sampled_ids.len(),
1165 parity.max_abs,
1166 parity.max_rel,
1167 parity.compared_values,
1168 tol.abs,
1169 tol.rel,
1170 parity.violations,
1171 parity
1172 .first_violation
1173 .as_deref()
1174 .map_or(String::new(), |v| format!(", first: {v}")),
1175 ),
1176 ));
1177
1178 // (c) common prefix held once, physical KV bounded.
1179 let prefix = tap.prefix_snapshot.as_ref();
1180 let block_bytes = prefix.map_or(0, |p| p.block_bytes);
1181 let r = plan.prefix_blocks;
1182 let prefix_ok = prefix.is_some_and(|p| {
1183 p.root_blocks.len() == r
1184 && p.branches_share_root_blocks
1185 && p.physical_pages == r
1186 && p.allocated_blocks == r
1187 && p.shared_pages == r
1188 && p.logical_pages == (n + 1) * r
1189 });
1190 checks.push(check(
1191 "c_prefix_held_once",
1192 prefix_ok,
1193 format!(
1194 "(c) PREFIX_MULTIPLIED_VIOLATION: N={n}: at the first decode: root blocks {:?} (expected \
1195 {r}), branches share them {:?}, KvMetrics physical {:?} logical {:?} (expected {}) \
1196 shared {:?}, allocated {:?}{run_note}",
1197 prefix.map(|p| p.root_blocks.len()),
1198 prefix.map(|p| p.branches_share_root_blocks),
1199 prefix.map(|p| p.physical_pages),
1200 prefix.map(|p| p.logical_pages),
1201 (n + 1) * r,
1202 prefix.map(|p| p.shared_pages),
1203 prefix.map(|p| p.allocated_blocks),
1204 ),
1205 ));
1206 let prefix_bytes = r * block_bytes;
1207 let per_branch_suffix_bytes = plan.per_branch_suffix_blocks * block_bytes;
1208 let bound_bytes = prefix_bytes + n * per_branch_suffix_bytes;
1209 let peak_bytes = tap.peak_physical_pages * block_bytes;
1210 let logical_bytes = prefix.map_or(0, |p| p.logical_pages * block_bytes);
1211 let physical_bytes = prefix.map_or(0, |p| p.physical_pages * block_bytes);
1212 let bounded = block_bytes > 0
1213 && tap.peak_physical_pages >= r
1214 && peak_bytes <= bound_bytes
1215 && (n == 1 || peak_bytes < logical_bytes);
1216 checks.push(check(
1217 "c_physical_kv_bounded",
1218 bounded,
1219 format!(
1220 "(c) PHYSICAL_KV_BOUND_VIOLATION: N={n}: physical peak {peak_bytes} bytes ({} pages) vs \
1221 bound prefix {prefix_bytes} + {n} x {per_branch_suffix_bytes} = {bound_bytes} bytes, \
1222 logical {logical_bytes} bytes (for N > 1 the peak must be below logical){run_note}",
1223 tap.peak_physical_pages
1224 ),
1225 ));
1226
1227 // (d) divergence and isolation (isolation proper is the controls above).
1228 let distinct: std::collections::HashSet<&Vec<u32>> = generated.iter().collect();
1229 let all_generated = generated.iter().all(|g| !g.is_empty());
1230 // Branches diverge only by their sampling seeds, so with few branches and
1231 // 4 tokens each, identical outputs are an ordinary coincidence (observed at
1232 // N=2, 2026-10-03). Divergence is required from DIVERGENCE_MIN_N branches
1233 // on, where every branch sampling the same 4 tokens would be a defect;
1234 // below that the distinct count is recorded, not judged.
1235 let divergence_required = n >= DIVERGENCE_MIN_N;
1236 let diverged = all_generated && (!divergence_required || distinct.len() >= 2);
1237 let mixed_batch = !divergence_required
1238 || tap.decode_batches.iter().any(|rows| {
1239 let fed: Vec<u32> = rows
1240 .iter()
1241 .filter(|(id, _)| branches.contains(id))
1242 .map(|(_, t)| *t)
1243 .collect();
1244 fed.len() >= 2 && fed.iter().any(|t| *t != fed[0])
1245 });
1246 checks.push(check(
1247 "d_isolation",
1248 diverged && mixed_batch && parity_pass,
1249 format!(
1250 "(d) BRANCH_ISOLATION_VIOLATION: N={n}: every branch produced tokens {all_generated}, \
1251 {} distinct outputs among {n} (need >= 2 when N >= {DIVERGENCE_MIN_N}), a decode batch mixed different \
1252 branch inputs {mixed_batch}, control parity {parity_pass}{run_note}",
1253 distinct.len()
1254 ),
1255 ));
1256
1257 // (e) everything reclaimed.
1258 let backend_sequences = tap.inner.sequences.len();
1259 let backend_pending = tap.inner.pending_prefill_token.len();
1260 let backend_sampling = std::iter::once(root)
1261 .chain(branches.iter().copied())
1262 .filter(|id| tap.inner.sampling_params(*id).is_some())
1263 .count();
1264 let kv_allocated = kv.read().allocated_block_count();
1265 let arena_active = spine.arena.active_count();
1266 let branch_worlds = swarm
1267 .branch_worlds
1268 .iter()
1269 .filter(|w| spine.world_store.get_world(**w).is_some())
1270 .count();
1271 let scheduler_live = spine.scheduler.running_count() + spine.scheduler.waiting_count();
1272 let finished = spine.scheduler.metrics().finished_requests as usize;
1273 checks.push(check(
1274 "e_reclaimed",
1275 run_ok
1276 && finished == n
1277 && backend_sequences == 0
1278 && backend_pending == 0
1279 && backend_sampling == 0
1280 && kv_allocated == 0
1281 && arena_active == 0
1282 && branch_worlds == 0
1283 && scheduler_live == 0
1284 && spine.swarm_manager.active_swarm_count() == 0,
1285 format!(
1286 "(e) RECLAIM_VIOLATION: N={n}: finished {finished}/{n}; backend sequences \
1287 {backend_sequences}, pending prefill tokens {backend_pending}, sampling entries \
1288 {backend_sampling}; KV allocated blocks {kv_allocated}; arena active {arena_active}; \
1289 branch worlds {branch_worlds}; scheduler live {scheduler_live}; active swarms {}{run_note}",
1290 spine.swarm_manager.active_swarm_count()
1291 ),
1292 ));
1293
1294 let pass = checks.iter().all(|c| c.pass);
1295 let prefill_secs = tap.prefill_wall.as_secs_f64();
1296 let ttft_ms: Option<f64> = tap.first_branch_token.map(|d| d.as_secs_f64() * 1e3);
1297 let prefill_tps: Option<f64> = if prefill_secs > 0.0 {
1298 Some(root_prefilled as f64 / prefill_secs)
1299 } else {
1300 None
1301 };
1302 let pool_bytes = plan.total_blocks * block_bytes;
1303 let parity_result = if parity_pass { "PASS" } else { "FAIL" };
1304 let verdict = if pass { "PASS" } else { "FAIL" };
1305 let checks_json: Vec<serde_json::Value> = checks
1306 .iter()
1307 .map(|c| serde_json::json!({ "name": c.name, "pass": c.pass }))
1308 .collect();
1309 let mut receipt = sh.common.clone();
1310 let obj = receipt.as_object_mut().expect("common receipt object");
1311 let fields = serde_json::json!({
1312 "branch_count": n,
1313 "max_tokens_per_branch": MAX_TOKENS_PER_BRANCH,
1314 "backend": backend_name,
1315 "prompt_chunks": root_chunks.len(),
1316 "ttft_ms": ttft_ms,
1317 "ttft_definition": "launch_swarm call to the end of the first execute_step that emitted a branch token",
1318 "prefill_tokens_per_s": prefill_tps,
1319 "physical_kv_bytes": physical_bytes,
1320 "physical_kv_bytes_peak": peak_bytes,
1321 "logical_kv_bytes": logical_bytes,
1322 "prefix_bytes": prefix_bytes,
1323 "per_branch_suffix_bytes": per_branch_suffix_bytes,
1324 "physical_kv_bytes_bound": bound_bytes,
1325 "bound_formula": "prefix_bytes + branch_count x per_branch_suffix_bytes",
1326 "kv_block_bytes": block_bytes,
1327 "kv_source": "KvMetrics physical_pages/logical_pages x pool block_bytes at the first decode batch; peak = max physical_pages after each decode step",
1328 "pool": {
1329 "total_blocks": plan.total_blocks,
1330 "pool_bytes": pool_bytes,
1331 "prefix_blocks": plan.prefix_blocks,
1332 "per_branch_suffix_blocks": plan.per_branch_suffix_blocks,
1333 "watermark_blocks": plan.watermark_blocks,
1334 "slack_blocks": POOL_SLACK_BLOCKS,
1335 "max_batch_size": max_batch,
1336 "host_mem_total_bytes": mem_total_bytes(),
1337 "headroom_reason": "scheduler admission (crates/aien-scheduler/src/lib.rs build_scheduled_batch step 3) asks AienKvManager::incremental_blocks_needed (GB10-2), so a fork child needs only its copy-on-write block at admission; the pool holds prefix + N x private suffix blocks + watermark, no whole-prompt headroom and no slack.",
1338 },
1339 "parity": {
1340 "result": parity_result,
1341 "max_abs": parity.max_abs,
1342 "max_rel": parity.max_rel,
1343 "tolerance_abs": tol.abs,
1344 "tolerance_rel": tol.rel,
1345 "relative_error_epsilon": tol.rel_eps,
1346 "compared_values": parity.compared_values,
1347 "tolerance_source": "docs/campaigns/c1/acceptance.toml [numerics.noise_floor.tinyllama]",
1348 "sampled_controls": sampled_ids.len(),
1349 "sampled_branch_indices": sampled_idx,
1350 "sampling_rule": "all branches when N <= 8, else 8 evenly spaced indices i*(N-1)/7 incl. first and last; every branch's step 1 is compared against the root continuation",
1351 "step1_all_branches": { "compared_values": step1.compared_values, "violations": step1.violations, "max_abs": step1.max_abs },
1352 },
1353 "distinct_outputs": distinct.len(),
1354 "generated_tokens": generated,
1355 "spine_steps": steps,
1356 "step_guard": step_guard,
1357 "step_guard_hit": guard_hit,
1358 "starved": starved,
1359 "run_error": run_error,
1360 "checks": checks_json,
1361 "verdict": verdict,
1362 });
1363 for (k, v) in fields.as_object().expect("fields").iter() {
1364 obj.insert(k.clone(), v.clone());
1365 }
1366 RunResult {
1367 receipt,
1368 checks,
1369 pass,
1370 }
1371}
1372
1373fn write_receipt(path: &Path, receipts: &[serde_json::Value]) {
1374 if let Some(dir) = path.parent() {
1375 if !dir.as_os_str().is_empty() {
1376 std::fs::create_dir_all(dir).expect("receipt directory");
1377 }
1378 }
1379 let line = serde_json::to_string(receipts).expect("receipt JSON");
1380 std::fs::write(path, format!("{line}\n")).expect("write receipt");
1381}
1382
1383// ---------------------------------------------------------------------------
1384// The gate
1385// ---------------------------------------------------------------------------
1386
1387#[tokio::test]
1388#[ignore = "PREFILL-E2E-1 real-checkpoint gate at N = 1/8/32/128/500: run with --ignored and \
1389 AIEN_E2E_CHECKPOINT + AIEN_E2E1_RECEIPT set (forge on the Spark)"]
1390async fn prefill_e2e1_real_checkpoint_n_branch_gate() {
1391 let checkpoint = required_env("AIEN_E2E_CHECKPOINT");
1392 let receipt_path = PathBuf::from(required_env("AIEN_E2E1_RECEIPT"));
1393
1394 let paths = checkpoint_paths(&checkpoint);
1395 let model_sha256 = sha256_file_hex(&paths.model);
1396 let tokenizer_sha256 = sha256_file_hex(&paths.tokenizer);
1397 let weights = strict_load(&paths);
1398 let model_id = weights.config.model_id.clone();
1399 let tokenizer = TinyLlamaTokenizer::from_file(&paths.tokenizer).unwrap_or_else(|e| {
1400 panic!(
1401 "STRICT_CHECKPOINT_VIOLATION: tokenizer {} failed to parse: {e:?}",
1402 paths.tokenizer.display()
1403 )
1404 });
1405 let tol = acceptance_tolerance();
1406 assert_eq!(
1407 tol.floor_status, "measured",
1408 "PARITY_TOLERANCE: [numerics.noise_floor.tinyllama] status must be measured"
1409 );
1410 assert_eq!(
1411 tol.floor_model_sha256, model_sha256,
1412 "PARITY_TOLERANCE: the frozen TinyLlama floor was measured on a different checkpoint"
1413 );
1414 assert!(
1415 tol.abs == 0.0 && tol.rel == 0.0,
1416 "PARITY_TOLERANCE: the frozen tolerance is exact equality (0.0); got abs {:e} rel {:e}",
1417 tol.abs,
1418 tol.rel
1419 );
1420
1421 let prompt_text = TinyLlamaTokenizer::format_prompt(Some(SYSTEM_PROMPT), USER_PROMPT);
1422 let prompt = tokenizer.encode(&prompt_text).expect("encode root prompt");
1423 let prompt_len = prompt.len();
1424 assert!(
1425 prompt_len > PREFILL_CHUNK,
1426 "PROMPT_LENGTH: root prompt is {prompt_len} tokens; it must exceed the {PREFILL_CHUNK}-token \
1427 prefill chunk so the chunk continuation runs"
1428 );
1429 let prompt_digest = {
1430 let mut h = Sha256::new();
1431 for t in &prompt {
1432 h.update(t.to_le_bytes());
1433 }
1434 hex(&h.finalize())
1435 };
1436 println!("PREFILL_E2E1 root prompt: {prompt_len} tokens");
1437
1438 let common = serde_json::json!({
1439 "gate": "PREFILL-E2E-1",
1440 "model": { "path": paths.model.display().to_string(), "id": model_id },
1441 "model_sha256": model_sha256,
1442 "tokenizer": { "path": paths.tokenizer.display().to_string() },
1443 "tokenizer_sha256": tokenizer_sha256,
1444 "prompt_tokens": prompt_len,
1445 "prompt_digest_sha256": prompt_digest,
1446 "prompt_digest_encoding": "sha256 over the token ids as little-endian u32",
1447 "hardware": hardware(),
1448 "kernel_exec_count": serde_json::Value::Null,
1449 "fallback_count": serde_json::Value::Null,
1450 "counters_reason": "ReferenceCpuBackend keeps no kernel/fallback counters; they exist only \
1451 on OmegaGb10Backend (CPU path per the 2026-10-01 queen ruling)",
1452 "commit_sha": commit_sha(),
1453 "commit_sha_source": "git rev-parse HEAD in CARGO_MANIFEST_DIR at runtime",
1454 "gb10": "NOT_RUN",
1455 "max_comparison": "NOT_RUN",
1456 });
1457 let shared = Shared {
1458 weights: &weights,
1459 prompt: &prompt,
1460 tol: &tol,
1461 common: &common,
1462 };
1463
1464 let mut receipts: Vec<serde_json::Value> = Vec::new();
1465 let mut results: Vec<(usize, Vec<Check>)> = Vec::new();
1466 let mut failed_at: Option<usize> = None;
1467 for &n in &BRANCH_COUNTS {
1468 if let Some(bad) = failed_at {
1469 receipts.push(serde_json::json!({
1470 "gate": "PREFILL-E2E-1",
1471 "branch_count": n,
1472 "verdict": "NOT_RUN",
1473 "not_run_after_failure": bad,
1474 }));
1475 continue;
1476 }
1477 println!("PREFILL_E2E1 running N = {n}");
1478 let run = run_one(n, &shared).await;
1479 println!(
1480 "PREFILL_E2E1_RECEIPT N={n} {}",
1481 serde_json::to_string(&run.receipt).expect("receipt JSON")
1482 );
1483 receipts.push(run.receipt);
1484 if !run.pass {
1485 failed_at = Some(n);
1486 }
1487 results.push((n, run.checks));
1488 // Partial receipt after every N so a later crash keeps the evidence.
1489 write_receipt(&receipt_path, &receipts);
1490 }
1491 write_receipt(&receipt_path, &receipts);
1492
1493 // Assert every check, in order, only after the receipt is on disk.
1494 for (_n, checks) in &results {
1495 for c in checks {
1496 assert!(c.pass, "{}", c.message);
1497 }
1498 }
1499 assert!(
1500 failed_at.is_none(),
1501 "PREFILL_E2E1 failed at N = {failed_at:?}"
1502 );
1503}