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-fp8/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-fp8 / src / lib.rs` 1105 lines ยท 36570 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 FP8 e4m3 block-scaled GEMV (`src/omega_gpu_fp8_api.h`, 17 //! OWN-30B cuts 5-6, no CUDA). 18 //! 19 //! A tensor holds `experts` projections of shape `[n][k]` (n output rows, k input columns) as 20 //! the checkpoint's e4m3 bytes plus bf16 `weight_scale_inv` in 128 x 128 blocks, exactly the 21 //! safetensors layout, experts concatenated. One call computes 22 //! `y[g][r] = sum_c W[id_g][r][c] * x[row(g)][c] * scale[id_g][r/128][c/128]` in f32 for up to 23 //! [`MAX_GROUPS`] experts in one launch, with one shared activation row (`x_rows == 1`) or one 24 //! row per group (`x_rows == groups`). 25 //! 26 //! Rules omega refuses otherwise (`BAD_ARGS` / `TOO_LARGE`): `n % 128 == 0`, `k % 128 == 0`, 27 //! `128 <= k <= 32768`, `1 <= groups <= 64`, every id `< experts`; any e4m3 NaN code in the 28 //! weights is refused at upload (`NAN_WEIGHT`). Without the native library (`is_native()` 29 //! false) every call returns `Unavailable`. 30 use aien_omega_gpu::OmegaGpuError; 31 use std::fmt; 32 33 /// Scale block edge (`weight_scale_inv` covers 128 x 128 weights). 34 pub const BLOCK: usize = 128; 35 /// Most experts one grouped call takes (`OMEGA_GPU_FP8_MAX_GROUPS`). 36 pub const MAX_GROUPS: usize = 64; 37 /// Widest `k` the kernel accepts (`OMEGA_FP8_MAX_K`, 32768 since omega#541: the Qwen3.8-27B 38 /// down_proj has k 17408; an omega archive older than that refuses past 16384 itself). 39 pub const MAX_K: usize = 32768; 40 41 /// True when the FP8 API is linked (not the stub). 42 pub const fn is_native() -> bool { 43 cfg!(has_omega_fp8) 44 } 45 46 /// True when the device-table entry points (`omega_gpu_fp8_gemv_grouped_dev`, 47 /// `omega_gpu_fp8_tensor_entry`, OWN-30B router cut) are linked. 48 pub const fn has_device_tables() -> bool { 49 cfg!(has_omega_fp8_dev) 50 } 51 52 /// True when the prefill grouped GEMM (`omega_gpu_fp8gemm_f32`, `src/omega_gpu_fp8gemm_api.h`) is linked. 53 pub const fn has_gemm() -> bool { 54 cfg!(has_omega_fp8gemm) 55 } 56 57 /// True when the grouped-launch CTA rule (`omega_gpu_fp8_grouped_ctas_auto`, L310 one-wave lever) is linked. 58 pub const fn has_grouped_rule() -> bool { 59 cfg!(has_omega_fp8_grouped_rule) 60 } 61 62 /// Most rows one GEMM launch takes (`OMEGA_GPU_FP8GEMM_MAX_ROWS`). 63 pub const GEMM_MAX_ROWS: usize = 1024; 64 /// Most distinct experts (segments) one GEMM launch takes (`OMEGA_GPU_FP8GEMM_MAX_SEGMENTS`). 65 pub const GEMM_MAX_SEGMENTS: usize = 256; 66 67 /// Mirror of `OmegaGpuFp8GemmInfo`: what the chip did for one GEMM call. 68 #[repr(C)] 69 #[derive(Debug, Clone, Copy, Default)] 70 pub struct GemmInfo { 71 pub rows: u32, 72 pub segments: u32, 73 pub n: u32, 74 pub k: u32, 75 pub mt: u32, 76 pub warps_per_cta: u32, 77 pub lane_bytes: u32, 78 pub grid_x: u32, 79 pub grid_y: u32, 80 pub passes_max: u32, 81 /// e4m3 bytes of the distinct experts, one pass each. 82 pub weight_bytes: u64, 83 /// Bytes the launch reads from the weights (sum over segments of passes x n x k). 84 pub streamed_bytes: u64, 85 /// Chip submit-to-second-marker. 86 pub elapsed_ns: u64, 87 /// Whole API call (host permute, launch, copy back). 88 pub call_ns: u64, 89 pub completion_marker: u32, 90 pub kernel_cache_hit: bool, 91 } 92 93 /// Mirror of `OmegaGpuFp8Info`: what the chip did for one call. 94 #[repr(C)] 95 #[derive(Debug, Clone, Copy)] 96 pub struct Fp8Info { 97 pub experts: u32, 98 pub n: u32, 99 pub k: u32, 100 pub groups: u32, 101 pub lane_bytes: u32, 102 pub rows_per_warp: u32, 103 pub warps_per_cta: u32, 104 pub depth: u32, 105 pub grid_x: u32, 106 pub grid_y: u32, 107 pub steps: u32, 108 pub weight_bytes: u64, 109 pub scale_bytes: u64, 110 pub elapsed_ns: u64, 111 pub call_ns: u64, 112 pub completion_marker: u32, 113 pub kernel_cache_hit: bool, 114 pub target_chip: [u8; 64], 115 pub sm_architecture: u32, 116 } 117 118 impl Default for Fp8Info { 119 fn default() -> Self { 120 // SAFETY: a plain C struct of integers, a bool and a byte array; all-zero is valid. 121 unsafe { std::mem::zeroed() } 122 } 123 } 124 125 #[cfg(has_omega_fp8)] 126 mod ffi { 127 use super::Fp8Info; 128 #[repr(C)] 129 pub struct OmegaGpuFp8Tensor { 130 _private: [u8; 0], 131 } 132 extern "C" { 133 pub fn omega_gpu_fp8_tensor_upload( 134 experts: u32, 135 n: u32, 136 k: u32, 137 w: *const u8, 138 scale_inv_bf16: *const u16, 139 out: *mut *mut OmegaGpuFp8Tensor, 140 ) -> i32; 141 pub fn omega_gpu_fp8_tensor_free(t: *mut OmegaGpuFp8Tensor); 142 pub fn omega_gpu_fp8_gemv_f32( 143 t: *const OmegaGpuFp8Tensor, 144 expert: u32, 145 x: *const f32, 146 y: *mut f32, 147 info: *mut Fp8Info, 148 ) -> i32; 149 pub fn omega_gpu_fp8_gemv_grouped_f32( 150 t: *const OmegaGpuFp8Tensor, 151 groups: u32, 152 expert_ids: *const u32, 153 x: *const f32, 154 x_rows: u32, 155 y: *mut f32, 156 info: *mut Fp8Info, 157 ) -> i32; 158 } 159 #[cfg(has_omega_fp8_dev)] 160 extern "C" { 161 pub fn omega_gpu_fp8_gemv_grouped_dev( 162 t: *const OmegaGpuFp8Tensor, 163 groups: u32, 164 tab_va: u64, 165 x_va: u64, 166 y: *mut f32, 167 info: *mut Fp8Info, 168 ) -> i32; 169 pub fn omega_gpu_fp8_tensor_entry( 170 t: *const OmegaGpuFp8Tensor, 171 expert: u32, 172 w_va: *mut u64, 173 s_va: *mut u64, 174 ) -> i32; 175 } 176 #[cfg(has_omega_fp8gemm)] 177 extern "C" { 178 pub fn omega_gpu_fp8gemm_f32( 179 t: *const OmegaGpuFp8Tensor, 180 m: u32, 181 expert_ids: *const u32, 182 token_rows: *const u32, 183 x: *const f32, 184 x_rows: u32, 185 y: *mut f32, 186 info: *mut super::GemmInfo, 187 ) -> i32; 188 pub fn omega_gpu_fp8gemm_prepare(k: u32) -> i32; 189 pub fn omega_gpu_fp8gemm_rc_name(rc: i32) -> *const std::os::raw::c_char; 190 pub fn omega_gpu_fp8gemm_last_error() -> *const std::os::raw::c_char; 191 pub fn omega_gpu_fp8gemm_test_set_mutant(mutant: i32); 192 } 193 #[cfg(has_omega_fp8_grouped_rule)] 194 extern "C" { 195 pub fn omega_gpu_fp8_grouped_ctas_auto(groups: u32) -> u32; 196 } 197 extern "C" { 198 pub fn omega_gpu_fp8_prepare(k: u32) -> i32; 199 pub fn omega_gpu_fp8_seal(on: i32); 200 pub fn omega_gpu_fp8_rc_name(rc: i32) -> *const std::os::raw::c_char; 201 pub fn omega_gpu_fp8_last_error() -> *const std::os::raw::c_char; 202 pub fn omega_gpu_fp8_cache_clear(); 203 pub fn omega_gpu_fp8_set_shape(lane_bytes: u32, rows_per_warp: u32, warps_per_cta: u32); 204 pub fn omega_gpu_fp8_set_cta_budget(ctas: u32); 205 pub fn omega_gpu_fp8_test_set_mutant(mutant: i32); 206 pub fn omega_gpu_fp8_test_set_no_fold(on: i32); 207 } 208 } 209 210 #[cfg(has_omega_fp8)] 211 fn rc_err(rc: i32) -> OmegaGpuError { 212 // SAFETY: both return static NUL-terminated strings (or NULL for last_error). 213 let name = unsafe { 214 let n = ffi::omega_gpu_fp8_rc_name(rc); 215 let n = if n.is_null() { 216 String::from("?") 217 } else { 218 std::ffi::CStr::from_ptr(n).to_string_lossy().into_owned() 219 }; 220 let e = ffi::omega_gpu_fp8_last_error(); 221 if e.is_null() { 222 n 223 } else { 224 format!("{n}: {}", std::ffi::CStr::from_ptr(e).to_string_lossy()) 225 } 226 }; 227 OmegaGpuError::Rc { rc, name } 228 } 229 230 fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> { 231 if expected == got { 232 Ok(()) 233 } else { 234 Err(OmegaGpuError::ShapeMismatch { 235 what, 236 expected, 237 got, 238 }) 239 } 240 } 241 242 fn bad(name: String) -> OmegaGpuError { 243 OmegaGpuError::Rc { rc: -1, name } 244 } 245 246 /// Host check of the upload shape rule, before any chip call (also in the stub). 247 pub fn check_shape(experts: usize, n: usize, k: usize) -> Result<(), OmegaGpuError> { 248 if experts == 0 249 || n == 0 250 || !n.is_multiple_of(BLOCK) 251 || !k.is_multiple_of(BLOCK) 252 || !(BLOCK..=MAX_K).contains(&k) 253 { 254 return Err(bad(format!( 255 "fp8 shape experts={experts} n={n} k={k} refused: experts >= 1, n and k multiples of {BLOCK}, {BLOCK} <= k <= {MAX_K}" 256 ))); 257 } 258 Ok(()) 259 } 260 261 /// `experts` FP8 projections of `[n][k]`, resident on the device until dropped. Not `Sync`: 262 /// callers serialise use behind a lock. 263 pub struct Fp8Tensor { 264 #[cfg(has_omega_fp8)] 265 ptr: *mut ffi::OmegaGpuFp8Tensor, 266 experts: usize, 267 n: usize, 268 k: usize, 269 } 270 271 // SAFETY: an owning handle to a device buffer; moved between threads, never shared unlocked. 272 unsafe impl Send for Fp8Tensor {} 273 274 impl fmt::Debug for Fp8Tensor { 275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 276 write!( 277 f, 278 "Fp8Tensor {{ experts: {}, n: {}, k: {} }}", 279 self.experts, self.n, self.k 280 ) 281 } 282 } 283 284 impl Fp8Tensor { 285 /// The C handle (`OmegaGpuFp8Tensor *`) for another omega API that takes this object (the decode 286 /// graph, OWN-30B cut 2). Null in the stub. The handle stays owned by `self`: the caller must 287 /// not free it, must not use it after `self` is dropped, and must serialise its use with 288 /// `self`'s own calls. 289 pub fn as_raw(&self) -> *mut std::ffi::c_void { 290 #[cfg(has_omega_fp8)] 291 { 292 self.ptr as *mut std::ffi::c_void 293 } 294 #[cfg(not(has_omega_fp8))] 295 { 296 std::ptr::null_mut() 297 } 298 } 299 300 /// Upload `experts * n * k` e4m3 bytes (`[expert][n][k]`) and 301 /// `experts * (n/128) * (k/128)` bf16 scale bits (`[expert][n/128][k/128]`). 302 pub fn upload( 303 experts: usize, 304 n: usize, 305 k: usize, 306 w: &[u8], 307 scale_inv_bf16: &[u16], 308 ) -> Result { 309 check_shape(experts, n, k)?; 310 check_len("fp8 weight bytes", experts * n * k, w.len())?; 311 check_len( 312 "fp8 scale words", 313 experts * (n / BLOCK) * (k / BLOCK), 314 scale_inv_bf16.len(), 315 )?; 316 #[cfg(has_omega_fp8)] 317 { 318 let mut ptr = std::ptr::null_mut(); 319 // SAFETY: lengths checked above; omega copies the bytes before returning. 320 let rc = unsafe { 321 ffi::omega_gpu_fp8_tensor_upload( 322 experts as u32, 323 n as u32, 324 k as u32, 325 w.as_ptr(), 326 scale_inv_bf16.as_ptr(), 327 &mut ptr, 328 ) 329 }; 330 if rc != 0 || ptr.is_null() { 331 return Err(rc_err(rc)); 332 } 333 Ok(Self { ptr, experts, n, k }) 334 } 335 #[cfg(not(has_omega_fp8))] 336 { 337 Err(OmegaGpuError::Unavailable) 338 } 339 } 340 341 pub fn experts(&self) -> usize { 342 self.experts 343 } 344 pub fn n(&self) -> usize { 345 self.n 346 } 347 pub fn k(&self) -> usize { 348 self.k 349 } 350 351 /// Bytes the device holds for this tensor (weights plus f32 scales). 352 pub fn resident_bytes(&self) -> usize { 353 self.experts * self.n * self.k + self.experts * (self.n / BLOCK) * (self.k / BLOCK) * 4 354 } 355 356 /// One projection, one launch: `y[n] = W[expert] * x[k]`. 357 pub fn gemv_f32( 358 &self, 359 expert: usize, 360 x: &[f32], 361 y: &mut [f32], 362 ) -> Result { 363 check_len("fp8 x", self.k, x.len())?; 364 check_len("fp8 y", self.n, y.len())?; 365 if expert >= self.experts { 366 return Err(bad(format!( 367 "fp8 expert {expert} >= experts {}", 368 self.experts 369 ))); 370 } 371 #[cfg(has_omega_fp8)] 372 { 373 let mut info = Fp8Info::default(); 374 // SAFETY: lengths checked; the tensor is live for &self. 375 let rc = unsafe { 376 ffi::omega_gpu_fp8_gemv_f32( 377 self.ptr, 378 expert as u32, 379 x.as_ptr(), 380 y.as_mut_ptr(), 381 &mut info, 382 ) 383 }; 384 if rc != 0 { 385 return Err(rc_err(rc)); 386 } 387 Ok(info) 388 } 389 #[cfg(not(has_omega_fp8))] 390 { 391 let _ = (x, y); 392 Err(OmegaGpuError::Unavailable) 393 } 394 } 395 396 /// Device addresses `(weights, scales)` of one expert, for a directory the router copies 397 /// group-table entries from (`omega_gpu_fp8_tensor_entry`). 398 pub fn entry(&self, expert: usize) -> Result<(u64, u64), OmegaGpuError> { 399 if expert >= self.experts { 400 return Err(bad(format!( 401 "fp8 expert {expert} >= experts {}", 402 self.experts 403 ))); 404 } 405 #[cfg(has_omega_fp8_dev)] 406 { 407 let (mut w, mut s) = (0u64, 0u64); 408 // SAFETY: expert is in range; both out pointers are valid for a write. 409 let rc = 410 unsafe { ffi::omega_gpu_fp8_tensor_entry(self.ptr, expert as u32, &mut w, &mut s) }; 411 if rc != 0 { 412 return Err(rc_err(rc)); 413 } 414 Ok((w, s)) 415 } 416 #[cfg(not(has_omega_fp8_dev))] 417 { 418 Err(OmegaGpuError::Unavailable) 419 } 420 } 421 422 /// `groups` experts in one launch whose group table and single activation row are already 423 /// on the device (written by the router launch): `tab_va` holds `groups` `{w_va, s_va}` 424 /// entries, `x_va` the f32 row already multiplied by 2^64. No host copy of either. 425 pub fn gemv_grouped_dev( 426 &self, 427 groups: usize, 428 tab_va: u64, 429 x_va: u64, 430 y: &mut [f32], 431 ) -> Result { 432 if groups == 0 || groups > MAX_GROUPS { 433 return Err(bad(format!("fp8 groups {groups} outside 1..={MAX_GROUPS}"))); 434 } 435 if tab_va == 0 || x_va == 0 { 436 return Err(bad("fp8 device table or row address is 0".into())); 437 } 438 check_len("fp8 y (groups*n)", groups * self.n, y.len())?; 439 #[cfg(has_omega_fp8_dev)] 440 { 441 let mut info = Fp8Info::default(); 442 // SAFETY: y length checked; the addresses come from the router that wrote them; the 443 // tensor is live for &self. 444 let rc = unsafe { 445 ffi::omega_gpu_fp8_gemv_grouped_dev( 446 self.ptr, 447 groups as u32, 448 tab_va, 449 x_va, 450 y.as_mut_ptr(), 451 &mut info, 452 ) 453 }; 454 if rc != 0 { 455 return Err(rc_err(rc)); 456 } 457 Ok(info) 458 } 459 #[cfg(not(has_omega_fp8_dev))] 460 { 461 let _ = y; 462 Err(OmegaGpuError::Unavailable) 463 } 464 } 465 466 /// `groups = ids.len()` experts in one launch. `x` is `k` values shared by every group, or 467 /// `groups * k` values (one row per group). `y` is `groups * n`, group-major. 468 pub fn gemv_grouped_f32( 469 &self, 470 ids: &[u32], 471 x: &[f32], 472 y: &mut [f32], 473 ) -> Result { 474 let groups = ids.len(); 475 if groups == 0 || groups > MAX_GROUPS { 476 return Err(bad(format!("fp8 groups {groups} outside 1..={MAX_GROUPS}"))); 477 } 478 if let Some(&id) = ids.iter().find(|&&id| id as usize >= self.experts) { 479 return Err(bad(format!( 480 "fp8 expert id {id} >= experts {}", 481 self.experts 482 ))); 483 } 484 let x_rows = if x.len() == self.k { 1 } else { groups }; 485 check_len("fp8 x (k or groups*k)", x_rows * self.k, x.len())?; 486 check_len("fp8 y (groups*n)", groups * self.n, y.len())?; 487 #[cfg(has_omega_fp8)] 488 { 489 let mut info = Fp8Info::default(); 490 // SAFETY: lengths checked; ids are in range; the tensor is live for &self. 491 let rc = unsafe { 492 ffi::omega_gpu_fp8_gemv_grouped_f32( 493 self.ptr, 494 groups as u32, 495 ids.as_ptr(), 496 x.as_ptr(), 497 x_rows as u32, 498 y.as_mut_ptr(), 499 &mut info, 500 ) 501 }; 502 if rc != 0 { 503 return Err(rc_err(rc)); 504 } 505 Ok(info) 506 } 507 #[cfg(not(has_omega_fp8))] 508 { 509 let _ = (x_rows, y); 510 Err(OmegaGpuError::Unavailable) 511 } 512 } 513 514 /// Prefill grouped GEMM, one launch (`omega_gpu_fp8gemm_f32`). Row `i` computes expert 515 /// `expert_ids[i]` on activation row `x[token_rows[i]]` (`x` is `x_rows * k` values); 516 /// `expert_ids` must be non-decreasing (sorted by expert). `y` is `M * n`, in row-table 517 /// order, bit-identical to calling the GEMV once per row. Dense projections are tensors 518 /// with `experts == 1`. 519 pub fn gemm_f32( 520 &self, 521 expert_ids: &[u32], 522 token_rows: &[u32], 523 x: &[f32], 524 y: &mut [f32], 525 ) -> Result { 526 let m = expert_ids.len(); 527 if m == 0 || m > GEMM_MAX_ROWS { 528 return Err(bad(format!( 529 "fp8 gemm rows {m} outside 1..={GEMM_MAX_ROWS}" 530 ))); 531 } 532 check_len("fp8 gemm token rows", m, token_rows.len())?; 533 if !x.len().is_multiple_of(self.k) || x.is_empty() { 534 return Err(bad(format!( 535 "fp8 gemm x length {} is not a positive multiple of k={}", 536 x.len(), 537 self.k 538 ))); 539 } 540 let x_rows = x.len() / self.k; 541 if let Some(&id) = expert_ids.iter().find(|&&id| id as usize >= self.experts) { 542 return Err(bad(format!( 543 "fp8 gemm expert id {id} >= experts {}", 544 self.experts 545 ))); 546 } 547 if expert_ids.windows(2).any(|w| w[0] > w[1]) { 548 return Err(bad( 549 "fp8 gemm expert ids must be sorted (non-decreasing)".into() 550 )); 551 } 552 let mut segments = 1; 553 for w in expert_ids.windows(2) { 554 if w[0] != w[1] { 555 segments += 1; 556 } 557 } 558 if segments > GEMM_MAX_SEGMENTS { 559 return Err(bad(format!( 560 "fp8 gemm segments {segments} > {GEMM_MAX_SEGMENTS}" 561 ))); 562 } 563 if let Some(&r) = token_rows.iter().find(|&&r| r as usize >= x_rows) { 564 return Err(bad(format!("fp8 gemm token row {r} >= x rows {x_rows}"))); 565 } 566 check_len("fp8 gemm y (rows*n)", m * self.n, y.len())?; 567 #[cfg(has_omega_fp8gemm)] 568 { 569 let mut info = GemmInfo::default(); 570 // SAFETY: lengths, ranges and sort order checked above; the tensor is live for &self. 571 let rc = unsafe { 572 ffi::omega_gpu_fp8gemm_f32( 573 self.ptr, 574 m as u32, 575 expert_ids.as_ptr(), 576 token_rows.as_ptr(), 577 x.as_ptr(), 578 x_rows as u32, 579 y.as_mut_ptr(), 580 &mut info, 581 ) 582 }; 583 if rc != 0 { 584 return Err(gemm_rc_err(rc)); 585 } 586 Ok(info) 587 } 588 #[cfg(not(has_omega_fp8gemm))] 589 { 590 let _ = (x_rows, y); 591 Err(OmegaGpuError::Unavailable) 592 } 593 } 594 } 595 596 impl Drop for Fp8Tensor { 597 fn drop(&mut self) { 598 #[cfg(has_omega_fp8)] 599 // SAFETY: ptr came from upload and is freed once. 600 unsafe { 601 ffi::omega_gpu_fp8_tensor_free(self.ptr) 602 } 603 } 604 } 605 606 #[cfg(has_omega_fp8gemm)] 607 fn gemm_rc_err(rc: i32) -> OmegaGpuError { 608 // SAFETY: both return static NUL-terminated strings (or NULL for last_error). 609 let name = unsafe { 610 let n = ffi::omega_gpu_fp8gemm_rc_name(rc); 611 let n = if n.is_null() { 612 String::from("?") 613 } else { 614 std::ffi::CStr::from_ptr(n).to_string_lossy().into_owned() 615 }; 616 let e = ffi::omega_gpu_fp8gemm_last_error(); 617 if e.is_null() { 618 n 619 } else { 620 format!("{n}: {}", std::ffi::CStr::from_ptr(e).to_string_lossy()) 621 } 622 }; 623 OmegaGpuError::Rc { rc, name } 624 } 625 626 /// Serving: build and pin the GEMM kernel for width `k`. 627 pub fn gemm_prepare(k: usize) -> Result<(), OmegaGpuError> { 628 #[cfg(has_omega_fp8gemm)] 629 { 630 // SAFETY: plain integer argument. 631 let rc = unsafe { ffi::omega_gpu_fp8gemm_prepare(k as u32) }; 632 if rc != 0 { 633 return Err(gemm_rc_err(rc)); 634 } 635 Ok(()) 636 } 637 #[cfg(not(has_omega_fp8gemm))] 638 { 639 let _ = k; 640 Err(OmegaGpuError::Unavailable) 641 } 642 } 643 644 /// TEST ONLY: deliberately wrong GEMM kernel (0 off; 1 scale dropped; 2 scale pointer never 645 /// advances; 3 neighbour row's x). Clears the GEMM kernel cache. 646 pub fn gemm_test_set_mutant(mutant: i32) { 647 #[cfg(has_omega_fp8gemm)] 648 // SAFETY: plain integer argument. 649 unsafe { 650 ffi::omega_gpu_fp8gemm_test_set_mutant(mutant) 651 } 652 #[cfg(not(has_omega_fp8gemm))] 653 let _ = mutant; 654 } 655 656 /// Serving: build and pin the kernel for width `k`. 657 pub fn prepare(k: usize) -> Result<(), OmegaGpuError> { 658 #[cfg(has_omega_fp8)] 659 { 660 // SAFETY: plain integer argument. 661 let rc = unsafe { ffi::omega_gpu_fp8_prepare(k as u32) }; 662 if rc != 0 { 663 return Err(rc_err(rc)); 664 } 665 Ok(()) 666 } 667 #[cfg(not(has_omega_fp8))] 668 { 669 let _ = k; 670 Err(OmegaGpuError::Unavailable) 671 } 672 } 673 674 /// Seal on: a call whose kernel is not cached is refused instead of built. 675 pub fn seal(on: bool) { 676 #[cfg(has_omega_fp8)] 677 // SAFETY: plain integer argument. 678 unsafe { 679 ffi::omega_gpu_fp8_seal(on as i32) 680 } 681 #[cfg(not(has_omega_fp8))] 682 let _ = on; 683 } 684 685 pub fn cache_clear() { 686 #[cfg(has_omega_fp8)] 687 // SAFETY: no arguments. 688 unsafe { 689 ffi::omega_gpu_fp8_cache_clear() 690 } 691 } 692 693 /// Kernel shape override (0 = automatic); clears the kernel cache. 694 pub fn set_shape(lane_bytes: u32, rows_per_warp: u32, warps_per_cta: u32) { 695 #[cfg(has_omega_fp8)] 696 // SAFETY: plain integer arguments. 697 unsafe { 698 ffi::omega_gpu_fp8_set_shape(lane_bytes, rows_per_warp, warps_per_cta) 699 } 700 #[cfg(not(has_omega_fp8))] 701 let _ = (lane_bytes, rows_per_warp, warps_per_cta); 702 } 703 704 /// CTAs per group per launch (0 = automatic: 256 single, 6 grouped). 705 pub fn set_cta_budget(ctas: u32) { 706 #[cfg(has_omega_fp8)] 707 // SAFETY: plain integer argument. 708 unsafe { 709 ffi::omega_gpu_fp8_set_cta_budget(ctas) 710 } 711 #[cfg(not(has_omega_fp8))] 712 let _ = ctas; 713 } 714 715 /// CTAs per group omega's automatic choice gives a grouped launch of `groups` groups (L310 wave rule: reads 716 /// AIEN_OMEGA_FP8_GROUPED_CTAS and AIEN_OMEGA_FP8_GROUPED_WAVE once, at the first call). `None` when the linked 717 /// library predates the rule, so a server log states that instead of guessing a number. 718 #[cfg(has_omega_fp8_grouped_rule)] 719 pub fn grouped_ctas_auto(groups: u32) -> Option { 720 // SAFETY: plain integer argument; a pure function of it and the process environment. 721 Some(unsafe { ffi::omega_gpu_fp8_grouped_ctas_auto(groups) }) 722 } 723 #[cfg(not(has_omega_fp8_grouped_rule))] 724 pub fn grouped_ctas_auto(groups: u32) -> Option { 725 let _ = groups; 726 None 727 } 728 729 /// TEST ONLY: deliberately wrong kernel (0 off; 1 scale dropped; 2 scale block never advances; 730 /// 3 group table entry skewed). A parity test must catch each. 731 pub fn test_set_mutant(mutant: i32) { 732 #[cfg(has_omega_fp8)] 733 // SAFETY: plain integer argument. 734 unsafe { 735 ffi::omega_gpu_fp8_test_set_mutant(mutant) 736 } 737 #[cfg(not(has_omega_fp8))] 738 let _ = mutant; 739 } 740 741 /// TEST ONLY: upload scales without the 2^56 fold (host-side mutant). 742 pub fn test_set_no_fold(on: bool) { 743 #[cfg(has_omega_fp8)] 744 // SAFETY: plain integer argument. 745 unsafe { 746 ffi::omega_gpu_fp8_test_set_no_fold(on as i32) 747 } 748 #[cfg(not(has_omega_fp8))] 749 let _ = on; 750 } 751 752 #[cfg(test)] 753 mod tests { 754 use super::*; 755 756 #[test] 757 fn shape_rule_is_checked_on_the_host() { 758 assert!(check_shape(1, 128, 128).is_ok()); 759 assert!(check_shape(128, 1536, 2048).is_ok()); 760 assert!(check_shape(0, 128, 128).is_err()); 761 assert!(check_shape(1, 100, 128).is_err()); 762 assert!(check_shape(1, 128, 64).is_err()); 763 assert!(check_shape(1, 5120, 17408).is_ok()); 764 assert!(check_shape(1, 128, MAX_K + 128).is_err()); 765 } 766 767 #[test] 768 fn lengths_are_checked_before_the_chip() { 769 let r = Fp8Tensor::upload(1, 128, 128, &[0u8; 100], &[0u16; 1]); 770 assert!(matches!( 771 r, 772 Err(OmegaGpuError::ShapeMismatch { 773 what: "fp8 weight bytes", 774 .. 775 }) 776 )); 777 let r = Fp8Tensor::upload(1, 128, 128, &[0u8; 128 * 128], &[0u16; 2]); 778 assert!(matches!( 779 r, 780 Err(OmegaGpuError::ShapeMismatch { 781 what: "fp8 scale words", 782 .. 783 }) 784 )); 785 } 786 787 #[test] 788 fn info_layout_matches_the_c_struct() { 789 // Measured with cc against omega_gpu_fp8_api.h (own30b/integration `da9a3d67`): 790 // sizeof 160, weight_bytes at 48, kernel_cache_hit at 84, sm_architecture at 152. 791 assert_eq!(std::mem::size_of::(), 160); 792 assert_eq!(std::mem::offset_of!(Fp8Info, weight_bytes), 48); 793 assert_eq!(std::mem::offset_of!(Fp8Info, kernel_cache_hit), 84); 794 assert_eq!(std::mem::offset_of!(Fp8Info, sm_architecture), 152); 795 } 796 797 #[test] 798 fn gemm_info_layout_matches_the_c_struct() { 799 // Measured with cc against omega_gpu_fp8gemm_api.h (own30b/integration `967b14c5`): 800 // sizeof 80, passes_max at 36, weight_bytes at 40, streamed_bytes at 48, elapsed_ns at 56, 801 // call_ns at 64, completion_marker at 72, kernel_cache_hit at 76. 802 assert_eq!(std::mem::size_of::(), 80); 803 assert_eq!(std::mem::offset_of!(GemmInfo, passes_max), 36); 804 assert_eq!(std::mem::offset_of!(GemmInfo, weight_bytes), 40); 805 assert_eq!(std::mem::offset_of!(GemmInfo, streamed_bytes), 48); 806 assert_eq!(std::mem::offset_of!(GemmInfo, elapsed_ns), 56); 807 assert_eq!(std::mem::offset_of!(GemmInfo, call_ns), 64); 808 assert_eq!(std::mem::offset_of!(GemmInfo, completion_marker), 72); 809 assert_eq!(std::mem::offset_of!(GemmInfo, kernel_cache_hit), 76); 810 } 811 } 812 813 // --------------------------------------------------------------------------------------------- 814 // Expert Ribbon (aienix#4, omega#533): versioned replaceable FP8 expert slots. 815 // --------------------------------------------------------------------------------------------- 816 817 #[cfg(has_omega_fp8_slots)] 818 mod slots_ffi { 819 use super::Fp8Info; 820 #[repr(C)] 821 pub struct OmegaGpuFp8Slots { 822 _private: [u8; 0], 823 } 824 #[repr(C)] 825 #[derive(Default, Debug, Clone, Copy)] 826 pub struct OmegaGpuFp8SlotsStats { 827 pub slots: u32, 828 pub n: u32, 829 pub k: u32, 830 pub device_bytes: u64, 831 pub loads: u64, 832 pub load_failures: u64, 833 pub busy_refusals: u64, 834 pub stale_refusals: u64, 835 pub evictions: u64, 836 pub pins: u64, 837 pub pinned_now: u32, 838 pub pinned_high: u32, 839 pub bytes_loaded: u64, 840 pub load_ns: u64, 841 } 842 extern "C" { 843 pub fn omega_gpu_fp8_slots_alloc( 844 slots: u32, 845 n: u32, 846 k: u32, 847 out: *mut *mut OmegaGpuFp8Slots, 848 ) -> i32; 849 pub fn omega_gpu_fp8_slots_free(p: *mut OmegaGpuFp8Slots) -> i32; 850 pub fn omega_gpu_fp8_slots_load( 851 p: *mut OmegaGpuFp8Slots, 852 slot: u32, 853 key: u64, 854 w: *const u8, 855 scale_inv_bf16: *const u16, 856 version: *mut u64, 857 ) -> i32; 858 pub fn omega_gpu_fp8_slots_gemv_grouped_f32( 859 p: *mut OmegaGpuFp8Slots, 860 groups: u32, 861 slots: *const u32, 862 versions: *const u64, 863 x: *const f32, 864 x_rows: u32, 865 y: *mut f32, 866 info: *mut Fp8Info, 867 ) -> i32; 868 pub fn omega_gpu_fp8_slots_stats(p: *mut OmegaGpuFp8Slots, out: *mut OmegaGpuFp8SlotsStats); 869 pub fn omega_gpu_fp8_slots_rc_name(rc: i32) -> *const std::os::raw::c_char; 870 } 871 } 872 873 /// Counters of one slot pool (omega `OmegaGpuFp8SlotsStats`). 874 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] 875 pub struct SlotPoolStats { 876 pub slots: u32, 877 pub device_bytes: u64, 878 pub loads: u64, 879 pub load_failures: u64, 880 pub busy_refusals: u64, 881 pub stale_refusals: u64, 882 pub pins: u64, 883 pub pinned_now: u32, 884 pub pinned_high: u32, 885 pub bytes_loaded: u64, 886 pub load_ns: u64, 887 } 888 889 /// A pool of `slots` versioned FP8 expert slots of one shape `[n][k]` (omega_gpu_fp8_slots.h): GPU-uncached, 890 /// refilled while the model runs. `load` hides the slot, copies and publishes a fresh version; it is refused 891 /// while a launch reads the slot. `grouped_f32` pins the given (slot, version) pairs for exactly its launch. 892 /// Thread-safe in omega (pool mutex; launches take the session lock), so `Sync`. 893 pub struct Fp8Slots { 894 #[cfg(has_omega_fp8_slots)] 895 ptr: *mut slots_ffi::OmegaGpuFp8Slots, 896 slots: usize, 897 n: usize, 898 k: usize, 899 } 900 901 // SAFETY: the omega pool serialises its own state (pthread mutex) and launches take the session lock. 902 unsafe impl Send for Fp8Slots {} 903 unsafe impl Sync for Fp8Slots {} 904 905 impl fmt::Debug for Fp8Slots { 906 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 907 write!( 908 f, 909 "Fp8Slots {{ slots: {}, n: {}, k: {} }}", 910 self.slots, self.n, self.k 911 ) 912 } 913 } 914 915 #[cfg(has_omega_fp8_slots)] 916 fn slots_err(rc: i32) -> OmegaGpuError { 917 // SAFETY: static NUL-terminated strings (last_error may be NULL). 918 let name = unsafe { 919 let n = slots_ffi::omega_gpu_fp8_slots_rc_name(rc); 920 let n = if n.is_null() { 921 String::from("?") 922 } else { 923 std::ffi::CStr::from_ptr(n).to_string_lossy().into_owned() 924 }; 925 let e = ffi::omega_gpu_fp8_last_error(); 926 if e.is_null() || rc == -6 || rc == -7 { 927 n 928 } else { 929 format!("{n}: {}", std::ffi::CStr::from_ptr(e).to_string_lossy()) 930 } 931 }; 932 OmegaGpuError::Rc { rc, name } 933 } 934 935 /// Whether this binary carries the slot pool API. 936 pub fn slots_native() -> bool { 937 cfg!(has_omega_fp8_slots) 938 } 939 940 impl Fp8Slots { 941 pub fn alloc(slots: usize, n: usize, k: usize) -> Result { 942 check_shape(slots, n, k)?; 943 #[cfg(has_omega_fp8_slots)] 944 { 945 let mut ptr = std::ptr::null_mut(); 946 // SAFETY: shape checked; omega writes the handle or leaves it NULL. 947 let rc = unsafe { 948 slots_ffi::omega_gpu_fp8_slots_alloc(slots as u32, n as u32, k as u32, &mut ptr) 949 }; 950 if rc != 0 || ptr.is_null() { 951 return Err(slots_err(rc)); 952 } 953 Ok(Self { ptr, slots, n, k }) 954 } 955 #[cfg(not(has_omega_fp8_slots))] 956 { 957 let _ = (slots, n, k); 958 Err(OmegaGpuError::Unavailable) 959 } 960 } 961 962 pub fn slots(&self) -> usize { 963 self.slots 964 } 965 pub fn n(&self) -> usize { 966 self.n 967 } 968 pub fn k(&self) -> usize { 969 self.k 970 } 971 /// Device bytes per slot (weights + f32 scales). 972 pub fn slot_bytes(&self) -> usize { 973 self.n * self.k + (self.n / BLOCK) * (self.k / BLOCK) * 4 974 } 975 976 /// Load one expert projection into `slot`; returns the published version. 977 pub fn load( 978 &self, 979 slot: usize, 980 key: u64, 981 w: &[u8], 982 scale_inv_bf16: &[u16], 983 ) -> Result { 984 check_len("fp8 slot weight bytes", self.n * self.k, w.len())?; 985 check_len( 986 "fp8 slot scale words", 987 (self.n / BLOCK) * (self.k / BLOCK), 988 scale_inv_bf16.len(), 989 )?; 990 if slot >= self.slots { 991 return Err(bad(format!("slot {slot} of {}", self.slots))); 992 } 993 #[cfg(has_omega_fp8_slots)] 994 { 995 let mut v = 0u64; 996 // SAFETY: lengths checked; omega copies before returning. 997 let rc = unsafe { 998 slots_ffi::omega_gpu_fp8_slots_load( 999 self.ptr, 1000 slot as u32, 1001 key, 1002 w.as_ptr(), 1003 scale_inv_bf16.as_ptr(), 1004 &mut v, 1005 ) 1006 }; 1007 if rc != 0 { 1008 return Err(slots_err(rc)); 1009 } 1010 Ok(v) 1011 } 1012 #[cfg(not(has_omega_fp8_slots))] 1013 { 1014 let _ = key; 1015 Err(OmegaGpuError::Unavailable) 1016 } 1017 } 1018 1019 /// One grouped launch over (slot, version) pairs, pinned for the launch (`x`: `k` values shared, or 1020 /// `slots.len() * k`, one row per group). Returns the chip info. 1021 pub fn grouped_f32( 1022 &self, 1023 slots: &[u32], 1024 versions: &[u64], 1025 x: &[f32], 1026 y: &mut [f32], 1027 ) -> Result { 1028 let g = slots.len(); 1029 check_len("fp8 slot versions", g, versions.len())?; 1030 if g == 0 || g > MAX_GROUPS { 1031 return Err(bad(format!("fp8 slot groups {g} (1..={MAX_GROUPS})"))); 1032 } 1033 let x_rows = if x.len() == self.k { 1034 1 1035 } else { 1036 check_len("fp8 slot x", g * self.k, x.len())?; 1037 g 1038 }; 1039 check_len("fp8 slot y", g * self.n, y.len())?; 1040 #[cfg(has_omega_fp8_slots)] 1041 { 1042 let mut info = Fp8Info::default(); 1043 // SAFETY: lengths checked above; omega pins, launches, waits for the marker, unpins. 1044 let rc = unsafe { 1045 slots_ffi::omega_gpu_fp8_slots_gemv_grouped_f32( 1046 self.ptr, 1047 g as u32, 1048 slots.as_ptr(), 1049 versions.as_ptr(), 1050 x.as_ptr(), 1051 x_rows as u32, 1052 y.as_mut_ptr(), 1053 &mut info, 1054 ) 1055 }; 1056 if rc != 0 { 1057 return Err(slots_err(rc)); 1058 } 1059 Ok(info) 1060 } 1061 #[cfg(not(has_omega_fp8_slots))] 1062 { 1063 let _ = x_rows; 1064 Err(OmegaGpuError::Unavailable) 1065 } 1066 } 1067 1068 pub fn stats(&self) -> SlotPoolStats { 1069 #[cfg(has_omega_fp8_slots)] 1070 { 1071 let mut s = slots_ffi::OmegaGpuFp8SlotsStats::default(); 1072 // SAFETY: valid handle, plain C struct out. 1073 unsafe { slots_ffi::omega_gpu_fp8_slots_stats(self.ptr, &mut s) }; 1074 SlotPoolStats { 1075 slots: s.slots, 1076 device_bytes: s.device_bytes, 1077 loads: s.loads, 1078 load_failures: s.load_failures, 1079 busy_refusals: s.busy_refusals, 1080 stale_refusals: s.stale_refusals, 1081 pins: s.pins, 1082 pinned_now: s.pinned_now, 1083 pinned_high: s.pinned_high, 1084 bytes_loaded: s.bytes_loaded, 1085 load_ns: s.load_ns, 1086 } 1087 } 1088 #[cfg(not(has_omega_fp8_slots))] 1089 { 1090 SlotPoolStats::default() 1091 } 1092 } 1093 } 1094 1095 impl Drop for Fp8Slots { 1096 fn drop(&mut self) { 1097 #[cfg(has_omega_fp8_slots)] 1098 { 1099 // SAFETY: owned handle. BUSY means a launch still pins a slot, which cannot happen here (launches 1100 // are synchronous and borrow &self); the pool is then leaked rather than freed under a reader. 1101 let rc = unsafe { slots_ffi::omega_gpu_fp8_slots_free(self.ptr) }; 1102 debug_assert_eq!(rc, 0, "slot pool freed while pinned"); 1103 } 1104 } 1105 }