interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / src / qwen3_dense_omega.rs

3179 lines · 129279 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 dense (Qwen3-8B family, bf16) on AIEN's own GPU engine (Omega), OWN-8B Stage 1.
17//!
18//! Design: `~/handoffs/2026-10-15-own8b-design.md` (section 2.2, stage table row 1). This stage
19//! is host only: no launch, no chip. It is the dense sibling of `qwen3_moe_omega.rs`, which it
20//! reuses (shard reader, peak RSS probe, matmul limits) but does not edit.
21//!
22//! - [`Qwen3DenseConfig`]: the shape, read from `config.json` through the strict Qwen3 reader of
23//! `model_dir.rs`, then held to what the dense Omega engine can run: model_type `qwen3` (the
24//! MoE family is refused by name), tied or untied embeddings, plain rope, head_dim 64 or 128, every
25//! projection inside the bf16 streaming GEMV rule (`k % 256 == 0`, `256 <= k <= 16384`) and
26//! inside the resident matmul limits used for prefill (`K <= 16384`, `N <= 262144`).
27//! - The streaming loader: no f32 image of the model. Every matrix is read from the shards as raw
28//! bf16 words into one reused host buffer, in the checkpoint's own `[n][k]` row layout (what the
29//! bf16 GEMV takes, no transpose), and handed to a [`DenseUploader`]. q, k and v are read back to
30//! back, so the fused `[q_dim + 2*kv_dim][hidden]` tensor is the three checkpoint tensors stacked
31//! in that order with no copy; gate and up likewise give `[2*intermediate][hidden]`, gate rows
32//! first. The host keeps the bf16 embedding (widened per row at lookup; the design's section
33//! 2.2 says f32, which would add 1.24 GB at the 8B for the same values, so bf16 as in the 30B
34//! engine and the design's section 0) and the f32 norms. Peak
35//! host memory is the embedding plus one buffer the size of the largest matrix (the lm_head):
36//! [`dense_loader_transient_bytes`].
37//!
38//! Stage 1b (FP8, design revision 2026-10-15): the same loader reads Qwen's FP8 checkpoint
39//! (`Qwen/Qwen3-8B-FP8`). [`DenseWeightFormat`] comes from `config.json`'s `quantization_config`
40//! (absent: bf16; exactly fp8 / e4m3 / block [128, 128] / dynamic: FP8; anything else refused by
41//! name). Per projection the safetensors header decides: an `F8_E4M3` weight must have its bf16
42//! `weight_scale_inv` grid `[n/128][k/128]` beside it, and a bf16 projection in an FP8 checkpoint
43//! is refused (no mixed loads); lm_head, embedding and norms stay bf16. The e4m3 bytes and the
44//! scale rows of q|k|v and of gate|up are stacked the same way as the bf16 rows and handed to
45//! [`DenseUploader::upload_fp8`]. [`HostFp8Gemv`] is the host reference
46//! (`y[r]` in f32, the omega `a647b6a9` FP8 GEMV schedule: a lane dots `lane_bytes`
47//! products, multiplies that dot by the block scale once, then a SHFL.DOWN reduction).
48
49use std::path::Path;
50use std::sync::Arc;
51use std::time::Instant;
52
53use crate::model_dir::model_config_from_hf_json;
54use crate::qwen3_moe::{bf16_to_f32, FP8_BLOCK};
55use crate::qwen3_moe_omega::{
56 dequant_fp8_sources_to_bf16_cols, peak_rss_bytes, Fp8Source, KvGeometry, ShardSource,
57 TensorSource, KV_BLOCK_SIZE, MAX_RESIDENT_K, MAX_RESIDENT_N,
58};
59
60// The loader reads little-endian bf16 words in place (see `read_bf16`).
61/// OWN-8B stage 2: the engine (decode, prefill, generation) over the loaded weights.
62#[path = "qwen3_dense_omega_engine.rs"]
63pub mod engine;
64
65const _: () = assert!(
66 cfg!(target_endian = "little"),
67 "the dense loader needs a little-endian host"
68);
69
70/// head_dim values omega's paged attention takes (`omega_gpu_attention_api.h`, `TOO_LARGE`).
71pub const ATTN_HEAD_DIMS: [usize; 2] = [64, 128];
72/// Most query heads one paged attention launch takes (`OMEGA_GPU_ATTN_MAX_Q_HEADS`).
73pub const ATTN_MAX_Q_HEADS: usize = 64;
74
75// ---------------------------------------------------------------------------
76// Model shape, read from the checkpoint.
77// ---------------------------------------------------------------------------
78
79/// The five matrices the dense engine streams, each `[n][k]` bf16 as the checkpoint stores it.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub enum DenseTensor {
82 /// `q_proj | k_proj | v_proj` rows: `[q_dim + 2*kv_dim][hidden]`.
83 Qkv,
84 /// `o_proj`: `[hidden][q_dim]`.
85 O,
86 /// `gate_proj | up_proj` rows: `[2*intermediate][hidden]`.
87 GateUp,
88 /// `down_proj`: `[hidden][intermediate]`.
89 Down,
90 /// `lm_head`: `[vocab][hidden]`.
91 LmHead,
92}
93
94impl DenseTensor {
95 pub fn name(self) -> &'static str {
96 match self {
97 Self::Qkv => "q|k|v",
98 Self::O => "o",
99 Self::GateUp => "gate|up",
100 Self::Down => "down",
101 Self::LmHead => "lm_head",
102 }
103 }
104}
105
106/// How the checkpoint stores the four per-layer projections (lm_head, embedding and norms are
107/// bf16 in both).
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109pub enum DenseWeightFormat {
110 /// No `quantization_config`: every tensor bf16.
111 #[default]
112 Bf16,
113 /// Qwen's FP8 recipe: e4m3 weights `[n][k]` with a bf16 `weight_scale_inv` per 128x128
114 /// block, `[n/128][k/128]`; activations quantised dynamically (not by this loader).
115 Fp8Block128,
116}
117
118impl DenseWeightFormat {
119 /// The format named by `config.json`'s `quantization_config` (absent or null: bf16). Only the
120 /// exact FP8 block-128 recipe is taken; another method, format, block size or activation
121 /// scheme, an unknown key, or a `modules_to_not_convert` entry that could match a projection is refused
122 /// by name.
123 pub fn from_config(raw: &serde_json::Value) -> Result<Self, String> {
124 let Some(q) = raw.get("quantization_config").filter(|q| !q.is_null()) else {
125 return Ok(Self::Bf16);
126 };
127 let refuse = |what: String| Err(format!("config refused: quantization_config {what}"));
128 let shown =
129 |v: Option<&serde_json::Value>| v.map_or("absent".to_string(), |v| v.to_string());
130 let Some(obj) = q.as_object() else {
131 return refuse(format!("{q} is not an object"));
132 };
133 // The method first, so an int4 / GPTQ / AWQ config is refused for what it is.
134 match obj.get("quant_method") {
135 Some(m) if m == "fp8" => {}
136 other => {
137 return refuse(format!(
138 "quant_method {}: only \"fp8\" (Qwen's e4m3 block-128) is implemented",
139 shown(other)
140 ))
141 }
142 }
143 let want = [
144 ("fmt", serde_json::json!("e4m3")),
145 (
146 "weight_block_size",
147 serde_json::json!([FP8_BLOCK, FP8_BLOCK]),
148 ),
149 ("activation_scheme", serde_json::json!("dynamic")),
150 ];
151 for (key, value) in &want {
152 match obj.get(*key) {
153 Some(v) if v == value => {}
154 other => return refuse(format!("{key} {}, expected {value}", shown(other))),
155 }
156 }
157 for (key, value) in obj {
158 match key.as_str() {
159 "quant_method" | "fmt" | "weight_block_size" | "activation_scheme" => {}
160 "modules_to_not_convert" => {
161 let names = value.as_array().ok_or_else(|| {
162 format!("config refused: quantization_config modules_to_not_convert {value} is not a list")
163 })?;
164 // Hugging Face skips a module when an entry is a substring of its name, so
165 // an entry is safe only if it cannot be a substring of any projection name
166 // (`model.layers.N.{self_attn,mlp}.*_proj`). Those names contain none of
167 // these words, so an entry containing one can only match a bf16 tensor.
168 let bf16_only = |s: &str| {
169 ["lm_head", "norm", "embed_tokens"]
170 .iter()
171 .any(|w| s.contains(w))
172 };
173 if let Some(p) = names
174 .iter()
175 .find(|n| n.as_str().is_none_or(|s| !bf16_only(s)))
176 {
177 return refuse(format!(
178 "modules_to_not_convert names {p}: it could match a projection, and every projection of this engine is FP8 in an FP8 checkpoint"
179 ));
180 }
181 }
182 other => return refuse(format!("field {other:?} is not implemented")),
183 }
184 }
185 Ok(Self::Fp8Block128)
186 }
187}
188
189/// The dense Qwen3 shape, read from `config.json` and validated against what the dense Omega
190/// engine can run.
191#[derive(Debug, Clone, PartialEq)]
192pub struct Qwen3DenseConfig {
193 /// How the projections are stored (`quantization_config`).
194 pub format: DenseWeightFormat,
195 pub layers: usize,
196 pub hidden: usize,
197 pub q_heads: usize,
198 pub kv_heads: usize,
199 pub head_dim: usize,
200 pub intermediate: usize,
201 pub vocab: usize,
202 pub rms_eps: f32,
203 pub rope_theta: f32,
204 pub max_position: usize,
205 /// Ids generation stops on (`generation_config.json` eos list, else `config.json` eos).
206 pub eos_token_ids: Vec<u32>,
207 /// `tie_word_embeddings`: the lm_head is the embedding matrix (Qwen3-4B, 0.6B, 1.7B). The
208 /// loader then uploads the host embedding as the lm_head and reads no `lm_head.weight`.
209 pub tie_word_embeddings: bool,
210}
211
212impl Qwen3DenseConfig {
213 /// `config.json` and, when present, `generation_config.json` of a checkpoint directory.
214 pub fn from_checkpoint(dir: &Path) -> Result<Self, String> {
215 let path = dir.join("config.json");
216 let text =
217 std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
218 let gen_path = dir.join("generation_config.json");
219 let gen = match std::fs::read_to_string(&gen_path) {
220 Ok(t) => Some(t),
221 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
222 Err(e) => return Err(format!("{}: {e}", gen_path.display())),
223 };
224 Self::from_json(&text, gen.as_deref()).map_err(|e| format!("{}: {e}", path.display()))
225 }
226
227 pub fn from_json(config_json: &str, generation_json: Option<&str>) -> Result<Self, String> {
228 let raw: serde_json::Value =
229 serde_json::from_str(config_json).map_err(|e| format!("config.json: {e}"))?;
230 match raw.get("model_type").and_then(|m| m.as_str()) {
231 Some("qwen3") => {}
232 Some("qwen3_moe") => {
233 return Err(
234 "config refused: model_type \"qwen3_moe\" is the mixture-of-experts \
235 family; this loader is for dense \"qwen3\" (the MoE engine is \
236 qwen3_moe_omega)"
237 .into(),
238 )
239 }
240 other => {
241 return Err(format!(
242 "config refused: model_type {other:?}, this loader is for dense \"qwen3\""
243 ))
244 }
245 }
246 // A checkpoint that is not bf16 is refused here, not at its first tensor read. An FP8
247 // checkpoint says bfloat16 too: it names the type of its unquantised tensors.
248 for key in ["torch_dtype", "dtype"] {
249 if let Some(d) = raw.get(key).filter(|d| !d.is_null()) {
250 if d.as_str() != Some("bfloat16") {
251 return Err(format!(
252 "config refused: {key} {d}, this loader streams bfloat16 weights"
253 ));
254 }
255 }
256 }
257 let format = DenseWeightFormat::from_config(&raw)?;
258 // The strict Qwen3ForCausalLM reader: unknown keys, sliding window, biases, activation,
259 // rope type, head_dim presence and the attention geometry are refused there by name. It
260 // does not know `quantization_config` (the bf16 engines must keep refusing an FP8
261 // checkpoint), so the key, read above, is taken out of what it sees.
262 let stripped;
263 let config_json = if raw.get("quantization_config").is_some() {
264 let mut rest = raw.clone();
265 if let Some(obj) = rest.as_object_mut() {
266 obj.remove("quantization_config");
267 }
268 stripped = rest.to_string();
269 stripped.as_str()
270 } else {
271 config_json
272 };
273 let mc = model_config_from_hf_json("qwen3-dense", config_json, generation_json)
274 .map_err(|e| format!("config refused: {e}"))?;
275 if !mc.qk_norm {
276 return Err(
277 "config refused: architectures must be [\"Qwen3ForCausalLM\"] (q/k norm)".into(),
278 );
279 }
280 if mc.rope_scaling.is_some() {
281 return Err("config refused: rope_scaling is not implemented (plain rope only)".into());
282 }
283 let cfg = Self {
284 format,
285 layers: mc.num_layers,
286 hidden: mc.hidden_dim,
287 q_heads: mc.num_heads,
288 kv_heads: mc.num_kv_heads,
289 head_dim: mc.head_dim,
290 intermediate: mc.intermediate_dim,
291 vocab: mc.vocab_size,
292 rms_eps: mc.rms_norm_eps,
293 rope_theta: mc.rope_theta,
294 max_position: mc.max_sequence_length,
295 eos_token_ids: mc.eos_token_ids,
296 tie_word_embeddings: mc.tie_word_embeddings,
297 };
298 cfg.validate()?;
299 Ok(cfg)
300 }
301
302 /// What the dense engine can run: omega's paged attention, the bf16 streaming GEMV for every
303 /// projection (decode) and the resident matmul limits (prefill, `[k][n]`).
304 pub fn validate(&self) -> Result<(), String> {
305 let bad = |what: String| Err(format!("config refused: {what}"));
306 if self.layers == 0
307 || self.vocab == 0
308 || self.q_heads == 0
309 || self.kv_heads == 0
310 || self.intermediate == 0
311 {
312 return bad("zero layers, vocab, heads or intermediate".into());
313 }
314 if !ATTN_HEAD_DIMS.contains(&self.head_dim) {
315 return bad(format!(
316 "head_dim {} (omega paged attention takes {ATTN_HEAD_DIMS:?})",
317 self.head_dim
318 ));
319 }
320 if !self.q_heads.is_multiple_of(self.kv_heads) || self.q_heads > ATTN_MAX_Q_HEADS {
321 return bad(format!(
322 "{} query heads over {} kv heads (need a whole GQA group and <= {ATTN_MAX_Q_HEADS} query heads)",
323 self.q_heads, self.kv_heads
324 ));
325 }
326 if self.format == DenseWeightFormat::Fp8Block128 {
327 // Each stacked part (q, k, v; gate, up) must start on a scale row, and every k on a
328 // scale column.
329 for (what, v) in [
330 ("hidden_size", self.hidden),
331 ("intermediate_size", self.intermediate),
332 ("q_dim", self.q_dim()),
333 ("kv_dim", self.kv_dim()),
334 ] {
335 if !v.is_multiple_of(FP8_BLOCK) {
336 return bad(format!(
337 "{what} {v} is not a multiple of the FP8 block {FP8_BLOCK}"
338 ));
339 }
340 }
341 }
342 for (what, n, k) in self.matrices() {
343 if self.is_fp8(what) {
344 if let Err(e) = aien_omega_fp8::check_shape(1, n, k) {
345 return bad(format!("{} [{n}][{k}]: {e}", what.name()));
346 }
347 continue;
348 }
349 if let Err(e) = aien_omega_bf16::check_shape(n, k) {
350 return bad(format!("{} [{n}][{k}]: {e}", what.name()));
351 }
352 if k > MAX_RESIDENT_K || n > MAX_RESIDENT_N {
353 return bad(format!(
354 "{} [{n}][{k}] exceeds the resident matmul limit K <= {MAX_RESIDENT_K}, N <= {MAX_RESIDENT_N}",
355 what.name()
356 ));
357 }
358 }
359 Ok(())
360 }
361
362 pub fn q_dim(&self) -> usize {
363 self.q_heads * self.head_dim
364 }
365 pub fn kv_dim(&self) -> usize {
366 self.kv_heads * self.head_dim
367 }
368 /// Rows of the fused q|k|v tensor.
369 pub fn qkv_n(&self) -> usize {
370 self.q_dim() + 2 * self.kv_dim()
371 }
372 /// Rows of the fused gate|up tensor.
373 pub fn gate_up_n(&self) -> usize {
374 2 * self.intermediate
375 }
376
377 /// Every streamed matrix as `(what, n, k)`, `[n][k]` row layout.
378 pub fn matrices(&self) -> [(DenseTensor, usize, usize); 5] {
379 let h = self.hidden;
380 [
381 (DenseTensor::Qkv, self.qkv_n(), h),
382 (DenseTensor::O, h, self.q_dim()),
383 (DenseTensor::GateUp, self.gate_up_n(), h),
384 (DenseTensor::Down, h, self.intermediate),
385 (DenseTensor::LmHead, self.vocab, h),
386 ]
387 }
388
389 /// bf16 words of the largest streamed matrix (the loader's one host buffer).
390 pub fn max_matrix_words(&self) -> usize {
391 self.matrices()
392 .iter()
393 .map(|&(_, n, k)| n * k)
394 .max()
395 .unwrap_or(0)
396 }
397
398 /// Whether `what` is stored as FP8 (the four projections of an FP8 checkpoint; the lm_head
399 /// is bf16 in both formats).
400 pub fn is_fp8(&self, what: DenseTensor) -> bool {
401 self.format == DenseWeightFormat::Fp8Block128 && what != DenseTensor::LmHead
402 }
403
404 /// Bytes of one streamed matrix as uploaded: `2nk` bf16, or `nk` e4m3 plus the bf16 scale
405 /// grid `[n/128][k/128]`.
406 pub fn matrix_bytes(&self, what: DenseTensor, n: usize, k: usize) -> usize {
407 if self.is_fp8(what) {
408 n * k + 2 * (n / FP8_BLOCK) * (k / FP8_BLOCK)
409 } else {
410 2 * n * k
411 }
412 }
413
414 /// Bytes of one layer's four streamed tensors.
415 pub fn layer_resident_bytes(&self) -> usize {
416 self.matrices()
417 .iter()
418 .filter(|m| m.0 != DenseTensor::LmHead)
419 .map(|&(what, n, k)| self.matrix_bytes(what, n, k))
420 .sum()
421 }
422
423 /// Bytes handed to the uploader for the whole model (layers plus lm_head). For FP8 this
424 /// counts the bf16 scale grids as the checkpoint stores them; a device that widens the
425 /// scales to f32 holds slightly more.
426 pub fn model_resident_bytes(&self) -> usize {
427 self.layers * self.layer_resident_bytes()
428 + self.matrix_bytes(DenseTensor::LmHead, self.vocab, self.hidden)
429 }
430
431 /// Words of the loader's one reused buffer: bf16, the largest matrix; FP8, the larger of the
432 /// bf16 lm_head and the largest projection's e4m3 bytes.
433 pub fn loader_buffer_words(&self) -> usize {
434 self.matrices()
435 .iter()
436 // A tied lm_head is uploaded from the host embedding, not read through the buffer.
437 .filter(|m| !(self.tie_word_embeddings && m.0 == DenseTensor::LmHead))
438 .map(|&(what, n, k)| {
439 if self.is_fp8(what) {
440 (n * k).div_ceil(2)
441 } else {
442 n * k
443 }
444 })
445 .max()
446 .unwrap_or(0)
447 }
448
449 /// bf16 words of the loader's scale buffer: the largest FP8 scale grid (0 for bf16).
450 pub fn loader_scale_words(&self) -> usize {
451 self.matrices()
452 .iter()
453 .filter(|m| self.is_fp8(m.0))
454 .map(|&(_, n, k)| (n / FP8_BLOCK) * (k / FP8_BLOCK))
455 .max()
456 .unwrap_or(0)
457 }
458
459 /// Bytes of the bf16 embedding the host keeps.
460 pub fn embed_host_bytes(&self) -> usize {
461 2 * self.vocab * self.hidden
462 }
463}
464
465/// The 8B's KV shape (ADR 0004 section 2.1): the dense engine will build its cache from this
466/// (step 6).
467impl From<&Qwen3DenseConfig> for KvGeometry {
468 fn from(c: &Qwen3DenseConfig) -> Self {
469 Self {
470 layers: c.layers,
471 q_heads: c.q_heads,
472 kv_heads: c.kv_heads,
473 head_dim: c.head_dim,
474 rope_theta: c.rope_theta,
475 block_size: KV_BLOCK_SIZE,
476 }
477 }
478}
479
480/// Largest host buffer the loader holds beyond the model's own host bytes: one buffer reused for
481/// every read (norms included), the size of the largest matrix as stored, plus, for FP8, the
482/// largest scale grid. At the 8B the lm_head (bf16 in both formats, 1.24 GB) sets it.
483pub fn dense_loader_transient_bytes(config: &Qwen3DenseConfig) -> usize {
484 2 * (config.loader_buffer_words() + config.loader_scale_words())
485}
486
487// ---------------------------------------------------------------------------
488// The device side, behind a trait so the loader runs without a chip.
489// ---------------------------------------------------------------------------
490
491/// One resident `[n][k]` bf16 matrix: `y[r] = sum_c W[r][c] * x[c]` in f32. Shared across
492/// threads: an implementation over omega's `Bf16Tensor` (not `Sync`) holds it behind a lock, as
493/// `OmegaLmHead` does for the 30B.
494pub trait DenseGemv: Send + Sync + std::fmt::Debug {
495 fn n(&self) -> usize;
496 fn k(&self) -> usize;
497 /// Returns the device time in ns (0 when not measured).
498 fn gemv_f32(&self, x: &[f32], y: &mut [f32]) -> Result<u64, String>;
499 /// `m` rows: `x` is `[m][k]`, `y` is `[m][n]`. Returns (device ns, launches). The default
500 /// runs the GEMV once per row; a multi-row kernel (omega's FP8 GEMM) must give the same
501 /// numbers bit for bit, so prefill and decode share one oracle.
502 fn rows_f32(&self, m: usize, x: &[f32], y: &mut [f32]) -> Result<(u64, u64), String> {
503 engine::rows_by_gemv(self, m, x, y)
504 }
505}
506
507/// Makes `[n][k]` bf16 matrices resident, byte for byte as given (the checkpoint row layout).
508/// The real one (omega's `Bf16Tensor`, NaN/Inf refused at upload) comes with the engine stage.
509pub trait DenseUploader {
510 /// `layer` is `None` for the lm_head.
511 fn upload_bf16(
512 &self,
513 layer: Option<usize>,
514 what: DenseTensor,
515 n: usize,
516 k: usize,
517 bits: &[u16],
518 ) -> Result<Arc<dyn DenseGemv>, String>;
519
520 /// An `[n][k]` FP8 projection as the checkpoint stores it: `w` is `n * k` e4m3 bytes, row
521 /// major, `scales` the `[n/128][k/128]` bf16 `weight_scale_inv` grid (fused tensors: the
522 /// parts' rows and scale rows stacked in the same order). Uploaders without FP8 refuse, as
523 /// `ModelUploader::upload_fp8` does for the 30B.
524 fn upload_fp8(
525 &self,
526 layer: Option<usize>,
527 what: DenseTensor,
528 n: usize,
529 k: usize,
530 w: &[u8],
531 scales: &[u16],
532 ) -> Result<Arc<dyn DenseGemv>, String> {
533 let _ = (layer, what, n, k, w, scales);
534 Err("this uploader has no FP8 path".into())
535 }
536}
537
538/// The FP8 upload rule (omega's `omega_gpu_fp8_tensor_upload`, checked on the host): lengths for
539/// `[n][k]` with block-128 scales, no e4m3 NaN code (0x7f, 0xff) in the weights and no NaN or
540/// infinite scale. The first offender is named.
541pub fn check_fp8_upload(n: usize, k: usize, w: &[u8], scales: &[u16]) -> Result<(), String> {
542 if !n.is_multiple_of(FP8_BLOCK) || !k.is_multiple_of(FP8_BLOCK) || n == 0 || k == 0 {
543 return Err(format!(
544 "fp8 [{n}][{k}]: n and k must be positive multiples of {FP8_BLOCK}"
545 ));
546 }
547 let grid = (n / FP8_BLOCK) * (k / FP8_BLOCK);
548 if w.len() != n * k || scales.len() != grid {
549 return Err(format!(
550 "fp8 [{n}][{k}]: {} weight bytes and {} scales, expected {} and {grid}",
551 w.len(),
552 scales.len(),
553 n * k
554 ));
555 }
556 if let Some(at) = w.iter().position(|&b| b & 0x7f == 0x7f) {
557 return Err(format!(
558 "weight byte {at} is an e4m3 NaN code (refused at upload)"
559 ));
560 }
561 // bf16 exponent all ones = Inf or NaN.
562 if let Some(at) = scales.iter().position(|&s| s & 0x7f80 == 0x7f80) {
563 return Err(format!("scale {at} is NaN or infinite (refused at upload)"));
564 }
565 Ok(())
566}
567
568/// The host reference of one FP8 projection (design section 2.2 item 4, the per-layer oracle of
569/// section 2.4). It follows the omega FP8 GEMV at pin `a647b6a9`
570/// (`omega_blackwell_codegen_moe.h`: per lane, an FFMA chain of `lane_bytes` products, then
571/// `acc = fma(dot, S', acc)` once, then SHFL.DOWN by 16, 8, 4, 2, 1). `S'` and `x'` carry the
572/// kernel's `2^56` and `2^64` folds, which cancel the `2^-120` in the e4m3 bit conversion.
573/// The real-arithmetic formula is still `sum_c e4m3(w) * x * scale`, but that per-product
574/// scaling is not the f32 schedule the chip runs, so the reference uses the chip's schedule.
575/// The kernel was not changed: this repository does not build it, and the schedule matches
576/// the omega header. [`HostFp8Gemv::dequantised_bf16`] rounds each dequantised weight to bf16
577/// and then uses the bf16 GEMV's lane schedule.
578#[derive(Debug)]
579pub struct HostFp8Gemv {
580 n: usize,
581 k: usize,
582 w: Vec<u8>,
583 scales: Vec<u16>,
584 /// `[n][k]` bf16 words of the dequantised weights, for the bf16 variant.
585 dequantised: Option<Vec<u16>>,
586}
587
588impl HostFp8Gemv {
589 /// Holds `w` and `scales` as given, after [`check_fp8_upload`].
590 pub fn new(n: usize, k: usize, w: Vec<u8>, scales: Vec<u16>) -> Result<Self, String> {
591 check_fp8_upload(n, k, &w, &scales)?;
592 Ok(Self {
593 n,
594 k,
595 w,
596 scales,
597 dequantised: None,
598 })
599 }
600
601 /// The same projection, dequantised once to bf16 (`e4m3(w) * scale` rounded to nearest even).
602 pub fn dequantised_bf16(
603 n: usize,
604 k: usize,
605 w: Vec<u8>,
606 scales: Vec<u16>,
607 ) -> Result<Self, String> {
608 let mut m = Self::new(n, k, w, scales)?;
609 // The 30B helper writes the transposed `[k][n]` layout; read it back by rows.
610 let mut cols = vec![0u16; k * n];
611 dequant_fp8_sources_to_bf16_cols(
612 &[Fp8Source {
613 weights: &m.w,
614 scales: &m.scales,
615 rows: n,
616 col0: 0,
617 }],
618 k,
619 &mut cols,
620 n,
621 )?;
622 let mut rows = vec![0u16; n * k];
623 for (c, col) in cols.chunks_exact(n).enumerate() {
624 for (r, &v) in col.iter().enumerate() {
625 rows[r * k + c] = v;
626 }
627 }
628 m.dequantised = Some(rows);
629 Ok(m)
630 }
631
632 /// The e4m3 bytes, `[n][k]`.
633 pub fn weights(&self) -> &[u8] {
634 &self.w
635 }
636
637 /// The bf16 scale grid, `[n/128][k/128]`.
638 pub fn scales(&self) -> &[u16] {
639 &self.scales
640 }
641}
642
643/// `2^64`, the kernel's `x' = x * 2^OMEGA_FP8_X_EXP` fold (exact in f32).
644const FP8_X_FOLD: f32 = f32::from_bits(0x5f80_0000);
645/// `2^56`, the kernel's `S' = S * 2^OMEGA_FP8_SCALE_EXP` fold (exact in f32).
646const FP8_S_FOLD: f32 = f32::from_bits(0x5b80_0000);
647
648/// e4m3 byte as the kernel sees it: f32 bits `((b & 0x7f) << 20) | ((b & 0x80) << 24)`,
649/// which equal `e4m3(b) * 2^-120` for every non-NaN code.
650pub(crate) fn e4m3_kernel_f32(b: u8) -> f32 {
651 f32::from_bits(((b & 0x7f) as u32) << 20 | ((b & 0x80) as u32) << 24)
652}
653
654/// SHFL.DOWN reduction by 16, 8, 4, 2, 1. Lane `i` adds lane `i + delta` while that lane
655/// still holds the value from the previous delta, matching `omega_warp_reduce_sum`.
656pub(crate) fn kernel_warp_sum(mut lane: [f32; 32]) -> f32 {
657 for d in [16usize, 8, 4, 2, 1] {
658 for i in 0..32 - d {
659 lane[i] += lane[i + d];
660 }
661 }
662 lane[0]
663}
664
665/// Widest `k` one bf16 launch stages (`BF16_MAX_SLICE_K` in the engine). Wider rows are
666/// separate launches whose f32 results add in slice order, which is what `OmegaBf16Gemv` does.
667pub(crate) const BF16_KERNEL_SLICE_K: usize = 4096;
668
669/// One `[n][k]` bf16 row in the omega bf16 GEMV's f32 schedule (pin `a647b6a9`,
670/// `omega_blackwell_codegen_bf16.h`): lane L owns 8 weights at the start of each 256-column
671/// step, FFMA in element order, then one SHFL.DOWN. `k` is a positive multiple of 256.
672pub(crate) fn bf16_kernel_row(row: &[u16], x: &[f32]) -> f32 {
673 let k = row.len();
674 let mut lane = [0.0f32; 32];
675 let mut base = 0;
676 while base < k {
677 for lane_i in 0..32 {
678 let c0 = base + lane_i * 8;
679 let mut acc = lane[lane_i];
680 for e in 0..8 {
681 acc = bf16_to_f32(row[c0 + e]).mul_add(x[c0 + e], acc);
682 }
683 lane[lane_i] = acc;
684 }
685 base += 256;
686 }
687 kernel_warp_sum(lane)
688}
689
690/// [`bf16_kernel_row`] over slices of [`BF16_KERNEL_SLICE_K`], partials added in slice order.
691pub(crate) fn bf16_kernel_gemv(
692 bits: &[u16],
693 n: usize,
694 k: usize,
695 x: &[f32],
696 y: &mut [f32],
697) -> Result<(), String> {
698 if k < 256 || !k.is_multiple_of(256) || bits.len() != n * k || x.len() != k || y.len() != n {
699 return Err(format!(
700 "bf16 kernel gemv [{n}][{k}] needs k a multiple of 256, got x {} y {} words {}",
701 x.len(),
702 y.len(),
703 bits.len()
704 ));
705 }
706 use rayon::prelude::*;
707 y.par_iter_mut().enumerate().for_each(|(r, out)| {
708 let row = &bits[r * k..(r + 1) * k];
709 let mut acc = 0.0f32;
710 let mut c = 0;
711 while c < k {
712 let len = (k - c).min(BF16_KERNEL_SLICE_K);
713 acc += bf16_kernel_row(&row[c..c + len], &x[c..c + len]);
714 c += len;
715 }
716 *out = acc;
717 });
718 Ok(())
719}
720
721/// One FP8 row in the omega FP8 GEMV's f32 schedule. `lane_bytes` is 16 when `k % 512 == 0`,
722/// else 8 (omega `omega_gpu_fp8_shape_for`). Each lane dots its chunk, multiplies by that
723/// chunk's block scale once, then the warp reduces.
724pub(crate) fn fp8_kernel_row(weights: &[u8], scales: &[u16], k: usize, x: &[f32]) -> f32 {
725 let lane_bytes = if k.is_multiple_of(512) { 16 } else { 8 };
726 let step = 32 * lane_bytes;
727 let mut lane = [0.0f32; 32];
728 let mut base = 0;
729 while base < k {
730 for lane_i in 0..32 {
731 let c0 = base + lane_i * lane_bytes;
732 let mut dot = 0.0f32;
733 for e in 0..lane_bytes {
734 let c = c0 + e;
735 dot = e4m3_kernel_f32(weights[c]).mul_add(x[c] * FP8_X_FOLD, dot);
736 }
737 let scale = bf16_to_f32(scales[c0 / FP8_BLOCK]) * FP8_S_FOLD;
738 lane[lane_i] = dot.mul_add(scale, lane[lane_i]);
739 }
740 base += step;
741 }
742 kernel_warp_sum(lane)
743}
744
745impl DenseGemv for HostFp8Gemv {
746 fn n(&self) -> usize {
747 self.n
748 }
749 fn k(&self) -> usize {
750 self.k
751 }
752 fn gemv_f32(&self, x: &[f32], y: &mut [f32]) -> Result<u64, String> {
753 let (n, k) = (self.n, self.k);
754 if x.len() != k || y.len() != n {
755 return Err(format!(
756 "fp8 gemv [{n}][{k}] given x {} y {}",
757 x.len(),
758 y.len()
759 ));
760 }
761 if k < 256 || !k.is_multiple_of(256) {
762 return Err(format!(
763 "fp8 gemv [{n}][{k}]: the omega kernel requires k a multiple of 256"
764 ));
765 }
766 if let Some(d) = &self.dequantised {
767 return bf16_kernel_gemv(d, n, k, x, y).map(|_| 0);
768 }
769 use rayon::prelude::*;
770 let kb = k / FP8_BLOCK;
771 y.par_iter_mut().enumerate().for_each(|(r, out)| {
772 let row = &self.w[r * k..(r + 1) * k];
773 let srow = &self.scales[(r / FP8_BLOCK) * kb..(r / FP8_BLOCK + 1) * kb];
774 *out = fp8_kernel_row(row, srow, k, x);
775 });
776 Ok(0)
777 }
778}
779
780// ---------------------------------------------------------------------------
781// The loaded model.
782// ---------------------------------------------------------------------------
783
784#[derive(Debug)]
785pub struct DenseLayer {
786 pub input_norm: Vec<f32>,
787 pub post_norm: Vec<f32>,
788 pub q_norm: Vec<f32>,
789 pub k_norm: Vec<f32>,
790 pub qkv: Arc<dyn DenseGemv>,
791 pub o: Arc<dyn DenseGemv>,
792 pub gate_up: Arc<dyn DenseGemv>,
793 pub down: Arc<dyn DenseGemv>,
794}
795
796/// The whole model: streamed matrices on the device, the bf16 embedding and f32 norms on the host.
797#[derive(Debug)]
798pub struct Qwen3DenseOmegaWeights {
799 pub config: Qwen3DenseConfig,
800 /// `[vocab][hidden]` bf16 bits; a row is widened to f32 at lookup.
801 pub embed_bf16: Vec<u16>,
802 pub layers: Vec<DenseLayer>,
803 pub final_norm: Vec<f32>,
804 pub lm_head: Arc<dyn DenseGemv>,
805}
806
807impl Qwen3DenseOmegaWeights {
808 /// The embedding row of `token` in f32; a token outside the vocabulary is refused.
809 pub fn embed_row(&self, token: u32) -> Result<Vec<f32>, String> {
810 let h = self.config.hidden;
811 let t = token as usize;
812 if t >= self.config.vocab {
813 return Err(format!(
814 "token {token} outside the vocabulary of {}",
815 self.config.vocab
816 ));
817 }
818 Ok(self.embed_bf16[t * h..(t + 1) * h]
819 .iter()
820 .map(|&b| bf16_to_f32(b))
821 .collect())
822 }
823
824 /// Bytes the host keeps after the load (embedding and norms).
825 pub fn host_bytes(&self) -> usize {
826 self.embed_bf16.len() * 2
827 + self.final_norm.len() * 4
828 + self
829 .layers
830 .iter()
831 .map(|l| {
832 4 * (l.input_norm.len() + l.post_norm.len() + l.q_norm.len() + l.k_norm.len())
833 })
834 .sum::<usize>()
835 }
836}
837
838/// What a load measured.
839#[derive(Debug, Clone, PartialEq)]
840pub struct DenseLoadReport {
841 /// Bytes handed to the uploader: bf16 words, or e4m3 bytes plus their bf16 scales.
842 pub resident_bytes: usize,
843 pub host_bytes: usize,
844 /// The loader's reused buffers, bytes ([`dense_loader_transient_bytes`]).
845 pub transient_bytes: usize,
846 pub uploads: usize,
847 /// Process peak resident set (VmHWM) before and after the load, if `/proc` is readable.
848 pub peak_rss_before_bytes: Option<u64>,
849 pub peak_rss_bytes: Option<u64>,
850 pub seconds: f64,
851}
852
853/// A u16 slice as bytes of twice the length.
854fn words_as_bytes_mut(words: &mut [u16]) -> &mut [u8] {
855 // SAFETY: u8 has no alignment need and every byte pattern is a valid u16 half; the length
856 // is exactly the slice's size in bytes.
857 unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 2) }
858}
859
860/// Reads one bf16 tensor (dtype and shape checked by the source) into `dst` as words.
861fn read_bf16(
862 source: &mut dyn TensorSource,
863 name: &str,
864 shape: &[usize],
865 dst: &mut [u16],
866) -> Result<(), String> {
867 if shape.iter().product::<usize>() != dst.len() {
868 return Err(format!(
869 "{name}: shape {shape:?} does not fill {} words",
870 dst.len()
871 ));
872 }
873 // The source writes little-endian bf16 words, this host's byte order (asserted at compile
874 // time).
875 source.read_into(name, "BF16", shape, words_as_bytes_mut(dst))
876}
877
878/// A norm vector, read through the front of the loader's buffer and widened to f32.
879fn read_norm(
880 source: &mut dyn TensorSource,
881 name: &str,
882 len: usize,
883 buf: &mut [u16],
884) -> Result<Vec<f32>, String> {
885 read_bf16(source, name, &[len], &mut buf[..len])?;
886 Ok(buf[..len].iter().map(|&b| bf16_to_f32(b)).collect())
887}
888
889/// Reads one FP8 projection `name` (`[rows][k]` e4m3) into `w` and its `weight_scale_inv`
890/// (`[rows/128][k/128]` bf16) into `scales`. The checkpoint header decides, not the name: the
891/// weight must be `F8_E4M3` with a scale grid beside it; a bf16 projection in an FP8 checkpoint
892/// and an FP8 weight without its scales are refused by name.
893fn read_fp8(
894 source: &mut dyn TensorSource,
895 name: &str,
896 rows: usize,
897 k: usize,
898 w: &mut [u8],
899 scales: &mut [u16],
900) -> Result<(), String> {
901 let scale_name = format!("{name}_scale_inv");
902 let dtype = source
903 .dtype_of(name)?
904 .ok_or_else(|| format!("{name}: not in the checkpoint"))?;
905 let has_scales = source.dtype_of(&scale_name)?.is_some();
906 match (dtype.as_str(), has_scales) {
907 ("F8_E4M3", true) => {}
908 ("F8_E4M3", false) => {
909 return Err(format!(
910 "{name}: F8_E4M3 without {scale_name}: refused (an FP8 weight needs its block scales)"
911 ))
912 }
913 ("BF16", _) => {
914 return Err(format!(
915 "{name}: BF16 projection in an FP8 checkpoint: refused (no mixed loads)"
916 ))
917 }
918 (other, _) => {
919 return Err(format!(
920 "{name}: dtype {other}, an FP8 checkpoint's projection must be F8_E4M3"
921 ))
922 }
923 }
924 source.read_into(name, "F8_E4M3", &[rows, k], w)?;
925 // dtype BF16 and shape [rows/128][k/128] checked by the source.
926 let grid = [rows / FP8_BLOCK, k / FP8_BLOCK];
927 if grid[0] * grid[1] != scales.len() {
928 return Err(format!(
929 "{scale_name}: grid {grid:?} does not fill {} scales",
930 scales.len()
931 ));
932 }
933 source.read_into(&scale_name, "BF16", &grid, words_as_bytes_mut(scales))
934}
935
936/// The streaming loader's state: the source, the uploader, its one reused buffer (plus the
937/// scale buffer for FP8) and the running totals.
938struct Stream<'a> {
939 config: &'a Qwen3DenseConfig,
940 source: &'a mut dyn TensorSource,
941 uploader: &'a dyn DenseUploader,
942 buf: Vec<u16>,
943 scales: Vec<u16>,
944 resident: usize,
945 uploads: usize,
946}
947
948impl Stream<'_> {
949 fn norm(&mut self, name: &str, len: usize) -> Result<Vec<f32>, String> {
950 read_norm(self.source, name, len, &mut self.buf)
951 }
952
953 /// `parts` (checkpoint tensor name, rows), each `[rows][k]`, read back to back into the
954 /// buffer, so the fused `[sum rows][k]` matrix is the parts stacked in order with no copy,
955 /// and uploaded. FP8: the e4m3 bytes and the scale rows are stacked the same way.
956 fn matrix(
957 &mut self,
958 layer: Option<usize>,
959 what: DenseTensor,
960 parts: &[(String, usize)],
961 k: usize,
962 ) -> Result<Arc<dyn DenseGemv>, String> {
963 let n: usize = parts.iter().map(|p| p.1).sum();
964 let at = layer.map_or("lm_head".to_string(), |l| format!("layer {l}"));
965 let uploaded = if self.config.is_fp8(what) {
966 let kb = k / FP8_BLOCK;
967 let bytes = words_as_bytes_mut(&mut self.buf);
968 let (mut off, mut s_off) = (0usize, 0usize);
969 for (name, rows) in parts {
970 let sl = (rows / FP8_BLOCK) * kb;
971 read_fp8(
972 self.source,
973 name,
974 *rows,
975 k,
976 &mut bytes[off..off + rows * k],
977 &mut self.scales[s_off..s_off + sl],
978 )?;
979 off += rows * k;
980 s_off += sl;
981 }
982 debug_assert_eq!(off, n * k);
983 self.uploader
984 .upload_fp8(layer, what, n, k, &bytes[..off], &self.scales[..s_off])
985 } else {
986 let mut off = 0usize;
987 for (name, rows) in parts {
988 read_bf16(
989 self.source,
990 name,
991 &[*rows, k],
992 &mut self.buf[off..off + rows * k],
993 )?;
994 off += rows * k;
995 }
996 debug_assert_eq!(off, n * k);
997 self.uploader
998 .upload_bf16(layer, what, n, k, &self.buf[..off])
999 };
1000 let m = uploaded.map_err(|e| format!("{at} {} [{n}][{k}] upload: {e}", what.name()))?;
1001 if m.n() != n || m.k() != k {
1002 return Err(format!(
1003 "{at} {} upload returned [{}][{}], asked [{n}][{k}]",
1004 what.name(),
1005 m.n(),
1006 m.k()
1007 ));
1008 }
1009 self.resident += self.config.matrix_bytes(what, n, k);
1010 self.uploads += 1;
1011 Ok(m)
1012 }
1013}
1014
1015/// Loads a checkpoint directory: `config.json` for the shape and format, the shards for the
1016/// weights.
1017pub fn load_qwen3_dense_omega(
1018 dir: &Path,
1019 uploader: &dyn DenseUploader,
1020 progress: &mut dyn FnMut(&str),
1021) -> Result<(Qwen3DenseOmegaWeights, DenseLoadReport), String> {
1022 let config = Qwen3DenseConfig::from_checkpoint(dir)?;
1023 let mut source = ShardSource::open(dir)?;
1024 load_qwen3_dense_omega_from(&config, &mut source, uploader, progress)
1025}
1026
1027/// The streaming load from any [`TensorSource`].
1028pub fn load_qwen3_dense_omega_from(
1029 config: &Qwen3DenseConfig,
1030 source: &mut dyn TensorSource,
1031 uploader: &dyn DenseUploader,
1032 progress: &mut dyn FnMut(&str),
1033) -> Result<(Qwen3DenseOmegaWeights, DenseLoadReport), String> {
1034 config.validate()?;
1035 let t0 = Instant::now();
1036 let peak_before = peak_rss_bytes();
1037 let (h, i, hd) = (config.hidden, config.intermediate, config.head_dim);
1038 let (qd, kvd) = (config.q_dim(), config.kv_dim());
1039
1040 let mut embed_bf16 = vec![0u16; config.vocab * h];
1041 read_bf16(
1042 source,
1043 "model.embed_tokens.weight",
1044 &[config.vocab, h],
1045 &mut embed_bf16,
1046 )?;
1047
1048 // The one transient: every matrix and norm is read through it, layer after layer.
1049 let mut s = Stream {
1050 config,
1051 source,
1052 uploader,
1053 buf: vec![0; config.loader_buffer_words()],
1054 scales: vec![0; config.loader_scale_words()],
1055 resident: 0,
1056 uploads: 0,
1057 };
1058 let transient_bytes = 2 * (s.buf.len() + s.scales.len());
1059
1060 let mut layers = Vec::with_capacity(config.layers);
1061 for layer in 0..config.layers {
1062 let p = format!("model.layers.{layer}");
1063 let input_norm = s.norm(&format!("{p}.input_layernorm.weight"), h)?;
1064 let post_norm = s.norm(&format!("{p}.post_attention_layernorm.weight"), h)?;
1065 let q_norm = s.norm(&format!("{p}.self_attn.q_norm.weight"), hd)?;
1066 let k_norm = s.norm(&format!("{p}.self_attn.k_norm.weight"), hd)?;
1067 let a = |n: &str| format!("{p}.self_attn.{n}.weight");
1068 let m = |n: &str| format!("{p}.mlp.{n}.weight");
1069 let l = Some(layer);
1070 let qkv = s.matrix(
1071 l,
1072 DenseTensor::Qkv,
1073 &[(a("q_proj"), qd), (a("k_proj"), kvd), (a("v_proj"), kvd)],
1074 h,
1075 )?;
1076 let o = s.matrix(l, DenseTensor::O, &[(a("o_proj"), h)], qd)?;
1077 // gate|up: gate rows first, then up rows.
1078 let gate_up = s.matrix(
1079 l,
1080 DenseTensor::GateUp,
1081 &[(m("gate_proj"), i), (m("up_proj"), i)],
1082 h,
1083 )?;
1084 let down = s.matrix(l, DenseTensor::Down, &[(m("down_proj"), h)], i)?;
1085 layers.push(DenseLayer {
1086 input_norm,
1087 post_norm,
1088 q_norm,
1089 k_norm,
1090 qkv,
1091 o,
1092 gate_up,
1093 down,
1094 });
1095 progress(&format!("layer {}/{} uploaded", layer + 1, config.layers));
1096 }
1097
1098 let final_norm = s.norm("model.norm.weight", h)?;
1099 let lm_head = if config.tie_word_embeddings {
1100 // Tied: the lm_head is the embedding matrix (`[vocab][hidden]`, the GEMV's `[n][k]`),
1101 // uploaded from the host copy; the checkpoint carries no `lm_head.weight`.
1102 let m = s
1103 .uploader
1104 .upload_bf16(None, DenseTensor::LmHead, config.vocab, h, &embed_bf16)
1105 .map_err(|e| format!("lm_head (tied to embed_tokens) upload: {e}"))?;
1106 if m.n() != config.vocab || m.k() != h {
1107 return Err(format!(
1108 "lm_head (tied) upload returned [{}][{}], asked [{}][{h}]",
1109 m.n(),
1110 m.k(),
1111 config.vocab
1112 ));
1113 }
1114 s.resident += config.matrix_bytes(DenseTensor::LmHead, config.vocab, h);
1115 s.uploads += 1;
1116 m
1117 } else {
1118 s.matrix(
1119 None,
1120 DenseTensor::LmHead,
1121 &[("lm_head.weight".to_string(), config.vocab)],
1122 h,
1123 )?
1124 };
1125 progress("lm_head uploaded");
1126 let (resident, uploads) = (s.resident, s.uploads);
1127 drop(s);
1128
1129 let weights = Qwen3DenseOmegaWeights {
1130 config: config.clone(),
1131 embed_bf16,
1132 layers,
1133 final_norm,
1134 lm_head,
1135 };
1136 let report = DenseLoadReport {
1137 resident_bytes: resident,
1138 host_bytes: weights.host_bytes(),
1139 transient_bytes,
1140 uploads,
1141 peak_rss_before_bytes: peak_before,
1142 peak_rss_bytes: peak_rss_bytes(),
1143 seconds: t0.elapsed().as_secs_f64(),
1144 };
1145 Ok((weights, report))
1146}
1147
1148// ---------------------------------------------------------------------------
1149// The tiny host-test dense model and the recording uploader.
1150// ---------------------------------------------------------------------------
1151
1152#[cfg(any(test, feature = "host-test-engine"))]
1153#[cfg_attr(not(test), allow(dead_code))]
1154pub(crate) mod test_support {
1155 //! A tiny dense Qwen3 checkpoint (in memory or written as two shards, bf16 or FP8) and a
1156 //! recording uploader with host GEMVs, so the loader runs end to end without a chip.
1157 use super::*;
1158 use crate::qwen3_moe::{f32_to_bf16, fp8_e4m3fn_to_f32};
1159 use crate::qwen3_moe_omega::test_support::{prand, MemorySource};
1160 use std::sync::Mutex;
1161
1162 /// 2 layers, hidden 256, 4 query heads over 2 kv heads of 128 (q_dim 512 differs from hidden,
1163 /// so a transposed o_proj fails), intermediate 512, vocab 64. bf16.
1164 pub fn tiny_config() -> Qwen3DenseConfig {
1165 Qwen3DenseConfig {
1166 format: DenseWeightFormat::Bf16,
1167 layers: 2,
1168 hidden: 256,
1169 q_heads: 4,
1170 kv_heads: 2,
1171 head_dim: 128,
1172 intermediate: 512,
1173 vocab: 64,
1174 rms_eps: 1e-6,
1175 rope_theta: 1e6,
1176 max_position: 4096,
1177 eos_token_ids: vec![3],
1178 tie_word_embeddings: false,
1179 }
1180 }
1181
1182 /// The same shape stored as Qwen's FP8 (e4m3 projections with block-128 scales).
1183 pub fn tiny_fp8_config() -> Qwen3DenseConfig {
1184 Qwen3DenseConfig {
1185 format: DenseWeightFormat::Fp8Block128,
1186 ..tiny_config()
1187 }
1188 }
1189
1190 /// The Hugging Face `config.json` text of `c` (the keys Qwen3-8B's carries, plus Qwen3-8B-FP8's
1191 /// `quantization_config` for an FP8 config).
1192 pub fn config_json(c: &Qwen3DenseConfig) -> String {
1193 let mut v = serde_json::json!({
1194 "architectures": ["Qwen3ForCausalLM"],
1195 "attention_bias": false,
1196 "attention_dropout": 0.0,
1197 "bos_token_id": 1,
1198 "eos_token_id": c.eos_token_ids,
1199 "head_dim": c.head_dim,
1200 "hidden_act": "silu",
1201 "hidden_size": c.hidden,
1202 "initializer_range": 0.02,
1203 "intermediate_size": c.intermediate,
1204 "max_position_embeddings": c.max_position,
1205 "max_window_layers": c.layers,
1206 "model_type": "qwen3",
1207 "num_attention_heads": c.q_heads,
1208 "num_hidden_layers": c.layers,
1209 "num_key_value_heads": c.kv_heads,
1210 "rms_norm_eps": c.rms_eps,
1211 "rope_scaling": null,
1212 "rope_theta": c.rope_theta,
1213 "sliding_window": null,
1214 "tie_word_embeddings": c.tie_word_embeddings,
1215 "torch_dtype": "bfloat16",
1216 "transformers_version": "4.51.0",
1217 "use_cache": true,
1218 "use_sliding_window": false,
1219 "vocab_size": c.vocab
1220 });
1221 if c.format == DenseWeightFormat::Fp8Block128 {
1222 v["quantization_config"] = serde_json::json!({
1223 "activation_scheme": "dynamic",
1224 "fmt": "e4m3",
1225 "quant_method": "fp8",
1226 "weight_block_size": [128, 128]
1227 });
1228 }
1229 v.to_string()
1230 }
1231
1232 /// What the tiny checkpoint's projections hold.
1233 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1234 pub enum TinyWeights {
1235 /// bf16: small random values. FP8: random e4m3 codes with random block scales.
1236 Random,
1237 /// The bf16/FP8 twin: every projection value is an e4m3 value; the FP8 copy stores the
1238 /// codes with scales of exactly 1.0, the bf16 copy the same values as bf16 (exact, e4m3
1239 /// is a subset of bf16). Every other tensor is the same in both.
1240 Twin,
1241 }
1242
1243 /// One tensor of the tiny checkpoint: name, safetensors dtype, shape, little-endian bytes.
1244 pub type TinyTensor = (String, &'static str, Vec<usize>, Vec<u8>);
1245
1246 /// A finite e4m3 code from the pseudo-random stream: any sign and mantissa, exponent field
1247 /// 0..=4 (magnitudes up to 0.234), never a NaN code.
1248 fn e4m3_code(seed: u64, i: usize) -> u8 {
1249 let b = ((prand(seed, i) + 1.0) * 32768.0) as u32;
1250 let e = ((b >> 3) & 7) % 5;
1251 ((b & 0x80) | (e << 3) | (b & 7)) as u8
1252 }
1253
1254 fn bf16_bytes(values: impl Iterator<Item = f32>) -> Vec<u8> {
1255 values.flat_map(|v| f32_to_bf16(v).to_le_bytes()).collect()
1256 }
1257
1258 /// Every tensor of the tiny checkpoint of `c` with random weights, each tensor with its own
1259 /// seed so rows of different tensors differ, in checkpoint order.
1260 pub fn tensors(c: &Qwen3DenseConfig) -> Vec<TinyTensor> {
1261 tensors_with(c, TinyWeights::Random)
1262 }
1263
1264 /// Every tensor of the tiny checkpoint of `c`, in checkpoint order (an FP8 projection is
1265 /// followed by its `weight_scale_inv`).
1266 pub fn tensors_with(c: &Qwen3DenseConfig, mode: TinyWeights) -> Vec<TinyTensor> {
1267 enum Kind {
1268 /// bf16 `bias + prand * scale`.
1269 Plain(f32, f32),
1270 /// A projection `[rows][cols]`.
1271 Proj,
1272 }
1273 let (h, i, hd) = (c.hidden, c.intermediate, c.head_dim);
1274 let mut spec: Vec<(String, Vec<usize>, Kind)> = vec![(
1275 "model.embed_tokens.weight".into(),
1276 vec![c.vocab, h],
1277 Kind::Plain(1.0, 0.0),
1278 )];
1279 for l in 0..c.layers {
1280 let p = format!("model.layers.{l}");
1281 let norm = Kind::Plain(0.1, 1.0);
1282 spec.push((format!("{p}.input_layernorm.weight"), vec![h], norm));
1283 spec.push((
1284 format!("{p}.self_attn.q_proj.weight"),
1285 vec![c.q_dim(), h],
1286 Kind::Proj,
1287 ));
1288 spec.push((
1289 format!("{p}.self_attn.k_proj.weight"),
1290 vec![c.kv_dim(), h],
1291 Kind::Proj,
1292 ));
1293 spec.push((
1294 format!("{p}.self_attn.v_proj.weight"),
1295 vec![c.kv_dim(), h],
1296 Kind::Proj,
1297 ));
1298 spec.push((
1299 format!("{p}.self_attn.o_proj.weight"),
1300 vec![h, c.q_dim()],
1301 Kind::Proj,
1302 ));
1303 spec.push((
1304 format!("{p}.self_attn.q_norm.weight"),
1305 vec![hd],
1306 Kind::Plain(0.1, 1.0),
1307 ));
1308 spec.push((
1309 format!("{p}.self_attn.k_norm.weight"),
1310 vec![hd],
1311 Kind::Plain(0.1, 1.0),
1312 ));
1313 spec.push((
1314 format!("{p}.post_attention_layernorm.weight"),
1315 vec![h],
1316 Kind::Plain(0.1, 1.0),
1317 ));
1318 spec.push((format!("{p}.mlp.gate_proj.weight"), vec![i, h], Kind::Proj));
1319 spec.push((format!("{p}.mlp.up_proj.weight"), vec![i, h], Kind::Proj));
1320 spec.push((format!("{p}.mlp.down_proj.weight"), vec![h, i], Kind::Proj));
1321 }
1322 spec.push(("model.norm.weight".into(), vec![h], Kind::Plain(0.1, 1.0)));
1323 if !c.tie_word_embeddings {
1324 spec.push((
1325 "lm_head.weight".into(),
1326 vec![c.vocab, h],
1327 Kind::Plain(0.1, 0.0),
1328 ));
1329 }
1330
1331 let fp8 = c.format == DenseWeightFormat::Fp8Block128;
1332 let mut out = Vec::new();
1333 for (index, (name, shape, kind)) in spec.into_iter().enumerate() {
1334 let seed = index as u64 + 1;
1335 let n: usize = shape.iter().product();
1336 let codes = || (0..n).map(move |j| e4m3_code(seed, j));
1337 match (kind, fp8, mode) {
1338 (Kind::Proj, false, TinyWeights::Twin) => {
1339 let values = codes().map(fp8_e4m3fn_to_f32);
1340 out.push((name, "BF16", shape, bf16_bytes(values)));
1341 }
1342 (Kind::Proj, true, mode) => {
1343 let grid = vec![shape[0] / FP8_BLOCK, shape[1] / FP8_BLOCK];
1344 let g = grid[0] * grid[1];
1345 let scales = match mode {
1346 TinyWeights::Twin => bf16_bytes((0..g).map(|_| 1.0)),
1347 TinyWeights::Random => bf16_bytes(
1348 (0..g).map(|j| 0.01 + 0.005 * (prand(seed ^ 0x5ca1e, j) + 1.0)),
1349 ),
1350 };
1351 out.push((name.clone(), "F8_E4M3", shape, codes().collect()));
1352 out.push((format!("{name}_scale_inv"), "BF16", grid, scales));
1353 }
1354 (kind, _, _) => {
1355 let (scale, bias) = match kind {
1356 Kind::Plain(s, b) => (s, b),
1357 Kind::Proj => (0.05, 0.0),
1358 };
1359 let v = bf16_bytes((0..n).map(|j| bias + prand(seed, j) * scale));
1360 out.push((name, "BF16", shape, v));
1361 }
1362 }
1363 }
1364 out
1365 }
1366
1367 pub fn memory_source(c: &Qwen3DenseConfig) -> MemorySource {
1368 memory_source_of(tensors(c))
1369 }
1370
1371 pub fn memory_source_of(tensors: Vec<TinyTensor>) -> MemorySource {
1372 let mut m = MemorySource::default();
1373 for (name, dtype, shape, bytes) in tensors {
1374 m.tensors.insert(name, (dtype.into(), shape, bytes));
1375 }
1376 m
1377 }
1378
1379 /// Writes `config.json`, `generation_config.json`, two safetensors shards (layer 0 and the
1380 /// embedding in the first, the rest in the second) and `model.safetensors.index.json`.
1381 pub fn write_checkpoint(dir: &Path, c: &Qwen3DenseConfig) -> Result<(), String> {
1382 write_checkpoint_of(dir, c, tensors(c))
1383 }
1384
1385 /// [`write_checkpoint`] with the given tensors.
1386 pub fn write_checkpoint_of(
1387 dir: &Path,
1388 c: &Qwen3DenseConfig,
1389 all: Vec<TinyTensor>,
1390 ) -> Result<(), String> {
1391 let io = |e: std::io::Error| format!("{}: {e}", dir.display());
1392 std::fs::create_dir_all(dir).map_err(io)?;
1393 std::fs::write(dir.join("config.json"), config_json(c)).map_err(io)?;
1394 std::fs::write(
1395 dir.join("generation_config.json"),
1396 serde_json::json!({ "eos_token_id": c.eos_token_ids }).to_string(),
1397 )
1398 .map_err(io)?;
1399 let split = all
1400 .iter()
1401 .position(|t| t.0.starts_with("model.layers.1."))
1402 .unwrap_or(all.len());
1403 let mut weight_map = serde_json::Map::new();
1404 for (index, part) in [&all[..split], &all[split..]].into_iter().enumerate() {
1405 let filename = format!("model-0000{}-of-00002.safetensors", index + 1);
1406 let mut header = serde_json::Map::new();
1407 let mut payload = Vec::new();
1408 for (name, dtype, shape, bytes) in part {
1409 header.insert(
1410 name.clone(),
1411 serde_json::json!({"dtype": dtype, "shape": shape,
1412 "data_offsets": [payload.len(), payload.len() + bytes.len()]}),
1413 );
1414 payload.extend_from_slice(bytes);
1415 weight_map.insert(name.clone(), serde_json::json!(filename));
1416 }
1417 let header = serde_json::to_vec(&header).map_err(|e| e.to_string())?;
1418 let mut file = (header.len() as u64).to_le_bytes().to_vec();
1419 file.extend_from_slice(&header);
1420 file.extend_from_slice(&payload);
1421 std::fs::write(dir.join(&filename), file).map_err(io)?;
1422 }
1423 std::fs::write(
1424 dir.join("model.safetensors.index.json"),
1425 serde_json::json!({ "metadata": {}, "weight_map": weight_map }).to_string(),
1426 )
1427 .map_err(io)
1428 }
1429
1430 /// An `[n][k]` bf16 matrix on the host, same f32 schedule as [`super::bf16_kernel_gemv`].
1431 #[derive(Debug)]
1432 pub struct HostGemv {
1433 pub n: usize,
1434 pub k: usize,
1435 pub bits: Vec<u16>,
1436 }
1437
1438 impl DenseGemv for HostGemv {
1439 fn n(&self) -> usize {
1440 self.n
1441 }
1442 fn k(&self) -> usize {
1443 self.k
1444 }
1445 fn gemv_f32(&self, x: &[f32], y: &mut [f32]) -> Result<u64, String> {
1446 if x.len() != self.k || y.len() != self.n {
1447 return Err(format!(
1448 "gemv [{}][{}] given x {} y {}",
1449 self.n,
1450 self.k,
1451 x.len(),
1452 y.len()
1453 ));
1454 }
1455 super::bf16_kernel_gemv(&self.bits, self.n, self.k, x, y).map(|()| 0)
1456 }
1457 }
1458
1459 /// What a record-only upload hands back: the shape, no weights.
1460 #[derive(Debug)]
1461 pub struct RecordedShape {
1462 pub n: usize,
1463 pub k: usize,
1464 }
1465
1466 impl DenseGemv for RecordedShape {
1467 fn n(&self) -> usize {
1468 self.n
1469 }
1470 fn k(&self) -> usize {
1471 self.k
1472 }
1473 fn gemv_f32(&self, _: &[f32], _: &mut [f32]) -> Result<u64, String> {
1474 Err("record-only upload keeps no weights".into())
1475 }
1476 }
1477
1478 /// A deliberately wrong uploader, for the negative controls.
1479 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1480 pub enum UploadMutant {
1481 /// Stores q|k|v with the k rows and the v rows exchanged (FP8: bytes and scale rows).
1482 SwapKv { q_rows: usize, kv_rows: usize },
1483 /// Stores gate|up with the gate rows and the up rows exchanged (FP8: bytes and scales).
1484 SwapGateUp { rows: usize },
1485 /// FP8 only: stores q|k|v with the k and v scale rows exchanged, the bytes right.
1486 SwapKvScales { q_rows: usize, kv_rows: usize },
1487 /// FP8 only: stores every scale grid transposed (`[k/128][n/128]` read as `[n/128][k/128]`).
1488 TransposeScales,
1489 }
1490
1491 /// One upload as the recording fake saw it.
1492 #[derive(Debug)]
1493 pub struct UploadRecord {
1494 pub layer: Option<usize>,
1495 pub what: DenseTensor,
1496 pub n: usize,
1497 pub k: usize,
1498 /// Bytes handed over (FP8: weights plus scales).
1499 pub bytes: usize,
1500 /// The stored bf16 matrix (`keep` uploaders only).
1501 pub matrix: Option<Arc<HostGemv>>,
1502 /// The stored FP8 matrix (`keep` uploaders only).
1503 pub fp8: Option<Arc<HostFp8Gemv>>,
1504 }
1505
1506 /// Records every upload; with `keep` it also stores the matrix for host GEMVs and the byte
1507 /// test. Like omega's `Bf16Tensor::upload` and `Fp8Tensor::upload` it refuses a wrong length,
1508 /// a NaN or infinite bf16 word or scale and an e4m3 NaN code, so every byte is looked at.
1509 #[derive(Debug, Default)]
1510 pub struct RecordingDenseUploader {
1511 pub keep: bool,
1512 pub mutant: Option<UploadMutant>,
1513 pub records: Mutex<Vec<UploadRecord>>,
1514 }
1515
1516 impl RecordingDenseUploader {
1517 pub fn keeping() -> Self {
1518 Self {
1519 keep: true,
1520 ..Self::default()
1521 }
1522 }
1523 /// Shapes and byte counts only (the real-checkpoint run: no host copy of the model).
1524 pub fn record_only() -> Self {
1525 Self::default()
1526 }
1527 fn with(mutant: UploadMutant) -> Self {
1528 Self {
1529 keep: true,
1530 mutant: Some(mutant),
1531 ..Self::default()
1532 }
1533 }
1534 pub fn swapping_kv(c: &Qwen3DenseConfig) -> Self {
1535 Self::with(UploadMutant::SwapKv {
1536 q_rows: c.q_dim(),
1537 kv_rows: c.kv_dim(),
1538 })
1539 }
1540 pub fn swapping_gate_up(c: &Qwen3DenseConfig) -> Self {
1541 Self::with(UploadMutant::SwapGateUp {
1542 rows: c.intermediate,
1543 })
1544 }
1545 pub fn swapping_kv_scales(c: &Qwen3DenseConfig) -> Self {
1546 Self::with(UploadMutant::SwapKvScales {
1547 q_rows: c.q_dim(),
1548 kv_rows: c.kv_dim(),
1549 })
1550 }
1551 pub fn transposing_scales() -> Self {
1552 Self::with(UploadMutant::TransposeScales)
1553 }
1554
1555 fn record(
1556 &self,
1557 layer: Option<usize>,
1558 what: DenseTensor,
1559 n: usize,
1560 k: usize,
1561 bytes: usize,
1562 matrix: Option<Arc<HostGemv>>,
1563 fp8: Option<Arc<HostFp8Gemv>>,
1564 ) {
1565 self.records.lock().unwrap().push(UploadRecord {
1566 layer,
1567 what,
1568 n,
1569 k,
1570 bytes,
1571 matrix,
1572 fp8,
1573 });
1574 }
1575 }
1576
1577 /// Exchanges rows `a..a+rows` and `b..b+rows` of a row-major matrix of `width` columns
1578 /// (`a + rows <= b`).
1579 fn swap_rows<T>(m: &mut [T], width: usize, a: usize, b: usize, rows: usize) {
1580 let (lo, hi) = m.split_at_mut(b * width);
1581 lo[a * width..(a + rows) * width].swap_with_slice(&mut hi[..rows * width]);
1582 }
1583
1584 impl DenseUploader for RecordingDenseUploader {
1585 fn upload_bf16(
1586 &self,
1587 layer: Option<usize>,
1588 what: DenseTensor,
1589 n: usize,
1590 k: usize,
1591 bits: &[u16],
1592 ) -> Result<Arc<dyn DenseGemv>, String> {
1593 if bits.len() != n * k {
1594 return Err(format!("{} words for [{n}][{k}]", bits.len()));
1595 }
1596 // bf16 exponent all ones = Inf or NaN.
1597 if let Some(at) = bits.iter().position(|&b| b & 0x7f80 == 0x7f80) {
1598 return Err(format!("word {at} is NaN or infinite (refused at upload)"));
1599 }
1600 let matrix = self.keep.then(|| {
1601 let mut stored = bits.to_vec();
1602 match (self.mutant, what) {
1603 (Some(UploadMutant::SwapKv { q_rows, kv_rows }), DenseTensor::Qkv) => {
1604 swap_rows(&mut stored, k, q_rows, q_rows + kv_rows, kv_rows);
1605 }
1606 (Some(UploadMutant::SwapGateUp { rows }), DenseTensor::GateUp) => {
1607 swap_rows(&mut stored, k, 0, rows, rows);
1608 }
1609 _ => {}
1610 }
1611 Arc::new(HostGemv { n, k, bits: stored })
1612 });
1613 self.record(layer, what, n, k, bits.len() * 2, matrix.clone(), None);
1614 Ok(match matrix {
1615 Some(m) => m,
1616 None => Arc::new(RecordedShape { n, k }),
1617 })
1618 }
1619
1620 fn upload_fp8(
1621 &self,
1622 layer: Option<usize>,
1623 what: DenseTensor,
1624 n: usize,
1625 k: usize,
1626 w: &[u8],
1627 scales: &[u16],
1628 ) -> Result<Arc<dyn DenseGemv>, String> {
1629 check_fp8_upload(n, k, w, scales)?;
1630 let fp8 = if self.keep {
1631 let (mut w, mut s) = (w.to_vec(), scales.to_vec());
1632 let (b, kb) = (FP8_BLOCK, k / FP8_BLOCK);
1633 match (self.mutant, what) {
1634 (Some(UploadMutant::SwapKv { q_rows, kv_rows }), DenseTensor::Qkv) => {
1635 swap_rows(&mut w, k, q_rows, q_rows + kv_rows, kv_rows);
1636 swap_rows(&mut s, kb, q_rows / b, (q_rows + kv_rows) / b, kv_rows / b);
1637 }
1638 (Some(UploadMutant::SwapGateUp { rows }), DenseTensor::GateUp) => {
1639 swap_rows(&mut w, k, 0, rows, rows);
1640 swap_rows(&mut s, kb, 0, rows / b, rows / b);
1641 }
1642 (Some(UploadMutant::SwapKvScales { q_rows, kv_rows }), DenseTensor::Qkv) => {
1643 swap_rows(&mut s, kb, q_rows / b, (q_rows + kv_rows) / b, kv_rows / b);
1644 }
1645 (Some(UploadMutant::TransposeScales), _) => {
1646 let nb = n / b;
1647 s = (0..nb * kb)
1648 .map(|j| scales[(j % nb) * kb + j / nb])
1649 .collect();
1650 }
1651 _ => {}
1652 }
1653 Some(Arc::new(HostFp8Gemv::new(n, k, w, s)?))
1654 } else {
1655 None
1656 };
1657 let bytes = w.len() + 2 * scales.len();
1658 self.record(layer, what, n, k, bytes, None, fp8.clone());
1659 Ok(match fp8 {
1660 Some(m) => m,
1661 None => Arc::new(RecordedShape { n, k }),
1662 })
1663 }
1664 }
1665
1666 /// The byte test: the uploads must be, in order, each layer's q|k|v, o, gate|up, down, then
1667 /// the lm_head, with the right shapes and byte counts, and every stored row (FP8: every e4m3
1668 /// row and every scale row) must equal the checkpoint row it stands for (read again,
1669 /// independently, from `source`). The first wrong row is named.
1670 pub fn check_upload_bytes(
1671 c: &Qwen3DenseConfig,
1672 source: &mut dyn TensorSource,
1673 records: &[UploadRecord],
1674 ) -> Result<(), String> {
1675 let (h, i, qd, kvd) = (c.hidden, c.intermediate, c.q_dim(), c.kv_dim());
1676 // (tensor name, rows, cols) of each checkpoint part, in row order.
1677 type Part = (String, usize, usize);
1678 type Expected = (Option<usize>, DenseTensor, usize, usize, Vec<Part>);
1679 let mut expected: Vec<Expected> = Vec::new();
1680 for l in 0..c.layers {
1681 let p = format!("model.layers.{l}");
1682 let a = |n: &str| format!("{p}.self_attn.{n}.weight");
1683 let m = |n: &str| format!("{p}.mlp.{n}.weight");
1684 expected.push((
1685 Some(l),
1686 DenseTensor::Qkv,
1687 c.qkv_n(),
1688 h,
1689 vec![
1690 (a("q_proj"), qd, h),
1691 (a("k_proj"), kvd, h),
1692 (a("v_proj"), kvd, h),
1693 ],
1694 ));
1695 expected.push((Some(l), DenseTensor::O, h, qd, vec![(a("o_proj"), h, qd)]));
1696 expected.push((
1697 Some(l),
1698 DenseTensor::GateUp,
1699 2 * i,
1700 h,
1701 vec![(m("gate_proj"), i, h), (m("up_proj"), i, h)],
1702 ));
1703 expected.push((
1704 Some(l),
1705 DenseTensor::Down,
1706 h,
1707 i,
1708 vec![(m("down_proj"), h, i)],
1709 ));
1710 }
1711 expected.push((
1712 None,
1713 DenseTensor::LmHead,
1714 c.vocab,
1715 h,
1716 vec![("lm_head.weight".into(), c.vocab, h)],
1717 ));
1718 if records.len() != expected.len() {
1719 return Err(format!(
1720 "{} uploads, expected {}",
1721 records.len(),
1722 expected.len()
1723 ));
1724 }
1725 for (rec, (layer, what, n, k, parts)) in records.iter().zip(expected) {
1726 let at = format!("upload {:?} {}", layer, what.name());
1727 let bytes = c.matrix_bytes(what, n, k);
1728 if (rec.layer, rec.what, rec.n, rec.k, rec.bytes) != (layer, what, n, k, bytes) {
1729 return Err(format!(
1730 "{at}: got {:?} {} [{}][{}] {} bytes, expected [{n}][{k}] {bytes} bytes",
1731 rec.layer,
1732 rec.what.name(),
1733 rec.n,
1734 rec.k,
1735 rec.bytes,
1736 ));
1737 }
1738 let mut row0 = 0usize;
1739 if c.is_fp8(what) {
1740 let m = rec
1741 .fp8
1742 .as_ref()
1743 .ok_or_else(|| format!("{at}: no FP8 kept"))?;
1744 let kb = k / FP8_BLOCK;
1745 for (name, rows, cols) in parts {
1746 let mut want = vec![0u8; rows * cols];
1747 source.read_into(&name, "F8_E4M3", &[rows, cols], &mut want)?;
1748 let got = &m.weights()[row0 * k..(row0 + rows) * k];
1749 if let Some(r) = (0..rows)
1750 .find(|&r| got[r * k..(r + 1) * k] != want[r * cols..(r + 1) * cols])
1751 {
1752 return Err(format!(
1753 "{at}: row {} is not {name} row {r} (rows {row0}..{} must be {name})",
1754 row0 + r,
1755 row0 + rows
1756 ));
1757 }
1758 let scale_name = format!("{name}_scale_inv");
1759 let (srows, s0) = (rows / FP8_BLOCK, row0 / FP8_BLOCK);
1760 let mut want = vec![0u16; srows * kb];
1761 read_bf16(source, &scale_name, &[srows, kb], &mut want)?;
1762 let got = &m.scales()[s0 * kb..(s0 + srows) * kb];
1763 if let Some(r) = (0..srows)
1764 .find(|&r| got[r * kb..(r + 1) * kb] != want[r * kb..(r + 1) * kb])
1765 {
1766 return Err(format!(
1767 "{at}: scale row {} is not {scale_name} row {r} (scale rows {s0}..{} must be {scale_name})",
1768 s0 + r,
1769 s0 + srows
1770 ));
1771 }
1772 row0 += rows;
1773 }
1774 continue;
1775 }
1776 let m = rec
1777 .matrix
1778 .as_ref()
1779 .ok_or_else(|| format!("{at}: not kept"))?;
1780 for (name, rows, cols) in parts {
1781 let mut want = vec![0u16; rows * cols];
1782 read_bf16(source, &name, &[rows, cols], &mut want)?;
1783 for r in 0..rows {
1784 let got = &m.bits[(row0 + r) * k..(row0 + r + 1) * k];
1785 if got != &want[r * cols..(r + 1) * cols] {
1786 return Err(format!(
1787 "{at}: row {} is not {name} row {r} (rows {row0}..{} must be {name})",
1788 row0 + r,
1789 row0 + rows
1790 ));
1791 }
1792 }
1793 row0 += rows;
1794 }
1795 }
1796 Ok(())
1797 }
1798}
1799
1800/// Host-only test model (feature `host-test-engine`): the tiny dense checkpoint and the recording
1801/// uploader, so other crates can load a dense model without a chip. Never in a server build.
1802#[cfg(feature = "host-test-engine")]
1803pub mod host_test_model {
1804 use super::test_support::{memory_source, tiny_config, tiny_fp8_config, write_checkpoint};
1805 /// The recording uploader (`keeping()` for host GEMVs), to load the written checkpoint
1806 /// with [`load_qwen3_dense_omega`].
1807 pub use super::test_support::{HostGemv, RecordingDenseUploader, UploadRecord};
1808 use super::*;
1809
1810 /// 2 layers, hidden 256, 4 query heads over 2 kv heads of 128 (q_dim 512 differs from hidden,
1811 /// so a transposed o_proj fails), intermediate 512, vocab 64.
1812 pub fn config() -> Qwen3DenseConfig {
1813 tiny_config()
1814 }
1815
1816 /// The same shape stored as Qwen's FP8 (e4m3 projections, block-128 bf16 scales).
1817 pub fn config_fp8() -> Qwen3DenseConfig {
1818 tiny_fp8_config()
1819 }
1820
1821 /// Writes the tiny checkpoint (config, generation config, two shards, index) into `dir`.
1822 pub fn write(dir: &Path) -> Result<(), String> {
1823 write_checkpoint(dir, &tiny_config())
1824 }
1825
1826 /// Writes the tiny FP8 checkpoint (random e4m3 codes and scales) into `dir`.
1827 pub fn write_fp8(dir: &Path) -> Result<(), String> {
1828 write_checkpoint(dir, &tiny_fp8_config())
1829 }
1830
1831 /// The tiny model loaded from memory, every matrix kept on the host for host GEMVs.
1832 pub fn load() -> Result<(Qwen3DenseOmegaWeights, DenseLoadReport), String> {
1833 let c = tiny_config();
1834 load_qwen3_dense_omega_from(
1835 &c,
1836 &mut memory_source(&c),
1837 &RecordingDenseUploader::keeping(),
1838 &mut |_| {},
1839 )
1840 }
1841}
1842
1843#[cfg(test)]
1844mod tests {
1845 use super::test_support::*;
1846 use super::*;
1847 use crate::qwen3_moe::f32_to_bf16;
1848 use crate::qwen3_moe_omega::test_support::MemorySource;
1849
1850 /// `~/models/qwen3-8b/config.json`, verbatim.
1851 const QWEN3_8B_CONFIG: &str = r#"{
1852 "architectures": ["Qwen3ForCausalLM"], "attention_bias": false, "attention_dropout": 0.0,
1853 "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": 128, "hidden_act": "silu",
1854 "hidden_size": 4096, "initializer_range": 0.02, "intermediate_size": 12288,
1855 "max_position_embeddings": 40960, "max_window_layers": 36, "model_type": "qwen3",
1856 "num_attention_heads": 32, "num_hidden_layers": 36, "num_key_value_heads": 8,
1857 "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sliding_window": null,
1858 "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.51.0",
1859 "use_cache": true, "use_sliding_window": false, "vocab_size": 151936
1860}"#;
1861 const QWEN3_8B_GENERATION: &str = r#"{"eos_token_id": [151645, 151643]}"#;
1862
1863 fn scratch(name: &str) -> std::path::PathBuf {
1864 std::env::temp_dir().join(format!("aien-own8b-{name}-{}", std::process::id()))
1865 }
1866
1867 fn load_tiny(
1868 up: &RecordingDenseUploader,
1869 ) -> Result<(Qwen3DenseOmegaWeights, DenseLoadReport), String> {
1870 let c = tiny_config();
1871 load_qwen3_dense_omega_from(&c, &mut memory_source(&c), up, &mut |_| {})
1872 }
1873
1874 /// The 8B config with one field replaced (`null` removes it).
1875 fn variant(key: &str, value: serde_json::Value) -> Result<Qwen3DenseConfig, String> {
1876 let mut v: serde_json::Value = serde_json::from_str(QWEN3_8B_CONFIG).unwrap();
1877 if value.is_null() {
1878 v.as_object_mut().unwrap().remove(key);
1879 } else {
1880 v[key] = value;
1881 }
1882 Qwen3DenseConfig::from_json(&v.to_string(), Some(QWEN3_8B_GENERATION))
1883 }
1884
1885 fn refused(r: Result<Qwen3DenseConfig, String>, needle: &str) {
1886 let e = r.expect_err("config must be refused");
1887 assert!(e.contains(needle), "refusal {e:?} does not name {needle:?}");
1888 }
1889
1890 // ADR 0004 step 1: the 8B's KV cache is built from this geometry (36 layers, 32/8, 128).
1891 #[test]
1892 fn kv_geometry_from_the_qwen3_8b_config() {
1893 let c = Qwen3DenseConfig::from_json(QWEN3_8B_CONFIG, Some(QWEN3_8B_GENERATION)).unwrap();
1894 assert_eq!(
1895 KvGeometry::from(&c),
1896 KvGeometry {
1897 layers: 36,
1898 q_heads: 32,
1899 kv_heads: 8,
1900 head_dim: 128,
1901 rope_theta: 1e6,
1902 block_size: KV_BLOCK_SIZE,
1903 }
1904 );
1905 }
1906
1907 #[test]
1908 fn reads_the_qwen3_8b_config() {
1909 let c = Qwen3DenseConfig::from_json(QWEN3_8B_CONFIG, Some(QWEN3_8B_GENERATION)).unwrap();
1910 assert_eq!(
1911 (
1912 c.layers,
1913 c.hidden,
1914 c.q_heads,
1915 c.kv_heads,
1916 c.head_dim,
1917 c.intermediate,
1918 c.vocab
1919 ),
1920 (36, 4096, 32, 8, 128, 12288, 151936)
1921 );
1922 assert_eq!((c.rms_eps, c.rope_theta), (1e-6, 1e6));
1923 assert_eq!(c.eos_token_ids, vec![151645, 151643]);
1924 assert_eq!((c.qkv_n(), c.gate_up_n()), (6144, 24576));
1925 // Design section 0: 7,568,097,280 weights streamed per token (lm_head in, embedding out).
1926 assert_eq!(c.model_resident_bytes(), 2 * 7_568_097_280);
1927 assert_eq!(c.layer_resident_bytes(), 2 * 192_937_984);
1928 let real = std::path::Path::new(env!("HOME")).join("models/qwen3-8b");
1929 if real.join("config.json").exists() {
1930 assert_eq!(Qwen3DenseConfig::from_checkpoint(&real).unwrap(), c);
1931 }
1932 }
1933
1934 #[test]
1935 fn refuses_qwen3_moe() {
1936 let moe = r#"{"architectures": ["Qwen3MoeForCausalLM"], "model_type": "qwen3_moe",
1937 "hidden_size": 2048, "num_experts": 128, "tie_word_embeddings": false}"#;
1938 refused(Qwen3DenseConfig::from_json(moe, None), "qwen3_moe");
1939 refused(variant("model_type", "qwen3_moe".into()), "qwen3_moe");
1940 refused(variant("model_type", "llama".into()), "model_type");
1941 }
1942
1943 #[test]
1944 fn tied_embeddings_config_parses() {
1945 let c = variant("tie_word_embeddings", true.into()).unwrap();
1946 assert!(c.tie_word_embeddings);
1947 assert!(
1948 !variant("tie_word_embeddings", false.into())
1949 .unwrap()
1950 .tie_word_embeddings
1951 );
1952 // The lm_head is not read through the loader buffer when tied: the largest projection
1953 // (gate|up, 2 * 12288 x 4096 words) sets it, not the 151936 x 4096 lm_head.
1954 assert_eq!(c.loader_buffer_words(), 2 * 12288 * 4096);
1955 }
1956
1957 /// Qwen3-4B-Instruct-2507's shape (tied, k 2560 and 9728) is inside every kernel rule.
1958 #[test]
1959 fn qwen3_4b_config_parses_with_tied_embeddings() {
1960 let cfg = r#"{"architectures": ["Qwen3ForCausalLM"], "attention_bias": false,
1961 "attention_dropout": 0.0, "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": 128,
1962 "hidden_act": "silu", "hidden_size": 2560, "initializer_range": 0.02,
1963 "intermediate_size": 9728, "max_position_embeddings": 262144, "max_window_layers": 36,
1964 "model_type": "qwen3", "num_attention_heads": 32, "num_hidden_layers": 36,
1965 "num_key_value_heads": 8, "rms_norm_eps": 1e-06, "rope_scaling": null,
1966 "rope_theta": 5000000, "sliding_window": null, "tie_word_embeddings": true,
1967 "torch_dtype": "bfloat16", "transformers_version": "4.51.0", "use_cache": true,
1968 "use_sliding_window": false, "vocab_size": 151936}"#;
1969 let c = Qwen3DenseConfig::from_json(cfg, None).unwrap();
1970 assert!(c.tie_word_embeddings);
1971 assert_eq!(c.format, DenseWeightFormat::Bf16);
1972 assert_eq!((c.hidden, c.intermediate, c.layers), (2560, 9728, 36));
1973 assert_eq!(c.qkv_n(), 6144);
1974 assert_eq!(c.rope_theta, 5e6);
1975 }
1976
1977 /// Tied: no `lm_head.weight` in the checkpoint, the lm_head upload is the embedding bit for
1978 /// bit, and an untied config over the same tensors is refused (lm_head missing).
1979 #[test]
1980 fn tied_lm_head_is_the_embedding() {
1981 let c = Qwen3DenseConfig {
1982 tie_word_embeddings: true,
1983 ..tiny_config()
1984 };
1985 let tensors = tensors(&c);
1986 assert!(tensors.iter().all(|t| t.0 != "lm_head.weight"));
1987 let up = RecordingDenseUploader::keeping();
1988 let (w, report) = load_qwen3_dense_omega_from(
1989 &c,
1990 &mut memory_source_of(tensors.clone()),
1991 &up,
1992 &mut |_| {},
1993 )
1994 .unwrap();
1995 let records = up.records.lock().unwrap();
1996 let lm = records
1997 .iter()
1998 .find(|r| r.what == DenseTensor::LmHead)
1999 .unwrap();
2000 assert_eq!(lm.matrix.as_ref().unwrap().bits, w.embed_bf16);
2001 assert_eq!(report.uploads, 4 * c.layers + 1);
2002 let untied = tiny_config();
2003 let e = load_qwen3_dense_omega_from(
2004 &untied,
2005 &mut memory_source_of(tensors),
2006 &RecordingDenseUploader::keeping(),
2007 &mut |_| {},
2008 )
2009 .unwrap_err();
2010 assert!(e.contains("lm_head"), "{e}");
2011 }
2012
2013 #[test]
2014 fn refuses_k_not_a_multiple_of_256() {
2015 // hidden 4224 = 16.5 * 256: q|k|v, gate|up and lm_head have k = 4224.
2016 refused(variant("hidden_size", 4224.into()), "k a multiple of 256");
2017 // intermediate 12416: down has k = 12416.
2018 refused(
2019 variant("intermediate_size", 12416.into()),
2020 "down [4096][12416]",
2021 );
2022 }
2023
2024 #[test]
2025 fn refuses_k_past_the_gemv_and_matmul_limits() {
2026 // down k = 16640 > 16384.
2027 refused(
2028 variant("intermediate_size", 16640.into()),
2029 "down [4096][16640]",
2030 );
2031 // lm_head n = 262400 > the resident matmul N limit 262144 (the GEMV itself would take it).
2032 refused(
2033 variant("vocab_size", 262400.into()),
2034 "resident matmul limit",
2035 );
2036 }
2037
2038 #[test]
2039 fn refuses_attention_shapes_omega_cannot_run() {
2040 refused(variant("head_dim", 96.into()), "head_dim 96");
2041 refused(
2042 variant("num_key_value_heads", 5.into()),
2043 "QueryHeadsNotDivisible",
2044 );
2045 let mut c = tiny_config();
2046 c.kv_heads = 3;
2047 refused(c.validate().map(|_| c.clone()), "GQA");
2048 refused(variant("num_attention_heads", 128.into()), "GQA");
2049 refused(variant("head_dim", serde_json::Value::Null), "head_dim");
2050 }
2051
2052 #[test]
2053 fn refuses_what_the_engine_does_not_implement() {
2054 refused(
2055 variant(
2056 "rope_scaling",
2057 serde_json::json!({"rope_type": "yarn", "factor": 4.0}),
2058 ),
2059 "rope_scaling",
2060 );
2061 refused(
2062 variant(
2063 "rope_scaling",
2064 serde_json::json!({"rope_type": "llama3", "factor": 8.0, "low_freq_factor": 1.0,
2065 "high_freq_factor": 4.0, "original_max_position_embeddings": 8192}),
2066 ),
2067 "rope_scaling is not implemented",
2068 );
2069 refused(variant("use_sliding_window", true.into()), "sliding_window");
2070 refused(variant("attention_bias", true.into()), "bias");
2071 refused(
2072 variant("architectures", serde_json::json!(["LlamaForCausalLM"])),
2073 "Qwen3ForCausalLM",
2074 );
2075 refused(variant("num_experts", 128.into()), "num_experts");
2076 refused(variant("torch_dtype", "float16".into()), "torch_dtype");
2077 refused(variant("dtype", "float32".into()), "dtype");
2078 }
2079
2080 #[test]
2081 fn tiny_load_shapes_byte_counts_and_order() {
2082 let c = tiny_config();
2083 let up = RecordingDenseUploader::keeping();
2084 let (w, report) = load_tiny(&up).unwrap();
2085 let recs = up.records.lock().unwrap();
2086 let got: Vec<_> = recs
2087 .iter()
2088 .map(|r| (r.layer, r.what, r.n, r.k, r.bytes))
2089 .collect();
2090 let mut want = Vec::new();
2091 for l in 0..c.layers {
2092 want.push((Some(l), DenseTensor::Qkv, 1024, 256, 2 * 1024 * 256));
2093 want.push((Some(l), DenseTensor::O, 256, 512, 2 * 256 * 512));
2094 want.push((Some(l), DenseTensor::GateUp, 1024, 256, 2 * 1024 * 256));
2095 want.push((Some(l), DenseTensor::Down, 256, 512, 2 * 256 * 512));
2096 }
2097 want.push((None, DenseTensor::LmHead, 64, 256, 2 * 64 * 256));
2098 assert_eq!(got, want);
2099 assert_eq!(report.uploads, want.len());
2100 assert_eq!(report.resident_bytes, c.model_resident_bytes());
2101 assert_eq!(
2102 report.resident_bytes,
2103 want.iter().map(|w| w.4).sum::<usize>()
2104 );
2105 assert_eq!(w.embed_bf16.len(), c.vocab * c.hidden);
2106 assert_eq!(
2107 report.host_bytes,
2108 c.embed_host_bytes() + 4 * (c.hidden + c.layers * (2 * c.hidden + 2 * c.head_dim))
2109 );
2110 for l in &w.layers {
2111 assert_eq!((l.qkv.n(), l.qkv.k()), (c.qkv_n(), c.hidden));
2112 assert_eq!((l.gate_up.n(), l.gate_up.k()), (c.gate_up_n(), c.hidden));
2113 assert_eq!((l.q_norm.len(), l.k_norm.len()), (c.head_dim, c.head_dim));
2114 }
2115 assert!(w.embed_row(63).is_ok());
2116 assert!(
2117 w.embed_row(64).is_err(),
2118 "out-of-vocabulary token refused, not wrapped"
2119 );
2120 }
2121
2122 #[test]
2123 fn byte_test_passes_and_concat_order_is_q_k_v_and_gate_up() {
2124 let c = tiny_config();
2125 let up = RecordingDenseUploader::keeping();
2126 load_tiny(&up).unwrap();
2127 let recs = up.records.lock().unwrap();
2128 check_upload_bytes(&c, &mut memory_source(&c), &recs).unwrap();
2129
2130 // Spot check by hand: first row of each block of the layer-1 fused tensors.
2131 let src = memory_source(&c);
2132 let row0 = |name: &str, k: usize| -> Vec<u16> {
2133 src.tensors[name].2[..2 * k]
2134 .chunks_exact(2)
2135 .map(|b| u16::from_le_bytes([b[0], b[1]]))
2136 .collect()
2137 };
2138 let (h, qd, kvd, i) = (c.hidden, c.q_dim(), c.kv_dim(), c.intermediate);
2139 let qkv = recs[4].matrix.as_ref().unwrap();
2140 let row = |m: &HostGemv, r: usize| m.bits[r * m.k..(r + 1) * m.k].to_vec();
2141 assert_eq!(
2142 row(qkv, 0),
2143 row0("model.layers.1.self_attn.q_proj.weight", h)
2144 );
2145 assert_eq!(
2146 row(qkv, qd),
2147 row0("model.layers.1.self_attn.k_proj.weight", h)
2148 );
2149 assert_eq!(
2150 row(qkv, qd + kvd),
2151 row0("model.layers.1.self_attn.v_proj.weight", h)
2152 );
2153 let gu = recs[6].matrix.as_ref().unwrap();
2154 assert_eq!(row(gu, 0), row0("model.layers.1.mlp.gate_proj.weight", h));
2155 assert_eq!(row(gu, i), row0("model.layers.1.mlp.up_proj.weight", h));
2156 }
2157
2158 /// Negative control: an uploader that stores q|k|v with the k and v rows exchanged must fail
2159 /// the byte test, naming the first wrong row.
2160 #[test]
2161 fn negative_control_kv_swap_fails_the_byte_test() {
2162 let c = tiny_config();
2163 let up = RecordingDenseUploader::swapping_kv(&c);
2164 load_tiny(&up).unwrap();
2165 let err = check_upload_bytes(&c, &mut memory_source(&c), &up.records.lock().unwrap())
2166 .expect_err("a k/v row swap must fail the byte test");
2167 assert!(
2168 err.contains(
2169 "upload Some(0) q|k|v: row 512 is not model.layers.0.self_attn.k_proj.weight row 0"
2170 ),
2171 "{err}"
2172 );
2173 }
2174
2175 /// Negative control for the MLP concat: gate and up rows exchanged must fail the byte test.
2176 #[test]
2177 fn negative_control_gate_up_swap_fails_the_byte_test() {
2178 let c = tiny_config();
2179 let up = RecordingDenseUploader::swapping_gate_up(&c);
2180 load_tiny(&up).unwrap();
2181 let err = check_upload_bytes(&c, &mut memory_source(&c), &up.records.lock().unwrap())
2182 .expect_err("a gate/up row swap must fail the byte test");
2183 assert!(
2184 err.contains(
2185 "upload Some(0) gate|up: row 0 is not model.layers.0.mlp.gate_proj.weight row 0"
2186 ),
2187 "{err}"
2188 );
2189 }
2190
2191 #[test]
2192 fn nan_and_missing_tensors_are_refused() {
2193 let c = tiny_config();
2194 let mut src = memory_source(&c);
2195 let name = "model.layers.1.mlp.up_proj.weight";
2196 let bytes = &mut src.tensors.get_mut(name).unwrap().2;
2197 bytes[10..12].copy_from_slice(&f32_to_bf16(f32::NAN).to_le_bytes());
2198 let e = load_qwen3_dense_omega_from(
2199 &c,
2200 &mut src,
2201 &RecordingDenseUploader::keeping(),
2202 &mut |_| {},
2203 )
2204 .unwrap_err();
2205 assert!(e.contains("layer 1 gate|up") && e.contains("NaN"), "{e}");
2206
2207 let mut src = memory_source(&c);
2208 src.tensors.remove("model.layers.1.self_attn.v_proj.weight");
2209 let e = load_qwen3_dense_omega_from(
2210 &c,
2211 &mut src,
2212 &RecordingDenseUploader::keeping(),
2213 &mut |_| {},
2214 )
2215 .unwrap_err();
2216 assert!(e.contains("model.layers.1.self_attn.v_proj.weight"), "{e}");
2217
2218 let mut src = memory_source(&c);
2219 let k = src
2220 .tensors
2221 .get_mut("model.layers.0.self_attn.k_proj.weight")
2222 .unwrap();
2223 k.1 = vec![c.kv_dim() / 2, 2 * c.hidden];
2224 let e = load_qwen3_dense_omega_from(
2225 &c,
2226 &mut src,
2227 &RecordingDenseUploader::keeping(),
2228 &mut |_| {},
2229 )
2230 .unwrap_err();
2231 assert!(e.contains("k_proj"), "{e}");
2232 }
2233
2234 /// Design gate: peak host memory under 2 GB over the embedding. The loader's one buffer is
2235 /// the largest matrix; at the 8B shape that is the lm_head, 1.24 GB.
2236 #[test]
2237 fn transient_is_one_buffer_under_2gb_at_the_8b_shape() {
2238 let c8 = Qwen3DenseConfig::from_json(QWEN3_8B_CONFIG, Some(QWEN3_8B_GENERATION)).unwrap();
2239 let t = dense_loader_transient_bytes(&c8);
2240 assert_eq!(t, 2 * 151936 * 4096);
2241 assert!(t < 2_000_000_000, "{t}");
2242 let (_, report) = load_tiny(&RecordingDenseUploader::keeping()).unwrap();
2243 assert_eq!(
2244 report.transient_bytes,
2245 dense_loader_transient_bytes(&tiny_config())
2246 );
2247 assert!(report.peak_rss_bytes.is_some_and(|b| b > 0));
2248 }
2249
2250 /// Fills every read with a finite pattern (0x3c bytes: bf16 1.17, e4m3 1.5), so a full-width
2251 /// model can be loaded without a checkpoint on disk. Reports the dtypes of `format`'s
2252 /// checkpoint.
2253 struct PatternSource(DenseWeightFormat);
2254
2255 impl TensorSource for PatternSource {
2256 fn read_into(
2257 &mut self,
2258 name: &str,
2259 dtype: &str,
2260 _: &[usize],
2261 dst: &mut [u8],
2262 ) -> Result<(), String> {
2263 assert_eq!(Some(dtype.to_string()), self.dtype_of(name).unwrap());
2264 dst.fill(0x3c);
2265 Ok(())
2266 }
2267
2268 fn dtype_of(&mut self, name: &str) -> Result<Option<String>, String> {
2269 let fp8 = self.0 == DenseWeightFormat::Fp8Block128;
2270 Ok(match (fp8, name) {
2271 (false, n) if n.ends_with("_scale_inv") => None,
2272 (true, n) if n.ends_with("_proj.weight") => Some("F8_E4M3".into()),
2273 _ => Some("BF16".into()),
2274 })
2275 }
2276 }
2277
2278 /// Process peak RSS growth over one load, with the high-water mark reset first
2279 /// (`/proc/self/clear_refs` 5). `None` when `/proc` cannot do that. The mark is per process:
2280 /// only meaningful where nothing else allocates, so it runs in [`rss_probe_child`].
2281 fn measured_peak_growth(c: &Qwen3DenseConfig, up: &RecordingDenseUploader) -> Option<u64> {
2282 std::fs::write("/proc/self/clear_refs", "5").ok()?;
2283 let before = crate::qwen3_moe_omega::current_rss_bytes()?;
2284 let (w, report) =
2285 load_qwen3_dense_omega_from(c, &mut PatternSource(c.format), up, &mut |_| {}).unwrap();
2286 drop(w);
2287 Some(report.peak_rss_bytes?.saturating_sub(before))
2288 }
2289
2290 /// One layer at the 8B widths with a 32k vocabulary (embedding 268 MB) in `format`.
2291 fn rss_config(format: DenseWeightFormat) -> Qwen3DenseConfig {
2292 let mut c =
2293 Qwen3DenseConfig::from_json(QWEN3_8B_CONFIG, Some(QWEN3_8B_GENERATION)).unwrap();
2294 c.format = format;
2295 c.layers = 1;
2296 c.vocab = 32768;
2297 c
2298 }
2299
2300 const RSS_CHILD_ENV: &str = "AIEN_OWN8B_RSS_CHILD";
2301 const RSS_CHILD_TEST: &str = "qwen3_dense_omega::tests::rss_probe_child";
2302
2303 /// The child side of [`measured_peak_growth_in_child`], ignored so it is not counted as a
2304 /// passing test; the parent runs it with `--ignored --exact`. It does nothing unless
2305 /// `AIEN_OWN8B_RSS_CHILD=<bf16|fp8>:<streaming|keeping>` is set; then it measures that one
2306 /// load and prints `OWN8B-RSS-GROWTH <bytes>` (or `skipped`). The harness prints it after the test name on
2307 /// the same line.
2308 #[test]
2309 #[ignore = "child process of the measured peak RSS gates; started by them"]
2310 fn rss_probe_child() {
2311 let Ok(case) = std::env::var(RSS_CHILD_ENV) else {
2312 return;
2313 };
2314 let (format, keep) = case.split_once(':').expect("case is <format>:<uploader>");
2315 let format = match format {
2316 "bf16" => DenseWeightFormat::Bf16,
2317 "fp8" => DenseWeightFormat::Fp8Block128,
2318 other => panic!("unknown format {other}"),
2319 };
2320 let up = match keep {
2321 "streaming" => RecordingDenseUploader::record_only(),
2322 "keeping" => RecordingDenseUploader::keeping(),
2323 other => panic!("unknown uploader {other}"),
2324 };
2325 match measured_peak_growth(&rss_config(format), &up) {
2326 Some(g) => println!("OWN8B-RSS-GROWTH {g}"),
2327 None => println!("OWN8B-RSS-GROWTH skipped"),
2328 }
2329 }
2330
2331 /// [`measured_peak_growth`] in a child process (this test binary re-run on
2332 /// [`rss_probe_child`] alone), so the high-water mark counts this one load and no other test
2333 /// thread. `None` when the child could not reset the mark.
2334 fn measured_peak_growth_in_child(case: &str) -> Option<u64> {
2335 let out = std::process::Command::new(std::env::current_exe().unwrap())
2336 .args([
2337 RSS_CHILD_TEST,
2338 "--ignored",
2339 "--exact",
2340 "--nocapture",
2341 "--test-threads=1",
2342 ])
2343 .env(RSS_CHILD_ENV, case)
2344 .output()
2345 .unwrap();
2346 let stdout = String::from_utf8_lossy(&out.stdout);
2347 assert!(
2348 out.status.success(),
2349 "RSS child {case} failed:\n{stdout}\n{}",
2350 String::from_utf8_lossy(&out.stderr)
2351 );
2352 let value = stdout
2353 .lines()
2354 .find_map(|l| l.split_once("OWN8B-RSS-GROWTH ").map(|(_, v)| v.trim()))
2355 .unwrap_or_else(|| panic!("RSS child {case} printed no measurement:\n{stdout}"));
2356 (value != "skipped").then(|| value.parse().unwrap())
2357 }
2358
2359 /// The memory gate measured, not just computed: one layer at the 8B widths with a 32k
2360 /// vocabulary must raise the peak RSS by at most the embedding plus the loader's buffers
2361 /// plus 128 MB slack. Control: the same load through the keeping uploader (a full host copy
2362 /// of the model, as an f32 or bf16 image would be) must break the same bound, so the check
2363 /// cannot pass vacuously. Each load is measured in its own child process.
2364 fn assert_peak_rss_bound(format: DenseWeightFormat, name: &str) {
2365 let c = rss_config(format);
2366 let bound = (c.embed_host_bytes() + dense_loader_transient_bytes(&c) + (128 << 20)) as u64;
2367 let Some(streaming) = measured_peak_growth_in_child(&format!("{name}:streaming")) else {
2368 // A CI runner is a plain Linux VM: the gate must run there, never skip silently.
2369 assert!(
2370 std::env::var_os("CI").is_none(),
2371 "no /proc/self/clear_refs under CI: the measured peak RSS gate cannot run"
2372 );
2373 println!("no /proc/self/clear_refs: measured peak RSS check skipped");
2374 return;
2375 };
2376 assert!(
2377 streaming <= bound,
2378 "{name} streaming load grew peak RSS by {streaming}, bound {bound}"
2379 );
2380 let keeping = measured_peak_growth_in_child(&format!("{name}:keeping")).unwrap();
2381 assert!(
2382 keeping > bound,
2383 "control: a full {name} host copy grew peak RSS by only {keeping}, bound {bound}"
2384 );
2385 }
2386
2387 #[test]
2388 fn measured_peak_rss_is_the_embedding_plus_one_buffer() {
2389 assert_peak_rss_bound(DenseWeightFormat::Bf16, "bf16");
2390 }
2391
2392 /// The same gate at FP8: the loader's buffer is the bf16 lm_head (268 MB at this vocab, 1.24
2393 /// GB at the 8B), the e4m3 projections fit inside it.
2394 #[test]
2395 fn measured_peak_rss_at_fp8_widths() {
2396 let c = rss_config(DenseWeightFormat::Fp8Block128);
2397 assert_eq!(
2398 dense_loader_transient_bytes(&c),
2399 2 * 32768 * 4096 + 2 * (24576 / 128) * (4096 / 128)
2400 );
2401 assert_peak_rss_bound(DenseWeightFormat::Fp8Block128, "fp8");
2402 }
2403
2404 /// The tiny model through the shard files: the loader's values equal
2405 /// `TransformerWeights::load_from_safetensors` (the f32 reference loader) bit for bit.
2406 #[test]
2407 fn loader_equals_transformer_weights_on_the_tiny_model() {
2408 let c = tiny_config();
2409 let dir = scratch("parity");
2410 let _ = std::fs::remove_dir_all(&dir);
2411 write_checkpoint(&dir, &c).unwrap();
2412 let up = RecordingDenseUploader::keeping();
2413 let (w, _) = load_qwen3_dense_omega(&dir, &up, &mut |_| {}).unwrap();
2414 assert_eq!(w.config, c);
2415 let mc = crate::model_dir::load_model_config(&dir).unwrap();
2416 let tw = crate::weights::TransformerWeights::load_from_safetensors(
2417 dir.join("model.safetensors.index.json"),
2418 &mc,
2419 )
2420 .unwrap();
2421 std::fs::remove_dir_all(&dir).unwrap();
2422
2423 let wide = |m: &HostGemv| -> Vec<f32> { m.bits.iter().map(|&b| bf16_to_f32(b)).collect() };
2424 let cat = |parts: &[&[f32]]| -> Vec<f32> { parts.concat() };
2425 let bits = |v: &[f32]| -> Vec<u32> { v.iter().map(|x| x.to_bits()).collect() };
2426 let recs = up.records.lock().unwrap();
2427 let embed: Vec<f32> = w.embed_bf16.iter().map(|&b| bf16_to_f32(b)).collect();
2428 assert_eq!(bits(&embed), bits(&tw.embed_tokens));
2429 for (l, (dl, tl)) in w.layers.iter().zip(&tw.layers).enumerate() {
2430 let m = |j: usize| recs[4 * l + j].matrix.as_ref().unwrap();
2431 assert_eq!(
2432 bits(&wide(m(0))),
2433 bits(&cat(&[&tl.q_proj, &tl.k_proj, &tl.v_proj]))
2434 );
2435 assert_eq!(bits(&wide(m(1))), bits(&tl.o_proj));
2436 assert_eq!(bits(&wide(m(2))), bits(&cat(&[&tl.gate_proj, &tl.up_proj])));
2437 assert_eq!(bits(&wide(m(3))), bits(&tl.down_proj));
2438 assert_eq!(bits(&dl.input_norm), bits(&tl.input_layernorm));
2439 assert_eq!(bits(&dl.post_norm), bits(&tl.post_attention_layernorm));
2440 assert_eq!(bits(&dl.q_norm), bits(tl.q_norm.as_ref().unwrap()));
2441 assert_eq!(bits(&dl.k_norm), bits(tl.k_norm.as_ref().unwrap()));
2442 }
2443 assert_eq!(bits(&w.final_norm), bits(&tw.final_norm));
2444 let head = recs.last().unwrap().matrix.as_ref().unwrap();
2445 assert_eq!(bits(&wide(head)), bits(tw.lm_head.as_ref().unwrap()));
2446
2447 // The fused GEMV gives the three separate projections' rows.
2448 let x: Vec<f32> = (0..c.hidden).map(prand_x).collect();
2449 let mut y = vec![0f32; c.qkv_n()];
2450 w.layers[0].qkv.gemv_f32(&x, &mut y).unwrap();
2451 let kv0 = c.q_dim();
2452 let k_bits: Vec<u16> = tw.layers[0].k_proj[..c.hidden]
2453 .iter()
2454 .copied()
2455 .map(f32_to_bf16)
2456 .collect();
2457 // The stored row is bf16-exact (checked above), so the kernel row of those bits is the
2458 // fused qkv output. A column-order sum is a different f32 value.
2459 assert_eq!(y[kv0].to_bits(), bf16_kernel_row(&k_bits, &x).to_bits());
2460 }
2461
2462 fn prand_x(j: usize) -> f32 {
2463 crate::qwen3_moe_omega::test_support::prand(77, j)
2464 }
2465
2466 /// The feature-gated door other crates use: the same tiny model from memory and from disk.
2467 #[cfg(feature = "host-test-engine")]
2468 #[test]
2469 fn host_test_model_loads_from_memory_and_from_disk() {
2470 let (mem, _) = super::host_test_model::load().unwrap();
2471 let dir = scratch("host-test-model");
2472 let _ = std::fs::remove_dir_all(&dir);
2473 super::host_test_model::write(&dir).unwrap();
2474 let (disk, _) =
2475 load_qwen3_dense_omega(&dir, &RecordingDenseUploader::keeping(), &mut |_| {}).unwrap();
2476 std::fs::remove_dir_all(&dir).unwrap();
2477 assert_eq!(mem.config, super::host_test_model::config());
2478 assert_eq!(disk.config, mem.config);
2479 assert_eq!(disk.embed_bf16, mem.embed_bf16);
2480 let x: Vec<f32> = (0..mem.config.hidden).map(prand_x).collect();
2481 let (mut a, mut b) = (vec![0f32; mem.config.vocab], vec![0f32; mem.config.vocab]);
2482 mem.lm_head.gemv_f32(&x, &mut a).unwrap();
2483 disk.lm_head.gemv_f32(&x, &mut b).unwrap();
2484 assert_eq!(a, b);
2485 }
2486
2487 /// The real Qwen3-8B through the streaming loader and the record-only fake (host memory
2488 /// only, no chip): per-tensor bytes, total, peak RSS, wall time. Run with
2489 /// `cargo test -p aien-inference-abi --lib qwen3_dense_omega::tests::real_qwen3_8b -- --ignored --nocapture --test-threads=1`
2490 /// (`AIEN_QWEN3_8B_DIR` overrides `~/models/qwen3-8b`).
2491 #[test]
2492 #[ignore = "reads the 16 GB Qwen3-8B checkpoint"]
2493 fn real_qwen3_8b_streaming_load_host_only() {
2494 let dir = std::env::var_os("AIEN_QWEN3_8B_DIR")
2495 .map(std::path::PathBuf::from)
2496 .unwrap_or_else(|| std::path::Path::new(env!("HOME")).join("models/qwen3-8b"));
2497 real_streaming_load(&dir, DenseWeightFormat::Bf16, 2 * 7_568_097_280);
2498 }
2499
2500 /// One real-checkpoint load through the record-only uploader, its numbers printed as
2501 /// `OWN8B-LOAD` lines and held to the design's byte count, upload count and memory bound.
2502 fn real_streaming_load(dir: &std::path::Path, format: DenseWeightFormat, resident: usize) {
2503 let rss_before = crate::qwen3_moe_omega::current_rss_bytes().unwrap();
2504 let up = RecordingDenseUploader::record_only();
2505 let (w, report) = load_qwen3_dense_omega(dir, &up, &mut |_| {}).unwrap();
2506 let c = &w.config;
2507 assert_eq!(c.format, format);
2508 let recs = up.records.lock().unwrap();
2509 let mut per: Vec<(DenseTensor, usize, usize, usize, usize)> = Vec::new();
2510 for r in recs.iter() {
2511 match per.iter_mut().find(|p| p.0 == r.what) {
2512 Some(p) => {
2513 p.3 += 1;
2514 p.4 += r.bytes;
2515 }
2516 None => per.push((r.what, r.n, r.k, 1, r.bytes)),
2517 }
2518 }
2519 for (what, n, k, count, bytes) in &per {
2520 println!(
2521 "OWN8B-LOAD {format:?} tensor {:<8} [{n}][{k}] bytes_each={} count={count} bytes_total={bytes}",
2522 what.name(),
2523 c.matrix_bytes(*what, *n, *k)
2524 );
2525 }
2526 let peak = report.peak_rss_bytes.unwrap();
2527 println!(
2528 "OWN8B-LOAD {format:?} resident_bytes={} model_resident_bytes={} uploads={} host_bytes={} \
2529 embed_bytes={} transient_bytes={} rss_before={rss_before} peak_rss_before={} \
2530 peak_rss={peak} peak_over_start={} seconds={:.2}",
2531 report.resident_bytes,
2532 c.model_resident_bytes(),
2533 report.uploads,
2534 report.host_bytes,
2535 c.embed_host_bytes(),
2536 report.transient_bytes,
2537 report.peak_rss_before_bytes.unwrap(),
2538 peak - rss_before,
2539 report.seconds
2540 );
2541 assert_eq!(report.resident_bytes, resident);
2542 assert_eq!(report.resident_bytes, c.model_resident_bytes());
2543 assert_eq!(report.uploads, 4 * 36 + 1);
2544 assert!(
2545 (peak - rss_before) as usize <= c.embed_host_bytes() + 2_000_000_000,
2546 "peak RSS grew {} bytes, limit is the embedding plus 2 GB",
2547 peak - rss_before
2548 );
2549 }
2550
2551 // -----------------------------------------------------------------------------------------
2552 // Stage 1b: the FP8 branch.
2553 // -----------------------------------------------------------------------------------------
2554
2555 /// `~/models/qwen3-8b-fp8/config.json` (Qwen/Qwen3-8B-FP8 at 220b46e3), verbatim values.
2556 const QWEN3_8B_FP8_CONFIG: &str = r#"{
2557 "architectures": ["Qwen3ForCausalLM"], "attention_bias": false, "attention_dropout": 0.0,
2558 "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": 128, "hidden_act": "silu",
2559 "hidden_size": 4096, "initializer_range": 0.02, "intermediate_size": 12288,
2560 "max_position_embeddings": 40960, "max_window_layers": 36, "model_type": "qwen3",
2561 "num_attention_heads": 32, "num_hidden_layers": 36, "num_key_value_heads": 8,
2562 "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sliding_window": null,
2563 "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.51.0",
2564 "use_cache": true, "use_sliding_window": false, "vocab_size": 151936,
2565 "quantization_config": {"activation_scheme": "dynamic", "fmt": "e4m3", "quant_method": "fp8",
2566 "weight_block_size": [128, 128]}
2567}"#;
2568
2569 /// The FP8 config with `quantization_config` replaced (`null` removes the key).
2570 fn quant_variant(q: serde_json::Value) -> Result<Qwen3DenseConfig, String> {
2571 let mut v: serde_json::Value = serde_json::from_str(QWEN3_8B_FP8_CONFIG).unwrap();
2572 if q.is_null() {
2573 v.as_object_mut().unwrap().remove("quantization_config");
2574 } else {
2575 v["quantization_config"] = q;
2576 }
2577 Qwen3DenseConfig::from_json(&v.to_string(), Some(QWEN3_8B_GENERATION))
2578 }
2579
2580 #[test]
2581 fn reads_the_qwen3_8b_fp8_config() {
2582 let c =
2583 Qwen3DenseConfig::from_json(QWEN3_8B_FP8_CONFIG, Some(QWEN3_8B_GENERATION)).unwrap();
2584 assert_eq!(c.format, DenseWeightFormat::Fp8Block128);
2585 let bf16 = Qwen3DenseConfig::from_json(QWEN3_8B_CONFIG, Some(QWEN3_8B_GENERATION)).unwrap();
2586 assert_eq!(bf16.format, DenseWeightFormat::Bf16);
2587 assert_eq!(
2588 c,
2589 Qwen3DenseConfig {
2590 format: DenseWeightFormat::Fp8Block128,
2591 ..bf16
2592 }
2593 );
2594 // Design section 0.1: e4m3 weights 6,945,767,424 bytes, scales 847,872 (bf16), lm_head
2595 // bf16 1,244,659,712; per layer 192,937,984 + 23,552.
2596 assert_eq!(c.layer_resident_bytes(), 192_937_984 + 2 * 11_776);
2597 assert_eq!(
2598 c.model_resident_bytes(),
2599 6_945_767_424 + 847_872 + 1_244_659_712
2600 );
2601 // The loader's buffer is still the bf16 lm_head; the scale buffer is gate|up's grid.
2602 assert_eq!(
2603 dense_loader_transient_bytes(&c),
2604 2 * 151936 * 4096 + 2 * 192 * 32
2605 );
2606 // The bf16 engines' strict reader keeps refusing the FP8 checkpoint by name.
2607 let e = crate::model_dir::model_config_from_hf_json("x", QWEN3_8B_FP8_CONFIG, None)
2608 .unwrap_err();
2609 assert!(e.contains("quantization_config"), "{e}");
2610 let real = std::path::Path::new(env!("HOME")).join("models/qwen3-8b-fp8");
2611 if real.join("config.json").exists() {
2612 assert_eq!(Qwen3DenseConfig::from_checkpoint(&real).unwrap(), c);
2613 }
2614 }
2615
2616 #[test]
2617 fn quantization_config_absent_null_or_exact_fp8() {
2618 assert_eq!(
2619 quant_variant(serde_json::Value::Null).unwrap().format,
2620 DenseWeightFormat::Bf16
2621 );
2622 let mut v: serde_json::Value = serde_json::from_str(QWEN3_8B_FP8_CONFIG).unwrap();
2623 v["quantization_config"] = serde_json::Value::Null;
2624 let c = Qwen3DenseConfig::from_json(&v.to_string(), None).unwrap();
2625 assert_eq!(c.format, DenseWeightFormat::Bf16);
2626 // Entries that cannot match a projection name are accepted (lm_head, the embedding and the
2627 // norms are bf16 anyway).
2628 let c = quant_variant(
2629 serde_json::json!({"activation_scheme": "dynamic", "fmt": "e4m3",
2630 "quant_method": "fp8", "weight_block_size": [128, 128],
2631 "modules_to_not_convert": ["lm_head", "model.layers.0.input_layernorm",
2632 "model.norm", "model.embed_tokens"]}),
2633 )
2634 .unwrap();
2635 assert_eq!(c.format, DenseWeightFormat::Fp8Block128);
2636 }
2637
2638 #[test]
2639 fn refuses_foreign_quantization_configs_by_name() {
2640 let fp8 = |key: &str, value: serde_json::Value| {
2641 let mut q = serde_json::json!({"activation_scheme": "dynamic", "fmt": "e4m3",
2642 "quant_method": "fp8", "weight_block_size": [128, 128]});
2643 if value.is_null() {
2644 q.as_object_mut().unwrap().remove(key);
2645 } else {
2646 q[key] = value;
2647 }
2648 quant_variant(q)
2649 };
2650 refused(
2651 fp8("weight_block_size", serde_json::json!([64, 64])),
2652 "weight_block_size",
2653 );
2654 refused(
2655 fp8("weight_block_size", serde_json::Value::Null),
2656 "weight_block_size absent",
2657 );
2658 refused(fp8("fmt", "e5m2".into()), "fmt");
2659 refused(
2660 fp8("activation_scheme", "static".into()),
2661 "activation_scheme",
2662 );
2663 refused(
2664 fp8(
2665 "modules_to_not_convert",
2666 serde_json::json!(["lm_head", "model.layers.3.mlp.down_proj"]),
2667 ),
2668 "modules_to_not_convert names \"model.layers.3.mlp.down_proj\"",
2669 );
2670 refused(
2671 fp8("modules_to_not_convert", "lm_head".into()),
2672 "not a list",
2673 );
2674 // Hugging Face skips a module when an entry is a substring of its name, so a layer or
2675 // block prefix (the 30B's list really has "model.layers.0.mlp.gate") leaves projections
2676 // unconverted: refused at config, not only at load.
2677 for prefix in [
2678 "model.layers.0.mlp.gate",
2679 "model.layers.3.mlp",
2680 "model.layers.3",
2681 "self_attn",
2682 "",
2683 ] {
2684 refused(
2685 fp8("modules_to_not_convert", serde_json::json!([prefix])),
2686 &format!("modules_to_not_convert names \"{prefix}\""),
2687 );
2688 }
2689 refused(
2690 fp8("modules_to_not_convert", serde_json::json!([3])),
2691 "modules_to_not_convert names 3",
2692 );
2693 refused(
2694 fp8("ignored_layers", serde_json::json!([])),
2695 "ignored_layers",
2696 );
2697 // int4 recipes are refused for their method.
2698 refused(
2699 quant_variant(
2700 serde_json::json!({"quant_method": "gptq", "bits": 4, "group_size": 128}),
2701 ),
2702 "quant_method \"gptq\": only",
2703 );
2704 refused(
2705 quant_variant(serde_json::json!({"quant_method": "awq", "bits": 4})),
2706 "quant_method \"awq\"",
2707 );
2708 refused(quant_variant("fp8".into()), "is not an object");
2709 }
2710
2711 #[test]
2712 fn fp8_shape_rules() {
2713 // head_dim 64 with 3 kv heads: kv_dim 192 is not a whole number of scale rows.
2714 let mut c = tiny_fp8_config();
2715 c.head_dim = 64;
2716 c.q_heads = 6;
2717 c.kv_heads = 3;
2718 refused(c.validate().map(|_| c.clone()), "kv_dim 192");
2719 // k past the FP8 GEMV's 32768 (aien_omega_fp8::MAX_K).
2720 let mut c = tiny_fp8_config();
2721 c.intermediate = aien_omega_fp8::MAX_K + 128;
2722 refused(c.validate().map(|_| c.clone()), "down [256][32896]");
2723 // The bf16 rule (k a multiple of 256) does not apply to an FP8 projection: k 384 is fine
2724 // for down, but the bf16 lm_head (k = hidden) keeps its rule.
2725 let mut c = tiny_fp8_config();
2726 c.intermediate = 384;
2727 c.validate().unwrap();
2728 c.hidden = 384;
2729 refused(c.validate().map(|_| c.clone()), "lm_head");
2730 }
2731
2732 fn load_tiny_fp8(
2733 up: &RecordingDenseUploader,
2734 ) -> Result<(Qwen3DenseOmegaWeights, DenseLoadReport), String> {
2735 let c = tiny_fp8_config();
2736 load_qwen3_dense_omega_from(&c, &mut memory_source(&c), up, &mut |_| {})
2737 }
2738
2739 #[test]
2740 fn tiny_fp8_load_shapes_byte_counts_and_order() {
2741 let c = tiny_fp8_config();
2742 let up = RecordingDenseUploader::keeping();
2743 let (w, report) = load_tiny_fp8(&up).unwrap();
2744 let recs = up.records.lock().unwrap();
2745 let got: Vec<_> = recs
2746 .iter()
2747 .map(|r| (r.layer, r.what, r.n, r.k, r.bytes, r.fp8.is_some()))
2748 .collect();
2749 let mut want = Vec::new();
2750 for l in 0..c.layers {
2751 let l = Some(l);
2752 want.push((l, DenseTensor::Qkv, 1024, 256, 1024 * 256 + 2 * 8 * 2, true));
2753 want.push((l, DenseTensor::O, 256, 512, 256 * 512 + 2 * 2 * 4, true));
2754 want.push((
2755 l,
2756 DenseTensor::GateUp,
2757 1024,
2758 256,
2759 1024 * 256 + 2 * 8 * 2,
2760 true,
2761 ));
2762 want.push((l, DenseTensor::Down, 256, 512, 256 * 512 + 2 * 2 * 4, true));
2763 }
2764 want.push((None, DenseTensor::LmHead, 64, 256, 2 * 64 * 256, false));
2765 assert_eq!(got, want);
2766 assert_eq!(report.uploads, want.len());
2767 assert_eq!(report.resident_bytes, c.model_resident_bytes());
2768 assert_eq!(
2769 report.resident_bytes,
2770 want.iter().map(|w| w.4).sum::<usize>()
2771 );
2772 assert_eq!(report.transient_bytes, dense_loader_transient_bytes(&c));
2773 assert_eq!(w.embed_bf16.len(), c.vocab * c.hidden);
2774 }
2775
2776 #[test]
2777 fn fp8_byte_test_passes_and_stacks_bytes_and_scale_rows() {
2778 let c = tiny_fp8_config();
2779 let up = RecordingDenseUploader::keeping();
2780 load_tiny_fp8(&up).unwrap();
2781 let recs = up.records.lock().unwrap();
2782 check_upload_bytes(&c, &mut memory_source(&c), &recs).unwrap();
2783
2784 // By hand, layer 1: the first row and first scale row of each stacked part.
2785 let src = memory_source(&c);
2786 let (h, qd, kvd, i, kb) = (c.hidden, c.q_dim(), c.kv_dim(), c.intermediate, 2);
2787 let scale_row0 = |name: &str| -> Vec<u16> {
2788 src.tensors[&format!("{name}_scale_inv")].2[..2 * kb]
2789 .chunks_exact(2)
2790 .map(|b| u16::from_le_bytes([b[0], b[1]]))
2791 .collect()
2792 };
2793 let p = |n: &str| format!("model.layers.1.{n}.weight");
2794 let qkv = recs[4].fp8.as_ref().unwrap();
2795 for (name, row) in [
2796 (p("self_attn.q_proj"), 0),
2797 (p("self_attn.k_proj"), qd),
2798 (p("self_attn.v_proj"), qd + kvd),
2799 ] {
2800 assert_eq!(
2801 &qkv.weights()[row * h..(row + 1) * h],
2802 &src.tensors[&name].2[..h]
2803 );
2804 let srow = row / 128;
2805 assert_eq!(&qkv.scales()[srow * kb..(srow + 1) * kb], scale_row0(&name));
2806 }
2807 let gu = recs[6].fp8.as_ref().unwrap();
2808 assert_eq!(
2809 &gu.weights()[i * h..(i + 1) * h],
2810 &src.tensors[&p("mlp.up_proj")].2[..h]
2811 );
2812 assert_eq!(
2813 &gu.scales()[(i / 128) * kb..(i / 128 + 1) * kb],
2814 scale_row0(&p("mlp.up_proj"))
2815 );
2816 }
2817
2818 fn byte_test_error(up: RecordingDenseUploader) -> String {
2819 let c = tiny_fp8_config();
2820 load_tiny_fp8(&up).unwrap();
2821 check_upload_bytes(&c, &mut memory_source(&c), &up.records.lock().unwrap())
2822 .expect_err("a wrong upload must fail the byte test")
2823 }
2824
2825 /// Negative controls: k and v rows exchanged (bytes and scales), gate and up exchanged, only
2826 /// the k and v scale rows exchanged, and every scale grid transposed must each fail the FP8
2827 /// byte test, naming the first wrong row.
2828 #[test]
2829 fn negative_controls_fail_the_fp8_byte_test() {
2830 let c = tiny_fp8_config();
2831 let e = byte_test_error(RecordingDenseUploader::swapping_kv(&c));
2832 assert!(
2833 e.contains(
2834 "upload Some(0) q|k|v: row 512 is not model.layers.0.self_attn.k_proj.weight row 0"
2835 ),
2836 "{e}"
2837 );
2838 let e = byte_test_error(RecordingDenseUploader::swapping_gate_up(&c));
2839 assert!(
2840 e.contains(
2841 "upload Some(0) gate|up: row 0 is not model.layers.0.mlp.gate_proj.weight row 0"
2842 ),
2843 "{e}"
2844 );
2845 let e = byte_test_error(RecordingDenseUploader::swapping_kv_scales(&c));
2846 assert!(
2847 e.contains("upload Some(0) q|k|v: scale row 4 is not model.layers.0.self_attn.k_proj.weight_scale_inv row 0"),
2848 "{e}"
2849 );
2850 let e = byte_test_error(RecordingDenseUploader::transposing_scales());
2851 assert!(
2852 e.contains("upload Some(0) q|k|v: scale row 0 is not model.layers.0.self_attn.q_proj.weight_scale_inv row 0"),
2853 "{e}"
2854 );
2855 }
2856
2857 fn load_fp8_err(edit: impl FnOnce(&mut MemorySource)) -> String {
2858 let c = tiny_fp8_config();
2859 let mut src = memory_source(&c);
2860 edit(&mut src);
2861 load_qwen3_dense_omega_from(
2862 &c,
2863 &mut src,
2864 &RecordingDenseUploader::keeping(),
2865 &mut |_| {},
2866 )
2867 .unwrap_err()
2868 }
2869
2870 /// The header decides per tensor: an FP8 weight without `weight_scale_inv`, a bf16
2871 /// projection in an FP8 checkpoint, an FP8 lm_head, a transposed scale grid in the file, an
2872 /// e4m3 NaN code and a NaN scale are each refused by name.
2873 #[test]
2874 fn fp8_per_tensor_dtype_rule_and_refusals() {
2875 let v = "model.layers.1.self_attn.v_proj.weight";
2876 let e = load_fp8_err(|s| {
2877 s.tensors.remove(&format!("{v}_scale_inv"));
2878 });
2879 assert!(
2880 e.contains(&format!("{v}: F8_E4M3 without {v}_scale_inv: refused")),
2881 "{e}"
2882 );
2883
2884 let e = load_fp8_err(|s| {
2885 let t = s.tensors.get_mut(v).unwrap();
2886 let words: Vec<u8> = t.2.iter().flat_map(|_| [0x80u8, 0x3c]).collect();
2887 *t = ("BF16".into(), t.1.clone(), words);
2888 });
2889 assert!(
2890 e.contains(&format!("{v}: BF16 projection in an FP8 checkpoint")),
2891 "{e}"
2892 );
2893
2894 let e = load_fp8_err(|s| {
2895 let t = s.tensors.get_mut("lm_head.weight").unwrap();
2896 let bytes = vec![0x38u8; t.2.len() / 2];
2897 *t = ("F8_E4M3".into(), t.1.clone(), bytes);
2898 });
2899 assert!(e.contains("lm_head.weight: F8_E4M3"), "{e}");
2900
2901 // The scale grid stored [k/128][n/128] in the file: refused by the shape check.
2902 let o = "model.layers.0.self_attn.o_proj.weight_scale_inv";
2903 let e = load_fp8_err(|s| {
2904 let t = s.tensors.get_mut(o).unwrap();
2905 t.1 = vec![t.1[1], t.1[0]];
2906 });
2907 assert!(e.contains(o) && e.contains("[4, 2]"), "{e}");
2908
2909 let e = load_fp8_err(|s| {
2910 s.tensors
2911 .get_mut("model.layers.1.mlp.up_proj.weight")
2912 .unwrap()
2913 .2[17] = 0xff;
2914 });
2915 assert!(
2916 e.contains("layer 1 gate|up") && e.contains("e4m3 NaN code"),
2917 "{e}"
2918 );
2919
2920 let e = load_fp8_err(|s| {
2921 let t = s
2922 .tensors
2923 .get_mut("model.layers.0.mlp.down_proj.weight_scale_inv")
2924 .unwrap();
2925 t.2[2..4].copy_from_slice(&0x7fc0u16.to_le_bytes());
2926 });
2927 assert!(
2928 e.contains("layer 0 down") && e.contains("scale 1 is NaN"),
2929 "{e}"
2930 );
2931
2932 // A bf16 checkpoint (no quantization_config) holding FP8 tensors is refused too.
2933 let c = tiny_config();
2934 let mut src = memory_source_of(tensors(&tiny_fp8_config()));
2935 let e = load_qwen3_dense_omega_from(
2936 &c,
2937 &mut src,
2938 &RecordingDenseUploader::keeping(),
2939 &mut |_| {},
2940 )
2941 .unwrap_err();
2942 assert!(e.contains("q_proj.weight") && e.contains("F8_E4M3"), "{e}");
2943 }
2944
2945 /// An uploader without an FP8 path refuses, named with the tensor.
2946 #[test]
2947 fn bf16_only_uploader_refuses_an_fp8_load() {
2948 struct Bf16Only;
2949 impl DenseUploader for Bf16Only {
2950 fn upload_bf16(
2951 &self,
2952 _: Option<usize>,
2953 _: DenseTensor,
2954 n: usize,
2955 k: usize,
2956 _: &[u16],
2957 ) -> Result<Arc<dyn DenseGemv>, String> {
2958 Ok(Arc::new(RecordedShape { n, k }))
2959 }
2960 }
2961 let c = tiny_fp8_config();
2962 let e = load_qwen3_dense_omega_from(&c, &mut memory_source(&c), &Bf16Only, &mut |_| {})
2963 .unwrap_err();
2964 assert!(
2965 e.contains("layer 0 q|k|v [1024][256] upload: this uploader has no FP8 path"),
2966 "{e}"
2967 );
2968 }
2969
2970 /// The host reference's formula, element by element: with a one-hot `x` every output is a
2971 /// single product, so `y[r]` must be `e4m3(w[r][c]) * scale[r/128][c/128]` exactly (exact
2972 /// variant) and that product rounded to bf16 (dequantised variant). A scale indexed by the
2973 /// wrong block fails here.
2974 #[test]
2975 fn host_fp8_gemv_is_the_block_scaled_formula() {
2976 let up = RecordingDenseUploader::keeping();
2977 load_tiny_fp8(&up).unwrap();
2978 let recs = up.records.lock().unwrap();
2979 let lut = crate::qwen3_moe::fp8_table();
2980 for rec in recs.iter().filter(|r| r.fp8.is_some()).take(4) {
2981 let m = rec.fp8.as_ref().unwrap();
2982 let (n, k) = (m.n(), m.k());
2983 let deq =
2984 HostFp8Gemv::dequantised_bf16(n, k, m.weights().to_vec(), m.scales().to_vec())
2985 .unwrap();
2986 for col in [0, 127, 128, k - 1] {
2987 let mut x = vec![0f32; k];
2988 x[col] = 1.0;
2989 let (mut y, mut yd) = (vec![0f32; n], vec![0f32; n]);
2990 m.gemv_f32(&x, &mut y).unwrap();
2991 deq.gemv_f32(&x, &mut yd).unwrap();
2992 for r in 0..n {
2993 let s = bf16_to_f32(m.scales()[(r / 128) * (k / 128) + col / 128]);
2994 let want = lut[m.weights()[r * k + col] as usize] * s;
2995 // Value equality: the zero terms of the sum make a -0.0 product +0.0.
2996 assert_eq!(y[r], want, "{:?} r{r} c{col}", rec.what);
2997 assert_eq!(
2998 yd[r],
2999 bf16_to_f32(f32_to_bf16(want)),
3000 "{:?} r{r} c{col} dequantised",
3001 rec.what
3002 );
3003 }
3004 }
3005 }
3006 // The scales differ between blocks, so the formula check above has teeth.
3007 let qkv = recs[0].fp8.as_ref().unwrap();
3008 assert_ne!(qkv.scales()[0], qkv.scales()[1]);
3009 assert_ne!(qkv.scales()[0], qkv.scales()[2]);
3010 }
3011
3012 /// Design 2.2 item 7: the same tiny model written twice, bf16 and FP8 (e4m3-exact values,
3013 /// scales exactly 1.0). The dequantised FP8 matrix uses the bf16 lane schedule and matches
3014 /// the bf16 GEMV bit for bit. The exact FP8 schedule (lane dot, then one scale) stays within
3015 /// 1e-5 relative. Embeddings and norms match. Control: the k/v-swapping uploader must differ.
3016 #[test]
3017 fn bf16_and_fp8_twins_load_to_equal_host_gemvs() {
3018 let load = |c: &Qwen3DenseConfig, name: &str, up: RecordingDenseUploader| {
3019 let dir = scratch(name);
3020 let _ = std::fs::remove_dir_all(&dir);
3021 write_checkpoint_of(&dir, c, tensors_with(c, TinyWeights::Twin)).unwrap();
3022 let (w, _) = load_qwen3_dense_omega(&dir, &up, &mut |_| {}).unwrap();
3023 std::fs::remove_dir_all(&dir).unwrap();
3024 (w, up)
3025 };
3026 let (wb, upb) = load(
3027 &tiny_config(),
3028 "twin-bf16",
3029 RecordingDenseUploader::keeping(),
3030 );
3031 let (wf, upf) = load(
3032 &tiny_fp8_config(),
3033 "twin-fp8",
3034 RecordingDenseUploader::keeping(),
3035 );
3036 assert_eq!(wb.config.format, DenseWeightFormat::Bf16);
3037 assert_eq!(wf.config.format, DenseWeightFormat::Fp8Block128);
3038 assert_eq!(wb.embed_bf16, wf.embed_bf16);
3039 assert_eq!(wb.final_norm, wf.final_norm);
3040 for (a, b) in wb.layers.iter().zip(&wf.layers) {
3041 assert_eq!(
3042 (&a.input_norm, &a.post_norm, &a.q_norm, &a.k_norm),
3043 (&b.input_norm, &b.post_norm, &b.q_norm, &b.k_norm)
3044 );
3045 }
3046 let gemv = |m: &dyn DenseGemv, seed: u64| -> Vec<u32> {
3047 let x: Vec<f32> = (0..m.k())
3048 .map(|j| crate::qwen3_moe_omega::test_support::prand(seed, j))
3049 .collect();
3050 let mut y = vec![0f32; m.n()];
3051 m.gemv_f32(&x, &mut y).unwrap();
3052 y.iter().map(|v| v.to_bits()).collect()
3053 };
3054 let (rb, rf) = (upb.records.lock().unwrap(), upf.records.lock().unwrap());
3055 assert_eq!(rb.len(), rf.len());
3056 let mut compared = 0;
3057 for (b, f) in rb.iter().zip(rf.iter()) {
3058 assert_eq!((b.layer, b.what, b.n, b.k), (f.layer, f.what, f.n, f.k));
3059 let hb = b.matrix.as_ref().unwrap();
3060 let other: Arc<dyn DenseGemv> = match &f.fp8 {
3061 Some(m) => {
3062 let d = HostFp8Gemv::dequantised_bf16(
3063 m.n(),
3064 m.k(),
3065 m.weights().to_vec(),
3066 m.scales().to_vec(),
3067 )
3068 .unwrap();
3069 for seed in [1, 2] {
3070 assert_eq!(gemv(&d, seed), gemv(hb.as_ref(), seed), "{:?}", f.what);
3071 }
3072 m.clone()
3073 }
3074 None => f.matrix.clone().unwrap(),
3075 };
3076 for seed in [1, 2, 3] {
3077 // Exact FP8 uses the lane-dot-then-scale schedule. With scale 1 that is within a
3078 // few ulps of the bf16 FFMA chain, not bit-identical.
3079 let (a, b) = (gemv(other.as_ref(), seed), gemv(hb.as_ref(), seed));
3080 if f.fp8.is_some() {
3081 for (x, y) in a.iter().zip(&b) {
3082 let (xf, yf) = (f32::from_bits(*x), f32::from_bits(*y));
3083 let scale = xf.abs().max(yf.abs()).max(1.0e-6);
3084 assert!(
3085 (xf - yf).abs() <= 1.0e-4 * scale,
3086 "{:?} {:?} seed {seed}: {xf} vs {yf}",
3087 f.layer,
3088 f.what
3089 );
3090 }
3091 } else {
3092 assert_eq!(a, b, "{:?} {:?} seed {seed}", f.layer, f.what);
3093 }
3094 }
3095 compared += 1;
3096 }
3097 assert_eq!(compared, 4 * 2 + 1);
3098
3099 let c = tiny_fp8_config();
3100 let (_, ups) = load(&c, "twin-fp8-swap", RecordingDenseUploader::swapping_kv(&c));
3101 let rs = ups.records.lock().unwrap();
3102 assert_ne!(
3103 gemv(rs[0].fp8.as_ref().unwrap().as_ref(), 1),
3104 gemv(rb[0].matrix.as_ref().unwrap().as_ref(), 1),
3105 "control: a k/v swap in the FP8 twin must change the q|k|v output"
3106 );
3107 }
3108
3109 /// The bf16 reference is the kernel's lane FFMA plus SHFL.DOWN, not a column-order sum.
3110 /// Lane 0 holds 1e8, lane 1 holds -1e8, lane 2 holds 1 (bf16-widened). The warp tree
3111 /// yields 0; adding the lanes in column order yields 1.
3112 #[test]
3113 fn bf16_kernel_gemv_uses_the_warp_tree_not_column_order() {
3114 let mut bits = vec![0u16; 256];
3115 let mut x = vec![0.0f32; 256];
3116 let put = |bits: &mut [u16], x: &mut [f32], lane: usize, value: f32| {
3117 bits[lane * 8] = f32_to_bf16(value);
3118 x[lane * 8] = 1.0;
3119 };
3120 put(&mut bits, &mut x, 0, 1.0e8);
3121 put(&mut bits, &mut x, 1, -1.0e8);
3122 put(&mut bits, &mut x, 2, 1.0);
3123 let mut y = [0.0f32; 1];
3124 bf16_kernel_gemv(&bits, 1, 256, &x, &mut y).unwrap();
3125 let mut sequential = 0.0f32;
3126 for c in 0..256 {
3127 sequential += bf16_to_f32(bits[c]) * x[c];
3128 }
3129 assert_eq!(y[0], 0.0, "warp tree");
3130 assert_eq!(sequential, 1.0, "column order");
3131 assert_ne!(y[0], sequential);
3132 }
3133
3134 /// FP8 reference: a lane dots its products, then multiplies by the block scale once.
3135 /// Two large products in lane 0 with a non-unit scale disagree with scaling each product.
3136 #[test]
3137 fn fp8_kernel_gemv_scales_the_lane_dot() {
3138 // k = 256 uses 8-byte lanes. Lane 0 / 1 / 2 hold +1e8, -1e8, and 1 (e4m3 1.0 times x).
3139 // The warp tree yields 0. Adding those lane dots in column order yields 1.
3140 let (n, k) = (128, 256);
3141 let mut w = vec![0u8; n * k];
3142 let mut x = vec![0.0f32; k];
3143 w[0] = 0x38;
3144 x[0] = 1.0e8;
3145 w[8] = 0xb8;
3146 x[8] = 1.0e8;
3147 w[16] = 0x38;
3148 x[16] = 1.0;
3149 let scales = vec![f32_to_bf16(1.0), f32_to_bf16(1.0)];
3150 let mut y = vec![0.0f32; n];
3151 let m = HostFp8Gemv::new(n, k, w, scales).unwrap();
3152 m.gemv_f32(&x, &mut y).unwrap();
3153 assert_eq!(y[0], 0.0);
3154 let mut sequential = 0.0f32;
3155 sequential += 1.0e8;
3156 sequential += -1.0e8;
3157 sequential += 1.0;
3158 assert_eq!(sequential, 1.0);
3159 assert_ne!(y[0], sequential);
3160 }
3161
3162 /// The real Qwen3-8B-FP8 through the FP8 branch and the record-only fake (host memory only,
3163 /// no chip; every e4m3 byte and scale is looked at for NaN): per-tensor bytes, total, peak
3164 /// RSS, wall time. Run with
3165 /// `cargo test -p aien-inference-abi --lib qwen3_dense_omega::tests::real_qwen3_8b_fp8 -- --ignored --nocapture --test-threads=1`
3166 /// (`AIEN_QWEN3_8B_FP8_DIR` overrides `~/models/qwen3-8b-fp8`).
3167 #[test]
3168 #[ignore = "reads the 9.4 GB Qwen3-8B-FP8 checkpoint"]
3169 fn real_qwen3_8b_fp8_streaming_load_host_only() {
3170 let dir = std::env::var_os("AIEN_QWEN3_8B_FP8_DIR")
3171 .map(std::path::PathBuf::from)
3172 .unwrap_or_else(|| std::path::Path::new(env!("HOME")).join("models/qwen3-8b-fp8"));
3173 real_streaming_load(
3174 &dir,
3175 DenseWeightFormat::Fp8Block128,
3176 6_945_767_424 + 847_872 + 1_244_659_712,
3177 );
3178 }
3179}