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