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 / qwen38_omega / moe.rs
| 1 | //! Qwen3.6-35B-A3B (`qwen3_5_moe`) onto the Omega decode graph `aien_omega_q38::q36::Q36Graph` |
| 2 | //! (sc L306). The mixers upload as for the 27B (see the parent module) at the 35B's shapes; the |
| 3 | //! MLP of every layer is the sparse block: |
| 4 | //! |
| 5 | //! - `mlp.experts.{e}.gate_proj | up_proj` for e in 0..256, then `mlp.shared_expert.gate_proj | |
| 6 | //! up_proj` -> one FP8 tensor of 257 experts `[1024][2048]` (each expert's gate rows, then its up |
| 7 | //! rows; the 128-blocks concatenate with them). `down_proj` likewise -> 257 x `[2048][512]`. |
| 8 | //! - `mlp.gate.weight` (bf16 `[256][2048]`) with `mlp.shared_expert_gate.weight` (`[1][2048]`) as |
| 9 | //! row 256 -> the router (`Router::alloc_shape(layers, 256, 1)`), with the post-attention norm |
| 10 | //! folded to `1 + w`; its directories point at the two expert tensors (entry 256 = the shared |
| 11 | //! expert, the graph's ninth group, weight sigmoid(shared gate . xn)). |
| 12 | //! |
| 13 | //! The host reference this must match is [`crate::qwen38`] (the `moe` branch). |
| 14 | use std::path::Path; |
| 15 | |
| 16 | use aien_omega_bf16::Bf16Tensor; |
| 17 | use aien_omega_fp8::Fp8Tensor; |
| 18 | use aien_omega_q38::q36::{self as q, Q36Config, Q36Graph}; |
| 19 | use aien_omega_q38::{Attn256Cache, Gdn}; |
| 20 | use aien_omega_router::Router; |
| 21 | |
| 22 | use super::rows::{GdnParams, RowSource}; |
| 23 | use super::{ |
| 24 | ab_rows, fold, fuse_fp8, gpu, upload_fp8, Graph, HeadState, LayerTensors, Qwen38Omega, EPS_L2, |
| 25 | }; |
| 26 | use crate::qwen38::{read_bf16_words, read_matrix, read_vec, text_prefix, Matrix, Qwen38Config}; |
| 27 | use crate::qwen3_moe::bf16_to_f32; |
| 28 | use crate::qwen3_moe_omega::TensorSource; |
| 29 | |
| 30 | /// The checkpoint shape the 35B graph is built for (config.json, checked before any upload). |
| 31 | fn check_shape(c: &Qwen38Config) -> Result<(), String> { |
| 32 | let m = c |
| 33 | .moe |
| 34 | .as_ref() |
| 35 | .ok_or("qwen36: not a qwen3_5_moe checkpoint")?; |
| 36 | let ok = c.hidden == q::HIDDEN |
| 37 | && m.experts == 256 |
| 38 | && m.top_k == 8 |
| 39 | && m.expert_inter == q::EXPERT_INTER |
| 40 | && m.shared_inter == q::EXPERT_INTER |
| 41 | && c.heads == q::Q_HEADS |
| 42 | && c.kv_heads == q::KV_HEADS |
| 43 | && c.head_dim == aien_omega_q38::HEAD_DIM |
| 44 | && c.heads * c.head_dim == q::MIXER_OUT |
| 45 | && 2 * c.heads * c.head_dim + 2 * c.kv_dim() == q::ATT_MIX |
| 46 | && c.conv_dim() == q::GDN_QKV |
| 47 | && c.conv_dim() + c.lin_value_dim() == q::GDN_MIX |
| 48 | && c.lin_v_heads == 16 * q::GDN_RATIO |
| 49 | && c.lin_k_heads == 16 |
| 50 | && c.lin_v_dim == aien_omega_q38::GDN_HEAD_DIM |
| 51 | && c.conv_kernel == aien_omega_q38::GDN_CONV_KERNEL |
| 52 | && c.rotary_dim == 64; |
| 53 | if !ok { |
| 54 | return Err( |
| 55 | "qwen36 omega: the checkpoint is not the Qwen3.6-35B-A3B shape the graph is built for" |
| 56 | .into(), |
| 57 | ); |
| 58 | } |
| 59 | if c.layers > aien_omega_q38::MAX_LAYERS { |
| 60 | return Err(format!( |
| 61 | "qwen36 omega: {} layers (at most {})", |
| 62 | c.layers, |
| 63 | aien_omega_q38::MAX_LAYERS |
| 64 | )); |
| 65 | } |
| 66 | Ok(()) |
| 67 | } |
| 68 | |
| 69 | /// Appends one FP8 matrix (whole 128-blocks, `[n][k]`) to an expert tensor's bytes and scales. |
| 70 | fn push_fp8( |
| 71 | name: &str, |
| 72 | m: Matrix, |
| 73 | n: usize, |
| 74 | k: usize, |
| 75 | w: &mut Vec<u8>, |
| 76 | s: &mut Vec<u16>, |
| 77 | ) -> Result<(), String> { |
| 78 | match m { |
| 79 | Matrix::Fp8 { |
| 80 | n: mn, |
| 81 | k: mk, |
| 82 | w: mw, |
| 83 | scales, |
| 84 | } if (mn, mk) == (n, k) => { |
| 85 | w.extend_from_slice(&mw); |
| 86 | s.extend_from_slice(&scales); |
| 87 | Ok(()) |
| 88 | } |
| 89 | Matrix::Fp8 { n: mn, k: mk, .. } => { |
| 90 | Err(format!("{name}: [{mn}][{mk}], expected [{n}][{k}]")) |
| 91 | } |
| 92 | Matrix::Bf16 { .. } => Err(format!("{name}: bf16 (the expert tensors take FP8)")), |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// The layer's 257-expert gate|up and down tensors (routed 0..256, then the shared expert). |
| 97 | fn upload_experts( |
| 98 | source: &mut dyn TensorSource, |
| 99 | m: &str, |
| 100 | h: usize, |
| 101 | ) -> Result<(Fp8Tensor, Fp8Tensor), String> { |
| 102 | let i = q::EXPERT_INTER; |
| 103 | let rows = q::EXPERT_ROWS; |
| 104 | let (mut gw, mut gs) = (Vec::with_capacity(rows * 2 * i * h), Vec::new()); |
| 105 | let (mut dw, mut ds) = (Vec::with_capacity(rows * h * i), Vec::new()); |
| 106 | for e in 0..rows { |
| 107 | let p = if e + 1 == rows { |
| 108 | format!("{m}.shared_expert") |
| 109 | } else { |
| 110 | format!("{m}.experts.{e}") |
| 111 | }; |
| 112 | for part in ["gate_proj", "up_proj"] { |
| 113 | let name = format!("{p}.{part}.weight"); |
| 114 | push_fp8( |
| 115 | &name, |
| 116 | read_matrix(source, &name, i, h)?, |
| 117 | i, |
| 118 | h, |
| 119 | &mut gw, |
| 120 | &mut gs, |
| 121 | )?; |
| 122 | } |
| 123 | let name = format!("{p}.down_proj.weight"); |
| 124 | push_fp8( |
| 125 | &name, |
| 126 | read_matrix(source, &name, h, i)?, |
| 127 | h, |
| 128 | i, |
| 129 | &mut dw, |
| 130 | &mut ds, |
| 131 | )?; |
| 132 | } |
| 133 | let gu = Fp8Tensor::upload(rows, 2 * i, h, &gw, &gs).map_err(gpu("experts gate|up"))?; |
| 134 | let dn = Fp8Tensor::upload(rows, h, i, &dw, &ds).map_err(gpu("experts down"))?; |
| 135 | Ok((gu, dn)) |
| 136 | } |
| 137 | |
| 138 | /// Router gate rows as bf16 bits: `mlp.gate.weight` `[256][h]` then `shared_expert_gate` `[1][h]`. |
| 139 | fn router_rows(source: &mut dyn TensorSource, m: &str, h: usize) -> Result<Vec<u16>, String> { |
| 140 | let mut rows = match read_matrix(source, &format!("{m}.gate.weight"), 256, h)? { |
| 141 | Matrix::Bf16 { w, .. } => w, |
| 142 | Matrix::Fp8 { .. } => return Err(format!("{m}.gate.weight: FP8 (the router takes bf16)")), |
| 143 | }; |
| 144 | rows.extend(read_bf16_words( |
| 145 | source, |
| 146 | &format!("{m}.shared_expert_gate.weight"), |
| 147 | &[1, h], |
| 148 | )?); |
| 149 | Ok(rows) |
| 150 | } |
| 151 | |
| 152 | impl Qwen38Omega { |
| 153 | /// Opens a Qwen3.6-35B-A3B checkpoint and uploads it (the first `layers` layers when `Some`). |
| 154 | pub fn open_moe(dir: &Path, layers: Option<usize>, max_pos: usize) -> Result<Self, String> { |
| 155 | Self::open(dir, layers, max_pos) |
| 156 | } |
| 157 | |
| 158 | pub(super) fn load_moe( |
| 159 | config: Qwen38Config, |
| 160 | first: usize, |
| 161 | source: &mut dyn TensorSource, |
| 162 | max_pos: usize, |
| 163 | heads: usize, |
| 164 | ) -> Result<Self, String> { |
| 165 | let c = &config; |
| 166 | check_shape(c)?; |
| 167 | if heads == 0 || heads > q::MAX_HEADS { |
| 168 | return Err(format!( |
| 169 | "qwen36 omega: {heads} heads (the graph strokes 1..={})", |
| 170 | q::MAX_HEADS |
| 171 | )); |
| 172 | } |
| 173 | let prefix = text_prefix(source)?; |
| 174 | let (v, h) = (c.vocab, c.hidden); |
| 175 | let embed = read_bf16_words(source, &format!("{prefix}embed_tokens.weight"), &[v, h])?; |
| 176 | let final_norm = fold(read_vec(source, &format!("{prefix}norm.weight"), h)?); |
| 177 | let head = read_matrix(source, "lm_head.weight", v, h)?; |
| 178 | let lm_head = match &head { |
| 179 | Matrix::Bf16 { n, k, w } => Bf16Tensor::upload(*n, *k, w).map_err(gpu("lm_head"))?, |
| 180 | Matrix::Fp8 { .. } => return Err("lm_head: FP8 (the graph takes a bf16 head)".into()), |
| 181 | }; |
| 182 | let n_attn = c.full_attention.iter().filter(|&&a| a).count(); |
| 183 | let n_gdn = c.layers - n_attn; |
| 184 | // One DeltaNet state and one attention cache per head (every head carries the same |
| 185 | // per-layer parameters, so a head swap can point any slot at any conversation). |
| 186 | let mut gdns: Vec<Option<Gdn>> = (0..heads) |
| 187 | .map(|_| { |
| 188 | (n_gdn > 0) |
| 189 | .then(|| Gdn::alloc_ratio(n_gdn, q::GDN_RATIO).map_err(gpu("gdn alloc"))) |
| 190 | .transpose() |
| 191 | }) |
| 192 | .collect::<Result<_, _>>()?; |
| 193 | let mut attns: Vec<Option<Attn256Cache>> = (0..heads) |
| 194 | .map(|_| { |
| 195 | (n_attn > 0) |
| 196 | .then(|| { |
| 197 | Attn256Cache::alloc_shape( |
| 198 | n_attn, |
| 199 | max_pos, |
| 200 | c.rope_theta, |
| 201 | c.rotary_dim, |
| 202 | q::Q_HEADS, |
| 203 | q::KV_HEADS, |
| 204 | q::Q_PER_CTA, |
| 205 | ) |
| 206 | .map_err(gpu("attn256 alloc")) |
| 207 | }) |
| 208 | .transpose() |
| 209 | }) |
| 210 | .collect::<Result<_, _>>()?; |
| 211 | let mut router = Router::alloc_shape(c.layers, 256, 1).map_err(gpu("router alloc"))?; |
| 212 | let attn_mask = c |
| 213 | .full_attention |
| 214 | .iter() |
| 215 | .enumerate() |
| 216 | .fold(0u64, |m, (l, &a)| if a { m | 1 << l } else { m }); |
| 217 | |
| 218 | let (mut gdn_params, mut attn_norms) = (Vec::new(), Vec::new()); |
| 219 | let mut layers = Vec::with_capacity(c.layers); |
| 220 | let mut norms = Vec::with_capacity(c.layers); |
| 221 | let (mut gi, mut ai) = (0usize, 0usize); |
| 222 | for l in 0..c.layers { |
| 223 | let p = format!("{prefix}layers.{}", first + l); |
| 224 | let rm = |s: &mut dyn TensorSource, name: String, n, k| read_matrix(s, &name, n, k); |
| 225 | let (mix, ab, o) = if c.full_attention[l] { |
| 226 | let a = format!("{p}.self_attn"); |
| 227 | let mix = fuse_fp8( |
| 228 | &format!("{a} q|k|v"), |
| 229 | vec![ |
| 230 | rm( |
| 231 | source, |
| 232 | format!("{a}.q_proj.weight"), |
| 233 | 2 * c.heads * c.head_dim, |
| 234 | h, |
| 235 | )?, |
| 236 | rm(source, format!("{a}.k_proj.weight"), c.kv_dim(), h)?, |
| 237 | rm(source, format!("{a}.v_proj.weight"), c.kv_dim(), h)?, |
| 238 | ], |
| 239 | )?; |
| 240 | let o = upload_fp8( |
| 241 | &format!("{a}.o_proj"), |
| 242 | rm( |
| 243 | source, |
| 244 | format!("{a}.o_proj.weight"), |
| 245 | h, |
| 246 | c.heads * c.head_dim, |
| 247 | )?, |
| 248 | )?; |
| 249 | let q_norm = read_vec(source, &format!("{a}.q_norm.weight"), c.head_dim)?; |
| 250 | let k_norm = read_vec(source, &format!("{a}.k_norm.weight"), c.head_dim)?; |
| 251 | for attn in attns.iter_mut() { |
| 252 | attn.as_mut() |
| 253 | .expect("an attention layer has a cache") |
| 254 | .set_norms(ai, &q_norm, &k_norm) |
| 255 | .map_err(gpu("attn256 set_norms"))?; |
| 256 | } |
| 257 | attn_norms.push((q_norm, k_norm)); |
| 258 | ai += 1; |
| 259 | (mix, None, o) |
| 260 | } else { |
| 261 | let a = format!("{p}.linear_attn"); |
| 262 | let mix = fuse_fp8( |
| 263 | &format!("{a} qkv|z"), |
| 264 | vec![ |
| 265 | rm(source, format!("{a}.in_proj_qkv.weight"), c.conv_dim(), h)?, |
| 266 | rm( |
| 267 | source, |
| 268 | format!("{a}.in_proj_z.weight"), |
| 269 | c.lin_value_dim(), |
| 270 | h, |
| 271 | )?, |
| 272 | ], |
| 273 | )?; |
| 274 | let ia = rm(source, format!("{a}.in_proj_a.weight"), c.lin_v_heads, h)?; |
| 275 | let ib = rm(source, format!("{a}.in_proj_b.weight"), c.lin_v_heads, h)?; |
| 276 | let (an, ak, aw) = ab_rows(&ia, &ib).map_err(|e| format!("{a}: {e}"))?; |
| 277 | let ab = Bf16Tensor::upload(an, ak, &aw).map_err(gpu("in_proj_a|b"))?; |
| 278 | let o = upload_fp8( |
| 279 | &format!("{a}.out_proj"), |
| 280 | rm(source, format!("{a}.out_proj.weight"), h, c.lin_value_dim())?, |
| 281 | )?; |
| 282 | let conv: Vec<f32> = read_bf16_words( |
| 283 | source, |
| 284 | &format!("{a}.conv1d.weight"), |
| 285 | &[c.conv_dim(), 1, c.conv_kernel], |
| 286 | )? |
| 287 | .into_iter() |
| 288 | .map(bf16_to_f32) |
| 289 | .collect(); |
| 290 | let a_log = read_vec(source, &format!("{a}.A_log"), c.lin_v_heads)?; |
| 291 | let dt_bias = read_vec(source, &format!("{a}.dt_bias"), c.lin_v_heads)?; |
| 292 | let norm = read_vec(source, &format!("{a}.norm.weight"), c.lin_v_dim)?; |
| 293 | for gdn in gdns.iter_mut() { |
| 294 | gdn.as_mut() |
| 295 | .expect("a DeltaNet layer has state") |
| 296 | .set_layer(gi, &conv, &a_log, &dt_bias, &norm) |
| 297 | .map_err(gpu("gdn set_layer"))?; |
| 298 | } |
| 299 | gdn_params.push(GdnParams { |
| 300 | conv, |
| 301 | a_log, |
| 302 | dt_bias, |
| 303 | norm, |
| 304 | }); |
| 305 | gi += 1; |
| 306 | (mix, Some(ab), o) |
| 307 | }; |
| 308 | let m = format!("{p}.mlp"); |
| 309 | let (gate_up, down) = upload_experts(source, &m, h)?; |
| 310 | let in_norm = fold(read_vec(source, &format!("{p}.input_layernorm.weight"), h)?); |
| 311 | let post_norm = fold(read_vec( |
| 312 | source, |
| 313 | &format!("{p}.post_attention_layernorm.weight"), |
| 314 | h, |
| 315 | )?); |
| 316 | router |
| 317 | .set_layer(l, &router_rows(source, &m, h)?, &post_norm) |
| 318 | .map_err(gpu("router set_layer"))?; |
| 319 | let (mut gu_dir, mut dn_dir) = ( |
| 320 | Vec::with_capacity(2 * q::EXPERT_ROWS), |
| 321 | Vec::with_capacity(2 * q::EXPERT_ROWS), |
| 322 | ); |
| 323 | for e in 0..q::EXPERT_ROWS { |
| 324 | let (w, s) = gate_up.entry(e).map_err(gpu("experts gate|up entry"))?; |
| 325 | gu_dir.extend([w, s]); |
| 326 | let (w, s) = down.entry(e).map_err(gpu("experts down entry"))?; |
| 327 | dn_dir.extend([w, s]); |
| 328 | } |
| 329 | router |
| 330 | .set_directory(l, &gu_dir, &dn_dir) |
| 331 | .map_err(gpu("router set_directory"))?; |
| 332 | layers.push(LayerTensors { |
| 333 | mix, |
| 334 | ab, |
| 335 | o, |
| 336 | gate_up, |
| 337 | down, |
| 338 | }); |
| 339 | norms.push((in_norm, post_norm)); |
| 340 | } |
| 341 | |
| 342 | let cfg = Q36Config { |
| 343 | layers: c.layers as u32, |
| 344 | attn_mask, |
| 345 | vocab: v as u32, |
| 346 | eps: c.eps, |
| 347 | eps_l2: EPS_L2, |
| 348 | gdn: gdns[0].as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw), |
| 349 | attn: attns[0] |
| 350 | .as_ref() |
| 351 | .map_or(std::ptr::null_mut(), Attn256Cache::as_raw), |
| 352 | router: router.as_raw(), |
| 353 | lm_head: lm_head.as_raw(), |
| 354 | }; |
| 355 | // SAFETY: every handle is live and owned by the returned struct, which drops the graph first. |
| 356 | let mut graph = |
| 357 | unsafe { Q36Graph::create_heads(&cfg, heads) }.map_err(gpu("q36 graph create"))?; |
| 358 | // L310 merge-train proof line. The omega graph (omega_gpu_q36_graph.c) keeps its chip-only intermediates |
| 359 | // GPU-L2-cached unless AIEN_OMEGA_Q36_BUF_CACHED is exactly "0"; it reads the switch itself at alloc. |
| 360 | // Mirror the switch here so the server log states which interior policy this process asked for. |
| 361 | let interior = match std::env::var("AIEN_OMEGA_Q36_BUF_CACHED") { |
| 362 | Ok(v) if v == "0" => "GPU-uncached (AIEN_OMEGA_Q36_BUF_CACHED=0)", |
| 363 | _ => "GPU-cached (default)", |
| 364 | }; |
| 365 | eprintln!("qwen36 omega: interior buffers {interior}"); |
| 366 | // L310 merge-train proof line (one-wave lever). omega picks the CTAs per group of the grouped expert launch |
| 367 | // (9 groups: 8 routed + the shared expert) at the first launch: the compiled 6 (measured on 8 groups), an exact |
| 368 | // AIEN_OMEGA_FP8_GROUPED_CTAS, or AIEN_OMEGA_FP8_GROUPED_WAVE=1 = min(6, 48 SMs / groups), one wave. Asking omega |
| 369 | // here (same env, same process) logs the number the chip gets; a library without the rule says so. |
| 370 | let how = if std::env::var("AIEN_OMEGA_FP8_GROUPED_CTAS").is_ok_and(|v| !v.is_empty()) { |
| 371 | "AIEN_OMEGA_FP8_GROUPED_CTAS" |
| 372 | } else if std::env::var("AIEN_OMEGA_FP8_GROUPED_WAVE").as_deref() == Ok("1") { |
| 373 | "wave rule" |
| 374 | } else { |
| 375 | "compiled default" |
| 376 | }; |
| 377 | match aien_omega_fp8::grouped_ctas_auto(q::GROUPS as u32) { |
| 378 | Some(n) => eprintln!("qwen36 omega: expert grouped launch {n} CTAs per group ({how})"), |
| 379 | None => eprintln!( |
| 380 | "qwen36 omega: expert grouped launch: library predates the wave rule ({how} asked)" |
| 381 | ), |
| 382 | } |
| 383 | // L803 (2026-10-24): AIEN_OMEGA_DATTN256_PER_SPLIT = positions per CTA of the single-row decode attention launch |
| 384 | // (a multiple of 256; default 256 = one 256-position chunk per CTA, grid (ceil((pos+1)/per_split), 4) on the 35B). |
| 385 | // Diagnostic for the attention block-count experiment: 512 / 1024 give fewer CTAs that loop over chunks. The |
| 386 | // multi-row (batched) launch refuses any value but 256, so this is for the single-row harness; the server keeps |
| 387 | // the default. The proof line is what the receipts quote. |
| 388 | match std::env::var("AIEN_OMEGA_DATTN256_PER_SPLIT") { |
| 389 | Ok(v) if !v.is_empty() => match v.trim().parse::<u32>() { |
| 390 | Ok(n) if n > 0 && n % 256 == 0 => { |
| 391 | aien_omega_q38::decode_attn256_set_per_split(n); |
| 392 | eprintln!( |
| 393 | "qwen36 omega: decode attn256 per_split {n} positions per CTA (AIEN_OMEGA_DATTN256_PER_SPLIT; single-row launches only)" |
| 394 | ); |
| 395 | } |
| 396 | _ => { |
| 397 | return Err(format!( |
| 398 | "AIEN_OMEGA_DATTN256_PER_SPLIT={v}: want a positive multiple of 256" |
| 399 | )) |
| 400 | } |
| 401 | }, |
| 402 | _ => eprintln!( |
| 403 | "qwen36 omega: decode attn256 per_split 256 positions per CTA (compiled default)" |
| 404 | ), |
| 405 | } |
| 406 | for h in 1..heads { |
| 407 | // SAFETY: the states live in `gdns` / `attns`, owned beside the graph (dropped after it). |
| 408 | unsafe { |
| 409 | graph.set_head_state( |
| 410 | h, |
| 411 | gdns[h].as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw), |
| 412 | attns[h] |
| 413 | .as_ref() |
| 414 | .map_or(std::ptr::null_mut(), Attn256Cache::as_raw), |
| 415 | ) |
| 416 | } |
| 417 | .map_err(gpu("q36 graph set_head_state"))?; |
| 418 | } |
| 419 | for (l, (t, (in_norm, _))) in layers.iter().zip(&norms).enumerate() { |
| 420 | let ab = |
| 421 | t.ab.as_ref() |
| 422 | .map_or(std::ptr::null_mut(), Bf16Tensor::as_raw); |
| 423 | // SAFETY: the tensors live in `layers`, owned beside the graph. |
| 424 | unsafe { |
| 425 | graph.set_layer( |
| 426 | l, |
| 427 | t.mix.as_raw(), |
| 428 | ab, |
| 429 | t.o.as_raw(), |
| 430 | t.gate_up.as_raw(), |
| 431 | t.down.as_raw(), |
| 432 | in_norm, |
| 433 | ) |
| 434 | } |
| 435 | .map_err(gpu("q36 graph set_layer"))?; |
| 436 | } |
| 437 | graph |
| 438 | .set_final_norm(&final_norm) |
| 439 | .map_err(gpu("q36 graph set_final_norm"))?; |
| 440 | // HUM L314 exact two-pass head, on by default (AIEN_Q36_EXACT_HEAD=0 keeps the plain head): |
| 441 | // greedy tokens identical to the full bf16 head by construction (exact_head.rs), half the |
| 442 | // head's bytes. The engine turns it off for sampled requests. |
| 443 | let (head_screen, head_coef) = if std::env::var("AIEN_Q36_EXACT_HEAD").as_deref() == Ok("0") |
| 444 | { |
| 445 | eprintln!("qwen36 omega: exact two-pass head OFF (AIEN_Q36_EXACT_HEAD=0)"); |
| 446 | (None, None) |
| 447 | } else { |
| 448 | let t = std::time::Instant::now(); |
| 449 | let (codes, scales, coef) = crate::exact_head::chip_screen(&head)?; |
| 450 | let screen = |
| 451 | Fp8Tensor::upload(1, v, h, &codes, &scales).map_err(gpu("exact head screen"))?; |
| 452 | // SAFETY: the screen is owned by the returned value and dropped after the graph (field order). |
| 453 | unsafe { graph.set_exact_head(screen.as_raw(), &coef) } |
| 454 | .map_err(gpu("q36 graph set_exact_head"))?; |
| 455 | eprintln!( |
| 456 | "qwen36 omega: exact two-pass head ON (fp8b screen + Row bound, built in {:.1} s)", |
| 457 | t.elapsed().as_secs_f64() |
| 458 | ); |
| 459 | (Some(screen), Some(coef)) |
| 460 | }; |
| 461 | drop(head); |
| 462 | // Negative controls for the gates (TEST ONLY): AIEN_Q36_TEST_MUTANT=4 drops the shared expert |
| 463 | // from COMBINE, 1 shifts the SWIGLU up half, 2 the attention GATHER, 3 drops the attention gate, |
| 464 | // 5 inverts the exact head's MASK, 6 drops its bound. |
| 465 | if let Some(m) = graph_mutant() { |
| 466 | eprintln!("qwen36 omega: TEST MUTANT {m} set (negative control; never serve this)"); |
| 467 | graph.test_set_mutant(m); |
| 468 | } |
| 469 | let row_src = RowSource { |
| 470 | layers: c.layers, |
| 471 | attn_mask, |
| 472 | vocab: v, |
| 473 | eps: c.eps, |
| 474 | rope_theta: c.rope_theta, |
| 475 | rotary_dim: c.rotary_dim, |
| 476 | gdn_params, |
| 477 | attn_norms, |
| 478 | mutant: graph_mutant(), |
| 479 | head_coef, |
| 480 | }; |
| 481 | let gdn = gdns.remove(0); |
| 482 | let attn = attns.remove(0); |
| 483 | let extra_heads = gdns |
| 484 | .into_iter() |
| 485 | .zip(attns) |
| 486 | .map(|(gdn, attn)| HeadState { gdn, attn, pos: 0 }) |
| 487 | .collect(); |
| 488 | Ok(Self { |
| 489 | graph: Graph::Moe(graph), |
| 490 | router: Some(router), |
| 491 | layers, |
| 492 | lm_head, |
| 493 | lm_head8: None, |
| 494 | head_screen, |
| 495 | gdn, |
| 496 | attn, |
| 497 | extra_heads, |
| 498 | config, |
| 499 | embed, |
| 500 | pos: 0, |
| 501 | max_pos, |
| 502 | norms, |
| 503 | final_norm, |
| 504 | ab_mm: Vec::new(), |
| 505 | pf: None, |
| 506 | row_stroke: None, |
| 507 | rows: Vec::new(), |
| 508 | row_src: Some(row_src), |
| 509 | row_steps: 0, |
| 510 | }) |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | /// `AIEN_Q36_TEST_MUTANT` (the gates' negative controls), read once per graph made. |
| 515 | fn graph_mutant() -> Option<i32> { |
| 516 | std::env::var("AIEN_Q36_TEST_MUTANT") |
| 517 | .ok() |
| 518 | .and_then(|v| v.parse::<i32>().ok()) |
| 519 | } |
| 520 | |
| 521 | /// TEST ONLY (L306 router probe): the 35B's router alone on the chip, every layer's gate rows and |
| 522 | /// folded post-attention norm uploaded exactly as [`Qwen38Omega::load_moe`] does, with |
| 523 | /// placeholder directories (the probe reads ids and weights, never the group tables' targets). |
| 524 | pub fn router_probe(dir: &Path) -> Result<(Router, Qwen38Config), String> { |
| 525 | let c = Qwen38Config::from_checkpoint(dir)?; |
| 526 | check_shape(&c)?; |
| 527 | let mut source = crate::qwen3_moe_omega::ShardSource::open(dir)?; |
| 528 | let prefix = text_prefix(&mut source)?; |
| 529 | let h = c.hidden; |
| 530 | let mut router = Router::alloc_shape(c.layers, 256, 1).map_err(gpu("router alloc"))?; |
| 531 | let dir_words: Vec<u64> = (0..2 * q::EXPERT_ROWS as u64) |
| 532 | .map(|i| 0x1000 + i * 0x100) |
| 533 | .collect(); |
| 534 | for l in 0..c.layers { |
| 535 | let p = format!("{prefix}layers.{l}"); |
| 536 | let post_norm = fold(read_vec( |
| 537 | &mut source, |
| 538 | &format!("{p}.post_attention_layernorm.weight"), |
| 539 | h, |
| 540 | )?); |
| 541 | router |
| 542 | .set_layer( |
| 543 | l, |
| 544 | &router_rows(&mut source, &format!("{p}.mlp"), h)?, |
| 545 | &post_norm, |
| 546 | ) |
| 547 | .map_err(gpu("router set_layer"))?; |
| 548 | router |
| 549 | .set_directory(l, &dir_words, &dir_words) |
| 550 | .map_err(gpu("router set_directory"))?; |
| 551 | } |
| 552 | Ok((router, c)) |
| 553 | } |