Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-omega-bf16/src/lib.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-omega-bf16 / src / lib.rs` 344 lines ยท 11410 bytes Raw Blame History 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 bf16 streaming GEMV (`src/omega_gpu_bf16_gemv_api.h`, 17 //! OWN-30B lm_head cut on the omega side; no CUDA). 18 //! 19 //! A tensor is an `[n][k]` bf16 matrix exactly as the checkpoint stores it (the lm_head is 20 //! `[vocab = 151936][hidden = 2048]`, no transpose), resident on the chip. One call is 21 //! `y[r] = sum_c W[r][c] * x[c]` in f32 with `x` f32 or bf16: one launch, deterministic 22 //! summation order (so the same input always gives the same logits). 23 //! 24 //! Rules omega refuses otherwise: `n >= 1`, `k % 256 == 0`, `256 <= k <= 16384`, and a NaN or 25 //! infinite bf16 weight is refused at upload. Without the native library (`is_native()` false) 26 //! every call returns `Unavailable`. 27 use aien_omega_gpu::OmegaGpuError; 28 use std::fmt; 29 30 /// Narrowest and widest `k` the kernel accepts, and its granule. 31 pub const MIN_K: usize = 256; 32 pub const MAX_K: usize = 16384; 33 pub const K_GRANULE: usize = 256; 34 35 /// True when the bf16 GEMV API is linked (not the stub). 36 pub const fn is_native() -> bool { 37 cfg!(has_omega_bf16) 38 } 39 40 /// Mirror of `OmegaGpuBf16Info`: what the chip did for one call. 41 #[repr(C)] 42 #[derive(Debug, Clone, Copy)] 43 pub struct Bf16Info { 44 pub n: u32, 45 pub k: u32, 46 pub rows_per_warp: u32, 47 pub warps_per_cta: u32, 48 pub depth: u32, 49 pub grid_x: u32, 50 pub steps: u32, 51 /// bf16 bytes the launch reads (`n * k * 2`). 52 pub weight_bytes: u64, 53 /// Chip submit-to-second-marker. 54 pub elapsed_ns: u64, 55 /// Whole API call. 56 pub call_ns: u64, 57 pub completion_marker: u32, 58 pub kernel_cache_hit: bool, 59 pub target_chip: [u8; 64], 60 pub sm_architecture: u32, 61 } 62 63 impl Default for Bf16Info { 64 fn default() -> Self { 65 // SAFETY: a plain C struct of integers, a bool and a byte array; all-zero is valid. 66 unsafe { std::mem::zeroed() } 67 } 68 } 69 70 #[cfg(has_omega_bf16)] 71 mod ffi { 72 use super::Bf16Info; 73 #[repr(C)] 74 pub struct OmegaGpuBf16Tensor { 75 _private: [u8; 0], 76 } 77 extern "C" { 78 pub fn omega_gpu_bf16_tensor_upload( 79 n: u32, 80 k: u32, 81 w_bf16: *const u16, 82 out: *mut *mut OmegaGpuBf16Tensor, 83 ) -> i32; 84 pub fn omega_gpu_bf16_tensor_free(t: *mut OmegaGpuBf16Tensor); 85 pub fn omega_gpu_bf16_gemv_f32( 86 t: *const OmegaGpuBf16Tensor, 87 x: *const f32, 88 y: *mut f32, 89 info: *mut Bf16Info, 90 ) -> i32; 91 pub fn omega_gpu_bf16_gemv_bf16( 92 t: *const OmegaGpuBf16Tensor, 93 x: *const u16, 94 y: *mut f32, 95 info: *mut Bf16Info, 96 ) -> i32; 97 pub fn omega_gpu_bf16_prepare(k: u32) -> i32; 98 pub fn omega_gpu_bf16_rc_name(rc: i32) -> *const std::os::raw::c_char; 99 pub fn omega_gpu_bf16_last_error() -> *const std::os::raw::c_char; 100 pub fn omega_gpu_bf16_test_set_mutant(mutant: i32); 101 } 102 } 103 104 #[cfg(has_omega_bf16)] 105 fn rc_err(rc: i32) -> OmegaGpuError { 106 // SAFETY: both return static NUL-terminated strings (or NULL for last_error). 107 let name = unsafe { 108 let n = ffi::omega_gpu_bf16_rc_name(rc); 109 let n = if n.is_null() { 110 String::from("?") 111 } else { 112 std::ffi::CStr::from_ptr(n).to_string_lossy().into_owned() 113 }; 114 let e = ffi::omega_gpu_bf16_last_error(); 115 if e.is_null() { 116 n 117 } else { 118 format!("{n}: {}", std::ffi::CStr::from_ptr(e).to_string_lossy()) 119 } 120 }; 121 OmegaGpuError::Rc { rc, name } 122 } 123 124 fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> { 125 if expected == got { 126 Ok(()) 127 } else { 128 Err(OmegaGpuError::ShapeMismatch { 129 what, 130 expected, 131 got, 132 }) 133 } 134 } 135 136 fn bad(name: String) -> OmegaGpuError { 137 OmegaGpuError::Rc { rc: -1, name } 138 } 139 140 /// Host check of the upload shape rule, before any chip call (also in the stub). 141 pub fn check_shape(n: usize, k: usize) -> Result<(), OmegaGpuError> { 142 if n == 0 || !k.is_multiple_of(K_GRANULE) || !(MIN_K..=MAX_K).contains(&k) { 143 return Err(bad(format!("bf16 gemv shape n={n} k={k} refused: n >= 1, k a multiple of {K_GRANULE} in {MIN_K}..={MAX_K}"))); 144 } 145 Ok(()) 146 } 147 148 /// An `[n][k]` bf16 matrix resident on the device until dropped. Not `Sync`: callers 149 /// serialise use behind a lock. 150 pub struct Bf16Tensor { 151 #[cfg(has_omega_bf16)] 152 ptr: *mut ffi::OmegaGpuBf16Tensor, 153 n: usize, 154 k: usize, 155 } 156 157 // SAFETY: an owning handle to a device buffer; moved between threads, never shared unlocked. 158 unsafe impl Send for Bf16Tensor {} 159 160 impl fmt::Debug for Bf16Tensor { 161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 162 write!(f, "Bf16Tensor {{ n: {}, k: {} }}", self.n, self.k) 163 } 164 } 165 166 impl Bf16Tensor { 167 /// The C handle (`OmegaGpuBf16Tensor *`) for another omega API that takes this object (the decode 168 /// graph, OWN-30B cut 2). Null in the stub. The handle stays owned by `self`: the caller must 169 /// not free it, must not use it after `self` is dropped, and must serialise its use with 170 /// `self`'s own calls. 171 pub fn as_raw(&self) -> *mut std::ffi::c_void { 172 #[cfg(has_omega_bf16)] 173 { 174 self.ptr as *mut std::ffi::c_void 175 } 176 #[cfg(not(has_omega_bf16))] 177 { 178 std::ptr::null_mut() 179 } 180 } 181 182 /// Upload `n * k` bf16 bit patterns, row-major `[n][k]` (the checkpoint's layout). 183 pub fn upload(n: usize, k: usize, w_bf16: &[u16]) -> Result { 184 check_shape(n, k)?; 185 check_len("bf16 gemv weight words", n * k, w_bf16.len())?; 186 #[cfg(has_omega_bf16)] 187 { 188 let mut ptr = std::ptr::null_mut(); 189 // SAFETY: shape and length checked; omega copies the bytes before returning. 190 let rc = unsafe { 191 ffi::omega_gpu_bf16_tensor_upload(n as u32, k as u32, w_bf16.as_ptr(), &mut ptr) 192 }; 193 if rc != 0 || ptr.is_null() { 194 return Err(rc_err(rc)); 195 } 196 Ok(Self { ptr, n, k }) 197 } 198 #[cfg(not(has_omega_bf16))] 199 { 200 Err(OmegaGpuError::Unavailable) 201 } 202 } 203 204 pub fn n(&self) -> usize { 205 self.n 206 } 207 pub fn k(&self) -> usize { 208 self.k 209 } 210 211 /// Bytes the device holds for this tensor. 212 pub fn resident_bytes(&self) -> usize { 213 self.n * self.k * 2 214 } 215 216 /// One launch: `y[n] = W * x[k]`, `x` f32. 217 pub fn gemv_f32(&self, x: &[f32], y: &mut [f32]) -> Result { 218 check_len("bf16 gemv x", self.k, x.len())?; 219 check_len("bf16 gemv y", self.n, y.len())?; 220 #[cfg(has_omega_bf16)] 221 { 222 let mut info = Bf16Info::default(); 223 // SAFETY: lengths checked; the tensor is live for &self. 224 let rc = unsafe { 225 ffi::omega_gpu_bf16_gemv_f32(self.ptr, x.as_ptr(), y.as_mut_ptr(), &mut info) 226 }; 227 if rc != 0 { 228 return Err(rc_err(rc)); 229 } 230 Ok(info) 231 } 232 #[cfg(not(has_omega_bf16))] 233 { 234 let _ = (x, y); 235 Err(OmegaGpuError::Unavailable) 236 } 237 } 238 239 /// As [`Self::gemv_f32`] with `x` given as bf16 bits. 240 pub fn gemv_bf16(&self, x: &[u16], y: &mut [f32]) -> Result { 241 check_len("bf16 gemv x", self.k, x.len())?; 242 check_len("bf16 gemv y", self.n, y.len())?; 243 #[cfg(has_omega_bf16)] 244 { 245 let mut info = Bf16Info::default(); 246 // SAFETY: lengths checked; the tensor is live for &self. 247 let rc = unsafe { 248 ffi::omega_gpu_bf16_gemv_bf16(self.ptr, x.as_ptr(), y.as_mut_ptr(), &mut info) 249 }; 250 if rc != 0 { 251 return Err(rc_err(rc)); 252 } 253 Ok(info) 254 } 255 #[cfg(not(has_omega_bf16))] 256 { 257 let _ = (x, y); 258 Err(OmegaGpuError::Unavailable) 259 } 260 } 261 } 262 263 impl Drop for Bf16Tensor { 264 fn drop(&mut self) { 265 #[cfg(has_omega_bf16)] 266 // SAFETY: ptr came from upload and is freed once. 267 unsafe { 268 ffi::omega_gpu_bf16_tensor_free(self.ptr) 269 } 270 } 271 } 272 273 /// Serving: build and pin the kernel for width `k`. 274 pub fn prepare(k: usize) -> Result<(), OmegaGpuError> { 275 #[cfg(has_omega_bf16)] 276 { 277 // SAFETY: plain integer argument. 278 let rc = unsafe { ffi::omega_gpu_bf16_prepare(k as u32) }; 279 if rc != 0 { 280 return Err(rc_err(rc)); 281 } 282 Ok(()) 283 } 284 #[cfg(not(has_omega_bf16))] 285 { 286 let _ = k; 287 Err(OmegaGpuError::Unavailable) 288 } 289 } 290 291 /// TEST ONLY: deliberately wrong kernels 1, 2, 3 (0 off); clears the kernel cache. 292 pub fn test_set_mutant(mutant: i32) { 293 #[cfg(has_omega_bf16)] 294 // SAFETY: plain integer argument. 295 unsafe { 296 ffi::omega_gpu_bf16_test_set_mutant(mutant) 297 } 298 #[cfg(not(has_omega_bf16))] 299 let _ = mutant; 300 } 301 302 #[cfg(test)] 303 mod tests { 304 use super::*; 305 306 #[test] 307 fn shape_rule_is_checked_on_the_host() { 308 assert!(check_shape(151_936, 2048).is_ok()); 309 assert!(check_shape(1, 256).is_ok()); 310 assert!(check_shape(0, 2048).is_err()); 311 assert!(check_shape(8, 100).is_err()); 312 assert!(check_shape(8, 128).is_err()); 313 assert!(check_shape(8, MAX_K + 256).is_err()); 314 } 315 316 #[test] 317 fn lengths_are_checked_before_the_chip() { 318 let r = Bf16Tensor::upload(4, 256, &[0u16; 100]); 319 assert!(matches!( 320 r, 321 Err(OmegaGpuError::ShapeMismatch { 322 what: "bf16 gemv weight words", 323 .. 324 }) 325 )); 326 } 327 328 #[test] 329 fn info_layout_matches_the_c_struct() { 330 // Measured with cc against omega_gpu_bf16_gemv_api.h (own30b/integration `3c12866a`): 331 // sizeof 136, weight_bytes at 32, elapsed_ns at 40, call_ns at 48, completion_marker at 332 // 56, kernel_cache_hit (bool) at 60, target_chip at 61, sm_architecture at 128. 333 assert_eq!(std::mem::size_of::(), 136); 334 assert_eq!(std::mem::offset_of!(Bf16Info, grid_x), 20); 335 assert_eq!(std::mem::offset_of!(Bf16Info, steps), 24); 336 assert_eq!(std::mem::offset_of!(Bf16Info, weight_bytes), 32); 337 assert_eq!(std::mem::offset_of!(Bf16Info, elapsed_ns), 40); 338 assert_eq!(std::mem::offset_of!(Bf16Info, call_ns), 48); 339 assert_eq!(std::mem::offset_of!(Bf16Info, completion_marker), 56); 340 assert_eq!(std::mem::offset_of!(Bf16Info, kernel_cache_hit), 60); 341 assert_eq!(std::mem::offset_of!(Bf16Info, target_chip), 61); 342 assert_eq!(std::mem::offset_of!(Bf16Info, sm_architecture), 128); 343 } 344 }