memra_engine/model.rs
1//! Dense transformer model: loads GGUF weights to GPU (Stage-1: dequant→f32), runs the
2//! shared full-attention + SwiGLU forward graph. Arch-agnostic via ModelConfig; this path is
3//! exactly the dense-transformer graph (qwen3) and the full-attention layers of hybrids.
4
5use crate::{
6 Engine, QT_BF16, QT_F8_E4M3, QT_F32, QT_IQ3_S, QT_IQ4_XS, QT_NVFP4, QT_NVFP4_RP, QT_Q2_K,
7 QT_Q3_K, QT_Q4_0, QT_Q4_K, QT_Q5_K, QT_Q6_K, QT_Q8_0,
8};
9use cudarc::driver::CudaSlice;
10use memra_gguf::config::ModelConfig;
11use memra_gguf::source::{DiskExtent, GgufSource, TensorSource};
12use memra_gguf::{GgmlType, GgufFile, dequant};
13use std::collections::HashMap;
14
15/// RESIDENCY CENSUS (lane/fp8-decode-v1, 2026-08-05) — per-qtype tally of the 2D matmul weights
16/// that actually went resident, keyed by `QT_*`. The FP8-ST decode arm's whole claim is about
17/// WHICH container the checkpoint's projections end up in, and the two candidate containers
18/// differ in bytes (e4m3 1.0 B/w vs the Q8_0 re-encode 1.0625 B/w). Before this instrument the
19/// only evidence available was end-to-end tok/s, which cannot distinguish "the arm ran and was
20/// flat" from "the arm never engaged" — the exact ambiguity in this lane's first loadprobe pair.
21/// Slot = qtype index; `.0` = tensor count, `.1` = resident bytes.
22static RESIDENCY_CENSUS: [(std::sync::atomic::AtomicUsize, std::sync::atomic::AtomicU64); 16] = {
23 #[allow(clippy::declare_interior_mutable_const)]
24 const Z: (std::sync::atomic::AtomicUsize, std::sync::atomic::AtomicU64) = (
25 std::sync::atomic::AtomicUsize::new(0),
26 std::sync::atomic::AtomicU64::new(0),
27 );
28 [Z; 16]
29};
30
31fn residency_census_note(qtype: i32, bytes: usize) {
32 use std::sync::atomic::Ordering::Relaxed;
33 if let Some(slot) = RESIDENCY_CENSUS.get(qtype as usize) {
34 slot.0.fetch_add(1, Relaxed);
35 slot.1.fetch_add(bytes as u64, Relaxed);
36 }
37}
38
39/// Human-readable residency census: one line per qtype that took at least one 2D weight, plus a
40/// total. Callers print it right after load — see `run-gen`'s `MEMRA_RESIDENCY_CENSUS=1`.
41pub fn residency_census_report() -> String {
42 use std::sync::atomic::Ordering::Relaxed;
43 let name = |q: usize| -> &'static str {
44 match q as i32 {
45 QT_Q8_0 => "Q8_0",
46 QT_Q4_K => "Q4_K",
47 QT_Q6_K => "Q6_K",
48 QT_Q5_K => "Q5_K",
49 QT_Q3_K => "Q3_K",
50 QT_IQ4_XS => "IQ4_XS",
51 QT_IQ3_S => "IQ3_S",
52 QT_NVFP4 => "NVFP4",
53 QT_F32 => "F32",
54 QT_NVFP4_RP => "NVFP4_RP",
55 QT_F8_E4M3 => "F8_E4M3",
56 QT_BF16 => "BF16",
57 QT_Q4_0 => "Q4_0",
58 QT_Q2_K => "Q2_K",
59 crate::QT_F8_E4M3_BLK => "F8_E4M3_BLK",
60 _ => "?",
61 }
62 };
63 let mut out = String::from("residency census (2D matmul weights, resident container):\n");
64 let (mut tn, mut tb) = (0usize, 0u64);
65 for (q, slot) in RESIDENCY_CENSUS.iter().enumerate() {
66 let (n, b) = (slot.0.load(Relaxed), slot.1.load(Relaxed));
67 if n == 0 {
68 continue;
69 }
70 tn += n;
71 tb += b;
72 out += &format!(
73 " {:>9}: {:>4} tensors {:>9.3} MiB\n",
74 name(q),
75 n,
76 b as f64 / (1024.0 * 1024.0)
77 );
78 }
79 out += &format!(
80 " {:>9}: {:>4} tensors {:>9.3} MiB",
81 "TOTAL",
82 tn,
83 tb as f64 / (1024.0 * 1024.0)
84 );
85 out
86}
87
88/// A weight tensor resident on GPU. Quantized weights stay in GGUF block bytes (`Quant`);
89/// small non-quant tensors (norms, sometimes embed/lm_head) are kept dequantized as f32 (`Float`).
90/// This keeps VRAM ~= on-disk quant size (fixes the f32-on-load OOM).
91pub enum GpuTensor {
92 Quant {
93 bytes: CudaSlice<u8>,
94 qtype: i32,
95 row_bytes: usize,
96 ne: Vec<u64>,
97 scale: f32,
98 /// SPLIT-PLANE walk-order repack (A6, 2026-07-04): NVFP4 matmul weights are repacked at
99 /// load into [quant plane out_f x in_f/64 x 32B][scale plane out_f x in_f/64 x 4B] — same
100 /// bytes, same total size, but a lane's per-group weight read becomes ONE 16B-aligned
101 /// LDG.128 + a dense 4B scale word instead of 5 scattered 4B LDGs at 36B stride (the "18B
102 /// straggle"). Every consumer kernel has an `_rp` twin (bit-identical: pure byte
103 /// permutation, same dot order). `rp=false` = original GGUF block layout (all other
104 /// dtypes, MoE-staged expert bytes, MEMRA_RP=0 escape).
105 rp: bool,
106 /// CUTLASS NVFP4 prefill operand (repacked B + swizzled SFB), built ALONGSIDE `bytes` at load
107 /// when MEMRA_FP4_CUTLASS is set. `bytes` stays raw GGUF so decode (MMVQ/dp4a) is untouched;
108 /// prefill (m>=128) reads this. Only ever Some for NVFP4 weights under cfg(memra_cutlass).
109 #[cfg(memra_cutlass)]
110 cutlass: Option<CutlassWeight>,
111 /// FP8-ACT PREFILL operand (MEMRA_PP_FP8=1, probe verdict 2026-07-08): the checkpoint's RAW
112 /// e4m3 bytes + per-tensor f32 weight_scale, stashed ALONGSIDE the Q8_0 re-encode for the
113 /// F8-E4M3-origin 2D projections (~1 B/w extra on those layers). `bytes` stays Q8_0 so
114 /// decode (dp4a/MMVQ) is untouched; only the m>=16 prefill dispatch (cuBLASLt FP8 TN,
115 /// fp8_ffi.rs) reads this. None unless the env is set at load (zero VRAM cost by default).
116 fp8: Option<Fp8Weight>,
117 /// Q4_0 SPLIT-PLANE MIRROR (2026-07-10, the 18B-straggle cure for decode): qs plane
118 /// [out_f x nblk x 16B] + d plane [out_f x nblk x 2B] built device-side at model load
119 /// (q4_0_split_rp_build) for decode-hot trunk weights. Raw `bytes` stay resident —
120 /// prefill (gemm/MMQ) and Stage-A read those; the m<=8 mmvq/batched/fused dispatch
121 /// reads this when present (`_rp` twins; microprobe m=1 1.34x, m=3 1.17x, bitwise).
122 /// None everywhere except where the arch-load hook opted in (VRAM cost = weight size).
123 rp4: Option<CudaSlice<u8>>,
124 /// BLOCK-128 WEIGHT-SCALE GRID for a NATIVE e4m3 resident weight (lane/fp8-blk128-decode,
125 /// 2026-08-05). `Some` iff `qtype == QT_F8_E4M3_BLK`, and then `bytes` are the checkpoint's
126 /// raw e4m3 codes ([out_f, in_f], row_bytes == in_f), `scale == 1.0`, and THIS is the only
127 /// dequant scale in the tensor — decode reads it in-kernel (`qmatvec_e4m3_blk_mmvq`),
128 /// prefill reads it in the per-block MMQ tile. Distinct from `fp8: Some(Fp8Weight { blk })`,
129 /// which is the MEMRA_PP_FP8 *stash*: a SECOND e4m3 copy carried alongside a Q8_0 slab.
130 /// Here there is one copy and `fp8` stays None.
131 blk: Option<Fp8BlockScales>,
132 /// FP16 DEQUANT MIRROR (MEMRA_PP_F16=1, probe 2026-07-26): row-major fp16 of a 2D Q8_0
133 /// projection, built device-side at load (f16_ffi::build_q8_f16). `bytes` stay Q8_0 so
134 /// decode is untouched; the m>=16 prefill dispatch (cuBLASLt FP16 TN, 611-687 TF vs
135 /// MMQ's ~200 TF class) reads this. None unless the env is set (VRAM = 2 B/w extra).
136 f16: Option<CudaSlice<u8>>,
137 },
138 Float {
139 data: CudaSlice<f32>,
140 ne: Vec<u64>,
141 },
142 /// BF16-RESIDENT full-precision matmul weight (MEMRA_FULL_PREC only). Holds the checkpoint's raw
143 /// bf16 bytes (`u8`, little-endian u16 pairs) — 2 B/w vs the 4 B/w a `Float` f32 materialization
144 /// would cost, so the 9B trunk stays ~18GB in VRAM instead of ~36GB. Consumed via dequant-on-use:
145 /// each matmul expands this to a transient f32 scratch and rides the SAME cuBLASLt f32 GEMV the
146 /// `Float` arm uses (bit-identical to a load-time bf16->f32 dequant, just deferred). Never a norm
147 /// (norms stay `Float` f32); never on a fast/GEMM/MMQ path (uses_q8_1_fast/gemm_supports = false).
148 FloatBf16 {
149 data: CudaSlice<u8>,
150 ne: Vec<u64>,
151 },
152}
153
154/// FP8-native prefill operand: raw checkpoint e4m3 codes `[out_f, in_f]` row-major (EXACT — the
155/// weight side of the FP8 GEMM does no re-quantization) + its weight scale(s). Per-tensor class:
156/// `scale` is the dequant scalar folded into the GEMM's scale pointer together with the per-batch
157/// activation scale, `blk == None`. Block-128 class (Qwen official FP8): `blk == Some` and
158/// `scale == 1.0` — see `Fp8BlockScales` for the resident layout contract.
159pub struct Fp8Weight {
160 pub bytes: CudaSlice<u8>,
161 pub scale: f32,
162 pub blk: Option<Fp8BlockScales>,
163}
164
165/// Device-resident block-128 weight-scale grid for an e4m3 operand (B1b, lane fp8st 2026-08-03).
166///
167/// STORAGE LAYOUT (the canonical device layout every future consumer builds from): a flat f32
168/// buffer in the CHECKPOINT'S on-disk order — row-major `[rows = ceil(out_f/128),
169/// cols = ceil(in_f/128)]`, so `scales[ob * cols + kb]` scales the 128x128 weight tile at
170/// output-block `ob`, input-block `kb` (uploaded verbatim from `memra_gguf::source::F8BlockGrid`,
171/// no permutation — one host decode, one htod). Rationale: (1) the per-block-dequant mmvq twin
172/// (qmatvec_e4m3_mmvq extension, DECISION.md B1) indexes `(o >> 7) * cols + (e >> 7)` — natural
173/// in this order; (2) for cuBLASLt BLK128x128 the weight `[out, in]` row-major is the TN GEMM's
174/// column-major `[k=in, n=out]` A operand, and this same linear order IS that view's column-major
175/// block grid with ld = cols(=kblk) — probe P1 (`probe/fp8_lt_blk_probe.cu`) verifies whether
176/// sm_120 accepts it directly; if Lt wants a different order, the reorder happens at the GEMM
177/// plan build, NOT here. NO KERNEL CONSUMES THIS YET: the loader keeps every block-128 tensor's
178/// decode/prefill on the Q8_0 re-encode until the consuming kernels land (try_fp8_gemm skips
179/// blk operands; the QT_F8_E4M3 one-copy arm rejects them). This struct's job is bytes+scales
180/// resident and correct.
181pub struct Fp8BlockScales {
182 pub scales: CudaSlice<f32>,
183 pub rows: usize, // ceil(out_f/128)
184 pub cols: usize, // ceil(in_f/128)
185}
186
187/// Host-side split-plane repack of NVFP4 GGUF block bytes (A6). Input: out_f rows of in_f/64
188/// 36-byte blocks ([4B UE4M3 scales][32B packed e2m1]). Output (same length): quant plane
189/// (out_f x nsb64 x 32B) followed by scale plane (out_f x nsb64 x 4B). Pure byte permutation.
190pub fn repack_nvfp4_split(bytes: &[u8], out_f: usize) -> Vec<u8> {
191 let row_bytes = bytes.len() / out_f;
192 let nsb64 = row_bytes / 36;
193 debug_assert_eq!(
194 row_bytes % 36,
195 0,
196 "NVFP4 row_bytes must be a multiple of 36"
197 );
198 let qplane = out_f * nsb64 * 32;
199 let mut rp = vec![0u8; bytes.len()];
200 for o in 0..out_f {
201 for s in 0..nsb64 {
202 let src = &bytes[o * row_bytes + s * 36..o * row_bytes + s * 36 + 36];
203 rp[qplane + (o * nsb64 + s) * 4..qplane + (o * nsb64 + s) * 4 + 4]
204 .copy_from_slice(&src[0..4]);
205 rp[(o * nsb64 + s) * 32..(o * nsb64 + s) * 32 + 32].copy_from_slice(&src[4..36]);
206 }
207 }
208 rp
209}
210
211/// Inverse of `repack_nvfp4_split` (the roundtrip gate).
212pub fn unpack_nvfp4_split(rp: &[u8], out_f: usize) -> Vec<u8> {
213 let row_bytes = rp.len() / out_f;
214 let nsb64 = row_bytes / 36;
215 let qplane = out_f * nsb64 * 32;
216 let mut back = vec![0u8; rp.len()];
217 for o in 0..out_f {
218 for s in 0..nsb64 {
219 back[o * row_bytes + s * 36..o * row_bytes + s * 36 + 4].copy_from_slice(
220 &rp[qplane + (o * nsb64 + s) * 4..qplane + (o * nsb64 + s) * 4 + 4],
221 );
222 back[o * row_bytes + s * 36 + 4..o * row_bytes + s * 36 + 36]
223 .copy_from_slice(&rp[(o * nsb64 + s) * 32..(o * nsb64 + s) * 32 + 32]);
224 }
225 }
226 back
227}
228
229/// A6 repack seam: default ON, `MEMRA_RP=0` restores the GGUF block layout everywhere (rollback/A-B).
230pub fn rp_enabled() -> bool {
231 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
232 *ON.get_or_init(|| std::env::var("MEMRA_RP").map(|v| v != "0").unwrap_or(true))
233}
234
235/// FULL-PRECISION LOADER MODE (MEMRA_FULL_PREC=1, default OFF — MTP-heal research platform).
236/// Bypasses the standing loader law (large BF16/F8 -> Q8_0/NVFP4 re-encode, the "Float-poison"
237/// tripwire). Under this flag every weight loads as Float and compute rides the Stage-A f32 oracle
238/// path end to end — SLOW IS FINE, this mode exists for exactness (the MTP acceptance CEILING at
239/// full precision), not speed. Large 2D matmul weights stay bf16-resident (`GpuTensor::FloatBf16`)
240/// with dequant-on-use so the 9B (~18GB bf16) + f32 activations fit 24GB instead of blowing to
241/// ~38GB as an all-f32 materialization. The Float-poison tripwire warnings are CORRECT behavior
242/// here and are suppressed. See docs/FLAGS.md and HANDOVER "MEMRA DUAL-SHAPE".
243pub fn full_prec_enabled() -> bool {
244 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
245 *ON.get_or_init(|| {
246 std::env::var("MEMRA_FULL_PREC")
247 .map(|v| v == "1")
248 .unwrap_or(false)
249 })
250}
251
252/// LOADER-LAW allowlist (loadersweep audit 2026-07-08): 2D Float tensors that are DELIBERATELY
253/// Float despite being matmul-class. Every entry needs an audit rationale — this list silences
254/// the tripwire below, so an unjustified entry re-opens the trap.
255/// * ffn_gate_inp (MoE router, 35B GGUF F32 [2048,256] / M3 ST F32 [6144,64]): the router's
256/// top-k SELECTION is discontinuous — quantizing shifts logits and flips expert choice (a
257/// class change, not an FP-order change). llama.cpp keeps every router F32 (its converter
258/// forces F32) so Float is bench-parity, it sits on NO all-or-nothing predicate, and the
259/// decode-exact contract is already built around its cuBLASLt path
260/// (hybrid_forward.rs moe_ffn_sequential_zq8 router comment).
261fn float_2d_audited(name: &str) -> bool {
262 name.ends_with("ffn_gate_inp.weight")
263}
264
265/// Once-per-name-pattern loader-law warning (`blk.{il}.` collapses to `blk.*.` so a 48-layer
266/// offender prints ONE line, not 48). See the call site in `load_from_source` for the law.
267fn warn_float_2d_once(name: &str, ne: &[u64], src_type: GgmlType) {
268 use std::sync::{Mutex, OnceLock};
269 static SEEN: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
270 let pat = match name.strip_prefix("blk.").and_then(|r| r.split_once('.')) {
271 Some((_, suffix)) => format!("blk.*.{suffix}"),
272 None => name.to_string(),
273 };
274 let mut seen = SEEN
275 .get_or_init(|| Mutex::new(std::collections::HashSet::new()))
276 .lock()
277 .unwrap();
278 if seen.insert(pat.clone()) {
279 eprintln!(
280 "[loader-law] WARNING: {pat} loads as 2D Float ne={ne:?} (src {src_type:?}) — \
281 a Float matmul weight rides cuBLAS f32 GEMV and poisons all-or-nothing q8-fast \
282 predicates (uses_q8_1_fast/mixer_in_q8_1_fast). If matmul-class: Q8_0-encode at \
283 load (model.rs ssm arm / source.rs BF16+F8 gates). If deliberately Float: add \
284 it to float_2d_audited with the audit rationale."
285 );
286 }
287}
288
289/// CUTLASS-layout NVFP4 weight (B operand) for the prefill FP4 GEMM. Built once at load from the raw
290/// GGUF bytes (de-interleave + SFB swizzle). Coexists with the raw `bytes` (decode reads bytes).
291#[cfg(memra_cutlass)]
292pub struct CutlassWeight {
293 /// Plain K-contiguous packed e2m1, [out_f, in_f/2] bytes.
294 pub b_packed: CudaSlice<u8>,
295 /// Swizzled SFB (CUTLASS SfAtom layout), sized via cutlass_sfb_size(out_f, in_f).
296 pub sfb_swizzled: CudaSlice<u8>,
297}
298
299impl GpuTensor {
300 pub fn ne(&self) -> &[u64] {
301 match self {
302 GpuTensor::Quant { ne, .. } => ne,
303 GpuTensor::Float { ne, .. } => ne,
304 GpuTensor::FloatBf16 { ne, .. } => ne,
305 }
306 }
307 pub fn in_features(&self) -> usize {
308 self.ne()[0] as usize
309 }
310 pub fn out_features(&self) -> usize {
311 self.ne()[1] as usize
312 }
313 /// Per-tensor post-matmul macro-scale (NVFP4 carries scale != 1.0; all others -> 1.0, a no-op).
314 /// Used by the fused SwiGLU epilogue to fold the gate/up scale into one kernel.
315 pub fn scale(&self) -> f32 {
316 match self {
317 GpuTensor::Quant { scale, .. } => *scale,
318 GpuTensor::Float { .. } | GpuTensor::FloatBf16 { .. } => 1.0,
319 }
320 }
321
322 /// Load a tensor, keeping quant types packed and float types as f32. (GGUF entry point —
323 /// thin wrapper over the source-agnostic `load_from_source`; behavior is unchanged.)
324 pub fn load(e: &Engine, g: &GgufFile, name: &str) -> Result<Self, Box<dyn std::error::Error>> {
325 Self::load_from_source(e, &GgufSource(g), name)
326 }
327
328 /// Source-agnostic load: works from any `TensorSource` (GGUF or safetensors). The engine's
329 /// forward graph only ever asks for ggml-style names; the source maps them to its own layout.
330 ///
331 /// RESIDENCY CENSUS (lane/fp8-decode-v1, 2026-08-05): the wrapper tallies what each 2D
332 /// matmul weight ACTUALLY became — resident qtype + resident bytes — so the FP8-ST decode
333 /// arm's claim ("e4m3 stays native instead of paying the Q8_0-slab tax") is a measured
334 /// per-checkpoint fact rather than an assumption about the checkpoint's dtype mix. Read it
335 /// with `residency_census_report()`; zero cost when never read.
336 pub fn load_from_source(
337 e: &Engine,
338 src: &dyn TensorSource,
339 name: &str,
340 ) -> Result<Self, Box<dyn std::error::Error>> {
341 let t = Self::load_from_source_inner(e, src, name)?;
342 if let GpuTensor::Quant {
343 qtype, bytes, ne, ..
344 } = &t
345 {
346 if ne.len() == 2 {
347 residency_census_note(*qtype, bytes.len());
348 }
349 }
350 Ok(t)
351 }
352
353 fn load_from_source_inner(
354 e: &Engine,
355 src: &dyn TensorSource,
356 name: &str,
357 ) -> Result<Self, Box<dyn std::error::Error>> {
358 // A1 DIRECT NVFP4 IMPORT (2026-07-04): a PLAIN modelopt/Reza NVFP4 weight from a
359 // safetensors source repacks straight into the A6 split-plane resident layout in ONE host
360 // pass (nvfp4_repack::repack_modelopt_to_split — the scale plane is the file's
361 // weight_scale bytes verbatim), never materializing the GGUF 36B-block intermediate.
362 // The GGUF hop remains only for MEMRA_ST_DIRECT=0 (rollback/A-B seam — byte-identical
363 // resident weights either way), MEMRA_RP=0, the hybrid V-reorder transforms, and the
364 // opt-in CUTLASS resident operand (which is built from raw GGUF-layout bytes).
365 let cutlass_wants_raw = cfg!(memra_cutlass) && std::env::var("MEMRA_FP4_CUTLASS").is_ok();
366 let st_direct = std::env::var("MEMRA_ST_DIRECT")
367 .map(|v| v != "0")
368 .unwrap_or(true);
369 if rp_enabled() && st_direct && !cutlass_wants_raw {
370 if let Some(nv) = src.find_nvfp4_native(name) {
371 if nv.in_f % 64 == 0 && nv.out_f > 0 {
372 // Same post-matmul macro-scale sibling lookup as the GGUF-layout arm below.
373 let stem = name.strip_suffix(".weight").unwrap_or(name);
374 let scale = match src.find(&format!("{stem}.scale")) {
375 Some(sv) => f32::from_le_bytes(sv.bytes[..4].try_into().unwrap()),
376 None => 1.0,
377 };
378 let bytes =
379 e.htod_bytes(&memra_gguf::nvfp4_repack::repack_modelopt_to_split(
380 nv.wbytes, nv.wscale, nv.out_f, nv.in_f,
381 ))?;
382 return Ok(GpuTensor::Quant {
383 bytes,
384 qtype: QT_NVFP4,
385 row_bytes: nv.in_f / 64 * 36,
386 ne: vec![nv.in_f as u64, nv.out_f as u64],
387 scale,
388 rp: true,
389 #[cfg(memra_cutlass)]
390 cutlass: None,
391 fp8: None,
392 blk: None,
393 f16: None,
394 rp4: None,
395 });
396 }
397 }
398 }
399 // E4M3-DIRECT (DEFAULT since lane/fp8-decode-v1 2026-08-05; MEMRA_ST_E4M3=0 rolls back to the
400 // Q8_0 slab. Introduced default-off by lane e4m3dec 2026-07-08): F8-E4M3-origin 2D projections keep
401 // the checkpoint's RAW e4m3 device bytes + per-tensor weight_scale as the ONE resident copy
402 // (QT_F8_E4M3) instead of the Q8_0 re-encode — decode dequants e4m3 in-kernel
403 // (qmatvec_e4m3_mmvq, the checkpoint's own precision, no lossy re-quant hop), prefill
404 // (m>=16) rides the cuBLASLt FP8 GEMM on the SAME bytes (try_fp8_gemm). Frees the Q8_0
405 // duplicate the MEMRA_PP_FP8 stash needed (~3.4GB on the NV-27B) — full FP8 prefill coverage
406 // with no VRAM budget. Placed BEFORE `find` so the host-side F8->Q8_0 re-encode is skipped
407 // entirely (faster load). in_f%32 is the q8_1 activation block gate (every F8 projection in
408 // the NV-27B satisfies it; a violator falls through to the Q8_0 arm unchanged).
409 // BLOCK-128 CLASS: served by its OWN qtype since lane/fp8-blk128-decode (2026-08-05) —
410 // see the second arm below. It must not enter the per-tensor arm: the QT_F8_E4M3 kernel
411 // family consumes ONE scalar weight scale, so a block-128 operand through it would
412 // silently dequant every tile at scale 1.0.
413 if crate::fp8_ffi::st_e4m3_enabled() {
414 if let Some(f8) = src.find_fp8_native(name) {
415 if f8.blk.is_none() && f8.in_f % 32 == 0 && f8.out_f > 0 {
416 return Ok(GpuTensor::Quant {
417 bytes: e.htod_bytes(&f8.bytes)?,
418 qtype: crate::QT_F8_E4M3,
419 row_bytes: f8.in_f,
420 ne: vec![f8.in_f as u64, f8.out_f as u64],
421 scale: f8.scale,
422 rp: false,
423 #[cfg(memra_cutlass)]
424 cutlass: None,
425 fp8: None,
426 blk: None,
427 f16: None,
428 rp4: None,
429 });
430 }
431 }
432 }
433 // E4M3-BLK-DIRECT (lane/fp8-blk128-decode, 2026-08-05) — the block-128 twin of the arm
434 // above, and the Qwen-3.8 day-one path. A block-128 FP8 checkpoint (Qwen3.6-FP8's
435 // `weight_block_size [128,128]`, the DeepSeek-V3 lineage) keeps its RAW e4m3 codes plus its
436 // [ceil(out/128), ceil(in/128)] f32 scale grid as the ONE resident copy (QT_F8_E4M3_BLK)
437 // instead of the ARM B' Q8_0 slab: decode dequants per k128 block in-kernel
438 // (qmatvec_e4m3_blk_mmvq — the checkpoint's own precision, no lossy re-quant hop) at
439 // 1.0 B/weight instead of 1.0625, and prefill (m>=16) rides the per-block FP8 MMQ tile on
440 // the SAME bytes+grid (try_fp8_blk_mmq) with NO stash duplicate.
441 //
442 // ORDERING / DISJOINTNESS (the decode-v1 landmine, restated for this arm): the three FP8
443 // arms are mutually exclusive by their scale class, checked in this order —
444 // 1. `blk.is_none()` -> QT_F8_E4M3 (per-tensor scalar; arm above)
445 // 2. `blk.is_some()` + native -> QT_F8_E4M3_BLK (this arm)
446 // 3. `blk.is_some()` -> ARM B' Q8_0 slab (MEMRA_FP8_BLK_GPU) / host re-encode
447 // so ARM B' KEEPS working wherever it is still the path: whenever this arm declines (env
448 // rollback, NaN codes present, ragged in_f, grid-shape mismatch) control falls through to
449 // it unchanged. It is not cross-gated on this arm's flag — a tensor this arm CLAIMS
450 // returns here and never reaches ARM B' at all, and one it declines must reach it.
451 //
452 // NaN PRECONDITION, enforced at LOAD (not asserted): the decode kernel decodes e4m3 with
453 // the HARDWARE intrinsic (magnitude 0x7F -> NaN) while the ARM B'/host reference decodes
454 // it to 0.0 (modelopt). A tensor carrying 0x7F/0xFF therefore cannot ride this kernel, so
455 // the bytes are scanned once on the device (fp8_blk_nan_count, the same precondition the
456 // prefill MMQ arm uses) and a non-zero count declines to the Q8_0 floor for THAT tensor.
457 // Real Qwen FP8 checkpoints carry none (the exporter saturates at +-448), so this is a
458 // guard, not a cost centre: one linear pass over bytes already on the device.
459 if crate::fp8_ffi::st_e4m3_blk_enabled() {
460 if let Some(f8) = src.find_fp8_native(name) {
461 if let Some(grid) = f8.blk.as_ref() {
462 let (in_f, out_f) = (f8.in_f, f8.out_f);
463 // in_f % 32: the q8_1 activation block gate (and the kernel's 2x LDG.128 line).
464 // The grid dims must match the shape — a mismatch means operand and grid came
465 // from different tensors; refuse rather than index a wrong block. scale == 1.0
466 // is the block class's identity (source.rs sets it alongside a grid); anything
467 // else would be a second, unapplied factor.
468 if in_f % 32 == 0
469 && out_f > 0
470 && f8.bytes.len() == out_f * in_f
471 && grid.rows == out_f.div_ceil(128)
472 && grid.cols == in_f.div_ceil(128)
473 && grid.scales.len() == grid.rows * grid.cols
474 && f8.scale == 1.0
475 {
476 let bytes = e.htod_bytes(&f8.bytes)?;
477 if e.fp8_blk_nan_count(&bytes)? == 0 {
478 let scales = e.htod(&grid.scales)?;
479 return Ok(GpuTensor::Quant {
480 bytes,
481 qtype: crate::QT_F8_E4M3_BLK,
482 row_bytes: in_f,
483 ne: vec![in_f as u64, out_f as u64],
484 scale: 1.0,
485 rp: false,
486 #[cfg(memra_cutlass)]
487 cutlass: None,
488 fp8: None,
489 blk: Some(Fp8BlockScales {
490 scales,
491 rows: grid.rows,
492 cols: grid.cols,
493 }),
494 f16: None,
495 rp4: None,
496 });
497 }
498 crate::fp8_ffi::note_blk_native_nan_refused();
499 }
500 }
501 }
502 }
503 // ARM B' — GPU BLOCK-128 DEQUANT (MEMRA_FP8_BLK_GPU=1, default OFF; lane fp8-gemm-arm
504 // 2026-08-03). A block-128 FP8 checkpoint (Qwen official FP8 / DeepSeek-V3 lineage)
505 // currently loads via the host path: full f32 dequant of the tensor (f8_deq_f32) then a
506 // host Q8_0 re-encode (f32_to_q8_0) — correct, but a serial CPU pass over every byte of
507 // every projection. This arm does the same math on the GPU in ONE pass
508 // (cu/fp8_blk_dequant.cu): upload the raw e4m3 codes + the scale grid, write Q8_0
509 // blocks directly. BYTE-IDENTICAL to the host path (kernel-check [fp8-blk-gpu] arm
510 // asserts it on ragged and aligned shapes), so the resident tensor, the MMQ/MMVQ
511 // dispatch, and decode are all bit-for-bit unchanged — this is a LOAD-TIME
512 // optimization only, not a numeric config change.
513 //
514 // Placed BEFORE `find` for exactly the reason the MEMRA_ST_E4M3 arm above is: `find`
515 // would otherwise do the host dequant+re-encode we are replacing. Per-tensor and
516 // per-row scale classes are NOT touched (find_fp8_native returns blk=None / None for
517 // them) and neither are V-reorder Transform targets (find_fp8_native rejects those with
518 // a grid — the permutation invalidates the on-disk grid, so they keep the host path).
519 //
520 // NO st_e4m3 EXCLUSION (lane/fp8-decode-v1 2026-08-05): this arm used to carry
521 // `&& !st_e4m3_enabled()`, written when MEMRA_ST_E4M3 was default OFF and meant only as
522 // "the native arm above already claimed this tensor". Once native residency became the
523 // DEFAULT that condition would have been true on every run and silently disabled ARM B'
524 // for the whole block-128 class — the exact silent-slow-path landmine the flags doctrine
525 // forbids. The two arms are already disjoint by construction and need no cross-gate: the
526 // arm above returns only when `f8.blk.is_none()`, this one runs only when `f8.blk` is
527 // Some, so a tensor that reaches here was never eligible for native residency.
528 if crate::fp8_ffi::fp8_blk_gpu_enabled() {
529 if let Some(f8) = src.find_fp8_native(name) {
530 if let Some(grid) = f8.blk.as_ref() {
531 let (in_f, out_f) = (f8.in_f, f8.out_f);
532 if in_f % 32 == 0 && out_f > 0 && f8.bytes.len() == out_f * in_f {
533 let bytes = e.fp8_blk_dequant_q8_0(&f8.bytes, &grid.scales, out_f, in_f)?;
534 return Ok(GpuTensor::Quant {
535 bytes,
536 qtype: QT_Q8_0,
537 row_bytes: in_f / 32 * 34,
538 ne: vec![in_f as u64, out_f as u64],
539 scale: 1.0,
540 rp: false,
541 #[cfg(memra_cutlass)]
542 cutlass: None,
543 fp8: None,
544 blk: None,
545 f16: None,
546 rp4: None,
547 });
548 }
549 }
550 }
551 }
552 let mut v = src
553 .find(name)
554 .unwrap_or_else(|| panic!("missing tensor {name}"));
555 // MEMRA_KQ_NVFP4=1 (opt-in, 2026-07-08): re-encode Q4_K/Q5_K 2D matmul weights to NVFP4 at
556 // load. The k-quant mmvq family runs at 61-70% of the bandwidth wall on this rig (measured
557 // BOTH engines — the kernels share ancestry) while the in-house NVFP4 path runs at 96%.
558 // The daily GGUF's quant mix was chosen for llama's kernels, not ours: Q4_K -> NVFP4 is
559 // 4-bit -> 4-bit at +26pp kernel efficiency; Q5_K -> NVFP4 also drops bytes (0.69 -> 0.56
560 // B/w) at a small real re-quant cost (5 -> 4 bit; gates + acceptance arbitrate). Q6_K/Q8_0
561 // excluded (6/8-bit -> 4-bit is a real quality cliff — the lm_head stays untouched).
562 // MEMRA_KQ_NVFP4 (opt-in SPEED-OVER-QUALITY mode, measured 2026-07-08 on the 9B):
563 // =2 (Q4_K+Q5_K -> NVFP4): +3.9% plain decode (129.5 -> 134.5, the Q5 bytes win),
564 // acceptance tax ~3pts on hard content (p2 74.0 -> 70.7, p3 66.9 -> 64.9).
565 // =1 (Q4_K only): NO perf gain AND still ~3pts tax — Q4_K is ASYMMETRIC (6-bit
566 // scale+min per 32); NVFP4 is symmetric e2m1: dropping the zero-point is real
567 // error even 4-bit -> 4-bit. The "same bpw = same class" assumption is FALSE
568 // across asymmetric/symmetric formats. Kept only for the record.
569 let kq = std::env::var("MEMRA_KQ_NVFP4")
570 .ok()
571 .and_then(|x| x.parse::<u8>().ok())
572 .unwrap_or(0);
573 if (kq >= 1 && v.ggml_type == GgmlType::Q4_K || kq >= 2 && v.ggml_type == GgmlType::Q5_K)
574 && v.ne.len() == 2
575 && v.ne[0] % 64 == 0
576 && !name.starts_with("output")
577 {
578 let n: u64 = v.ne.iter().product();
579 let f32v = dequant::dequantize(v.ggml_type, &v.bytes, n as usize);
580 let packed = memra_gguf::nvfp4_repack::f32_to_nvfp4(&f32v);
581 v = memra_gguf::source::TensorView {
582 bytes: std::borrow::Cow::Owned(packed),
583 ggml_type: GgmlType::NVFP4,
584 ne: v.ne.clone(),
585 };
586 }
587 let qtype = match v.ggml_type {
588 GgmlType::Q8_0 => Some(QT_Q8_0),
589 GgmlType::Q4_K => Some(QT_Q4_K),
590 GgmlType::Q6_K => Some(QT_Q6_K),
591 GgmlType::Q5_K => Some(QT_Q5_K),
592 GgmlType::Q3_K => Some(QT_Q3_K),
593 GgmlType::IQ4_XS => Some(QT_IQ4_XS),
594 GgmlType::IQ3_S => Some(QT_IQ3_S),
595 GgmlType::NVFP4 => Some(QT_NVFP4),
596 GgmlType::Q4_0 => Some(QT_Q4_0),
597 // F32/F16/BF16 (the dtypes safetensors carries) -> Float path below.
598 _ => None,
599 };
600 match qtype {
601 Some(qt) => {
602 let out_f = v.ne[1] as usize;
603 let row_bytes = v.bytes.len() / out_f;
604 // NVFP4 two-level scale: per-16 ue4m3 micro-scale is in the dequant; the per-tensor
605 // F32 macro-scale lives in a sibling "<stem>.scale" tensor, applied POST-matmul
606 // (llama build_lora_mm: ggml_mul(res, w_s)). ".input_scale" is the W4A4 activation
607 // scale — UNUSED on our W4A16/f32 path. Only NVFP4 carries it; others -> 1.0 (no-op).
608 let scale = if qt == QT_NVFP4 {
609 let stem = name.strip_suffix(".weight").unwrap_or(name);
610 match src.find(&format!("{stem}.scale")) {
611 Some(sv) => f32::from_le_bytes(sv.bytes[..4].try_into().unwrap()),
612 None => 1.0,
613 }
614 } else {
615 1.0
616 };
617 // A6 SPLIT-PLANE repack: NVFP4 2-D matmul weights upload in walk-order layout
618 // (host-side permutation before htod — zero VRAM spike, layer-streamed by
619 // construction). Every consumer kernel dispatches its `_rp` twin off the flag.
620 let rp = qt == QT_NVFP4
621 && v.ne.len() == 2
622 && (v.ne[0] as usize) % 64 == 0
623 && v.bytes.len() % out_f == 0
624 && (v.bytes.len() / out_f) % 36 == 0
625 && rp_enabled();
626 let bytes = if rp {
627 e.htod_bytes(&repack_nvfp4_split(&v.bytes, out_f))?
628 } else {
629 e.htod_bytes(&v.bytes)?
630 };
631 // CUTLASS NVFP4 prefill operand, built from the RAW GGUF bytes (a temp raw upload
632 // when the resident `bytes` are repacked). Gated: only NVFP4 weights, only when
633 // MEMRA_FP4_CUTLASS is set, only under cfg(memra_cutlass). in_f%64==0 is the NVFP4
634 // K-block constraint (same as the dispatch).
635 #[cfg(memra_cutlass)]
636 let cutlass = {
637 let in_f = v.ne[0] as usize;
638 // Skip the resident repack when OTF is requested (per-call repack instead) — the
639 // resident path ~doubles NVFP4 weight VRAM and OOMs larger models (e.g. 27B/24GB).
640 if qt == QT_NVFP4
641 && in_f % 64 == 0
642 && v.ne.len() == 2
643 && std::env::var("MEMRA_FP4_CUTLASS").is_ok()
644 && std::env::var("MEMRA_FP4_CUTLASS_OTF").is_err()
645 {
646 let raw_dev;
647 let src_dev = if rp {
648 raw_dev = e.htod_bytes(&v.bytes)?;
649 &raw_dev
650 } else {
651 &bytes
652 };
653 let (b_packed, sfb_swizzled) =
654 e.build_cutlass_weight(src_dev, out_f, in_f, row_bytes)?;
655 Some(CutlassWeight {
656 b_packed,
657 sfb_swizzled,
658 })
659 } else {
660 None
661 }
662 };
663 // FP8-ACT PREFILL operand (MEMRA_PP_FP8=1): for F8-E4M3-sourced projections (they
664 // surface as Q8_0 from the source's re-encode) ALSO stash the raw e4m3 device
665 // bytes + weight_scale. The source guarantees byte order matches `v` (the
666 // Transform arm's V-reorder is baked into both); the ne check guards a mixup.
667 // VRAM BUDGET (24GB rigs, 2026-07-08): the stash duplicates every F8-origin
668 // projection (~+3.4GB on the 27B) — fine on the 96GB box, OOM here. The stash
669 // spends from MEMRA_PP_FP8_BUDGET_MB (default 1536); once spent, remaining
670 // tensors ride the old path. Load order is layer order, so the budget covers a
671 // PREFIX of layers — coverage (and the prefill win) scales with the budget.
672 // MEMRA_FP8_MMQ=1 (lane/fp8-mmq) admits the SAME stash for the block-128 class:
673 // the per-block MMQ prefill kernel is that class's consumer, and it needs exactly
674 // what this arm makes resident (raw e4m3 bytes + the verbatim f32 grid). It shares
675 // the budget accounting below, so a 24GB rig still caps the duplicate.
676 // NOTE the gate here is `fp8_mmq_enabled` (the STASH gate, still opt-in) and NOT
677 // `fp8_blk_mmq_native_enabled` (default ON since 2026-08-05). That is deliberate:
678 // this arm's whole product is a DUPLICATE weight copy, and the native-resident route
679 // exists precisely to avoid one. A QT_F8_E4M3_BLK tensor already carries its own
680 // e4m3 bytes + grid, so it needs nothing from here; wiring the default-ON gate into
681 // this condition would spend the budget on copies no kernel reads.
682 let fp8 = if qt == QT_Q8_0
683 && (crate::fp8_ffi::pp_fp8_enabled() || crate::fp8_ffi::fp8_mmq_enabled())
684 {
685 match src.find_fp8_native(name) {
686 Some(f8)
687 if v.ne.len() == 2
688 && f8.in_f as u64 == v.ne[0]
689 && f8.out_f as u64 == v.ne[1] =>
690 {
691 use std::sync::atomic::{AtomicUsize, Ordering};
692 static FP8_SPENT: AtomicUsize = AtomicUsize::new(0);
693 static FP8_BUDGET: std::sync::OnceLock<usize> =
694 std::sync::OnceLock::new();
695 let budget = *FP8_BUDGET.get_or_init(|| {
696 std::env::var("MEMRA_PP_FP8_BUDGET_MB")
697 .ok()
698 .and_then(|v| v.parse::<usize>().ok())
699 .unwrap_or(1536)
700 << 20
701 });
702 let sz = f8.bytes.len();
703 if FP8_SPENT.fetch_add(sz, Ordering::Relaxed) + sz <= budget {
704 // Block-128 grid rides along resident (checkpoint order,
705 // Fp8BlockScales layout contract). try_fp8_gemm still skips blk
706 // operands (cuBLASLt takes no block grid on sm_120, P1-VERDICT);
707 // try_fp8_blk_mmq is their consumer under MEMRA_FP8_MMQ=1.
708 let blk = match f8.blk {
709 Some(g) => Some(Fp8BlockScales {
710 scales: e.htod(&g.scales)?,
711 rows: g.rows,
712 cols: g.cols,
713 }),
714 None => None,
715 };
716 Some(Fp8Weight {
717 bytes: e.htod_bytes(&f8.bytes)?,
718 scale: f8.scale,
719 blk,
720 })
721 } else {
722 FP8_SPENT.fetch_sub(sz, Ordering::Relaxed);
723 None
724 }
725 }
726 _ => None,
727 }
728 } else {
729 None
730 };
731 Ok(GpuTensor::Quant {
732 bytes,
733 qtype: qt,
734 row_bytes,
735 ne: v.ne.clone(),
736 scale,
737 rp,
738 #[cfg(memra_cutlass)]
739 cutlass,
740 fp8,
741 blk: None,
742 rp4: None,
743 f16: None,
744 })
745 }
746 None => {
747 let n: u64 = v.ne.iter().product();
748 // FULL-PRECISION MODE (MEMRA_FULL_PREC): NO re-encodes. Large 2D bf16 matmul weights
749 // stay bf16-resident (FloatBf16, dequant-on-use) so the trunk fits VRAM; everything
750 // else (small 2D, 1D norms, F16/F32) rides the exact f32 Float path below. The ssm
751 // Q8_0 re-encode and the Float-poison tripwire are BYPASSED here (both are the loader
752 // law this mode exists to suspend — the warnings would be correct but noise).
753 if full_prec_enabled() {
754 // Only bf16 sources take the resident-bf16 arm; F16/F32 fall through to f32 Float
755 // (exact, and tiny/absent in the bf16 ST checkpoints this mode targets). The 1M
756 // threshold keeps small tensors (norms, gate_inp) on the proven f32 path — only
757 // the big trunk matrices need the 2 B/w VRAM saving.
758 if v.ggml_type == GgmlType::BF16 && v.ne.len() == 2 && n >= 1_000_000 {
759 let data = e.htod_bytes(&v.bytes)?; // raw bf16 bytes, u16 LE pairs
760 return Ok(GpuTensor::FloatBf16 {
761 data,
762 ne: v.ne.clone(),
763 });
764 }
765 let f32v = dequant::dequantize(v.ggml_type, &v.bytes, n as usize);
766 return Ok(GpuTensor::Float {
767 data: e.htod(&f32v)?,
768 ne: v.ne.clone(),
769 });
770 }
771 let f32v = dequant::dequantize(v.ggml_type, &v.bytes, n as usize);
772 // ssm_beta/ssm_alpha stored F32 (the 35B GGUF): Q8_0-encode at load. F32 here
773 // fails `mixer_in_q8_1_fast` for the whole linear-attn mixer -> every linear
774 // layer falls off the fused norm+quantize chain onto cuBLAS f32 GEMV pairs
775 // (the NV-27B in_proj_a/b lesson, same all-or-nothing capability check; nsys
776 // 35B: 100 dot+reduce launches/token). Q8_0 of an F32 source is the same
777 // class-lossless step every 9B GGUF already ships for these tensors.
778 if v.ne.len() == 2
779 && v.ne[0] % 32 == 0
780 && (name.ends_with("ssm_beta.weight") || name.ends_with("ssm_alpha.weight")
781 // E4B per_layer_model_proj (F16 [2560, 10752]): matmul-class — the
782 // loader-law recipe (2026-07-12). As Float it rode cuBLAS f32 whose
783 // m=1-vs-m=16 FP-order gap seeds inp_pl noise into EVERY layer's PLE
784 // tail; the 42-layer stack amplifies it to logit maxdiff ~27 and the
785 // chat-prompt prefill-vs-decode argmax gate fails.
786 || name.ends_with("per_layer_model_proj.weight"))
787 {
788 let q8 = memra_gguf::nvfp4_repack::f32_to_q8_0(&f32v);
789 return GpuTensor::from_quant_bytes(
790 e,
791 &q8,
792 GgmlType::Q8_0,
793 v.ne[0],
794 v.ne[1],
795 1.0,
796 );
797 }
798 // LOADER-LAW TRIPWIRE (loadersweep 2026-07-08): a 2D Float tensor with both dims
799 // >= 16 is almost certainly MATMUL-class, and a Float matmul weight (a) rides
800 // cuBLAS f32 GEMV pairs (dot_kernel + reduce_1Block in nsys) and (b) fails
801 // uses_q8_1_fast, poisoning every ALL-OR-NOTHING fast-path predicate it sits on
802 // (mixer_in_q8_1_fast etc.) — the trap that cost measurable perf 4 times (NV-27B
803 // in_proj_a/b BF16, 35B ssm_beta/alpha F32, M3 shexp cousin, M3 BF16 lm_head).
804 // Fix recipe: name-gated f32_to_q8_0 encode at load (see the ssm arm above /
805 // source.rs BF16+F8 gates). Norm-class tensors are 1D or have a dim < 16
806 // (conv1d ne[0]=4) and never reach this warning.
807 if v.ne.len() == 2 && v.ne[0] >= 16 && v.ne[1] >= 16 && !float_2d_audited(name) {
808 warn_float_2d_once(name, &v.ne, v.ggml_type);
809 }
810 // F32/F16/BF16 (or as-yet-unhandled quant): dequant to f32. Small tensors only.
811 Ok(GpuTensor::Float {
812 data: e.htod(&f32v)?,
813 ne: v.ne.clone(),
814 })
815 }
816 }
817 }
818
819 /// Build a Quant tensor directly from raw ggml block bytes (FR-Spec self-trim: byte-level row
820 /// gather from an already-loaded weight — rows in every ggml quant are independent, so a
821 /// contiguous per-row byte copy is a lossless "trim"). `ne0` = in_features, `ne1` = rows.
822 pub fn from_quant_bytes(
823 e: &Engine,
824 bytes: &[u8],
825 ty: GgmlType,
826 ne0: u64,
827 ne1: u64,
828 scale: f32,
829 ) -> Result<Self, Box<dyn std::error::Error>> {
830 let qt = match ty {
831 GgmlType::Q8_0 => QT_Q8_0,
832 GgmlType::Q4_K => QT_Q4_K,
833 GgmlType::Q6_K => QT_Q6_K,
834 GgmlType::Q5_K => QT_Q5_K,
835 GgmlType::Q3_K => QT_Q3_K,
836 GgmlType::IQ4_XS => QT_IQ4_XS,
837 GgmlType::IQ3_S => QT_IQ3_S,
838 GgmlType::NVFP4 => QT_NVFP4,
839 GgmlType::Q4_0 => QT_Q4_0,
840 other => panic!("from_quant_bytes: unsupported dtype {other:?}"),
841 };
842 let row_bytes = bytes.len() / ne1 as usize;
843 // Same A6 repack as load_from_source: callers pass GGUF-layout host bytes (the FR-Spec
844 // self-trim row-gathers from the source file bytes, which are always original layout).
845 let rp = qt == QT_NVFP4 && ne0 % 64 == 0 && row_bytes % 36 == 0 && rp_enabled();
846 let dev = if rp {
847 e.htod_bytes(&repack_nvfp4_split(bytes, ne1 as usize))?
848 } else {
849 e.htod_bytes(bytes)?
850 };
851 Ok(GpuTensor::Quant {
852 bytes: dev,
853 qtype: qt,
854 row_bytes,
855 ne: vec![ne0, ne1],
856 scale,
857 rp,
858 #[cfg(memra_cutlass)]
859 cutlass: None,
860 fp8: None,
861 blk: None,
862 f16: None,
863 rp4: None,
864 })
865 }
866
867 pub fn load_opt(
868 e: &Engine,
869 g: &GgufFile,
870 name: &str,
871 ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
872 Self::load_opt_from_source(e, &GgufSource(g), name)
873 }
874
875 pub fn load_opt_from_source(
876 e: &Engine,
877 src: &dyn TensorSource,
878 name: &str,
879 ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
880 if src.has(name) {
881 Ok(Some(Self::load_from_source(e, src, name)?))
882 } else {
883 Ok(None)
884 }
885 }
886
887 /// Accessor for tensors that MUST be f32 (norm weights). Panics if quantized.
888 pub fn float_data(&self) -> &CudaSlice<f32> {
889 match self {
890 GpuTensor::Float { data, .. } => data,
891 GpuTensor::Quant { .. } => panic!("expected float tensor (norm), got quantized"),
892 GpuTensor::FloatBf16 { .. } => {
893 panic!("expected f32 float tensor (norm), got bf16-resident matmul weight")
894 }
895 }
896 }
897}
898
899pub struct Layer {
900 pub attn_norm: GpuTensor,
901 pub wq: GpuTensor,
902 pub wk: GpuTensor,
903 pub wv: GpuTensor,
904 pub wo: GpuTensor,
905 pub q_norm: Option<GpuTensor>,
906 pub k_norm: Option<GpuTensor>,
907 pub ffn_norm: GpuTensor,
908 /// FFN: dense SwiGLU or routed MoE (OLMoE — dense attention + MoE FFN). Reuses the hybrid
909 /// `Ffn` enum + `load_ffn` so the routed-expert forward is shared with `HybridModel::moe_ffn`.
910 pub ffn: crate::hybrid::Ffn,
911}
912
913/// Host-resident embedding table for row gather (dequant only the needed token rows).
914pub struct EmbedHost {
915 pub raw: Vec<u8>,
916 pub ggml_type: GgmlType,
917 pub n_embd: usize,
918}
919impl EmbedHost {
920 pub fn from_gguf(g: &GgufFile, name: &str) -> Self {
921 Self::from_source(&GgufSource(g), name)
922 }
923 pub fn from_source(src: &dyn TensorSource, name: &str) -> Self {
924 let v = src
925 .find(name)
926 .unwrap_or_else(|| panic!("missing embed {name}"));
927 EmbedHost {
928 raw: v.bytes.to_vec(),
929 ggml_type: v.ggml_type,
930 n_embd: v.ne[0] as usize,
931 }
932 }
933 /// QT int + row_bytes for this embed table's dtype (for the device embed-gather kernel).
934 /// CUDA-GRAPH-PLAN Phase 1. Mirrors the GpuTensor qtype mapping.
935 pub fn qt_and_row_bytes(&self, n_embd: usize) -> (i32, usize) {
936 let (blk, tsize) = self.ggml_type.block_and_type_size();
937 let row_bytes = (n_embd as u64 / blk * tsize) as usize;
938 let qt = match self.ggml_type {
939 GgmlType::Q8_0 => QT_Q8_0,
940 GgmlType::Q4_K => QT_Q4_K,
941 GgmlType::Q6_K => QT_Q6_K,
942 GgmlType::Q5_K => QT_Q5_K,
943 GgmlType::Q3_K => QT_Q3_K,
944 GgmlType::IQ4_XS => QT_IQ4_XS,
945 GgmlType::IQ3_S => QT_IQ3_S,
946 GgmlType::NVFP4 => QT_NVFP4,
947 GgmlType::F32 => QT_F32,
948 // BF16 embed table (FULL_PREC research mode: qwen35-9b-hf) — device gather does the
949 // exact bits<<16 expansion; 2 B/elem resident instead of an f32-doubled table.
950 GgmlType::BF16 => QT_BF16,
951 other => panic!("embed_gather: unsupported dtype {other:?}"),
952 };
953 (qt, row_bytes)
954 }
955
956 /// Gather rows for tokens -> [T, n_embd] f32. Dequant per-row from raw bytes.
957 pub fn gather(&self, n_embd: usize, tokens: &[u32]) -> Vec<f32> {
958 let (blk, tsize) = self.ggml_type.block_and_type_size();
959 let row_bytes = (n_embd as u64 / blk * tsize) as usize;
960 let mut x = vec![0f32; tokens.len() * n_embd];
961 for (ti, &tok) in tokens.iter().enumerate() {
962 let off = tok as usize * row_bytes;
963 let row = dequant::dequantize(self.ggml_type, &self.raw[off..off + row_bytes], n_embd);
964 x[ti * n_embd..ti * n_embd + n_embd].copy_from_slice(&row);
965 }
966 x
967 }
968}
969
970pub struct Model {
971 pub cfg: ModelConfig,
972 pub embd: EmbedHost,
973 pub output_norm: GpuTensor,
974 pub output: GpuTensor,
975 pub layers: Vec<Layer>,
976}
977
978impl Model {
979 /// Load a dense (vanilla-transformer) model from GGUF. Thin wrapper over
980 /// `load_dense_from_source`. Panics if the arch has SSM/MoE layers.
981 pub fn load_dense(e: &Engine, g: &GgufFile) -> Result<Self, Box<dyn std::error::Error>> {
982 Self::load_dense_from_source(e, &GgufSource(g))
983 }
984
985 /// Load a dense-attention model from any `TensorSource` — GGUF or a safetensors HF checkpoint.
986 /// The whole loop speaks ggml names; the source maps them. The FFN is dense SwiGLU OR routed MoE
987 /// (OLMoE: dense full-attention + MoE FFN). Panics on hybrid (SSM) arches — use the hybrid path.
988 pub fn load_dense_from_source(
989 e: &Engine,
990 src: &dyn TensorSource,
991 ) -> Result<Self, Box<dyn std::error::Error>> {
992 let cfg = src.config();
993 assert!(
994 cfg.full_attention_interval == 0,
995 "model has linear-attn layers; use hybrid path"
996 );
997 // FP8-KV per-model door: OFF everywhere by default (explicit MEMRA_KV_FP8 wins).
998 // The 2026-07-12 9B "+0.7-4% scaling with depth" did NOT reproduce on the
999 // 2026-07-28 build (12k A/B: fp8 117.0/118.2 vs q8 119.3/119.2 = −1%; d1736
1000 // flat; the fa-v3/f16pv/PDL stack moved underneath it). Adoption reverted by
1001 // measurement — fp8-KV's remaining value is bytes (~45% smaller KV) for
1002 // ctx-limited serving, not speed. Gates all green under both formats.
1003 crate::KV_FP8_FORCE.store(0, std::sync::atomic::Ordering::Relaxed);
1004
1005 let embd = EmbedHost::from_source(src, "token_embd.weight");
1006 let output_norm = GpuTensor::load_from_source(e, src, "output_norm.weight")?;
1007 // tied embeddings: fall back to tok_embd if output.weight absent (OLMoE has untied output).
1008 let output = if src.has("output.weight") {
1009 GpuTensor::load_from_source(e, src, "output.weight")?
1010 } else {
1011 GpuTensor::load_from_source(e, src, "token_embd.weight")?
1012 };
1013 let mut resident = crate::hybrid::ResidentPlan::unsharded(e, src, &cfg);
1014
1015 let mut layers = Vec::with_capacity(cfg.n_layer as usize);
1016 for il in 0..cfg.n_layer {
1017 let p = |s: &str| format!("blk.{il}.{s}");
1018 let hy3_dense_ffn = cfg
1019 .hy3
1020 .as_ref()
1021 .is_some_and(|h| il < h.first_k_dense_replace);
1022 let ffn = if hy3_dense_ffn {
1023 crate::hybrid::Ffn::Dense {
1024 ffn_gate: GpuTensor::load_from_source(e, src, &p("ffn_gate.weight"))?,
1025 ffn_up: GpuTensor::load_from_source(e, src, &p("ffn_up.weight"))?,
1026 ffn_down: GpuTensor::load_from_source(e, src, &p("ffn_down.weight"))?,
1027 }
1028 } else {
1029 crate::hybrid::load_ffn(e, src, &cfg, il, None, &mut resident)?
1030 };
1031 layers.push(Layer {
1032 attn_norm: GpuTensor::load_from_source(e, src, &p("attn_norm.weight"))?,
1033 wq: GpuTensor::load_from_source(e, src, &p("attn_q.weight"))?,
1034 wk: GpuTensor::load_from_source(e, src, &p("attn_k.weight"))?,
1035 wv: GpuTensor::load_from_source(e, src, &p("attn_v.weight"))?,
1036 wo: GpuTensor::load_from_source(e, src, &p("attn_output.weight"))?,
1037 q_norm: GpuTensor::load_opt_from_source(e, src, &p("attn_q_norm.weight"))?,
1038 k_norm: GpuTensor::load_opt_from_source(e, src, &p("attn_k_norm.weight"))?,
1039 ffn_norm: GpuTensor::load_from_source(e, src, &p("ffn_norm.weight"))?,
1040 ffn,
1041 });
1042 }
1043 Ok(Model {
1044 cfg,
1045 embd,
1046 output_norm,
1047 output,
1048 layers,
1049 })
1050 }
1051
1052 /// Largest expert block (bytes) across all MoE layers — the fixed cache-slot size (mirrors
1053 /// `HybridModel::max_moe_block`). 0 for a dense (non-MoE) model.
1054 pub(crate) fn max_moe_block(&self) -> usize {
1055 use crate::hybrid::Ffn;
1056 let mut mx = 0usize;
1057 for l in &self.layers {
1058 if let Ffn::Moe(m) = &l.ffn {
1059 mx = mx
1060 .max(m.gate_exps.max_expert_bytes())
1061 .max(m.up_exps.max_expert_bytes())
1062 .max(m.down_exps.max_expert_bytes());
1063 }
1064 }
1065 mx
1066 }
1067
1068 /// Gather embedding rows into f32 [T, n_embd] (token-major) by dequantizing only the needed
1069 /// rows from the host-side embedding bytes (token_embd is [n_embd, n_vocab], row per token).
1070 pub fn embed_tokens(
1071 &self,
1072 e: &Engine,
1073 tokens: &[u32],
1074 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1075 let n_embd = self.cfg.n_embd as usize;
1076 let x = self.embd.gather(n_embd, tokens);
1077 Ok(e.htod(&x)?)
1078 }
1079}
1080
1081pub type TensorMap = HashMap<String, GpuTensor>;
1082
1083/// One layer's stacked 256-expert tensor, raw GGUF quant bytes held HOST-RESIDENT.
1084///
1085/// EDGE-1: these bytes are NEVER uploaded at load (uploading 29.75GB would OOM a 24GB GPU —
1086/// this is BUG-4). Per token, only the 8 routed experts are staged H2D into a small GPU scratch.
1087///
1088/// ne = [in_f, out_f, n_expert]; the expert axis (ne[2]) is the slowest/highest-stride axis, so
1089/// expert `e` occupies the CONTIGUOUS byte block `bytes[e*expert_stride .. (e+1)*expert_stride]`.
1090///
1091/// THE 3D FIX: GpuTensor::load computes `row_bytes = raw.len()/ne[1]`, which for a stacked 3D
1092/// tensor ignores the 256-expert axis and is 256x too large (gate_exps -> 430080 instead of 1680).
1093/// load() here uses `row_bytes = raw.len() / (out_f * n_expert)` (= 1680 gate/up, 544 down).
1094/// Host byte storage for the expert blocks. Default = a pageable `Vec<u8>` (current behavior). Under
1095/// MEMRA_MOE_PINNED (auto-on when MEMRA_MOE_CACHE is set), the bytes live in CUDA pinned host memory so
1096/// the miss-path `memcpy_htod` is a true DMA, not a pageable bounce copy (MOE-SLRU-PLAN §C.1).
1097///
1098/// CAVEAT (§C.1): `alloc_pinned` uses CU_MEMHOSTALLOC_WRITECOMBINED — great for H2D-only (the expert
1099/// bytes are never read by the CPU on the hot path), but write-combined memory is SLOW for CPU reads.
1100/// A future CPU-VNNI cold-expert fallback must NOT read from this buffer.
1101pub enum HostBuf {
1102 Paged(Vec<u8>),
1103 /// Pinned host memory. We keep the `PinnedHostSlice` alive (it owns the allocation; Drop frees it)
1104 /// AND cache its raw base pointer + len so the hot-path `as_bytes()` needs no per-call event sync.
1105 Pinned {
1106 slice: std::sync::Arc<cudarc::driver::PinnedHostSlice<u8>>,
1107 base: *const u8,
1108 len: usize,
1109 },
1110 /// Alias into a shared pinned slab (ST pinned tier): `owner` keeps the slab alive; `base`/`len`
1111 /// select this expert's window. Same DMA class as `Pinned`.
1112 PinnedAlias {
1113 owner: std::sync::Arc<HostBuf>,
1114 base: *const u8,
1115 len: usize,
1116 },
1117 /// SPILLING-PLAN §1, Tier 2 (disk): the bytes live in an mmap'd region of the GGUF file, NOT in
1118 /// RAM. `map` is `MAP_SHARED`, no `MAP_POPULATE` — zero upfront copy. The first `memcpy_htod` of
1119 /// this slice page-faults → NVMe read → DMA (the demand-fault disk path). `off`/`len` select this
1120 /// expert's contiguous block within the shared file mmap. Bit-identical to `Paged`/`Pinned` —
1121 /// those copied FROM exactly these on-disk bytes, so the GEMM result is unchanged.
1122 Mmap {
1123 map: std::sync::Arc<memmap2::Mmap>,
1124 /// The same opened inode backing `map`. It must outlive the loader source so future explicit
1125 /// positioned reads cannot accidentally reopen a replaced path.
1126 file: std::sync::Arc<std::fs::File>,
1127 /// Absolute byte offset within both the whole-file mmap and `file`.
1128 off: usize,
1129 len: usize,
1130 },
1131}
1132// SAFETY: `base` is a stable pinned-host pointer owned by `slice`; the buffer is written once at load
1133// then only READ for H2D. HostExps is shared `&` across the (single per-Engine) forward, so Send/Sync
1134// mirror the underlying PinnedHostSlice (which is already Send+Sync). The `Mmap` arm holds
1135// `Arc<Mmap>` + `Arc<File>` (both Send+Sync) plus plain usize fields, so it does not weaken bounds.
1136unsafe impl Send for HostBuf {}
1137unsafe impl Sync for HostBuf {}
1138impl HostBuf {
1139 #[inline]
1140 pub fn as_bytes(&self) -> &[u8] {
1141 match self {
1142 HostBuf::Paged(v) => v.as_slice(),
1143 // SAFETY: base+len are the pinned allocation's stable extent; written once at load, then
1144 // read-only. We avoid `as_slice()` here because it would synchronize the buffer's event
1145 // on every hot-path call.
1146 HostBuf::Pinned { base, len, .. } => unsafe { std::slice::from_raw_parts(*base, *len) },
1147 HostBuf::PinnedAlias { base, len, .. } => unsafe {
1148 std::slice::from_raw_parts(*base, *len)
1149 },
1150 // Slicing the mmap is the same `&[u8]` the kernel DMAs; the read page-faults the NVMe.
1151 HostBuf::Mmap { map, off, len, .. } => &map[*off..*off + *len],
1152 }
1153 }
1154 #[inline]
1155 pub fn len(&self) -> usize {
1156 match self {
1157 HostBuf::Paged(v) => v.len(),
1158 HostBuf::Pinned { len, .. } => *len,
1159 HostBuf::PinnedAlias { len, .. } => *len,
1160 HostBuf::Mmap { len, .. } => *len,
1161 }
1162 }
1163
1164 /// Best-effort OS read-ahead for a future mmap-backed expert range. This does not touch or
1165 /// copy the bytes, so the zero-copy ownership contract is unchanged. Non-mmap buffers are
1166 /// already resident and need no advice. Kept fallible-at-the-OS but non-fatal at the call site:
1167 /// an unsupported/pressured kernel simply leaves the normal demand-fault path in place.
1168 #[inline]
1169 pub fn advise_willneed(&self, rel_off: usize, len: usize) -> bool {
1170 let HostBuf::Mmap {
1171 map,
1172 off,
1173 len: extent,
1174 ..
1175 } = self
1176 else {
1177 return false;
1178 };
1179 if len == 0 || rel_off > *extent || len > *extent - rel_off {
1180 return false;
1181 }
1182 #[cfg(unix)]
1183 {
1184 map.advise_range(memmap2::Advice::WillNeed, *off + rel_off, len)
1185 .is_ok()
1186 }
1187 #[cfg(not(unix))]
1188 {
1189 let _ = (map, off);
1190 false
1191 }
1192 }
1193
1194 #[inline]
1195 fn expert_source(&self, rel_off: usize, len: usize) -> ExpertSource<'_> {
1196 debug_assert!(rel_off <= self.len() && len <= self.len() - rel_off);
1197 match self {
1198 HostBuf::Mmap { map, file, off, .. } => {
1199 let offset = *off + rel_off;
1200 ExpertSource::Disk {
1201 file,
1202 offset: offset as u64,
1203 len,
1204 fallback: &map[offset..offset + len],
1205 keepalive: ExpertKeepalive::Mmap(map.clone()),
1206 }
1207 }
1208 HostBuf::Pinned { slice, .. } => ExpertSource::Memory {
1209 bytes: &self.as_bytes()[rel_off..rel_off + len],
1210 keepalive: Some(ExpertKeepalive::Pinned(slice.clone())),
1211 },
1212 HostBuf::PinnedAlias { owner, .. } => ExpertSource::Memory {
1213 bytes: &self.as_bytes()[rel_off..rel_off + len],
1214 keepalive: Some(ExpertKeepalive::Buffer(owner.clone())),
1215 },
1216 HostBuf::Paged(_) => ExpertSource::Memory {
1217 bytes: &self.as_bytes()[rel_off..rel_off + len],
1218 // CUDA stages pageable input before returning from the async-copy API. Only true
1219 // pinned and mmap-backed sources need an explicit lifetime owner in the cache.
1220 keepalive: None,
1221 },
1222 }
1223 }
1224}
1225
1226/// Clonable ownership retained by asynchronous cache transfers. The payload is intentionally never
1227/// read: keeping it alive is the contract.
1228#[allow(dead_code)]
1229pub(crate) enum ExpertKeepalive {
1230 Pinned(std::sync::Arc<cudarc::driver::PinnedHostSlice<u8>>),
1231 Buffer(std::sync::Arc<HostBuf>),
1232 Mmap(std::sync::Arc<memmap2::Mmap>),
1233}
1234
1235/// Source-aware view of one expert block. The mmap fallback remains the byte oracle; retaining the
1236/// opened file enables a later explicit-read backend without changing tensor layout or numerics.
1237pub(crate) enum ExpertSource<'a> {
1238 Memory {
1239 bytes: &'a [u8],
1240 keepalive: Option<ExpertKeepalive>,
1241 },
1242 Disk {
1243 file: &'a std::sync::Arc<std::fs::File>,
1244 offset: u64,
1245 len: usize,
1246 fallback: &'a [u8],
1247 keepalive: ExpertKeepalive,
1248 },
1249}
1250
1251/// One layer's stacked 256-expert tensor, raw GGUF quant bytes held HOST-RESIDENT.
1252///
1253/// EDGE-1: these bytes are NEVER uploaded at load (uploading 29.75GB would OOM a 24GB GPU —
1254/// this is BUG-4). Per token, only the 8 routed experts are staged H2D into a small GPU scratch.
1255///
1256/// ne = [in_f, out_f, n_expert]; the expert axis (ne[2]) is the slowest/highest-stride axis, so
1257/// expert `e` occupies the CONTIGUOUS byte block `bytes[e*expert_stride .. (e+1)*expert_stride]`.
1258///
1259/// THE 3D FIX: GpuTensor::load computes `row_bytes = raw.len()/ne[1]`, which for a stacked 3D
1260/// tensor ignores the 256-expert axis and is 256x too large (gate_exps -> 430080 instead of 1680).
1261/// load() here uses `row_bytes = raw.len() / (out_f * n_expert)` (= 1680 gate/up, 544 down).
1262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1263pub struct ExpertLayout {
1264 pub offset: usize,
1265 pub len: usize,
1266 pub qtype: i32,
1267 pub row_bytes: usize,
1268}
1269
1270fn staged_expert_qtype(ty: GgmlType) -> Option<i32> {
1271 Some(match ty {
1272 GgmlType::Q8_0 => QT_Q8_0,
1273 GgmlType::Q2_K => QT_Q2_K,
1274 GgmlType::Q4_K => QT_Q4_K,
1275 GgmlType::Q6_K => QT_Q6_K,
1276 GgmlType::Q5_K => QT_Q5_K,
1277 GgmlType::Q3_K => QT_Q3_K,
1278 GgmlType::IQ4_XS => QT_IQ4_XS,
1279 GgmlType::IQ3_S => QT_IQ3_S,
1280 GgmlType::NVFP4 => QT_NVFP4,
1281 GgmlType::F32 => QT_F32,
1282 GgmlType::BF16 => QT_BF16,
1283 _ => return None,
1284 })
1285}
1286
1287fn staged_expert_row_bytes(ty: GgmlType, in_f: usize) -> Option<usize> {
1288 staged_expert_qtype(ty)?;
1289 let (block, type_size) = ty.block_and_type_size();
1290 assert_eq!(
1291 in_f as u64 % block,
1292 0,
1293 "expert row width {in_f} is not divisible by {ty:?} block {block}"
1294 );
1295 Some((in_f as u64 / block * type_size) as usize)
1296}
1297
1298fn find_expert_disk_strict(
1299 src: &dyn TensorSource,
1300 name: &str,
1301) -> Result<Option<DiskExtent>, Box<dyn std::error::Error>> {
1302 if let Some(extent) = src.find_expert_disk(name) {
1303 return Ok(Some(extent));
1304 }
1305 if src.find_expert_mmap(name).is_some() {
1306 return Err(std::io::Error::new(
1307 std::io::ErrorKind::InvalidData,
1308 format!(
1309 "expert tensor {name} exposes legacy find_expert_mmap without find_expert_disk; \
1310 disk-backed expert loading requires a retained Arc<File>"
1311 ),
1312 )
1313 .into());
1314 }
1315 Ok(None)
1316}
1317
1318pub struct HostExps {
1319 pub bytes: HostBuf, // raw GGUF block bytes (host); per-token DMA src for the 8 routed exps
1320 /// SPILLING-PLAN §1.1: per-expert backing tier. `None` => the layer fits in one `bytes` store and
1321 /// every expert slices it (the unchanged in-RAM path). `Some` => per-expert split: the hottest
1322 /// experts are `Pinned` (Tier 1, fast async DMA), the rest `Mmap` into the GGUF (Tier 2, disk
1323 /// demand-fault). `expert_bytes(e)` resolves `tiers[e]` if present, else slices `bytes`.
1324 pub tiers: Option<Vec<HostBuf>>,
1325 pub qtype: i32, // QT_Q6_K (gate/up) | QT_Q8_0 (down)
1326 pub in_f: usize, // ne[0] (gate/up = 2048, down = 512)
1327 pub out_f: usize, // ne[1] (gate/up = 512, down = 2048)
1328 pub n_expert: usize, // ne[2] = 256
1329 pub row_bytes: usize, // raw.len()/(out_f*n_expert) -> 1680 (gate/up) / 544 (down)
1330 pub expert_stride: usize, // raw.len()/n_expert -> 860160 (gate/up) / 1114112 (down)
1331 /// Per-expert encoding metadata when experts in this projection do not share one dtype/layout.
1332 /// `None` preserves the existing uniform slab contract and every resident/fused fast path.
1333 /// `Some` routes through the per-expert staged/cache path, using each entry's qtype/row size.
1334 pub layouts: Option<Vec<ExpertLayout>>,
1335 /// Per-expert post-matmul macro-scale (ModelOpt NVFP4 `weight_scale_2`, one scalar per expert
1336 /// tensor). `None` => all 1.0 (GGUF experts; block scales carry everything). The MoE forward
1337 /// folds gate/up macros into the activation epilogue (gs/us) and the down macro into the
1338 /// per-expert accumulate weight.
1339 pub macros: Option<Vec<f32>>,
1340}
1341
1342impl HostExps {
1343 /// Load a stacked 3D expert tensor, keeping its quant bytes on the HOST. `e` supplies the CUDA
1344 /// context for the optional pinned allocation (§C.1). Default storage is pageable `Vec<u8>`
1345 /// (identical to the prior behavior); pinned is chosen when MEMRA_MOE_PINNED or MEMRA_MOE_CACHE is set.
1346 pub fn load(e: &Engine, g: &GgufFile, name: &str) -> Result<Self, Box<dyn std::error::Error>> {
1347 Self::load_stacked_from_source(e, &GgufSource(g), name)
1348 }
1349
1350 /// Load a STACKED 3D expert tensor (`ne=[in_f,out_f,n_expert]`) from any source. GGUF stores the
1351 /// experts this way; the source returns the same mmap bytes (`GgufSource::find` == `tensor_data`),
1352 /// so the GGUF path is byte-identical to the prior direct-`GgufFile` loader. (Safetensors stores N
1353 /// 2D tensors instead — those go through `load_from_source`, which gathers them.)
1354 /// Row-range variant for FUSED stacked tensors (gemma4 ffn_gate_up_exps: gate = rows
1355 /// [0,ff), up = [ff,2ff) per expert — llama-graph view convention). Copies only the range.
1356 pub fn load_stacked_split_from_source(
1357 e: &Engine,
1358 src: &dyn TensorSource,
1359 name: &str,
1360 row0: usize,
1361 row1: usize,
1362 ) -> Result<Self, Box<dyn std::error::Error>> {
1363 let t = src
1364 .find(name)
1365 .unwrap_or_else(|| panic!("missing exps tensor {name}"));
1366 assert_eq!(t.ne.len(), 3, "{name} is not 3D (ne={:?})", t.ne);
1367 let qtype = match t.ggml_type {
1368 GgmlType::Q8_0 => QT_Q8_0,
1369 GgmlType::Q4_K => QT_Q4_K,
1370 GgmlType::Q6_K => QT_Q6_K,
1371 GgmlType::Q5_K => QT_Q5_K,
1372 GgmlType::Q3_K => QT_Q3_K,
1373 GgmlType::IQ4_XS => QT_IQ4_XS,
1374 GgmlType::IQ3_S => QT_IQ3_S,
1375 GgmlType::NVFP4 => QT_NVFP4,
1376 GgmlType::Q4_0 => QT_Q4_0,
1377 other => panic!("exps {name} unsupported quant {other:?}"),
1378 };
1379 let raw: &[u8] = &t.bytes;
1380 let in_f = t.ne[0] as usize;
1381 let out_full = t.ne[1] as usize;
1382 let n_expert = t.ne[2] as usize;
1383 let full_stride = raw.len() / n_expert;
1384 let row_bytes = raw.len() / (out_full * n_expert);
1385 assert_eq!(full_stride, out_full * row_bytes, "{name} stride mismatch");
1386 let out_f = row1 - row0;
1387 let expert_stride = out_f * row_bytes;
1388 let mut buf = vec![0u8; n_expert * expert_stride];
1389 for ex in 0..n_expert {
1390 let s0 = ex * full_stride + row0 * row_bytes;
1391 buf[ex * expert_stride..(ex + 1) * expert_stride]
1392 .copy_from_slice(&raw[s0..s0 + expert_stride]);
1393 }
1394 let pinned = std::env::var("MEMRA_MOE_PINNED").is_ok()
1395 || std::env::var("MEMRA_MOE_CACHE").as_deref() != Ok("0");
1396 let bytes = if pinned {
1397 let mut pn = unsafe { e.ctx().alloc_pinned::<u8>(buf.len())? };
1398 {
1399 let dst = pn.as_mut_slice()?;
1400 dst.copy_from_slice(&buf);
1401 }
1402 let base = pn.as_ptr()? as *const u8;
1403 let len = buf.len();
1404 HostBuf::Pinned {
1405 slice: std::sync::Arc::new(pn),
1406 base,
1407 len,
1408 }
1409 } else {
1410 HostBuf::Paged(buf)
1411 };
1412 Ok(HostExps {
1413 bytes,
1414 tiers: None,
1415 qtype,
1416 in_f,
1417 out_f,
1418 n_expert,
1419 row_bytes,
1420 expert_stride,
1421 layouts: None,
1422 macros: None,
1423 })
1424 }
1425
1426 /// Stacked per-expert macro-scale sidecar: `blk.N.ffn_{proj}_exps.scale` f32 [n_expert]
1427 /// (the qwen3.6 NVFP4 converter emits one per stacked expert tensor — compressed-tensors
1428 /// global scales, inverted to multipliers). Absent (every k-quant GGUF) => None.
1429 /// NOTE gemma4 consumes ffn_down_exps.scale through its OWN router-fold (Gemma4MoeBits) —
1430 /// its MoE forward does not read HostExps::macros, so a Some here is inert there.
1431 fn stacked_macros(src: &dyn TensorSource, name: &str) -> Option<Vec<f32>> {
1432 let stem = name.strip_suffix(".weight")?;
1433 let sv = src.find(&format!("{stem}.scale"))?;
1434 if sv.ggml_type != GgmlType::F32 {
1435 return None;
1436 }
1437 let macros: Vec<f32> = sv
1438 .bytes
1439 .chunks_exact(4)
1440 .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
1441 .collect();
1442 if macros.iter().all(|&m| m == 1.0) {
1443 None
1444 } else {
1445 Some(macros)
1446 }
1447 }
1448
1449 pub fn load_stacked_from_source(
1450 e: &Engine,
1451 src: &dyn TensorSource,
1452 name: &str,
1453 ) -> Result<Self, Box<dyn std::error::Error>> {
1454 let t = src
1455 .find(name)
1456 .unwrap_or_else(|| panic!("missing exps tensor {name}"));
1457 assert_eq!(
1458 t.ne.len(),
1459 3,
1460 "{name} is not a 3D stacked-expert tensor (ne={:?})",
1461 t.ne
1462 );
1463 // MMAP-BACKED SPILL TIER (Hy3 repack dir, 2026-07-09): when the source's on-disk layout IS
1464 // already the engine's expert layout (one expert-axis-slowest slab file per (layer, proj),
1465 // the transcoder's contract), back the HostExps with `HostBuf::Mmap` directly — ZERO host
1466 // copy. The default copy path below would pin/allocate the WHOLE stacked slab (80.5 GB for
1467 // Hy3-REAP50 on a 60 GB host = the M3 first-load OOM class); the mmap tier instead lets the
1468 // page cache carry the hot expert mass (RAM tier) and demand-faults the overflow from NVMe,
1469 // exactly like the proven M3 `.memra-repack` path (model.rs NVFP4 disk arm). Bit-identity:
1470 // `expert_bytes(e)` slices the same on-disk bytes the copy would have staged. The SLRU VRAM
1471 // cache stacks on top unchanged. The configured whole-map advice is applied at source open.
1472 if let Some(DiskExtent {
1473 map,
1474 file,
1475 offset,
1476 len,
1477 }) = find_expert_disk_strict(src, name)?
1478 {
1479 let off = usize::try_from(offset)
1480 .map_err(|_| format!("{name} disk offset {offset} does not fit usize"))?;
1481 let qtype = match t.ggml_type {
1482 GgmlType::Q8_0 => QT_Q8_0,
1483 GgmlType::Q4_K => QT_Q4_K,
1484 GgmlType::Q6_K => QT_Q6_K,
1485 GgmlType::Q5_K => QT_Q5_K,
1486 GgmlType::Q3_K => QT_Q3_K,
1487 GgmlType::IQ4_XS => QT_IQ4_XS,
1488 GgmlType::IQ3_S => QT_IQ3_S,
1489 GgmlType::NVFP4 => QT_NVFP4,
1490 GgmlType::Q4_0 => QT_Q4_0,
1491 other => panic!("exps {name} unsupported quant {other:?}"),
1492 };
1493 let in_f = t.ne[0] as usize;
1494 let out_f = t.ne[1] as usize;
1495 let n_expert = t.ne[2] as usize;
1496 let expert_stride = len / n_expert;
1497 let row_bytes = len / (out_f * n_expert);
1498 assert_eq!(
1499 expert_stride,
1500 out_f * row_bytes,
1501 "{name} stride mismatch: stride={expert_stride} out_f={out_f} row_bytes={row_bytes}"
1502 );
1503 assert_eq!(
1504 len,
1505 n_expert * expert_stride,
1506 "{name} mmap len != n_expert*stride"
1507 );
1508 return Ok(HostExps {
1509 bytes: HostBuf::Mmap {
1510 map,
1511 file,
1512 off,
1513 len,
1514 },
1515 tiers: None,
1516 qtype,
1517 in_f,
1518 out_f,
1519 n_expert,
1520 row_bytes,
1521 expert_stride,
1522 layouts: None,
1523 macros: Self::stacked_macros(src, name),
1524 });
1525 }
1526 let raw: &[u8] = &t.bytes;
1527 // All quant types the staged-expert qmatvec can decode (dp4a-fast or Stage-A f32).
1528 let qtype = match t.ggml_type {
1529 GgmlType::Q8_0 => QT_Q8_0,
1530 GgmlType::Q4_K => QT_Q4_K,
1531 GgmlType::Q6_K => QT_Q6_K,
1532 GgmlType::Q5_K => QT_Q5_K,
1533 GgmlType::Q3_K => QT_Q3_K,
1534 GgmlType::IQ4_XS => QT_IQ4_XS,
1535 GgmlType::IQ3_S => QT_IQ3_S,
1536 GgmlType::NVFP4 => QT_NVFP4,
1537 GgmlType::Q4_0 => QT_Q4_0,
1538 other => panic!("exps {name} unsupported quant {other:?}"),
1539 };
1540 let in_f = t.ne[0] as usize;
1541 let out_f = t.ne[1] as usize;
1542 let n_expert = t.ne[2] as usize;
1543 // VERIFIED: gate/up Q6_K total/256 = 860160; row = total/(512*256) = 1680.
1544 // down Q8_0 total/256 = 1114112; row = total/(2048*256) = 544.
1545 let expert_stride = raw.len() / n_expert;
1546 let row_bytes = raw.len() / (out_f * n_expert);
1547 // sanity: expert_stride must equal out_f * row_bytes exactly (catches a dim mixup)
1548 assert_eq!(
1549 expert_stride,
1550 out_f * row_bytes,
1551 "{name} stride mismatch: stride={expert_stride} out_f={out_f} row_bytes={row_bytes}"
1552 );
1553
1554 let pinned = std::env::var("MEMRA_MOE_PINNED").is_ok()
1555 || std::env::var("MEMRA_MOE_CACHE").as_deref() != Ok("0");
1556 let bytes = if pinned {
1557 // alloc pinned host memory, copy the GGUF block bytes in once, cache the base pointer.
1558 let mut p = unsafe { e.ctx().alloc_pinned::<u8>(raw.len())? };
1559 {
1560 let dst = p.as_mut_slice()?;
1561 dst.copy_from_slice(raw);
1562 }
1563 let base = p.as_ptr()? as *const u8; // syncs once here at load; stable afterward
1564 let len = raw.len();
1565 HostBuf::Pinned {
1566 slice: std::sync::Arc::new(p),
1567 base,
1568 len,
1569 }
1570 } else {
1571 HostBuf::Paged(raw.to_vec())
1572 };
1573 Ok(HostExps {
1574 bytes,
1575 tiers: None,
1576 qtype,
1577 in_f,
1578 out_f,
1579 n_expert,
1580 row_bytes,
1581 expert_stride,
1582 layouts: None,
1583 macros: Self::stacked_macros(src, name),
1584 })
1585 }
1586
1587 /// SPILLING-PLAN §1.1, §2 step 4: load a stacked 3D expert tensor with a PER-EXPERT tier split.
1588 /// Under `MEMRA_SPILL_DISK`, the hottest experts (greedy in expert order, until the shared pinned
1589 /// budget in `ctx` is exhausted) get `HostBuf::Pinned` (Tier 1, fast async DMA); every remaining
1590 /// expert is `HostBuf::Mmap` into the GGUF (Tier 2, demand-faulted from disk on first H2D). The
1591 /// resulting bytes are bit-identical to the in-RAM path either way — `qmatvec_view` is untouched.
1592 ///
1593 /// `ctx.file_map` is ONE shared `MAP_SHARED` mmap of the whole GGUF (`Arc`-cloned per spilled
1594 /// expert), so the 120 expert tensors of a 40-layer MoE never open the file more than once.
1595 pub fn load_tiered(
1596 e: &Engine,
1597 g: &GgufFile,
1598 name: &str,
1599 ctx: &mut crate::spill::SpillCtx,
1600 ) -> Result<Self, Box<dyn std::error::Error>> {
1601 let t = g
1602 .find(name)
1603 .unwrap_or_else(|| panic!("missing exps tensor {name}"));
1604 assert_eq!(
1605 t.ne.len(),
1606 3,
1607 "{name} is not a 3D stacked-expert tensor (ne={:?})",
1608 t.ne
1609 );
1610 let raw = g.tensor_data(t);
1611 let qtype = match t.ggml_type {
1612 GgmlType::Q8_0 => QT_Q8_0,
1613 GgmlType::Q4_K => QT_Q4_K,
1614 GgmlType::Q6_K => QT_Q6_K,
1615 GgmlType::Q5_K => QT_Q5_K,
1616 GgmlType::Q3_K => QT_Q3_K,
1617 GgmlType::IQ4_XS => QT_IQ4_XS,
1618 GgmlType::IQ3_S => QT_IQ3_S,
1619 GgmlType::NVFP4 => QT_NVFP4,
1620 GgmlType::Q4_0 => QT_Q4_0,
1621 other => panic!("exps {name} unsupported quant {other:?}"),
1622 };
1623 let in_f = t.ne[0] as usize;
1624 let out_f = t.ne[1] as usize;
1625 let n_expert = t.ne[2] as usize;
1626 let expert_stride = raw.len() / n_expert;
1627 let row_bytes = raw.len() / (out_f * n_expert);
1628 assert_eq!(
1629 expert_stride,
1630 out_f * row_bytes,
1631 "{name} stride mismatch: stride={expert_stride} out_f={out_f} row_bytes={row_bytes}"
1632 );
1633
1634 // Byte offset of this tensor's data (start of expert 0) WITHIN ITS OWN SHARD's file; each
1635 // expert is the next `expert_stride` bytes. The `Mmap` arm slices `ctx.file_maps[t.shard]`
1636 // at these offsets — a split model's offsets are per-shard, not global.
1637 let (file_start, _file_end) = g.tensor_file_range(t);
1638
1639 // Per-expert tier decision under the shared running budget. `bytes` keeps a 0-byte sentinel
1640 // (`Paged(empty)`) since every read now goes through `tiers`.
1641 let mut tiers = Vec::with_capacity(n_expert);
1642 for ex in 0..n_expert {
1643 let blk = &raw[ex * expert_stride..(ex + 1) * expert_stride];
1644 let file_off = file_start + ex * expert_stride;
1645 tiers.push(crate::spill::place_expert(ctx, e, blk, file_off, t.shard)?);
1646 }
1647 Ok(HostExps {
1648 bytes: HostBuf::Paged(Vec::new()), // unused when `tiers` is Some
1649 tiers: Some(tiers),
1650 qtype,
1651 in_f,
1652 out_f,
1653 n_expert,
1654 row_bytes,
1655 expert_stride,
1656 layouts: None,
1657 macros: Self::stacked_macros(&GgufSource(g), name),
1658 })
1659 }
1660
1661 /// MoE expert GATHER from a `TensorSource` (the safetensors path; ST-MOE-PLAN §1.3). GGUF stacks
1662 /// all experts into ONE 3D tensor; HF stores them as N separate 2D tensors
1663 /// `model.layers.{il}.mlp.experts.{e}.{gate,up,down}_proj.weight`. `find` returns `None` for the
1664 /// ggml `*_exps` name on purpose, so the experts are gathered out-of-band here.
1665 ///
1666 /// PATH A (load-time only, no quantize): each HF 2D expert tensor is dequantized to f32 and the
1667 /// per-expert blocks are concatenated expert-axis-slowest into ONE contiguous buffer — exactly the
1668 /// layout `expert_bytes(e)` slices and the staged `qmatvec_view` (qtype=QT_F32) reads. The same
1669 /// `expert_stride == out_f*row_bytes` invariant as the GGUF path is asserted at the end.
1670 ///
1671 /// `ggml_exps_name` is `blk.{il}.ffn_{gate,up,down}_exps.weight`; it is split to recover `il` and
1672 /// the proj. `n_expert` comes from `cfg.moe`. The HF per-expert literal `mlp.experts.{e}.{p}_proj`
1673 /// is the qwen3moe / olmoe layout (a future arch with `block_sparse_moe.experts.*` would need a
1674 /// branch in `hf_expert_name`).
1675 pub fn load_from_source(
1676 e: &Engine,
1677 src: &dyn TensorSource,
1678 ggml_exps_name: &str,
1679 n_expert: usize,
1680 ) -> Result<Self, Box<dyn std::error::Error>> {
1681 // Recover il + proj from `blk.{il}.ffn_{gate,up,down}_exps.weight`.
1682 let rest = ggml_exps_name
1683 .strip_prefix("blk.")
1684 .unwrap_or_else(|| panic!("not a blk.* name: {ggml_exps_name}"));
1685 let (il_s, suffix) = rest.split_once('.').unwrap();
1686 let il: u32 = il_s.parse().unwrap();
1687 let proj = match suffix {
1688 "ffn_gate_exps.weight" => "gate",
1689 "ffn_up_exps.weight" => "up",
1690 "ffn_down_exps.weight" => "down",
1691 other => panic!("not a *_exps suffix: {other}"),
1692 };
1693
1694 // A mixed-precision safetensors/repack source exposes experts as separate 2D tensors.
1695 // Detect a dtype/layout change before the uniform gather paths normalize the whole layer
1696 // to one encoding. Uniform checkpoints take the unchanged optimized path below.
1697 let mut signatures = Vec::with_capacity(n_expert);
1698 let active = src.active_experts(il);
1699 for ex in 0..n_expert {
1700 if active.is_some_and(|mask| !mask[ex]) {
1701 signatures.push((i32::MIN, 0));
1702 continue;
1703 }
1704 let name = format!("blk.{il}.ffn_{proj}_exps.{ex}.weight");
1705 if let Some(nv) = src.find_nvfp4_native(&name) {
1706 signatures.push((QT_NVFP4, nv.in_f / 64 * 36));
1707 } else {
1708 let v = src
1709 .find(&name)
1710 .unwrap_or_else(|| panic!("missing expert tensor {name}"));
1711 let in_f = v.ne[0] as usize;
1712 signatures.push(match staged_expert_row_bytes(v.ggml_type, in_f) {
1713 Some(row_bytes) => (staged_expert_qtype(v.ggml_type).unwrap(), row_bytes),
1714 None => (QT_F32, in_f * 4),
1715 });
1716 }
1717 }
1718 let mixed_layout = signatures.windows(2).any(|pair| pair[0] != pair[1]);
1719 if src.preserve_expert_encodings() && !mixed_layout {
1720 if let Some(uniform) = Self::load_uniform_mmap_from_source(src, il, proj, n_expert)? {
1721 return Ok(uniform);
1722 }
1723 }
1724 if src.preserve_expert_encodings() || mixed_layout {
1725 return Self::load_mixed_from_source(src, il, proj, n_expert);
1726 }
1727
1728 // PATH B (NVFP4-NATIVE GATHER, 2026-07-05): when the source exposes the experts as packed
1729 // ModelOpt/Reza NVFP4 (find_nvfp4_native), keep them QUANTIZED — repack each expert's
1730 // modelopt bytes to the GGUF 36B-block layout the staged qmatvec decodes, and concatenate.
1731 // No f32 blow-up: a 129GB checkpoint gathers to ~the same bytes instead of ~8x (which is
1732 // what makes MiniMax-M3 REAP50 loadable on a 60GB-RAM host at all, with spill on top).
1733 // Per-expert `weight_scale_2` macros go to `macros` (folded post-matmul by the MoE forward).
1734 {
1735 let name0 = format!("blk.{il}.ffn_{proj}_exps.0.weight");
1736 if let Some(nv0) = src.find_nvfp4_native(&name0) {
1737 let (in_f, out_f) = (nv0.in_f, nv0.out_f);
1738 let row_bytes = in_f / 64 * 36;
1739 let expert_stride = out_f * row_bytes;
1740 // ST DISK TIER (2026-07-06, the MiniMax OOM fix): when the total expert bytes
1741 // exceed host RAM (M3 REAP50 = 122GB repacked on a 60GB host, first-load host-OOM
1742 // at layer ~24), repack each layer ONCE into an on-disk cache file next to the
1743 // checkpoint and mmap it (HostBuf::Mmap, MAP_SHARED no-populate — the same tier-2
1744 // mechanism the GGUF spill path uses). Reloads hit the cache (size-checked), pay
1745 // zero repack. MEMRA_ST_REPACK_DISK=0 forces the old in-RAM gather.
1746 let disk = std::env::var("MEMRA_ST_REPACK_DISK")
1747 .map(|v| v != "0")
1748 .unwrap_or(true)
1749 && src.st_dir().is_some();
1750 let cache_path = src.st_dir().map(|d| {
1751 let cd = d.join(".memra-repack");
1752 let _ = std::fs::create_dir_all(&cd);
1753 cd.join(format!("blk{il}-{proj}-{n_expert}x{out_f}x{in_f}.nvfp4"))
1754 });
1755 let total = n_expert * expert_stride;
1756 let mut macros = vec![1.0f32; n_expert];
1757 let read_macros = |macros: &mut Vec<f32>| {
1758 for ex in 0..n_expert {
1759 let stem = format!("blk.{il}.ffn_{proj}_exps.{ex}");
1760 if let Some(sv) = src.find(&format!("{stem}.scale")) {
1761 macros[ex] = f32::from_le_bytes(sv.bytes[..4].try_into().unwrap());
1762 }
1763 }
1764 };
1765 let bytes = if disk {
1766 let cp = cache_path.as_ref().unwrap();
1767 let fresh = std::fs::metadata(cp)
1768 .map(|m| m.len() as usize == total)
1769 .unwrap_or(false);
1770 if !fresh {
1771 // stream one expert at a time to disk — peak RAM = one expert (~8MB)
1772 use std::io::Write;
1773 let mut f = std::io::BufWriter::new(std::fs::File::create(cp)?);
1774 for ex in 0..n_expert {
1775 let name = format!("blk.{il}.ffn_{proj}_exps.{ex}.weight");
1776 let nv = src.find_nvfp4_native(&name).unwrap_or_else(|| {
1777 panic!("expert {name} lost NVFP4-native mid-gather")
1778 });
1779 assert_eq!(
1780 (nv.in_f, nv.out_f),
1781 (in_f, out_f),
1782 "expert {ex} dims ({},{}) != expert 0 ({in_f},{out_f})",
1783 nv.in_f,
1784 nv.out_f
1785 );
1786 f.write_all(&memra_gguf::nvfp4_repack::repack_modelopt_to_gguf(
1787 nv.wbytes, nv.wscale, out_f, in_f,
1788 ))?;
1789 }
1790 f.flush()?;
1791 }
1792 read_macros(&mut macros);
1793 let file = std::sync::Arc::new(std::fs::File::open(cp)?);
1794 let map = unsafe { memmap2::Mmap::map(file.as_ref())? };
1795 assert_eq!(map.len(), total, "repack cache {cp:?} size mismatch");
1796 // Default random preserves the original policy; normal lets Linux readahead
1797 // within each multi-megabyte expert on the spill-bound path.
1798 let _ = memra_gguf::source::apply_expert_mmap_advice(&map);
1799 let map = std::sync::Arc::new(map);
1800 // ST PINNED TIER (2026-07-07, the M3 1.5-tok/s lever): mmap-only backing makes
1801 // every SLRU miss a page-cache (or NVMe) synchronous read into the H2D copy.
1802 // Pin as many experts as the live budget allows (same MemBudget probe + 0.6
1803 // MemAvailable cap as the GGUF spill tier) — pinned pages upload via true
1804 // async DMA at full PCIe. Budget is GLOBAL across layers (first-come: earlier
1805 // layers pin first; routing is roughly uniform so early-layer bias is benign).
1806 // MEMRA_ST_PINNED=0 disables (pure-mmap, the 2026-07-06 behavior).
1807 // DEFAULT OFF (2026-07-07 measured): with a 122GB expert set on 60GB RAM,
1808 // pinning 26GB EVICTED the page cache backing the mmap tier — every unpinned
1809 // expert faulted cold from NVMe and gen fell 1.5 -> 0.05 tok/s (30x WORSE).
1810 // Pinning only pays when (total - pinned) fits page cache; here it never can.
1811 // MEMRA_ST_PINNED=1 opt-in for fits-in-RAM checkpoints (e.g. REAP-heavier cuts).
1812 let tiers = if std::env::var("MEMRA_ST_PINNED")
1813 .map(|v| v == "1")
1814 .unwrap_or(false)
1815 {
1816 static PIN_BUDGET: std::sync::OnceLock<std::sync::Mutex<usize>> =
1817 std::sync::OnceLock::new();
1818 let budget = PIN_BUDGET.get_or_init(|| {
1819 let b = crate::spill::MemBudget::probe(e)
1820 .map(|b| b.free_pinnable_ram)
1821 .unwrap_or(0);
1822 eprintln!("[st-spill] free_pinnable_ram={} MiB", b >> 20);
1823 std::sync::Mutex::new(b)
1824 });
1825 let mut rem = budget.lock().unwrap();
1826 // ONE pinned slab per file prefix (n_pin experts contiguous): 1 alloc +
1827 // 1 bulk copy instead of n_pin small allocs (per-expert cudaHostAllocs
1828 // stalled the 122GB M3 load >10min).
1829 let n_pin = (*rem / expert_stride).min(n_expert);
1830 if n_pin == 0 {
1831 None
1832 } else {
1833 let slab_len = n_pin * expert_stride;
1834 let mut pn = unsafe { e.ctx().alloc_pinned::<u8>(slab_len)? };
1835 {
1836 let dst = pn.as_mut_slice()?;
1837 dst.copy_from_slice(&map[..slab_len]);
1838 }
1839 let base = pn.as_ptr()? as *const u8;
1840 *rem -= slab_len;
1841 let slab = std::sync::Arc::new(HostBuf::Pinned {
1842 slice: std::sync::Arc::new(pn),
1843 base,
1844 len: slab_len,
1845 });
1846 let mut tiers: Vec<HostBuf> = Vec::with_capacity(n_expert);
1847 for ex in 0..n_expert {
1848 let off = ex * expert_stride;
1849 if ex < n_pin {
1850 tiers.push(HostBuf::PinnedAlias {
1851 owner: slab.clone(),
1852 base: unsafe { base.add(off) },
1853 len: expert_stride,
1854 });
1855 } else {
1856 tiers.push(HostBuf::Mmap {
1857 map: map.clone(),
1858 file: file.clone(),
1859 off,
1860 len: expert_stride,
1861 });
1862 }
1863 }
1864 Some(tiers)
1865 }
1866 } else {
1867 None
1868 };
1869 if let Some(tiers) = tiers {
1870 let all_one = macros.iter().all(|&m| m == 1.0);
1871 return Ok(HostExps {
1872 bytes: HostBuf::Mmap {
1873 map,
1874 file,
1875 off: 0,
1876 len: total,
1877 },
1878 tiers: Some(tiers),
1879 qtype: QT_NVFP4,
1880 in_f,
1881 out_f,
1882 n_expert,
1883 row_bytes,
1884 expert_stride,
1885 layouts: None,
1886 macros: if all_one { None } else { Some(macros) },
1887 });
1888 }
1889 HostBuf::Mmap {
1890 map,
1891 file,
1892 off: 0,
1893 len: total,
1894 }
1895 } else {
1896 let mut buf: Vec<u8> = Vec::with_capacity(total);
1897 for ex in 0..n_expert {
1898 let name = format!("blk.{il}.ffn_{proj}_exps.{ex}.weight");
1899 let nv = src.find_nvfp4_native(&name).unwrap_or_else(|| {
1900 panic!("expert {name} lost NVFP4-native mid-gather")
1901 });
1902 assert_eq!(
1903 (nv.in_f, nv.out_f),
1904 (in_f, out_f),
1905 "expert {ex} dims ({},{}) != expert 0 ({in_f},{out_f})",
1906 nv.in_f,
1907 nv.out_f
1908 );
1909 buf.extend_from_slice(&memra_gguf::nvfp4_repack::repack_modelopt_to_gguf(
1910 nv.wbytes, nv.wscale, out_f, in_f,
1911 ));
1912 }
1913 assert_eq!(buf.len(), total);
1914 read_macros(&mut macros);
1915 let pinned = std::env::var("MEMRA_MOE_PINNED").is_ok()
1916 || std::env::var("MEMRA_MOE_CACHE").as_deref() != Ok("0");
1917 if pinned {
1918 let mut p = unsafe { e.ctx().alloc_pinned::<u8>(buf.len())? };
1919 {
1920 let dst = p.as_mut_slice()?;
1921 dst.copy_from_slice(&buf);
1922 }
1923 let base = p.as_ptr()? as *const u8;
1924 let len = buf.len();
1925 HostBuf::Pinned {
1926 slice: std::sync::Arc::new(p),
1927 base,
1928 len,
1929 }
1930 } else {
1931 HostBuf::Paged(buf)
1932 }
1933 };
1934 let all_one = macros.iter().all(|&m| m == 1.0);
1935 return Ok(HostExps {
1936 bytes,
1937 tiers: None,
1938 qtype: QT_NVFP4,
1939 in_f,
1940 out_f,
1941 n_expert,
1942 row_bytes,
1943 expert_stride,
1944 layouts: None,
1945 macros: if all_one { None } else { Some(macros) },
1946 });
1947 }
1948 }
1949
1950 // expert 0 fixes (in_f, out_f); every later expert must match (catches a layer/arch mixup).
1951 let mut buf: Vec<u8> = Vec::new();
1952 let mut in_f = 0usize;
1953 let mut out_f = 0usize;
1954 for ex in 0..n_expert {
1955 // Per-expert ggml name; the source maps it to the HF expert tensor (ST-MOE-PLAN §1.3).
1956 let name = format!("blk.{il}.ffn_{proj}_exps.{ex}.weight");
1957 let v = src
1958 .find(&name)
1959 .unwrap_or_else(|| panic!("missing expert tensor {name}"));
1960 assert_eq!(v.ne.len(), 2, "expert {name} is not 2D (ne={:?})", v.ne);
1961 let (cur_in, cur_out) = (v.ne[0] as usize, v.ne[1] as usize);
1962 if ex == 0 {
1963 in_f = cur_in;
1964 out_f = cur_out;
1965 } else {
1966 assert_eq!(
1967 (cur_in, cur_out),
1968 (in_f, out_f),
1969 "expert {ex} dims {:?} != expert 0 [{in_f},{out_f}]",
1970 (cur_in, cur_out)
1971 );
1972 }
1973 // PATH A: dequant the 2D expert (F32/F16/BF16) to f32, append its bytes verbatim. The
1974 // dequantized [out_f, in_f] row-major f32 block is exactly one expert_stride slow→fast.
1975 let n = cur_in * cur_out;
1976 let f32v = dequant::dequantize(v.ggml_type, &v.bytes, n);
1977 buf.reserve(n * 4);
1978 for f in &f32v {
1979 buf.extend_from_slice(&f.to_le_bytes());
1980 }
1981 }
1982 let row_bytes = in_f * 4; // one out-row = in_f contiguous f32s
1983 let expert_stride = out_f * row_bytes;
1984 assert_eq!(
1985 buf.len(),
1986 n_expert * expert_stride,
1987 "{ggml_exps_name} gather size {} != n_expert*stride {}",
1988 buf.len(),
1989 n_expert * expert_stride
1990 );
1991 // Hold to the identical invariant as the GGUF path (ST-MOE-PLAN §1.3 step 4).
1992 assert_eq!(
1993 expert_stride,
1994 out_f * row_bytes,
1995 "{ggml_exps_name} stride mismatch: stride={expert_stride} out_f={out_f} row_bytes={row_bytes}"
1996 );
1997
1998 // Same pinned-vs-paged choice as the GGUF loader (the bytes are H2D-only on the hot path).
1999 let pinned = std::env::var("MEMRA_MOE_PINNED").is_ok()
2000 || std::env::var("MEMRA_MOE_CACHE").as_deref() != Ok("0");
2001 let bytes = if pinned {
2002 let mut p = unsafe { e.ctx().alloc_pinned::<u8>(buf.len())? };
2003 {
2004 let dst = p.as_mut_slice()?;
2005 dst.copy_from_slice(&buf);
2006 }
2007 let base = p.as_ptr()? as *const u8;
2008 let len = buf.len();
2009 HostBuf::Pinned {
2010 slice: std::sync::Arc::new(p),
2011 base,
2012 len,
2013 }
2014 } else {
2015 HostBuf::Paged(buf)
2016 };
2017 Ok(HostExps {
2018 bytes,
2019 tiers: None,
2020 qtype: QT_F32,
2021 in_f,
2022 out_f,
2023 n_expert,
2024 row_bytes,
2025 expert_stride,
2026 layouts: None,
2027 macros: None,
2028 })
2029 }
2030
2031 /// Coalesce a uniform v2 overlay back into the existing stacked-slab contract without copying.
2032 /// The artifact stores one record per original expert for coverage validation, but a full-bank
2033 /// uniform arm writes those records contiguously into one file. Keeping `layouts=None` preserves
2034 /// the uniform fused kernels while `HostBuf::Mmap` keeps the >RAM artifact zero-copy.
2035 fn load_uniform_mmap_from_source(
2036 src: &dyn TensorSource,
2037 il: u32,
2038 proj: &str,
2039 n_expert: usize,
2040 ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
2041 if src
2042 .active_experts(il)
2043 .is_some_and(|mask| mask.iter().any(|&active| !active))
2044 {
2045 return Ok(None);
2046 }
2047 let mut first_map = None;
2048 let mut first_file = None;
2049 let mut base_offset = 0u64;
2050 let mut expert_stride = 0usize;
2051 let mut in_f = 0usize;
2052 let mut out_f = 0usize;
2053 let mut qtype = 0i32;
2054 let mut row_bytes = 0usize;
2055 let mut macros = vec![1.0f32; n_expert];
2056 for ex in 0..n_expert {
2057 let stem = format!("blk.{il}.ffn_{proj}_exps.{ex}");
2058 let name = format!("{stem}.weight");
2059 let Some(DiskExtent {
2060 map,
2061 file,
2062 offset,
2063 len,
2064 }) = find_expert_disk_strict(src, &name)?
2065 else {
2066 return Ok(None);
2067 };
2068 let Some(v) = src.find(&name) else {
2069 return Ok(None);
2070 };
2071 if v.ne.len() != 2 {
2072 return Ok(None);
2073 }
2074 let (cur_in, cur_out) = (v.ne[0] as usize, v.ne[1] as usize);
2075 let Some(cur_row_bytes) = staged_expert_row_bytes(v.ggml_type, cur_in) else {
2076 return Ok(None);
2077 };
2078 let cur_qtype = staged_expert_qtype(v.ggml_type).unwrap();
2079 if ex == 0 {
2080 base_offset = offset;
2081 expert_stride = len;
2082 in_f = cur_in;
2083 out_f = cur_out;
2084 qtype = cur_qtype;
2085 row_bytes = cur_row_bytes;
2086 first_map = Some(map);
2087 first_file = Some(file);
2088 } else if !std::sync::Arc::ptr_eq(first_map.as_ref().unwrap(), &map)
2089 || !std::sync::Arc::ptr_eq(first_file.as_ref().unwrap(), &file)
2090 || offset != base_offset + (ex * expert_stride) as u64
2091 || len != expert_stride
2092 || (cur_in, cur_out, cur_qtype, cur_row_bytes) != (in_f, out_f, qtype, row_bytes)
2093 {
2094 return Ok(None);
2095 }
2096 if let Some(scale) = src.find(&format!("{stem}.scale")) {
2097 macros[ex] = f32::from_le_bytes(scale.bytes[..4].try_into().unwrap());
2098 }
2099 }
2100 assert_eq!(expert_stride, out_f * row_bytes);
2101 let total = n_expert * expert_stride;
2102 let off = usize::try_from(base_offset)
2103 .map_err(|_| format!("uniform expert disk offset {base_offset} does not fit usize"))?;
2104 let all_one = macros.iter().all(|&scale| scale == 1.0);
2105 Ok(Some(HostExps {
2106 bytes: HostBuf::Mmap {
2107 map: first_map.unwrap(),
2108 file: first_file.unwrap(),
2109 off,
2110 len: total,
2111 },
2112 tiers: None,
2113 qtype,
2114 in_f,
2115 out_f,
2116 n_expert,
2117 row_bytes,
2118 expert_stride,
2119 layouts: None,
2120 macros: if all_one { None } else { Some(macros) },
2121 }))
2122 }
2123
2124 fn load_mixed_from_source(
2125 src: &dyn TensorSource,
2126 il: u32,
2127 proj: &str,
2128 n_expert: usize,
2129 ) -> Result<Self, Box<dyn std::error::Error>> {
2130 let mut tiers = Vec::with_capacity(n_expert);
2131 let mut layouts = Vec::with_capacity(n_expert);
2132 let mut macros = vec![1.0f32; n_expert];
2133 let mut in_f = 0usize;
2134 let mut out_f = 0usize;
2135 let active = src.active_experts(il);
2136 let mut first_active = None;
2137
2138 for ex in 0..n_expert {
2139 if active.is_some_and(|mask| !mask[ex]) {
2140 layouts.push(ExpertLayout {
2141 offset: 0,
2142 len: 0,
2143 qtype: QT_F32,
2144 row_bytes: 0,
2145 });
2146 tiers.push(HostBuf::Paged(Vec::new()));
2147 continue;
2148 }
2149 let name = format!("blk.{il}.ffn_{proj}_exps.{ex}.weight");
2150 let stem = format!("blk.{il}.ffn_{proj}_exps.{ex}");
2151 if let Some(scale) = src.find(&format!("{stem}.scale")) {
2152 macros[ex] = f32::from_le_bytes(scale.bytes[..4].try_into().unwrap());
2153 }
2154 let (host, byte_len, qtype, row_bytes, cur_in, cur_out) = if let Some(DiskExtent {
2155 map,
2156 file,
2157 offset,
2158 len,
2159 }) =
2160 find_expert_disk_strict(src, &name)?
2161 {
2162 let v = src
2163 .find(&name)
2164 .unwrap_or_else(|| panic!("missing expert tensor {name}"));
2165 assert_eq!(v.ne.len(), 2, "expert {name} is not 2D (ne={:?})", v.ne);
2166 let (cur_in, cur_out) = (v.ne[0] as usize, v.ne[1] as usize);
2167 let row_bytes = staged_expert_row_bytes(v.ggml_type, cur_in).ok_or_else(|| {
2168 format!("mmap expert {name} has unsupported qtype {:?}", v.ggml_type)
2169 })?;
2170 let off = usize::try_from(offset).map_err(|_| {
2171 format!("expert {name} disk offset {offset} does not fit usize")
2172 })?;
2173 (
2174 HostBuf::Mmap {
2175 map,
2176 file,
2177 off,
2178 len,
2179 },
2180 len,
2181 staged_expert_qtype(v.ggml_type).unwrap(),
2182 row_bytes,
2183 cur_in,
2184 cur_out,
2185 )
2186 } else if let Some(nv) = src.find_nvfp4_native(&name) {
2187 let bytes = memra_gguf::nvfp4_repack::repack_modelopt_to_gguf(
2188 nv.wbytes, nv.wscale, nv.out_f, nv.in_f,
2189 );
2190 let row_bytes = nv.in_f / 64 * 36;
2191 let byte_len = bytes.len();
2192 (
2193 HostBuf::Paged(bytes),
2194 byte_len,
2195 QT_NVFP4,
2196 row_bytes,
2197 nv.in_f,
2198 nv.out_f,
2199 )
2200 } else {
2201 let v = src
2202 .find(&name)
2203 .unwrap_or_else(|| panic!("missing expert tensor {name}"));
2204 assert_eq!(v.ne.len(), 2, "expert {name} is not 2D (ne={:?})", v.ne);
2205 let (cur_in, cur_out) = (v.ne[0] as usize, v.ne[1] as usize);
2206 if let Some(row_bytes) = staged_expert_row_bytes(v.ggml_type, cur_in) {
2207 let bytes = v.bytes.into_owned();
2208 let byte_len = bytes.len();
2209 (
2210 HostBuf::Paged(bytes),
2211 byte_len,
2212 staged_expert_qtype(v.ggml_type).unwrap(),
2213 row_bytes,
2214 cur_in,
2215 cur_out,
2216 )
2217 } else {
2218 let f32v = dequant::dequantize(v.ggml_type, &v.bytes, cur_in * cur_out);
2219 let mut bytes = Vec::with_capacity(f32v.len() * 4);
2220 for f in f32v {
2221 bytes.extend_from_slice(&f.to_le_bytes());
2222 }
2223 let byte_len = bytes.len();
2224 (
2225 HostBuf::Paged(bytes),
2226 byte_len,
2227 QT_F32,
2228 cur_in * 4,
2229 cur_in,
2230 cur_out,
2231 )
2232 }
2233 };
2234
2235 if first_active.is_none() {
2236 in_f = cur_in;
2237 out_f = cur_out;
2238 first_active = Some(ex);
2239 } else {
2240 assert_eq!(
2241 (cur_in, cur_out),
2242 (in_f, out_f),
2243 "expert {ex} dims ({cur_in},{cur_out}) != first active expert ({in_f},{out_f})"
2244 );
2245 }
2246 assert_eq!(
2247 byte_len,
2248 cur_out * row_bytes,
2249 "expert {name} bytes {byte_len} != out_f*row_bytes {}",
2250 cur_out * row_bytes
2251 );
2252 layouts.push(ExpertLayout {
2253 offset: 0,
2254 len: byte_len,
2255 qtype,
2256 row_bytes,
2257 });
2258 tiers.push(host);
2259 }
2260
2261 let first = layouts[*first_active
2262 .as_ref()
2263 .expect("expert mask pruned every expert")];
2264 let expert_stride = layouts.iter().map(|layout| layout.len).max().unwrap_or(0);
2265 let all_one = macros.iter().all(|&scale| scale == 1.0);
2266 Ok(HostExps {
2267 bytes: HostBuf::Paged(Vec::new()),
2268 tiers: Some(tiers),
2269 qtype: first.qtype,
2270 in_f,
2271 out_f,
2272 n_expert,
2273 row_bytes: first.row_bytes,
2274 expert_stride,
2275 layouts: Some(layouts),
2276 macros: if all_one { None } else { Some(macros) },
2277 })
2278 }
2279
2280 /// Host byte slice for expert `e` (the H2D DMA source). Contiguous block, offset honored.
2281 /// Resolves the per-expert tier when spilling is active (`tiers` Some), else slices the single
2282 /// Per-expert post-matmul macro-scale (1.0 when absent).
2283 #[inline]
2284 pub fn macro_scale(&self, e: usize) -> f32 {
2285 self.macros.as_ref().map(|m| m[e]).unwrap_or(1.0)
2286 }
2287
2288 #[inline]
2289 pub fn is_uniform_layout(&self) -> bool {
2290 self.layouts.is_none()
2291 }
2292
2293 #[inline]
2294 pub fn expert_layout(&self, e: usize) -> ExpertLayout {
2295 debug_assert!(
2296 e < self.n_expert,
2297 "expert index {e} >= n_expert {}",
2298 self.n_expert
2299 );
2300 self.layouts
2301 .as_ref()
2302 .map(|layouts| layouts[e])
2303 .unwrap_or(ExpertLayout {
2304 offset: e * self.expert_stride,
2305 len: self.expert_stride,
2306 qtype: self.qtype,
2307 row_bytes: self.row_bytes,
2308 })
2309 }
2310
2311 #[inline]
2312 pub fn max_expert_bytes(&self) -> usize {
2313 self.layouts
2314 .as_ref()
2315 .and_then(|layouts| layouts.iter().map(|layout| layout.len).max())
2316 .unwrap_or(self.expert_stride)
2317 }
2318
2319 /// backing store (unchanged in-RAM path). Each `tiers[e]` is exactly one expert's stride.
2320 #[inline]
2321 pub fn expert_bytes(&self, e: usize) -> &[u8] {
2322 let layout = self.expert_layout(e);
2323 match &self.tiers {
2324 Some(tiers) => {
2325 debug_assert_eq!(tiers[e].len(), layout.len);
2326 tiers[e].as_bytes()
2327 }
2328 None => &self.bytes.as_bytes()[layout.offset..layout.offset + layout.len],
2329 }
2330 }
2331
2332 /// Source-aware twin of `expert_bytes`. Per-expert tiers already point at one exact block, while
2333 /// a uniform slab needs the expert layout offset added to its base. Keeping those cases separate
2334 /// prevents expert `e` from being offset twice when a tier vector is present.
2335 #[inline]
2336 pub(crate) fn expert_source(&self, e: usize) -> ExpertSource<'_> {
2337 let layout = self.expert_layout(e);
2338 match &self.tiers {
2339 Some(tiers) => tiers[e].expert_source(0, layout.len),
2340 None => self.bytes.expert_source(layout.offset, layout.len),
2341 }
2342 }
2343
2344 /// Hint that expert `e` will be staged soon. Uniform slabs advise only this expert's window;
2345 /// mixed/pruned layouts advise the selected per-expert mmap. Returns false for resident or
2346 /// empty buffers and on unsupported kernels; callers always retain the demand-fault fallback.
2347 #[inline]
2348 pub fn prefetch_expert_pages(&self, e: usize) -> bool {
2349 let layout = self.expert_layout(e);
2350 match &self.tiers {
2351 Some(tiers) => tiers[e].advise_willneed(0, layout.len),
2352 None => self.bytes.advise_willneed(layout.offset, layout.len),
2353 }
2354 }
2355}
2356
2357#[cfg(test)]
2358mod tests {
2359 use super::{
2360 ExpertKeepalive, ExpertSource, HostBuf, HostExps, QT_BF16, QT_NVFP4, QT_Q2_K, QT_Q4_K,
2361 repack_nvfp4_split, unpack_nvfp4_split,
2362 };
2363 use memra_gguf::nvfp4_repack::{repack_modelopt_to_gguf, repack_modelopt_to_split};
2364 use memra_gguf::source::{DiskExtent, TensorSource, TensorView};
2365 use memra_gguf::{GgmlType, config::ModelConfig};
2366 use std::borrow::Cow;
2367
2368 struct MixedExpertSource {
2369 bf16: Vec<u8>,
2370 q4k: Vec<u8>,
2371 }
2372
2373 impl TensorSource for MixedExpertSource {
2374 fn config(&self) -> ModelConfig {
2375 panic!("unused by HostExps mixed-loader test")
2376 }
2377
2378 fn find(&self, name: &str) -> Option<TensorView<'_>> {
2379 let (bytes, ggml_type) = if name == "blk.0.ffn_gate_exps.0.weight" {
2380 (&self.bf16, GgmlType::BF16)
2381 } else if name == "blk.0.ffn_gate_exps.1.weight" {
2382 (&self.q4k, GgmlType::Q4_K)
2383 } else {
2384 return None;
2385 };
2386 Some(TensorView {
2387 bytes: Cow::Borrowed(bytes),
2388 ggml_type,
2389 ne: vec![256, 2],
2390 })
2391 }
2392 }
2393
2394 struct PrunedExpertSource {
2395 q2k: Vec<u8>,
2396 nvfp4: Vec<u8>,
2397 active: Vec<bool>,
2398 }
2399
2400 struct MmapExpertSource {
2401 file: std::sync::Arc<std::fs::File>,
2402 map: std::sync::Arc<memmap2::Mmap>,
2403 base_offset: usize,
2404 expert_len: usize,
2405 }
2406
2407 struct LegacyMmapExpertSource {
2408 map: std::sync::Arc<memmap2::Mmap>,
2409 expert_len: usize,
2410 }
2411
2412 impl TensorSource for MmapExpertSource {
2413 fn config(&self) -> ModelConfig {
2414 panic!("unused by HostExps mmap-loader test")
2415 }
2416 fn preserve_expert_encodings(&self) -> bool {
2417 true
2418 }
2419 fn find(&self, name: &str) -> Option<TensorView<'_>> {
2420 let ex = match name {
2421 "blk.0.ffn_gate_exps.0.weight" => 0,
2422 "blk.0.ffn_gate_exps.1.weight" => 1,
2423 _ => return None,
2424 };
2425 let off = self.base_offset + ex * self.expert_len;
2426 Some(TensorView {
2427 bytes: Cow::Borrowed(&self.map[off..off + self.expert_len]),
2428 ggml_type: GgmlType::Q2_K,
2429 ne: vec![256, 2],
2430 })
2431 }
2432 fn find_expert_disk(&self, name: &str) -> Option<DiskExtent> {
2433 let ex = match name {
2434 "blk.0.ffn_gate_exps.0.weight" => 0,
2435 "blk.0.ffn_gate_exps.1.weight" => 1,
2436 _ => return None,
2437 };
2438 Some(DiskExtent {
2439 map: self.map.clone(),
2440 file: self.file.clone(),
2441 offset: (self.base_offset + ex * self.expert_len) as u64,
2442 len: self.expert_len,
2443 })
2444 }
2445 }
2446
2447 impl TensorSource for LegacyMmapExpertSource {
2448 fn config(&self) -> ModelConfig {
2449 panic!("unused by legacy mmap guard test")
2450 }
2451 fn preserve_expert_encodings(&self) -> bool {
2452 true
2453 }
2454 fn find(&self, name: &str) -> Option<TensorView<'_>> {
2455 let ex = match name {
2456 "blk.0.ffn_gate_exps.0.weight" => 0,
2457 "blk.0.ffn_gate_exps.1.weight" => 1,
2458 _ => return None,
2459 };
2460 let off = ex * self.expert_len;
2461 Some(TensorView {
2462 bytes: Cow::Borrowed(&self.map[off..off + self.expert_len]),
2463 ggml_type: GgmlType::Q2_K,
2464 ne: vec![256, 2],
2465 })
2466 }
2467 fn find_expert_mmap(
2468 &self,
2469 name: &str,
2470 ) -> Option<(std::sync::Arc<memmap2::Mmap>, usize, usize)> {
2471 let ex = match name {
2472 "blk.0.ffn_gate_exps.0.weight" => 0,
2473 "blk.0.ffn_gate_exps.1.weight" => 1,
2474 _ => return None,
2475 };
2476 Some((self.map.clone(), ex * self.expert_len, self.expert_len))
2477 }
2478 }
2479
2480 impl TensorSource for PrunedExpertSource {
2481 fn config(&self) -> ModelConfig {
2482 panic!("unused by HostExps pruned-loader test")
2483 }
2484 fn active_experts(&self, layer: u32) -> Option<&[bool]> {
2485 (layer == 0).then_some(self.active.as_slice())
2486 }
2487 fn find(&self, name: &str) -> Option<TensorView<'_>> {
2488 let (bytes, ggml_type) = match name {
2489 "blk.0.ffn_gate_exps.0.weight" => (&self.q2k, GgmlType::Q2_K),
2490 "blk.0.ffn_gate_exps.2.weight" => (&self.nvfp4, GgmlType::NVFP4),
2491 _ => return None,
2492 };
2493 Some(TensorView {
2494 bytes: Cow::Borrowed(bytes),
2495 ggml_type,
2496 ne: vec![256, 2],
2497 })
2498 }
2499 }
2500
2501 /// A1 direct-import gate (engine side): the fused modelopt->split repack must be byte-for-byte
2502 /// the composition of the two passes it replaces (modelopt->GGUF blocks, then the A6
2503 /// split-plane repack). Also pins the split roundtrip on the same buffers.
2504 #[test]
2505 fn direct_split_equals_chained() {
2506 for (out_f, in_f) in [(1usize, 64usize), (3, 128), (5, 320), (8, 1024)] {
2507 let mut w = vec![0u8; out_f * in_f / 2];
2508 let mut s = vec![0u8; out_f * in_f / 16];
2509 for (i, b) in w.iter_mut().enumerate() {
2510 *b = ((i * 41 + 7) & 0xFF) as u8;
2511 }
2512 for (i, b) in s.iter_mut().enumerate() {
2513 *b = (0x20 + ((i * 11 + 5) % 0x50)) as u8;
2514 }
2515 let gguf = repack_modelopt_to_gguf(&w, &s, out_f, in_f);
2516 let chained = repack_nvfp4_split(&gguf, out_f);
2517 let direct = repack_modelopt_to_split(&w, &s, out_f, in_f);
2518 assert_eq!(
2519 direct, chained,
2520 "fused != chained at out_f={out_f} in_f={in_f}"
2521 );
2522 assert_eq!(
2523 unpack_nvfp4_split(&direct, out_f),
2524 gguf,
2525 "split roundtrip broken at out_f={out_f} in_f={in_f}"
2526 );
2527 }
2528 }
2529
2530 #[test]
2531 fn mixed_expert_loader_keeps_each_encoding_and_extent() {
2532 let source = MixedExpertSource {
2533 bf16: vec![0x5a; 256 * 2 * 2],
2534 q4k: vec![0xa5; 2 * 144],
2535 };
2536 let exps = HostExps::load_mixed_from_source(&source, 0, "gate", 2).unwrap();
2537 assert!(!exps.is_uniform_layout());
2538 assert_eq!(exps.max_expert_bytes(), 1024);
2539 assert_eq!(exps.expert_layout(0).qtype, QT_BF16);
2540 assert_eq!(exps.expert_layout(0).row_bytes, 512);
2541 assert_eq!(exps.expert_layout(0).len, 1024);
2542 assert_eq!(exps.expert_layout(1).qtype, QT_Q4_K);
2543 assert_eq!(exps.expert_layout(1).row_bytes, 144);
2544 assert_eq!(exps.expert_layout(1).len, 288);
2545 assert_eq!(exps.expert_bytes(0), source.bf16);
2546 assert_eq!(exps.expert_bytes(1), source.q4k);
2547 match exps.expert_source(1) {
2548 ExpertSource::Memory { bytes, .. } => assert_eq!(bytes, source.q4k),
2549 ExpertSource::Disk { .. } => panic!("paged expert unexpectedly became disk-backed"),
2550 }
2551 }
2552
2553 #[test]
2554 fn mixed_expert_loader_omits_masked_expert_bytes() {
2555 let source = PrunedExpertSource {
2556 q2k: vec![0x22; 2 * 84],
2557 nvfp4: vec![0x44; 2 * 4 * 36],
2558 active: vec![true, false, true],
2559 };
2560 let exps = HostExps::load_mixed_from_source(&source, 0, "gate", 3).unwrap();
2561 assert_eq!(exps.expert_layout(0).qtype, QT_Q2_K);
2562 assert_eq!(exps.expert_layout(0).row_bytes, 84);
2563 assert_eq!(exps.expert_layout(1).len, 0);
2564 assert_eq!(exps.expert_bytes(1), &[]);
2565 assert_eq!(exps.expert_layout(2).qtype, QT_NVFP4);
2566 assert_eq!(exps.expert_layout(2).row_bytes, 4 * 36);
2567 }
2568
2569 #[test]
2570 fn mixed_expert_loader_keeps_mmap_backing_zero_copy() {
2571 let path = std::env::temp_dir().join(format!("memra-mixed-mmap-{}", std::process::id()));
2572 let base_offset = 3usize;
2573 let expert_len = 2 * 84;
2574 let mut bytes = vec![0xE1; base_offset];
2575 bytes.extend(vec![0x31; expert_len]);
2576 bytes.extend(vec![0x72; expert_len]);
2577 std::fs::write(&path, &bytes).unwrap();
2578 let file = std::sync::Arc::new(std::fs::File::open(&path).unwrap());
2579 let map = std::sync::Arc::new(unsafe { memmap2::Mmap::map(file.as_ref()).unwrap() });
2580 let source = MmapExpertSource {
2581 file: file.clone(),
2582 map,
2583 base_offset,
2584 expert_len,
2585 };
2586 let exps = HostExps::load_mixed_from_source(&source, 0, "gate", 2).unwrap();
2587 assert!(matches!(
2588 exps.tiers.as_ref().unwrap()[0],
2589 HostBuf::Mmap { .. }
2590 ));
2591 assert!(matches!(
2592 exps.tiers.as_ref().unwrap()[1],
2593 HostBuf::Mmap { .. }
2594 ));
2595 assert_eq!(
2596 exps.expert_bytes(0),
2597 &bytes[base_offset..base_offset + expert_len]
2598 );
2599 assert_eq!(exps.expert_bytes(1), &bytes[base_offset + expert_len..]);
2600 match exps.expert_source(1) {
2601 ExpertSource::Disk {
2602 file: got_file,
2603 offset,
2604 len,
2605 fallback,
2606 keepalive,
2607 } => {
2608 assert!(std::sync::Arc::ptr_eq(got_file, &file));
2609 assert_eq!(offset, (base_offset + expert_len) as u64);
2610 assert_eq!(len, expert_len);
2611 assert_eq!(fallback, &bytes[base_offset + expert_len..]);
2612 match keepalive {
2613 ExpertKeepalive::Mmap(owner) => {
2614 assert!(std::sync::Arc::ptr_eq(&owner, &source.map));
2615 }
2616 _ => panic!("mmap expert did not retain its mmap owner"),
2617 }
2618 }
2619 ExpertSource::Memory { .. } => panic!("mixed mmap tier lost its disk extent"),
2620 }
2621 #[cfg(unix)]
2622 assert!(exps.prefetch_expert_pages(1));
2623 std::fs::remove_file(path).ok();
2624 }
2625
2626 #[test]
2627 fn tiered_expert_source_does_not_double_apply_layout_offset() {
2628 let path =
2629 std::env::temp_dir().join(format!("memra-tiered-source-offset-{}", std::process::id()));
2630 let base_offset = 7usize;
2631 let expert_len = 2 * 84;
2632 let mut bytes = vec![0xE3; base_offset];
2633 bytes.extend(vec![0x41; expert_len]);
2634 bytes.extend(vec![0x82; expert_len]);
2635 std::fs::write(&path, &bytes).unwrap();
2636 let file = std::sync::Arc::new(std::fs::File::open(&path).unwrap());
2637 let map = std::sync::Arc::new(unsafe { memmap2::Mmap::map(file.as_ref()).unwrap() });
2638 let exps = HostExps {
2639 bytes: HostBuf::Paged(Vec::new()),
2640 tiers: Some(vec![
2641 HostBuf::Mmap {
2642 map: map.clone(),
2643 file: file.clone(),
2644 off: base_offset,
2645 len: expert_len,
2646 },
2647 HostBuf::Mmap {
2648 map,
2649 file: file.clone(),
2650 off: base_offset + expert_len,
2651 len: expert_len,
2652 },
2653 ]),
2654 qtype: QT_Q2_K,
2655 in_f: 256,
2656 out_f: 2,
2657 n_expert: 2,
2658 row_bytes: 84,
2659 expert_stride: expert_len,
2660 layouts: None,
2661 macros: None,
2662 };
2663
2664 // `expert_layout(1).offset == expert_len`, but tier 1 already starts at expert 1.
2665 assert_eq!(exps.expert_layout(1).offset, expert_len);
2666 match exps.expert_source(1) {
2667 ExpertSource::Disk {
2668 offset,
2669 len,
2670 fallback,
2671 ..
2672 } => {
2673 assert_eq!(offset, (base_offset + expert_len) as u64);
2674 assert_eq!(len, expert_len);
2675 assert_eq!(fallback, &bytes[base_offset + expert_len..]);
2676 }
2677 ExpertSource::Memory { .. } => panic!("tiered mmap expert lost its disk extent"),
2678 }
2679 std::fs::remove_file(path).ok();
2680 }
2681
2682 #[test]
2683 fn legacy_mmap_source_requires_retained_file_extent() {
2684 let path =
2685 std::env::temp_dir().join(format!("memra-legacy-mmap-source-{}", std::process::id()));
2686 let expert_len = 2 * 84;
2687 std::fs::write(&path, vec![0x64; 2 * expert_len]).unwrap();
2688 let file = std::fs::File::open(&path).unwrap();
2689 let map = std::sync::Arc::new(unsafe { memmap2::Mmap::map(&file).unwrap() });
2690 let source = LegacyMmapExpertSource { map, expert_len };
2691
2692 let err = match HostExps::load_uniform_mmap_from_source(&source, 0, "gate", 2) {
2693 Ok(_) => panic!("legacy mmap-only source silently fell back instead of failing"),
2694 Err(err) => err,
2695 };
2696 let message = err.to_string();
2697 assert!(
2698 message.contains("legacy find_expert_mmap without find_expert_disk"),
2699 "{message}"
2700 );
2701 assert!(message.contains("retained Arc<File>"), "{message}");
2702 std::fs::remove_file(path).ok();
2703 }
2704
2705 #[test]
2706 fn uniform_expert_loader_coalesces_contiguous_mmap() {
2707 let path = std::env::temp_dir().join(format!("memra-uniform-mmap-{}", std::process::id()));
2708 let base_offset = 5usize;
2709 let expert_len = 2 * 84;
2710 let mut bytes = vec![0xE2; base_offset];
2711 bytes.extend(vec![0x19; expert_len]);
2712 bytes.extend(vec![0x91; expert_len]);
2713 std::fs::write(&path, &bytes).unwrap();
2714 let file = std::sync::Arc::new(std::fs::File::open(&path).unwrap());
2715 let map = std::sync::Arc::new(unsafe { memmap2::Mmap::map(file.as_ref()).unwrap() });
2716 let source = MmapExpertSource {
2717 file: file.clone(),
2718 map,
2719 base_offset,
2720 expert_len,
2721 };
2722 let exps = HostExps::load_uniform_mmap_from_source(&source, 0, "gate", 2)
2723 .unwrap()
2724 .expect("contiguous mmap should coalesce");
2725 assert!(exps.is_uniform_layout());
2726 assert!(matches!(&exps.bytes, HostBuf::Mmap { .. }));
2727 assert_eq!(exps.expert_stride, expert_len);
2728 assert_eq!(
2729 exps.expert_bytes(0),
2730 &bytes[base_offset..base_offset + expert_len]
2731 );
2732 assert_eq!(exps.expert_bytes(1), &bytes[base_offset + expert_len..]);
2733 match exps.expert_source(1) {
2734 ExpertSource::Disk {
2735 file: got_file,
2736 offset,
2737 len,
2738 fallback,
2739 ..
2740 } => {
2741 assert!(std::sync::Arc::ptr_eq(got_file, &file));
2742 assert_eq!(offset, (base_offset + expert_len) as u64);
2743 assert_eq!(len, expert_len);
2744 assert_eq!(fallback, &bytes[base_offset + expert_len..]);
2745 }
2746 ExpertSource::Memory { .. } => panic!("uniform mmap slab lost its disk extent"),
2747 }
2748 #[cfg(unix)]
2749 assert!(exps.prefetch_expert_pages(1));
2750 std::fs::remove_file(path).ok();
2751 }
2752}