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

509 lines · 17565 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 MoE router for Qwen3-30B-A3B
17//! (`src/omega_gpu_router_api.h`, OWN-30B router cut on the omega side; no CUDA).
18//!
19//! One call per layer per token does what the host did between attention and the experts:
20//! RMSNorm of the residual row with the layer's `post_attention_layernorm` weight, the 128
21//! router logits over bf16 weights, softmax, top-8 and (when `norm_topk_prob`) renormalised
22//! weights. Besides the ids and weights it hands the host, the launch leaves `x' =
23//! RMSNorm(x) * out_scale` and the two grouped-GEMV group tables on the device, at the
24//! addresses [`Router::device_outputs`] returns, so the FP8 gate|up launch
25//! (`Fp8Tensor::gemv_grouped_dev`) reads them with no host round trip.
26//!
27//! Shapes are fixed by the kernel: 128 experts, hidden 2048, top-8, at most [`MAX_LAYERS`]
28//! layers. Without the native library (`is_native()` false) every call returns `Unavailable`.
29use aien_omega_gpu::OmegaGpuError;
30use std::fmt;
31
32/// Experts the router scores (`OMEGA_ROUTER_EXPERTS`).
33pub const EXPERTS: usize = 128;
34/// Hidden width (`OMEGA_ROUTER_HIDDEN`).
35pub const HIDDEN: usize = 2048;
36/// Experts selected per token (`OMEGA_ROUTER_TOPK`).
37pub const TOP_K: usize = 8;
38/// Most layers one router holds (`OMEGA_GPU_ROUTER_MAX_LAYERS`).
39pub const MAX_LAYERS: usize = 64;
40/// The x' scale that gives the FP8 grouped GEMV its activation row (2^64).
41pub const OUT_SCALE_FP8: f32 = 18_446_744_073_709_551_616.0;
42
43/// True when the router API is linked (not the stub).
44pub const fn is_native() -> bool {
45 cfg!(has_omega_router)
46}
47
48/// Mirror of `OmegaGpuRouterInfo`: what the chip did for one call.
49#[repr(C)]
50#[derive(Debug, Clone, Copy, Default)]
51pub struct RouterInfo {
52 pub layer: u32,
53 pub warps: u32,
54 pub depth: u32,
55 pub threads: u32,
56 /// bf16 router bytes the launch streams: `128 * 2048 * 2`.
57 pub weight_bytes: u64,
58 /// Marker-to-marker chip time.
59 pub elapsed_ns: u64,
60 /// Whole call.
61 pub call_ns: u64,
62 pub completion_marker: u32,
63 /// C `int`: non-zero when the kernel came from the cache.
64 pub kernel_cache_hit: i32,
65}
66
67/// Device addresses of the last call's outputs.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub struct DeviceOutputs {
70 /// `x' = RMSNorm(x) * out_scale`, f32 `[2048]`.
71 pub xout_va: u64,
72 /// Group table for the gate|up launch (8 entries of `{w_va, s_va}`).
73 pub tab_gu_va: u64,
74 /// Group table for the down launch.
75 pub tab_dn_va: u64,
76}
77
78#[cfg(has_omega_router)]
79mod ffi {
80 use super::RouterInfo;
81 #[repr(C)]
82 pub struct OmegaGpuRouter {
83 _private: [u8; 0],
84 }
85 extern "C" {
86 pub fn omega_gpu_router_alloc_shape(
87 layers: u32,
88 experts: u32,
89 shared: u32,
90 out: *mut *mut OmegaGpuRouter,
91 ) -> i32;
92 pub fn omega_gpu_router_free(r: *mut OmegaGpuRouter);
93 pub fn omega_gpu_router_set_layer(
94 r: *mut OmegaGpuRouter,
95 layer: u32,
96 gate_bf16: *const u16,
97 norm_w: *const f32,
98 ) -> i32;
99 pub fn omega_gpu_router_set_directory(
100 r: *mut OmegaGpuRouter,
101 layer: u32,
102 gu: *const u64,
103 dn: *const u64,
104 ) -> i32;
105 pub fn omega_gpu_router(
106 r: *mut OmegaGpuRouter,
107 layer: u32,
108 x: *const f32,
109 eps: f32,
110 norm_topk: i32,
111 out_scale: f32,
112 ids: *mut u32,
113 weights: *mut f32,
114 info: *mut RouterInfo,
115 ) -> i32;
116 pub fn omega_gpu_router_device_outputs(
117 r: *const OmegaGpuRouter,
118 xout_va: *mut u64,
119 tab_gu_va: *mut u64,
120 tab_dn_va: *mut u64,
121 );
122 pub fn omega_gpu_router_read_back(
123 r: *mut OmegaGpuRouter,
124 xout: *mut f32,
125 tab_gu: *mut u64,
126 tab_dn: *mut u64,
127 ) -> i32;
128 pub fn omega_gpu_router_last_error() -> *const std::os::raw::c_char;
129 pub fn omega_gpu_router_rc_name(rc: i32) -> *const std::os::raw::c_char;
130 pub fn omega_gpu_router_test_set_mutant(mutant: i32);
131 }
132}
133
134#[cfg(has_omega_router)]
135fn rc_err(rc: i32) -> OmegaGpuError {
136 // SAFETY: both return static NUL-terminated strings (or NULL for last_error).
137 let name = unsafe {
138 let n = ffi::omega_gpu_router_rc_name(rc);
139 let n = if n.is_null() {
140 String::from("?")
141 } else {
142 std::ffi::CStr::from_ptr(n).to_string_lossy().into_owned()
143 };
144 let e = ffi::omega_gpu_router_last_error();
145 if e.is_null() {
146 n
147 } else {
148 format!("{n}: {}", std::ffi::CStr::from_ptr(e).to_string_lossy())
149 }
150 };
151 OmegaGpuError::Rc { rc, name }
152}
153
154fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> {
155 if expected == got {
156 Ok(())
157 } else {
158 Err(OmegaGpuError::ShapeMismatch {
159 what,
160 expected,
161 got,
162 })
163 }
164}
165
166fn bad(name: String) -> OmegaGpuError {
167 OmegaGpuError::Rc { rc: -1, name }
168}
169
170/// Host check of the allocation rule, before any chip call (also in the stub).
171pub fn check_layers(layers: usize) -> Result<(), OmegaGpuError> {
172 if layers == 0 || layers > MAX_LAYERS {
173 return Err(bad(format!(
174 "router layers={layers} refused: 1 <= layers <= {MAX_LAYERS}"
175 )));
176 }
177 Ok(())
178}
179
180/// The device-resident router weights, norm weights and expert directories of every layer plus
181/// the launch buffers. Not `Sync`: callers serialise use behind a lock.
182pub struct Router {
183 #[cfg(has_omega_router)]
184 ptr: *mut ffi::OmegaGpuRouter,
185 layers: usize,
186 /// Gate rows and directory entries: the routed experts plus the shared expert slot (128 for
187 /// the 30B, 257 for Qwen3.6-35B-A3B).
188 rows: usize,
189 /// Output slots of one route: [`TOP_K`], plus 1 with the shared expert slot.
190 slots: usize,
191}
192
193// SAFETY: an owning handle to device buffers; moved between threads, never shared unlocked.
194unsafe impl Send for Router {}
195
196impl fmt::Debug for Router {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 write!(f, "Router {{ layers: {} }}", self.layers)
199 }
200}
201
202impl Router {
203 /// The C handle (`OmegaGpuRouter *`) for another omega API that takes this object (the decode
204 /// graph, OWN-30B cut 2). Null in the stub. The handle stays owned by `self`: the caller must
205 /// not free it, must not use it after `self` is dropped, and must serialise its use with
206 /// `self`'s own calls.
207 pub fn as_raw(&self) -> *mut std::ffi::c_void {
208 #[cfg(has_omega_router)]
209 {
210 self.ptr as *mut std::ffi::c_void
211 }
212 #[cfg(not(has_omega_router))]
213 {
214 std::ptr::null_mut()
215 }
216 }
217
218 /// Allocates the per-layer tables and launch buffers on the chip.
219 pub fn alloc(layers: usize) -> Result<Self, OmegaGpuError> {
220 Self::alloc_shape(layers, EXPERTS, 0)
221 }
222
223 /// Another model's shape (omega `omega_gpu_router_alloc_shape`): `experts` 128 or 256 and
224 /// `shared` 0 or 1. With the shared slot the gate has `experts + 1` rows (the last =
225 /// shared_expert_gate), the directories `experts + 1` entries, and every output 9 slots (slot
226 /// 8 = the shared expert, weight sigmoid(shared gate . xn)).
227 pub fn alloc_shape(
228 layers: usize,
229 experts: usize,
230 shared: usize,
231 ) -> Result<Self, OmegaGpuError> {
232 check_layers(layers)?;
233 if !(experts == 128 || experts == 256) || shared > 1 {
234 return Err(bad(format!(
235 "router shape experts {experts} shared {shared}: 128 or 256, 0 or 1"
236 )));
237 }
238 let rows = experts + shared;
239 #[cfg(has_omega_router)]
240 {
241 let mut ptr = std::ptr::null_mut();
242 // SAFETY: layers checked; omega writes the handle on success.
243 let rc = unsafe {
244 ffi::omega_gpu_router_alloc_shape(
245 layers as u32,
246 experts as u32,
247 shared as u32,
248 &mut ptr,
249 )
250 };
251 if rc != 0 || ptr.is_null() {
252 return Err(rc_err(rc));
253 }
254 Ok(Self {
255 ptr,
256 layers,
257 rows,
258 slots: TOP_K + shared,
259 })
260 }
261 #[cfg(not(has_omega_router))]
262 {
263 let _ = rows;
264 Err(OmegaGpuError::Unavailable)
265 }
266 }
267
268 pub fn layers(&self) -> usize {
269 self.layers
270 }
271
272 /// Output slots of [`Self::route`]: 8, or 9 with the shared expert slot (slot 8).
273 pub fn slots(&self) -> usize {
274 self.slots
275 }
276
277 fn check_layer(&self, layer: usize) -> Result<(), OmegaGpuError> {
278 if layer >= self.layers {
279 return Err(bad(format!(
280 "router layer {layer} >= layers {}",
281 self.layers
282 )));
283 }
284 Ok(())
285 }
286
287 /// The layer's `mlp.gate.weight` (`[128][2048]` bf16 bits) and `post_attention_layernorm`
288 /// weight (`[2048]` f32, widened by the caller).
289 pub fn set_layer(
290 &mut self,
291 layer: usize,
292 gate_bf16: &[u16],
293 norm_w: &[f32],
294 ) -> Result<(), OmegaGpuError> {
295 check_len("router gate words", self.rows * HIDDEN, gate_bf16.len())?;
296 check_len("router norm weight", HIDDEN, norm_w.len())?;
297 self.check_layer(layer)?;
298 #[cfg(has_omega_router)]
299 {
300 // SAFETY: lengths and layer checked; omega copies before returning.
301 let rc = unsafe {
302 ffi::omega_gpu_router_set_layer(
303 self.ptr,
304 layer as u32,
305 gate_bf16.as_ptr(),
306 norm_w.as_ptr(),
307 )
308 };
309 if rc != 0 {
310 return Err(rc_err(rc));
311 }
312 Ok(())
313 }
314 #[cfg(not(has_omega_router))]
315 {
316 Err(OmegaGpuError::Unavailable)
317 }
318 }
319
320 /// The layer's expert directories: `gu` and `dn` are `[128][2]` `{w_va, s_va}` (flat, 256
321 /// words each), one pair per expert of the resident gate|up and down FP8 tensors.
322 pub fn set_directory(
323 &mut self,
324 layer: usize,
325 gu: &[u64],
326 dn: &[u64],
327 ) -> Result<(), OmegaGpuError> {
328 check_len("router gate|up directory", self.rows * 2, gu.len())?;
329 check_len("router down directory", self.rows * 2, dn.len())?;
330 self.check_layer(layer)?;
331 #[cfg(has_omega_router)]
332 {
333 // SAFETY: lengths and layer checked; omega copies before returning.
334 let rc = unsafe {
335 ffi::omega_gpu_router_set_directory(
336 self.ptr,
337 layer as u32,
338 gu.as_ptr(),
339 dn.as_ptr(),
340 )
341 };
342 if rc != 0 {
343 return Err(rc_err(rc));
344 }
345 Ok(())
346 }
347 #[cfg(not(has_omega_router))]
348 {
349 Err(OmegaGpuError::Unavailable)
350 }
351 }
352
353 /// One launch for `layer`: routes the residual row `x` (`[2048]` f32). Writes the 8 chosen
354 /// expert ids (descending by logit; slot 8 = the shared expert when allocated with it, see
355 /// [`Self::slots`]) and their weights to the host and `x' = RMSNorm(x) *
356 /// out_scale` plus both group tables to the device ([`Self::device_outputs`]).
357 #[allow(clippy::too_many_arguments)]
358 pub fn route(
359 &mut self,
360 layer: usize,
361 x: &[f32],
362 eps: f32,
363 norm_topk: bool,
364 out_scale: f32,
365 ids: &mut [u32],
366 weights: &mut [f32],
367 ) -> Result<RouterInfo, OmegaGpuError> {
368 check_len("router x", HIDDEN, x.len())?;
369 // The chip writes every slot (9 with the shared expert), so both buffers must hold them.
370 check_len("router ids", self.slots, ids.len())?;
371 check_len("router weights", self.slots, weights.len())?;
372 self.check_layer(layer)?;
373 #[cfg(has_omega_router)]
374 {
375 let mut info = RouterInfo::default();
376 // SAFETY: lengths and layer checked; omega fills ids and weights before returning.
377 let rc = unsafe {
378 ffi::omega_gpu_router(
379 self.ptr,
380 layer as u32,
381 x.as_ptr(),
382 eps,
383 norm_topk as i32,
384 out_scale,
385 ids.as_mut_ptr(),
386 weights.as_mut_ptr(),
387 &mut info,
388 )
389 };
390 if rc != 0 {
391 return Err(rc_err(rc));
392 }
393 Ok(info)
394 }
395 #[cfg(not(has_omega_router))]
396 {
397 let _ = (eps, norm_topk, out_scale);
398 Err(OmegaGpuError::Unavailable)
399 }
400 }
401
402 /// Device addresses of the outputs of the last [`Self::route`] (fixed for the router's life).
403 pub fn device_outputs(&self) -> DeviceOutputs {
404 #[cfg(has_omega_router)]
405 {
406 let mut o = DeviceOutputs::default();
407 // SAFETY: the router is live for &self; the three out pointers are valid.
408 unsafe {
409 ffi::omega_gpu_router_device_outputs(
410 self.ptr,
411 &mut o.xout_va,
412 &mut o.tab_gu_va,
413 &mut o.tab_dn_va,
414 )
415 };
416 o
417 }
418 #[cfg(not(has_omega_router))]
419 {
420 DeviceOutputs::default()
421 }
422 }
423
424 /// Test and trace helper: copies `x'` of the last call to the host.
425 pub fn read_xout(&mut self, xout: &mut [f32]) -> Result<(), OmegaGpuError> {
426 check_len("router xout", HIDDEN, xout.len())?;
427 #[cfg(has_omega_router)]
428 {
429 // SAFETY: length checked; the two table pointers are NULL (not wanted).
430 let rc = unsafe {
431 ffi::omega_gpu_router_read_back(
432 self.ptr,
433 xout.as_mut_ptr(),
434 std::ptr::null_mut(),
435 std::ptr::null_mut(),
436 )
437 };
438 if rc != 0 {
439 return Err(rc_err(rc));
440 }
441 Ok(())
442 }
443 #[cfg(not(has_omega_router))]
444 {
445 let _ = xout;
446 Err(OmegaGpuError::Unavailable)
447 }
448 }
449}
450
451impl Drop for Router {
452 fn drop(&mut self) {
453 #[cfg(has_omega_router)]
454 // SAFETY: ptr came from alloc and is freed once.
455 unsafe {
456 ffi::omega_gpu_router_free(self.ptr)
457 }
458 }
459}
460
461/// TEST ONLY: deliberately wrong router kernel (0 off; 1 RMSNorm without the weight; 2 the
462/// mask after each argmax round removes expert `id ^ 1`; 3 the directory entries copied are
463/// those of `id ^ 1`; 4 the weights are not normalised). A parity test must catch each.
464/// Clears the kernel cache.
465pub fn test_set_mutant(mutant: i32) {
466 #[cfg(has_omega_router)]
467 // SAFETY: plain integer argument.
468 unsafe {
469 ffi::omega_gpu_router_test_set_mutant(mutant)
470 }
471 #[cfg(not(has_omega_router))]
472 let _ = mutant;
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478
479 #[test]
480 fn layer_rule_is_checked_on_the_host() {
481 assert!(check_layers(48).is_ok());
482 assert!(check_layers(0).is_err());
483 assert!(check_layers(MAX_LAYERS + 1).is_err());
484 }
485
486 #[test]
487 fn lengths_are_checked_before_the_chip() {
488 // Without a chip alloc is Unavailable or refused by shape, never a C call.
489 assert!(Router::alloc(0).is_err());
490 assert_eq!(EXPERTS * HIDDEN * 2, 524_288);
491 assert_eq!(OUT_SCALE_FP8, 2f32.powi(64));
492 }
493
494 #[test]
495 fn info_layout_matches_the_c_struct() {
496 // Measured with cc against omega_gpu_router_api.h (own30b/integration 3c12866a):
497 // sizeof 48, warps at 4, depth at 8, threads at 12, weight_bytes at 16, elapsed_ns at 24,
498 // call_ns at 32, completion_marker at 40, kernel_cache_hit (int) at 44.
499 assert_eq!(std::mem::size_of::<RouterInfo>(), 48);
500 assert_eq!(std::mem::offset_of!(RouterInfo, warps), 4);
501 assert_eq!(std::mem::offset_of!(RouterInfo, depth), 8);
502 assert_eq!(std::mem::offset_of!(RouterInfo, threads), 12);
503 assert_eq!(std::mem::offset_of!(RouterInfo, weight_bytes), 16);
504 assert_eq!(std::mem::offset_of!(RouterInfo, elapsed_ns), 24);
505 assert_eq!(std::mem::offset_of!(RouterInfo, call_ns), 32);
506 assert_eq!(std::mem::offset_of!(RouterInfo, completion_marker), 40);
507 assert_eq!(std::mem::offset_of!(RouterInfo, kernel_cache_hit), 44);
508 }
509}