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
aien-sovereign-core-mv / crates / aien-inference-abi / src / qwen3_moe_omega_dgraph.rs
| 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 | //! One command list per decode token (OWN-30B L2 cut 2), behind `OWN30B_DECODE_GRAPH=1`. |
| 17 | //! |
| 18 | //! Off (the default) nothing changes: every decode step is [`Qwen3MoeOmegaEngine::step`], about |
| 19 | //! 289 synchronous launches with host work between them. On, a decode step records the whole |
| 20 | //! token into one omega command list (`aien-omega-dgraph`): all 48 layers, the final norm, the |
| 21 | //! bf16 lm_head and the argmax, one submission. The residual row never leaves the chip; the host |
| 22 | //! writes the token's embedding row before and reads the greedy token after. |
| 23 | //! |
| 24 | //! The graph reuses the objects the engine already uploaded (FP8 q|k|v, o, gate|up, down; the |
| 25 | //! device router; the fused-attention KV cache; the lm_head GEMV) by their omega handles. It |
| 26 | //! needs `--weights fp8 --attn fused --router device --lm-head gemv`; any other load with the |
| 27 | //! switch on is refused with a plain message, never silently run on the old path. |
| 28 | //! |
| 29 | //! Prefill stays as it is. Traced steps (the parity harness) and the host routing mutant take |
| 30 | //! the old path: they need the host-side intermediates the graph does not produce. |
| 31 | //! |
| 32 | //! Token choice: with a greedy request through [`Qwen3MoeOmegaEngine::generate`] the graph's own |
| 33 | //! argmax is used (the same rule as `sample_argmax`: lowest index of the max logit). Any other |
| 34 | //! sampler gets the graph's logits read back from the chip (no second lm_head launch). |
| 35 | //! |
| 36 | //! Test hook: `OWN30B_DECODE_GRAPH_MUTANT` (only read when the switch is on) wires the graph |
| 37 | //! wrongly on purpose so a token check must fail: `norm-shift` (layer l gets layer l+1's input |
| 38 | //! norm), `skip-final-norm`, or `1`/`2`/`3` (omega's own kernel mutants). |
| 39 | use super::*; |
| 40 | use aien_omega_dgraph::{DecodeGraph, GraphConfig, GraphStats}; |
| 41 | |
| 42 | /// The switch: `1` turns the one-list decode on. |
| 43 | pub const ENV: &str = "OWN30B_DECODE_GRAPH"; |
| 44 | /// TEST ONLY: deliberate wrong wiring (see the module doc). |
| 45 | pub const MUTANT_ENV: &str = "OWN30B_DECODE_GRAPH_MUTANT"; |
| 46 | |
| 47 | /// Measurement: `1` (with [`ENV`]`=1`) records a GPU timestamp after every launch of every graph |
| 48 | /// token and sums them per launch kind ([`Timeline`]). Costs a timestamp per launch plus a read. |
| 49 | pub const STAMPS_ENV: &str = "OWN30B_DECODE_GRAPH_STAMPS"; |
| 50 | |
| 51 | /// Whether the environment asks for the per-launch timeline. |
| 52 | pub fn stamps_requested() -> bool { |
| 53 | std::env::var(STAMPS_ENV).as_deref() == Ok("1") |
| 54 | } |
| 55 | |
| 56 | /// Per-kind GPU time of the graph tokens since the last [`Qwen3MoeOmegaEngine::take_decode_timeline`]. |
| 57 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 58 | pub struct Timeline { |
| 59 | /// Graph tokens summed. |
| 60 | pub steps: u64, |
| 61 | /// Launches and GPU ns per kind (`aien_omega_dgraph::KIND_NAMES` order). |
| 62 | pub launches: [u64; 12], |
| 63 | pub ns: [u64; 12], |
| 64 | /// Sum of each token's first-to-last stamp span, and of the graph's own chip_ns. |
| 65 | pub span_ns: u64, |
| 66 | pub chip_ns: u64, |
| 67 | } |
| 68 | |
| 69 | /// Whether the environment asks for the one-list decode. |
| 70 | pub fn requested() -> bool { |
| 71 | std::env::var(ENV).as_deref() == Ok("1") |
| 72 | } |
| 73 | |
| 74 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 75 | enum Mutant { |
| 76 | None, |
| 77 | NormShift, |
| 78 | SkipFinalNorm, |
| 79 | Omega(i32), |
| 80 | } |
| 81 | |
| 82 | fn mutant() -> Result<Mutant, String> { |
| 83 | match std::env::var(MUTANT_ENV).as_deref() { |
| 84 | Err(_) | Ok("") | Ok("0") => Ok(Mutant::None), |
| 85 | Ok("norm-shift") => Ok(Mutant::NormShift), |
| 86 | Ok("skip-final-norm") => Ok(Mutant::SkipFinalNorm), |
| 87 | Ok(v @ ("1" | "2" | "3")) => Ok(Mutant::Omega(v.parse().unwrap_or(0))), |
| 88 | Ok(v) => Err(format!( |
| 89 | "{MUTANT_ENV}={v} is not one of norm-shift, skip-final-norm, 1, 2, 3" |
| 90 | )), |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// The engine's graph and the token it produced but nobody consumed yet. |
| 95 | pub(super) struct GraphState { |
| 96 | graph: DecodeGraph, |
| 97 | pending: bool, |
| 98 | pending_token: u32, |
| 99 | mutant: String, |
| 100 | stamps: bool, |
| 101 | timeline: Timeline, |
| 102 | } |
| 103 | |
| 104 | impl std::fmt::Debug for GraphState { |
| 105 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 106 | write!( |
| 107 | f, |
| 108 | "GraphState {{ {:?}, pending: {}, mutant: {} }}", |
| 109 | self.graph, self.pending, self.mutant |
| 110 | ) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | const NEEDS: &str = "OWN30B_DECODE_GRAPH=1 needs the load --weights fp8 --attn fused --router device --lm-head gemv"; |
| 115 | |
| 116 | /// Every handle the graph takes, or the plain reason this load cannot run it. |
| 117 | fn handles( |
| 118 | w: &Qwen3MoeOmegaWeights, |
| 119 | ) -> Result<(GraphConfig, Vec<[*mut std::ffi::c_void; 4]>), String> { |
| 120 | let c = &w.config; |
| 121 | if !aien_omega_dgraph::is_native() { |
| 122 | return Err(format!("{ENV}=1 but this binary has no one-list decode linked (omega before d3f465dc, or a CPU stub build)")); |
| 123 | } |
| 124 | if c.hidden != aien_omega_dgraph::HIDDEN { |
| 125 | return Err(format!( |
| 126 | "{NEEDS}; and hidden {} (the graph is built for {})", |
| 127 | c.hidden, |
| 128 | aien_omega_dgraph::HIDDEN |
| 129 | )); |
| 130 | } |
| 131 | let router = match &w.device_router { |
| 132 | Some(r) => r.omega_raw(), |
| 133 | None => { |
| 134 | return Err(format!( |
| 135 | "{NEEDS}; this load routes on the host (no device router)" |
| 136 | )) |
| 137 | } |
| 138 | }; |
| 139 | let lm_head = match &w.lm_head { |
| 140 | LmHead::Gemv(g) => g.omega_raw(), |
| 141 | LmHead::Dense(_) => return Err(format!("{NEEDS}; this load has the dense lm_head")), |
| 142 | }; |
| 143 | if router.is_null() || lm_head.is_null() { |
| 144 | return Err(format!( |
| 145 | "{NEEDS}; the router or lm_head is not an omega object" |
| 146 | )); |
| 147 | } |
| 148 | let mut layers = Vec::with_capacity(w.layers.len()); |
| 149 | for (l, layer) in w.layers.iter().enumerate() { |
| 150 | let (AttnWeights::Fp8 { qkv, o }, ExpertWeights::Fp8 { gate_up, down }) = |
| 151 | (&layer.attn, &layer.experts) |
| 152 | else { |
| 153 | return Err(format!("{NEEDS}; layer {l} has bf16 attention or experts")); |
| 154 | }; |
| 155 | let h = [ |
| 156 | qkv.omega_raw(), |
| 157 | o.omega_raw(), |
| 158 | gate_up.omega_raw(), |
| 159 | down.omega_raw(), |
| 160 | ]; |
| 161 | if h.iter().any(|p| p.is_null()) { |
| 162 | return Err(format!( |
| 163 | "{NEEDS}; layer {l} has a projection that is not an omega FP8 tensor" |
| 164 | )); |
| 165 | } |
| 166 | layers.push(h); |
| 167 | } |
| 168 | let cfg = GraphConfig { |
| 169 | layers: c.layers as u32, |
| 170 | vocab: c.vocab as u32, |
| 171 | eps: c.rms_eps, |
| 172 | norm_topk: c.norm_topk_prob as i32, |
| 173 | router, |
| 174 | attn: std::ptr::null_mut(), |
| 175 | lm_head, |
| 176 | }; |
| 177 | Ok((cfg, layers)) |
| 178 | } |
| 179 | |
| 180 | impl Qwen3MoeOmegaEngine { |
| 181 | /// Whether decode steps run as one command list (`OWN30B_DECODE_GRAPH=1` at engine creation). |
| 182 | pub fn decode_graph_on(&self) -> bool { |
| 183 | self.decode_graph |
| 184 | } |
| 185 | |
| 186 | /// Builds the graph now (it is otherwise built at the first decode step), so a load that |
| 187 | /// cannot run it fails before any generation. No-op when the switch is off. |
| 188 | pub fn prepare_decode_graph(&mut self) -> Result<(), String> { |
| 189 | if !self.decode_graph || self.dgraph.is_some() { |
| 190 | return Ok(()); |
| 191 | } |
| 192 | let (mut cfg, layers) = handles(&self.weights)?; |
| 193 | cfg.attn = match self.kv.dgraph_cache(self.pos) { |
| 194 | Some(r) => r?, |
| 195 | None => { |
| 196 | return Err(format!( |
| 197 | "{NEEDS}; this load has the {} attention path", |
| 198 | self.kv.path_name() |
| 199 | )) |
| 200 | } |
| 201 | }; |
| 202 | if cfg.attn.is_null() { |
| 203 | return Err(format!("{NEEDS}; the KV cache is not an omega object")); |
| 204 | } |
| 205 | let m = mutant()?; |
| 206 | // SAFETY: every handle is an omega object owned by self.weights / self.kv, which live as |
| 207 | // long as the engine; `dgraph` is declared before them, so it is dropped first. |
| 208 | let mut graph = unsafe { DecodeGraph::create(&cfg) } |
| 209 | .map_err(|e| format!("decode graph create: {e}"))?; |
| 210 | let n = layers.len(); |
| 211 | for (l, h) in layers.iter().enumerate() { |
| 212 | let norm_from = if m == Mutant::NormShift { |
| 213 | (l + 1) % n |
| 214 | } else { |
| 215 | l |
| 216 | }; |
| 217 | // SAFETY: as above. |
| 218 | unsafe { |
| 219 | graph.set_layer( |
| 220 | l, |
| 221 | h[0], |
| 222 | h[1], |
| 223 | h[2], |
| 224 | h[3], |
| 225 | &self.weights.layers[norm_from].input_norm, |
| 226 | ) |
| 227 | } |
| 228 | .map_err(|e| format!("decode graph layer {l}: {e}"))?; |
| 229 | } |
| 230 | if m != Mutant::SkipFinalNorm { |
| 231 | graph |
| 232 | .set_final_norm(&self.weights.final_norm) |
| 233 | .map_err(|e| format!("decode graph final norm: {e}"))?; |
| 234 | } |
| 235 | if let Mutant::Omega(k) = m { |
| 236 | graph.test_set_mutant(k); |
| 237 | } |
| 238 | let stamps = stamps_requested(); |
| 239 | graph.set_stamps(stamps); |
| 240 | let mutant = match m { |
| 241 | Mutant::None => "none".to_string(), |
| 242 | other => format!("{other:?} (TEST ONLY: wrong on purpose)"), |
| 243 | }; |
| 244 | self.dgraph = Some(GraphState { |
| 245 | graph, |
| 246 | pending: false, |
| 247 | pending_token: 0, |
| 248 | mutant, |
| 249 | stamps, |
| 250 | timeline: Timeline::default(), |
| 251 | }); |
| 252 | Ok(()) |
| 253 | } |
| 254 | |
| 255 | /// The per-kind timeline summed since the last call (stamps on), reset to empty. |
| 256 | pub fn take_decode_timeline(&mut self) -> Option<Timeline> { |
| 257 | let g = self.dgraph.as_mut()?; |
| 258 | g.stamps.then(|| std::mem::take(&mut g.timeline)) |
| 259 | } |
| 260 | |
| 261 | /// The deliberate wrong wiring in force ("none" normally), for receipts. |
| 262 | pub fn decode_graph_mutant(&self) -> &str { |
| 263 | self.dgraph.as_ref().map_or("none", |g| g.mutant.as_str()) |
| 264 | } |
| 265 | |
| 266 | /// A decode step: the one-list token when the switch is on (and the step is not traced), |
| 267 | /// else [`Self::step`]. On the graph path the returned hidden state is empty and the token is |
| 268 | /// held for [`Self::dgraph_take_greedy`] / [`Self::logits`]. |
| 269 | pub(super) fn decode_step(&mut self, token: u32) -> Result<Vec<f32>, String> { |
| 270 | if !self.decode_graph |
| 271 | || !self.trace_layers.is_empty() |
| 272 | || self.routing_mutant |
| 273 | || self.draft_on() |
| 274 | { |
| 275 | return self.step(token); |
| 276 | } |
| 277 | let t0 = Instant::now(); |
| 278 | let pos = self.pos; |
| 279 | if pos >= self.kv.capacity() { |
| 280 | return Err(format!("context full: {pos} of {}", self.kv.capacity())); |
| 281 | } |
| 282 | self.prepare_decode_graph()?; |
| 283 | match self.kv.dgraph_cache(pos) { |
| 284 | Some(r) => { |
| 285 | r?; |
| 286 | } |
| 287 | None => { |
| 288 | return Err(format!( |
| 289 | "{NEEDS}; this load has the {} attention path", |
| 290 | self.kv.path_name() |
| 291 | )) |
| 292 | } |
| 293 | } |
| 294 | let x = self.weights.embed_row(token); |
| 295 | let g = self |
| 296 | .dgraph |
| 297 | .as_mut() |
| 298 | .ok_or("decode graph missing after prepare")?; |
| 299 | let (next, st): (u32, GraphStats) = g |
| 300 | .graph |
| 301 | .token(&x, pos) |
| 302 | .map_err(|e| format!("decode graph token at {pos}: {e}"))?; |
| 303 | g.pending = true; |
| 304 | g.pending_token = next; |
| 305 | // The token ran and wrote this position's KV: book it before reporting a timeline error. |
| 306 | let mut timeline_err = None; |
| 307 | if g.stamps { |
| 308 | match g.graph.stamps() { |
| 309 | Err(e) => timeline_err = Some(format!("decode graph timeline at {pos}: {e}")), |
| 310 | Ok((stamps, kinds)) => { |
| 311 | let t = &mut g.timeline; |
| 312 | t.steps += 1; |
| 313 | for (i, &k) in kinds.iter().enumerate() { |
| 314 | let k = (k as usize).min(11); |
| 315 | t.launches[k] += 1; |
| 316 | t.ns[k] += stamps[i + 1].saturating_sub(stamps[i]); |
| 317 | } |
| 318 | t.span_ns += stamps |
| 319 | .last() |
| 320 | .copied() |
| 321 | .unwrap_or(0) |
| 322 | .saturating_sub(stamps.first().copied().unwrap_or(0)); |
| 323 | t.chip_ns += st.chip_ns; |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | self.kv.dgraph_commit(pos); |
| 328 | self.pos = pos + 1; |
| 329 | self.history.push(token); |
| 330 | let total_ns = t0.elapsed().as_nanos() as u64; |
| 331 | self.last_timing = StepTiming { |
| 332 | total_ns, |
| 333 | chip_ns: st.chip_ns, |
| 334 | launches: st.launches as u64, |
| 335 | host_ns: total_ns.saturating_sub(st.chip_ns), |
| 336 | graph_tokens: 1, |
| 337 | graph_launches: st.launches as u64, |
| 338 | graph_submits: st.submits as u64, |
| 339 | graph_record_ns: st.record_ns, |
| 340 | ..StepTiming::default() |
| 341 | }; |
| 342 | match timeline_err { |
| 343 | Some(e) => Err(e), |
| 344 | None => Ok(Vec::new()), |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | /// The graph's greedy token of the last decode step, when the caller's sampler is the |
| 349 | /// argmax (the graph used the same rule). Consumes it. |
| 350 | pub(super) fn dgraph_take_greedy(&mut self, argmax_sampler: bool) -> Option<u32> { |
| 351 | let g = self.dgraph.as_mut()?; |
| 352 | if !argmax_sampler || !g.pending { |
| 353 | return None; |
| 354 | } |
| 355 | g.pending = false; |
| 356 | Some(g.pending_token) |
| 357 | } |
| 358 | |
| 359 | /// The graph's logits of the last decode step, read back from the chip (any sampler). |
| 360 | /// Consumes the pending token. `None`: no graph token is pending. |
| 361 | pub(super) fn dgraph_take_logits(&mut self) -> Option<Result<Vec<f32>, String>> { |
| 362 | let g = self.dgraph.as_mut()?; |
| 363 | if !g.pending { |
| 364 | return None; |
| 365 | } |
| 366 | g.pending = false; |
| 367 | let mut logits = vec![0.0f32; g.graph.vocab()]; |
| 368 | Some( |
| 369 | g.graph |
| 370 | .read(None, None, Some(&mut logits)) |
| 371 | .map(|_| logits) |
| 372 | .map_err(|e| format!("decode graph logits: {e}")), |
| 373 | ) |
| 374 | } |
| 375 | |
| 376 | /// Forgets a pending graph token (reset, rewind, a new generation). |
| 377 | pub(super) fn dgraph_clear(&mut self) { |
| 378 | if let Some(g) = self.dgraph.as_mut() { |
| 379 | g.pending = false; |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | #[cfg(test)] |
| 385 | mod tests { |
| 386 | use super::*; |
| 387 | |
| 388 | #[test] |
| 389 | fn mutant_names_parse_and_unknown_ones_are_refused() { |
| 390 | // The env is process-wide: this test only reads it through `mutant()` with values it sets. |
| 391 | std::env::set_var(MUTANT_ENV, "norm-shift"); |
| 392 | assert_eq!(mutant(), Ok(Mutant::NormShift)); |
| 393 | std::env::set_var(MUTANT_ENV, "skip-final-norm"); |
| 394 | assert_eq!(mutant(), Ok(Mutant::SkipFinalNorm)); |
| 395 | std::env::set_var(MUTANT_ENV, "3"); |
| 396 | assert_eq!(mutant(), Ok(Mutant::Omega(3))); |
| 397 | std::env::set_var(MUTANT_ENV, "eps2"); |
| 398 | assert!(mutant().is_err()); |
| 399 | std::env::remove_var(MUTANT_ENV); |
| 400 | assert_eq!(mutant(), Ok(Mutant::None)); |
| 401 | } |
| 402 | } |