interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-runtime / tests / strict_real_model.rs

517 lines · 20394 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! GB10-4: strict real-model execution gate (AIEN 0.1 commissioning).
17//!
18//! Non-ignored tests prove the production build fails closed: no checkpoint
19//! on disk means a refusal, not reference weights. The ignored gate runs the
20//! real TinyLlama checkpoint on the GB10 backend and writes the acceptance
21//! receipt (checkpoint sha256, tokenizer sha256, backend identity, model
22//! config, fallback_count). Run on the Spark:
23//! AIEN_E2E_CHECKPOINT=~/models/TinyLlama-1.1B-Chat-v1.0 \
24//! AIEN_STRICT_RECEIPT=/path/receipt.json \
25//! cargo test -p aien-inference-runtime --release --test strict_real_model -- --ignored --nocapture
26
27mod drift;
28mod oracle;
29
30use aien_inference_abi::backend::TensorBackend;
31use aien_inference_abi::strict::{self, StrictModelReceipt};
32use aien_inference_abi::ExecutionSurface;
33use aien_inference_runtime::model::EmbeddedModel;
34use sha2::{Digest, Sha256};
35use std::path::{Path, PathBuf};
36
37fn sha256_file_hex(path: &Path) -> String {
38 let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
39 let mut h = Sha256::new();
40 h.update(&bytes);
41 format!("{:x}", h.finalize())
42}
43
44#[test]
45fn production_build_is_strict_unless_opted_in() {
46 if std::env::var(strict::DEV_FALLBACK_ENV).is_ok() {
47 eprintln!(
48 "dev fallback opted in by {}; strictness not asserted",
49 strict::DEV_FALLBACK_ENV
50 );
51 return;
52 }
53 assert!(
54 strict::production_strict(),
55 "this build has dev-fallback on; the strict gate must run on a production build"
56 );
57}
58
59#[test]
60fn missing_checkpoint_is_refused_not_faked() {
61 let missing = PathBuf::from("/nonexistent/aien-strict-gate/model.safetensors");
62 let tok = PathBuf::from("/nonexistent/aien-strict-gate/tokenizer.json");
63 let err = EmbeddedModel::load_checkpoint(&missing, &tok, true, true)
64 .err()
65 .expect("a missing checkpoint must be an error");
66 assert!(
67 !err.contains("reference"),
68 "refusal must not route to reference weights: {err}"
69 );
70}
71
72#[test]
73fn receipt_rejects_fallbacks_and_dev_builds() {
74 let mut r = StrictModelReceipt {
75 checkpoint_path: "x".into(),
76 checkpoint_sha256: "0".repeat(64),
77 tokenizer_path: "y".into(),
78 tokenizer_sha256: "0".repeat(64),
79 backend_identity: "OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)"
80 .into(),
81 model_id: "tinyllama".into(),
82 model_config: serde_json::json!({}),
83 fallback_count: 0,
84 op_report: None,
85 dev_fallback_build: false,
86 verdict: String::new(),
87 };
88 assert!(r.verify().is_ok(), "{}", r.verdict);
89 r.fallback_count = 1;
90 assert!(r.verify().is_err());
91 r.fallback_count = 0;
92 r.dev_fallback_build = true;
93 assert!(r.verify().is_err());
94 r.dev_fallback_build = false;
95 r.backend_identity = "ReferenceCpuBackend".into();
96 assert!(r.verify().is_err());
97}
98
99#[test]
100#[ignore = "needs the real checkpoint on the Spark: AIEN_E2E_CHECKPOINT + AIEN_STRICT_RECEIPT"]
101fn strict_real_model_gate() {
102 let ckpt = PathBuf::from(std::env::var("AIEN_E2E_CHECKPOINT").expect("AIEN_E2E_CHECKPOINT"));
103 let receipt_path =
104 PathBuf::from(std::env::var("AIEN_STRICT_RECEIPT").expect("AIEN_STRICT_RECEIPT"));
105 let (model_path, dir) = if ckpt.is_dir() {
106 (ckpt.join("model.safetensors"), ckpt.clone())
107 } else {
108 (
109 ckpt.clone(),
110 ckpt.parent().map(Path::to_path_buf).unwrap_or_default(),
111 )
112 };
113 let tokenizer_path = dir.join("tokenizer.json");
114 assert!(
115 model_path.is_file(),
116 "STRICT: checkpoint {} missing",
117 model_path.display()
118 );
119 assert!(
120 tokenizer_path.is_file(),
121 "STRICT: tokenizer {} missing",
122 tokenizer_path.display()
123 );
124
125 let surface = ExecutionSurface::detect();
126 println!("STRICT_GATE surface: {}", surface.display_name());
127 let mut model = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true)
128 .unwrap_or_else(|e| panic!("STRICT: bind refused: {e}"));
129 let backend_identity = model.transformer.tensor_backend.name().to_string();
130 println!("STRICT_GATE backend: {backend_identity}");
131
132 let prompt = "The DGX Spark is a small computer with a large";
133 let out = model
134 .generate(prompt, 8, 0.0)
135 .unwrap_or_else(|e| panic!("STRICT: generate failed: {e}"));
136 println!("STRICT_GATE output: {out:?}");
137 let fallback_count = model.transformer.tensor_backend.fallback_count();
138
139 println!(
140 "STRICT_GATE {}",
141 model.transformer.tensor_backend.op_report().line()
142 );
143 let mut receipt = StrictModelReceipt {
144 checkpoint_path: model_path.display().to_string(),
145 checkpoint_sha256: sha256_file_hex(&model_path),
146 tokenizer_path: tokenizer_path.display().to_string(),
147 tokenizer_sha256: sha256_file_hex(&tokenizer_path),
148 backend_identity,
149 model_id: model.config.model_id.clone(),
150 model_config: serde_json::to_value(&model.config)
151 .unwrap_or(serde_json::json!({"model_id": model.config.model_id})),
152 fallback_count,
153 op_report: Some(model.transformer.tensor_backend.op_report()),
154 dev_fallback_build: strict::dev_fallback_active(),
155 verdict: String::new(),
156 };
157 let verdict = receipt.verify();
158 std::fs::write(
159 &receipt_path,
160 serde_json::to_string_pretty(&receipt).unwrap(),
161 )
162 .expect("write receipt");
163 println!(
164 "STRICT_GATE verdict: {} (receipt {})",
165 receipt.verdict,
166 receipt_path.display()
167 );
168 assert!(!out.trim().is_empty(), "STRICT: empty output");
169 verdict.unwrap_or_else(|e| panic!("{e}"));
170}
171
172/// FB-1 cut 3b gate: the same greedy generation on the CPU reference backend and on
173/// the Omega backend (the default GPU path), same checkpoint. Records tok/s for
174/// both, checks zero fallbacks and all nine ops native, and judges the backend by teacher-
175/// forced logits (tests/drift): greedy text alone cannot tell a wrong backend from a
176/// near-tie flip (cut 3d: "processing" led "memory" by 0.0005 logits). Text equality is
177/// printed (tokens_match) but no longer asserted.
178/// AIEN_E2E_CHECKPOINT=~/models/TinyLlama-1.1B-Chat-v1.0 AIEN_STRICT_RECEIPT=/path/receipt.json \
179/// cargo test -p aien-inference-runtime --release --test strict_real_model \
180/// omega_vs_reference_real_model -- --ignored --nocapture
181#[test]
182#[ignore = "needs the real checkpoint and the GB10 with a native Omega build; heavy queue only"]
183fn omega_vs_reference_real_model() {
184 let ckpt = PathBuf::from(std::env::var("AIEN_E2E_CHECKPOINT").expect("AIEN_E2E_CHECKPOINT"));
185 let receipt_path =
186 PathBuf::from(std::env::var("AIEN_STRICT_RECEIPT").expect("AIEN_STRICT_RECEIPT"));
187 let (model_path, dir) = if ckpt.is_dir() {
188 (ckpt.join("model.safetensors"), ckpt.clone())
189 } else {
190 (
191 ckpt.clone(),
192 ckpt.parent().map(Path::to_path_buf).unwrap_or_default(),
193 )
194 };
195 let tokenizer_path = dir.join("tokenizer.json");
196 let prompt = "The DGX Spark is a small computer with a large";
197 let max_tokens = 32usize;
198
199 let run = |model: &mut EmbeddedModel| -> (String, usize, f64) {
200 let mut text = String::new();
201 let mut n = 0usize;
202 let t = std::time::Instant::now();
203 model
204 .generate_stream(prompt, max_tokens, 0.0, |piece| {
205 text.push_str(piece);
206 n += 1;
207 true
208 })
209 .unwrap_or_else(|e| panic!("generate failed: {e}"));
210 (text, n, t.elapsed().as_secs_f64())
211 };
212
213 // Reference (CPU) leg.
214 let mut cpu = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, false, true)
215 .unwrap_or_else(|e| panic!("reference load: {e}"));
216 println!(
217 "OMEGA_GATE ref backend: {}",
218 cpu.transformer.tensor_backend.name()
219 );
220 let (cpu_text, cpu_n, cpu_s) = run(&mut cpu);
221 println!(
222 "OMEGA_GATE ref tokens={cpu_n} secs={cpu_s:.3} tok/s={:.3} text={cpu_text:?}",
223 cpu_n as f64 / cpu_s
224 );
225 let ptoks = cpu.tokenizer.encode(prompt).expect("encode");
226 let (ref_logits, ref_toks) =
227 drift::logits_per_step(&mut cpu.transformer, &ptoks, max_tokens, &[]);
228 drop(cpu);
229
230 // Omega leg. No AIEN_GPU_BACKEND switch: since FB-1 cut 6 the GPU path is Omega by default.
231 let mut om = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true)
232 .unwrap_or_else(|e| panic!("STRICT: omega bind refused: {e}"));
233 let backend_identity = om.transformer.tensor_backend.name().to_string();
234 println!("OMEGA_GATE omega backend: {backend_identity}");
235 // Warm-up: first call uploads every weight matrix; reported separately.
236 let t = std::time::Instant::now();
237 let _ = om.generate(prompt, 1, 0.0).expect("omega warm-up");
238 println!(
239 "OMEGA_GATE omega warm-up (weight upload + 1 token) secs={:.3}",
240 t.elapsed().as_secs_f64()
241 );
242 let (om_text, om_n, om_s) = run(&mut om);
243 let (om_logits, _) = drift::logits_per_step(&mut om.transformer, &ptoks, max_tokens, &ref_toks);
244 let cmp = drift::compare(&ref_logits, &om_logits);
245 for c in cmp.iter().filter(|c| c.ref_tok != c.cand_tok) {
246 println!(
247 "OMEGA_GATE flip step={} ref_tok={} omega_tok={} ref_margin={:.4} max_abs_dlogit={:.4}",
248 c.step, c.ref_tok, c.cand_tok, c.ref_margin, c.max_abs_dlogit
249 );
250 }
251 let worst = cmp.iter().map(|c| c.max_abs_dlogit).fold(0.0f32, f32::max);
252 let drift_verdict = drift::judge(&cmp);
253 println!(
254 "OMEGA_GATE teacher_forced steps={} worst_max_abs_dlogit={worst:.4} bound={} judge={drift_verdict:?}",
255 cmp.len(),
256 drift::MAX_ABS_DLOGIT
257 );
258 println!(
259 "OMEGA_GATE omega tokens={om_n} secs={om_s:.3} tok/s={:.3} text={om_text:?}",
260 om_n as f64 / om_s
261 );
262 let report = om.transformer.tensor_backend.op_report();
263 println!("OMEGA_GATE {}", report.line());
264 let fallback_count = om.transformer.tensor_backend.fallback_count();
265 println!("OMEGA_GATE tokens_match={}", cpu_text == om_text);
266 for op in [
267 "matmul_vec",
268 "matmul_batch",
269 "compute_logits",
270 "rmsnorm",
271 "apply_rope",
272 "swiglu",
273 "gqa_attention",
274 "paged_attention",
275 "paged_attention_batch",
276 ] {
277 assert!(
278 report.native_ops.iter().any(|n| n == op),
279 "{op} not in the native mask: {}",
280 report.line()
281 );
282 }
283 assert!(
284 report.native_fallbacks.is_empty(),
285 "native fallbacks: {}",
286 report.line()
287 );
288
289 let mut receipt = StrictModelReceipt {
290 checkpoint_path: model_path.display().to_string(),
291 checkpoint_sha256: sha256_file_hex(&model_path),
292 tokenizer_path: tokenizer_path.display().to_string(),
293 tokenizer_sha256: sha256_file_hex(&tokenizer_path),
294 backend_identity,
295 model_id: om.config.model_id.clone(),
296 model_config: serde_json::to_value(&om.config)
297 .unwrap_or(serde_json::json!({"model_id": om.config.model_id})),
298 fallback_count,
299 op_report: Some(report),
300 dev_fallback_build: strict::dev_fallback_active(),
301 verdict: String::new(),
302 };
303 let verdict = receipt.verify();
304 std::fs::write(
305 &receipt_path,
306 serde_json::to_string_pretty(&receipt).unwrap(),
307 )
308 .expect("write receipt");
309 println!(
310 "OMEGA_GATE verdict: {} (receipt {})",
311 receipt.verdict,
312 receipt_path.display()
313 );
314 if let Err(e) = drift_verdict {
315 panic!("Omega backend logits disagree with the reference: {e}");
316 }
317 verdict.unwrap_or_else(|e| panic!("{e}"));
318}
319
320/// The oracle fixture is self-consistent: its recorded sha256 matches the file, the prompt is
321/// 46 tokens, the greedy decode is 16 tokens and starts with the oracle's argmax. Host test.
322#[test]
323fn oracle_fixture_is_intact() {
324 let o = oracle::load();
325 assert_eq!(
326 sha256_file_hex(&oracle::fixtures_dir().join("tinyllama_oracle.safetensors")),
327 o.safetensors_sha256
328 );
329 assert_eq!(o.prompt_tokens.len(), 46);
330 assert_eq!(o.greedy_tokens.len(), 16);
331 assert_eq!(
332 drift::top2(&o.last_token_logits).0 as u32,
333 o.greedy_tokens[0]
334 );
335}
336
337/// GB10 strict gate against the INDEPENDENT reference (Hugging Face FP32 oracle fixture), not
338/// our own CPU backend. The backend is chosen by the production runtime path
339/// (`EmbeddedModel::load_checkpoint`, use_gpu), then wrapped only to count calls per op.
340/// Judged with the frozen drift rule (`drift::MAX_ABS_DLOGIT`, near-tie flips only):
341/// step 0 compares all 32000 logits with the oracle's; steps 0..15 are teacher-forced with the
342/// oracle's greedy tokens and every argmax must equal the oracle token unless the oracle token
343/// is within 2 * MAX_ABS_DLOGIT of the Omega top logit (the same near-tie bound `drift::judge`
344/// uses). Every op that ran must have run natively (zero fallbacks, zero reference runs).
345/// AIEN_E2E_CHECKPOINT=<TinyLlama dir with model.safetensors + tokenizer.json> \
346/// AIEN_STRICT_RECEIPT=/path/receipt.json cargo test -p aien-inference-runtime --release \
347/// --test strict_real_model omega_vs_hf_oracle -- --ignored --nocapture
348#[test]
349#[ignore = "needs the real checkpoint and the GB10 with a native Omega build; heavy queue only"]
350fn omega_vs_hf_oracle() {
351 use aien_inference_abi::native_ops::TensorOp;
352 use std::sync::Arc;
353
354 let o = oracle::load();
355 let ckpt = PathBuf::from(std::env::var("AIEN_E2E_CHECKPOINT").expect("AIEN_E2E_CHECKPOINT"));
356 let receipt_path =
357 PathBuf::from(std::env::var("AIEN_STRICT_RECEIPT").expect("AIEN_STRICT_RECEIPT"));
358 let model_path = ckpt.join("model.safetensors");
359 let tokenizer_path = ckpt.join("tokenizer.json");
360 let model_sha = sha256_file_hex(&model_path);
361 let tokenizer_sha = sha256_file_hex(&tokenizer_path);
362 println!(
363 "ORACLE_GATE checkpoint {} sha256={model_sha}",
364 model_path.display()
365 );
366 println!(
367 "ORACLE_GATE tokenizer {} sha256={tokenizer_sha}",
368 tokenizer_path.display()
369 );
370 assert_eq!(
371 model_sha, o.model_sha256,
372 "checkpoint is not the oracle's model"
373 );
374 assert_eq!(
375 tokenizer_sha, o.tokenizer_sha256,
376 "tokenizer is not the oracle's"
377 );
378
379 let mut model = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true)
380 .unwrap_or_else(|e| panic!("STRICT: omega bind refused: {e}"));
381 let backend_identity = model.transformer.tensor_backend.name().to_string();
382 println!("ORACLE_GATE backend: {backend_identity}");
383 println!(
384 "ORACLE_GATE dev_fallback_active={}",
385 strict::dev_fallback_active()
386 );
387 let counting = Arc::new(oracle::CountingBackend::new(
388 model.transformer.tensor_backend.clone(),
389 ));
390 model.transformer.tensor_backend = counting.clone();
391
392 let steps = o.greedy_tokens.len();
393 let (logits, fed) = drift::logits_per_step(
394 &mut model.transformer,
395 &o.prompt_tokens,
396 steps,
397 &o.greedy_tokens,
398 );
399 assert_eq!(fed, o.greedy_tokens);
400 assert_eq!(logits.len(), steps);
401
402 // Step 0: the full logit vector against the oracle.
403 let cmp0 = drift::compare(std::slice::from_ref(&o.last_token_logits), &logits[..1]);
404 println!(
405 "ORACLE_GATE step0 max_abs_dlogit={:.4} oracle_tok={} omega_tok={} oracle_margin={:.4} bound={}",
406 cmp0[0].max_abs_dlogit,
407 cmp0[0].ref_tok,
408 cmp0[0].cand_tok,
409 cmp0[0].ref_margin,
410 drift::MAX_ABS_DLOGIT
411 );
412 let step0 = drift::judge(&cmp0);
413
414 // Steps 0..15: argmax against the oracle's greedy tokens, near-tie rule from the frozen bound.
415 let mut bad = Vec::new();
416 let mut flips = 0usize;
417 for (s, (l, &want)) in logits.iter().zip(&o.greedy_tokens).enumerate() {
418 let (top, top_v, _, _) = drift::top2(l);
419 let gap = top_v - l[want as usize];
420 if top as u32 != want {
421 println!("ORACLE_GATE flip step={s} oracle_tok={want} omega_tok={top} gap={gap:.4}");
422 if gap.is_nan() || gap > 2.0 * drift::MAX_ABS_DLOGIT {
423 bad.push(format!("step {s}: omega {top} vs oracle {want}, gap {gap}"));
424 }
425 flips += 1;
426 }
427 }
428 let text = model.tokenizer.decode(&fed).unwrap_or_default();
429 println!(
430 "ORACLE_GATE teacher_forced steps={steps} flips={flips} oracle_text={:?} fed_text={text:?}",
431 o.greedy_text
432 );
433
434 // Per-op accounting: every op that ran ran natively. "native" below is calls minus the
435 // backend's counted fallbacks and reference runs, so it only means native on a backend that
436 // counts them (OmegaGb10Backend); a CPU backend reports none and is refused by the receipt.
437 let native_engine = backend_identity.contains("native Omega engine");
438 println!(
439 "ORACLE_GATE {} native_engine={native_engine}",
440 counting.line()
441 );
442 let report = counting.op_report();
443 println!("ORACLE_GATE {}", report.line());
444 let mut op_problems = Vec::new();
445 if !native_engine {
446 op_problems.push(format!(
447 "backend is not the native Omega engine: {backend_identity}"
448 ));
449 }
450 for (op, calls, native) in counting.native_calls() {
451 if calls != native {
452 op_problems.push(format!("{}: {calls} calls, {native} native", op.name()));
453 }
454 }
455 if !report.native_fallbacks.is_empty() || !report.reference_runs.is_empty() {
456 op_problems.push(report.line());
457 }
458 for op in [
459 TensorOp::Rmsnorm,
460 TensorOp::ApplyRope,
461 TensorOp::Swiglu,
462 TensorOp::ComputeLogits,
463 ] {
464 if counting.calls(op) == 0 {
465 op_problems.push(format!("{} never ran", op.name()));
466 }
467 }
468 if counting.calls(TensorOp::MatmulVec) + counting.calls(TensorOp::MatmulBatch) == 0 {
469 op_problems.push("no matmul ran".into());
470 }
471 if counting.calls(TensorOp::GqaAttention)
472 + counting.calls(TensorOp::PagedAttention)
473 + counting.calls(TensorOp::PagedAttentionBatch)
474 == 0
475 {
476 op_problems.push("no attention ran".into());
477 }
478
479 let mut receipt = StrictModelReceipt {
480 checkpoint_path: model_path.display().to_string(),
481 checkpoint_sha256: model_sha,
482 tokenizer_path: tokenizer_path.display().to_string(),
483 tokenizer_sha256: tokenizer_sha,
484 backend_identity,
485 model_id: model.config.model_id.clone(),
486 model_config: serde_json::to_value(&model.config)
487 .unwrap_or(serde_json::json!({"model_id": model.config.model_id})),
488 fallback_count: counting.fallback_count(),
489 op_report: Some(report),
490 dev_fallback_build: strict::dev_fallback_active(),
491 verdict: String::new(),
492 };
493 let verdict = receipt.verify();
494 std::fs::write(
495 &receipt_path,
496 serde_json::to_string_pretty(&receipt).unwrap(),
497 )
498 .expect("write receipt");
499 println!(
500 "ORACLE_GATE receipt verdict: {} (receipt {})",
501 receipt.verdict,
502 receipt_path.display()
503 );
504 if let Err(e) = step0 {
505 panic!("Omega step-0 logits disagree with the HF oracle: {e}");
506 }
507 assert!(
508 bad.is_empty(),
509 "argmax disagreements beyond the near-tie bound: {bad:?}"
510 );
511 assert!(
512 op_problems.is_empty(),
513 "per-op native accounting: {op_problems:?}"
514 );
515 verdict.unwrap_or_else(|e| panic!("{e}"));
516 println!("ORACLE_GATE verdict: PASS");
517}