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 / src / native_ops.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 | //! Per-operation native accounting for `TensorBackend` (FB-1 cut 3a). |
| 17 | //! |
| 18 | //! A backend that runs only some operations on the device (for example |
| 19 | //! matmuls first, attention last) declares a [`NativeOpMask`]: the set of |
| 20 | //! operations it CLAIMS to run natively. Operations outside the mask run on |
| 21 | //! the reference CPU path by design and never trip strict mode. An operation |
| 22 | //! inside the mask that runs on CPU is a fallback: it is counted, and in a |
| 23 | //! production build it is fatal. Nothing is hidden: [`OpReport`] lists |
| 24 | //! native and reference operations and the per-op counters for every run. |
| 25 | //! |
| 26 | //! Default for every existing backend: all operations native, which is the |
| 27 | //! pre-existing strict semantics. |
| 28 | |
| 29 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 30 | |
| 31 | /// The ten operations of `TensorBackend` (fallback_count is not an op). New ops go last so |
| 32 | /// existing mask bits keep their positions. |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] |
| 34 | #[serde(rename_all = "snake_case")] |
| 35 | pub enum TensorOp { |
| 36 | Rmsnorm, |
| 37 | ApplyRope, |
| 38 | MatmulVec, |
| 39 | MatmulBatch, |
| 40 | Swiglu, |
| 41 | GqaAttention, |
| 42 | PagedAttention, |
| 43 | PagedAttentionBatch, |
| 44 | ComputeLogits, |
| 45 | RmsnormHeads, |
| 46 | } |
| 47 | |
| 48 | impl TensorOp { |
| 49 | pub const COUNT: usize = 10; |
| 50 | pub const ALL: [TensorOp; Self::COUNT] = [ |
| 51 | TensorOp::Rmsnorm, |
| 52 | TensorOp::ApplyRope, |
| 53 | TensorOp::MatmulVec, |
| 54 | TensorOp::MatmulBatch, |
| 55 | TensorOp::Swiglu, |
| 56 | TensorOp::GqaAttention, |
| 57 | TensorOp::PagedAttention, |
| 58 | TensorOp::PagedAttentionBatch, |
| 59 | TensorOp::ComputeLogits, |
| 60 | TensorOp::RmsnormHeads, |
| 61 | ]; |
| 62 | |
| 63 | fn index(self) -> usize { |
| 64 | self as usize |
| 65 | } |
| 66 | |
| 67 | /// Stable name, equal to the trait method name. |
| 68 | pub fn name(self) -> &'static str { |
| 69 | match self { |
| 70 | TensorOp::Rmsnorm => "rmsnorm", |
| 71 | TensorOp::ApplyRope => "apply_rope", |
| 72 | TensorOp::MatmulVec => "matmul_vec", |
| 73 | TensorOp::MatmulBatch => "matmul_batch", |
| 74 | TensorOp::Swiglu => "swiglu", |
| 75 | TensorOp::GqaAttention => "gqa_attention", |
| 76 | TensorOp::PagedAttention => "paged_attention", |
| 77 | TensorOp::PagedAttentionBatch => "paged_attention_batch", |
| 78 | TensorOp::ComputeLogits => "compute_logits", |
| 79 | TensorOp::RmsnormHeads => "rmsnorm_heads", |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// The set of operations a backend claims to run natively on its device. |
| 85 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 86 | pub struct NativeOpMask(u16); |
| 87 | |
| 88 | impl NativeOpMask { |
| 89 | /// Every op claimed native (today's semantics, the trait default). |
| 90 | pub const ALL: NativeOpMask = NativeOpMask((1 << TensorOp::COUNT) - 1); |
| 91 | /// No op claimed native (pure reference backend that wants no strict trips). |
| 92 | pub const NONE: NativeOpMask = NativeOpMask(0); |
| 93 | |
| 94 | pub fn from_ops(ops: &[TensorOp]) -> Self { |
| 95 | ops.iter().fold(Self::NONE, |m, op| m.with(*op)) |
| 96 | } |
| 97 | |
| 98 | pub fn with(self, op: TensorOp) -> Self { |
| 99 | NativeOpMask(self.0 | (1 << op.index())) |
| 100 | } |
| 101 | |
| 102 | pub fn without(self, op: TensorOp) -> Self { |
| 103 | NativeOpMask(self.0 & !(1 << op.index())) |
| 104 | } |
| 105 | |
| 106 | pub fn contains(self, op: TensorOp) -> bool { |
| 107 | self.0 & (1 << op.index()) != 0 |
| 108 | } |
| 109 | |
| 110 | pub fn native_ops(self) -> Vec<TensorOp> { |
| 111 | TensorOp::ALL |
| 112 | .into_iter() |
| 113 | .filter(|op| self.contains(*op)) |
| 114 | .collect() |
| 115 | } |
| 116 | |
| 117 | pub fn reference_ops(self) -> Vec<TensorOp> { |
| 118 | TensorOp::ALL |
| 119 | .into_iter() |
| 120 | .filter(|op| !self.contains(*op)) |
| 121 | .collect() |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | impl Default for NativeOpMask { |
| 126 | fn default() -> Self { |
| 127 | Self::ALL |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /// Per-run record of which ops were native versus reference, with counters. |
| 132 | /// Goes into the strict receipt and the run log so nothing is hidden. |
| 133 | #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 134 | pub struct OpReport { |
| 135 | pub native_ops: Vec<String>, |
| 136 | pub reference_ops: Vec<String>, |
| 137 | /// Fallbacks of ops in the native mask (these trip strict mode), by op name. |
| 138 | pub native_fallbacks: Vec<(String, u64)>, |
| 139 | /// Runs of ops outside the mask on the reference CPU path (by design), by op name. |
| 140 | pub reference_runs: Vec<(String, u64)>, |
| 141 | } |
| 142 | |
| 143 | impl OpReport { |
| 144 | /// The evidence a run keeps (sc#337): `backend`, the summed fallback and |
| 145 | /// reference-run counts, and this report's [`OpReport::line`]. |
| 146 | pub fn evidence(&self, backend: &str) -> aien_abi_core::OpEvidence { |
| 147 | let total = |v: &[(String, u64)]| v.iter().map(|(_, c)| c).sum(); |
| 148 | aien_abi_core::OpEvidence { |
| 149 | backend: backend.to_string(), |
| 150 | native_fallbacks: total(&self.native_fallbacks), |
| 151 | reference_runs: total(&self.reference_runs), |
| 152 | report: self.line(), |
| 153 | gpu_executions: None, |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /// One greppable line: `OP_REPORT native=[..] reference=[..] native_fallbacks=[..] reference_runs=[..]`. |
| 158 | pub fn line(&self) -> String { |
| 159 | let counts = |v: &[(String, u64)]| { |
| 160 | v.iter() |
| 161 | .map(|(n, c)| format!("{n}:{c}")) |
| 162 | .collect::<Vec<_>>() |
| 163 | .join(",") |
| 164 | }; |
| 165 | format!( |
| 166 | "OP_REPORT native=[{}] reference=[{}] native_fallbacks=[{}] reference_runs=[{}]", |
| 167 | self.native_ops.join(","), |
| 168 | self.reference_ops.join(","), |
| 169 | counts(&self.native_fallbacks), |
| 170 | counts(&self.reference_runs), |
| 171 | ) |
| 172 | } |
| 173 | |
| 174 | /// Report for a backend with every op native and no fallbacks (the default). |
| 175 | pub fn all_native() -> Self { |
| 176 | OpAccounting::new(NativeOpMask::ALL).report() |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | /// Counters a backend embeds. The backend calls [`OpAccounting::reference_path`] |
| 181 | /// every time an op runs on the reference CPU path; the mask decides whether |
| 182 | /// that is by design or a fallback. |
| 183 | #[derive(Debug)] |
| 184 | pub struct OpAccounting { |
| 185 | mask: NativeOpMask, |
| 186 | native_fallbacks: [AtomicU64; TensorOp::COUNT], |
| 187 | reference_runs: [AtomicU64; TensorOp::COUNT], |
| 188 | } |
| 189 | |
| 190 | impl OpAccounting { |
| 191 | pub fn new(mask: NativeOpMask) -> Self { |
| 192 | Self { |
| 193 | mask, |
| 194 | native_fallbacks: Default::default(), |
| 195 | reference_runs: Default::default(), |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | pub fn mask(&self) -> NativeOpMask { |
| 200 | self.mask |
| 201 | } |
| 202 | |
| 203 | /// Record that `op` ran on the reference CPU path. Returns true when this |
| 204 | /// was a fallback (the op is claimed native). Does not panic; see |
| 205 | /// [`OpAccounting::reference_path`] for the strict-aware call. |
| 206 | pub fn record_reference(&self, op: TensorOp) -> bool { |
| 207 | if self.mask.contains(op) { |
| 208 | self.native_fallbacks[op.index()].fetch_add(1, Ordering::Relaxed); |
| 209 | true |
| 210 | } else { |
| 211 | self.reference_runs[op.index()].fetch_add(1, Ordering::Relaxed); |
| 212 | false |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// Record a reference-path run and, if the op is claimed native, enter |
| 217 | /// strict mode (fatal in a production build). |
| 218 | pub fn reference_path(&self, backend: &str, op: TensorOp) { |
| 219 | if self.record_reference(op) { |
| 220 | crate::strict::fallback_taken(backend, op.name()); |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | /// What strict mode compares against zero: fallbacks of native-claimed ops only. |
| 225 | pub fn fallback_count(&self) -> u64 { |
| 226 | TensorOp::ALL |
| 227 | .into_iter() |
| 228 | .map(|op| self.native_fallbacks[op.index()].load(Ordering::Relaxed)) |
| 229 | .sum() |
| 230 | } |
| 231 | |
| 232 | pub fn fallbacks_for(&self, op: TensorOp) -> u64 { |
| 233 | self.native_fallbacks[op.index()].load(Ordering::Relaxed) |
| 234 | } |
| 235 | |
| 236 | pub fn reference_runs_for(&self, op: TensorOp) -> u64 { |
| 237 | self.reference_runs[op.index()].load(Ordering::Relaxed) |
| 238 | } |
| 239 | |
| 240 | pub fn report(&self) -> OpReport { |
| 241 | let names = |ops: Vec<TensorOp>| ops.into_iter().map(|o| o.name().to_string()).collect(); |
| 242 | let nonzero = |ctr: &[AtomicU64; TensorOp::COUNT]| { |
| 243 | TensorOp::ALL |
| 244 | .into_iter() |
| 245 | .filter_map(|op| { |
| 246 | let c = ctr[op.index()].load(Ordering::Relaxed); |
| 247 | (c > 0).then(|| (op.name().to_string(), c)) |
| 248 | }) |
| 249 | .collect() |
| 250 | }; |
| 251 | OpReport { |
| 252 | native_ops: names(self.mask.native_ops()), |
| 253 | reference_ops: names(self.mask.reference_ops()), |
| 254 | native_fallbacks: nonzero(&self.native_fallbacks), |
| 255 | reference_runs: nonzero(&self.reference_runs), |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | #[cfg(test)] |
| 261 | mod tests { |
| 262 | use super::*; |
| 263 | |
| 264 | /// sc#337: the evidence a run keeps sums the counters by kind and keeps |
| 265 | /// the full line; a forced fallback (counted without the strict check) |
| 266 | /// shows as a non-zero `native_fallbacks`. |
| 267 | #[test] |
| 268 | fn evidence_sums_the_counters_and_keeps_the_line() { |
| 269 | let acct = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); |
| 270 | assert_eq!(acct.report().evidence("omega-gb10").native_fallbacks, 0); |
| 271 | assert!(acct.record_reference(TensorOp::MatmulVec)); |
| 272 | acct.record_reference(TensorOp::Rmsnorm); |
| 273 | acct.record_reference(TensorOp::Rmsnorm); |
| 274 | acct.record_reference(TensorOp::Swiglu); |
| 275 | let e = acct.report().evidence("omega-gb10"); |
| 276 | assert_eq!(e.backend, "omega-gb10"); |
| 277 | assert_eq!((e.native_fallbacks, e.reference_runs), (1, 3)); |
| 278 | assert_eq!(e.report, acct.report().line()); |
| 279 | assert!( |
| 280 | e.report.contains("native_fallbacks=[matmul_vec:1]"), |
| 281 | "{}", |
| 282 | e.report |
| 283 | ); |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn default_mask_is_all_native() { |
| 288 | let m = NativeOpMask::default(); |
| 289 | assert_eq!(m, NativeOpMask::ALL); |
| 290 | assert!(TensorOp::ALL.iter().all(|op| m.contains(*op))); |
| 291 | assert!(m.reference_ops().is_empty()); |
| 292 | assert_eq!(m.native_ops().len(), TensorOp::COUNT); |
| 293 | } |
| 294 | |
| 295 | #[test] |
| 296 | fn op_bits_are_stable() { |
| 297 | // The nine original ops keep bits 0..8; rmsnorm_heads (Qwen3 q/k norm) is bit 9. |
| 298 | assert_eq!(NativeOpMask::from_ops(&[TensorOp::Rmsnorm]).0, 1 << 0); |
| 299 | assert_eq!(NativeOpMask::from_ops(&[TensorOp::ComputeLogits]).0, 1 << 8); |
| 300 | assert_eq!(NativeOpMask::from_ops(&[TensorOp::RmsnormHeads]).0, 1 << 9); |
| 301 | assert_eq!(TensorOp::RmsnormHeads.name(), "rmsnorm_heads"); |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn mask_with_without_and_lists() { |
| 306 | let m = NativeOpMask::from_ops(&[TensorOp::MatmulVec, TensorOp::MatmulBatch]); |
| 307 | assert!(m.contains(TensorOp::MatmulVec)); |
| 308 | assert!(!m.contains(TensorOp::Rmsnorm)); |
| 309 | assert_eq!(m.native_ops().len(), 2); |
| 310 | assert_eq!(m.reference_ops().len(), TensorOp::COUNT - 2); |
| 311 | let m2 = m.with(TensorOp::ComputeLogits).without(TensorOp::MatmulVec); |
| 312 | assert!(m2.contains(TensorOp::ComputeLogits)); |
| 313 | assert!(!m2.contains(TensorOp::MatmulVec)); |
| 314 | assert_eq!(NativeOpMask::NONE.native_ops().len(), 0); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn op_names_unique_and_match_indices() { |
| 319 | let mut names: Vec<_> = TensorOp::ALL.iter().map(|o| o.name()).collect(); |
| 320 | names.sort(); |
| 321 | names.dedup(); |
| 322 | assert_eq!(names.len(), TensorOp::COUNT); |
| 323 | for (i, op) in TensorOp::ALL.iter().enumerate() { |
| 324 | assert_eq!(op.index(), i); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn reference_op_outside_mask_does_not_count_as_fallback() { |
| 330 | let acct = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); |
| 331 | assert!(!acct.record_reference(TensorOp::Rmsnorm)); |
| 332 | assert!(!acct.record_reference(TensorOp::Rmsnorm)); |
| 333 | assert_eq!(acct.fallback_count(), 0); |
| 334 | assert_eq!(acct.reference_runs_for(TensorOp::Rmsnorm), 2); |
| 335 | // strict-aware call must not panic for a reference-by-design op. |
| 336 | acct.reference_path("T", TensorOp::Swiglu); |
| 337 | assert_eq!(acct.fallback_count(), 0); |
| 338 | } |
| 339 | |
| 340 | /// Negative control: a claimed-native op that runs on CPU is counted |
| 341 | /// and trips strict mode (fatal in a production build). |
| 342 | #[test] |
| 343 | fn claimed_native_op_falling_back_is_counted_and_trips_strict() { |
| 344 | let acct = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); |
| 345 | assert!(acct.record_reference(TensorOp::MatmulVec)); |
| 346 | assert_eq!(acct.fallback_count(), 1); |
| 347 | assert_eq!(acct.fallbacks_for(TensorOp::MatmulVec), 1); |
| 348 | assert_eq!(acct.fallbacks_for(TensorOp::Rmsnorm), 0); |
| 349 | if crate::strict::production_strict() { |
| 350 | let r = std::panic::catch_unwind(|| { |
| 351 | let a = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); |
| 352 | a.reference_path("T", TensorOp::MatmulVec); |
| 353 | }); |
| 354 | let err = r.expect_err("strict mode must panic on claimed-native fallback"); |
| 355 | let msg = err.downcast_ref::<String>().cloned().unwrap_or_default(); |
| 356 | assert!( |
| 357 | msg.contains(crate::strict::STRICT_VIOLATION_PREFIX), |
| 358 | "{msg}" |
| 359 | ); |
| 360 | assert!(msg.contains("matmul_vec"), "{msg}"); |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | #[test] |
| 365 | fn report_lists_native_and_reference_and_counters() { |
| 366 | let acct = OpAccounting::new(NativeOpMask::from_ops(&[ |
| 367 | TensorOp::MatmulVec, |
| 368 | TensorOp::MatmulBatch, |
| 369 | ])); |
| 370 | acct.record_reference(TensorOp::Rmsnorm); |
| 371 | acct.record_reference(TensorOp::MatmulBatch); |
| 372 | let rep = acct.report(); |
| 373 | assert_eq!(rep.native_ops, vec!["matmul_vec", "matmul_batch"]); |
| 374 | assert_eq!(rep.reference_ops.len(), TensorOp::COUNT - 2); |
| 375 | assert_eq!(rep.native_fallbacks, vec![("matmul_batch".to_string(), 1)]); |
| 376 | assert_eq!(rep.reference_runs, vec![("rmsnorm".to_string(), 1)]); |
| 377 | let line = rep.line(); |
| 378 | assert!(line.starts_with("OP_REPORT native=[matmul_vec,matmul_batch]")); |
| 379 | assert!(line.contains("native_fallbacks=[matmul_batch:1]")); |
| 380 | assert!(line.contains("reference_runs=[rmsnorm:1]")); |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn default_report_is_all_native() { |
| 385 | let rep = OpReport::all_native(); |
| 386 | assert_eq!(rep.native_ops.len(), TensorOp::COUNT); |
| 387 | assert!(rep.reference_ops.is_empty()); |
| 388 | assert!(rep.native_fallbacks.is_empty()); |
| 389 | } |
| 390 | } |