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-q38/src/q36.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-q38 / src / q36.rs` 882 lines ยท 31096 bytes Raw Blame History 1 //! Qwen3.6-35B-A3B decode graph (omega `src/omega_gpu_q36_graph.h`, sc L306): the 27B graph's 2 //! mixers at the 35B shapes (DeltaNet ratio 2, attention 16 q / 2 kv heads) and the 30B's sparse 3 //! block with the shared expert as the ninth group. One whole token per [`Q36Graph::token`]. 4 //! 5 //! As [`crate::Q38Graph`], the graph owns neither the weights nor the state: it takes the C 6 //! handles of a [`crate::Gdn`] (ratio 2), an [`crate::Attn256Cache`] (shape 16 / 2 / 4), an 7 //! `aien_omega_router::Router` (shape 256 + 1 shared, every layer and directory set) and the FP8 / 8 //! bf16 tensors, which must outlive the graph and not be used concurrently with a token. 9 #[cfg(has_omega_q36)] 10 use crate::session_err; 11 use crate::{bad, check_len, GraphStats}; 12 use aien_omega_gpu::OmegaGpuError; 13 use std::ffi::c_void; 14 use std::fmt; 15 16 /// Residual width (`OMEGA_GPU_Q36_HIDDEN`). 17 pub const HIDDEN: usize = 2048; 18 /// Routed and shared expert width (`OMEGA_GPU_Q36_EXPERT_INTER`). 19 pub const EXPERT_INTER: usize = 512; 20 /// Expert groups per token: 8 routed + the shared one. 21 pub const GROUPS: usize = 9; 22 /// Experts in each layer's gate_up / down tensor: 256 routed, then the shared expert. 23 pub const EXPERT_ROWS: usize = 257; 24 /// DeltaNet fused projection rows: in_proj_qkv 8192 | in_proj_z 4096. 25 pub const GDN_MIX: usize = 12288; 26 /// DeltaNet in_proj_qkv rows (the conv width). 27 pub const GDN_QKV: usize = 8192; 28 /// DeltaNet a|b rows: 32 heads x {a, b}, interleaved. 29 pub const AB: usize = 64; 30 /// Attention fused projection rows: q_proj 8192 (16 x [q 256 | gate 256]) | k 512 | v 512. 31 pub const ATT_MIX: usize = 9216; 32 /// Mixer output width (DeltaNet 32 x 128 = attention 16 x 256): the o_proj input. 33 pub const MIXER_OUT: usize = 4096; 34 /// Attention heads: query, key/value, queries per CTA row (`omega_gpu_decode_attn256_cache_alloc_shape`). 35 pub const Q_HEADS: usize = 16; 36 pub const KV_HEADS: usize = 2; 37 pub const Q_PER_CTA: usize = 4; 38 /// DeltaNet value heads per key head. 39 pub const GDN_RATIO: usize = 2; 40 41 /// The C config (`OmegaGpuQ36GraphConfig`). 42 #[repr(C)] 43 #[derive(Debug, Clone, Copy)] 44 pub struct Q36Config { 45 pub layers: u32, 46 pub attn_mask: u64, 47 pub vocab: u32, 48 pub eps: f32, 49 pub eps_l2: f32, 50 pub gdn: *mut c_void, 51 pub attn: *mut c_void, 52 pub router: *mut c_void, 53 pub lm_head: *const c_void, 54 } 55 56 #[cfg(has_omega_q36)] 57 mod ffi { 58 use super::{GraphStats, Q36Config}; 59 use std::ffi::c_void; 60 #[repr(C)] 61 pub struct OmegaGpuQ36Graph { 62 _private: [u8; 0], 63 } 64 extern "C" { 65 pub fn omega_gpu_q36_graph_free(g: *mut OmegaGpuQ36Graph); 66 pub fn omega_gpu_q36_graph_set_layer( 67 g: *mut OmegaGpuQ36Graph, 68 layer: u32, 69 mix: *const c_void, 70 ab: *const c_void, 71 o: *const c_void, 72 gate_up: *const c_void, 73 down: *const c_void, 74 in_norm: *const f32, 75 ) -> i32; 76 pub fn omega_gpu_q36_graph_set_final_norm( 77 g: *mut OmegaGpuQ36Graph, 78 final_norm: *const f32, 79 ) -> i32; 80 pub fn omega_gpu_q36_graph_create_heads( 81 cfg: *const Q36Config, 82 heads: u32, 83 out: *mut *mut OmegaGpuQ36Graph, 84 ) -> i32; 85 pub fn omega_gpu_q36_graph_set_head_state( 86 g: *mut OmegaGpuQ36Graph, 87 head: u32, 88 gdn: *mut c_void, 89 attn: *mut c_void, 90 ) -> i32; 91 pub fn omega_gpu_q36_graph_stroke( 92 g: *mut OmegaGpuQ36Graph, 93 x_embed: *const f32, 94 pos: *const u32, 95 heads: u32, 96 tokens: *mut u32, 97 st: *mut GraphStats, 98 ) -> i32; 99 pub fn omega_gpu_q36_graph_prefill_alloc(g: *mut OmegaGpuQ36Graph, cap: u32) -> i32; 100 pub fn omega_gpu_q36_graph_prefill_cap(g: *const OmegaGpuQ36Graph) -> u32; 101 pub fn omega_gpu_q36_graph_prefill_streamed(g: *const OmegaGpuQ36Graph) -> u64; 102 pub fn omega_gpu_q36_graph_prefill( 103 g: *mut OmegaGpuQ36Graph, 104 head: u32, 105 x_embed: *const f32, 106 n: u32, 107 pos0: u32, 108 want_token: i32, 109 token: *mut u32, 110 st: *mut GraphStats, 111 ) -> i32; 112 pub fn omega_gpu_q36_graph_read_head( 113 g: *mut OmegaGpuQ36Graph, 114 head: u32, 115 x: *mut f32, 116 hidden: *mut f32, 117 logits: *mut f32, 118 ) -> i32; 119 pub fn omega_gpu_q36_graph_token( 120 g: *mut OmegaGpuQ36Graph, 121 x_embed: *const f32, 122 pos: u32, 123 token: *mut u32, 124 st: *mut GraphStats, 125 ) -> i32; 126 pub fn omega_gpu_q36_graph_read( 127 g: *mut OmegaGpuQ36Graph, 128 x: *mut f32, 129 hidden: *mut f32, 130 logits: *mut f32, 131 ) -> i32; 132 pub fn omega_gpu_q36_graph_read_buf( 133 g: *mut OmegaGpuQ36Graph, 134 which: i32, 135 out: *mut f32, 136 n: u32, 137 ) -> i32; 138 pub fn omega_gpu_q36_graph_set_flush_each(g: *mut OmegaGpuQ36Graph, on: i32); 139 pub fn omega_gpu_q36_graph_set_batch(g: *mut OmegaGpuQ36Graph, on: i32) -> i32; 140 pub fn omega_gpu_q36_graph_batch(g: *const OmegaGpuQ36Graph) -> i32; 141 pub fn omega_gpu_q36_graph_set_stamps(g: *mut OmegaGpuQ36Graph, on: i32); 142 pub fn omega_gpu_q36_graph_stamps( 143 g: *const OmegaGpuQ36Graph, 144 stamps: *mut u64, 145 kinds: *mut u8, 146 cap: u32, 147 ) -> i32; 148 pub fn omega_gpu_q36_graph_kind_name(kind: u8) -> *const std::ffi::c_char; 149 pub fn omega_gpu_q36_graph_test_set_mutant(g: *mut OmegaGpuQ36Graph, mutant: i32); 150 pub fn omega_gpu_q36_graph_set_exact_head( 151 g: *mut OmegaGpuQ36Graph, 152 screen: *const c_void, 153 coef: *const f32, 154 ) -> i32; 155 pub fn omega_gpu_q36_graph_set_exact_head_on(g: *mut OmegaGpuQ36Graph, on: i32); 156 pub fn omega_gpu_q36_graph_exact_head_active(g: *const OmegaGpuQ36Graph) -> i32; 157 pub fn omega_gpu_q36_graph_set_head_exact_head_on( 158 g: *mut OmegaGpuQ36Graph, 159 head: u32, 160 on: i32, 161 ); 162 pub fn omega_gpu_q36_graph_exact_head_active_head( 163 g: *const OmegaGpuQ36Graph, 164 head: u32, 165 ) -> i32; 166 } 167 } 168 169 /// True when the 35B graph is linked (not the stub). 170 pub const fn is_native() -> bool { 171 cfg!(has_omega_q36) 172 } 173 174 /// Intermediates [`Q36Graph::read_buf`] can copy (`OMEGA_GPU_Q36_BUF_*`). 175 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 176 pub enum Q36Buf { 177 X = 0, 178 Xq, 179 Mix, 180 Ab, 181 Agg, 182 Att, 183 O, 184 Gu, 185 Act, 186 Hidden, 187 Dn, 188 } 189 190 /// Heads per stroke the chip library lays out at most (one 4096-launch command list holds eight 40-layer tokens of 444 launches). 191 pub const MAX_HEADS: usize = 8; 192 /// Most tokens one prefill chunk carries (`OMEGA_GPU_Q36_PREFILL_MAX_ROWS`). 193 pub const PREFILL_MAX_ROWS: usize = 128; 194 195 pub struct Q36Graph { 196 #[cfg(has_omega_q36)] 197 ptr: *mut ffi::OmegaGpuQ36Graph, 198 layers: usize, 199 attn_mask: u64, 200 vocab: usize, 201 heads: usize, 202 } 203 204 // SAFETY: an owning handle to device buffers; moved between threads, never shared unlocked. 205 unsafe impl Send for Q36Graph {} 206 207 impl fmt::Debug for Q36Graph { 208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 209 write!( 210 f, 211 "Q36Graph {{ layers: {}, attn_mask: {:#x}, vocab: {} }}", 212 self.layers, self.attn_mask, self.vocab 213 ) 214 } 215 } 216 217 impl Q36Graph { 218 /// # Safety 219 /// Every handle in `cfg` must be live, of the shape the header names, and outlive the graph. 220 pub unsafe fn create(cfg: &Q36Config) -> Result { 221 // SAFETY: the caller's contract, passed through. 222 unsafe { Self::create_heads(cfg, 1) } 223 } 224 225 /// A graph with `heads` slots (1..=MAX_HEADS): head 0 uses `cfg.gdn` / `cfg.attn`, the others take 226 /// their state objects from [`Self::set_head_state`] before a stroke. 227 /// 228 /// # Safety 229 /// As [`Self::create`]. 230 pub unsafe fn create_heads(cfg: &Q36Config, heads: usize) -> Result { 231 if heads == 0 || heads > MAX_HEADS { 232 return Err(bad(format!("q36 graph: heads {heads} (1..={MAX_HEADS})"))); 233 } 234 if cfg.layers == 0 || cfg.layers > 64 || cfg.vocab == 0 { 235 return Err(bad(format!( 236 "q36 graph: layers {} vocab {}", 237 cfg.layers, cfg.vocab 238 ))); 239 } 240 if cfg.gdn.is_null() || cfg.attn.is_null() || cfg.router.is_null() || cfg.lm_head.is_null() 241 { 242 return Err(bad("q36 graph: a state or weight handle is null".into())); 243 } 244 #[cfg(has_omega_q36)] 245 { 246 let mut ptr = std::ptr::null_mut(); 247 let rc = ffi::omega_gpu_q36_graph_create_heads(cfg, heads as u32, &mut ptr); 248 if rc != 0 || ptr.is_null() { 249 return Err(session_err("q36 graph create", rc)); 250 } 251 Ok(Self { 252 ptr, 253 layers: cfg.layers as usize, 254 attn_mask: cfg.attn_mask, 255 vocab: cfg.vocab as usize, 256 heads, 257 }) 258 } 259 #[cfg(not(has_omega_q36))] 260 Err(OmegaGpuError::Unavailable) 261 } 262 263 pub fn heads(&self) -> usize { 264 self.heads 265 } 266 267 /// Point head `head` at a DeltaNet state and an attention cache of the configured shapes (head swap). 268 /// 269 /// # Safety 270 /// Both handles must be live and outlive every stroke that uses the head. 271 pub unsafe fn set_head_state( 272 &mut self, 273 head: usize, 274 gdn: *mut c_void, 275 attn: *mut c_void, 276 ) -> Result<(), OmegaGpuError> { 277 if head >= self.heads || gdn.is_null() || attn.is_null() { 278 return Err(bad(format!( 279 "q36 graph: head {head} of {} or a null state handle", 280 self.heads 281 ))); 282 } 283 #[cfg(has_omega_q36)] 284 { 285 // SAFETY: ptr is live; the handles are the caller's contract. 286 let rc = unsafe { 287 ffi::omega_gpu_q36_graph_set_head_state(self.ptr, head as u32, gdn, attn) 288 }; 289 if rc != 0 { 290 return Err(session_err("q36 graph set_head_state", rc)); 291 } 292 Ok(()) 293 } 294 #[cfg(not(has_omega_q36))] 295 Err(OmegaGpuError::Unavailable) 296 } 297 298 /// One stroke: `pos.len()` heads through one command list (`x_embed` holds HIDDEN values per head, 299 /// head h at position `pos[h]`), one submit; the greedy token of every head. 300 pub fn stroke( 301 &mut self, 302 x_embed: &[f32], 303 pos: &[usize], 304 ) -> Result<(Vec, GraphStats), OmegaGpuError> { 305 let heads = pos.len(); 306 if heads == 0 || heads > self.heads { 307 return Err(bad(format!( 308 "q36 graph: stroke of {heads} heads on a graph of {}", 309 self.heads 310 ))); 311 } 312 check_len("q36 graph stroke x_embed", HIDDEN * heads, x_embed.len())?; 313 let pos: Vec = pos 314 .iter() 315 .map(|&p| u32::try_from(p).map_err(|_| bad(format!("q36 graph: pos {p} too large")))) 316 .collect::>()?; 317 #[cfg(has_omega_q36)] 318 { 319 let mut tokens = vec![0u32; heads]; 320 let mut st = GraphStats::default(); 321 // SAFETY: ptr is live; x_embed holds HIDDEN * heads f32 and pos/tokens heads u32 (checked). 322 let rc = unsafe { 323 ffi::omega_gpu_q36_graph_stroke( 324 self.ptr, 325 x_embed.as_ptr(), 326 pos.as_ptr(), 327 heads as u32, 328 tokens.as_mut_ptr(), 329 &mut st, 330 ) 331 }; 332 if rc != 0 { 333 return Err(session_err("q36 graph stroke", rc)); 334 } 335 Ok((tokens, st)) 336 } 337 #[cfg(not(has_omega_q36))] 338 { 339 let _ = pos; 340 Err(OmegaGpuError::Unavailable) 341 } 342 } 343 344 /// L369 prefill: the chunk size the buffers hold (0 before [`Self::prefill_alloc`]). 345 pub fn prefill_cap(&self) -> usize { 346 #[cfg(has_omega_q36)] 347 { 348 // SAFETY: ptr is live. 349 unsafe { ffi::omega_gpu_q36_graph_prefill_cap(self.ptr) as usize } 350 } 351 #[cfg(not(has_omega_q36))] 352 0 353 } 354 355 /// L369 prefill: fp8 GEMM weight bytes every prefill call so far streamed (a running count; the 356 /// difference around a call over its time against the memory bandwidth is the ceiling receipt). 357 pub fn prefill_streamed(&self) -> u64 { 358 #[cfg(has_omega_q36)] 359 { 360 // SAFETY: ptr is live. 361 unsafe { ffi::omega_gpu_q36_graph_prefill_streamed(self.ptr) } 362 } 363 #[cfg(not(has_omega_q36))] 364 0 365 } 366 367 /// L369 prefill: sizes the chunk buffers for up to `cap` tokens (1..=[`PREFILL_MAX_ROWS`]). 368 pub fn prefill_alloc(&mut self, cap: usize) -> Result<(), OmegaGpuError> { 369 if cap == 0 || cap > PREFILL_MAX_ROWS { 370 return Err(bad(format!( 371 "q36 graph: prefill cap {cap} (1..={PREFILL_MAX_ROWS})" 372 ))); 373 } 374 #[cfg(has_omega_q36)] 375 { 376 // SAFETY: ptr is live. 377 let rc = unsafe { ffi::omega_gpu_q36_graph_prefill_alloc(self.ptr, cap as u32) }; 378 if rc != 0 { 379 return Err(session_err("q36 graph prefill_alloc", rc)); 380 } 381 Ok(()) 382 } 383 #[cfg(not(has_omega_q36))] 384 Err(OmegaGpuError::Unavailable) 385 } 386 387 /// L369 prefill: `n` prompt tokens (embeddings `x_embed`, `[n][HIDDEN]`) of the conversation in 388 /// head slot `head` at positions `pos0..pos0 + n`, each as if it went through a token step in 389 /// turn (the decode step's kernels, so the state matches token by token bit for bit). With 390 /// `want_token` the last token's greedy token (and [`Self::read_head`] for its logits). 391 pub fn prefill( 392 &mut self, 393 head: usize, 394 x_embed: &[f32], 395 pos0: usize, 396 want_token: bool, 397 ) -> Result<(Option, GraphStats), OmegaGpuError> { 398 let n = x_embed.len() / HIDDEN; 399 if head >= self.heads || n == 0 { 400 return Err(bad(format!( 401 "q36 graph: prefill head {head} of {}, {n} tokens", 402 self.heads 403 ))); 404 } 405 check_len("q36 graph prefill x_embed", HIDDEN * n, x_embed.len())?; 406 let pos0 = 407 u32::try_from(pos0).map_err(|_| bad(format!("q36 graph: pos {pos0} too large")))?; 408 #[cfg(has_omega_q36)] 409 { 410 let mut token = 0u32; 411 let mut st = GraphStats::default(); 412 // SAFETY: ptr is live; x_embed holds HIDDEN * n f32 (checked). 413 let rc = unsafe { 414 ffi::omega_gpu_q36_graph_prefill( 415 self.ptr, 416 head as u32, 417 x_embed.as_ptr(), 418 n as u32, 419 pos0, 420 want_token as i32, 421 &mut token, 422 &mut st, 423 ) 424 }; 425 if rc != 0 { 426 return Err(session_err("q36 graph prefill", rc)); 427 } 428 Ok((want_token.then_some(token), st)) 429 } 430 #[cfg(not(has_omega_q36))] 431 { 432 let _ = (pos0, want_token); 433 Err(OmegaGpuError::Unavailable) 434 } 435 } 436 437 /// As [`Self::read`], for head `head` of the last stroke. 438 pub fn read_head( 439 &mut self, 440 head: usize, 441 x: Option<&mut [f32]>, 442 hidden: Option<&mut [f32]>, 443 logits: Option<&mut [f32]>, 444 ) -> Result<(), OmegaGpuError> { 445 if head >= self.heads { 446 return Err(bad(format!("q36 graph: head {head} of {}", self.heads))); 447 } 448 if let Some(x) = &x { 449 check_len("q36 graph read x", HIDDEN, x.len())?; 450 } 451 if let Some(h) = &hidden { 452 check_len("q36 graph read hidden", HIDDEN, h.len())?; 453 } 454 if let Some(l) = &logits { 455 check_len("q36 graph read logits", self.vocab, l.len())?; 456 } 457 #[cfg(has_omega_q36)] 458 { 459 let p = |s: Option<&mut [f32]>| s.map_or(std::ptr::null_mut(), |s| s.as_mut_ptr()); 460 // SAFETY: ptr is live; every non-null pointer holds the length checked above. 461 let rc = unsafe { 462 ffi::omega_gpu_q36_graph_read_head( 463 self.ptr, 464 head as u32, 465 p(x), 466 p(hidden), 467 p(logits), 468 ) 469 }; 470 if rc != 0 { 471 return Err(session_err("q36 graph read_head", rc)); 472 } 473 Ok(()) 474 } 475 #[cfg(not(has_omega_q36))] 476 Err(OmegaGpuError::Unavailable) 477 } 478 479 pub fn layers(&self) -> usize { 480 self.layers 481 } 482 483 pub fn vocab(&self) -> usize { 484 self.vocab 485 } 486 487 pub fn is_attention(&self, l: usize) -> bool { 488 l < 64 && self.attn_mask >> l & 1 == 1 489 } 490 491 /// # Safety 492 /// The handles must be live FP8 / bf16 tensors of the header's shapes and outlive the graph. 493 #[allow(clippy::too_many_arguments)] 494 pub unsafe fn set_layer( 495 &mut self, 496 layer: usize, 497 mix: *const c_void, 498 ab: *const c_void, 499 o: *const c_void, 500 gate_up: *const c_void, 501 down: *const c_void, 502 in_norm: &[f32], 503 ) -> Result<(), OmegaGpuError> { 504 check_len("q36 graph in_norm", HIDDEN, in_norm.len())?; 505 if layer >= self.layers { 506 return Err(bad(format!("q36 graph: layer {layer} of {}", self.layers))); 507 } 508 if mix.is_null() || o.is_null() || gate_up.is_null() || down.is_null() { 509 return Err(bad(format!( 510 "q36 graph layer {layer}: a projection has no device handle" 511 ))); 512 } 513 if ab.is_null() != self.is_attention(layer) { 514 return Err(bad(format!( 515 "q36 graph layer {layer}: the a|b tensor is for DeltaNet layers only" 516 ))); 517 } 518 #[cfg(has_omega_q36)] 519 { 520 let rc = ffi::omega_gpu_q36_graph_set_layer( 521 self.ptr, 522 layer as u32, 523 mix, 524 ab, 525 o, 526 gate_up, 527 down, 528 in_norm.as_ptr(), 529 ); 530 if rc != 0 { 531 return Err(session_err("q36 graph set_layer", rc)); 532 } 533 Ok(()) 534 } 535 #[cfg(not(has_omega_q36))] 536 Err(OmegaGpuError::Unavailable) 537 } 538 539 pub fn set_final_norm(&mut self, final_norm: &[f32]) -> Result<(), OmegaGpuError> { 540 check_len("q36 graph final_norm", HIDDEN, final_norm.len())?; 541 #[cfg(has_omega_q36)] 542 { 543 // SAFETY: ptr is live; the slice holds HIDDEN f32 (checked). 544 let rc = 545 unsafe { ffi::omega_gpu_q36_graph_set_final_norm(self.ptr, final_norm.as_ptr()) }; 546 if rc != 0 { 547 return Err(session_err("q36 graph set_final_norm", rc)); 548 } 549 Ok(()) 550 } 551 #[cfg(not(has_omega_q36))] 552 Err(OmegaGpuError::Unavailable) 553 } 554 555 /// One whole token: the embedding row in, the greedy token out (position `pos`). 556 pub fn token( 557 &mut self, 558 x_embed: &[f32], 559 pos: usize, 560 ) -> Result<(u32, GraphStats), OmegaGpuError> { 561 check_len("q36 graph x_embed", HIDDEN, x_embed.len())?; 562 let pos = u32::try_from(pos).map_err(|_| bad(format!("q36 graph: pos {pos} too large")))?; 563 #[cfg(has_omega_q36)] 564 { 565 let mut token = 0u32; 566 let mut st = GraphStats::default(); 567 // SAFETY: ptr is live; x_embed holds HIDDEN f32 (checked); token and st are local. 568 let rc = unsafe { 569 ffi::omega_gpu_q36_graph_token(self.ptr, x_embed.as_ptr(), pos, &mut token, &mut st) 570 }; 571 if rc != 0 { 572 return Err(session_err("q36 graph token", rc)); 573 } 574 Ok((token, st)) 575 } 576 #[cfg(not(has_omega_q36))] 577 { 578 let _ = pos; 579 Err(OmegaGpuError::Unavailable) 580 } 581 } 582 583 /// The last token's residual, final hidden and logits (any may be `None`). 584 pub fn read( 585 &mut self, 586 x: Option<&mut [f32]>, 587 hidden: Option<&mut [f32]>, 588 logits: Option<&mut [f32]>, 589 ) -> Result<(), OmegaGpuError> { 590 if let Some(x) = &x { 591 check_len("q36 graph read x", HIDDEN, x.len())?; 592 } 593 if let Some(h) = &hidden { 594 check_len("q36 graph read hidden", HIDDEN, h.len())?; 595 } 596 if let Some(l) = &logits { 597 check_len("q36 graph read logits", self.vocab, l.len())?; 598 } 599 #[cfg(has_omega_q36)] 600 { 601 let p = |s: Option<&mut [f32]>| s.map_or(std::ptr::null_mut(), |s| s.as_mut_ptr()); 602 // SAFETY: ptr is live; every non-null pointer holds the length checked above. 603 let rc = unsafe { ffi::omega_gpu_q36_graph_read(self.ptr, p(x), p(hidden), p(logits)) }; 604 if rc != 0 { 605 return Err(session_err("q36 graph read", rc)); 606 } 607 Ok(()) 608 } 609 #[cfg(not(has_omega_q36))] 610 Err(OmegaGpuError::Unavailable) 611 } 612 613 /// One intermediate of the last token (the first `out.len()` values). 614 pub fn read_buf(&mut self, which: Q36Buf, out: &mut [f32]) -> Result<(), OmegaGpuError> { 615 #[cfg(has_omega_q36)] 616 { 617 // SAFETY: ptr is live; omega refuses n above the buffer's capacity. 618 let rc = unsafe { 619 ffi::omega_gpu_q36_graph_read_buf( 620 self.ptr, 621 which as i32, 622 out.as_mut_ptr(), 623 out.len() as u32, 624 ) 625 }; 626 if rc != 0 { 627 return Err(session_err("q36 graph read_buf", rc)); 628 } 629 Ok(()) 630 } 631 #[cfg(not(has_omega_q36))] 632 { 633 let _ = (which, out); 634 Err(OmegaGpuError::Unavailable) 635 } 636 } 637 638 /// HUM L314 exact two-pass head (omega `omega_gpu_q36_graph_set_exact_head`): `screen` is the 639 /// fp8b copy of the bf16 lm_head (`[vocab][2048]`, one bf16 scale per 128 x 128 block), 640 /// `coef` the Row bound per row (`exact_head::Screen::row_coef`). The greedy token stays the 641 /// plain head's by construction; the logits read back are -inf off the candidates, so turn it 642 /// off ([`Self::set_exact_head_on`]) for any token that is sampled. Null `screen` removes it. 643 /// 644 /// # Safety 645 /// `screen` is null or a live `OmegaGpuFp8Tensor` that outlives every later token of this graph. 646 pub unsafe fn set_exact_head( 647 &mut self, 648 screen: *mut c_void, 649 coef: &[f32], 650 ) -> Result<(), OmegaGpuError> { 651 if !screen.is_null() { 652 check_len("q36 graph exact head coef", self.vocab, coef.len())?; 653 } 654 #[cfg(has_omega_q36)] 655 { 656 // SAFETY: ptr is live; screen per the caller's contract; coef holds vocab f32 (checked). 657 let rc = 658 unsafe { ffi::omega_gpu_q36_graph_set_exact_head(self.ptr, screen, coef.as_ptr()) }; 659 if rc != 0 { 660 return Err(session_err("q36 graph set_exact_head", rc)); 661 } 662 Ok(()) 663 } 664 #[cfg(not(has_omega_q36))] 665 { 666 let _ = (screen, coef); 667 Err(OmegaGpuError::Unavailable) 668 } 669 } 670 671 /// Use the exact two-pass head for the next tokens (greedy) or the plain head (sampled). 672 pub fn set_exact_head_on(&mut self, on: bool) { 673 #[cfg(has_omega_q36)] 674 // SAFETY: ptr is live. 675 unsafe { 676 ffi::omega_gpu_q36_graph_set_exact_head_on(self.ptr, on as i32) 677 } 678 #[cfg(not(has_omega_q36))] 679 let _ = on; 680 } 681 682 /// The next token runs the exact two-pass head (set, on, no FP8 lm_head). 683 pub fn exact_head_active(&self) -> bool { 684 #[cfg(has_omega_q36)] 685 // SAFETY: ptr is live. 686 unsafe { 687 ffi::omega_gpu_q36_graph_exact_head_active(self.ptr) != 0 688 } 689 #[cfg(not(has_omega_q36))] 690 false 691 } 692 693 /// The batch (v2, L312): each layer recorded for every conversation at once, one weight read per layer. 694 /// Pins the GEMM kernels on the session; `Err` carries the chip rc. 695 pub fn set_batch(&mut self, on: bool) -> Result<(), i32> { 696 #[cfg(has_omega_q36)] 697 // SAFETY: ptr is live. 698 unsafe { 699 let rc = ffi::omega_gpu_q36_graph_set_batch(self.ptr, on as i32); 700 if rc == 0 { 701 Ok(()) 702 } else { 703 Err(rc) 704 } 705 } 706 #[cfg(not(has_omega_q36))] 707 { 708 let _ = on; 709 Err(-1) 710 } 711 } 712 /// Whether the batch is on (also set by `AIEN_OMEGA_Q36_BATCH=1` at create). 713 pub fn batch(&self) -> bool { 714 #[cfg(has_omega_q36)] 715 // SAFETY: ptr is live. 716 unsafe { 717 ffi::omega_gpu_q36_graph_batch(self.ptr) != 0 718 } 719 #[cfg(not(has_omega_q36))] 720 false 721 } 722 /// Strokes: the exact head on / off for one head slot (a stroke may mix greedy and sampled 723 /// rows). Call between tokens; out-of-range heads are ignored. 724 pub fn set_head_exact_head_on(&mut self, head: usize, on: bool) { 725 #[cfg(has_omega_q36)] 726 // SAFETY: ptr is live; plain integer arguments. 727 unsafe { 728 ffi::omega_gpu_q36_graph_set_head_exact_head_on(self.ptr, head as u32, on as i32) 729 } 730 #[cfg(not(has_omega_q36))] 731 let _ = (head, on); 732 } 733 734 /// The next stroke runs the exact two-pass head on this head slot. 735 pub fn exact_head_active_head(&self, head: usize) -> bool { 736 #[cfg(has_omega_q36)] 737 // SAFETY: ptr is live. 738 unsafe { 739 ffi::omega_gpu_q36_graph_exact_head_active_head(self.ptr, head as u32) != 0 740 } 741 #[cfg(not(has_omega_q36))] 742 { 743 let _ = head; 744 false 745 } 746 } 747 748 /// Chip timestamps around every launch of the next tokens (a timeline; off by default). 749 pub fn set_stamps(&mut self, on: bool) { 750 #[cfg(has_omega_q36)] 751 // SAFETY: ptr is live. 752 unsafe { 753 ffi::omega_gpu_q36_graph_set_stamps(self.ptr, on as i32); 754 } 755 #[cfg(not(has_omega_q36))] 756 let _ = on; 757 } 758 /// The last token's timeline: (kind, chip ns) per launch, in launch order. Needs `set_stamps(true)` 759 /// before that token; Err(rc) when there is none. 760 pub fn timeline(&self) -> Result, i32> { 761 #[cfg(has_omega_q36)] 762 // SAFETY: ptr is live; the buffers hold the most launches one command list carries, plus one. 763 unsafe { 764 const CAP: usize = 4097; 765 let mut stamps = vec![0u64; CAP]; 766 let mut kinds = vec![0u8; CAP]; 767 let n = ffi::omega_gpu_q36_graph_stamps( 768 self.ptr, 769 stamps.as_mut_ptr(), 770 kinds.as_mut_ptr(), 771 CAP as u32, 772 ); 773 if n < 0 { 774 return Err(n); 775 } 776 let n = n as usize; 777 Ok((0..n) 778 .map(|i| (kinds[i], stamps[i + 1].wrapping_sub(stamps[i]))) 779 .collect()) 780 } 781 #[cfg(not(has_omega_q36))] 782 Err(-1) 783 } 784 /// omega's own name for a launch kind of the 35B graph. 785 pub fn kind_name(kind: u8) -> String { 786 #[cfg(has_omega_q36)] 787 // SAFETY: the library returns a static NUL-terminated string for every kind value. 788 unsafe { 789 let p = ffi::omega_gpu_q36_graph_kind_name(kind); 790 if p.is_null() { 791 return "?".into(); 792 } 793 std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned() 794 } 795 #[cfg(not(has_omega_q36))] 796 { 797 let _ = kind; 798 "?".into() 799 } 800 } 801 802 /// The last token's timeline: `launches + 1` GPU timestamps (ns) and one kind per launch 803 /// (launch `i` took `stamps[i + 1] - stamps[i]`). Refused when stamps are off or the token 804 /// failed. 805 pub fn stamps(&self) -> Result<(Vec, Vec), OmegaGpuError> { 806 #[cfg(has_omega_q36)] 807 { 808 // 11 per layer + 4, with room to spare. 809 let cap = (self.layers * 16 + 16) as u32; 810 let mut stamps = vec![0u64; cap as usize + 1]; 811 let mut kinds = vec![0u8; cap as usize + 1]; 812 // SAFETY: ptr is live; both buffers hold cap + 1 entries. 813 let n = unsafe { 814 ffi::omega_gpu_q36_graph_stamps( 815 self.ptr, 816 stamps.as_mut_ptr(), 817 kinds.as_mut_ptr(), 818 cap + 1, 819 ) 820 }; 821 if n < 0 { 822 return Err(session_err("q36 graph stamps", n)); 823 } 824 let n = n as usize; 825 stamps.truncate(n + 1); 826 kinds.truncate(n); 827 Ok((stamps, kinds)) 828 } 829 #[cfg(not(has_omega_q36))] 830 Err(OmegaGpuError::Unavailable) 831 } 832 833 /// 1: submit after every launch (the comparison path). 834 pub fn set_flush_each(&mut self, on: bool) { 835 #[cfg(has_omega_q36)] 836 // SAFETY: ptr is live. 837 unsafe { 838 ffi::omega_gpu_q36_graph_set_flush_each(self.ptr, on as i32) 839 } 840 #[cfg(not(has_omega_q36))] 841 let _ = on; 842 } 843 844 /// TEST ONLY (negative controls): 1 SWIGLU up half off by one, 2 GATHER index + 1, 3 GATE 845 /// dropped, 4 COMBINE skips the shared expert, 5 the exact head's MASK inverted, 6 its bound 846 /// dropped. 0 none. 847 pub fn test_set_mutant(&mut self, mutant: i32) { 848 #[cfg(has_omega_q36)] 849 // SAFETY: ptr is live. 850 unsafe { 851 ffi::omega_gpu_q36_graph_test_set_mutant(self.ptr, mutant) 852 } 853 #[cfg(not(has_omega_q36))] 854 let _ = mutant; 855 } 856 } 857 858 impl Drop for Q36Graph { 859 fn drop(&mut self) { 860 #[cfg(has_omega_q36)] 861 // SAFETY: ptr came from create and is freed once. 862 unsafe { 863 ffi::omega_gpu_q36_graph_free(self.ptr) 864 } 865 } 866 } 867 868 /// omega's own name for a 35B launch kind (`omega_gpu_q36_graph_kind_name`). 869 pub fn kind_name(kind: u8) -> String { 870 #[cfg(has_omega_q36)] 871 { 872 // SAFETY: returns a static NUL-terminated string or NULL. 873 let p = unsafe { ffi::omega_gpu_q36_graph_kind_name(kind) }; 874 if !p.is_null() { 875 // SAFETY: non-null static string. 876 return unsafe { std::ffi::CStr::from_ptr(p) } 877 .to_string_lossy() 878 .into_owned(); 879 } 880 } 881 format!("kind{kind}") 882 }