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-gpu/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-gpu / src / lib.rs` 1466 lines ยท 50194 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 native GPU matmul (no CUDA). 17 //! 18 //! Built against the omega commit in `omega.lock`. With `cfg(has_omega_gpu)` the 19 //! real library is linked; otherwise (`AIEN_FORCE_CPU_STUB=1`, or no omega checkout 20 //! given) every chip call returns [`OmegaGpuError::Unavailable`], so CI passes 21 //! without the chip. Only the API on omega main at the pinned commit is wrapped. 22 //! 23 //! Conventions: row-major, `C[m x n] = A[m x k] * B[k x n]`, f32 output. 24 //! Inputs are bf16 (`matmul_bf16`) or f32 rounded to bf16 on the host (`matmul_f32`). 25 //! Limits (omega FB-1 cut 1b: M <= 8192, K <= 16384, N <= 262144) are enforced by omega 26 //! and surface as `Rc { rc: -2 (TOO_LARGE) }`. 27 pub mod ffi; 28 29 use std::fmt; 30 31 pub use ffi::OmegaGpuMatmulInfo; 32 33 /// Omega commit this crate was built against (from `omega.lock`). 34 pub const PINNED_OMEGA_SHA: &str = env!("AIEN_OMEGA_PINNED_SHA"); 35 36 /// True when the real native library is linked (not the stub). 37 pub const fn is_native() -> bool { 38 cfg!(has_omega_gpu) 39 } 40 41 /// What this binary linked for the omega GPU engine (stub, pinned source, developer override or 42 /// prebuilt), the C ABI check result and the archive digest, as `build.rs` established them. 43 /// Only `qualifies()` identities count as release-grade native qualification. 44 pub fn native_identity() -> aien_abi_conformance::NativeIdentity { 45 aien_abi_conformance::NativeIdentity { 46 component: "libomega_gpu.a", 47 link: env!("AIEN_OMEGA_GPU_LINK"), 48 abi: env!("AIEN_OMEGA_GPU_ABI"), 49 digest: env!("AIEN_OMEGA_GPU_DIGEST"), 50 archive_sha256: env!("AIEN_OMEGA_GPU_ARCHIVE_SHA256"), 51 source_sha: env!("AIEN_OMEGA_GPU_SOURCE_SHA"), 52 aienos_lock: env!("AIEN_OMEGA_GPU_AIENOS_LOCK"), 53 physics_lock: env!("AIEN_OMEGA_GPU_PHYSICS_LOCK"), 54 target: env!("AIEN_OMEGA_GPU_TARGET"), 55 cc: env!("AIEN_OMEGA_GPU_CC"), 56 } 57 } 58 59 #[derive(Debug, Clone, PartialEq, Eq)] 60 pub enum OmegaGpuError { 61 /// Stub build: no native library linked. 62 Unavailable, 63 /// A slice length does not match the stated shape (caught before the C call). 64 ShapeMismatch { 65 what: &'static str, 66 expected: usize, 67 got: usize, 68 }, 69 /// Omega returned a non-zero code; `name` is `omega_gpu_matmul_rc_name(rc)`. 70 Rc { rc: i32, name: String }, 71 } 72 73 impl fmt::Display for OmegaGpuError { 74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 75 match self { 76 Self::Unavailable => write!(f, "omega gpu unavailable (stub build)"), 77 Self::ShapeMismatch { 78 what, 79 expected, 80 got, 81 } => write!(f, "{what}: expected {expected} elements, got {got}"), 82 Self::Rc { rc, name } => write!(f, "omega_gpu rc={rc} ({name})"), 83 } 84 } 85 } 86 87 impl std::error::Error for OmegaGpuError {} 88 89 /// Name of a return code; the C function when native, the same table otherwise. 90 pub fn rc_name(rc: i32) -> String { 91 #[cfg(has_omega_gpu)] 92 { 93 // SAFETY: returns a pointer to a static NUL-terminated string. 94 let p = unsafe { ffi::omega_gpu_matmul_rc_name(rc) }; 95 if !p.is_null() { 96 // SAFETY: non-null, static, NUL-terminated. 97 return unsafe { std::ffi::CStr::from_ptr(p) } 98 .to_string_lossy() 99 .into_owned(); 100 } 101 } 102 match rc { 103 ffi::OMEGA_GPU_MATMUL_OK => "OK", 104 ffi::OMEGA_GPU_MATMUL_BAD_ARGS => "BAD_ARGS", 105 ffi::OMEGA_GPU_MATMUL_TOO_LARGE => "TOO_LARGE", 106 ffi::OMEGA_GPU_MATMUL_CODEGEN_FAIL => "CODEGEN_FAIL", 107 ffi::OMEGA_GPU_MATMUL_CHIP_FAIL => "CHIP_FAIL", 108 ffi::OMEGA_GPU_MATMUL_PARITY_FAIL => "PARITY_FAIL", 109 _ => "UNKNOWN", 110 } 111 .to_string() 112 } 113 114 /// Per-call receipt from omega (copy of `OmegaGpuMatmulInfo`). 115 #[derive(Debug, Clone)] 116 pub struct MatmulInfo { 117 pub raw: OmegaGpuMatmulInfo, 118 } 119 120 impl MatmulInfo { 121 pub fn target_chip(&self) -> String { 122 let bytes: Vec = self 123 .raw 124 .target_chip 125 .iter() 126 .take_while(|&&c| c != 0) 127 .map(|c| c.to_ne_bytes()[0]) 128 .collect(); 129 String::from_utf8_lossy(&bytes).into_owned() 130 } 131 } 132 133 /// Element count of a shape, refused with `TOO_LARGE` (before any C call) if the product 134 /// overflows `usize`: a wrapped product could let a short slice pass `check_len` and hand 135 /// omega dimensions larger than the buffer behind the pointer. 136 fn prod(dims: &[usize]) -> Result { 137 dims.iter() 138 .try_fold(1usize, |acc, &d| acc.checked_mul(d)) 139 .ok_or_else(|| OmegaGpuError::Rc { 140 rc: ffi::OMEGA_GPU_MATMUL_TOO_LARGE, 141 name: rc_name(ffi::OMEGA_GPU_MATMUL_TOO_LARGE), 142 }) 143 } 144 145 fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> { 146 if expected == got { 147 Ok(()) 148 } else { 149 Err(OmegaGpuError::ShapeMismatch { 150 what, 151 expected, 152 got, 153 }) 154 } 155 } 156 157 fn dims(m: usize, k: usize, n: usize) -> Result<(u32, u32, u32), OmegaGpuError> { 158 let conv = |v: usize| { 159 u32::try_from(v).map_err(|_| OmegaGpuError::Rc { 160 rc: ffi::OMEGA_GPU_MATMUL_TOO_LARGE, 161 name: rc_name(ffi::OMEGA_GPU_MATMUL_TOO_LARGE), 162 }) 163 }; 164 Ok((conv(m)?, conv(k)?, conv(n)?)) 165 } 166 167 #[cfg(has_omega_gpu)] 168 fn finish(rc: i32, info: OmegaGpuMatmulInfo) -> Result { 169 if rc == ffi::OMEGA_GPU_MATMUL_OK { 170 Ok(MatmulInfo { raw: info }) 171 } else { 172 Err(OmegaGpuError::Rc { 173 rc, 174 name: rc_name(rc), 175 }) 176 } 177 } 178 179 /// `c = a * b`, bf16 inputs (raw bits), f32 output. 180 pub fn matmul_bf16( 181 m: usize, 182 k: usize, 183 n: usize, 184 a: &[u16], 185 b: &[u16], 186 c: &mut [f32], 187 ) -> Result { 188 check_len("a", prod(&[m, k])?, a.len())?; 189 check_len("b", prod(&[k, n])?, b.len())?; 190 check_len("c", prod(&[m, n])?, c.len())?; 191 let (mu, ku, nu) = dims(m, k, n)?; 192 #[cfg(has_omega_gpu)] 193 { 194 let mut info = OmegaGpuMatmulInfo::zeroed(); 195 // SAFETY: lengths checked above match m*k, k*n, m*n; pointers are valid 196 // for the call; info is a valid out-pointer. 197 let rc = unsafe { 198 ffi::omega_gpu_matmul_bf16( 199 mu, 200 ku, 201 nu, 202 a.as_ptr(), 203 b.as_ptr(), 204 c.as_mut_ptr(), 205 &mut info, 206 ) 207 }; 208 finish(rc, info) 209 } 210 #[cfg(not(has_omega_gpu))] 211 { 212 let _ = (mu, ku, nu); 213 Err(OmegaGpuError::Unavailable) 214 } 215 } 216 217 /// `c = a * b`, f32 inputs rounded to bf16 on the host, f32 output. 218 pub fn matmul_f32( 219 m: usize, 220 k: usize, 221 n: usize, 222 a: &[f32], 223 b: &[f32], 224 c: &mut [f32], 225 ) -> Result { 226 check_len("a", prod(&[m, k])?, a.len())?; 227 check_len("b", prod(&[k, n])?, b.len())?; 228 check_len("c", prod(&[m, n])?, c.len())?; 229 let (mu, ku, nu) = dims(m, k, n)?; 230 #[cfg(has_omega_gpu)] 231 { 232 let mut info = OmegaGpuMatmulInfo::zeroed(); 233 // SAFETY: as in matmul_bf16. 234 let rc = unsafe { 235 ffi::omega_gpu_matmul_f32( 236 mu, 237 ku, 238 nu, 239 a.as_ptr(), 240 b.as_ptr(), 241 c.as_mut_ptr(), 242 &mut info, 243 ) 244 }; 245 finish(rc, info) 246 } 247 #[cfg(not(has_omega_gpu))] 248 { 249 let _ = (mu, ku, nu); 250 Err(OmegaGpuError::Unavailable) 251 } 252 } 253 254 /// Drop every cached kernel (tests; otherwise never needed). No-op in the stub. 255 pub fn cache_clear() { 256 #[cfg(has_omega_gpu)] 257 // SAFETY: takes no arguments; omega guards its cache with a mutex. 258 unsafe { 259 ffi::omega_gpu_matmul_cache_clear() 260 } 261 } 262 263 /// A weight matrix (k x n, bf16, zero-padded by omega) resident on the device 264 /// until dropped. Not `Sync`: omega's resident-call thread safety is not 265 /// documented, so callers must serialize use (the backend holds it in a Mutex). 266 pub struct ResidentTensor { 267 #[cfg(has_omega_gpu)] 268 ptr: *mut ffi::OmegaGpuTensor, 269 k: usize, 270 n: usize, 271 } 272 273 // SAFETY: the handle is an owning pointer to a device buffer with no thread 274 // affinity that we know of (UNVERIFIED in omega docs); we only ever move it 275 // between threads and never share it without external locking. 276 unsafe impl Send for ResidentTensor {} 277 278 impl fmt::Debug for ResidentTensor { 279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 280 write!(f, "ResidentTensor {{ k: {}, n: {} }}", self.k, self.n) 281 } 282 } 283 284 impl ResidentTensor { 285 /// Upload a row-major k x n f32 matrix (rounded to bf16 on the host by omega). 286 pub fn upload_f32(k: usize, n: usize, b: &[f32]) -> Result { 287 check_len("b", prod(&[k, n])?, b.len())?; 288 let (_, ku, nu) = dims(1, k, n)?; 289 #[cfg(has_omega_gpu)] 290 { 291 let mut ptr: *mut ffi::OmegaGpuTensor = std::ptr::null_mut(); 292 // SAFETY: b has k*n elements (checked); ptr is a valid out-pointer. 293 let rc = unsafe { ffi::omega_gpu_tensor_upload_f32(ku, nu, b.as_ptr(), &mut ptr) }; 294 if rc != ffi::OMEGA_GPU_MATMUL_OK || ptr.is_null() { 295 return Err(rc_error(if rc == 0 { 296 ffi::OMEGA_GPU_MATMUL_BAD_ARGS 297 } else { 298 rc 299 })); 300 } 301 Ok(Self { ptr, k, n }) 302 } 303 #[cfg(not(has_omega_gpu))] 304 { 305 let _ = (ku, nu); 306 Err(OmegaGpuError::Unavailable) 307 } 308 } 309 310 /// Upload a row-major k x n matrix of bf16 bit patterns exactly as given (no rounding). 311 /// The resident data equals `upload_f32` of the widened values, except that omega's 312 /// f32-to-bf16 step quiets signaling NaNs (see `aien-inference-abi` `resident.rs`). 313 pub fn upload_bf16(k: usize, n: usize, b: &[u16]) -> Result { 314 check_len("b", prod(&[k, n])?, b.len())?; 315 let (_, ku, nu) = dims(1, k, n)?; 316 #[cfg(has_omega_gpu)] 317 { 318 let mut ptr: *mut ffi::OmegaGpuTensor = std::ptr::null_mut(); 319 // SAFETY: b has k*n elements (checked); ptr is a valid out-pointer. 320 let rc = unsafe { ffi::omega_gpu_tensor_upload_bf16(ku, nu, b.as_ptr(), &mut ptr) }; 321 if rc != ffi::OMEGA_GPU_MATMUL_OK || ptr.is_null() { 322 return Err(rc_error(if rc == 0 { 323 ffi::OMEGA_GPU_MATMUL_BAD_ARGS 324 } else { 325 rc 326 })); 327 } 328 Ok(Self { ptr, k, n }) 329 } 330 #[cfg(not(has_omega_gpu))] 331 { 332 let _ = (ku, nu); 333 Err(OmegaGpuError::Unavailable) 334 } 335 } 336 337 pub fn k(&self) -> usize { 338 self.k 339 } 340 341 pub fn n(&self) -> usize { 342 self.n 343 } 344 345 /// `c[m x n] = a[m x k] * self`, f32 `a` rounded to bf16 on the host, no host oracle. 346 pub fn matmul_f32( 347 &self, 348 m: usize, 349 a: &[f32], 350 c: &mut [f32], 351 ) -> Result { 352 check_len("a", prod(&[m, self.k])?, a.len())?; 353 check_len("c", prod(&[m, self.n])?, c.len())?; 354 let (mu, _, _) = dims(m, self.k, self.n)?; 355 #[cfg(has_omega_gpu)] 356 { 357 let mut info = OmegaGpuMatmulInfo::zeroed(); 358 // SAFETY: lengths checked; self.ptr is a live handle owned by self. 359 let rc = unsafe { 360 ffi::omega_gpu_matmul_resident_f32( 361 mu, 362 a.as_ptr(), 363 self.ptr, 364 c.as_mut_ptr(), 365 &mut info, 366 ) 367 }; 368 finish(rc, info) 369 } 370 #[cfg(not(has_omega_gpu))] 371 { 372 let _ = mu; 373 Err(OmegaGpuError::Unavailable) 374 } 375 } 376 } 377 378 impl Drop for ResidentTensor { 379 fn drop(&mut self) { 380 #[cfg(has_omega_gpu)] 381 // SAFETY: ptr came from a successful upload and is freed exactly once. 382 unsafe { 383 ffi::omega_gpu_tensor_free(self.ptr) 384 } 385 } 386 } 387 388 #[cfg(has_omega_gpu)] 389 fn rc_error(rc: i32) -> OmegaGpuError { 390 OmegaGpuError::Rc { 391 rc, 392 name: rc_name(rc), 393 } 394 } 395 396 /// Stage name of the most recent chip failure ("" if none; always "" in the stub). 397 pub fn last_error() -> String { 398 #[cfg(has_omega_gpu)] 399 { 400 // SAFETY: returns a pointer to a static or internal NUL-terminated string. 401 let p = unsafe { ffi::omega_gpu_matmul_last_error() }; 402 if !p.is_null() { 403 // SAFETY: non-null and NUL-terminated. 404 return unsafe { std::ffi::CStr::from_ptr(p) } 405 .to_string_lossy() 406 .into_owned(); 407 } 408 } 409 String::new() 410 } 411 412 /// True once an uncertain completion has latched the process (every later chip call fails). 413 pub fn is_blocked() -> bool { 414 #[cfg(has_omega_gpu)] 415 // SAFETY: no arguments, returns an int. 416 return unsafe { ffi::omega_gpu_matmul_is_blocked() } != 0; 417 #[cfg(not(has_omega_gpu))] 418 false 419 } 420 421 // ---- matmul launch budget (omega `c0369e6` `omega_gpu_matmul_api.h:130-133`) ---- 422 423 /// Daemon setting that picks the matmul CTA budget per launch. Unset or empty 424 /// means the AIEN daemon default ([`DAEMON_DEFAULT_CTA_BUDGET`], 1024); omega's 425 /// own library default ([`ffi::OMEGA_GPU_MATMUL_MAX_CTAS`], 1024 since omega `98cecadc`, #473) 426 /// is not changed by it. 427 pub const CTA_BUDGET_ENV: &str = "AIEN_OMEGA_CTA_BUDGET"; 428 429 /// Largest budget [`parse_cta_budget`] accepts. Budgets chip-tested on the GB10: 430 /// 64 (the old omega default) and 256 (T4 2026-10-06, t4fix), and 512 and 1024 on 431 /// 2026-10-12 (fragment kernel, Qwen3-8B decode shapes, parity ok, mutant 432 /// killed; see [`DAEMON_DEFAULT_CTA_BUDGET_EVIDENCE`]). Larger values were 433 /// never chip-tested, so they are refused. 434 pub const CTA_BUDGET_MAX_MEASURED: u32 = 1024; 435 436 /// A validated CTA budget (1..=[`CTA_BUDGET_MAX_MEASURED`]). Only 437 /// [`parse_cta_budget`] and [`DAEMON_DEFAULT_CTA_BUDGET`] build one, so 438 /// [`set_cta_budget`] never sees 0 (which omega reads as "restore the 439 /// default") or an unmeasured size. 440 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 441 pub struct CtaBudget(u32); 442 443 impl CtaBudget { 444 pub const fn get(self) -> u32 { 445 self.0 446 } 447 } 448 449 /// The AIEN daemon's budget when [`CTA_BUDGET_ENV`] is unset: 1024. Sealed 450 /// GB10 evidence in [`DAEMON_DEFAULT_CTA_BUDGET_EVIDENCE`] (2026-10-12, Qwen3-8B 451 /// bf16 decode shapes, median of 100 calls): 4096x12288 2.25 ms at 64, 0.52 at 452 /// 512, 0.42 at 1024 (240 GB/s of the 273 GB/s the chip moves); 4096x4096 0.82 -> 453 /// 0.21; lm_head 4096x151936 24.3 -> 6.3 / 6.9; parity ok on every run, the 454 /// mutant kernel killed; Qwen3-8B smoke p3 decode 116 -> 100 ms/token, replies 455 /// unchanged. The earlier 256 evidence (t4fix-20261006T2254Z: decode 456 /// 89.7 ms/token at 256 vs 184.7 at 64 on Qwen3-4B) stands as history. 457 pub const DAEMON_DEFAULT_CTA_BUDGET: CtaBudget = CtaBudget(1024); 458 459 /// Repository path of the evidence behind [`DAEMON_DEFAULT_CTA_BUDGET`]. 460 pub const DAEMON_DEFAULT_CTA_BUDGET_EVIDENCE: &str = 461 "docs/inference/evidence/cta1024-20261012T0315Z"; 462 463 /// Parse the [`CTA_BUDGET_ENV`] setting. `None` or blank: `Ok(None)` (the caller 464 /// picks its default). Otherwise a plain decimal integer in 465 /// 1..=[`CTA_BUDGET_MAX_MEASURED`]; anything else is an error naming the value. 466 pub fn parse_cta_budget(raw: Option<&str>) -> Result, String> { 467 let Some(text) = raw.map(str::trim).filter(|t| !t.is_empty()) else { 468 return Ok(None); 469 }; 470 let refuse = |why: &str| { 471 Err(format!( 472 "{CTA_BUDGET_ENV}={text:?} refused: {why} (allowed 1..={CTA_BUDGET_MAX_MEASURED}; unset uses the AIEN daemon default {})", 473 DAEMON_DEFAULT_CTA_BUDGET.get() 474 )) 475 }; 476 if !text.bytes().all(|b| b.is_ascii_digit()) { 477 return refuse("not a plain decimal integer"); 478 } 479 match text.parse::() { 480 Ok(0) => refuse("0 would silently restore omega's default"), 481 Ok(v) if v <= CTA_BUDGET_MAX_MEASURED => Ok(Some(CtaBudget(v))), 482 Ok(_) | Err(_) => refuse("larger than any budget measured on the GB10"), 483 } 484 } 485 486 /// Set omega's per-launch CTA budget. Omega clears its kernel cache (kernels 487 /// bake in the grid), so call it before the first matmul. Stub: `Unavailable`. 488 pub fn set_cta_budget(budget: CtaBudget) -> Result<(), OmegaGpuError> { 489 #[cfg(has_omega_gpu)] 490 { 491 // SAFETY: plain u32 argument; omega takes its session lock inside. 492 unsafe { ffi::omega_gpu_matmul_set_cta_budget(budget.0) }; 493 Ok(()) 494 } 495 #[cfg(not(has_omega_gpu))] 496 { 497 let _ = budget; 498 Err(OmegaGpuError::Unavailable) 499 } 500 } 501 502 /// The CTA budget omega will use for the next launch; `None` in the stub. 503 pub fn cta_budget() -> Option { 504 #[cfg(has_omega_gpu)] 505 // SAFETY: no arguments; reads one u32 field, does not open the device. 506 return Some(unsafe { ffi::omega_gpu_matmul_cta_budget() }); 507 #[cfg(not(has_omega_gpu))] 508 None 509 } 510 511 /// Environment setting for omega's marker-wait spin window, in microseconds 512 /// (omega#328). Unset or blank means the AIEN daemon default 513 /// ([`DAEMON_DEFAULT_SPIN_US`]); 0 restores omega's own default, the 50 us 514 /// sleep-poll that timer slack rounds to about 102 us per launch. 515 pub const SPIN_US_ENV: &str = "AIEN_OMEGA_SPIN_US"; 516 517 /// The AIEN daemon's window when [`SPIN_US_ENV`] is unset: 2000 us. Sealed GB10 518 /// evidence in [`DAEMON_DEFAULT_SPIN_US_EVIDENCE`]: Qwen3-4B decode 310 -> 268 ms/token 519 /// with identical replies (two alternating pairs). 520 pub const DAEMON_DEFAULT_SPIN_US: u32 = 2000; 521 522 /// Repository path of the evidence behind [`DAEMON_DEFAULT_SPIN_US`]. 523 pub const DAEMON_DEFAULT_SPIN_US_EVIDENCE: &str = "docs/inference/evidence/spin-20261007T0726Z"; 524 525 /// Largest window omega accepts (`OMEGA_GPU_SESSION_MAX_SPIN_US`). 526 pub const SPIN_US_MAX: u32 = 1_000_000; 527 528 // The daemon default must be a window omega accepts (checked at build time). 529 const _: () = assert!(DAEMON_DEFAULT_SPIN_US <= SPIN_US_MAX); 530 531 /// Parse the [`SPIN_US_ENV`] setting. `None` or blank: `Ok(None)` (the caller 532 /// picks its default). Otherwise a plain decimal integer in 0..=[`SPIN_US_MAX`]; 533 /// anything else is an error naming the value. 534 pub fn parse_spin_us(raw: Option<&str>) -> Result, String> { 535 let Some(text) = raw.map(str::trim).filter(|t| !t.is_empty()) else { 536 return Ok(None); 537 }; 538 let refuse = |why: &str| { 539 Err(format!( 540 "{SPIN_US_ENV}={text:?} refused: {why} (allowed 0..={SPIN_US_MAX}; unset uses the AIEN daemon default {DAEMON_DEFAULT_SPIN_US})" 541 )) 542 }; 543 if !text.bytes().all(|b| b.is_ascii_digit()) { 544 return refuse("not a plain decimal integer"); 545 } 546 match text.parse::() { 547 Ok(v) if v <= SPIN_US_MAX => Ok(Some(v)), 548 Ok(_) | Err(_) => refuse("larger than omega's maximum"), 549 } 550 } 551 552 /// Set omega's marker-wait spin window. Stub: `Unavailable`. 553 pub fn set_spin_us(us: u32) -> Result<(), OmegaGpuError> { 554 #[cfg(has_omega_gpu)] 555 { 556 // SAFETY: plain u32 argument; omega stores it atomically and does not open the device. 557 let rc = unsafe { ffi::omega_gpu_session_set_spin_us(us) }; 558 if rc == 0 { 559 Ok(()) 560 } else { 561 Err(OmegaGpuError::Rc { 562 rc, 563 name: format!("spin window {us} us refused (maximum {SPIN_US_MAX})"), 564 }) 565 } 566 } 567 #[cfg(not(has_omega_gpu))] 568 { 569 let _ = us; 570 Err(OmegaGpuError::Unavailable) 571 } 572 } 573 574 /// The spin window omega will use for the next launch; `None` in the stub. 575 pub fn spin_us() -> Option { 576 #[cfg(has_omega_gpu)] 577 // SAFETY: no arguments; reads one u32, does not open the device. 578 return Some(unsafe { ffi::omega_gpu_session_spin_us() }); 579 #[cfg(not(has_omega_gpu))] 580 None 581 } 582 583 // ---- native elementwise ops (omega FB-1 cut 4) ---- 584 585 pub use ffi::OmegaGpuEwInfo; 586 587 /// Name of an elementwise return code (omega's table when native). 588 pub fn ew_rc_name(rc: i32) -> String { 589 #[cfg(has_omega_gpu)] 590 { 591 // SAFETY: returns a pointer to a static NUL-terminated string. 592 let p = unsafe { ffi::omega_gpu_elementwise_rc_name(rc) }; 593 if !p.is_null() { 594 // SAFETY: non-null, static, NUL-terminated. 595 return unsafe { std::ffi::CStr::from_ptr(p) } 596 .to_string_lossy() 597 .into_owned(); 598 } 599 } 600 match rc { 601 ffi::OMEGA_GPU_EW_OK => "OK", 602 ffi::OMEGA_GPU_EW_BAD_ARGS => "BAD_ARGS", 603 ffi::OMEGA_GPU_EW_TOO_LARGE => "TOO_LARGE", 604 ffi::OMEGA_GPU_EW_CODEGEN_FAIL => "CODEGEN_FAIL", 605 ffi::OMEGA_GPU_EW_CHIP_FAIL => "CHIP_FAIL", 606 ffi::OMEGA_GPU_EW_UNWRITTEN => "UNWRITTEN", 607 _ => "UNKNOWN", 608 } 609 .to_string() 610 } 611 612 #[cfg(has_omega_gpu)] 613 fn ew_finish(rc: i32, info: OmegaGpuEwInfo) -> Result { 614 if rc == ffi::OMEGA_GPU_EW_OK { 615 Ok(info) 616 } else { 617 Err(OmegaGpuError::Rc { 618 rc, 619 name: ew_rc_name(rc), 620 }) 621 } 622 } 623 624 fn ew_dim(v: usize) -> Result { 625 u32::try_from(v).map_err(|_| OmegaGpuError::Rc { 626 rc: ffi::OMEGA_GPU_EW_TOO_LARGE, 627 name: ew_rc_name(ffi::OMEGA_GPU_EW_TOO_LARGE), 628 }) 629 } 630 631 /// `out[r*dim+i] = x[r*dim+i] * scale_r * weight[i]`, `scale_r = 1/sqrt(mean(x^2)+eps)`. 632 /// omega requires `dim % 128 == 0` and `dim <= 16384`; otherwise `Rc { rc: -1 | -2 }`. 633 pub fn rmsnorm_f32( 634 rows: usize, 635 dim: usize, 636 x: &[f32], 637 weight: &[f32], 638 eps: f32, 639 out: &mut [f32], 640 ) -> Result { 641 check_len("x", prod(&[rows, dim])?, x.len())?; 642 check_len("weight", dim, weight.len())?; 643 check_len("out", prod(&[rows, dim])?, out.len())?; 644 let (ru, du) = (ew_dim(rows)?, ew_dim(dim)?); 645 #[cfg(has_omega_gpu)] 646 { 647 let mut info = OmegaGpuEwInfo::zeroed(); 648 // SAFETY: lengths checked above; pointers valid for the call; info is an out-pointer. 649 let rc = unsafe { 650 ffi::omega_gpu_rmsnorm_f32( 651 ru, 652 du, 653 x.as_ptr(), 654 weight.as_ptr(), 655 eps, 656 out.as_mut_ptr(), 657 &mut info, 658 ) 659 }; 660 ew_finish(rc, info) 661 } 662 #[cfg(not(has_omega_gpu))] 663 { 664 let _ = (ru, du, eps); 665 Err(OmegaGpuError::Unavailable) 666 } 667 } 668 669 /// Rotate `heads` heads of `head_dim` values (rotate_half pairing `i, i+head_dim/2`) with a 670 /// host-provided table of `head_dim/2` cos and sin values (same for every head). 671 /// `out` may not alias `v` in safe Rust; omega itself copies through its own buffers. 672 pub fn rope_f32( 673 heads: usize, 674 head_dim: usize, 675 v: &[f32], 676 cos_half: &[f32], 677 sin_half: &[f32], 678 out: &mut [f32], 679 ) -> Result { 680 check_len("v", prod(&[heads, head_dim])?, v.len())?; 681 check_len("cos_half", head_dim / 2, cos_half.len())?; 682 check_len("sin_half", head_dim / 2, sin_half.len())?; 683 check_len("out", prod(&[heads, head_dim])?, out.len())?; 684 let (hu, du) = (ew_dim(heads)?, ew_dim(head_dim)?); 685 #[cfg(has_omega_gpu)] 686 { 687 let mut info = OmegaGpuEwInfo::zeroed(); 688 // SAFETY: lengths checked above; pointers valid for the call. 689 let rc = unsafe { 690 ffi::omega_gpu_rope_f32( 691 hu, 692 du, 693 v.as_ptr(), 694 cos_half.as_ptr(), 695 sin_half.as_ptr(), 696 out.as_mut_ptr(), 697 &mut info, 698 ) 699 }; 700 ew_finish(rc, info) 701 } 702 #[cfg(not(has_omega_gpu))] 703 { 704 let _ = (hu, du); 705 Err(OmegaGpuError::Unavailable) 706 } 707 } 708 709 /// `out[i] = silu(gate[i]) * up[i]` for `i < n` (`n = gate.len()`, all three equal length). 710 pub fn swiglu_f32( 711 gate: &[f32], 712 up: &[f32], 713 out: &mut [f32], 714 ) -> Result { 715 check_len("up", gate.len(), up.len())?; 716 check_len("out", gate.len(), out.len())?; 717 let nu = ew_dim(gate.len())?; 718 #[cfg(has_omega_gpu)] 719 { 720 let mut info = OmegaGpuEwInfo::zeroed(); 721 // SAFETY: lengths checked equal; pointers valid for the call. 722 let rc = unsafe { 723 ffi::omega_gpu_swiglu_f32(nu, gate.as_ptr(), up.as_ptr(), out.as_mut_ptr(), &mut info) 724 }; 725 ew_finish(rc, info) 726 } 727 #[cfg(not(has_omega_gpu))] 728 { 729 let _ = nu; 730 Err(OmegaGpuError::Unavailable) 731 } 732 } 733 734 // ---- native decode attention (omega FB-1 cut 5, persistent session cut 4b) ---- 735 736 pub use ffi::{OmegaGpuAttnInfo, OmegaGpuKvLayout}; 737 738 /// Name of an attention return code (omega's table when native). 739 pub fn attn_rc_name(rc: i32) -> String { 740 #[cfg(has_omega_gpu)] 741 { 742 // SAFETY: returns a pointer to a static NUL-terminated string. 743 let p = unsafe { ffi::omega_gpu_attention_rc_name(rc) }; 744 if !p.is_null() { 745 // SAFETY: non-null, static, NUL-terminated. 746 return unsafe { std::ffi::CStr::from_ptr(p) } 747 .to_string_lossy() 748 .into_owned(); 749 } 750 } 751 match rc { 752 ffi::OMEGA_GPU_ATTN_OK => "OK", 753 ffi::OMEGA_GPU_ATTN_BAD_ARGS => "BAD_ARGS", 754 ffi::OMEGA_GPU_ATTN_TOO_LARGE => "TOO_LARGE", 755 ffi::OMEGA_GPU_ATTN_CODEGEN_FAIL => "CODEGEN_FAIL", 756 ffi::OMEGA_GPU_ATTN_CHIP_FAIL => "CHIP_FAIL", 757 ffi::OMEGA_GPU_ATTN_UNWRITTEN => "UNWRITTEN", 758 _ => "UNKNOWN", 759 } 760 .to_string() 761 } 762 763 #[cfg(has_omega_gpu)] 764 fn attn_finish(rc: i32, info: OmegaGpuAttnInfo) -> Result { 765 if rc == ffi::OMEGA_GPU_ATTN_OK { 766 Ok(info) 767 } else { 768 Err(OmegaGpuError::Rc { 769 rc, 770 name: attn_rc_name(rc), 771 }) 772 } 773 } 774 775 fn attn_dim(v: usize) -> Result { 776 u32::try_from(v).map_err(|_| OmegaGpuError::Rc { 777 rc: ffi::OMEGA_GPU_ATTN_TOO_LARGE, 778 name: attn_rc_name(ffi::OMEGA_GPU_ATTN_TOO_LARGE), 779 }) 780 } 781 782 /// Decode attention over contiguous f32 KV (`TensorBackend::gqa_attention`). 783 /// `q`, `out`: `[num_q_heads][head_dim]`; `k_cache`, `v_cache`: `[seq_len][num_kv_heads][head_dim]`. 784 /// omega requires `head_dim` 64 or 128 and `num_q_heads <= 64`; otherwise `Rc { rc: -1 | -2 }`. 785 #[allow(clippy::too_many_arguments)] 786 pub fn gqa_attention_f32( 787 q: &[f32], 788 k_cache: &[f32], 789 v_cache: &[f32], 790 seq_len: usize, 791 num_q_heads: usize, 792 num_kv_heads: usize, 793 head_dim: usize, 794 out: &mut [f32], 795 ) -> Result { 796 check_len("q", prod(&[num_q_heads, head_dim])?, q.len())?; 797 check_len( 798 "k_cache", 799 prod(&[seq_len, num_kv_heads, head_dim])?, 800 k_cache.len(), 801 )?; 802 check_len( 803 "v_cache", 804 prod(&[seq_len, num_kv_heads, head_dim])?, 805 v_cache.len(), 806 )?; 807 check_len("out", prod(&[num_q_heads, head_dim])?, out.len())?; 808 let (su, qh, kh, hd) = ( 809 attn_dim(seq_len)?, 810 attn_dim(num_q_heads)?, 811 attn_dim(num_kv_heads)?, 812 attn_dim(head_dim)?, 813 ); 814 #[cfg(has_omega_gpu)] 815 { 816 let mut info = OmegaGpuAttnInfo::zeroed(); 817 // SAFETY: lengths checked above; pointers valid for the call; info is an out-pointer. 818 let rc = unsafe { 819 ffi::omega_gpu_gqa_attention_f32( 820 q.as_ptr(), 821 k_cache.as_ptr(), 822 v_cache.as_ptr(), 823 su, 824 qh, 825 kh, 826 hd, 827 out.as_mut_ptr(), 828 &mut info, 829 ) 830 }; 831 attn_finish(rc, info) 832 } 833 #[cfg(not(has_omega_gpu))] 834 { 835 let _ = (su, qh, kh, hd); 836 Err(OmegaGpuError::Unavailable) 837 } 838 } 839 840 /// Prompt-read attention over a contiguous f32 KV cache, many query rows in one call 841 /// (omega#406). `q`, `out`: `[num_rows][num_q_heads][head_dim]`; `k_cache`, `v_cache`: 842 /// `[base_len + num_rows][num_kv_heads][head_dim]`. Row `i` attends over the first 843 /// `base_len + i + 1` tokens (causal). The KV is staged once; the rows go in launches of up to 844 /// 1024 CTAs. One row is bit-identical to [`gqa_attention_f32`]. 845 #[allow(clippy::too_many_arguments)] 846 pub fn gqa_attention_rows_f32( 847 q: &[f32], 848 k_cache: &[f32], 849 v_cache: &[f32], 850 base_len: usize, 851 num_rows: usize, 852 num_q_heads: usize, 853 num_kv_heads: usize, 854 head_dim: usize, 855 out: &mut [f32], 856 ) -> Result { 857 let total = base_len 858 .checked_add(num_rows) 859 .ok_or_else(|| OmegaGpuError::Rc { 860 rc: ffi::OMEGA_GPU_MATMUL_TOO_LARGE, 861 name: rc_name(ffi::OMEGA_GPU_MATMUL_TOO_LARGE), 862 })?; 863 check_len("q", prod(&[num_rows, num_q_heads, head_dim])?, q.len())?; 864 check_len( 865 "k_cache", 866 prod(&[total, num_kv_heads, head_dim])?, 867 k_cache.len(), 868 )?; 869 check_len( 870 "v_cache", 871 prod(&[total, num_kv_heads, head_dim])?, 872 v_cache.len(), 873 )?; 874 check_len("out", prod(&[num_rows, num_q_heads, head_dim])?, out.len())?; 875 let (bl, nr, qh, kh, hd) = ( 876 attn_dim(base_len)?, 877 attn_dim(num_rows)?, 878 attn_dim(num_q_heads)?, 879 attn_dim(num_kv_heads)?, 880 attn_dim(head_dim)?, 881 ); 882 #[cfg(has_omega_gpu)] 883 { 884 let mut info = OmegaGpuAttnInfo::zeroed(); 885 // SAFETY: lengths checked above; pointers valid for the call; info is an out-pointer. 886 let rc = unsafe { 887 ffi::omega_gpu_gqa_attention_rows_f32( 888 q.as_ptr(), 889 k_cache.as_ptr(), 890 v_cache.as_ptr(), 891 bl, 892 nr, 893 qh, 894 kh, 895 hd, 896 out.as_mut_ptr(), 897 &mut info, 898 ) 899 }; 900 attn_finish(rc, info) 901 } 902 #[cfg(not(has_omega_gpu))] 903 { 904 let _ = (bl, nr, qh, kh, hd); 905 Err(OmegaGpuError::Unavailable) 906 } 907 } 908 909 /// Decode attention over the bf16 paged KV pool (`TensorBackend::paged_attention`). 910 /// `pool` is the whole pool (at least `layout.pool_bytes` bytes); `block_ids` lists the 911 /// sequence's blocks in token order. `q`, `out`: `[num_q_heads][head_dim]`. 912 #[allow(clippy::too_many_arguments)] 913 pub fn paged_attention_bf16( 914 q: &[f32], 915 pool: &[u8], 916 layout: &OmegaGpuKvLayout, 917 block_ids: &[u32], 918 context_len: usize, 919 layer_idx: usize, 920 num_q_heads: usize, 921 num_kv_heads: usize, 922 head_dim: usize, 923 out: &mut [f32], 924 ) -> Result { 925 check_len("q", prod(&[num_q_heads, head_dim])?, q.len())?; 926 check_len("out", prod(&[num_q_heads, head_dim])?, out.len())?; 927 check_pool(pool, layout)?; 928 let (nb, cl, li, qh, kh, hd) = ( 929 attn_dim(block_ids.len())?, 930 attn_dim(context_len)?, 931 attn_dim(layer_idx)?, 932 attn_dim(num_q_heads)?, 933 attn_dim(num_kv_heads)?, 934 attn_dim(head_dim)?, 935 ); 936 #[cfg(has_omega_gpu)] 937 { 938 let mut info = OmegaGpuAttnInfo::zeroed(); 939 // SAFETY: q/out lengths checked; pool covers layout.pool_bytes; block_ids has nb entries. 940 let rc = unsafe { 941 ffi::omega_gpu_paged_attention_bf16( 942 q.as_ptr(), 943 pool.as_ptr().cast(), 944 layout, 945 block_ids.as_ptr(), 946 nb, 947 cl, 948 li, 949 qh, 950 kh, 951 hd, 952 out.as_mut_ptr(), 953 &mut info, 954 ) 955 }; 956 attn_finish(rc, info) 957 } 958 #[cfg(not(has_omega_gpu))] 959 { 960 let _ = (nb, cl, li, qh, kh, hd); 961 Err(OmegaGpuError::Unavailable) 962 } 963 } 964 965 /// Batched decode attention (`TensorBackend::paged_attention_batch`). 966 /// `block_tables`: `[num_seqs][max_blocks_per_seq]` (negative = none), `context_lens`: `[num_seqs]`. 967 /// `q`, `out`: `[num_seqs][num_q_heads][head_dim]`. 968 #[allow(clippy::too_many_arguments)] 969 pub fn paged_attention_batch_bf16( 970 q: &[f32], 971 pool: &[u8], 972 layout: &OmegaGpuKvLayout, 973 block_tables: &[i32], 974 context_lens: &[i32], 975 max_blocks_per_seq: usize, 976 num_seqs: usize, 977 layer_idx: usize, 978 num_q_heads: usize, 979 num_kv_heads: usize, 980 head_dim: usize, 981 out: &mut [f32], 982 ) -> Result { 983 check_len("q", prod(&[num_seqs, num_q_heads, head_dim])?, q.len())?; 984 check_len("out", prod(&[num_seqs, num_q_heads, head_dim])?, out.len())?; 985 check_len("context_lens", num_seqs, context_lens.len())?; 986 check_len( 987 "block_tables", 988 prod(&[num_seqs, max_blocks_per_seq])?, 989 block_tables.len(), 990 )?; 991 check_pool(pool, layout)?; 992 let (mb, ns, li, qh, kh, hd) = ( 993 attn_dim(max_blocks_per_seq)?, 994 attn_dim(num_seqs)?, 995 attn_dim(layer_idx)?, 996 attn_dim(num_q_heads)?, 997 attn_dim(num_kv_heads)?, 998 attn_dim(head_dim)?, 999 ); 1000 #[cfg(has_omega_gpu)] 1001 { 1002 let mut info = OmegaGpuAttnInfo::zeroed(); 1003 // SAFETY: every slice length checked against the stated shape; pool covers the layout. 1004 let rc = unsafe { 1005 ffi::omega_gpu_paged_attention_batch_bf16( 1006 q.as_ptr(), 1007 pool.as_ptr().cast(), 1008 layout, 1009 block_tables.as_ptr(), 1010 context_lens.as_ptr(), 1011 mb, 1012 ns, 1013 li, 1014 qh, 1015 kh, 1016 hd, 1017 out.as_mut_ptr(), 1018 &mut info, 1019 ) 1020 }; 1021 attn_finish(rc, info) 1022 } 1023 #[cfg(not(has_omega_gpu))] 1024 { 1025 let _ = (mb, ns, li, qh, kh, hd); 1026 Err(OmegaGpuError::Unavailable) 1027 } 1028 } 1029 1030 fn check_pool(pool: &[u8], layout: &OmegaGpuKvLayout) -> Result<(), OmegaGpuError> { 1031 let need = usize::try_from(layout.pool_bytes).unwrap_or(usize::MAX); 1032 if pool.len() < need { 1033 return Err(OmegaGpuError::ShapeMismatch { 1034 what: "pool", 1035 expected: need, 1036 got: pool.len(), 1037 }); 1038 } 1039 Ok(()) 1040 } 1041 1042 // ---- opt-in serving reservation (omega `b980783`, omega#333; sovereign-core#277) ---- 1043 1044 /// Declared serving bounds, the Rust twin of omega's `OmegaGpuServingBounds` 1045 /// (`src/omega_gpu_serving.h`). Every field is a bound the daemon declares at start-up; 1046 /// omega reserves the driver memory for them once and refuses a call past them. 1047 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 1048 pub struct ServingBounds { 1049 /// Longest sequence (tokens) one attention call may cover. 1050 pub max_context: u32, 1051 /// Sequences per attention call (the GB10 backend calls attention one sequence at a time: 1). 1052 pub max_seqs: u32, 1053 pub num_q_heads: u32, 1054 pub num_kv_heads: u32, 1055 pub head_dim: u32, 1056 /// Paged KV block size in tokens (power of two). 1057 pub kv_block_size: u32, 1058 /// Most rows one matmul call may carry. 1059 pub max_rows: u32, 1060 /// Widest weight input dimension. 1061 pub max_k: u32, 1062 /// Widest weight output dimension for calls of up to `max_rows` rows. 1063 pub max_n: u32, 1064 /// Widest output dimension for calls of at most 16 rows (the logits projection). 1065 pub max_n_one_row: u32, 1066 /// Matmul kernel cache slots (omega allows at most 128, CACHE_SLOTS_MAX). 1067 pub kernel_slots: u32, 1068 } 1069 1070 /// Driver bytes a reservation asks for, computed with omega's own formulas 1071 /// (`omega_gpu_attention_reserve`, attention_api.c:664-681; `omega_gpu_matmul_reserve`, 1072 /// matmul_api.c:130-150, at `b980783`). Reported in the daemon log so a chip run can compare 1073 /// it with the driver's allocation counters. 1074 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 1075 pub struct ServingBytes { 1076 pub attention_pool: u64, 1077 pub attention_q_out: u64, 1078 pub attention_table: u64, 1079 pub matmul_activation: u64, 1080 pub matmul_result: u64, 1081 } 1082 1083 impl ServingBytes { 1084 pub fn total(&self) -> u64 { 1085 self.attention_pool 1086 + 2 * self.attention_q_out 1087 + self.attention_table 1088 + self.matmul_activation 1089 + self.matmul_result 1090 } 1091 } 1092 1093 fn round_up(v: u64, to: u64) -> u64 { 1094 v.div_ceil(to) * to 1095 } 1096 1097 impl ServingBounds { 1098 /// Bytes omega will reserve for these bounds. Tiles: omega `OMEGA_GPU_MATMUL_TILE_M` 16, 1099 /// `_TILE_N` 8, `_TILE_K` 16 (omega_gpu_matmul_api.h:46-48). 1100 pub fn bytes(&self) -> ServingBytes { 1101 // Each buffer is rounded to a 4 KiB page by omega (checked against omega's fake driver 1102 // layer: `194170880` bytes for the Qwen3-4B daemon bounds, see the unit test). 1103 let (ctx, seqs) = (self.max_context as u64, self.max_seqs.max(1) as u64); 1104 let (kvh, hd) = (self.num_kv_heads as u64, self.head_dim as u64); 1105 let mut per_seq = 2 * ctx * kvh * hd * 4; 1106 if self.kv_block_size != 0 { 1107 let bs = self.kv_block_size as u64; 1108 per_seq = per_seq.max(round_up(ctx, bs) * kvh * hd * 4); 1109 } 1110 let qo = seqs * self.num_q_heads as u64 * hd * 4; 1111 let table = round_up(((seqs * ctx + seqs) * 4).max(8), 4096); 1112 let mp = round_up(self.max_rows as u64, 16); 1113 let kp = round_up(self.max_k as u64, 16); 1114 let mut c = mp * round_up(self.max_n as u64, 8) * 4; 1115 if self.max_n_one_row != 0 { 1116 c = c.max(16 * round_up(self.max_n_one_row as u64, 8) * 4); 1117 } 1118 ServingBytes { 1119 attention_pool: round_up(per_seq * seqs, 4096), 1120 attention_q_out: round_up(qo, 4096), 1121 attention_table: table, 1122 matmul_activation: round_up(mp * kp * 2, 4096), 1123 matmul_result: round_up(c, 4096), 1124 } 1125 } 1126 } 1127 1128 /// Reserve the serving buffers once (opens the device if needed): omega's own all-or-nothing 1129 /// `omega_gpu_reserve_serving` (`src/omega_gpu_serving.c`, in libomega_gpu.a since omega#338). 1130 /// On refusal the error carries omega's return-code name; callers add `last_error()` for the 1131 /// stage text (for example "serving reservation exceeded" or the driver's allocation failure). 1132 /// Stub: `Unavailable`. 1133 pub fn reserve_serving(b: &ServingBounds) -> Result<(), OmegaGpuError> { 1134 #[cfg(has_omega_gpu)] 1135 { 1136 let c = ffi::OmegaGpuServingBounds { 1137 max_context: b.max_context, 1138 max_seqs: b.max_seqs, 1139 num_q_heads: b.num_q_heads, 1140 num_kv_heads: b.num_kv_heads, 1141 head_dim: b.head_dim, 1142 kv_block_size: b.kv_block_size, 1143 max_rows: b.max_rows, 1144 max_k: b.max_k, 1145 max_n: b.max_n, 1146 max_n_one_row: b.max_n_one_row, 1147 kernel_slots: b.kernel_slots, 1148 }; 1149 // SAFETY: `c` is a valid, fully initialised repr(C) struct that omega only reads. 1150 let rc = unsafe { ffi::omega_gpu_reserve_serving(&c) }; 1151 if rc == 0 { 1152 Ok(()) 1153 } else { 1154 // matmul and attention codes share the numbering 0/-1..-5; the matmul table names them. 1155 Err(rc_error(rc)) 1156 } 1157 } 1158 #[cfg(not(has_omega_gpu))] 1159 { 1160 let _ = b; 1161 Err(OmegaGpuError::Unavailable) 1162 } 1163 } 1164 1165 /// Driver allocation counters since the process started (omega `omega_gpu_session_alloc_stats`). 1166 pub use ffi::OmegaGpuAllocStats as AllocStats; 1167 1168 /// Read omega's allocation counters; `None` in the stub (no engine, nothing allocates). 1169 pub fn alloc_stats() -> Option { 1170 #[cfg(has_omega_gpu)] 1171 { 1172 let mut s = AllocStats::default(); 1173 // SAFETY: `s` is a valid repr(C) struct that omega fills; no lock is held across the call. 1174 unsafe { ffi::omega_gpu_session_alloc_stats(&mut s) }; 1175 Some(s) 1176 } 1177 #[cfg(not(has_omega_gpu))] 1178 None 1179 } 1180 1181 /// `OmegaGpuAttnInfo.kv_source`: the KV layer slices were copied into staging for the call. 1182 pub const KV_SOURCE_STAGED: u32 = 0; 1183 /// `OmegaGpuAttnInfo.kv_source`: the paged attention read the resident pool in place. 1184 pub const KV_SOURCE_RESIDENT: u32 = 1; 1185 1186 /// Allocate omega's resident KV pool (omega `omega_gpu_attention_pool_alloc`): one GPU-uncached, 1187 /// host-visible allocation of `bytes` whose chip address equals its host address. A paged 1188 /// attention call whose pool is this memory reads it in place (nothing staged) whenever every 1189 /// referenced block fits the kernel's 32-bit block arithmetic; otherwise it stages as before. 1190 /// One per process; free with `resident_kv_pool_free`. Returns the host pointer and the length. 1191 /// Stub: `Unavailable`. 1192 pub fn resident_kv_pool_alloc(bytes: usize) -> Result<(*mut u8, usize), OmegaGpuError> { 1193 if bytes == 0 { 1194 return Err(OmegaGpuError::ShapeMismatch { 1195 what: "resident KV pool bytes", 1196 expected: 1, 1197 got: 0, 1198 }); 1199 } 1200 #[cfg(has_omega_gpu)] 1201 { 1202 let mut cpu: *mut std::ffi::c_void = std::ptr::null_mut(); 1203 // SAFETY: omega writes the host pointer; the allocation lives until resident_kv_pool_free. 1204 let rc = unsafe { ffi::omega_gpu_attention_pool_alloc(bytes, &mut cpu) }; 1205 if rc != ffi::OMEGA_GPU_ATTN_OK { 1206 return Err(OmegaGpuError::Rc { 1207 rc, 1208 name: attn_rc_name(rc), 1209 }); 1210 } 1211 if cpu.is_null() { 1212 return Err(OmegaGpuError::Rc { 1213 rc: ffi::OMEGA_GPU_ATTN_CHIP_FAIL, 1214 name: "pool alloc returned OK with a null pointer".to_string(), 1215 }); 1216 } 1217 Ok((cpu.cast(), bytes)) 1218 } 1219 #[cfg(not(has_omega_gpu))] 1220 Err(OmegaGpuError::Unavailable) 1221 } 1222 1223 /// Free the resident KV pool (omega `omega_gpu_attention_pool_free`). No-op when none is 1224 /// allocated or in the stub. 1225 pub fn resident_kv_pool_free() { 1226 #[cfg(has_omega_gpu)] 1227 // SAFETY: omega checks for a live allocation itself; no call may be in flight (the pool 1228 // buffer that owns it is dropped after the backend's last use). 1229 unsafe { 1230 ffi::omega_gpu_attention_pool_free() 1231 }; 1232 } 1233 1234 /// Build and pin the matmul kernel a call of `m` rows over a `k` x `n` weight will use (omega 1235 /// `omega_gpu_matmul_prepare`). Stub: `Unavailable`. 1236 pub fn matmul_prepare(m: u32, k: u32, n: u32) -> Result<(), OmegaGpuError> { 1237 #[cfg(has_omega_gpu)] 1238 { 1239 // SAFETY: plain integer arguments; omega takes its own lock. 1240 let rc = unsafe { ffi::omega_gpu_matmul_prepare(m, k, n) }; 1241 if rc == 0 { 1242 Ok(()) 1243 } else { 1244 Err(rc_error(rc)) 1245 } 1246 } 1247 #[cfg(not(has_omega_gpu))] 1248 { 1249 let _ = (m, k, n); 1250 Err(OmegaGpuError::Unavailable) 1251 } 1252 } 1253 1254 /// Seal the serving state: from now on a matmul kernel that was not prepared is refused, never 1255 /// built (omega `omega_gpu_serving_seal`). No-op in the stub. 1256 pub fn seal_serving() { 1257 #[cfg(has_omega_gpu)] 1258 // SAFETY: no arguments; omega takes its own lock. 1259 unsafe { 1260 ffi::omega_gpu_serving_seal(); 1261 } 1262 } 1263 1264 /// Lift the reservation and the seal (buffers stay, growth is allowed again). The daemon never 1265 /// calls this: the reservation is held for the life of the process and ends when omega closes 1266 /// the device at exit. No-op in the stub. 1267 pub fn release_serving() { 1268 #[cfg(has_omega_gpu)] 1269 // SAFETY: no arguments; omega takes its own lock. 1270 unsafe { 1271 ffi::omega_gpu_serving_release(); 1272 } 1273 } 1274 1275 #[cfg(test)] 1276 mod cta_budget_tests { 1277 use super::*; 1278 1279 #[test] 1280 fn unset_or_blank_parses_to_none_caller_default() { 1281 assert_eq!(parse_cta_budget(None), Ok(None)); 1282 assert_eq!(parse_cta_budget(Some("")), Ok(None)); 1283 assert_eq!(parse_cta_budget(Some(" ")), Ok(None)); 1284 } 1285 1286 #[test] 1287 fn measured_budgets_parse() { 1288 for (raw, v) in [ 1289 ("64", 64), 1290 ("256", 256), 1291 (" 256\n", 256), 1292 ("1", 1), 1293 ("512", 512), 1294 ("1024", 1024), 1295 ] { 1296 assert_eq!( 1297 parse_cta_budget(Some(raw)).unwrap().map(CtaBudget::get), 1298 Some(v) 1299 ); 1300 } 1301 } 1302 1303 #[test] 1304 fn invalid_values_are_refused() { 1305 for raw in [ 1306 "0", 1307 "-1", 1308 "+64", 1309 "abc", 1310 "64.0", 1311 "0x40", 1312 "1025", 1313 "2048", 1314 "`99999999999`", 1315 ] { 1316 let err = parse_cta_budget(Some(raw)).expect_err(raw); 1317 assert!(err.contains(CTA_BUDGET_ENV), "{raw}: {err}"); 1318 } 1319 } 1320 1321 #[test] 1322 fn default_budget_is_omega_max_ctas() { 1323 assert_eq!(ffi::OMEGA_GPU_MATMUL_MAX_CTAS, 1024); 1324 // Reading the budget never opens the device (omega_gpu_matmul_api.c:121). 1325 if is_native() { 1326 assert_eq!(cta_budget(), Some(ffi::OMEGA_GPU_MATMUL_MAX_CTAS)); 1327 } else { 1328 assert_eq!(cta_budget(), None); 1329 let b = parse_cta_budget(Some("256")).unwrap().unwrap(); 1330 assert_eq!(set_cta_budget(b), Err(OmegaGpuError::Unavailable)); 1331 } 1332 } 1333 1334 #[test] 1335 fn daemon_default_is_1024_and_inside_the_measured_range() { 1336 assert_eq!(DAEMON_DEFAULT_CTA_BUDGET.get(), 1024); 1337 assert!(DAEMON_DEFAULT_CTA_BUDGET.get() <= CTA_BUDGET_MAX_MEASURED); 1338 // The same value as an explicit setting parses to the same budget. 1339 assert_eq!( 1340 parse_cta_budget(Some("1024")), 1341 Ok(Some(DAEMON_DEFAULT_CTA_BUDGET)) 1342 ); 1343 // Omega's own library default is untouched by the AIEN default. 1344 assert_eq!(ffi::OMEGA_GPU_MATMUL_MAX_CTAS, 1024); 1345 assert!(DAEMON_DEFAULT_CTA_BUDGET_EVIDENCE.starts_with("docs/inference/evidence/")); 1346 let doc = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) 1347 .join("../..") 1348 .join(DAEMON_DEFAULT_CTA_BUDGET_EVIDENCE) 1349 .join("FINDINGS.md"); 1350 assert!(doc.is_file(), "evidence missing: {}", doc.display()); 1351 } 1352 } 1353 1354 #[cfg(test)] 1355 mod spin_us_tests { 1356 use super::*; 1357 1358 #[test] 1359 fn unset_or_blank_keeps_omega_default() { 1360 assert_eq!(parse_spin_us(None), Ok(None)); 1361 assert_eq!(parse_spin_us(Some("")), Ok(None)); 1362 assert_eq!(parse_spin_us(Some(" \n")), Ok(None)); 1363 } 1364 1365 #[test] 1366 fn in_range_values_parse() { 1367 for (raw, v) in [ 1368 ("0", 0), 1369 ("2000", 2000), 1370 (" 2000\n", 2000), 1371 ("`1000000`", SPIN_US_MAX), 1372 ] { 1373 assert_eq!(parse_spin_us(Some(raw)), Ok(Some(v)), "{raw}"); 1374 } 1375 } 1376 1377 #[test] 1378 fn invalid_values_are_refused() { 1379 for raw in [ 1380 "-1", 1381 "+2000", 1382 "abc", 1383 "2000.0", 1384 "0x10", 1385 "`1000001`", 1386 "`99999999999`", 1387 ] { 1388 let err = parse_spin_us(Some(raw)).expect_err(raw); 1389 assert!(err.contains(SPIN_US_ENV), "{raw}: {err}"); 1390 } 1391 } 1392 1393 #[test] 1394 fn daemon_default_is_2000_with_sealed_evidence() { 1395 assert_eq!(DAEMON_DEFAULT_SPIN_US, 2000); 1396 assert_eq!( 1397 parse_spin_us(Some("2000")), 1398 Ok(Some(DAEMON_DEFAULT_SPIN_US)) 1399 ); 1400 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) 1401 .join("../..") 1402 .join(DAEMON_DEFAULT_SPIN_US_EVIDENCE); 1403 for file in ["FINDINGS.md", "SHA256SUMS", "run-ab.sh"] { 1404 assert!( 1405 dir.join(file).is_file(), 1406 "evidence missing: {}", 1407 dir.join(file).display() 1408 ); 1409 } 1410 } 1411 1412 fn qwen3_4b_bounds() -> ServingBounds { 1413 ServingBounds { 1414 max_context: 4096, 1415 max_seqs: 1, 1416 num_q_heads: 32, 1417 num_kv_heads: 8, 1418 head_dim: 128, 1419 kv_block_size: 16, 1420 max_rows: 256, 1421 max_k: 9728, 1422 max_n: 151936, 1423 max_n_one_row: 151936, 1424 kernel_slots: 32, 1425 } 1426 } 1427 1428 #[test] 1429 fn serving_bytes_follow_omegas_formulas() { 1430 // omega attention_api.c:664-681 and matmul_api.c:130-150 at `b980783`, Qwen3-4B shape. 1431 let y = qwen3_4b_bounds().bytes(); 1432 assert_eq!(y.attention_pool, 2 * 4096 * 8 * 128 * 4); // 32 MiB 1433 assert_eq!(y.attention_q_out, 16384); 1434 assert_eq!(y.attention_table, 20480); // (4096 + 1) * 4 rounded up to a page 1435 // Measured, not derived: omega_gpu_reserve_serving on its fake driver layer with these 1436 // bounds asked the driver for exactly `194170880` bytes (6 buffers). 1437 assert_eq!(y.total(), 194_170_880); 1438 assert_eq!(y.matmul_activation, 256 * 9728 * 2); 1439 assert_eq!(y.matmul_result, 256 * 151936 * 4); 1440 // under half a block of context the paged path stages a whole block, the larger one 1441 let mut b = qwen3_4b_bounds(); 1442 (b.max_context, b.kv_block_size) = (16, 64); 1443 assert_eq!(b.bytes().attention_pool, 64 * 8 * 128 * 4); 1444 } 1445 1446 #[test] 1447 fn reserving_without_the_engine_is_unavailable() { 1448 if !is_native() { 1449 assert_eq!( 1450 reserve_serving(&qwen3_4b_bounds()), 1451 Err(OmegaGpuError::Unavailable) 1452 ); 1453 release_serving(); 1454 } 1455 } 1456 1457 #[test] 1458 fn reading_the_window_matches_the_build() { 1459 if is_native() { 1460 assert!(spin_us().is_some_and(|us| us <= SPIN_US_MAX)); 1461 } else { 1462 assert_eq!(spin_us(), None); 1463 assert_eq!(set_spin_us(2000), Err(OmegaGpuError::Unavailable)); 1464 } 1465 } 1466 }