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 / om / ribbon / measured-qwen3_moe_omega.rs.txt

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