interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-omega-dattn / src / lib.rs

457 lines · 15686 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 one-launch decode attention for Qwen3-30B-A3B
17//! (`src/omega_gpu_decode_attn_api.h`, OWN-30B cut 8 on the omega side; no CUDA).
18//!
19//! One call per layer per token does what the split path did in one launch plus host work:
20//! per-head RMSNorm of q and k, RoPE from a chip-resident table, the append of the new K/V
21//! (bf16) into a GPU-resident cache, and the softmax attention over the whole context. The
22//! cache ([`DecodeAttnCache`]) owns the KV of every layer; the caller keeps positions in
23//! order (`0..pos` must be in the cache for that layer before the call at `pos`).
24//!
25//! Shapes are fixed by the kernel: 32 query heads, 4 KV heads, head_dim 128, so the input row
26//! is [`QKV_WORDS`] f32 (`q[32][128] | k[4][128] | v[4][128]`, exactly what the fused q/k/v
27//! GEMV writes) and the output is `32 * 128` f32. `max_pos` must be a multiple of 256 and at
28//! most [`MAX_POS`]; `layers` at most [`MAX_LAYERS`]. Without the native library
29//! (`is_native()` false) every call returns `Unavailable`.
30use aien_omega_gpu::OmegaGpuError;
31use std::fmt;
32pub mod raw;
33pub mod rows;
34
35/// Query heads the kernel is built for (`OMEGA_GPU_DATTN_Q_HEADS`).
36pub const Q_HEADS: usize = 32;
37/// KV heads (`OMEGA_GPU_DATTN_KV_HEADS`).
38pub const KV_HEADS: usize = 4;
39/// Head width.
40pub const HEAD_DIM: usize = 128;
41/// f32 words of one input row (`OMEGA_GPU_DATTN_QKV_WORDS`).
42pub const QKV_WORDS: usize = Q_HEADS * HEAD_DIM + 2 * KV_HEADS * HEAD_DIM;
43/// f32 words of one output row.
44pub const OUT_WORDS: usize = Q_HEADS * HEAD_DIM;
45/// Positions per split CTA (`OMEGA_DATTN_CHUNK`); `max_pos` is rounded to this.
46pub const POS_ROUND: usize = 256;
47/// Most positions one cache can hold (`OMEGA_GPU_DATTN_MAX_POS`).
48pub const MAX_POS: usize = 131072;
49/// Most layers one cache can hold (`OMEGA_GPU_DATTN_MAX_LAYERS`).
50pub const MAX_LAYERS: usize = 64;
51
52/// True when the decode attention API is linked (not the stub).
53pub const fn is_native() -> bool {
54 cfg!(has_omega_dattn)
55}
56
57/// Mirror of `OmegaGpuDecodeAttnInfo`: what the chip did for one call.
58#[repr(C)]
59#[derive(Debug, Clone, Copy, Default)]
60pub struct DecodeAttnInfo {
61 pub layer: u32,
62 pub pos: u32,
63 pub splits: u32,
64 pub per_split: u32,
65 pub depth: u32,
66 pub grid_x: u32,
67 pub grid_y: u32,
68 pub threads: u32,
69 /// K + V bytes the launch streams: `2 * 4 * (pos + 1) * 256`.
70 pub kv_bytes: u64,
71 /// Marker-to-marker chip time.
72 pub elapsed_ns: u64,
73 /// Whole call.
74 pub call_ns: u64,
75 pub completion_marker: u32,
76 /// C `int`: non-zero when the kernel came from the cache.
77 pub kernel_cache_hit: i32,
78}
79
80#[cfg(has_omega_dattn)]
81mod ffi {
82 use super::DecodeAttnInfo;
83 #[repr(C)]
84 pub struct OmegaGpuDecodeAttnCache {
85 _private: [u8; 0],
86 }
87 extern "C" {
88 pub fn omega_gpu_decode_attn_cache_alloc(
89 layers: u32,
90 max_pos: u32,
91 rope_theta: f64,
92 out: *mut *mut OmegaGpuDecodeAttnCache,
93 ) -> i32;
94 pub fn omega_gpu_decode_attn_cache_free(c: *mut OmegaGpuDecodeAttnCache);
95 pub fn omega_gpu_decode_attn_set_norms(
96 c: *mut OmegaGpuDecodeAttnCache,
97 layer: u32,
98 q_norm: *const f32,
99 k_norm: *const f32,
100 ) -> i32;
101 pub fn omega_gpu_decode_attn(
102 c: *mut OmegaGpuDecodeAttnCache,
103 layer: u32,
104 pos: u32,
105 qkv: *const f32,
106 eps: f32,
107 out_scale: f32,
108 out: *mut f32,
109 info: *mut DecodeAttnInfo,
110 ) -> i32;
111 pub fn omega_gpu_decode_attn_last_error() -> *const std::os::raw::c_char;
112 pub fn omega_gpu_decode_attn_rc_name(rc: i32) -> *const std::os::raw::c_char;
113 pub fn omega_gpu_decode_attn_set_depth(depth: u32);
114 pub fn omega_gpu_decode_attn_set_per_split(per_split: u32);
115 pub fn omega_gpu_decode_attn_test_set_mutant(mutant: i32);
116 // Row access to the cache (omega src/omega_gpu_decode_attn_api.c, test helpers used by the
117 // persistent KV park/restore of sc#505).
118 pub fn omega_gpu_decode_attn_cache_write(
119 c: *mut OmegaGpuDecodeAttnCache,
120 layer: u32,
121 kv_head: u32,
122 pos: u32,
123 count: u32,
124 k_bf16: *const u16,
125 v_bf16: *const u16,
126 ) -> i32;
127 pub fn omega_gpu_decode_attn_cache_read(
128 c: *mut OmegaGpuDecodeAttnCache,
129 layer: u32,
130 kv_head: u32,
131 pos: u32,
132 k_bf16: *mut u16,
133 v_bf16: *mut u16,
134 ) -> i32;
135 }
136}
137
138#[cfg(has_omega_dattn)]
139fn rc_err(rc: i32) -> OmegaGpuError {
140 // SAFETY: both return static NUL-terminated strings (or NULL for last_error).
141 let name = unsafe {
142 let n = ffi::omega_gpu_decode_attn_rc_name(rc);
143 let n = if n.is_null() {
144 String::from("?")
145 } else {
146 std::ffi::CStr::from_ptr(n).to_string_lossy().into_owned()
147 };
148 let e = ffi::omega_gpu_decode_attn_last_error();
149 if e.is_null() {
150 n
151 } else {
152 format!("{n}: {}", std::ffi::CStr::from_ptr(e).to_string_lossy())
153 }
154 };
155 OmegaGpuError::Rc { rc, name }
156}
157
158fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> {
159 if expected == got {
160 Ok(())
161 } else {
162 Err(OmegaGpuError::ShapeMismatch {
163 what,
164 expected,
165 got,
166 })
167 }
168}
169
170fn bad(name: String) -> OmegaGpuError {
171 OmegaGpuError::Rc { rc: -1, name }
172}
173
174/// Host check of the allocation rule, before any chip call (also in the stub).
175pub fn check_shape(layers: usize, max_pos: usize) -> Result<(), OmegaGpuError> {
176 if layers == 0
177 || layers > MAX_LAYERS
178 || max_pos == 0
179 || max_pos > MAX_POS
180 || !max_pos.is_multiple_of(POS_ROUND)
181 {
182 return Err(bad(format!(
183 "decode attn cache layers={layers} max_pos={max_pos} refused: 1 <= layers <= {MAX_LAYERS}, max_pos a multiple of {POS_ROUND} up to {MAX_POS}"
184 )));
185 }
186 Ok(())
187}
188
189/// Rounds a context length up to the cache granule, capped at [`MAX_POS`].
190pub fn round_max_pos(max_context: usize) -> usize {
191 max_context
192 .div_ceil(POS_ROUND)
193 .clamp(1, MAX_POS / POS_ROUND)
194 * POS_ROUND
195}
196
197/// Bytes the chip holds for a cache of `layers` x `max_pos` (K and V planes, without the
198/// small RoPE / norm / partial buffers).
199pub fn kv_bytes(layers: usize, max_pos: usize) -> usize {
200 layers * 2 * KV_HEADS * max_pos * HEAD_DIM * 2
201}
202
203/// The GPU-resident KV of every layer plus the RoPE table and norm weights. Not `Sync`:
204/// callers serialise use behind a lock.
205pub struct DecodeAttnCache {
206 #[cfg(has_omega_dattn)]
207 ptr: *mut ffi::OmegaGpuDecodeAttnCache,
208 layers: usize,
209 max_pos: usize,
210}
211
212// SAFETY: an owning handle to device buffers; moved between threads, never shared unlocked.
213unsafe impl Send for DecodeAttnCache {}
214
215impl fmt::Debug for DecodeAttnCache {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 write!(
218 f,
219 "DecodeAttnCache {{ layers: {}, max_pos: {} }}",
220 self.layers, self.max_pos
221 )
222 }
223}
224
225impl DecodeAttnCache {
226 /// The C handle (`OmegaGpuDecodeAttnCache *`) for another omega API that takes this object (the decode
227 /// graph, OWN-30B cut 2). Null in the stub. The handle stays owned by `self`: the caller must
228 /// not free it, must not use it after `self` is dropped, and must serialise its use with
229 /// `self`'s own calls.
230 pub fn as_raw(&self) -> *mut std::ffi::c_void {
231 #[cfg(has_omega_dattn)]
232 {
233 self.ptr as *mut std::ffi::c_void
234 }
235 #[cfg(not(has_omega_dattn))]
236 {
237 std::ptr::null_mut()
238 }
239 }
240
241 /// Allocates the cache on the chip and builds the RoPE table for `rope_theta`.
242 pub fn alloc(layers: usize, max_pos: usize, rope_theta: f64) -> Result<Self, OmegaGpuError> {
243 check_shape(layers, max_pos)?;
244 if rope_theta.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
245 return Err(bad(format!(
246 "decode attn rope_theta {rope_theta} must be positive"
247 )));
248 }
249 #[cfg(has_omega_dattn)]
250 {
251 let mut ptr = std::ptr::null_mut();
252 // SAFETY: arguments checked above; omega writes the handle on success.
253 let rc = unsafe {
254 ffi::omega_gpu_decode_attn_cache_alloc(
255 layers as u32,
256 max_pos as u32,
257 rope_theta,
258 &mut ptr,
259 )
260 };
261 if rc != 0 || ptr.is_null() {
262 return Err(rc_err(rc));
263 }
264 Ok(Self {
265 ptr,
266 layers,
267 max_pos,
268 })
269 }
270 #[cfg(not(has_omega_dattn))]
271 {
272 Err(OmegaGpuError::Unavailable)
273 }
274 }
275
276 pub fn layers(&self) -> usize {
277 self.layers
278 }
279 pub fn max_pos(&self) -> usize {
280 self.max_pos
281 }
282
283 /// The per-head RMSNorm weights of `layer` (`q_norm`, `k_norm`: 128 f32 each).
284 pub fn set_norms(
285 &mut self,
286 layer: usize,
287 q_norm: &[f32],
288 k_norm: &[f32],
289 ) -> Result<(), OmegaGpuError> {
290 check_len("decode attn q_norm", HEAD_DIM, q_norm.len())?;
291 check_len("decode attn k_norm", HEAD_DIM, k_norm.len())?;
292 if layer >= self.layers {
293 return Err(bad(format!(
294 "decode attn layer {layer} >= layers {}",
295 self.layers
296 )));
297 }
298 #[cfg(has_omega_dattn)]
299 {
300 // SAFETY: lengths checked; the cache is live for &mut self.
301 let rc = unsafe {
302 ffi::omega_gpu_decode_attn_set_norms(
303 self.ptr,
304 layer as u32,
305 q_norm.as_ptr(),
306 k_norm.as_ptr(),
307 )
308 };
309 if rc != 0 {
310 return Err(rc_err(rc));
311 }
312 Ok(())
313 }
314 #[cfg(not(has_omega_dattn))]
315 {
316 Err(OmegaGpuError::Unavailable)
317 }
318 }
319
320 /// One layer step for the token at `pos`: appends its K/V and writes the attention output
321 /// (`out[32 * 128] * out_scale`). `qkv` is the raw fused projection row (pre-norm, pre-rope).
322 pub fn attend(
323 &mut self,
324 layer: usize,
325 pos: usize,
326 qkv: &[f32],
327 eps: f32,
328 out_scale: f32,
329 out: &mut [f32],
330 ) -> Result<DecodeAttnInfo, OmegaGpuError> {
331 check_len("decode attn qkv", QKV_WORDS, qkv.len())?;
332 check_len("decode attn out", OUT_WORDS, out.len())?;
333 if layer >= self.layers {
334 return Err(bad(format!(
335 "decode attn layer {layer} >= layers {}",
336 self.layers
337 )));
338 }
339 if pos >= self.max_pos {
340 return Err(bad(format!(
341 "decode attn pos {pos} >= max_pos {}",
342 self.max_pos
343 )));
344 }
345 #[cfg(has_omega_dattn)]
346 {
347 let mut info = DecodeAttnInfo::default();
348 // SAFETY: lengths and ranges checked; the cache is live for &mut self.
349 let rc = unsafe {
350 ffi::omega_gpu_decode_attn(
351 self.ptr,
352 layer as u32,
353 pos as u32,
354 qkv.as_ptr(),
355 eps,
356 out_scale,
357 out.as_mut_ptr(),
358 &mut info,
359 )
360 };
361 if rc != 0 {
362 return Err(rc_err(rc));
363 }
364 Ok(info)
365 }
366 #[cfg(not(has_omega_dattn))]
367 {
368 let _ = (eps, out_scale, out);
369 Err(OmegaGpuError::Unavailable)
370 }
371 }
372}
373
374impl Drop for DecodeAttnCache {
375 fn drop(&mut self) {
376 #[cfg(has_omega_dattn)]
377 // SAFETY: ptr came from alloc and is freed once.
378 unsafe {
379 ffi::omega_gpu_decode_attn_cache_free(self.ptr)
380 }
381 }
382}
383
384/// Prefetch depth of the K and V streams, 1..4 (0 = the default); clears the kernel cache.
385pub fn set_depth(depth: u32) {
386 #[cfg(has_omega_dattn)]
387 // SAFETY: plain integer argument.
388 unsafe {
389 ffi::omega_gpu_decode_attn_set_depth(depth)
390 }
391 #[cfg(not(has_omega_dattn))]
392 let _ = depth;
393}
394
395/// Positions per split CTA, a multiple of 256 (0 = the default).
396pub fn set_per_split(per_split: u32) {
397 #[cfg(has_omega_dattn)]
398 // SAFETY: plain integer argument.
399 unsafe {
400 ffi::omega_gpu_decode_attn_set_per_split(per_split)
401 }
402 #[cfg(not(has_omega_dattn))]
403 let _ = per_split;
404}
405
406/// TEST ONLY: deliberately wrong kernel (0 off; 1 no RoPE on q and k; 2 V read one position
407/// late; 3 the new K/V not written to the cache; 4 cross-split combine ignores the max). A
408/// parity test must catch the one it sets. Clears the kernel cache.
409pub fn test_set_mutant(mutant: i32) {
410 #[cfg(has_omega_dattn)]
411 // SAFETY: plain integer argument.
412 unsafe {
413 ffi::omega_gpu_decode_attn_test_set_mutant(mutant)
414 }
415 #[cfg(not(has_omega_dattn))]
416 let _ = mutant;
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422
423 #[test]
424 fn shape_rule_is_checked_on_the_host() {
425 assert!(check_shape(48, 32768).is_ok());
426 assert!(check_shape(0, 256).is_err());
427 assert!(check_shape(65, 256).is_err());
428 assert!(check_shape(1, 100).is_err());
429 assert!(check_shape(1, MAX_POS + 256).is_err());
430 assert_eq!(round_max_pos(1), 256);
431 assert_eq!(round_max_pos(8192), 8192);
432 assert_eq!(round_max_pos(8193), 8448);
433 assert_eq!(round_max_pos(1 << 20), MAX_POS);
434 }
435
436 #[test]
437 fn lengths_are_checked_before_the_chip() {
438 // Without a chip the constructor is Unavailable or refused by shape, never a C call.
439 assert!(DecodeAttnCache::alloc(1, 100, 1e7).is_err());
440 assert_eq!(QKV_WORDS, 5120);
441 assert_eq!(OUT_WORDS, 4096);
442 assert_eq!(kv_bytes(48, 32768), 48 * 2 * 4 * 32768 * 256);
443 }
444
445 #[test]
446 fn info_layout_matches_the_c_struct() {
447 // Measured with cc against omega_gpu_decode_attn_api.h (own30b/integration 831001cc):
448 // sizeof 64, kv_bytes at 32, elapsed_ns at 40, call_ns at 48, completion_marker at 56,
449 // kernel_cache_hit (int) at 60.
450 assert_eq!(std::mem::size_of::<DecodeAttnInfo>(), 64);
451 assert_eq!(std::mem::offset_of!(DecodeAttnInfo, kv_bytes), 32);
452 assert_eq!(std::mem::offset_of!(DecodeAttnInfo, elapsed_ns), 40);
453 assert_eq!(std::mem::offset_of!(DecodeAttnInfo, call_ns), 48);
454 assert_eq!(std::mem::offset_of!(DecodeAttnInfo, completion_marker), 56);
455 assert_eq!(std::mem::offset_of!(DecodeAttnInfo, kernel_cache_hit), 60);
456 }
457}