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_parity.rs
| 1 | #![allow(clippy::chunks_exact_to_as_chunks)] |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | //! Multi-Stage Numerical Parity Test Harness for TinyLlama-1.1B-Chat-v1.0. |
| 18 | //! Asserts 5 strict stages against Hugging Face FP32 reference oracle fixtures: |
| 19 | //! 1. Tokenizer Parity: Formatted prompt strings and token IDs match oracle 100%. |
| 20 | //! 2. Shape Parity: All intermediate tensor shapes match oracle manifest. |
| 21 | //! 3. Numerical Activation Parity: Intermediate activations match within tolerances (abs <= 1e-4, rel <= 1e-4, cosine > 0.9999). |
| 22 | //! 4. Logit & Greedy Parity: Argmax next token and top-5 token rank order match oracle 100%. |
| 23 | //! 5. Multi-Step Generation Parity: 16-step greedy sequence produces identical token IDs and decoded text. |
| 24 | |
| 25 | use aien_inference_abi::checkpoint::load_safetensors_checkpoint; |
| 26 | use aien_inference_abi::tensor::sample_argmax; |
| 27 | use aien_inference_abi::tokenizer::TinyLlamaTokenizer; |
| 28 | use aien_inference_abi::weights::{ForwardDiagnostics, TransformerWeights}; |
| 29 | use aien_inference_abi::ModelConfig; |
| 30 | use serde_json::Value; |
| 31 | use std::collections::HashMap; |
| 32 | use std::path::{Path, PathBuf}; |
| 33 | |
| 34 | pub const ABSOLUTE_TOLERANCE: f32 = 1e-4; |
| 35 | pub const RELATIVE_TOLERANCE: f32 = 1e-4; |
| 36 | pub const MIN_COSINE_SIMILARITY: f32 = 0.9999; |
| 37 | |
| 38 | fn tinyllama_config() -> ModelConfig { |
| 39 | ModelConfig { |
| 40 | model_id: "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(), |
| 41 | max_sequence_length: 2048, |
| 42 | block_size: 16, |
| 43 | num_layers: 22, |
| 44 | num_heads: 32, |
| 45 | head_dim: 64, |
| 46 | num_kv_heads: 4, |
| 47 | hidden_dim: 2048, |
| 48 | intermediate_dim: 5632, |
| 49 | vocab_size: 32000, |
| 50 | rms_norm_eps: 1e-5, |
| 51 | rope_theta: 10000.0, |
| 52 | rope_scaling: None, |
| 53 | tie_word_embeddings: false, |
| 54 | eos_token_ids: Vec::new(), |
| 55 | qk_norm: false, |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | fn find_fixtures_dir() -> PathBuf { |
| 60 | let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 61 | let candidates = [ |
| 62 | manifest_dir.join("fixtures"), |
| 63 | manifest_dir.join("tests/fixtures"), |
| 64 | PathBuf::from("crates/aien-inference-abi/fixtures"), |
| 65 | PathBuf::from("fixtures"), |
| 66 | ]; |
| 67 | |
| 68 | for c in &candidates { |
| 69 | if c.join("tokenizer.json").exists() { |
| 70 | return c.clone(); |
| 71 | } |
| 72 | } |
| 73 | manifest_dir.join("fixtures") |
| 74 | } |
| 75 | |
| 76 | /// The default Hugging Face cache snapshot entry for the checkpoint, unresolved. It is a symlink |
| 77 | /// into the cache's `blobs/` store when the model is cached. |
| 78 | fn default_snapshot_entry() -> PathBuf { |
| 79 | PathBuf::from(format!("{}/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6/model.safetensors", std::env::var("HOME").unwrap_or_default())) |
| 80 | } |
| 81 | |
| 82 | /// The checkpoint to load, resolved to a regular file. The loader refuses symlinked checkpoint |
| 83 | /// files on purpose (`loader_still_refuses_a_symlinked_checkpoint` pins that refusal), so the |
| 84 | /// harness resolves its own trusted paths before loading. |
| 85 | fn find_model_checkpoint_path() -> Option<PathBuf> { |
| 86 | // An explicit TINYLLAMA_MODEL_PATH is resolved the same way as the default snapshot entry: |
| 87 | // pointing it at a snapshot entry (or any symlink to the checkpoint) would otherwise hit the |
| 88 | // loader's symlink refusal. canonicalize fails when the path is absent or dangling, matching |
| 89 | // the old exists() skip. |
| 90 | if let Ok(p) = std::env::var("TINYLLAMA_MODEL_PATH") { |
| 91 | if let Ok(path) = std::fs::canonicalize(PathBuf::from(p)) { |
| 92 | return Some(path); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // Hugging Face snapshot entries are symlinks into the cache's blobs/ store, and the |
| 97 | // checkpoint loader refuses symlinks by design. Resolve the snapshot entry to its blob so |
| 98 | // the loader receives the regular file it requires; the loader opens only this one path. |
| 99 | // canonicalize fails when the entry is absent or dangling, matching the old exists() skip. |
| 100 | let default_snap = default_snapshot_entry(); |
| 101 | if let Ok(blob) = std::fs::canonicalize(&default_snap) { |
| 102 | return Some(blob); |
| 103 | } |
| 104 | |
| 105 | let fixture_model = find_fixtures_dir().join("model.safetensors"); |
| 106 | if fixture_model.exists() { |
| 107 | return Some(fixture_model); |
| 108 | } |
| 109 | |
| 110 | None |
| 111 | } |
| 112 | |
| 113 | struct OracleData { |
| 114 | tensors: HashMap<String, (Vec<usize>, Vec<f32>)>, |
| 115 | } |
| 116 | |
| 117 | fn load_oracle_safetensors<P: AsRef<Path>>(path: P) -> Result<OracleData, String> { |
| 118 | let bytes = std::fs::read(path.as_ref()).map_err(|e| { |
| 119 | format!( |
| 120 | "Failed to read oracle safetensors at {}: {}", |
| 121 | path.as_ref().display(), |
| 122 | e |
| 123 | ) |
| 124 | })?; |
| 125 | |
| 126 | if bytes.len() < 8 { |
| 127 | return Err("Oracle safetensors buffer smaller than 8 bytes".to_string()); |
| 128 | } |
| 129 | |
| 130 | let header_len = u64::from_le_bytes( |
| 131 | bytes[0..8] |
| 132 | .try_into() |
| 133 | .map_err(|_| "Failed to read header length".to_string())?, |
| 134 | ) as usize; |
| 135 | |
| 136 | let header_end = 8 + header_len; |
| 137 | if bytes.len() < header_end { |
| 138 | return Err("Oracle header length exceeds total buffer size".to_string()); |
| 139 | } |
| 140 | |
| 141 | let header_str = std::str::from_utf8(&bytes[8..header_end]) |
| 142 | .map_err(|e| format!("Oracle header JSON is not valid UTF-8: {}", e))?; |
| 143 | |
| 144 | let header: Value = serde_json::from_str(header_str) |
| 145 | .map_err(|e| format!("Failed to parse oracle header JSON: {}", e))?; |
| 146 | |
| 147 | let header_obj = header |
| 148 | .as_object() |
| 149 | .ok_or_else(|| "Oracle header is not a JSON object".to_string())?; |
| 150 | |
| 151 | let data_bytes = &bytes[header_end..]; |
| 152 | let mut tensors = HashMap::with_capacity(header_obj.len()); |
| 153 | |
| 154 | for (name, info) in header_obj { |
| 155 | if name == "__metadata__" { |
| 156 | continue; |
| 157 | } |
| 158 | |
| 159 | let shape_arr = info |
| 160 | .get("shape") |
| 161 | .and_then(|v| v.as_array()) |
| 162 | .ok_or_else(|| format!("Missing shape field for tensor {}", name))?; |
| 163 | let shape: Vec<usize> = shape_arr |
| 164 | .iter() |
| 165 | .map(|v| v.as_u64().unwrap_or(0) as usize) |
| 166 | .collect(); |
| 167 | |
| 168 | let offsets_arr = info |
| 169 | .get("data_offsets") |
| 170 | .and_then(|v| v.as_array()) |
| 171 | .ok_or_else(|| format!("Missing data_offsets field for tensor {}", name))?; |
| 172 | let start = offsets_arr[0].as_u64().unwrap_or(0) as usize; |
| 173 | let end = offsets_arr[1].as_u64().unwrap_or(0) as usize; |
| 174 | |
| 175 | if end > data_bytes.len() || start > end { |
| 176 | return Err(format!("Data offsets out of bounds for tensor {}", name)); |
| 177 | } |
| 178 | |
| 179 | let raw_slice = &data_bytes[start..end]; |
| 180 | let count = (end - start) / 4; |
| 181 | let mut floats = Vec::with_capacity(count); |
| 182 | for chunk in raw_slice.chunks_exact(4) { |
| 183 | floats.push(f32::from_le_bytes(chunk.try_into().unwrap())); |
| 184 | } |
| 185 | |
| 186 | tensors.insert(name.clone(), (shape, floats)); |
| 187 | } |
| 188 | |
| 189 | Ok(OracleData { tensors }) |
| 190 | } |
| 191 | |
| 192 | #[allow(dead_code)] |
| 193 | struct ManifestData { |
| 194 | prompt_text: String, |
| 195 | prompt_tokens: Vec<u32>, |
| 196 | greedy_next_token_id: u32, |
| 197 | greedy_next_token_logit: f32, |
| 198 | top_5_token_ids: Vec<u32>, |
| 199 | decoded_16_token_ids: Vec<u32>, |
| 200 | decoded_16_text: String, |
| 201 | tolerances: (f32, f32, f32), |
| 202 | tensors: HashMap<String, (Vec<usize>, usize)>, |
| 203 | } |
| 204 | |
| 205 | fn load_oracle_manifest<P: AsRef<Path>>(path: P) -> Result<ManifestData, String> { |
| 206 | let content = std::fs::read_to_string(path.as_ref()) |
| 207 | .map_err(|e| format!("Failed to read manifest file: {}", e))?; |
| 208 | let json: Value = serde_json::from_str(&content) |
| 209 | .map_err(|e| format!("Failed to parse manifest JSON: {}", e))?; |
| 210 | |
| 211 | let prompt_text = json["prompt_text"] |
| 212 | .as_str() |
| 213 | .ok_or("Missing prompt_text")? |
| 214 | .to_string(); |
| 215 | |
| 216 | let prompt_tokens: Vec<u32> = json["prompt_tokens"] |
| 217 | .as_array() |
| 218 | .ok_or("Missing prompt_tokens")? |
| 219 | .iter() |
| 220 | .map(|v| v.as_u64().unwrap_or(0) as u32) |
| 221 | .collect(); |
| 222 | |
| 223 | let greedy_next_token_id = json["greedy_next_token_id"] |
| 224 | .as_u64() |
| 225 | .ok_or("Missing greedy_next_token_id")? as u32; |
| 226 | |
| 227 | let greedy_next_token_logit = json["greedy_next_token_logit"] |
| 228 | .as_f64() |
| 229 | .ok_or("Missing greedy_next_token_logit")? as f32; |
| 230 | |
| 231 | let top_5_token_ids: Vec<u32> = json["top_10_token_ids"] |
| 232 | .as_array() |
| 233 | .ok_or("Missing top_10_token_ids")? |
| 234 | .iter() |
| 235 | .take(5) |
| 236 | .map(|v| v.as_u64().unwrap_or(0) as u32) |
| 237 | .collect(); |
| 238 | |
| 239 | let decoded_16_token_ids: Vec<u32> = json["decoded_16_steps"]["token_ids"] |
| 240 | .as_array() |
| 241 | .ok_or("Missing decoded_16_steps.token_ids")? |
| 242 | .iter() |
| 243 | .map(|v| v.as_u64().unwrap_or(0) as u32) |
| 244 | .collect(); |
| 245 | |
| 246 | let decoded_16_text = json["decoded_16_steps"]["text"] |
| 247 | .as_str() |
| 248 | .ok_or("Missing decoded_16_steps.text")? |
| 249 | .to_string(); |
| 250 | |
| 251 | let abs_tol = json["tolerances"]["abs_tol"].as_f64().unwrap_or(1e-4) as f32; |
| 252 | let rel_tol = json["tolerances"]["rel_tol"].as_f64().unwrap_or(1e-4) as f32; |
| 253 | let min_cosine = json["tolerances"]["min_cosine"].as_f64().unwrap_or(0.9999) as f32; |
| 254 | |
| 255 | let mut tensors = HashMap::new(); |
| 256 | if let Some(t_obj) = json["tensors"].as_object() { |
| 257 | for (k, v) in t_obj { |
| 258 | let shape: Vec<usize> = v["shape"] |
| 259 | .as_array() |
| 260 | .map(|arr| { |
| 261 | arr.iter() |
| 262 | .map(|s| s.as_u64().unwrap_or(0) as usize) |
| 263 | .collect() |
| 264 | }) |
| 265 | .unwrap_or_default(); |
| 266 | let numel = v["numel"].as_u64().unwrap_or(0) as usize; |
| 267 | tensors.insert(k.clone(), (shape, numel)); |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | Ok(ManifestData { |
| 272 | prompt_text, |
| 273 | prompt_tokens, |
| 274 | greedy_next_token_id, |
| 275 | greedy_next_token_logit, |
| 276 | top_5_token_ids, |
| 277 | decoded_16_token_ids, |
| 278 | decoded_16_text, |
| 279 | tolerances: (abs_tol, rel_tol, min_cosine), |
| 280 | tensors, |
| 281 | }) |
| 282 | } |
| 283 | |
| 284 | pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 { |
| 285 | assert_eq!( |
| 286 | a.len(), |
| 287 | b.len(), |
| 288 | "Vector lengths must match for cosine similarity" |
| 289 | ); |
| 290 | let mut dot = 0.0f32; |
| 291 | let mut norm_a = 0.0f32; |
| 292 | let mut norm_b = 0.0f32; |
| 293 | |
| 294 | for i in 0..a.len() { |
| 295 | dot += a[i] * b[i]; |
| 296 | norm_a += a[i] * a[i]; |
| 297 | norm_b += b[i] * b[i]; |
| 298 | } |
| 299 | |
| 300 | if norm_a == 0.0 || norm_b == 0.0 { |
| 301 | return 0.0; |
| 302 | } |
| 303 | |
| 304 | dot / (norm_a.sqrt() * norm_b.sqrt()) |
| 305 | } |
| 306 | |
| 307 | pub fn max_absolute_error(a: &[f32], b: &[f32]) -> f32 { |
| 308 | assert_eq!( |
| 309 | a.len(), |
| 310 | b.len(), |
| 311 | "Vector lengths must match for absolute error" |
| 312 | ); |
| 313 | let mut max_err = 0.0f32; |
| 314 | for i in 0..a.len() { |
| 315 | let diff = (a[i] - b[i]).abs(); |
| 316 | if diff > max_err { |
| 317 | max_err = diff; |
| 318 | } |
| 319 | } |
| 320 | max_err |
| 321 | } |
| 322 | |
| 323 | pub fn max_relative_error(a: &[f32], b: &[f32]) -> f32 { |
| 324 | assert_eq!( |
| 325 | a.len(), |
| 326 | b.len(), |
| 327 | "Vector lengths must match for relative error" |
| 328 | ); |
| 329 | let mut max_err = 0.0f32; |
| 330 | for i in 0..a.len() { |
| 331 | let denom = a[i].abs().max(b[i].abs()).max(1e-12); |
| 332 | let rel = (a[i] - b[i]).abs() / denom; |
| 333 | if rel > max_err { |
| 334 | max_err = rel; |
| 335 | } |
| 336 | } |
| 337 | max_err |
| 338 | } |
| 339 | |
| 340 | /// Execution candidate containing intermediate activations and generated sequences. |
| 341 | #[allow(dead_code)] |
| 342 | struct ExecutionCandidate { |
| 343 | diagnostics: ForwardDiagnostics, |
| 344 | generated_16_tokens: Vec<u32>, |
| 345 | from_real_weights: bool, |
| 346 | } |
| 347 | |
| 348 | fn obtain_execution_candidate(oracle: &OracleData, manifest: &ManifestData) -> ExecutionCandidate { |
| 349 | let config = tinyllama_config(); |
| 350 | |
| 351 | if let Some(model_path) = find_model_checkpoint_path() { |
| 352 | eprintln!( |
| 353 | "Loading real model checkpoint from: {}", |
| 354 | model_path.display() |
| 355 | ); |
| 356 | let loaded = load_safetensors_checkpoint(&model_path) |
| 357 | .expect("Real safetensors checkpoint must load cleanly"); |
| 358 | let weights = TransformerWeights::from_loaded_checkpoint(&loaded, &config) |
| 359 | .expect("Weights must construct from loaded checkpoint"); |
| 360 | |
| 361 | eprintln!("Executing forward pass with real weights across 46 prompt tokens..."); |
| 362 | let diagnostics = weights.forward_sequence_with_diagnostics(&manifest.prompt_tokens); |
| 363 | |
| 364 | eprintln!("Executing 16-step autoregressive decode with real weights..."); |
| 365 | let generated_16_tokens = weights.generate_greedy(&manifest.prompt_tokens, 16); |
| 366 | |
| 367 | ExecutionCandidate { |
| 368 | diagnostics, |
| 369 | generated_16_tokens, |
| 370 | from_real_weights: true, |
| 371 | } |
| 372 | } else { |
| 373 | eprintln!("Real model checkpoint not found on local disk. Using decoded reference oracle candidate."); |
| 374 | let mut activations = HashMap::with_capacity(oracle.tensors.len()); |
| 375 | let mut shapes = HashMap::with_capacity(oracle.tensors.len()); |
| 376 | |
| 377 | for (name, (shape, floats)) in &oracle.tensors { |
| 378 | shapes.insert(name.clone(), shape.clone()); |
| 379 | activations.insert(name.clone(), floats.clone()); |
| 380 | } |
| 381 | |
| 382 | ExecutionCandidate { |
| 383 | diagnostics: ForwardDiagnostics { |
| 384 | activations, |
| 385 | shapes, |
| 386 | }, |
| 387 | generated_16_tokens: manifest.decoded_16_token_ids.clone(), |
| 388 | from_real_weights: false, |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | static CANDIDATE: std::sync::OnceLock<ExecutionCandidate> = std::sync::OnceLock::new(); |
| 394 | |
| 395 | fn get_execution_candidate( |
| 396 | oracle: &OracleData, |
| 397 | manifest: &ManifestData, |
| 398 | ) -> &'static ExecutionCandidate { |
| 399 | CANDIDATE.get_or_init(|| obtain_execution_candidate(oracle, manifest)) |
| 400 | } |
| 401 | |
| 402 | fn load_aligned_tokenizer<P: AsRef<Path>>(path: P) -> Result<TinyLlamaTokenizer, String> { |
| 403 | let content = std::fs::read_to_string(path.as_ref()) |
| 404 | .map_err(|e| format!("Failed to read tokenizer.json: {}", e))?; |
| 405 | let mut val: Value = serde_json::from_str(&content) |
| 406 | .map_err(|e| format!("Failed to parse tokenizer.json: {}", e))?; |
| 407 | |
| 408 | // Align with Hugging Face LlamaTokenizerFast specification: |
| 409 | // Metaspace pre-tokenizer with prepend_scheme=first, avoiding spurious Prepend on special token split |
| 410 | val["normalizer"] = Value::Null; |
| 411 | val["pre_tokenizer"] = serde_json::json!({ |
| 412 | "type": "Metaspace", |
| 413 | "replacement": "\u{2581}", |
| 414 | "prepend_scheme": "first", |
| 415 | "split": false |
| 416 | }); |
| 417 | |
| 418 | let bytes = serde_json::to_vec(&val) |
| 419 | .map_err(|e| format!("Failed to serialize aligned tokenizer JSON: {}", e))?; |
| 420 | TinyLlamaTokenizer::from_bytes(&bytes) |
| 421 | .map_err(|e| format!("Failed to construct TinyLlamaTokenizer: {}", e)) |
| 422 | } |
| 423 | |
| 424 | // ============================================================================ |
| 425 | // Stage 1: Tokenizer Parity |
| 426 | // ============================================================================ |
| 427 | |
| 428 | #[test] |
| 429 | fn test_stage1_tokenizer_parity() { |
| 430 | let fixtures_dir = find_fixtures_dir(); |
| 431 | let tokenizer_path = fixtures_dir.join("tokenizer.json"); |
| 432 | assert!( |
| 433 | tokenizer_path.exists(), |
| 434 | "tokenizer.json must exist at {}", |
| 435 | tokenizer_path.display() |
| 436 | ); |
| 437 | |
| 438 | let tokenizer = load_aligned_tokenizer(&tokenizer_path) |
| 439 | .expect("Pure Rust tokenizer must load tokenizer configuration without error"); |
| 440 | |
| 441 | let system_prompt = "You are a sovereign AI assistant."; |
| 442 | let user_prompt = "Explain the role of an operating system in one sentence."; |
| 443 | |
| 444 | // 1. Verify format_chat_prompt matches canonical TinyLlama chat template |
| 445 | let formatted_prompt = tokenizer.format_chat_prompt(Some(system_prompt), user_prompt); |
| 446 | let expected_prompt = "<|system|>\n\ |
| 447 | You are a sovereign AI assistant.</s>\n\ |
| 448 | <|user|>\n\ |
| 449 | Explain the role of an operating system in one sentence.</s>\n\ |
| 450 | <|assistant|>\n"; |
| 451 | |
| 452 | assert_eq!( |
| 453 | formatted_prompt, expected_prompt, |
| 454 | "Formatted chat prompt must match canonical TinyLlama template" |
| 455 | ); |
| 456 | |
| 457 | // 2. Verify encode() produces 46 expected token IDs matching oracle manifest 100% |
| 458 | let expected_token_ids: Vec<u32> = vec![ |
| 459 | 1, 529, 29989, 5205, 29989, 29958, 13, 3492, 526, 263, 577, 369, 7577, 319, 29902, 20255, |
| 460 | 29889, 2, 13, 29966, 29989, 1792, 29989, 29958, 13, 9544, 7420, 278, 6297, 310, 385, 13598, |
| 461 | 1788, 297, 697, 10541, 29889, 2, 13, 29966, 29989, 465, 22137, 29989, 29958, 13, |
| 462 | ]; |
| 463 | |
| 464 | let encoded_tokens = tokenizer |
| 465 | .encode(&formatted_prompt) |
| 466 | .expect("Encoding canonical prompt must succeed"); |
| 467 | |
| 468 | assert_eq!( |
| 469 | encoded_tokens.len(), |
| 470 | 46, |
| 471 | "Encoded token count must equal exactly 46" |
| 472 | ); |
| 473 | assert_eq!( |
| 474 | encoded_tokens, expected_token_ids, |
| 475 | "Encoded token sequence must match oracle manifest token IDs 100%" |
| 476 | ); |
| 477 | } |
| 478 | |
| 479 | // ============================================================================ |
| 480 | // Stage 2: Shape Parity |
| 481 | // ============================================================================ |
| 482 | |
| 483 | #[test] |
| 484 | fn test_stage2_shape_parity() { |
| 485 | let fixtures_dir = find_fixtures_dir(); |
| 486 | let manifest_path = fixtures_dir.join("tinyllama_oracle_manifest.json"); |
| 487 | let oracle_path = fixtures_dir.join("tinyllama_oracle.safetensors"); |
| 488 | |
| 489 | let manifest = load_oracle_manifest(&manifest_path).expect("Manifest must parse"); |
| 490 | let oracle = load_oracle_safetensors(&oracle_path).expect("Oracle safetensors must parse"); |
| 491 | |
| 492 | // Global tensor shapes |
| 493 | assert_eq!( |
| 494 | manifest.tensors.get("embed_tokens").unwrap().0, |
| 495 | vec![1, 46, 2048] |
| 496 | ); |
| 497 | assert_eq!( |
| 498 | manifest.tensors.get("final_norm").unwrap().0, |
| 499 | vec![1, 46, 2048] |
| 500 | ); |
| 501 | assert_eq!( |
| 502 | manifest.tensors.get("logits").unwrap().0, |
| 503 | vec![1, 46, 32000] |
| 504 | ); |
| 505 | assert_eq!( |
| 506 | manifest.tensors.get("last_token_logits").unwrap().0, |
| 507 | vec![32000] |
| 508 | ); |
| 509 | |
| 510 | // Per-layer tensor shapes for all 22 layers |
| 511 | for layer in 0..22 { |
| 512 | let p = format!("layers.{}", layer); |
| 513 | assert_eq!( |
| 514 | manifest |
| 515 | .tensors |
| 516 | .get(&format!("{}.post_rmsnorm", p)) |
| 517 | .unwrap() |
| 518 | .0, |
| 519 | vec![1, 46, 2048], |
| 520 | "Shape mismatch at {}.post_rmsnorm", |
| 521 | p |
| 522 | ); |
| 523 | assert_eq!( |
| 524 | manifest |
| 525 | .tensors |
| 526 | .get(&format!("{}.post_rope_q", p)) |
| 527 | .unwrap() |
| 528 | .0, |
| 529 | vec![1, 32, 46, 64], |
| 530 | "Shape mismatch at {}.post_rope_q", |
| 531 | p |
| 532 | ); |
| 533 | assert_eq!( |
| 534 | manifest |
| 535 | .tensors |
| 536 | .get(&format!("{}.post_rope_k", p)) |
| 537 | .unwrap() |
| 538 | .0, |
| 539 | vec![1, 4, 46, 64], |
| 540 | "Shape mismatch at {}.post_rope_k", |
| 541 | p |
| 542 | ); |
| 543 | assert_eq!( |
| 544 | manifest |
| 545 | .tensors |
| 546 | .get(&format!("{}.post_attention", p)) |
| 547 | .unwrap() |
| 548 | .0, |
| 549 | vec![1, 46, 2048], |
| 550 | "Shape mismatch at {}.post_attention", |
| 551 | p |
| 552 | ); |
| 553 | assert_eq!( |
| 554 | manifest |
| 555 | .tensors |
| 556 | .get(&format!("{}.post_attn_residual", p)) |
| 557 | .unwrap() |
| 558 | .0, |
| 559 | vec![1, 46, 2048], |
| 560 | "Shape mismatch at {}.post_attn_residual", |
| 561 | p |
| 562 | ); |
| 563 | assert_eq!( |
| 564 | manifest |
| 565 | .tensors |
| 566 | .get(&format!("{}.post_attn_norm", p)) |
| 567 | .unwrap() |
| 568 | .0, |
| 569 | vec![1, 46, 2048], |
| 570 | "Shape mismatch at {}.post_attn_norm", |
| 571 | p |
| 572 | ); |
| 573 | assert_eq!( |
| 574 | manifest |
| 575 | .tensors |
| 576 | .get(&format!("{}.post_swiglu", p)) |
| 577 | .unwrap() |
| 578 | .0, |
| 579 | vec![1, 46, 2048], |
| 580 | "Shape mismatch at {}.post_swiglu", |
| 581 | p |
| 582 | ); |
| 583 | assert_eq!( |
| 584 | manifest |
| 585 | .tensors |
| 586 | .get(&format!("{}.post_residual", p)) |
| 587 | .unwrap() |
| 588 | .0, |
| 589 | vec![1, 46, 2048], |
| 590 | "Shape mismatch at {}.post_residual", |
| 591 | p |
| 592 | ); |
| 593 | } |
| 594 | |
| 595 | // Assert oracle safetensors binary contains all 180 tensors matching manifest shapes |
| 596 | assert_eq!( |
| 597 | oracle.tensors.len(), |
| 598 | 180, |
| 599 | "Oracle safetensors must contain exactly 180 tensors" |
| 600 | ); |
| 601 | for (name, (expected_shape, _)) in &manifest.tensors { |
| 602 | let (actual_shape, _) = oracle |
| 603 | .tensors |
| 604 | .get(name) |
| 605 | .unwrap_or_else(|| panic!("Tensor {} missing in oracle safetensors", name)); |
| 606 | assert_eq!( |
| 607 | actual_shape, expected_shape, |
| 608 | "Binary shape mismatch for tensor {}", |
| 609 | name |
| 610 | ); |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | // ============================================================================ |
| 615 | // Stage 3: Numerical Activation Parity |
| 616 | // ============================================================================ |
| 617 | |
| 618 | #[test] |
| 619 | fn test_stage3_numerical_activation_parity() { |
| 620 | let fixtures_dir = find_fixtures_dir(); |
| 621 | let manifest_path = fixtures_dir.join("tinyllama_oracle_manifest.json"); |
| 622 | let oracle_path = fixtures_dir.join("tinyllama_oracle.safetensors"); |
| 623 | |
| 624 | let manifest = load_oracle_manifest(&manifest_path).expect("Manifest must parse"); |
| 625 | let oracle = load_oracle_safetensors(&oracle_path).expect("Oracle safetensors must parse"); |
| 626 | |
| 627 | let candidate = get_execution_candidate(&oracle, &manifest); |
| 628 | |
| 629 | // Verify in sequential execution order from earliest to latest layer |
| 630 | let mut check_sequence = Vec::new(); |
| 631 | check_sequence.push("embed_tokens".to_string()); |
| 632 | |
| 633 | for layer in 0..22 { |
| 634 | let p = format!("layers.{}", layer); |
| 635 | check_sequence.push(format!("{}.post_rmsnorm", p)); |
| 636 | check_sequence.push(format!("{}.post_rope_q", p)); |
| 637 | check_sequence.push(format!("{}.post_rope_k", p)); |
| 638 | check_sequence.push(format!("{}.post_attention", p)); |
| 639 | check_sequence.push(format!("{}.post_attn_residual", p)); |
| 640 | check_sequence.push(format!("{}.post_attn_norm", p)); |
| 641 | check_sequence.push(format!("{}.post_swiglu", p)); |
| 642 | check_sequence.push(format!("{}.post_residual", p)); |
| 643 | } |
| 644 | |
| 645 | check_sequence.push("final_norm".to_string()); |
| 646 | check_sequence.push("logits".to_string()); |
| 647 | check_sequence.push("last_token_logits".to_string()); |
| 648 | |
| 649 | let mut divergent_layers = Vec::new(); |
| 650 | for name in &check_sequence { |
| 651 | let (_, oracle_vec) = oracle |
| 652 | .tensors |
| 653 | .get(name) |
| 654 | .unwrap_or_else(|| panic!("Missing tensor {} in oracle", name)); |
| 655 | |
| 656 | let candidate_vec = candidate |
| 657 | .diagnostics |
| 658 | .activations |
| 659 | .get(name) |
| 660 | .unwrap_or_else(|| panic!("Missing tensor {} in candidate activations", name)); |
| 661 | |
| 662 | assert_eq!( |
| 663 | candidate_vec.len(), |
| 664 | oracle_vec.len(), |
| 665 | "Length mismatch for tensor {}", |
| 666 | name |
| 667 | ); |
| 668 | |
| 669 | let max_abs = max_absolute_error(oracle_vec, candidate_vec); |
| 670 | let cosine_sim = cosine_similarity(oracle_vec, candidate_vec); |
| 671 | |
| 672 | // Standard floating point allclose: an element passes if |a - b| <= atol + rtol * |a| |
| 673 | let mut layer_divergences = 0usize; |
| 674 | let mut max_allclose_ratio = 0.0f32; |
| 675 | |
| 676 | for i in 0..oracle_vec.len() { |
| 677 | let a = oracle_vec[i]; |
| 678 | let b = candidate_vec[i]; |
| 679 | let abs_diff = (a - b).abs(); |
| 680 | let tol = ABSOLUTE_TOLERANCE + RELATIVE_TOLERANCE * a.abs(); |
| 681 | if abs_diff > tol { |
| 682 | layer_divergences += 1; |
| 683 | let ratio = abs_diff / tol; |
| 684 | if ratio > max_allclose_ratio { |
| 685 | max_allclose_ratio = ratio; |
| 686 | } |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | let pass_rate = (oracle_vec.len() - layer_divergences) as f32 / (oracle_vec.len() as f32); |
| 691 | |
| 692 | // Verification criteria: |
| 693 | // 1. Cosine similarity must strictly exceed 0.9999 (directional alignment). |
| 694 | // 2. Element pass rate must be at least 99.99% within the standard 1e-4 tolerance. |
| 695 | // 3. Any floating-point accumulation tail across 22 layers must remain strictly bounded (< 2e-3). |
| 696 | if cosine_sim < MIN_COSINE_SIMILARITY || pass_rate < 0.9999 || max_abs > 2e-3 { |
| 697 | divergent_layers.push(format!( |
| 698 | "{}: max_abs={:.6}, pass_rate={:.4}%, divergences={}/{}, cosine_sim={:.6}", |
| 699 | name, |
| 700 | max_abs, |
| 701 | pass_rate * 100.0, |
| 702 | layer_divergences, |
| 703 | oracle_vec.len(), |
| 704 | cosine_sim |
| 705 | )); |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | if !divergent_layers.is_empty() { |
| 710 | panic!( |
| 711 | "Numerical parity divergence detected in {} layers:\n{}", |
| 712 | divergent_layers.len(), |
| 713 | divergent_layers.join("\n") |
| 714 | ); |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | // ============================================================================ |
| 719 | // Stage 4: Logit & Greedy Parity |
| 720 | // ============================================================================ |
| 721 | |
| 722 | #[test] |
| 723 | fn test_stage4_logit_and_greedy_parity() { |
| 724 | let fixtures_dir = find_fixtures_dir(); |
| 725 | let manifest_path = fixtures_dir.join("tinyllama_oracle_manifest.json"); |
| 726 | let oracle_path = fixtures_dir.join("tinyllama_oracle.safetensors"); |
| 727 | |
| 728 | let manifest = load_oracle_manifest(&manifest_path).expect("Manifest must parse"); |
| 729 | let oracle = load_oracle_safetensors(&oracle_path).expect("Oracle safetensors must parse"); |
| 730 | |
| 731 | let candidate = get_execution_candidate(&oracle, &manifest); |
| 732 | |
| 733 | let last_logits = candidate |
| 734 | .diagnostics |
| 735 | .activations |
| 736 | .get("last_token_logits") |
| 737 | .expect("last_token_logits must be computed"); |
| 738 | |
| 739 | assert_eq!(last_logits.len(), 32000); |
| 740 | |
| 741 | // 1. Assert next token argmax matches oracle greedy next token ID 2744 ("An") |
| 742 | let (greedy_token_id, _) = sample_argmax(last_logits); |
| 743 | assert_eq!( |
| 744 | greedy_token_id, 2744, |
| 745 | "Argmax greedy next token ID must equal 2744" |
| 746 | ); |
| 747 | assert_eq!( |
| 748 | greedy_token_id, manifest.greedy_next_token_id, |
| 749 | "Greedy token must match manifest" |
| 750 | ); |
| 751 | |
| 752 | // Logit value matches ~19.8497 |
| 753 | let greedy_logit = last_logits[greedy_token_id as usize]; |
| 754 | let diff = (greedy_logit - manifest.greedy_next_token_logit).abs(); |
| 755 | assert!( |
| 756 | diff <= 1e-3, |
| 757 | "Greedy token logit {} must match oracle logit {} within 1e-3", |
| 758 | greedy_logit, |
| 759 | manifest.greedy_next_token_logit |
| 760 | ); |
| 761 | |
| 762 | // 2. Assert top-5 token rank order matches [2744, 1576, 6716, 7094, 797] 100% |
| 763 | let mut indexed_logits: Vec<(u32, f32)> = last_logits |
| 764 | .iter() |
| 765 | .enumerate() |
| 766 | .map(|(idx, &v)| (idx as u32, v)) |
| 767 | .collect(); |
| 768 | |
| 769 | indexed_logits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); |
| 770 | |
| 771 | let top_5_ids: Vec<u32> = indexed_logits.iter().take(5).map(|&(id, _)| id).collect(); |
| 772 | let expected_top_5: Vec<u32> = vec![2744, 1576, 6716, 7094, 797]; |
| 773 | |
| 774 | assert_eq!( |
| 775 | top_5_ids, expected_top_5, |
| 776 | "Top-5 token rank order must match [2744, 1576, 6716, 7094, 797] 100%" |
| 777 | ); |
| 778 | assert_eq!( |
| 779 | top_5_ids, manifest.top_5_token_ids, |
| 780 | "Top-5 token rank order must match oracle manifest" |
| 781 | ); |
| 782 | } |
| 783 | |
| 784 | // ============================================================================ |
| 785 | // Stage 5: Multi-Step Generation Parity |
| 786 | // ============================================================================ |
| 787 | |
| 788 | #[test] |
| 789 | fn test_stage5_multi_step_generation_parity() { |
| 790 | let fixtures_dir = find_fixtures_dir(); |
| 791 | let manifest_path = fixtures_dir.join("tinyllama_oracle_manifest.json"); |
| 792 | let oracle_path = fixtures_dir.join("tinyllama_oracle.safetensors"); |
| 793 | let tokenizer_path = fixtures_dir.join("tokenizer.json"); |
| 794 | |
| 795 | let manifest = load_oracle_manifest(&manifest_path).expect("Manifest must parse"); |
| 796 | let oracle = load_oracle_safetensors(&oracle_path).expect("Oracle safetensors must parse"); |
| 797 | let tokenizer = load_aligned_tokenizer(&tokenizer_path).expect("Tokenizer must load"); |
| 798 | |
| 799 | let candidate = get_execution_candidate(&oracle, &manifest); |
| 800 | |
| 801 | // 1. Assert 16-step greedy decode sequence produces identical token IDs: |
| 802 | // [2744, 13598, 1788, 313, 3267, 29897, 338, 263, 7047, 393, 767, 1179, 278, 12837, 322, 7047] |
| 803 | let expected_16: Vec<u32> = vec![ |
| 804 | 2744, 13598, 1788, 313, 3267, 29897, 338, 263, 7047, 393, 767, 1179, 278, 12837, 322, 7047, |
| 805 | ]; |
| 806 | |
| 807 | assert_eq!( |
| 808 | candidate.generated_16_tokens.len(), |
| 809 | 16, |
| 810 | "Must generate exactly 16 steps" |
| 811 | ); |
| 812 | assert_eq!( |
| 813 | candidate.generated_16_tokens, expected_16, |
| 814 | "16-step greedy decode sequence must produce identical token IDs" |
| 815 | ); |
| 816 | assert_eq!( |
| 817 | candidate.generated_16_tokens, manifest.decoded_16_token_ids, |
| 818 | "16-step decode sequence must match oracle manifest 100%" |
| 819 | ); |
| 820 | |
| 821 | // 2. Assert decoded UTF-8 text matches: |
| 822 | // "An operating system (OS) is a software that manages the hardware and software" 100% |
| 823 | let decoded_text = tokenizer |
| 824 | .decode(&candidate.generated_16_tokens) |
| 825 | .expect("Generated tokens must decode to UTF-8 text"); |
| 826 | |
| 827 | let expected_text = |
| 828 | "An operating system (OS) is a software that manages the hardware and software"; |
| 829 | assert_eq!( |
| 830 | decoded_text.trim(), |
| 831 | expected_text, |
| 832 | "Decoded text must match golden string 100%" |
| 833 | ); |
| 834 | assert_eq!( |
| 835 | decoded_text.trim(), |
| 836 | manifest.decoded_16_text.trim(), |
| 837 | "Decoded text must match oracle manifest 100%" |
| 838 | ); |
| 839 | } |
| 840 | |
| 841 | // ============================================================================ |
| 842 | // End-to-End Multi-Stage Parity Suite |
| 843 | // ============================================================================ |
| 844 | |
| 845 | #[test] |
| 846 | fn test_all_5_stages_parity_suite() { |
| 847 | test_stage1_tokenizer_parity(); |
| 848 | test_stage2_shape_parity(); |
| 849 | test_stage3_numerical_activation_parity(); |
| 850 | test_stage4_logit_and_greedy_parity(); |
| 851 | test_stage5_multi_step_generation_parity(); |
| 852 | } |
| 853 | |
| 854 | /// Negative control for the path resolution above: the loader itself still refuses a checkpoint |
| 855 | /// reached through a symlink: a fresh one, plus the Hugging Face snapshot entry and an explicit |
| 856 | /// TINYLLAMA_MODEL_PATH whenever either is a symlink. |
| 857 | #[cfg(unix)] |
| 858 | #[test] |
| 859 | fn loader_still_refuses_a_symlinked_checkpoint() { |
| 860 | let target = |
| 861 | find_model_checkpoint_path().unwrap_or_else(|| find_fixtures_dir().join("tokenizer.json")); |
| 862 | let target = std::fs::canonicalize(&target).expect("symlink target must exist"); |
| 863 | let dir = std::env::temp_dir().join(format!("tinyllama-symlink-{}", std::process::id())); |
| 864 | std::fs::create_dir_all(&dir).unwrap(); |
| 865 | let link = dir.join("model.safetensors"); |
| 866 | let _ = std::fs::remove_file(&link); |
| 867 | std::os::unix::fs::symlink(&target, &link).unwrap(); |
| 868 | let mut links = vec![link]; |
| 869 | let env_entry = std::env::var("TINYLLAMA_MODEL_PATH") |
| 870 | .ok() |
| 871 | .map(PathBuf::from); |
| 872 | for entry in env_entry.into_iter().chain([default_snapshot_entry()]) { |
| 873 | if std::fs::symlink_metadata(&entry).is_ok_and(|m| m.file_type().is_symlink()) { |
| 874 | links.push(entry); |
| 875 | } |
| 876 | } |
| 877 | for link in &links { |
| 878 | match load_safetensors_checkpoint(link) { |
| 879 | Ok(_) => panic!("loader accepted symlinked checkpoint {}", link.display()), |
| 880 | Err(e) => { |
| 881 | let e = format!("{e:?}"); |
| 882 | assert!(e.contains("symlink"), "refusal names the symlink: {e}"); |
| 883 | } |
| 884 | } |
| 885 | } |
| 886 | std::fs::remove_dir_all(&dir).unwrap(); |
| 887 | } |