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-inference-abi / tests / tinyllama_noise_floor.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 C7: measure the TinyLlama noise floor that branch parity will face. |
| 17 | //! |
| 18 | //! Tolerance rule this measurement feeds (no number is fixed here): |
| 19 | //! - `docs/campaigns/c1/acceptance.toml:21-22`: tolerance = noise_multiplier_k (2.0) x measured floor. |
| 20 | //! - `docs/campaigns/c1/acceptance.toml:23-24`: relative error = |a - b| / max(|ref|, 1.0e-3). |
| 21 | //! - `docs/campaigns/c1/acceptance.toml:31-32`: tinyllama floor is `status = "unmeasured"`; a later |
| 22 | //! cut freezes the number from the forge log of this test. |
| 23 | //! - aien-architecture b4fce15 `docs/plans/prefill/PREFILL-3-SPEC.md:127-131` (floor = maximum |
| 24 | //! observed over mathematically equal summation orders, reported with its run count) and |
| 25 | //! `docs/plans/prefill/PREFILL-0-SPEC.md:142,145` (G6: measured, not assumed, recorded). |
| 26 | //! |
| 27 | //! What is measured, on the CPU reference backend (`ReferenceCpuBackend`, no CUDA), per prompt: |
| 28 | //! - (a) one-shot prefill of prompt + k teacher-forced tokens, last-position logits; |
| 29 | //! - (b) prefill(prompt) then k single-token forward steps (teacher forced), last-position logits; |
| 30 | //! - (c) repeat-run determinism: (a) and (b) repeated `runs` times on fresh sequences. |
| 31 | //! |
| 32 | //! Floor = max over prompts and runs of |a_r - a_0|, |b_r - a_0| (abs and rel, reference a_0). |
| 33 | //! Prompts are kept at <= 120 tokens total so the chunked-prefill continuation defect (Cut 3, |
| 34 | //! 128-token daemon chunks) cannot touch this measurement: both paths here are single-call. |
| 35 | //! |
| 36 | //! The ignored test asserts only sanity (finite, non-constant logits, expected vocab width). |
| 37 | //! Optional `AIEN_NOISE_FLOOR_EXPECT_MIN_ABS=<x>` makes it also assert max_abs >= x; the forge |
| 38 | //! uses it with a perturbation mutant to prove the measurement sees a 1e-2 change. |
| 39 | //! |
| 40 | //! Run: AIEN_E2E_CHECKPOINT=$HOME/models/TinyLlama-1.1B-Chat-v1.0 \ |
| 41 | //! cargo test --release -p aien-inference-abi --test tinyllama_noise_floor -- --ignored --nocapture |
| 42 | |
| 43 | use aien_inference_abi::tokenizer::TinyLlamaTokenizer; |
| 44 | use aien_inference_abi::transformer_backend::NativeTransformerBackend; |
| 45 | use aien_inference_abi::weights::TransformerWeights; |
| 46 | use aien_inference_abi::ModelConfig; |
| 47 | use sha2::{Digest, Sha256}; |
| 48 | use std::fmt::Write as _; |
| 49 | use std::io::Read; |
| 50 | use std::path::{Path, PathBuf}; |
| 51 | |
| 52 | /// `docs/campaigns/c1/acceptance.toml:24`. |
| 53 | const RELATIVE_ERROR_EPSILON: f64 = 1.0e-3; |
| 54 | /// Teacher-forced tokens per prompt (brief: k >= 8). |
| 55 | const K_TEACHER: usize = 8; |
| 56 | /// Upper bound on prompt + teacher tokens (brief: <= 120, below the 128-token chunk size). |
| 57 | const MAX_TOTAL_TOKENS: usize = 120; |
| 58 | const DEFAULT_RUNS: usize = 3; |
| 59 | |
| 60 | /// Fixed prompts and teacher continuations (R = 5). Token ids come from the in-repo |
| 61 | /// tokenizer fixture `crates/aien-inference-abi/tests/fixtures/tokenizer.json` via |
| 62 | /// `TinyLlamaTokenizer` (`src/tokenizer.rs:52,96`). |
| 63 | const PROMPTS: [(&str, &str); 5] = [ |
| 64 | ( |
| 65 | "The capital of France is", |
| 66 | " Paris, which is also the largest city in the country.", |
| 67 | ), |
| 68 | ( |
| 69 | "Water boils at sea level when it reaches a temperature of", |
| 70 | " one hundred degrees Celsius, or two hundred twelve Fahrenheit.", |
| 71 | ), |
| 72 | ( |
| 73 | "In a small village near the mountains, an old clockmaker repaired", |
| 74 | " every watch that people brought to his narrow wooden shop.", |
| 75 | ), |
| 76 | ( |
| 77 | "To compute the area of a circle, multiply pi by", |
| 78 | " the square of the radius, then round the result.", |
| 79 | ), |
| 80 | ( |
| 81 | "def add(a, b):\n return", |
| 82 | " a + b\n\ndef sub(a, b):\n return a - b\n", |
| 83 | ), |
| 84 | ]; |
| 85 | |
| 86 | #[derive(Debug, Default, Clone, Copy, PartialEq)] |
| 87 | struct Diff { |
| 88 | max_abs: f64, |
| 89 | max_rel: f64, |
| 90 | } |
| 91 | |
| 92 | impl Diff { |
| 93 | fn merge(self, other: Diff) -> Diff { |
| 94 | Diff { |
| 95 | max_abs: self.max_abs.max(other.max_abs), |
| 96 | max_rel: self.max_rel.max(other.max_rel), |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Element-wise difference of `other` against `reference`, relative error per |
| 102 | /// `acceptance.toml:23`: |a - b| / max(|ref|, epsilon). |
| 103 | fn compare(reference: &[f32], other: &[f32], epsilon: f64) -> Diff { |
| 104 | assert_eq!( |
| 105 | reference.len(), |
| 106 | other.len(), |
| 107 | "logit vectors differ in length" |
| 108 | ); |
| 109 | let mut d = Diff::default(); |
| 110 | for (&r, &o) in reference.iter().zip(other.iter()) { |
| 111 | let abs = (r as f64 - o as f64).abs(); |
| 112 | assert!(abs.is_finite(), "non-finite logit difference"); |
| 113 | let rel = abs / (r as f64).abs().max(epsilon); |
| 114 | d.max_abs = d.max_abs.max(abs); |
| 115 | d.max_rel = d.max_rel.max(rel); |
| 116 | } |
| 117 | d |
| 118 | } |
| 119 | |
| 120 | // `!(x >= min)` on purpose: a NaN floor must fail the expected-minimum check. |
| 121 | #[allow(clippy::neg_cmp_op_on_partial_ord)] |
| 122 | fn check_expected_min(max_abs: f64, expected_min: Option<f64>) -> Result<(), String> { |
| 123 | match expected_min { |
| 124 | Some(min) if !(max_abs >= min) => Err(format!( |
| 125 | "NOISE_FLOOR max_abs={:.6e} is below expected minimum {:.6e}", |
| 126 | max_abs, min |
| 127 | )), |
| 128 | _ => Ok(()), |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | fn assert_sane(logits: &[f32], vocab: usize, what: &str) { |
| 133 | assert_eq!(logits.len(), vocab, "{what}: logits width != vocab"); |
| 134 | assert!( |
| 135 | logits.iter().all(|x| x.is_finite()), |
| 136 | "{what}: non-finite logit" |
| 137 | ); |
| 138 | let min = logits.iter().cloned().fold(f32::INFINITY, f32::min); |
| 139 | let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max); |
| 140 | assert!(max > min, "{what}: logits are constant ({min})"); |
| 141 | } |
| 142 | |
| 143 | fn sha256_file(path: &Path) -> String { |
| 144 | let mut f = std::fs::File::open(path) |
| 145 | .unwrap_or_else(|e| panic!("cannot open {} for hashing: {e}", path.display())); |
| 146 | let mut hasher = Sha256::new(); |
| 147 | let mut buf = vec![0u8; 8 << 20]; |
| 148 | loop { |
| 149 | let n = f |
| 150 | .read(&mut buf) |
| 151 | .unwrap_or_else(|e| panic!("read {}: {e}", path.display())); |
| 152 | if n == 0 { |
| 153 | break; |
| 154 | } |
| 155 | hasher.update(&buf[..n]); |
| 156 | } |
| 157 | let mut hex = String::with_capacity(64); |
| 158 | for b in hasher.finalize().iter() { |
| 159 | let _ = write!(hex, "{b:02x}"); |
| 160 | } |
| 161 | hex |
| 162 | } |
| 163 | |
| 164 | fn resolve_checkpoint() -> PathBuf { |
| 165 | let raw = std::env::var("AIEN_E2E_CHECKPOINT").unwrap_or_else(|_| { |
| 166 | panic!( |
| 167 | "AIEN_E2E_CHECKPOINT is unset: this measurement needs the real TinyLlama checkpoint \ |
| 168 | (directory with model.safetensors, or the file itself). Refusing to fall back." |
| 169 | ) |
| 170 | }); |
| 171 | let p = PathBuf::from(raw); |
| 172 | let file = if p.is_dir() { |
| 173 | p.join("model.safetensors") |
| 174 | } else { |
| 175 | p |
| 176 | }; |
| 177 | assert!( |
| 178 | file.is_file(), |
| 179 | "AIEN_E2E_CHECKPOINT does not resolve to a file: {}", |
| 180 | file.display() |
| 181 | ); |
| 182 | file |
| 183 | } |
| 184 | |
| 185 | /// Path (a): one-shot prefill on a fresh sequence, last-position logits. |
| 186 | fn one_shot(be: &mut NativeTransformerBackend, seq_id: u64, tokens: &[u32]) -> Vec<f32> { |
| 187 | let logits = be |
| 188 | .prefill_sequence(seq_id, tokens) |
| 189 | .unwrap_or_else(|e| panic!("one-shot prefill failed: {e}")); |
| 190 | be.release_sequence(seq_id); |
| 191 | logits |
| 192 | } |
| 193 | |
| 194 | /// Path (b): prefill(prompt), then one forward step per teacher token at position |
| 195 | /// `tokens.len()` (same convention as `append_branch_token`, `transformer_backend.rs:286`). |
| 196 | fn incremental( |
| 197 | be: &mut NativeTransformerBackend, |
| 198 | seq_id: u64, |
| 199 | prompt: &[u32], |
| 200 | teacher: &[u32], |
| 201 | ) -> Vec<f32> { |
| 202 | let mut logits = be |
| 203 | .prefill_sequence(seq_id, prompt) |
| 204 | .unwrap_or_else(|e| panic!("prompt prefill failed: {e}")); |
| 205 | for &tok in teacher { |
| 206 | let NativeTransformerBackend { |
| 207 | weights, |
| 208 | sequences, |
| 209 | tensor_backend, |
| 210 | kv_manager, |
| 211 | .. |
| 212 | } = &mut *be; |
| 213 | let seq = sequences |
| 214 | .get_mut(&seq_id) |
| 215 | .expect("sequence vanished after prefill"); |
| 216 | let pos = seq.tokens.len(); |
| 217 | let hidden = NativeTransformerBackend::forward_token_impl_paged( |
| 218 | weights, |
| 219 | &**tensor_backend, |
| 220 | tok, |
| 221 | pos, |
| 222 | seq, |
| 223 | seq_id, |
| 224 | kv_manager.as_ref(), |
| 225 | ); |
| 226 | seq.tokens.push(tok); |
| 227 | logits = NativeTransformerBackend::compute_logits_impl(weights, &**tensor_backend, &hidden); |
| 228 | } |
| 229 | be.release_sequence(seq_id); |
| 230 | logits |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | #[ignore = "needs AIEN_E2E_CHECKPOINT (real TinyLlama); run by the forge with --ignored"] |
| 235 | fn tinyllama_noise_floor_cpu_reference() { |
| 236 | let model_path = resolve_checkpoint(); |
| 237 | let runs: usize = std::env::var("AIEN_NOISE_FLOOR_RUNS") |
| 238 | .ok() |
| 239 | .map(|v| v.parse().expect("AIEN_NOISE_FLOOR_RUNS must be an integer")) |
| 240 | .unwrap_or(DEFAULT_RUNS); |
| 241 | assert!(runs >= 2, "need at least 2 runs for a repeat-run floor"); |
| 242 | let expected_min: Option<f64> = |
| 243 | std::env::var("AIEN_NOISE_FLOOR_EXPECT_MIN_ABS") |
| 244 | .ok() |
| 245 | .map(|v| { |
| 246 | v.parse() |
| 247 | .expect("AIEN_NOISE_FLOOR_EXPECT_MIN_ABS must be a number") |
| 248 | }); |
| 249 | |
| 250 | let tokenizer_path = |
| 251 | PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/tokenizer.json"); |
| 252 | let tokenizer = TinyLlamaTokenizer::from_file(&tokenizer_path) |
| 253 | .unwrap_or_else(|e| panic!("in-repo tokenizer {}: {e}", tokenizer_path.display())); |
| 254 | |
| 255 | let model_sha256 = sha256_file(&model_path); |
| 256 | let config = ModelConfig::tinyllama_1_1b(); |
| 257 | let vocab = config.vocab_size; |
| 258 | let weights = TransformerWeights::load_from_safetensors(&model_path, &config) |
| 259 | .unwrap_or_else(|e| panic!("load {}: {e}", model_path.display())); |
| 260 | // CPU reference backend only (no CUDA, no AIEN_REQUIRE_BLACKWELL). |
| 261 | let mut be = NativeTransformerBackend::new_reference(weights); |
| 262 | let backend_name = be.tensor_backend.name(); |
| 263 | assert_eq!(backend_name, "ReferenceCpuBackend"); |
| 264 | |
| 265 | let mut floor = Diff::default(); |
| 266 | let mut next_id: u64 = 0xC7_0000; |
| 267 | for (idx, (prompt_text, cont_text)) in PROMPTS.iter().enumerate() { |
| 268 | let prompt = tokenizer |
| 269 | .encode_with_special(prompt_text, true) |
| 270 | .expect("encode prompt"); |
| 271 | let cont = tokenizer |
| 272 | .encode_with_special(cont_text, false) |
| 273 | .expect("encode continuation"); |
| 274 | assert!( |
| 275 | cont.len() >= K_TEACHER, |
| 276 | "prompt {idx}: continuation has {} tokens, need {K_TEACHER}", |
| 277 | cont.len() |
| 278 | ); |
| 279 | let teacher = &cont[..K_TEACHER]; |
| 280 | let mut full = prompt.clone(); |
| 281 | full.extend_from_slice(teacher); |
| 282 | assert!( |
| 283 | prompt.len() >= 2 && full.len() <= MAX_TOTAL_TOKENS, |
| 284 | "prompt {idx}: {} total tokens outside [2, {MAX_TOTAL_TOKENS}]", |
| 285 | full.len() |
| 286 | ); |
| 287 | |
| 288 | let mut reference: Option<Vec<f32>> = None; |
| 289 | let mut ab = Diff::default(); |
| 290 | let mut repeat = Diff::default(); |
| 291 | for run in 0..runs { |
| 292 | next_id += 1; |
| 293 | let a = one_shot(&mut be, next_id, &full); |
| 294 | next_id += 1; |
| 295 | let b = incremental(&mut be, next_id, &prompt, teacher); |
| 296 | assert_sane(&a, vocab, &format!("prompt {idx} run {run} path a")); |
| 297 | assert_sane(&b, vocab, &format!("prompt {idx} run {run} path b")); |
| 298 | let a0: &[f32] = reference.get_or_insert_with(|| a.clone()); |
| 299 | repeat = repeat.merge(compare(a0, &a, RELATIVE_ERROR_EPSILON)); |
| 300 | ab = ab.merge(compare(a0, &b, RELATIVE_ERROR_EPSILON)); |
| 301 | } |
| 302 | println!( |
| 303 | "NOISE_FLOOR_PROMPT idx={idx} prompt_tokens={} k={K_TEACHER} ab_max_abs={:.6e} ab_max_rel={:.6e} repeat_max_abs={:.6e} repeat_max_rel={:.6e}", |
| 304 | prompt.len(), |
| 305 | ab.max_abs, |
| 306 | ab.max_rel, |
| 307 | repeat.max_abs, |
| 308 | repeat.max_rel |
| 309 | ); |
| 310 | floor = floor.merge(ab).merge(repeat); |
| 311 | } |
| 312 | |
| 313 | println!( |
| 314 | "NOISE_FLOOR_META tokenizer=tests/fixtures/tokenizer.json tokenizer_sha256={} relative_error_epsilon={RELATIVE_ERROR_EPSILON:e}", |
| 315 | sha256_file(&tokenizer_path) |
| 316 | ); |
| 317 | println!( |
| 318 | "NOISE_FLOOR max_abs={:.6e} max_rel={:.6e} runs={runs} prompts={} k={K_TEACHER} backend={backend_name} model_sha256={model_sha256}", |
| 319 | floor.max_abs, |
| 320 | floor.max_rel, |
| 321 | PROMPTS.len() |
| 322 | ); |
| 323 | |
| 324 | if let Err(e) = check_expected_min(floor.max_abs, expected_min) { |
| 325 | panic!("{e}"); |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn compare_sees_injected_perturbation() { |
| 331 | let a: Vec<f32> = (0..64).map(|i| (i as f32) * 0.25 - 4.0).collect(); |
| 332 | assert_eq!(compare(&a, &a, RELATIVE_ERROR_EPSILON), Diff::default()); |
| 333 | let mut b = a.clone(); |
| 334 | b[17] += 1e-2; |
| 335 | let d = compare(&a, &b, RELATIVE_ERROR_EPSILON); |
| 336 | assert!((d.max_abs - 1e-2).abs() < 1e-5, "max_abs {}", d.max_abs); |
| 337 | // a[16] == 0.0: relative error must use the epsilon denominator, not divide by zero. |
| 338 | let mut c = a.clone(); |
| 339 | c[16] += 1e-4; |
| 340 | let dc = compare(&a, &c, RELATIVE_ERROR_EPSILON); |
| 341 | assert!((dc.max_rel - 0.1).abs() < 1e-3, "max_rel {}", dc.max_rel); |
| 342 | } |
| 343 | |
| 344 | #[test] |
| 345 | fn expected_minimum_rejects_small_floor() { |
| 346 | assert!(check_expected_min(5e-3, Some(1e-2)).is_err()); |
| 347 | assert!(check_expected_min(f64::NAN, Some(1e-2)).is_err()); |
| 348 | assert!(check_expected_min(1e-2, Some(1e-2)).is_ok()); |
| 349 | assert!(check_expected_min(0.0, None).is_ok()); |
| 350 | } |
| 351 | |
| 352 | #[test] |
| 353 | fn sanity_rejects_constant_and_nonfinite_logits() { |
| 354 | let flat = vec![1.0f32; 8]; |
| 355 | assert!(std::panic::catch_unwind(|| assert_sane(&flat, 8, "flat")).is_err()); |
| 356 | let mut nan = vec![0.0f32, 1.0, 2.0, 3.0]; |
| 357 | nan[2] = f32::NAN; |
| 358 | assert!(std::panic::catch_unwind(|| assert_sane(&nan, 4, "nan")).is_err()); |
| 359 | assert!(std::panic::catch_unwind(|| assert_sane(&[0.0, 1.0], 2, "ok")).is_ok()); |
| 360 | } |