From a9da81c021f2f2f37f7c7e6dadd8d4d1d7754549 Mon Sep 17 00:00:00 2001 From: aien Date: Sat, 3 Oct 2026 19:36:05 -0500 Subject: [PATCH] FB-1 cut 3a: per-op native mask for strict mode Adds TensorOp (9 ops), NativeOpMask, OpAccounting and OpReport. Backends declare which ops they claim native; strict mode (panic and receipt fallback_count) fires only for fallbacks of claimed-native ops. Receipt carries a native-vs-reference op report. Trait defaults keep today's semantics (all ops native); existing backends unchanged. Co-Authored-By: Claude Sonnet 5.5 --- crates/aien-inference-abi/receipt.json | 2 +- crates/aien-inference-abi/src/backend.rs | 13 + crates/aien-inference-abi/src/lib.rs | 1 + crates/aien-inference-abi/src/native_ops.rs | 327 ++++++++++++++++++ crates/aien-inference-abi/src/strict.rs | 42 +++ .../tests/strict_real_model.rs | 6 + 6 files changed, 390 insertions(+), 1 deletion(-) create mode 100644 crates/aien-inference-abi/src/native_ops.rs diff --git a/crates/aien-inference-abi/receipt.json b/crates/aien-inference-abi/receipt.json index 5a451400..9b11e2d4 100644 --- a/crates/aien-inference-abi/receipt.json +++ b/crates/aien-inference-abi/receipt.json @@ -8,6 +8,6 @@ "parity_cases": 5, "max_abs_error": 0.0010267794, "max_rel_error": 0.0045229797, - "timestamp": "1790190417", + "timestamp": "1791073695", "status": "CERTIFIED" } \ No newline at end of file diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index ff1a6241..aa8ce8f9 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -90,6 +90,19 @@ pub trait TensorBackend: Send + Sync { 0 } + /// Operations this backend claims to run natively on its device. Strict mode + /// fails only on fallbacks of ops in this mask; ops outside it run on the + /// reference CPU path by design. Default: all ops native (original semantics). + fn native_ops(&self) -> crate::native_ops::NativeOpMask { + crate::native_ops::NativeOpMask::ALL + } + + /// Native-versus-reference listing and per-op counters for receipts. + /// Default: all native, no counters. + fn op_report(&self) -> crate::native_ops::OpReport { + crate::native_ops::OpReport::all_native() + } + /// In-place Root Mean Square Normalization: /// out[i] = x[i] * weight[i] / sqrt(mean(x^2) + eps) fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32); diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 92f0b1db..768c6780 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -14,6 +14,7 @@ pub mod capsule; pub mod checkpoint; pub mod moe_plan; pub mod mojo_backend; +pub mod native_ops; pub mod qwen3_coder; pub mod qwen3_moe; pub mod qwen3_serve; diff --git a/crates/aien-inference-abi/src/native_ops.rs b/crates/aien-inference-abi/src/native_ops.rs new file mode 100644 index 00000000..837246e2 --- /dev/null +++ b/crates/aien-inference-abi/src/native_ops.rs @@ -0,0 +1,327 @@ +//! Per-operation native accounting for `TensorBackend` (FB-1 cut 3a). +//! +//! A backend that runs only some operations on the device (for example +//! matmuls first, attention last) declares a [`NativeOpMask`]: the set of +//! operations it CLAIMS to run natively. Operations outside the mask run on +//! the reference CPU path by design and never trip strict mode. An operation +//! inside the mask that runs on CPU is a fallback: it is counted, and in a +//! production build it is fatal. Nothing is hidden: [`OpReport`] lists +//! native and reference operations and the per-op counters for every run. +//! +//! Default for every existing backend: all operations native, which is the +//! pre-existing strict semantics. + +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The nine operations of `TensorBackend` (fallback_count is not an op). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TensorOp { + Rmsnorm, + ApplyRope, + MatmulVec, + MatmulBatch, + Swiglu, + GqaAttention, + PagedAttention, + PagedAttentionBatch, + ComputeLogits, +} + +impl TensorOp { + pub const COUNT: usize = 9; + pub const ALL: [TensorOp; Self::COUNT] = [ + TensorOp::Rmsnorm, + TensorOp::ApplyRope, + TensorOp::MatmulVec, + TensorOp::MatmulBatch, + TensorOp::Swiglu, + TensorOp::GqaAttention, + TensorOp::PagedAttention, + TensorOp::PagedAttentionBatch, + TensorOp::ComputeLogits, + ]; + + fn index(self) -> usize { + self as usize + } + + /// Stable name, equal to the trait method name. + pub fn name(self) -> &'static str { + match self { + TensorOp::Rmsnorm => "rmsnorm", + TensorOp::ApplyRope => "apply_rope", + TensorOp::MatmulVec => "matmul_vec", + TensorOp::MatmulBatch => "matmul_batch", + TensorOp::Swiglu => "swiglu", + TensorOp::GqaAttention => "gqa_attention", + TensorOp::PagedAttention => "paged_attention", + TensorOp::PagedAttentionBatch => "paged_attention_batch", + TensorOp::ComputeLogits => "compute_logits", + } + } +} + +/// The set of operations a backend claims to run natively on its device. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NativeOpMask(u16); + +impl NativeOpMask { + /// Every op claimed native (today's semantics, the trait default). + pub const ALL: NativeOpMask = NativeOpMask((1 << TensorOp::COUNT) - 1); + /// No op claimed native (pure reference backend that wants no strict trips). + pub const NONE: NativeOpMask = NativeOpMask(0); + + pub fn from_ops(ops: &[TensorOp]) -> Self { + ops.iter().fold(Self::NONE, |m, op| m.with(*op)) + } + + pub fn with(self, op: TensorOp) -> Self { + NativeOpMask(self.0 | (1 << op.index())) + } + + pub fn without(self, op: TensorOp) -> Self { + NativeOpMask(self.0 & !(1 << op.index())) + } + + pub fn contains(self, op: TensorOp) -> bool { + self.0 & (1 << op.index()) != 0 + } + + pub fn native_ops(self) -> Vec { + TensorOp::ALL + .into_iter() + .filter(|op| self.contains(*op)) + .collect() + } + + pub fn reference_ops(self) -> Vec { + TensorOp::ALL + .into_iter() + .filter(|op| !self.contains(*op)) + .collect() + } +} + +impl Default for NativeOpMask { + fn default() -> Self { + Self::ALL + } +} + +/// Per-run record of which ops were native versus reference, with counters. +/// Goes into the strict receipt and the run log so nothing is hidden. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct OpReport { + pub native_ops: Vec, + pub reference_ops: Vec, + /// Fallbacks of ops in the native mask (these trip strict mode), by op name. + pub native_fallbacks: Vec<(String, u64)>, + /// Runs of ops outside the mask on the reference CPU path (by design), by op name. + pub reference_runs: Vec<(String, u64)>, +} + +impl OpReport { + /// One greppable line: `OP_REPORT native=[..] reference=[..] native_fallbacks=[..] reference_runs=[..]`. + pub fn line(&self) -> String { + let counts = |v: &[(String, u64)]| { + v.iter() + .map(|(n, c)| format!("{n}:{c}")) + .collect::>() + .join(",") + }; + format!( + "OP_REPORT native=[{}] reference=[{}] native_fallbacks=[{}] reference_runs=[{}]", + self.native_ops.join(","), + self.reference_ops.join(","), + counts(&self.native_fallbacks), + counts(&self.reference_runs), + ) + } + + /// Report for a backend with every op native and no fallbacks (the default). + pub fn all_native() -> Self { + OpAccounting::new(NativeOpMask::ALL).report() + } +} + +/// Counters a backend embeds. The backend calls [`OpAccounting::reference_path`] +/// every time an op runs on the reference CPU path; the mask decides whether +/// that is by design or a fallback. +#[derive(Debug)] +pub struct OpAccounting { + mask: NativeOpMask, + native_fallbacks: [AtomicU64; TensorOp::COUNT], + reference_runs: [AtomicU64; TensorOp::COUNT], +} + +impl OpAccounting { + pub fn new(mask: NativeOpMask) -> Self { + Self { + mask, + native_fallbacks: Default::default(), + reference_runs: Default::default(), + } + } + + pub fn mask(&self) -> NativeOpMask { + self.mask + } + + /// Record that `op` ran on the reference CPU path. Returns true when this + /// was a fallback (the op is claimed native). Does not panic; see + /// [`OpAccounting::reference_path`] for the strict-aware call. + pub fn record_reference(&self, op: TensorOp) -> bool { + if self.mask.contains(op) { + self.native_fallbacks[op.index()].fetch_add(1, Ordering::Relaxed); + true + } else { + self.reference_runs[op.index()].fetch_add(1, Ordering::Relaxed); + false + } + } + + /// Record a reference-path run and, if the op is claimed native, enter + /// strict mode (fatal in a production build). + pub fn reference_path(&self, backend: &str, op: TensorOp) { + if self.record_reference(op) { + crate::strict::fallback_taken(backend, op.name()); + } + } + + /// What strict mode compares against zero: fallbacks of native-claimed ops only. + pub fn fallback_count(&self) -> u64 { + TensorOp::ALL + .into_iter() + .map(|op| self.native_fallbacks[op.index()].load(Ordering::Relaxed)) + .sum() + } + + pub fn fallbacks_for(&self, op: TensorOp) -> u64 { + self.native_fallbacks[op.index()].load(Ordering::Relaxed) + } + + pub fn reference_runs_for(&self, op: TensorOp) -> u64 { + self.reference_runs[op.index()].load(Ordering::Relaxed) + } + + pub fn report(&self) -> OpReport { + let names = |ops: Vec| ops.into_iter().map(|o| o.name().to_string()).collect(); + let nonzero = |ctr: &[AtomicU64; TensorOp::COUNT]| { + TensorOp::ALL + .into_iter() + .filter_map(|op| { + let c = ctr[op.index()].load(Ordering::Relaxed); + (c > 0).then(|| (op.name().to_string(), c)) + }) + .collect() + }; + OpReport { + native_ops: names(self.mask.native_ops()), + reference_ops: names(self.mask.reference_ops()), + native_fallbacks: nonzero(&self.native_fallbacks), + reference_runs: nonzero(&self.reference_runs), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_mask_is_all_native() { + let m = NativeOpMask::default(); + assert_eq!(m, NativeOpMask::ALL); + assert!(TensorOp::ALL.iter().all(|op| m.contains(*op))); + assert!(m.reference_ops().is_empty()); + assert_eq!(m.native_ops().len(), 9); + } + + #[test] + fn mask_with_without_and_lists() { + let m = NativeOpMask::from_ops(&[TensorOp::MatmulVec, TensorOp::MatmulBatch]); + assert!(m.contains(TensorOp::MatmulVec)); + assert!(!m.contains(TensorOp::Rmsnorm)); + assert_eq!(m.native_ops().len(), 2); + assert_eq!(m.reference_ops().len(), 7); + let m2 = m.with(TensorOp::ComputeLogits).without(TensorOp::MatmulVec); + assert!(m2.contains(TensorOp::ComputeLogits)); + assert!(!m2.contains(TensorOp::MatmulVec)); + assert_eq!(NativeOpMask::NONE.native_ops().len(), 0); + } + + #[test] + fn op_names_unique_and_match_indices() { + let mut names: Vec<_> = TensorOp::ALL.iter().map(|o| o.name()).collect(); + names.sort(); + names.dedup(); + assert_eq!(names.len(), TensorOp::COUNT); + for (i, op) in TensorOp::ALL.iter().enumerate() { + assert_eq!(op.index(), i); + } + } + + #[test] + fn reference_op_outside_mask_does_not_count_as_fallback() { + let acct = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); + assert!(!acct.record_reference(TensorOp::Rmsnorm)); + assert!(!acct.record_reference(TensorOp::Rmsnorm)); + assert_eq!(acct.fallback_count(), 0); + assert_eq!(acct.reference_runs_for(TensorOp::Rmsnorm), 2); + // strict-aware call must not panic for a reference-by-design op. + acct.reference_path("T", TensorOp::Swiglu); + assert_eq!(acct.fallback_count(), 0); + } + + /// Negative control: a claimed-native op that runs on CPU is counted + /// and trips strict mode (fatal in a production build). + #[test] + fn claimed_native_op_falling_back_is_counted_and_trips_strict() { + let acct = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); + assert!(acct.record_reference(TensorOp::MatmulVec)); + assert_eq!(acct.fallback_count(), 1); + assert_eq!(acct.fallbacks_for(TensorOp::MatmulVec), 1); + assert_eq!(acct.fallbacks_for(TensorOp::Rmsnorm), 0); + if crate::strict::production_strict() { + let r = std::panic::catch_unwind(|| { + let a = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); + a.reference_path("T", TensorOp::MatmulVec); + }); + let err = r.expect_err("strict mode must panic on claimed-native fallback"); + let msg = err.downcast_ref::().cloned().unwrap_or_default(); + assert!( + msg.contains(crate::strict::STRICT_VIOLATION_PREFIX), + "{msg}" + ); + assert!(msg.contains("matmul_vec"), "{msg}"); + } + } + + #[test] + fn report_lists_native_and_reference_and_counters() { + let acct = OpAccounting::new(NativeOpMask::from_ops(&[ + TensorOp::MatmulVec, + TensorOp::MatmulBatch, + ])); + acct.record_reference(TensorOp::Rmsnorm); + acct.record_reference(TensorOp::MatmulBatch); + let rep = acct.report(); + assert_eq!(rep.native_ops, vec!["matmul_vec", "matmul_batch"]); + assert_eq!(rep.reference_ops.len(), 7); + assert_eq!(rep.native_fallbacks, vec![("matmul_batch".to_string(), 1)]); + assert_eq!(rep.reference_runs, vec![("rmsnorm".to_string(), 1)]); + let line = rep.line(); + assert!(line.starts_with("OP_REPORT native=[matmul_vec,matmul_batch]")); + assert!(line.contains("native_fallbacks=[matmul_batch:1]")); + assert!(line.contains("reference_runs=[rmsnorm:1]")); + } + + #[test] + fn default_report_is_all_native() { + let rep = OpReport::all_native(); + assert_eq!(rep.native_ops.len(), 9); + assert!(rep.reference_ops.is_empty()); + assert!(rep.native_fallbacks.is_empty()); + } +} diff --git a/crates/aien-inference-abi/src/strict.rs b/crates/aien-inference-abi/src/strict.rs index c77aa99c..b808d5cb 100644 --- a/crates/aien-inference-abi/src/strict.rs +++ b/crates/aien-inference-abi/src/strict.rs @@ -67,6 +67,9 @@ pub struct StrictModelReceipt { pub model_id: String, pub model_config: serde_json::Value, pub fallback_count: u64, + /// Native-versus-reference op listing for the run (None for receipts that predate cut 3a). + #[serde(default)] + pub op_report: Option, pub dev_fallback_build: bool, pub verdict: String, } @@ -99,3 +102,42 @@ impl StrictModelReceipt { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::native_ops::{NativeOpMask, OpAccounting, TensorOp}; + + fn receipt(fallback_count: u64, report: crate::native_ops::OpReport) -> StrictModelReceipt { + StrictModelReceipt { + checkpoint_path: "x".into(), + checkpoint_sha256: "0".repeat(64), + tokenizer_path: "y".into(), + tokenizer_sha256: "0".repeat(64), + backend_identity: "OmegaGb10Backend (sm_121)".into(), + model_id: "m".into(), + model_config: serde_json::json!({}), + fallback_count, + op_report: Some(report), + dev_fallback_build: false, + verdict: String::new(), + } + } + + #[test] + fn reference_ops_by_design_pass_the_receipt_gate() { + let acct = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); + acct.record_reference(TensorOp::Rmsnorm); + let mut r = receipt(acct.fallback_count(), acct.report()); + assert!(r.verify().is_ok(), "{}", r.verdict); + assert!(r.op_report.as_ref().unwrap().line().contains("rmsnorm:1")); + } + + #[test] + fn claimed_native_fallback_fails_the_receipt_gate() { + let acct = OpAccounting::new(NativeOpMask::from_ops(&[TensorOp::MatmulVec])); + acct.record_reference(TensorOp::MatmulVec); + let mut r = receipt(acct.fallback_count(), acct.report()); + assert!(r.verify().is_err()); + } +} diff --git a/crates/aien-inference-runtime/tests/strict_real_model.rs b/crates/aien-inference-runtime/tests/strict_real_model.rs index a243cb3e..22ba8d11 100644 --- a/crates/aien-inference-runtime/tests/strict_real_model.rs +++ b/crates/aien-inference-runtime/tests/strict_real_model.rs @@ -61,6 +61,7 @@ fn receipt_rejects_fallbacks_and_dev_builds() { model_id: "tinyllama".into(), model_config: serde_json::json!({}), fallback_count: 0, + op_report: None, dev_fallback_build: false, verdict: String::new(), }; @@ -115,6 +116,10 @@ fn strict_real_model_gate() { println!("STRICT_GATE output: {out:?}"); let fallback_count = model.transformer.tensor_backend.fallback_count(); + println!( + "STRICT_GATE {}", + model.transformer.tensor_backend.op_report().line() + ); let mut receipt = StrictModelReceipt { checkpoint_path: model_path.display().to_string(), checkpoint_sha256: sha256_file_hex(&model_path), @@ -125,6 +130,7 @@ fn strict_real_model_gate() { model_config: serde_json::to_value(&model.config) .unwrap_or(serde_json::json!({"model_id": model.config.model_id})), fallback_count, + op_report: Some(model.transformer.tensor_backend.op_report()), dev_fallback_build: strict::dev_fallback_active(), verdict: String::new(), };