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#176 (code only)
Apply it
git checkout -b patch-95c5a65122f4c5d3 5fdab70b943443a6e0b3f9a4a45438e632d11623 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/95c5a65122f4c5d3.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
176
6f2cafb3259145f55e43a7145c1b69a01875841e
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":176,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/176","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:12Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Cargo.lock b/Cargo.lock index b8e04796..cb100b27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -176,6 +176,10 @@ dependencies = [ "tokio", ] +[[package]] +name = "aien-omega-gpu" +version = "0.1.0" + [[package]] name = "aien-platform" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c33d0dcf..b9b804df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ members = [ "crates/aien-inference-service", "crates/aien-inference-runtime", "crates/cortex-path-m1", + "crates/aien-omega-gpu", "crates/aien-campaign-verifier", "crates/aien-proof", "crates/crumbs", diff --git a/crates/aien-omega-gpu/Cargo.toml b/crates/aien-omega-gpu/Cargo.toml new file mode 100644 index 00000000..9f571e78 --- /dev/null +++ b/crates/aien-omega-gpu/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "aien-omega-gpu" +version = "0.1.0" +edition = "2021" +authors = ["Drake Stapleton <aien@aienos.com>"] +description = "FFI to the native (no CUDA) Omega GPU matmul engine, pinned by omega.lock" +license.workspace = true +build = "build.rs" + +[dependencies] diff --git a/crates/aien-omega-gpu/build.rs b/crates/aien-omega-gpu/build.rs new file mode 100644 index 00000000..538f641c --- /dev/null +++ b/crates/aien-omega-gpu/build.rs @@ -0,0 +1,101 @@ +//! Links `libomega_gpu.a` from the omega commit pinned in `omega.lock`. +//! +//! Offline by design: nothing is downloaded and no CUDA/nvcc is used. Order: +//! 1. `AIEN_FORCE_CPU_STUB=1` -> stub (CI without the chip). +//! 2. `AIEN_OMEGA_GPU_LIB=<file>` -> link that prebuilt archive (not sha-checked). +//! 3. `AIEN_OMEGA_DIR=<checkout>` -> its HEAD must equal omega.lock; built with +//! `make libomega_gpu` into OUT_DIR. `AIEN_PHYSICS_DIR` (default `<omega>/../physics`) +//! is passed as PHYSICS_DIR; omega's own physics.lock check still runs. +//! 4. otherwise -> stub, with a build warning. +//! +//! `cfg(has_omega_gpu)` is set only when the real library is linked. +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn main() { + println!("cargo:rustc-check-cfg=cfg(has_omega_gpu)"); + for v in [ + "AIEN_FORCE_CPU_STUB", + "AIEN_OMEGA_GPU_LIB", + "AIEN_OMEGA_DIR", + "AIEN_PHYSICS_DIR", + ] { + println!("cargo:rerun-if-env-changed={v}"); + } + let lock_path = Path::new(&env("CARGO_MANIFEST_DIR")).join("../../omega.lock"); + println!("cargo:rerun-if-changed={}", lock_path.display()); + let pinned = std::fs::read_to_string(&lock_path) + .unwrap_or_else(|e| panic!("cannot read {}: {e}", lock_path.display())) + .trim() + .to_string(); + assert!( + pinned.len() == 40 && pinned.bytes().all(|b| b.is_ascii_hexdigit()), + "omega.lock must hold one full 40-hex sha" + ); + println!("cargo:rustc-env=AIEN_OMEGA_PINNED_SHA={pinned}"); + + if std::env::var("AIEN_FORCE_CPU_STUB").as_deref() == Ok("1") { + return; + } + if let Ok(lib) = std::env::var("AIEN_OMEGA_GPU_LIB") { + let lib = PathBuf::from(lib); + assert!( + lib.is_file(), + "AIEN_OMEGA_GPU_LIB {} is not a file", + lib.display() + ); + link(&lib); + return; + } + let Ok(dir) = std::env::var("AIEN_OMEGA_DIR") else { + println!("cargo:warning=aien-omega-gpu: no AIEN_OMEGA_DIR or AIEN_OMEGA_GPU_LIB, building the CPU stub"); + return; + }; + let dir = PathBuf::from(dir); + let head = Command::new("git") + .arg("-C") + .arg(&dir) + .args(["rev-parse", "HEAD"]) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default(); + assert!( + head == pinned, + "omega checkout {} is at '{head}', omega.lock pins {pinned}", + dir.display() + ); + let physics = std::env::var("AIEN_PHYSICS_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| dir.join("../physics")); + let out = PathBuf::from(env("OUT_DIR")).join("omega-build"); + std::fs::create_dir_all(&out).expect("create omega build dir"); + let status = Command::new("make") + .current_dir(&dir) + .arg(format!("OUT_DIR={}", out.display())) + .arg(format!("PHYSICS_DIR={}", physics.display())) + .arg(out.join("libomega_gpu.a")) + .status() + .expect("run make"); + assert!( + status.success(), + "make libomega_gpu failed in {}", + dir.display() + ); + link(&out.join("libomega_gpu.a")); +} + +fn link(lib: &Path) { + let dir = lib.parent().expect("lib has a parent dir"); + println!("cargo:rustc-link-search=native={}", dir.display()); + println!("cargo:rustc-link-lib=static=omega_gpu"); + println!("cargo:rustc-link-lib=dylib=pthread"); + println!("cargo:rustc-link-lib=dylib=m"); + println!("cargo:rerun-if-changed={}", lib.display()); + println!("cargo:rustc-cfg=has_omega_gpu"); +} + +fn env(k: &str) -> String { + std::env::var(k).unwrap_or_else(|_| panic!("{k} not set")) +} diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs new file mode 100644 index 00000000..7476815b --- /dev/null +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -0,0 +1,88 @@ +//! 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. +use std::os::raw::{c_char, c_int}; + +pub const OMEGA_GPU_MATMUL_OK: c_int = 0; +pub const OMEGA_GPU_MATMUL_BAD_ARGS: c_int = -1; +pub const OMEGA_GPU_MATMUL_TOO_LARGE: c_int = -2; +pub const OMEGA_GPU_MATMUL_CODEGEN_FAIL: c_int = -3; +pub const OMEGA_GPU_MATMUL_CHIP_FAIL: c_int = -4; +pub const OMEGA_GPU_MATMUL_PARITY_FAIL: c_int = -5; + +pub const OMEGA_GPU_MATMUL_TILE_M: u32 = 16; +pub const OMEGA_GPU_MATMUL_TILE_N: u32 = 8; +pub const OMEGA_GPU_MATMUL_TILE_K: u32 = 16; +pub const OMEGA_GPU_MATMUL_MAX_CTAS: u32 = 64; + +/// Mirrors `OmegaGpuMatmulInfo` field for field, same order. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct OmegaGpuMatmulInfo { + pub m: u32, + pub k: u32, + pub n: u32, + pub padded_m: u32, + pub padded_n: u32, + pub k_slices: u32, + pub chip_calls: u32, + pub rows_per_call: u32, + pub elapsed_ns: u64, + pub max_abs_err: f32, + pub max_rel_err: f32, + pub mismatch_count: usize, + pub parity_verified: bool, + pub completion_marker: u32, + pub kernel_cache_hit: bool, + pub target_chip: [c_char; 64], + pub sm_architecture: u32, +} + +impl OmegaGpuMatmulInfo { + pub fn zeroed() -> Self { + Self { + m: 0, + k: 0, + n: 0, + padded_m: 0, + padded_n: 0, + k_slices: 0, + chip_calls: 0, + rows_per_call: 0, + elapsed_ns: 0, + max_abs_err: 0.0, + max_rel_err: 0.0, + mismatch_count: 0, + parity_verified: false, + completion_marker: 0, + kernel_cache_hit: false, + target_chip: [0; 64], + sm_architecture: 0, + } + } +} + +#[cfg(has_omega_gpu)] +extern "C" { + pub fn omega_gpu_matmul_bf16( + m: u32, + k: u32, + n: u32, + a: *const u16, + b: *const u16, + c: *mut f32, + info: *mut OmegaGpuMatmulInfo, + ) -> c_int; + pub fn omega_gpu_matmul_f32( + m: u32, + k: u32, + n: u32, + a: *const f32, + b: *const f32, + c: *mut f32, + info: *mut OmegaGpuMatmulInfo, + ) -> c_int; + pub fn omega_gpu_matmul_rc_name(rc: c_int) -> *const c_char; + pub fn omega_gpu_matmul_cache_clear(); +} diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs new file mode 100644 index 00000000..1cf1f183 --- /dev/null +++ b/crates/aien-omega-gpu/src/lib.rs @@ -0,0 +1,216 @@ +//! Safe Rust wrapper over omega's native GPU matmul (no CUDA). +//! +//! Built against the omega commit in `omega.lock`. With `cfg(has_omega_gpu)` the +//! real library is linked; otherwise (`AIEN_FORCE_CPU_STUB=1`, or no omega checkout +//! given) every chip call returns [`OmegaGpuError::Unavailable`], so CI passes +//! without the chip. Only the API on omega main at the pinned commit is wrapped. +//! +//! 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`. +pub mod ffi; + +use std::fmt; + +pub use ffi::OmegaGpuMatmulInfo; + +/// Omega commit this crate was built against (from `omega.lock`). +pub const PINNED_OMEGA_SHA: &str = env!("AIEN_OMEGA_PINNED_SHA"); + +/// True when the real native library is linked (not the stub). +pub const fn is_native() -> bool { + cfg!(has_omega_gpu) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OmegaGpuError { + /// Stub build: no native library linked. + Unavailable, + /// A slice length does not match the stated shape (caught before the C call). + ShapeMismatch { + what: &'static str, + expected: usize, + got: usize, + }, + /// Omega returned a non-zero code; `name` is `omega_gpu_matmul_rc_name(rc)`. + Rc { rc: i32, name: String }, +} + +impl fmt::Display for OmegaGpuError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unavailable => write!(f, "omega gpu unavailable (stub build)"), + Self::ShapeMismatch { + what, + expected, + got, + } => write!(f, "{what}: expected {expected} elements, got {got}"), + Self::Rc { rc, name } => write!(f, "omega_gpu_matmul rc={rc} ({name})"), + } + } +} + +impl std::error::Error for OmegaGpuError {} + +/// Name of a return code; the C function when native, the same table otherwise. +pub fn 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_matmul_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_MATMUL_OK => "OK", + ffi::OMEGA_GPU_MATMUL_BAD_ARGS => "BAD_ARGS", + ffi::OMEGA_GPU_MATMUL_TOO_LARGE => "TOO_LARGE", + ffi::OMEGA_GPU_MATMUL_CODEGEN_FAIL => "CODEGEN_FAIL", + ffi::OMEGA_GPU_MATMUL_CHIP_FAIL => "CHIP_FAIL", + ffi::OMEGA_GPU_MATMUL_PARITY_FAIL => "PARITY_FAIL", + _ => "UNKNOWN", + } + .to_string() +} + +/// Per-call receipt from omega (copy of `OmegaGpuMatmulInfo`). +#[derive(Debug, Clone)] +pub struct MatmulInfo { + pub raw: OmegaGpuMatmulInfo, +} + +impl MatmulInfo { + pub fn target_chip(&self) -> String { + let bytes: Vec<u8> = self + .raw + .target_chip + .iter() + .take_while(|&&c| c != 0) + .map(|c| c.to_ne_bytes()[0]) + .collect(); + String::from_utf8_lossy(&bytes).into_owned() + } +} + +fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> { + if expected == got { + Ok(()) + } else { + Err(OmegaGpuError::ShapeMismatch { + what, + expected, + got, + }) + } +} + +fn dims(m: usize, k: usize, n: usize) -> Result<(u32, u32, u32), OmegaGpuError> { + let conv = |v: usize| { + u32::try_from(v).map_err(|_| OmegaGpuError::Rc { + rc: ffi::OMEGA_GPU_MATMUL_TOO_LARGE, + name: rc_name(ffi::OMEGA_GPU_MATMUL_TOO_LARGE), + }) + }; + Ok((conv(m)?, conv(k)?, conv(n)?)) +} + +#[cfg(has_omega_gpu)] +fn finish(rc: i32, info: OmegaGpuMatmulInfo) -> Result<MatmulInfo, OmegaGpuError> { + if rc == ffi::OMEGA_GPU_MATMUL_OK { + Ok(MatmulInfo { raw: info }) + } else { + Err(OmegaGpuError::Rc { + rc, + name: rc_name(rc), + }) + } +} + +/// `c = a * b`, bf16 inputs (raw bits), f32 output. +pub fn matmul_bf16( + m: usize, + k: usize, + n: usize, + a: &[u16], + b: &[u16], + c: &mut [f32], +) -> Result<MatmulInfo, OmegaGpuError> { + check_len("a", m * k, a.len())?; + check_len("b", k * n, b.len())?; + check_len("c", m * n, c.len())?; + let (mu, ku, nu) = dims(m, k, n)?; + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuMatmulInfo::zeroed(); + // SAFETY: lengths checked above match m*k, k*n, m*n; pointers are valid + // for the call; info is a valid out-pointer. + let rc = unsafe { + ffi::omega_gpu_matmul_bf16( + mu, + ku, + nu, + a.as_ptr(), + b.as_ptr(), + c.as_mut_ptr(), + &mut info, + ) + }; + finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (mu, ku, nu); + Err(OmegaGpuError::Unavailable) + } +} + +/// `c = a * b`, f32 inputs rounded to bf16 on the host, f32 output. +pub fn matmul_f32( + m: usize, + k: usize, + n: usize, + a: &[f32], + b: &[f32], + c: &mut [f32], +) -> Result<MatmulInfo, OmegaGpuError> { + check_len("a", m * k, a.len())?; + check_len("b", k * n, b.len())?; + check_len("c", m * n, c.len())?; + let (mu, ku, nu) = dims(m, k, n)?; + #[cfg(has_omega_gpu)] + { + let mut info = OmegaGpuMatmulInfo::zeroed(); + // SAFETY: as in matmul_bf16. + let rc = unsafe { + ffi::omega_gpu_matmul_f32( + mu, + ku, + nu, + a.as_ptr(), + b.as_ptr(), + c.as_mut_ptr(), + &mut info, + ) + }; + finish(rc, info) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (mu, ku, nu); + Err(OmegaGpuError::Unavailable) + } +} + +/// Drop every cached kernel (tests; otherwise never needed). No-op in the stub. +pub fn cache_clear() { + #[cfg(has_omega_gpu)] + // SAFETY: takes no arguments; omega guards its cache with a mutex. + unsafe { + ffi::omega_gpu_matmul_cache_clear() + } +} diff --git a/crates/aien-omega-gpu/tests/parity.rs b/crates/aien-omega-gpu/tests/parity.rs new file mode 100644 index 00000000..1299d80d --- /dev/null +++ b/crates/aien-omega-gpu/tests/parity.rs @@ -0,0 +1,140 @@ +//! Host tests run everywhere (stub-aware). The chip parity test is #[ignore]d: +//! run it on the Spark through the heavy queue with a native build. +use aien_omega_gpu::*; + +fn lcg(s: &mut u32) -> f32 { + *s = s.wrapping_mul(1664525).wrapping_add(1013904223); + ((*s >> 8) as f32 / (1u32 << 24) as f32) - 0.5 +} + +/// Round to nearest even bf16, return the bits. +fn bf16_bits(f: f32) -> u16 { + let u = f.to_bits(); + if f.is_nan() { + return ((u >> 16) | 0x40) as u16; + } + let r = u.wrapping_add(0x7fff + ((u >> 16) & 1)); + (r >> 16) as u16 +} +fn bf16_val(b: u16) -> f32 { + f32::from_bits((b as u32) << 16) +} + +fn reference(m: usize, k: usize, n: usize, a: &[f32], b: &[f32]) -> Vec<f32> { + let mut c = vec![0f32; m * n]; + for i in 0..m { + for j in 0..n { + let mut s = 0f64; + for p in 0..k { + s += a[i * k + p] as f64 * b[p * n + j] as f64; + } + c[i * n + j] = s as f32; + } + } + c +} + +#[test] +fn lock_is_full_sha() { + assert_eq!(PINNED_OMEGA_SHA.len(), 40); + assert!(PINNED_OMEGA_SHA.starts_with("d0ca8ce")); +} + +#[test] +fn rc_names() { + assert_eq!(rc_name(0), "OK"); + assert_eq!(rc_name(-2), "TOO_LARGE"); + assert_eq!(rc_name(-5), "PARITY_FAIL"); + assert_eq!(rc_name(-99), "UNKNOWN"); +} + +#[test] +fn shape_mismatch_is_caught_before_ffi() { + let mut c = vec![0f32; 4]; + let e = matmul_f32(2, 2, 2, &[0.0; 3], &[0.0; 4], &mut c).unwrap_err(); + assert!(matches!(e, OmegaGpuError::ShapeMismatch { what: "a", .. })); +} + +#[test] +fn stub_reports_unavailable() { + if is_native() { + return; + } + let mut c = vec![0f32; 4]; + assert_eq!( + matmul_f32(2, 2, 2, &[0.0; 4], &[0.0; 4], &mut c).unwrap_err(), + OmegaGpuError::Unavailable + ); +} + +#[test] +fn native_refuses_bad_args_without_chip() { + if !is_native() { + return; + } + let mut c = vec![0f32; 0]; + match matmul_f32(0, 16, 16, &[], &[0.0; 256], &mut c).unwrap_err() { + OmegaGpuError::Rc { rc, name } => { + assert_eq!(rc, -1); + assert_eq!(name, "BAD_ARGS"); + } + e => panic!("unexpected {e}"), + } +} + +#[test] +#[ignore = "needs the GB10 chip: run through lanes.sh queue --heavy with a native build"] +fn chip_parity_f32_and_bf16() { + assert!( + is_native(), + "build with AIEN_OMEGA_DIR to link the chip library" + ); + let shapes = [ + (16, 16, 16), + (1, 64, 64), + (33, 40, 24), + (64, 256, 32), + (1, 1024, 128), + ]; + let mut seed = 12345u32; + for (m, k, n) in shapes { + let a: Vec<f32> = (0..m * k).map(|_| lcg(&mut seed)).collect(); + let b: Vec<f32> = (0..k * n).map(|_| lcg(&mut seed)).collect(); + // bf16 path: reference uses the bf16-rounded inputs + let ab: Vec<u16> = a.iter().map(|&x| bf16_bits(x)).collect(); + let bb: Vec<u16> = b.iter().map(|&x| bf16_bits(x)).collect(); + let ar: Vec<f32> = ab.iter().map(|&x| bf16_val(x)).collect(); + let br: Vec<f32> = bb.iter().map(|&x| bf16_val(x)).collect(); + let want = reference(m, k, n, &ar, &br); + let scale = (k as f32).sqrt() * 0.25 + 1e-3; // accumulation scale, inputs in [-0.5,0.5] + for (label, got, info) in [ + { + let mut c = vec![0f32; m * n]; + let i = matmul_bf16(m, k, n, &ab, &bb, &mut c).expect("bf16"); + ("bf16", c, i) + }, + { + let mut c = vec![0f32; m * n]; + let i = matmul_f32(m, k, n, &a, &b, &mut c).expect("f32"); + ("f32", c, i) + }, + ] { + let worst = got + .iter() + .zip(&want) + .map(|(g, w)| (g - w).abs()) + .fold(0f32, f32::max); + println!( + "CHIP_PARITY {label} {m}x{k}x{n} worst_abs={worst:e} scale={scale:e} chip_calls={} parity_verified={} chip={}", + info.raw.chip_calls, + info.raw.parity_verified, + info.target_chip() + ); + assert!(info.raw.parity_verified, "{label} {m}x{k}x{n}"); + assert!( + worst < 1e-5 * scale * 10.0, + "{label} {m}x{k}x{n} worst {worst}" + ); + } + } +} diff --git a/omega.lock b/omega.lock new file mode 100644 index 00000000..1eaee794 --- /dev/null +++ b/omega.lock @@ -0,0 +1 @@ +d0ca8cedee1a5494c10d8ae70c79621f3544a1c9