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 / ops_evidence_test.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 | //! sc#337: "no silent fallback" must be shown by what a run keeps, not by the |
| 17 | //! absence of a crash. The real submission path the daemon uses |
| 18 | //! (`submit_work` -> scheduler -> `NativeTransformerBackend::execute_step`) |
| 19 | //! reports, in `CompletionEvent::Finished`, the tensor backend and its op |
| 20 | //! counters; the generation record and the daemon's `OP_REPORT` log line carry |
| 21 | //! them. CPU reference tensors, micro model, no chip. |
| 22 | use aien_inference_abi::native_ops::{NativeOpMask, OpAccounting, TensorOp}; |
| 23 | use aien_inference_abi::{ |
| 24 | MockInferenceBackend, ModelConfig, NativeTransformerBackend, OpEvidence, ReferenceCpuBackend, |
| 25 | RopeParams, SamplingParams, TensorBackend, TransformerWeights, |
| 26 | }; |
| 27 | use aien_kv_cache::{create_shared_kv_manager, SharedKvManager}; |
| 28 | use aien_runtime::spine::AienRuntimeSpine; |
| 29 | use aien_scheduler::{ChannelCompletionSink, CompletionEvent, PromptHandle, SchedulerConfig}; |
| 30 | use std::sync::Arc; |
| 31 | |
| 32 | fn micro_config() -> ModelConfig { |
| 33 | ModelConfig { |
| 34 | model_id: "aien-micro-v1".to_string(), |
| 35 | max_sequence_length: 512, |
| 36 | block_size: 16, |
| 37 | num_layers: 2, |
| 38 | num_heads: 4, |
| 39 | head_dim: 16, |
| 40 | num_kv_heads: 2, |
| 41 | hidden_dim: 64, |
| 42 | intermediate_dim: 128, |
| 43 | vocab_size: 256, |
| 44 | rms_norm_eps: 1e-5, |
| 45 | rope_theta: 10000.0, |
| 46 | rope_scaling: None, |
| 47 | tie_word_embeddings: false, |
| 48 | eos_token_ids: Vec::new(), |
| 49 | qk_norm: false, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | fn spine() -> (AienRuntimeSpine, SharedKvManager) { |
| 54 | let kv = create_shared_kv_manager(64, 16); |
| 55 | let cfg = SchedulerConfig { |
| 56 | max_batch_size: 16, |
| 57 | max_batch_tokens: 512, |
| 58 | max_prefill_tokens: 256, |
| 59 | prefill_chunk_size: 64, |
| 60 | chunk_prefill: true, |
| 61 | watermark_blocks: 4, |
| 62 | }; |
| 63 | (AienRuntimeSpine::new(64, cfg, kv.clone()), kv) |
| 64 | } |
| 65 | |
| 66 | fn greedy() -> SamplingParams { |
| 67 | SamplingParams { |
| 68 | temperature: 0.0, |
| 69 | top_p: 1.0, |
| 70 | max_tokens: 3, |
| 71 | stop_token_ids: vec![], |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// Runs one request to completion; returns the `Finished` op evidence. |
| 76 | async fn run<B: aien_inference_abi::AienInferenceBackend>( |
| 77 | backend_for: impl FnOnce(SharedKvManager) -> B, |
| 78 | ) -> Option<OpEvidence> { |
| 79 | let (mut spine, kv) = spine(); |
| 80 | let mut backend = backend_for(kv); |
| 81 | let (sink, mut rx) = ChannelCompletionSink::channel(); |
| 82 | let sink_id = spine.register_completion_sink(Arc::new(sink)); |
| 83 | let prompt: PromptHandle = Arc::from([1u32, 10, 25, 42].as_slice()); |
| 84 | spine |
| 85 | .submit_work(prompt, greedy(), 1, Some(sink_id)) |
| 86 | .unwrap(); |
| 87 | spine.run_until_complete(&mut backend, 40).await.unwrap(); |
| 88 | let mut ops = None; |
| 89 | let mut finished = false; |
| 90 | while let Ok(event) = rx.try_recv() { |
| 91 | match event { |
| 92 | CompletionEvent::Finished { ops: o, .. } => { |
| 93 | finished = true; |
| 94 | ops = o; |
| 95 | } |
| 96 | CompletionEvent::Error { message, .. } => panic!("{message}"), |
| 97 | CompletionEvent::Token { .. } => {} |
| 98 | } |
| 99 | } |
| 100 | assert!(finished, "the request must finish"); |
| 101 | ops |
| 102 | } |
| 103 | |
| 104 | fn native_with( |
| 105 | tensors: Arc<dyn TensorBackend>, |
| 106 | ) -> impl FnOnce(SharedKvManager) -> NativeTransformerBackend { |
| 107 | move |kv| { |
| 108 | NativeTransformerBackend::with_shared_kv_and_backend( |
| 109 | TransformerWeights::reference_test_weights(µ_config()), |
| 110 | tensors, |
| 111 | kv, |
| 112 | ) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// The reference CPU math, with every op claimed native and every `rmsnorm` |
| 117 | /// counted as a fallback: what a dev build (`AIEN_DEV_FALLBACK=1`) records |
| 118 | /// when a claimed-native op runs on the CPU. `record_reference` counts |
| 119 | /// without the strict check, so the test runs the same in any build. |
| 120 | struct ForcedFallback { |
| 121 | cpu: ReferenceCpuBackend, |
| 122 | acct: OpAccounting, |
| 123 | /// sc#402: when Some, every `matmul_vec` counts as one chip call, the way the |
| 124 | /// Omega GB10 backend counts `chip_calls`; None is a backend with no chip. |
| 125 | chip_calls: Option<std::sync::atomic::AtomicU64>, |
| 126 | } |
| 127 | |
| 128 | impl TensorBackend for ForcedFallback { |
| 129 | fn name(&self) -> &'static str { |
| 130 | "forced-fallback" |
| 131 | } |
| 132 | fn op_report(&self) -> aien_inference_abi::native_ops::OpReport { |
| 133 | self.acct.report() |
| 134 | } |
| 135 | fn gpu_executions(&self) -> Option<u64> { |
| 136 | self.chip_calls |
| 137 | .as_ref() |
| 138 | .map(|c| c.load(std::sync::atomic::Ordering::Relaxed)) |
| 139 | } |
| 140 | fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { |
| 141 | self.acct.record_reference(TensorOp::Rmsnorm); |
| 142 | self.cpu.rmsnorm(out, x, weight, eps) |
| 143 | } |
| 144 | fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { |
| 145 | self.cpu.rmsnorm_heads(x, weight, head_dim, eps) |
| 146 | } |
| 147 | #[allow(clippy::too_many_arguments)] |
| 148 | fn apply_rope( |
| 149 | &self, |
| 150 | q: &mut [f32], |
| 151 | k: &mut [f32], |
| 152 | pos: usize, |
| 153 | head_dim: usize, |
| 154 | num_q_heads: usize, |
| 155 | num_kv_heads: usize, |
| 156 | rope: &RopeParams, |
| 157 | ) { |
| 158 | self.cpu |
| 159 | .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope) |
| 160 | } |
| 161 | fn matmul_vec( |
| 162 | &self, |
| 163 | out: &mut [f32], |
| 164 | x: &[f32], |
| 165 | weight: &[f32], |
| 166 | out_dim: usize, |
| 167 | in_dim: usize, |
| 168 | ) { |
| 169 | if let Some(c) = &self.chip_calls { |
| 170 | c.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 171 | } |
| 172 | self.cpu.matmul_vec(out, x, weight, out_dim, in_dim) |
| 173 | } |
| 174 | fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { |
| 175 | self.cpu.swiglu(out, gate, up) |
| 176 | } |
| 177 | fn compute_logits( |
| 178 | &self, |
| 179 | logits: &mut [f32], |
| 180 | hidden: &[f32], |
| 181 | embed_weight: &[f32], |
| 182 | vocab_size: usize, |
| 183 | hidden_dim: usize, |
| 184 | ) { |
| 185 | self.cpu |
| 186 | .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim) |
| 187 | } |
| 188 | #[allow(clippy::too_many_arguments)] |
| 189 | fn gqa_attention( |
| 190 | &self, |
| 191 | out: &mut [f32], |
| 192 | q: &[f32], |
| 193 | k_cache: &[f32], |
| 194 | v_cache: &[f32], |
| 195 | seq_len: usize, |
| 196 | num_q_heads: usize, |
| 197 | num_kv_heads: usize, |
| 198 | head_dim: usize, |
| 199 | ) { |
| 200 | self.cpu.gqa_attention( |
| 201 | out, |
| 202 | q, |
| 203 | k_cache, |
| 204 | v_cache, |
| 205 | seq_len, |
| 206 | num_q_heads, |
| 207 | num_kv_heads, |
| 208 | head_dim, |
| 209 | ) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /// A production run on the CPU reference backend: the call reports the |
| 214 | /// backend by name and zero fallbacks. |
| 215 | #[tokio::test] |
| 216 | async fn a_production_run_reports_its_backend_and_zero_fallbacks() { |
| 217 | let ops = run(native_with(Arc::new(ReferenceCpuBackend::new()))) |
| 218 | .await |
| 219 | .expect("the native backend reports its op evidence"); |
| 220 | assert_eq!(ops.backend, "ReferenceCpuBackend"); |
| 221 | assert_eq!(ops.native_fallbacks, 0, "{ops:?}"); |
| 222 | assert!(ops.report.starts_with("OP_REPORT "), "{}", ops.report); |
| 223 | } |
| 224 | |
| 225 | /// A forced fallback shows: a non-zero `native_fallbacks` and the op by name. |
| 226 | #[tokio::test] |
| 227 | async fn a_forced_fallback_shows_a_non_zero_count() { |
| 228 | let tensors = Arc::new(ForcedFallback { |
| 229 | cpu: ReferenceCpuBackend::new(), |
| 230 | acct: OpAccounting::new(NativeOpMask::ALL), |
| 231 | chip_calls: None, |
| 232 | }); |
| 233 | let ops = run(native_with(tensors)) |
| 234 | .await |
| 235 | .expect("the native backend reports its op evidence"); |
| 236 | assert_eq!(ops.backend, "forced-fallback"); |
| 237 | assert!(ops.native_fallbacks > 0, "{ops:?}"); |
| 238 | assert!( |
| 239 | ops.report.contains("native_fallbacks=[rmsnorm:"), |
| 240 | "{}", |
| 241 | ops.report |
| 242 | ); |
| 243 | let line = aien_runtime::generation::op_report_line(Some(&ops)).unwrap(); |
| 244 | assert!( |
| 245 | line.starts_with("OP_REPORT ") && line.ends_with(" backend=forced-fallback"), |
| 246 | "{line}" |
| 247 | ); |
| 248 | } |
| 249 | |
| 250 | /// A backend that does not account its ops makes no claim: None, never zero. |
| 251 | #[tokio::test] |
| 252 | async fn a_backend_without_op_accounting_makes_no_claim() { |
| 253 | assert_eq!(run(|_| MockInferenceBackend::new(1)).await, None); |
| 254 | assert_eq!(aien_runtime::generation::op_report_line(None), None); |
| 255 | } |
| 256 | |
| 257 | /// The record field: present with the backend's evidence, absent without it. |
| 258 | #[test] |
| 259 | fn record_field_matches_the_evidence_and_is_absent_without_it() { |
| 260 | let id = aien_runtime::generation::ModelIdentity { |
| 261 | model_sha256: "m".repeat(64), |
| 262 | model_digest_kind: "file".into(), |
| 263 | model_path: "/m".into(), |
| 264 | tokenizer_sha256: "t".repeat(64), |
| 265 | tokenizer_path: "/t".into(), |
| 266 | }; |
| 267 | let ops = OpEvidence { |
| 268 | backend: "omega-gb10".into(), |
| 269 | native_fallbacks: 0, |
| 270 | reference_runs: 7, |
| 271 | report: "OP_REPORT native=[matmul_vec] reference=[rmsnorm] native_fallbacks=[] reference_runs=[rmsnorm:7]".into(), |
| 272 | gpu_executions: None, |
| 273 | }; |
| 274 | let ev = |o| aien_runtime::generation::TurnEvidence { |
| 275 | prompt_ids: &[1, 2], |
| 276 | output_ids: &[3, 4, 5], |
| 277 | text: "abc", |
| 278 | total_tokens: 5, |
| 279 | finish_reason: "eos", |
| 280 | request_id: 1, |
| 281 | operation_id: 1, |
| 282 | decoding: None, |
| 283 | ops: o, |
| 284 | }; |
| 285 | let start = aien_runtime::generation::DaemonStart(1); |
| 286 | let with = aien_runtime::generation::build_record(&id, &ev(Some(&ops)), start); |
| 287 | assert_eq!( |
| 288 | with["ops"], |
| 289 | serde_json::json!({ |
| 290 | "backend": "omega-gb10", |
| 291 | "native_fallbacks": 0, |
| 292 | "reference_runs": 7, |
| 293 | "scope": "process", |
| 294 | "report": ops.report, |
| 295 | }) |
| 296 | ); |
| 297 | let without = aien_runtime::generation::build_record(&id, &ev(None), start); |
| 298 | assert!(without.get("ops").is_none(), "{without}"); |
| 299 | } |
| 300 | |
| 301 | /// sc#402: a backend that counts chip calls reports them with the call |
| 302 | /// (`gpu_executions`, process total), in the record and in the log line; the |
| 303 | /// CPU reference backend has no chip and makes no claim (None, never zero). |
| 304 | #[tokio::test] |
| 305 | async fn chip_calls_are_reported_and_absent_without_a_chip() { |
| 306 | let tensors = Arc::new(ForcedFallback { |
| 307 | cpu: ReferenceCpuBackend::new(), |
| 308 | acct: OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])), |
| 309 | chip_calls: Some(std::sync::atomic::AtomicU64::new(0)), |
| 310 | }); |
| 311 | let ops = run(native_with(tensors.clone())) |
| 312 | .await |
| 313 | .expect("the native backend reports its op evidence"); |
| 314 | let counted = tensors.gpu_executions().unwrap(); |
| 315 | assert!(counted > 0, "the micro model runs matmul_vec"); |
| 316 | assert_eq!(ops.gpu_executions, Some(counted), "{ops:?}"); |
| 317 | assert_eq!(ops.native_fallbacks, 0, "{ops:?}"); |
| 318 | let line = aien_runtime::generation::op_report_line(Some(&ops)).unwrap(); |
| 319 | assert!( |
| 320 | line.ends_with(&format!( |
| 321 | " backend=forced-fallback gpu_executions={counted}" |
| 322 | )), |
| 323 | "{line}" |
| 324 | ); |
| 325 | let json = serde_json::to_value(&ops).unwrap(); |
| 326 | assert_eq!(json["gpu_executions"], serde_json::json!(counted)); |
| 327 | |
| 328 | let cpu = run(native_with(Arc::new(ReferenceCpuBackend::new()))) |
| 329 | .await |
| 330 | .expect("the native backend reports its op evidence"); |
| 331 | assert_eq!(cpu.gpu_executions, None); |
| 332 | let cpu_json = serde_json::to_value(&cpu).unwrap(); |
| 333 | assert!(cpu_json.get("gpu_executions").is_none(), "{cpu_json}"); |
| 334 | assert!(!aien_runtime::generation::op_report_line(Some(&cpu)) |
| 335 | .unwrap() |
| 336 | .contains("gpu_executions")); |
| 337 | } |
| 338 | |
| 339 | /// sc#402: the record carries `ops.gpu_executions` only when the evidence has it. |
| 340 | #[test] |
| 341 | fn record_carries_gpu_executions_only_when_counted() { |
| 342 | let id = aien_runtime::generation::ModelIdentity { |
| 343 | model_sha256: "m".repeat(64), |
| 344 | model_digest_kind: "file".into(), |
| 345 | model_path: "/m".into(), |
| 346 | tokenizer_sha256: "t".repeat(64), |
| 347 | tokenizer_path: "/t".into(), |
| 348 | }; |
| 349 | let ops = OpEvidence { |
| 350 | backend: "omega-gb10".into(), |
| 351 | native_fallbacks: 0, |
| 352 | reference_runs: 0, |
| 353 | report: "OP_REPORT native=[matmul_vec] reference=[] native_fallbacks=[] reference_runs=[]" |
| 354 | .into(), |
| 355 | gpu_executions: Some(156), |
| 356 | }; |
| 357 | let ev = aien_runtime::generation::TurnEvidence { |
| 358 | prompt_ids: &[1, 2], |
| 359 | output_ids: &[3, 4, 5], |
| 360 | text: "abc", |
| 361 | total_tokens: 5, |
| 362 | finish_reason: "eos", |
| 363 | request_id: 1, |
| 364 | operation_id: 1, |
| 365 | decoding: None, |
| 366 | ops: Some(&ops), |
| 367 | }; |
| 368 | let start = aien_runtime::generation::DaemonStart(1); |
| 369 | let rec = aien_runtime::generation::build_record(&id, &ev, start); |
| 370 | assert_eq!(rec["ops"]["gpu_executions"], serde_json::json!(156)); |
| 371 | assert_eq!(rec["ops"]["scope"], serde_json::json!("process")); |
| 372 | } |
| 373 | |
| 374 | /// sc#384 (2026-10-11): the frozen OPEN-MODEL-QWEN3 v5 row `-OPR` parses the |
| 375 | /// daemon's OP_REPORT line as `... reference_runs=[..] backend=<rest>`. The chip |
| 376 | /// call count (sc#402) must come after `backend=`, or every qualification launch |
| 377 | /// fails that product row (v7 dry attempt 2 did). |
| 378 | #[test] |
| 379 | fn op_report_line_keeps_backend_right_after_reference_runs() { |
| 380 | let ops = aien_abi_core::OpEvidence { |
| 381 | report: "OP_REPORT native=[matmul_vec] reference=[] native_fallbacks=[] reference_runs=[]" |
| 382 | .into(), |
| 383 | backend: "OmegaGb10Backend (native Omega engine)".into(), |
| 384 | gpu_executions: Some(7), |
| 385 | ..Default::default() |
| 386 | }; |
| 387 | let line = aien_runtime::generation::op_report_line(Some(&ops)).unwrap(); |
| 388 | // The v5 regex reads the four bracketed fields and then ` backend=` directly; |
| 389 | // the same check without a regex dependency: the bracketed prefix is intact |
| 390 | // and ` backend=` follows `reference_runs=[]` immediately. |
| 391 | assert!( |
| 392 | line.starts_with( |
| 393 | "OP_REPORT native=[matmul_vec] reference=[] native_fallbacks=[] reference_runs=[] backend=OmegaGb10" |
| 394 | ), |
| 395 | "{line}" |
| 396 | ); |
| 397 | assert!( |
| 398 | !line[..line.find(" backend=").unwrap()].contains("gpu_executions"), |
| 399 | "{line}" |
| 400 | ); |
| 401 | assert!(line.ends_with(" gpu_executions=7"), "{line}"); |
| 402 | } |