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#187 (code only)
Apply it
git checkout -b patch-89bd968a5f2174ad b7de7c1b7e7c5468c292eff04cd7ac175608ed38 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/89bd968a5f2174ad.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
187
af674732e6d8ac58bb8e9ef812e4f33c32814ff4
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":187,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/187","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:14Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index 6c5f509c..e7224f24 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -1,9 +1,10 @@ -//! `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`. +//! `OmegaGb10Backend` (FB-1 cuts 3b and 3c): the three matrix-multiply ops, rmsnorm, +//! rope and swiglu of `TensorBackend` run on our own native GPU engine +//! (`libomega_gpu.a`, no CUDA) through the `aien-omega-gpu` crate; the attention ops +//! run on the reference CPU path by design and are counted by `OpAccounting`. //! -//! Native mask: `matmul_vec`, `matmul_batch`, `compute_logits`. A chip error in +//! Native mask: `matmul_vec`, `matmul_batch`, `compute_logits`, `rmsnorm`, +//! `apply_rope`, `swiglu`. 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. @@ -28,7 +29,7 @@ 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; +use std::sync::{Arc, 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. @@ -45,18 +46,26 @@ const BACKEND_NAME: &str = "OmegaGb10Backend"; type Key = (usize, usize, usize, usize); +/// Rope cos/sin table for one position: `head_dim / 2` values each. +type RopeTable = Arc<(Vec<f32>, Vec<f32>)>; + +/// Cache key: (head_dim, theta bits, position). Drop everything past this many entries. +type RopeKey = (usize, u32, usize); +const ROPE_CACHE_MAX: usize = 16384; + struct Resident { fingerprint: u64, tensor: ResidentTensor, } -/// Native-matmul backend on the Omega GPU engine. +/// Native backend on the Omega GPU engine (matmuls and elementwise ops). 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>>, + rope_tables: Mutex<HashMap<RopeKey, RopeTable>>, chip_errors: AtomicU64, chip_calls: AtomicU64, chip_ns: AtomicU64, @@ -92,8 +101,12 @@ impl OmegaGb10Backend { TensorOp::MatmulVec, TensorOp::MatmulBatch, TensorOp::ComputeLogits, + TensorOp::Rmsnorm, + TensorOp::ApplyRope, + TensorOp::Swiglu, ])), chip: Mutex::new(HashMap::new()), + rope_tables: Mutex::new(HashMap::new()), chip_errors: AtomicU64::new(0), chip_calls: AtomicU64::new(0), chip_ns: AtomicU64::new(0), @@ -203,6 +216,120 @@ impl OmegaGb10Backend { } } + /// Rope cos/sin table for `pos`, built exactly as the reference does + /// (`tensor::apply_rope`, tensor.rs:101): f64 frequency and angle, then cast to f32. + /// Cached per (head_dim, theta, pos). + fn rope_table(&self, head_dim: usize, theta: f32, pos: usize) -> RopeTable { + let key: RopeKey = (head_dim, theta.to_bits(), pos); + let mut cache = self + .rope_tables + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(t) = cache.get(&key) { + return Arc::clone(t); + } + let half = head_dim / 2; + let mut cos = Vec::with_capacity(half); + let mut sin = Vec::with_capacity(half); + for i in 0..half { + let exponent = (2 * i) as f64 / (head_dim as f64); + let freq = 1.0 / (theta as f64).powf(exponent); + let rot = (pos as f64) * freq; + sin.push(rot.sin() as f32); + cos.push(rot.cos() as f32); + } + if cache.len() >= ROPE_CACHE_MAX { + cache.clear(); + } + let t: RopeTable = Arc::new((cos, sin)); + cache.insert(key, Arc::clone(&t)); + t + } + + /// Run one elementwise chip call under the chip lock. False on any error (recorded). + fn chip_elementwise( + &self, + what: &str, + call: impl FnOnce() -> Result<aien_omega_gpu::OmegaGpuEwInfo, aien_omega_gpu::OmegaGpuError>, + ) -> bool { + let guard = match self.chip.lock() { + Ok(g) => g, + Err(_) => return self.fail("chip lock poisoned".into()), + }; + let res = call(); + drop(guard); + match res { + Ok(info) => { + self.chip_calls.fetch_add(1, Ordering::Relaxed); + self.chip_ns.fetch_add(info.elapsed_ns, Ordering::Relaxed); + true + } + Err(e) => self.fail(format!("{what}: {e}")), + } + } + + fn chip_rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) -> bool { + let dim = x.len(); + self.chip_elementwise(&format!("rmsnorm dim={dim}"), || { + aien_omega_gpu::rmsnorm_f32(1, dim, x, weight, eps, out) + }) + } + + /// q then k go to the chip as one `heads` run (the table is the same for every head). + #[allow(clippy::too_many_arguments)] + fn chip_rope( + &self, + q: &mut [f32], + k: &mut [f32], + pos: usize, + head_dim: usize, + num_q_heads: usize, + num_kv_heads: usize, + theta: f32, + ) -> bool { + if head_dim == 0 + || !head_dim.is_multiple_of(2) + || q.len() != num_q_heads * head_dim + || k.len() != num_kv_heads * head_dim + { + return self.fail(format!( + "rope shape mismatch: q={} k={} head_dim={head_dim} q_heads={num_q_heads} kv_heads={num_kv_heads}", + q.len(), + k.len() + )); + } + let table = self.rope_table(head_dim, theta, pos); + let mut both = Vec::with_capacity(q.len() + k.len()); + both.extend_from_slice(q); + both.extend_from_slice(k); + let mut rotated = vec![0.0f32; both.len()]; + let heads = num_q_heads + num_kv_heads; + let ok = self.chip_elementwise(&format!("rope heads={heads} head_dim={head_dim}"), || { + aien_omega_gpu::rope_f32(heads, head_dim, &both, &table.0, &table.1, &mut rotated) + }); + if ok { + let (rq, rk) = rotated.split_at(q.len()); + q.copy_from_slice(rq); + k.copy_from_slice(rk); + } + ok + } + + fn chip_swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) -> bool { + // The reference uses min(len) of the three; the chip path demands equal lengths. + if gate.len() != up.len() || gate.len() != out.len() { + return self.fail(format!( + "swiglu shape mismatch: gate={} up={} out={}", + gate.len(), + up.len(), + out.len() + )); + } + self.chip_elementwise(&format!("swiglu n={}", gate.len()), || { + aien_omega_gpu::swiglu_f32(gate, up, out) + }) + } + fn fail(&self, msg: String) -> bool { self.chip_errors.fetch_add(1, Ordering::Relaxed); let stage = aien_omega_gpu::last_error(); @@ -211,6 +338,7 @@ impl OmegaGb10Backend { } else { format!("{msg} (stage: {stage})") }; + eprintln!("OMEGA_BACKEND chip error: {full}"); if let Ok(mut l) = self.last_error.lock() { *l = full; } @@ -244,8 +372,10 @@ impl TensorBackend for OmegaGb10Backend { } fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { - self.reference_for(TensorOp::Rmsnorm); - self.reference.rmsnorm(out, x, weight, eps); + if !self.chip_rmsnorm(out, x, weight, eps) { + self.reference_for(TensorOp::Rmsnorm); + self.reference.rmsnorm(out, x, weight, eps); + } } fn apply_rope( @@ -258,9 +388,11 @@ impl TensorBackend for OmegaGb10Backend { 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); + if !self.chip_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta) { + self.reference_for(TensorOp::ApplyRope); + self.reference + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta); + } } fn matmul_vec( @@ -294,8 +426,10 @@ impl TensorBackend for OmegaGb10Backend { } fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { - self.reference_for(TensorOp::Swiglu); - self.reference.swiglu(out, gate, up); + if !self.chip_swiglu(out, gate, up) { + self.reference_for(TensorOp::Swiglu); + self.reference.swiglu(out, gate, up); + } } fn gqa_attention( @@ -406,7 +540,7 @@ mod tests { } #[test] - fn mask_is_exactly_the_three_matmuls() { + fn mask_is_exactly_the_six_native_ops() { let b = OmegaGb10Backend::new(); let names: Vec<_> = b .native_ops() @@ -414,16 +548,26 @@ mod tests { .iter() .map(|o| o.name()) .collect(); - assert_eq!(names, ["matmul_vec", "matmul_batch", "compute_logits"]); + assert_eq!( + names, + [ + "rmsnorm", + "apply_rope", + "matmul_vec", + "matmul_batch", + "swiglu", + "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]); + let mut out = [0.0f32; 2]; + b.gqa_attention(&mut out, &[1.0; 2], &[1.0; 2], &[1.0; 2], 1, 1, 1, 2); assert_eq!(b.fallback_count(), 0); - assert!(b.op_report().line().contains("swiglu:1")); + assert!(b.op_report().line().contains("gqa_attention:1")); } /// Stub build only: a chip error on a claimed-native op is a counted fallback @@ -462,6 +606,68 @@ mod tests { b.matmul_vec(&mut out, &[1.0; 2], &[1.0; 4], 2, 2); } + /// The cached cos/sin table, applied on the host with the same f32 formulas as the + /// chip kernel (FMUL, FMUL, FADD), must equal the reference rope bit for bit. + #[test] + fn rope_table_reproduces_reference_rope() { + let b = OmegaGb10Backend::new(); + let (head_dim, nq, nkv, pos, theta) = (64usize, 4usize, 2usize, 37usize, 10000.0f32); + let mut s = 99u32; + let q0: Vec<f32> = (0..nq * head_dim).map(|_| lcg(&mut s)).collect(); + let k0: Vec<f32> = (0..nkv * head_dim).map(|_| lcg(&mut s)).collect(); + let (mut qr, mut kr) = (q0.clone(), k0.clone()); + ReferenceCpuBackend::new().apply_rope(&mut qr, &mut kr, pos, head_dim, nq, nkv, theta); + let t = b.rope_table(head_dim, theta, pos); + let half = head_dim / 2; + let rot = |v: &[f32]| -> Vec<f32> { + let mut o = v.to_vec(); + for h in 0..v.len() / head_dim { + for i in 0..half { + let (a, c) = (v[h * head_dim + i], v[h * head_dim + i + half]); + o[h * head_dim + i] = a * t.0[i] - c * t.1[i]; + o[h * head_dim + i + half] = a * t.1[i] + c * t.0[i]; + } + } + o + }; + assert_eq!(rot(&q0), qr); + assert_eq!(rot(&k0), kr); + // cached: same allocation on the second ask + assert!(Arc::ptr_eq(&t, &b.rope_table(head_dim, theta, pos))); + } + + /// Stub build only: each newly native elementwise op is a counted fallback with the + /// reference result when the chip is unavailable, never silent. + #[test] + fn elementwise_chip_errors_are_counted_fallbacks() { + if aien_omega_gpu::is_native() || !crate::strict::dev_fallback_active() { + return; + } + let b = OmegaGb10Backend::new(); + let r = ReferenceCpuBackend::new(); + let mut s = 5u32; + let x: Vec<f32> = (0..128).map(|_| lcg(&mut s)).collect(); + let w: Vec<f32> = (0..128).map(|_| lcg(&mut s)).collect(); + let (mut got, mut want) = (vec![0.0f32; 128], vec![0.0f32; 128]); + b.rmsnorm(&mut got, &x, &w, 1e-5); + r.rmsnorm(&mut want, &x, &w, 1e-5); + assert_eq!(got, want); + b.swiglu(&mut got, &x, &w); + r.swiglu(&mut want, &x, &w); + assert_eq!(got, want); + let (mut q, mut k) = (x[..64].to_vec(), x[64..].to_vec()); + let (mut qw, mut kw) = (q.clone(), k.clone()); + b.apply_rope(&mut q, &mut k, 3, 32, 2, 2, 10000.0); + r.apply_rope(&mut qw, &mut kw, 3, 32, 2, 2, 10000.0); + assert_eq!((q, k), (qw, kw)); + assert_eq!(b.fallback_count(), 3); + let line = b.op_report().line(); + assert!( + line.contains("native_fallbacks=[rmsnorm:1,apply_rope:1,swiglu:1]"), + "{line}" + ); + } + #[test] fn fingerprint_changes_with_content() { let a = vec![1.0f32; 1000]; diff --git a/crates/aien-inference-abi/tests/omega_backend_parity.rs b/crates/aien-inference-abi/tests/omega_backend_parity.rs index 616f3bc3..6fb1467f 100644 --- a/crates/aien-inference-abi/tests/omega_backend_parity.rs +++ b/crates/aien-inference-abi/tests/omega_backend_parity.rs @@ -45,7 +45,7 @@ fn worst_ratio( 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); + assert_eq!(b.native_ops().native_ops().len(), 6); } #[test] @@ -98,3 +98,109 @@ fn chip_parity_on_tinyllama_shapes() { println!("PARITY resident weights = {}", omega.resident_count()); println!("PARITY {}", omega.op_report().line()); } + +/// Worst of |got - want| / (1e-6 + 1e-5 * |want|) over all elements; <= 1 means inside the +/// omega cut-4 elementwise tolerance (1e-5 relative + 1e-6 absolute). +fn worst_tol_ratio(got: &[f32], want: &[f32]) -> f64 { + assert_eq!(got.len(), want.len()); + got.iter() + .zip(want) + .map(|(g, w)| (*g as f64 - *w as f64).abs() / (1e-6 + 1e-5 * (*w as f64).abs())) + .fold(0.0, f64::max) +} + +/// FB-1 cut 3c: rmsnorm, apply_rope and swiglu on the chip at TinyLlama shapes +/// (hidden 2048, 32 q heads, 4 kv heads, head_dim 64, intermediate 5632, eps 1e-5, +/// theta 10000) against ReferenceCpuBackend. Rope must be bit-exact (omega emits +/// FMUL/FMUL/FADD, no fused multiply-add); rmsnorm and swiglu within the tolerance +/// stated in omega docs/numeric/FB1_CUT4_ELEMENTWISE.md (1e-5 relative + 1e-6 absolute). +#[test] +#[ignore = "chip test: needs a native build and the GB10; run through the heavy queue"] +fn chip_elementwise_parity_on_tinyllama_shapes() { + let omega = OmegaGb10Backend::new(); + assert!(omega.is_available(), "native build required"); + let reference = ReferenceCpuBackend::new(); + let mut seed = 777u32; + + // rmsnorm, dim 2048 (hidden), 20 different rows of data incl. a large-magnitude one. + let dim = 2048usize; + let w: Vec<f32> = (0..dim).map(|_| lcg(&mut seed) * 4.0 + 1.0).collect(); + let mut rms_worst = 0.0f64; + for trial in 0..20 { + let scale = if trial == 19 { 50.0 } else { 2.0 }; + let x: Vec<f32> = (0..dim).map(|_| lcg(&mut seed) * scale).collect(); + let (mut got, mut want) = (vec![0.0f32; dim], vec![0.0f32; dim]); + omega.rmsnorm(&mut got, &x, &w, 1e-5); + reference.rmsnorm(&mut want, &x, &w, 1e-5); + rms_worst = rms_worst.max(worst_tol_ratio(&got, &want)); + } + println!("PARITY rmsnorm 2048 worst err/tolerance = {rms_worst:.3e} (must be <= 1)"); + assert!(rms_worst <= 1.0, "rmsnorm outside tolerance"); + + // rope, 32 q heads + 4 kv heads of 64, several positions. + let (hd, nq, nkv, theta) = (64usize, 32usize, 4usize, 10000.0f32); + let mut rope_mismatch = 0usize; + for pos in [0usize, 1, 2, 37, 511, 1500, 2047] { + let q0: Vec<f32> = (0..nq * hd).map(|_| lcg(&mut seed) * 3.0).collect(); + let k0: Vec<f32> = (0..nkv * hd).map(|_| lcg(&mut seed) * 3.0).collect(); + let (mut qg, mut kg) = (q0.clone(), k0.clone()); + let (mut qw, mut kw) = (q0.clone(), k0.clone()); + omega.apply_rope(&mut qg, &mut kg, pos, hd, nq, nkv, theta); + reference.apply_rope(&mut qw, &mut kw, pos, hd, nq, nkv, theta); + rope_mismatch += qg + .iter() + .zip(&qw) + .chain(kg.iter().zip(&kw)) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); + } + println!("PARITY rope 32+4 heads x 64, 7 positions: bit mismatches = {rope_mismatch}"); + assert_eq!(rope_mismatch, 0, "rope must be bit-exact"); + + // swiglu, n = 5632 (intermediate), gate in a wide range. + let n = 5632usize; + let mut sw_worst = 0.0f64; + for _ in 0..10 { + let gate: Vec<f32> = (0..n).map(|_| lcg(&mut seed) * 16.0).collect(); + let up: Vec<f32> = (0..n).map(|_| lcg(&mut seed) * 4.0).collect(); + let (mut got, mut want) = (vec![0.0f32; n], vec![0.0f32; n]); + omega.swiglu(&mut got, &gate, &up); + reference.swiglu(&mut want, &gate, &up); + sw_worst = sw_worst.max(worst_tol_ratio(&got, &want)); + } + println!("PARITY swiglu 5632 worst err/tolerance = {sw_worst:.3e} (must be <= 1)"); + assert!(sw_worst <= 1.0, "swiglu outside tolerance"); + + assert_eq!(omega.fallback_count(), 0, "{}", omega.last_error()); + assert_eq!(omega.chip_errors(), 0, "{}", omega.last_error()); + println!("PARITY elementwise {}", omega.op_report().line()); +} + +/// Diagnostic for the cut-3c finding: elementwise launches after the matmul device is +/// open. Run with AIEN_DEV_FALLBACK=1 so a failure is reported instead of a strict panic. +#[test] +#[ignore = "chip diagnostic: heavy queue only"] +fn chip_mixed_matmul_then_elementwise() { + let omega = OmegaGb10Backend::new(); + assert!(omega.is_available(), "native build required"); + let mut seed = 4242u32; + let (k, n) = (256usize, 64usize); + let w: Vec<f32> = (0..n * k).map(|_| lcg(&mut seed)).collect(); + let x: Vec<f32> = (0..k).map(|_| lcg(&mut seed)).collect(); + let mut out = vec![0.0f32; n]; + let wn: Vec<f32> = (0..256).map(|_| lcg(&mut seed)).collect(); + let mut no = vec![0.0f32; 256]; + omega.rmsnorm(&mut no, &x, &wn, 1e-5); + println!( + "MIXED rmsnorm before matmul: chip_errors={}", + omega.chip_errors() + ); + omega.matmul_vec(&mut out, &x, &w, n, k); + println!("MIXED matmul: chip_errors={}", omega.chip_errors()); + omega.rmsnorm(&mut no, &x, &wn, 1e-5); + println!( + "MIXED rmsnorm after matmul: chip_errors={} last_error={}", + omega.chip_errors(), + omega.last_error() + ); +} diff --git a/crates/aien-inference-runtime/tests/strict_real_model.rs b/crates/aien-inference-runtime/tests/strict_real_model.rs index f2930e3f..ecd5717f 100644 --- a/crates/aien-inference-runtime/tests/strict_real_model.rs +++ b/crates/aien-inference-runtime/tests/strict_real_model.rs @@ -223,6 +223,25 @@ fn omega_vs_reference_real_model() { println!("OMEGA_GATE {}", report.line()); let fallback_count = om.transformer.tensor_backend.fallback_count(); println!("OMEGA_GATE tokens_match={}", cpu_text == om_text); + for op in [ + "matmul_vec", + "matmul_batch", + "compute_logits", + "rmsnorm", + "apply_rope", + "swiglu", + ] { + assert!( + report.native_ops.iter().any(|n| n == op), + "{op} not in the native mask: {}", + report.line() + ); + } + assert!( + report.native_fallbacks.is_empty(), + "native fallbacks: {}", + report.line() + ); let mut receipt = StrictModelReceipt { checkpoint_path: model_path.display().to_string(), diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs index 3ec850cb..7abdb5df 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -1,5 +1,5 @@ //! Raw declarations, written by hand from omega `src/omega_gpu_matmul_api.h` -//! at the commit pinned in `omega.lock` (5e29b82). Nothing generated. +//! at the commit pinned in `omega.lock` (2636409). Nothing generated. //! Includes the resident-weights handles added by omega FB-1 cut 1b. use std::os::raw::{c_char, c_int}; @@ -135,3 +135,78 @@ extern "C" { pub fn omega_gpu_matmul_is_blocked() -> c_int; pub fn omega_gpu_device_close(); } + +// ---- omega `src/omega_gpu_elementwise_api.h` (FB-1 cut 4, pinned 2636409) ---- +pub const OMEGA_GPU_EW_OK: c_int = 0; +pub const OMEGA_GPU_EW_BAD_ARGS: c_int = -1; +pub const OMEGA_GPU_EW_TOO_LARGE: c_int = -2; +pub const OMEGA_GPU_EW_CODEGEN_FAIL: c_int = -3; +pub const OMEGA_GPU_EW_CHIP_FAIL: c_int = -4; +pub const OMEGA_GPU_EW_UNWRITTEN: c_int = -5; + +/// Mirrors `OmegaGpuEwInfo` field for field, same order. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct OmegaGpuEwInfo { + pub chip_calls: u32, + pub elapsed_ns: u64, + pub completion_marker: u32, + pub unwritten_words: u32, + pub kernel_cache_hit: bool, + pub gpr_count: u32, + pub insn_count: u32, + pub threads_per_cta: u32, + pub ctas_last_launch: u32, + pub target_chip: [c_char; 64], + pub sm_architecture: u32, + pub call_ns: u64, +} + +impl OmegaGpuEwInfo { + pub fn zeroed() -> Self { + Self { + chip_calls: 0, + elapsed_ns: 0, + completion_marker: 0, + unwritten_words: 0, + kernel_cache_hit: false, + gpr_count: 0, + insn_count: 0, + threads_per_cta: 0, + ctas_last_launch: 0, + target_chip: [0; 64], + sm_architecture: 0, + call_ns: 0, + } + } +} + +#[cfg(has_omega_gpu)] +extern "C" { + pub fn omega_gpu_rmsnorm_f32( + rows: u32, + dim: u32, + x: *const f32, + weight: *const f32, + eps: f32, + out: *mut f32, + info: *mut OmegaGpuEwInfo, + ) -> c_int; + pub fn omega_gpu_rope_f32( + heads: u32, + head_dim: u32, + v: *const f32, + cos_half: *const f32, + sin_half: *const f32, + out: *mut f32, + info: *mut OmegaGpuEwInfo, + ) -> c_int; + pub fn omega_gpu_swiglu_f32( + n: u32, + gate: *const f32, + up: *const f32, + out: *mut f32, + info: *mut OmegaGpuEwInfo, + ) -> c_int; + pub fn omega_gpu_elementwise_rc_name(rc: c_int) -> *const c_char; +} diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 8e7d1f02..382ec8c2 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -46,7 +46,7 @@ impl fmt::Display for OmegaGpuError { expected, got, } => write!(f, "{what}: expected {expected} elements, got {got}"), - Self::Rc { rc, name } => write!(f, "omega_gpu_matmul rc={rc} ({name})"), + Self::Rc { rc, name } => write!(f, "omega_gpu rc={rc} ({name})"), } } } @@ -345,3 +345,154 @@ pub fn is_blocked() -> bool { #[cfg(not(has_omega_gpu))] false } + +// ---- native elementwise ops (omega FB-1 cut 4) ---- + +pub use ffi::OmegaGpuEwInfo; + +/// Name of an elementwise return code (omega's table when native). +pub fn ew_rc_name(rc: i32) -> String { + #[cfg(has_omega_gpu)] + { + // SAFETY: returns a pointer to a static NUL-terminated string. + let p = unsafe { ffi::omega_gpu_elementwise_rc_name(rc) }; + if !p.is_null() { + // SAFETY: non-null, static, NUL-terminated. + return unsafe { std::ffi::CStr::from_ptr(p) } + .to_string_lossy() + .into_owned(); + } + } + match rc { + ffi::OMEGA_GPU_EW_OK => "OK", + ffi::OMEGA_GPU_EW_BAD_ARGS => "BAD_ARGS", + ffi::OMEGA_GPU_EW_TOO_LARGE => "TOO_LARGE", + ffi::OMEGA_GPU_EW_CODEGEN_FAIL => "CODEGEN_FAIL", + ffi::OMEGA_GPU_EW_CHIP_FAIL => "CHIP_FAIL", + ffi::OMEGA_GPU_EW_UNWRITTEN => "UNWRITTEN", + _ => "UNKNOWN", + } + .to_string() +} + +#[cfg(has_omega_gpu)] +fn ew_finish(rc: i32, info: OmegaGpuEwInfo) -> Result<OmegaGpuEwInfo, OmegaGpuError> { + if rc == ffi::OMEGA_GPU_EW_OK { + Ok(info) + } else { + Err(OmegaGpuError::Rc { + rc, + name: ew_rc_name(rc), + }) + } +} + +fn ew_dim(v: usize) -> Result<u32, OmegaGpuError> { + u32::try_from(v).map_err(|_| OmegaGpuError::Rc { + rc: ffi::OMEGA_GPU_EW_TOO_LARGE, + name: ew_rc_name(ffi::OMEGA_GPU_EW_TOO_LARGE), + }) +} + +/// `out[r*dim+i] = x[r*dim+i] * scale_r * weight[i]`, `scale_r = 1/sqrt(mean(x^2)+eps)`. +/// omega requires `dim % 128 == 0` and `dim <= 16384`; otherwise `Rc { rc: -1 | -2 }`. +pub fn rmsnorm_f32( + rows: usize, + dim: usize, + x: &[f32], + weight: &[f32], + eps: f32, + out: &mut [f32], +) -> Result<OmegaGpuEwInfo, OmegaGpuError> { + check_len("x", rows * dim, x.len())?; + check_len("weight", dim, weight.len())?; + check_len("out", rows * dim, out.len())?; + let (ru, du) = (ew_dim(rows)?, ew_dim(dim)?); + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuEwInfo::zeroed(); + // SAFETY: lengths checked above; pointers valid for the call; info is an out-pointer. + let rc = unsafe { + ffi::omega_gpu_rmsnorm_f32( + ru, + du, + x.as_ptr(), + weight.as_ptr(), + eps, + out.as_mut_ptr(), + &mut info, + ) + }; + ew_finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (ru, du, eps); + Err(OmegaGpuError::Unavailable) + } +} + +/// Rotate `heads` heads of `head_dim` values (rotate_half pairing `i, i+head_dim/2`) with a +/// host-provided table of `head_dim/2` cos and sin values (same for every head). +/// `out` may not alias `v` in safe Rust; omega itself copies through its own buffers. +pub fn rope_f32( + heads: usize, + head_dim: usize, + v: &[f32], + cos_half: &[f32], + sin_half: &[f32], + out: &mut [f32], +) -> Result<OmegaGpuEwInfo, OmegaGpuError> { + check_len("v", heads * head_dim, v.len())?; + check_len("cos_half", head_dim / 2, cos_half.len())?; + check_len("sin_half", head_dim / 2, sin_half.len())?; + check_len("out", heads * head_dim, out.len())?; + let (hu, du) = (ew_dim(heads)?, ew_dim(head_dim)?); + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuEwInfo::zeroed(); + // SAFETY: lengths checked above; pointers valid for the call. + let rc = unsafe { + ffi::omega_gpu_rope_f32( + hu, + du, + v.as_ptr(), + cos_half.as_ptr(), + sin_half.as_ptr(), + out.as_mut_ptr(), + &mut info, + ) + }; + ew_finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (hu, du); + Err(OmegaGpuError::Unavailable) + } +} + +/// `out[i] = silu(gate[i]) * up[i]` for `i < n` (`n = gate.len()`, all three equal length). +pub fn swiglu_f32( + gate: &[f32], + up: &[f32], + out: &mut [f32], +) -> Result<OmegaGpuEwInfo, OmegaGpuError> { + check_len("up", gate.len(), up.len())?; + check_len("out", gate.len(), out.len())?; + let nu = ew_dim(gate.len())?; + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuEwInfo::zeroed(); + // SAFETY: lengths checked equal; pointers valid for the call. + let rc = unsafe { + ffi::omega_gpu_swiglu_f32(nu, gate.as_ptr(), up.as_ptr(), out.as_mut_ptr(), &mut info) + }; + ew_finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = nu; + Err(OmegaGpuError::Unavailable) + } +} diff --git a/crates/aien-omega-gpu/tests/parity.rs b/crates/aien-omega-gpu/tests/parity.rs index eb2f7ed3..0d752d94 100644 --- a/crates/aien-omega-gpu/tests/parity.rs +++ b/crates/aien-omega-gpu/tests/parity.rs @@ -37,7 +37,8 @@ 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("5e29b82")); + // The build reads omega.lock; the constant must be exactly that file's sha. + assert_eq!(PINNED_OMEGA_SHA, include_str!("../../../omega.lock").trim()); } #[test] diff --git a/omega.lock b/omega.lock index b195cb95..49c20dca 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -5e29b826cce3c18e891c114a616317df2939af6c +6b940faa9df2baffa7d38ec3cafdf4a55fd91289