aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-omega-moe / src / lib.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Safe Rust wrapper over omega's column-window matmul for mixture-of-experts weights |
| 17 | //! (`src/omega_gpu_moe_api.h`, OWN-30B cut 2, no CUDA). |
| 18 | //! |
| 19 | //! One resident bf16 tensor holds every expert's projection side by side along N; a call |
| 20 | //! multiplies the activation rows by the column windows of the selected experts only, with the |
| 21 | //! same chip-proven kernel as the whole-tensor matmul (B is tile-major, so a window that starts on |
| 22 | //! a column tile is the kernel with its B base advanced). Conventions as in `aien-omega-gpu`: |
| 23 | //! row-major, `C[m x cols] = A[m x k] * B[:, col0 .. col0 + cols)`, f32 out, `a` rounded to bf16. |
| 24 | //! |
| 25 | //! Alignment rule (omega refuses otherwise, `BAD_ARGS`): `col0 % 8 == 0`, `1 <= cols`, |
| 26 | //! `col0 + cols <= n`, `1 <= m <= 8192`, at most [`MAX_WINDOWS`] windows per call. |
| 27 | //! Without the native library (`is_native()` false) every call returns `Unavailable`. |
| 28 | #[cfg(has_omega_moe)] |
| 29 | use aien_omega_gpu::OmegaGpuMatmulInfo; |
| 30 | use aien_omega_gpu::{rc_name, MatmulInfo, OmegaGpuError}; |
| 31 | use std::fmt; |
| 32 | |
| 33 | /// Column tile width: a window must start on a multiple of this (`OMEGA_GPU_MATMUL_TILE_N`). |
| 34 | pub const TILE_N: usize = 8; |
| 35 | /// Most windows one `windows_f32` call takes (`OMEGA_GPU_MOE_MAX_WINDOWS`). |
| 36 | pub const MAX_WINDOWS: usize = 64; |
| 37 | /// Row limit of one call (`OMEGA_BW_MATMUL_MAX_M`). |
| 38 | pub const MAX_ROWS: usize = 8192; |
| 39 | |
| 40 | /// True when the window API is linked (not the stub). |
| 41 | pub const fn is_native() -> bool { |
| 42 | cfg!(has_omega_moe) |
| 43 | } |
| 44 | |
| 45 | #[cfg(has_omega_moe)] |
| 46 | mod ffi { |
| 47 | use aien_omega_gpu::OmegaGpuMatmulInfo; |
| 48 | #[repr(C)] |
| 49 | pub struct OmegaGpuMoeTensor { |
| 50 | _private: [u8; 0], |
| 51 | } |
| 52 | extern "C" { |
| 53 | pub fn omega_gpu_moe_tensor_upload_bf16( |
| 54 | k: u32, |
| 55 | n: u32, |
| 56 | b: *const u16, |
| 57 | out: *mut *mut OmegaGpuMoeTensor, |
| 58 | ) -> i32; |
| 59 | pub fn omega_gpu_moe_tensor_free(t: *mut OmegaGpuMoeTensor); |
| 60 | pub fn omega_gpu_matmul_resident_window_f32( |
| 61 | m: u32, |
| 62 | a: *const f32, |
| 63 | t: *const OmegaGpuMoeTensor, |
| 64 | col0: u32, |
| 65 | cols: u32, |
| 66 | c: *mut f32, |
| 67 | info: *mut OmegaGpuMatmulInfo, |
| 68 | ) -> i32; |
| 69 | pub fn omega_gpu_matmul_resident_windows_f32( |
| 70 | m: u32, |
| 71 | a: *const f32, |
| 72 | t: *const OmegaGpuMoeTensor, |
| 73 | nwin: u32, |
| 74 | col0: *const u32, |
| 75 | cols: u32, |
| 76 | c: *mut f32, |
| 77 | info: *mut OmegaGpuMatmulInfo, |
| 78 | ) -> i32; |
| 79 | pub fn omega_gpu_moe_reserve( |
| 80 | max_rows: u32, |
| 81 | max_k: u32, |
| 82 | max_cols: u32, |
| 83 | kernel_slots: u32, |
| 84 | ) -> i32; |
| 85 | pub fn omega_gpu_moe_prepare(m: u32, k: u32, cols: u32) -> i32; |
| 86 | pub fn omega_gpu_moe_seal(on: i32); |
| 87 | pub fn omega_gpu_moe_unreserve(); |
| 88 | pub fn omega_gpu_moe_cache_clear(); |
| 89 | pub fn omega_gpu_moe_set_cta_budget(ctas: u32); |
| 90 | pub fn omega_gpu_moe_cta_budget() -> u32; |
| 91 | pub fn omega_gpu_moe_window_byte_offset(kp: u32, col0: u32) -> u64; |
| 92 | pub fn omega_gpu_moe_test_set_mutant(on: i32); |
| 93 | pub fn omega_gpu_moe_test_set_window_skew(tiles: i32); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn rc_err(rc: i32) -> OmegaGpuError { |
| 98 | OmegaGpuError::Rc { |
| 99 | rc, |
| 100 | name: rc_name(rc), |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn dim(v: usize) -> Result<u32, OmegaGpuError> { |
| 105 | u32::try_from(v).map_err(|_| rc_err(aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_TOO_LARGE)) |
| 106 | } |
| 107 | |
| 108 | fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> { |
| 109 | if expected == got { |
| 110 | Ok(()) |
| 111 | } else { |
| 112 | Err(OmegaGpuError::ShapeMismatch { |
| 113 | what, |
| 114 | expected, |
| 115 | got, |
| 116 | }) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// Checks the window alignment rule on the host, before any chip call, so a wrong offset is |
| 121 | /// refused by name even in the stub. |
| 122 | pub fn check_window(n: usize, col0: usize, cols: usize) -> Result<(), OmegaGpuError> { |
| 123 | if !col0.is_multiple_of(TILE_N) || cols == 0 || col0.checked_add(cols).is_none_or(|end| end > n) |
| 124 | { |
| 125 | return Err(OmegaGpuError::Rc { |
| 126 | rc: aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_BAD_ARGS, |
| 127 | name: format!( |
| 128 | "window col0={col0} cols={cols} refused: col0 must be a multiple of {TILE_N}, cols >= 1, col0 + cols <= n={n}" |
| 129 | ), |
| 130 | }); |
| 131 | } |
| 132 | Ok(()) |
| 133 | } |
| 134 | |
| 135 | /// A `k x n` bf16 tensor resident on the device until dropped, addressable by column window. |
| 136 | /// Not `Sync` (as `ResidentTensor`): callers serialise use behind a lock. |
| 137 | pub struct MoeTensor { |
| 138 | #[cfg(has_omega_moe)] |
| 139 | ptr: *mut ffi::OmegaGpuMoeTensor, |
| 140 | k: usize, |
| 141 | n: usize, |
| 142 | } |
| 143 | |
| 144 | // SAFETY: an owning handle to a device buffer; moved between threads, never shared unlocked. |
| 145 | unsafe impl Send for MoeTensor {} |
| 146 | |
| 147 | impl fmt::Debug for MoeTensor { |
| 148 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 149 | write!(f, "MoeTensor {{ k: {}, n: {} }}", self.k, self.n) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | impl MoeTensor { |
| 154 | /// Upload a row-major `k x n` matrix of bf16 bit patterns (no rounding). |
| 155 | pub fn upload_bf16(k: usize, n: usize, b: &[u16]) -> Result<Self, OmegaGpuError> { |
| 156 | let elems = k |
| 157 | .checked_mul(n) |
| 158 | .ok_or_else(|| rc_err(aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_TOO_LARGE))?; |
| 159 | check_len("b", elems, b.len())?; |
| 160 | let (ku, nu) = (dim(k)?, dim(n)?); |
| 161 | #[cfg(has_omega_moe)] |
| 162 | { |
| 163 | let mut ptr: *mut ffi::OmegaGpuMoeTensor = std::ptr::null_mut(); |
| 164 | // SAFETY: b has k*n elements (checked); ptr is a valid out-pointer. |
| 165 | let rc = unsafe { ffi::omega_gpu_moe_tensor_upload_bf16(ku, nu, b.as_ptr(), &mut ptr) }; |
| 166 | if rc != aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_OK || ptr.is_null() { |
| 167 | return Err(rc_err(if rc == 0 { |
| 168 | aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_BAD_ARGS |
| 169 | } else { |
| 170 | rc |
| 171 | })); |
| 172 | } |
| 173 | Ok(Self { ptr, k, n }) |
| 174 | } |
| 175 | #[cfg(not(has_omega_moe))] |
| 176 | { |
| 177 | let _ = (ku, nu); |
| 178 | Err(OmegaGpuError::Unavailable) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | pub fn k(&self) -> usize { |
| 183 | self.k |
| 184 | } |
| 185 | |
| 186 | pub fn n(&self) -> usize { |
| 187 | self.n |
| 188 | } |
| 189 | |
| 190 | /// `c[m x cols] = a[m x k] * self[:, col0 .. col0 + cols)`. |
| 191 | pub fn window_f32( |
| 192 | &self, |
| 193 | m: usize, |
| 194 | a: &[f32], |
| 195 | col0: usize, |
| 196 | cols: usize, |
| 197 | c: &mut [f32], |
| 198 | ) -> Result<MatmulInfo, OmegaGpuError> { |
| 199 | check_window(self.n, col0, cols)?; |
| 200 | check_len("a", m * self.k, a.len())?; |
| 201 | check_len("c", m * cols, c.len())?; |
| 202 | let (mu, c0, cw) = (dim(m)?, dim(col0)?, dim(cols)?); |
| 203 | #[cfg(has_omega_moe)] |
| 204 | { |
| 205 | let mut info = OmegaGpuMatmulInfo::zeroed(); |
| 206 | // SAFETY: lengths checked; self.ptr is a live handle owned by self. |
| 207 | let rc = unsafe { |
| 208 | ffi::omega_gpu_matmul_resident_window_f32( |
| 209 | mu, |
| 210 | a.as_ptr(), |
| 211 | self.ptr, |
| 212 | c0, |
| 213 | cw, |
| 214 | c.as_mut_ptr(), |
| 215 | &mut info, |
| 216 | ) |
| 217 | }; |
| 218 | finish(rc, info) |
| 219 | } |
| 220 | #[cfg(not(has_omega_moe))] |
| 221 | { |
| 222 | let _ = (mu, c0, cw); |
| 223 | Err(OmegaGpuError::Unavailable) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// `windows.len()` windows of one width in one call: `c` holds the results back to back, |
| 228 | /// window `w` at `c[w * m * cols ..][.. m * cols]`. A is staged once. |
| 229 | pub fn windows_f32( |
| 230 | &self, |
| 231 | m: usize, |
| 232 | a: &[f32], |
| 233 | col0s: &[u32], |
| 234 | cols: usize, |
| 235 | c: &mut [f32], |
| 236 | ) -> Result<MatmulInfo, OmegaGpuError> { |
| 237 | if col0s.is_empty() || col0s.len() > MAX_WINDOWS { |
| 238 | return Err(OmegaGpuError::Rc { |
| 239 | rc: aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_BAD_ARGS, |
| 240 | name: format!("{} windows, allowed 1..={MAX_WINDOWS}", col0s.len()), |
| 241 | }); |
| 242 | } |
| 243 | for &c0 in col0s { |
| 244 | check_window(self.n, c0 as usize, cols)?; |
| 245 | } |
| 246 | check_len("a", m * self.k, a.len())?; |
| 247 | check_len("c", col0s.len() * m * cols, c.len())?; |
| 248 | let (mu, nw, cw) = (dim(m)?, dim(col0s.len())?, dim(cols)?); |
| 249 | #[cfg(has_omega_moe)] |
| 250 | { |
| 251 | let mut info = OmegaGpuMatmulInfo::zeroed(); |
| 252 | // SAFETY: lengths checked; col0s has nw entries; self.ptr is live. |
| 253 | let rc = unsafe { |
| 254 | ffi::omega_gpu_matmul_resident_windows_f32( |
| 255 | mu, |
| 256 | a.as_ptr(), |
| 257 | self.ptr, |
| 258 | nw, |
| 259 | col0s.as_ptr(), |
| 260 | cw, |
| 261 | c.as_mut_ptr(), |
| 262 | &mut info, |
| 263 | ) |
| 264 | }; |
| 265 | finish(rc, info) |
| 266 | } |
| 267 | #[cfg(not(has_omega_moe))] |
| 268 | { |
| 269 | let _ = (mu, nw, cw); |
| 270 | Err(OmegaGpuError::Unavailable) |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | impl Drop for MoeTensor { |
| 276 | fn drop(&mut self) { |
| 277 | #[cfg(has_omega_moe)] |
| 278 | // SAFETY: ptr came from a successful upload and is freed exactly once. |
| 279 | unsafe { |
| 280 | ffi::omega_gpu_moe_tensor_free(self.ptr) |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | #[cfg(has_omega_moe)] |
| 286 | fn finish(rc: i32, info: OmegaGpuMatmulInfo) -> Result<MatmulInfo, OmegaGpuError> { |
| 287 | if rc == aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_OK { |
| 288 | Ok(MatmulInfo { raw: info }) |
| 289 | } else { |
| 290 | Err(rc_err(rc)) |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | /// Serving reservation for the window API (its own staging buffers and kernel cache; a server |
| 295 | /// reserves the whole-tensor API too). Stub: `Unavailable`. |
| 296 | pub fn reserve( |
| 297 | max_rows: u32, |
| 298 | max_k: u32, |
| 299 | max_cols: u32, |
| 300 | kernel_slots: u32, |
| 301 | ) -> Result<(), OmegaGpuError> { |
| 302 | #[cfg(has_omega_moe)] |
| 303 | { |
| 304 | // SAFETY: plain integers; omega takes its own lock. |
| 305 | let rc = unsafe { ffi::omega_gpu_moe_reserve(max_rows, max_k, max_cols, kernel_slots) }; |
| 306 | if rc == 0 { |
| 307 | Ok(()) |
| 308 | } else { |
| 309 | Err(rc_err(rc)) |
| 310 | } |
| 311 | } |
| 312 | #[cfg(not(has_omega_moe))] |
| 313 | { |
| 314 | let _ = (max_rows, max_k, max_cols, kernel_slots); |
| 315 | Err(OmegaGpuError::Unavailable) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | /// Build and pin the kernel a call of `m` rows over `k` x `cols` windows uses. |
| 320 | pub fn prepare(m: u32, k: u32, cols: u32) -> Result<(), OmegaGpuError> { |
| 321 | #[cfg(has_omega_moe)] |
| 322 | { |
| 323 | // SAFETY: plain integers; omega takes its own lock. |
| 324 | let rc = unsafe { ffi::omega_gpu_moe_prepare(m, k, cols) }; |
| 325 | if rc == 0 { |
| 326 | Ok(()) |
| 327 | } else { |
| 328 | Err(rc_err(rc)) |
| 329 | } |
| 330 | } |
| 331 | #[cfg(not(has_omega_moe))] |
| 332 | { |
| 333 | let _ = (m, k, cols); |
| 334 | Err(OmegaGpuError::Unavailable) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | /// Sealed: an unprepared kernel is refused, never built. No-op in the stub. |
| 339 | pub fn seal(on: bool) { |
| 340 | #[cfg(has_omega_moe)] |
| 341 | // SAFETY: no pointers; omega takes its own lock. |
| 342 | unsafe { |
| 343 | ffi::omega_gpu_moe_seal(on as i32) |
| 344 | } |
| 345 | #[cfg(not(has_omega_moe))] |
| 346 | let _ = on; |
| 347 | } |
| 348 | |
| 349 | /// Lift the reservation. No-op in the stub. |
| 350 | pub fn unreserve() { |
| 351 | #[cfg(has_omega_moe)] |
| 352 | // SAFETY: no arguments. |
| 353 | unsafe { |
| 354 | ffi::omega_gpu_moe_unreserve() |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /// Drop every cached window kernel. No-op in the stub. |
| 359 | pub fn cache_clear() { |
| 360 | #[cfg(has_omega_moe)] |
| 361 | // SAFETY: no arguments. |
| 362 | unsafe { |
| 363 | ffi::omega_gpu_moe_cache_clear() |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | /// CTA budget per window launch (0 restores omega's default; clears the kernel cache). |
| 368 | pub fn set_cta_budget(ctas: u32) { |
| 369 | #[cfg(has_omega_moe)] |
| 370 | // SAFETY: plain integer. |
| 371 | unsafe { |
| 372 | ffi::omega_gpu_moe_set_cta_budget(ctas) |
| 373 | } |
| 374 | #[cfg(not(has_omega_moe))] |
| 375 | let _ = ctas; |
| 376 | } |
| 377 | |
| 378 | pub fn cta_budget() -> Option<u32> { |
| 379 | #[cfg(has_omega_moe)] |
| 380 | // SAFETY: reads one value. |
| 381 | return Some(unsafe { ffi::omega_gpu_moe_cta_budget() }); |
| 382 | #[cfg(not(has_omega_moe))] |
| 383 | None |
| 384 | } |
| 385 | |
| 386 | /// Byte offset of column tile `col0 / 8` inside a packed tensor of padded depth `kp`: omega's |
| 387 | /// own arithmetic when native, the same formula (`(col0 / 8) * kp * 8 * 2`) otherwise. |
| 388 | pub fn window_byte_offset(kp: u32, col0: u32) -> u64 { |
| 389 | #[cfg(has_omega_moe)] |
| 390 | // SAFETY: pure host arithmetic. |
| 391 | return unsafe { ffi::omega_gpu_moe_window_byte_offset(kp, col0) }; |
| 392 | #[cfg(not(has_omega_moe))] |
| 393 | { |
| 394 | (col0 as u64 / TILE_N as u64) * kp as u64 * TILE_N as u64 * 2 |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | /// TEST ONLY: deliberately wrong window kernels (last K pass dropped). No-op in the stub. |
| 399 | pub fn test_set_mutant(on: bool) { |
| 400 | #[cfg(has_omega_moe)] |
| 401 | // SAFETY: plain integer. |
| 402 | unsafe { |
| 403 | ffi::omega_gpu_moe_test_set_mutant(on as i32) |
| 404 | } |
| 405 | #[cfg(not(has_omega_moe))] |
| 406 | let _ = on; |
| 407 | } |
| 408 | |
| 409 | /// TEST ONLY: move every window's B base by `tiles` column tiles (the wrong-window control). |
| 410 | pub fn test_set_window_skew(tiles: i32) { |
| 411 | #[cfg(has_omega_moe)] |
| 412 | // SAFETY: plain integer. |
| 413 | unsafe { |
| 414 | ffi::omega_gpu_moe_test_set_window_skew(tiles) |
| 415 | } |
| 416 | #[cfg(not(has_omega_moe))] |
| 417 | let _ = tiles; |
| 418 | } |
| 419 | |
| 420 | #[cfg(test)] |
| 421 | mod tests { |
| 422 | use super::*; |
| 423 | |
| 424 | #[test] |
| 425 | fn window_rule_is_checked_on_the_host() { |
| 426 | assert!(check_window(262144, 0, 2048).is_ok()); |
| 427 | assert!(check_window(262144, 127 * 2048, 2048).is_ok()); |
| 428 | assert!(check_window(196608, 5 * 1536, 1536).is_ok()); |
| 429 | assert!( |
| 430 | check_window(196608, 4, 8).is_err(), |
| 431 | "col0 not a tile multiple" |
| 432 | ); |
| 433 | assert!(check_window(196608, 0, 0).is_err(), "empty window"); |
| 434 | assert!(check_window(196608, 196608 - 8, 16).is_err(), "past n"); |
| 435 | } |
| 436 | |
| 437 | #[test] |
| 438 | fn stub_reports_unavailable() { |
| 439 | if !is_native() { |
| 440 | assert!(matches!( |
| 441 | MoeTensor::upload_bf16(8, 8, &[0; 64]), |
| 442 | Err(OmegaGpuError::Unavailable) |
| 443 | )); |
| 444 | assert_eq!(cta_budget(), None); |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | #[test] |
| 449 | fn byte_offset_formula() { |
| 450 | // tile-major: column tile t of a tensor with padded depth kp starts at t * kp * 8 elements. |
| 451 | assert_eq!(window_byte_offset(2048, 0), 0); |
| 452 | assert_eq!(window_byte_offset(2048, 1536), (1536 / 8) * 2048 * 8 * 2); |
| 453 | } |
| 454 | } |