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 / oracle / mod.rs

305 lines · 10016 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//! Independent reference and per-op native accounting for the GB10 strict gate.
17//!
18//! The independent reference is the Hugging Face FP32 oracle fixture checked into
19//! `aien-inference-abi/fixtures` (tinyllama_oracle_manifest.json + tinyllama_oracle.safetensors):
20//! TinyLlama-1.1B-Chat-v1.0 logits for a 46-token prompt and its 16-step greedy decode,
21//! produced outside this codebase. The CPU reference backend is our own code, so comparing
22//! Omega only against it cannot catch a bug both share.
23//!
24//! [`CountingBackend`] wraps the backend the production path selected and counts calls per
25//! op, so a receipt can show every op that ran and that none of them fell back.
26#![allow(dead_code)]
27use aien_inference_abi::backend::TensorBackend;
28use aien_inference_abi::native_ops::{NativeOpMask, OpReport, TensorOp};
29use std::path::{Path, PathBuf};
30use std::sync::atomic::{AtomicU64, Ordering};
31use std::sync::Arc;
32
33pub fn fixtures_dir() -> PathBuf {
34 Path::new(env!("CARGO_MANIFEST_DIR")).join("../aien-inference-abi/fixtures")
35}
36
37pub struct Oracle {
38 pub model_sha256: String,
39 pub tokenizer_sha256: String,
40 pub safetensors_sha256: String,
41 pub prompt_text: String,
42 pub prompt_tokens: Vec<u32>,
43 pub greedy_tokens: Vec<u32>,
44 pub greedy_text: String,
45 /// Oracle logits for the token after the prompt (32000 values).
46 pub last_token_logits: Vec<f32>,
47}
48
49fn str_field(v: &serde_json::Value, k: &str) -> String {
50 v[k].as_str()
51 .unwrap_or_else(|| panic!("oracle manifest: missing {k}"))
52 .to_string()
53}
54
55fn u32_list(v: &serde_json::Value) -> Vec<u32> {
56 v.as_array()
57 .expect("oracle manifest: expected an array")
58 .iter()
59 .map(|t| t.as_u64().expect("oracle manifest: token id") as u32)
60 .collect()
61}
62
63/// One f32 tensor from a safetensors file (header JSON, then raw little-endian data).
64fn read_f32_tensor(path: &Path, name: &str) -> Vec<f32> {
65 let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
66 let hlen = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize;
67 let header: serde_json::Value =
68 serde_json::from_slice(&bytes[8..8 + hlen]).expect("oracle safetensors header");
69 let t = &header[name];
70 assert_eq!(t["dtype"].as_str(), Some("F32"), "{name} dtype: {t}");
71 let off = t["data_offsets"].as_array().expect("data_offsets");
72 let (a, b) = (
73 off[0].as_u64().unwrap() as usize,
74 off[1].as_u64().unwrap() as usize,
75 );
76 let (words, rest) = bytes[8 + hlen + a..8 + hlen + b].as_chunks::<4>();
77 assert!(rest.is_empty(), "{name}: byte length not a multiple of 4");
78 words.iter().map(|w| f32::from_le_bytes(*w)).collect()
79}
80
81pub fn load() -> Oracle {
82 let dir = fixtures_dir();
83 let manifest: serde_json::Value = serde_json::from_slice(
84 &std::fs::read(dir.join("tinyllama_oracle_manifest.json")).expect("oracle manifest"),
85 )
86 .expect("oracle manifest JSON");
87 let st = dir.join(str_field(&manifest, "safetensors_file"));
88 let last_token_logits = read_f32_tensor(&st, "last_token_logits");
89 assert_eq!(last_token_logits.len(), 32000, "oracle last_token_logits");
90 Oracle {
91 model_sha256: str_field(&manifest, "model_sha256"),
92 tokenizer_sha256: str_field(&manifest, "tokenizer_sha256"),
93 safetensors_sha256: str_field(&manifest, "safetensors_sha256"),
94 prompt_text: str_field(&manifest, "prompt_text"),
95 prompt_tokens: u32_list(&manifest["prompt_tokens"]),
96 greedy_tokens: u32_list(&manifest["decoded_16_steps"]["token_ids"]),
97 greedy_text: str_field(&manifest["decoded_16_steps"], "text"),
98 last_token_logits,
99 }
100}
101
102/// Delegates every op to the backend the production path chose and counts calls per op.
103pub struct CountingBackend {
104 inner: Arc<dyn TensorBackend>,
105 calls: [AtomicU64; TensorOp::COUNT],
106}
107
108impl CountingBackend {
109 pub fn new(inner: Arc<dyn TensorBackend>) -> Self {
110 Self {
111 inner,
112 calls: Default::default(),
113 }
114 }
115
116 fn hit(&self, op: TensorOp) {
117 self.calls[TensorOp::ALL.iter().position(|o| *o == op).unwrap()]
118 .fetch_add(1, Ordering::Relaxed);
119 }
120
121 pub fn calls(&self, op: TensorOp) -> u64 {
122 self.calls[TensorOp::ALL.iter().position(|o| *o == op).unwrap()].load(Ordering::Relaxed)
123 }
124
125 /// Calls per op minus reference runs and fallbacks of that op: the native executions.
126 pub fn native_calls(&self) -> Vec<(TensorOp, u64, u64)> {
127 let rep = self.inner.op_report();
128 let count = |v: &[(String, u64)], op: TensorOp| {
129 v.iter()
130 .find(|(n, _)| n == op.name())
131 .map_or(0, |(_, c)| *c)
132 };
133 TensorOp::ALL
134 .into_iter()
135 .map(|op| {
136 let off = count(&rep.native_fallbacks, op) + count(&rep.reference_runs, op);
137 (op, self.calls(op), self.calls(op).saturating_sub(off))
138 })
139 .collect()
140 }
141
142 /// `NATIVE_CALLS op:calls/native,...` for the run log.
143 pub fn line(&self) -> String {
144 let parts: Vec<String> = self
145 .native_calls()
146 .into_iter()
147 .map(|(op, c, n)| format!("{}:{c}/{n}", op.name()))
148 .collect();
149 format!("NATIVE_CALLS {}", parts.join(","))
150 }
151}
152
153impl TensorBackend for CountingBackend {
154 fn name(&self) -> &'static str {
155 self.inner.name()
156 }
157 fn fallback_count(&self) -> u64 {
158 self.inner.fallback_count()
159 }
160 fn native_ops(&self) -> NativeOpMask {
161 self.inner.native_ops()
162 }
163 fn op_report(&self) -> OpReport {
164 self.inner.op_report()
165 }
166 fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) {
167 self.hit(TensorOp::Rmsnorm);
168 self.inner.rmsnorm(out, x, weight, eps)
169 }
170 fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) {
171 self.hit(TensorOp::RmsnormHeads);
172 self.inner.rmsnorm_heads(x, weight, head_dim, eps)
173 }
174 fn apply_rope(
175 &self,
176 q: &mut [f32],
177 k: &mut [f32],
178 pos: usize,
179 head_dim: usize,
180 num_q_heads: usize,
181 num_kv_heads: usize,
182 rope: &aien_inference_abi::RopeParams,
183 ) {
184 self.hit(TensorOp::ApplyRope);
185 self.inner
186 .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope)
187 }
188 fn matmul_vec(
189 &self,
190 out: &mut [f32],
191 x: &[f32],
192 weight: &[f32],
193 out_dim: usize,
194 in_dim: usize,
195 ) {
196 self.hit(TensorOp::MatmulVec);
197 self.inner.matmul_vec(out, x, weight, out_dim, in_dim)
198 }
199 fn matmul_batch(
200 &self,
201 out: &mut [f32],
202 x: &[f32],
203 weight: &[f32],
204 batch_size: usize,
205 in_dim: usize,
206 out_dim: usize,
207 ) {
208 self.hit(TensorOp::MatmulBatch);
209 self.inner
210 .matmul_batch(out, x, weight, batch_size, in_dim, out_dim)
211 }
212 fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) {
213 self.hit(TensorOp::Swiglu);
214 self.inner.swiglu(out, gate, up)
215 }
216 fn gqa_attention(
217 &self,
218 out: &mut [f32],
219 q: &[f32],
220 k_cache: &[f32],
221 v_cache: &[f32],
222 seq_len: usize,
223 num_q_heads: usize,
224 num_kv_heads: usize,
225 head_dim: usize,
226 ) {
227 self.hit(TensorOp::GqaAttention);
228 self.inner.gqa_attention(
229 out,
230 q,
231 k_cache,
232 v_cache,
233 seq_len,
234 num_q_heads,
235 num_kv_heads,
236 head_dim,
237 )
238 }
239 fn paged_attention(
240 &self,
241 out: &mut [f32],
242 q: &[f32],
243 pool: &aien_kv_cache::UnifiedKvTensorPool,
244 block_ids: &[usize],
245 context_len: usize,
246 layer_idx: usize,
247 num_q_heads: usize,
248 num_kv_heads: usize,
249 head_dim: usize,
250 ) {
251 self.hit(TensorOp::PagedAttention);
252 self.inner.paged_attention(
253 out,
254 q,
255 pool,
256 block_ids,
257 context_len,
258 layer_idx,
259 num_q_heads,
260 num_kv_heads,
261 head_dim,
262 )
263 }
264 fn paged_attention_batch(
265 &self,
266 out: &mut [f32],
267 q: &[f32],
268 pool: &aien_kv_cache::UnifiedKvTensorPool,
269 block_tables: &[i32],
270 context_lens: &[i32],
271 max_blocks_per_seq: usize,
272 num_seqs: usize,
273 layer_idx: usize,
274 num_q_heads: usize,
275 num_kv_heads: usize,
276 head_dim: usize,
277 ) {
278 self.hit(TensorOp::PagedAttentionBatch);
279 self.inner.paged_attention_batch(
280 out,
281 q,
282 pool,
283 block_tables,
284 context_lens,
285 max_blocks_per_seq,
286 num_seqs,
287 layer_idx,
288 num_q_heads,
289 num_kv_heads,
290 head_dim,
291 )
292 }
293 fn compute_logits(
294 &self,
295 logits: &mut [f32],
296 hidden: &[f32],
297 embed_weight: &[f32],
298 vocab_size: usize,
299 hidden_dim: usize,
300 ) {
301 self.hit(TensorOp::ComputeLogits);
302 self.inner
303 .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim)
304 }
305}