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-pf/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-pf / src / lib.rs` 1535 lines ยท 52393 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 device-resident prefill API (`src/omega_gpu_prefill.h`, W-L1G 17 //! cut `1e76e728`) and the causal prefill attention (`src/omega_gpu_prefill_attn_api.h`, W-L1A). 18 //! No CUDA: every launch is omega's own Blackwell code generator. 19 //! 20 //! What is bound: 21 //! * buffers: `omega_gpu_pf_alloc_dev` (GPU-cached, device-private: the CPU never touches them) 22 //! and `omega_gpu_pf_alloc_host` (GPU-uncached session memory the CPU reads and writes). 23 //! * `omega_gpu_pf_quant`: f32 or bf16 rows of `k` -> e4m3 rows + f32 power-of-two scales per 24 //! 128-wide group (`omega_blackwell_codegen_qg.h`). 25 //! * `omega_gpu_pf_qgemm`: grouped GEMM on QMMA, weights read IN PLACE from FP8 GEMV tensors 26 //! through a tile table of per-expert `(w_va, s_va)`; layouts [`Layout::Plain`] (f32 rows of n) 27 //! and [`Layout::SwigluNat`] (bf16 act rows of n/2, act = silu(gate) * up). 28 //! * `omega_gpu_prefill_attn` (+ `_dev`): one call for all `m` prompt tokens of a layer. 29 //! 30 //! The two traits [`PrefillDevice`] and [`PrefillAttention`] are the seams the whole-prompt 31 //! driver (`aien-inference-abi`, `qwen3_moe_omega_prefill`) is written against, so host tests use 32 //! fakes. Without the native library every call returns `Unavailable`. 33 use aien_omega_gpu::OmegaGpuError; 34 35 /// Scale group width of the quantiser and the GEMM (k blocks of 128). 36 pub const BLOCK: usize = 128; 37 /// Widest row the quantiser takes (`omega_pq_spec_ok`: 128 <= k <= 32768; rows wider than 32 38 /// blocks are split over grid y, omega qwen38/prefill-graph `6e24f7fd`). 39 pub const QUANT_MAX_K: usize = 32768; 40 /// Widest `k` the QMMA GEMM takes (`omega_qg_spec_ok`, omega#541). 41 pub const GEMM_MAX_K: usize = 32768; 42 /// Bytes of one tile-table entry (`OMEGA_QG_TILE_BYTES`). 43 pub const TILE_BYTES: usize = 32; 44 /// Most tiles one GEMM launch takes (grid y, `omega_gpu_pf_qgemm` refuses more with TOO_LARGE). 45 pub const MAX_TILES: usize = 65535; 46 /// Rows per tile at the default shape (16 x rt 4); the device reports the live value. 47 pub const DEFAULT_BM: usize = 64; 48 /// GEMM output columns one CTA covers at the default 8 warps (`n` must be a multiple). 49 pub const DEFAULT_SPAN: usize = 128; 50 51 /// True when the quantiser / QMMA GEMM / pf buffers are linked (not the stub). 52 pub const fn is_native() -> bool { 53 cfg!(has_omega_pf) 54 } 55 /// True when `omega_gpu_prefill_attn` (host-pointer entry) is linked. 56 pub const fn has_attention() -> bool { 57 cfg!(has_omega_pattn) 58 } 59 /// True when `omega_gpu_prefill_attn_dev` (device-pointer entry) is linked. 60 pub const fn has_attention_dev() -> bool { 61 cfg!(has_omega_pattn_dev) 62 } 63 64 /// GEMM output layout (`OMEGA_GPU_PF_PLAIN` / `OMEGA_GPU_PF_SWIGLU_NAT`). 65 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 66 #[repr(u32)] 67 pub enum Layout { 68 /// `y` f32 rows of `n`. 69 Plain = 0, 70 /// Tensor `[E][2I][k]` (gate rows then up rows, checkpoint order); `y` bf16 act rows of `I = n / 2`. 71 SwigluNat = 2, 72 } 73 74 /// Quantiser input element type (`OMEGA_QG_IN_F32` / `OMEGA_QG_IN_BF16`). 75 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 76 #[repr(u32)] 77 pub enum QuantIn { 78 F32 = 0, 79 Bf16 = 1, 80 } 81 82 /// One tile-table entry, byte-exact with the C `Tile` (`{ w_va u64, s_va u64, row0 u32, cnt u32, pad u64 }`). 83 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] 84 #[repr(C)] 85 pub struct Tile { 86 pub w_va: u64, 87 pub s_va: u64, 88 pub row0: u32, 89 pub cnt: u32, 90 pub pad: u64, 91 } 92 93 const _: () = assert!(std::mem::size_of::() == TILE_BYTES); 94 95 impl Tile { 96 /// Little-endian bytes as the kernel reads them. 97 pub fn to_bytes(&self) -> [u8; TILE_BYTES] { 98 let mut b = [0u8; TILE_BYTES]; 99 b[0..8].copy_from_slice(&self.w_va.to_le_bytes()); 100 b[8..16].copy_from_slice(&self.s_va.to_le_bytes()); 101 b[16..20].copy_from_slice(&self.row0.to_le_bytes()); 102 b[20..24].copy_from_slice(&self.cnt.to_le_bytes()); 103 b[24..32].copy_from_slice(&self.pad.to_le_bytes()); 104 b 105 } 106 pub fn from_bytes(b: &[u8]) -> Self { 107 let u64_at = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().expect("8 bytes")); 108 let u32_at = |o: usize| u32::from_le_bytes(b[o..o + 4].try_into().expect("4 bytes")); 109 Self { 110 w_va: u64_at(0), 111 s_va: u64_at(8), 112 row0: u32_at(16), 113 cnt: u32_at(20), 114 pad: u64_at(24), 115 } 116 } 117 } 118 119 /// The tile table for rows grouped by expert (`counts[e]` rows of expert `e`, experts in order), 120 /// a Rust mirror of `omega_gpu_pf_qgemm_tiles_va`: experts with no rows get no tile, each tile 121 /// covers up to `bm` rows of one expert, `row0` counts rows over all experts. 122 pub fn build_tiles( 123 bm: usize, 124 w_va: &[u64], 125 s_va: &[u64], 126 counts: &[u32], 127 ) -> Result, OmegaGpuError> { 128 if bm == 0 || w_va.len() != counts.len() || s_va.len() != counts.len() { 129 return Err(bad(format!( 130 "pf tiles: bm {bm}, {} weight / {} scale addresses for {} experts", 131 w_va.len(), 132 s_va.len(), 133 counts.len() 134 ))); 135 } 136 let mut tiles = Vec::new(); 137 let mut row = 0u32; 138 for (e, &c) in counts.iter().enumerate() { 139 let mut r = 0u32; 140 while r < c { 141 let cnt = (c - r).min(bm as u32); 142 tiles.push(Tile { 143 w_va: w_va[e], 144 s_va: s_va[e], 145 row0: row + r, 146 cnt, 147 pad: 0, 148 }); 149 r += cnt; 150 } 151 row += c; 152 } 153 if tiles.len() > MAX_TILES { 154 return Err(bad(format!( 155 "pf tiles: {} tiles > {MAX_TILES}", 156 tiles.len() 157 ))); 158 } 159 Ok(tiles) 160 } 161 162 /// Host check of the quantiser rule (`omega_pq_spec_ok`), before any chip call. 163 pub fn check_quant(k: usize) -> Result<(), OmegaGpuError> { 164 if !k.is_multiple_of(BLOCK) || !(BLOCK..=QUANT_MAX_K).contains(&k) { 165 return Err(bad(format!( 166 "pf quant k={k} refused: multiple of {BLOCK}, {BLOCK} <= k <= {QUANT_MAX_K}" 167 ))); 168 } 169 Ok(()) 170 } 171 172 /// Host check of the GEMM rule at the default shape (rt 4, 8 warps; `omega_qg_spec_ok`). 173 pub fn check_qgemm(n: usize, k: usize, layout: Layout, ntiles: usize) -> Result<(), OmegaGpuError> { 174 if !k.is_multiple_of(BLOCK) || !(BLOCK..=GEMM_MAX_K).contains(&k) { 175 return Err(bad(format!( 176 "pf qgemm k={k} refused: multiple of {BLOCK}, {BLOCK} <= k <= {GEMM_MAX_K}" 177 ))); 178 } 179 // Row stride (n f32, or n / 2 bf16 act rows = n bytes) x the tile's rows: the store offset. 180 let row_bytes = if layout == Layout::SwigluNat { 181 n 182 } else { 183 4 * n 184 }; 185 if n == 0 || !n.is_multiple_of(DEFAULT_SPAN) || row_bytes * DEFAULT_BM >= 1 << 23 { 186 return Err(bad(format!( 187 "pf qgemm n={n} refused: positive multiple of {DEFAULT_SPAN}, row bytes x {DEFAULT_BM} < 2^23" 188 ))); 189 } 190 if layout == Layout::SwigluNat && !n.is_multiple_of(2 * BLOCK) { 191 return Err(bad(format!( 192 "pf qgemm SwiGLU n={n} refused: multiple of 256 (gate and up halves on scale blocks)" 193 ))); 194 } 195 if ntiles > MAX_TILES { 196 return Err(bad(format!("pf qgemm {ntiles} tiles > {MAX_TILES}"))); 197 } 198 Ok(()) 199 } 200 201 // --------------------------------------------------------------------------- 202 // The seams the driver is written against. 203 // --------------------------------------------------------------------------- 204 205 /// A device buffer: its GPU address, size, and (host buffers only) the CPU view. 206 pub trait PfBuffer { 207 fn va(&self) -> u64; 208 fn bytes(&self) -> usize; 209 /// The CPU view of a HOST buffer; `None` for device-private buffers (the CPU never touches those). 210 fn host(&self) -> Option<&[u8]>; 211 fn host_mut(&mut self) -> Option<&mut [u8]>; 212 } 213 214 /// One grouped GEMM launch (`omega_gpu_pf_qgemm` arguments). 215 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 216 pub struct QgemmCall { 217 pub n: usize, 218 pub k: usize, 219 pub layout: Layout, 220 pub tiles_va: u64, 221 pub ntiles: usize, 222 /// 0 = direct rows (output row r reads activation row r); else u32 `[rows + bm]` source rows. 223 pub rowidx_va: u64, 224 pub xq_va: u64, 225 pub xs_va: u64, 226 pub y_va: u64, 227 } 228 229 /// omega's prefill kernels on the shared session. Every call is synchronous (it returns after 230 /// the chip finished, with the chip nanoseconds). Real: [`OmegaPfDevice`]. 231 pub trait PrefillDevice { 232 type Buf: PfBuffer; 233 /// GPU-cached, device-private buffer. 234 fn alloc_dev(&mut self, bytes: usize) -> Result; 235 /// GPU-uncached buffer the host reads and writes. 236 fn alloc_host(&mut self, bytes: usize) -> Result; 237 /// Rows per GEMM tile (the GEMM reads activation rows up to `row0 + bm - 1` of every tile). 238 fn qgemm_bm(&self) -> usize; 239 /// Activation quantiser over `rows` rows of `k`. 240 fn quant( 241 &mut self, 242 k: usize, 243 input: QuantIn, 244 rows: usize, 245 x_va: u64, 246 q_va: u64, 247 s_va: u64, 248 ) -> Result; 249 /// One grouped GEMM launch. 250 fn qgemm(&mut self, call: &QgemmCall) -> Result; 251 /// Device-to-device copy by address (16-byte multiples). Default: refused. 252 fn copy_va(&mut self, _dst_va: u64, _src_va: u64, _bytes: usize) -> Result<(), String> { 253 Err("pf copy: not offered by this device".into()) 254 } 255 /// Rows per CTA of the device router-logits launch (W-L1G-D), or `None` when this device has 256 /// no router-logits / combine kernels. The router reads and writes `ceil(rows / t) * t` rows. 257 fn router_rows(&self) -> Option { 258 None 259 } 260 /// Router logits for `rows` rows of `k` f32 at `x_va` against the packed weights at `wq_va` 261 /// ([`pack_router`]) into f32 rows of `e` at `logits_va`; bit-identical to [`router_logits_ref`]. 262 fn router_logits( 263 &mut self, 264 _k: usize, 265 _e: usize, 266 _rows: usize, 267 _x_va: u64, 268 _wq_va: u64, 269 _logits_va: u64, 270 ) -> Result { 271 Err("pf router logits: not offered by this device".into()) 272 } 273 /// MoE weighted combine ([`moe_combine_ref`]): `out[r] = sum_slot wt[r][slot] * down[inv[r][slot]]`. 274 #[allow(clippy::too_many_arguments)] 275 fn moe_combine( 276 &mut self, 277 _h: usize, 278 _top_k: usize, 279 _rows: usize, 280 _down_va: u64, 281 _inv_va: u64, 282 _wt_va: u64, 283 _out_va: u64, 284 ) -> Result { 285 Err("pf moe combine: not offered by this device".into()) 286 } 287 } 288 289 /// The attention call boundary: `omega_gpu_prefill_attn` exactly. One call does layer `layer` 290 /// for the `m` tokens at positions `pos0 .. pos0 + m - 1` (positions `0 .. pos0 - 1` already in 291 /// the KV cache): `qkv` f32 `[m][5120]` raw fused projection rows (q 32 x 128 | k 4 x 128 | 292 /// v 4 x 128), appends their K/V, writes `out` f32 `[m][4096]` (token-major, head h at h * 128) 293 /// multiplied by `out_scale`. Returns chip nanoseconds. 294 pub trait PrefillAttention { 295 #[allow(clippy::too_many_arguments)] 296 fn attend( 297 &mut self, 298 layer: u32, 299 pos0: u32, 300 m: u32, 301 qkv: &[f32], 302 eps: f32, 303 out_scale: f32, 304 out: &mut [f32], 305 ) -> Result; 306 /// Whether [`Self::attend_dev`] is available. 307 fn has_dev(&self) -> bool { 308 false 309 } 310 /// The device-pointer variant (`omega_gpu_prefill_attn_dev`): `qkv_va` f32 `[m][5120]` and 311 /// `out_va` f32 `[m][4096]` rows in session memory (no host copies). `None`: not offered. 312 #[allow(clippy::too_many_arguments)] 313 fn attend_dev( 314 &mut self, 315 layer: u32, 316 pos0: u32, 317 m: u32, 318 qkv_va: u64, 319 eps: f32, 320 out_scale: f32, 321 out_va: u64, 322 ) -> Option> { 323 let _ = (layer, pos0, m, qkv_va, eps, out_scale, out_va); 324 None 325 } 326 } 327 328 /// Query heads x head dim of the attention kernel's fixed shape (Qwen3-30B-A3B). 329 pub const ATTN_OUT_WORDS: usize = 32 * 128; 330 /// Fused q|k|v row of the attention kernel's fixed shape. 331 pub const ATTN_QKV_WORDS: usize = (32 + 2 * 4) * 128; 332 333 // --------------------------------------------------------------------------- 334 // FFI. 335 // --------------------------------------------------------------------------- 336 337 /// Mirror of `OmegaGpuMem` (omega_gpu_session.h): handle {index, generation}, kind, cpu, va, size. 338 #[repr(C)] 339 #[derive(Debug, Clone, Copy)] 340 pub struct OmegaGpuMem { 341 pub handle_index: u32, 342 pub handle_generation: u32, 343 pub kind: u32, 344 pub cpu: *mut std::ffi::c_void, 345 pub va: u64, 346 pub size: u64, 347 } 348 349 impl Default for OmegaGpuMem { 350 fn default() -> Self { 351 Self { 352 handle_index: 0, 353 handle_generation: 0, 354 kind: 0, 355 cpu: std::ptr::null_mut(), 356 va: 0, 357 size: 0, 358 } 359 } 360 } 361 362 /// Mirror of `OmegaGpuPrefillAttnInfo` (omega_gpu_prefill_attn_api.h). 363 #[repr(C)] 364 #[derive(Debug, Clone, Copy, Default)] 365 pub struct PrefillAttnInfo { 366 pub layer: u32, 367 pub pos0: u32, 368 pub m: u32, 369 pub chunks: u32, 370 pub grid_x: u32, 371 pub grid_y: u32, 372 pub threads: u32, 373 pub splits: u32, 374 pub per_split: u32, 375 pub elapsed_ns: u64, 376 pub call_ns: u64, 377 pub kernel_cache_hit: i32, 378 } 379 380 #[cfg(has_omega_pf)] 381 mod ffi { 382 use super::OmegaGpuMem; 383 use std::os::raw::{c_char, c_void}; 384 extern "C" { 385 pub fn omega_gpu_pf_rc_name(rc: i32) -> *const c_char; 386 pub fn omega_gpu_session_last_error() -> *const c_char; 387 pub fn omega_gpu_pf_alloc_dev(bytes: usize, out: *mut OmegaGpuMem) -> i32; 388 pub fn omega_gpu_pf_alloc_host(bytes: usize, out: *mut OmegaGpuMem) -> i32; 389 pub fn omega_gpu_pf_free(m: *mut OmegaGpuMem); 390 pub fn omega_gpu_pf_copy_va(dst_va: u64, src_va: u64, bytes: usize) -> i32; 391 pub fn omega_gpu_pf_stats(chip_ns: *mut u64, launches: *mut u64); 392 pub fn omega_gpu_pf_stats_reset(); 393 pub fn omega_gpu_pf_quant( 394 k: u32, 395 in_type: u32, 396 rows: u32, 397 x_va: u64, 398 q_va: u64, 399 s_va: u64, 400 ns: *mut u64, 401 ) -> i32; 402 pub fn omega_gpu_pf_qgemm_bm() -> u32; 403 #[cfg(has_omega_pf_reading)] 404 pub fn omega_gpu_pf_qgemm_reading_option(rows: u32, index: u32) -> u32; 405 #[cfg(has_omega_pf_reading)] 406 pub fn omega_gpu_pf_qgemm_workspace_fits( 407 capacity: u64, 408 padded: u64, 409 tiles: u64, 410 rows: u64, 411 bm: u64, 412 ) -> i32; 413 #[cfg(has_omega_pf_scoped)] 414 pub fn omega_gpu_pf_qgemm_scoped_bm(rt: u32, warps: u32, wait: u32, group: u32) -> u32; 415 #[cfg(has_omega_pf_scoped)] 416 pub fn omega_gpu_pf_qgemm_scoped( 417 rt: u32, 418 warps: u32, 419 wait: u32, 420 group: u32, 421 n: u32, 422 k: u32, 423 layout: u32, 424 tiles_va: u64, 425 ntiles: u32, 426 rowidx_va: u64, 427 xq_va: u64, 428 xs_va: u64, 429 y_va: u64, 430 ns: *mut u64, 431 ) -> i32; 432 pub fn omega_gpu_pf_qgemm_tiles_va( 433 experts: u32, 434 w_va: *const u64, 435 s_va: *const u64, 436 counts: *const u32, 437 tab: *mut c_void, 438 max: u32, 439 ) -> u32; 440 pub fn omega_gpu_pf_qgemm( 441 n: u32, 442 k: u32, 443 layout: u32, 444 tiles_va: u64, 445 ntiles: u32, 446 rowidx_va: u64, 447 xq_va: u64, 448 xs_va: u64, 449 y_va: u64, 450 ns: *mut u64, 451 ) -> i32; 452 } 453 } 454 455 /// Router logits and MoE combine kernels (W-L1G-D, omega_gpu_pfhost.h). 456 #[cfg(has_omega_pfhost)] 457 mod ffi_host { 458 extern "C" { 459 pub fn omega_gpu_pf_router_rows() -> u32; 460 pub fn omega_gpu_pf_router_pack(e: u32, k: u32, w: *const f32, wq: *mut f32); 461 pub fn omega_gpu_pf_router_logits( 462 k: u32, 463 e: u32, 464 rows: u32, 465 x_va: u64, 466 wq_va: u64, 467 logits_va: u64, 468 ns: *mut u64, 469 ) -> i32; 470 pub fn omega_gpu_pf_moe_combine( 471 h: u32, 472 top_k: u32, 473 rows: u32, 474 down_va: u64, 475 inv_va: u64, 476 wt_va: u64, 477 out_va: u64, 478 ns: *mut u64, 479 ) -> i32; 480 } 481 } 482 483 /// True when omega's router-logits and combine kernels (omega_gpu_pfhost.h) are linked. 484 pub const fn has_pfhost() -> bool { 485 cfg!(has_omega_pfhost) 486 } 487 488 /// f32 count of the packed router layout R4 plus its pad group: `(k / 4 + 1) * e * 4`. 489 pub fn router_packed_len(e: usize, k: usize) -> usize { 490 (k / 4 + 1) * e * 4 491 } 492 493 /// Packs a router `w` (f32 `[e][k]`, row = expert) into the kernel's layout R4: 494 /// `wq[g][ex][q] = w[ex][4g + q]`, then one zero pad group (omega_gpu_pf_router_pack). 495 pub fn pack_router(e: usize, k: usize, w: &[f32]) -> Vec { 496 assert!( 497 k.is_multiple_of(4) && w.len() == e * k, 498 "pack_router: w must be e x k with k a multiple of 4" 499 ); 500 let mut wq = vec![0.0f32; router_packed_len(e, k)]; 501 for g in 0..k / 4 { 502 for ex in 0..e { 503 wq[(g * e + ex) * 4..(g * e + ex) * 4 + 4] 504 .copy_from_slice(&w[ex * k + 4 * g..ex * k + 4 * g + 4]); 505 } 506 } 507 wq 508 } 509 510 /// The C packer (omega_gpu_pf_router_pack), for checking [`pack_router`] against it. 511 pub fn pack_router_c(e: usize, k: usize, w: &[f32]) -> Result, OmegaGpuError> { 512 if !k.is_multiple_of(4) || w.len() != e * k { 513 return Err(bad( 514 "pack_router_c: w must be e x k with k a multiple of 4".into() 515 )); 516 } 517 #[cfg(has_omega_pfhost)] 518 { 519 let mut wq = vec![f32::NAN; router_packed_len(e, k)]; 520 // SAFETY: w has e * k floats, wq router_packed_len(e, k) (the C packer's size). 521 unsafe { 522 ffi_host::omega_gpu_pf_router_pack(e as u32, k as u32, w.as_ptr(), wq.as_mut_ptr()) 523 }; 524 Ok(wq) 525 } 526 #[cfg(not(has_omega_pfhost))] 527 { 528 Err(OmegaGpuError::Unavailable) 529 } 530 } 531 532 /// Host mirror of the router-logits kernel: `out[r][ex]` = the sequential f32 sum from -0.0 of 533 /// `w[ex][j] * x[r][j]` (Rust's `map(a * b).sum::()`), read from the packed layout. 534 pub fn router_logits_ref(k: usize, e: usize, rows: usize, x: &[f32], wq: &[f32], out: &mut [f32]) { 535 for r in 0..rows { 536 for ex in 0..e { 537 let mut acc = -0.0f32; 538 for j in 0..k { 539 acc += wq[((j / 4) * e + ex) * 4 + j % 4] * x[r * k + j]; 540 } 541 out[r * e + ex] = acc; 542 } 543 } 544 } 545 546 /// Host mirror of the combine kernel: `out[r][c]` = the sum from +0.0, in slot order, of 547 /// `wt[r][slot] * down[inv[r][slot]][c]` (the driver's combine accumulator). 548 pub fn moe_combine_ref( 549 h: usize, 550 top_k: usize, 551 rows: usize, 552 down: &[f32], 553 inv: &[u32], 554 wt: &[f32], 555 out: &mut [f32], 556 ) { 557 for r in 0..rows { 558 for c in 0..h { 559 let mut acc = 0.0f32; 560 for s in 0..top_k { 561 acc += wt[r * top_k + s] * down[inv[r * top_k + s] as usize * h + c]; 562 } 563 out[r * h + c] = acc; 564 } 565 } 566 } 567 #[cfg(has_omega_pattn)] 568 mod ffi_attn { 569 use super::PrefillAttnInfo; 570 use std::os::raw::{c_char, c_void}; 571 extern "C" { 572 pub fn omega_gpu_prefill_attn( 573 c: *mut c_void, 574 layer: u32, 575 pos0: u32, 576 m: u32, 577 qkv: *const f32, 578 eps: f32, 579 out_scale: f32, 580 out: *mut f32, 581 info: *mut PrefillAttnInfo, 582 ) -> i32; 583 pub fn omega_gpu_decode_attn_rc_name(rc: i32) -> *const c_char; 584 pub fn omega_gpu_decode_attn_last_error() -> *const c_char; 585 } 586 #[cfg(has_omega_pattn_dev)] 587 extern "C" { 588 pub fn omega_gpu_prefill_attn_dev( 589 c: *mut c_void, 590 layer: u32, 591 pos0: u32, 592 m: u32, 593 qkv_va: u64, 594 eps: f32, 595 out_scale: f32, 596 out_va: u64, 597 info: *mut PrefillAttnInfo, 598 ) -> i32; 599 } 600 } 601 602 fn bad(name: String) -> OmegaGpuError { 603 OmegaGpuError::Rc { rc: -1, name } 604 } 605 606 #[cfg(any(has_omega_pf, has_omega_pattn))] 607 fn cstr(p: *const std::os::raw::c_char) -> Option { 608 // SAFETY: omega returns static NUL-terminated strings or NULL. 609 (!p.is_null()).then(|| { 610 unsafe { std::ffi::CStr::from_ptr(p) } 611 .to_string_lossy() 612 .into_owned() 613 }) 614 } 615 616 #[cfg(has_omega_pf)] 617 fn rc_err(rc: i32) -> OmegaGpuError { 618 // SAFETY: both functions take no pointers and return static strings or NULL. 619 let name = cstr(unsafe { ffi::omega_gpu_pf_rc_name(rc) }).unwrap_or_else(|| "?".into()); 620 let name = match cstr(unsafe { ffi::omega_gpu_session_last_error() }) { 621 Some(e) => format!("{name}: {e}"), 622 None => name, 623 }; 624 OmegaGpuError::Rc { rc, name } 625 } 626 627 #[cfg(has_omega_pattn)] 628 fn attn_rc_err(rc: i32) -> OmegaGpuError { 629 // SAFETY: as rc_err. 630 let name = 631 cstr(unsafe { ffi_attn::omega_gpu_decode_attn_rc_name(rc) }).unwrap_or_else(|| "?".into()); 632 let name = match cstr(unsafe { ffi_attn::omega_gpu_decode_attn_last_error() }) { 633 Some(e) => format!("{name}: {e}"), 634 None => name, 635 }; 636 OmegaGpuError::Rc { rc, name } 637 } 638 639 /// An owned pf buffer (freed on drop). Host buffers expose their CPU view. 640 #[derive(Debug)] 641 pub struct PfMem { 642 mem: OmegaGpuMem, 643 bytes: usize, 644 host: bool, 645 } 646 647 // SAFETY: an owning handle to session memory; moved between threads, never shared unlocked. 648 unsafe impl Send for PfMem {} 649 650 impl PfMem { 651 fn alloc(bytes: usize, host: bool) -> Result { 652 if bytes == 0 { 653 return Err(bad("pf alloc of 0 bytes".into())); 654 } 655 #[cfg(has_omega_pf)] 656 { 657 let mut mem = OmegaGpuMem::default(); 658 // SAFETY: `mem` is a valid out pointer for the call. 659 let rc = unsafe { 660 if host { 661 ffi::omega_gpu_pf_alloc_host(bytes, &mut mem) 662 } else { 663 ffi::omega_gpu_pf_alloc_dev(bytes, &mut mem) 664 } 665 }; 666 if rc != 0 { 667 return Err(rc_err(rc)); 668 } 669 if mem.va == 0 || (mem.size as usize) < bytes || (host && mem.cpu.is_null()) { 670 // SAFETY: the buffer came from the alloc above. 671 unsafe { ffi::omega_gpu_pf_free(&mut mem) }; 672 return Err(bad(format!( 673 "pf alloc of {bytes} bytes returned no usable view" 674 ))); 675 } 676 Ok(Self { mem, bytes, host }) 677 } 678 #[cfg(not(has_omega_pf))] 679 { 680 let _ = host; 681 Err(OmegaGpuError::Unavailable) 682 } 683 } 684 /// GPU-cached device-private buffer (`omega_gpu_pf_alloc_dev`). 685 pub fn alloc_dev(bytes: usize) -> Result { 686 Self::alloc(bytes, false) 687 } 688 /// GPU-uncached host-visible buffer (`omega_gpu_pf_alloc_host`). 689 pub fn alloc_host(bytes: usize) -> Result { 690 Self::alloc(bytes, true) 691 } 692 } 693 694 impl PfBuffer for PfMem { 695 fn va(&self) -> u64 { 696 self.mem.va 697 } 698 fn bytes(&self) -> usize { 699 self.bytes 700 } 701 fn host(&self) -> Option<&[u8]> { 702 // SAFETY: a host buffer's CPU view covers `bytes` and lives until drop; launches are 703 // synchronous, so the GPU does not write it while this borrow is in use. 704 self.host 705 .then(|| unsafe { std::slice::from_raw_parts(self.mem.cpu as *const u8, self.bytes) }) 706 } 707 fn host_mut(&mut self) -> Option<&mut [u8]> { 708 // SAFETY: as host(); &mut self makes the view exclusive. 709 self.host 710 .then(|| unsafe { std::slice::from_raw_parts_mut(self.mem.cpu as *mut u8, self.bytes) }) 711 } 712 } 713 714 impl Drop for PfMem { 715 fn drop(&mut self) { 716 #[cfg(has_omega_pf)] 717 // SAFETY: the buffer came from alloc and is freed once. 718 unsafe { 719 ffi::omega_gpu_pf_free(&mut self.mem) 720 } 721 } 722 } 723 724 /// omega's prefill kernels (the real [`PrefillDevice`]). 725 #[derive(Debug, Default)] 726 pub struct OmegaPfDevice; 727 728 impl OmegaPfDevice { 729 /// Accumulated chip time and launches of the pf module since the last reset. 730 pub fn stats(&self) -> (u64, u64) { 731 #[cfg(has_omega_pf)] 732 { 733 let (mut ns, mut n) = (0u64, 0u64); 734 // SAFETY: two valid out pointers. 735 unsafe { ffi::omega_gpu_pf_stats(&mut ns, &mut n) }; 736 (ns, n) 737 } 738 #[cfg(not(has_omega_pf))] 739 { 740 (0, 0) 741 } 742 } 743 pub fn stats_reset(&self) { 744 #[cfg(has_omega_pf)] 745 // SAFETY: no arguments. 746 unsafe { 747 ffi::omega_gpu_pf_stats_reset() 748 } 749 } 750 /// The C tile builder (`omega_gpu_pf_qgemm_tiles_va`), for checking [`build_tiles`] against it. 751 pub fn tiles_va_c( 752 &self, 753 w_va: &[u64], 754 s_va: &[u64], 755 counts: &[u32], 756 ) -> Result, OmegaGpuError> { 757 if w_va.len() != counts.len() || s_va.len() != counts.len() || counts.is_empty() { 758 return Err(bad( 759 "pf tiles_va: one weight and scale address per expert".into() 760 )); 761 } 762 #[cfg(has_omega_pf)] 763 { 764 let mut tab = vec![Tile::default(); MAX_TILES]; 765 // SAFETY: arrays have `counts.len()` entries; tab holds MAX_TILES entries of 32 bytes. 766 let n = unsafe { 767 ffi::omega_gpu_pf_qgemm_tiles_va( 768 counts.len() as u32, 769 w_va.as_ptr(), 770 s_va.as_ptr(), 771 counts.as_ptr(), 772 tab.as_mut_ptr().cast(), 773 MAX_TILES as u32, 774 ) 775 }; 776 if n == 0 && counts.iter().any(|&c| c > 0) { 777 return Err(bad("pf tiles_va: table overflow or bad arguments".into())); 778 } 779 tab.truncate(n as usize); 780 Ok(tab) 781 } 782 #[cfg(not(has_omega_pf))] 783 { 784 Err(OmegaGpuError::Unavailable) 785 } 786 } 787 } 788 789 impl PrefillDevice for OmegaPfDevice { 790 type Buf = PfMem; 791 fn router_rows(&self) -> Option { 792 #[cfg(has_omega_pfhost)] 793 { 794 // SAFETY: no arguments. 795 Some(unsafe { ffi_host::omega_gpu_pf_router_rows() } as usize) 796 } 797 #[cfg(not(has_omega_pfhost))] 798 { 799 None 800 } 801 } 802 fn router_logits( 803 &mut self, 804 k: usize, 805 e: usize, 806 rows: usize, 807 x_va: u64, 808 wq_va: u64, 809 logits_va: u64, 810 ) -> Result { 811 if x_va == 0 812 || wq_va == 0 813 || logits_va == 0 814 || rows > u32::MAX as usize 815 || k > u32::MAX as usize 816 || e > u32::MAX as usize 817 { 818 return Err(format!("pf router logits: null address or {rows} rows")); 819 } 820 #[cfg(has_omega_pfhost)] 821 { 822 let mut ns = 0u64; 823 // SAFETY: plain values and one out pointer; the addresses are session buffers the caller owns. 824 let rc = unsafe { 825 ffi_host::omega_gpu_pf_router_logits( 826 k as u32, 827 e as u32, 828 rows as u32, 829 x_va, 830 wq_va, 831 logits_va, 832 &mut ns, 833 ) 834 }; 835 if rc != 0 { 836 return Err(rc_err(rc).to_string()); 837 } 838 Ok(ns) 839 } 840 #[cfg(not(has_omega_pfhost))] 841 { 842 Err(OmegaGpuError::Unavailable.to_string()) 843 } 844 } 845 fn moe_combine( 846 &mut self, 847 h: usize, 848 top_k: usize, 849 rows: usize, 850 down_va: u64, 851 inv_va: u64, 852 wt_va: u64, 853 out_va: u64, 854 ) -> Result { 855 if down_va == 0 856 || inv_va == 0 857 || wt_va == 0 858 || out_va == 0 859 || rows > u32::MAX as usize 860 || h > u32::MAX as usize 861 || top_k > u32::MAX as usize 862 { 863 return Err(format!("pf moe combine: null address or {rows} rows")); 864 } 865 #[cfg(has_omega_pfhost)] 866 { 867 let mut ns = 0u64; 868 // SAFETY: plain values and one out pointer; the addresses are session buffers the caller owns. 869 let rc = unsafe { 870 ffi_host::omega_gpu_pf_moe_combine( 871 h as u32, 872 top_k as u32, 873 rows as u32, 874 down_va, 875 inv_va, 876 wt_va, 877 out_va, 878 &mut ns, 879 ) 880 }; 881 if rc != 0 { 882 return Err(rc_err(rc).to_string()); 883 } 884 Ok(ns) 885 } 886 #[cfg(not(has_omega_pfhost))] 887 { 888 Err(OmegaGpuError::Unavailable.to_string()) 889 } 890 } 891 fn copy_va(&mut self, dst_va: u64, src_va: u64, bytes: usize) -> Result<(), String> { 892 if dst_va == 0 893 || src_va == 0 894 || !dst_va.is_multiple_of(16) 895 || !src_va.is_multiple_of(16) 896 || !bytes.is_multiple_of(16) 897 { 898 return Err(format!( 899 "pf copy: addresses and {bytes} bytes must be non-zero 16-byte multiples" 900 )); 901 } 902 #[cfg(has_omega_pf)] 903 { 904 // SAFETY: plain values; both ranges are session buffers the caller owns. 905 let rc = unsafe { ffi::omega_gpu_pf_copy_va(dst_va, src_va, bytes) }; 906 if rc != 0 { 907 return Err(rc_err(rc).to_string()); 908 } 909 Ok(()) 910 } 911 #[cfg(not(has_omega_pf))] 912 { 913 Err(OmegaGpuError::Unavailable.to_string()) 914 } 915 } 916 fn alloc_dev(&mut self, bytes: usize) -> Result { 917 PfMem::alloc_dev(bytes).map_err(|e| e.to_string()) 918 } 919 fn alloc_host(&mut self, bytes: usize) -> Result { 920 PfMem::alloc_host(bytes).map_err(|e| e.to_string()) 921 } 922 fn qgemm_bm(&self) -> usize { 923 #[cfg(has_omega_pf)] 924 { 925 // SAFETY: no arguments. 926 unsafe { ffi::omega_gpu_pf_qgemm_bm() as usize } 927 } 928 #[cfg(not(has_omega_pf))] 929 { 930 DEFAULT_BM 931 } 932 } 933 fn quant( 934 &mut self, 935 k: usize, 936 input: QuantIn, 937 rows: usize, 938 x_va: u64, 939 q_va: u64, 940 s_va: u64, 941 ) -> Result { 942 check_quant(k).map_err(|e| e.to_string())?; 943 if x_va == 0 || q_va == 0 || s_va == 0 || rows > u32::MAX as usize { 944 return Err(format!("pf quant: null address or {rows} rows")); 945 } 946 #[cfg(has_omega_pf)] 947 { 948 let mut ns = 0u64; 949 // SAFETY: plain values and one out pointer; the addresses are session buffers the caller owns. 950 let rc = unsafe { 951 ffi::omega_gpu_pf_quant( 952 k as u32, 953 input as u32, 954 rows as u32, 955 x_va, 956 q_va, 957 s_va, 958 &mut ns, 959 ) 960 }; 961 if rc != 0 { 962 return Err(rc_err(rc).to_string()); 963 } 964 Ok(ns) 965 } 966 #[cfg(not(has_omega_pf))] 967 { 968 let _ = input; 969 Err(OmegaGpuError::Unavailable.to_string()) 970 } 971 } 972 fn qgemm(&mut self, c: &QgemmCall) -> Result { 973 check_qgemm(c.n, c.k, c.layout, c.ntiles).map_err(|e| e.to_string())?; 974 if c.tiles_va == 0 || c.xq_va == 0 || c.xs_va == 0 || c.y_va == 0 { 975 return Err("pf qgemm: null address".into()); 976 } 977 #[cfg(has_omega_pf)] 978 { 979 let mut ns = 0u64; 980 // SAFETY: plain values and one out pointer; the addresses are session buffers the caller owns. 981 let rc = unsafe { 982 ffi::omega_gpu_pf_qgemm( 983 c.n as u32, 984 c.k as u32, 985 c.layout as u32, 986 c.tiles_va, 987 c.ntiles as u32, 988 c.rowidx_va, 989 c.xq_va, 990 c.xs_va, 991 c.y_va, 992 &mut ns, 993 ) 994 }; 995 if rc != 0 { 996 return Err(rc_err(rc).to_string()); 997 } 998 Ok(ns) 999 } 1000 #[cfg(not(has_omega_pf))] 1001 { 1002 Err(OmegaGpuError::Unavailable.to_string()) 1003 } 1004 } 1005 } 1006 1007 /// Prefill device with optional per-call reading options. The original device and 1008 /// other models retain their own settings; this never uses a global tuning setter. 1009 #[derive(Debug, Default)] 1010 pub struct ScopedPfDevice { 1011 inner: OmegaPfDevice, 1012 profile: Option<[u32; 4]>, 1013 bm: usize, 1014 } 1015 impl ScopedPfDevice { 1016 /// Query the Omega-owned candidate for this request. Refuses missing native support. 1017 pub fn reading_fast(rows: usize) -> Result { 1018 let rows = u32::try_from(rows).map_err(|_| "reading row count exceeds u32")?; 1019 #[cfg(has_omega_pf_reading)] 1020 { 1021 let mut profile = [0; 4]; 1022 for (index, option) in profile.iter_mut().enumerate() { 1023 // SAFETY: pure scalar policy query; no session state changes. 1024 *option = unsafe { ffi::omega_gpu_pf_qgemm_reading_option(rows, index as u32) }; 1025 } 1026 // SAFETY: pure checked scalar query, no session or model state is changed. 1027 let bm = unsafe { 1028 ffi::omega_gpu_pf_qgemm_scoped_bm(profile[0], profile[1], profile[2], profile[3]) 1029 } as usize; 1030 if bm == 0 { 1031 return Err("scoped reading profile refused by native policy".into()); 1032 } 1033 Ok(Self { 1034 inner: OmegaPfDevice, 1035 profile: Some(profile), 1036 bm, 1037 }) 1038 } 1039 #[cfg(not(has_omega_pf_reading))] 1040 { 1041 let _ = rows; 1042 Err("adaptive reading profile unavailable in the linked native library".into()) 1043 } 1044 } 1045 /// Checked admission for existing storage. None means this library lacks the query. 1046 pub fn workspace_fits( 1047 &self, 1048 capacity: usize, 1049 padded: usize, 1050 tiles: usize, 1051 rows: usize, 1052 ) -> Option { 1053 #[cfg(has_omega_pf_reading)] 1054 { 1055 // SAFETY: pure scalar admission query, no memory access or session state. 1056 Some( 1057 unsafe { 1058 ffi::omega_gpu_pf_qgemm_workspace_fits( 1059 capacity as u64, 1060 padded as u64, 1061 tiles as u64, 1062 rows as u64, 1063 self.qgemm_bm() as u64, 1064 ) 1065 } == 1, 1066 ) 1067 } 1068 #[cfg(not(has_omega_pf_reading))] 1069 { 1070 let _ = (capacity, padded, tiles, rows); 1071 None 1072 } 1073 } 1074 /// Buffer reuse must keep the complete per-call profile, not just its height. 1075 pub fn same_profile(&self, other: &Self) -> bool { 1076 self.profile == other.profile 1077 } 1078 } 1079 1080 impl PrefillDevice for ScopedPfDevice { 1081 type Buf = PfMem; 1082 fn alloc_dev(&mut self, bytes: usize) -> Result { 1083 self.inner.alloc_dev(bytes) 1084 } 1085 fn alloc_host(&mut self, bytes: usize) -> Result { 1086 self.inner.alloc_host(bytes) 1087 } 1088 fn qgemm_bm(&self) -> usize { 1089 if self.profile.is_some() { 1090 self.bm 1091 } else { 1092 self.inner.qgemm_bm() 1093 } 1094 } 1095 fn quant( 1096 &mut self, 1097 k: usize, 1098 input: QuantIn, 1099 rows: usize, 1100 x_va: u64, 1101 q_va: u64, 1102 s_va: u64, 1103 ) -> Result { 1104 self.inner.quant(k, input, rows, x_va, q_va, s_va) 1105 } 1106 fn copy_va(&mut self, dst: u64, src: u64, bytes: usize) -> Result<(), String> { 1107 self.inner.copy_va(dst, src, bytes) 1108 } 1109 fn qgemm(&mut self, c: &QgemmCall) -> Result { 1110 if self.profile.is_none() { 1111 return self.inner.qgemm(c); 1112 } 1113 #[cfg(has_omega_pf_scoped)] 1114 { 1115 let p = self.profile.expect("checked above"); 1116 let n = u32::try_from(c.n).map_err(|_| "scoped qgemm n exceeds u32")?; 1117 let k = u32::try_from(c.k).map_err(|_| "scoped qgemm k exceeds u32")?; 1118 let nt = u32::try_from(c.ntiles).map_err(|_| "scoped qgemm tile count exceeds u32")?; 1119 let mut ns = 0; 1120 // SAFETY: plain checked-width values, one valid output pointer, and live 1121 // session buffers supplied by the caller. Omega validates shape and ordering. 1122 let rc = unsafe { 1123 ffi::omega_gpu_pf_qgemm_scoped( 1124 p[0], 1125 p[1], 1126 p[2], 1127 p[3], 1128 n, 1129 k, 1130 c.layout as u32, 1131 c.tiles_va, 1132 nt, 1133 c.rowidx_va, 1134 c.xq_va, 1135 c.xs_va, 1136 c.y_va, 1137 &mut ns, 1138 ) 1139 }; 1140 if rc != 0 { 1141 return Err(rc_err(rc).to_string()); 1142 } 1143 Ok(ns) 1144 } 1145 #[cfg(not(has_omega_pf_scoped))] 1146 { 1147 Err("scoped reading profile unavailable in the linked native library".into()) 1148 } 1149 } 1150 } 1151 1152 /// omega's prefill attention on a decode attention cache (the real [`PrefillAttention`]). 1153 /// The KV cache is shared with decode: after a call, decode continues at `pos0 + m`. 1154 pub struct OmegaPrefillAttention<'a> { 1155 cache: &'a mut aien_omega_dattn::DecodeAttnCache, 1156 } 1157 1158 impl std::fmt::Debug for OmegaPrefillAttention<'_> { 1159 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 1160 write!( 1161 f, 1162 "OmegaPrefillAttention {{ layers: {}, max_pos: {} }}", 1163 self.cache.layers(), 1164 self.cache.max_pos() 1165 ) 1166 } 1167 } 1168 1169 impl<'a> OmegaPrefillAttention<'a> { 1170 pub fn new(cache: &'a mut aien_omega_dattn::DecodeAttnCache) -> Self { 1171 Self { cache } 1172 } 1173 fn check(&self, layer: u32, pos0: u32, m: u32) -> Result<(), String> { 1174 if m == 0 1175 || layer as usize >= self.cache.layers() 1176 || pos0 as usize + m as usize > self.cache.max_pos() 1177 { 1178 return Err(format!( 1179 "prefill attn layer {layer} pos0 {pos0} m {m} refused: m >= 1, layer < {}, pos0 + m <= {}", 1180 self.cache.layers(), 1181 self.cache.max_pos() 1182 )); 1183 } 1184 Ok(()) 1185 } 1186 } 1187 1188 impl PrefillAttention for OmegaPrefillAttention<'_> { 1189 fn attend( 1190 &mut self, 1191 layer: u32, 1192 pos0: u32, 1193 m: u32, 1194 qkv: &[f32], 1195 eps: f32, 1196 out_scale: f32, 1197 out: &mut [f32], 1198 ) -> Result { 1199 self.check(layer, pos0, m)?; 1200 let mu = m as usize; 1201 if qkv.len() != mu * ATTN_QKV_WORDS || out.len() != mu * ATTN_OUT_WORDS { 1202 return Err(format!( 1203 "prefill attn: qkv {} / out {} words, want {} / {}", 1204 qkv.len(), 1205 out.len(), 1206 mu * ATTN_QKV_WORDS, 1207 mu * ATTN_OUT_WORDS 1208 )); 1209 } 1210 #[cfg(has_omega_pattn)] 1211 { 1212 let c = self.cache.raw_handle(); 1213 if c.is_null() { 1214 return Err("prefill attn: the decode attention cache is a stub".into()); 1215 } 1216 let mut info = PrefillAttnInfo::default(); 1217 // SAFETY: lengths and ranges checked; the cache is exclusively borrowed for the call. 1218 let rc = unsafe { 1219 ffi_attn::omega_gpu_prefill_attn( 1220 c, 1221 layer, 1222 pos0, 1223 m, 1224 qkv.as_ptr(), 1225 eps, 1226 out_scale, 1227 out.as_mut_ptr(), 1228 &mut info, 1229 ) 1230 }; 1231 if rc != 0 { 1232 return Err(attn_rc_err(rc).to_string()); 1233 } 1234 Ok(info.elapsed_ns) 1235 } 1236 #[cfg(not(has_omega_pattn))] 1237 { 1238 let _ = (eps, out_scale); 1239 Err(OmegaGpuError::Unavailable.to_string()) 1240 } 1241 } 1242 fn has_dev(&self) -> bool { 1243 has_attention_dev() 1244 } 1245 fn attend_dev( 1246 &mut self, 1247 layer: u32, 1248 pos0: u32, 1249 m: u32, 1250 qkv_va: u64, 1251 eps: f32, 1252 out_scale: f32, 1253 out_va: u64, 1254 ) -> Option> { 1255 #[cfg(has_omega_pattn_dev)] 1256 { 1257 if let Err(e) = self.check(layer, pos0, m) { 1258 return Some(Err(e)); 1259 } 1260 if qkv_va == 0 1261 || out_va == 0 1262 || !qkv_va.is_multiple_of(16) 1263 || !out_va.is_multiple_of(16) 1264 { 1265 return Some(Err( 1266 "prefill attn dev: addresses must be non-zero and 16-byte aligned".into(), 1267 )); 1268 } 1269 let c = self.cache.raw_handle(); 1270 if c.is_null() { 1271 return Some(Err( 1272 "prefill attn: the decode attention cache is a stub".into() 1273 )); 1274 } 1275 let mut info = PrefillAttnInfo::default(); 1276 // SAFETY: ranges checked; the addresses are session buffers the caller owns; the cache is 1277 // exclusively borrowed for the call. 1278 let rc = unsafe { 1279 ffi_attn::omega_gpu_prefill_attn_dev( 1280 c, layer, pos0, m, qkv_va, eps, out_scale, out_va, &mut info, 1281 ) 1282 }; 1283 Some(if rc != 0 { 1284 Err(attn_rc_err(rc).to_string()) 1285 } else { 1286 Ok(info.elapsed_ns) 1287 }) 1288 } 1289 #[cfg(not(has_omega_pattn_dev))] 1290 { 1291 let _ = (layer, pos0, m, qkv_va, eps, out_scale, out_va); 1292 None 1293 } 1294 } 1295 } 1296 1297 #[cfg(test)] 1298 mod tests { 1299 use super::*; 1300 1301 #[test] 1302 fn tile_bytes_match_the_c_layout() { 1303 let t = Tile { 1304 w_va: 0x1122_3344_5566_7788, 1305 s_va: 0x99aa_bbcc_ddee_ff00, 1306 row0: 7, 1307 cnt: 64, 1308 pad: 0, 1309 }; 1310 let b = t.to_bytes(); 1311 assert_eq!(&b[0..8], &0x1122_3344_5566_7788u64.to_le_bytes()); 1312 assert_eq!(&b[16..20], &7u32.to_le_bytes()); 1313 assert_eq!(&b[20..24], &64u32.to_le_bytes()); 1314 assert_eq!(Tile::from_bytes(&b), t); 1315 assert_eq!(std::mem::offset_of!(Tile, row0), 16); 1316 assert_eq!(std::mem::offset_of!(Tile, cnt), 20); 1317 } 1318 1319 #[test] 1320 fn tiles_follow_the_c_builder_rules() { 1321 // expert 0: 130 rows (3 tiles: 64, 64, 2), expert 1: none, expert 2: 64 rows (1 tile) 1322 let t = build_tiles(64, &[10, 20, 30], &[11, 21, 31], &[130, 0, 64]).unwrap(); 1323 let rows: Vec<(u64, u32, u32)> = t.iter().map(|t| (t.w_va, t.row0, t.cnt)).collect(); 1324 assert_eq!( 1325 rows, 1326 vec![(10, 0, 64), (10, 64, 64), (10, 128, 2), (30, 130, 64)] 1327 ); 1328 assert!(t.iter().all(|t| t.s_va == t.w_va + 1 && t.pad == 0)); 1329 assert!(build_tiles(64, &[1], &[1, 2], &[3]).is_err()); 1330 assert!(build_tiles(0, &[1], &[1], &[3]).is_err()); 1331 } 1332 1333 #[test] 1334 fn host_checks_mirror_the_spec_rules() { 1335 assert!(check_quant(2048).is_ok() && check_quant(4096).is_ok() && check_quant(768).is_ok()); 1336 // Qwen3.8-27B widths (split rows) and the 32768 bound. 1337 assert!( 1338 check_quant(5120).is_ok() && check_quant(6144).is_ok() && check_quant(17408).is_ok() 1339 ); 1340 assert!(check_quant(32768).is_ok() && check_quant(32896).is_err()); 1341 assert!(check_quant(100).is_err()); 1342 assert!(check_qgemm(16384, 5120, Layout::Plain, 1).is_ok()); 1343 assert!(check_qgemm(5120, 17408, Layout::Plain, 1).is_ok()); 1344 assert!(check_qgemm(34816, 5120, Layout::SwigluNat, 1).is_ok()); 1345 assert!(check_qgemm(5120, 32896, Layout::Plain, 1).is_err()); 1346 assert!(check_qgemm(5120, 2048, Layout::Plain, 57).is_ok()); 1347 assert!(check_qgemm(2048, 4096, Layout::Plain, 1).is_ok()); 1348 assert!(check_qgemm(1536, 2048, Layout::SwigluNat, 1).is_ok()); 1349 assert!(check_qgemm(2048, 768, Layout::Plain, 1).is_ok()); 1350 assert!( 1351 check_qgemm(384, 2048, Layout::SwigluNat, 1).is_err(), 1352 "SwiGLU n must be a multiple of 256" 1353 ); 1354 assert!(check_qgemm(100, 2048, Layout::Plain, 1).is_err()); 1355 assert!( 1356 check_qgemm(32768, 2048, Layout::Plain, 1).is_err(), 1357 "n * 256 >= 2^23" 1358 ); 1359 assert!(check_qgemm(128, 2048, Layout::Plain, MAX_TILES + 1).is_err()); 1360 } 1361 1362 #[test] 1363 fn scoped_profile_keeps_legacy_height() { 1364 let original = OmegaPfDevice.qgemm_bm(); 1365 assert_eq!(ScopedPfDevice::default().qgemm_bm(), original); 1366 #[cfg(has_omega_pf_reading)] 1367 { 1368 let fast = ScopedPfDevice::reading_fast(5017).unwrap(); 1369 assert_eq!(fast.qgemm_bm(), 128); 1370 let small = ScopedPfDevice::reading_fast(64).unwrap(); 1371 assert_eq!(small.qgemm_bm(), 64); 1372 assert!(small.same_profile(&ScopedPfDevice::reading_fast(1).unwrap())); 1373 assert!(!small.same_profile(&fast)); 1374 assert!(fast.same_profile(&ScopedPfDevice::reading_fast(65).unwrap())); 1375 assert!(ScopedPfDevice::reading_fast(0).is_err()); 1376 assert_eq!(small.workspace_fits(4096, 4224, 33, 30), Some(true)); 1377 assert_eq!(fast.workspace_fits(4096, 4224, 33, 4096), Some(true)); 1378 assert_eq!(small.workspace_fits(4096, 4224, 33, 4096), Some(false)); 1379 assert_eq!(fast.workspace_fits(64, 128, 2, 64), Some(false)); 1380 assert_eq!(OmegaPfDevice.qgemm_bm(), original); 1381 assert_eq!(ScopedPfDevice::default().qgemm_bm(), original); 1382 } 1383 #[cfg(not(has_omega_pf_reading))] 1384 assert!(ScopedPfDevice::reading_fast(5017) 1385 .unwrap_err() 1386 .contains("unavailable")); 1387 } 1388 #[cfg(all(has_omega_pf_reading, target_pointer_width = "64"))] 1389 #[test] 1390 fn scoped_call_refuses_truncation_before_native() { 1391 let mut fast = ScopedPfDevice::reading_fast(5017).unwrap(); 1392 let valid = QgemmCall { 1393 n: 256, 1394 k: 128, 1395 layout: Layout::Plain, 1396 tiles_va: 16, 1397 ntiles: 1, 1398 rowidx_va: 0, 1399 xq_va: 32, 1400 xs_va: 48, 1401 y_va: 64, 1402 }; 1403 for field in 0..3 { 1404 let mut call = valid; 1405 match field { 1406 0 => call.n = usize::MAX, 1407 1 => call.k = usize::MAX, 1408 _ => call.ntiles = usize::MAX, 1409 }; 1410 assert!(fast.qgemm(&call).unwrap_err().contains("exceeds u32")); 1411 } 1412 } 1413 1414 #[test] 1415 fn ffi_struct_layouts() { 1416 assert_eq!(std::mem::size_of::(), 40); 1417 assert_eq!(std::mem::offset_of!(OmegaGpuMem, cpu), 16); 1418 assert_eq!(std::mem::offset_of!(OmegaGpuMem, va), 24); 1419 assert_eq!(std::mem::offset_of!(PrefillAttnInfo, elapsed_ns), 40); 1420 assert_eq!(std::mem::size_of::(), 64); 1421 } 1422 1423 /// Host only (no session, no chip): the Rust tile builder equals omega's C builder. 1424 #[cfg(has_omega_pf)] 1425 #[test] 1426 fn rust_tiles_equal_the_c_builder() { 1427 let d = OmegaPfDevice; 1428 let bm = d.qgemm_bm(); 1429 assert_eq!(bm, DEFAULT_BM); 1430 let counts = [130u32, 0, 64, 1, 0, 200]; 1431 let w: Vec = (0..6).map(|e| 0x1000 * (e + 1)).collect(); 1432 let s: Vec = (0..6).map(|e| 0x10_0000 + e).collect(); 1433 assert_eq!( 1434 build_tiles(bm, &w, &s, &counts).unwrap(), 1435 d.tiles_va_c(&w, &s, &counts).unwrap() 1436 ); 1437 } 1438 1439 #[cfg(not(has_omega_pf))] 1440 #[test] 1441 fn stub_refuses() { 1442 let mut d = OmegaPfDevice; 1443 assert!(matches!( 1444 PfMem::alloc_dev(64), 1445 Err(OmegaGpuError::Unavailable) 1446 )); 1447 assert!(d 1448 .quant(2048, QuantIn::F32, 1, 1, 1, 1) 1449 .unwrap_err() 1450 .contains("unavailable")); 1451 assert_eq!(d.qgemm_bm(), DEFAULT_BM); 1452 } 1453 1454 // ---- W-L1G-D: router logits + combine host mirrors ---- 1455 fn lcg_vec(seed: &mut u64, n: usize, scale: f32) -> Vec { 1456 (0..n) 1457 .map(|_| { 1458 *seed = seed 1459 .wrapping_mul(`6364136223846793005`) 1460 .wrapping_add(`1442695040888963407`); 1461 ((*seed >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale 1462 }) 1463 .collect() 1464 } 1465 1466 #[test] 1467 fn router_mirror_equals_the_rust_sum_bit_for_bit() { 1468 let (e, k, rows) = (16usize, 64usize, 5usize); 1469 let mut s = 7u64; 1470 let w = lcg_vec(&mut s, e * k, 0.1); 1471 let mut x = lcg_vec(&mut s, rows * k, 2.0); 1472 x[2 * k..3 * k].fill(-0.0); // signed-zero products: the sign of the sum depends on the -0.0 start 1473 let wq = pack_router(e, k, &w); 1474 assert_eq!(wq.len(), router_packed_len(e, k)); 1475 assert!( 1476 wq[(k / 4) * e * 4..].iter().all(|&v| v.to_bits() == 0), 1477 "pad group is zero" 1478 ); 1479 let mut got = vec![0.0f32; rows * e]; 1480 router_logits_ref(k, e, rows, &x, &wq, &mut got); 1481 for r in 0..rows { 1482 for ex in 0..e { 1483 let want: f32 = w[ex * k..(ex + 1) * k] 1484 .iter() 1485 .zip(&x[r * k..(r + 1) * k]) 1486 .map(|(a, b)| a * b) 1487 .sum(); 1488 assert_eq!( 1489 got[r * e + ex].to_bits(), 1490 want.to_bits(), 1491 "row {r} expert {ex}" 1492 ); 1493 } 1494 } 1495 } 1496 1497 #[test] 1498 fn combine_mirror_accumulates_from_zero_in_slot_order() { 1499 let (h, top_k, rows) = (8usize, 4usize, 3usize); 1500 let mut s = 11u64; 1501 let down = lcg_vec(&mut s, rows * top_k * h, 1.0); 1502 let wt = lcg_vec(&mut s, rows * top_k, 0.5); 1503 let inv: Vec = (0..(rows * top_k) as u32).rev().collect(); 1504 let mut got = vec![0.0f32; rows * h]; 1505 moe_combine_ref(h, top_k, rows, &down, &inv, &wt, &mut got); 1506 for r in 0..rows { 1507 for c in 0..h { 1508 let mut acc = 0.0f32; 1509 for sl in 0..top_k { 1510 acc += wt[r * top_k + sl] * down[inv[r * top_k + sl] as usize * h + c]; 1511 } 1512 assert_eq!(got[r * h + c].to_bits(), acc.to_bits()); 1513 } 1514 } 1515 } 1516 1517 #[cfg(has_omega_pfhost)] 1518 #[test] 1519 fn rust_router_pack_equals_the_c_packer() { 1520 let (e, k) = (128usize, 2048usize); 1521 let mut s = 3u64; 1522 let w = lcg_vec(&mut s, e * k, 0.1); 1523 let a = pack_router(e, k, &w); 1524 let b = pack_router_c(e, k, &w).unwrap(); 1525 assert!(a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()) && a.len() == b.len()); 1526 assert_eq!(OmegaPfDevice.router_rows(), Some(16)); 1527 } 1528 1529 #[cfg(not(has_omega_pfhost))] 1530 #[test] 1531 fn pfhost_stub_offers_no_router() { 1532 assert_eq!(OmegaPfDevice.router_rows(), None); 1533 assert!(pack_router_c(4, 4, &[0.0; 16]).is_err()); 1534 } 1535 }