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-inference-abi / src / qwen3_moe_omega.rs

6253 lines · 240815 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//! Qwen3-MoE (Qwen3-30B-A3B family) on AIEN's own GPU engine (Omega), OWN-30B Stage A.
17//!
18//! Design: `~/handoffs/2026-10-13-own30b-design.md` (section 2, Stage A). No CUDA, no Mojo, no
19//! Python: attention and every matmul run as Omega launches, routing / norms / rope / swiglu run
20//! on the host for one row.
21//!
22//! Cut 1 (this file's first half): a general-model loader. The checkpoint path and the model
23//! shape come from the caller and `config.json` (nothing is hard-coded to the Coder snapshot).
24//! Each layer's FP8 block-128 weights are dequantised with the exact e4m3 conversion
25//! (`fp8_e4m3fn_to_f32`) times the bf16 inverse scale, rounded to bf16 (round-to-nearest-even),
26//! written straight into the `[k][n]` layout the engine wants, and uploaded as four resident
27//! tensors per layer: fused q|k|v, o, every expert's gate|up side by side along N, and every
28//! expert's down side by side along N. The host copy of a layer is reused for the next one, so
29//! the peak host memory stays near one layer's transient plus the bf16 embedding.
30//!
31//! Second half: the Stage A forward (`Qwen3MoeOmegaEngine`): paged bf16 KV, host top-8 routing
32//! with `norm_topk_prob`, expert windows through `omega_gpu_matmul_resident_windows_f32`,
33//! sampling, prefill and decode, and a library entry (`load` / `generate` with a token callback)
34//! for the HTTP server.
35
36use std::collections::HashMap;
37use std::path::{Path, PathBuf};
38use std::sync::{Arc, Mutex};
39use std::time::Instant;
40
41use rayon::prelude::*;
42
43use crate::moe_plan::MoeBatchPlan;
44use crate::qwen3_moe::{bf16_to_f32, f32_to_bf16, fp8_table, shard_path, Shard, FP8_BLOCK};
45use crate::resident::transpose_bf16_for_upload;
46mod forward_pass;
47/// Expert Ribbon: FP8 experts paged from the NVMe into GPU slots (aienix#4, sc#632).
48pub mod ribbon;
49pub mod w8a8_control;
50mod whole_prompt;
51pub use whole_prompt::{
52 estimate_growth, PrefillGrowth, WholePromptFootprint, DEFAULT_CHUNK, SCRATCH_BYTES_PER_TOKEN,
53};
54
55/// The one-list decode token (OWN-30B L2 cut 2), off unless `OWN30B_DECODE_GRAPH=1`.
56#[path = "qwen3_moe_omega_dgraph.rs"]
57pub mod dgraph;
58/// Persistent KV export and import (sc#505): the `HostPagedPoolV1` payload of a token prefix.
59#[path = "qwen3_moe_omega_kvio.rs"]
60pub mod kvio;
61
62/// Column tile of the engine's tile-major B layout: every expert window must start on one.
63pub const WINDOW_TILE: usize = aien_omega_moe::TILE_N;
64/// Engine limits for one resident tensor (`omega_blackwell_matmul.h` at omega.lock).
65pub const MAX_RESIDENT_K: usize = 16384;
66pub const MAX_RESIDENT_N: usize = 262144;
67
68// ---------------------------------------------------------------------------
69// Model shape, read from the checkpoint.
70// ---------------------------------------------------------------------------
71
72/// The Qwen3-MoE shape, read from `config.json` and validated against what Stage A can run.
73#[derive(Debug, Clone, PartialEq)]
74pub struct Qwen3MoeConfig {
75 pub layers: usize,
76 pub hidden: usize,
77 pub q_heads: usize,
78 pub kv_heads: usize,
79 pub head_dim: usize,
80 pub experts: usize,
81 pub top_k: usize,
82 pub moe_intermediate: usize,
83 pub vocab: usize,
84 pub rms_eps: f32,
85 pub rope_theta: f32,
86 pub norm_topk_prob: bool,
87 pub tie_word_embeddings: bool,
88 /// Ids generation stops on (`config.json` eos plus `generation_config.json` eos list).
89 pub eos_token_ids: Vec<u32>,
90}
91
92impl Qwen3MoeConfig {
93 pub fn from_checkpoint(dir: &Path) -> Result<Self, String> {
94 let path = dir.join("config.json");
95 let text =
96 std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
97 let mut cfg = Self::from_json(&text)?;
98 let gen_path = dir.join("generation_config.json");
99 if let Ok(gen) = std::fs::read_to_string(&gen_path) {
100 let v: serde_json::Value =
101 serde_json::from_str(&gen).map_err(|e| format!("{}: {e}", gen_path.display()))?;
102 for id in eos_ids(v.get("eos_token_id")) {
103 if !cfg.eos_token_ids.contains(&id) {
104 cfg.eos_token_ids.push(id);
105 }
106 }
107 }
108 Ok(cfg)
109 }
110
111 pub fn from_json(text: &str) -> Result<Self, String> {
112 let v: serde_json::Value =
113 serde_json::from_str(text).map_err(|e| format!("config.json: {e}"))?;
114 let model_type = v.get("model_type").and_then(|m| m.as_str()).unwrap_or("");
115 if model_type != "qwen3_moe" {
116 return Err(format!(
117 "config.json model_type {model_type:?}, this loader is for qwen3_moe"
118 ));
119 }
120 let num = |key: &str| -> Result<usize, String> {
121 v.get(key)
122 .and_then(|x| x.as_u64())
123 .map(|x| x as usize)
124 .ok_or_else(|| format!("config.json: missing integer {key}"))
125 };
126 let flt = |key: &str| -> Result<f32, String> {
127 v.get(key)
128 .and_then(|x| x.as_f64())
129 .map(|x| x as f32)
130 .ok_or_else(|| format!("config.json: missing number {key}"))
131 };
132 let cfg = Self {
133 layers: num("num_hidden_layers")?,
134 hidden: num("hidden_size")?,
135 q_heads: num("num_attention_heads")?,
136 kv_heads: num("num_key_value_heads")?,
137 head_dim: num("head_dim")?,
138 experts: num("num_experts")?,
139 top_k: num("num_experts_per_tok")?,
140 moe_intermediate: num("moe_intermediate_size")?,
141 vocab: num("vocab_size")?,
142 rms_eps: flt("rms_norm_eps")?,
143 rope_theta: flt("rope_theta")?,
144 norm_topk_prob: v
145 .get("norm_topk_prob")
146 .and_then(|x| x.as_bool())
147 .unwrap_or(false),
148 tie_word_embeddings: v
149 .get("tie_word_embeddings")
150 .and_then(|x| x.as_bool())
151 .unwrap_or(false),
152 eos_token_ids: eos_ids(v.get("eos_token_id")),
153 };
154 if !v
155 .get("mlp_only_layers")
156 .and_then(|x| x.as_array())
157 .is_none_or(|a| a.is_empty())
158 {
159 return Err(
160 "config.json: mlp_only_layers is not empty; every layer must be MoE".into(),
161 );
162 }
163 if v.get("decoder_sparse_step").and_then(|x| x.as_u64()) != Some(1) {
164 return Err("config.json: decoder_sparse_step must be 1 (every layer MoE)".into());
165 }
166 cfg.validate()?;
167 Ok(cfg)
168 }
169
170 /// Stage A limits: block-128 quantisation, head_dim 128 attention, one resident tensor per
171 /// projection within the engine's K and N limits, top-k within one window call.
172 pub fn validate(&self) -> Result<(), String> {
173 let bad = |what: &str| Err(format!("config refused: {what}"));
174 if self.layers == 0 || self.experts == 0 || self.top_k == 0 || self.vocab == 0 {
175 return bad("zero layers, experts, top_k or vocab");
176 }
177 if !self.hidden.is_multiple_of(FP8_BLOCK)
178 || !self.moe_intermediate.is_multiple_of(FP8_BLOCK)
179 {
180 return bad("hidden and moe_intermediate must be multiples of 128 (FP8 block)");
181 }
182 if self.head_dim != 128 || !self.q_heads.is_multiple_of(self.kv_heads) || self.q_heads > 64
183 {
184 return bad(
185 "attention must be head_dim 128, q_heads a multiple of kv_heads, q_heads <= 64",
186 );
187 }
188 if self.top_k > self.experts || self.top_k > aien_omega_moe::MAX_WINDOWS {
189 return bad("top_k must be <= experts and <= one window call");
190 }
191 if !self.norm_topk_prob {
192 return bad("norm_topk_prob=false is not implemented (Qwen3-MoE uses true)");
193 }
194 if self.tie_word_embeddings {
195 return bad("tie_word_embeddings=true is not implemented");
196 }
197 for (what, k, n) in [
198 ("q|k|v", self.hidden, self.qkv_n()),
199 ("o", self.q_dim(), self.hidden),
200 ("gate|up", self.hidden, self.gate_up_n()),
201 ("down", self.moe_intermediate, self.down_n()),
202 ("lm_head", self.hidden, self.vocab),
203 ] {
204 if k > MAX_RESIDENT_K || n > MAX_RESIDENT_N {
205 return Err(format!(
206 "config refused: {what} tensor {k}x{n} exceeds the engine limit {MAX_RESIDENT_K}x{MAX_RESIDENT_N}"
207 ));
208 }
209 }
210 if !(2 * self.moe_intermediate).is_multiple_of(WINDOW_TILE)
211 || !self.hidden.is_multiple_of(WINDOW_TILE)
212 {
213 return bad("expert windows must start on a column tile of 8");
214 }
215 Ok(())
216 }
217
218 pub fn q_dim(&self) -> usize {
219 self.q_heads * self.head_dim
220 }
221 pub fn kv_dim(&self) -> usize {
222 self.kv_heads * self.head_dim
223 }
224 /// Fused q|k|v output width.
225 pub fn qkv_n(&self) -> usize {
226 self.q_dim() + 2 * self.kv_dim()
227 }
228 /// Width of one expert's gate|up window.
229 pub fn gate_up_cols(&self) -> usize {
230 2 * self.moe_intermediate
231 }
232 /// All experts' gate|up side by side.
233 pub fn gate_up_n(&self) -> usize {
234 self.experts * self.gate_up_cols()
235 }
236 /// Width of one expert's down window.
237 pub fn down_cols(&self) -> usize {
238 self.hidden
239 }
240 pub fn down_n(&self) -> usize {
241 self.experts * self.down_cols()
242 }
243 /// First column of expert `e` in the gate|up tensor (gate first, then up).
244 pub fn gate_up_col0(&self, expert: usize) -> usize {
245 expert * self.gate_up_cols()
246 }
247 pub fn down_col0(&self, expert: usize) -> usize {
248 expert * self.down_cols()
249 }
250
251 /// Bytes of one layer's four resident bf16 tensors.
252 pub fn layer_resident_bytes(&self) -> usize {
253 2 * (self.hidden * self.qkv_n()
254 + self.q_dim() * self.hidden
255 + self.hidden * self.gate_up_n()
256 + self.moe_intermediate * self.down_n())
257 }
258 /// Bytes resident for the whole model (layers plus lm_head).
259 pub fn model_resident_bytes(&self) -> usize {
260 self.layers * self.layer_resident_bytes() + 2 * self.hidden * self.vocab
261 }
262 /// Bytes the engine reads per generated token (attention + top_k experts + lm_head), bf16.
263 pub fn bytes_per_token_bf16(&self) -> usize {
264 2 * self.layers * (self.hidden * self.qkv_n() + self.q_dim() * self.hidden)
265 + 2 * self.layers
266 * self.top_k
267 * (self.hidden * self.gate_up_cols() + self.moe_intermediate * self.down_cols())
268 + 2 * self.hidden * self.vocab
269 }
270}
271
272fn eos_ids(v: Option<&serde_json::Value>) -> Vec<u32> {
273 match v {
274 Some(serde_json::Value::Number(n)) => {
275 n.as_u64().map(|x| vec![x as u32]).unwrap_or_default()
276 }
277 Some(serde_json::Value::Array(a)) => a
278 .iter()
279 .filter_map(|x| x.as_u64().map(|x| x as u32))
280 .collect(),
281 _ => Vec::new(),
282 }
283}
284
285// ---------------------------------------------------------------------------
286// Where the tensors come from: the checkpoint shards, or a fake in tests.
287// ---------------------------------------------------------------------------
288
289/// Reads one raw tensor (dtype and shape checked) into `dst`.
290pub trait TensorSource {
291 fn read_into(
292 &mut self,
293 name: &str,
294 dtype: &str,
295 shape: &[usize],
296 dst: &mut [u8],
297 ) -> Result<(), String>;
298
299 /// The dtype the checkpoint records for `name` (`"F8_E4M3"`, `"BF16"`, ...), `None` when the
300 /// checkpoint has no such tensor. A source that cannot tell refuses.
301 fn dtype_of(&mut self, name: &str) -> Result<Option<String>, String> {
302 Err(format!("{name}: this tensor source cannot report dtypes"))
303 }
304}
305
306/// The safetensors shards behind `model.safetensors.index.json` (the same validated reader as
307/// the MoE capsule loader: dtype, shape and byte range are checked per tensor).
308pub struct ShardSource {
309 dir: PathBuf,
310 weight_map: serde_json::Map<String, serde_json::Value>,
311 shards: HashMap<String, Shard>,
312}
313
314impl ShardSource {
315 pub fn open(dir: &Path) -> Result<Self, String> {
316 let index_path = dir.join("model.safetensors.index.json");
317 let index: serde_json::Value = serde_json::from_slice(
318 &std::fs::read(&index_path).map_err(|e| format!("{}: {e}", index_path.display()))?,
319 )
320 .map_err(|e| format!("{}: {e}", index_path.display()))?;
321 let weight_map = index
322 .get("weight_map")
323 .and_then(|v| v.as_object())
324 .cloned()
325 .ok_or_else(|| "index: missing weight_map object".to_string())?;
326 Ok(Self {
327 dir: dir.to_path_buf(),
328 weight_map,
329 shards: HashMap::new(),
330 })
331 }
332}
333
334impl ShardSource {
335 /// The opened shard the index names for `name`, `None` when the index has no entry.
336 fn shard_for(&mut self, name: &str) -> Result<Option<&Shard>, String> {
337 let Some(filename) = self.weight_map.get(name) else {
338 return Ok(None);
339 };
340 let filename = filename
341 .as_str()
342 .ok_or_else(|| format!("index: shard of {name} is not a string"))?;
343 if !self.shards.contains_key(filename) {
344 let path = shard_path(&self.dir, filename).map_err(|e| e.to_string())?;
345 let shard = Shard::open(&path).map_err(|e| e.to_string())?;
346 self.shards.insert(filename.to_string(), shard);
347 }
348 Ok(Some(&self.shards[filename]))
349 }
350}
351
352impl TensorSource for ShardSource {
353 fn read_into(
354 &mut self,
355 name: &str,
356 dtype: &str,
357 shape: &[usize],
358 dst: &mut [u8],
359 ) -> Result<(), String> {
360 self.shard_for(name)?
361 .ok_or_else(|| format!("index: no shard for {name}"))?
362 .read(name, dtype, shape, dst)
363 .map_err(|e| e.to_string())
364 }
365
366 fn dtype_of(&mut self, name: &str) -> Result<Option<String>, String> {
367 match self.shard_for(name)? {
368 None => Ok(None),
369 Some(shard) => shard
370 .dtype(name)
371 .map(|d| Some(d.to_string()))
372 .ok_or_else(|| format!("{name}: in the index but not in its shard's header")),
373 }
374 }
375}
376
377// ---------------------------------------------------------------------------
378// FP8 block-128 -> bf16, written transposed into column windows.
379// ---------------------------------------------------------------------------
380
381/// One `[rows][k]` FP8 matrix with its `[ceil(rows/128)][k/128]` bf16 inverse scales, and the
382/// column of the destination where its rows land (row `r` becomes column `col0 + r`).
383pub struct Fp8Source<'a> {
384 pub weights: &'a [u8],
385 pub scales: &'a [u16],
386 pub rows: usize,
387 pub col0: usize,
388}
389
390/// Dequantises every source exactly (`fp8_e4m3fn_to_f32(w) * bf16(scale)`), rounds to bf16
391/// (round-to-nearest-even, as the engine's own upload does) and writes `dst[k][col0 + r]`,
392/// `dst` being `[k_dim][dst_n]` row-major: the transposed `[in][out]` layout a resident tensor
393/// takes. The e4m3 NaN codes (0x7f, 0xff) are refused: a weight is never NaN, so one in the
394/// file means a corrupt or foreign checkpoint.
395pub fn dequant_fp8_sources_to_bf16_cols(
396 sources: &[Fp8Source<'_>],
397 k_dim: usize,
398 dst: &mut [u16],
399 dst_n: usize,
400) -> Result<(), String> {
401 if k_dim == 0 || !k_dim.is_multiple_of(FP8_BLOCK) {
402 return Err(format!(
403 "k_dim {k_dim} must be a positive multiple of {FP8_BLOCK}"
404 ));
405 }
406 if dst.len() != k_dim * dst_n {
407 return Err(format!(
408 "dst holds {} values, {k_dim}x{dst_n} expected",
409 dst.len()
410 ));
411 }
412 let k_blocks = k_dim / FP8_BLOCK;
413 for (i, s) in sources.iter().enumerate() {
414 if s.weights.len() != s.rows * k_dim {
415 return Err(format!(
416 "source {i}: {} weight bytes, {}x{k_dim} expected",
417 s.weights.len(),
418 s.rows
419 ));
420 }
421 let want = s.rows.div_ceil(FP8_BLOCK) * k_blocks;
422 if s.scales.len() != want {
423 return Err(format!(
424 "source {i}: {} scales, {want} expected",
425 s.scales.len()
426 ));
427 }
428 if s.col0 + s.rows > dst_n {
429 return Err(format!(
430 "source {i}: columns {}..{} past dst_n {dst_n}",
431 s.col0,
432 s.col0 + s.rows
433 ));
434 }
435 }
436 let lut = fp8_table();
437 let nan_seen = std::sync::atomic::AtomicBool::new(false);
438 // Each task owns one 128-deep band of k (one scale block), all destination columns.
439 dst.par_chunks_mut(dst_n * FP8_BLOCK)
440 .enumerate()
441 .for_each(|(kb, band)| {
442 let k0 = kb * FP8_BLOCK;
443 for s in sources {
444 for r in 0..s.rows {
445 let scale = bf16_to_f32(s.scales[(r / FP8_BLOCK) * k_blocks + kb]);
446 let row = &s.weights[r * k_dim + k0..r * k_dim + k0 + FP8_BLOCK];
447 let col = s.col0 + r;
448 for (j, &w) in row.iter().enumerate() {
449 if w & 0x7f == 0x7f {
450 nan_seen.store(true, std::sync::atomic::Ordering::Relaxed);
451 }
452 band[j * dst_n + col] = f32_to_bf16(lut[w as usize] * scale);
453 }
454 }
455 }
456 });
457 if nan_seen.load(std::sync::atomic::Ordering::Relaxed) {
458 return Err("FP8 weight holds an e4m3 NaN code (0x7f/0xff): refused".into());
459 }
460 Ok(())
461}
462
463// ---------------------------------------------------------------------------
464// The device side: resident matmuls, uploaded through a trait so tests need no chip.
465// ---------------------------------------------------------------------------
466
467/// A resident `k x n` weight used whole: `c[m x n] = a[m x k] * W`. Returns chip nanoseconds.
468pub trait DenseMatmul: Send + Sync + std::fmt::Debug {
469 fn k(&self) -> usize;
470 fn n(&self) -> usize;
471 fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result<u64, String>;
472}
473
474/// A resident `k x n` tensor of experts side by side, used by column windows: for each window
475/// `w`, `c[w][m x cols] = a[m x k] * W[:, col0s[w] .. col0s[w] + cols)`. Returns chip nanoseconds.
476pub trait ExpertMatmul: Send + Sync + std::fmt::Debug {
477 fn k(&self) -> usize;
478 fn n(&self) -> usize;
479 fn windows_f32(
480 &self,
481 m: usize,
482 a: &[f32],
483 col0s: &[u32],
484 cols: usize,
485 c: &mut [f32],
486 ) -> Result<u64, String>;
487}
488
489/// `experts` resident FP8 projections of `[n][k]` with block-128 scales (the checkpoint bytes as
490/// they are). `grouped_f32(ids, x, y)`: one launch for `ids.len()` experts; `x` is `k` values
491/// shared by every group or `ids.len() * k` (one row per group); `y` is `ids.len() * n`,
492/// group-major. A single projection is `ids == [0]`. Returns chip nanoseconds.
493pub trait Fp8Gemv: Send + Sync + std::fmt::Debug {
494 fn experts(&self) -> usize;
495 fn n(&self) -> usize;
496 fn k(&self) -> usize;
497 fn grouped_f32(&self, ids: &[u32], x: &[f32], y: &mut [f32]) -> Result<u64, String>;
498 /// Device addresses `(weights, scales)` of one expert (for the router's directory).
499 fn tensor_entry(&self, expert: usize) -> Result<(u64, u64), String> {
500 let _ = expert;
501 Err("this FP8 tensor has no device addresses".into())
502 }
503 /// `groups` experts in one launch whose group table and single activation row are already
504 /// on the device (written by the [`DeviceRouter`] launch). Returns chip nanoseconds.
505 fn grouped_dev(
506 &self,
507 groups: usize,
508 tab_va: u64,
509 x_va: u64,
510 y: &mut [f32],
511 ) -> Result<u64, String> {
512 let _ = (groups, tab_va, x_va, y);
513 Err("this FP8 tensor takes no device-resident group table".into())
514 }
515 /// Whether [`Self::gemm_f32`] (the prefill grouped GEMM) is available on this tensor.
516 fn has_gemm(&self) -> bool {
517 false
518 }
519 /// Prefill grouped GEMM, one launch: row `i` computes expert `expert_ids[i]` on activation
520 /// row `token_rows[i]` of `x` (`x.len() / k` rows); `expert_ids` is sorted (non-decreasing);
521 /// `y` is `rows * n` in row-table order and equals one GEMV per row. Returns chip nanoseconds.
522 fn gemm_f32(
523 &self,
524 expert_ids: &[u32],
525 token_rows: &[u32],
526 x: &[f32],
527 y: &mut [f32],
528 ) -> Result<u64, String> {
529 let _ = (expert_ids, token_rows, x, y);
530 Err("this FP8 tensor has no prefill GEMM".into())
531 }
532 /// The omega C handle (`OmegaGpuFp8Tensor *`) for the one-list decode graph; null when this
533 /// tensor is not an omega FP8 tensor.
534 fn omega_raw(&self) -> *mut std::ffi::c_void {
535 std::ptr::null_mut()
536 }
537}
538
539/// Device addresses the router left its outputs at (valid until the next `route`).
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub struct RouteAddrs {
542 /// `x' = RMSNorm(x) * 2^64`, f32 `[hidden]`: the gate|up launch's activation row.
543 pub x_va: u64,
544 /// The gate|up group table (`top_k` entries of `{w_va, s_va}`).
545 pub tab_gu_va: u64,
546}
547
548/// The MoE router as one device launch: RMSNorm of the residual row, router logits, softmax,
549/// top-k and renormalised weights, with the gate|up group table and the normed row left on the
550/// device for the grouped FP8 GEMV (no host round trip for either).
551pub trait DeviceRouter: Send + Sync + std::fmt::Debug {
552 /// The layer's `mlp.gate.weight` as bf16 bits `[experts][hidden]` and its
553 /// `post_attention_layernorm` weight.
554 fn set_layer(&self, layer: usize, gate_bf16: &[u16], norm_w: &[f32]) -> Result<(), String>;
555 /// `{w_va, s_va}` per expert of the layer's gate|up and down FP8 tensors (flat, 2 words per expert).
556 fn set_directory(&self, layer: usize, gu: &[u64], dn: &[u64]) -> Result<(), String>;
557 /// Routes the residual row `x`: writes `top_k` ids (descending by logit) and weights, returns
558 /// chip nanoseconds and where the device outputs are.
559 fn route(
560 &self,
561 layer: usize,
562 x: &[f32],
563 eps: f32,
564 ids: &mut [u32],
565 weights: &mut [f32],
566 ) -> Result<(u64, RouteAddrs), String>;
567 /// Trace helper: the last call's `RMSNorm(x)` read back from the device (undoing the 2^64).
568 fn read_post(&self, out: &mut [f32]) -> Result<(), String>;
569 /// The omega C handle (`OmegaGpuRouter *`) for the one-list decode graph; null when none.
570 fn omega_raw(&self) -> *mut std::ffi::c_void {
571 std::ptr::null_mut()
572 }
573}
574
575/// The lm_head as one streaming launch over the checkpoint's `[vocab][hidden]` bf16 rows.
576pub trait LmHeadGemv: Send + Sync + std::fmt::Debug {
577 fn logits_f32(&self, hidden: &[f32], out: &mut [f32]) -> Result<u64, String>;
578 /// The omega C handle (`OmegaGpuBf16Tensor *`) for the one-list decode graph; null when none.
579 fn omega_raw(&self) -> *mut std::ffi::c_void {
580 std::ptr::null_mut()
581 }
582}
583
584/// The lm_head in the form the loader chose.
585#[derive(Debug, Clone)]
586pub enum LmHead {
587 /// `[hidden][vocab]` bf16 through the generic matmul (Stage A / cut 7 path).
588 Dense(Arc<dyn DenseMatmul>),
589 /// `[vocab][hidden]` bf16 through the streaming GEMV.
590 Gemv(Arc<dyn LmHeadGemv>),
591}
592
593/// Which implementation to use for a step the device can take over.
594#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
595pub enum PathChoice {
596 /// The device one when the uploader offers it, else the host/dense one.
597 #[default]
598 Auto,
599 /// Always the host/dense one.
600 Host,
601 /// The device one; the load fails when the uploader cannot offer it.
602 Device,
603}
604
605/// Router and lm_head choices for a load.
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
607pub struct DevicePaths {
608 pub router: PathChoice,
609 pub lm_head: PathChoice,
610}
611
612/// How the loader hands weights to the device.
613#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614pub enum WeightFormat {
615 /// Everything dequantised to bf16 (Stage A): about 60.4 GB resident.
616 Bf16,
617 /// Experts as FP8 with the checkpoint scales (grouped GEMV, one launch per projection per
618 /// layer); attention and lm_head bf16. About 31.5 GB resident.
619 Fp8Experts,
620 /// Experts and the q/k/v/o projections as FP8; lm_head bf16. About 30.6 GB resident.
621 Fp8All,
622}
623
624impl WeightFormat {
625 pub fn fp8_experts(self) -> bool {
626 self != WeightFormat::Bf16
627 }
628 pub fn fp8_attention(self) -> bool {
629 self == WeightFormat::Fp8All
630 }
631}
632
633/// Makes `[k][n]` bf16 matrices resident. The real one is [`OmegaModelUploader`].
634pub trait ModelUploader {
635 fn upload_dense(
636 &self,
637 k: usize,
638 n: usize,
639 bits: &[u16],
640 ) -> Result<Arc<dyn DenseMatmul>, String>;
641 fn upload_experts(
642 &self,
643 k: usize,
644 n: usize,
645 bits: &[u16],
646 ) -> Result<Arc<dyn ExpertMatmul>, String>;
647 /// FP8 projections as in the checkpoint: `w` is `experts * n * k` e4m3 bytes `[expert][n][k]`,
648 /// `scales` is `experts * (n/128) * (k/128)` bf16 bits. Uploaders without FP8 refuse.
649 fn upload_fp8(
650 &self,
651 experts: usize,
652 n: usize,
653 k: usize,
654 w: &[u8],
655 scales: &[u16],
656 ) -> Result<Arc<dyn Fp8Gemv>, String> {
657 let _ = (experts, n, k, w, scales);
658 Err("this uploader has no FP8 path".into())
659 }
660 /// The device router for `config` (its kernel is fixed at 128 experts, hidden 2048, top-8),
661 /// or `None` when this uploader has none.
662 fn new_router(&self, config: &Qwen3MoeConfig) -> Result<Option<Arc<dyn DeviceRouter>>, String> {
663 let _ = config;
664 Ok(None)
665 }
666 /// The lm_head as a streaming GEMV over `bits` = `[vocab = n][hidden = k]` bf16 (the
667 /// checkpoint layout), or `None` when this uploader has none.
668 fn upload_lm_head_gemv(
669 &self,
670 n: usize,
671 k: usize,
672 bits: &[u16],
673 ) -> Result<Option<Arc<dyn LmHeadGemv>>, String> {
674 let _ = (n, k, bits);
675 Ok(None)
676 }
677}
678
679/// Omega's whole-tensor resident matmul behind a lock.
680#[derive(Debug)]
681pub struct OmegaDense(Mutex<aien_omega_gpu::ResidentTensor>, usize, usize);
682
683impl DenseMatmul for OmegaDense {
684 fn k(&self) -> usize {
685 self.1
686 }
687 fn n(&self) -> usize {
688 self.2
689 }
690 fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result<u64, String> {
691 let t = self
692 .0
693 .lock()
694 .map_err(|_| "resident tensor lock poisoned".to_string())?;
695 t.matmul_f32(m, a, c)
696 .map(|i| i.raw.elapsed_ns)
697 .map_err(|e| e.to_string())
698 }
699}
700
701/// Omega's column-window matmul (cut 2) behind a lock.
702#[derive(Debug)]
703pub struct OmegaExperts(Mutex<aien_omega_moe::MoeTensor>, usize, usize);
704
705impl ExpertMatmul for OmegaExperts {
706 fn k(&self) -> usize {
707 self.1
708 }
709 fn n(&self) -> usize {
710 self.2
711 }
712 fn windows_f32(
713 &self,
714 m: usize,
715 a: &[f32],
716 col0s: &[u32],
717 cols: usize,
718 c: &mut [f32],
719 ) -> Result<u64, String> {
720 let t = self
721 .0
722 .lock()
723 .map_err(|_| "expert tensor lock poisoned".to_string())?;
724 t.windows_f32(m, a, col0s, cols, c)
725 .map(|i| i.raw.elapsed_ns)
726 .map_err(|e| e.to_string())
727 }
728}
729
730/// Fallback when the window API is not linked: the whole-tensor product, windows copied out.
731/// Correct, and far slower (every expert is computed): only for bring-up without cut 2.
732#[derive(Debug)]
733pub struct WholeTensorExperts {
734 dense: OmegaDense,
735 scratch: Mutex<Vec<f32>>,
736}
737
738impl ExpertMatmul for WholeTensorExperts {
739 fn k(&self) -> usize {
740 self.dense.k()
741 }
742 fn n(&self) -> usize {
743 self.dense.n()
744 }
745 fn windows_f32(
746 &self,
747 m: usize,
748 a: &[f32],
749 col0s: &[u32],
750 cols: usize,
751 c: &mut [f32],
752 ) -> Result<u64, String> {
753 let n = self.n();
754 let mut full = self
755 .scratch
756 .lock()
757 .map_err(|_| "scratch lock poisoned".to_string())?;
758 full.resize(m * n, 0.0);
759 let ns = self.dense.matmul_f32(m, a, &mut full)?;
760 copy_windows_out(&full, m, n, col0s, cols, c)?;
761 Ok(ns)
762 }
763}
764
765/// Copies `col0s.len()` column windows of a `[m][n]` product into `c` (window-major, `[m][cols]`
766/// each). Shared by the fallback and the test fake.
767pub fn copy_windows_out(
768 full: &[f32],
769 m: usize,
770 n: usize,
771 col0s: &[u32],
772 cols: usize,
773 c: &mut [f32],
774) -> Result<(), String> {
775 if c.len() != col0s.len() * m * cols {
776 return Err(format!(
777 "window output holds {} values, {} expected",
778 c.len(),
779 col0s.len() * m * cols
780 ));
781 }
782 for (w, &col0) in col0s.iter().enumerate() {
783 aien_omega_moe::check_window(n, col0 as usize, cols).map_err(|e| e.to_string())?;
784 let col0 = col0 as usize;
785 for r in 0..m {
786 let src = &full[r * n + col0..r * n + col0 + cols];
787 c[(w * m + r) * cols..(w * m + r + 1) * cols].copy_from_slice(src);
788 }
789 }
790 Ok(())
791}
792
793/// The real uploader: Omega resident tensors; experts through the window API when it is linked,
794/// the whole-tensor fallback otherwise (`uses_window_api` says which).
795pub struct OmegaModelUploader;
796
797/// Which attention path the engine runs.
798#[derive(Debug, Clone, Copy, PartialEq, Eq)]
799pub enum AttnPath {
800 /// Fused when omega's decode attention is linked and the model has its shape, else split.
801 Auto,
802 /// Host norms and rope, paged bf16 KV, omega's paged attention launch.
803 Split,
804 /// omega's one-launch decode attention (refused when not linked).
805 Fused,
806}
807
808impl OmegaModelUploader {
809 /// True when omega's one-launch decode attention (OWN-30B cut 8/9) is linked.
810 pub fn uses_dattn_api() -> bool {
811 aien_omega_dattn::is_native()
812 }
813 pub fn uses_window_api() -> bool {
814 aien_omega_moe::is_native()
815 }
816 pub fn uses_fp8_api() -> bool {
817 aien_omega_fp8::is_native()
818 }
819 /// True when the one-launch MoE router and the FP8 device-table entry points are linked.
820 pub fn uses_router_api() -> bool {
821 aien_omega_router::is_native() && aien_omega_fp8::has_device_tables()
822 }
823 /// True when the bf16 streaming GEMV (the lm_head kernel) is linked.
824 pub fn uses_bf16_api() -> bool {
825 aien_omega_bf16::is_native()
826 }
827}
828
829impl ModelUploader for OmegaModelUploader {
830 fn upload_dense(
831 &self,
832 k: usize,
833 n: usize,
834 bits: &[u16],
835 ) -> Result<Arc<dyn DenseMatmul>, String> {
836 let t =
837 aien_omega_gpu::ResidentTensor::upload_bf16(k, n, bits).map_err(|e| e.to_string())?;
838 Ok(Arc::new(OmegaDense(Mutex::new(t), k, n)))
839 }
840 fn upload_experts(
841 &self,
842 k: usize,
843 n: usize,
844 bits: &[u16],
845 ) -> Result<Arc<dyn ExpertMatmul>, String> {
846 if Self::uses_window_api() {
847 let t =
848 aien_omega_moe::MoeTensor::upload_bf16(k, n, bits).map_err(|e| e.to_string())?;
849 Ok(Arc::new(OmegaExperts(Mutex::new(t), k, n)))
850 } else {
851 let t = aien_omega_gpu::ResidentTensor::upload_bf16(k, n, bits)
852 .map_err(|e| e.to_string())?;
853 Ok(Arc::new(WholeTensorExperts {
854 dense: OmegaDense(Mutex::new(t), k, n),
855 scratch: Mutex::new(Vec::new()),
856 }))
857 }
858 }
859 fn upload_fp8(
860 &self,
861 experts: usize,
862 n: usize,
863 k: usize,
864 w: &[u8],
865 scales: &[u16],
866 ) -> Result<Arc<dyn Fp8Gemv>, String> {
867 if !Self::uses_fp8_api() {
868 return Err("this binary carries no FP8 GEMV (omega before OWN-30B cut 5, or AIEN_OMEGA_GPU_LIB without it)".into());
869 }
870 let t = aien_omega_fp8::Fp8Tensor::upload(experts, n, k, w, scales)
871 .map_err(|e| e.to_string())?;
872 Ok(Arc::new(OmegaFp8(Mutex::new(t), experts, n, k)))
873 }
874 fn new_router(&self, config: &Qwen3MoeConfig) -> Result<Option<Arc<dyn DeviceRouter>>, String> {
875 if !Self::uses_router_api() {
876 return Ok(None);
877 }
878 if config.experts != aien_omega_router::EXPERTS
879 || config.hidden != aien_omega_router::HIDDEN
880 || config.top_k != aien_omega_router::TOP_K
881 {
882 return Ok(None);
883 }
884 let r = aien_omega_router::Router::alloc(config.layers).map_err(|e| e.to_string())?;
885 Ok(Some(Arc::new(OmegaRouter(Mutex::new(r)))))
886 }
887 fn upload_lm_head_gemv(
888 &self,
889 n: usize,
890 k: usize,
891 bits: &[u16],
892 ) -> Result<Option<Arc<dyn LmHeadGemv>>, String> {
893 if !Self::uses_bf16_api() {
894 return Ok(None);
895 }
896 let t = aien_omega_bf16::Bf16Tensor::upload(n, k, bits).map_err(|e| e.to_string())?;
897 Ok(Some(Arc::new(OmegaLmHead(Mutex::new(t)))))
898 }
899}
900
901/// Omega's FP8 grouped GEMV behind a lock.
902#[derive(Debug)]
903pub struct OmegaFp8(Mutex<aien_omega_fp8::Fp8Tensor>, usize, usize, usize);
904
905impl Fp8Gemv for OmegaFp8 {
906 fn experts(&self) -> usize {
907 self.1
908 }
909 fn n(&self) -> usize {
910 self.2
911 }
912 fn k(&self) -> usize {
913 self.3
914 }
915 fn grouped_f32(&self, ids: &[u32], x: &[f32], y: &mut [f32]) -> Result<u64, String> {
916 let t = self
917 .0
918 .lock()
919 .map_err(|_| "fp8 tensor lock poisoned".to_string())?;
920 let info = t.gemv_grouped_f32(ids, x, y).map_err(|e| e.to_string())?;
921 Ok(info.elapsed_ns)
922 }
923 fn tensor_entry(&self, expert: usize) -> Result<(u64, u64), String> {
924 let t = self
925 .0
926 .lock()
927 .map_err(|_| "fp8 tensor lock poisoned".to_string())?;
928 t.entry(expert).map_err(|e| e.to_string())
929 }
930 fn grouped_dev(
931 &self,
932 groups: usize,
933 tab_va: u64,
934 x_va: u64,
935 y: &mut [f32],
936 ) -> Result<u64, String> {
937 let t = self
938 .0
939 .lock()
940 .map_err(|_| "fp8 tensor lock poisoned".to_string())?;
941 let info = t
942 .gemv_grouped_dev(groups, tab_va, x_va, y)
943 .map_err(|e| e.to_string())?;
944 Ok(info.elapsed_ns)
945 }
946 fn has_gemm(&self) -> bool {
947 aien_omega_fp8::has_gemm()
948 }
949 fn gemm_f32(
950 &self,
951 expert_ids: &[u32],
952 token_rows: &[u32],
953 x: &[f32],
954 y: &mut [f32],
955 ) -> Result<u64, String> {
956 let t = self
957 .0
958 .lock()
959 .map_err(|_| "fp8 tensor lock poisoned".to_string())?;
960 let info = t
961 .gemm_f32(expert_ids, token_rows, x, y)
962 .map_err(|e| e.to_string())?;
963 Ok(info.elapsed_ns)
964 }
965 fn omega_raw(&self) -> *mut std::ffi::c_void {
966 self.0.lock().map_or(std::ptr::null_mut(), |t| t.as_raw())
967 }
968}
969
970/// Omega's one-launch MoE router behind a lock.
971#[derive(Debug)]
972pub struct OmegaRouter(Mutex<aien_omega_router::Router>);
973
974impl DeviceRouter for OmegaRouter {
975 fn set_layer(&self, layer: usize, gate_bf16: &[u16], norm_w: &[f32]) -> Result<(), String> {
976 let mut r = self
977 .0
978 .lock()
979 .map_err(|_| "router lock poisoned".to_string())?;
980 r.set_layer(layer, gate_bf16, norm_w)
981 .map_err(|e| e.to_string())
982 }
983 fn set_directory(&self, layer: usize, gu: &[u64], dn: &[u64]) -> Result<(), String> {
984 let mut r = self
985 .0
986 .lock()
987 .map_err(|_| "router lock poisoned".to_string())?;
988 r.set_directory(layer, gu, dn).map_err(|e| e.to_string())
989 }
990 fn route(
991 &self,
992 layer: usize,
993 x: &[f32],
994 eps: f32,
995 ids: &mut [u32],
996 weights: &mut [f32],
997 ) -> Result<(u64, RouteAddrs), String> {
998 let mut r = self
999 .0
1000 .lock()
1001 .map_err(|_| "router lock poisoned".to_string())?;
1002 // norm_topk_prob is true (the config check refuses false); out_scale 2^64 gives the FP8
1003 // GEMV its activation row.
1004 let info = r
1005 .route(
1006 layer,
1007 x,
1008 eps,
1009 true,
1010 aien_omega_router::OUT_SCALE_FP8,
1011 ids,
1012 weights,
1013 )
1014 .map_err(|e| e.to_string())?;
1015 let o = r.device_outputs();
1016 Ok((
1017 info.elapsed_ns,
1018 RouteAddrs {
1019 x_va: o.xout_va,
1020 tab_gu_va: o.tab_gu_va,
1021 },
1022 ))
1023 }
1024 fn read_post(&self, out: &mut [f32]) -> Result<(), String> {
1025 let mut r = self
1026 .0
1027 .lock()
1028 .map_err(|_| "router lock poisoned".to_string())?;
1029 r.read_xout(out).map_err(|e| e.to_string())?;
1030 for v in out.iter_mut() {
1031 *v /= aien_omega_router::OUT_SCALE_FP8;
1032 }
1033 Ok(())
1034 }
1035 fn omega_raw(&self) -> *mut std::ffi::c_void {
1036 self.0.lock().map_or(std::ptr::null_mut(), |r| r.as_raw())
1037 }
1038}
1039
1040/// Omega's bf16 streaming GEMV (the lm_head) behind a lock.
1041#[derive(Debug)]
1042pub struct OmegaLmHead(Mutex<aien_omega_bf16::Bf16Tensor>);
1043
1044impl LmHeadGemv for OmegaLmHead {
1045 fn logits_f32(&self, hidden: &[f32], out: &mut [f32]) -> Result<u64, String> {
1046 let t = self
1047 .0
1048 .lock()
1049 .map_err(|_| "lm_head lock poisoned".to_string())?;
1050 let info = t.gemv_f32(hidden, out).map_err(|e| e.to_string())?;
1051 Ok(info.elapsed_ns)
1052 }
1053 fn omega_raw(&self) -> *mut std::ffi::c_void {
1054 self.0.lock().map_or(std::ptr::null_mut(), |t| t.as_raw())
1055 }
1056}
1057
1058// ---------------------------------------------------------------------------
1059// The loaded model.
1060// ---------------------------------------------------------------------------
1061
1062#[derive(Debug)]
1063pub struct OmegaLayer {
1064 pub input_norm: Vec<f32>,
1065 pub post_norm: Vec<f32>,
1066 pub q_norm: Vec<f32>,
1067 pub k_norm: Vec<f32>,
1068 /// Router `[experts][hidden]` f32.
1069 pub router: Vec<f32>,
1070 pub attn: AttnWeights,
1071 pub experts: ExpertWeights,
1072}
1073
1074/// The q|k|v and o projections of one layer, in the format the loader chose.
1075#[derive(Debug)]
1076pub enum AttnWeights {
1077 Bf16 {
1078 qkv: Arc<dyn DenseMatmul>,
1079 o: Arc<dyn DenseMatmul>,
1080 },
1081 Fp8 {
1082 qkv: Arc<dyn Fp8Gemv>,
1083 o: Arc<dyn Fp8Gemv>,
1084 },
1085}
1086
1087/// The expert projections of one layer, in the format the loader chose.
1088#[derive(Debug)]
1089pub enum ExpertWeights {
1090 Bf16 {
1091 gate_up: Arc<dyn ExpertMatmul>,
1092 down: Arc<dyn ExpertMatmul>,
1093 },
1094 Fp8 {
1095 gate_up: Arc<dyn Fp8Gemv>,
1096 down: Arc<dyn Fp8Gemv>,
1097 },
1098 /// FP8 experts paged from the NVMe into GPU slots (Expert Ribbon); one pool shared by all layers.
1099 Paged(Arc<ribbon::PagedExperts>),
1100}
1101
1102/// The whole model: resident matmuls on the device, bf16 embedding and f32 norms/routers on the host.
1103pub struct Qwen3MoeOmegaWeights {
1104 pub config: Qwen3MoeConfig,
1105 /// `[vocab][hidden]` bf16 bits; a row is widened to f32 at lookup.
1106 pub embed_bf16: Vec<u16>,
1107 pub layers: Vec<OmegaLayer>,
1108 pub final_norm: Vec<f32>,
1109 pub lm_head: LmHead,
1110 /// The one-launch router, set up for every layer (None: host routing only).
1111 pub device_router: Option<Arc<dyn DeviceRouter>>,
1112}
1113
1114impl Qwen3MoeOmegaWeights {
1115 pub fn embed_row(&self, token: u32) -> Vec<f32> {
1116 let h = self.config.hidden;
1117 let t = (token as usize) % self.config.vocab;
1118 self.embed_bf16[t * h..(t + 1) * h]
1119 .iter()
1120 .map(|&b| bf16_to_f32(b))
1121 .collect()
1122 }
1123
1124 /// Bytes the host keeps after the load (embedding, norms, routers).
1125 pub fn host_bytes(&self) -> usize {
1126 self.embed_bf16.len() * 2
1127 + self.final_norm.len() * 4
1128 + self
1129 .layers
1130 .iter()
1131 .map(|l| {
1132 4 * (l.input_norm.len()
1133 + l.post_norm.len()
1134 + l.q_norm.len()
1135 + l.k_norm.len()
1136 + l.router.len())
1137 })
1138 .sum::<usize>()
1139 }
1140}
1141
1142/// What a load measured.
1143#[derive(Debug, Clone, PartialEq)]
1144pub struct LoadReport {
1145 pub resident_bytes: usize,
1146 pub format: WeightFormat,
1147 pub host_bytes: usize,
1148 /// Process peak resident set (VmHWM) after the load, if `/proc` is readable.
1149 pub peak_rss_bytes: Option<u64>,
1150 pub peak_rss_before_bytes: Option<u64>,
1151 pub seconds: f64,
1152 pub window_api: bool,
1153}
1154
1155/// Peak resident set size of this process (`VmHWM` in `/proc/self/status`), bytes.
1156pub fn peak_rss_bytes() -> Option<u64> {
1157 proc_status_kb("VmHWM:").map(|kb| kb * 1024)
1158}
1159
1160/// Current resident set size (`VmRSS`), bytes.
1161pub fn current_rss_bytes() -> Option<u64> {
1162 proc_status_kb("VmRSS:").map(|kb| kb * 1024)
1163}
1164
1165fn proc_status_kb(key: &str) -> Option<u64> {
1166 let text = std::fs::read_to_string("/proc/self/status").ok()?;
1167 text.lines()
1168 .find(|l| l.starts_with(key))
1169 .and_then(|l| l.split_whitespace().nth(1))
1170 .and_then(|v| v.parse().ok())
1171}
1172
1173/// Loads a checkpoint directory: `config.json` for the shape, the shards for the weights.
1174pub fn load_qwen3_moe_omega(
1175 dir: &Path,
1176 uploader: &dyn ModelUploader,
1177 progress: &mut dyn FnMut(&str),
1178) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1179 load_qwen3_moe_omega_with(dir, uploader, WeightFormat::Bf16, progress)
1180}
1181
1182/// As [`load_qwen3_moe_omega`] with a chosen [`WeightFormat`].
1183pub fn load_qwen3_moe_omega_with(
1184 dir: &Path,
1185 uploader: &dyn ModelUploader,
1186 format: WeightFormat,
1187 progress: &mut dyn FnMut(&str),
1188) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1189 load_qwen3_moe_omega_paths(dir, uploader, format, DevicePaths::default(), progress)
1190}
1191
1192/// As [`load_qwen3_moe_omega_with`] with the router and lm_head paths chosen.
1193pub fn load_qwen3_moe_omega_paths(
1194 dir: &Path,
1195 uploader: &dyn ModelUploader,
1196 format: WeightFormat,
1197 paths: DevicePaths,
1198 progress: &mut dyn FnMut(&str),
1199) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1200 let config = Qwen3MoeConfig::from_checkpoint(dir)?;
1201 let mut source = ShardSource::open(dir)?;
1202 load_qwen3_moe_omega_from_paths(&config, &mut source, uploader, format, paths, progress)
1203}
1204
1205/// The loader proper, over any tensor source (tests use an in-memory one).
1206pub fn load_qwen3_moe_omega_from(
1207 config: &Qwen3MoeConfig,
1208 source: &mut dyn TensorSource,
1209 uploader: &dyn ModelUploader,
1210 progress: &mut dyn FnMut(&str),
1211) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1212 load_qwen3_moe_omega_from_with(config, source, uploader, WeightFormat::Bf16, progress)
1213}
1214
1215/// The loader proper with a chosen [`WeightFormat`]. FP8 projections go up as the checkpoint
1216/// bytes (`[n][k]` per expert, scales `[n/128][k/128]`), bf16 ones through the exact dequant.
1217pub fn load_qwen3_moe_omega_from_with(
1218 config: &Qwen3MoeConfig,
1219 source: &mut dyn TensorSource,
1220 uploader: &dyn ModelUploader,
1221 format: WeightFormat,
1222 progress: &mut dyn FnMut(&str),
1223) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1224 load_qwen3_moe_omega_from_paths(
1225 config,
1226 source,
1227 uploader,
1228 format,
1229 DevicePaths::default(),
1230 progress,
1231 )
1232}
1233
1234/// As [`load_qwen3_moe_omega_from_with`] with the router and lm_head implementations chosen:
1235/// [`PathChoice::Auto`] takes the device router / streaming lm_head GEMV when the uploader
1236/// offers them (the router also needs FP8 experts), [`PathChoice::Host`] keeps host routing
1237/// and the dense lm_head matmul, [`PathChoice::Device`] fails the load when unavailable.
1238pub fn load_qwen3_moe_omega_from_paths(
1239 config: &Qwen3MoeConfig,
1240 source: &mut dyn TensorSource,
1241 uploader: &dyn ModelUploader,
1242 format: WeightFormat,
1243 paths: DevicePaths,
1244 progress: &mut dyn FnMut(&str),
1245) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1246 load_from_inner(config, source, uploader, format, paths, None, progress)
1247}
1248
1249/// As [`load_qwen3_moe_omega_from_paths`] with the experts paged (Expert Ribbon): no expert bytes are read
1250/// or uploaded; every layer gets [`ExpertWeights::Paged`] over the one shared slot pool. Needs FP8 experts.
1251pub fn load_qwen3_moe_omega_paged_from(
1252 config: &Qwen3MoeConfig,
1253 source: &mut dyn TensorSource,
1254 uploader: &dyn ModelUploader,
1255 format: WeightFormat,
1256 paths: DevicePaths,
1257 paged: Arc<ribbon::PagedExperts>,
1258 progress: &mut dyn FnMut(&str),
1259) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1260 if !format.fp8_experts() {
1261 return Err("paged experts need FP8 experts (--weights fp8-experts or fp8)".into());
1262 }
1263 load_from_inner(
1264 config,
1265 source,
1266 uploader,
1267 format,
1268 paths,
1269 Some(paged),
1270 progress,
1271 )
1272}
1273
1274/// As [`load_qwen3_moe_omega_paged_from`] from a checkpoint directory.
1275pub fn load_qwen3_moe_omega_paged(
1276 dir: &Path,
1277 uploader: &dyn ModelUploader,
1278 format: WeightFormat,
1279 paths: DevicePaths,
1280 paged: Arc<ribbon::PagedExperts>,
1281 progress: &mut dyn FnMut(&str),
1282) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1283 let config = Qwen3MoeConfig::from_checkpoint(dir)?;
1284 let mut source = ShardSource::open(dir)?;
1285 load_qwen3_moe_omega_paged_from(
1286 &config,
1287 &mut source,
1288 uploader,
1289 format,
1290 paths,
1291 paged,
1292 progress,
1293 )
1294}
1295
1296fn load_from_inner(
1297 config: &Qwen3MoeConfig,
1298 source: &mut dyn TensorSource,
1299 uploader: &dyn ModelUploader,
1300 format: WeightFormat,
1301 paths: DevicePaths,
1302 paged: Option<Arc<ribbon::PagedExperts>>,
1303 progress: &mut dyn FnMut(&str),
1304) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
1305 config.validate()?;
1306 let device_router: Option<Arc<dyn DeviceRouter>> = if paths.router == PathChoice::Host {
1307 None
1308 } else if !format.fp8_experts() {
1309 if paths.router == PathChoice::Device {
1310 return Err(
1311 "the device router needs FP8 experts (--weights fp8-experts or fp8)".into(),
1312 );
1313 }
1314 None
1315 } else {
1316 let r = uploader.new_router(config)?;
1317 if r.is_none() && paths.router == PathChoice::Device {
1318 return Err("the device router was asked for but is not available (omega before the router cut, or a model shape the kernel does not take)".into());
1319 }
1320 r
1321 };
1322 let mut resident = 0usize;
1323 let t0 = Instant::now();
1324 let peak_before = peak_rss_bytes();
1325 let (h, i, e) = (config.hidden, config.moe_intermediate, config.experts);
1326 let (qd, kvd, hd) = (config.q_dim(), config.kv_dim(), config.head_dim);
1327 let kb = h / FP8_BLOCK;
1328 let ib = i / FP8_BLOCK;
1329 let qkv_n = config.qkv_n();
1330
1331 // Transient host buffers, sized once for the largest use and reused for every layer.
1332 let gu_cols = if paged.is_some() {
1333 0
1334 } else {
1335 config.gate_up_n()
1336 };
1337 let mut bits: Vec<u16> = vec![0; h * gu_cols.max(qkv_n).max(qd)];
1338 // Paged experts never pass through these buffers: size them for attention only.
1339 let ex_bytes = if paged.is_some() { 0 } else { e * 2 * i * h };
1340 let ex_scales = if paged.is_some() { 0 } else { e * 2 * ib * kb };
1341 let mut fp8: Vec<u8> = vec![0; ex_bytes.max(qd * h + 2 * kvd * h)];
1342 let mut scales: Vec<u16> =
1343 vec![0; ex_scales.max((qd / FP8_BLOCK + 2 * (kvd / FP8_BLOCK)) * kb)];
1344 let mut small: Vec<u8> = Vec::new();
1345
1346 let read_bf16_f32 = |source: &mut dyn TensorSource,
1347 name: &str,
1348 shape: &[usize],
1349 small: &mut Vec<u8>|
1350 -> Result<Vec<f32>, String> {
1351 let n: usize = shape.iter().product();
1352 small.resize(n * 2, 0);
1353 source.read_into(name, "BF16", shape, small)?;
1354 Ok(small
1355 .chunks_exact(2)
1356 .map(|b| bf16_to_f32(u16::from_le_bytes([b[0], b[1]])))
1357 .collect())
1358 };
1359
1360 let mut layers = Vec::with_capacity(config.layers);
1361 for layer in 0..config.layers {
1362 let p = format!("model.layers.{layer}");
1363 // --- fused q|k|v: sources q [qd][h], k [kvd][h], v [kvd][h] at columns 0, qd, qd+kvd ---
1364 let specs = [
1365 ("q_proj", qd, 0usize),
1366 ("k_proj", kvd, qd),
1367 ("v_proj", kvd, qd + kvd),
1368 ];
1369 let mut w_off = 0usize;
1370 let mut s_off = 0usize;
1371 let mut ranges = Vec::new();
1372 for (name, rows, col0) in specs {
1373 let wl = rows * h;
1374 let sl = (rows / FP8_BLOCK) * kb;
1375 source.read_into(
1376 &format!("{p}.self_attn.{name}.weight"),
1377 "F8_E4M3",
1378 &[rows, h],
1379 &mut fp8[w_off..w_off + wl],
1380 )?;
1381 read_scales(
1382 source,
1383 &format!("{p}.self_attn.{name}.weight_scale_inv"),
1384 &[rows / FP8_BLOCK, kb],
1385 &mut scales[s_off..s_off + sl],
1386 )?;
1387 ranges.push((w_off..w_off + wl, s_off..s_off + sl, rows, col0));
1388 w_off += wl;
1389 s_off += sl;
1390 }
1391 let sources: Vec<Fp8Source> = ranges
1392 .iter()
1393 .map(|(w, s, rows, col0)| Fp8Source {
1394 weights: &fp8[w.clone()],
1395 scales: &scales[s.clone()],
1396 rows: *rows,
1397 col0: *col0,
1398 })
1399 .collect();
1400 let qkv_fp8 = if format.fp8_attention() {
1401 // q, k, v rows stacked: [qkv_n][h] with scales [qkv_n/128][kb], exactly the chip layout.
1402 resident += w_off + s_off * 4;
1403 Some(uploader.upload_fp8(1, qkv_n, h, &fp8[..w_off], &scales[..s_off])?)
1404 } else {
1405 None
1406 };
1407 let qkv = if qkv_fp8.is_none() {
1408 dequant_fp8_sources_to_bf16_cols(&sources, h, &mut bits[..h * qkv_n], qkv_n)?;
1409 resident += 2 * h * qkv_n;
1410 Some(uploader.upload_dense(h, qkv_n, &bits[..h * qkv_n])?)
1411 } else {
1412 None
1413 };
1414 progress(&format!("{p}.self_attn.qkv"));
1415
1416 // --- o: [h][qd] -> dst [qd][h] ---
1417 source.read_into(
1418 &format!("{p}.self_attn.o_proj.weight"),
1419 "F8_E4M3",
1420 &[h, qd],
1421 &mut fp8[..h * qd],
1422 )?;
1423 read_scales(
1424 source,
1425 &format!("{p}.self_attn.o_proj.weight_scale_inv"),
1426 &[kb, qd / FP8_BLOCK],
1427 &mut scales[..kb * (qd / FP8_BLOCK)],
1428 )?;
1429 let attn = if format.fp8_attention() {
1430 resident += h * qd + kb * (qd / FP8_BLOCK) * 4;
1431 let o =
1432 uploader.upload_fp8(1, h, qd, &fp8[..h * qd], &scales[..kb * (qd / FP8_BLOCK)])?;
1433 AttnWeights::Fp8 {
1434 qkv: qkv_fp8.expect("fp8 qkv"),
1435 o,
1436 }
1437 } else {
1438 dequant_fp8_sources_to_bf16_cols(
1439 &[Fp8Source {
1440 weights: &fp8[..h * qd],
1441 scales: &scales[..kb * (qd / FP8_BLOCK)],
1442 rows: h,
1443 col0: 0,
1444 }],
1445 qd,
1446 &mut bits[..qd * h],
1447 h,
1448 )?;
1449 resident += 2 * qd * h;
1450 let o = uploader.upload_dense(qd, h, &bits[..qd * h])?;
1451 AttnWeights::Bf16 {
1452 qkv: qkv.expect("bf16 qkv"),
1453 o,
1454 }
1455 };
1456 progress(&format!("{p}.self_attn.o_proj"));
1457
1458 // Expert Ribbon: no expert bytes are read here; the pager reads them on first use.
1459 let experts = if let Some(pe) = &paged {
1460 progress(&format!("{p}.mlp.experts paged"));
1461 ExpertWeights::Paged(pe.clone())
1462 } else {
1463 // --- experts gate|up: per expert gate [i][h] then up [i][h]; columns e*2i (gate), e*2i+i (up) ---
1464 let gu_n = config.gate_up_n();
1465 for ex in 0..e {
1466 for (j, proj) in ["gate_proj", "up_proj"].into_iter().enumerate() {
1467 let w0 = (ex * 2 + j) * i * h;
1468 let s0 = (ex * 2 + j) * ib * kb;
1469 let base = format!("{p}.mlp.experts.{ex}.{proj}");
1470 source.read_into(
1471 &format!("{base}.weight"),
1472 "F8_E4M3",
1473 &[i, h],
1474 &mut fp8[w0..w0 + i * h],
1475 )?;
1476 read_scales(
1477 source,
1478 &format!("{base}.weight_scale_inv"),
1479 &[ib, kb],
1480 &mut scales[s0..s0 + ib * kb],
1481 )?;
1482 }
1483 }
1484 let sources: Vec<Fp8Source> = (0..e)
1485 .flat_map(|ex| (0..2).map(move |j| (ex, j)))
1486 .map(|(ex, j)| {
1487 let w0 = (ex * 2 + j) * i * h;
1488 let s0 = (ex * 2 + j) * ib * kb;
1489 Fp8Source {
1490 weights: &fp8[w0..w0 + i * h],
1491 scales: &scales[s0..s0 + ib * kb],
1492 rows: i,
1493 col0: config.gate_up_col0(ex) + j * i,
1494 }
1495 })
1496 .collect();
1497 let gate_up_fp8 = if format.fp8_experts() {
1498 // [e][2i][h] bytes with scales [e][2ib][kb]: the capsule GATE_UP layout, as the chip wants it.
1499 resident += e * 2 * i * h + e * 2 * ib * kb * 4;
1500 Some(uploader.upload_fp8(
1501 e,
1502 2 * i,
1503 h,
1504 &fp8[..e * 2 * i * h],
1505 &scales[..e * 2 * ib * kb],
1506 )?)
1507 } else {
1508 None
1509 };
1510 let gate_up = if gate_up_fp8.is_none() {
1511 dequant_fp8_sources_to_bf16_cols(&sources, h, &mut bits[..h * gu_n], gu_n)?;
1512 resident += 2 * h * gu_n;
1513 Some(uploader.upload_experts(h, gu_n, &bits[..h * gu_n])?)
1514 } else {
1515 None
1516 };
1517 progress(&format!("{p}.mlp.experts.gate_up"));
1518
1519 // --- experts down: per expert [h][i]; columns e*h ---
1520 let dn_n = config.down_n();
1521 for ex in 0..e {
1522 let base = format!("{p}.mlp.experts.{ex}.down_proj");
1523 source.read_into(
1524 &format!("{base}.weight"),
1525 "F8_E4M3",
1526 &[h, i],
1527 &mut fp8[ex * h * i..(ex + 1) * h * i],
1528 )?;
1529 read_scales(
1530 source,
1531 &format!("{base}.weight_scale_inv"),
1532 &[kb, ib],
1533 &mut scales[ex * kb * ib..(ex + 1) * kb * ib],
1534 )?;
1535 }
1536 let sources: Vec<Fp8Source> = (0..e)
1537 .map(|ex| Fp8Source {
1538 weights: &fp8[ex * h * i..(ex + 1) * h * i],
1539 scales: &scales[ex * kb * ib..(ex + 1) * kb * ib],
1540 rows: h,
1541 col0: config.down_col0(ex),
1542 })
1543 .collect();
1544 let experts = if format.fp8_experts() {
1545 resident += e * h * i + e * kb * ib * 4;
1546 let down =
1547 uploader.upload_fp8(e, h, i, &fp8[..e * h * i], &scales[..e * kb * ib])?;
1548 ExpertWeights::Fp8 {
1549 gate_up: gate_up_fp8.expect("fp8 gate_up"),
1550 down,
1551 }
1552 } else {
1553 dequant_fp8_sources_to_bf16_cols(&sources, i, &mut bits[..i * dn_n], dn_n)?;
1554 resident += 2 * i * dn_n;
1555 let down = uploader.upload_experts(i, dn_n, &bits[..i * dn_n])?;
1556 ExpertWeights::Bf16 {
1557 gate_up: gate_up.expect("bf16 gate_up"),
1558 down,
1559 }
1560 };
1561 progress(&format!("{p}.mlp.experts.down"));
1562 experts
1563 };
1564
1565 layers.push(OmegaLayer {
1566 input_norm: read_bf16_f32(
1567 source,
1568 &format!("{p}.input_layernorm.weight"),
1569 &[h],
1570 &mut small,
1571 )?,
1572 post_norm: read_bf16_f32(
1573 source,
1574 &format!("{p}.post_attention_layernorm.weight"),
1575 &[h],
1576 &mut small,
1577 )?,
1578 q_norm: read_bf16_f32(
1579 source,
1580 &format!("{p}.self_attn.q_norm.weight"),
1581 &[hd],
1582 &mut small,
1583 )?,
1584 k_norm: read_bf16_f32(
1585 source,
1586 &format!("{p}.self_attn.k_norm.weight"),
1587 &[hd],
1588 &mut small,
1589 )?,
1590 router: read_bf16_f32(source, &format!("{p}.mlp.gate.weight"), &[e, h], &mut small)?,
1591 attn,
1592 experts,
1593 });
1594 if let (Some(router), Some(layer)) = (&device_router, layers.last()) {
1595 let li = layers.len() - 1;
1596 // The router carries the bf16 gate weights; the host copy is an exact widening of them.
1597 let gate_bf16: Vec<u16> = layer
1598 .router
1599 .iter()
1600 .map(|v| (v.to_bits() >> 16) as u16)
1601 .collect();
1602 router
1603 .set_layer(li, &gate_bf16, &layer.post_norm)
1604 .map_err(|e| format!("router layer {li}: {e}"))?;
1605 let (gu, dn) = match &layer.experts {
1606 ExpertWeights::Fp8 { gate_up, down } => {
1607 let (mut gu, mut dn) = (Vec::with_capacity(2 * e), Vec::with_capacity(2 * e));
1608 for ex in 0..e {
1609 let (w, s) = gate_up.tensor_entry(ex)?;
1610 gu.extend([w, s]);
1611 let (w, s) = down.tensor_entry(ex)?;
1612 dn.extend([w, s]);
1613 }
1614 (gu, dn)
1615 }
1616 // The paged path never reads the router's group tables (ribbon.rs).
1617 ExpertWeights::Paged(_) => (
1618 ribbon::directory_placeholder(e),
1619 ribbon::directory_placeholder(e),
1620 ),
1621 ExpertWeights::Bf16 { .. } => {
1622 return Err(format!("layer {li}: the device router needs FP8 experts"))
1623 }
1624 };
1625 router
1626 .set_directory(li, &gu, &dn)
1627 .map_err(|e| format!("router directory layer {li}: {e}"))?;
1628 }
1629 }
1630 drop(fp8);
1631 drop(scales);
1632
1633 // lm_head: bf16 [vocab][h]. The streaming GEMV takes the rows as they are; the dense matmul
1634 // takes them transposed to [h][vocab].
1635 let vocab = config.vocab;
1636 let mut raw = vec![0u8; vocab * h * 2];
1637 source.read_into("lm_head.weight", "BF16", &[vocab, h], &mut raw)?;
1638 let gemv = if paths.lm_head == PathChoice::Host {
1639 None
1640 } else {
1641 let rows: Vec<u16> = raw
1642 .chunks_exact(2)
1643 .map(|b| u16::from_le_bytes([b[0], b[1]]))
1644 .collect();
1645 let g = uploader.upload_lm_head_gemv(vocab, h, &rows)?;
1646 if g.is_none() && paths.lm_head == PathChoice::Device {
1647 return Err("the lm_head GEMV was asked for but is not available (omega before the bf16 GEMV cut)".into());
1648 }
1649 g
1650 };
1651 let lm_head = match gemv {
1652 Some(g) => LmHead::Gemv(g),
1653 None => {
1654 bits.clear();
1655 transpose_bf16_for_upload(&raw, vocab, h, &mut bits);
1656 LmHead::Dense(uploader.upload_dense(h, vocab, &bits)?)
1657 }
1658 };
1659 resident += 2 * h * vocab;
1660 progress("lm_head");
1661 drop(bits);
1662
1663 // Embedding stays on the host as bf16 bits (half the f32 size).
1664 source.read_into("model.embed_tokens.weight", "BF16", &[vocab, h], &mut raw)?;
1665 let embed_bf16: Vec<u16> = raw
1666 .chunks_exact(2)
1667 .map(|b| u16::from_le_bytes([b[0], b[1]]))
1668 .collect();
1669 drop(raw);
1670 let final_norm = read_bf16_f32(source, "model.norm.weight", &[h], &mut small)?;
1671
1672 let weights = Qwen3MoeOmegaWeights {
1673 config: config.clone(),
1674 embed_bf16,
1675 layers,
1676 final_norm,
1677 lm_head,
1678 device_router,
1679 };
1680 let report = LoadReport {
1681 resident_bytes: resident,
1682 format,
1683 host_bytes: weights.host_bytes(),
1684 peak_rss_bytes: peak_rss_bytes(),
1685 peak_rss_before_bytes: peak_before,
1686 seconds: t0.elapsed().as_secs_f64(),
1687 window_api: aien_omega_moe::is_native(),
1688 };
1689 Ok((weights, report))
1690}
1691
1692fn read_scales(
1693 source: &mut dyn TensorSource,
1694 name: &str,
1695 shape: &[usize],
1696 dst: &mut [u16],
1697) -> Result<(), String> {
1698 // SAFETY: a u16 slice viewed as bytes of twice the length; the source writes little-endian
1699 // bf16 words, which is this host's byte order (aarch64 / x86 little endian).
1700 let bytes =
1701 unsafe { std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::<u8>(), dst.len() * 2) };
1702 source.read_into(name, "BF16", shape, bytes)
1703}
1704
1705/// Largest transient the loader holds beyond the model's own host bytes, for the given shape:
1706/// the bf16 upload buffer, the FP8 layer buffer, its scales and the raw lm_head/embedding read.
1707pub fn loader_transient_bytes(config: &Qwen3MoeConfig) -> usize {
1708 let (h, i, e) = (config.hidden, config.moe_intermediate, config.experts);
1709 let bits = 2 * h * config.gate_up_n().max(config.qkv_n()).max(config.q_dim());
1710 let fp8 = (e * 2 * i * h).max(config.q_dim() * h + 2 * config.kv_dim() * h);
1711 let scales = 2
1712 * (e * 2 * (i / FP8_BLOCK) * (h / FP8_BLOCK))
1713 .max(((config.q_dim() + 2 * config.kv_dim()) / FP8_BLOCK) * (h / FP8_BLOCK));
1714 let raw = 2 * config.vocab * h;
1715 bits + fp8 + scales + raw
1716}
1717
1718#[cfg(any(test, feature = "host-test-engine"))]
1719#[cfg_attr(not(test), allow(dead_code))]
1720pub(crate) mod test_support {
1721 //! An in-memory checkpoint and a recording uploader with host matmuls, so the loader and the
1722 //! forward can be exercised end to end without a chip.
1723 use super::*;
1724 use crate::qwen3_moe::{f32_to_bf16, f32_to_fp8_e4m3fn};
1725
1726 pub fn tiny_config() -> Qwen3MoeConfig {
1727 Qwen3MoeConfig {
1728 layers: 2,
1729 hidden: 256,
1730 q_heads: 2,
1731 kv_heads: 1,
1732 head_dim: 128,
1733 experts: 4,
1734 top_k: 2,
1735 moe_intermediate: 128,
1736 vocab: 64,
1737 rms_eps: 1e-6,
1738 rope_theta: 1e7,
1739 norm_topk_prob: true,
1740 tie_word_embeddings: false,
1741 eos_token_ids: vec![3],
1742 }
1743 }
1744
1745 /// Deterministic pseudo-random values in [-1, 1).
1746 pub fn prand(seed: u64, idx: usize) -> f32 {
1747 let mut x = seed
1748 .wrapping_mul(0x9E37_79B9_7F4A_7C15)
1749 .wrapping_add(idx as u64 + 1);
1750 x ^= x >> 29;
1751 x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
1752 x ^= x >> 32;
1753 ((x & 0xFFFF) as f32 / 32768.0) - 1.0
1754 }
1755
1756 #[derive(Default)]
1757 pub struct MemorySource {
1758 pub tensors: HashMap<String, (String, Vec<usize>, Vec<u8>)>,
1759 pub reads: Vec<String>,
1760 }
1761
1762 impl MemorySource {
1763 fn put_bf16(&mut self, name: &str, shape: &[usize], seed: u64, scale: f32) {
1764 let n: usize = shape.iter().product();
1765 let bytes: Vec<u8> = (0..n)
1766 .flat_map(|i| f32_to_bf16(prand(seed, i) * scale).to_le_bytes())
1767 .collect();
1768 self.tensors
1769 .insert(name.to_string(), ("BF16".into(), shape.to_vec(), bytes));
1770 }
1771 fn put_fp8(&mut self, name: &str, rows: usize, cols: usize, seed: u64) {
1772 let w: Vec<u8> = (0..rows * cols)
1773 .map(|i| f32_to_fp8_e4m3fn(prand(seed, i) * 8.0))
1774 .collect();
1775 self.tensors
1776 .insert(name.to_string(), ("F8_E4M3".into(), vec![rows, cols], w));
1777 let sshape = [rows.div_ceil(FP8_BLOCK), cols / FP8_BLOCK];
1778 let s: Vec<u8> = (0..sshape[0] * sshape[1])
1779 .flat_map(|i| {
1780 f32_to_bf16(0.02 + 0.01 * (prand(seed ^ 0x55, i) + 1.0)).to_le_bytes()
1781 })
1782 .collect();
1783 self.tensors.insert(
1784 format!("{name}_scale_inv"),
1785 ("BF16".into(), sshape.to_vec(), s),
1786 );
1787 }
1788
1789 pub fn for_config(c: &Qwen3MoeConfig) -> Self {
1790 let mut m = Self::default();
1791 let (h, i, e, hd) = (c.hidden, c.moe_intermediate, c.experts, c.head_dim);
1792 m.put_bf16("model.embed_tokens.weight", &[c.vocab, h], 1, 1.0);
1793 m.put_bf16("lm_head.weight", &[c.vocab, h], 2, 0.1);
1794 m.put_bf16("model.norm.weight", &[h], 3, 1.0);
1795 for l in 0..c.layers {
1796 let p = format!("model.layers.{l}");
1797 let seed = 100 + l as u64 * 1000;
1798 m.put_fp8(
1799 &format!("{p}.self_attn.q_proj.weight"),
1800 c.q_dim(),
1801 h,
1802 seed + 1,
1803 );
1804 m.put_fp8(
1805 &format!("{p}.self_attn.k_proj.weight"),
1806 c.kv_dim(),
1807 h,
1808 seed + 2,
1809 );
1810 m.put_fp8(
1811 &format!("{p}.self_attn.v_proj.weight"),
1812 c.kv_dim(),
1813 h,
1814 seed + 3,
1815 );
1816 m.put_fp8(
1817 &format!("{p}.self_attn.o_proj.weight"),
1818 h,
1819 c.q_dim(),
1820 seed + 4,
1821 );
1822 m.put_bf16(
1823 &format!("{p}.self_attn.q_norm.weight"),
1824 &[hd],
1825 seed + 5,
1826 1.0,
1827 );
1828 m.put_bf16(
1829 &format!("{p}.self_attn.k_norm.weight"),
1830 &[hd],
1831 seed + 6,
1832 1.0,
1833 );
1834 m.put_bf16(&format!("{p}.input_layernorm.weight"), &[h], seed + 7, 1.0);
1835 m.put_bf16(
1836 &format!("{p}.post_attention_layernorm.weight"),
1837 &[h],
1838 seed + 8,
1839 1.0,
1840 );
1841 m.put_bf16(&format!("{p}.mlp.gate.weight"), &[e, h], seed + 9, 1.0);
1842 for ex in 0..e {
1843 let b = format!("{p}.mlp.experts.{ex}");
1844 m.put_fp8(
1845 &format!("{b}.gate_proj.weight"),
1846 i,
1847 h,
1848 seed + 10 + ex as u64 * 3,
1849 );
1850 m.put_fp8(
1851 &format!("{b}.up_proj.weight"),
1852 i,
1853 h,
1854 seed + 11 + ex as u64 * 3,
1855 );
1856 m.put_fp8(
1857 &format!("{b}.down_proj.weight"),
1858 h,
1859 i,
1860 seed + 12 + ex as u64 * 3,
1861 );
1862 }
1863 }
1864 m
1865 }
1866
1867 pub fn fp8_f32(&self, name: &str) -> (Vec<f32>, usize, usize) {
1868 let (_, shape, w) = &self.tensors[name];
1869 let (_, _, s) = &self.tensors[&format!("{name}_scale_inv")];
1870 let (rows, cols) = (shape[0], shape[1]);
1871 let kb = cols / FP8_BLOCK;
1872 let scales: Vec<u16> = s
1873 .chunks_exact(2)
1874 .map(|b| u16::from_le_bytes([b[0], b[1]]))
1875 .collect();
1876 let lut = fp8_table();
1877 let out = (0..rows * cols)
1878 .map(|idx| {
1879 let (r, k) = (idx / cols, idx % cols);
1880 lut[w[idx] as usize] * bf16_to_f32(scales[(r / FP8_BLOCK) * kb + k / FP8_BLOCK])
1881 })
1882 .collect();
1883 (out, rows, cols)
1884 }
1885 }
1886
1887 impl TensorSource for MemorySource {
1888 fn read_into(
1889 &mut self,
1890 name: &str,
1891 dtype: &str,
1892 shape: &[usize],
1893 dst: &mut [u8],
1894 ) -> Result<(), String> {
1895 let (dt, sh, bytes) = self
1896 .tensors
1897 .get(name)
1898 .ok_or_else(|| format!("no tensor {name}"))?;
1899 if dt != dtype || sh != shape {
1900 return Err(format!("{name}: {dt} {sh:?} asked as {dtype} {shape:?}"));
1901 }
1902 if bytes.len() != dst.len() {
1903 return Err(format!("{name}: {} bytes, dst {}", bytes.len(), dst.len()));
1904 }
1905 dst.copy_from_slice(bytes);
1906 self.reads.push(name.to_string());
1907 Ok(())
1908 }
1909
1910 fn dtype_of(&mut self, name: &str) -> Result<Option<String>, String> {
1911 Ok(self.tensors.get(name).map(|t| t.0.clone()))
1912 }
1913 }
1914
1915 /// A `[k][n]` bf16 matrix on the host; matmul in f32 with `a` rounded to bf16 as omega does.
1916 #[derive(Debug)]
1917 pub struct HostMatrix {
1918 pub k: usize,
1919 pub n: usize,
1920 pub bits: Vec<u16>,
1921 }
1922
1923 impl HostMatrix {
1924 pub fn full(&self, m: usize, a: &[f32], c: &mut [f32]) {
1925 assert_eq!(a.len(), m * self.k);
1926 assert_eq!(c.len(), m * self.n);
1927 for r in 0..m {
1928 let ar: Vec<f32> = a[r * self.k..(r + 1) * self.k]
1929 .iter()
1930 .map(|&v| bf16_to_f32(f32_to_bf16(v)))
1931 .collect();
1932 for j in 0..self.n {
1933 let mut acc = 0.0f32;
1934 for kk in 0..self.k {
1935 acc += ar[kk] * bf16_to_f32(self.bits[kk * self.n + j]);
1936 }
1937 c[r * self.n + j] = acc;
1938 }
1939 }
1940 }
1941 }
1942
1943 impl DenseMatmul for HostMatrix {
1944 fn k(&self) -> usize {
1945 self.k
1946 }
1947 fn n(&self) -> usize {
1948 self.n
1949 }
1950 fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result<u64, String> {
1951 self.full(m, a, c);
1952 Ok(0)
1953 }
1954 }
1955
1956 impl ExpertMatmul for HostMatrix {
1957 fn k(&self) -> usize {
1958 self.k
1959 }
1960 fn n(&self) -> usize {
1961 self.n
1962 }
1963 fn windows_f32(
1964 &self,
1965 m: usize,
1966 a: &[f32],
1967 col0s: &[u32],
1968 cols: usize,
1969 c: &mut [f32],
1970 ) -> Result<u64, String> {
1971 // Only the windows are computed (so a wrong col0 is a wrong answer, as on the chip).
1972 if c.len() != col0s.len() * m * cols {
1973 return Err("window output size".into());
1974 }
1975 for (w, &col0) in col0s.iter().enumerate() {
1976 aien_omega_moe::check_window(self.n, col0 as usize, cols)
1977 .map_err(|e| e.to_string())?;
1978 for r in 0..m {
1979 let ar: Vec<f32> = a[r * self.k..(r + 1) * self.k]
1980 .iter()
1981 .map(|&v| bf16_to_f32(f32_to_bf16(v)))
1982 .collect();
1983 for j in 0..cols {
1984 let col = col0 as usize + j;
1985 let mut acc = 0.0f32;
1986 for kk in 0..self.k {
1987 acc += ar[kk] * bf16_to_f32(self.bits[kk * self.n + col]);
1988 }
1989 c[(w * m + r) * cols + j] = acc;
1990 }
1991 }
1992 }
1993 Ok(0)
1994 }
1995 }
1996
1997 /// Records every upload (kind, k, n, bytes) and keeps the matrices for host matmuls.
1998 #[derive(Default)]
1999 pub struct RecordingUploader {
2000 pub uploads: Mutex<Vec<(&'static str, usize, usize, usize)>>,
2001 pub matrices: Mutex<Vec<Arc<HostMatrix>>>,
2002 /// Offer a host-computed device router and lm_head GEMV (the real uploader offers omega's).
2003 pub device_fakes: bool,
2004 /// Offer the prefill GEMM on the FP8 tensors (host-computed, checks the row table).
2005 pub gemm_fakes: bool,
2006 pub dev: Arc<Mutex<FakeDevice>>,
2007 }
2008
2009 /// What the fake router "left on the device" for the next grouped launch.
2010 #[derive(Debug, Default)]
2011 pub struct FakeDevice {
2012 pub post: Vec<f32>,
2013 pub ids: Vec<u32>,
2014 pub routes: usize,
2015 pub grouped_dev_calls: usize,
2016 pub gemv_calls: usize,
2017 pub gemm_calls: usize,
2018 pub gemm_rows: usize,
2019 }
2020
2021 pub const FAKE_X_VA: u64 = 0xA000;
2022 pub const FAKE_TAB_VA: u64 = 0xB000;
2023
2024 /// Host router with the device router's contract: RMSNorm, router logits over the bf16 gate,
2025 /// top-k with renormalised weights; the normed row and the chosen ids stay in `FakeDevice`.
2026 #[derive(Debug)]
2027 pub struct FakeRouter {
2028 pub dev: Arc<Mutex<FakeDevice>>,
2029 pub experts: usize,
2030 pub hidden: usize,
2031 pub layers: Mutex<Vec<(Vec<f32>, Vec<f32>)>>,
2032 pub directories: Mutex<Vec<usize>>,
2033 }
2034
2035 impl DeviceRouter for FakeRouter {
2036 fn set_layer(&self, layer: usize, gate_bf16: &[u16], norm_w: &[f32]) -> Result<(), String> {
2037 assert_eq!(gate_bf16.len(), self.experts * self.hidden);
2038 let gate: Vec<f32> = gate_bf16.iter().map(|&b| bf16_to_f32(b)).collect();
2039 let mut l = self.layers.lock().unwrap();
2040 assert_eq!(l.len(), layer, "layers are set in order");
2041 l.push((gate, norm_w.to_vec()));
2042 Ok(())
2043 }
2044 fn set_directory(&self, layer: usize, gu: &[u64], dn: &[u64]) -> Result<(), String> {
2045 assert_eq!((gu.len(), dn.len()), (2 * self.experts, 2 * self.experts));
2046 // tensor_entry of expert x is (x + 1, 0): the directory must list them in order. A paged
2047 // load (Expert Ribbon) sets the fixed placeholder instead: its tables are never read.
2048 let placeholder = super::ribbon::directory_placeholder(self.experts);
2049 assert!(
2050 (gu == placeholder.as_slice() && dn == placeholder.as_slice())
2051 || gu
2052 .chunks(2)
2053 .enumerate()
2054 .all(|(x, p)| p == [x as u64 + 1, 0])
2055 );
2056 self.directories.lock().unwrap().push(layer);
2057 Ok(())
2058 }
2059 fn route(
2060 &self,
2061 layer: usize,
2062 x: &[f32],
2063 eps: f32,
2064 ids: &mut [u32],
2065 weights: &mut [f32],
2066 ) -> Result<(u64, RouteAddrs), String> {
2067 let l = self.layers.lock().unwrap();
2068 let (gate, norm) = &l[layer];
2069 let mut post = vec![0.0f32; self.hidden];
2070 rmsnorm(x, norm, eps, &mut post);
2071 let logits: Vec<f32> = (0..self.experts)
2072 .map(|e| {
2073 gate[e * self.hidden..(e + 1) * self.hidden]
2074 .iter()
2075 .zip(&post)
2076 .map(|(a, b)| a * b)
2077 .sum()
2078 })
2079 .collect();
2080 let plan = MoeBatchPlan::from_logits(&logits, 1, self.experts, ids.len())
2081 .map_err(|e| e.to_string())?;
2082 ids.copy_from_slice(&plan.topk_experts);
2083 weights.copy_from_slice(&plan.topk_weights);
2084 let mut d = self.dev.lock().unwrap();
2085 d.post = post;
2086 d.ids = plan.topk_experts;
2087 d.routes += 1;
2088 Ok((
2089 0,
2090 RouteAddrs {
2091 x_va: FAKE_X_VA,
2092 tab_gu_va: FAKE_TAB_VA,
2093 },
2094 ))
2095 }
2096 fn read_post(&self, out: &mut [f32]) -> Result<(), String> {
2097 out.copy_from_slice(&self.dev.lock().unwrap().post);
2098 Ok(())
2099 }
2100 }
2101
2102 /// `[vocab][hidden]` bf16 rows on the host; f32 dot products.
2103 #[derive(Debug)]
2104 pub struct FakeLmHead {
2105 pub dev: Arc<Mutex<FakeDevice>>,
2106 pub n: usize,
2107 pub k: usize,
2108 pub bits: Vec<u16>,
2109 }
2110
2111 impl LmHeadGemv for FakeLmHead {
2112 fn logits_f32(&self, hidden: &[f32], out: &mut [f32]) -> Result<u64, String> {
2113 assert_eq!((hidden.len(), out.len()), (self.k, self.n));
2114 for (r, o) in out.iter_mut().enumerate() {
2115 *o = self.bits[r * self.k..(r + 1) * self.k]
2116 .iter()
2117 .zip(hidden)
2118 .map(|(&w, &x)| bf16_to_f32(w) * x)
2119 .sum();
2120 }
2121 self.dev.lock().unwrap().gemv_calls += 1;
2122 Ok(0)
2123 }
2124 }
2125
2126 /// Exact host FP8 GEMV (`e4m3(w) * bf16(scale)` in f32) over the checkpoint bytes, the
2127 /// oracle the chip path is measured against in `own30b_check` and the fake for host tests.
2128 #[derive(Debug)]
2129 pub struct HostFp8 {
2130 pub experts: usize,
2131 pub n: usize,
2132 pub k: usize,
2133 pub w: Vec<u8>,
2134 pub scales: Vec<u16>,
2135 /// Set by the uploader when it offers the fake router: serves `tensor_entry` / `grouped_dev`.
2136 pub dev: Option<Arc<Mutex<FakeDevice>>>,
2137 /// Set by the uploader when it offers the prefill GEMM: counts the calls and rows.
2138 pub gemm: Option<Arc<Mutex<FakeDevice>>>,
2139 }
2140
2141 impl Fp8Gemv for HostFp8 {
2142 fn has_gemm(&self) -> bool {
2143 self.gemm.is_some()
2144 }
2145 fn gemm_f32(
2146 &self,
2147 expert_ids: &[u32],
2148 token_rows: &[u32],
2149 x: &[f32],
2150 y: &mut [f32],
2151 ) -> Result<u64, String> {
2152 let dev = self.gemm.as_ref().ok_or_else(|| "no gemm".to_string())?;
2153 let (m, k, n) = (expert_ids.len(), self.k, self.n);
2154 assert_eq!(token_rows.len(), m);
2155 assert_eq!(y.len(), m * n);
2156 assert!(
2157 expert_ids.windows(2).all(|w| w[0] <= w[1]),
2158 "the row table must be sorted by expert"
2159 );
2160 let x_rows = x.len() / k;
2161 for (i, &tr) in token_rows.iter().enumerate() {
2162 assert!((tr as usize) < x_rows);
2163 self.grouped_f32(
2164 &expert_ids[i..=i],
2165 &x[tr as usize * k..(tr as usize + 1) * k],
2166 &mut y[i * n..(i + 1) * n],
2167 )?;
2168 }
2169 let mut d = dev.lock().unwrap();
2170 d.gemm_calls += 1;
2171 d.gemm_rows += m;
2172 Ok(0)
2173 }
2174 fn tensor_entry(&self, expert: usize) -> Result<(u64, u64), String> {
2175 self.dev
2176 .as_ref()
2177 .map(|_| (expert as u64 + 1, 0))
2178 .ok_or_else(|| "no device".to_string())
2179 }
2180 fn grouped_dev(
2181 &self,
2182 groups: usize,
2183 tab_va: u64,
2184 x_va: u64,
2185 y: &mut [f32],
2186 ) -> Result<u64, String> {
2187 let dev = self.dev.as_ref().ok_or_else(|| "no device".to_string())?;
2188 assert_eq!(
2189 (tab_va, x_va),
2190 (FAKE_TAB_VA, FAKE_X_VA),
2191 "the engine must pass the router's addresses"
2192 );
2193 let (ids, post) = {
2194 let mut d = dev.lock().unwrap();
2195 d.grouped_dev_calls += 1;
2196 (d.ids.clone(), d.post.clone())
2197 };
2198 assert_eq!(ids.len(), groups);
2199 self.grouped_f32(&ids, &post, y)
2200 }
2201
2202 fn experts(&self) -> usize {
2203 self.experts
2204 }
2205 fn n(&self) -> usize {
2206 self.n
2207 }
2208 fn k(&self) -> usize {
2209 self.k
2210 }
2211 fn grouped_f32(&self, ids: &[u32], x: &[f32], y: &mut [f32]) -> Result<u64, String> {
2212 let (n, k) = (self.n, self.k);
2213 let kb = k / FP8_BLOCK;
2214 let lut = fp8_table();
2215 assert!(x.len() == k || x.len() == ids.len() * k);
2216 assert_eq!(y.len(), ids.len() * n);
2217 for (g, &id) in ids.iter().enumerate() {
2218 let id = id as usize;
2219 assert!(id < self.experts);
2220 let xr = if x.len() == k {
2221 x
2222 } else {
2223 &x[g * k..(g + 1) * k]
2224 };
2225 let w = &self.w[id * n * k..(id + 1) * n * k];
2226 let s = &self.scales[id * (n / FP8_BLOCK) * kb..(id + 1) * (n / FP8_BLOCK) * kb];
2227 for r in 0..n {
2228 let mut acc = 0.0f32;
2229 for c in 0..k {
2230 acc += lut[w[r * k + c] as usize]
2231 * bf16_to_f32(s[(r / FP8_BLOCK) * kb + c / FP8_BLOCK])
2232 * xr[c];
2233 }
2234 y[g * n + r] = acc;
2235 }
2236 }
2237 Ok(0)
2238 }
2239 }
2240
2241 impl ModelUploader for RecordingUploader {
2242 fn upload_dense(
2243 &self,
2244 k: usize,
2245 n: usize,
2246 bits: &[u16],
2247 ) -> Result<Arc<dyn DenseMatmul>, String> {
2248 assert_eq!(bits.len(), k * n);
2249 self.uploads
2250 .lock()
2251 .unwrap()
2252 .push(("dense", k, n, bits.len() * 2));
2253 let m = Arc::new(HostMatrix {
2254 k,
2255 n,
2256 bits: bits.to_vec(),
2257 });
2258 self.matrices.lock().unwrap().push(m.clone());
2259 Ok(m)
2260 }
2261 fn upload_experts(
2262 &self,
2263 k: usize,
2264 n: usize,
2265 bits: &[u16],
2266 ) -> Result<Arc<dyn ExpertMatmul>, String> {
2267 assert_eq!(bits.len(), k * n);
2268 self.uploads
2269 .lock()
2270 .unwrap()
2271 .push(("experts", k, n, bits.len() * 2));
2272 let m = Arc::new(HostMatrix {
2273 k,
2274 n,
2275 bits: bits.to_vec(),
2276 });
2277 self.matrices.lock().unwrap().push(m.clone());
2278 Ok(m)
2279 }
2280 fn upload_fp8(
2281 &self,
2282 experts: usize,
2283 n: usize,
2284 k: usize,
2285 w: &[u8],
2286 scales: &[u16],
2287 ) -> Result<Arc<dyn Fp8Gemv>, String> {
2288 assert_eq!(w.len(), experts * n * k);
2289 assert_eq!(scales.len(), experts * (n / FP8_BLOCK) * (k / FP8_BLOCK));
2290 self.uploads
2291 .lock()
2292 .unwrap()
2293 .push(("fp8", experts * n, k, w.len() + scales.len() * 4));
2294 Ok(Arc::new(HostFp8 {
2295 experts,
2296 n,
2297 k,
2298 w: w.to_vec(),
2299 scales: scales.to_vec(),
2300 dev: self.device_fakes.then(|| self.dev.clone()),
2301 gemm: self.gemm_fakes.then(|| self.dev.clone()),
2302 }))
2303 }
2304 fn new_router(
2305 &self,
2306 config: &Qwen3MoeConfig,
2307 ) -> Result<Option<Arc<dyn DeviceRouter>>, String> {
2308 Ok(self.device_fakes.then(|| {
2309 Arc::new(FakeRouter {
2310 dev: self.dev.clone(),
2311 experts: config.experts,
2312 hidden: config.hidden,
2313 layers: Mutex::new(Vec::new()),
2314 directories: Mutex::new(Vec::new()),
2315 }) as Arc<dyn DeviceRouter>
2316 }))
2317 }
2318 fn upload_lm_head_gemv(
2319 &self,
2320 n: usize,
2321 k: usize,
2322 bits: &[u16],
2323 ) -> Result<Option<Arc<dyn LmHeadGemv>>, String> {
2324 assert_eq!(bits.len(), n * k);
2325 Ok(self.device_fakes.then(|| {
2326 Arc::new(FakeLmHead {
2327 dev: self.dev.clone(),
2328 n,
2329 k,
2330 bits: bits.to_vec(),
2331 }) as Arc<dyn LmHeadGemv>
2332 }))
2333 }
2334 }
2335}
2336
2337#[cfg(test)]
2338mod loader_tests {
2339 use super::test_support::*;
2340 use super::*;
2341 use crate::qwen3_moe::fp8_e4m3fn_to_f32;
2342
2343 const REAL_CONFIG: &str = r#"{"architectures":["Qwen3MoeForCausalLM"],"bos_token_id":151643,"decoder_sparse_step":1,"eos_token_id":151645,"head_dim":128,"hidden_size":2048,"max_position_embeddings":262144,"mlp_only_layers":[],"model_type":"qwen3_moe","moe_intermediate_size":768,"norm_topk_prob":true,"num_attention_heads":32,"num_experts":128,"num_experts_per_tok":8,"num_hidden_layers":48,"num_key_value_heads":4,"rms_norm_eps":0.000001,"rope_theta":10000000,"tie_word_embeddings":false,"vocab_size":151936}"#;
2344
2345 #[test]
2346 fn real_config_parses_and_sizes_match_the_design() {
2347 let c = Qwen3MoeConfig::from_json(REAL_CONFIG).unwrap();
2348 assert_eq!(
2349 (c.layers, c.hidden, c.q_heads, c.kv_heads, c.head_dim),
2350 (48, 2048, 32, 4, 128)
2351 );
2352 assert_eq!(
2353 (c.experts, c.top_k, c.moe_intermediate, c.vocab),
2354 (128, 8, 768, 151936)
2355 );
2356 assert_eq!(c.eos_token_ids, vec![151645]);
2357 assert_eq!(c.qkv_n(), 5120);
2358 assert_eq!(c.gate_up_n(), 196608);
2359 assert_eq!(c.down_n(), 262144);
2360 // Design section 0: experts 48 x 1.21 GB, attention 1.8 GB, lm_head 0.62 GB: about 60.4 GB.
2361 let layer = c.layer_resident_bytes();
2362 assert_eq!(
2363 layer,
2364 2 * (2048 * 5120 + 4096 * 2048 + 2048 * 196608 + 768 * 262144)
2365 );
2366 let total = c.model_resident_bytes();
2367 assert!((60.0e9..61.0e9).contains(&(total as f64)), "{total}");
2368 // bf16 bytes per generated token: about 6.1 GB (design section 0).
2369 let per_tok = c.bytes_per_token_bf16() as f64;
2370 assert!((6.0e9..6.2e9).contains(&per_tok), "{per_tok}");
2371 }
2372
2373 #[test]
2374 fn config_refuses_shapes_stage_a_cannot_run() {
2375 let mut c = Qwen3MoeConfig::from_json(REAL_CONFIG).unwrap();
2376 c.head_dim = 64;
2377 assert!(c.validate().is_err());
2378 let mut c = Qwen3MoeConfig::from_json(REAL_CONFIG).unwrap();
2379 c.experts = 129;
2380 assert!(c.validate().unwrap_err().contains("down"));
2381 let mut c = Qwen3MoeConfig::from_json(REAL_CONFIG).unwrap();
2382 c.norm_topk_prob = false;
2383 assert!(c.validate().is_err());
2384 assert!(Qwen3MoeConfig::from_json(&REAL_CONFIG.replace("qwen3_moe", "qwen3")).is_err());
2385 }
2386
2387 #[test]
2388 fn expert_windows_start_on_a_column_tile_and_stay_inside_the_tensor() {
2389 let c = Qwen3MoeConfig::from_json(REAL_CONFIG).unwrap();
2390 for e in 0..c.experts {
2391 let gu = c.gate_up_col0(e);
2392 let dn = c.down_col0(e);
2393 assert_eq!(gu % WINDOW_TILE, 0);
2394 assert_eq!(dn % WINDOW_TILE, 0);
2395 assert!(aien_omega_moe::check_window(c.gate_up_n(), gu, c.gate_up_cols()).is_ok());
2396 assert!(aien_omega_moe::check_window(c.down_n(), dn, c.down_cols()).is_ok());
2397 }
2398 assert_eq!(c.gate_up_col0(5), 7680);
2399 assert_eq!(c.down_col0(127), 260096);
2400 assert_eq!(c.down_col0(127) + c.down_cols(), MAX_RESIDENT_N);
2401 // Up half of expert e sits i columns after its gate half.
2402 assert_eq!(c.gate_up_col0(3) + c.moe_intermediate, 3 * 1536 + 768);
2403 }
2404
2405 #[test]
2406 fn dequant_matches_the_exact_conversion_transposed_and_rounded() {
2407 // rows 200 (not a block multiple: 2 row blocks), k 256 (2 blocks).
2408 let (rows, k) = (200usize, 256usize);
2409 let w: Vec<u8> = (0..rows * k)
2410 .map(|i| ((i * 37 + 11) % 256) as u8)
2411 .map(|b| if b & 0x7f == 0x7f { 0 } else { b })
2412 .collect();
2413 let scales: Vec<u16> = (0..2 * 2)
2414 .map(|i| f32_to_bf16(0.5 + i as f32 * 0.25))
2415 .collect();
2416 let dst_n = 208;
2417 let mut dst = vec![0u16; k * dst_n];
2418 dequant_fp8_sources_to_bf16_cols(
2419 &[Fp8Source {
2420 weights: &w,
2421 scales: &scales,
2422 rows,
2423 col0: 8,
2424 }],
2425 k,
2426 &mut dst,
2427 dst_n,
2428 )
2429 .unwrap();
2430 for r in 0..rows {
2431 for kk in 0..k {
2432 let s = bf16_to_f32(scales[(r / 128) * 2 + kk / 128]);
2433 let want = f32_to_bf16(fp8_e4m3fn_to_f32(w[r * k + kk]) * s);
2434 assert_eq!(dst[kk * dst_n + 8 + r], want, "r={r} k={kk}");
2435 }
2436 // Spot values: the exact table says 0x38 is 1.0 and 0xBC is -1.5.
2437 }
2438 assert_eq!(bf16_to_f32(f32_to_bf16(fp8_e4m3fn_to_f32(0x38))), 1.0);
2439 assert_eq!(fp8_e4m3fn_to_f32(0xBC), -1.5);
2440 // Untouched columns stay zero.
2441 assert!(dst
2442 .iter()
2443 .enumerate()
2444 .filter(|(i, _)| i % dst_n < 8)
2445 .all(|(_, &v)| v == 0));
2446 }
2447
2448 #[test]
2449 fn dequant_refuses_nan_codes_and_bad_shapes() {
2450 let w = vec![0x7fu8; 128];
2451 let s = vec![f32_to_bf16(1.0)];
2452 let mut dst = vec![0u16; 128 * 8];
2453 let err = dequant_fp8_sources_to_bf16_cols(
2454 &[Fp8Source {
2455 weights: &w,
2456 scales: &s,
2457 rows: 1,
2458 col0: 0,
2459 }],
2460 128,
2461 &mut dst,
2462 8,
2463 )
2464 .unwrap_err();
2465 assert!(err.contains("NaN"), "{err}");
2466 let w = vec![0u8; 128];
2467 let err = dequant_fp8_sources_to_bf16_cols(
2468 &[Fp8Source {
2469 weights: &w,
2470 scales: &s,
2471 rows: 1,
2472 col0: 8,
2473 }],
2474 128,
2475 &mut dst,
2476 8,
2477 )
2478 .unwrap_err();
2479 assert!(err.contains("past dst_n"), "{err}");
2480 let err = dequant_fp8_sources_to_bf16_cols(
2481 &[Fp8Source {
2482 weights: &w,
2483 scales: &[],
2484 rows: 1,
2485 col0: 0,
2486 }],
2487 128,
2488 &mut dst,
2489 8,
2490 )
2491 .unwrap_err();
2492 assert!(err.contains("scales"), "{err}");
2493 }
2494
2495 #[test]
2496 fn loader_uploads_the_right_shapes_bytes_and_values() {
2497 let c = tiny_config();
2498 let mut src = MemorySource::for_config(&c);
2499 let up = RecordingUploader::default();
2500 let mut seen = Vec::new();
2501 let (w, report) =
2502 load_qwen3_moe_omega_from(&c, &mut src, &up, &mut |s| seen.push(s.to_string()))
2503 .unwrap();
2504 let uploads = up.uploads.lock().unwrap().clone();
2505 // Per layer: qkv, o, gate_up, down; then lm_head.
2506 assert_eq!(uploads.len(), 4 * c.layers + 1);
2507 for l in 0..c.layers {
2508 assert_eq!(
2509 uploads[4 * l],
2510 ("dense", c.hidden, c.qkv_n(), 2 * c.hidden * c.qkv_n())
2511 );
2512 assert_eq!(
2513 uploads[4 * l + 1],
2514 ("dense", c.q_dim(), c.hidden, 2 * c.q_dim() * c.hidden)
2515 );
2516 assert_eq!(
2517 uploads[4 * l + 2],
2518 (
2519 "experts",
2520 c.hidden,
2521 c.gate_up_n(),
2522 2 * c.hidden * c.gate_up_n()
2523 )
2524 );
2525 assert_eq!(
2526 uploads[4 * l + 3],
2527 (
2528 "experts",
2529 c.moe_intermediate,
2530 c.down_n(),
2531 2 * c.moe_intermediate * c.down_n()
2532 )
2533 );
2534 }
2535 assert_eq!(
2536 uploads[4 * c.layers],
2537 ("dense", c.hidden, c.vocab, 2 * c.hidden * c.vocab)
2538 );
2539 let total: usize = uploads.iter().map(|u| u.3).sum();
2540 assert_eq!(total, c.model_resident_bytes());
2541 assert_eq!(report.resident_bytes, total);
2542 assert_eq!(seen.len(), uploads.len());
2543 assert_eq!(w.host_bytes(), report.host_bytes);
2544 assert_eq!(w.embed_bf16.len(), c.vocab * c.hidden);
2545 assert_eq!(w.layers[1].router.len(), c.experts * c.hidden);
2546
2547 // Values: expert 2's up projection of layer 1, row 5, column k=130 must sit at
2548 // gate_up[k=130][col0(2) + i + 5], equal to the exact dequant rounded to bf16.
2549 let mats = up.matrices.lock().unwrap();
2550 let gate_up = &mats[4 + 2];
2551 let (upw, rows, cols) = src.fp8_f32("model.layers.1.mlp.experts.2.up_proj.weight");
2552 assert_eq!((rows, cols), (c.moe_intermediate, c.hidden));
2553 let col = c.gate_up_col0(2) + c.moe_intermediate + 5;
2554 assert_eq!(
2555 gate_up.bits[130 * c.gate_up_n() + col],
2556 f32_to_bf16(upw[5 * cols + 130])
2557 );
2558 // down of expert 3, layer 0: W[h=7][i=100] at down[k=100][col0(3) + 7].
2559 let down = &mats[3];
2560 let (dw, _, dcols) = src.fp8_f32("model.layers.0.mlp.experts.3.down_proj.weight");
2561 assert_eq!(
2562 down.bits[100 * c.down_n() + c.down_col0(3) + 7],
2563 f32_to_bf16(dw[7 * dcols + 100])
2564 );
2565 // v_proj row 3 of layer 0 lands at qkv column q_dim + kv_dim + 3.
2566 let qkv = &mats[0];
2567 let (vw, _, vcols) = src.fp8_f32("model.layers.0.self_attn.v_proj.weight");
2568 assert_eq!(
2569 qkv.bits[77 * c.qkv_n() + c.q_dim() + c.kv_dim() + 3],
2570 f32_to_bf16(vw[3 * vcols + 77])
2571 );
2572 // o_proj: W[h=9][qd=200] at o[k=200][9].
2573 let o = &mats[1];
2574 let (ow, _, ocols) = src.fp8_f32("model.layers.0.self_attn.o_proj.weight");
2575 assert_eq!(o.bits[200 * c.hidden + 9], f32_to_bf16(ow[9 * ocols + 200]));
2576 // lm_head [vocab][h] transposed: row 10, k 33 at lm_head[33][10].
2577 let lm = &mats[mats.len() - 1];
2578 let (_, _, raw) = &src.tensors["lm_head.weight"];
2579 let want = u16::from_le_bytes([
2580 raw[(10 * c.hidden + 33) * 2],
2581 raw[(10 * c.hidden + 33) * 2 + 1],
2582 ]);
2583 assert_eq!(lm.bits[33 * c.vocab + 10], want);
2584 // Embedding row is the bf16 row widened.
2585 let (_, _, eraw) = &src.tensors["model.embed_tokens.weight"];
2586 let e0 = u16::from_le_bytes([eraw[(5 * c.hidden) * 2], eraw[(5 * c.hidden) * 2 + 1]]);
2587 assert_eq!(w.embed_row(5)[0], bf16_to_f32(e0));
2588 }
2589
2590 #[test]
2591 fn loader_transient_budget_is_one_layer_plus_embedding() {
2592 let c = Qwen3MoeConfig::from_json(REAL_CONFIG).unwrap();
2593 let t = loader_transient_bytes(&c) as f64;
2594 // bits 805 MB + fp8 403 MB + scales 1.5 MB + raw lm_head 622 MB: about 1.83 GB.
2595 assert!((1.7e9..2.0e9).contains(&t), "{t}");
2596 // With the fake uploader the process holds the matrices itself, so only the report's
2597 // bookkeeping is checked here; the real-load assertion is in own30b_check.
2598 assert!(peak_rss_bytes().is_some_and(|b| b > 0));
2599 }
2600}
2601
2602// ===========================================================================
2603// Cut 3: the Stage A forward.
2604// ===========================================================================
2605
2606use crate::qwen3_coder::rmsnorm_per_head;
2607use crate::tensor::{
2608 apply_rope, kernel_online_attention, rmsnorm, scaled_dot_product_attention_single,
2609};
2610use crate::transformer_backend::{decode_sampling_seed, sample_with_params};
2611use aien_abi_core::SamplingParams;
2612
2613/// Model-independent KV shape (ADR 0004 section 2.1). Produced by a model config, consumed by
2614/// every cache constructor and by persistence. bf16 elements, `HostPagedPoolV1` payload (ADR 0003).
2615#[derive(Clone, Copy, Debug, PartialEq)]
2616pub struct KvGeometry {
2617 pub layers: usize,
2618 /// Attend output width; the fused kernel's `fits` check.
2619 pub q_heads: usize,
2620 pub kv_heads: usize,
2621 pub head_dim: usize,
2622 /// The fused cache applies RoPE on the chip.
2623 pub rope_theta: f32,
2624 /// [`KV_BLOCK_SIZE`].
2625 pub block_size: usize,
2626}
2627
2628impl KvGeometry {
2629 /// The byte geometry of one `HostPagedPoolV1` block of this shape.
2630 pub fn pool_block(&self) -> kvio::PoolBlockGeometry {
2631 kvio::PoolBlockGeometry::for_geometry(self)
2632 }
2633}
2634
2635impl From<&Qwen3MoeConfig> for KvGeometry {
2636 fn from(c: &Qwen3MoeConfig) -> Self {
2637 Self {
2638 layers: c.layers,
2639 q_heads: c.q_heads,
2640 kv_heads: c.kv_heads,
2641 head_dim: c.head_dim,
2642 rope_theta: c.rope_theta,
2643 block_size: KV_BLOCK_SIZE,
2644 }
2645 }
2646}
2647
2648/// The pool caches index blocks by [`KV_BLOCK_SIZE`]; a geometry with another size is refused.
2649fn check_block_size(who: &str, g: &KvGeometry) -> Result<(), String> {
2650 if g.block_size != KV_BLOCK_SIZE {
2651 return Err(format!(
2652 "{who}: block size {} is not this cache's layout ({KV_BLOCK_SIZE})",
2653 g.block_size
2654 ));
2655 }
2656 Ok(())
2657}
2658
2659/// The model-independent half of a KV cache (ADR 0004 section 2.1): what the generation
2660/// controller may see. Split out of [`KvAttention`] as its supertrait.
2661pub trait KvStore: Send {
2662 /// The shape this cache was built for.
2663 fn geometry(&self) -> KvGeometry;
2664 /// Tokens the cache can hold.
2665 fn capacity(&self) -> usize;
2666 /// Positions held in every layer (the smallest per-layer filled count).
2667 fn len(&self) -> usize;
2668 /// Whether no layer holds any position.
2669 fn is_empty(&self) -> bool {
2670 self.len() == 0
2671 }
2672 /// "split" (host norm/rope, `append` + `attend`), "host-pool" (the host bf16 pool) or "fused"
2673 /// (one launch per layer).
2674 fn path_name(&self) -> &'static str {
2675 "split"
2676 }
2677 /// Drops every position at or past `len` (the next append is at `len`). Prefix reuse;
2678 /// `truncate(0)` empties the cache (what `reset` did, for all four caches).
2679 fn truncate(&mut self, len: usize);
2680 /// Persistent KV park (sc#505): the K/V of positions `start..start + len` as the
2681 /// `HostPagedPoolV1` payload of [`kvio`] (`start` a multiple of [`KV_BLOCK_SIZE`]; every
2682 /// layer must hold those positions). `None`: this cache cannot export, nothing is parked.
2683 fn export_blocks(&mut self, _start: usize, _len: usize) -> Option<Result<Vec<u8>, String>> {
2684 None
2685 }
2686 /// Persistent KV restore (sc#505): writes a [`kvio`] payload for positions `start..start +
2687 /// len`; every layer must hold exactly `0..start` before the call and holds `0..start + len`
2688 /// after it. `None`: this cache cannot import, the caller prefills instead. On `Err` the
2689 /// cache may hold part of the payload: the caller must reset it.
2690 fn import_blocks(
2691 &mut self,
2692 _start: usize,
2693 _len: usize,
2694 _bytes: &[u8],
2695 ) -> Option<Result<(), String>> {
2696 None
2697 }
2698}
2699
2700/// The KV cache of one sequence plus the attention over it. Omega's paged bf16 pool in
2701/// production; a host f32 cache in tests. Model-private: the controller sees only [`KvStore`].
2702pub trait KvAttention: KvStore {
2703 /// Stores the roped key and the value of position `pos` for `layer`.
2704 fn append(&mut self, layer: usize, pos: usize, k: &[f32], v: &[f32]) -> Result<(), String>;
2705 /// `out[q_heads x head_dim]` = attention of the (unscaled) query over positions `0..context_len`.
2706 fn attend(
2707 &mut self,
2708 layer: usize,
2709 q: &[f32],
2710 context_len: usize,
2711 out: &mut [f32],
2712 ) -> Result<u64, String>;
2713 /// Whether the chip reads the pool in place (no per-call staging).
2714 fn resident(&self) -> bool;
2715 /// The fused path (OWN-30B cut 9): from the raw fused q|k|v projection row of position
2716 /// `pos`, do the q/k per-head norms, RoPE, the K/V append and the attention over
2717 /// `0..=pos` on the chip in one launch, writing `out[q_heads x head_dim]`. `None` means
2718 /// this cache has no fused kernel and the engine runs the split path (`append` + `attend`).
2719 fn fused_attend(
2720 &mut self,
2721 _layer: usize,
2722 _pos: usize,
2723 _qkv: &[f32],
2724 _eps: f32,
2725 _out: &mut [f32],
2726 ) -> Option<Result<u64, String>> {
2727 None
2728 }
2729 /// omega's fused cache behind this attention, if any (the whole-prompt prefill drives it).
2730 fn fused_kv(&mut self) -> Option<&mut crate::qwen3_moe_omega_dattn::OmegaFusedKv> {
2731 None
2732 }
2733 /// The one-list decode graph (OWN-30B L2 cut 2): the omega C handle of the KV cache
2734 /// (`OmegaGpuDecodeAttnCache *`) after checking every layer holds exactly `0..pos`. `None`:
2735 /// this cache cannot take part in the graph.
2736 fn dgraph_cache(&mut self, _pos: usize) -> Option<Result<*mut std::ffi::c_void, String>> {
2737 None
2738 }
2739 /// The graph wrote position `pos` of every layer.
2740 fn dgraph_commit(&mut self, _pos: usize) {}
2741}
2742
2743/// Positions `start..start + len` of a bf16 `aien_kv_cache` pool (blocks `0..n` in order, block
2744/// size [`KV_BLOCK_SIZE`]) as a [`kvio`] payload: the pool layout is the payload layout, so the
2745/// blocks are copied as they are and the rows past `len` in the last block are zeroed in the copy.
2746fn pool_export(
2747 pool: &aien_kv_cache::UnifiedKvTensorPool,
2748 filled: &[usize],
2749 start: usize,
2750 len: usize,
2751) -> Result<Vec<u8>, String> {
2752 let c = pool.config();
2753 let g = kvio::PoolBlockGeometry {
2754 layers: c.num_layers,
2755 kv_heads: c.num_kv_heads,
2756 head_dim: c.head_dim,
2757 block_size: c.block_size,
2758 };
2759 if c.dtype != aien_kv_cache::KvDType::Bf16 || g.block_stride() != pool.block_bytes() {
2760 return Err(format!(
2761 "kv export: pool {:?} with {} byte blocks is not the bf16 payload layout",
2762 c.dtype,
2763 pool.block_bytes()
2764 ));
2765 }
2766 if len == 0 || !start.is_multiple_of(g.block_size) {
2767 return Err(format!(
2768 "kv export {start}+{len}: start must be a multiple of {}, len non-zero",
2769 g.block_size
2770 ));
2771 }
2772 if let Some((l, f)) = filled.iter().enumerate().find(|(_, &f)| f < start + len) {
2773 return Err(format!(
2774 "kv export {start}+{len}: layer {l} holds only {f} positions"
2775 ));
2776 }
2777 let off = (start / g.block_size) * g.block_stride();
2778 let n = g.payload_len(len);
2779 if off + n > pool.total_bytes() {
2780 return Err(format!(
2781 "kv export {start}+{len}: past the pool ({} bytes)",
2782 pool.total_bytes()
2783 ));
2784 }
2785 // SAFETY: the pool owns total_bytes() readable bytes at base_ptr(); the range is checked.
2786 let mut out = unsafe { std::slice::from_raw_parts(pool.base_ptr().add(off), n) }.to_vec();
2787 kvio::zero_padding(&g, len, &mut out);
2788 Ok(out)
2789}
2790
2791/// The inverse of [`pool_export`]: writes the payload's blocks into the pool and marks
2792/// `0..start + len` filled in every layer.
2793fn pool_import(
2794 pool: &mut aien_kv_cache::UnifiedKvTensorPool,
2795 filled: &mut [usize],
2796 start: usize,
2797 len: usize,
2798 bytes: &[u8],
2799) -> Result<(), String> {
2800 let c = pool.config();
2801 let g = kvio::PoolBlockGeometry {
2802 layers: c.num_layers,
2803 kv_heads: c.num_kv_heads,
2804 head_dim: c.head_dim,
2805 block_size: c.block_size,
2806 };
2807 if c.dtype != aien_kv_cache::KvDType::Bf16 || g.block_stride() != pool.block_bytes() {
2808 return Err(format!(
2809 "kv import: pool {:?} with {} byte blocks is not the bf16 payload layout",
2810 c.dtype,
2811 pool.block_bytes()
2812 ));
2813 }
2814 if len == 0 || !start.is_multiple_of(g.block_size) {
2815 return Err(format!(
2816 "kv import {start}+{len}: start must be a multiple of {}, len non-zero",
2817 g.block_size
2818 ));
2819 }
2820 if let Some((l, f)) = filled.iter().enumerate().find(|(_, &f)| f != start) {
2821 return Err(format!(
2822 "kv import at {start}: layer {l} holds {f} positions"
2823 ));
2824 }
2825 kvio::check_payload(&g, len, bytes)?;
2826 let off = (start / g.block_size) * g.block_stride();
2827 if off + bytes.len() > pool.total_bytes() {
2828 return Err(format!(
2829 "kv import {start}+{len}: past the pool ({} bytes)",
2830 pool.total_bytes()
2831 ));
2832 }
2833 // SAFETY: the pool owns total_bytes() writable bytes at base_mut_ptr(); the range is checked
2834 // and `bytes` is a separate allocation.
2835 unsafe {
2836 std::ptr::copy_nonoverlapping(bytes.as_ptr(), pool.base_mut_ptr().add(off), bytes.len())
2837 };
2838 filled.iter_mut().for_each(|f| *f = start + len);
2839 Ok(())
2840}
2841
2842/// A host bf16 pool with the reference attention over the bf16 values: the same bytes as
2843/// [`OmegaPagedKv`] (append rounds to bf16 in the pool, export/import copy blocks), with no chip.
2844/// Host tests of the persistent KV path (sc#505) run the real engine over it.
2845pub struct HostPoolKv {
2846 pool: aien_kv_cache::UnifiedKvTensorPool,
2847 capacity: usize,
2848 geometry: KvGeometry,
2849 filled: Vec<usize>,
2850}
2851
2852impl HostPoolKv {
2853 pub fn new(geometry: &KvGeometry, max_context: usize) -> Result<Self, String> {
2854 check_block_size("host pool kv", geometry)?;
2855 let num_blocks = max_context.div_ceil(KV_BLOCK_SIZE).max(1);
2856 let cfg = aien_kv_cache::KvPoolConfig::for_model(
2857 num_blocks,
2858 KV_BLOCK_SIZE,
2859 geometry.layers,
2860 geometry.kv_heads,
2861 geometry.head_dim,
2862 aien_kv_cache::KvDType::Bf16,
2863 );
2864 Ok(Self {
2865 pool: aien_kv_cache::UnifiedKvTensorPool::allocate(cfg)?,
2866 capacity: num_blocks * KV_BLOCK_SIZE,
2867 geometry: *geometry,
2868 filled: vec![0; geometry.layers],
2869 })
2870 }
2871
2872 /// Positions held in `layer` alone (ADR 0004 test R1 checks every layer against the ledger;
2873 /// [`KvStore::len`] is only the smallest of them).
2874 pub fn layer_len(&self, layer: usize) -> usize {
2875 self.filled[layer]
2876 }
2877
2878 fn row(&self, layer: usize, pos: usize, value: bool) -> Vec<f32> {
2879 let kv_dim = self.geometry.kv_heads * self.geometry.head_dim;
2880 let off = self
2881 .pool
2882 .element_offset(pos / KV_BLOCK_SIZE, layer, value, pos % KV_BLOCK_SIZE);
2883 // SAFETY: the offset is inside the pool (pos < filled <= capacity), kv_dim bf16 values.
2884 let b = unsafe { std::slice::from_raw_parts(self.pool.base_ptr().add(off), kv_dim * 2) };
2885 b.chunks_exact(2)
2886 .map(|w| bf16_to_f32(u16::from_le_bytes([w[0], w[1]])))
2887 .collect()
2888 }
2889}
2890
2891impl KvStore for HostPoolKv {
2892 fn geometry(&self) -> KvGeometry {
2893 self.geometry
2894 }
2895 fn capacity(&self) -> usize {
2896 self.capacity
2897 }
2898 fn len(&self) -> usize {
2899 self.filled.iter().copied().min().unwrap_or(0)
2900 }
2901 fn path_name(&self) -> &'static str {
2902 "host-pool"
2903 }
2904 fn truncate(&mut self, len: usize) {
2905 for f in self.filled.iter_mut() {
2906 *f = (*f).min(len);
2907 }
2908 }
2909 fn export_blocks(&mut self, start: usize, len: usize) -> Option<Result<Vec<u8>, String>> {
2910 Some(pool_export(&self.pool, &self.filled, start, len))
2911 }
2912 fn import_blocks(
2913 &mut self,
2914 start: usize,
2915 len: usize,
2916 bytes: &[u8],
2917 ) -> Option<Result<(), String>> {
2918 Some(pool_import(
2919 &mut self.pool,
2920 &mut self.filled,
2921 start,
2922 len,
2923 bytes,
2924 ))
2925 }
2926}
2927
2928impl KvAttention for HostPoolKv {
2929 fn append(&mut self, layer: usize, pos: usize, k: &[f32], v: &[f32]) -> Result<(), String> {
2930 if pos != self.filled[layer] || pos >= self.capacity {
2931 return Err(format!(
2932 "host pool kv: append at {pos}, have {} (capacity {})",
2933 self.filled[layer], self.capacity
2934 ));
2935 }
2936 self.pool
2937 .write_token_kv(pos / KV_BLOCK_SIZE, layer, pos % KV_BLOCK_SIZE, k, v);
2938 self.filled[layer] = pos + 1;
2939 Ok(())
2940 }
2941 fn attend(
2942 &mut self,
2943 layer: usize,
2944 q: &[f32],
2945 context_len: usize,
2946 out: &mut [f32],
2947 ) -> Result<u64, String> {
2948 if context_len > self.filled[layer] {
2949 return Err(format!(
2950 "host pool kv: attend over {context_len}, only {} stored",
2951 self.filled[layer]
2952 ));
2953 }
2954 let keys: Vec<Vec<f32>> = (0..context_len)
2955 .map(|p| self.row(layer, p, false))
2956 .collect();
2957 let values: Vec<Vec<f32>> = (0..context_len).map(|p| self.row(layer, p, true)).collect();
2958 // Oracle A: the chip's f32 online softmax, not the f64 reference softmax.
2959 kernel_online_attention(
2960 q,
2961 &keys,
2962 &values,
2963 self.geometry.q_heads,
2964 self.geometry.kv_heads,
2965 self.geometry.head_dim,
2966 out,
2967 );
2968 Ok(0)
2969 }
2970 fn resident(&self) -> bool {
2971 false
2972 }
2973}
2974
2975/// Host f32 cache with the reference attention (tests, and the oracle side of parity runs).
2976pub struct HostKv {
2977 geometry: KvGeometry,
2978 capacity: usize,
2979 keys: Vec<Vec<Vec<f32>>>,
2980 values: Vec<Vec<Vec<f32>>>,
2981}
2982
2983impl HostKv {
2984 pub fn new(geometry: &KvGeometry, capacity: usize) -> Self {
2985 Self {
2986 geometry: *geometry,
2987 capacity,
2988 keys: vec![Vec::new(); geometry.layers],
2989 values: vec![Vec::new(); geometry.layers],
2990 }
2991 }
2992}
2993
2994impl KvStore for HostKv {
2995 fn geometry(&self) -> KvGeometry {
2996 self.geometry
2997 }
2998 fn capacity(&self) -> usize {
2999 self.capacity
3000 }
3001 fn len(&self) -> usize {
3002 self.keys.iter().map(Vec::len).min().unwrap_or(0)
3003 }
3004 fn truncate(&mut self, len: usize) {
3005 for (k, v) in self.keys.iter_mut().zip(self.values.iter_mut()) {
3006 k.truncate(len);
3007 v.truncate(len);
3008 }
3009 }
3010}
3011
3012impl KvAttention for HostKv {
3013 fn append(&mut self, layer: usize, pos: usize, k: &[f32], v: &[f32]) -> Result<(), String> {
3014 if pos != self.keys[layer].len() || pos >= self.capacity {
3015 return Err(format!(
3016 "host kv: append at {pos}, have {} (capacity {})",
3017 self.keys[layer].len(),
3018 self.capacity
3019 ));
3020 }
3021 self.keys[layer].push(k.to_vec());
3022 self.values[layer].push(v.to_vec());
3023 Ok(())
3024 }
3025 fn attend(
3026 &mut self,
3027 layer: usize,
3028 q: &[f32],
3029 context_len: usize,
3030 out: &mut [f32],
3031 ) -> Result<u64, String> {
3032 scaled_dot_product_attention_single(
3033 q,
3034 &self.keys[layer][..context_len],
3035 &self.values[layer][..context_len],
3036 self.geometry.q_heads,
3037 self.geometry.kv_heads,
3038 self.geometry.head_dim,
3039 out,
3040 );
3041 Ok(0)
3042 }
3043 fn resident(&self) -> bool {
3044 false
3045 }
3046}
3047
3048/// Paged KV block size (tokens): the size the 8B daemon runs (`gb10_serving`), a power of two.
3049pub const KV_BLOCK_SIZE: usize = 16;
3050
3051/// Most prompt tokens one batched prefill step takes: `PREFILL_CHUNK x top_k` expert rows must
3052/// fit one grouped FP8 launch (`aien_omega_fp8::MAX_GROUPS` = 64, top_k = 8).
3053pub const PREFILL_CHUNK: usize = 8;
3054
3055/// Default prompt tokens per batched prefill step on the FP8 grouped GEMM (64 x top_k = 512 expert
3056/// rows, the size the kernel was measured at; the GEMM takes up to 128 tokens = 1024 rows).
3057pub const PREFILL_CHUNK_GEMM: usize = 64;
3058
3059/// Omega's paged bf16 KV: one sequence, blocks `0..n` in order, the pool in the engine's resident
3060/// allocation when the driver grants it (attention reads in place), a host-mapped pool otherwise.
3061pub struct OmegaPagedKv {
3062 pool: aien_kv_cache::UnifiedKvTensorPool,
3063 layout: aien_omega_gpu::OmegaGpuKvLayout,
3064 block_ids: Vec<u32>,
3065 capacity: usize,
3066 geometry: KvGeometry,
3067 resident: bool,
3068 filled: Vec<usize>,
3069}
3070
3071impl OmegaPagedKv {
3072 pub fn new(geometry: &KvGeometry, max_context: usize) -> Result<Self, String> {
3073 check_block_size("paged kv", geometry)?;
3074 let num_blocks = max_context.div_ceil(KV_BLOCK_SIZE).max(1);
3075 let cfg = aien_kv_cache::KvPoolConfig::for_model(
3076 num_blocks,
3077 KV_BLOCK_SIZE,
3078 geometry.layers,
3079 geometry.kv_heads,
3080 geometry.head_dim,
3081 aien_kv_cache::KvDType::Bf16,
3082 );
3083 let bytes = cfg.layout()?.total_bytes;
3084 let (pool, resident) = match aien_omega_gpu::resident_kv_pool_alloc(bytes) {
3085 Ok((ptr, len)) => {
3086 // SAFETY: omega owns `len` bytes at `ptr` until `resident_kv_pool_free`, which the
3087 // release callback runs exactly once; chip address == host address for this memory.
3088 let buf = unsafe {
3089 aien_kv_cache::external_default_buffer(
3090 ptr,
3091 len,
3092 ptr as u64,
3093 Box::new(aien_omega_gpu::resident_kv_pool_free),
3094 )
3095 };
3096 match buf {
3097 Ok(b) => (
3098 aien_kv_cache::UnifiedKvTensorPool::new(cfg.clone(), b)?,
3099 true,
3100 ),
3101 Err(e) => {
3102 aien_omega_gpu::resident_kv_pool_free();
3103 return Err(e);
3104 }
3105 }
3106 }
3107 Err(_) => (
3108 aien_kv_cache::UnifiedKvTensorPool::allocate(cfg.clone())?,
3109 false,
3110 ),
3111 };
3112 let d = pool.layout_desc();
3113 let layout = aien_omega_gpu::OmegaGpuKvLayout {
3114 block_stride_bytes: d.block_stride_bytes,
3115 layer_stride_bytes: d.layer_stride_bytes,
3116 kv_plane_stride_bytes: d.kv_plane_stride_bytes,
3117 token_stride_bytes: d.token_stride_bytes,
3118 head_stride_bytes: d.head_stride_bytes,
3119 pool_bytes: d.pool_bytes,
3120 num_blocks: d.num_blocks,
3121 num_layers: d.num_layers,
3122 block_size: d.block_size,
3123 };
3124 Ok(Self {
3125 pool,
3126 layout,
3127 block_ids: (0..num_blocks as u32).collect(),
3128 capacity: num_blocks * KV_BLOCK_SIZE,
3129 geometry: *geometry,
3130 resident,
3131 filled: vec![0; geometry.layers],
3132 })
3133 }
3134
3135 pub fn pool_bytes(&self) -> usize {
3136 self.pool.total_bytes()
3137 }
3138}
3139
3140impl KvStore for OmegaPagedKv {
3141 fn geometry(&self) -> KvGeometry {
3142 self.geometry
3143 }
3144 fn capacity(&self) -> usize {
3145 self.capacity
3146 }
3147 fn len(&self) -> usize {
3148 self.filled.iter().copied().min().unwrap_or(0)
3149 }
3150 fn truncate(&mut self, len: usize) {
3151 // The pool keeps its bytes; positions past `len` are rewritten by later appends.
3152 for f in self.filled.iter_mut() {
3153 *f = (*f).min(len);
3154 }
3155 }
3156 // The chip reads and writes this pool in place (GPU-uncached host-visible memory when
3157 // resident) and no launch is in flight between steps, so the host copies see the bytes the
3158 // attention reads.
3159 fn export_blocks(&mut self, start: usize, len: usize) -> Option<Result<Vec<u8>, String>> {
3160 Some(pool_export(&self.pool, &self.filled, start, len))
3161 }
3162 fn import_blocks(
3163 &mut self,
3164 start: usize,
3165 len: usize,
3166 bytes: &[u8],
3167 ) -> Option<Result<(), String>> {
3168 Some(pool_import(
3169 &mut self.pool,
3170 &mut self.filled,
3171 start,
3172 len,
3173 bytes,
3174 ))
3175 }
3176}
3177
3178impl KvAttention for OmegaPagedKv {
3179 fn append(&mut self, layer: usize, pos: usize, k: &[f32], v: &[f32]) -> Result<(), String> {
3180 if pos != self.filled[layer] || pos >= self.capacity {
3181 return Err(format!(
3182 "paged kv: append at {pos}, have {} (capacity {})",
3183 self.filled[layer], self.capacity
3184 ));
3185 }
3186 self.pool
3187 .write_token_kv(pos / KV_BLOCK_SIZE, layer, pos % KV_BLOCK_SIZE, k, v);
3188 self.filled[layer] = pos + 1;
3189 Ok(())
3190 }
3191 fn attend(
3192 &mut self,
3193 layer: usize,
3194 q: &[f32],
3195 context_len: usize,
3196 out: &mut [f32],
3197 ) -> Result<u64, String> {
3198 if context_len > self.filled[layer] {
3199 return Err(format!(
3200 "paged kv: attend over {context_len}, only {} stored",
3201 self.filled[layer]
3202 ));
3203 }
3204 let nblocks = context_len.div_ceil(KV_BLOCK_SIZE);
3205 // SAFETY: the pool owns total_bytes() readable bytes at base_ptr() for its lifetime.
3206 let bytes =
3207 unsafe { std::slice::from_raw_parts(self.pool.base_ptr(), self.pool.total_bytes()) };
3208 let info = aien_omega_gpu::paged_attention_bf16(
3209 q,
3210 bytes,
3211 &self.layout,
3212 &self.block_ids[..nblocks],
3213 context_len,
3214 layer,
3215 self.geometry.q_heads,
3216 self.geometry.kv_heads,
3217 self.geometry.head_dim,
3218 out,
3219 )
3220 .map_err(|e| {
3221 format!(
3222 "paged attention layer {layer} ctx {context_len}: {e}; {}",
3223 aien_omega_gpu::last_error()
3224 )
3225 })?;
3226 Ok(info.elapsed_ns)
3227 }
3228 fn resident(&self) -> bool {
3229 self.resident
3230 }
3231}
3232
3233/// Generation request (field for field what the HTTP door's `GenerateParams` carries).
3234#[derive(Debug, Clone, PartialEq)]
3235pub struct GenerateParams {
3236 /// Hard cap on emitted tokens; stop tokens do not count.
3237 pub max_new_tokens: usize,
3238 /// `<= 0.001` means greedy.
3239 pub temperature: f32,
3240 /// `(0, 1]`; 1.0 disables nucleus filtering.
3241 pub top_p: f32,
3242 /// 0 disables.
3243 pub top_k: usize,
3244 /// Request seed; per-step seeds are `decode_sampling_seed(seed, step)`.
3245 pub seed: u64,
3246 pub stop_token_ids: Vec<u32>,
3247}
3248
3249impl GenerateParams {
3250 pub fn greedy(max_new_tokens: usize, stop_token_ids: Vec<u32>) -> Self {
3251 Self {
3252 max_new_tokens,
3253 temperature: 0.0,
3254 top_p: 1.0,
3255 top_k: 0,
3256 seed: 0,
3257 stop_token_ids,
3258 }
3259 }
3260}
3261
3262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3263pub enum FinishReason {
3264 Stop,
3265 Length,
3266 Cancelled,
3267 /// A constraint said the output is complete (`StepRule::Finish`, ADR 0004 section 2.3).
3268 Constraint,
3269}
3270
3271#[derive(Debug, Clone, PartialEq)]
3272pub struct GenerateOutcome {
3273 pub emitted_tokens: usize,
3274 pub finish: FinishReason,
3275 pub prefill_ms: u64,
3276 pub decode_ms: u64,
3277 pub prompt_tokens: usize,
3278 /// Prompt tokens whose KV was still valid from the previous generation (not re-prefilled).
3279 pub reused_prompt_tokens: usize,
3280 /// Sum of the per-step timings over the decode steps.
3281 pub decode_timing: StepTiming,
3282 /// Sum of the per-step timings over the prefill steps (batched steps count once).
3283 pub prefill_timing: StepTiming,
3284}
3285
3286/// Where one step's time went. `*_ns` are host wall-clock sections; `chip_ns` is the sum of the
3287/// chip-reported kernel times; `launches` counts engine calls.
3288#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3289pub struct StepTiming {
3290 pub total_ns: u64,
3291 pub attention_ns: u64,
3292 pub experts_ns: u64,
3293 pub lm_head_ns: u64,
3294 pub host_ns: u64,
3295 pub chip_ns: u64,
3296 pub launches: u64,
3297 /// Batched prefill only (both are inside `experts_ns`): routing (host logits and top-k, or the
3298 /// device router launches) and the host work around the expert GEMMs (sort, SwiGLU, combine).
3299 pub route_ns: u64,
3300 pub moe_host_ns: u64,
3301 /// One-list decode graph only (`OWN30B_DECODE_GRAPH=1`): tokens run as one command list,
3302 /// their submissions and the host time spent recording the lists.
3303 pub graph_tokens: u64,
3304 pub graph_launches: u64,
3305 pub graph_submits: u64,
3306 pub graph_record_ns: u64,
3307 /// Expert Ribbon only (inside `experts_ns`): wall time pinning the top-k in slots, misses read
3308 /// from the NVMe and loaded included.
3309 pub page_ns: u64,
3310}
3311
3312impl StepTiming {
3313 pub fn add(&mut self, o: &StepTiming) {
3314 self.graph_tokens += o.graph_tokens;
3315 self.graph_launches += o.graph_launches;
3316 self.graph_submits += o.graph_submits;
3317 self.graph_record_ns += o.graph_record_ns;
3318 self.page_ns += o.page_ns;
3319 self.route_ns += o.route_ns;
3320 self.moe_host_ns += o.moe_host_ns;
3321 self.total_ns += o.total_ns;
3322 self.attention_ns += o.attention_ns;
3323 self.experts_ns += o.experts_ns;
3324 self.lm_head_ns += o.lm_head_ns;
3325 self.host_ns += o.host_ns;
3326 self.chip_ns += o.chip_ns;
3327 self.launches += o.launches;
3328 }
3329}
3330
3331/// What one traced layer did for one token (the parity harness replays it on the host).
3332#[derive(Debug, Clone, PartialEq)]
3333pub struct LayerTrace {
3334 pub layer: usize,
3335 pub pos: usize,
3336 pub x_in: Vec<f32>,
3337 pub attn_proj: Vec<f32>,
3338 pub post: Vec<f32>,
3339 /// The device router's own x' (RMSNorm(x), read back), empty on the host-routing path. `post`
3340 /// is always the host's independent RMSNorm, so the MoE oracle checks the router too.
3341 pub post_device: Vec<f32>,
3342 pub experts: Vec<u32>,
3343 pub weights: Vec<f32>,
3344 pub moe_out: Vec<f32>,
3345 pub x_out: Vec<f32>,
3346}
3347
3348/// Samples like the HTTP door's `sample_next`: top-k mask, then the workspace sampler with a
3349/// per-step seed, so greedy and seeded replies match across engines.
3350pub fn sample_next(logits: &[f32], params: &GenerateParams, step: usize) -> u32 {
3351 let masked;
3352 let logits = if params.top_k > 0 && params.top_k < logits.len() && params.temperature > 0.001 {
3353 let mut order: Vec<usize> = (0..logits.len()).collect();
3354 order.sort_by(|&a, &b| {
3355 logits[b]
3356 .partial_cmp(&logits[a])
3357 .unwrap_or(std::cmp::Ordering::Equal)
3358 .then(a.cmp(&b))
3359 });
3360 let mut out = vec![f32::NEG_INFINITY; logits.len()];
3361 for &i in &order[..params.top_k] {
3362 out[i] = logits[i];
3363 }
3364 masked = out;
3365 masked.as_slice()
3366 } else {
3367 logits
3368 };
3369 let sp = SamplingParams {
3370 temperature: params.temperature,
3371 top_p: params.top_p,
3372 max_tokens: 1,
3373 stop_token_ids: Vec::new(),
3374 };
3375 sample_with_params(logits, &sp, decode_sampling_seed(params.seed, step)).0
3376}
3377
3378/// Every run setting of a [`Qwen3MoeOmegaEngine`] that can change a K/V byte (persistent KV
3379/// engine identity, sc#505). When unsure whether a setting moves a byte it is listed (fail
3380/// closed: a needless entry only costs a cache miss). The caller adds the settings that live
3381/// outside the engine (weight format, the omega environment switches, the build).
3382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3383pub struct OmegaKvSwitches {
3384 /// "fused" (one-launch attention, bf16 RNE on the chip), "split" (host norm and RoPE, the
3385 /// paged pool), or a test cache's name.
3386 pub attention_path: &'static str,
3387 /// Decode steps route with the device router.
3388 pub device_routing: bool,
3389 /// Prompt tokens per batched prefill step (the batch shape of the activation rounding).
3390 pub prefill_chunk: usize,
3391 /// Batched prefill on the FP8 grouped GEMM instead of the grouped GEMV.
3392 pub prefill_gemm: bool,
3393 /// GEMM prefill routes with the device router.
3394 pub prefill_device_routing: bool,
3395 /// Whole-prompt prefill (changes activation rounding, chip gate W-RC).
3396 pub whole_prompt: bool,
3397 /// Router logits and MoE combine of the whole-prompt prefill on the chip.
3398 pub whole_prompt_device_host: bool,
3399 /// The one-list decode graph (`OWN30B_DECODE_GRAPH=1`).
3400 pub decode_graph: bool,
3401 /// lm_head on the bf16 GEMV (logits only; listed anyway).
3402 pub lm_head_gemv: bool,
3403 /// Negative control: routing deliberately wrong. Persistence must refuse it.
3404 pub routing_mutant: bool,
3405 /// Parity tracing on (records activations; listed anyway).
3406 pub trace_layers: bool,
3407}
3408
3409/// The Stage A engine: one sequence, token-at-a-time prefill and decode.
3410pub struct Qwen3MoeOmegaEngine {
3411 /// The one-list decode graph (built at the first graph decode step). Declared first so it is
3412 /// dropped before the weights and KV cache whose omega handles it holds.
3413 dgraph: Option<dgraph::GraphState>,
3414 /// `OWN30B_DECODE_GRAPH=1` at creation: decode steps run as one command list.
3415 decode_graph: bool,
3416 weights: Qwen3MoeOmegaWeights,
3417 kv: Box<dyn KvAttention>,
3418 /// Layers whose activations are recorded into `traces` (parity harness).
3419 pub trace_layers: Vec<usize>,
3420 pub traces: Vec<LayerTrace>,
3421 /// Negative control: every chosen expert id is replaced by its neighbour (weights stay), so
3422 /// every expert window is a wrong expert. The layer oracle must then disagree loudly.
3423 pub routing_mutant: bool,
3424 /// Route decode steps with the device router launch when the weights carry one. The host
3425 /// routing mutant forces the host path for its steps.
3426 pub device_routing: bool,
3427 /// Self-draft mode (aienix#4, Heartbeat H0): per layer, the sorted expert ids the router may
3428 /// pick from. `None` (the default) is the exact full router. When set, `step` routes on the
3429 /// host, takes top_k among the allowed experts only and renormalizes their weights exactly as
3430 /// the full router does; batched prefill and the one-list decode graph refuse or step around it.
3431 draft_allowed: Option<Vec<Vec<u32>>>,
3432 /// Router-choice counter (`layers x experts`, row-major): every `step` adds one per chosen
3433 /// expert when set. Calibration traces for the self-draft resident set.
3434 pub expert_counts: Option<Vec<u64>>,
3435 pub last_timing: StepTiming,
3436 /// Prompt tokens per prefill step (1 = token-at-a-time). Batched prefill needs FP8 attention
3437 /// and experts; with the grouped GEMM a step takes up to 128 tokens, with the grouped GEMV 8
3438 /// (`step_batch` splits a larger chunk to fit).
3439 pub prefill_chunk: usize,
3440 /// Batched prefill uses the FP8 grouped GEMM (when every projection has it) instead of the
3441 /// grouped GEMV.
3442 pub prefill_gemm: bool,
3443 /// GEMM prefill routes with the device router (one launch per token and layer) instead of
3444 /// the host.
3445 pub prefill_device_routing: bool,
3446 pos: usize,
3447 /// Tokens whose KV is stored at positions `0..pos` (prefix reuse across generations).
3448 history: Vec<u32>,
3449 /// Whole-prompt prefill driver (OFF = None; `set_whole_prompt`). See `whole_prompt.rs`.
3450 whole_prompt: Option<Box<whole_prompt::EngineWholePrompt>>,
3451 /// Tokens per whole-prompt pass (0 = the whole prompt at once). Bounds the prompt-sized
3452 /// scratch the driver keeps resident. See `whole_prompt::DEFAULT_CHUNK`.
3453 whole_prompt_chunk: usize,
3454 /// A whole-prompt pass has run: omega's per-layer KV mirror (one cache-sized copy of the KV,
3455 /// allocated by the first pass and kept) exists.
3456 whole_prompt_mirror_live: bool,
3457 /// This request skips the whole-prompt driver and uses the classic `prefill_chunk` loop.
3458 /// The door sets it when the KV mirror is not live and does not fit, so a cold server can
3459 /// still answer and a later request can warm the mirror. Cleared when the request returns.
3460 whole_prompt_suspended: bool,
3461 /// The host head (ADR 0004 adapter): the last forward call's final hidden state, unread.
3462 /// `None` once read or forgotten. Empty on the decode graph, whose head is its pending token.
3463 head_hidden: Option<Vec<f32>>,
3464 /// The logits `ForwardPass::next` lends out (the last head read).
3465 head_logits: Vec<f32>,
3466 /// The cache was lent through `ForwardPass::kv` since the last forward call: the mirror's
3467 /// tokens are taken from the ledger at the next one.
3468 kv_lent: bool,
3469}
3470
3471impl Qwen3MoeOmegaEngine {
3472 pub fn new(weights: Qwen3MoeOmegaWeights, kv: Box<dyn KvAttention>) -> Self {
3473 let device_routing = weights.device_router.is_some();
3474 let prefill_gemm = gemm_everywhere(&weights);
3475 Self {
3476 dgraph: None,
3477 decode_graph: dgraph::requested(),
3478 weights,
3479 kv,
3480 trace_layers: Vec::new(),
3481 traces: Vec::new(),
3482 routing_mutant: false,
3483 device_routing,
3484 draft_allowed: None,
3485 expert_counts: None,
3486 last_timing: StepTiming::default(),
3487 prefill_chunk: if prefill_gemm {
3488 PREFILL_CHUNK_GEMM
3489 } else {
3490 PREFILL_CHUNK
3491 },
3492 prefill_gemm,
3493 prefill_device_routing: false,
3494 pos: 0,
3495 history: Vec::new(),
3496 whole_prompt: None,
3497 whole_prompt_chunk: whole_prompt::DEFAULT_CHUNK,
3498 whole_prompt_mirror_live: false,
3499 whole_prompt_suspended: false,
3500 head_hidden: None,
3501 head_logits: Vec::new(),
3502 kv_lent: false,
3503 }
3504 }
3505
3506 /// Turns self-draft mode on with `allowed[layer]` = the expert ids the router may pick at that
3507 /// layer, or off with `None` (the exact full router again). Each list is sorted and duplicate
3508 /// ids are merged; refuses a mask that is not one list per layer, a layer with fewer than
3509 /// top_k distinct ids, or an id out of range.
3510 pub fn set_draft_experts(&mut self, allowed: Option<Vec<Vec<u32>>>) -> Result<(), String> {
3511 let c = &self.weights.config;
3512 let Some(mut allowed) = allowed else {
3513 self.draft_allowed = None;
3514 return Ok(());
3515 };
3516 if allowed.len() != c.layers {
3517 return Err(format!(
3518 "draft mask: {} layers given, model has {}",
3519 allowed.len(),
3520 c.layers
3521 ));
3522 }
3523 for (l, ids) in allowed.iter_mut().enumerate() {
3524 ids.sort_unstable();
3525 ids.dedup();
3526 if ids.len() < c.top_k {
3527 return Err(format!(
3528 "draft mask layer {l}: {} distinct experts, top_k is {}",
3529 ids.len(),
3530 c.top_k
3531 ));
3532 }
3533 if ids.last().is_some_and(|&x| x as usize >= c.experts) {
3534 return Err(format!("draft mask layer {l}: expert id out of range"));
3535 }
3536 }
3537 self.dgraph_clear();
3538 self.draft_allowed = Some(allowed);
3539 Ok(())
3540 }
3541
3542 /// True while self-draft mode (an allowed-expert mask) is on.
3543 pub fn draft_on(&self) -> bool {
3544 self.draft_allowed.is_some()
3545 }
3546
3547 /// Skips the whole-prompt driver for the next `generate_with` when `yes` (the classic
3548 /// prefill loop runs instead, and does not allocate the KV mirror). The door clears it
3549 /// when the request returns.
3550 pub fn suspend_whole_prompt(&mut self, yes: bool) {
3551 self.whole_prompt_suspended = yes;
3552 }
3553
3554 /// Whether every layer runs attention and experts on the FP8 grouped GEMV (the only
3555 /// kernels that take one activation row per group, which batched prefill needs).
3556 pub fn batched_prefill_possible(&self) -> bool {
3557 self.weights.layers.iter().all(|l| {
3558 matches!(l.attn, AttnWeights::Fp8 { .. })
3559 && matches!(l.experts, ExpertWeights::Fp8 { .. })
3560 })
3561 }
3562
3563 /// Runs `tokens` (consecutive positions) through every layer, layer-major: one grouped
3564 /// q|k|v GEMV with a row per token, one attention launch per token, one grouped o GEMV,
3565 /// then one gate|up and one down launch for all `tokens x top_k` expert rows. Returns the
3566 /// final-normed hidden state of the LAST token (the earlier ones are prefill only). The
3567 /// maths per token is the same as [`Self::step`] in the same order (the MoE sum is
3568 /// accumulated per token before the residual add), so greedy tokens must not change.
3569 /// Falls back to `step` per token when tracing, for one token, or without the FP8 kernels.
3570 pub fn step_batch(&mut self, tokens: &[u32]) -> Result<Vec<f32>, String> {
3571 let m = tokens.len();
3572 if m == 0 {
3573 return Err("step_batch: empty batch".into());
3574 }
3575 if self.draft_allowed.is_some() {
3576 return Err("step_batch: self-draft mode is on (draft steps go through step)".into());
3577 }
3578 let top_k = self.weights.config.top_k;
3579 if m == 1 || !self.trace_layers.is_empty() || !self.batched_prefill_possible() {
3580 let mut hidden = Vec::new();
3581 let mut timing = StepTiming::default();
3582 for &t in tokens {
3583 hidden = self.step(t)?;
3584 timing.add(&self.last_timing);
3585 }
3586 self.last_timing = timing;
3587 return Ok(hidden);
3588 }
3589 let gemm = self.prefill_gemm && gemm_everywhere(&self.weights);
3590 let limit = if gemm {
3591 aien_omega_fp8::GEMM_MAX_ROWS / top_k
3592 } else {
3593 aien_omega_fp8::MAX_GROUPS / top_k
3594 };
3595 if m > limit {
3596 // A chunk wider than one launch takes: run it as consecutive launches-sized pieces.
3597 let mut hidden = Vec::new();
3598 let mut timing = StepTiming::default();
3599 for piece in tokens.chunks(limit) {
3600 hidden = self.step_batch(piece)?;
3601 timing.add(&self.last_timing);
3602 }
3603 self.last_timing = timing;
3604 return Ok(hidden);
3605 }
3606 if gemm {
3607 return self.step_batch_gemm(tokens);
3608 }
3609 let t_step = Instant::now();
3610 let mut timing = StepTiming::default();
3611 let c = &self.weights.config;
3612 let (h, qd, kvd, hd, eps) = (c.hidden, c.q_dim(), c.kv_dim(), c.head_dim, c.rms_eps);
3613 let (e, i, qkv_n) = (c.experts, c.moe_intermediate, c.qkv_n());
3614 let pos0 = self.pos;
3615 if pos0 + m > self.kv.capacity() {
3616 return Err(format!(
3617 "context full: {pos0} + {m} of {}",
3618 self.kv.capacity()
3619 ));
3620 }
3621 let g = m * top_k;
3622 let mut x: Vec<f32> = tokens
3623 .iter()
3624 .flat_map(|&t| self.weights.embed_row(t))
3625 .collect();
3626 let mut x_norm = vec![0.0f32; m * h];
3627 let mut qkv_all = vec![0.0f32; m * qkv_n];
3628 let mut qn = vec![0.0f32; qd];
3629 let mut kn = vec![0.0f32; kvd];
3630 let mut attn_all = vec![0.0f32; m * qd];
3631 let mut proj_all = vec![0.0f32; m * h];
3632 let mut post = vec![0.0f32; m * h];
3633 let mut logits = vec![0.0f32; e];
3634 let mut ids = vec![0u32; g];
3635 let mut wts = vec![0.0f32; g];
3636 let mut post_rep = vec![0.0f32; g * h];
3637 let mut gu_all = vec![0.0f32; g * 2 * i];
3638 let mut act_all = vec![0.0f32; g * i];
3639 let mut down_all = vec![0.0f32; g * h];
3640 let mut moe_out = vec![0.0f32; h];
3641 let dense_ids = vec![0u32; m];
3642
3643 for (layer_idx, layer) in self.weights.layers.iter().enumerate() {
3644 let (AttnWeights::Fp8 { qkv, o }, ExpertWeights::Fp8 { gate_up, down }) =
3645 (&layer.attn, &layer.experts)
3646 else {
3647 return Err(format!(
3648 "layer {layer_idx}: batched prefill needs FP8 attention and experts"
3649 ));
3650 };
3651 // --- attention: one grouped q|k|v launch (a row per token), one attention launch per token, one grouped o launch ---
3652 let t0 = Instant::now();
3653 for r in 0..m {
3654 rmsnorm(
3655 &x[r * h..(r + 1) * h],
3656 &layer.input_norm,
3657 eps,
3658 &mut x_norm[r * h..(r + 1) * h],
3659 );
3660 }
3661 timing.host_ns += t0.elapsed().as_nanos() as u64;
3662 let t1 = Instant::now();
3663 timing.chip_ns += qkv
3664 .grouped_f32(&dense_ids, &x_norm, &mut qkv_all)
3665 .map_err(|e| format!("layer {layer_idx} qkv x{m}: {e}"))?;
3666 timing.launches += 1;
3667 for r in 0..m {
3668 let pos = pos0 + r;
3669 let qkv_r = &qkv_all[r * qkv_n..(r + 1) * qkv_n];
3670 let out_r = &mut attn_all[r * qd..(r + 1) * qd];
3671 match self.kv.fused_attend(layer_idx, pos, qkv_r, eps, out_r) {
3672 Some(res) => timing.chip_ns += res?,
3673 None => {
3674 let t2 = Instant::now();
3675 rmsnorm_per_head(&qkv_r[..qd], &layer.q_norm, eps, c.q_heads, hd, &mut qn);
3676 rmsnorm_per_head(
3677 &qkv_r[qd..qd + kvd],
3678 &layer.k_norm,
3679 eps,
3680 c.kv_heads,
3681 hd,
3682 &mut kn,
3683 );
3684 apply_rope(
3685 &mut qn,
3686 &mut kn,
3687 pos,
3688 c.q_heads,
3689 c.kv_heads,
3690 hd,
3691 c.rope_theta,
3692 );
3693 self.kv.append(layer_idx, pos, &kn, &qkv_r[qd + kvd..])?;
3694 timing.host_ns += t2.elapsed().as_nanos() as u64;
3695 timing.chip_ns += self.kv.attend(layer_idx, &qn, pos + 1, out_r)?;
3696 }
3697 }
3698 timing.launches += 1;
3699 }
3700 timing.chip_ns += o
3701 .grouped_f32(&dense_ids, &attn_all, &mut proj_all)
3702 .map_err(|e| format!("layer {layer_idx} o x{m}: {e}"))?;
3703 timing.launches += 1;
3704 timing.attention_ns += t1.elapsed().as_nanos() as u64;
3705
3706 // --- residual, post norm, routing per token (host); the expert row table for the chunk ---
3707 let t3 = Instant::now();
3708 for r in 0..m {
3709 let xr = &mut x[r * h..(r + 1) * h];
3710 for (xi, p) in xr.iter_mut().zip(&proj_all[r * h..(r + 1) * h]) {
3711 *xi += p;
3712 }
3713 let pr = &mut post[r * h..(r + 1) * h];
3714 rmsnorm(xr, &layer.post_norm, eps, pr);
3715 for (ex, l) in logits.iter_mut().enumerate() {
3716 *l = layer.router[ex * h..(ex + 1) * h]
3717 .iter()
3718 .zip(pr.iter())
3719 .map(|(a, b)| a * b)
3720 .sum();
3721 }
3722 let plan = MoeBatchPlan::from_logits(&logits, 1, e, top_k)
3723 .map_err(|e| format!("layer {layer_idx} routing: {e}"))?;
3724 for (slot, (&ex, &w)) in
3725 plan.topk_experts.iter().zip(&plan.topk_weights).enumerate()
3726 {
3727 let gi = r * top_k + slot;
3728 ids[gi] = if self.routing_mutant {
3729 (ex + 1) % e as u32
3730 } else {
3731 ex
3732 };
3733 wts[gi] = w;
3734 post_rep[gi * h..(gi + 1) * h].copy_from_slice(pr);
3735 }
3736 }
3737 timing.host_ns += t3.elapsed().as_nanos() as u64;
3738
3739 // --- experts: one gate|up launch and one down launch for every (token, expert) row ---
3740 let t4 = Instant::now();
3741 timing.chip_ns += gate_up
3742 .grouped_f32(&ids, &post_rep, &mut gu_all)
3743 .map_err(|e| format!("layer {layer_idx} gate_up fp8 x{g}: {e}"))?;
3744 timing.launches += 1;
3745 let th = Instant::now();
3746 for gi in 0..g {
3747 swiglu(
3748 &gu_all[gi * 2 * i..(gi + 1) * 2 * i],
3749 i,
3750 &mut act_all[gi * i..(gi + 1) * i],
3751 );
3752 }
3753 timing.host_ns += th.elapsed().as_nanos() as u64;
3754 timing.chip_ns += down
3755 .grouped_f32(&ids, &act_all, &mut down_all)
3756 .map_err(|e| format!("layer {layer_idx} down fp8 x{g}: {e}"))?;
3757 timing.launches += 1;
3758 let th = Instant::now();
3759 for r in 0..m {
3760 moe_out.iter_mut().for_each(|v| *v = 0.0);
3761 for slot in 0..top_k {
3762 let gi = r * top_k + slot;
3763 let w = wts[gi];
3764 for (mo, d) in moe_out.iter_mut().zip(&down_all[gi * h..(gi + 1) * h]) {
3765 *mo += w * d;
3766 }
3767 }
3768 for (xi, mo) in x[r * h..(r + 1) * h].iter_mut().zip(&moe_out) {
3769 *xi += mo;
3770 }
3771 }
3772 timing.host_ns += th.elapsed().as_nanos() as u64;
3773 timing.experts_ns += t4.elapsed().as_nanos() as u64;
3774 }
3775 let t5 = Instant::now();
3776 let mut hidden = vec![0.0f32; h];
3777 rmsnorm(
3778 &x[(m - 1) * h..],
3779 &self.weights.final_norm,
3780 eps,
3781 &mut hidden,
3782 );
3783 timing.host_ns += t5.elapsed().as_nanos() as u64;
3784 self.pos = pos0 + m;
3785 self.history.extend_from_slice(tokens);
3786 timing.total_ns = t_step.elapsed().as_nanos() as u64;
3787 self.last_timing = timing;
3788 Ok(hidden)
3789 }
3790
3791 /// Batched prefill on the FP8 grouped GEMM (OWN-30B cut 10): the same layer-major maths as the
3792 /// GEMV path above, but q|k|v, o, gate|up and down are each ONE launch for the whole chunk
3793 /// (up to 128 tokens = 1024 expert rows), and every distinct expert's weights are streamed
3794 /// once per pass of rows instead of once per row. Attention stays one fused launch per token.
3795 /// The expert rows are sorted by expert (a counting sort on the host); the GEMM output comes
3796 /// back in sorted order and the per-token MoE sum is accumulated in slot order, exactly as
3797 /// before, so the result is bit-identical to the GEMV path. Routing is the host's (logits on
3798 /// worker threads) or, with `prefill_device_routing`, the device router per token.
3799 fn step_batch_gemm(&mut self, tokens: &[u32]) -> Result<Vec<f32>, String> {
3800 let m = tokens.len();
3801 let t_step = Instant::now();
3802 let mut timing = StepTiming::default();
3803 let c = &self.weights.config;
3804 let top_k = c.top_k;
3805 let (h, qd, kvd, hd, eps) = (c.hidden, c.q_dim(), c.kv_dim(), c.head_dim, c.rms_eps);
3806 let (e, i, qkv_n) = (c.experts, c.moe_intermediate, c.qkv_n());
3807 let pos0 = self.pos;
3808 if pos0 + m > self.kv.capacity() {
3809 return Err(format!(
3810 "context full: {pos0} + {m} of {}",
3811 self.kv.capacity()
3812 ));
3813 }
3814 let g = m * top_k;
3815 let mut x: Vec<f32> = tokens
3816 .iter()
3817 .flat_map(|&t| self.weights.embed_row(t))
3818 .collect();
3819 let mut x_norm = vec![0.0f32; m * h];
3820 let mut qkv_all = vec![0.0f32; m * qkv_n];
3821 let mut qn = vec![0.0f32; qd];
3822 let mut kn = vec![0.0f32; kvd];
3823 let mut attn_all = vec![0.0f32; m * qd];
3824 let mut proj_all = vec![0.0f32; m * h];
3825 let mut post = vec![0.0f32; m * h];
3826 let mut logits = vec![0.0f32; m * e];
3827 let mut ids = vec![0u32; g];
3828 let mut wts = vec![0.0f32; g];
3829 let mut sorted_expert = vec![0u32; g];
3830 let mut sorted_token = vec![0u32; g];
3831 let mut inv = vec![0u32; g];
3832 let mut gu_all = vec![0.0f32; g * 2 * i];
3833 let mut act_all = vec![0.0f32; g * i];
3834 let mut down_all = vec![0.0f32; g * h];
3835 let dense_ids = vec![0u32; m];
3836 let rows_m: Vec<u32> = (0..m as u32).collect();
3837 let rows_g: Vec<u32> = (0..g as u32).collect();
3838 let device_router = match &self.weights.device_router {
3839 Some(r) if self.prefill_device_routing && !self.routing_mutant => Some(r.clone()),
3840 _ => None,
3841 };
3842
3843 for (layer_idx, layer) in self.weights.layers.iter().enumerate() {
3844 let (AttnWeights::Fp8 { qkv, o }, ExpertWeights::Fp8 { gate_up, down }) =
3845 (&layer.attn, &layer.experts)
3846 else {
3847 return Err(format!(
3848 "layer {layer_idx}: batched prefill needs FP8 attention and experts"
3849 ));
3850 };
3851 // --- attention: one q|k|v GEMM, one fused attention launch per token, one o GEMM ---
3852 let t0 = Instant::now();
3853 for r in 0..m {
3854 rmsnorm(
3855 &x[r * h..(r + 1) * h],
3856 &layer.input_norm,
3857 eps,
3858 &mut x_norm[r * h..(r + 1) * h],
3859 );
3860 }
3861 timing.host_ns += t0.elapsed().as_nanos() as u64;
3862 let t1 = Instant::now();
3863 timing.chip_ns += qkv
3864 .gemm_f32(&dense_ids, &rows_m, &x_norm, &mut qkv_all)
3865 .map_err(|e| format!("layer {layer_idx} qkv gemm x{m}: {e}"))?;
3866 timing.launches += 1;
3867 for r in 0..m {
3868 let pos = pos0 + r;
3869 let qkv_r = &qkv_all[r * qkv_n..(r + 1) * qkv_n];
3870 let out_r = &mut attn_all[r * qd..(r + 1) * qd];
3871 match self.kv.fused_attend(layer_idx, pos, qkv_r, eps, out_r) {
3872 Some(res) => timing.chip_ns += res?,
3873 None => {
3874 let t2 = Instant::now();
3875 rmsnorm_per_head(&qkv_r[..qd], &layer.q_norm, eps, c.q_heads, hd, &mut qn);
3876 rmsnorm_per_head(
3877 &qkv_r[qd..qd + kvd],
3878 &layer.k_norm,
3879 eps,
3880 c.kv_heads,
3881 hd,
3882 &mut kn,
3883 );
3884 apply_rope(
3885 &mut qn,
3886 &mut kn,
3887 pos,
3888 c.q_heads,
3889 c.kv_heads,
3890 hd,
3891 c.rope_theta,
3892 );
3893 self.kv.append(layer_idx, pos, &kn, &qkv_r[qd + kvd..])?;
3894 timing.host_ns += t2.elapsed().as_nanos() as u64;
3895 timing.chip_ns += self.kv.attend(layer_idx, &qn, pos + 1, out_r)?;
3896 }
3897 }
3898 timing.launches += 1;
3899 }
3900 timing.chip_ns += o
3901 .gemm_f32(&dense_ids, &rows_m, &attn_all, &mut proj_all)
3902 .map_err(|e| format!("layer {layer_idx} o gemm x{m}: {e}"))?;
3903 timing.launches += 1;
3904 timing.attention_ns += t1.elapsed().as_nanos() as u64;
3905
3906 // --- residual and post norm for every token, then routing ---
3907 let t3 = Instant::now();
3908 for r in 0..m {
3909 let xr = &mut x[r * h..(r + 1) * h];
3910 for (xi, p) in xr.iter_mut().zip(&proj_all[r * h..(r + 1) * h]) {
3911 *xi += p;
3912 }
3913 rmsnorm(xr, &layer.post_norm, eps, &mut post[r * h..(r + 1) * h]);
3914 }
3915 timing.host_ns += t3.elapsed().as_nanos() as u64;
3916 let t4 = Instant::now();
3917 let tr = Instant::now();
3918 if let Some(router) = &device_router {
3919 for r in 0..m {
3920 let (a, b) = (r * top_k, (r + 1) * top_k);
3921 let (ns, _) = router
3922 .route(
3923 layer_idx,
3924 &x[r * h..(r + 1) * h],
3925 eps,
3926 &mut ids[a..b],
3927 &mut wts[a..b],
3928 )
3929 .map_err(|e| {
3930 format!("layer {layer_idx} device router (token {r} of {m}): {e}")
3931 })?;
3932 timing.chip_ns += ns;
3933 timing.launches += 1;
3934 }
3935 } else {
3936 router_logits(&layer.router, &post, h, e, &mut logits);
3937 let plan = MoeBatchPlan::from_logits(&logits, m, e, top_k)
3938 .map_err(|e| format!("layer {layer_idx} routing: {e}"))?;
3939 for (dst, &ex) in ids.iter_mut().zip(&plan.topk_experts) {
3940 *dst = if self.routing_mutant {
3941 (ex + 1) % e as u32
3942 } else {
3943 ex
3944 };
3945 }
3946 wts.copy_from_slice(&plan.topk_weights);
3947 }
3948 timing.route_ns += tr.elapsed().as_nanos() as u64;
3949
3950 // --- the (expert, row) table sorted by expert (stable counting sort) ---
3951 let ts = Instant::now();
3952 let mut start = vec![0u32; e + 1];
3953 for &ex in &ids {
3954 start[ex as usize + 1] += 1;
3955 }
3956 for ex in 0..e {
3957 start[ex + 1] += start[ex];
3958 }
3959 for (gi, &ex) in ids.iter().enumerate() {
3960 let slot = &mut start[ex as usize];
3961 sorted_expert[*slot as usize] = ex;
3962 sorted_token[*slot as usize] = (gi / top_k) as u32;
3963 inv[gi] = *slot;
3964 *slot += 1;
3965 }
3966 timing.moe_host_ns += ts.elapsed().as_nanos() as u64;
3967
3968 // --- experts: one gate|up GEMM, SwiGLU, one down GEMM, over every (token, expert) row ---
3969 timing.chip_ns += gate_up
3970 .gemm_f32(&sorted_expert, &sorted_token, &post, &mut gu_all)
3971 .map_err(|e| format!("layer {layer_idx} gate_up gemm x{g}: {e}"))?;
3972 timing.launches += 1;
3973 let th = Instant::now();
3974 swiglu_rows(&gu_all, &mut act_all, i);
3975 timing.moe_host_ns += th.elapsed().as_nanos() as u64;
3976 timing.chip_ns += down
3977 .gemm_f32(&sorted_expert, &rows_g, &act_all, &mut down_all)
3978 .map_err(|e| format!("layer {layer_idx} down gemm x{g}: {e}"))?;
3979 timing.launches += 1;
3980 let th = Instant::now();
3981 combine_rows(&mut x, &down_all, &wts, &inv, h, top_k);
3982 timing.moe_host_ns += th.elapsed().as_nanos() as u64;
3983 timing.experts_ns += t4.elapsed().as_nanos() as u64;
3984 }
3985 let t5 = Instant::now();
3986 let mut hidden = vec![0.0f32; h];
3987 rmsnorm(
3988 &x[(m - 1) * h..],
3989 &self.weights.final_norm,
3990 eps,
3991 &mut hidden,
3992 );
3993 timing.host_ns += t5.elapsed().as_nanos() as u64;
3994 self.pos = pos0 + m;
3995 self.history.extend_from_slice(tokens);
3996 timing.total_ns = t_step.elapsed().as_nanos() as u64;
3997 self.last_timing = timing;
3998 Ok(hidden)
3999 }
4000
4001 /// The production constructor: loads the checkpoint onto Omega and allocates the paged KV.
4002 pub fn load_omega(
4003 dir: &Path,
4004 max_context: usize,
4005 progress: &mut dyn FnMut(&str),
4006 ) -> Result<(Self, LoadReport), String> {
4007 Self::load_omega_with(dir, max_context, WeightFormat::Bf16, progress)
4008 }
4009
4010 /// As [`Self::load_omega`] with a chosen weight format (FP8 needs omega's FP8 GEMV linked).
4011 /// Attention takes the fused one-launch path when it is linked ([`AttnPath::Auto`]).
4012 pub fn load_omega_with(
4013 dir: &Path,
4014 max_context: usize,
4015 format: WeightFormat,
4016 progress: &mut dyn FnMut(&str),
4017 ) -> Result<(Self, LoadReport), String> {
4018 Self::load_omega_with_attn(dir, max_context, format, AttnPath::Auto, progress)
4019 }
4020
4021 /// As [`Self::load_omega_with`] with the attention path chosen explicitly.
4022 pub fn load_omega_with_attn(
4023 dir: &Path,
4024 max_context: usize,
4025 format: WeightFormat,
4026 attn: AttnPath,
4027 progress: &mut dyn FnMut(&str),
4028 ) -> Result<(Self, LoadReport), String> {
4029 Self::load_omega_paths(
4030 dir,
4031 max_context,
4032 format,
4033 attn,
4034 DevicePaths::default(),
4035 progress,
4036 )
4037 }
4038
4039 /// As [`Self::load_omega_with_attn`] with the router and lm_head paths chosen
4040 /// ([`DevicePaths::default`] takes the device ones when linked).
4041 pub fn load_omega_paths(
4042 dir: &Path,
4043 max_context: usize,
4044 format: WeightFormat,
4045 attn: AttnPath,
4046 paths: DevicePaths,
4047 progress: &mut dyn FnMut(&str),
4048 ) -> Result<(Self, LoadReport), String> {
4049 Self::load_omega_experts(dir, max_context, format, attn, paths, None, progress)
4050 }
4051
4052 /// As [`Self::load_omega_paths`] with the experts paged into GPU slots (Expert Ribbon) when
4053 /// `paged` is given: no expert bytes are read at load, every expert comes from the pager.
4054 pub fn load_omega_experts(
4055 dir: &Path,
4056 max_context: usize,
4057 format: WeightFormat,
4058 attn: AttnPath,
4059 paths: DevicePaths,
4060 paged: Option<Arc<ribbon::PagedExperts>>,
4061 progress: &mut dyn FnMut(&str),
4062 ) -> Result<(Self, LoadReport), String> {
4063 if !aien_omega_gpu::is_native() {
4064 return Err("this binary carries the CPU stub of the Omega engine (build with AIEN_OMEGA_DIR or AIEN_OMEGA_GPU_LIB)".into());
4065 }
4066 let (weights, report) = match paged {
4067 None => load_qwen3_moe_omega_paths(dir, &OmegaModelUploader, format, paths, progress)?,
4068 Some(p) => {
4069 load_qwen3_moe_omega_paged(dir, &OmegaModelUploader, format, paths, p, progress)?
4070 }
4071 };
4072 let geometry = KvGeometry::from(&weights.config);
4073 let fused = match attn {
4074 AttnPath::Split => false,
4075 AttnPath::Fused => true,
4076 AttnPath::Auto => {
4077 OmegaModelUploader::uses_dattn_api()
4078 && crate::qwen3_moe_omega_dattn::OmegaFusedKv::fits(&geometry)
4079 }
4080 };
4081 let kv: Box<dyn KvAttention> = if fused {
4082 let kv = crate::qwen3_moe_omega_dattn::OmegaFusedKv::new(
4083 &geometry,
4084 max_context,
4085 &weights.layers,
4086 )?;
4087 progress(&format!(
4088 "kv fused cache {} MB resident=true",
4089 kv.kv_bytes() >> 20
4090 ));
4091 Box::new(kv)
4092 } else {
4093 let kv = OmegaPagedKv::new(&geometry, max_context)?;
4094 progress(&format!(
4095 "kv pool {} MB resident={}",
4096 kv.pool_bytes() >> 20,
4097 kv.resident()
4098 ));
4099 Box::new(kv)
4100 };
4101 Ok((Self::new(weights, kv), report))
4102 }
4103
4104 /// "split" or "fused": which attention path this engine runs.
4105 pub fn attention_path(&self) -> &'static str {
4106 self.kv.path_name()
4107 }
4108
4109 pub fn config(&self) -> &Qwen3MoeConfig {
4110 &self.weights.config
4111 }
4112
4113 pub fn weights(&self) -> &Qwen3MoeOmegaWeights {
4114 &self.weights
4115 }
4116
4117 pub fn max_context_tokens(&self) -> usize {
4118 self.kv.capacity()
4119 }
4120
4121 pub fn kv_resident(&self) -> bool {
4122 self.kv.resident()
4123 }
4124
4125 /// Current sequence length (tokens already in the KV).
4126 pub fn position(&self) -> usize {
4127 self.pos
4128 }
4129
4130 pub fn reset(&mut self) {
4131 self.dgraph_clear();
4132 self.kv.truncate(0);
4133 self.pos = 0;
4134 self.history.clear();
4135 self.traces.clear();
4136 }
4137
4138 /// Tokens whose KV is stored (positions `0..position()`).
4139 pub fn history(&self) -> &[u32] {
4140 &self.history
4141 }
4142
4143 /// Keeps the first `len` stored tokens and forgets the rest; the next step is at `len`.
4144 pub fn rewind(&mut self, len: usize) {
4145 let len = len.min(self.pos);
4146 self.dgraph_clear();
4147 self.kv.truncate(len);
4148 self.history.truncate(len);
4149 self.pos = len;
4150 }
4151
4152 /// Tokens `generate` would keep from the stored history for `prompt`: the longest common
4153 /// prefix, capped at `prompt.len() - 1` (the last prompt token is always stepped). The same
4154 /// rule as `generate_inner`; persistent KV (sc#505) restores only when the store beats it.
4155 pub fn reusable_prefix(&self, prompt: &[u32]) -> usize {
4156 let common = self
4157 .history
4158 .iter()
4159 .zip(prompt)
4160 .take_while(|(a, b)| a == b)
4161 .count();
4162 common.min(prompt.len().saturating_sub(1))
4163 }
4164
4165 /// Persistent KV park (sc#505): the K/V of stored positions `start..start + len` as the
4166 /// [`kvio`] payload (`start` a multiple of [`KV_BLOCK_SIZE`], `start + len <= position()`).
4167 pub fn export_kv(&mut self, start: usize, len: usize) -> Result<Vec<u8>, String> {
4168 if start + len > self.pos {
4169 return Err(format!(
4170 "kv export {start}+{len}: only {} positions stored",
4171 self.pos
4172 ));
4173 }
4174 self.kv.export_blocks(start, len).unwrap_or_else(|| {
4175 Err(format!(
4176 "the {} attention cache cannot export its KV",
4177 self.kv.path_name()
4178 ))
4179 })
4180 }
4181
4182 /// Persistent KV restore (sc#505): replaces the stored sequence by `tokens` with the K/V of
4183 /// `payload` (a [`kvio`] payload of `tokens.len()` positions from position 0). On success the
4184 /// engine is exactly as if it had stepped `tokens` itself and kept them in its history, so the
4185 /// next `generate` reuses them by the usual prefix rule. On any error the engine is reset
4186 /// (empty history): the next `generate` prefills from position 0, never from a partial prefix.
4187 pub fn restore_kv(&mut self, tokens: &[u32], payload: &[u8]) -> Result<(), String> {
4188 self.reset();
4189 if tokens.is_empty() || tokens.len() >= self.kv.capacity() {
4190 return Err(format!(
4191 "kv restore of {} tokens, context is {}",
4192 tokens.len(),
4193 self.kv.capacity()
4194 ));
4195 }
4196 let r = self
4197 .kv
4198 .import_blocks(0, tokens.len(), payload)
4199 .unwrap_or_else(|| {
4200 Err(format!(
4201 "the {} attention cache cannot import KV",
4202 self.kv.path_name()
4203 ))
4204 });
4205 match r {
4206 Ok(()) => {
4207 self.history = tokens.to_vec();
4208 self.pos = tokens.len();
4209 Ok(())
4210 }
4211 Err(e) => {
4212 self.reset();
4213 Err(e)
4214 }
4215 }
4216 }
4217
4218 /// Every setting of this engine that can change a K/V byte, for the persistent KV engine
4219 /// identity (sc#505). See [`OmegaKvSwitches`].
4220 pub fn kv_switches(&self) -> OmegaKvSwitches {
4221 OmegaKvSwitches {
4222 attention_path: self.kv.path_name(),
4223 device_routing: self.device_routing,
4224 prefill_chunk: self.prefill_chunk,
4225 prefill_gemm: self.prefill_gemm,
4226 prefill_device_routing: self.prefill_device_routing,
4227 whole_prompt: self.whole_prompt_on(),
4228 whole_prompt_device_host: self.whole_prompt_device_host_on(),
4229 decode_graph: self.decode_graph,
4230 lm_head_gemv: matches!(self.weights.lm_head, LmHead::Gemv(_)),
4231 routing_mutant: self.routing_mutant,
4232 trace_layers: !self.trace_layers.is_empty(),
4233 }
4234 }
4235
4236 /// Runs `token` at the next position through every layer. Returns the final-normed hidden
4237 /// state (feed it to `logits`). Records `last_timing`.
4238 pub fn step(&mut self, token: u32) -> Result<Vec<f32>, String> {
4239 let t_step = Instant::now();
4240 let mut timing = StepTiming::default();
4241 let c = &self.weights.config;
4242 let (h, qd, kvd, hd, eps) = (c.hidden, c.q_dim(), c.kv_dim(), c.head_dim, c.rms_eps);
4243 let (e, top_k, i) = (c.experts, c.top_k, c.moe_intermediate);
4244 let pos = self.pos;
4245 if pos >= self.kv.capacity() {
4246 return Err(format!("context full: {pos} of {}", self.kv.capacity()));
4247 }
4248 let mut x = self.weights.embed_row(token);
4249 let mut x_norm = vec![0.0f32; h];
4250 let mut qkv_out = vec![0.0f32; c.qkv_n()];
4251 let mut qn = vec![0.0f32; qd];
4252 let mut kn = vec![0.0f32; kvd];
4253 let mut attn_out = vec![0.0f32; qd];
4254 let mut attn_proj = vec![0.0f32; h];
4255 let mut post = vec![0.0f32; h];
4256 let mut logits = vec![0.0f32; e];
4257 let mut gu_out = vec![0.0f32; top_k * 2 * i];
4258 let mut act = vec![0.0f32; i];
4259 let mut down_out = vec![0.0f32; h];
4260 let mut moe_out = vec![0.0f32; h];
4261 let mut col0s: Vec<u32> = vec![0; top_k];
4262 // FP8 grouped path: all top_k activations and down outputs in one buffer each.
4263 let mut act_all = vec![0.0f32; top_k * i];
4264 let mut down_all = vec![0.0f32; top_k * h];
4265
4266 for (layer_idx, layer) in self.weights.layers.iter().enumerate() {
4267 let traced = self.trace_layers.contains(&layer_idx);
4268 let x_in = if traced { x.clone() } else { Vec::new() };
4269
4270 // --- attention ---
4271 let t0 = Instant::now();
4272 rmsnorm(&x, &layer.input_norm, eps, &mut x_norm);
4273 timing.host_ns += t0.elapsed().as_nanos() as u64;
4274 let t1 = Instant::now();
4275 timing.chip_ns += match &layer.attn {
4276 AttnWeights::Bf16 { qkv, .. } => qkv.matmul_f32(1, &x_norm, &mut qkv_out),
4277 AttnWeights::Fp8 { qkv, .. } => qkv.grouped_f32(&[0], &x_norm, &mut qkv_out),
4278 }
4279 .map_err(|e| format!("layer {layer_idx} qkv: {e}"))?;
4280 timing.launches += 1;
4281 match self
4282 .kv
4283 .fused_attend(layer_idx, pos, &qkv_out, eps, &mut attn_out)
4284 {
4285 // One launch: norms, rope, KV append and attention on the chip.
4286 Some(r) => timing.chip_ns += r?,
4287 // Split path: host norms and rope, KV write, then the paged attention launch.
4288 None => {
4289 let t2 = Instant::now();
4290 rmsnorm_per_head(&qkv_out[..qd], &layer.q_norm, eps, c.q_heads, hd, &mut qn);
4291 rmsnorm_per_head(
4292 &qkv_out[qd..qd + kvd],
4293 &layer.k_norm,
4294 eps,
4295 c.kv_heads,
4296 hd,
4297 &mut kn,
4298 );
4299 apply_rope(
4300 &mut qn,
4301 &mut kn,
4302 pos,
4303 c.q_heads,
4304 c.kv_heads,
4305 hd,
4306 c.rope_theta,
4307 );
4308 self.kv.append(layer_idx, pos, &kn, &qkv_out[qd + kvd..])?;
4309 timing.host_ns += t2.elapsed().as_nanos() as u64;
4310 timing.chip_ns += self.kv.attend(layer_idx, &qn, pos + 1, &mut attn_out)?;
4311 }
4312 }
4313 timing.launches += 1;
4314 timing.chip_ns += match &layer.attn {
4315 AttnWeights::Bf16 { o, .. } => o.matmul_f32(1, &attn_out, &mut attn_proj),
4316 AttnWeights::Fp8 { o, .. } => o.grouped_f32(&[0], &attn_out, &mut attn_proj),
4317 }
4318 .map_err(|e| format!("layer {layer_idx} o: {e}"))?;
4319 timing.launches += 1;
4320 timing.attention_ns += t1.elapsed().as_nanos() as u64;
4321
4322 // --- residual, post norm, routing (host) ---
4323 let t3 = Instant::now();
4324 for (xi, p) in x.iter_mut().zip(&attn_proj) {
4325 *xi += p;
4326 }
4327 // The device router takes the residual row and leaves the normed row and the gate|up
4328 // group table on the chip: no host RMSNorm, router matmul, top-k or table build.
4329 // The host routing mutant (a host-side swap of the chosen ids) needs the host path.
4330 let device_router = match (&self.weights.device_router, &layer.experts) {
4331 (Some(r), ExpertWeights::Fp8 { .. } | ExpertWeights::Paged(_))
4332 if self.device_routing
4333 && !self.routing_mutant
4334 && self.draft_allowed.is_none() =>
4335 {
4336 Some(r)
4337 }
4338 _ => None,
4339 };
4340 let mut addrs: Option<RouteAddrs> = None;
4341 let mut post_device: Vec<f32> = Vec::new();
4342 let t4;
4343 let (experts, topk_weights): (Vec<u32>, Vec<f32>) = if let Some(router) = device_router
4344 {
4345 timing.host_ns += t3.elapsed().as_nanos() as u64;
4346 t4 = Instant::now();
4347 let (mut ids, mut wts) = ([0u32; 16], [0.0f32; 16]);
4348 let (ns, a) = router
4349 .route(layer_idx, &x, eps, &mut ids[..top_k], &mut wts[..top_k])
4350 .map_err(|e| format!("layer {layer_idx} device router: {e}"))?;
4351 timing.chip_ns += ns;
4352 timing.launches += 1;
4353 addrs = Some(a);
4354 if traced {
4355 // The oracle input is the host's own RMSNorm; the device x' is kept beside it.
4356 rmsnorm(&x, &layer.post_norm, eps, &mut post);
4357 post_device = vec![0.0f32; h];
4358 router
4359 .read_post(&mut post_device)
4360 .map_err(|e| format!("layer {layer_idx} router readback: {e}"))?;
4361 }
4362 (ids[..top_k].to_vec(), wts[..top_k].to_vec())
4363 } else {
4364 rmsnorm(&x, &layer.post_norm, eps, &mut post);
4365 for (ex, l) in logits.iter_mut().enumerate() {
4366 *l = layer.router[ex * h..(ex + 1) * h]
4367 .iter()
4368 .zip(&post)
4369 .map(|(a, b)| a * b)
4370 .sum();
4371 }
4372 let plan = match self.draft_allowed.as_ref().map(|a| &a[layer_idx]) {
4373 None => MoeBatchPlan::from_logits(&logits, 1, e, top_k)
4374 .map_err(|e| format!("layer {layer_idx} routing: {e}"))?,
4375 // Self-draft: the same softmax/top-k/renormalize over the allowed logits
4376 // only (ascending ids, so ties still go to the lower expert id).
4377 Some(ids) => {
4378 let sub: Vec<f32> = ids.iter().map(|&x| logits[x as usize]).collect();
4379 let mut p = MoeBatchPlan::from_logits(&sub, 1, sub.len(), top_k)
4380 .map_err(|e| format!("layer {layer_idx} draft routing: {e}"))?;
4381 p.topk_experts
4382 .iter_mut()
4383 .for_each(|x| *x = ids[*x as usize]);
4384 p
4385 }
4386 };
4387 let mut experts: Vec<u32> = plan.topk_experts.clone();
4388 if self.routing_mutant {
4389 experts.iter_mut().for_each(|ex| *ex = (*ex + 1) % e as u32);
4390 }
4391 for (slot, &ex) in experts.iter().enumerate() {
4392 col0s[slot] = c.gate_up_col0(ex as usize) as u32;
4393 }
4394 timing.host_ns += t3.elapsed().as_nanos() as u64;
4395 t4 = Instant::now();
4396 (experts, plan.topk_weights.clone())
4397 };
4398 if let Some(counts) = self.expert_counts.as_mut() {
4399 for &ex in &experts {
4400 counts[layer_idx * e + ex as usize] += 1;
4401 }
4402 }
4403
4404 moe_out.iter_mut().for_each(|v| *v = 0.0);
4405 match &layer.experts {
4406 // --- bf16 windows: 1 gate|up call over top_k windows, top_k down calls ---
4407 ExpertWeights::Bf16 { gate_up, down } => {
4408 timing.chip_ns += gate_up
4409 .windows_f32(1, &post, &col0s, 2 * i, &mut gu_out)
4410 .map_err(|e| format!("layer {layer_idx} gate_up: {e}"))?;
4411 timing.launches += top_k as u64;
4412 for (slot, &ex) in experts.iter().enumerate() {
4413 let th = Instant::now();
4414 swiglu(&gu_out[slot * 2 * i..(slot + 1) * 2 * i], i, &mut act);
4415 timing.host_ns += th.elapsed().as_nanos() as u64;
4416 let col0 = c.down_col0(ex as usize) as u32;
4417 timing.chip_ns += down
4418 .windows_f32(1, &act, std::slice::from_ref(&col0), h, &mut down_out)
4419 .map_err(|e| format!("layer {layer_idx} down expert {ex}: {e}"))?;
4420 timing.launches += 1;
4421 let w = topk_weights[slot];
4422 for (m, d) in moe_out.iter_mut().zip(&down_out) {
4423 *m += w * d;
4424 }
4425 }
4426 }
4427 // --- FP8 grouped: one gate|up launch (shared row), one down launch (a row per expert) ---
4428 ExpertWeights::Fp8 { gate_up, down } => {
4429 timing.chip_ns += match addrs {
4430 // The router left the normed row and the group table on the chip.
4431 Some(a) => gate_up.grouped_dev(top_k, a.tab_gu_va, a.x_va, &mut gu_out),
4432 None => gate_up.grouped_f32(&experts, &post, &mut gu_out),
4433 }
4434 .map_err(|e| format!("layer {layer_idx} gate_up fp8: {e}"))?;
4435 timing.launches += 1;
4436 let th = Instant::now();
4437 for slot in 0..top_k {
4438 swiglu(
4439 &gu_out[slot * 2 * i..(slot + 1) * 2 * i],
4440 i,
4441 &mut act_all[slot * i..(slot + 1) * i],
4442 );
4443 }
4444 timing.host_ns += th.elapsed().as_nanos() as u64;
4445 timing.chip_ns += down
4446 .grouped_f32(&experts, &act_all, &mut down_all)
4447 .map_err(|e| format!("layer {layer_idx} down fp8: {e}"))?;
4448 timing.launches += 1;
4449 let th = Instant::now();
4450 for (slot, &w) in topk_weights.iter().enumerate() {
4451 for (m, d) in moe_out.iter_mut().zip(&down_all[slot * h..(slot + 1) * h]) {
4452 *m += w * d;
4453 }
4454 }
4455 timing.host_ns += th.elapsed().as_nanos() as u64;
4456 }
4457 // --- Expert Ribbon: pin the top-k in GPU slots (misses paged in), two grouped launches ---
4458 ExpertWeights::Paged(paged) => {
4459 // With the device router the resident path reads the router's normed row on the
4460 // chip; read the same row back (exact: see ribbon.rs). Host routing already has it.
4461 let row: &[f32] = match (device_router, addrs.is_some()) {
4462 (Some(router), true) => {
4463 if post_device.is_empty() {
4464 post_device = vec![0.0f32; h];
4465 router.read_post(&mut post_device).map_err(|e| {
4466 format!("layer {layer_idx} router readback: {e}")
4467 })?;
4468 }
4469 &post_device
4470 }
4471 _ => &post,
4472 };
4473 let f = paged.ffn(
4474 layer_idx,
4475 &experts,
4476 row,
4477 &mut gu_out,
4478 &mut act_all,
4479 &mut down_all,
4480 )?;
4481 timing.chip_ns += f.chip_ns;
4482 timing.host_ns += f.host_ns;
4483 timing.launches += f.launches;
4484 timing.page_ns += f.page_ns;
4485 let th = Instant::now();
4486 for (slot, &w) in topk_weights.iter().enumerate() {
4487 for (m, d) in moe_out.iter_mut().zip(&down_all[slot * h..(slot + 1) * h]) {
4488 *m += w * d;
4489 }
4490 }
4491 timing.host_ns += th.elapsed().as_nanos() as u64;
4492 }
4493 }
4494 for (xi, m) in x.iter_mut().zip(&moe_out) {
4495 *xi += m;
4496 }
4497 timing.experts_ns += t4.elapsed().as_nanos() as u64;
4498
4499 if traced {
4500 self.traces.push(LayerTrace {
4501 layer: layer_idx,
4502 pos,
4503 x_in,
4504 attn_proj: attn_proj.clone(),
4505 post: post.clone(),
4506 post_device,
4507 experts: experts.clone(),
4508 weights: topk_weights.clone(),
4509 moe_out: moe_out.clone(),
4510 x_out: x.clone(),
4511 });
4512 }
4513 }
4514 let t5 = Instant::now();
4515 let mut hidden = vec![0.0f32; h];
4516 rmsnorm(&x, &self.weights.final_norm, eps, &mut hidden);
4517 timing.host_ns += t5.elapsed().as_nanos() as u64;
4518 self.pos = pos + 1;
4519 self.history.push(token);
4520 timing.total_ns = t_step.elapsed().as_nanos() as u64;
4521 self.last_timing = timing;
4522 Ok(hidden)
4523 }
4524
4525 /// Vocabulary logits of a final hidden state (one lm_head launch), added to `last_timing`.
4526 pub fn logits(&mut self, hidden: &[f32]) -> Result<Vec<f32>, String> {
4527 // A one-list decode step already ran the lm_head on the chip: read its logits back.
4528 if let Some(r) = self.dgraph_take_logits() {
4529 return r;
4530 }
4531 let t0 = Instant::now();
4532 let mut logits = vec![0.0f32; self.weights.config.vocab];
4533 let ns = match &self.weights.lm_head {
4534 LmHead::Dense(m) => m.matmul_f32(1, hidden, &mut logits),
4535 LmHead::Gemv(g) => g.logits_f32(hidden, &mut logits),
4536 }
4537 .map_err(|e| format!("lm_head: {e}"))?;
4538 let dt = t0.elapsed().as_nanos() as u64;
4539 self.last_timing.lm_head_ns += dt;
4540 self.last_timing.total_ns += dt;
4541 self.last_timing.chip_ns += ns;
4542 self.last_timing.launches += 1;
4543 Ok(logits)
4544 }
4545
4546 /// Prefill `prompt` then decode with `sampler(logits, step)`; `on_token` gets every emitted
4547 /// token and may return `false` to cancel. Stop ids are consumed, never emitted. The engine
4548 /// is reset first (one sequence at a time).
4549 pub fn generate_with(
4550 &mut self,
4551 prompt: &[u32],
4552 params: &GenerateParams,
4553 sampler: &mut dyn FnMut(&[f32], usize) -> u32,
4554 on_token: &mut dyn FnMut(u32) -> bool,
4555 ) -> Result<GenerateOutcome, String> {
4556 self.generate_inner(prompt, params, sampler, false, on_token)
4557 }
4558
4559 /// `generate_with`; `argmax_sampler` says the sampler is the plain argmax (a greedy
4560 /// `sample_next`), so a one-list decode step's own chip argmax can stand in for it.
4561 fn generate_inner(
4562 &mut self,
4563 prompt: &[u32],
4564 params: &GenerateParams,
4565 sampler: &mut dyn FnMut(&[f32], usize) -> u32,
4566 argmax_sampler: bool,
4567 on_token: &mut dyn FnMut(u32) -> bool,
4568 ) -> Result<GenerateOutcome, String> {
4569 self.dgraph_clear();
4570 if prompt.is_empty() {
4571 return Err("empty prompt".into());
4572 }
4573 if prompt.len() >= self.kv.capacity() {
4574 return Err(format!(
4575 "prompt of {} tokens, context is {}",
4576 prompt.len(),
4577 self.kv.capacity()
4578 ));
4579 }
4580 // Prefix reuse: the KV of the longest common prefix with the stored history stays; at
4581 // least the last prompt token is always stepped so the logits come from this prompt.
4582 let common = self
4583 .history
4584 .iter()
4585 .zip(prompt)
4586 .take_while(|(a, b)| a == b)
4587 .count();
4588 let reused = common.min(prompt.len() - 1);
4589 if reused > 0 {
4590 self.rewind(reused);
4591 } else {
4592 self.reset();
4593 }
4594 let t0 = Instant::now();
4595 let mut hidden = Vec::new();
4596 let mut prefill_timing = StepTiming::default();
4597 let whole =
4598 self.whole_prompt_prefill(&prompt[reused..], &mut hidden, &mut prefill_timing)?;
4599 for chunk in prompt[reused + whole..].chunks(self.prefill_chunk.max(1)) {
4600 hidden = self.step_batch(chunk)?;
4601 prefill_timing.add(&self.last_timing);
4602 }
4603 let prefill_ms = t0.elapsed().as_millis() as u64;
4604 // The first decode step is the lm_head of the prefill's hidden state: start its timing
4605 // from zero, so the last prefill step is not counted twice (once here, once in decode).
4606 self.last_timing = StepTiming::default();
4607 let t1 = Instant::now();
4608 let mut decode_timing = StepTiming::default();
4609 let mut emitted = 0usize;
4610 let mut finish = FinishReason::Length;
4611 let mut step = 0usize;
4612 loop {
4613 if emitted >= params.max_new_tokens {
4614 break;
4615 }
4616 let next = match self.dgraph_take_greedy(argmax_sampler) {
4617 // The one-list step already took the argmax on the chip (same rule as sample_argmax).
4618 Some(t) => {
4619 decode_timing.add(&self.last_timing);
4620 t
4621 }
4622 None => {
4623 let logits = self.logits(&hidden)?;
4624 decode_timing.add(&self.last_timing);
4625 sampler(&logits, step)
4626 }
4627 };
4628 step += 1;
4629 if params.stop_token_ids.contains(&next) {
4630 finish = FinishReason::Stop;
4631 break;
4632 }
4633 emitted += 1;
4634 if !on_token(next) {
4635 finish = FinishReason::Cancelled;
4636 break;
4637 }
4638 if emitted >= params.max_new_tokens || self.pos >= self.kv.capacity() {
4639 break;
4640 }
4641 hidden = self.decode_step(next)?;
4642 }
4643 Ok(GenerateOutcome {
4644 emitted_tokens: emitted,
4645 finish,
4646 prefill_ms,
4647 decode_ms: t1.elapsed().as_millis() as u64,
4648 prompt_tokens: prompt.len(),
4649 reused_prompt_tokens: reused,
4650 decode_timing,
4651 prefill_timing,
4652 })
4653 }
4654
4655 /// `generate_with` using [`sample_next`] (the door's sampling rule).
4656 pub fn generate(
4657 &mut self,
4658 prompt: &[u32],
4659 params: &GenerateParams,
4660 on_token: &mut dyn FnMut(u32) -> bool,
4661 ) -> Result<GenerateOutcome, String> {
4662 let p = params.clone();
4663 // sample_next is the plain argmax at temperature <= 0.001 (no top-k mask; sample_with_params greedy).
4664 let argmax = params.temperature <= 0.001;
4665 self.generate_inner(
4666 prompt,
4667 params,
4668 &mut |logits, step| sample_next(logits, &p, step),
4669 argmax,
4670 on_token,
4671 )
4672 }
4673}
4674
4675/// The library entry for the HTTP door: `&self` generation behind one lock (one sequence at a
4676/// time, as the door's contract says). `Send + Sync`.
4677pub struct OmegaEngine {
4678 inner: Mutex<Qwen3MoeOmegaEngine>,
4679 max_context: usize,
4680 pub load_report: LoadReport,
4681}
4682
4683impl OmegaEngine {
4684 /// Loads the checkpoint at `dir` onto Omega with a KV for `max_context` tokens.
4685 pub fn load(
4686 dir: &Path,
4687 max_context: usize,
4688 progress: &mut dyn FnMut(&str),
4689 ) -> Result<Self, String> {
4690 Self::load_with(dir, max_context, WeightFormat::Bf16, progress)
4691 }
4692
4693 /// As [`Self::load`] with a chosen [`WeightFormat`].
4694 pub fn load_with(
4695 dir: &Path,
4696 max_context: usize,
4697 format: WeightFormat,
4698 progress: &mut dyn FnMut(&str),
4699 ) -> Result<Self, String> {
4700 let (engine, load_report) =
4701 Qwen3MoeOmegaEngine::load_omega_with(dir, max_context, format, progress)?;
4702 let max_context = engine.max_context_tokens();
4703 Ok(Self {
4704 inner: Mutex::new(engine),
4705 max_context,
4706 load_report,
4707 })
4708 }
4709
4710 pub fn from_engine(engine: Qwen3MoeOmegaEngine, load_report: LoadReport) -> Self {
4711 let max_context = engine.max_context_tokens();
4712 Self {
4713 inner: Mutex::new(engine),
4714 max_context,
4715 load_report,
4716 }
4717 }
4718
4719 pub fn kind(&self) -> &str {
4720 "omega"
4721 }
4722
4723 pub fn max_context_tokens(&self) -> usize {
4724 self.max_context
4725 }
4726
4727 pub fn generate(
4728 &self,
4729 prompt: &[u32],
4730 params: &GenerateParams,
4731 on_token: &mut dyn FnMut(u32) -> bool,
4732 ) -> Result<GenerateOutcome, String> {
4733 let mut g = self
4734 .inner
4735 .lock()
4736 .map_err(|_| "engine lock poisoned".to_string())?;
4737 g.generate(prompt, params, on_token)
4738 }
4739
4740 /// Same with the caller's sampler (the door passes its `sample_next`).
4741 pub fn generate_with(
4742 &self,
4743 prompt: &[u32],
4744 params: &GenerateParams,
4745 sampler: &mut dyn FnMut(&[f32], usize) -> u32,
4746 on_token: &mut dyn FnMut(u32) -> bool,
4747 ) -> Result<GenerateOutcome, String> {
4748 let mut g = self
4749 .inner
4750 .lock()
4751 .map_err(|_| "engine lock poisoned".to_string())?;
4752 g.generate_with(prompt, params, sampler, on_token)
4753 }
4754
4755 pub fn with_engine<R>(
4756 &self,
4757 f: impl FnOnce(&mut Qwen3MoeOmegaEngine) -> R,
4758 ) -> Result<R, String> {
4759 let mut g = self
4760 .inner
4761 .lock()
4762 .map_err(|_| "engine lock poisoned".to_string())?;
4763 Ok(f(&mut g))
4764 }
4765}
4766
4767#[cfg(test)]
4768mod forward_tests {
4769 use super::test_support::*;
4770 use super::*;
4771 use crate::qwen3_moe::parity_stats;
4772
4773 /// Plain f32 forward over the dequantised weights (rounded to bf16 as uploaded), no engine
4774 /// code shared: embedding, GQA attention with q/k norms and rope, top-k routing, swiglu
4775 /// experts, lm_head. Returns the logits at every position.
4776 fn naive_forward(src: &MemorySource, c: &Qwen3MoeConfig, tokens: &[u32]) -> Vec<Vec<f32>> {
4777 let r = |v: f32| bf16_to_f32(f32_to_bf16(v));
4778 let bf = |name: &str| -> Vec<f32> {
4779 let (_, _, b) = &src.tensors[name];
4780 b.chunks_exact(2)
4781 .map(|x| bf16_to_f32(u16::from_le_bytes([x[0], x[1]])))
4782 .collect()
4783 };
4784 let fp8 = |name: &str| -> Vec<f32> { src.fp8_f32(name).0.into_iter().map(r).collect() };
4785 let (h, qd, kvd, hd, i) = (
4786 c.hidden,
4787 c.q_dim(),
4788 c.kv_dim(),
4789 c.head_dim,
4790 c.moe_intermediate,
4791 );
4792 let matvec = |x: &[f32], w: &[f32], out_dim: usize| -> Vec<f32> {
4793 let x: Vec<f32> = x.iter().map(|&v| r(v)).collect();
4794 (0..out_dim)
4795 .map(|o| {
4796 x.iter()
4797 .zip(&w[o * x.len()..(o + 1) * x.len()])
4798 .map(|(a, b)| a * b)
4799 .sum()
4800 })
4801 .collect()
4802 };
4803 let embed = bf("model.embed_tokens.weight");
4804 let lm = bf("lm_head.weight");
4805 let fnorm = bf("model.norm.weight");
4806 let mut keys = vec![Vec::<Vec<f32>>::new(); c.layers];
4807 let mut vals = vec![Vec::<Vec<f32>>::new(); c.layers];
4808 let mut out = Vec::new();
4809 for (pos, &t) in tokens.iter().enumerate() {
4810 let mut x = embed[t as usize * h..(t as usize + 1) * h].to_vec();
4811 for l in 0..c.layers {
4812 let p = format!("model.layers.{l}");
4813 let mut xn = vec![0.0; h];
4814 rmsnorm(
4815 &x,
4816 &bf(&format!("{p}.input_layernorm.weight")),
4817 c.rms_eps,
4818 &mut xn,
4819 );
4820 let q = matvec(&xn, &fp8(&format!("{p}.self_attn.q_proj.weight")), qd);
4821 let k = matvec(&xn, &fp8(&format!("{p}.self_attn.k_proj.weight")), kvd);
4822 let v = matvec(&xn, &fp8(&format!("{p}.self_attn.v_proj.weight")), kvd);
4823 let mut qn = vec![0.0; qd];
4824 let mut kn = vec![0.0; kvd];
4825 rmsnorm_per_head(
4826 &q,
4827 &bf(&format!("{p}.self_attn.q_norm.weight")),
4828 c.rms_eps,
4829 c.q_heads,
4830 hd,
4831 &mut qn,
4832 );
4833 rmsnorm_per_head(
4834 &k,
4835 &bf(&format!("{p}.self_attn.k_norm.weight")),
4836 c.rms_eps,
4837 c.kv_heads,
4838 hd,
4839 &mut kn,
4840 );
4841 apply_rope(
4842 &mut qn,
4843 &mut kn,
4844 pos,
4845 c.q_heads,
4846 c.kv_heads,
4847 hd,
4848 c.rope_theta,
4849 );
4850 keys[l].push(kn.clone());
4851 vals[l].push(v);
4852 let mut att = vec![0.0; qd];
4853 scaled_dot_product_attention_single(
4854 &qn, &keys[l], &vals[l], c.q_heads, c.kv_heads, hd, &mut att,
4855 );
4856 let o = matvec(&att, &fp8(&format!("{p}.self_attn.o_proj.weight")), h);
4857 for j in 0..h {
4858 x[j] += o[j];
4859 }
4860 let mut post = vec![0.0; h];
4861 rmsnorm(
4862 &x,
4863 &bf(&format!("{p}.post_attention_layernorm.weight")),
4864 c.rms_eps,
4865 &mut post,
4866 );
4867 let router = bf(&format!("{p}.mlp.gate.weight"));
4868 let logits: Vec<f32> = (0..c.experts)
4869 .map(|e| {
4870 post.iter()
4871 .zip(&router[e * h..(e + 1) * h])
4872 .map(|(a, b)| a * b)
4873 .sum()
4874 })
4875 .collect();
4876 let plan = MoeBatchPlan::from_logits(&logits, 1, c.experts, c.top_k).unwrap();
4877 for slot in 0..c.top_k {
4878 let e = plan.topk_experts[slot] as usize;
4879 let b = format!("{p}.mlp.experts.{e}");
4880 let g = matvec(&post, &fp8(&format!("{b}.gate_proj.weight")), i);
4881 let u = matvec(&post, &fp8(&format!("{b}.up_proj.weight")), i);
4882 let a: Vec<f32> = (0..i)
4883 .map(|j| g[j] / (1.0 + (-g[j]).exp()) * u[j])
4884 .collect();
4885 let d = matvec(&a, &fp8(&format!("{b}.down_proj.weight")), h);
4886 for j in 0..h {
4887 x[j] += plan.topk_weights[slot] * d[j];
4888 }
4889 }
4890 }
4891 let mut hid = vec![0.0; h];
4892 rmsnorm(&x, &fnorm, c.rms_eps, &mut hid);
4893 out.push(matvec(&hid, &lm, c.vocab));
4894 }
4895 out
4896 }
4897
4898 fn engine() -> (Qwen3MoeOmegaEngine, MemorySource, Qwen3MoeConfig) {
4899 let c = tiny_config();
4900 let mut src = MemorySource::for_config(&c);
4901 let up = RecordingUploader::default();
4902 let (w, _) = load_qwen3_moe_omega_from(&c, &mut src, &up, &mut |_| {}).unwrap();
4903 let kv = HostKv::new(&KvGeometry::from(&c), 32);
4904 (Qwen3MoeOmegaEngine::new(w, Box::new(kv)), src, c)
4905 }
4906
4907 fn engine_with(
4908 format: WeightFormat,
4909 ) -> (
4910 Qwen3MoeOmegaEngine,
4911 MemorySource,
4912 Qwen3MoeConfig,
4913 LoadReport,
4914 ) {
4915 let c = tiny_config();
4916 let mut src = MemorySource::for_config(&c);
4917 let up = RecordingUploader::default();
4918 let (w, report) =
4919 load_qwen3_moe_omega_from_with(&c, &mut src, &up, format, &mut |_| {}).unwrap();
4920 let kv = HostKv::new(&KvGeometry::from(&c), 32);
4921 (Qwen3MoeOmegaEngine::new(w, Box::new(kv)), src, c, report)
4922 }
4923
4924 fn engine_fakes(
4925 format: WeightFormat,
4926 paths: DevicePaths,
4927 fakes: bool,
4928 ) -> Result<(Qwen3MoeOmegaEngine, RecordingUploader, Qwen3MoeConfig), String> {
4929 let c = tiny_config();
4930 let mut src = MemorySource::for_config(&c);
4931 let up = RecordingUploader {
4932 device_fakes: fakes,
4933 ..Default::default()
4934 };
4935 let (w, _) =
4936 load_qwen3_moe_omega_from_paths(&c, &mut src, &up, format, paths, &mut |_| {})?;
4937 let kv = HostKv::new(&KvGeometry::from(&c), 32);
4938 Ok((Qwen3MoeOmegaEngine::new(w, Box::new(kv)), up, c))
4939 }
4940
4941 #[test]
4942 fn decode_graph_switch_refuses_a_load_it_cannot_run_instead_of_falling_back() {
4943 // A host-KV, host-routed load: with the switch on, preparing and generating must both
4944 // fail with the plain reason; with it off, the same engine generates as before.
4945 let (mut e, _, c) = engine();
4946 assert!(!e.decode_graph_on() || dgraph::requested());
4947 e.decode_graph = true;
4948 let err = e.prepare_decode_graph().unwrap_err();
4949 assert!(err.contains("OWN30B_DECODE_GRAPH=1"), "{err}");
4950 let p = GenerateParams::greedy(3, Vec::new());
4951 let err = e.generate(&[1, 2, 3], &p, &mut |_| true).unwrap_err();
4952 assert!(err.contains("OWN30B_DECODE_GRAPH=1"), "{err}");
4953 e.decode_graph = false;
4954 let mut got = Vec::new();
4955 e.generate(&[1, 2, 3], &p, &mut |t| {
4956 got.push(t);
4957 true
4958 })
4959 .unwrap();
4960 assert_eq!(got.len(), 3);
4961 let _ = c;
4962 }
4963
4964 #[test]
4965 fn device_router_and_lm_head_match_the_host_paths_and_add_one_launch_per_layer() {
4966 let tokens = [5u32, 17, 42, 3, 9, 60];
4967 for format in [WeightFormat::Fp8Experts, WeightFormat::Fp8All] {
4968 let (mut host, _, c) = engine_fakes(
4969 format,
4970 DevicePaths {
4971 router: PathChoice::Host,
4972 lm_head: PathChoice::Host,
4973 },
4974 true,
4975 )
4976 .unwrap();
4977 let (mut dev, up, _) = engine_fakes(format, DevicePaths::default(), true).unwrap();
4978 assert!(
4979 host.weights().device_router.is_none()
4980 && matches!(host.weights().lm_head, LmHead::Dense(_))
4981 );
4982 assert!(
4983 dev.weights().device_router.is_some()
4984 && matches!(dev.weights().lm_head, LmHead::Gemv(_))
4985 );
4986 for &t in &tokens {
4987 let hh = host.step(t).unwrap();
4988 let hd = dev.step(t).unwrap();
4989 // Same maths in the same order: the hidden state is bit-identical.
4990 assert_eq!(
4991 hh, hd,
4992 "{format:?}: hidden state differs between host and device routing"
4993 );
4994 let (lh, ld) = (host.logits(&hh).unwrap(), dev.logits(&hd).unwrap());
4995 let s = crate::qwen3_moe::parity_stats(&ld, &lh);
4996 assert!(s.cosine > 0.99999 && s.non_finite == 0, "{format:?}: {s:?}");
4997 assert_eq!(
4998 crate::tensor::sample_argmax(&ld).0,
4999 crate::tensor::sample_argmax(&lh).0
5000 );
5001 }
5002 let attn_launches = 3;
5003 // Device routing: attention 3 + router 1 + gate|up 1 + down 1 per layer, plus the lm_head.
5004 assert_eq!(
5005 dev.last_timing.launches as usize,
5006 c.layers * (attn_launches + 1 + 2) + 1
5007 );
5008 assert_eq!(
5009 host.last_timing.launches as usize,
5010 c.layers * (attn_launches + 2) + 1
5011 );
5012 let d = up.dev.lock().unwrap();
5013 assert_eq!(d.routes, tokens.len() * c.layers);
5014 assert_eq!(d.grouped_dev_calls, tokens.len() * c.layers);
5015 assert_eq!(d.gemv_calls, tokens.len());
5016 }
5017 }
5018
5019 #[test]
5020 fn device_paths_are_refused_when_asked_for_and_missing_and_fall_back_on_auto() {
5021 let dev = DevicePaths {
5022 router: PathChoice::Device,
5023 lm_head: PathChoice::Auto,
5024 };
5025 let e = engine_fakes(WeightFormat::Fp8All, dev, false)
5026 .err()
5027 .expect("no router offered");
5028 assert!(e.contains("device router"), "{e}");
5029 let e = engine_fakes(WeightFormat::Bf16, dev, true)
5030 .err()
5031 .expect("router needs FP8 experts");
5032 assert!(e.contains("FP8 experts"), "{e}");
5033 let head = DevicePaths {
5034 router: PathChoice::Auto,
5035 lm_head: PathChoice::Device,
5036 };
5037 let e = engine_fakes(WeightFormat::Fp8All, head, false)
5038 .err()
5039 .expect("no gemv offered");
5040 assert!(e.contains("lm_head GEMV"), "{e}");
5041 // Auto without an offer is the host/dense path, with FP8 or bf16 experts alike.
5042 for format in [WeightFormat::Bf16, WeightFormat::Fp8All] {
5043 let (eng, _, _) = engine_fakes(format, DevicePaths::default(), false).unwrap();
5044 assert!(
5045 eng.weights().device_router.is_none()
5046 && matches!(eng.weights().lm_head, LmHead::Dense(_))
5047 );
5048 assert!(!eng.device_routing);
5049 }
5050 // Auto with bf16 experts and an offering uploader: no router (it needs FP8 experts), but the GEMV.
5051 let (eng, _, _) = engine_fakes(WeightFormat::Bf16, DevicePaths::default(), true).unwrap();
5052 assert!(
5053 eng.weights().device_router.is_none()
5054 && matches!(eng.weights().lm_head, LmHead::Gemv(_))
5055 );
5056 }
5057
5058 /// Logits of every step of `tokens` from an empty KV, bit patterns.
5059 fn step_bits(e: &mut Qwen3MoeOmegaEngine, tokens: &[u32]) -> Vec<Vec<u32>> {
5060 e.reset();
5061 tokens
5062 .iter()
5063 .map(|&t| {
5064 let h = e.step(t).unwrap();
5065 e.logits(&h).unwrap().iter().map(|v| v.to_bits()).collect()
5066 })
5067 .collect()
5068 }
5069
5070 #[test]
5071 fn draft_mask_off_is_bit_identical_and_on_routes_only_allowed_experts() {
5072 let tokens = [5u32, 17, 42, 3, 9, 60];
5073 for (paths, fakes) in [
5074 (DevicePaths::default(), true),
5075 (
5076 DevicePaths {
5077 router: PathChoice::Host,
5078 lm_head: PathChoice::Host,
5079 },
5080 false,
5081 ),
5082 ] {
5083 let (mut base, up_b, c) = engine_fakes(WeightFormat::Fp8All, paths, fakes).unwrap();
5084 let (mut e, up, _) = engine_fakes(WeightFormat::Fp8All, paths, fakes).unwrap();
5085 let want = step_bits(&mut base, &tokens);
5086 assert!(!e.draft_on());
5087 // Default off: identical, and the device router (when present) still runs.
5088 assert_eq!(step_bits(&mut e, &tokens), want);
5089 assert_eq!(
5090 up.dev.lock().unwrap().routes,
5091 up_b.dev.lock().unwrap().routes
5092 );
5093 // On with every expert allowed: the host path gives the same bits.
5094 let all: Vec<Vec<u32>> = vec![(0..c.experts as u32).collect(); c.layers];
5095 e.set_draft_experts(Some(all)).unwrap();
5096 assert_eq!(step_bits(&mut e, &tokens), want);
5097 // On then off again: identical to never having been on.
5098 e.set_draft_experts(None).unwrap();
5099 assert_eq!(step_bits(&mut e, &tokens), want);
5100 // A restricted mask: only allowed experts are ever chosen, and the output moves.
5101 let allowed = vec![vec![1u32, 3], vec![0u32, 2]];
5102 e.set_draft_experts(Some(allowed.clone())).unwrap();
5103 e.expert_counts = Some(vec![0; c.layers * c.experts]);
5104 assert_ne!(step_bits(&mut e, &tokens), want);
5105 let counts = e.expert_counts.take().unwrap();
5106 for l in 0..c.layers {
5107 for x in 0..c.experts {
5108 let n = counts[l * c.experts + x];
5109 assert_eq!(
5110 n > 0,
5111 allowed[l].contains(&(x as u32)),
5112 "layer {l} expert {x}"
5113 );
5114 }
5115 }
5116 // Batched prefill refuses rather than silently running the full router.
5117 assert!(e
5118 .step_batch(&tokens[..2])
5119 .unwrap_err()
5120 .contains("self-draft"));
5121 }
5122 // Bad masks are refused.
5123 let (mut e, _, c) =
5124 engine_fakes(WeightFormat::Fp8All, DevicePaths::default(), true).unwrap();
5125 assert!(e.set_draft_experts(Some(vec![vec![0, 1]])).is_err());
5126 assert!(e
5127 .set_draft_experts(Some(vec![vec![0, 0]; c.layers]))
5128 .is_err());
5129 assert!(e
5130 .set_draft_experts(Some(vec![vec![0, c.experts as u32]; c.layers]))
5131 .is_err());
5132 assert!(!e.draft_on());
5133 }
5134
5135 #[test]
5136 fn device_router_trace_keeps_the_host_post_as_oracle_input_and_the_mutant_forces_host_routing()
5137 {
5138 let (mut eng, up, c) =
5139 engine_fakes(WeightFormat::Fp8All, DevicePaths::default(), true).unwrap();
5140 eng.trace_layers = vec![0, 1];
5141 for &t in &[7u32, 1, 33] {
5142 eng.step(t).unwrap();
5143 }
5144 assert_eq!(eng.traces.len(), 6);
5145 for t in &eng.traces {
5146 assert_eq!(t.post_device.len(), c.hidden);
5147 assert_eq!(
5148 t.post, t.post_device,
5149 "fake router computes the same RMSNorm as the host"
5150 );
5151 assert_eq!(t.experts.len(), c.top_k);
5152 }
5153 let routes_before = up.dev.lock().unwrap().routes;
5154 // The host routing mutant swaps ids on the host: it must take the host path (no router call).
5155 eng.traces.clear();
5156 eng.reset();
5157 eng.routing_mutant = true;
5158 eng.step(7).unwrap();
5159 assert_eq!(
5160 up.dev.lock().unwrap().routes,
5161 routes_before,
5162 "mutant steps are host-routed"
5163 );
5164 assert_eq!(eng.last_timing.launches as usize, c.layers * (3 + 2));
5165 eng.routing_mutant = false;
5166 eng.device_routing = false;
5167 eng.reset();
5168 eng.step(7).unwrap();
5169 assert_eq!(
5170 up.dev.lock().unwrap().routes,
5171 routes_before,
5172 "device_routing=false is host routing"
5173 );
5174 }
5175
5176 fn engine_gemm(
5177 gemm: bool,
5178 device: bool,
5179 ) -> (Qwen3MoeOmegaEngine, RecordingUploader, Qwen3MoeConfig) {
5180 let c = tiny_config();
5181 let mut src = MemorySource::for_config(&c);
5182 let up = RecordingUploader {
5183 device_fakes: device,
5184 gemm_fakes: gemm,
5185 ..Default::default()
5186 };
5187 let paths = if device {
5188 DevicePaths::default()
5189 } else {
5190 DevicePaths {
5191 router: PathChoice::Host,
5192 lm_head: PathChoice::Host,
5193 }
5194 };
5195 let (w, _) = load_qwen3_moe_omega_from_paths(
5196 &c,
5197 &mut src,
5198 &up,
5199 WeightFormat::Fp8All,
5200 paths,
5201 &mut |_| {},
5202 )
5203 .unwrap();
5204 let kv = HostKv::new(&KvGeometry::from(&c), 32);
5205 (Qwen3MoeOmegaEngine::new(w, Box::new(kv)), up, c)
5206 }
5207
5208 #[test]
5209 fn gemm_prefill_matches_the_gemv_and_per_token_paths_with_one_launch_per_projection() {
5210 let tokens = [5u32, 17, 42, 3, 9, 60, 7, 1, 33, 12, 25];
5211 let (mut per_token, _, c) = engine_gemm(false, false);
5212 let mut want = Vec::new();
5213 for &t in &tokens {
5214 want = per_token.step(t).unwrap();
5215 }
5216 // The GEMV batch path (no GEMM offered), chunks of 4.
5217 let (mut gemv, _, _) = engine_gemm(false, false);
5218 assert!(!gemv.prefill_gemm);
5219 let mut got = Vec::new();
5220 for chunk in tokens.chunks(4) {
5221 got = gemv.step_batch(chunk).unwrap();
5222 }
5223 assert_eq!(got, want, "GEMV batch differs from per-token");
5224 // The GEMM batch path, host routing and device routing, several chunk sizes.
5225 for device in [false, true] {
5226 for chunk_len in [11usize, 4, 3] {
5227 let (mut eng, up, _) = engine_gemm(true, device);
5228 assert!(eng.prefill_gemm, "the offered GEMM is used by default");
5229 eng.prefill_device_routing = device;
5230 let mut hidden = Vec::new();
5231 for chunk in tokens.chunks(chunk_len) {
5232 hidden = eng.step_batch(chunk).unwrap();
5233 // q|k|v, o, gate|up, down once per layer, attention per token, and one router launch per token when device-routed.
5234 let m = chunk.len();
5235 assert_eq!(
5236 eng.last_timing.launches as usize,
5237 c.layers * (4 + m + if device { m } else { 0 })
5238 );
5239 }
5240 assert_eq!(hidden, want, "GEMM batch (device routing {device}, chunk {chunk_len}) differs from per-token");
5241 assert_eq!(eng.position(), tokens.len());
5242 let d = up.dev.lock().unwrap();
5243 assert_eq!(
5244 d.gemm_calls,
5245 tokens.chunks(chunk_len).count() * c.layers * 4
5246 );
5247 assert_eq!(d.gemm_rows, tokens.len() * c.layers * (2 + 2 * c.top_k));
5248 assert_eq!(d.routes, if device { tokens.len() * c.layers } else { 0 });
5249 }
5250 }
5251 }
5252
5253 #[test]
5254 fn gemm_prefill_routing_mutant_changes_the_result_and_forces_host_routing() {
5255 let tokens = [5u32, 17, 42, 3, 9];
5256 let (mut clean, _, _) = engine_gemm(true, true);
5257 let want = clean.step_batch(&tokens).unwrap();
5258 let (mut bad, up, _) = engine_gemm(true, true);
5259 bad.prefill_device_routing = true;
5260 bad.routing_mutant = true;
5261 let got = bad.step_batch(&tokens).unwrap();
5262 assert_ne!(got, want, "swapped experts must change the hidden state");
5263 assert_eq!(
5264 up.dev.lock().unwrap().routes,
5265 0,
5266 "mutant steps are host-routed"
5267 );
5268 }
5269
5270 #[test]
5271 fn fp8_paths_match_the_naive_reference_with_fewer_launches() {
5272 let tokens = [5u32, 17, 42, 3, 9, 60];
5273 for format in [WeightFormat::Fp8Experts, WeightFormat::Fp8All] {
5274 let (mut eng, src, c, report) = engine_with(format);
5275 assert_eq!(report.format, format);
5276 let want = naive_forward(&src, &c, &tokens);
5277 for (pos, &t) in tokens.iter().enumerate() {
5278 let hid = eng.step(t).unwrap();
5279 let got = eng.logits(&hid).unwrap();
5280 let s = parity_stats(&got, &want[pos]);
5281 assert!(
5282 s.cosine > 0.9999 && s.non_finite == 0,
5283 "{format:?} pos {pos}: {s:?}"
5284 );
5285 assert_eq!(
5286 crate::tensor::sample_argmax(&got).0,
5287 crate::tensor::sample_argmax(&want[pos]).0,
5288 "{format:?} pos {pos}"
5289 );
5290 }
5291 // Experts: 2 launches per layer instead of 2 * top_k; attention still 3.
5292 assert_eq!(
5293 eng.last_timing.launches as usize,
5294 c.layers * (3 + 2) + 1,
5295 "{format:?}"
5296 );
5297 // Resident bytes: FP8 experts are 1 byte + f32 block scales, attention per format.
5298 let (h, i, e) = (c.hidden, c.moe_intermediate, c.experts);
5299 let experts = e * (2 * i * h + h * i)
5300 + e * 4 * (2 * (i / 128) * (h / 128) + (h / 128) * (i / 128));
5301 let attn = if format == WeightFormat::Fp8All {
5302 c.qkv_n() * h
5303 + 4 * (c.qkv_n() / 128) * (h / 128)
5304 + h * c.q_dim()
5305 + 4 * (h / 128) * (c.q_dim() / 128)
5306 } else {
5307 2 * (h * c.qkv_n() + c.q_dim() * h)
5308 };
5309 assert_eq!(
5310 report.resident_bytes,
5311 c.layers * (experts + attn) + 2 * h * c.vocab,
5312 "{format:?}"
5313 );
5314 }
5315 }
5316
5317 #[test]
5318 fn prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run() {
5319 let (mut cold, _, c, _) = engine_with(WeightFormat::Fp8All);
5320 let (mut warm, _, _, _) = engine_with(WeightFormat::Fp8All);
5321 let p = GenerateParams::greedy(4, vec![]);
5322 let turn1 = [5u32, 17, 42, 3, 9, 60];
5323 let mut reply1 = Vec::new();
5324 let o1 = warm
5325 .generate(&turn1, &p, &mut |t| {
5326 reply1.push(t);
5327 true
5328 })
5329 .unwrap();
5330 assert_eq!(o1.reused_prompt_tokens, 0);
5331 assert_eq!(
5332 warm.history().len(),
5333 turn1.len() + 3,
5334 "prompt plus every stepped reply token"
5335 );
5336 // Turn 2 resends turn 1, the reply, and new user tokens (a chat app resending the thread).
5337 let mut turn2 = turn1.to_vec();
5338 turn2.extend_from_slice(&reply1);
5339 turn2.extend_from_slice(&[11, 23, 8]);
5340 let mut warm_out = Vec::new();
5341 let o2 = warm
5342 .generate(&turn2, &p, &mut |t| {
5343 warm_out.push(t);
5344 true
5345 })
5346 .unwrap();
5347 assert_eq!(
5348 o2.reused_prompt_tokens,
5349 turn1.len() + 3,
5350 "prompt + stepped reply tokens reused"
5351 );
5352 let mut cold_out = Vec::new();
5353 let o3 = cold
5354 .generate(&turn2, &p, &mut |t| {
5355 cold_out.push(t);
5356 true
5357 })
5358 .unwrap();
5359 assert_eq!(o3.reused_prompt_tokens, 0);
5360 assert_eq!(
5361 warm_out, cold_out,
5362 "warm (prefix reused) and cold runs must agree token for token"
5363 );
5364 assert_eq!(warm.position(), cold.position());
5365 // A prompt equal to the whole history still steps its last token (fresh logits).
5366 let hist = warm.history().to_vec();
5367 let o4 = warm.generate(&hist, &p, &mut |_| true).unwrap();
5368 assert_eq!(o4.reused_prompt_tokens, hist.len() - 1);
5369 // An unrelated prompt starts cold.
5370 let o5 = warm.generate(&[1, 2, 3], &p, &mut |_| true).unwrap();
5371 assert_eq!(o5.reused_prompt_tokens, 0);
5372 assert!(c.layers > 0);
5373 }
5374
5375 #[test]
5376 fn batched_prefill_matches_token_at_a_time_bit_for_bit_with_fewer_launches() {
5377 let argmax = |lg: &[f32]| {
5378 lg.iter()
5379 .enumerate()
5380 .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
5381 .unwrap()
5382 .0 as u32
5383 };
5384 let (mut one, _, c, _) = engine_with(WeightFormat::Fp8All);
5385 let (mut batched, _, _, _) = engine_with(WeightFormat::Fp8All);
5386 assert!(batched.batched_prefill_possible());
5387 one.prefill_chunk = 1;
5388 batched.prefill_chunk = PREFILL_CHUNK;
5389 // 12 tokens: one full chunk of 8 and a tail of 4.
5390 let prompt = [5u32, 17, 42, 3, 9, 60, 11, 23, 8, 2, 7, 19];
5391 let p = GenerateParams::greedy(3, vec![]);
5392 let (mut l1, mut l2, mut t1, mut t2) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
5393 let o1 = one
5394 .generate_with(
5395 &prompt,
5396 &p,
5397 &mut |lg, _| {
5398 l1.push(lg.to_vec());
5399 argmax(lg)
5400 },
5401 &mut |t| {
5402 t1.push(t);
5403 true
5404 },
5405 )
5406 .unwrap();
5407 let o2 = batched
5408 .generate_with(
5409 &prompt,
5410 &p,
5411 &mut |lg, _| {
5412 l2.push(lg.to_vec());
5413 argmax(lg)
5414 },
5415 &mut |t| {
5416 t2.push(t);
5417 true
5418 },
5419 )
5420 .unwrap();
5421 assert_eq!(t1, t2, "greedy tokens after batched prefill");
5422 assert_eq!(
5423 l1, l2,
5424 "logits after batched prefill must equal token-at-a-time bit for bit"
5425 );
5426 assert_eq!(one.history(), batched.history());
5427 // Launches: 5 per layer per token at chunk 1; 4 + tokens per layer per chunk when batched.
5428 assert_eq!(
5429 o1.prefill_timing.launches as usize,
5430 prompt.len() * c.layers * 5
5431 );
5432 assert_eq!(
5433 o2.prefill_timing.launches as usize,
5434 c.layers * ((4 + 8) + (4 + 4))
5435 );
5436 // A bf16 engine has no batched path: chunk 8 falls back to token-at-a-time, same launches as chunk 1.
5437 let (mut bf, _, _, _) = engine_with(WeightFormat::Bf16);
5438 assert!(!bf.batched_prefill_possible());
5439 bf.prefill_chunk = PREFILL_CHUNK;
5440 let o3 = bf.generate(&prompt, &p, &mut |_| true).unwrap();
5441 assert_eq!(
5442 o3.prefill_timing.launches as usize,
5443 prompt.len() * c.layers * (3 + 2 * c.top_k)
5444 );
5445 }
5446
5447 #[test]
5448 fn fp8_experts_path_agrees_with_the_bf16_path_and_catches_the_routing_mutant() {
5449 let tokens = [7u32, 1, 33, 12];
5450 let (mut a, _, _, _) = engine_with(WeightFormat::Bf16);
5451 let (mut b, _, c, _) = engine_with(WeightFormat::Fp8Experts);
5452 a.trace_layers = vec![0];
5453 b.trace_layers = vec![0];
5454 for &t in &tokens {
5455 let ha = a.step(t).unwrap();
5456 let la = a.logits(&ha).unwrap();
5457 let hb = b.step(t).unwrap();
5458 let lb = b.logits(&hb).unwrap();
5459 let s = parity_stats(&lb, &la);
5460 assert!(s.cosine > 0.9999, "{s:?}");
5461 }
5462 for (ta, tb) in a.traces.iter().zip(&b.traces) {
5463 assert_eq!(ta.experts, tb.experts, "same routing at pos {}", ta.pos);
5464 let s = parity_stats(&tb.moe_out, &ta.moe_out);
5465 assert!(s.cosine > 0.9999, "moe_out pos {}: {s:?}", ta.pos);
5466 }
5467 let mut m = Qwen3MoeOmegaEngine::new(
5468 engine_with(WeightFormat::Fp8Experts).0.weights,
5469 Box::new(HostKv::new(&KvGeometry::from(&c), 32)),
5470 );
5471 m.trace_layers = vec![0];
5472 m.routing_mutant = true;
5473 for &t in &tokens {
5474 m.step(t).unwrap();
5475 }
5476 let worst = m
5477 .traces
5478 .iter()
5479 .zip(&b.traces)
5480 .map(|(x, y)| parity_stats(&x.moe_out, &y.moe_out).cosine)
5481 .fold(1.0, f64::min);
5482 assert!(
5483 worst < 0.99,
5484 "routing mutant must break the FP8 path too: {worst}"
5485 );
5486 }
5487
5488 #[test]
5489 fn engine_forward_matches_a_naive_reference_at_every_position() {
5490 let (mut eng, src, c) = engine();
5491 let tokens = [5u32, 17, 42, 3, 9, 60];
5492 let want = naive_forward(&src, &c, &tokens);
5493 for (pos, &t) in tokens.iter().enumerate() {
5494 let hid = eng.step(t).unwrap();
5495 let got = eng.logits(&hid).unwrap();
5496 let s = parity_stats(&got, &want[pos]);
5497 assert!(s.cosine > 0.9999 && s.non_finite == 0, "pos {pos}: {s:?}");
5498 assert_eq!(
5499 crate::tensor::sample_argmax(&got).0,
5500 crate::tensor::sample_argmax(&want[pos]).0,
5501 "pos {pos}"
5502 );
5503 }
5504 assert_eq!(eng.position(), tokens.len());
5505 assert_eq!(
5506 eng.last_timing.launches as usize,
5507 c.layers * (3 + c.top_k + c.top_k) + 1
5508 );
5509 }
5510
5511 #[test]
5512 fn routing_mutant_breaks_the_layer_and_the_trace_records_it() {
5513 let (mut eng, _, _) = engine();
5514 eng.trace_layers = vec![0];
5515 eng.step(5).unwrap();
5516 let good = eng.traces[0].clone();
5517 eng.reset();
5518 eng.routing_mutant = true;
5519 eng.step(5).unwrap();
5520 let bad = eng.traces[0].clone();
5521 assert_eq!(good.layer, 0);
5522 assert_eq!(
5523 good.post, bad.post,
5524 "attention is untouched by the routing mutant"
5525 );
5526 assert_ne!(good.experts, bad.experts);
5527 let s = parity_stats(&bad.moe_out, &good.moe_out);
5528 assert!(s.cosine < 0.99, "mutant must be caught: {s:?}");
5529 }
5530
5531 #[test]
5532 fn generate_stops_on_stop_ids_caps_length_and_cancels() {
5533 let (mut eng, src, c) = engine();
5534 let prompt = [5u32, 17, 42];
5535 let want = naive_forward(&src, &c, &prompt);
5536 let first = crate::tensor::sample_argmax(&want[2]).0;
5537 // Length cap.
5538 let mut got = Vec::new();
5539 let o = eng
5540 .generate(&prompt, &GenerateParams::greedy(3, vec![]), &mut |t| {
5541 got.push(t);
5542 true
5543 })
5544 .unwrap();
5545 assert_eq!(o.finish, FinishReason::Length);
5546 assert_eq!(o.emitted_tokens, 3);
5547 assert_eq!(got[0], first);
5548 assert_eq!(o.prompt_tokens, 3);
5549 assert_eq!(
5550 eng.position(),
5551 3 + 2,
5552 "the last emitted token is not stepped"
5553 );
5554 // Stop id: the first greedy token is a stop id, nothing emitted.
5555 let o = eng
5556 .generate(
5557 &prompt,
5558 &GenerateParams::greedy(3, vec![first]),
5559 &mut |_| true,
5560 )
5561 .unwrap();
5562 assert_eq!((o.finish, o.emitted_tokens), (FinishReason::Stop, 0));
5563 // Cancel after the first token.
5564 let o = eng
5565 .generate(&prompt, &GenerateParams::greedy(3, vec![]), &mut |_| false)
5566 .unwrap();
5567 assert_eq!((o.finish, o.emitted_tokens), (FinishReason::Cancelled, 1));
5568 // The locked wrapper behaves the same and is Send + Sync.
5569 fn assert_sync<T: Send + Sync>(_: &T) {}
5570 let report = LoadReport {
5571 resident_bytes: 0,
5572 format: WeightFormat::Bf16,
5573 host_bytes: 0,
5574 peak_rss_bytes: None,
5575 peak_rss_before_bytes: None,
5576 seconds: 0.0,
5577 window_api: false,
5578 };
5579 let shared = OmegaEngine::from_engine(eng, report);
5580 assert_sync(&shared);
5581 let o = shared
5582 .generate(&prompt, &GenerateParams::greedy(2, vec![]), &mut |_| true)
5583 .unwrap();
5584 assert_eq!(o.emitted_tokens, 2);
5585 assert_eq!(shared.kind(), "omega");
5586 }
5587
5588 #[test]
5589 fn seeded_sampling_replays_and_greedy_is_argmax() {
5590 let logits: Vec<f32> = (0..50).map(|i| ((i * 7919) % 50) as f32 / 10.0).collect();
5591 let p = GenerateParams {
5592 max_new_tokens: 1,
5593 temperature: 0.7,
5594 top_p: 0.8,
5595 top_k: 20,
5596 seed: 42,
5597 stop_token_ids: vec![],
5598 };
5599 assert_eq!(sample_next(&logits, &p, 3), sample_next(&logits, &p, 3));
5600 let g = GenerateParams::greedy(1, vec![]);
5601 assert_eq!(
5602 sample_next(&logits, &g, 0),
5603 crate::tensor::sample_argmax(&logits).0
5604 );
5605 let mut seen = std::collections::HashSet::new();
5606 for step in 0..64 {
5607 seen.insert(sample_next(&logits, &p, step));
5608 }
5609 assert!(seen.len() > 1 && seen.len() <= 20, "{}", seen.len());
5610 }
5611}
5612
5613// ===========================================================================
5614// Parity harness support: host replays of a traced layer.
5615// ===========================================================================
5616
5617use crate::qwen3_coder::{bf16_words, CoderShardCache, Qwen3CoderAttention};
5618use crate::qwen3_moe::{
5619 parity_stats, reference_moe_forward, reference_router_logits, ParityStats, Qwen3MoeLayer,
5620};
5621
5622/// One layer's attention weights decoded exactly (FP8 x bf16 scale) to f32 row-major, for the
5623/// host replay. About 75 MB per layer.
5624pub fn load_attention_layer_f32(
5625 dir: &Path,
5626 config: &Qwen3MoeConfig,
5627 layer: usize,
5628) -> Result<Qwen3CoderAttention, String> {
5629 let mut cache = CoderShardCache::open(dir).map_err(|e| e.to_string())?;
5630 let (h, qd, kvd, hd) = (
5631 config.hidden,
5632 config.q_dim(),
5633 config.kv_dim(),
5634 config.head_dim,
5635 );
5636 let p = format!("model.layers.{layer}");
5637 let lut = fp8_table();
5638 let mut fp8_f32 = |name: &str, rows: usize, cols: usize| -> Result<Vec<f32>, String> {
5639 let w = cache
5640 .read_raw(name, "F8_E4M3", &[rows, cols], 1)
5641 .map_err(|e| e.to_string())?;
5642 let s = cache
5643 .read_raw(
5644 &format!("{name}_scale_inv"),
5645 "BF16",
5646 &[rows / FP8_BLOCK, cols / FP8_BLOCK],
5647 2,
5648 )
5649 .map_err(|e| e.to_string())?;
5650 let s = bf16_words(&s);
5651 let kb = cols / FP8_BLOCK;
5652 Ok((0..rows * cols)
5653 .map(|idx| {
5654 lut[w[idx] as usize]
5655 * bf16_to_f32(s[(idx / cols / FP8_BLOCK) * kb + (idx % cols) / FP8_BLOCK])
5656 })
5657 .collect())
5658 };
5659 let q_proj = fp8_f32(&format!("{p}.self_attn.q_proj.weight"), qd, h)?;
5660 let k_proj = fp8_f32(&format!("{p}.self_attn.k_proj.weight"), kvd, h)?;
5661 let v_proj = fp8_f32(&format!("{p}.self_attn.v_proj.weight"), kvd, h)?;
5662 let o_proj = fp8_f32(&format!("{p}.self_attn.o_proj.weight"), h, qd)?;
5663 let mut bf16_f32 = |name: &str, n: usize| -> Result<Vec<f32>, String> {
5664 let b = cache
5665 .read_raw(name, "BF16", &[n], 2)
5666 .map_err(|e| e.to_string())?;
5667 Ok(bf16_words(&b).iter().map(|&x| bf16_to_f32(x)).collect())
5668 };
5669 Ok(Qwen3CoderAttention {
5670 q_proj,
5671 k_proj,
5672 v_proj,
5673 o_proj,
5674 q_norm: bf16_f32(&format!("{p}.self_attn.q_norm.weight"), hd)?,
5675 k_norm: bf16_f32(&format!("{p}.self_attn.k_norm.weight"), hd)?,
5676 input_norm: bf16_f32(&format!("{p}.input_layernorm.weight"), h)?,
5677 post_norm: bf16_f32(&format!("{p}.post_attention_layernorm.weight"), h)?,
5678 })
5679}
5680
5681fn matvec_rows(x: &[f32], w: &[f32], out_dim: usize) -> Vec<f32> {
5682 let k = x.len();
5683 (0..out_dim)
5684 .into_par_iter()
5685 .map(|o| {
5686 w[o * k..(o + 1) * k]
5687 .iter()
5688 .zip(x)
5689 .map(|(a, b)| a * b)
5690 .sum()
5691 })
5692 .collect()
5693}
5694
5695/// Host replay of one layer's attention over consecutive traces (positions 0..n of one
5696/// sequence) with exact f32 weights and an f32 KV: returns the `attn_proj` the host computes
5697/// for each trace, to compare with the chip's `trace.attn_proj`.
5698pub fn replay_attention(
5699 config: &Qwen3MoeConfig,
5700 attn: &Qwen3CoderAttention,
5701 traces: &[LayerTrace],
5702) -> Vec<Vec<f32>> {
5703 let (h, qd, kvd, hd, eps) = (
5704 config.hidden,
5705 config.q_dim(),
5706 config.kv_dim(),
5707 config.head_dim,
5708 config.rms_eps,
5709 );
5710 let mut keys: Vec<Vec<f32>> = Vec::new();
5711 let mut vals: Vec<Vec<f32>> = Vec::new();
5712 let mut out = Vec::new();
5713 for t in traces {
5714 let mut xn = vec![0.0; h];
5715 rmsnorm(&t.x_in, &attn.input_norm, eps, &mut xn);
5716 let q = matvec_rows(&xn, &attn.q_proj, qd);
5717 let k = matvec_rows(&xn, &attn.k_proj, kvd);
5718 let v = matvec_rows(&xn, &attn.v_proj, kvd);
5719 let mut qn = vec![0.0; qd];
5720 let mut kn = vec![0.0; kvd];
5721 rmsnorm_per_head(&q, &attn.q_norm, eps, config.q_heads, hd, &mut qn);
5722 rmsnorm_per_head(&k, &attn.k_norm, eps, config.kv_heads, hd, &mut kn);
5723 apply_rope(
5724 &mut qn,
5725 &mut kn,
5726 t.pos,
5727 config.q_heads,
5728 config.kv_heads,
5729 hd,
5730 config.rope_theta,
5731 );
5732 keys.push(kn);
5733 vals.push(v);
5734 let mut att = vec![0.0; qd];
5735 scaled_dot_product_attention_single(
5736 &qn,
5737 &keys,
5738 &vals,
5739 config.q_heads,
5740 config.kv_heads,
5741 hd,
5742 &mut att,
5743 );
5744 out.push(matvec_rows(&att, &attn.o_proj, h));
5745 }
5746 out
5747}
5748
5749/// Host oracle of one traced MoE: routes `trace.post` with the capsule's router, runs the exact
5750/// FP8 oracle, and reports the parity of the chip's `moe_out` plus whether the chip's expert
5751/// choice equals the oracle's.
5752pub struct MoeParity {
5753 pub stats: ParityStats,
5754 pub oracle_experts: Vec<u32>,
5755 pub routing_agrees: bool,
5756 /// Largest |chip weight - oracle weight| over the chip's experts (an expert the oracle did
5757 /// not pick counts as its full weight). Cosine of `moe_out` is blind to a common scale, so the
5758 /// weights are compared directly.
5759 pub max_weight_err: f32,
5760}
5761
5762pub fn replay_moe(layer: &Qwen3MoeLayer, trace: &LayerTrace, top_k: usize) -> MoeParity {
5763 let logits = reference_router_logits(layer, &trace.post, 1);
5764 let plan =
5765 MoeBatchPlan::from_logits(&logits, 1, layer.router_bf16().len() / layer.hidden, top_k)
5766 .expect("plan");
5767 let want = reference_moe_forward(layer, &trace.post, &plan);
5768 let mut chip_sorted = trace.experts.clone();
5769 chip_sorted.sort_unstable();
5770 let mut oracle_sorted = plan.topk_experts.clone();
5771 oracle_sorted.sort_unstable();
5772 let max_weight_err = trace
5773 .experts
5774 .iter()
5775 .zip(&trace.weights)
5776 .map(|(id, w)| {
5777 let want = plan
5778 .topk_experts
5779 .iter()
5780 .position(|e| e == id)
5781 .map_or(0.0, |p| plan.topk_weights[p]);
5782 (w - want).abs()
5783 })
5784 .fold(0.0f32, f32::max);
5785 MoeParity {
5786 stats: parity_stats(&trace.moe_out, &want),
5787 routing_agrees: chip_sorted == oracle_sorted,
5788 oracle_experts: plan.topk_experts,
5789 max_weight_err,
5790 }
5791}
5792
5793/// SwiGLU of one expert's gate|up row: `act[j] = silu(gu[j]) * gu[i + j]`.
5794fn swiglu(gu: &[f32], i: usize, act: &mut [f32]) {
5795 for j in 0..i {
5796 let g = gu[j];
5797 act[j] = g / (1.0 + (-g).exp()) * gu[i + j];
5798 }
5799}
5800
5801/// True when every layer's FP8 projections (q|k|v, o, gate|up, down) carry the prefill GEMM.
5802fn gemm_everywhere(weights: &Qwen3MoeOmegaWeights) -> bool {
5803 !weights.layers.is_empty()
5804 && weights.layers.iter().all(|l| match (&l.attn, &l.experts) {
5805 (AttnWeights::Fp8 { qkv, o }, ExpertWeights::Fp8 { gate_up, down }) => {
5806 qkv.has_gemm() && o.has_gemm() && gate_up.has_gemm() && down.has_gemm()
5807 }
5808 _ => false,
5809 })
5810}
5811
5812/// Router logits for every row of `post` (`m x h`): `logits[r][ex] = dot(router[ex], post[r])`,
5813/// each dot summed in index order (so the value does not depend on the thread count).
5814fn router_logits(router: &[f32], post: &[f32], h: usize, e: usize, logits: &mut [f32]) {
5815 logits
5816 .par_chunks_mut(e)
5817 .zip(post.par_chunks(h))
5818 .for_each(|(lr, pr)| {
5819 for (ex, l) in lr.iter_mut().enumerate() {
5820 *l = router[ex * h..(ex + 1) * h]
5821 .iter()
5822 .zip(pr)
5823 .map(|(a, b)| a * b)
5824 .sum();
5825 }
5826 });
5827}
5828
5829/// SwiGLU of every gate|up row (`gu`: rows x 2i) into `act` (rows x i).
5830fn swiglu_rows(gu: &[f32], act: &mut [f32], i: usize) {
5831 act.par_chunks_mut(i)
5832 .zip(gu.par_chunks(2 * i))
5833 .for_each(|(a, g)| swiglu(g, i, a));
5834}
5835
5836/// MoE combine and residual add per token: `x[r] += sum_slot wts[r*top_k+slot] * down[inv[..]]`,
5837/// accumulated in slot order from zero (the order the per-token path uses).
5838fn combine_rows(
5839 x: &mut [f32],
5840 down_sorted: &[f32],
5841 wts: &[f32],
5842 inv: &[u32],
5843 h: usize,
5844 top_k: usize,
5845) {
5846 x.par_chunks_mut(h).enumerate().for_each(|(r, xr)| {
5847 let mut acc = vec![0.0f32; h];
5848 for slot in 0..top_k {
5849 let gi = r * top_k + slot;
5850 let w = wts[gi];
5851 let row = inv[gi] as usize;
5852 for (a, d) in acc.iter_mut().zip(&down_sorted[row * h..(row + 1) * h]) {
5853 *a += w * d;
5854 }
5855 }
5856 for (xi, a) in xr.iter_mut().zip(&acc) {
5857 *xi += a;
5858 }
5859 });
5860}
5861
5862/// Host-only test engine (sc#505, feature `host-test-engine`): a real [`OmegaEngine`] over the
5863/// tiny in-memory Qwen3-MoE checkpoint, host matmuls and a [`HostPoolKv`] (bf16 pool, the
5864/// `HostPagedPoolV1` bytes), so the persistent KV path of the HTTP door can be tested end to end
5865/// without a chip. Never in a server build.
5866#[cfg(feature = "host-test-engine")]
5867pub mod host_test_engine {
5868 use super::test_support::{tiny_config, MemorySource, RecordingUploader};
5869 use super::*;
5870
5871 /// The tiny checkpoint's config (2 layers, 1 KV head of 128, 4 experts, top 2, vocab 64).
5872 pub fn config() -> Qwen3MoeConfig {
5873 tiny_config()
5874 }
5875
5876 /// A fresh engine (same weights every call, so two calls stand for one server restarted) with
5877 /// room for `max_context` tokens.
5878 pub fn engine(format: WeightFormat, max_context: usize) -> Result<OmegaEngine, String> {
5879 let c = tiny_config();
5880 let mut src = MemorySource::for_config(&c);
5881 let up = RecordingUploader::default();
5882 let (w, report) = load_qwen3_moe_omega_from_with(&c, &mut src, &up, format, &mut |_| {})?;
5883 let kv = HostPoolKv::new(&KvGeometry::from(&c), max_context)?;
5884 Ok(OmegaEngine::from_engine(
5885 Qwen3MoeOmegaEngine::new(w, Box::new(kv)),
5886 report,
5887 ))
5888 }
5889}
5890
5891/// Persistent KV export and import on the engine (sc#505), host only.
5892#[cfg(test)]
5893mod kv_persist_tests {
5894 use super::test_support::*;
5895 use super::*;
5896
5897 fn pool_engine(cap: usize) -> Qwen3MoeOmegaEngine {
5898 let c = tiny_config();
5899 let mut src = MemorySource::for_config(&c);
5900 let up = RecordingUploader::default();
5901 let (w, _) =
5902 load_qwen3_moe_omega_from_with(&c, &mut src, &up, WeightFormat::Fp8All, &mut |_| {})
5903 .unwrap();
5904 Qwen3MoeOmegaEngine::new(
5905 w,
5906 Box::new(HostPoolKv::new(&KvGeometry::from(&c), cap).unwrap()),
5907 )
5908 }
5909
5910 fn argmax(lg: &[f32]) -> u32 {
5911 lg.iter()
5912 .enumerate()
5913 .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
5914 .unwrap()
5915 .0 as u32
5916 }
5917
5918 /// Greedy turn: (tokens, every logit vector, reused prompt tokens).
5919 fn turn(
5920 e: &mut Qwen3MoeOmegaEngine,
5921 prompt: &[u32],
5922 n: usize,
5923 ) -> (Vec<u32>, Vec<Vec<f32>>, usize) {
5924 let (mut toks, mut logits) = (Vec::new(), Vec::new());
5925 let o = e
5926 .generate_with(
5927 prompt,
5928 &GenerateParams::greedy(n, vec![]),
5929 &mut |lg, _| {
5930 logits.push(lg.to_vec());
5931 argmax(lg)
5932 },
5933 &mut |t| {
5934 toks.push(t);
5935 true
5936 },
5937 )
5938 .unwrap();
5939 (toks, logits, o.reused_prompt_tokens)
5940 }
5941
5942 fn rows(seed: u64, n: usize) -> Vec<f32> {
5943 (0..n).map(|i| prand(seed, i)).collect()
5944 }
5945
5946 /// The 30B's KV shape (`~/models/qwen3-30b-a3b-instruct-2507-fp8` config.json: 48 layers, 32 q
5947 /// heads, 4 KV heads, head_dim 128, rope_theta 1e7); the other fields do not reach the KV cache.
5948 fn qwen3_30b_kv_config() -> Qwen3MoeConfig {
5949 Qwen3MoeConfig {
5950 layers: 48,
5951 q_heads: 32,
5952 kv_heads: 4,
5953 head_dim: 128,
5954 rope_theta: 1e7,
5955 ..tiny_config()
5956 }
5957 }
5958
5959 // ADR 0004 step 1: the geometry carries exactly the numbers the cache constructors and
5960 // `PoolBlockGeometry::for_config` read from `Qwen3MoeConfig` before the split, so every cache
5961 // and every exported byte is the same.
5962 #[test]
5963 fn kv_geometry_from_config_carries_the_numbers_for_config_read() {
5964 for c in [tiny_config(), qwen3_30b_kv_config()] {
5965 let g = KvGeometry::from(&c);
5966 assert_eq!(
5967 g,
5968 KvGeometry {
5969 layers: c.layers,
5970 q_heads: c.q_heads,
5971 kv_heads: c.kv_heads,
5972 head_dim: c.head_dim,
5973 rope_theta: c.rope_theta,
5974 block_size: KV_BLOCK_SIZE,
5975 }
5976 );
5977 // What `for_config` built before the split, field by field.
5978 let before = kvio::PoolBlockGeometry {
5979 layers: c.layers,
5980 kv_heads: c.kv_heads,
5981 head_dim: c.head_dim,
5982 block_size: KV_BLOCK_SIZE,
5983 };
5984 assert_eq!(g.pool_block(), before);
5985 assert_eq!(kvio::PoolBlockGeometry::for_geometry(&g), before);
5986 assert_eq!(kvio::PoolBlockGeometry::for_config(&c), before);
5987 }
5988 }
5989
5990 // The three host-buildable caches; OmegaFusedKv needs the chip and real weights (its geometry,
5991 // len and path are covered by the chip gates and `the_fused_cache_fits_only_the_kernel_shape`).
5992 #[test]
5993 fn every_host_buildable_cache_reports_its_geometry_len_and_path_through_the_kv_store_view() {
5994 let c = tiny_config();
5995 let g = KvGeometry::from(&c);
5996 let kvd = c.kv_heads * c.head_dim;
5997 let caches: Vec<(Box<dyn KvAttention>, &str)> = vec![
5998 (Box::new(HostKv::new(&g, 32)), "split"),
5999 (Box::new(HostPoolKv::new(&g, 32).unwrap()), "host-pool"),
6000 (Box::new(OmegaPagedKv::new(&g, 32).unwrap()), "split"),
6001 ];
6002 for (mut kv, path) in caches {
6003 let store: &mut dyn KvStore = &mut *kv;
6004 assert_eq!(store.geometry(), g, "{path}");
6005 assert_eq!(store.path_name(), path);
6006 assert_eq!(store.capacity(), 32, "{path}");
6007 assert_eq!(store.len(), 0, "{path}");
6008 for pos in 0..5 {
6009 kv.append(0, pos, &rows(pos as u64, kvd), &rows(pos as u64 + 1, kvd))
6010 .unwrap();
6011 }
6012 // Layer 1 still holds nothing: the smallest per-layer count.
6013 assert_eq!(kv.len(), 0, "{path}");
6014 for pos in 0..3 {
6015 kv.append(1, pos, &rows(pos as u64, kvd), &rows(pos as u64 + 1, kvd))
6016 .unwrap();
6017 }
6018 assert_eq!(kv.len(), 3, "{path}");
6019 kv.truncate(2);
6020 assert_eq!(kv.len(), 2, "{path}");
6021 // `truncate(0)` is what `reset` was: every layer empty, the next append is at 0.
6022 kv.truncate(0);
6023 assert_eq!(kv.len(), 0, "{path}");
6024 kv.append(0, 0, &rows(9, kvd), &rows(10, kvd)).unwrap();
6025 assert!(
6026 kv.append(1, 1, &rows(9, kvd), &rows(10, kvd)).is_err(),
6027 "{path}"
6028 );
6029 }
6030 }
6031
6032 #[test]
6033 fn pool_caches_refuse_a_block_size_their_layout_does_not_use() {
6034 let g = KvGeometry {
6035 block_size: KV_BLOCK_SIZE * 2,
6036 ..KvGeometry::from(&tiny_config())
6037 };
6038 assert!(HostPoolKv::new(&g, 32).is_err());
6039 assert!(OmegaPagedKv::new(&g, 32).is_err());
6040 }
6041
6042 #[test]
6043 fn the_fused_cache_fits_only_the_kernel_shape() {
6044 use crate::qwen3_moe_omega_dattn::OmegaFusedKv;
6045 assert!(OmegaFusedKv::fits(
6046 &KvGeometry::from(&qwen3_30b_kv_config())
6047 ));
6048 assert!(!OmegaFusedKv::fits(&KvGeometry::from(&tiny_config())));
6049 // The 8B's 8 KV heads wait for K2.
6050 let dense = KvGeometry {
6051 layers: 36,
6052 kv_heads: 8,
6053 ..KvGeometry::from(&qwen3_30b_kv_config())
6054 };
6055 assert!(!OmegaFusedKv::fits(&dense));
6056 }
6057
6058 /// FNV-1a 64 of the `HostPagedPoolV1` export of positions `0..37` filled with `rows`.
6059 fn export_digest(c: &Qwen3MoeConfig, kv: &mut dyn KvAttention) -> (usize, u64) {
6060 let kvd = c.kv_heads * c.head_dim;
6061 for pos in 0..37 {
6062 for l in 0..c.layers {
6063 let s = pos as u64 * 100 + l as u64;
6064 kv.append(l, pos, &rows(s, kvd), &rows(s + 7, kvd)).unwrap();
6065 }
6066 }
6067 let b = kv.export_blocks(0, 37).unwrap().unwrap();
6068 let h = b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| {
6069 (h ^ x as u64).wrapping_mul(0x0000_0100_0000_01b3)
6070 });
6071 (b.len(), h)
6072 }
6073
6074 // ADR 0004 step 1: the payload bytes are those main exported before the split. The digests were
6075 // printed by this same fill and hash on origin/main 559f0f1e (constructors taking the config).
6076 #[test]
6077 fn exported_kv_bytes_match_the_digests_recorded_on_main() {
6078 for (c, want) in [
6079 (tiny_config(), (49_152usize, 0xbbf5_a8d4_5a90_9242u64)),
6080 (qwen3_30b_kv_config(), (4_718_592, 0x60da_5a45_da83_5b1a)),
6081 ] {
6082 let g = KvGeometry::from(&c);
6083 let host = export_digest(&c, &mut HostPoolKv::new(&g, 64).unwrap());
6084 let paged = export_digest(&c, &mut OmegaPagedKv::new(&g, 64).unwrap());
6085 assert_eq!(host, want, "host pool, {} layers", c.layers);
6086 assert_eq!(paged, want, "paged, {} layers", c.layers);
6087 }
6088 }
6089
6090 #[test]
6091 fn paged_and_host_pool_caches_export_the_same_bytes_and_round_trip() {
6092 let c = tiny_config();
6093 let kvd = c.kv_heads * c.head_dim;
6094 // Stub build: a host pool. Linked native build (AIEN_REQUIRE_NATIVE_LIBS=1, abi-qualify
6095 // chip-inference-linked): the resident chip pool. The exported bytes must match either way.
6096 let mut paged = OmegaPagedKv::new(&KvGeometry::from(&c), 64).unwrap();
6097 let mut host = HostPoolKv::new(&KvGeometry::from(&c), 64).unwrap();
6098 for pos in 0..37 {
6099 for l in 0..c.layers {
6100 let (k, v) = (
6101 rows(pos as u64 * 10 + l as u64, kvd),
6102 rows(pos as u64 * 10 + l as u64 + 5, kvd),
6103 );
6104 paged.append(l, pos, &k, &v).unwrap();
6105 host.append(l, pos, &k, &v).unwrap();
6106 }
6107 }
6108 let g = kvio::PoolBlockGeometry::for_config(&c);
6109 for (start, len) in [(0usize, 37usize), (0, 16), (16, 21), (32, 1)] {
6110 let a = paged.export_blocks(start, len).unwrap().unwrap();
6111 let b = host.export_blocks(start, len).unwrap().unwrap();
6112 assert_eq!(a, b, "{start}+{len}");
6113 assert_eq!(a.len(), g.payload_len(len));
6114 kvio::check_payload(&g, len, &a).unwrap();
6115 }
6116 // Past what is stored: refused.
6117 assert!(paged.export_blocks(32, 6).unwrap().is_err());
6118 // Import into a fresh cache in two pieces, export again: identical bytes.
6119 let whole = host.export_blocks(0, 37).unwrap().unwrap();
6120 let mut fresh = OmegaPagedKv::new(&KvGeometry::from(&c), 64).unwrap();
6121 assert!(
6122 fresh
6123 .import_blocks(16, 21, &host.export_blocks(16, 21).unwrap().unwrap())
6124 .unwrap()
6125 .is_err(),
6126 "must start where the cache ends"
6127 );
6128 fresh
6129 .import_blocks(0, 16, &host.export_blocks(0, 16).unwrap().unwrap())
6130 .unwrap()
6131 .unwrap();
6132 fresh
6133 .import_blocks(16, 21, &host.export_blocks(16, 21).unwrap().unwrap())
6134 .unwrap()
6135 .unwrap();
6136 assert_eq!(fresh.export_blocks(0, 37).unwrap().unwrap(), whole);
6137 // The f32 test cache cannot export: None, never a guess.
6138 assert!(HostKv::new(&KvGeometry::from(&c), 8)
6139 .export_blocks(0, 1)
6140 .is_none());
6141 }
6142
6143 #[test]
6144 fn restored_prefix_continues_exactly_like_the_uninterrupted_engine() {
6145 let turn1 = [
6146 5u32, 17, 42, 3, 9, 60, 11, 23, 8, 2, 7, 19, 33, 40, 1, 6, 14, 29,
6147 ];
6148 // Uninterrupted: turn 1, then turn 2 reusing the in-RAM prefix.
6149 let mut live = pool_engine(128);
6150 let (reply1, _, r1) = turn(&mut live, &turn1, 5);
6151 assert_eq!(r1, 0);
6152 let history = live.history().to_vec();
6153 let snapshot = live.export_kv(0, history.len()).unwrap();
6154 let mut turn2 = turn1.to_vec();
6155 turn2.extend_from_slice(&reply1);
6156 turn2.extend_from_slice(&[12, 31, 4]);
6157 let (want, want_logits, reused_live) = turn(&mut live, &turn2, 6);
6158 assert_eq!(
6159 reused_live,
6160 history.len(),
6161 "turn 2 reuses every stepped token of turn 1"
6162 );
6163
6164 // Restarted: a fresh engine (same weights), the parked prefix restored, then turn 2.
6165 let mut restarted = pool_engine(128);
6166 restarted.restore_kv(&history, &snapshot).unwrap();
6167 assert_eq!(restarted.history(), &history[..]);
6168 assert_eq!(restarted.position(), history.len());
6169 assert_eq!(
6170 restarted.export_kv(0, history.len()).unwrap(),
6171 snapshot,
6172 "import then export is byte-identical"
6173 );
6174 assert_eq!(restarted.reusable_prefix(&turn2), reused_live);
6175 let (got, got_logits, reused_restored) = turn(&mut restarted, &turn2, 6);
6176 assert_eq!(
6177 reused_restored, reused_live,
6178 "the restore point is the uninterrupted reuse point"
6179 );
6180 assert_eq!(
6181 got, want,
6182 "restored continuation equals the uninterrupted one"
6183 );
6184 assert_eq!(got_logits, want_logits, "bit for bit");
6185 }
6186
6187 #[test]
6188 fn a_damaged_or_impossible_restore_leaves_a_clean_engine_that_prefills_from_zero() {
6189 let prompt = [5u32, 17, 42, 3, 9, 60, 11, 23, 8, 2];
6190 let mut a = pool_engine(64);
6191 let _ = turn(&mut a, &prompt, 3);
6192 let history = a.history().to_vec();
6193 let mut snap = a.export_kv(0, history.len()).unwrap();
6194 let mut cold = pool_engine(64);
6195 let (want, _, _) = turn(&mut cold, &prompt, 3);
6196
6197 let mut b = pool_engine(64);
6198 let _ = turn(&mut b, &[1, 2, 3, 4], 2);
6199 // Wrong length, a padding byte set, an empty or oversized token list: all refused.
6200 assert!(b.restore_kv(&history, &snap[..snap.len() - 2]).is_err());
6201 assert_eq!(
6202 (b.position(), b.history().len()),
6203 (0, 0),
6204 "reset, not a partial prefix"
6205 );
6206 let last = snap.len() - 1;
6207 snap[last] ^= 1;
6208 assert!(b.restore_kv(&history, &snap).is_err());
6209 assert!(b.restore_kv(&[], &[]).is_err());
6210 assert!(b.restore_kv(&[1u32; 64], &snap).is_err());
6211 assert_eq!((b.position(), b.history().len()), (0, 0));
6212 let (got, _, reused) = turn(&mut b, &prompt, 3);
6213 assert_eq!(reused, 0);
6214 assert_eq!(got, want, "plain prefill after a refused restore");
6215 // An engine whose cache cannot export refuses the park.
6216 let (mut f32_engine, _, _, _) = {
6217 let c = tiny_config();
6218 let mut src = MemorySource::for_config(&c);
6219 let up = RecordingUploader::default();
6220 let (w, r) = load_qwen3_moe_omega_from_with(
6221 &c,
6222 &mut src,
6223 &up,
6224 WeightFormat::Fp8All,
6225 &mut |_| {},
6226 )
6227 .unwrap();
6228 (
6229 Qwen3MoeOmegaEngine::new(w, Box::new(HostKv::new(&KvGeometry::from(&c), 32))),
6230 (),
6231 (),
6232 r,
6233 )
6234 };
6235 let _ = turn(&mut f32_engine, &prompt, 2);
6236 assert!(f32_engine.export_kv(0, 4).is_err());
6237 assert!(f32_engine.export_kv(0, 99).is_err());
6238 }
6239
6240 #[test]
6241 fn kv_switches_report_every_run_setting() {
6242 let mut e = pool_engine(32);
6243 let s = e.kv_switches();
6244 assert_eq!(s.attention_path, "host-pool");
6245 assert!(!s.whole_prompt && !s.decode_graph && !s.routing_mutant);
6246 e.prefill_chunk = 3;
6247 e.routing_mutant = true;
6248 let t = e.kv_switches();
6249 assert_eq!(t.prefill_chunk, 3);
6250 assert!(t.routing_mutant);
6251 assert_ne!(s, t);
6252 }
6253}