Skip to main content

memra_engine/
hybrid.rs

1//! Qwen3.5/3.6 hybrid model: linear-attention (Gated DeltaNet) layers + periodic full-attention
2//! layers + SwiGLU FFN. Loads weights, runs the forward, dual cache. Builds on the validated
3//! conv1d + gdn_scan kernels (M2/M3) and the dense full-attn path (M0).
4
5use crate::model::{EmbedHost, GpuTensor, HostExps};
6use crate::Engine;
7use memra_gguf::config::{LayerKind, MlaConfig, ModelConfig};
8use memra_gguf::source::{GgufSource, TensorSource};
9use memra_gguf::{GgmlType, GgufFile};
10use cudarc::driver::CudaSlice;
11
12// Source-agnostic load helpers (GGUF or safetensors). The GGUF wrappers below keep `load()`
13// byte-identical; only the source object differs.
14fn load_t(
15    e: &Engine,
16    src: &dyn TensorSource,
17    name: &str,
18) -> Result<GpuTensor, Box<dyn std::error::Error>> {
19    GpuTensor::load_from_source(e, src, name)
20}
21fn load_opt(
22    e: &Engine,
23    src: &dyn TensorSource,
24    name: &str,
25) -> Result<Option<GpuTensor>, Box<dyn std::error::Error>> {
26    GpuTensor::load_opt_from_source(e, src, name)
27}
28
29/// Load the mixer (full-attn, linear-attn, or MLA) for block `il`. Shared by the trunk loop and
30/// the MTP head. `kind` overrides cfg.layer_kind (the MTP/NextN block is ALWAYS full-attn
31/// regardless of the periodic interval — its GGUF carries attn_q/k/v, not ssm_*/attn_qkv).
32/// `mla` is the Arch gate: `Some` only for glm-dsa (cfg.mla) — every layer of an MLA model,
33/// INCLUDING its NextN/MTP block (dense MLA, no indexer), takes the Mla arm.
34fn load_mixer_kind(
35    e: &Engine,
36    src: &dyn TensorSource,
37    il: u32,
38    kind: LayerKind,
39    mla: Option<&MlaConfig>,
40) -> Result<Mixer, Box<dyn std::error::Error>> {
41    let p = |s: &str| format!("blk.{il}.{s}");
42    if let Some(m) = mla {
43        assert_eq!(kind, LayerKind::FullAttention, "MLA layers are full-attention class");
44        return Ok(Mixer::Mla(MlaAttnLayer::load(e, src, il, m)?));
45    }
46    Ok(match kind {
47        LayerKind::FullAttention => Mixer::Full(FullAttnLayer {
48            wq: load_t(e, src, &p("attn_q.weight"))?,
49            wk: load_t(e, src, &p("attn_k.weight"))?,
50            // gemma4 global layers ship NO v_proj (attention_k_eq_v): V = the K projection
51            // output pre-rope (llama gemma4.cpp: `Vcur = wv ? mm(wv,cur) : Kcur`). Loading
52            // wv := wk reproduces that exactly with zero forward changes; the gemma forward
53            // adds the weightless V rms_norm (R7 part 2).
54            wv: match load_opt(e, src, &p("attn_v.weight"))? {
55                Some(v) => v,
56                None => load_t(e, src, &p("attn_k.weight"))?,
57            },
58            wo: load_t(e, src, &p("attn_output.weight"))?,
59            q_norm: load_t(e, src, &p("attn_q_norm.weight"))?,
60            k_norm: load_t(e, src, &p("attn_k_norm.weight"))?,
61        }),
62        LayerKind::LinearAttention => Mixer::Linear(LinearAttnLayer {
63            wqkv: load_t(e, src, &p("attn_qkv.weight"))?,
64            wqkv_gate: load_t(e, src, &p("attn_gate.weight"))?,
65            ssm_beta: load_t(e, src, &p("ssm_beta.weight"))?,
66            ssm_alpha: load_t(e, src, &p("ssm_alpha.weight"))?,
67            ssm_a: load_t(e, src, &p("ssm_a"))?,
68            ssm_dt: load_t(e, src, &p("ssm_dt.bias"))?,
69            ssm_conv1d: load_t(e, src, &p("ssm_conv1d.weight"))?,
70            ssm_norm: load_t(e, src, &p("ssm_norm.weight"))?,
71            ssm_out: load_t(e, src, &p("ssm_out.weight"))?,
72        }),
73    })
74}
75
76/// Load the FFN (dense SwiGLU or routed MoE) for block `il`. Source-agnostic (GGUF or safetensors
77/// via `TensorSource`); shared by the hybrid trunk/MTP loops AND the dense-attention MoE path (OLMoE).
78/// Shared-expert tensors are OPTIONAL (`load_opt`): qwen35moe has them, OLMoE/vanilla-MoE do not.
79/// When `spill` is `Some` (MEMRA_SPILL_DISK on) AND the source is the GGUF on disk, MoE experts load
80/// through the per-expert tier split (`HostExps::load_tiered`: hottest pinned, rest mmap'd from disk);
81/// otherwise experts take the all-host / gather path. Spill tiering is GGUF-only (needs the file mmap).
82pub(crate) fn load_ffn(
83    e: &Engine,
84    src: &dyn TensorSource,
85    cfg: &ModelConfig,
86    il: u32,
87    spill: Option<(&GgufFile, &mut crate::spill::SpillCtx)>,
88) -> Result<Ffn, Box<dyn std::error::Error>> {
89    let p = |s: &str| format!("blk.{il}.{s}");
90    // MiniMax-M3: moe_layer_freq[il]==0 -> this layer is a DENSE-FFN layer (layers 0..2) even
91    // though the arch is MoE; force the Dense arm (its mlp.{p}_proj names map via ggml_to_hf).
92    // Hy3: `first_k_dense_replace` leading layers are dense-FFN (REAP50: layer 0 only).
93    let dense_override = cfg.m3.as_ref()
94        .is_some_and(|m| m.moe_layer_freq.get(il as usize).copied() == Some(0))
95        || cfg.hy3.as_ref().is_some_and(|h| il < h.first_k_dense_replace)
96        // glm-dsa: leading_dense_block_count layers (GLM-5.2: 3) are dense-FFN
97        || cfg.mla.as_ref().is_some_and(|m| il < m.first_k_dense_replace)
98        // gemma4 DENSE variants (31B/E4B): the arch is MoE-capable but the file ships no
99        // expert tensors at all — tensor presence decides.
100        || (cfg.gemma4.is_some() && !src.has(&p("ffn_gate_exps.weight"))
101            && !src.has(&p("ffn_gate_up_exps.weight")));
102    Ok(
103        if let Some(moe) = cfg.moe.as_ref().filter(|_| !dense_override) {
104            let n_expert = moe.expert_count as usize;
105            // Expert loader. `spill` carries an optional (GgufFile, SpillCtx) — only the GGUF on-disk
106            // path can tier (it needs the file mmap); safetensors always gathers/stacks all-host.
107            //  - spill Some -> per-expert tier split (hottest pinned, rest mmap'd from the GGUF).
108            //  - GGUF 3D stacked name resolves -> load_stacked_from_source (all-host).
109            //  - else (safetensors) -> gather N separate 2D expert tensors.
110            let (gate_exps, up_exps, down_exps) = match spill {
111                Some((g, ctx)) => (
112                    HostExps::load_tiered(e, g, &p("ffn_gate_exps.weight"), ctx)?,
113                    HostExps::load_tiered(e, g, &p("ffn_up_exps.weight"), ctx)?,
114                    HostExps::load_tiered(e, g, &p("ffn_down_exps.weight"), ctx)?,
115                ),
116                None => {
117                    let exps =
118                        |e: &Engine, n: &str| -> Result<HostExps, Box<dyn std::error::Error>> {
119                            if src.has(n) {
120                                HostExps::load_stacked_from_source(e, src, n)
121                            } else {
122                                HostExps::load_from_source(e, src, n, n_expert)
123                            }
124                        };
125                    // gemma4: gate+up ship FUSED (ffn_gate_up_exps, gate rows first) — split at load.
126                    let fused = p("ffn_gate_up_exps.weight");
127                    if !src.has(&p("ffn_gate_exps.weight")) && src.has(&fused) {
128                        let ff = moe.expert_ff_length as usize;
129                        (
130                            HostExps::load_stacked_split_from_source(e, src, &fused, 0, ff)?,
131                            HostExps::load_stacked_split_from_source(e, src, &fused, ff, 2 * ff)?,
132                            exps(e, &p("ffn_down_exps.weight"))?,
133                        )
134                    } else {
135                        (
136                            exps(e, &p("ffn_gate_exps.weight"))?,
137                            exps(e, &p("ffn_up_exps.weight"))?,
138                            exps(e, &p("ffn_down_exps.weight"))?,
139                        )
140                    }
141                }
142            };
143            // FITS-VRAM RESIDENT EXPERTS: upload this layer's 3 expert slabs to device when a global
144            // budget (MEMRA_MOE_RESIDENT_GB override; default = free VRAM minus the file's non-expert
145            // bytes minus a measured headroom reserve) covers the whole model's expert bytes, summed
146            // exactly from the GGUF header. Decision is made ONCE (first MoE layer). Failure to fit
147            // => None => the SLRU spill machinery.
148            let dev_exps = build_dev_exps(e, src, cfg, &gate_exps, &up_exps, &down_exps)?;
149            // Device macro row [3*n_expert]: gate, up, down (ones when the artifact carries none).
150            let mut macro_row = vec![1.0f32; 3 * n_expert];
151            for (slot, exps) in [(0usize, &gate_exps), (1, &up_exps), (2, &down_exps)] {
152                if let Some(ms) = exps.macros.as_ref() {
153                    macro_row[slot * n_expert..(slot + 1) * n_expert].copy_from_slice(ms);
154                }
155            }
156            let has_macros = macro_row.iter().any(|&m| m != 1.0);
157            let dev_macros = e.htod(&macro_row)?;
158            // e_score_correction_bias (M3 sigmoid routing): tiny [n_expert] f32, host-side.
159            let exp_probs_b = src
160                .find(&p("exp_probs_b.bias"))
161                .map(|v| memra_gguf::dequant::dequantize(v.ggml_type, &v.bytes, n_expert));
162            let active_experts = src.active_experts(il).map(<[bool]>::to_vec);
163            Ffn::Moe(MoeWeights {
164                gate_inp: load_t(e, src, &p("ffn_gate_inp.weight"))?,
165                gate_inp_shexp: load_opt(e, src, &p("ffn_gate_inp_shexp.weight"))?,
166                exp_probs_b,
167                active_experts,
168                gate_exps,
169                up_exps,
170                down_exps,
171                gate_shexp: load_opt(e, src, &p("ffn_gate_shexp.weight"))?,
172                up_shexp: load_opt(e, src, &p("ffn_up_shexp.weight"))?,
173                down_shexp: load_opt(e, src, &p("ffn_down_shexp.weight"))?,
174                dev_exps,
175                dev_macros,
176                has_macros,
177            })
178        } else {
179            Ffn::Dense {
180                ffn_gate: load_t(e, src, &p("ffn_gate.weight"))?,
181                ffn_up: load_t(e, src, &p("ffn_up.weight"))?,
182                ffn_down: load_t(e, src, &p("ffn_down.weight"))?,
183            }
184        }
185    )
186}
187
188/// Decide + build the resident expert slabs for one layer. Budget check runs once (static),
189/// RESIDENT-IF-FITS (2026-08-02, research/residency-cap-20260802/): the bank is resident when
190/// its EXACT byte total (summed from the GGUF header — UD-quants make per-layer bytes
191/// non-uniform, Ornith-35B blk.0 is +7% over the mean, so first-layer x n_layer misprojects)
192/// plus the file's non-expert bytes plus a measured headroom reserve fits free VRAM. The old
193/// default (0.80 x free vs first-layer x n_layer) reserved 20% of the card (4.8GB on 24GB)
194/// and spilled the Ornith-35B bank that fits — a priced -33% decode / -54% prefill. Measured
195/// need beside the weights at board shape is ~1.7GB (CUDA ctx + KV + workspace); reserve
196/// default 2.0GB, machine-specific override `MEMRA_MOE_RESIDENT_HEADROOM_GB` (VRAM-budget
197/// class). `MEMRA_MOE_RESIDENT_GB` stays the absolute expert-budget override;
198/// MEMRA_MOE_RESIDENT=0 forces the SLRU path. Fits => every subsequent layer uploads too.
199fn build_dev_exps(
200    e: &Engine,
201    src: &dyn TensorSource,
202    cfg: &ModelConfig,
203    gate: &HostExps,
204    up: &HostExps,
205    down: &HostExps,
206) -> Result<Option<crate::hybrid::DevExps>, Box<dyn std::error::Error>> {
207    // The resident pointer-table kernels take one qtype/row stride per projection. Mixed-expert
208    // layers stay on the metadata-aware staged/SLRU paths until those kernels group by layout.
209    if !gate.is_uniform_layout() || !up.is_uniform_layout() || !down.is_uniform_layout() {
210        return Ok(None);
211    }
212    use std::sync::OnceLock;
213    static DECISION: OnceLock<bool> = OnceLock::new();
214    let per_layer =
215        gate.bytes.as_bytes().len() + up.bytes.as_bytes().len() + down.bytes.as_bytes().len();
216    let fits = *DECISION.get_or_init(|| {
217        if std::env::var("MEMRA_MOE_RESIDENT").as_deref() == Ok("0") { return false; }
218        if gate.tiers.is_some() { return false; }   // tiered/spill loads keep the cache path
219        let (free, _total) = match e.ctx().mem_get_info() { Ok(v) => v, Err(_) => return false };
220        // EXACT bank + trunk accounting from the GGUF header (metadata only, no data reads).
221        // Non-GGUF sources keep the first-layer upper bound with trunk unknown (the ST spill
222        // profiles load tiered and never reach this decision).
223        let (projected, trunk) = match src.gguf() {
224            Some(g) => {
225                let (mut exps, mut rest) = (0usize, 0usize);
226                for t in &g.tensors {
227                    if t.name.starts_with("blk.") && t.name.contains("_exps.") {
228                        exps += t.n_bytes as usize;
229                    } else {
230                        rest += t.n_bytes as usize;
231                    }
232                }
233                if exps > 0 { (exps, rest) } else { (per_layer * cfg.n_layer as usize, 0) }
234            }
235            None => (per_layer * cfg.n_layer as usize, 0),
236        };
237        let budget = std::env::var("MEMRA_MOE_RESIDENT_GB").ok()
238            .and_then(|v| v.parse::<f64>().ok())
239            .map(|gb| (gb * 1e9) as usize)
240            .unwrap_or_else(|| {
241                let reserve = std::env::var("MEMRA_MOE_RESIDENT_HEADROOM_GB").ok()
242                    .and_then(|v| v.parse::<f64>().ok())
243                    .map(|gb| (gb * 1e9) as usize)
244                    .unwrap_or(2_000_000_000);
245                (free as usize).saturating_sub(trunk + reserve)
246            });
247        let ok = projected <= budget;
248        eprintln!("[moe] resident-experts decision: experts {:.2}GB + trunk {:.2}GB vs free {:.2}GB (expert budget {:.2}GB) -> {}",
249                  projected as f64 / 1e9, trunk as f64 / 1e9, free as f64 / 1e9, budget as f64 / 1e9,
250                  if ok { "RESIDENT" } else { "SLRU cache" });
251        ok
252    });
253    if !fits {
254        return Ok(None);
255    }
256    use cudarc::driver::DevicePtr;
257    let gu_il = std::env::var("MEMRA_MOE_GU_IL").as_deref() == Ok("1")
258        && gate.out_f == up.out_f
259        && gate.in_f == up.in_f;
260    let n_expert = gate.n_expert;
261    let (g, u) = if gu_il {
262        // interleave gate/up rows: [ex][row o] = gate-row-o bytes ++ up-row-o bytes.
263        let (rbg, rbu) = (gate.row_bytes, up.row_bytes);
264        let n_rows = gate.out_f;
265        let gb = gate.bytes.as_bytes();
266        let ub = up.bytes.as_bytes();
267        let mut il = vec![0u8; n_expert * n_rows * (rbg + rbu)];
268        for ex in 0..n_expert {
269            for o in 0..n_rows {
270                let dst = (ex * n_rows + o) * (rbg + rbu);
271                let sg = ex * gate.expert_stride + o * rbg;
272                let su = ex * up.expert_stride + o * rbu;
273                il[dst..dst + rbg].copy_from_slice(&gb[sg..sg + rbg]);
274                il[dst + rbg..dst + rbg + rbu].copy_from_slice(&ub[su..su + rbu]);
275            }
276        }
277        let ild = e.htod_bytes_padded(&il, 8)?;
278        // `up` slot points into the same buffer via ptr math; keep a tiny placeholder alloc so
279        // the struct shape is unchanged (the table below carries the real pointers).
280        (ild, e.htod_bytes(&[0u8; 16])?)
281    } else {
282        (
283            e.htod_bytes_padded(gate.bytes.as_bytes(), 8)?,
284            e.htod_bytes_padded(up.bytes.as_bytes(), 8)?,
285        )
286    };
287    // 144B tail slack (2026-07-31, g26 prefill lever): the ragged-k expert MMA walks
288    // whole 256-val superblocks — the LAST row's final partial superblock overreads up
289    // to 144B past the slab (harmless bytes: the act's zero-padded k-range multiplies
290    // every overread weight to zero; the slack only prevents the OOB fault).
291    let d = e.htod_bytes_padded(down.bytes.as_bytes(), 144)?;
292    let mut host = vec![0u64; 3 * n_expert];
293    let (pg, pu, pd) = {
294        let __s_e0 = e.stream();
295        let (pg, _e0) = g.device_ptr(&__s_e0);
296        let __s_e1 = e.stream();
297        let (pu, _e1) = u.device_ptr(&__s_e1);
298        let __s_e2 = e.stream();
299        let (pd, _e2) = d.device_ptr(&__s_e2);
300        (pg as u64, pu as u64, pd as u64)
301    };
302    for ex in 0..n_expert {
303        if gu_il {
304            let stride = gate.out_f * (gate.row_bytes + up.row_bytes);
305            host[ex] = pg + (ex * stride) as u64;
306            host[n_expert + ex] = pg + (ex * stride + gate.row_bytes) as u64;
307        } else {
308            host[ex] = pg + (ex * gate.expert_stride) as u64;
309            host[n_expert + ex] = pu + (ex * up.expert_stride) as u64;
310        }
311        host[2 * n_expert + ex] = pd + (ex * down.expert_stride) as u64;
312    }
313    if gu_il {
314        eprintln!("[moe] gate/up dev slab INTERLEAVED (MEMRA_MOE_GU_IL)");
315    }
316    let ptr_row = e.htod_u64(&host)?;
317    Ok(Some(crate::hybrid::DevExps {
318        gate: g,
319        up: u,
320        down: d,
321        ptr_row,
322        gu_il,
323    }))
324}
325
326pub struct FullAttnLayer {
327    pub wq: GpuTensor,
328    pub wk: GpuTensor,
329    pub wv: GpuTensor,
330    pub wo: GpuTensor,
331    pub q_norm: GpuTensor,
332    pub k_norm: GpuTensor,
333}
334
335/// Latent-KV geometry for one MLA layer, resolved at load from `MlaConfig` (glm-dsa). The KV
336/// cache stores ONE `latent_dim`-wide row per token per layer: [rmsnorm(c_kv) | rope(k_pe)];
337/// V is the first `kv_rank` elements of the SAME row (no V plane). All heads stream it (MQA).
338#[derive(Clone, Copy, Debug)]
339pub struct MlaGeom {
340    pub n_head: usize,     // 64  — query heads; n_head_kv semantics = 1
341    pub d_nope: usize,     // 192 — qk nope head dim (absorb GEMM K)
342    pub d_rope: usize,     // 64  — decoupled rope width (q_pe / k_pe)
343    pub d_v: usize,        // 256 — v head dim after wv_b decompression
344    pub kv_rank: usize,    // 512 — latent rank (absorbed qk dim, AV accumulator width)
345    pub latent_dim: usize, // 576 = kv_rank + d_rope — the cache row / K width
346    pub scale: f32,        // 1/sqrt(d_nope + d_rope) = 1/16 — NOT 1/sqrt(latent_dim)
347}
348
349/// GLM-5.2 MLA attention block (DESIGN.md §3.1 mapping). INCREMENT 2: loader-only — the
350/// projections + latent-cache geometry land on device; forward arms (prefill/decode/dc/graph)
351/// are increment 4. The CPU oracle for those arms is `crate::mla` (naive ≡ absorbed, proven).
352pub struct MlaAttnLayer {
353    pub wq_a: GpuTensor,      // attn_q_a.weight      [H -> Lq] (q down-projection)
354    pub q_a_norm: GpuTensor,  // attn_q_a_norm.weight [Lq]
355    pub wq_b: GpuTensor,      // attn_q_b.weight      [Lq -> N*(nope+rope)] (q up, per head [nope|rope])
356    pub wkv_a: GpuTensor,     // attn_kv_a_mqa.weight [H -> Lkv+rope] (latent row producer)
357    pub kv_a_norm: GpuTensor, // attn_kv_a_norm.weight [Lkv] (c_kv rms; k_pe is NOT normed)
358    pub wk_b: GpuTensor,      // attn_k_b.weight      [nope, Lkv, N] 3D — TRANSPOSED nope slice of
359                              //   kv_b (conversion split): the per-head absorb GEMM operand
360    pub wv_b: GpuTensor,      // attn_v_b.weight      [Lkv, V, N] 3D — the post-softmax decompress
361    pub wo: GpuTensor,        // attn_output.weight   [N*V -> H]
362    pub geom: MlaGeom,
363}
364
365impl MlaAttnLayer {
366    /// Load one MLA attention block to device. `attn_kv_b` (the unsplit tensor, when present)
367    /// is intentionally NOT loaded — v1 runs absorbed-form everywhere; the MHA-prefill arm that
368    /// would consume it is a later arc (DESIGN.md §3.1 "unused v1").
369    ///
370    /// NOTE (increment-3+): wk_b/wv_b are 3D. The F32 fixture rides the Float path (exact, full
371    /// ne kept). Quantized 3D tensors would mis-derive `row_bytes` in the generic 2D Quant arm
372    /// (out_f = ne[1] only) — the real-weights loader must split per head or flatten ne[1]*ne[2]
373    /// before the batched-GEMM kernels consume them. Guarded by the assert below.
374    pub fn load(
375        e: &Engine,
376        src: &dyn TensorSource,
377        il: u32,
378        m: &MlaConfig,
379    ) -> Result<Self, Box<dyn std::error::Error>> {
380        let p = |s: &str| format!("blk.{il}.{s}");
381        let geom = MlaGeom {
382            n_head: 0, // patched below from wq_b's out width (metadata cross-check)
383            d_nope: m.qk_nope_head_dim as usize,
384            d_rope: m.qk_rope_head_dim as usize,
385            d_v: m.v_head_dim as usize,
386            kv_rank: m.kv_lora_rank as usize,
387            latent_dim: m.latent_dim() as usize,
388            scale: m.scale(),
389        };
390        let wq_a = load_t(e, src, &p("attn_q_a.weight"))?;
391        let wq_b = load_t(e, src, &p("attn_q_b.weight"))?;
392        let wkv_a = load_t(e, src, &p("attn_kv_a_mqa.weight"))?;
393        let wk_b = load_t(e, src, &p("attn_k_b.weight"))?;
394        let wv_b = load_t(e, src, &p("attn_v_b.weight"))?;
395        let wo = load_t(e, src, &p("attn_output.weight"))?;
396        // shape audit at load (fail loudly, not as garbage activations later):
397        let n_head = wq_b.out_features() / (geom.d_nope + geom.d_rope);
398        assert_eq!(wq_b.out_features(), n_head * (geom.d_nope + geom.d_rope),
399                   "wq_b out {} not a multiple of qk_head_dim {}", wq_b.out_features(),
400                   geom.d_nope + geom.d_rope);
401        assert_eq!(wq_a.in_features() , wkv_a.in_features(), "q_a/kv_a hidden mismatch");
402        assert_eq!(wq_b.in_features(), m.q_lora_rank as usize, "wq_b in != q_lora_rank");
403        assert_eq!(wkv_a.out_features(), geom.latent_dim, "wkv_a out != kv_lora_rank + rope");
404        assert_eq!(wk_b.ne(), &[geom.d_nope as u64, geom.kv_rank as u64, n_head as u64],
405                   "attn_k_b must be the TRANSPOSED (nope, kv_rank, head) conversion split");
406        assert_eq!(wv_b.ne(), &[geom.kv_rank as u64, geom.d_v as u64, n_head as u64],
407                   "attn_v_b must be the (kv_rank, v, head) conversion split");
408        assert_eq!(wo.in_features(), n_head * geom.d_v, "wo in != n_head * v_head_dim");
409        Ok(MlaAttnLayer {
410            wq_a,
411            q_a_norm: load_t(e, src, &p("attn_q_a_norm.weight"))?,
412            wq_b,
413            wkv_a,
414            kv_a_norm: load_t(e, src, &p("attn_kv_a_norm.weight"))?,
415            wk_b,
416            wv_b,
417            wo,
418            geom: MlaGeom { n_head, ..geom },
419        })
420    }
421}
422
423/// Increment-2 guard: every forward-path `match` on `Mixer` routes Mla here until increment 4
424/// lands the MLA kernels. Loading a glm-dsa model works; running it panics with THIS message
425/// instead of garbage math. Zero behavior change for Full/Linear arches (arm never taken).
426#[track_caller]
427pub(crate) fn mla_forward_unimplemented() -> ! {
428    panic!("Mixer::Mla has no forward arm yet — glm-dsa is loader-only in increment 2; \
429            the CUDA forward lands in increment 4 (research/mla-bringup-20260801/DESIGN.md §4)")
430}
431
432pub struct LinearAttnLayer {
433    pub wqkv: GpuTensor,       // [n_embd, conv_dim] -> qkv_mixed
434    pub wqkv_gate: GpuTensor,  // [n_embd, value_dim] -> z
435    pub ssm_beta: GpuTensor,   // [n_embd, num_v_heads]
436    pub ssm_alpha: GpuTensor,  // [n_embd, num_v_heads]
437    pub ssm_a: GpuTensor,      // [num_v_heads] (pre-negated -exp(A_log))
438    pub ssm_dt: GpuTensor,     // [num_v_heads] bias
439    pub ssm_conv1d: GpuTensor, // [d_conv, conv_dim]
440    pub ssm_norm: GpuTensor,   // [head_v_dim]
441    pub ssm_out: GpuTensor,    // [value_dim, n_embd]
442}
443
444pub enum Mixer {
445    Full(FullAttnLayer),
446    Linear(LinearAttnLayer),
447    /// glm-dsa MLA block (loader-only in increment 2; forward = increment 4).
448    Mla(MlaAttnLayer),
449}
450
451/// MoE weights for one layer. Router + shared expert stay GPU-RESIDENT (tiny); the routed
452/// experts stay HOST-RESIDENT (HostExps) and are staged per-token (EDGE-1).
453///
454/// The shared-expert fields are `Option`: qwen35moe carries a shared expert, but OLMoE (and most
455/// vanilla MoE) have none (`shared_expert_intermediate_size` absent) — those layers `load_opt` the
456/// shexp tensors to `None` (ST-MOE-PLAN §1.3, §3.2). When `None` the shared-expert branch is skipped.
457pub struct MoeWeights {
458    pub gate_inp: GpuTensor, // F32 [n_embd, n_expert] router  (GPU resident, Float)
459    pub gate_inp_shexp: Option<GpuTensor>, // F32 [n_embd] 1-D shared gate dot (qwen35moe only)
460    /// DeepSeek-V3/MiniMax-M3 `e_score_correction_bias` [n_expert]: added to the sigmoid scores
461    /// for expert SELECTION only; the routing weights use the un-biased scores. Kept host-side —
462    /// routing's top-k is a host loop and this is n_expert floats.
463    pub exp_probs_b: Option<Vec<f32>>,
464    /// Original-width router mask for physically pruned expert overlays. Inactive ids never enter
465    /// top-k, so their absent weight files cannot be dispatched.
466    pub active_experts: Option<Vec<bool>>,
467    pub gate_exps: HostExps, // [n_embd, n_ff_exp, n_expert]   (HOST)
468    pub up_exps: HostExps,   // [n_embd, n_ff_exp, n_expert]   (HOST)
469    pub down_exps: HostExps, // [n_ff_exp, n_embd, n_expert] TRANSPOSED (HOST)
470    pub gate_shexp: Option<GpuTensor>,
471    pub up_shexp: Option<GpuTensor>,
472    pub down_shexp: Option<GpuTensor>,
473    /// FITS-VRAM RESIDENT EXPERTS (2026-07-06): when the WHOLE model's expert bytes fit the VRAM
474    /// budget, each (proj) slab is uploaded once as a contiguous device buffer and the fused
475    /// _dev kernels take base+ex*stride pointers — no SLRU, no dispatch, no residency checks
476    /// (llama's full-offload regime; measured 169.55 vs memra's cache path 28.5 on the local 35B).
477    /// None => the SLRU host-expert machinery (the spill regime, where it WINS vs llama's
478    /// CPU-offload degradation). Decided at load in `load_ffn` (MEMRA_MOE_RESIDENT=0 forces off).
479    pub dev_exps: Option<DevExps>,
480    /// Per-expert post-matmul macro-scales on DEVICE: [3*n_expert] f32 in (gate, up, down)
481    /// order — all 1.0 unless the checkpoint carries compressed-tensors NVFP4 global scales
482    /// (unsloth qwen3.6 class). The _dev gate_up epilogues multiply unconditionally (x*1.0f
483    /// is bit-exact — zero change for macro-free artifacts); the down fold is one
484    /// moe_w_scale_by_expert launch gated on `has_macros`.
485    pub dev_macros: cudarc::driver::CudaSlice<f32>,
486    pub has_macros: bool,
487}
488
489impl MoeWeights {
490    #[inline]
491    pub fn has_uniform_expert_layout(&self) -> bool {
492        self.gate_exps.is_uniform_layout()
493            && self.up_exps.is_uniform_layout()
494            && self.down_exps.is_uniform_layout()
495    }
496}
497
498/// Device-resident expert slabs for one layer (gate/up/down) + the prebuilt [3, n_expert]
499/// pointer row the _dev kernels consume.
500pub struct DevExps {
501    pub gate: CudaSlice<u8>,
502    pub up: CudaSlice<u8>,
503    pub down: CudaSlice<u8>,
504    /// [3*n_expert] u64 device row: gate ptrs, up ptrs, down ptrs (proj-major like layer_dev_row).
505    pub ptr_row: CudaSlice<u64>,
506    /// WALL-GAP ARC (MEMRA_MOE_GU_IL=1): gate/up rows INTERLEAVED in one slab — row o of gate at
507    /// base + o*(rb_g+rb_u), up at +rb_g. Consumers on the dev path must use (rb_g+rb_u) as the
508    /// row stride for BOTH projections (see MoeWeights::dev_rb_gu). One contiguous 1760B stream
509    /// per (expert,row) instead of two scattered 880B streams — the measured 56%-of-wall fix
510    /// candidate. Kernels unchanged (stride is already a parameter everywhere).
511    pub gu_il: bool,
512}
513
514/// Per-layer FFN: dense SwiGLU (qwen35) or 256-expert MoE (qwen35moe).
515pub enum Ffn {
516    Dense {
517        ffn_gate: GpuTensor,
518        ffn_up: GpuTensor,
519        ffn_down: GpuTensor,
520    },
521    Moe(MoeWeights),
522}
523
524pub struct HybridLayer {
525    pub attn_norm: GpuTensor,
526    pub post_attn_norm: GpuTensor, // "post_attention_norm" = PRE-FFN norm
527    pub mixer: Mixer,
528    pub ffn: Ffn,
529    pub gemma4: Option<Gemma4LayerBits>,
530}
531
532/// Gemma-4 per-layer extras (R8 wiring, HANDOVER "R8 VERIFIED WIRING"): the parallel shared
533/// FFN branch, the four extra norms, the router prologue scale vector, per-expert output
534/// scales, and the layer output scalar.
535pub struct Gemma4LayerBits {
536    pub ffn_norm: GpuTensor, // ffn pre-norm (dense: THE ffn norm; moe: shared branch)
537    pub post_ffw_norm: GpuTensor, // combined post (before the attn_out residual)
538    /// MoE-layer extras (None on the dense gemma4 variants — 31B/E4B): the parallel shared
539    /// branch norms + tensors, the router prologue vector, per-expert output scales.
540    pub moe_bits: Option<Gemma4MoeBits>,
541    pub layer_scale: f32, // layer_output_scale [1]
542    /// E4B extras (None on 26B/31B): the per-layer-embedding tail block + KV-share target.
543    pub e4b: Option<Gemma4E4bLayer>,
544}
545
546/// gemma-4 E4B per-layer bits (see research/gemma4-bringup/e4b-arch-map.md):
547/// tail block  cur += rms_norm(proj . (gelu(inp_gate . cur) * inp_pl[il]), post_norm)
548/// and the KV-share map — layers il >= n_layer-shared_kv_layers have NO own k/v projections
549/// and attend the cache of layer (n_layer-shared) - (swa ? 2 : 1) with their own Q.
550pub struct Gemma4E4bLayer {
551    pub inp_gate: GpuTensor,           // blk.N.inp_gate  [n_embd, n_epl]
552    pub proj: GpuTensor,               // blk.N.proj      [n_epl, n_embd]
553    pub post_norm: GpuTensor,          // blk.N.post_norm [n_embd]
554    /// wave-4b: wq|wk|wv concatenated along OUT (one Q4_0 matvec at t=1 instead of the
555    /// fused3 3-subgrid launch). Built at the mirror hook from the GPU byte planes (rows
556    /// are independent in Q4_0, so an out-dim concat is a byte concat); own-KV layers only.
557    pub qkv_cat: Option<GpuTensor>,
558    /// Some(target_layer) on KV-shared layers (wk/wv here are the TARGET layer's tensors,
559    /// loaded for shape symmetry only — the forward must skip k/v compute + append and read
560    /// the target's cache; TODO dedupe the duplicate weight upload ~63MB).
561    pub kv_share: Option<u32>,
562}
563
564/// gemma-4 E4B model-level per-layer-embedding tensors (prologue inputs). The token table
565/// stays HOST-side raw GGUF bytes at load (Q6_K [n_epl*n_layer, n_vocab], ~2.3GB VRAM when
566/// uploaded — the forward arc decides resident-vs-gather placement).
567pub struct Gemma4E4bModel {
568    /// device copy of the per-layer token table, uploaded on first use (the 26B embd_gpu
569    /// pattern — keeps the ~2.3GB off load-critical paths that never decode).
570    pub tok_tbl_gpu: std::sync::OnceLock<CudaSlice<u8>>,
571    pub tok_embd_bytes: Vec<u8>,
572    pub tok_embd_qt: i32,
573    pub tok_embd_row_bytes: usize,
574    pub model_proj: GpuTensor, // per_layer_model_proj [n_embd, n_epl*n_layer] F16
575    pub proj_norm: GpuTensor,  // per_layer_proj_norm [n_epl]
576    pub n_epl: usize,
577}
578
579pub struct Gemma4MoeBits {
580    pub post_ffw_norm_1: GpuTensor, // shared-branch post
581    pub pre_ffw_norm_2: GpuTensor,  // moe-branch pre
582    pub post_ffw_norm_2: GpuTensor, // moe-branch post
583    pub shared_gate: GpuTensor,
584    pub shared_up: GpuTensor,
585    pub shared_down: GpuTensor,
586    /// ffn_gate_inp.scale [n_embd] PRE-multiplied by 1/sqrt(n_embd) at load: the router
587    /// prologue (weightless rms_norm x 1/sqrt(n_embd) x scale-vec) collapses to ONE rms_norm
588    /// with this as the norm weight (x_hat * (v*s) vs llama's (x_hat*s)*v — one reassociation;
589    /// the argmax gate arbitrates).
590    pub router_scale_pre: CudaSlice<f32>,
591    pub per_expert_scale: Vec<f32>, // ffn_down_exps.scale [n_expert] (host)
592    pub per_expert_scale_d: CudaSlice<f32>, // device copy (router-weight fold kernel)
593}
594
595/// Qwen3.5 NextN/MTP head: a full transformer block (attn+FFN, same tensors as a trunk layer)
596/// plus the MTP glue (enorm/hnorm/eh_proj that fold the next-token embedding into the trunk
597/// hidden, and an optional shared_head_norm/head). Loaded from blk.{n_trunk}.* — the block the
598/// trunk loop drops. Used for speculative decode (drafts 1 token per call). See research/mtp/MTP-PLAN.md.
599pub struct MtpHead {
600    pub enorm: GpuTensor, // blk.N.nextn.enorm   — RMSNorm of the next-token embedding
601    pub hnorm: GpuTensor, // blk.N.nextn.hnorm   — RMSNorm of the trunk hidden
602    pub eh_proj: GpuTensor, // blk.N.nextn.eh_proj [2*n_embd, n_embd]: [e_norm; h_norm] -> n_embd
603    pub attn_norm: GpuTensor, // blk.N.attn_norm
604    pub post_attn_norm: GpuTensor, // blk.N.post_attention_norm (pre-FFN)
605    pub mixer: Mixer,     // full-attn block (qwen35 MTP block is full-attn)
606    pub ffn: Ffn,         // Dense or Moe, same loader as trunk
607    pub shared_head_norm: Option<GpuTensor>, // blk.N.nextn.shared_head_norm (else reuse output_norm)
608    pub shared_head_head: Option<GpuTensor>, // blk.N.nextn.shared_head      (else reuse output)
609    /// FR-Spec draft->target vocab map: the draft lm_head is TRIMMED to the highest-frequency
610    /// tokens (e.g. 32768 rows of the full 248320-row head); `d2t[draft_idx]` = the target vocab
611    /// token id of trimmed row `draft_idx`. `None` for a full-vocab head (identity map). Host-side:
612    /// the draft argmax already lands on host as one u32, so the map is a single Vec index.
613    pub d2t: Option<Vec<u32>>,
614    /// DISTILLED-STUDENT geometry (None = the natural NextN block at trunk shape). A distilled
615    /// draft (StudentSV) runs the same block structure at a narrower inner width with fewer
616    /// heads, then up-projects back to n_embd (`out_up`) — the chain carrier and the head input
617    /// stay at n_embd, so the trunk/verify interface is unchanged. Selected by the presence of
618    /// `blk.N.nextn.out_up.weight` in a MEMRA_MTP_DRAFT file.
619    pub geom: Option<DraftGeom>,
620}
621
622/// Draft-head geometry override for a distilled (narrower) student block.
623pub struct DraftGeom {
624    pub d_inner: usize, // block inner width (eh_proj out / attn / ffn), e.g. 2048
625    pub n_head: usize,  // draft attention heads (head_dim = main head_dim)
626    pub n_head_kv: usize,
627    pub out_up: GpuTensor, // [d_inner -> n_embd]: carrier + head input up-projection
628}
629
630impl MtpHead {
631    /// Load an MTP/NextN head from a STANDALONE draft GGUF (MEMRA_MTP_DRAFT override). The draft
632    /// file carries ONLY the NextN block (blk.N.nextn.* glue + attn/ffn) plus its own lm_head
633    /// (`output.weight`) — which for an FR-Spec draft is TRIMMED to the top-frequency rows, with
634    /// a `d2t` (i32/i64) tensor mapping trimmed-row index -> target vocab token id. Draft-token
635    /// embedding still uses the MAIN model's token_embd (identical weights, saves VRAM), so the
636    /// draft file's full-vocab token_embd copy is ignored.
637    pub fn load_draft(
638        e: &Engine,
639        g: &GgufFile,
640        main_cfg: &ModelConfig,
641    ) -> Result<Self, Box<dyn std::error::Error>> {
642        let src = GgufSource(g);
643        let dcfg = src.config();
644        // NextN block index INSIDE THE DRAFT FILE (its block_count includes the trunk numbering).
645        // Graceful error, not assert: the server's `+draft` attach path surfaces this to the
646        // user (a gemma-assistant draft or any non-NextN GGUF lands here; a panic killed the
647        // whole worker — serve-smoke find, 2026-07-30).
648        if dcfg.nextn_predict_layers == 0 {
649            return Err(format!(
650                "draft GGUF has no nextn_predict_layers (arch {:?}) — not a NextN/MTP regime \
651                 draft; gemma assistant drafters attach via MEMRA_DRAFT, not '+draft'",
652                g.arch()).into());
653        }
654        let n = dcfg.n_layer - dcfg.nextn_predict_layers;
655        let p = |s: &str| format!("blk.{n}.{s}");
656
657        // Distilled student (narrow block + out_up) vs natural NextN clone. The interface dims
658        // (n_embd in/out, head_dim for the shared rope kernel) must match the main model; a
659        // student may shrink the inner width and head counts.
660        let student = src.has(&p("nextn.out_up.weight"));
661        assert_eq!(dcfg.n_embd, main_cfg.n_embd, "draft n_embd != model n_embd");
662        assert_eq!(
663            dcfg.head_dim_k, main_cfg.head_dim_k,
664            "draft head_dim != model head_dim"
665        );
666        if !student {
667            // The head forward runs with the MAIN model's cfg — the draft block must be the
668            // same shape or the forward is garbage.
669            assert_eq!(dcfg.n_head, main_cfg.n_head, "draft n_head != model n_head");
670            assert_eq!(
671                dcfg.n_head_kv, main_cfg.n_head_kv,
672                "draft n_head_kv != model n_head_kv"
673            );
674        }
675
676        // Draft lm_head: the file's own output.weight (+ shared_head_norm / output_norm). For
677        // FR-Spec this is [n_embd, draft_vocab] with draft_vocab << n_vocab.
678        let head = load_t(e, &src, "output.weight")?;
679        let head_norm = match load_opt(e, &src, &p("nextn.shared_head_norm.weight"))? {
680            Some(t) => Some(t),
681            None => load_opt(e, &src, "output_norm.weight")?,
682        };
683
684        // d2t: draft-row -> target-token-id map (absolute ids, verified against the tokenizer).
685        let d2t: Option<Vec<u32>> = g.find("d2t").map(|t| {
686            let bytes = g.tensor_data(t);
687            match t.ggml_type {
688                GgmlType::I32 => bytes
689                    .chunks_exact(4)
690                    .map(|c| i32::from_le_bytes(c.try_into().unwrap()) as u32)
691                    .collect(),
692                GgmlType::I64 => bytes
693                    .chunks_exact(8)
694                    .map(|c| i64::from_le_bytes(c.try_into().unwrap()) as u32)
695                    .collect(),
696                other => panic!("d2t must be I32/I64, got {other:?}"),
697            }
698        });
699        if let Some(map) = &d2t {
700            assert_eq!(
701                map.len(),
702                head.out_features(),
703                "d2t len {} != draft head rows {}",
704                map.len(),
705                head.out_features()
706            );
707            let n_vocab = main_cfg.n_vocab as u64;
708            assert!(
709                map.iter().all(|&t| (t as u64) < n_vocab),
710                "d2t contains token id >= model n_vocab {n_vocab}"
711            );
712        }
713        let eh_proj = load_t(e, &src, &p("nextn.eh_proj.weight"))?;
714        // defensive load gates (review feedback): a malformed student gguf fails HERE with a
715        // named assert, not later as garbage drafts. eh_proj consumes concat(e_norm, h_norm).
716        assert_eq!(
717            eh_proj.in_features(),
718            2 * main_cfg.n_embd as usize,
719            "eh_proj in dim != 2*n_embd"
720        );
721        let geom = if student {
722            let out_up = load_t(e, &src, &p("nextn.out_up.weight"))?;
723            let d_inner = eh_proj.out_features();
724            assert_eq!(
725                out_up.out_features(),
726                main_cfg.n_embd as usize,
727                "out_up out dim != n_embd"
728            );
729            assert_eq!(
730                out_up.in_features(),
731                d_inner,
732                "out_up in dim != eh_proj out dim (d_inner)"
733            );
734            assert!(
735                dcfg.n_head >= 1 && dcfg.n_head_kv >= 1 && dcfg.n_head % dcfg.n_head_kv == 0,
736                "student head counts malformed ({}/{})",
737                dcfg.n_head,
738                dcfg.n_head_kv
739            );
740            Some(DraftGeom {
741                d_inner,
742                n_head: dcfg.n_head as usize,
743                n_head_kv: dcfg.n_head_kv as usize,
744                out_up,
745            })
746        } else {
747            None
748        };
749        eprintln!(
750            "[mtp-draft] external draft head: blk.{n}, head_vocab={}{}{}",
751            head.out_features(),
752            if d2t.is_some() {
753                " (trimmed, d2t map)"
754            } else {
755                " (full)"
756            },
757            match &geom {
758                Some(g) => format!(
759                    " (student d_inner={} heads={}/{})",
760                    g.d_inner, g.n_head, g.n_head_kv
761                ),
762                None => String::new(),
763            }
764        );
765
766        Ok(MtpHead {
767            enorm: load_t(e, &src, &p("nextn.enorm.weight"))?,
768            hnorm: load_t(e, &src, &p("nextn.hnorm.weight"))?,
769            eh_proj,
770            attn_norm: load_t(e, &src, &p("attn_norm.weight"))?,
771            post_attn_norm: load_opt(e, &src, &p("post_attention_norm.weight"))?
772                .or(load_opt(e, &src, &p("ffn_norm.weight"))?)
773                .expect("draft NextN block needs post_attention_norm or ffn_norm"),
774            mixer: load_mixer_kind(e, &src, n, LayerKind::FullAttention, dcfg.mla.as_ref())?,
775            ffn: load_ffn(e, &src, &dcfg, n, None)?,
776            shared_head_norm: head_norm,
777            shared_head_head: Some(head),
778            d2t,
779            geom,
780        })
781    }
782}
783
784/// gemma4 model-level auxiliaries.
785pub struct GemmaAux {
786    /// rope_freqs.weight [hd_global/2] freq factors — global layers' RoPE (R9).
787    pub rope_freqs: Option<CudaSlice<f32>>,
788    /// all-ones norm weight [512] (max head_dim) — the weightless rms_norms (R7 V-norm).
789    pub ones: CudaSlice<f32>,
790    /// tokenizer suppress_tokens uploaded once (None when the model ships none) — masked to
791    /// -inf on every logits row before argmax/sampling (12B QAT ships two control ids).
792    pub suppress_d: Option<(CudaSlice<i32>, usize)>,
793    /// E4B per-layer-embedding model tensors (None on 26B/31B).
794    pub e4b: Option<Gemma4E4bModel>,
795}
796
797pub struct HybridModel {
798    pub cfg: ModelConfig,
799    pub embd: EmbedHost,
800    pub output_norm: GpuTensor,
801    pub output: GpuTensor,
802    pub layers: Vec<HybridLayer>,
803    pub mtp: Option<MtpHead>, // NextN spec-decode head (None if nextn_predict_layers == 0)
804    /// Lazily-uploaded DEVICE copy of the raw embed table (spec/graph hot loops gather rows
805    /// on-device instead of host-dequant + htod). ~0.5GB; uploaded once on first use.
806    pub embd_gpu: std::sync::OnceLock<cudarc::driver::CudaSlice<u8>>,
807    pub gemma4_aux: Option<GemmaAux>,
808    /// PRIME ACTIVATION SLABS (piecewise-graph foundation, 2026-07-26): the layer loop's
809    /// seven trunk transients live in RESIDENT per-model buffers instead of per-call pool
810    /// allocs — kills ~224 alloc/free API calls per prime AND freezes the Lt GEMM operand
811    /// addresses (nvjet's alignment-variant kernels become run-to-run stable once their
812    /// pointers stop moving). Sized on first prime to the largest T seen; Mutex = lazy init
813    /// only (single GPU worker).
814    pub prime_slabs: std::sync::Mutex<Option<crate::hybrid_forward::PrimeSlabs>>,
815}
816
817impl HybridModel {
818    /// Load a hybrid (qwen35) model from GGUF. Thin byte-identical wrapper over `load_from_source`.
819    pub fn load(e: &Engine, g: &GgufFile) -> Result<Self, Box<dyn std::error::Error>> {
820        Self::load_from_source(e, &GgufSource(g))
821    }
822
823    /// Plain-generation loader. `run-gen` never calls the optional draft head, so avoid loading
824    /// its weights and expert bank while preserving the model config and all trunk semantics.
825    pub fn load_without_mtp(e: &Engine, g: &GgufFile) -> Result<Self, Box<dyn std::error::Error>> {
826        Self::load_from_source_impl(e, &GgufSource(g), false)
827    }
828
829    /// Load a hybrid model from any `TensorSource` (GGUF or a safetensors HF checkpoint). The whole
830    /// loop speaks ggml names; the source maps them (and, for safetensors, applies the SSM value
831    /// transforms via the owned-buffer seam). The forward graph is untouched.
832    pub fn load_from_source(
833        e: &Engine,
834        src: &dyn TensorSource,
835    ) -> Result<Self, Box<dyn std::error::Error>> {
836        Self::load_from_source_impl(e, src, true)
837    }
838
839    /// Source-backed twin of `load_without_mtp`, used by the safetensors/repack `run-gen` path.
840    pub fn load_from_source_without_mtp(
841        e: &Engine,
842        src: &dyn TensorSource,
843    ) -> Result<Self, Box<dyn std::error::Error>> {
844        Self::load_from_source_impl(e, src, false)
845    }
846
847    fn load_from_source_impl(
848        e: &Engine,
849        src: &dyn TensorSource,
850        load_mtp: bool,
851    ) -> Result<Self, Box<dyn std::error::Error>> {
852        let cfg = src.config();
853        assert!(cfg.arch.is_hybrid(), "not a hybrid arch");
854        // SPEC-SERVING stream-k key, per model, set at LOAD so it governs the PRIME too
855        // (2026-07-27; explicit MEMRA_MMQ_SK wins): the sk autotune's per-process kernel
856        // coin flips knife-edge prime shapes between kernels run-to-run — the 12B depth
857        // spec cell was BIMODAL (205 @ 0.756 / 260 @ 0.943 identical invocations; tiling
858        // x6 = stable 263-269 @ 0.953, chat +3%; 31B neutral). The 26B is opposite: its
859        // drafter accepts BETTER under sk's fold order (depth 328 @ 0.826 vs 293 @ 0.750).
860        // Big dense (n_embd >= 3500) forces tiling under spec intent; MoE/small keep sk.
861        // An earlier attempt set this in generate_spec_gemma — too late, the prime's
862        // GEMMs had already autotuned.
863        if std::env::var("MEMRA_DRAFT").is_ok() && std::env::var("MEMRA_MMQ_SK").is_err() {
864            let force = if cfg.n_embd >= 3500 { 0i8 } else { -1i8 };
865            crate::MMQ_SK_FORCE.store(force, std::sync::atomic::Ordering::Relaxed);
866        }
867        // FP8-KV door: OFF for every hybrid-path model (35B: fp8 format-gates its v3
868        // dp4a lane, −2% measured 2026-07-12; gemma keys its KV formats independently
869        // of this flag). The 9B dense loader is the only ON site.
870        crate::KV_FP8_FORCE.store(0, std::sync::atomic::Ordering::Relaxed);
871
872        // B0 FIX (hoisted): cfg.n_layer == block_count INCLUDES the MTP/NextN block(s)
873        // (41 for the 35B-MoE); the trunk is n_layer - nextn. Computed before any tensor
874        // upload because the M2 sharded loader (crate::pp::layer_engine) places tensors
875        // by the trunk stage map.
876        let n_trunk = (cfg.n_layer - cfg.nextn_predict_layers) as usize;
877        let embd = EmbedHost::from_source(src, "token_embd.weight");
878        // M2 increment 2 (weight sharding): output_norm + lm head upload through the LAST
879        // stage's engine — the stage that runs them (outside the pp door / MEMRA_PP_SHARD=0
880        // this is the primary engine, byte-identical to the M1 loader).
881        let e_head = crate::pp::layer_engine(e, n_trunk, n_trunk - 1)?;
882        let output_norm = load_t(e_head, src, "output_norm.weight")?;
883        // tied embeddings: fall back to tok_embd if output.weight absent.
884        let mut output = if src.has("output.weight") {
885            load_t(e_head, src, "output.weight")?
886        } else {
887            load_t(e_head, src, "token_embd.weight")?
888        };
889
890        // SPILLING-PLAN §2: build the tiered-spill context ONCE, before loading any experts, but
891        // only for a MoE model with the disk tier forced on (`MEMRA_SPILL_DISK`). It probes free VRAM
892        // + host RAM at runtime (never hardcoded) and opens one shared GGUF mmap; all expert tensors
893        // draw down its single pinned-RAM budget (hottest pinned, the rest mmap'd from disk). When
894        // unset/dense this stays `None` and the load takes the byte-identical all-host path.
895        // Disk spill is GGUF-only (needs the on-disk file mmap); src.gguf() is None for safetensors.
896        let gguf: Option<&GgufFile> = src.gguf();
897        // expert_count > 0: Arch::Gemma4 carries cfg.moe = Some on its DENSE variants too
898        // (the 2026-07-14 discriminator-bug class) — a dense 31B/E4B under the spill env
899        // would otherwise probe budgets + open an expert mmap it never consumes.
900        let mut spill: Option<crate::spill::SpillCtx> =
901            if cfg.moe.as_ref().is_some_and(|m| m.expert_count > 0)
902                && crate::spill::disk_tier_enabled() && gguf.is_some() {
903                let budget = crate::spill::MemBudget::probe(e)?;
904                let ctx = crate::spill::SpillCtx::open(gguf.unwrap(), &budget)?;
905                eprintln!("[spill] disk tier ON: free_vram={} MiB  pinnable_ram={} MiB (MemAvailable*frac)",
906                          budget.free_vram >> 20, budget.free_pinnable_ram >> 20);
907                Some(ctx)
908            } else { None };
909
910        // Running the MTP block as a trunk layer is wrong; iterate only the trunk layers
911        // (n_trunk hoisted above). 9B (nextn=0): n_trunk = 32. 35B-MoE (nextn=1): 40.
912        let mut layers = Vec::with_capacity(n_trunk);
913        for il in 0..n_trunk as u32 {
914            let p = |s: &str| format!("blk.{il}.{s}");
915            // M2 weight sharding: this layer's tensors upload through the OWNING stage's
916            // engine (shadowed `e`) — the bring-up remote peer-read placement dies here.
917            // Door shut / MEMRA_PP_SHARD=0: `layer_engine` returns the primary (no change).
918            let e = crate::pp::layer_engine(e, n_trunk, il as usize)?;
919            // attn_norm always; post_attention_norm is the pre-FFN norm in qwen35
920            layers.push(HybridLayer {
921                attn_norm: load_t(e, src, &p("attn_norm.weight"))?,
922                post_attn_norm: load_opt(e, src, &p("post_attention_norm.weight"))?
923                    .or(load_opt(e, src, &p("ffn_norm.weight"))?)
924                    .expect("need post_attention_norm or ffn_norm"),
925                mixer: {
926                    // E4B KV-shared layers ship NO attn_k/attn_v — load the SHARE TARGET's
927                    // k/v tensors for shape symmetry (forward skips k/v compute there and
928                    // reads the target layer's cache; see Gemma4E4bLayer::kv_share).
929                    let g4_shared = cfg.gemma4.as_ref().map(|g| g.shared_kv_layers).unwrap_or(0);
930                    let kv_from = n_trunk as u32 - g4_shared;
931                    if g4_shared > 0
932                        && il >= kv_from
933                        && !src.has(&format!("blk.{il}.attn_k.weight"))
934                    {
935                        let g4 = cfg.gemma4.as_ref().unwrap();
936                        let swa = g4.swa_pattern.get(il as usize).copied().unwrap_or(true);
937                        let tgt = kv_from - if swa { 2 } else { 1 };
938                        let tp = |s: &str| format!("blk.{tgt}.{s}");
939                        Mixer::Full(FullAttnLayer {
940                            wq: load_t(e, src, &p("attn_q.weight"))?,
941                            wk: load_t(e, src, &tp("attn_k.weight"))?,
942                            wv: load_t(e, src, &tp("attn_v.weight"))?,
943                            wo: load_t(e, src, &p("attn_output.weight"))?,
944                            q_norm: load_t(e, src, &p("attn_q_norm.weight"))?,
945                            k_norm: load_t(e, src, &tp("attn_k_norm.weight"))?,
946                        })
947                    } else {
948                        load_mixer_kind(e, src, il, cfg.layer_kind(il), cfg.mla.as_ref())?
949                    }
950                },
951                ffn: load_ffn(e, src, &cfg, il, spill.as_mut().map(|c| (gguf.unwrap(), c)))?,
952                gemma4: if cfg.gemma4.is_some() {
953                    let scalar = |n: &str| -> f32 {
954                        let t = src.find(&p(n)).unwrap_or_else(|| panic!("missing {n}"));
955                        memra_gguf::dequant::dequantize(t.ggml_type, &t.bytes, 1)[0]
956                    };
957                    let vecf = |n: &str| -> Vec<f32> {
958                        let t = src.find(&p(n)).unwrap_or_else(|| panic!("missing {n}"));
959                        memra_gguf::dequant::dequantize(
960                            t.ggml_type,
961                            &t.bytes,
962                            t.ne.iter().product::<u64>() as usize,
963                        )
964                    };
965                    let moe_bits = if src.find(&p("ffn_gate_inp.scale")).is_some() {
966                        Some(crate::hybrid::Gemma4MoeBits {
967                            post_ffw_norm_1: load_t(e, src, &p("post_ffw_norm_1.weight"))?,
968                            pre_ffw_norm_2: load_t(e, src, &p("pre_ffw_norm_2.weight"))?,
969                            post_ffw_norm_2: load_t(e, src, &p("post_ffw_norm_2.weight"))?,
970                            shared_gate: load_t(e, src, &p("ffn_gate.weight"))?,
971                            shared_up: load_t(e, src, &p("ffn_up.weight"))?,
972                            shared_down: load_t(e, src, &p("ffn_down.weight"))?,
973                            router_scale_pre: {
974                                let inv = 1.0 / (cfg.n_embd as f32).sqrt();
975                                let v: Vec<f32> =
976                                    vecf("ffn_gate_inp.scale").iter().map(|x| x * inv).collect();
977                                e.htod(&v)?
978                            },
979                            per_expert_scale: vecf("ffn_down_exps.scale"),
980                            per_expert_scale_d: e.htod(&vecf("ffn_down_exps.scale"))?,
981                        })
982                    } else {
983                        None
984                    };
985                    // E4B extras (tensor-presence: blk.N.inp_gate only exists on E4B)
986                    let e4b = if src.has(&p("inp_gate.weight")) {
987                        let g4 = cfg.gemma4.as_ref().unwrap();
988                        let kv_from = n_trunk as u32 - g4.shared_kv_layers;
989                        let kv_share = if g4.shared_kv_layers > 0 && il >= kv_from {
990                            let swa = g4.swa_pattern.get(il as usize).copied().unwrap_or(true);
991                            Some(kv_from - if swa { 2 } else { 1 })
992                        } else {
993                            None
994                        };
995                        Some(crate::hybrid::Gemma4E4bLayer {
996                            inp_gate: load_t(e, src, &p("inp_gate.weight"))?,
997                            proj: load_t(e, src, &p("proj.weight"))?,
998                            post_norm: load_t(e, src, &p("post_norm.weight"))?,
999                            kv_share,
1000                            qkv_cat: None,   // built at the mirror hook (wave 4b)
1001                        })
1002                    } else {
1003                        None
1004                    };
1005                    Some(Gemma4LayerBits {
1006                        ffn_norm: load_t(e, src, &p("ffn_norm.weight"))?,
1007                        post_ffw_norm: load_t(e, src, &p("post_ffw_norm.weight"))?,
1008                        moe_bits,
1009                        layer_scale: scalar("layer_output_scale.weight"),
1010                        e4b,
1011                    })
1012                } else {
1013                    None
1014                },
1015            });
1016        }
1017
1018        // MTP/NextN head: load the block the trunk loop drops (il = n_trunk). It is a full
1019        // transformer block PLUS the nextn.{enorm,hnorm,eh_proj} glue. Only when nextn>0 and the
1020        // eh_proj tensor actually exists in the file (some MTP GGUFs ship the draft separately).
1021        let mtp = if load_mtp && cfg.nextn_predict_layers > 0 {
1022            let n = n_trunk as u32;
1023            let p = |s: &str| format!("blk.{n}.{s}");
1024            match src.has(&p("nextn.eh_proj.weight")) {
1025                true => Some(MtpHead {
1026                    enorm: load_t(e, src, &p("nextn.enorm.weight"))?,
1027                    hnorm: load_t(e, src, &p("nextn.hnorm.weight"))?,
1028                    eh_proj: load_t(e, src, &p("nextn.eh_proj.weight"))?,
1029                    attn_norm: load_t(e, src, &p("attn_norm.weight"))?,
1030                    post_attn_norm: load_opt(e, src, &p("post_attention_norm.weight"))?
1031                        .or(load_opt(e, src, &p("ffn_norm.weight"))?)
1032                        .expect("MTP block needs post_attention_norm or ffn_norm"),
1033                    mixer: load_mixer_kind(e, src, n, LayerKind::FullAttention, cfg.mla.as_ref())?,
1034                    ffn: load_ffn(e, src, &cfg, n, spill.as_mut().map(|c| (gguf.unwrap(), c)))?,
1035                    shared_head_norm: load_opt(e, src, &p("nextn.shared_head_norm.weight"))?,
1036                    shared_head_head: load_opt(e, src, &p("nextn.shared_head.weight"))?,
1037                    d2t: None,
1038                    geom: None,
1039                }),
1040                false => None, // nextn>0 but no embedded eh_proj (external draft GGUF) -> no head
1041            }
1042        } else {
1043            None
1044        };
1045
1046        // MEMRA_MTP_DRAFT=<path.gguf>: REPLACE the MTP head with one loaded from a standalone
1047        // draft GGUF (e.g. an FR-Spec trimmed-vocab draft). Verify-based spec decode stays exact
1048        // regardless of the draft — a different draft only changes WHICH tokens get proposed.
1049        let mtp = if load_mtp {
1050            match std::env::var("MEMRA_MTP_DRAFT") {
1051                Ok(path) if !path.is_empty() => {
1052                    eprintln!("[mtp-draft] loading external MTP draft: {path}");
1053                    let dg = GgufFile::open(&path)?;
1054                    Some(MtpHead::load_draft(e, &dg, &cfg)?)
1055                }
1056                _ => mtp,
1057            }
1058        } else {
1059            None
1060        };
1061
1062        // MEMRA_FRSPEC_TRIM=<frspec.gguf>: SELF-TRIMMED draft head. Reads ONLY the d2t ranked-token
1063        // list from the given file and gathers those rows from the MAIN model's own output.weight
1064        // bytes (quantized rows are independent — a byte-level row gather, zero requant). The MTP
1065        // block, norms, and head quant all stay main-model, so there is no cross-file quality
1066        // mismatch (the external Q4_K draft file measured -15pts acceptance vs the native block).
1067        // Draft lm_head reads drop vocab/32768-fold; verify stays full-vocab -> exactness unchanged.
1068        // FULL_PREC (MTP-heal ceiling): the self-trim gathers rows into `from_quant_bytes` (Quant
1069        // only) and, more to the point, the full-precision ceiling wants the model's NATURAL full
1070        // head — trimming the draft vocab is a speed lever, not part of the exactness measurement.
1071        // Disable trim under the flag (documented resolution, §item 2).
1072        let trim_env = if load_mtp {
1073            std::env::var("MEMRA_FRSPEC_TRIM")
1074        } else {
1075            Err(std::env::VarError::NotPresent)
1076        };
1077        if crate::model::full_prec_enabled()
1078            && trim_env.as_deref().map(|p| !p.is_empty()).unwrap_or(false)
1079        {
1080            eprintln!(
1081                "[frspec-trim] DISABLED under MEMRA_FULL_PREC — using the natural full MTP head"
1082            );
1083        }
1084        let mtp = match (
1085            if crate::model::full_prec_enabled() {
1086                Err(std::env::VarError::NotPresent)
1087            } else {
1088                trim_env
1089            },
1090            mtp,
1091        ) {
1092            (Ok(path), Some(mut head)) if !path.is_empty() => {
1093                let tg = GgufFile::open(&path)?;
1094                let d2t_t = tg
1095                    .find("d2t")
1096                    .expect("MEMRA_FRSPEC_TRIM file has no d2t tensor");
1097                let d2t_bytes = tg.tensor_data(d2t_t);
1098                let d2t: Vec<u32> = match d2t_t.ggml_type {
1099                    GgmlType::I32 => d2t_bytes
1100                        .chunks_exact(4)
1101                        .map(|c| i32::from_le_bytes(c.try_into().unwrap()) as u32)
1102                        .collect(),
1103                    GgmlType::I64 => d2t_bytes
1104                        .chunks_exact(8)
1105                        .map(|c| i64::from_le_bytes(c.try_into().unwrap()) as u32)
1106                        .collect(),
1107                    other => panic!("d2t must be I32/I64, got {other:?}"),
1108                };
1109                let v = src
1110                    .find("output.weight")
1111                    .or_else(|| src.find("token_embd.weight"))
1112                    .expect("model has no output.weight for FR-Spec trim");
1113                let out_f = v.ne[1] as usize;
1114                let row_bytes = v.bytes.len() / out_f;
1115                assert!(
1116                    d2t.iter().all(|&t| (t as usize) < out_f),
1117                    "d2t token id >= lm_head rows {out_f}"
1118                );
1119                let mut gathered = Vec::with_capacity(d2t.len() * row_bytes);
1120                for &t in &d2t {
1121                    let off = t as usize * row_bytes;
1122                    gathered.extend_from_slice(&v.bytes[off..off + row_bytes]);
1123                }
1124                let trimmed = GpuTensor::from_quant_bytes(
1125                    e,
1126                    &gathered,
1127                    v.ggml_type,
1128                    v.ne[0],
1129                    d2t.len() as u64,
1130                    /*nvfp4 macro-scale*/
1131                    match src.find("output.scale") {
1132                        Some(sv) => f32::from_le_bytes(sv.bytes[..4].try_into().unwrap()),
1133                        None => 1.0,
1134                    },
1135                )?;
1136                eprintln!(
1137                    "[frspec-trim] self-trimmed head: {} rows of main output.weight ({:?})",
1138                    d2t.len(),
1139                    v.ggml_type
1140                );
1141                head.shared_head_head = Some(trimmed);
1142                head.d2t = Some(d2t);
1143                Some(head)
1144            }
1145            (_, m) => m,
1146        };
1147
1148        if let Some(ctx) = spill.as_ref() {
1149            eprintln!(
1150                "[spill] experts placed: {} pinned (Tier 1), {} mmap'd from disk (Tier 2, {} MiB)",
1151                ctx.n_pinned,
1152                ctx.n_mmap,
1153                ctx.mmap_bytes >> 20
1154            );
1155        }
1156
1157        if cfg.gemma4.is_some() {
1158            // gemma4 fa-vec crossover default (measured sweep 2026-07-10; env overrides).
1159            crate::FA_VEC_MIN_DEFAULT.store(1, std::sync::atomic::Ordering::Relaxed);
1160            // windowed split per gemma variant (2026-07-12 sweeps): MoE 26B = 32 (grid-limited
1161            // t=1 under the raw-e4m3 sV ceiling), dense 31B = 64 (37.13 vs 36.87 at 1.7k, N=2).
1162            // DISCRIMINATOR FIX (2026-07-14): Arch::Gemma4 is in is_moe(), so cfg.moe is
1163            // Some (expert_count 0) on the DENSE 31B/E4B too — `cfg.moe.is_some()` keyed
1164            // every "per-variant" default to the 26B values and the dense arms of the
1165            // 2026-07-12 sweeps (SPW 64, SP512 32) never actually reached the 31B. Key on
1166            // expert_count instead.
1167            let real_moe = cfg.moe.as_ref().is_some_and(|m| m.expert_count > 0);
1168            crate::FA_SPW_DEFAULT.store(if real_moe { 32 } else { 64 },
1169                                        std::sync::atomic::Ordering::Relaxed);
1170            // hd512 global split per variant (26B=16 landed 2026-07-11; 31B=32 swept 2026-07-12).
1171            crate::FA_SP512_DEFAULT.store(if real_moe { 16 } else { 32 },
1172                                          std::sync::atomic::Ordering::Relaxed);
1173            // gemma4 router w8 RE-ARBITRATED 2026-08-01 (g26 decode dig): the 2026-07-31
1174            // knife-edge that stored false here was single-synthetic-prompt roulette — on 6
1175            // real prompts the w8 twin's gate outcome is IDENTICAL to the lone-warp form
1176            // (5 MATCH/5 MATCH; the one MISMATCH prompt fails both arms with the same
1177            // argmax pair, router-independent). w8 = +13% g26 decode (182->206 tok/s x3
1178            // interleaved, H100). Receipts: research/g26-decode-20260801/. gemma4 now rides
1179            // the global default (true); MEMRA_ROUTER_V2=0 is the rollback seam.
1180            // fused t=1 pair/triple mr1 per variant (2026-07-14 DRAM-duty arc: dense +1.1%
1181            // short / +0.6% depth on 31B; MoE 26B −1.2% — stays mr2).
1182            crate::FUSED_MR1_DEFAULT.store(!real_moe,
1183                                           std::sync::atomic::Ordering::Relaxed);
1184            // gemma4 rms_norm block 1024 (single-row 2816-col norms; battery-arbitrated per model).
1185            crate::RMS_BLOCK_DEFAULT.store(1024, std::sync::atomic::Ordering::Relaxed);
1186            // gemma4 fa split ladder (d1736 sweep; see fa_split_keys).
1187            crate::FA_SP_GEMMA.store(true, std::sync::atomic::Ordering::Relaxed);
1188            // depth fa: PARITY LAW (2026-07-10) — decode and verify share the rows_w/rows_dpl16
1189            // kernel symbols (decode t=1), so lane choice is freely tunable; v4 measured the
1190            // depth winner. Seams: MEMRA_FA_V4_MAX / MEMRA_FA_SMEM_TKV / MEMRA_GEMMA_ROWS_W.
1191        }
1192        // gemma4: the dc serving loop + spec draft gather read the device embed table every
1193        // step — upload it AT LOAD (OnceLock init) so first-use cost never lands in a timed span.
1194        let force_embd_gpu = cfg.gemma4.is_some();
1195        let gemma4_aux = if cfg.gemma4.is_some() {
1196            let rope_freqs = match src.find("rope_freqs.weight") {
1197                Some(t) => Some(e.htod(&memra_gguf::dequant::dequantize(
1198                    t.ggml_type,
1199                    &t.bytes,
1200                    t.ne.iter().product::<u64>() as usize,
1201                ))?),
1202                None => None,
1203            };
1204            // E4B per-layer-embedding model tensors (tensor-presence gated).
1205            let e4b = match src.find("per_layer_token_embd.weight") {
1206                Some(t) => {
1207                    let n_epl = cfg
1208                        .gemma4
1209                        .as_ref()
1210                        .map(|g| g.n_embd_per_layer as usize)
1211                        .unwrap_or(0);
1212                    let row = t.ne[0] as usize; // n_epl * n_layer
1213                    let row_bytes = t.bytes.len() / (t.ne[1] as usize);
1214                    eprintln!(
1215                        "[gemma4-e4b] per-layer-embed model detected (n_epl={n_epl}, row {row}) — \
1216                               first-light forward (eager decode + prime); dc/graph/spec unwired \
1217                               (HANDOVER-E4B.md)"
1218                    );
1219                    Some(crate::hybrid::Gemma4E4bModel {
1220                        tok_tbl_gpu: std::sync::OnceLock::new(),
1221                        tok_embd_bytes: t.bytes.to_vec(),
1222                        tok_embd_qt: match t.ggml_type {
1223                            memra_gguf::GgmlType::Q6_K => crate::QT_Q6_K,
1224                            memra_gguf::GgmlType::Q8_0 => crate::QT_Q8_0,
1225                            other => panic!("e4b per-layer tok embd: unhandled dtype {other:?}"),
1226                        },
1227                        tok_embd_row_bytes: row_bytes,
1228                        model_proj: load_t(e, src, "per_layer_model_proj.weight")?,
1229                        proj_norm: load_t(e, src, "per_layer_proj_norm.weight")?,
1230                        n_epl,
1231                    })
1232                }
1233                None => None,
1234            };
1235            let suppress_d = {
1236                let sup = &cfg.gemma4.as_ref().unwrap().suppress_tokens;
1237                if sup.is_empty() { None } else {
1238                    let ids: Vec<i32> = sup.iter().map(|&x| x as i32).collect();
1239                    eprintln!("[gemma4] suppress_tokens: {} ids masked at sampling", ids.len());
1240                    Some((e.htod_i32(&ids)?, ids.len()))
1241                }
1242            };
1243            Some(GemmaAux {
1244                rope_freqs,
1245                ones: e.htod(&[1.0f32; 512])?,
1246                suppress_d,
1247                e4b,
1248            })
1249        } else {
1250            None
1251        };
1252        let mut layers = layers;
1253        // Q8_0 SPLIT-PLANE DECODE MIRRORS (2026-07-26, the H100 lane): Q8_0-trunk models
1254        // (Qwen3.5-9B class) stream their whole weight mass through the 34B-stride GGUF
1255        // layout — ncu on H100 held Max Bandwidth at 41-46% (Mem Busy 66-76%) from sector
1256        // overfetch. Mirrors route the m<=16 mmvq/batched decode family to the aligned-16B
1257        // `_rp` twins (bit-identical). VRAM cost == the mirrored trunk (~model size), so
1258        // DEFAULT ON only on the Hopper lane (80GB); MEMRA_Q8RP=1/0 overrides either way.
1259        {
1260            let q8rp_on = match std::env::var("MEMRA_Q8RP").as_deref() {
1261                Ok("0") => false,
1262                Ok(_) => true,
1263                Err(_) => cfg!(memra_hopper_mma),
1264            };
1265            // K-quant split-plane mirrors (q4_K/q6_K, 2026-08-01 H100 coalescing fix) ride
1266            // the same trunk walk under their own seam (MEMRA_KQRP, default = hopper lane).
1267            let kqrp_on = crate::Engine::kqrp_enabled();
1268            if q8rp_on || kqrp_on {
1269                // f16 prefill mirrors, PER-MODEL argmax-gate arbitration (round 45): on the
1270                // qwen Q8_0 dense class the f16-prefill-vs-int8-decode gap (maxdiff ~0.67)
1271                // flips the run-gen argmax gate on real prompts (board-2048: 485 vs 332,
1272                // deterministic x5) — gate-violating defaults don't ship. gemma (Q4_0) and
1273                // the MoE hybrids hold MATCH on the same prompt and keep their mirrors.
1274                // MEMRA_PP_F16=1 forces (diagnostic seam); =0 still kills everywhere.
1275                let f16_model_ok = cfg.gemma4.is_some() || cfg.moe.is_some()
1276                    || std::env::var("MEMRA_PP_F16").as_deref() == Ok("1");
1277                let mut nmir = 0usize;
1278                // M2 weight sharding: mirrors are the DECODE weights on these paths — each
1279                // builds through its layer's OWNING stage engine (`e_ref` param), so the
1280                // mirror lands on the device that dereferences it.
1281                let mut mir = |e_ref: &crate::Engine, w: &mut crate::model::GpuTensor| -> Result<(), Box<dyn std::error::Error>> {
1282                    let before = matches!(w, crate::model::GpuTensor::Quant { rp4: Some(_), .. });
1283                    if q8rp_on { e_ref.build_q8_rp4(w)?; }
1284                    if kqrp_on {
1285                        e_ref.build_q4k_rp4(w)?;
1286                        e_ref.build_q6k_rp4(w)?;
1287                    }
1288                    // Q6_K mirrors are model-CLASS-agnostic (round 47): no MMQ arm exists for
1289                    // Q6_K — the fallback dequant-GEMM is ~10x the f16 lane (q27's prefill
1290                    // wall). The qwen-dense argmax-flip evidence (round 45) was the Q8_0
1291                    // mirror specifically; Q6_K admission is arbitrated by its own gate runs.
1292                    let q6k = matches!(w, crate::model::GpuTensor::Quant { qtype, .. }
1293                                       if *qtype == crate::QT_Q6_K);
1294                    if q8rp_on && crate::f16_ffi::pp_f16_enabled() && (f16_model_ok || q6k) {
1295                        e_ref.build_q8_f16(w)?;
1296                    }
1297                    if !before && matches!(w, crate::model::GpuTensor::Quant { rp4: Some(_), .. }) {
1298                        nmir += 1;
1299                    }
1300                    Ok(())
1301                };
1302                for (il, layer) in layers.iter_mut().enumerate() {
1303                    let el = crate::pp::layer_engine(e, n_trunk, il)?;
1304                    match &mut layer.mixer {
1305                        Mixer::Full(fa) => {
1306                            for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] { mir(el, w)?; }
1307                        }
1308                        Mixer::Linear(la) => {
1309                            for w in [&mut la.wqkv, &mut la.wqkv_gate, &mut la.ssm_beta,
1310                                      &mut la.ssm_alpha, &mut la.ssm_out] { mir(el, w)?; }
1311                        }
1312                        // MLA: no decode mirrors in increment 2 (its kernels arrive in inc 4;
1313                        // mirror admission is arbitrated there with measurements).
1314                        Mixer::Mla(_) => {}
1315                    }
1316                    if let Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &mut layer.ffn {
1317                        for w in [ffn_gate, ffn_up, ffn_down] { mir(el, w)?; }
1318                    }
1319                }
1320                mir(e_head, &mut output)?;
1321                if nmir > 0 {
1322                    eprintln!("[q8rp] split-plane decode mirrors built: {nmir} tensors");
1323                }
1324                // Q4_K f16 prefill mirrors (round 49): Q4_K joins the q6k carve-out —
1325                // model-class-agnostic admission, arbitrated by per-model argmax gates
1326                // (the round-45 flip evidence was the Q8_0 mirror on qwen-dense; the q27
1327                // Q4_K bulk rides mul_mat_q_q45k int8-MMA, which the Lt f16 lane beats at
1328                // large m — campaign-A precedent). SECOND pass over the trunk so the shared
1329                // MEMRA_PP_F16_BUDGET_MB keeps FULL Q6_K coverage as its floor: Q6_K mirrors
1330                // replace a ~10x dequant-GEMM (no MMQ arm exists), Q4_K mirrors upgrade a
1331                // working int8-MMA arm — a joint walk would evict late-layer Q6_K mirrors
1332                // for the weaker lever. Layer-order prefix within the Q4_K class.
1333                // Round 49b: Q5_K (q27's 48 ssm_out — the last mul_mat_q_q45k class) rides
1334                // a THIRD pass strictly after all Q4_K, so the default-budget composition
1335                // (and its banked gates) stays byte-identical: the 32GB default is exhausted
1336                // by the Q4_K pass; Q5_K mirrors only light up under a raised
1337                // MEMRA_PP_F16_BUDGET_MB (machine-specific config).
1338                if q8rp_on && crate::f16_ffi::pp_f16_enabled() {
1339                    for (want, tag) in [(crate::QT_Q4_K, "q4kf16"), (crate::QT_Q5_K, "q5kf16")] {
1340                        let (mut n4, mut b4) = (0usize, 0usize);
1341                        let mut mirk = |e_ref: &crate::Engine, w: &mut crate::model::GpuTensor|
1342                                       -> Result<(), Box<dyn std::error::Error>> {
1343                            if matches!(w, crate::model::GpuTensor::Quant { qtype, f16: None, .. }
1344                                        if *qtype == want) {
1345                                e_ref.build_q8_f16(w)?;
1346                                if let crate::model::GpuTensor::Quant { f16: Some(m), .. } = w {
1347                                    n4 += 1;
1348                                    b4 += m.len();
1349                                }
1350                            }
1351                            Ok(())
1352                        };
1353                        for (il, layer) in layers.iter_mut().enumerate() {
1354                            let el = crate::pp::layer_engine(e, n_trunk, il)?;
1355                            match &mut layer.mixer {
1356                                Mixer::Full(fa) => {
1357                                    for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] { mirk(el, w)?; }
1358                                }
1359                                Mixer::Linear(la) => {
1360                                    for w in [&mut la.wqkv, &mut la.wqkv_gate, &mut la.ssm_beta,
1361                                              &mut la.ssm_alpha, &mut la.ssm_out] { mirk(el, w)?; }
1362                                }
1363                                Mixer::Mla(_) => {} // no mirrors in increment 2 (see above)
1364                            }
1365                            if let Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &mut layer.ffn {
1366                                for w in [ffn_gate, ffn_up, ffn_down] { mirk(el, w)?; }
1367                            }
1368                        }
1369                        mirk(e_head, &mut output)?;
1370                        if n4 > 0 {
1371                            eprintln!("[{tag}] prefill fp16 mirrors built: {n4} tensors \
1372                                       ({} MB)", b4 >> 20);
1373                        }
1374                    }
1375                }
1376            }
1377        }
1378        // Q4_0 SPLIT-PLANE DECODE MIRRORS (2026-07-10, MEMRA_Q4RP seam): gemma-4 MoE-class trunk
1379        // (26B — attn wq/wk/wv/wo + the parallel shared FFN triple). The 18B GGUF block stride
1380        // costs ~25-35% decode bandwidth in sector overfetch (rp_q4_probe: m=1 1.34x, m=3 1.17x,
1381        // bitwise); the mirror (~0.7GB for the 26B) fixes the m<=8 mmvq/batched/fused family.
1382        // Dense 31B is NOT mirrored (its 15GB trunk mirror does not fit 24GB — the full layout
1383        // swap is the follow-up arc); raw bytes stay for prefill/gemm/Stage-A either way.
1384        if cfg.gemma4.is_some() && crate::Engine::q4rp_enabled() {
1385            let mut nmir = 0usize;
1386            for (il, layer) in layers.iter_mut().enumerate() {
1387                // M2 weight sharding: mirrors/concats build through the owning stage engine.
1388                let e = crate::pp::layer_engine(e, n_trunk, il)?;
1389                // 26B MoE-class trunk (moe_bits) OR the E4B dense trunk (e4b bits). E4B mirror
1390                // arithmetic: attn ~7.5MB/layer (shared layers skip wk/wv via build's no-op on
1391                // duplicate mirrors is NOT automatic — they alias the target's tensors as
1392                // separate GpuTensors, so their mirrors double ~1.5MB/shared-layer; acceptable)
1393                // + dense ffn 3 x 2560x10240 Q4_0 ~44MB + inp_gate/proj ~0.75MB => ~2.2GB for
1394                // the 5.2GB model; 24GB card holds model+mirror+KV with >14GB headroom.
1395                // Dense 31B stays unmirrored (15GB mirror does not fit) — its arm is the
1396                // layout-swap follow-up.
1397                let is_moe26 = layer.gemma4.as_ref().is_some_and(|g| g.moe_bits.is_some());
1398                let is_e4b = layer.gemma4.as_ref().is_some_and(|g| g.e4b.is_some());
1399                if !(is_moe26 || is_e4b) {
1400                    continue;
1401                }
1402                if let Mixer::Full(fa) = &mut layer.mixer {
1403                    for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] {
1404                        e.build_q4_rp4(w)?;
1405                        nmir += 1;
1406                    }
1407                }
1408                if is_e4b {
1409                    // wave-4b: own-KV layers get the wq|wk|wv OUT-concat (one matvec at t=1).
1410                    let own_kv = layer.gemma4.as_ref().unwrap().e4b.as_ref()
1411                        .is_some_and(|e4| e4.kv_share.is_none());
1412                    if own_kv {
1413                        if let Mixer::Full(fa) = &layer.mixer {
1414                            if let Some(mut cat) = e.build_q4_out_concat3(&fa.wq, &fa.wk, &fa.wv)? {
1415                                e.build_q4_rp4(&mut cat)?; nmir += 1;
1416                                layer.gemma4.as_mut().unwrap().e4b.as_mut().unwrap()
1417                                    .qkv_cat = Some(cat);
1418                            }
1419                        }
1420                    }
1421                    if let Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &mut layer.ffn {
1422                        for w in [ffn_gate, ffn_up, ffn_down] {
1423                            e.build_q4_rp4(w)?;
1424                            nmir += 1;
1425                        }
1426                    }
1427                    let e4 = layer.gemma4.as_mut().unwrap().e4b.as_mut().unwrap();
1428                    for w in [&mut e4.inp_gate, &mut e4.proj] {
1429                        e.build_q4_rp4(w)?;
1430                        nmir += 1;
1431                    }
1432                }
1433                if let Some(mb) = layer.gemma4.as_mut().unwrap().moe_bits.as_mut() {
1434                    for w in [&mut mb.shared_gate, &mut mb.shared_up, &mut mb.shared_down] {
1435                        e.build_q4_rp4(w)?;
1436                        nmir += 1;
1437                    }
1438                }
1439            }
1440            if nmir > 0 {
1441                eprintln!("[q4rp] split-plane decode mirrors built: {nmir} trunk tensors");
1442            }
1443            // DENSE gemma (31B / E4B trunks): the trunk is too big to MIRROR on 24GB, so the
1444            // split layout replaces the GGUF bytes IN PLACE (zero steady-state VRAM; the 31B
1445            // profile put 76% of decode on the non-rp q4_0 matvecs). Every consumer routes
1446            // off the tensor's rp flag: mmvq/batched `_rp` twins + qmatvec_gemm_q4_0_rp
1447            // prefill. The Stage-A f32 oracle reads GGUF layout, so the swap is gated on the
1448            // fast path being active (MEMRA_FAST=0 keeps GGUF bytes end to end — exact oracle).
1449            let fast_on = std::env::var("MEMRA_FAST").as_deref() != Ok("0");
1450            if fast_on {
1451                let mut nswap = 0usize;
1452                let mut nf16 = 0usize;
1453                // f16 prefill mirrors (campaign A, 2026-07-31): built from the GGUF Q4_0
1454                // bytes BEFORE the in-place rp swap destroys that layout. Same Lt lane and
1455                // budget env as the qwen Q8_0 mirrors (MEMRA_PP_F16 / MEMRA_PP_F16_BUDGET_MB;
1456                // Hopper default ON, sm_120a default OFF — the 24GB card can't carry them).
1457                // Per-model (battery-keyed, 2026-07-31, REAL-prompt gates — the fox-repeat
1458                // family is layout-lottery degenerate and was retired from campaign gates):
1459                // 12B pp1736 8.3k -> 17.1k MATCH; 31B pp1736 4.8k -> 7.6k MATCH but ONLY
1460                // with the full-trunk mirror (420 tensors ~53GB — set
1461                // MEMRA_PP_F16_BUDGET_MB=57344 on 80GB boxes; the default 32GB partial
1462                // mirror measured FLAT there). MEMRA_Q4F16=1|0 forces either way.
1463                let q4f16_model_ok = matches!(cfg.n_embd, 3840 | 5376); // 12B | 31B geometry
1464                let f16_on = match std::env::var("MEMRA_Q4F16").as_deref() {
1465                    Ok("1") => crate::f16_ffi::pp_f16_enabled(),
1466                    Ok("0") => false,
1467                    _ => crate::f16_ffi::pp_f16_enabled() && q4f16_model_ok,
1468                };
1469                for (il, layer) in layers.iter_mut().enumerate() {
1470                    // M2 weight sharding: swap/mirror through the owning stage engine.
1471                    let e = crate::pp::layer_engine(e, n_trunk, il)?;
1472                    let dense_gemma = layer.gemma4.as_ref().is_some_and(|g| g.moe_bits.is_none());
1473                    if !dense_gemma {
1474                        continue;
1475                    }
1476                    if let Mixer::Full(fa) = &mut layer.mixer {
1477                        for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] {
1478                            if f16_on {
1479                                e.build_q8_f16(w)?;
1480                                if matches!(w, crate::model::GpuTensor::Quant { f16: Some(_), .. }) {
1481                                    nf16 += 1;
1482                                }
1483                            }
1484                            if e.build_q4_rp_swap(w)? {
1485                                nswap += 1;
1486                            }
1487                        }
1488                    }
1489                    if let Ffn::Dense {
1490                        ffn_gate,
1491                        ffn_up,
1492                        ffn_down,
1493                    } = &mut layer.ffn
1494                    {
1495                        for w in [ffn_gate, ffn_up, ffn_down] {
1496                            if f16_on {
1497                                e.build_q8_f16(w)?;
1498                                if matches!(w, crate::model::GpuTensor::Quant { f16: Some(_), .. }) {
1499                                    nf16 += 1;
1500                                }
1501                            }
1502                            if e.build_q4_rp_swap(w)? {
1503                                nswap += 1;
1504                            }
1505                        }
1506                    }
1507                }
1508                if nswap > 0 {
1509                    eprintln!("[q4rp] split-plane IN-PLACE swap: {nswap} dense trunk tensors");
1510                }
1511                if nf16 > 0 {
1512                    eprintln!("[q4f16] prefill fp16 mirrors built: {nf16} dense trunk tensors");
1513                }
1514            }
1515        }
1516        let model = HybridModel {
1517            cfg,
1518            embd,
1519            output_norm,
1520            output,
1521            layers,
1522            mtp,
1523            embd_gpu: std::sync::OnceLock::new(),
1524            gemma4_aux,
1525            prime_slabs: std::sync::Mutex::new(None),
1526        };
1527        e.configure_moe_cache_layout(model.moe_cache_block_sizes());
1528        if force_embd_gpu {
1529            let _ = model
1530                .embd_gpu
1531                .get_or_init(|| e.upload_u8(&model.embd.raw).expect("embed table upload"));
1532        }
1533        // M2 LOAD BARRIER (pp door open at load): uploads + mirror builds above ran on
1534        // the loading engines' worker streams; the first decode consumer runs on OTHER
1535        // streams with no event between them. Synchronize every stage context once so
1536        // no consumer can ever read a half-built tensor (the 2026-08-02 split5 ref=0.0
1537        // head-mirror find). No-op with the door shut.
1538        crate::pp::sync_stages_after_load(e, n_trunk)?;
1539        Ok(model)
1540    }
1541
1542    /// Force the device embed table resident, FALLIBLY (F5 right-size ladder,
1543    /// 2026-08-05). The lazy `embd_gpu.get_or_init(.. expect ..)` sites panic the
1544    /// GPU worker on OOM; on a VRAM-tight rig a right-sized spec session that
1545    /// "fits" can leave too little for this ~hundreds-of-MB upload and die on its
1546    /// first prefill (observed: research/specpool-20260804/server-ladder-miss.log).
1547    /// The server calls this after each ladder landing so the biggest lazy
1548    /// transient surfaces as a catchable Err (shrink further / fall back) instead
1549    /// of a panic. No-op when the host-gather door (MEMRA_EMBED_DEV=0) is open or
1550    /// the table is already resident.
1551    pub fn ensure_embed_resident(&self, e: &Engine) -> Result<(), Box<dyn std::error::Error>> {
1552        if std::env::var("MEMRA_EMBED_DEV").as_deref() == Ok("0") {
1553            return Ok(());
1554        }
1555        if self.embd_gpu.get().is_none() {
1556            let buf = e.upload_u8(&self.embd.raw)?;
1557            let _ = self.embd_gpu.set(buf); // racing set = already resident; fine
1558        }
1559        Ok(())
1560    }
1561
1562    pub fn embed(
1563        &self,
1564        e: &Engine,
1565        tokens: &[u32],
1566    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1567        let n_embd = self.cfg.n_embd as usize;
1568        // DEVICE embed gather (round 30; the gemma4 machinery adopted for every model):
1569        // resident quantized table + gather kernel — replaces the CPU row gather + 31MB
1570        // pageable HtoD (2.2ms at T=2048, the lane's largest host stall). Same d*q
1571        // dequant math as the CPU gather; the greedy-stream A/B arbitrates.
1572        // MEMRA_EMBED_DEV=0 reverts.
1573        if std::env::var("MEMRA_EMBED_DEV").as_deref() != Ok("0") {
1574            let tbl = self
1575                .embd_gpu
1576                .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload"));
1577            let tok_d = e.htod_u32_v(tokens)?;
1578            let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
1579            return e.embed_gather_device_td(tbl, &tok_d, tokens.len(), n_embd, qt, rb);
1580        }
1581        let x = self.embd.gather(n_embd, tokens);
1582        Ok(e.htod(&x)?)
1583    }
1584}