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
GitHub aien-dev/aien-sovereign-core-mv#183 (code only)
Apply it
git checkout -b patch-c4d7a9d091314d84 8b5caedcba164997bc49a35993282a099a80e452 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/c4d7a9d091314d84.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
183
3ed1f36d5dcb41136a1551b2b59c7c12966f3fb8
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":183,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/183","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:13Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Cargo.lock b/Cargo.lock index cb100b27..de02aa82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -106,6 +106,7 @@ version = "0.1.0" dependencies = [ "aien-abi-core", "aien-kv-cache", + "aien-omega-gpu", "aien-platform", "async-trait", "libloading 0.8.9", diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 4eb12e09..3f61b3dd 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1306,6 +1306,25 @@ fn build_native_daemon_backend() -> Result<DaemonBackendParts, String> { label: model_label, .. } = load_daemon_model(manifest, policy.require_checkpoint)?; + if aien_inference_abi::omega_backend_selected() { + let omega = aien_inference_abi::OmegaGb10Backend::new(); + if omega.is_available() { + let name = aien_inference_abi::TensorBackend::name(&omega).to_string(); + let tensor_backend: std::sync::Arc<dyn aien_inference_abi::TensorBackend> = + std::sync::Arc::new(omega); + return Ok(( + weights, + tensor_backend, + format!("NativeTransformerBackend/{name}"), + model_label, + tokenizer, + )); + } + return Err( + "AIEN_GPU_BACKEND=omega is set but the Omega GPU engine is not linked (stub build)" + .to_string(), + ); + } let probe = aien_inference_abi::BlackwellGb10Backend::new(); let require_blackwell = std::env::var("AIEN_REQUIRE_BLACKWELL") .map(|v| v.trim() == "1" || v.trim().eq_ignore_ascii_case("true")) diff --git a/crates/aien-inference-abi/Cargo.toml b/crates/aien-inference-abi/Cargo.toml index e327df1a..f2ba94ac 100644 --- a/crates/aien-inference-abi/Cargo.toml +++ b/crates/aien-inference-abi/Cargo.toml @@ -18,6 +18,7 @@ rayon = "1.10" aien-abi-core = { path = "../aien-abi-core" } aien-kv-cache = { path = "../aien-kv-cache" } aien-platform = { path = "../aien-platform" } +aien-omega-gpu = { path = "../aien-omega-gpu" } parking_lot = "0.12" sha2 = "0.10" diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 768c6780..15234b62 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -15,6 +15,7 @@ pub mod checkpoint; pub mod moe_plan; pub mod mojo_backend; pub mod native_ops; +pub mod omega_backend; pub mod qwen3_coder; pub mod qwen3_moe; pub mod qwen3_serve; @@ -38,6 +39,7 @@ pub use capsule::*; pub use checkpoint::*; pub use moe_plan::*; pub use mojo_backend::*; +pub use omega_backend::{omega_backend_selected, OmegaGb10Backend, GPU_BACKEND_ENV}; pub use qwen3_coder::*; pub use qwen3_moe::*; pub use qwen3_serve::*; diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs new file mode 100644 index 00000000..6c5f509c --- /dev/null +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -0,0 +1,472 @@ +//! `OmegaGb10Backend` (FB-1 cut 3b): the three matrix-multiply ops of +//! `TensorBackend` run on our own native GPU engine (`libomega_gpu.a`, no CUDA) +//! through the `aien-omega-gpu` crate; every other op runs on the reference CPU +//! path by design and is counted by `OpAccounting`. +//! +//! Native mask: `matmul_vec`, `matmul_batch`, `compute_logits`. A chip error in +//! one of those is a fallback of a claimed-native op: it is counted, goes through +//! `OpAccounting::reference_path` (fatal in a production build, see `strict.rs`) +//! and, in a dev build only, the reference result is computed so the run goes on. +//! +//! Weights: the trait hands weights as `&[f32]` slices per call (row-major +//! `[out_dim, in_dim]`, computing `x * W^T`). The first call for a slice uploads +//! `W^T` (k = in_dim, n = out_dim, rounded to bf16 by omega) once and keeps it +//! resident; later calls move only activations. The cache key is +//! (pointer, length, in_dim, out_dim) plus a sampled content fingerprint. +//! +//! INVARIANT: weight slices are immutable and outlive the backend's use of them. +//! Checked for the model path: `TransformerWeights` (weights.rs:35) owns plain +//! `Vec<f32>` fields; the forward passes borrow it as `&TransformerWeights` +//! (transformer_backend.rs:287, :399) and nothing in the crate mutates a loaded +//! checkpoint after construction (UNVERIFIED for external callers: `weights` is a +//! `pub` field, so a caller that mutates it in place gets stale device weights; +//! the fingerprint catches a freed-and-reused address or a changed sample point, +//! not every in-place edit). Use one backend per weight set, or call +//! [`OmegaGb10Backend::clear_resident`] after changing weights. +use crate::backend::{ReferenceCpuBackend, TensorBackend}; +use crate::native_ops::{NativeOpMask, OpAccounting, OpReport, TensorOp}; +use aien_omega_gpu::ResidentTensor; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +/// Opt-in selection: `AIEN_GPU_BACKEND=omega` binds this backend instead of the +/// default CUDA `BlackwellGb10Backend`. Unset (or any other value) keeps the default. +pub const GPU_BACKEND_ENV: &str = "AIEN_GPU_BACKEND"; + +/// True when the environment asks for the Omega backend. +pub fn omega_backend_selected() -> bool { + std::env::var(GPU_BACKEND_ENV) + .map(|v| v.trim().eq_ignore_ascii_case("omega")) + .unwrap_or(false) +} + +const BACKEND_NAME: &str = "OmegaGb10Backend"; + +type Key = (usize, usize, usize, usize); + +struct Resident { + fingerprint: u64, + tensor: ResidentTensor, +} + +/// Native-matmul backend on the Omega GPU engine. +pub struct OmegaGb10Backend { + reference: ReferenceCpuBackend, + acct: OpAccounting, + /// One lock serializes every chip call and guards the resident cache + /// (omega's resident-call thread safety is not documented). + chip: Mutex<HashMap<Key, Resident>>, + chip_errors: AtomicU64, + chip_calls: AtomicU64, + chip_ns: AtomicU64, + last_error: Mutex<String>, +} + +impl Default for OmegaGb10Backend { + fn default() -> Self { + Self::new() + } +} + +/// Cheap content check: FNV-1a over up to 64 evenly spaced elements plus the last one. +fn fingerprint(w: &[f32]) -> u64 { + let mut h: u64 = 0xcbf29ce484222325; + let step = (w.len() / 64).max(1); + let mut i = 0; + while i < w.len() { + h = (h ^ w[i].to_bits() as u64).wrapping_mul(0x100000001b3); + i += step; + } + if let Some(last) = w.last() { + h = (h ^ last.to_bits() as u64).wrapping_mul(0x100000001b3); + } + h +} + +impl OmegaGb10Backend { + pub fn new() -> Self { + Self { + reference: ReferenceCpuBackend::new(), + acct: OpAccounting::new(NativeOpMask::from_ops(&[ + TensorOp::MatmulVec, + TensorOp::MatmulBatch, + TensorOp::ComputeLogits, + ])), + chip: Mutex::new(HashMap::new()), + chip_errors: AtomicU64::new(0), + chip_calls: AtomicU64::new(0), + chip_ns: AtomicU64::new(0), + last_error: Mutex::new(String::new()), + } + } + + /// True when the real native library is linked (not the CI stub). + pub fn is_available(&self) -> bool { + aien_omega_gpu::is_native() + } + + pub fn chip_calls(&self) -> u64 { + self.chip_calls.load(Ordering::Relaxed) + } + + pub fn chip_errors(&self) -> u64 { + self.chip_errors.load(Ordering::Relaxed) + } + + /// Sum of chip launch-to-completion time reported by omega, in nanoseconds. + pub fn chip_ns(&self) -> u64 { + self.chip_ns.load(Ordering::Relaxed) + } + + pub fn last_error(&self) -> String { + self.last_error + .lock() + .map(|s| s.clone()) + .unwrap_or_default() + } + + /// Drop every resident weight (call after changing weights in place). + pub fn clear_resident(&self) { + if let Ok(mut c) = self.chip.lock() { + c.clear(); + } + } + + /// Number of resident weight matrices (for tests and receipts). + pub fn resident_count(&self) -> usize { + self.chip.lock().map(|c| c.len()).unwrap_or(0) + } + + /// `out[m x out_dim] = x[m x in_dim] * W^T`, W row-major `[out_dim, in_dim]`. + /// Returns false on any chip error (already recorded). + fn chip_matmul( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + m: usize, + in_dim: usize, + out_dim: usize, + ) -> bool { + if x.len() != m * in_dim || out.len() != m * out_dim || weight.len() != out_dim * in_dim { + return self.fail(format!( + "shape mismatch: x={} out={} w={} for m={m} in={in_dim} out_dim={out_dim}", + x.len(), + out.len(), + weight.len() + )); + } + let key: Key = (weight.as_ptr() as usize, weight.len(), in_dim, out_dim); + let fp = fingerprint(weight); + let mut cache = match self.chip.lock() { + Ok(g) => g, + Err(_) => return self.fail("chip lock poisoned".into()), + }; + if cache.get(&key).is_some_and(|r| r.fingerprint != fp) { + cache.remove(&key); + } + if let std::collections::hash_map::Entry::Vacant(slot) = cache.entry(key) { + // W is [out, in]; the engine wants B = W^T as [k = in, n = out]. + let mut wt = vec![0.0f32; weight.len()]; + for o in 0..out_dim { + let row = &weight[o * in_dim..(o + 1) * in_dim]; + for (i, v) in row.iter().enumerate() { + wt[i * out_dim + o] = *v; + } + } + match ResidentTensor::upload_f32(in_dim, out_dim, &wt) { + Ok(tensor) => { + slot.insert(Resident { + fingerprint: fp, + tensor, + }); + } + Err(e) => { + let msg = format!("upload {in_dim}x{out_dim}: {e}"); + return self.fail(msg); + } + } + } + let res = &cache[&key]; + match res.tensor.matmul_f32(m, x, out) { + Ok(info) => { + self.chip_calls.fetch_add(1, Ordering::Relaxed); + self.chip_ns + .fetch_add(info.raw.elapsed_ns, Ordering::Relaxed); + true + } + Err(e) => { + drop(cache); + self.fail(format!("matmul m={m} k={in_dim} n={out_dim}: {e}")) + } + } + } + + fn fail(&self, msg: String) -> bool { + self.chip_errors.fetch_add(1, Ordering::Relaxed); + let stage = aien_omega_gpu::last_error(); + let full = if stage.is_empty() { + msg + } else { + format!("{msg} (stage: {stage})") + }; + if let Ok(mut l) = self.last_error.lock() { + *l = full; + } + false + } + + fn reference_for(&self, op: TensorOp) { + self.acct.reference_path(BACKEND_NAME, op); + } +} + +impl TensorBackend for OmegaGb10Backend { + fn name(&self) -> &'static str { + if self.is_available() { + "OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + } else { + "OmegaGb10Backend (stub, no chip)" + } + } + + fn fallback_count(&self) -> u64 { + self.acct.fallback_count() + } + + fn native_ops(&self) -> NativeOpMask { + self.acct.mask() + } + + fn op_report(&self) -> OpReport { + self.acct.report() + } + + fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { + self.reference_for(TensorOp::Rmsnorm); + self.reference.rmsnorm(out, x, weight, eps); + } + + fn apply_rope( + &self, + q: &mut [f32], + k: &mut [f32], + pos: usize, + head_dim: usize, + num_q_heads: usize, + num_kv_heads: usize, + theta: f32, + ) { + self.reference_for(TensorOp::ApplyRope); + self.reference + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta); + } + + fn matmul_vec( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + out_dim: usize, + in_dim: usize, + ) { + if !self.chip_matmul(out, x, weight, 1, in_dim, out_dim) { + self.reference_for(TensorOp::MatmulVec); + self.reference.matmul_vec(out, x, weight, out_dim, in_dim); + } + } + + fn matmul_batch( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + batch_size: usize, + in_dim: usize, + out_dim: usize, + ) { + if !self.chip_matmul(out, x, weight, batch_size, in_dim, out_dim) { + self.reference_for(TensorOp::MatmulBatch); + self.reference + .matmul_batch(out, x, weight, batch_size, in_dim, out_dim); + } + } + + fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { + self.reference_for(TensorOp::Swiglu); + self.reference.swiglu(out, gate, up); + } + + fn gqa_attention( + &self, + out: &mut [f32], + q: &[f32], + k_cache: &[f32], + v_cache: &[f32], + seq_len: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) { + self.reference_for(TensorOp::GqaAttention); + self.reference.gqa_attention( + out, + q, + k_cache, + v_cache, + seq_len, + num_q_heads, + num_kv_heads, + head_dim, + ); + } + + fn paged_attention( + &self, + out: &mut [f32], + q: &[f32], + pool: &aien_kv_cache::UnifiedKvTensorPool, + block_ids: &[usize], + context_len: usize, + layer_idx: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) { + self.reference_for(TensorOp::PagedAttention); + self.reference.paged_attention( + out, + q, + pool, + block_ids, + context_len, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + ); + } + + fn paged_attention_batch( + &self, + out: &mut [f32], + q: &[f32], + pool: &aien_kv_cache::UnifiedKvTensorPool, + block_tables: &[i32], + context_lens: &[i32], + max_blocks_per_seq: usize, + num_seqs: usize, + layer_idx: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) { + // Counted once as a batch op; the reference batch calls the reference + // single-sequence path, not ours, so there is no double count. + self.reference_for(TensorOp::PagedAttentionBatch); + self.reference.paged_attention_batch( + out, + q, + pool, + block_tables, + context_lens, + max_blocks_per_seq, + num_seqs, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + ); + } + + fn compute_logits( + &self, + logits: &mut [f32], + hidden: &[f32], + embed_weight: &[f32], + vocab_size: usize, + hidden_dim: usize, + ) { + if !self.chip_matmul(logits, hidden, embed_weight, 1, hidden_dim, vocab_size) { + self.reference_for(TensorOp::ComputeLogits); + self.reference + .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lcg(s: &mut u32) -> f32 { + *s = s.wrapping_mul(1664525).wrapping_add(1013904223); + ((*s >> 8) as f32 / (1u32 << 24) as f32) - 0.5 + } + + #[test] + fn mask_is_exactly_the_three_matmuls() { + let b = OmegaGb10Backend::new(); + let names: Vec<_> = b + .native_ops() + .native_ops() + .iter() + .map(|o| o.name()) + .collect(); + assert_eq!(names, ["matmul_vec", "matmul_batch", "compute_logits"]); + } + + #[test] + fn reference_ops_are_counted_by_design_and_never_trip() { + let b = OmegaGb10Backend::new(); + let mut out = [0.0f32; 4]; + b.swiglu(&mut out, &[1.0; 4], &[1.0; 4]); + assert_eq!(b.fallback_count(), 0); + assert!(b.op_report().line().contains("swiglu:1")); + } + + /// Stub build only: a chip error on a claimed-native op is a counted fallback + /// (dev build) with the reference result, never silent. + #[test] + fn chip_error_is_a_counted_fallback() { + if aien_omega_gpu::is_native() || !crate::strict::dev_fallback_active() { + return; // native: nothing fails here; production: it would (correctly) panic + } + let b = OmegaGb10Backend::new(); + let mut s = 7u32; + let (m, k, n) = (3usize, 32usize, 16usize); + let x: Vec<f32> = (0..m * k).map(|_| lcg(&mut s)).collect(); + let w: Vec<f32> = (0..n * k).map(|_| lcg(&mut s)).collect(); + let mut got = vec![0.0f32; m * n]; + let mut want = vec![0.0f32; m * n]; + b.matmul_batch(&mut got, &x, &w, m, k, n); + ReferenceCpuBackend::new().matmul_batch(&mut want, &x, &w, m, k, n); + assert_eq!(got, want); + assert_eq!(b.fallback_count(), 1); + assert_eq!(b.chip_errors(), 1); + assert!(b + .op_report() + .line() + .contains("native_fallbacks=[matmul_batch:1]")); + } + + #[test] + #[should_panic(expected = "STRICT_REAL_MODEL_VIOLATION")] + fn chip_error_trips_strict_in_production() { + if aien_omega_gpu::is_native() || crate::strict::dev_fallback_active() { + panic!("STRICT_REAL_MODEL_VIOLATION (skipped: native or dev build)"); + } + let b = OmegaGb10Backend::new(); + let mut out = [0.0f32; 2]; + b.matmul_vec(&mut out, &[1.0; 2], &[1.0; 4], 2, 2); + } + + #[test] + fn fingerprint_changes_with_content() { + let a = vec![1.0f32; 1000]; + let mut b = a.clone(); + b[999] = 2.0; + assert_ne!(fingerprint(&a), fingerprint(&b)); + } +} diff --git a/crates/aien-inference-abi/tests/omega_backend_parity.rs b/crates/aien-inference-abi/tests/omega_backend_parity.rs new file mode 100644 index 00000000..616f3bc3 --- /dev/null +++ b/crates/aien-inference-abi/tests/omega_backend_parity.rs @@ -0,0 +1,100 @@ +//! FB-1 cut 3b: OmegaGb10Backend against ReferenceCpuBackend on TinyLlama layer shapes. +//! +//! Host test (runs everywhere, stub-aware): in a stub build the backend must +//! report itself unavailable. Chip test (`#[ignore]`, run through the heavy +//! queue with a native build): +//! AIEN_OMEGA_DIR=... AIEN_PHYSICS_DIR=... cargo test -p aien-inference-abi --release \ +//! --test omega_backend_parity -- --ignored --nocapture +//! +//! Error metric: |chip - ref| divided by sum_i |x_i * w_i| (the accumulation +//! scale). Both sides see bf16-rounded inputs on the chip and f32 on the +//! reference, so each product carries at most ~2 * 2^-8 relative error; the bound +//! asserted is 8e-3 of the scale, and the typical value is far lower (random signs). +use aien_inference_abi::{OmegaGb10Backend, ReferenceCpuBackend, TensorBackend}; + +fn lcg(s: &mut u32) -> f32 { + *s = s.wrapping_mul(1664525).wrapping_add(1013904223); + ((*s >> 8) as f32 / (1u32 << 24) as f32) - 0.5 +} + +/// Max over outputs of |got - want| / sum|x*w|, for out = X * W^T. +fn worst_ratio( + got: &[f32], + want: &[f32], + x: &[f32], + w: &[f32], + m: usize, + k: usize, + n: usize, +) -> f64 { + let mut worst = 0.0f64; + for r in 0..m { + for o in 0..n { + let mut scale = 0.0f64; + for i in 0..k { + scale += (x[r * k + i] as f64 * w[o * k + i] as f64).abs(); + } + let d = (got[r * n + o] as f64 - want[r * n + o] as f64).abs(); + worst = worst.max(d / scale.max(1e-30)); + } + } + worst +} + +#[test] +fn stub_backend_reports_unavailable() { + let b = OmegaGb10Backend::new(); + assert_eq!(b.is_available(), aien_omega_gpu::is_native()); + assert_eq!(b.native_ops().native_ops().len(), 3); +} + +#[test] +#[ignore = "chip test: needs a native build and the GB10; run through the heavy queue"] +fn chip_parity_on_tinyllama_shapes() { + let omega = OmegaGb10Backend::new(); + assert!(omega.is_available(), "native build required"); + let reference = ReferenceCpuBackend::new(); + // (name, out_dim, in_dim): TinyLlama 1.1B hidden 2048, kv 256, inter 5632, vocab 32000. + let shapes = [ + ("q_proj/o_proj", 2048usize, 2048usize), + ("k_proj/v_proj", 256, 2048), + ("gate/up_proj", 5632, 2048), + ("down_proj", 2048, 5632), + ("lm_head", 32000, 2048), + ]; + let mut seed = 12345u32; + let mut overall = 0.0f64; + for (name, out_dim, in_dim) in shapes { + let w: Vec<f32> = (0..out_dim * in_dim).map(|_| lcg(&mut seed)).collect(); + // matmul_vec (and compute_logits for lm_head), batch 1 + let x: Vec<f32> = (0..in_dim).map(|_| lcg(&mut seed)).collect(); + let mut got = vec![0.0f32; out_dim]; + let mut want = vec![0.0f32; out_dim]; + if name == "lm_head" { + omega.compute_logits(&mut got, &x, &w, out_dim, in_dim); + reference.compute_logits(&mut want, &x, &w, out_dim, in_dim); + } else { + omega.matmul_vec(&mut got, &x, &w, out_dim, in_dim); + reference.matmul_vec(&mut want, &x, &w, out_dim, in_dim); + } + let r1 = worst_ratio(&got, &want, &x, &w, 1, in_dim, out_dim); + // matmul_batch, batch 7 (same resident weights, different m) + let batch = 7usize; + let xb: Vec<f32> = (0..batch * in_dim).map(|_| lcg(&mut seed)).collect(); + let mut gotb = vec![0.0f32; batch * out_dim]; + let mut wantb = vec![0.0f32; batch * out_dim]; + omega.matmul_batch(&mut gotb, &xb, &w, batch, in_dim, out_dim); + reference.matmul_batch(&mut wantb, &xb, &w, batch, in_dim, out_dim); + let rb = worst_ratio(&gotb, &wantb, &xb, &w, batch, in_dim, out_dim); + println!( + "PARITY {name} {out_dim}x{in_dim}: vec max_err/scale={r1:.3e} batch7 max_err/scale={rb:.3e}" + ); + assert!(r1 < 8e-3 && rb < 8e-3, "{name}: parity bound exceeded"); + overall = overall.max(r1).max(rb); + } + assert_eq!(omega.fallback_count(), 0, "{}", omega.last_error()); + assert_eq!(omega.chip_errors(), 0, "{}", omega.last_error()); + println!("PARITY overall worst max_err/scale = {overall:.3e}"); + println!("PARITY resident weights = {}", omega.resident_count()); + println!("PARITY {}", omega.op_report().line()); +} diff --git a/crates/aien-inference-runtime/src/model.rs b/crates/aien-inference-runtime/src/model.rs index d4cff5ad..ab35aea2 100644 --- a/crates/aien-inference-runtime/src/model.rs +++ b/crates/aien-inference-runtime/src/model.rs @@ -75,7 +75,24 @@ impl EmbeddedModel { let weights = TransformerWeights::load_from_safetensors(checkpoint_path.as_ref(), &config) .map_err(|e| format!("Failed to load safetensors checkpoint: {}", e))?; - let tensor_backend: Arc<dyn TensorBackend> = if use_gpu { + let tensor_backend: Arc<dyn TensorBackend> = if use_gpu + && aien_inference_abi::omega_backend_selected() + { + let omega = aien_inference_abi::OmegaGb10Backend::new(); + if omega.is_available() { + info!( + "Binding EmbeddedModel to the native Omega GPU engine (AIEN_GPU_BACKEND=omega)" + ); + Arc::new(omega) + } else if aien_inference_abi::strict::production_strict() { + return Err(aien_inference_abi::strict::violation( + "AIEN_GPU_BACKEND=omega requested but the Omega GPU engine is not linked (stub build)", + )); + } else { + info!("Omega GPU engine unavailable, falling back to CPU reference execution"); + Arc::new(ReferenceCpuBackend::new()) + } + } else if use_gpu { let surface = ExecutionSurface::detect(); if surface.is_accelerated_gpu() { let gpu = BlackwellGb10Backend::new(); diff --git a/crates/aien-inference-runtime/tests/strict_real_model.rs b/crates/aien-inference-runtime/tests/strict_real_model.rs index 22ba8d11..f2930e3f 100644 --- a/crates/aien-inference-runtime/tests/strict_real_model.rs +++ b/crates/aien-inference-runtime/tests/strict_real_model.rs @@ -148,3 +148,107 @@ fn strict_real_model_gate() { assert!(!out.trim().is_empty(), "STRICT: empty output"); verdict.unwrap_or_else(|e| panic!("{e}")); } + +/// FB-1 cut 3b gate: the same greedy generation on the CPU reference backend and on +/// the Omega backend (AIEN_GPU_BACKEND=omega), same checkpoint. Records tok/s for +/// both, asserts identical text and zero fallbacks of the claimed-native matmul ops. +/// AIEN_E2E_CHECKPOINT=~/models/TinyLlama-1.1B-Chat-v1.0 AIEN_STRICT_RECEIPT=/path/receipt.json \ +/// cargo test -p aien-inference-runtime --release --test strict_real_model \ +/// omega_vs_reference_real_model -- --ignored --nocapture +#[test] +#[ignore = "needs the real checkpoint and the GB10 with a native Omega build; heavy queue only"] +fn omega_vs_reference_real_model() { + let ckpt = PathBuf::from(std::env::var("AIEN_E2E_CHECKPOINT").expect("AIEN_E2E_CHECKPOINT")); + let receipt_path = + PathBuf::from(std::env::var("AIEN_STRICT_RECEIPT").expect("AIEN_STRICT_RECEIPT")); + let (model_path, dir) = if ckpt.is_dir() { + (ckpt.join("model.safetensors"), ckpt.clone()) + } else { + ( + ckpt.clone(), + ckpt.parent().map(Path::to_path_buf).unwrap_or_default(), + ) + }; + let tokenizer_path = dir.join("tokenizer.json"); + let prompt = "The DGX Spark is a small computer with a large"; + let max_tokens = 32usize; + + let run = |model: &mut EmbeddedModel| -> (String, usize, f64) { + let mut text = String::new(); + let mut n = 0usize; + let t = std::time::Instant::now(); + model + .generate_stream(prompt, max_tokens, 0.0, |piece| { + text.push_str(piece); + n += 1; + true + }) + .unwrap_or_else(|e| panic!("generate failed: {e}")); + (text, n, t.elapsed().as_secs_f64()) + }; + + // Reference (CPU) leg. + let mut cpu = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, false, true) + .unwrap_or_else(|e| panic!("reference load: {e}")); + println!( + "OMEGA_GATE ref backend: {}", + cpu.transformer.tensor_backend.name() + ); + let (cpu_text, cpu_n, cpu_s) = run(&mut cpu); + println!( + "OMEGA_GATE ref tokens={cpu_n} secs={cpu_s:.3} tok/s={:.3} text={cpu_text:?}", + cpu_n as f64 / cpu_s + ); + drop(cpu); + + // Omega leg. The env var is read inside load_checkpoint; set before loading. + std::env::set_var(aien_inference_abi::GPU_BACKEND_ENV, "omega"); + let mut om = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true) + .unwrap_or_else(|e| panic!("STRICT: omega bind refused: {e}")); + let backend_identity = om.transformer.tensor_backend.name().to_string(); + println!("OMEGA_GATE omega backend: {backend_identity}"); + // Warm-up: first call uploads every weight matrix; reported separately. + let t = std::time::Instant::now(); + let _ = om.generate(prompt, 1, 0.0).expect("omega warm-up"); + println!( + "OMEGA_GATE omega warm-up (weight upload + 1 token) secs={:.3}", + t.elapsed().as_secs_f64() + ); + let (om_text, om_n, om_s) = run(&mut om); + println!( + "OMEGA_GATE omega tokens={om_n} secs={om_s:.3} tok/s={:.3} text={om_text:?}", + om_n as f64 / om_s + ); + let report = om.transformer.tensor_backend.op_report(); + println!("OMEGA_GATE {}", report.line()); + let fallback_count = om.transformer.tensor_backend.fallback_count(); + println!("OMEGA_GATE tokens_match={}", cpu_text == om_text); + + let mut receipt = StrictModelReceipt { + checkpoint_path: model_path.display().to_string(), + checkpoint_sha256: sha256_file_hex(&model_path), + tokenizer_path: tokenizer_path.display().to_string(), + tokenizer_sha256: sha256_file_hex(&tokenizer_path), + backend_identity, + model_id: om.config.model_id.clone(), + model_config: serde_json::to_value(&om.config) + .unwrap_or(serde_json::json!({"model_id": om.config.model_id})), + fallback_count, + op_report: Some(report), + dev_fallback_build: strict::dev_fallback_active(), + verdict: String::new(), + }; + let verdict = receipt.verify(); + std::fs::write( + &receipt_path, + serde_json::to_string_pretty(&receipt).unwrap(), + ) + .expect("write receipt"); + println!( + "OMEGA_GATE verdict: {} (receipt {})", + receipt.verdict, + receipt_path.display() + ); + assert_eq!(cpu_text, om_text, "Omega backend changed the greedy output"); + verdict.unwrap_or_else(|e| panic!("{e}")); +} diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs index 7476815b..3ec850cb 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -1,7 +1,6 @@ //! Raw declarations, written by hand from omega `src/omega_gpu_matmul_api.h` -//! at the commit pinned in `omega.lock` (d0ca8ce). Nothing generated. -//! Functions added by later omega cuts (resident-weights handles, FB-1 cut 1b) -//! get their own declarations here once they are on omega main and the lock moves. +//! at the commit pinned in `omega.lock` (5e29b82). Nothing generated. +//! Includes the resident-weights handles added by omega FB-1 cut 1b. use std::os::raw::{c_char, c_int}; pub const OMEGA_GPU_MATMUL_OK: c_int = 0; @@ -37,6 +36,13 @@ pub struct OmegaGpuMatmulInfo { pub kernel_cache_hit: bool, pub target_chip: [c_char; 64], pub sm_architecture: u32, + // cut 1b additions (appended in the C header, same order) + pub grid_x: u32, + pub grid_y: u32, + pub padded_k: u32, + pub resident: bool, + pub oracle_ran: bool, + pub call_ns: u64, } impl OmegaGpuMatmulInfo { @@ -59,10 +65,22 @@ impl OmegaGpuMatmulInfo { kernel_cache_hit: false, target_chip: [0; 64], sm_architecture: 0, + grid_x: 0, + grid_y: 0, + padded_k: 0, + resident: false, + oracle_ran: false, + call_ns: 0, } } } +/// Opaque resident weight tensor (omega `OmegaGpuTensor`). +#[repr(C)] +pub struct OmegaGpuTensor { + _private: [u8; 0], +} + #[cfg(has_omega_gpu)] extern "C" { pub fn omega_gpu_matmul_bf16( @@ -85,4 +103,35 @@ extern "C" { ) -> c_int; pub fn omega_gpu_matmul_rc_name(rc: c_int) -> *const c_char; pub fn omega_gpu_matmul_cache_clear(); + pub fn omega_gpu_tensor_upload_bf16( + k: u32, + n: u32, + b: *const u16, + out: *mut *mut OmegaGpuTensor, + ) -> c_int; + pub fn omega_gpu_tensor_upload_f32( + k: u32, + n: u32, + b: *const f32, + out: *mut *mut OmegaGpuTensor, + ) -> c_int; + pub fn omega_gpu_tensor_free(t: *mut OmegaGpuTensor); + pub fn omega_gpu_tensor_shape(t: *const OmegaGpuTensor, k: *mut u32, n: *mut u32); + pub fn omega_gpu_matmul_resident_bf16( + m: u32, + a: *const u16, + b: *const OmegaGpuTensor, + c: *mut f32, + info: *mut OmegaGpuMatmulInfo, + ) -> c_int; + pub fn omega_gpu_matmul_resident_f32( + m: u32, + a: *const f32, + b: *const OmegaGpuTensor, + c: *mut f32, + info: *mut OmegaGpuMatmulInfo, + ) -> c_int; + pub fn omega_gpu_matmul_last_error() -> *const c_char; + pub fn omega_gpu_matmul_is_blocked() -> c_int; + pub fn omega_gpu_device_close(); } diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 1cf1f183..8e7d1f02 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -7,8 +7,8 @@ //! //! Conventions: row-major, `C[m x n] = A[m x k] * B[k x n]`, f32 output. //! Inputs are bf16 (`matmul_bf16`) or f32 rounded to bf16 on the host (`matmul_f32`). -//! Limits (omega `omega_blackwell_matmul.h`: M, K, N <= 1024) are enforced by omega -//! and surface as `TooLarge`. +//! Limits (omega FB-1 cut 1b: M <= 8192, K <= 16384, N <= 262144) are enforced by omega +//! and surface as `Rc { rc: -2 (TOO_LARGE) }`. pub mod ffi; use std::fmt; @@ -214,3 +214,134 @@ pub fn cache_clear() { ffi::omega_gpu_matmul_cache_clear() } } + +/// A weight matrix (k x n, bf16, zero-padded by omega) resident on the device +/// until dropped. Not `Sync`: omega's resident-call thread safety is not +/// documented, so callers must serialize use (the backend holds it in a Mutex). +pub struct ResidentTensor { + #[cfg(has_omega_gpu)] + ptr: *mut ffi::OmegaGpuTensor, + k: usize, + n: usize, +} + +// SAFETY: the handle is an owning pointer to a device buffer with no thread +// affinity that we know of (UNVERIFIED in omega docs); we only ever move it +// between threads and never share it without external locking. +unsafe impl Send for ResidentTensor {} + +impl fmt::Debug for ResidentTensor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ResidentTensor {{ k: {}, n: {} }}", self.k, self.n) + } +} + +impl ResidentTensor { + /// Upload a row-major k x n f32 matrix (rounded to bf16 on the host by omega). + pub fn upload_f32(k: usize, n: usize, b: &[f32]) -> Result<Self, OmegaGpuError> { + check_len("b", k * n, b.len())?; + let (_, ku, nu) = dims(1, k, n)?; + #[cfg(has_omega_gpu)] + { + let mut ptr: *mut ffi::OmegaGpuTensor = std::ptr::null_mut(); + // SAFETY: b has k*n elements (checked); ptr is a valid out-pointer. + let rc = unsafe { ffi::omega_gpu_tensor_upload_f32(ku, nu, b.as_ptr(), &mut ptr) }; + if rc != ffi::OMEGA_GPU_MATMUL_OK || ptr.is_null() { + return Err(rc_error(if rc == 0 { + ffi::OMEGA_GPU_MATMUL_BAD_ARGS + } else { + rc + })); + } + Ok(Self { ptr, k, n }) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (ku, nu); + Err(OmegaGpuError::Unavailable) + } + } + + pub fn k(&self) -> usize { + self.k + } + + pub fn n(&self) -> usize { + self.n + } + + /// `c[m x n] = a[m x k] * self`, f32 `a` rounded to bf16 on the host, no host oracle. + pub fn matmul_f32( + &self, + m: usize, + a: &[f32], + c: &mut [f32], + ) -> Result<MatmulInfo, OmegaGpuError> { + check_len("a", m * self.k, a.len())?; + check_len("c", m * self.n, c.len())?; + let (mu, _, _) = dims(m, self.k, self.n)?; + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuMatmulInfo::zeroed(); + // SAFETY: lengths checked; self.ptr is a live handle owned by self. + let rc = unsafe { + ffi::omega_gpu_matmul_resident_f32( + mu, + a.as_ptr(), + self.ptr, + c.as_mut_ptr(), + &mut info, + ) + }; + finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = mu; + Err(OmegaGpuError::Unavailable) + } + } +} + +impl Drop for ResidentTensor { + fn drop(&mut self) { + #[cfg(has_omega_gpu)] + // SAFETY: ptr came from a successful upload and is freed exactly once. + unsafe { + ffi::omega_gpu_tensor_free(self.ptr) + } + } +} + +#[cfg(has_omega_gpu)] +fn rc_error(rc: i32) -> OmegaGpuError { + OmegaGpuError::Rc { + rc, + name: rc_name(rc), + } +} + +/// Stage name of the most recent chip failure ("" if none; always "" in the stub). +pub fn last_error() -> String { + #[cfg(has_omega_gpu)] + { + // SAFETY: returns a pointer to a static or internal NUL-terminated string. + let p = unsafe { ffi::omega_gpu_matmul_last_error() }; + if !p.is_null() { + // SAFETY: non-null and NUL-terminated. + return unsafe { std::ffi::CStr::from_ptr(p) } + .to_string_lossy() + .into_owned(); + } + } + String::new() +} + +/// True once an uncertain completion has latched the process (every later chip call fails). +pub fn is_blocked() -> bool { + #[cfg(has_omega_gpu)] + // SAFETY: no arguments, returns an int. + return unsafe { ffi::omega_gpu_matmul_is_blocked() } != 0; + #[cfg(not(has_omega_gpu))] + false +} diff --git a/crates/aien-omega-gpu/tests/parity.rs b/crates/aien-omega-gpu/tests/parity.rs index 1299d80d..eb2f7ed3 100644 --- a/crates/aien-omega-gpu/tests/parity.rs +++ b/crates/aien-omega-gpu/tests/parity.rs @@ -37,7 +37,7 @@ fn reference(m: usize, k: usize, n: usize, a: &[f32], b: &[f32]) -> Vec<f32> { #[test] fn lock_is_full_sha() { assert_eq!(PINNED_OMEGA_SHA.len(), 40); - assert!(PINNED_OMEGA_SHA.starts_with("d0ca8ce")); + assert!(PINNED_OMEGA_SHA.starts_with("5e29b82")); } #[test] diff --git a/omega.lock b/omega.lock index 1eaee794..b195cb95 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -d0ca8cedee1a5494c10d8ae70c79621f3544a1c9 +5e29b826cce3c18e891c114a616317df2939af6c