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-dgraph / src / lib.rs

582 lines · 20338 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-ish Rust wrapper over omega's one-command-list decode token for Qwen3-30B-A3B
17//! (`src/omega_gpu_decode_graph.h`, OWN-30B L2 cut 2 on the omega side; no CUDA).
18//!
19//! One call ([`DecodeGraph::token`]) records every layer (input norm, q|k|v FP8, decode
20//! attention, o FP8, residual add, router, gate|up FP8, SwiGLU, down FP8, combine) plus the
21//! final norm, the bf16 lm_head and a two-stage argmax into ONE omega command list and submits
22//! it once. The residual row stays on the device for the whole token; the host writes the
23//! token's embedding row before and reads the greedy token after.
24//!
25//! The graph does not own the weights, the router or the KV cache: it takes the C handles of
26//! objects the caller already uploaded (`as_raw()` of `aien_omega_fp8::Fp8Tensor`,
27//! `aien_omega_router::Router`, `aien_omega_dattn::DecodeAttnCache`,
28//! `aien_omega_bf16::Bf16Tensor`). Those objects must outlive the graph and must not be used
29//! concurrently with a [`DecodeGraph::token`] call. Without the native library
30//! (`is_native()` false) every call returns `Unavailable`.
31use aien_omega_gpu::OmegaGpuError;
32use std::ffi::c_void;
33use std::fmt;
34
35/// Residual width (`OMEGA_GPU_DGRAPH_HIDDEN`).
36pub const HIDDEN: usize = 2048;
37/// Most layers (`OMEGA_GPU_DGRAPH_MAX_LAYERS`).
38pub const MAX_LAYERS: usize = 64;
39/// Largest vocabulary the two-stage argmax covers (`2048 * 2048`).
40pub const MAX_VOCAB: usize = 2048 * 2048;
41
42/// True when the decode graph API is linked (not the stub).
43pub const fn is_native() -> bool {
44 cfg!(has_omega_dgraph)
45}
46
47/// Launch kinds of the timeline (`OMEGA_GPU_DGRAPH_K_*`), in enum order.
48pub const KIND_NAMES: [&str; 12] = [
49 "norm",
50 "qkv",
51 "attn",
52 "o_proj",
53 "res_add",
54 "router",
55 "gate_up",
56 "swiglu",
57 "down",
58 "combine_norm",
59 "lm_head",
60 "argmax",
61];
62
63/// omega's own name for a launch kind (`omega_gpu_decode_graph_kind_name`); the table above
64/// in the stub.
65pub fn kind_name(kind: u8) -> String {
66 #[cfg(has_omega_dgraph)]
67 {
68 // SAFETY: returns a static NUL-terminated string or NULL.
69 let p = unsafe { ffi::omega_gpu_decode_graph_kind_name(kind) };
70 if !p.is_null() {
71 // SAFETY: non-null static string.
72 return unsafe { std::ffi::CStr::from_ptr(p) }
73 .to_string_lossy()
74 .into_owned();
75 }
76 }
77 KIND_NAMES
78 .get(kind as usize)
79 .map_or_else(|| format!("kind{kind}"), |s| s.to_string())
80}
81
82/// Mirror of `OmegaGpuDecodeGraphStats`: what one token cost.
83#[repr(C)]
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
85pub struct GraphStats {
86 /// Launches recorded for the token.
87 pub launches: u32,
88 /// Submissions (1 normally).
89 pub submits: u32,
90 /// Chip time of the submission(s): first submit to last marker.
91 pub chip_ns: u64,
92 /// Host: begin_token to the submit (recording).
93 pub record_ns: u64,
94 /// Host: begin_token to end_token return.
95 pub total_ns: u64,
96 /// Launch semaphores found DONE.
97 pub sems_done: u32,
98}
99
100/// Mirror of `OmegaGpuDecodeGraphConfig`.
101#[repr(C)]
102#[derive(Debug, Clone, Copy)]
103pub struct GraphConfig {
104 pub layers: u32,
105 pub vocab: u32,
106 pub eps: f32,
107 pub norm_topk: i32,
108 pub router: *mut c_void,
109 pub attn: *mut c_void,
110 pub lm_head: *const c_void,
111}
112
113#[cfg(has_omega_dgraph)]
114mod ffi {
115 use super::{GraphConfig, GraphStats};
116 use std::ffi::c_void;
117 #[repr(C)]
118 pub struct OmegaGpuDecodeGraph {
119 _private: [u8; 0],
120 }
121 extern "C" {
122 pub fn omega_gpu_decode_graph_create(
123 cfg: *const GraphConfig,
124 out: *mut *mut OmegaGpuDecodeGraph,
125 ) -> i32;
126 pub fn omega_gpu_decode_graph_free(g: *mut OmegaGpuDecodeGraph);
127 pub fn omega_gpu_decode_graph_set_layer(
128 g: *mut OmegaGpuDecodeGraph,
129 layer: u32,
130 qkv: *const c_void,
131 o: *const c_void,
132 gate_up: *const c_void,
133 down: *const c_void,
134 input_norm: *const f32,
135 ) -> i32;
136 pub fn omega_gpu_decode_graph_set_final_norm(
137 g: *mut OmegaGpuDecodeGraph,
138 final_norm: *const f32,
139 ) -> i32;
140 pub fn omega_gpu_decode_graph_token(
141 g: *mut OmegaGpuDecodeGraph,
142 x_embed: *const f32,
143 pos: u32,
144 token: *mut u32,
145 st: *mut GraphStats,
146 ) -> i32;
147 pub fn omega_gpu_decode_graph_read(
148 g: *mut OmegaGpuDecodeGraph,
149 x: *mut f32,
150 hidden: *mut f32,
151 logits: *mut f32,
152 ) -> i32;
153 pub fn omega_gpu_decode_graph_set_flush_each(g: *mut OmegaGpuDecodeGraph, on: i32);
154 pub fn omega_gpu_decode_graph_test_set_mutant(g: *mut OmegaGpuDecodeGraph, mutant: i32);
155 pub fn omega_gpu_decode_graph_set_stamps(g: *mut OmegaGpuDecodeGraph, on: i32);
156 pub fn omega_gpu_decode_graph_stamps(
157 g: *const OmegaGpuDecodeGraph,
158 stamps: *mut u64,
159 kinds: *mut u8,
160 cap: u32,
161 ) -> i32;
162 pub fn omega_gpu_decode_graph_kind_name(kind: u8) -> *const std::os::raw::c_char;
163 pub fn omega_gpu_session_last_error() -> *const std::os::raw::c_char;
164 }
165}
166
167#[cfg(has_omega_dgraph)]
168fn rc_err(stage: &str, rc: i32) -> OmegaGpuError {
169 let name = match rc {
170 -1 => "BAD_ARGS",
171 -3 => "CODEGEN_FAIL",
172 -4 => "CHIP_FAIL",
173 _ => "?",
174 };
175 // SAFETY: returns a static NUL-terminated string or NULL.
176 let detail = unsafe {
177 let e = ffi::omega_gpu_session_last_error();
178 if e.is_null() {
179 String::new()
180 } else {
181 std::ffi::CStr::from_ptr(e).to_string_lossy().into_owned()
182 }
183 };
184 OmegaGpuError::Rc {
185 rc,
186 name: format!("decode graph {stage}: {name}: {detail}"),
187 }
188}
189
190fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> {
191 if expected == got {
192 Ok(())
193 } else {
194 Err(OmegaGpuError::ShapeMismatch {
195 what,
196 expected,
197 got,
198 })
199 }
200}
201
202fn bad(name: String) -> OmegaGpuError {
203 OmegaGpuError::Rc { rc: -1, name }
204}
205
206/// Host check of the configuration, before any chip call (also in the stub).
207pub fn check_config(cfg: &GraphConfig) -> Result<(), OmegaGpuError> {
208 if cfg.layers == 0 || cfg.layers as usize > MAX_LAYERS {
209 return Err(bad(format!(
210 "decode graph: {} layers, 1..={MAX_LAYERS} supported",
211 cfg.layers
212 )));
213 }
214 if cfg.vocab == 0 || cfg.vocab as usize > MAX_VOCAB {
215 return Err(bad(format!(
216 "decode graph: vocab {} outside 1..={MAX_VOCAB}",
217 cfg.vocab
218 )));
219 }
220 if cfg.router.is_null() || cfg.attn.is_null() || cfg.lm_head.is_null() {
221 return Err(bad(
222 "decode graph: the router, the KV cache and the lm_head must all be device objects"
223 .into(),
224 ));
225 }
226 Ok(())
227}
228
229/// One recorded-per-token decode graph. Not `Sync`: callers serialise use behind a lock.
230pub struct DecodeGraph {
231 #[cfg(has_omega_dgraph)]
232 ptr: *mut ffi::OmegaGpuDecodeGraph,
233 layers: usize,
234 vocab: usize,
235}
236
237// SAFETY: an owning handle to device buffers; moved between threads, never shared unlocked.
238unsafe impl Send for DecodeGraph {}
239
240impl fmt::Debug for DecodeGraph {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 write!(
243 f,
244 "DecodeGraph {{ layers: {}, vocab: {} }}",
245 self.layers, self.vocab
246 )
247 }
248}
249
250impl DecodeGraph {
251 /// Allocates the graph's device buffers.
252 ///
253 /// # Safety
254 /// `cfg.router`, `cfg.attn` and `cfg.lm_head` are live omega handles (`as_raw()` of the
255 /// matching crates' objects) that outlive the graph.
256 pub unsafe fn create(cfg: &GraphConfig) -> Result<Self, OmegaGpuError> {
257 check_config(cfg)?;
258 #[cfg(has_omega_dgraph)]
259 {
260 let mut ptr = std::ptr::null_mut();
261 let rc = ffi::omega_gpu_decode_graph_create(cfg, &mut ptr);
262 if rc != 0 || ptr.is_null() {
263 return Err(rc_err("create", rc));
264 }
265 Ok(Self {
266 ptr,
267 layers: cfg.layers as usize,
268 vocab: cfg.vocab as usize,
269 })
270 }
271 #[cfg(not(has_omega_dgraph))]
272 Err(OmegaGpuError::Unavailable)
273 }
274
275 pub fn layers(&self) -> usize {
276 self.layers
277 }
278
279 pub fn vocab(&self) -> usize {
280 self.vocab
281 }
282
283 /// Binds one layer's FP8 projections (omega checks the shapes) and copies its
284 /// `input_layernorm` weight (f32 `[HIDDEN]`).
285 ///
286 /// # Safety
287 /// The four pointers are live `OmegaGpuFp8Tensor` handles that outlive the graph.
288 pub unsafe fn set_layer(
289 &mut self,
290 layer: usize,
291 qkv: *const c_void,
292 o: *const c_void,
293 gate_up: *const c_void,
294 down: *const c_void,
295 input_norm: &[f32],
296 ) -> Result<(), OmegaGpuError> {
297 check_len("decode graph input_norm", HIDDEN, input_norm.len())?;
298 if layer >= self.layers {
299 return Err(bad(format!(
300 "decode graph: layer {layer} of {}",
301 self.layers
302 )));
303 }
304 if qkv.is_null() || o.is_null() || gate_up.is_null() || down.is_null() {
305 return Err(bad(format!(
306 "decode graph layer {layer}: a projection has no device handle"
307 )));
308 }
309 #[cfg(has_omega_dgraph)]
310 {
311 let rc = ffi::omega_gpu_decode_graph_set_layer(
312 self.ptr,
313 layer as u32,
314 qkv,
315 o,
316 gate_up,
317 down,
318 input_norm.as_ptr(),
319 );
320 if rc != 0 {
321 return Err(rc_err("set_layer", rc));
322 }
323 Ok(())
324 }
325 #[cfg(not(has_omega_dgraph))]
326 Err(OmegaGpuError::Unavailable)
327 }
328
329 /// Copies the final RMSNorm weight (f32 `[HIDDEN]`).
330 pub fn set_final_norm(&mut self, final_norm: &[f32]) -> Result<(), OmegaGpuError> {
331 check_len("decode graph final_norm", HIDDEN, final_norm.len())?;
332 #[cfg(has_omega_dgraph)]
333 {
334 // SAFETY: ptr is live; the slice holds HIDDEN f32 (checked).
335 let rc = unsafe {
336 ffi::omega_gpu_decode_graph_set_final_norm(self.ptr, final_norm.as_ptr())
337 };
338 if rc != 0 {
339 return Err(rc_err("set_final_norm", rc));
340 }
341 Ok(())
342 }
343 #[cfg(not(has_omega_dgraph))]
344 Err(OmegaGpuError::Unavailable)
345 }
346
347 /// One whole token as one command list: `x_embed` (the token's embedding row, f32
348 /// `[HIDDEN]`) at position `pos` -> the greedy token (lowest index of the max logit) and
349 /// what it cost. The KV cache gets this position's K/V for every layer.
350 pub fn token(
351 &mut self,
352 x_embed: &[f32],
353 pos: usize,
354 ) -> Result<(u32, GraphStats), OmegaGpuError> {
355 check_len("decode graph x_embed", HIDDEN, x_embed.len())?;
356 let pos =
357 u32::try_from(pos).map_err(|_| bad(format!("decode graph: pos {pos} too large")))?;
358 #[cfg(has_omega_dgraph)]
359 {
360 let mut token = 0u32;
361 let mut st = GraphStats::default();
362 // SAFETY: ptr is live; x_embed holds HIDDEN f32 (checked); token and st are local.
363 let rc = unsafe {
364 ffi::omega_gpu_decode_graph_token(
365 self.ptr,
366 x_embed.as_ptr(),
367 pos,
368 &mut token,
369 &mut st,
370 )
371 };
372 if rc != 0 {
373 return Err(rc_err("token", rc));
374 }
375 Ok((token, st))
376 }
377 #[cfg(not(has_omega_dgraph))]
378 {
379 let _ = pos;
380 Err(OmegaGpuError::Unavailable)
381 }
382 }
383
384 /// Copies the last token's device residual `x`, final-normed `hidden` (both `[HIDDEN]`)
385 /// and `logits` (`[vocab]`); any of them may be `None`. Costs a device read.
386 pub fn read(
387 &mut self,
388 x: Option<&mut [f32]>,
389 hidden: Option<&mut [f32]>,
390 logits: Option<&mut [f32]>,
391 ) -> Result<(), OmegaGpuError> {
392 if let Some(x) = &x {
393 check_len("decode graph read x", HIDDEN, x.len())?;
394 }
395 if let Some(h) = &hidden {
396 check_len("decode graph read hidden", HIDDEN, h.len())?;
397 }
398 if let Some(l) = &logits {
399 check_len("decode graph read logits", self.vocab, l.len())?;
400 }
401 #[cfg(has_omega_dgraph)]
402 {
403 let p = |s: Option<&mut [f32]>| s.map_or(std::ptr::null_mut(), |s| s.as_mut_ptr());
404 // SAFETY: ptr is live; each non-null buffer has the length omega copies (checked).
405 let rc =
406 unsafe { ffi::omega_gpu_decode_graph_read(self.ptr, p(x), p(hidden), p(logits)) };
407 if rc != 0 {
408 return Err(rc_err("read", rc));
409 }
410 Ok(())
411 }
412 #[cfg(not(has_omega_dgraph))]
413 Err(OmegaGpuError::Unavailable)
414 }
415
416 /// Timeline (measurement): when on, every later token also records a GPU timestamp before
417 /// the first launch and after each launch. Call between tokens. Off by default.
418 pub fn set_stamps(&mut self, on: bool) {
419 #[cfg(has_omega_dgraph)]
420 // SAFETY: ptr is live; plain integer argument.
421 unsafe {
422 ffi::omega_gpu_decode_graph_set_stamps(self.ptr, on as i32)
423 }
424 #[cfg(not(has_omega_dgraph))]
425 let _ = on;
426 }
427
428 /// The last token's timeline: `launches + 1` GPU timestamps (ns) and one kind per launch
429 /// (launch `i` took `stamps[i + 1] - stamps[i]`). Refused when stamps are off or the token failed.
430 pub fn stamps(&self) -> Result<(Vec<u64>, Vec<u8>), OmegaGpuError> {
431 #[cfg(has_omega_dgraph)]
432 {
433 // 9 per layer + 4, with room to spare.
434 let cap = (MAX_LAYERS * 16 + 16) as u32;
435 let mut stamps = vec![0u64; cap as usize + 1];
436 let mut kinds = vec![0u8; cap as usize + 1];
437 // SAFETY: ptr is live; both buffers hold cap + 1 entries.
438 let n = unsafe {
439 ffi::omega_gpu_decode_graph_stamps(
440 self.ptr,
441 stamps.as_mut_ptr(),
442 kinds.as_mut_ptr(),
443 cap + 1,
444 )
445 };
446 if n < 0 {
447 return Err(rc_err("stamps", n));
448 }
449 let n = n as usize;
450 stamps.truncate(n + 1);
451 kinds.truncate(n);
452 Ok((stamps, kinds))
453 }
454 #[cfg(not(has_omega_dgraph))]
455 Err(OmegaGpuError::Unavailable)
456 }
457
458 /// TEST ONLY: submit after every launch (the batching comparison).
459 pub fn set_flush_each(&mut self, on: bool) {
460 #[cfg(has_omega_dgraph)]
461 // SAFETY: ptr is live; plain integer argument.
462 unsafe {
463 ffi::omega_gpu_decode_graph_set_flush_each(self.ptr, on as i32)
464 }
465 #[cfg(not(has_omega_dgraph))]
466 let _ = on;
467 }
468
469 /// TEST ONLY: omega's deliberate wrong kernels (0 off; 1 SwiGLU reads the wrong half;
470 /// 2 combine skips expert 7; 3 attention written at scale 1 instead of 2^64). A token
471 /// check must catch the one it sets.
472 pub fn test_set_mutant(&mut self, mutant: i32) {
473 #[cfg(has_omega_dgraph)]
474 // SAFETY: ptr is live; plain integer argument.
475 unsafe {
476 ffi::omega_gpu_decode_graph_test_set_mutant(self.ptr, mutant)
477 }
478 #[cfg(not(has_omega_dgraph))]
479 let _ = mutant;
480 }
481}
482
483impl Drop for DecodeGraph {
484 fn drop(&mut self) {
485 #[cfg(has_omega_dgraph)]
486 // SAFETY: ptr came from create and is freed once.
487 unsafe {
488 ffi::omega_gpu_decode_graph_free(self.ptr)
489 }
490 }
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 fn cfg(layers: u32, vocab: u32, live: bool) -> GraphConfig {
498 let p = if live {
499 8usize as *mut c_void
500 } else {
501 std::ptr::null_mut()
502 };
503 GraphConfig {
504 layers,
505 vocab,
506 eps: 1e-6,
507 norm_topk: 1,
508 router: p,
509 attn: p,
510 lm_head: p,
511 }
512 }
513
514 #[test]
515 fn config_is_checked_on_the_host() {
516 assert!(check_config(&cfg(48, 151936, true)).is_ok());
517 assert!(check_config(&cfg(0, 151936, true)).is_err());
518 assert!(check_config(&cfg(65, 151936, true)).is_err());
519 assert!(check_config(&cfg(48, 0, true)).is_err());
520 assert!(check_config(&cfg(48, (MAX_VOCAB + 1) as u32, true)).is_err());
521 assert!(check_config(&cfg(48, 151936, false)).is_err());
522 }
523
524 #[test]
525 fn create_refuses_null_handles_before_any_c_call() {
526 // SAFETY: the null handles are refused by check_config before the C call.
527 let r = unsafe { DecodeGraph::create(&cfg(48, 151936, false)) };
528 assert!(r.is_err());
529 }
530
531 #[test]
532 fn layouts_match_the_c_structs() {
533 // Measured with cc against omega_gpu_decode_graph.h (omega d3f465dc): config sizeof 40,
534 // layers 0 vocab 4 eps 8 norm_topk 12 router 16 attn 24 lm_head 32; stats sizeof 40,
535 // launches 0 submits 4 chip_ns 8 record_ns 16 total_ns 24 sems_done 32.
536 assert_eq!(std::mem::size_of::<GraphConfig>(), 40);
537 assert_eq!(std::mem::offset_of!(GraphConfig, eps), 8);
538 assert_eq!(std::mem::offset_of!(GraphConfig, norm_topk), 12);
539 assert_eq!(std::mem::offset_of!(GraphConfig, router), 16);
540 assert_eq!(std::mem::offset_of!(GraphConfig, attn), 24);
541 assert_eq!(std::mem::offset_of!(GraphConfig, lm_head), 32);
542 assert_eq!(std::mem::size_of::<GraphStats>(), 40);
543 assert_eq!(std::mem::offset_of!(GraphStats, submits), 4);
544 assert_eq!(std::mem::offset_of!(GraphStats, chip_ns), 8);
545 assert_eq!(std::mem::offset_of!(GraphStats, record_ns), 16);
546 assert_eq!(std::mem::offset_of!(GraphStats, total_ns), 24);
547 assert_eq!(std::mem::offset_of!(GraphStats, sems_done), 32);
548 }
549
550 /// Native binding smoke without the chip: omega's own argument checks answer BAD_ARGS
551 /// before touching any handle or the device.
552 #[cfg(has_omega_dgraph)]
553 #[test]
554 fn native_symbols_link_and_refuse_bad_args_without_the_chip() {
555 let c = cfg(0, 151936, true);
556 let mut out = std::ptr::null_mut();
557 // SAFETY: layers == 0 is refused by omega before any handle is read (omega_gpu_decode_graph.c create).
558 let rc = unsafe { ffi::omega_gpu_decode_graph_create(&c, &mut out) };
559 assert_eq!(rc, -1);
560 assert!(out.is_null());
561 let norm = [0.0f32; HIDDEN];
562 // SAFETY: a NULL graph is refused first.
563 assert_eq!(
564 unsafe {
565 ffi::omega_gpu_decode_graph_set_final_norm(std::ptr::null_mut(), norm.as_ptr())
566 },
567 -1
568 );
569 let e = rc_err("smoke", -1).to_string();
570 assert!(e.contains("BAD_ARGS"), "{e}");
571 // omega's kind names are the table's, in enum order.
572 for (k, want) in KIND_NAMES.iter().enumerate() {
573 assert_eq!(kind_name(k as u8), *want);
574 }
575 assert_eq!(kind_name(12), "?");
576 }
577
578 #[test]
579 fn native_flag_matches_the_cfg() {
580 assert_eq!(is_native(), cfg!(has_omega_dgraph));
581 }
582}