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
aien-sovereign-core-mv / crates / aien-runtime / tests / prefill_e2e2.rs
| 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-2: append 24 tokens to an already prefilled context that is |
| 17 | //! shared with a witness, recompute only the new part, fork two branches off |
| 18 | //! the longer context and decode them (TinyLlama, CPU, strict checkpoint). |
| 19 | //! |
| 20 | //! `#[ignore]`d for normal CI. Run with `--ignored`; it FAILS (never skips) |
| 21 | //! when `AIEN_E2E_CHECKPOINT` or `AIEN_E2E2_RECEIPT` is unset. |
| 22 | //! |
| 23 | //! `AIEN_E2E_CHECKPOINT` is the TinyLlama-1.1B-Chat-v1.0 directory (holding |
| 24 | //! `model.safetensors` and `tokenizer.json`) or the `.safetensors` file. |
| 25 | //! `AIEN_E2E2_RECEIPT` is the path of the JSON receipt (one object). |
| 26 | //! |
| 27 | //! Level of the test: the backend, driven with hand-built `ScheduledBatch` |
| 28 | //! values through `execute_step` for every prefill step (two chunks of 128 and |
| 29 | //! 89 tokens, then the append). There is no scheduler and no spine step. The |
| 30 | //! KV manager calls the scheduler makes around a prefill (`allocate_sequence` |
| 31 | //! for the whole prompt, `mark_prefill_pending`, `complete_prefill`, then |
| 32 | //! `fork_prefilled` plus the backend fork hook) are made here by hand in the |
| 33 | //! same order (crates/aien-scheduler/src/lib.rs `build_scheduled_batch` and |
| 34 | //! `step`). Decode steps call `forward_decode_batch_with_logits`, the inherent |
| 35 | //! method that `execute_step` itself reaches through `forward_decode_batch` |
| 36 | //! (both end in `forward_decode_batch_impl`), because `execute_step` does not |
| 37 | //! return logits and the gate compares full logit vectors at tolerance 0.0. |
| 38 | //! |
| 39 | //! Flow: the 217-token prompt is prefilled in two chunks and fenced. A witness |
| 40 | //! sequence W is forked from it BEFORE the append, so the root's partial tail |
| 41 | //! block (block 13, 9 of 16 slots used) is shared. The root then receives ONE |
| 42 | //! more prefill request for the same sequence id holding only the 24 new |
| 43 | //! tokens. That append starts mid-block (block 13, slot 9) and crosses two |
| 44 | //! block boundaries, ending at 241 tokens in 16 blocks. Its first write must |
| 45 | //! copy-on-write the shared tail (crates/aien-kv-cache/src/lib.rs |
| 46 | //! `append_token_with_slot`). Two branches are then forked off the 241-token |
| 47 | //! root and decode 4 tokens each, in one batch together with W. Branch 2 is |
| 48 | //! teacher forced to its second best token after every step so the two |
| 49 | //! branches really diverge, which is what lets the isolation checks bite. |
| 50 | //! |
| 51 | //! Controls: a fresh UNPAGED `NativeTransformerBackend` prefills all 241 tokens |
| 52 | //! in one shot (the E1 `control_after_prompt` pattern) and decodes the same 4 |
| 53 | //! steps per branch with the branch's own fed tokens; a second unpaged |
| 54 | //! sequence prefills only the 217-token prompt and is the control for W. |
| 55 | //! Tolerance is 0.0 (docs/campaigns/c1/acceptance.toml |
| 56 | //! `[numerics.noise_floor.tinyllama]`), asserted explicitly. |
| 57 | //! |
| 58 | //! Counting backend: a `TensorBackend` wrapper that forwards every method to |
| 59 | //! `ReferenceCpuBackend` (so the arithmetic is bit identical) and records the |
| 60 | //! position of every `apply_rope` call. It is injected through the |
| 61 | //! `Arc<dyn TensorBackend>` parameter of `build_shared_kv_runtime`, so no |
| 62 | //! runtime code changes. During the append the recorded positions must be |
| 63 | //! exactly 217..=240, each once per layer. |
| 64 | //! |
| 65 | //! Checks (each has its own marker in the failure message, all failing |
| 66 | //! messages are printed and the receipt is written before any assert fires): |
| 67 | //! a_kv_equals_control KV_PARITY_VIOLATION, b_logits_and_tokens |
| 68 | //! LOGITS_TOKENS_VIOLATION, c_blocks OLD_BLOCKS_REWRITTEN_VIOLATION, |
| 69 | //! d_only_new_computed RECOMPUTE_ALL_VIOLATION, e_isolation |
| 70 | //! BRANCH_ISOLATION_VIOLATION, e_cow_witness COW_VIOLATION, |
| 71 | //! f_no_pool_exhaustion POOL_EXHAUSTION_VIOLATION (or APPEND_ERROR_VIOLATION |
| 72 | //! when the append returns Err), g_reclaimed RECLAIM_VIOLATION, h_fence |
| 73 | //! FENCE_VIOLATION (carried over from E1). |
| 74 | //! |
| 75 | //! Evidence label: host CPU only (ReferenceCpuBackend, FP32). Not a GB10 GPU |
| 76 | //! result and not a MAX comparison; both are recorded as NOT_RUN. |
| 77 | |
| 78 | #![recursion_limit = "512"] |
| 79 | |
| 80 | use std::collections::{BTreeMap, HashMap}; |
| 81 | use std::io::{Read, Seek, SeekFrom}; |
| 82 | use std::path::{Path, PathBuf}; |
| 83 | use std::sync::Arc; |
| 84 | use std::time::Instant; |
| 85 | |
| 86 | use aien_inference_abi::tensor::sample_argmax; |
| 87 | use aien_inference_abi::{ |
| 88 | AienInferenceBackend, DecodeOutput, FinishReason, ModelConfig, NativeTransformerBackend, |
| 89 | PrefillState, ReferenceCpuBackend, SamplingParams, ScheduledBatch, SequenceRequest, |
| 90 | TensorBackend, TinyLlamaTokenizer, TransformerWeights, |
| 91 | }; |
| 92 | use aien_kv_cache::SharedKvManager; |
| 93 | use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing, SHARED_KV_DTYPE}; |
| 94 | use aien_scheduler::SchedulerConfig; |
| 95 | use parking_lot::Mutex; |
| 96 | use sha2::{Digest, Sha256}; |
| 97 | |
| 98 | /// Prompt length the block arithmetic below is built for (E1 prompt). |
| 99 | const PROMPT_TOKENS: usize = 217; |
| 100 | /// Tokens appended to the prefilled context in ONE prefill request. |
| 101 | const APPENDED_TOKENS: usize = 24; |
| 102 | const TOTAL_TOKENS: usize = PROMPT_TOKENS + APPENDED_TOKENS; |
| 103 | /// Decode budget per branch (and for the witness). |
| 104 | const DECODE_STEPS: usize = 4; |
| 105 | /// The daemon's prefill chunk size (crates/aien-cli/src/commands.rs). |
| 106 | const PREFILL_CHUNK: usize = 128; |
| 107 | /// Extra free blocks on top of the exact need. |
| 108 | const POOL_SLACK_BLOCKS: usize = 3; |
| 109 | |
| 110 | /// Sequence ids in the paged runtime. |
| 111 | const ROOT: u64 = 100; |
| 112 | const WITNESS: u64 = 101; |
| 113 | const BRANCH_1: u64 = 102; |
| 114 | const BRANCH_2: u64 = 103; |
| 115 | /// Never gets a table; target of the fork-before-fence refusal probe. |
| 116 | const SCRATCH: u64 = 999; |
| 117 | const BRANCHES: [u64; 2] = [BRANCH_1, BRANCH_2]; |
| 118 | /// Sequence ids inside the single unpaged control backend. |
| 119 | const CTL_ROOT: u64 = 1; |
| 120 | const CTL_B1: u64 = 2; |
| 121 | const CTL_B2: u64 = 3; |
| 122 | const CTL_W: u64 = 4; |
| 123 | |
| 124 | const SYSTEM_PROMPT: &str = "You are a careful engineering assistant. You answer in plain \ |
| 125 | English, you show the steps of your reasoning, and you never invent numbers you were not given."; |
| 126 | |
| 127 | const USER_PROMPT: &str = "A small workshop builds wooden chairs. Each chair needs four legs, \ |
| 128 | one seat, two side rails, one back rest and twelve screws. The workshop has ninety legs, \ |
| 129 | twenty seats, forty side rails, eighteen back rests and two hundred screws in stock. Two of \ |
| 130 | the seats are cracked and cannot be used, and one box of twenty screws turned out to be the \ |
| 131 | wrong size. The carpenter wants to know how many complete chairs can be built today, which \ |
| 132 | part runs out first, and how many of every other part will be left over afterwards. After \ |
| 133 | that, suggest the smallest order of extra parts that would let the workshop build exactly \ |
| 134 | twenty five chairs tomorrow, and explain briefly why that order is the smallest one."; |
| 135 | |
| 136 | /// Fixed text for the appended span. It is tokenized without special tokens and |
| 137 | /// the first APPENDED_TOKENS ids are used (the text is longer than that). |
| 138 | const APPEND_TEXT: &str = "Please also list the tools the carpenter needs on the bench for \ |
| 139 | this job: a saw, a drill, a sander and a screwdriver, and say which one is used first and why."; |
| 140 | |
| 141 | // --------------------------------------------------------------------------- |
| 142 | // Environment, strict checkpoint, acceptance tolerance (copied from E1) |
| 143 | // --------------------------------------------------------------------------- |
| 144 | |
| 145 | struct CheckpointPaths { |
| 146 | model: PathBuf, |
| 147 | tokenizer: PathBuf, |
| 148 | } |
| 149 | |
| 150 | fn required_env(name: &str) -> String { |
| 151 | match std::env::var(name) { |
| 152 | Ok(v) if !v.trim().is_empty() => v.trim().to_string(), |
| 153 | _ => panic!( |
| 154 | "PREFILL_E2E2_ENV: {name} is unset; this gate never skips (set it and rerun with \ |
| 155 | --ignored)" |
| 156 | ), |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn checkpoint_paths(raw: &str) -> CheckpointPaths { |
| 161 | let p = PathBuf::from(raw); |
| 162 | let (model, dir) = if p.is_dir() { |
| 163 | (p.join("model.safetensors"), p.clone()) |
| 164 | } else { |
| 165 | let dir = p.parent().map(Path::to_path_buf).unwrap_or_default(); |
| 166 | (p.clone(), dir) |
| 167 | }; |
| 168 | let tokenizer = dir.join("tokenizer.json"); |
| 169 | assert!( |
| 170 | model.is_file(), |
| 171 | "STRICT_CHECKPOINT_VIOLATION: checkpoint {} does not exist; refusing to fall back \ |
| 172 | (AIEN_REQUIRE_CHECKPOINT=1 semantics)", |
| 173 | model.display() |
| 174 | ); |
| 175 | assert!( |
| 176 | tokenizer.is_file(), |
| 177 | "STRICT_CHECKPOINT_VIOLATION: tokenizer {} does not exist; refusing to fall back", |
| 178 | tokenizer.display() |
| 179 | ); |
| 180 | CheckpointPaths { model, tokenizer } |
| 181 | } |
| 182 | |
| 183 | fn sha256_file_hex(path: &Path) -> String { |
| 184 | let mut file = std::fs::File::open(path) |
| 185 | .unwrap_or_else(|e| panic!("STRICT_CHECKPOINT_VIOLATION: open {}: {e}", path.display())); |
| 186 | let mut hasher = Sha256::new(); |
| 187 | let mut buf = vec![0u8; 1 << 20]; |
| 188 | loop { |
| 189 | let n = file |
| 190 | .read(&mut buf) |
| 191 | .unwrap_or_else(|e| panic!("read {}: {e}", path.display())); |
| 192 | if n == 0 { |
| 193 | break; |
| 194 | } |
| 195 | hasher.update(&buf[..n]); |
| 196 | } |
| 197 | hex(&hasher.finalize()) |
| 198 | } |
| 199 | |
| 200 | fn hex(bytes: &[u8]) -> String { |
| 201 | bytes.iter().map(|b| format!("{b:02x}")).collect() |
| 202 | } |
| 203 | |
| 204 | fn f16_to_f32(bits: u16) -> f32 { |
| 205 | let sign = ((bits >> 15) & 1) as u32; |
| 206 | let exp = ((bits >> 10) & 0x1f) as u32; |
| 207 | let frac = (bits & 0x3ff) as u32; |
| 208 | let out = if exp == 0 { |
| 209 | if frac == 0 { |
| 210 | sign << 31 |
| 211 | } else { |
| 212 | // Subnormal: renormalize. |
| 213 | let mut e: i32 = 0; |
| 214 | let mut f = frac; |
| 215 | while f & 0x400 == 0 { |
| 216 | f <<= 1; |
| 217 | e -= 1; |
| 218 | } |
| 219 | let exp32 = (127 - 15 + 1 + e) as u32; |
| 220 | (sign << 31) | (exp32 << 23) | ((f & 0x3ff) << 13) |
| 221 | } |
| 222 | } else if exp == 31 { |
| 223 | (sign << 31) | (0xff << 23) | (frac << 13) |
| 224 | } else { |
| 225 | (sign << 31) | ((exp + 127 - 15) << 23) | (frac << 13) |
| 226 | }; |
| 227 | f32::from_bits(out) |
| 228 | } |
| 229 | |
| 230 | /// Reads `count` values starting at element `first` of tensor `name` straight |
| 231 | /// from the safetensors file (8-byte header length, JSON header, data), with |
| 232 | /// no aien code involved. |
| 233 | fn read_tensor_values(path: &Path, name: &str, first: usize, count: usize) -> Vec<f32> { |
| 234 | let mut file = std::fs::File::open(path).expect("open checkpoint"); |
| 235 | let mut len_buf = [0u8; 8]; |
| 236 | file.read_exact(&mut len_buf) |
| 237 | .expect("safetensors header length"); |
| 238 | let header_len = u64::from_le_bytes(len_buf) as usize; |
| 239 | let mut header = vec![0u8; header_len]; |
| 240 | file.read_exact(&mut header).expect("safetensors header"); |
| 241 | let header: serde_json::Value = serde_json::from_slice(&header).expect("header JSON"); |
| 242 | let info = header |
| 243 | .get(name) |
| 244 | .unwrap_or_else(|| panic!("STRICT_CHECKPOINT_VIOLATION: tensor {name} not in checkpoint")); |
| 245 | let dtype = info["dtype"].as_str().expect("dtype").to_string(); |
| 246 | let start = info["data_offsets"][0].as_u64().expect("data_offsets") as usize; |
| 247 | let width = match dtype.as_str() { |
| 248 | "F32" => 4, |
| 249 | "BF16" | "F16" => 2, |
| 250 | other => panic!("unsupported checkpoint dtype {other}"), |
| 251 | }; |
| 252 | let mut raw = vec![0u8; count * width]; |
| 253 | file.seek(SeekFrom::Start( |
| 254 | (8 + header_len + start + first * width) as u64, |
| 255 | )) |
| 256 | .expect("seek tensor"); |
| 257 | file.read_exact(&mut raw).expect("read tensor bytes"); |
| 258 | raw.chunks_exact(width) |
| 259 | .map(|c| match dtype.as_str() { |
| 260 | "F32" => f32::from_le_bytes([c[0], c[1], c[2], c[3]]), |
| 261 | "BF16" => f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16), |
| 262 | _ => f16_to_f32(u16::from_le_bytes([c[0], c[1]])), |
| 263 | }) |
| 264 | .collect() |
| 265 | } |
| 266 | |
| 267 | /// Loads TinyLlama with no fallback and proves the weights came from the file. |
| 268 | fn strict_load(paths: &CheckpointPaths) -> TransformerWeights { |
| 269 | let config = ModelConfig::tinyllama_1_1b(); |
| 270 | let weights = |
| 271 | TransformerWeights::load_from_safetensors(&paths.model, &config).unwrap_or_else(|e| { |
| 272 | panic!( |
| 273 | "STRICT_CHECKPOINT_VIOLATION: {} failed to load against the {} config: {e:?}; \ |
| 274 | refusing to fall back (AIEN_REQUIRE_CHECKPOINT=1 semantics)", |
| 275 | paths.model.display(), |
| 276 | config.model_id |
| 277 | ) |
| 278 | }); |
| 279 | let hidden = config.hidden_dim; |
| 280 | let vocab = config.vocab_size; |
| 281 | assert_eq!( |
| 282 | weights.embed_tokens.len(), |
| 283 | vocab * hidden, |
| 284 | "STRICT_CHECKPOINT_VIOLATION: embedding shape does not match the TinyLlama config" |
| 285 | ); |
| 286 | for row in [0usize, vocab - 1] { |
| 287 | let from_file = read_tensor_values( |
| 288 | &paths.model, |
| 289 | "model.embed_tokens.weight", |
| 290 | row * hidden, |
| 291 | hidden, |
| 292 | ); |
| 293 | let loaded = &weights.embed_tokens[row * hidden..(row + 1) * hidden]; |
| 294 | assert!( |
| 295 | loaded |
| 296 | .iter() |
| 297 | .zip(&from_file) |
| 298 | .all(|(a, b)| a.to_bits() == b.to_bits()), |
| 299 | "STRICT_CHECKPOINT_VIOLATION: loaded embedding row {row} differs from the bytes in \ |
| 300 | {} (weights did not come from the checkpoint; reference fallback?)", |
| 301 | paths.model.display() |
| 302 | ); |
| 303 | } |
| 304 | weights |
| 305 | } |
| 306 | |
| 307 | struct Tolerance { |
| 308 | abs: f64, |
| 309 | rel: f64, |
| 310 | rel_eps: f64, |
| 311 | floor_status: String, |
| 312 | floor_model_sha256: String, |
| 313 | } |
| 314 | |
| 315 | /// Minimal reader for `key = value` lines of one TOML table (no new crate). |
| 316 | fn toml_table(text: &str, table: &str) -> HashMap<String, String> { |
| 317 | let header = format!("[{table}]"); |
| 318 | let mut out = HashMap::new(); |
| 319 | let mut inside = false; |
| 320 | for line in text.lines() { |
| 321 | let line = line.trim(); |
| 322 | if line.starts_with('[') { |
| 323 | inside = line == header; |
| 324 | continue; |
| 325 | } |
| 326 | if !inside || line.is_empty() || line.starts_with('#') { |
| 327 | continue; |
| 328 | } |
| 329 | if let Some((k, v)) = line.split_once('=') { |
| 330 | let v = v.split('#').next().unwrap_or("").trim().trim_matches('"'); |
| 331 | out.insert(k.trim().to_string(), v.to_string()); |
| 332 | } |
| 333 | } |
| 334 | out |
| 335 | } |
| 336 | |
| 337 | fn acceptance_tolerance() -> Tolerance { |
| 338 | let path = |
| 339 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/campaigns/c1/acceptance.toml"); |
| 340 | let text = std::fs::read_to_string(&path) |
| 341 | .unwrap_or_else(|e| panic!("PARITY_TOLERANCE: cannot read {}: {e}", path.display())); |
| 342 | let floor = toml_table(&text, "numerics.noise_floor.tinyllama"); |
| 343 | let numerics = toml_table(&text, "numerics"); |
| 344 | let num = |t: &HashMap<String, String>, k: &str| -> f64 { |
| 345 | t.get(k) |
| 346 | .unwrap_or_else(|| panic!("PARITY_TOLERANCE: {k} missing in {}", path.display())) |
| 347 | .parse::<f64>() |
| 348 | .unwrap_or_else(|e| panic!("PARITY_TOLERANCE: {k} not a number: {e}")) |
| 349 | }; |
| 350 | Tolerance { |
| 351 | abs: num(&floor, "tolerance_abs"), |
| 352 | rel: num(&floor, "tolerance_rel"), |
| 353 | rel_eps: num(&numerics, "relative_error_epsilon"), |
| 354 | floor_status: floor.get("status").cloned().unwrap_or_default(), |
| 355 | floor_model_sha256: floor.get("model_sha256").cloned().unwrap_or_default(), |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | // --------------------------------------------------------------------------- |
| 360 | // Parity |
| 361 | // --------------------------------------------------------------------------- |
| 362 | |
| 363 | #[derive(Default)] |
| 364 | struct Parity { |
| 365 | max_abs: f64, |
| 366 | max_rel: f64, |
| 367 | compared_values: usize, |
| 368 | violations: usize, |
| 369 | first_violation: Option<String>, |
| 370 | } |
| 371 | |
| 372 | impl Parity { |
| 373 | /// Element passes iff |a-c| <= tolerance_abs or |a-c| / max(|c|, eps) <= |
| 374 | /// tolerance_rel (acceptance.toml [numerics] relative error definition). |
| 375 | /// NaN never passes. |
| 376 | fn compare(&mut self, what: &str, row: &[f32], control: &[f32], tol: &Tolerance) { |
| 377 | if row.len() != control.len() { |
| 378 | self.violations += 1; |
| 379 | if self.first_violation.is_none() { |
| 380 | self.first_violation = Some(format!( |
| 381 | "{what}: length {} vs control {}", |
| 382 | row.len(), |
| 383 | control.len() |
| 384 | )); |
| 385 | } |
| 386 | return; |
| 387 | } |
| 388 | for (i, (a, c)) in row.iter().zip(control).enumerate() { |
| 389 | let abs = (f64::from(*a) - f64::from(*c)).abs(); |
| 390 | let rel = abs / f64::from(c.abs()).max(tol.rel_eps); |
| 391 | self.compared_values += 1; |
| 392 | if abs.is_nan() || abs > self.max_abs { |
| 393 | self.max_abs = if abs.is_nan() { f64::INFINITY } else { abs }; |
| 394 | } |
| 395 | if rel.is_nan() || rel > self.max_rel { |
| 396 | self.max_rel = if rel.is_nan() { f64::INFINITY } else { rel }; |
| 397 | } |
| 398 | let ok = abs <= tol.abs || rel <= tol.rel; |
| 399 | if !ok { |
| 400 | self.violations += 1; |
| 401 | if self.first_violation.is_none() { |
| 402 | self.first_violation = Some(format!( |
| 403 | "{what}: logit {i} = {a} vs control {c} (abs {abs:e}, rel {rel:e})" |
| 404 | )); |
| 405 | } |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | fn pass(&self) -> bool { |
| 411 | self.violations == 0 && self.compared_values > 0 |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | // --------------------------------------------------------------------------- |
| 416 | // Receipt helpers |
| 417 | // --------------------------------------------------------------------------- |
| 418 | |
| 419 | fn hardware() -> serde_json::Value { |
| 420 | let cpuinfo = std::fs::read_to_string("/proc/cpuinfo").unwrap_or_default(); |
| 421 | let processors = cpuinfo |
| 422 | .lines() |
| 423 | .filter(|l| l.starts_with("processor")) |
| 424 | .count(); |
| 425 | let mut fields: HashMap<String, Vec<String>> = HashMap::new(); |
| 426 | for line in cpuinfo.lines() { |
| 427 | if let Some((k, v)) = line.split_once(':') { |
| 428 | let k = k.trim(); |
| 429 | if matches!( |
| 430 | k, |
| 431 | "model name" | "Hardware" | "CPU implementer" | "CPU part" | "CPU architecture" |
| 432 | ) { |
| 433 | let entry = fields.entry(k.to_string()).or_default(); |
| 434 | let v = v.trim().to_string(); |
| 435 | if !entry.contains(&v) { |
| 436 | entry.push(v); |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | let uname = std::process::Command::new("uname") |
| 442 | .arg("-a") |
| 443 | .output() |
| 444 | .ok() |
| 445 | .filter(|o| o.status.success()) |
| 446 | .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()); |
| 447 | serde_json::json!({ |
| 448 | "source": "/proc/cpuinfo + uname -a, read at runtime", |
| 449 | "processors": processors, |
| 450 | "cpuinfo": fields, |
| 451 | "uname": uname, |
| 452 | }) |
| 453 | } |
| 454 | |
| 455 | /// `git rev-parse HEAD` in this crate's directory, at runtime. |
| 456 | fn commit_sha() -> Option<String> { |
| 457 | std::process::Command::new("git") |
| 458 | .args(["-C", env!("CARGO_MANIFEST_DIR"), "rev-parse", "HEAD"]) |
| 459 | .output() |
| 460 | .ok() |
| 461 | .filter(|o| o.status.success()) |
| 462 | .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) |
| 463 | } |
| 464 | |
| 465 | struct Check { |
| 466 | name: &'static str, |
| 467 | pass: bool, |
| 468 | message: String, |
| 469 | } |
| 470 | |
| 471 | fn check(name: &'static str, pass: bool, message: String) -> Check { |
| 472 | Check { |
| 473 | name, |
| 474 | pass, |
| 475 | message, |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | // --------------------------------------------------------------------------- |
| 480 | // Counting tensor backend |
| 481 | // --------------------------------------------------------------------------- |
| 482 | |
| 483 | /// Forwards every `TensorBackend` method to `ReferenceCpuBackend` and records |
| 484 | /// the position of every `apply_rope` call. Nothing else is changed, so the |
| 485 | /// arithmetic is bit identical to the plain reference backend. |
| 486 | struct CountingBackend { |
| 487 | inner: ReferenceCpuBackend, |
| 488 | rope_positions: Mutex<Vec<usize>>, |
| 489 | } |
| 490 | |
| 491 | impl CountingBackend { |
| 492 | fn new() -> Self { |
| 493 | Self { |
| 494 | inner: ReferenceCpuBackend::new(), |
| 495 | rope_positions: Mutex::new(Vec::new()), |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | /// Returns the positions recorded since the last call and clears them. |
| 500 | fn take_rope_positions(&self) -> Vec<usize> { |
| 501 | std::mem::take(&mut *self.rope_positions.lock()) |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | #[allow(clippy::too_many_arguments)] |
| 506 | impl TensorBackend for CountingBackend { |
| 507 | fn name(&self) -> &'static str { |
| 508 | "CountingBackend(ReferenceCpuBackend)" |
| 509 | } |
| 510 | |
| 511 | fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { |
| 512 | self.inner.rmsnorm(out, x, weight, eps); |
| 513 | } |
| 514 | |
| 515 | fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { |
| 516 | self.inner.rmsnorm_heads(x, weight, head_dim, eps); |
| 517 | } |
| 518 | |
| 519 | fn apply_rope( |
| 520 | &self, |
| 521 | q: &mut [f32], |
| 522 | k: &mut [f32], |
| 523 | pos: usize, |
| 524 | head_dim: usize, |
| 525 | num_q_heads: usize, |
| 526 | num_kv_heads: usize, |
| 527 | rope: &aien_inference_abi::RopeParams, |
| 528 | ) { |
| 529 | self.rope_positions.lock().push(pos); |
| 530 | self.inner |
| 531 | .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope); |
| 532 | } |
| 533 | |
| 534 | fn matmul_vec( |
| 535 | &self, |
| 536 | out: &mut [f32], |
| 537 | x: &[f32], |
| 538 | weight: &[f32], |
| 539 | out_dim: usize, |
| 540 | in_dim: usize, |
| 541 | ) { |
| 542 | self.inner.matmul_vec(out, x, weight, out_dim, in_dim); |
| 543 | } |
| 544 | |
| 545 | fn matmul_batch( |
| 546 | &self, |
| 547 | out: &mut [f32], |
| 548 | x: &[f32], |
| 549 | weight: &[f32], |
| 550 | batch_size: usize, |
| 551 | in_dim: usize, |
| 552 | out_dim: usize, |
| 553 | ) { |
| 554 | self.inner |
| 555 | .matmul_batch(out, x, weight, batch_size, in_dim, out_dim); |
| 556 | } |
| 557 | |
| 558 | fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { |
| 559 | self.inner.swiglu(out, gate, up); |
| 560 | } |
| 561 | |
| 562 | fn gqa_attention( |
| 563 | &self, |
| 564 | out: &mut [f32], |
| 565 | q: &[f32], |
| 566 | k_cache: &[f32], |
| 567 | v_cache: &[f32], |
| 568 | seq_len: usize, |
| 569 | num_q_heads: usize, |
| 570 | num_kv_heads: usize, |
| 571 | head_dim: usize, |
| 572 | ) { |
| 573 | self.inner.gqa_attention( |
| 574 | out, |
| 575 | q, |
| 576 | k_cache, |
| 577 | v_cache, |
| 578 | seq_len, |
| 579 | num_q_heads, |
| 580 | num_kv_heads, |
| 581 | head_dim, |
| 582 | ); |
| 583 | } |
| 584 | |
| 585 | fn paged_attention( |
| 586 | &self, |
| 587 | out: &mut [f32], |
| 588 | q: &[f32], |
| 589 | pool: &aien_kv_cache::UnifiedKvTensorPool, |
| 590 | block_ids: &[usize], |
| 591 | context_len: usize, |
| 592 | layer_idx: usize, |
| 593 | num_q_heads: usize, |
| 594 | num_kv_heads: usize, |
| 595 | head_dim: usize, |
| 596 | ) { |
| 597 | self.inner.paged_attention( |
| 598 | out, |
| 599 | q, |
| 600 | pool, |
| 601 | block_ids, |
| 602 | context_len, |
| 603 | layer_idx, |
| 604 | num_q_heads, |
| 605 | num_kv_heads, |
| 606 | head_dim, |
| 607 | ); |
| 608 | } |
| 609 | |
| 610 | fn paged_attention_batch( |
| 611 | &self, |
| 612 | out: &mut [f32], |
| 613 | q: &[f32], |
| 614 | pool: &aien_kv_cache::UnifiedKvTensorPool, |
| 615 | block_tables: &[i32], |
| 616 | context_lens: &[i32], |
| 617 | max_blocks_per_seq: usize, |
| 618 | num_seqs: usize, |
| 619 | layer_idx: usize, |
| 620 | num_q_heads: usize, |
| 621 | num_kv_heads: usize, |
| 622 | head_dim: usize, |
| 623 | ) { |
| 624 | self.inner.paged_attention_batch( |
| 625 | out, |
| 626 | q, |
| 627 | pool, |
| 628 | block_tables, |
| 629 | context_lens, |
| 630 | max_blocks_per_seq, |
| 631 | num_seqs, |
| 632 | layer_idx, |
| 633 | num_q_heads, |
| 634 | num_kv_heads, |
| 635 | head_dim, |
| 636 | ); |
| 637 | } |
| 638 | |
| 639 | fn compute_logits( |
| 640 | &self, |
| 641 | logits: &mut [f32], |
| 642 | hidden: &[f32], |
| 643 | embed_weight: &[f32], |
| 644 | vocab_size: usize, |
| 645 | hidden_dim: usize, |
| 646 | ) { |
| 647 | self.inner |
| 648 | .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim); |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | // --------------------------------------------------------------------------- |
| 653 | // Pool sizing |
| 654 | // --------------------------------------------------------------------------- |
| 655 | |
| 656 | struct PoolPlan { |
| 657 | block_size: usize, |
| 658 | prompt_blocks: usize, |
| 659 | final_blocks: usize, |
| 660 | append_new_blocks: usize, |
| 661 | branch_cow_blocks: usize, |
| 662 | needed_blocks: usize, |
| 663 | slack_blocks: usize, |
| 664 | total_blocks: usize, |
| 665 | } |
| 666 | |
| 667 | /// Blocks the pool needs for the whole run, derived (not guessed): |
| 668 | /// |
| 669 | /// The prompt holds `ceil(217 / 16) = 14` blocks. The append reaches 241 |
| 670 | /// tokens = 16 blocks. Its first write copies the shared partial tail block |
| 671 | /// (one new block, crates/aien-kv-cache/src/lib.rs `append_token_with_slot` |
| 672 | /// copy-on-write path), and the two block boundaries it crosses need |
| 673 | /// `16 - 14 = 2` fresh blocks, so the append allocates 3 blocks. Each of the |
| 674 | /// two branches copies the shared 1-token tail block once on its first |
| 675 | /// decode (2 blocks). The witness decodes in place in its own original tail |
| 676 | /// block (the root already copied away from it), so it needs none. Total |
| 677 | /// `14 + 3 + 2 = 19`, plus a small slack. |
| 678 | fn pool_plan(block_size: usize) -> PoolPlan { |
| 679 | let prompt_blocks = PROMPT_TOKENS.div_ceil(block_size); |
| 680 | let final_blocks = TOTAL_TOKENS.div_ceil(block_size); |
| 681 | let append_new_blocks = final_blocks - prompt_blocks + 1; |
| 682 | let branch_cow_blocks = BRANCHES.len(); |
| 683 | let needed_blocks = prompt_blocks + append_new_blocks + branch_cow_blocks; |
| 684 | PoolPlan { |
| 685 | block_size, |
| 686 | prompt_blocks, |
| 687 | final_blocks, |
| 688 | append_new_blocks, |
| 689 | branch_cow_blocks, |
| 690 | needed_blocks, |
| 691 | slack_blocks: POOL_SLACK_BLOCKS, |
| 692 | total_blocks: needed_blocks + POOL_SLACK_BLOCKS, |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | // --------------------------------------------------------------------------- |
| 697 | // KV helpers (all guard use stays inside these plain functions, never across |
| 698 | // an await point) |
| 699 | // --------------------------------------------------------------------------- |
| 700 | |
| 701 | type KvGather = Vec<(Vec<f32>, Vec<f32>)>; |
| 702 | |
| 703 | fn table_of(kv: &SharedKvManager, seq: u64) -> (Vec<usize>, usize) { |
| 704 | kv.read() |
| 705 | .get_block_table(seq) |
| 706 | .map_or((Vec::new(), 0), |t| (t.block_ids.clone(), t.total_tokens)) |
| 707 | } |
| 708 | |
| 709 | /// SHA-256 over every K and V value (as raw bits) of one physical block, all |
| 710 | /// layers, all slots. Used to prove blocks are byte-identical before/after. |
| 711 | fn block_digest( |
| 712 | kv: &SharedKvManager, |
| 713 | block: usize, |
| 714 | layers: usize, |
| 715 | block_size: usize, |
| 716 | kv_dim: usize, |
| 717 | ) -> String { |
| 718 | let guard = kv.read(); |
| 719 | let Some(pool) = guard.tensor_pool() else { |
| 720 | return "no-pool".to_string(); |
| 721 | }; |
| 722 | let mut hasher = Sha256::new(); |
| 723 | let mut k = vec![0.0f32; kv_dim]; |
| 724 | let mut v = vec![0.0f32; kv_dim]; |
| 725 | for layer in 0..layers { |
| 726 | for slot in 0..block_size { |
| 727 | pool.read_token_kv(block, layer, slot, &mut k, &mut v); |
| 728 | for x in k.iter().chain(v.iter()) { |
| 729 | hasher.update(x.to_bits().to_le_bytes()); |
| 730 | } |
| 731 | } |
| 732 | } |
| 733 | hex(&hasher.finalize()) |
| 734 | } |
| 735 | |
| 736 | fn block_digests( |
| 737 | kv: &SharedKvManager, |
| 738 | ids: &[usize], |
| 739 | layers: usize, |
| 740 | block_size: usize, |
| 741 | kv_dim: usize, |
| 742 | ) -> Vec<String> { |
| 743 | ids.iter() |
| 744 | .map(|b| block_digest(kv, *b, layers, block_size, kv_dim)) |
| 745 | .collect() |
| 746 | } |
| 747 | |
| 748 | /// Block bookkeeping the KV manager keeps for one physical block |
| 749 | /// (`aien_kv_cache::KvBlock`: `ref_count`, `num_tokens`, `is_shared`). |
| 750 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 751 | struct BlockMeta { |
| 752 | ref_count: usize, |
| 753 | num_tokens: usize, |
| 754 | is_shared: bool, |
| 755 | } |
| 756 | |
| 757 | impl BlockMeta { |
| 758 | fn json(self) -> serde_json::Value { |
| 759 | serde_json::json!({ |
| 760 | "ref_count": self.ref_count, |
| 761 | "num_tokens": self.num_tokens, |
| 762 | "is_shared": self.is_shared, |
| 763 | }) |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | fn block_meta(kv: &SharedKvManager, block: usize) -> Option<BlockMeta> { |
| 768 | kv.read().get_block(block).map(|b| BlockMeta { |
| 769 | ref_count: b.ref_count, |
| 770 | num_tokens: b.num_tokens, |
| 771 | is_shared: b.is_shared, |
| 772 | }) |
| 773 | } |
| 774 | |
| 775 | /// Indexes whose digests differ between two snapshots of the same block list. |
| 776 | fn changed_indexes(a: &[String], b: &[String]) -> Vec<usize> { |
| 777 | a.iter() |
| 778 | .zip(b) |
| 779 | .enumerate() |
| 780 | .filter(|(_, (x, y))| x != y) |
| 781 | .map(|(i, _)| i) |
| 782 | .collect() |
| 783 | } |
| 784 | |
| 785 | /// PASS or FAIL label for one sub-result inside a check message. |
| 786 | fn tag(ok: bool) -> &'static str { |
| 787 | if ok { |
| 788 | "PASS" |
| 789 | } else { |
| 790 | "FAIL" |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | fn gather_all(kv: &SharedKvManager, seq: u64, layers: usize) -> Result<KvGather, String> { |
| 795 | let mut out = Vec::with_capacity(layers); |
| 796 | for layer in 0..layers { |
| 797 | out.push(kv.read().gather_layer_kv(seq, layer)?); |
| 798 | } |
| 799 | Ok(out) |
| 800 | } |
| 801 | |
| 802 | fn bits_eq(a: &[f32], b: &[f32]) -> bool { |
| 803 | a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()) |
| 804 | } |
| 805 | |
| 806 | fn same_bits(a: &[(Vec<f32>, Vec<f32>)], b: &[(Vec<f32>, Vec<f32>)]) -> bool { |
| 807 | a.len() == b.len() |
| 808 | && a.iter() |
| 809 | .zip(b) |
| 810 | .all(|((ak, av), (bk, bv))| bits_eq(ak, bk) && bits_eq(av, bv)) |
| 811 | } |
| 812 | |
| 813 | /// Compares the K and V of paged sequence `seq` (gathered from the shared |
| 814 | /// pool) with the dense K/V of control sequence `ctl_id`, layer by layer. |
| 815 | fn compare_kv( |
| 816 | parity: &mut Parity, |
| 817 | what: &str, |
| 818 | kv: &SharedKvManager, |
| 819 | seq: u64, |
| 820 | control: &NativeTransformerBackend, |
| 821 | ctl_id: u64, |
| 822 | tol: &Tolerance, |
| 823 | ) -> Result<(), String> { |
| 824 | let layers = control.weights.config.num_layers; |
| 825 | let ctl = control |
| 826 | .sequences |
| 827 | .get(&ctl_id) |
| 828 | .ok_or_else(|| format!("control sequence {ctl_id} missing"))?; |
| 829 | for layer in 0..layers { |
| 830 | let (k, v) = kv.read().gather_layer_kv(seq, layer)?; |
| 831 | let cache = ctl |
| 832 | .layers |
| 833 | .get(layer) |
| 834 | .ok_or_else(|| format!("control layer {layer} missing"))?; |
| 835 | parity.compare(&format!("{what} K layer {layer}"), &k, &cache.flat_k, tol); |
| 836 | parity.compare(&format!("{what} V layer {layer}"), &v, &cache.flat_v, tol); |
| 837 | } |
| 838 | Ok(()) |
| 839 | } |
| 840 | |
| 841 | /// Highest logit that is not the argmax and not a special token (ids 0..=2). |
| 842 | fn second_best(logits: &[f32]) -> u32 { |
| 843 | let (best, _) = sample_argmax(logits); |
| 844 | let mut idx = 0usize; |
| 845 | let mut val = f32::NEG_INFINITY; |
| 846 | for (i, v) in logits.iter().enumerate() { |
| 847 | if i as u32 == best || i <= 2 { |
| 848 | continue; |
| 849 | } |
| 850 | if *v > val { |
| 851 | val = *v; |
| 852 | idx = i; |
| 853 | } |
| 854 | } |
| 855 | idx as u32 |
| 856 | } |
| 857 | |
| 858 | fn token_digest(tokens: &[u32]) -> String { |
| 859 | let mut h = Sha256::new(); |
| 860 | for t in tokens { |
| 861 | h.update(t.to_le_bytes()); |
| 862 | } |
| 863 | hex(&h.finalize()) |
| 864 | } |
| 865 | |
| 866 | /// One prefill request through `execute_step`, no scheduler. Returns the token |
| 867 | /// and logprob the backend sampled after the last token of the request. |
| 868 | async fn prefill_step( |
| 869 | backend: &mut NativeTransformerBackend, |
| 870 | id: u64, |
| 871 | tokens: &[u32], |
| 872 | sampling: &SamplingParams, |
| 873 | step_id: u64, |
| 874 | ) -> Result<(u32, f32), String> { |
| 875 | let batch = ScheduledBatch { |
| 876 | prefill_requests: vec![SequenceRequest { |
| 877 | request_id: id, |
| 878 | prompt_tokens: tokens.to_vec(), |
| 879 | sampling_params: sampling.clone(), |
| 880 | arrival_time_ns: 0, |
| 881 | priority: 1, |
| 882 | }], |
| 883 | decode_requests: Vec::new(), |
| 884 | block_tables: HashMap::new(), |
| 885 | step_id, |
| 886 | }; |
| 887 | let (outputs, _metrics) = backend.execute_step(&batch).await?; |
| 888 | for out in outputs { |
| 889 | if let DecodeOutput::Token { |
| 890 | request_id, |
| 891 | token_id, |
| 892 | logprob, |
| 893 | } = out |
| 894 | { |
| 895 | if request_id == id { |
| 896 | return Ok((token_id, logprob.unwrap_or(f32::NAN))); |
| 897 | } |
| 898 | } |
| 899 | } |
| 900 | Err(format!( |
| 901 | "execute_step returned no sampled token for request {id}" |
| 902 | )) |
| 903 | } |
| 904 | |
| 905 | // --------------------------------------------------------------------------- |
| 906 | // Evidence |
| 907 | // --------------------------------------------------------------------------- |
| 908 | |
| 909 | /// What the two forked branches did to the root's blocks during the FIRST |
| 910 | /// decode step, read at three moments: right after the branch forks (before any |
| 911 | /// decode write), right after the first decode step, and at the end of the |
| 912 | /// run. The end-of-run facts alone cannot see a branch that wrote into the |
| 913 | /// shared 1-token tail block on step 1 (the second step copies the block once |
| 914 | /// it holds 2 tokens, so the table ids look private again by the end), so the |
| 915 | /// step-1 snapshot is what makes copy-on-write failures visible. Defaults mean |
| 916 | /// "not captured" and every check that needs them then fails. |
| 917 | #[derive(Default)] |
| 918 | struct Isolation { |
| 919 | /// Table entry `final_blocks - 1` of the root, branch 1 and branch 2 right |
| 920 | /// after the first decode step. |
| 921 | root_tail: Option<usize>, |
| 922 | b1_tail: Option<usize>, |
| 923 | b2_tail: Option<usize>, |
| 924 | /// Bookkeeping of the root's tail block after the forks, after step 1 and |
| 925 | /// at the end. |
| 926 | tail_meta_before: Option<BlockMeta>, |
| 927 | tail_meta_step1: Option<BlockMeta>, |
| 928 | tail_meta_end: Option<BlockMeta>, |
| 929 | /// SHA-256 of the raw K/V (every layer, every slot, K and V) of each block |
| 930 | /// of the root's table, in table order, at the same three moments. |
| 931 | root_digests_before: Vec<String>, |
| 932 | root_digests_step1: Vec<String>, |
| 933 | root_digests_end: Vec<String>, |
| 934 | } |
| 935 | |
| 936 | struct Reclaim { |
| 937 | allocated: usize, |
| 938 | free: usize, |
| 939 | kv_sequences: usize, |
| 940 | physical_pages: usize, |
| 941 | backend_sequences: usize, |
| 942 | backend_pending: usize, |
| 943 | backend_sampling: usize, |
| 944 | free_errors: Vec<String>, |
| 945 | } |
| 946 | |
| 947 | /// Everything the run observed. Filled stage by stage; a stage that fails |
| 948 | /// leaves the later fields at their defaults and every check that needs them |
| 949 | /// then fails (never panics). |
| 950 | #[derive(Default)] |
| 951 | struct Evidence { |
| 952 | // Fence (carried over from E1). |
| 953 | state_after_alloc: Option<PrefillState>, |
| 954 | state_after_pending: Option<PrefillState>, |
| 955 | state_after_chunk1: Option<PrefillState>, |
| 956 | state_after_chunk2: Option<PrefillState>, |
| 957 | state_after_fence: Option<PrefillState>, |
| 958 | state_root_after_witness_fork: Option<PrefillState>, |
| 959 | state_root_after_append: Option<PrefillState>, |
| 960 | chunk_lens: Vec<usize>, |
| 961 | early_kv_fork_refused: bool, |
| 962 | early_backend_fork_refused: bool, |
| 963 | witness_forked: bool, |
| 964 | pending_217: Option<u32>, |
| 965 | pending_241: Option<u32>, |
| 966 | sampled_217: Option<(u32, f32)>, |
| 967 | sampled_241: Option<(u32, f32)>, |
| 968 | // Before the append (root and witness share these 14 blocks). |
| 969 | root_ids_before: Vec<usize>, |
| 970 | digests_before: Vec<String>, |
| 971 | block_bytes: usize, |
| 972 | physical_before: usize, |
| 973 | cow_before: usize, |
| 974 | // After the append. |
| 975 | append_error: Option<String>, |
| 976 | append_positions: Vec<usize>, |
| 977 | prefill_rope_calls: usize, |
| 978 | root_ids_after: Vec<usize>, |
| 979 | root_total_after: usize, |
| 980 | witness_ids_after: Vec<usize>, |
| 981 | witness_total_after: usize, |
| 982 | digests_after: Vec<String>, |
| 983 | physical_after: usize, |
| 984 | cow_after: usize, |
| 985 | free_after_append: usize, |
| 986 | root_kv_after: KvGather, |
| 987 | // Controls. |
| 988 | ctl_217: Option<(u32, f32)>, |
| 989 | ctl_241: Option<(u32, f32)>, |
| 990 | root_kv: Parity, |
| 991 | witness_kv: Parity, |
| 992 | // Decode. |
| 993 | fed: HashMap<u64, Vec<u32>>, |
| 994 | sampled: HashMap<u64, Vec<u32>>, |
| 995 | rows: HashMap<u64, Vec<Vec<f32>>>, |
| 996 | preempted: Vec<(u64, usize)>, |
| 997 | logits_b: Parity, |
| 998 | logits_w: Parity, |
| 999 | token_mismatch: Vec<u64>, |
| 1000 | branch_kv: Parity, |
| 1001 | witness_final_kv: Parity, |
| 1002 | // First decode step snapshots (see `Isolation`). |
| 1003 | iso: Isolation, |
| 1004 | // After decode. |
| 1005 | root_stable: bool, |
| 1006 | b1_ids: Vec<usize>, |
| 1007 | b2_ids: Vec<usize>, |
| 1008 | b1_total: usize, |
| 1009 | b2_total: usize, |
| 1010 | physical_final: usize, |
| 1011 | free_final: usize, |
| 1012 | // Reclaim. |
| 1013 | reclaim: Option<Reclaim>, |
| 1014 | // Timings. |
| 1015 | prefill_ms: f64, |
| 1016 | append_ms: f64, |
| 1017 | control_prefill_ms: f64, |
| 1018 | } |
| 1019 | |
| 1020 | /// What the stages need from the outside. |
| 1021 | struct Env<'a> { |
| 1022 | weights: &'a TransformerWeights, |
| 1023 | prompt: &'a [u32], |
| 1024 | appended: &'a [u32], |
| 1025 | tol: &'a Tolerance, |
| 1026 | counting: Arc<CountingBackend>, |
| 1027 | plan: &'a PoolPlan, |
| 1028 | } |
| 1029 | |
| 1030 | // --------------------------------------------------------------------------- |
| 1031 | // The run |
| 1032 | // --------------------------------------------------------------------------- |
| 1033 | |
| 1034 | /// Runs every stage in order and fills `ev`. Returns Err at the first stage |
| 1035 | /// that cannot continue; the caller still evaluates all checks on what was |
| 1036 | /// recorded and writes the receipt. |
| 1037 | async fn run_stages(env: &Env<'_>, ev: &mut Evidence) -> Result<(), String> { |
| 1038 | // Fresh controller state (RuntimeController persists operation ids). |
| 1039 | let state_dir = tempfile::tempdir().map_err(|e| format!("state dir: {e}"))?; |
| 1040 | std::env::set_var("AIEN_RUNTIME_STATE_DIR", state_dir.path()); |
| 1041 | |
| 1042 | let cfg = &env.weights.config; |
| 1043 | let block_size = cfg.block_size; |
| 1044 | let layers = cfg.num_layers; |
| 1045 | let kv_dim = cfg.num_kv_heads * cfg.head_dim; |
| 1046 | |
| 1047 | // The counting wrapper goes in through the Arc<dyn TensorBackend> |
| 1048 | // parameter: no runtime change. |
| 1049 | let tensor: Arc<dyn TensorBackend> = env.counting.clone(); |
| 1050 | let scheduler = SchedulerConfig { |
| 1051 | max_batch_size: 32, |
| 1052 | max_batch_tokens: 4096, |
| 1053 | max_prefill_tokens: 8192, |
| 1054 | prefill_chunk_size: PREFILL_CHUNK, |
| 1055 | chunk_prefill: true, |
| 1056 | watermark_blocks: 2, |
| 1057 | }; |
| 1058 | let (spine, mut backend) = build_shared_kv_runtime( |
| 1059 | env.weights.clone(), |
| 1060 | tensor, |
| 1061 | scheduler, |
| 1062 | SharedKvSizing { |
| 1063 | arena_capacity: 16, |
| 1064 | total_blocks: env.plan.total_blocks, |
| 1065 | }, |
| 1066 | )?; |
| 1067 | let kv = spine.kv_manager.clone(); |
| 1068 | let sampling = SamplingParams { |
| 1069 | temperature: 0.0, |
| 1070 | top_p: 1.0, |
| 1071 | max_tokens: 64, |
| 1072 | stop_token_ids: Vec::new(), |
| 1073 | }; |
| 1074 | |
| 1075 | // Stage 1: allocate the whole prompt, prefill in two chunks, fence. The |
| 1076 | // scheduler does exactly this order (allocate_sequence, mark_prefill_pending, |
| 1077 | // one execute_step per chunk, complete_prefill after the last chunk). |
| 1078 | let t_prefill = Instant::now(); |
| 1079 | kv.write().allocate_sequence(ROOT, env.prompt)?; |
| 1080 | ev.state_after_alloc = kv.read().prefill_state(ROOT); |
| 1081 | kv.write() |
| 1082 | .mark_prefill_pending(ROOT) |
| 1083 | .map_err(|e| format!("mark_prefill_pending: {e}"))?; |
| 1084 | ev.state_after_pending = kv.read().prefill_state(ROOT); |
| 1085 | |
| 1086 | let (first, second) = env.prompt.split_at(PREFILL_CHUNK); |
| 1087 | ev.chunk_lens = vec![first.len(), second.len()]; |
| 1088 | prefill_step(&mut backend, ROOT, first, &sampling, 1).await?; |
| 1089 | ev.state_after_chunk1 = kv.read().prefill_state(ROOT); |
| 1090 | let sampled_217 = prefill_step(&mut backend, ROOT, second, &sampling, 2).await?; |
| 1091 | ev.state_after_chunk2 = kv.read().prefill_state(ROOT); |
| 1092 | ev.sampled_217 = Some(sampled_217); |
| 1093 | ev.pending_217 = backend.pending_prefill_token.get(&ROOT).copied(); |
| 1094 | |
| 1095 | // A fork before the fence must be refused by the KV gate and by the |
| 1096 | // backend hook, and must leave nothing behind. |
| 1097 | let early_kv = kv.write().fork_prefilled(ROOT, SCRATCH); |
| 1098 | let scratch_table = kv.read().get_block_table(SCRATCH).is_some(); |
| 1099 | ev.early_kv_fork_refused = early_kv.is_err() && !scratch_table; |
| 1100 | let early_backend = backend.fork_sequence(ROOT, SCRATCH); |
| 1101 | ev.early_backend_fork_refused = |
| 1102 | early_backend.is_err() && !backend.sequences.contains_key(&SCRATCH); |
| 1103 | |
| 1104 | kv.write() |
| 1105 | .complete_prefill(ROOT) |
| 1106 | .map_err(|e| format!("complete_prefill: {e}"))?; |
| 1107 | ev.state_after_fence = kv.read().prefill_state(ROOT); |
| 1108 | ev.prefill_ms = t_prefill.elapsed().as_secs_f64() * 1e3; |
| 1109 | ev.prefill_rope_calls = env.counting.take_rope_positions().len(); |
| 1110 | |
| 1111 | // Stage 2: fork the witness BEFORE the append (copy-on-write option A), so |
| 1112 | // the root's partial tail block is shared when the append starts. |
| 1113 | let (ids_before, _total_before) = table_of(&kv, ROOT); |
| 1114 | ev.root_ids_before = ids_before.clone(); |
| 1115 | ev.digests_before = block_digests(&kv, &ids_before, layers, block_size, kv_dim); |
| 1116 | ev.block_bytes = kv.read().tensor_pool().map_or(0, |p| p.block_bytes()); |
| 1117 | kv.write() |
| 1118 | .fork_prefilled(ROOT, WITNESS) |
| 1119 | .map_err(|e| format!("witness fork_prefilled: {e}"))?; |
| 1120 | backend.fork_sequence(ROOT, WITNESS)?; |
| 1121 | ev.witness_forked = true; |
| 1122 | ev.state_root_after_witness_fork = kv.read().prefill_state(ROOT); |
| 1123 | ev.physical_before = kv.read().metrics().physical_pages; |
| 1124 | ev.cow_before = kv.read().cow_faults(); |
| 1125 | |
| 1126 | // Stage 3: ONE more prefill request for the same sequence id holding only |
| 1127 | // the 24 new tokens. The backend continues at offset = tokens already in |
| 1128 | // the sequence (transformer_backend.rs `prefill_prompt_layer_by_layer_paged`). |
| 1129 | let t_append = Instant::now(); |
| 1130 | let appended = prefill_step(&mut backend, ROOT, env.appended, &sampling, 3).await; |
| 1131 | ev.append_ms = t_append.elapsed().as_secs_f64() * 1e3; |
| 1132 | ev.append_positions = env.counting.take_rope_positions(); |
| 1133 | match appended { |
| 1134 | Ok(sample) => ev.sampled_241 = Some(sample), |
| 1135 | Err(e) => { |
| 1136 | ev.append_error = Some(e.clone()); |
| 1137 | return Err(format!("append execute_step failed: {e}")); |
| 1138 | } |
| 1139 | } |
| 1140 | ev.pending_241 = backend.pending_prefill_token.get(&ROOT).copied(); |
| 1141 | let (ids_after, total_after) = table_of(&kv, ROOT); |
| 1142 | ev.root_ids_after = ids_after; |
| 1143 | ev.root_total_after = total_after; |
| 1144 | let (witness_ids, witness_total) = table_of(&kv, WITNESS); |
| 1145 | ev.witness_ids_after = witness_ids; |
| 1146 | ev.witness_total_after = witness_total; |
| 1147 | ev.digests_after = block_digests(&kv, &ids_before, layers, block_size, kv_dim); |
| 1148 | ev.physical_after = kv.read().metrics().physical_pages; |
| 1149 | ev.cow_after = kv.read().cow_faults(); |
| 1150 | ev.free_after_append = kv.read().free_block_count(); |
| 1151 | ev.state_root_after_append = kv.read().prefill_state(ROOT); |
| 1152 | ev.root_kv_after = gather_all(&kv, ROOT, layers)?; |
| 1153 | |
| 1154 | // Stage 4: unpaged one-shot controls. The 241-token control is the E1 |
| 1155 | // control_after_prompt pattern with the append folded into the prompt; the |
| 1156 | // 217-token control is the witness control. |
| 1157 | let t_control = Instant::now(); |
| 1158 | let mut control = NativeTransformerBackend::new(env.weights.clone()); |
| 1159 | // The control is dense (no pool) but is the reference for a pool of |
| 1160 | // SHARED_KV_DTYPE, so it rounds K/V at birth exactly as the paged backend does. |
| 1161 | control.kv_dtype = SHARED_KV_DTYPE; |
| 1162 | if control.kv_manager.is_some() { |
| 1163 | return Err("control must be unpaged".to_string()); |
| 1164 | } |
| 1165 | let mut full = env.prompt.to_vec(); |
| 1166 | full.extend_from_slice(env.appended); |
| 1167 | let logits_241 = control.prefill_sequence(CTL_ROOT, &full)?; |
| 1168 | let logits_217 = control.prefill_sequence(CTL_W, env.prompt)?; |
| 1169 | ev.control_prefill_ms = t_control.elapsed().as_secs_f64() * 1e3; |
| 1170 | ev.ctl_241 = Some(sample_argmax(&logits_241)); |
| 1171 | ev.ctl_217 = Some(sample_argmax(&logits_217)); |
| 1172 | compare_kv( |
| 1173 | &mut ev.root_kv, |
| 1174 | "root", |
| 1175 | &kv, |
| 1176 | ROOT, |
| 1177 | &control, |
| 1178 | CTL_ROOT, |
| 1179 | env.tol, |
| 1180 | )?; |
| 1181 | compare_kv( |
| 1182 | &mut ev.witness_kv, |
| 1183 | "witness", |
| 1184 | &kv, |
| 1185 | WITNESS, |
| 1186 | &control, |
| 1187 | CTL_W, |
| 1188 | env.tol, |
| 1189 | )?; |
| 1190 | |
| 1191 | // Branch and witness controls start from the same fed tokens as the paged |
| 1192 | // sequences: the root's pending token (241 context) and the witness's |
| 1193 | // pending token (217 context), exactly what the fork hook gives them. |
| 1194 | let p217 = ev |
| 1195 | .pending_217 |
| 1196 | .ok_or("root has no pending token after the fence")?; |
| 1197 | let p241 = ev |
| 1198 | .pending_241 |
| 1199 | .ok_or("root has no pending token after the append")?; |
| 1200 | let base = control |
| 1201 | .sequences |
| 1202 | .get(&CTL_ROOT) |
| 1203 | .ok_or("control root sequence missing")? |
| 1204 | .clone(); |
| 1205 | let mut ctl_b1 = base.clone(); |
| 1206 | ctl_b1.tokens.push(p241); |
| 1207 | control.sequences.insert(CTL_B1, ctl_b1); |
| 1208 | let mut ctl_b2 = base; |
| 1209 | ctl_b2.tokens.push(p241); |
| 1210 | control.sequences.insert(CTL_B2, ctl_b2); |
| 1211 | control |
| 1212 | .sequences |
| 1213 | .get_mut(&CTL_W) |
| 1214 | .ok_or("control witness sequence missing")? |
| 1215 | .tokens |
| 1216 | .push(p217); |
| 1217 | |
| 1218 | // Stage 5: fork two branches off the 241-token root (KV gate first, then |
| 1219 | // the backend hook, as the swarm manager does) and decode 4 steps in one |
| 1220 | // batch together with the witness. |
| 1221 | for b in BRANCHES { |
| 1222 | kv.write() |
| 1223 | .fork_prefilled(ROOT, b) |
| 1224 | .map_err(|e| format!("branch {b} fork_prefilled: {e}"))?; |
| 1225 | backend.fork_sequence(ROOT, b)?; |
| 1226 | } |
| 1227 | // Isolation snapshot 1: the root's blocks exactly as the forks left them, |
| 1228 | // before any decode write. The tail block (table entry `final_blocks - 1`) |
| 1229 | // holds 1 token and is shared by the root and both branches here. |
| 1230 | let tail_pos = env.plan.final_blocks.saturating_sub(1); |
| 1231 | let root_blocks = ev.root_ids_after.clone(); |
| 1232 | ev.iso.root_digests_before = block_digests(&kv, &root_blocks, layers, block_size, kv_dim); |
| 1233 | ev.iso.tail_meta_before = root_blocks.get(tail_pos).and_then(|b| block_meta(&kv, *b)); |
| 1234 | let order = [BRANCH_1, BRANCH_2, WITNESS]; |
| 1235 | let mut dead: Vec<u64> = Vec::new(); |
| 1236 | for step in 1..=DECODE_STEPS { |
| 1237 | let live: Vec<u64> = order |
| 1238 | .iter() |
| 1239 | .copied() |
| 1240 | .filter(|id| !dead.contains(id)) |
| 1241 | .collect(); |
| 1242 | if live.is_empty() { |
| 1243 | break; |
| 1244 | } |
| 1245 | for id in &live { |
| 1246 | let last = backend |
| 1247 | .sequences |
| 1248 | .get(id) |
| 1249 | .and_then(|s| s.tokens.last().copied()) |
| 1250 | .ok_or_else(|| format!("sequence {id} has no tokens before decode step {step}"))?; |
| 1251 | ev.fed.entry(*id).or_default().push(last); |
| 1252 | } |
| 1253 | let (outs, rows) = backend.forward_decode_batch_with_logits(&live)?; |
| 1254 | if step == 1 { |
| 1255 | // Isolation snapshot 2: straight after the first decode step, before |
| 1256 | // the second step can copy a block the first step wrote into. |
| 1257 | ev.iso.root_tail = table_of(&kv, ROOT).0.get(tail_pos).copied(); |
| 1258 | ev.iso.b1_tail = table_of(&kv, BRANCH_1).0.get(tail_pos).copied(); |
| 1259 | ev.iso.b2_tail = table_of(&kv, BRANCH_2).0.get(tail_pos).copied(); |
| 1260 | ev.iso.tail_meta_step1 = root_blocks.get(tail_pos).and_then(|b| block_meta(&kv, *b)); |
| 1261 | ev.iso.root_digests_step1 = |
| 1262 | block_digests(&kv, &root_blocks, layers, block_size, kv_dim); |
| 1263 | } |
| 1264 | let preempted: Vec<u64> = outs |
| 1265 | .iter() |
| 1266 | .filter_map(|o| match o { |
| 1267 | DecodeOutput::Finished { |
| 1268 | request_id, |
| 1269 | reason: FinishReason::Preempted, |
| 1270 | .. |
| 1271 | } => Some(*request_id), |
| 1272 | _ => None, |
| 1273 | }) |
| 1274 | .collect(); |
| 1275 | let computed: Vec<u64> = live |
| 1276 | .iter() |
| 1277 | .copied() |
| 1278 | .filter(|id| !preempted.contains(id)) |
| 1279 | .collect(); |
| 1280 | if rows.len() != computed.len() { |
| 1281 | return Err(format!( |
| 1282 | "decode step {step}: {} logit rows for {} computed rows", |
| 1283 | rows.len(), |
| 1284 | computed.len() |
| 1285 | )); |
| 1286 | } |
| 1287 | for (id, row) in computed.iter().zip(rows) { |
| 1288 | let tok = backend |
| 1289 | .sequences |
| 1290 | .get(id) |
| 1291 | .and_then(|s| s.tokens.last().copied()) |
| 1292 | .ok_or_else(|| format!("sequence {id} has no tokens after decode step {step}"))?; |
| 1293 | ev.sampled.entry(*id).or_default().push(tok); |
| 1294 | ev.rows.entry(*id).or_default().push(row); |
| 1295 | } |
| 1296 | for id in preempted { |
| 1297 | ev.preempted.push((id, step)); |
| 1298 | dead.push(id); |
| 1299 | } |
| 1300 | // Teacher forcing: branch 2 continues with its second best token so |
| 1301 | // the two branches diverge from step 2 on. |
| 1302 | if step < DECODE_STEPS && computed.contains(&BRANCH_2) { |
| 1303 | let forced = ev |
| 1304 | .rows |
| 1305 | .get(&BRANCH_2) |
| 1306 | .and_then(|r| r.last()) |
| 1307 | .map(|row| second_best(row)); |
| 1308 | if let (Some(forced), Some(seq)) = (forced, backend.sequences.get_mut(&BRANCH_2)) { |
| 1309 | seq.tokens.pop(); |
| 1310 | seq.tokens.push(forced); |
| 1311 | } |
| 1312 | } |
| 1313 | } |
| 1314 | |
| 1315 | // Stage 6: the controls decode the same steps with the same fed tokens and |
| 1316 | // every step's full logit vector is compared at tolerance 0.0. |
| 1317 | for (id, ctl_id, name) in [ |
| 1318 | (BRANCH_1, CTL_B1, "branch1"), |
| 1319 | (BRANCH_2, CTL_B2, "branch2"), |
| 1320 | (WITNESS, CTL_W, "witness"), |
| 1321 | ] { |
| 1322 | let rows = ev.rows.get(&id).cloned().unwrap_or_default(); |
| 1323 | let fed = ev.fed.get(&id).cloned().unwrap_or_default(); |
| 1324 | let sampled = ev.sampled.get(&id).cloned().unwrap_or_default(); |
| 1325 | for (k, row) in rows.iter().enumerate() { |
| 1326 | let (_outs, ctl_rows) = control.forward_decode_batch_with_logits(&[ctl_id])?; |
| 1327 | let ctl_row = ctl_rows |
| 1328 | .into_iter() |
| 1329 | .next() |
| 1330 | .ok_or_else(|| format!("control {name} step {} gave no logits", k + 1))?; |
| 1331 | let target = if id == WITNESS { |
| 1332 | &mut ev.logits_w |
| 1333 | } else { |
| 1334 | &mut ev.logits_b |
| 1335 | }; |
| 1336 | target.compare(&format!("{name} step {}", k + 1), row, &ctl_row, env.tol); |
| 1337 | let ctl_tok = control |
| 1338 | .sequences |
| 1339 | .get(&ctl_id) |
| 1340 | .and_then(|s| s.tokens.last().copied()); |
| 1341 | if sampled.get(k).copied() != ctl_tok { |
| 1342 | ev.token_mismatch.push(id); |
| 1343 | } |
| 1344 | if let Some(next) = fed.get(k + 1).copied() { |
| 1345 | if let Some(seq) = control.sequences.get_mut(&ctl_id) { |
| 1346 | seq.tokens.pop(); |
| 1347 | seq.tokens.push(next); |
| 1348 | } |
| 1349 | } |
| 1350 | } |
| 1351 | } |
| 1352 | compare_kv( |
| 1353 | &mut ev.branch_kv, |
| 1354 | "branch1", |
| 1355 | &kv, |
| 1356 | BRANCH_1, |
| 1357 | &control, |
| 1358 | CTL_B1, |
| 1359 | env.tol, |
| 1360 | )?; |
| 1361 | compare_kv( |
| 1362 | &mut ev.branch_kv, |
| 1363 | "branch2", |
| 1364 | &kv, |
| 1365 | BRANCH_2, |
| 1366 | &control, |
| 1367 | CTL_B2, |
| 1368 | env.tol, |
| 1369 | )?; |
| 1370 | compare_kv( |
| 1371 | &mut ev.witness_final_kv, |
| 1372 | "witness-final", |
| 1373 | &kv, |
| 1374 | WITNESS, |
| 1375 | &control, |
| 1376 | CTL_W, |
| 1377 | env.tol, |
| 1378 | )?; |
| 1379 | |
| 1380 | // Stage 7: the root is untouched by everything the branches and the |
| 1381 | // witness did, and the tables look as copy-on-write says they must. |
| 1382 | let (root_ids_end, root_total_end) = table_of(&kv, ROOT); |
| 1383 | let root_end = gather_all(&kv, ROOT, layers)?; |
| 1384 | ev.root_stable = root_ids_end == ev.root_ids_after |
| 1385 | && root_total_end == ev.root_total_after |
| 1386 | && same_bits(&root_end, &ev.root_kv_after); |
| 1387 | // Isolation snapshot 3: the same block facts at the end of the run. |
| 1388 | ev.iso.tail_meta_end = root_blocks.get(tail_pos).and_then(|b| block_meta(&kv, *b)); |
| 1389 | ev.iso.root_digests_end = block_digests(&kv, &root_blocks, layers, block_size, kv_dim); |
| 1390 | let (b1_ids, b1_total) = table_of(&kv, BRANCH_1); |
| 1391 | let (b2_ids, b2_total) = table_of(&kv, BRANCH_2); |
| 1392 | ev.b1_ids = b1_ids; |
| 1393 | ev.b1_total = b1_total; |
| 1394 | ev.b2_ids = b2_ids; |
| 1395 | ev.b2_total = b2_total; |
| 1396 | ev.physical_final = kv.read().metrics().physical_pages; |
| 1397 | ev.free_final = kv.read().free_block_count(); |
| 1398 | |
| 1399 | // Stage 8: reclaim. The KV tables are freed the way the scheduler and the |
| 1400 | // swarm manager free them; the backend hook (trait method, which never |
| 1401 | // touches the KV manager) removes the per-request backend state. |
| 1402 | let mut free_errors: Vec<String> = Vec::new(); |
| 1403 | for id in [ROOT, WITNESS, BRANCH_1, BRANCH_2] { |
| 1404 | if let Err(e) = kv.write().free_sequence(id) { |
| 1405 | free_errors.push(format!("{id}: {e}")); |
| 1406 | } |
| 1407 | AienInferenceBackend::release_sequence(&mut backend, id)?; |
| 1408 | } |
| 1409 | let backend_sampling = [ROOT, WITNESS, BRANCH_1, BRANCH_2] |
| 1410 | .iter() |
| 1411 | .filter(|id| backend.sampling_params(**id).is_some()) |
| 1412 | .count(); |
| 1413 | ev.reclaim = Some(Reclaim { |
| 1414 | allocated: kv.read().allocated_block_count(), |
| 1415 | free: kv.read().free_block_count(), |
| 1416 | kv_sequences: kv.read().active_sequence_count(), |
| 1417 | physical_pages: kv.read().metrics().physical_pages, |
| 1418 | backend_sequences: backend.sequences.len(), |
| 1419 | backend_pending: backend.pending_prefill_token.len(), |
| 1420 | backend_sampling, |
| 1421 | free_errors, |
| 1422 | }); |
| 1423 | Ok(()) |
| 1424 | } |
| 1425 | |
| 1426 | // --------------------------------------------------------------------------- |
| 1427 | // Checks |
| 1428 | // --------------------------------------------------------------------------- |
| 1429 | |
| 1430 | fn parity_summary(p: &Parity) -> String { |
| 1431 | format!( |
| 1432 | "{} violations in {} values (max_abs {:e}, max_rel {:e}){}", |
| 1433 | p.violations, |
| 1434 | p.compared_values, |
| 1435 | p.max_abs, |
| 1436 | p.max_rel, |
| 1437 | p.first_violation |
| 1438 | .as_ref() |
| 1439 | .map(|f| format!(", first: {f}")) |
| 1440 | .unwrap_or_default() |
| 1441 | ) |
| 1442 | } |
| 1443 | |
| 1444 | fn same_sample(a: Option<(u32, f32)>, b: Option<(u32, f32)>) -> bool { |
| 1445 | match (a, b) { |
| 1446 | (Some((ta, la)), Some((tb, lb))) => ta == tb && la.to_bits() == lb.to_bits(), |
| 1447 | _ => false, |
| 1448 | } |
| 1449 | } |
| 1450 | |
| 1451 | /// What the counting backend saw during the append. |
| 1452 | struct PositionStats { |
| 1453 | min: Option<usize>, |
| 1454 | max: Option<usize>, |
| 1455 | count: usize, |
| 1456 | distinct: usize, |
| 1457 | per_layer_count: usize, |
| 1458 | /// Exactly the positions PROMPT_TOKENS..TOTAL_TOKENS, each once per layer. |
| 1459 | exact: bool, |
| 1460 | } |
| 1461 | |
| 1462 | fn position_stats(positions: &[usize], layers: usize) -> PositionStats { |
| 1463 | let mut counts: BTreeMap<usize, usize> = BTreeMap::new(); |
| 1464 | for p in positions { |
| 1465 | *counts.entry(*p).or_default() += 1; |
| 1466 | } |
| 1467 | let expected: Vec<usize> = (PROMPT_TOKENS..TOTAL_TOKENS).collect(); |
| 1468 | let keys: Vec<usize> = counts.keys().copied().collect(); |
| 1469 | let exact = keys == expected && counts.values().all(|c| *c == layers); |
| 1470 | PositionStats { |
| 1471 | min: counts.keys().next().copied(), |
| 1472 | max: counts.keys().next_back().copied(), |
| 1473 | count: positions.len(), |
| 1474 | distinct: counts.len(), |
| 1475 | per_layer_count: positions.len().checked_div(layers).unwrap_or(0), |
| 1476 | exact, |
| 1477 | } |
| 1478 | } |
| 1479 | |
| 1480 | /// Verdicts on the first-decode-step snapshots (see `Isolation`). Both the |
| 1481 | /// isolation check and the receipt read these, so they report the same facts. |
| 1482 | struct FirstStep { |
| 1483 | /// Table entry the shared tail block sits at (`final_blocks - 1`). |
| 1484 | tail: usize, |
| 1485 | /// Tokens the root's tail block holds: 241 - 15 * 16 = 1. |
| 1486 | tail_tokens: usize, |
| 1487 | /// Right after step 1 branch 1, branch 2 and the root hold three distinct |
| 1488 | /// tail blocks, and the root's tail block id did not move. |
| 1489 | tails_private: bool, |
| 1490 | /// After the forks the tail block is shared by the root and both branches |
| 1491 | /// (ref_count 3, shared flag set) and holds `tail_tokens` tokens. |
| 1492 | meta_before_ok: bool, |
| 1493 | /// After step 1 both branches have copied away: the root is the sole owner |
| 1494 | /// (ref_count 1, shared flag clear) and nobody wrote into the block, so it |
| 1495 | /// still holds `tail_tokens` tokens. Same expectation at the end. |
| 1496 | meta_step1_ok: bool, |
| 1497 | meta_end_ok: bool, |
| 1498 | /// Every one of the three digest snapshots covers every root block. |
| 1499 | snapshots_complete: bool, |
| 1500 | /// Root block indexes whose raw K/V changed between the forks and step 1, |
| 1501 | /// and between the forks and the end. |
| 1502 | changed_step1: Vec<usize>, |
| 1503 | changed_end: Vec<usize>, |
| 1504 | blocks_same_step1: bool, |
| 1505 | blocks_same_end: bool, |
| 1506 | /// The root's tail block (all slots, all layers, K and V) is bit identical |
| 1507 | /// after step 1 and at the end. |
| 1508 | tail_snapshot_equal: bool, |
| 1509 | } |
| 1510 | |
| 1511 | fn first_step(plan: &PoolPlan, ev: &Evidence) -> FirstStep { |
| 1512 | let iso = &ev.iso; |
| 1513 | let tail = plan.final_blocks.saturating_sub(1); |
| 1514 | let tail_tokens = TOTAL_TOKENS.saturating_sub(tail * plan.block_size); |
| 1515 | let tails_private = matches!( |
| 1516 | (iso.b1_tail, iso.b2_tail, iso.root_tail), |
| 1517 | (Some(x), Some(y), Some(r)) if x != y && x != r && y != r |
| 1518 | ) && iso.root_tail == ev.root_ids_after.get(tail).copied(); |
| 1519 | let shared = BlockMeta { |
| 1520 | ref_count: 1 + BRANCHES.len(), |
| 1521 | num_tokens: tail_tokens, |
| 1522 | is_shared: true, |
| 1523 | }; |
| 1524 | let sole_owner = BlockMeta { |
| 1525 | ref_count: 1, |
| 1526 | num_tokens: tail_tokens, |
| 1527 | is_shared: false, |
| 1528 | }; |
| 1529 | let snapshots_complete = iso.root_digests_before.len() == plan.final_blocks |
| 1530 | && iso.root_digests_step1.len() == plan.final_blocks |
| 1531 | && iso.root_digests_end.len() == plan.final_blocks; |
| 1532 | let changed_step1 = changed_indexes(&iso.root_digests_before, &iso.root_digests_step1); |
| 1533 | let changed_end = changed_indexes(&iso.root_digests_before, &iso.root_digests_end); |
| 1534 | let blocks_same_step1 = snapshots_complete && changed_step1.is_empty(); |
| 1535 | let blocks_same_end = snapshots_complete && changed_end.is_empty(); |
| 1536 | let tail_snapshot_equal = |
| 1537 | snapshots_complete && !changed_step1.contains(&tail) && !changed_end.contains(&tail); |
| 1538 | FirstStep { |
| 1539 | tail, |
| 1540 | tail_tokens, |
| 1541 | tails_private, |
| 1542 | meta_before_ok: iso.tail_meta_before == Some(shared), |
| 1543 | meta_step1_ok: iso.tail_meta_step1 == Some(sole_owner), |
| 1544 | meta_end_ok: iso.tail_meta_end == Some(sole_owner), |
| 1545 | snapshots_complete, |
| 1546 | changed_step1, |
| 1547 | changed_end, |
| 1548 | blocks_same_step1, |
| 1549 | blocks_same_end, |
| 1550 | tail_snapshot_equal, |
| 1551 | } |
| 1552 | } |
| 1553 | |
| 1554 | /// Builds the nine checks from the evidence. Every message carries its marker |
| 1555 | /// and the numbers behind it. Nothing here can panic on missing evidence. |
| 1556 | fn evaluate(env: &Env<'_>, ev: &Evidence) -> Vec<Check> { |
| 1557 | let cfg = &env.weights.config; |
| 1558 | let layers = cfg.num_layers; |
| 1559 | let kv_dim = cfg.num_kv_heads * cfg.head_dim; |
| 1560 | let vocab = cfg.vocab_size; |
| 1561 | let plan = env.plan; |
| 1562 | let tail_idx = plan.prompt_blocks - 1; |
| 1563 | let mut checks: Vec<Check> = Vec::new(); |
| 1564 | |
| 1565 | // (a) K/V of the root equals a one-shot 241-token control, the witness |
| 1566 | // equals a 217-token control, and both still equal their controls after |
| 1567 | // the branches and the witness decoded. |
| 1568 | let root_expected = layers * 2 * TOTAL_TOKENS * kv_dim; |
| 1569 | let witness_expected = layers * 2 * PROMPT_TOKENS * kv_dim; |
| 1570 | let branch_expected = BRANCHES.len() * layers * 2 * (TOTAL_TOKENS + DECODE_STEPS) * kv_dim; |
| 1571 | let witness_final_expected = layers * 2 * (PROMPT_TOKENS + DECODE_STEPS) * kv_dim; |
| 1572 | let a_root = ev.root_kv.pass() && ev.root_kv.compared_values == root_expected; |
| 1573 | let a_witness = ev.witness_kv.pass() && ev.witness_kv.compared_values == witness_expected; |
| 1574 | let a_branches = ev.branch_kv.pass() && ev.branch_kv.compared_values == branch_expected; |
| 1575 | let a_witness_final = |
| 1576 | ev.witness_final_kv.pass() && ev.witness_final_kv.compared_values == witness_final_expected; |
| 1577 | let pass_a = a_root && a_witness && a_branches && a_witness_final; |
| 1578 | checks.push(check( |
| 1579 | "a_kv_equals_control", |
| 1580 | pass_a, |
| 1581 | format!( |
| 1582 | "(a) KV_PARITY_VIOLATION: each sub-comparison below carries its own verdict; root \ |
| 1583 | after append vs one-shot 241 control: {}, {} (expected {} values); witness vs 217 \ |
| 1584 | control: {}, {} (expected {}); two branches after decode vs controls: {}, {} \ |
| 1585 | (expected {}); witness after decode vs control: {}, {} (expected {})", |
| 1586 | tag(a_root), |
| 1587 | parity_summary(&ev.root_kv), |
| 1588 | root_expected, |
| 1589 | tag(a_witness), |
| 1590 | parity_summary(&ev.witness_kv), |
| 1591 | witness_expected, |
| 1592 | tag(a_branches), |
| 1593 | parity_summary(&ev.branch_kv), |
| 1594 | branch_expected, |
| 1595 | tag(a_witness_final), |
| 1596 | parity_summary(&ev.witness_final_kv), |
| 1597 | witness_final_expected |
| 1598 | ), |
| 1599 | )); |
| 1600 | |
| 1601 | // (b) the sampled tokens and every logit vector equal the controls. |
| 1602 | let b_expected = BRANCHES.len() * DECODE_STEPS * vocab; |
| 1603 | let w_expected = DECODE_STEPS * vocab; |
| 1604 | let b_sample_217 = same_sample(ev.sampled_217, ev.ctl_217); |
| 1605 | let b_sample_241 = same_sample(ev.sampled_241, ev.ctl_241); |
| 1606 | let b_branch_logits = ev.logits_b.pass() && ev.logits_b.compared_values == b_expected; |
| 1607 | let b_witness_logits = ev.logits_w.pass() && ev.logits_w.compared_values == w_expected; |
| 1608 | let b_tokens = ev.token_mismatch.is_empty(); |
| 1609 | let pass_b = b_sample_217 && b_sample_241 && b_branch_logits && b_witness_logits && b_tokens; |
| 1610 | checks.push(check( |
| 1611 | "b_logits_and_tokens", |
| 1612 | pass_b, |
| 1613 | format!( |
| 1614 | "(b) LOGITS_TOKENS_VIOLATION: each sub-comparison below carries its own verdict; \ |
| 1615 | sample after 217 {:?} vs control {:?}: {}; sample after 241 {:?} vs control {:?}: \ |
| 1616 | {}; branch logits: {}, {} (expected {} values); witness logits: {}, {} (expected \ |
| 1617 | {}); decode token mismatches (sequence ids) {:?}: {}", |
| 1618 | ev.sampled_217, |
| 1619 | ev.ctl_217, |
| 1620 | tag(b_sample_217), |
| 1621 | ev.sampled_241, |
| 1622 | ev.ctl_241, |
| 1623 | tag(b_sample_241), |
| 1624 | tag(b_branch_logits), |
| 1625 | parity_summary(&ev.logits_b), |
| 1626 | b_expected, |
| 1627 | tag(b_witness_logits), |
| 1628 | parity_summary(&ev.logits_w), |
| 1629 | w_expected, |
| 1630 | ev.token_mismatch, |
| 1631 | tag(b_tokens) |
| 1632 | ), |
| 1633 | )); |
| 1634 | |
| 1635 | // (c) the 14 old blocks are byte identical (raw K/V of every layer and |
| 1636 | // slot, hashed) after the append, and the 13 full ones are still the same |
| 1637 | // block ids in the root's table. |
| 1638 | let digests_same = |
| 1639 | ev.digests_before.len() == plan.prompt_blocks && ev.digests_before == ev.digests_after; |
| 1640 | let changed: Vec<usize> = ev |
| 1641 | .digests_before |
| 1642 | .iter() |
| 1643 | .zip(&ev.digests_after) |
| 1644 | .enumerate() |
| 1645 | .filter(|(_, (before, after))| before != after) |
| 1646 | .map(|(i, _)| i) |
| 1647 | .collect(); |
| 1648 | let prefix_before = ev.root_ids_before.get(..tail_idx); |
| 1649 | let prefix_same = prefix_before.is_some() && prefix_before == ev.root_ids_after.get(..tail_idx); |
| 1650 | checks.push(check( |
| 1651 | "c_blocks", |
| 1652 | ev.root_ids_before.len() == plan.prompt_blocks && digests_same && prefix_same, |
| 1653 | format!( |
| 1654 | "(c) OLD_BLOCKS_REWRITTEN_VIOLATION: old block ids {:?}, root table after append {:?}; \ |
| 1655 | {} digests before, {} after; old block indexes whose bytes changed {:?}; the first {} \ |
| 1656 | block ids unchanged {}", |
| 1657 | ev.root_ids_before, |
| 1658 | ev.root_ids_after, |
| 1659 | ev.digests_before.len(), |
| 1660 | ev.digests_after.len(), |
| 1661 | changed, |
| 1662 | tail_idx, |
| 1663 | prefix_same |
| 1664 | ), |
| 1665 | )); |
| 1666 | |
| 1667 | // (d) only the 24 new positions were computed. |
| 1668 | let stats = position_stats(&ev.append_positions, layers); |
| 1669 | checks.push(check( |
| 1670 | "d_only_new_computed", |
| 1671 | stats.exact && stats.count == APPENDED_TOKENS * layers, |
| 1672 | format!( |
| 1673 | "(d) RECOMPUTE_ALL_VIOLATION: the append computed positions {:?}..={:?} ({} distinct, \ |
| 1674 | {} rope calls, {} per layer); expected exactly {}..={} ({} positions) once per layer \ |
| 1675 | ({} layers, {} calls)", |
| 1676 | stats.min, |
| 1677 | stats.max, |
| 1678 | stats.distinct, |
| 1679 | stats.count, |
| 1680 | stats.per_layer_count, |
| 1681 | PROMPT_TOKENS, |
| 1682 | TOTAL_TOKENS - 1, |
| 1683 | APPENDED_TOKENS, |
| 1684 | layers, |
| 1685 | APPENDED_TOKENS * layers |
| 1686 | ), |
| 1687 | )); |
| 1688 | |
| 1689 | // (e) branch isolation: the root is untouched by what the branches did, |
| 1690 | // the branches share the full prefix blocks, keep private tails, and really |
| 1691 | // diverged (so cross contamination would show). |
| 1692 | let fed_at = |id: u64, i: usize| ev.fed.get(&id).and_then(|f| f.get(i)).copied(); |
| 1693 | let diverged = matches!( |
| 1694 | (fed_at(BRANCH_1, 1), fed_at(BRANCH_2, 1)), |
| 1695 | (Some(a), Some(b)) if a != b |
| 1696 | ); |
| 1697 | let tail = plan.final_blocks - 1; |
| 1698 | let root_prefix = ev.root_ids_after.get(..tail); |
| 1699 | let prefix_shared = root_prefix.is_some() |
| 1700 | && ev.b1_ids.get(..tail) == root_prefix |
| 1701 | && ev.b2_ids.get(..tail) == root_prefix; |
| 1702 | let tails_private = matches!( |
| 1703 | (ev.b1_ids.get(tail), ev.b2_ids.get(tail), ev.root_ids_after.get(tail)), |
| 1704 | (Some(x), Some(y), Some(r)) if x != y && x != r && y != r |
| 1705 | ); |
| 1706 | let branch_total = TOTAL_TOKENS + DECODE_STEPS; |
| 1707 | // The end-of-run facts above cannot see a branch that wrote into the shared |
| 1708 | // 1-token tail block on its first decode step (the second step copies the |
| 1709 | // block once it holds 2 tokens, so the ids look private again by the end, |
| 1710 | // and the root's own 241 positions never include the written slot). The |
| 1711 | // snapshots taken right after the forks and right after step 1 can. |
| 1712 | let fs = first_step(plan, ev); |
| 1713 | let pass_e = ev.root_stable |
| 1714 | && diverged |
| 1715 | && prefix_shared |
| 1716 | && tails_private |
| 1717 | && ev.b1_total == branch_total |
| 1718 | && ev.b2_total == branch_total |
| 1719 | && ev.physical_final == plan.needed_blocks |
| 1720 | && fs.tails_private |
| 1721 | && fs.meta_before_ok |
| 1722 | && fs.meta_step1_ok |
| 1723 | && fs.meta_end_ok |
| 1724 | && fs.blocks_same_step1 |
| 1725 | && fs.blocks_same_end; |
| 1726 | checks.push(check( |
| 1727 | "e_isolation", |
| 1728 | pass_e, |
| 1729 | format!( |
| 1730 | "(e) BRANCH_ISOLATION_VIOLATION: root unchanged by branch decode {}; branches fed \ |
| 1731 | different tokens at step 2 {} ({:?} vs {:?}); the first {} block ids shared with the \ |
| 1732 | root {}; private tail blocks (branch 1 {:?}, branch 2 {:?}, root {:?}) {}; branch \ |
| 1733 | totals {} and {} (expected {}); physical pages at the end {} (expected {}); first \ |
| 1734 | decode step: tail block ids right after step 1 (branch 1 {:?}, branch 2 {:?}, root \ |
| 1735 | {:?}) distinct and the root's id unmoved: {}; tail block (ref_count, tokens, shared \ |
| 1736 | flag) after the forks {:?} (expected ref_count {}, {} tokens, shared): {}, after step \ |
| 1737 | 1 {:?} (expected the root as sole owner: ref_count 1, {} tokens, not shared): {}, at \ |
| 1738 | the end {:?}: {}; raw K/V of all {} root blocks (every slot, layer, K and V) vs the \ |
| 1739 | snapshot taken after the forks: after step 1 changed block indexes {:?} ({}), at the \ |
| 1740 | end {:?} ({}); root tail block byte identical: {}; snapshots complete: {}", |
| 1741 | ev.root_stable, |
| 1742 | diverged, |
| 1743 | fed_at(BRANCH_1, 1), |
| 1744 | fed_at(BRANCH_2, 1), |
| 1745 | tail, |
| 1746 | prefix_shared, |
| 1747 | ev.b1_ids.get(tail), |
| 1748 | ev.b2_ids.get(tail), |
| 1749 | ev.root_ids_after.get(tail), |
| 1750 | tails_private, |
| 1751 | ev.b1_total, |
| 1752 | ev.b2_total, |
| 1753 | branch_total, |
| 1754 | ev.physical_final, |
| 1755 | plan.needed_blocks, |
| 1756 | ev.iso.b1_tail, |
| 1757 | ev.iso.b2_tail, |
| 1758 | ev.iso.root_tail, |
| 1759 | tag(fs.tails_private), |
| 1760 | ev.iso.tail_meta_before, |
| 1761 | 1 + BRANCHES.len(), |
| 1762 | fs.tail_tokens, |
| 1763 | tag(fs.meta_before_ok), |
| 1764 | ev.iso.tail_meta_step1, |
| 1765 | fs.tail_tokens, |
| 1766 | tag(fs.meta_step1_ok), |
| 1767 | ev.iso.tail_meta_end, |
| 1768 | tag(fs.meta_end_ok), |
| 1769 | plan.final_blocks, |
| 1770 | fs.changed_step1, |
| 1771 | tag(fs.blocks_same_step1), |
| 1772 | fs.changed_end, |
| 1773 | tag(fs.blocks_same_end), |
| 1774 | fs.tail_snapshot_equal, |
| 1775 | fs.snapshots_complete |
| 1776 | ), |
| 1777 | )); |
| 1778 | |
| 1779 | // (e2) copy on write: the witness shares the root's tail when the append |
| 1780 | // starts, so the first appended token must copy it. The witness keeps the |
| 1781 | // original tail block, byte identical (also covered by (c)). |
| 1782 | let cow_delta = ev.cow_after.saturating_sub(ev.cow_before); |
| 1783 | let witness_untouched = |
| 1784 | ev.witness_ids_after == ev.root_ids_before && ev.witness_total_after == PROMPT_TOKENS; |
| 1785 | let root_tail_moved = matches!( |
| 1786 | (ev.root_ids_after.get(tail_idx), ev.root_ids_before.get(tail_idx)), |
| 1787 | (Some(after), Some(before)) if after != before |
| 1788 | ); |
| 1789 | let pages_before_ok = ev.physical_before == plan.prompt_blocks; |
| 1790 | let pages_after_ok = ev.physical_after == plan.prompt_blocks + plan.append_new_blocks; |
| 1791 | checks.push(check( |
| 1792 | "e_cow_witness", |
| 1793 | cow_delta == 1 |
| 1794 | && witness_untouched |
| 1795 | && root_tail_moved |
| 1796 | && pages_before_ok |
| 1797 | && pages_after_ok, |
| 1798 | format!( |
| 1799 | "(e) COW_VIOLATION: copy-on-write faults during the append {} (expected 1); witness \ |
| 1800 | table {:?} with {} tokens (expected the old table {:?} with {}); root tail block moved \ |
| 1801 | {} (before {:?}, after {:?}); physical pages before {} (expected {}) and after {} \ |
| 1802 | (expected {})", |
| 1803 | cow_delta, |
| 1804 | ev.witness_ids_after, |
| 1805 | ev.witness_total_after, |
| 1806 | ev.root_ids_before, |
| 1807 | PROMPT_TOKENS, |
| 1808 | root_tail_moved, |
| 1809 | ev.root_ids_before.get(tail_idx), |
| 1810 | ev.root_ids_after.get(tail_idx), |
| 1811 | ev.physical_before, |
| 1812 | plan.prompt_blocks, |
| 1813 | ev.physical_after, |
| 1814 | plan.prompt_blocks + plan.append_new_blocks |
| 1815 | ), |
| 1816 | )); |
| 1817 | |
| 1818 | // (f) the pool was big enough: no allocation failed, nothing was preempted |
| 1819 | // and the free block counts match the plan exactly. |
| 1820 | let free_after_expected = plan |
| 1821 | .total_blocks |
| 1822 | .saturating_sub(plan.prompt_blocks + plan.append_new_blocks); |
| 1823 | let free_final_expected = plan.total_blocks.saturating_sub(plan.needed_blocks); |
| 1824 | let pass_f = ev.append_error.is_none() |
| 1825 | && ev.root_total_after == TOTAL_TOKENS |
| 1826 | && ev.root_ids_after.len() == plan.final_blocks |
| 1827 | && ev.preempted.is_empty() |
| 1828 | && ev.free_after_append == free_after_expected |
| 1829 | && ev.free_final == free_final_expected; |
| 1830 | let append_note = ev |
| 1831 | .append_error |
| 1832 | .as_ref() |
| 1833 | .map(|e| format!("; APPEND_ERROR_VIOLATION: the append returned Err: {e}")) |
| 1834 | .unwrap_or_default(); |
| 1835 | checks.push(check( |
| 1836 | "f_no_pool_exhaustion", |
| 1837 | pass_f, |
| 1838 | format!( |
| 1839 | "(f) POOL_EXHAUSTION_VIOLATION: pool of {} blocks (plan needs {}); root holds {} tokens \ |
| 1840 | in {} blocks after the append (expected {} in {}); free blocks after append {} \ |
| 1841 | (expected {}) and at the end {} (expected {}); preempted decode rows {:?}{}", |
| 1842 | plan.total_blocks, |
| 1843 | plan.needed_blocks, |
| 1844 | ev.root_total_after, |
| 1845 | ev.root_ids_after.len(), |
| 1846 | TOTAL_TOKENS, |
| 1847 | plan.final_blocks, |
| 1848 | ev.free_after_append, |
| 1849 | free_after_expected, |
| 1850 | ev.free_final, |
| 1851 | free_final_expected, |
| 1852 | ev.preempted, |
| 1853 | append_note |
| 1854 | ), |
| 1855 | )); |
| 1856 | |
| 1857 | // (g) everything reclaimed. |
| 1858 | let (pass_g, reclaim_note) = match &ev.reclaim { |
| 1859 | Some(r) => ( |
| 1860 | r.allocated == 0 |
| 1861 | && r.free == plan.total_blocks |
| 1862 | && r.kv_sequences == 0 |
| 1863 | && r.physical_pages == 0 |
| 1864 | && r.backend_sequences == 0 |
| 1865 | && r.backend_pending == 0 |
| 1866 | && r.backend_sampling == 0 |
| 1867 | && r.free_errors.is_empty(), |
| 1868 | format!( |
| 1869 | "allocated blocks {} (expected 0), free {} (expected {}), KV sequences {}, physical \ |
| 1870 | pages {}, backend sequences {}, pending prefill tokens {}, sampling entries {}, \ |
| 1871 | free errors {:?}", |
| 1872 | r.allocated, |
| 1873 | r.free, |
| 1874 | plan.total_blocks, |
| 1875 | r.kv_sequences, |
| 1876 | r.physical_pages, |
| 1877 | r.backend_sequences, |
| 1878 | r.backend_pending, |
| 1879 | r.backend_sampling, |
| 1880 | r.free_errors |
| 1881 | ), |
| 1882 | ), |
| 1883 | None => (false, "the run never reached the reclaim stage".to_string()), |
| 1884 | }; |
| 1885 | checks.push(check( |
| 1886 | "g_reclaimed", |
| 1887 | pass_g, |
| 1888 | format!("(g) RECLAIM_VIOLATION: {reclaim_note}"), |
| 1889 | )); |
| 1890 | |
| 1891 | // (h) the completion fence, carried over from E1, plus the witness fork. |
| 1892 | let states_ok = ev.state_after_alloc == Some(PrefillState::Allocated) |
| 1893 | && ev.state_after_pending == Some(PrefillState::PrefillPending) |
| 1894 | && ev.state_after_chunk1 == Some(PrefillState::PrefillPending) |
| 1895 | && ev.state_after_chunk2 == Some(PrefillState::PrefillPending) |
| 1896 | && ev.state_after_fence == Some(PrefillState::PrefillReady) |
| 1897 | && ev.state_root_after_witness_fork == Some(PrefillState::SharedFrozen) |
| 1898 | && ev.state_root_after_append == Some(PrefillState::SharedFrozen); |
| 1899 | let chunks_ok = ev.chunk_lens == [PREFILL_CHUNK, PROMPT_TOKENS - PREFILL_CHUNK]; |
| 1900 | checks.push(check( |
| 1901 | "h_fence", |
| 1902 | states_ok |
| 1903 | && chunks_ok |
| 1904 | && ev.early_kv_fork_refused |
| 1905 | && ev.early_backend_fork_refused |
| 1906 | && ev.witness_forked, |
| 1907 | format!( |
| 1908 | "(h) FENCE_VIOLATION: root KV states after allocate {:?}, mark pending {:?}, chunk 1 \ |
| 1909 | {:?}, chunk 2 {:?}, fence {:?}, witness fork {:?}, append {:?}; chunk lengths {:?}; \ |
| 1910 | KV fork before the fence refused {}; backend fork before the fence refused {}; \ |
| 1911 | witness forked {}", |
| 1912 | ev.state_after_alloc, |
| 1913 | ev.state_after_pending, |
| 1914 | ev.state_after_chunk1, |
| 1915 | ev.state_after_chunk2, |
| 1916 | ev.state_after_fence, |
| 1917 | ev.state_root_after_witness_fork, |
| 1918 | ev.state_root_after_append, |
| 1919 | ev.chunk_lens, |
| 1920 | ev.early_kv_fork_refused, |
| 1921 | ev.early_backend_fork_refused, |
| 1922 | ev.witness_forked |
| 1923 | ), |
| 1924 | )); |
| 1925 | |
| 1926 | checks |
| 1927 | } |
| 1928 | |
| 1929 | // --------------------------------------------------------------------------- |
| 1930 | // Receipt |
| 1931 | // --------------------------------------------------------------------------- |
| 1932 | |
| 1933 | /// Run-wide facts the main test gathers before the stages run. |
| 1934 | struct Meta { |
| 1935 | model_path: String, |
| 1936 | model_id: String, |
| 1937 | model_sha256: String, |
| 1938 | tokenizer_path: String, |
| 1939 | tokenizer_sha256: String, |
| 1940 | prompt_digest: String, |
| 1941 | appended_digest: String, |
| 1942 | } |
| 1943 | |
| 1944 | fn parity_json(p: &Parity) -> serde_json::Value { |
| 1945 | serde_json::json!({ |
| 1946 | "pass": p.pass(), |
| 1947 | "compared_values": p.compared_values, |
| 1948 | "violations": p.violations, |
| 1949 | "max_abs": p.max_abs, |
| 1950 | "max_rel": p.max_rel, |
| 1951 | "first_violation": p.first_violation, |
| 1952 | }) |
| 1953 | } |
| 1954 | |
| 1955 | fn build_receipt( |
| 1956 | meta: &Meta, |
| 1957 | env: &Env<'_>, |
| 1958 | ev: &Evidence, |
| 1959 | checks: &[Check], |
| 1960 | run_error: Option<&str>, |
| 1961 | ) -> serde_json::Value { |
| 1962 | let plan = env.plan; |
| 1963 | let layers = env.weights.config.num_layers; |
| 1964 | let stats = position_stats(&ev.append_positions, layers); |
| 1965 | let fs = first_step(plan, ev); |
| 1966 | let verdict = if run_error.is_none() && !checks.is_empty() && checks.iter().all(|c| c.pass) { |
| 1967 | "PASS" |
| 1968 | } else { |
| 1969 | "FAIL" |
| 1970 | }; |
| 1971 | let append_s = ev.append_ms / 1e3; |
| 1972 | let append_tokens_per_s = if append_s > 0.0 { |
| 1973 | APPENDED_TOKENS as f64 / append_s |
| 1974 | } else { |
| 1975 | 0.0 |
| 1976 | }; |
| 1977 | let control_s = ev.control_prefill_ms / 1e3; |
| 1978 | let control_tokens = TOTAL_TOKENS + PROMPT_TOKENS; |
| 1979 | let control_tokens_per_s = if control_s > 0.0 { |
| 1980 | control_tokens as f64 / control_s |
| 1981 | } else { |
| 1982 | 0.0 |
| 1983 | }; |
| 1984 | let bytes = |pages: usize| pages * ev.block_bytes; |
| 1985 | serde_json::json!({ |
| 1986 | "gate": "PREFILL-E2E-2", |
| 1987 | "backend": "NativeTransformerBackend over CountingBackend(ReferenceCpuBackend), shared pooled \ |
| 1988 | KV manager, FP32 pool, host CPU", |
| 1989 | "commit_sha": commit_sha(), |
| 1990 | "commit_sha_source": "git rev-parse HEAD in CARGO_MANIFEST_DIR at runtime", |
| 1991 | "model": { "path": meta.model_path, "id": meta.model_id, "sha256": meta.model_sha256 }, |
| 1992 | "tokenizer": { "path": meta.tokenizer_path, "sha256": meta.tokenizer_sha256 }, |
| 1993 | "hardware": hardware(), |
| 1994 | "gb10": "NOT_RUN", |
| 1995 | "max_comparison": "NOT_RUN", |
| 1996 | "prompt_tokens": PROMPT_TOKENS, |
| 1997 | "appended_tokens": APPENDED_TOKENS, |
| 1998 | "total_tokens": TOTAL_TOKENS, |
| 1999 | "decode_steps": DECODE_STEPS, |
| 2000 | "prefill_chunks": ev.chunk_lens, |
| 2001 | "prompt_digest_sha256": meta.prompt_digest, |
| 2002 | "appended_digest_sha256": meta.appended_digest, |
| 2003 | "digest_encoding": "sha256 over the token ids as little-endian u32", |
| 2004 | "tolerance": { "abs": env.tol.abs, "rel": env.tol.rel }, |
| 2005 | "checks": checks |
| 2006 | .iter() |
| 2007 | .map(|c| serde_json::json!({ |
| 2008 | "name": c.name, |
| 2009 | "pass": c.pass, |
| 2010 | "message": if c.pass { serde_json::Value::Null } else { serde_json::json!(c.message) }, |
| 2011 | })) |
| 2012 | .collect::<Vec<_>>(), |
| 2013 | "parity": { |
| 2014 | "root_kv_vs_one_shot_241": parity_json(&ev.root_kv), |
| 2015 | "witness_kv_vs_217": parity_json(&ev.witness_kv), |
| 2016 | "branch_logits": parity_json(&ev.logits_b), |
| 2017 | "witness_logits": parity_json(&ev.logits_w), |
| 2018 | "branch_kv_after_decode": parity_json(&ev.branch_kv), |
| 2019 | "witness_kv_after_decode": parity_json(&ev.witness_final_kv), |
| 2020 | "token_mismatch_sequence_ids": ev.token_mismatch, |
| 2021 | }, |
| 2022 | "samples": { |
| 2023 | "after_217": ev.sampled_217.map(|(t, l)| serde_json::json!({ "token": t, "logprob_bits": l.to_bits() })), |
| 2024 | "after_241": ev.sampled_241.map(|(t, l)| serde_json::json!({ "token": t, "logprob_bits": l.to_bits() })), |
| 2025 | "control_217": ev.ctl_217.map(|(t, l)| serde_json::json!({ "token": t, "logprob_bits": l.to_bits() })), |
| 2026 | "control_241": ev.ctl_241.map(|(t, l)| serde_json::json!({ "token": t, "logprob_bits": l.to_bits() })), |
| 2027 | }, |
| 2028 | "computed_positions_during_append": { |
| 2029 | "min": stats.min, |
| 2030 | "max": stats.max, |
| 2031 | "count": stats.count, |
| 2032 | "distinct": stats.distinct, |
| 2033 | "per_layer_count": stats.per_layer_count, |
| 2034 | "exact": stats.exact, |
| 2035 | "prompt_prefill_rope_calls": ev.prefill_rope_calls, |
| 2036 | }, |
| 2037 | "old_block_ids": { |
| 2038 | "before": ev.root_ids_before, |
| 2039 | "after_append_root_table": ev.root_ids_after, |
| 2040 | "after_append_witness_table": ev.witness_ids_after, |
| 2041 | "digests_unchanged": ev.digests_before == ev.digests_after, |
| 2042 | }, |
| 2043 | "branch_isolation_first_step": { |
| 2044 | "tail_block_index": fs.tail, |
| 2045 | "tail_tokens_expected": fs.tail_tokens, |
| 2046 | "tails_after_step1": { |
| 2047 | "branch1": ev.iso.b1_tail, |
| 2048 | "branch2": ev.iso.b2_tail, |
| 2049 | "root": ev.iso.root_tail, |
| 2050 | }, |
| 2051 | "tails_distinct_and_root_unmoved": fs.tails_private, |
| 2052 | "shared_tail_block_before_decode": ev.iso.tail_meta_before.map(BlockMeta::json), |
| 2053 | "shared_tail_block_after_step1": ev.iso.tail_meta_step1.map(BlockMeta::json), |
| 2054 | "shared_tail_block_at_end": ev.iso.tail_meta_end.map(BlockMeta::json), |
| 2055 | "shared_tail_num_tokens_after_step1": ev.iso.tail_meta_step1.map(|m| m.num_tokens), |
| 2056 | "shared_tail_meta_ok": { |
| 2057 | "before_decode": fs.meta_before_ok, |
| 2058 | "after_step1": fs.meta_step1_ok, |
| 2059 | "at_end": fs.meta_end_ok, |
| 2060 | }, |
| 2061 | "root_blocks_snapshots_complete": fs.snapshots_complete, |
| 2062 | "root_blocks_changed_after_step1": fs.changed_step1, |
| 2063 | "root_blocks_changed_at_end": fs.changed_end, |
| 2064 | "root_tail_block_snapshot_equal": fs.tail_snapshot_equal, |
| 2065 | }, |
| 2066 | "kv_block_bytes": ev.block_bytes, |
| 2067 | "physical_kv": { |
| 2068 | "pages_before_append": ev.physical_before, |
| 2069 | "pages_after_append": ev.physical_after, |
| 2070 | "pages_after_decode": ev.physical_final, |
| 2071 | "bytes_before_append": bytes(ev.physical_before), |
| 2072 | "bytes_after_append": bytes(ev.physical_after), |
| 2073 | "bytes_after_decode": bytes(ev.physical_final), |
| 2074 | "cow_faults_during_append": ev.cow_after.saturating_sub(ev.cow_before), |
| 2075 | }, |
| 2076 | "timings": { |
| 2077 | "prefill_ms": ev.prefill_ms, |
| 2078 | "append_ms": ev.append_ms, |
| 2079 | "control_prefill_ms": ev.control_prefill_ms, |
| 2080 | "control_prefill_tokens": control_tokens, |
| 2081 | "append_tokens_per_s": append_tokens_per_s, |
| 2082 | "control_tokens_per_s": control_tokens_per_s, |
| 2083 | }, |
| 2084 | "preempted_decode_rows": ev.preempted, |
| 2085 | "pool": { |
| 2086 | "block_size": plan.block_size, |
| 2087 | "kv_dtype": "Fp32", |
| 2088 | "prompt_blocks": plan.prompt_blocks, |
| 2089 | "final_blocks": plan.final_blocks, |
| 2090 | "append_new_blocks": plan.append_new_blocks, |
| 2091 | "branch_cow_blocks": plan.branch_cow_blocks, |
| 2092 | "needed_blocks": plan.needed_blocks, |
| 2093 | "slack_blocks": plan.slack_blocks, |
| 2094 | "total_blocks": plan.total_blocks, |
| 2095 | "formula": "needed = ceil(217/bs) + (ceil(241/bs) - ceil(217/bs) + 1) + 2 branch tail \ |
| 2096 | copies; total = needed + slack; the +1 is the copy-on-write copy of the \ |
| 2097 | shared partial tail block", |
| 2098 | }, |
| 2099 | "verdict": verdict, |
| 2100 | "run_error": run_error, |
| 2101 | }) |
| 2102 | } |
| 2103 | |
| 2104 | fn write_receipt(path: &Path, receipt: &serde_json::Value) { |
| 2105 | if let Some(dir) = path.parent() { |
| 2106 | if !dir.as_os_str().is_empty() { |
| 2107 | std::fs::create_dir_all(dir).expect("receipt directory"); |
| 2108 | } |
| 2109 | } |
| 2110 | let line = serde_json::to_string(receipt).expect("receipt JSON"); |
| 2111 | std::fs::write(path, format!("{line}\n")).expect("write receipt"); |
| 2112 | } |
| 2113 | |
| 2114 | // --------------------------------------------------------------------------- |
| 2115 | // The gate |
| 2116 | // --------------------------------------------------------------------------- |
| 2117 | |
| 2118 | /// The prompt must be longer than one prefill chunk so the chunk continuation |
| 2119 | /// really runs before the append. |
| 2120 | const _: () = assert!(PROMPT_TOKENS > PREFILL_CHUNK); |
| 2121 | |
| 2122 | #[tokio::test] |
| 2123 | #[ignore = "PREFILL-E2E-2 real-checkpoint gate (append 24 tokens to a shared prefilled context): \ |
| 2124 | run with --ignored and AIEN_E2E_CHECKPOINT + AIEN_E2E2_RECEIPT set (forge on the Spark)"] |
| 2125 | async fn prefill_e2e2_real_checkpoint_append_gate() { |
| 2126 | let checkpoint = required_env("AIEN_E2E_CHECKPOINT"); |
| 2127 | let receipt_path = PathBuf::from(required_env("AIEN_E2E2_RECEIPT")); |
| 2128 | |
| 2129 | let paths = checkpoint_paths(&checkpoint); |
| 2130 | let model_sha256 = sha256_file_hex(&paths.model); |
| 2131 | let tokenizer_sha256 = sha256_file_hex(&paths.tokenizer); |
| 2132 | let weights = strict_load(&paths); |
| 2133 | let model_id = weights.config.model_id.clone(); |
| 2134 | let tokenizer = TinyLlamaTokenizer::from_file(&paths.tokenizer).unwrap_or_else(|e| { |
| 2135 | panic!( |
| 2136 | "STRICT_CHECKPOINT_VIOLATION: tokenizer {} failed to parse: {e:?}", |
| 2137 | paths.tokenizer.display() |
| 2138 | ) |
| 2139 | }); |
| 2140 | let tol = acceptance_tolerance(); |
| 2141 | assert_eq!( |
| 2142 | tol.floor_status, "measured", |
| 2143 | "PARITY_TOLERANCE: [numerics.noise_floor.tinyllama] status must be measured" |
| 2144 | ); |
| 2145 | assert_eq!( |
| 2146 | tol.floor_model_sha256, model_sha256, |
| 2147 | "PARITY_TOLERANCE: the frozen TinyLlama floor was measured on a different checkpoint" |
| 2148 | ); |
| 2149 | assert!( |
| 2150 | tol.abs == 0.0 && tol.rel == 0.0, |
| 2151 | "PARITY_TOLERANCE: the frozen tolerance is exact equality (0.0); got abs {:e} rel {:e}", |
| 2152 | tol.abs, |
| 2153 | tol.rel |
| 2154 | ); |
| 2155 | |
| 2156 | let block_size = weights.config.block_size; |
| 2157 | let prompt_text = TinyLlamaTokenizer::format_prompt(Some(SYSTEM_PROMPT), USER_PROMPT); |
| 2158 | let prompt = tokenizer.encode(&prompt_text).expect("encode root prompt"); |
| 2159 | assert_eq!( |
| 2160 | prompt.len(), |
| 2161 | PROMPT_TOKENS, |
| 2162 | "PROMPT_LENGTH: the root prompt is {} tokens; the block arithmetic of this gate is built \ |
| 2163 | for {PROMPT_TOKENS}", |
| 2164 | prompt.len() |
| 2165 | ); |
| 2166 | assert_eq!( |
| 2167 | block_size, 16, |
| 2168 | "PROMPT_LENGTH: the block arithmetic of this gate is built for 16-slot blocks" |
| 2169 | ); |
| 2170 | assert_eq!( |
| 2171 | PROMPT_TOKENS % block_size, |
| 2172 | 9, |
| 2173 | "PROMPT_LENGTH: the prompt must end 9 tokens into its last block so the append starts \ |
| 2174 | mid-block (got {})", |
| 2175 | PROMPT_TOKENS % block_size |
| 2176 | ); |
| 2177 | let appended_all = tokenizer |
| 2178 | .encode_with_special(APPEND_TEXT, false) |
| 2179 | .expect("encode appended text"); |
| 2180 | assert!( |
| 2181 | appended_all.len() >= APPENDED_TOKENS, |
| 2182 | "APPEND_LENGTH: the appended text is {} tokens; need at least {APPENDED_TOKENS}", |
| 2183 | appended_all.len() |
| 2184 | ); |
| 2185 | let appended = &appended_all[..APPENDED_TOKENS]; |
| 2186 | |
| 2187 | let plan = pool_plan(block_size); |
| 2188 | let meta = Meta { |
| 2189 | model_path: paths.model.display().to_string(), |
| 2190 | model_id, |
| 2191 | model_sha256, |
| 2192 | tokenizer_path: paths.tokenizer.display().to_string(), |
| 2193 | tokenizer_sha256, |
| 2194 | prompt_digest: token_digest(&prompt), |
| 2195 | appended_digest: token_digest(appended), |
| 2196 | }; |
| 2197 | let env = Env { |
| 2198 | weights: &weights, |
| 2199 | prompt: &prompt, |
| 2200 | appended, |
| 2201 | tol: &tol, |
| 2202 | counting: Arc::new(CountingBackend::new()), |
| 2203 | plan: &plan, |
| 2204 | }; |
| 2205 | println!( |
| 2206 | "PREFILL_E2E2 prompt {} tokens, appended {} tokens, pool {} blocks (needs {})", |
| 2207 | prompt.len(), |
| 2208 | appended.len(), |
| 2209 | plan.total_blocks, |
| 2210 | plan.needed_blocks |
| 2211 | ); |
| 2212 | |
| 2213 | // A FAIL receipt exists from the start so a crash still leaves evidence. |
| 2214 | write_receipt( |
| 2215 | &receipt_path, |
| 2216 | &build_receipt( |
| 2217 | &meta, |
| 2218 | &env, |
| 2219 | &Evidence::default(), |
| 2220 | &[], |
| 2221 | Some("run did not finish"), |
| 2222 | ), |
| 2223 | ); |
| 2224 | |
| 2225 | let mut ev = Evidence::default(); |
| 2226 | let run_error = run_stages(&env, &mut ev).await.err(); |
| 2227 | let checks = evaluate(&env, &ev); |
| 2228 | write_receipt( |
| 2229 | &receipt_path, |
| 2230 | &build_receipt(&meta, &env, &ev, &checks, run_error.as_deref()), |
| 2231 | ); |
| 2232 | |
| 2233 | // Print every failing message before any assert fires, so every marker |
| 2234 | // that applies is in the log. |
| 2235 | println!( |
| 2236 | "PREFILL_E2E2 append took {:.1} ms for {} tokens; one-shot controls took {:.1} ms", |
| 2237 | ev.append_ms, APPENDED_TOKENS, ev.control_prefill_ms |
| 2238 | ); |
| 2239 | if let Some(e) = &run_error { |
| 2240 | println!("PREFILL_E2E2 RUN_ERROR: {e}"); |
| 2241 | } |
| 2242 | for c in &checks { |
| 2243 | if c.pass { |
| 2244 | println!("PREFILL_E2E2 check {} PASS", c.name); |
| 2245 | } else { |
| 2246 | println!("PREFILL_E2E2 check {} FAIL: {}", c.name, c.message); |
| 2247 | } |
| 2248 | } |
| 2249 | |
| 2250 | if let Some(e) = &run_error { |
| 2251 | panic!("RUN_ERROR: {e}"); |
| 2252 | } |
| 2253 | for c in &checks { |
| 2254 | assert!(c.pass, "{}", c.message); |
| 2255 | } |
| 2256 | } |