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_e2e0.rs

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