Skip to main content

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