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;
11use std::collections::HashMap;
12
13// Source-agnostic load helpers (GGUF or safetensors). The GGUF wrappers below keep `load()`
14// byte-identical; only the source object differs.
15fn load_t(
16    e: &Engine,
17    src: &dyn TensorSource,
18    name: &str,
19) -> Result<GpuTensor, Box<dyn std::error::Error>> {
20    GpuTensor::load_from_source(e, src, name)
21}
22fn load_opt(
23    e: &Engine,
24    src: &dyn TensorSource,
25    name: &str,
26) -> Result<Option<GpuTensor>, Box<dyn std::error::Error>> {
27    GpuTensor::load_opt_from_source(e, src, name)
28}
29
30struct ResidencyBytes {
31    experts: HashMap<usize, usize>,
32    rest: usize,
33    saw_experts: bool,
34}
35
36fn block_index(name: &str) -> Option<usize> {
37    name.strip_prefix("blk.")?.split('.').next()?.parse().ok()
38}
39
40fn residency_bytes_by_device<'a>(
41    tensors: impl IntoIterator<Item = (&'a str, usize)>,
42    layer_devices: &[usize],
43    primary_device: usize,
44) -> ResidencyBytes {
45    let mut out = ResidencyBytes {
46        experts: HashMap::new(),
47        rest: 0,
48        saw_experts: false,
49    };
50    for (name, bytes) in tensors {
51        if name.starts_with("blk.") && name.contains("_exps.") {
52            let device = block_index(name)
53                .and_then(|il| layer_devices.get(il).copied())
54                .unwrap_or(primary_device);
55            *out.experts.entry(device).or_default() += bytes;
56            out.saw_experts = true;
57        } else {
58            out.rest += bytes;
59        }
60    }
61    out
62}
63
64/// Load-local resident-expert capacity decisions. PP stages on distinct devices are charged only
65/// for their own layer slices; co-located stages share a device key and are charged together.
66pub(crate) struct ResidentPlan {
67    primary_device: usize,
68    layer_devices: Vec<usize>,
69    layer_counts: HashMap<usize, usize>,
70    exact_expert_bytes: Option<HashMap<usize, usize>>,
71    trunk_bytes: usize,
72    decisions: HashMap<usize, bool>,
73    pp: bool,
74}
75
76impl ResidentPlan {
77    fn from_layout(
78        src: &dyn TensorSource,
79        primary_device: usize,
80        layer_devices: Vec<usize>,
81        pp: bool,
82    ) -> Self {
83        let mut layer_counts = HashMap::new();
84        for &device in &layer_devices {
85            *layer_counts.entry(device).or_default() += 1;
86        }
87        let (exact_expert_bytes, trunk_bytes) = match src.gguf() {
88            Some(g) => {
89                let bytes = residency_bytes_by_device(
90                    g.tensors.iter().map(|t| (t.name.as_str(), t.n_bytes as usize)),
91                    &layer_devices,
92                    primary_device,
93                );
94                if bytes.saw_experts {
95                    (Some(bytes.experts), bytes.rest)
96                } else {
97                    (None, 0)
98                }
99            }
100            None => (None, 0),
101        };
102        Self {
103            primary_device,
104            layer_devices,
105            layer_counts,
106            exact_expert_bytes,
107            trunk_bytes,
108            decisions: HashMap::new(),
109            pp,
110        }
111    }
112
113    pub(crate) fn unsharded(e: &Engine, src: &dyn TensorSource, cfg: &ModelConfig) -> Self {
114        let device = e.ctx().ordinal();
115        Self::from_layout(src, device, vec![device; cfg.n_layer as usize], false)
116    }
117
118    pub(crate) fn pp(
119        e: &Engine,
120        src: &dyn TensorSource,
121        cfg: &ModelConfig,
122        n_trunk: usize,
123    ) -> Result<Self, Box<dyn std::error::Error>> {
124        let primary = e.ctx().ordinal();
125        let Some(_fence) = crate::pp::pp_cuts(n_trunk) else {
126            return Ok(Self::unsharded(e, src, cfg));
127        };
128        let mut layer_devices = vec![primary; cfg.n_layer as usize];
129        for (il, device) in layer_devices.iter_mut().take(n_trunk).enumerate() {
130            *device = crate::pp::layer_engine(e, n_trunk, il)?.ctx().ordinal();
131        }
132        Ok(Self::from_layout(src, primary, layer_devices, true))
133    }
134
135    fn should_reside(&mut self, e: &Engine, il: usize, per_layer: usize) -> bool {
136        let device = self.layer_devices.get(il).copied().unwrap_or(self.primary_device);
137        debug_assert_eq!(e.ctx().ordinal(), device);
138        if let Some(&decision) = self.decisions.get(&device) {
139            return decision;
140        }
141        if std::env::var("MEMRA_MOE_RESIDENT").as_deref() == Ok("0") {
142            self.decisions.insert(device, false);
143            return false;
144        }
145        let (free, _total) = match e.ctx().mem_get_info() {
146            Ok(v) => v,
147            Err(_) => {
148                self.decisions.insert(device, false);
149                return false;
150            }
151        };
152        let projected = self.exact_expert_bytes.as_ref()
153            .map(|bytes| bytes.get(&device).copied().unwrap_or(0))
154            .unwrap_or(per_layer * self.layer_counts.get(&device).copied().unwrap_or(1));
155        let budget = std::env::var("MEMRA_MOE_RESIDENT_GB").ok()
156            .and_then(|v| v.parse::<f64>().ok())
157            .map(|gb| (gb * 1e9) as usize)
158            .unwrap_or_else(|| {
159                let reserve = std::env::var("MEMRA_MOE_RESIDENT_HEADROOM_GB").ok()
160                    .and_then(|v| v.parse::<f64>().ok())
161                    .map(|gb| (gb * 1e9) as usize)
162                    .unwrap_or(2_000_000_000);
163                (free as usize).saturating_sub(self.trunk_bytes + reserve)
164            });
165        let ok = projected <= budget;
166        eprintln!("[moe] resident-experts decision ({}dev{}): experts {:.2}GB + trunk {:.2}GB vs free {:.2}GB (expert budget {:.2}GB) -> {}",
167                  if self.pp { "PP " } else { "" }, device, projected as f64 / 1e9,
168                  self.trunk_bytes as f64 / 1e9, free as f64 / 1e9, budget as f64 / 1e9,
169                  if ok { "RESIDENT" } else { "SLRU cache" });
170        self.decisions.insert(device, ok);
171        ok
172    }
173}
174
175/// Load the mixer (full-attn, linear-attn, or MLA) for block `il`. Shared by the trunk loop and
176/// the MTP head. `kind` overrides cfg.layer_kind (the MTP/NextN block is ALWAYS full-attn
177/// regardless of the periodic interval — its GGUF carries attn_q/k/v, not ssm_*/attn_qkv).
178/// `mla` is the Arch gate: `Some` only for glm-dsa (cfg.mla) — every layer of an MLA model,
179/// INCLUDING its NextN/MTP block (dense MLA, no indexer), takes the Mla arm.
180///
181/// `sep_gate` = `ModelConfig::attn_gate_separate()`: load step35's separate head-wise
182/// `attn_gate.weight` onto the full-attn arm. It is passed in rather than read off a cfg so the
183/// MTP/draft call sites (which build a synthetic cfg) opt in explicitly.
184fn load_mixer_kind(
185    e: &Engine,
186    src: &dyn TensorSource,
187    il: u32,
188    kind: LayerKind,
189    mla: Option<&MlaConfig>,
190    sep_gate: bool,
191) -> Result<Mixer, Box<dyn std::error::Error>> {
192    let p = |s: &str| format!("blk.{il}.{s}");
193    if let Some(m) = mla {
194        assert_eq!(kind, LayerKind::FullAttention, "MLA layers are full-attention class");
195        return Ok(Mixer::Mla(MlaAttnLayer::load(e, src, il, m)?));
196    }
197    Ok(match kind {
198        LayerKind::FullAttention => Mixer::Full(FullAttnLayer {
199            wq: load_t(e, src, &p("attn_q.weight"))?,
200            wk: load_t(e, src, &p("attn_k.weight"))?,
201            // gemma4 global layers ship NO v_proj (attention_k_eq_v): V = the K projection
202            // output pre-rope (llama gemma4.cpp: `Vcur = wv ? mm(wv,cur) : Kcur`). Loading
203            // wv := wk reproduces that exactly with zero forward changes; the gemma forward
204            // adds the weightless V rms_norm (R7 part 2).
205            wv: match load_opt(e, src, &p("attn_v.weight"))? {
206                Some(v) => v,
207                None => load_t(e, src, &p("attn_k.weight"))?,
208            },
209            wo: load_t(e, src, &p("attn_output.weight"))?,
210            q_norm: load_t(e, src, &p("attn_q_norm.weight"))?,
211            k_norm: load_t(e, src, &p("attn_k_norm.weight"))?,
212            // step35: REQUIRED when the arch says so — a missing gate would silently drop the
213            // per-head sigmoid and produce plausible-but-wrong logits, so this is load_t not
214            // load_opt. Step-3.7-Flash ships it on all 45 blocks (width = that layer's n_head).
215            attn_gate: if sep_gate {
216                Some(load_t(e, src, &p("attn_gate.weight"))?)
217            } else {
218                None
219            },
220        }),
221        LayerKind::LinearAttention => Mixer::Linear(LinearAttnLayer {
222            wqkv: load_t(e, src, &p("attn_qkv.weight"))?,
223            wqkv_gate: load_t(e, src, &p("attn_gate.weight"))?,
224            ssm_beta: load_t(e, src, &p("ssm_beta.weight"))?,
225            ssm_alpha: load_t(e, src, &p("ssm_alpha.weight"))?,
226            ssm_a: load_t(e, src, &p("ssm_a"))?,
227            ssm_dt: load_t(e, src, &p("ssm_dt.bias"))?,
228            ssm_conv1d: load_t(e, src, &p("ssm_conv1d.weight"))?,
229            ssm_norm: load_t(e, src, &p("ssm_norm.weight"))?,
230            ssm_out: load_t(e, src, &p("ssm_out.weight"))?,
231        }),
232    })
233}
234
235/// Load the FFN (dense SwiGLU or routed MoE) for block `il`. Source-agnostic (GGUF or safetensors
236/// via `TensorSource`); shared by the hybrid trunk/MTP loops AND the dense-attention MoE path (OLMoE).
237/// Shared-expert tensors are OPTIONAL (`load_opt`): qwen35moe has them, OLMoE/vanilla-MoE do not.
238/// When `spill` is `Some` (MEMRA_SPILL_DISK on) AND the source is the GGUF on disk, MoE experts load
239/// through the per-expert tier split (`HostExps::load_tiered`: hottest pinned, rest mmap'd from disk);
240/// otherwise experts take the all-host / gather path. Spill tiering is GGUF-only (needs the file mmap).
241pub(crate) fn load_ffn(
242    e: &Engine,
243    src: &dyn TensorSource,
244    cfg: &ModelConfig,
245    il: u32,
246    spill: Option<(&GgufFile, &mut crate::spill::SpillCtx)>,
247    resident: &mut ResidentPlan,
248) -> Result<Ffn, Box<dyn std::error::Error>> {
249    let p = |s: &str| format!("blk.{il}.{s}");
250    // MiniMax-M3: moe_layer_freq[il]==0 -> this layer is a DENSE-FFN layer (layers 0..2) even
251    // though the arch is MoE; force the Dense arm (its mlp.{p}_proj names map via ggml_to_hf).
252    // Hy3: `first_k_dense_replace` leading layers are dense-FFN (REAP50: layer 0 only).
253    let dense_override = cfg.m3.as_ref()
254        .is_some_and(|m| m.moe_layer_freq.get(il as usize).copied() == Some(0))
255        || cfg.hy3.as_ref().is_some_and(|h| il < h.first_k_dense_replace)
256        // glm-dsa: leading_dense_block_count layers (GLM-5.2: 3) are dense-FFN
257        || cfg.mla.as_ref().is_some_and(|m| il < m.first_k_dense_replace)
258        // step35: leading_dense_block_count (Step-3.7-Flash: 3) — blocks 0-2 ship
259        // ffn_gate/up/down and NO ffn_gate_inp, so the MoE arm's load_t would fail.
260        || cfg.step35.as_ref().is_some_and(|s| il < s.first_k_dense_replace)
261        // gemma4 DENSE variants (31B/E4B): the arch is MoE-capable but the file ships no
262        // expert tensors at all — tensor presence decides.
263        || (cfg.gemma4.is_some() && !src.has(&p("ffn_gate_exps.weight"))
264            && !src.has(&p("ffn_gate_up_exps.weight")))
265        // A NextN/MTP BLOCK can be DENSE inside a MoE trunk. Step-3.7-Flash's standalone drafter
266        // (Step3.7-flash-mtp-Q8_0.gguf) ships blk.45/46/47 with `ffn_gate/up/down.weight` and NO
267        // `ffn_gate_inp`/`ffn_*_exps`, while the same file's config declares expert_count=288 (it
268        // carries the TRUNK's hparams) — so the MoE arm's `load_t("ffn_gate_exps.weight")` would
269        // fail on a perfectly well-formed file. Scoped to `il >= n_trunk` and gated on tensor
270        // presence: only an MTP block can take this door, so no trunk MoE layer's dispatch can
271        // shift. (qwen35's MTP block IS MoE and keeps the MoE arm — it ships the expert slabs.)
272        || (cfg.nextn_predict_layers > 0
273            && il >= cfg.n_layer.saturating_sub(cfg.nextn_predict_layers)
274            && src.has(&p("ffn_gate.weight"))
275            && !src.has(&p("ffn_gate_exps.weight"))
276            && !src.has(&p("ffn_gate_up_exps.weight")));
277    Ok(
278        if let Some(moe) = cfg.moe.as_ref().filter(|_| !dense_override) {
279            let n_expert = moe.expert_count as usize;
280            // Expert loader. `spill` carries an optional (GgufFile, SpillCtx) — only the GGUF on-disk
281            // path can tier (it needs the file mmap); safetensors always gathers/stacks all-host.
282            //  - spill Some -> per-expert tier split (hottest pinned, rest mmap'd from the GGUF).
283            //  - GGUF 3D stacked name resolves -> load_stacked_from_source (all-host).
284            //  - else (safetensors) -> gather N separate 2D expert tensors.
285            let (gate_exps, up_exps, down_exps) = match spill {
286                Some((g, ctx)) => (
287                    HostExps::load_tiered(e, g, &p("ffn_gate_exps.weight"), ctx)?,
288                    HostExps::load_tiered(e, g, &p("ffn_up_exps.weight"), ctx)?,
289                    HostExps::load_tiered(e, g, &p("ffn_down_exps.weight"), ctx)?,
290                ),
291                None => {
292                    let exps =
293                        |e: &Engine, n: &str| -> Result<HostExps, Box<dyn std::error::Error>> {
294                            if src.has(n) {
295                                HostExps::load_stacked_from_source(e, src, n)
296                            } else {
297                                HostExps::load_from_source(e, src, n, n_expert)
298                            }
299                        };
300                    // gemma4: gate+up ship FUSED (ffn_gate_up_exps, gate rows first) — split at load.
301                    let fused = p("ffn_gate_up_exps.weight");
302                    if !src.has(&p("ffn_gate_exps.weight")) && src.has(&fused) {
303                        let ff = moe.expert_ff_length as usize;
304                        (
305                            HostExps::load_stacked_split_from_source(e, src, &fused, 0, ff)?,
306                            HostExps::load_stacked_split_from_source(e, src, &fused, ff, 2 * ff)?,
307                            exps(e, &p("ffn_down_exps.weight"))?,
308                        )
309                    } else {
310                        (
311                            exps(e, &p("ffn_gate_exps.weight"))?,
312                            exps(e, &p("ffn_up_exps.weight"))?,
313                            exps(e, &p("ffn_down_exps.weight"))?,
314                        )
315                    }
316                }
317            };
318            // FITS-VRAM RESIDENT EXPERTS: upload this layer's 3 expert slabs when the owning
319            // device's budget (MEMRA_MOE_RESIDENT_GB override; default = free VRAM minus the file's
320            // non-expert bytes minus a measured headroom reserve) covers the expert bytes assigned
321            // to that device, summed exactly from the GGUF header. Decision is made once per device
322            // (first MoE layer there). Failure to fit => None => the SLRU spill machinery.
323            let dev_exps =
324                build_dev_exps(e, resident, il as usize, &gate_exps, &up_exps, &down_exps)?;
325            // Device macro row [3*n_expert]: gate, up, down (ones when the artifact carries none).
326            let mut macro_row = vec![1.0f32; 3 * n_expert];
327            for (slot, exps) in [(0usize, &gate_exps), (1, &up_exps), (2, &down_exps)] {
328                if let Some(ms) = exps.macros.as_ref() {
329                    macro_row[slot * n_expert..(slot + 1) * n_expert].copy_from_slice(ms);
330                }
331            }
332            let has_macros = macro_row.iter().any(|&m| m != 1.0);
333            let dev_macros = e.htod(&macro_row)?;
334            // e_score_correction_bias (M3 sigmoid routing): tiny [n_expert] f32, host-side.
335            let exp_probs_b = src
336                .find(&p("exp_probs_b.bias"))
337                .map(|v| memra_gguf::dequant::dequantize(v.ggml_type, &v.bytes, n_expert));
338            let active_experts = src.active_experts(il).map(<[bool]>::to_vec);
339            Ffn::Moe(MoeWeights {
340                gate_inp: load_t(e, src, &p("ffn_gate_inp.weight"))?,
341                gate_inp_shexp: load_opt(e, src, &p("ffn_gate_inp_shexp.weight"))?,
342                exp_probs_b,
343                active_experts,
344                gate_exps,
345                up_exps,
346                down_exps,
347                gate_shexp: load_opt(e, src, &p("ffn_gate_shexp.weight"))?,
348                up_shexp: load_opt(e, src, &p("ffn_up_shexp.weight"))?,
349                down_shexp: load_opt(e, src, &p("ffn_down_shexp.weight"))?,
350                dev_exps,
351                dev_macros,
352                has_macros,
353            })
354        } else {
355            Ffn::Dense {
356                ffn_gate: load_t(e, src, &p("ffn_gate.weight"))?,
357                ffn_up: load_t(e, src, &p("ffn_up.weight"))?,
358                ffn_down: load_t(e, src, &p("ffn_down.weight"))?,
359            }
360        }
361    )
362}
363
364/// Decide + build the resident expert slabs for one layer. Budget check runs once per device,
365/// RESIDENT-IF-FITS (2026-08-02, research/residency-cap-20260802/): the bank is resident when
366/// its EXACT byte total (summed from the GGUF header — UD-quants make per-layer bytes
367/// non-uniform, Ornith-35B blk.0 is +7% over the mean, so first-layer x n_layer misprojects)
368/// plus the file's non-expert bytes plus a measured headroom reserve fits free VRAM. The old
369/// default (0.80 x free vs first-layer x n_layer) reserved 20% of the card (4.8GB on 24GB)
370/// and spilled the Ornith-35B bank that fits — a priced -33% decode / -54% prefill. Measured
371/// need beside the weights at board shape is ~1.7GB (CUDA ctx + KV + workspace); reserve
372/// default 2.0GB, machine-specific override `MEMRA_MOE_RESIDENT_HEADROOM_GB` (VRAM-budget
373/// class). `MEMRA_MOE_RESIDENT_GB` stays the absolute expert-budget override;
374/// MEMRA_MOE_RESIDENT=0 forces the SLRU path. Fits => every subsequent layer on that device
375/// uploads too.
376fn build_dev_exps(
377    e: &Engine,
378    resident: &mut ResidentPlan,
379    il: usize,
380    gate: &HostExps,
381    up: &HostExps,
382    down: &HostExps,
383) -> Result<Option<crate::hybrid::DevExps>, Box<dyn std::error::Error>> {
384    // The resident pointer-table kernels take one qtype/row stride per projection. Mixed-expert
385    // layers stay on the metadata-aware staged/SLRU paths until those kernels group by layout.
386    if !gate.is_uniform_layout() || !up.is_uniform_layout() || !down.is_uniform_layout() {
387        return Ok(None);
388    }
389    let per_layer =
390        gate.bytes.as_bytes().len() + up.bytes.as_bytes().len() + down.bytes.as_bytes().len();
391    if gate.tiers.is_some() {
392        return Ok(None); // tiered/spill loads keep the cache path
393    }
394    let fits = resident.should_reside(e, il, per_layer);
395    if !fits {
396        return Ok(None);
397    }
398    use cudarc::driver::DevicePtr;
399    let gu_il = std::env::var("MEMRA_MOE_GU_IL").as_deref() == Ok("1")
400        && gate.out_f == up.out_f
401        && gate.in_f == up.in_f;
402    let n_expert = gate.n_expert;
403    let (g, u) = if gu_il {
404        // interleave gate/up rows: [ex][row o] = gate-row-o bytes ++ up-row-o bytes.
405        let (rbg, rbu) = (gate.row_bytes, up.row_bytes);
406        let n_rows = gate.out_f;
407        let gb = gate.bytes.as_bytes();
408        let ub = up.bytes.as_bytes();
409        let mut il = vec![0u8; n_expert * n_rows * (rbg + rbu)];
410        for ex in 0..n_expert {
411            for o in 0..n_rows {
412                let dst = (ex * n_rows + o) * (rbg + rbu);
413                let sg = ex * gate.expert_stride + o * rbg;
414                let su = ex * up.expert_stride + o * rbu;
415                il[dst..dst + rbg].copy_from_slice(&gb[sg..sg + rbg]);
416                il[dst + rbg..dst + rbg + rbu].copy_from_slice(&ub[su..su + rbu]);
417            }
418        }
419        let ild = e.htod_bytes_padded(&il, 8)?;
420        // `up` slot points into the same buffer via ptr math; keep a tiny placeholder alloc so
421        // the struct shape is unchanged (the table below carries the real pointers).
422        (ild, e.htod_bytes(&[0u8; 16])?)
423    } else {
424        (
425            e.htod_bytes_padded(gate.bytes.as_bytes(), 8)?,
426            e.htod_bytes_padded(up.bytes.as_bytes(), 8)?,
427        )
428    };
429    // 144B tail slack (2026-07-31, g26 prefill lever): the ragged-k expert MMA walks
430    // whole 256-val superblocks — the LAST row's final partial superblock overreads up
431    // to 144B past the slab (harmless bytes: the act's zero-padded k-range multiplies
432    // every overread weight to zero; the slack only prevents the OOB fault).
433    let d = e.htod_bytes_padded(down.bytes.as_bytes(), 144)?;
434    let mut host = vec![0u64; 3 * n_expert];
435    let (pg, pu, pd) = {
436        let __s_e0 = e.stream();
437        let (pg, _e0) = g.device_ptr(&__s_e0);
438        let __s_e1 = e.stream();
439        let (pu, _e1) = u.device_ptr(&__s_e1);
440        let __s_e2 = e.stream();
441        let (pd, _e2) = d.device_ptr(&__s_e2);
442        (pg as u64, pu as u64, pd as u64)
443    };
444    for ex in 0..n_expert {
445        if gu_il {
446            let stride = gate.out_f * (gate.row_bytes + up.row_bytes);
447            host[ex] = pg + (ex * stride) as u64;
448            host[n_expert + ex] = pg + (ex * stride + gate.row_bytes) as u64;
449        } else {
450            host[ex] = pg + (ex * gate.expert_stride) as u64;
451            host[n_expert + ex] = pu + (ex * up.expert_stride) as u64;
452        }
453        host[2 * n_expert + ex] = pd + (ex * down.expert_stride) as u64;
454    }
455    if gu_il {
456        eprintln!("[moe] gate/up dev slab INTERLEAVED (MEMRA_MOE_GU_IL)");
457    }
458    let ptr_row = e.htod_u64(&host)?;
459    Ok(Some(crate::hybrid::DevExps {
460        gate: g,
461        up: u,
462        down: d,
463        ptr_row,
464        gu_il,
465        dev: e.ctx().ordinal(),
466    }))
467}
468
469pub struct FullAttnLayer {
470    pub wq: GpuTensor,
471    pub wk: GpuTensor,
472    pub wv: GpuTensor,
473    pub wo: GpuTensor,
474    pub q_norm: GpuTensor,
475    pub k_norm: GpuTensor,
476    /// step35-class SEPARATE head-wise attention gate: `blk.N.attn_gate.weight [n_embd, n_head_l]`
477    /// where `n_head_l` is this layer's query-head count (64 full / 96 SWA on Step-3.7-Flash, so
478    /// the width VARIES per layer). Produces one pre-sigmoid scalar per head from the
479    /// post-attn_norm hidden state; the forward broadcasts sigmoid(gate) over head_dim and
480    /// multiplies attn_out before wo (upstream `step35.cpp:267-285`).
481    ///
482    /// `None` for every other arch. Do NOT confuse with `LinearAttnLayer::wqkv_gate`, which reads
483    /// the SAME tensor name on qwen35's SSM layers but is a different mechanism (a full-width
484    /// z-gate, not a per-head scalar), nor with the qwen35 FUSED gate packed inside wq that
485    /// `ModelConfig::attn_out_gate()` / `q_gate_split` handle.
486    pub attn_gate: Option<GpuTensor>,
487}
488
489/// Latent-KV geometry for one MLA layer, resolved at load from `MlaConfig` (glm-dsa). The KV
490/// cache stores ONE `latent_dim`-wide row per token per layer: [rmsnorm(c_kv) | rope(k_pe)];
491/// V is the first `kv_rank` elements of the SAME row (no V plane). All heads stream it (MQA).
492#[derive(Clone, Copy, Debug)]
493pub struct MlaGeom {
494    pub n_head: usize,     // 64  — query heads; n_head_kv semantics = 1
495    pub d_nope: usize,     // 192 — qk nope head dim (absorb GEMM K)
496    pub d_rope: usize,     // 64  — decoupled rope width (q_pe / k_pe)
497    pub d_v: usize,        // 256 — v head dim after wv_b decompression
498    pub kv_rank: usize,    // 512 — latent rank (absorbed qk dim, AV accumulator width)
499    pub latent_dim: usize, // 576 = kv_rank + d_rope — the cache row / K width
500    pub scale: f32,        // 1/sqrt(d_nope + d_rope) = 1/16 — NOT 1/sqrt(latent_dim)
501}
502
503/// GLM-5.2 MLA attention block (DESIGN.md §3.1 mapping). INCREMENT 2: loader-only — the
504/// projections + latent-cache geometry land on device; forward arms (prefill/decode/dc/graph)
505/// are increment 4. The CPU oracle for those arms is `crate::mla` (naive ≡ absorbed, proven).
506pub struct MlaAttnLayer {
507    pub wq_a: GpuTensor,      // attn_q_a.weight      [H -> Lq] (q down-projection)
508    pub q_a_norm: GpuTensor,  // attn_q_a_norm.weight [Lq]
509    pub wq_b: GpuTensor,      // attn_q_b.weight      [Lq -> N*(nope+rope)] (q up, per head [nope|rope])
510    pub wkv_a: GpuTensor,     // attn_kv_a_mqa.weight [H -> Lkv+rope] (latent row producer)
511    pub kv_a_norm: GpuTensor, // attn_kv_a_norm.weight [Lkv] (c_kv rms; k_pe is NOT normed)
512    pub wk_b: GpuTensor,      // attn_k_b.weight      [nope, Lkv, N] 3D — TRANSPOSED nope slice of
513                              //   kv_b (conversion split): the per-head absorb GEMM operand
514    pub wv_b: GpuTensor,      // attn_v_b.weight      [Lkv, V, N] 3D — the post-softmax decompress
515    pub wo: GpuTensor,        // attn_output.weight   [N*V -> H]
516    pub geom: MlaGeom,
517}
518
519impl MlaAttnLayer {
520    /// Load one MLA attention block to device. `attn_kv_b` (the unsplit tensor, when present)
521    /// is intentionally NOT loaded — v1 runs absorbed-form everywhere; the MHA-prefill arm that
522    /// would consume it is a later arc (DESIGN.md §3.1 "unused v1").
523    ///
524    /// NOTE (increment-3+): wk_b/wv_b are 3D. The F32 fixture rides the Float path (exact, full
525    /// ne kept). Quantized 3D tensors would mis-derive `row_bytes` in the generic 2D Quant arm
526    /// (out_f = ne[1] only) — the real-weights loader must split per head or flatten ne[1]*ne[2]
527    /// before the batched-GEMM kernels consume them. Guarded by the assert below.
528    pub fn load(
529        e: &Engine,
530        src: &dyn TensorSource,
531        il: u32,
532        m: &MlaConfig,
533    ) -> Result<Self, Box<dyn std::error::Error>> {
534        let p = |s: &str| format!("blk.{il}.{s}");
535        let geom = MlaGeom {
536            n_head: 0, // patched below from wq_b's out width (metadata cross-check)
537            d_nope: m.qk_nope_head_dim as usize,
538            d_rope: m.qk_rope_head_dim as usize,
539            d_v: m.v_head_dim as usize,
540            kv_rank: m.kv_lora_rank as usize,
541            latent_dim: m.latent_dim() as usize,
542            scale: m.scale(),
543        };
544        let wq_a = load_t(e, src, &p("attn_q_a.weight"))?;
545        let wq_b = load_t(e, src, &p("attn_q_b.weight"))?;
546        let wkv_a = load_t(e, src, &p("attn_kv_a_mqa.weight"))?;
547        let wk_b = load_t(e, src, &p("attn_k_b.weight"))?;
548        let wv_b = load_t(e, src, &p("attn_v_b.weight"))?;
549        let wo = load_t(e, src, &p("attn_output.weight"))?;
550        // shape audit at load (fail loudly, not as garbage activations later):
551        let n_head = wq_b.out_features() / (geom.d_nope + geom.d_rope);
552        assert_eq!(wq_b.out_features(), n_head * (geom.d_nope + geom.d_rope),
553                   "wq_b out {} not a multiple of qk_head_dim {}", wq_b.out_features(),
554                   geom.d_nope + geom.d_rope);
555        assert_eq!(wq_a.in_features() , wkv_a.in_features(), "q_a/kv_a hidden mismatch");
556        assert_eq!(wq_b.in_features(), m.q_lora_rank as usize, "wq_b in != q_lora_rank");
557        assert_eq!(wkv_a.out_features(), geom.latent_dim, "wkv_a out != kv_lora_rank + rope");
558        assert_eq!(wk_b.ne(), &[geom.d_nope as u64, geom.kv_rank as u64, n_head as u64],
559                   "attn_k_b must be the TRANSPOSED (nope, kv_rank, head) conversion split");
560        assert_eq!(wv_b.ne(), &[geom.kv_rank as u64, geom.d_v as u64, n_head as u64],
561                   "attn_v_b must be the (kv_rank, v, head) conversion split");
562        assert_eq!(wo.in_features(), n_head * geom.d_v, "wo in != n_head * v_head_dim");
563        Ok(MlaAttnLayer {
564            wq_a,
565            q_a_norm: load_t(e, src, &p("attn_q_a_norm.weight"))?,
566            wq_b,
567            wkv_a,
568            kv_a_norm: load_t(e, src, &p("attn_kv_a_norm.weight"))?,
569            wk_b,
570            wv_b,
571            wo,
572            geom: MlaGeom { n_head, ..geom },
573        })
574    }
575}
576
577/// Increment-2 guard: every forward-path `match` on `Mixer` routes Mla here until increment 4
578/// lands the MLA kernels. Loading a glm-dsa model works; running it panics with THIS message
579/// instead of garbage math. Zero behavior change for Full/Linear arches (arm never taken).
580#[track_caller]
581pub(crate) fn mla_forward_unimplemented() -> ! {
582    panic!("Mixer::Mla has no forward arm yet — glm-dsa is loader-only in increment 2; \
583            the CUDA forward lands in increment 4 (research/mla-bringup-20260801/DESIGN.md §4)")
584}
585
586pub struct LinearAttnLayer {
587    pub wqkv: GpuTensor,       // [n_embd, conv_dim] -> qkv_mixed
588    pub wqkv_gate: GpuTensor,  // [n_embd, value_dim] -> z
589    pub ssm_beta: GpuTensor,   // [n_embd, num_v_heads]
590    pub ssm_alpha: GpuTensor,  // [n_embd, num_v_heads]
591    pub ssm_a: GpuTensor,      // [num_v_heads] (pre-negated -exp(A_log))
592    pub ssm_dt: GpuTensor,     // [num_v_heads] bias
593    pub ssm_conv1d: GpuTensor, // [d_conv, conv_dim]
594    pub ssm_norm: GpuTensor,   // [head_v_dim]
595    pub ssm_out: GpuTensor,    // [value_dim, n_embd]
596}
597
598pub enum Mixer {
599    Full(FullAttnLayer),
600    Linear(LinearAttnLayer),
601    /// glm-dsa MLA block (loader-only in increment 2; forward = increment 4).
602    Mla(MlaAttnLayer),
603}
604
605/// MoE weights for one layer. Router + shared expert stay GPU-RESIDENT (tiny); the routed
606/// experts stay HOST-RESIDENT (HostExps) and are staged per-token (EDGE-1).
607///
608/// The shared-expert fields are `Option`: qwen35moe carries a shared expert, but OLMoE (and most
609/// vanilla MoE) have none (`shared_expert_intermediate_size` absent) — those layers `load_opt` the
610/// shexp tensors to `None` (ST-MOE-PLAN §1.3, §3.2). When `None` the shared-expert branch is skipped.
611pub struct MoeWeights {
612    pub gate_inp: GpuTensor, // F32 [n_embd, n_expert] router  (GPU resident, Float)
613    pub gate_inp_shexp: Option<GpuTensor>, // F32 [n_embd] 1-D shared gate dot (qwen35moe only)
614    /// DeepSeek-V3/MiniMax-M3 `e_score_correction_bias` [n_expert]: added to the sigmoid scores
615    /// for expert SELECTION only; the routing weights use the un-biased scores. Kept host-side —
616    /// routing's top-k is a host loop and this is n_expert floats.
617    pub exp_probs_b: Option<Vec<f32>>,
618    /// Original-width router mask for physically pruned expert overlays. Inactive ids never enter
619    /// top-k, so their absent weight files cannot be dispatched.
620    pub active_experts: Option<Vec<bool>>,
621    pub gate_exps: HostExps, // [n_embd, n_ff_exp, n_expert]   (HOST)
622    pub up_exps: HostExps,   // [n_embd, n_ff_exp, n_expert]   (HOST)
623    pub down_exps: HostExps, // [n_ff_exp, n_embd, n_expert] TRANSPOSED (HOST)
624    pub gate_shexp: Option<GpuTensor>,
625    pub up_shexp: Option<GpuTensor>,
626    pub down_shexp: Option<GpuTensor>,
627    /// FITS-VRAM RESIDENT EXPERTS (2026-07-06): when the WHOLE model's expert bytes fit the VRAM
628    /// budget, each (proj) slab is uploaded once as a contiguous device buffer and the fused
629    /// _dev kernels take base+ex*stride pointers — no SLRU, no dispatch, no residency checks
630    /// (llama's full-offload regime; measured 169.55 vs memra's cache path 28.5 on the local 35B).
631    /// None => the SLRU host-expert machinery (the spill regime, where it WINS vs llama's
632    /// CPU-offload degradation). Decided at load in `load_ffn` (MEMRA_MOE_RESIDENT=0 forces off).
633    pub dev_exps: Option<DevExps>,
634    /// Per-expert post-matmul macro-scales on DEVICE: [3*n_expert] f32 in (gate, up, down)
635    /// order — all 1.0 unless the checkpoint carries compressed-tensors NVFP4 global scales
636    /// (unsloth qwen3.6 class). The _dev gate_up epilogues multiply unconditionally (x*1.0f
637    /// is bit-exact — zero change for macro-free artifacts); the down fold is one
638    /// moe_w_scale_by_expert launch gated on `has_macros`.
639    pub dev_macros: cudarc::driver::CudaSlice<f32>,
640    pub has_macros: bool,
641}
642
643impl MoeWeights {
644    #[inline]
645    pub fn has_uniform_expert_layout(&self) -> bool {
646        self.gate_exps.is_uniform_layout()
647            && self.up_exps.is_uniform_layout()
648            && self.down_exps.is_uniform_layout()
649    }
650}
651
652/// Device-resident expert slabs for one layer (gate/up/down) + the prebuilt [3, n_expert]
653/// pointer row the _dev kernels consume.
654pub struct DevExps {
655    pub gate: CudaSlice<u8>,
656    pub up: CudaSlice<u8>,
657    pub down: CudaSlice<u8>,
658    /// [3*n_expert] u64 device row: gate ptrs, up ptrs, down ptrs (proj-major like layer_dev_row).
659    pub ptr_row: CudaSlice<u64>,
660    /// The CUDA device ordinal these slabs live on (the OWNING stage's device under the PP
661    /// sharded loader — cx-503b sizes and `layer_engine` places per device). Consumers that
662    /// dispatch from a DIFFERENT device must NOT dereference the slabs: an m=1 qmatvec over
663    /// peer-read expert bytes is the measured 34-150x slow class (research/pp-prefill-20260807
664    /// anatomy), strictly worse than SLRU staging. The sequential arm's slab-locality gate
665    /// (lane/pp-leverb) keys on this field; the per-stage prime walker makes every layer's
666    /// slab local by construction.
667    pub dev: usize,
668    /// WALL-GAP ARC (MEMRA_MOE_GU_IL=1): gate/up rows INTERLEAVED in one slab — row o of gate at
669    /// base + o*(rb_g+rb_u), up at +rb_g. Consumers on the dev path must use (rb_g+rb_u) as the
670    /// row stride for BOTH projections (see MoeWeights::dev_rb_gu). One contiguous 1760B stream
671    /// per (expert,row) instead of two scattered 880B streams — the measured 56%-of-wall fix
672    /// candidate. Kernels unchanged (stride is already a parameter everywhere).
673    pub gu_il: bool,
674}
675
676/// Per-layer FFN: dense SwiGLU (qwen35) or 256-expert MoE (qwen35moe).
677pub enum Ffn {
678    Dense {
679        ffn_gate: GpuTensor,
680        ffn_up: GpuTensor,
681        ffn_down: GpuTensor,
682    },
683    Moe(MoeWeights),
684}
685
686pub struct HybridLayer {
687    pub attn_norm: GpuTensor,
688    pub post_attn_norm: GpuTensor, // "post_attention_norm" = PRE-FFN norm
689    pub mixer: Mixer,
690    pub ffn: Ffn,
691    pub gemma4: Option<Gemma4LayerBits>,
692}
693
694/// Gemma-4 per-layer extras (R8 wiring, HANDOVER "R8 VERIFIED WIRING"): the parallel shared
695/// FFN branch, the four extra norms, the router prologue scale vector, per-expert output
696/// scales, and the layer output scalar.
697pub struct Gemma4LayerBits {
698    pub ffn_norm: GpuTensor, // ffn pre-norm (dense: THE ffn norm; moe: shared branch)
699    pub post_ffw_norm: GpuTensor, // combined post (before the attn_out residual)
700    /// MoE-layer extras (None on the dense gemma4 variants — 31B/E4B): the parallel shared
701    /// branch norms + tensors, the router prologue vector, per-expert output scales.
702    pub moe_bits: Option<Gemma4MoeBits>,
703    pub layer_scale: f32, // layer_output_scale [1]
704    /// E4B extras (None on 26B/31B): the per-layer-embedding tail block + KV-share target.
705    pub e4b: Option<Gemma4E4bLayer>,
706}
707
708/// gemma-4 E4B per-layer bits (see research/gemma4-bringup/e4b-arch-map.md):
709/// tail block  cur += rms_norm(proj . (gelu(inp_gate . cur) * inp_pl[il]), post_norm)
710/// and the KV-share map — layers il >= n_layer-shared_kv_layers have NO own k/v projections
711/// and attend the cache of layer (n_layer-shared) - (swa ? 2 : 1) with their own Q.
712pub struct Gemma4E4bLayer {
713    pub inp_gate: GpuTensor,           // blk.N.inp_gate  [n_embd, n_epl]
714    pub proj: GpuTensor,               // blk.N.proj      [n_epl, n_embd]
715    pub post_norm: GpuTensor,          // blk.N.post_norm [n_embd]
716    /// wave-4b: wq|wk|wv concatenated along OUT (one Q4_0 matvec at t=1 instead of the
717    /// fused3 3-subgrid launch). Built at the mirror hook from the GPU byte planes (rows
718    /// are independent in Q4_0, so an out-dim concat is a byte concat); own-KV layers only.
719    pub qkv_cat: Option<GpuTensor>,
720    /// Some(target_layer) on KV-shared layers (wk/wv here are the TARGET layer's tensors,
721    /// loaded for shape symmetry only — the forward must skip k/v compute + append and read
722    /// the target's cache; TODO dedupe the duplicate weight upload ~63MB).
723    pub kv_share: Option<u32>,
724}
725
726/// gemma-4 E4B model-level per-layer-embedding tensors (prologue inputs). The token table
727/// stays HOST-side raw GGUF bytes at load (Q6_K [n_epl*n_layer, n_vocab], ~2.3GB VRAM when
728/// uploaded — the forward arc decides resident-vs-gather placement).
729pub struct Gemma4E4bModel {
730    /// device copy of the per-layer token table, uploaded on first use (the 26B embd_gpu
731    /// pattern — keeps the ~2.3GB off load-critical paths that never decode).
732    pub tok_tbl_gpu: std::sync::OnceLock<CudaSlice<u8>>,
733    pub tok_embd_bytes: Vec<u8>,
734    pub tok_embd_qt: i32,
735    pub tok_embd_row_bytes: usize,
736    pub model_proj: GpuTensor, // per_layer_model_proj [n_embd, n_epl*n_layer] F16
737    pub proj_norm: GpuTensor,  // per_layer_proj_norm [n_epl]
738    pub n_epl: usize,
739}
740
741pub struct Gemma4MoeBits {
742    pub post_ffw_norm_1: GpuTensor, // shared-branch post
743    pub pre_ffw_norm_2: GpuTensor,  // moe-branch pre
744    pub post_ffw_norm_2: GpuTensor, // moe-branch post
745    pub shared_gate: GpuTensor,
746    pub shared_up: GpuTensor,
747    pub shared_down: GpuTensor,
748    /// ffn_gate_inp.scale [n_embd] PRE-multiplied by 1/sqrt(n_embd) at load: the router
749    /// prologue (weightless rms_norm x 1/sqrt(n_embd) x scale-vec) collapses to ONE rms_norm
750    /// with this as the norm weight (x_hat * (v*s) vs llama's (x_hat*s)*v — one reassociation;
751    /// the argmax gate arbitrates).
752    pub router_scale_pre: CudaSlice<f32>,
753    pub per_expert_scale: Vec<f32>, // ffn_down_exps.scale [n_expert] (host)
754    pub per_expert_scale_d: CudaSlice<f32>, // device copy (router-weight fold kernel)
755}
756
757/// Qwen3.5 NextN/MTP head: a full transformer block (attn+FFN, same tensors as a trunk layer)
758/// plus the MTP glue (enorm/hnorm/eh_proj that fold the next-token embedding into the trunk
759/// hidden, and an optional shared_head_norm/head). Loaded from blk.{n_trunk}.* — the block the
760/// trunk loop drops. Used for speculative decode (drafts 1 token per call). See research/mtp/MTP-PLAN.md.
761pub struct MtpHead {
762    pub enorm: GpuTensor, // blk.N.nextn.enorm   — RMSNorm of the next-token embedding
763    pub hnorm: GpuTensor, // blk.N.nextn.hnorm   — RMSNorm of the trunk hidden
764    pub eh_proj: GpuTensor, // blk.N.nextn.eh_proj [2*n_embd, n_embd]: [e_norm; h_norm] -> n_embd
765    pub attn_norm: GpuTensor, // blk.N.attn_norm
766    pub post_attn_norm: GpuTensor, // blk.N.post_attention_norm (pre-FFN)
767    pub mixer: Mixer,     // full-attn block (qwen35 MTP block is full-attn)
768    pub ffn: Ffn,         // Dense or Moe, same loader as trunk
769    pub shared_head_norm: Option<GpuTensor>, // blk.N.nextn.shared_head_norm (else reuse output_norm)
770    pub shared_head_head: Option<GpuTensor>, // blk.N.nextn.shared_head      (else reuse output)
771    /// FR-Spec draft->target vocab map: the draft lm_head is TRIMMED to the highest-frequency
772    /// tokens (e.g. 32768 rows of the full 248320-row head); `d2t[draft_idx]` = the target vocab
773    /// token id of trimmed row `draft_idx`. `None` for a full-vocab head (identity map). Host-side:
774    /// the draft argmax already lands on host as one u32, so the map is a single Vec index.
775    pub d2t: Option<Vec<u32>>,
776    /// DISTILLED-STUDENT geometry (None = the natural NextN block at trunk shape). A distilled
777    /// draft (StudentSV) runs the same block structure at a narrower inner width with fewer
778    /// heads, then up-projects back to n_embd (`out_up`) — the chain carrier and the head input
779    /// stay at n_embd, so the trunk/verify interface is unchanged. Selected by the presence of
780    /// `blk.N.nextn.out_up.weight` in a MEMRA_MTP_DRAFT file.
781    pub geom: Option<DraftGeom>,
782    /// step35: the DRAFT BLOCK's RESOLVED per-layer geometry (`None` for every arch whose
783    /// geometry is uniform). Without it the head forward would use the trunk's max-derived
784    /// scalars and compute wrong attention — and the failure mode is plausible-but-wrong drafts
785    /// (tanked acceptance, correct output), exactly what the exactness gates cannot see.
786    pub step35: Option<Step35MtpGeom>,
787}
788
789/// step35 MTP-block geometry, RESOLVED at load time from the file that actually carries the
790/// block's own `Step35Config` arrays.
791///
792/// Why resolved and not "look it up per forward from the model's cfg": Step-3.7-Flash ships MTP
793/// as a SEPARATE GGUF, and the two files disagree about which layers exist. The trunk artifact
794/// declares `block_count=45` / `nextn_predict_layers=0`, so its per-layer arrays hold 45 entries
795/// (0..=44) and `Step35Config::n_head(45)` falls off the end into the `.last()` fallback — index
796/// 44, which is a FULL-attn layer at 64 heads. The draft file declares `block_count=48` /
797/// `nextn=3` and its arrays' index 45 is the truth: SWA, 96 heads (matching that file's
798/// `blk.45.attn_q.weight [4096, 12288]` = 96*128 and `blk.45.attn_gate.weight [4096, 96]`).
799/// Receipt: `research/step37-bringup-20260802/raw/gguf-header-stepfun-mtp-q8-20260802.txt` plus
800/// the tail dump in `research/step37-p2-20260806/raw/` — `head_count[43..48] = [96, 64, 96, 96,
801/// 96]`, `sliding_window_pattern[43..48] = [True, False, True, True, True]`.
802#[derive(Debug, Clone)]
803pub struct Step35MtpGeom {
804    /// Block index inside the file that carries it (45 for Step-3.7-Flash). Diagnostics only.
805    pub il: u32,
806    pub n_head: usize,    // 96 on Step-3.7-Flash's MTP block (SWA-type)
807    pub n_head_kv: usize, // 8
808    pub n_rot: usize,     // 128 (SWA keeps the unhalved rotary width)
809    pub rope_base: f32,   // 1e4 (SWA base, not the trunk's 5e6 global)
810    pub swa: bool,        // true
811    pub window: usize,    // 512
812    /// This block's `swiglu_clamp_shexp` limit. The MTP block's FFN is a DENSE SwiGLU, and
813    /// upstream's one `build_ffn` serves both the dense MLP and the shared expert off the
814    /// SHEXP array (llama-graph.cpp:1751) — so a dense MTP block keys off shexp, not exp.
815    /// 0.0 (`None`) on Step-3.7-Flash's block 45; live (16.0) only on trunk layers 43-44.
816    pub clamp_shexp: Option<f32>,
817}
818
819impl Step35MtpGeom {
820    /// Resolve block `il`'s geometry from the `Step35Config` of the file that OWNS that block.
821    pub fn resolve(s: &memra_gguf::config::Step35Config, il: u32) -> Self {
822        Step35MtpGeom {
823            il,
824            n_head: s.n_head(il) as usize,
825            n_head_kv: s.n_head_kv(il) as usize,
826            n_rot: s.n_rot(il) as usize,
827            rope_base: s.rope_base(il),
828            swa: s.is_swa(il),
829            window: s.sliding_window as usize,
830            clamp_shexp: s.clamp_shexp(il),
831        }
832    }
833}
834
835/// Draft-head geometry override for a distilled (narrower) student block.
836pub struct DraftGeom {
837    pub d_inner: usize, // block inner width (eh_proj out / attn / ffn), e.g. 2048
838    pub n_head: usize,  // draft attention heads (head_dim = main head_dim)
839    pub n_head_kv: usize,
840    pub out_up: GpuTensor, // [d_inner -> n_embd]: carrier + head input up-projection
841}
842
843/// Which tensor is the DRAFT lm_head, for a standalone NextN/MTP draft GGUF whose block index is
844/// `n`. Preference order is the artifact's, not ours — upstream step35.cpp:553 is
845/// `layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output`.
846///
847/// Split out of `MtpHead::load_draft` purely so it is unit-testable: the loader needs a CUDA
848/// device and a multi-GB file, while the failure this guards is invisible to every exactness gate
849/// (a wrong head still produces CORRECT output — the verify arbitrates — it just accepts nothing).
850/// `has` is the tensor-presence predicate (`src.has`).
851pub fn draft_head_tensor(has: impl Fn(&str) -> bool, n: u32) -> String {
852    let own = format!("blk.{n}.nextn.shared_head_head.weight");
853    if has(&own) {
854        return own;
855    }
856    // Legacy name kept as a probe so anything that ever matched it still does; no shipped
857    // artifact or upstream mapping uses it (see the `load_draft` note).
858    let legacy = format!("blk.{n}.nextn.shared_head.weight");
859    if has(&legacy) {
860        return legacy;
861    }
862    // FR-Spec / tied-head drafts: the file-level head IS the draft head.
863    "output.weight".to_string()
864}
865
866impl MtpHead {
867    /// Load an MTP/NextN head from a STANDALONE draft GGUF (MEMRA_MTP_DRAFT override). The draft
868    /// file carries ONLY the NextN block (blk.N.nextn.* glue + attn/ffn) plus its own lm_head
869    /// (`output.weight`) — which for an FR-Spec draft is TRIMMED to the top-frequency rows, with
870    /// a `d2t` (i32/i64) tensor mapping trimmed-row index -> target vocab token id. Draft-token
871    /// embedding still uses the MAIN model's token_embd (identical weights, saves VRAM), so the
872    /// draft file's full-vocab token_embd copy is ignored.
873    pub fn load_draft(
874        e: &Engine,
875        g: &GgufFile,
876        main_cfg: &ModelConfig,
877    ) -> Result<Self, Box<dyn std::error::Error>> {
878        let src = GgufSource(g);
879        let dcfg = src.config();
880        // NextN block index INSIDE THE DRAFT FILE (its block_count includes the trunk numbering).
881        // Graceful error, not assert: the server's `+draft` attach path surfaces this to the
882        // user (a gemma-assistant draft or any non-NextN GGUF lands here; a panic killed the
883        // whole worker — serve-smoke find, 2026-07-30).
884        if dcfg.nextn_predict_layers == 0 {
885            return Err(format!(
886                "draft GGUF has no nextn_predict_layers (arch {:?}) — not a NextN/MTP regime \
887                 draft; gemma assistant drafters attach via MEMRA_DRAFT, not '+draft'",
888                g.arch()).into());
889        }
890        let n = dcfg.n_layer - dcfg.nextn_predict_layers;
891        let p = |s: &str| format!("blk.{n}.{s}");
892
893        // Distilled student (narrow block + out_up) vs natural NextN clone. The interface dims
894        // (n_embd in/out, head_dim for the shared rope kernel) must match the main model; a
895        // student may shrink the inner width and head counts.
896        let student = src.has(&p("nextn.out_up.weight"));
897        assert_eq!(dcfg.n_embd, main_cfg.n_embd, "draft n_embd != model n_embd");
898        assert_eq!(
899            dcfg.head_dim_k, main_cfg.head_dim_k,
900            "draft head_dim != model head_dim"
901        );
902        // step35: geometry is PER-LAYER, so "same shape as the trunk" is the wrong question — the
903        // draft block at il=45 is an SWA-type block (96 q heads, 128 rotary dims, rope base 1e4)
904        // while the trunk's full-attn layers are 64/64/5e6. Resolve the block's geometry from the
905        // DRAFT FILE's own arrays (the trunk artifact's arrays stop at index 44 — see
906        // `Step35MtpGeom`'s note) and verify it against the block's real tensor shapes. The dims
907        // that must still agree with the trunk are the INTERFACE ones (n_embd, head_dim, KV width).
908        let step35 = match (main_cfg.step35.as_ref(), dcfg.step35.as_ref()) {
909            (Some(_), Some(s)) => {
910                let g = Step35MtpGeom::resolve(s, n);
911                // ne is inner-fastest: ne[0] = in_features, ne[1] = out_features for a [in, out] 2D.
912                let out_f = |t: &str| -> Option<usize> {
913                    src.find(&p(t)).and_then(|v| v.ne.get(1).copied()).map(|x| x as usize)
914                };
915                let hd = dcfg.head_dim_k as usize;
916                let wq_out = out_f("attn_q.weight")
917                    .ok_or("step35 draft block has no attn_q.weight")?;
918                assert_eq!(
919                    wq_out, g.n_head * hd,
920                    "step35 draft blk.{n}: attn_q out {wq_out} != n_head({}) * head_dim({hd}) — \
921                     the draft file's head_count array disagrees with its own tensors",
922                    g.n_head
923                );
924                // The SEPARATE head-wise gate is [n_embd, n_head_l] — one scalar per head. Its
925                // width is the second independent witness of this block's head count.
926                let wg_out = out_f("attn_gate.weight")
927                    .ok_or("step35 draft block has no attn_gate.weight (head-wise gate)")?;
928                assert_eq!(
929                    wg_out, g.n_head,
930                    "step35 draft blk.{n}: attn_gate out {wg_out} != n_head({})", g.n_head
931                );
932                // The draft attends its OWN scratch, but `MtpScratch::new` sizes those rows from
933                // the TRUNK cfg's `n_head_kv` (for step35, the max over its per-layer array).
934                // Compare against exactly that value, not a per-layer accessor.
935                assert_eq!(
936                    g.n_head_kv, main_cfg.n_head_kv as usize,
937                    "step35 draft blk.{n} KV heads {} != trunk n_head_kv {} — the MTP scratch \
938                     rows are sized from the trunk cfg, so a differing draft KV width would \
939                     write past the row",
940                    g.n_head_kv, main_cfg.n_head_kv
941                );
942                eprintln!(
943                    "[mtp-draft] step35 MTP geometry blk.{n}: n_head={} n_head_kv={} n_rot={} \
944                     rope_base={:.0} swa={} window={}",
945                    g.n_head, g.n_head_kv, g.n_rot, g.rope_base, g.swa, g.window
946                );
947                Some(g)
948            }
949            (Some(_), None) => {
950                return Err(format!(
951                    "MEMRA_MTP_DRAFT points at a non-step35 GGUF (arch {:?}) but the model is \
952                     step35 — the draft block's per-layer geometry is unknowable from the trunk \
953                     config (its arrays stop at the trunk's last layer)",
954                    g.arch()
955                ).into())
956            }
957            (None, Some(_)) => {
958                return Err("MEMRA_MTP_DRAFT is a step35 draft but the model is not step35".into())
959            }
960            (None, None) => None,
961        };
962        if step35.is_none() && !student {
963            // The head forward runs with the MAIN model's cfg — the draft block must be the
964            // same shape or the forward is garbage.
965            assert_eq!(dcfg.n_head, main_cfg.n_head, "draft n_head != model n_head");
966            assert_eq!(
967                dcfg.n_head_kv, main_cfg.n_head_kv,
968                "draft n_head_kv != model n_head_kv"
969            );
970        }
971
972        // Draft lm_head. PREFERENCE ORDER IS THE ARTIFACT'S, NOT OURS (upstream step35.cpp:553
973        // `layer.nextn.shared_head_head ? ... : model.output`): a NextN block owns its OWN head,
974        // and only a file that omits it falls back to the file-level `output.weight`.
975        //
976        // MEASURED ON THE SHIPPED ARTIFACT (Step3.7-flash-mtp-Q8_0.gguf, byte hashes in
977        // research/step37-p2-20260806/raw/draft-head-tensor-hashes-20260807.txt): the file carries
978        // BOTH, they are DIFFERENT matrices, and the three MTP blocks' heads differ from each
979        // other too —
980        //     output.weight                        sha 3eec5831…  <- the TRUNK lm_head, re-quantized
981        //     blk.45.nextn.shared_head_head.weight sha c90b907b…  <- block 45's own head
982        //     blk.46 …                             sha a22d2957…
983        //     blk.47 …                             sha 4b21e137…
984        // The tell: this file's top-level `output_norm.weight` is BYTE-IDENTICAL to the trunk
985        // artifact's (both sha d7526f44…), i.e. the top level is a copy of the trunk's output
986        // stack, present so the draft gguf stands alone. Reading it as the draft head projects
987        // the MTP block's hidden through the TRUNK's head — coherent-looking drafts the verify
988        // never accepts. Receipt: acceptance 0/248 across K=1..8 with self-consistency PASS
989        // (raw/mtp-draft-20260806T212902Z.log) — the exact failure class run_spec.rs's
990        // "acceptance == 0 with identical output" WARNING exists to catch.
991        //
992        // FR-Spec drafts (trimmed [n_embd, draft_vocab] + d2t) publish the trimmed head as the
993        // file-level `output.weight` and carry no `nextn.shared_head_head`, so they keep the
994        // fallback — hence preference, not replacement.
995        // Name choice is factored into `draft_head_tensor` so it is testable WITHOUT a GPU or a
996        // 3.5 GB artifact (this whole function needs both). Getting it wrong is invisible to
997        // every exactness gate, so the choice itself is pinned by a unit test.
998        let head_name = draft_head_tensor(|t| src.has(t), n);
999        let head = load_t(e, &src, &head_name)?;
1000        let head_norm = match load_opt(e, &src, &p("nextn.shared_head_norm.weight"))? {
1001            Some(t) => Some(t),
1002            None => load_opt(e, &src, "output_norm.weight")?,
1003        };
1004
1005        // d2t: draft-row -> target-token-id map (absolute ids, verified against the tokenizer).
1006        let d2t: Option<Vec<u32>> = g.find("d2t").map(|t| {
1007            let bytes = g.tensor_data(t);
1008            match t.ggml_type {
1009                GgmlType::I32 => bytes
1010                    .chunks_exact(4)
1011                    .map(|c| i32::from_le_bytes(c.try_into().unwrap()) as u32)
1012                    .collect(),
1013                GgmlType::I64 => bytes
1014                    .chunks_exact(8)
1015                    .map(|c| i64::from_le_bytes(c.try_into().unwrap()) as u32)
1016                    .collect(),
1017                other => panic!("d2t must be I32/I64, got {other:?}"),
1018            }
1019        });
1020        if let Some(map) = &d2t {
1021            assert_eq!(
1022                map.len(),
1023                head.out_features(),
1024                "d2t len {} != draft head rows {}",
1025                map.len(),
1026                head.out_features()
1027            );
1028            let n_vocab = main_cfg.n_vocab as u64;
1029            assert!(
1030                map.iter().all(|&t| (t as u64) < n_vocab),
1031                "d2t contains token id >= model n_vocab {n_vocab}"
1032            );
1033        }
1034        let eh_proj = load_t(e, &src, &p("nextn.eh_proj.weight"))?;
1035        // defensive load gates (review feedback): a malformed student gguf fails HERE with a
1036        // named assert, not later as garbage drafts. eh_proj consumes concat(e_norm, h_norm).
1037        assert_eq!(
1038            eh_proj.in_features(),
1039            2 * main_cfg.n_embd as usize,
1040            "eh_proj in dim != 2*n_embd"
1041        );
1042        let geom = if student {
1043            let out_up = load_t(e, &src, &p("nextn.out_up.weight"))?;
1044            let d_inner = eh_proj.out_features();
1045            assert_eq!(
1046                out_up.out_features(),
1047                main_cfg.n_embd as usize,
1048                "out_up out dim != n_embd"
1049            );
1050            assert_eq!(
1051                out_up.in_features(),
1052                d_inner,
1053                "out_up in dim != eh_proj out dim (d_inner)"
1054            );
1055            assert!(
1056                dcfg.n_head >= 1 && dcfg.n_head_kv >= 1 && dcfg.n_head % dcfg.n_head_kv == 0,
1057                "student head counts malformed ({}/{})",
1058                dcfg.n_head,
1059                dcfg.n_head_kv
1060            );
1061            Some(DraftGeom {
1062                d_inner,
1063                n_head: dcfg.n_head as usize,
1064                n_head_kv: dcfg.n_head_kv as usize,
1065                out_up,
1066            })
1067        } else {
1068            None
1069        };
1070        // Log the name WITHOUT the blk.{n}. prefix (already printed) so the line reads
1071        // `source=nextn.shared_head_head` vs `source=output.weight` — the one-glance receipt
1072        // that the head choice went the right way on this artifact.
1073        let blk_prefix = format!("blk.{n}.");
1074        let head_src = head_name.strip_prefix(&blk_prefix).unwrap_or(&head_name);
1075        eprintln!(
1076            "[mtp-draft] external draft head: blk.{n}, source={}, head_vocab={}{}{}",
1077            head_src,
1078            head.out_features(),
1079            if d2t.is_some() {
1080                " (trimmed, d2t map)"
1081            } else {
1082                " (full)"
1083            },
1084            match &geom {
1085                Some(g) => format!(
1086                    " (student d_inner={} heads={}/{})",
1087                    g.d_inner, g.n_head, g.n_head_kv
1088                ),
1089                None => String::new(),
1090            }
1091        );
1092
1093        let mut resident = ResidentPlan::unsharded(e, &src, &dcfg);
1094        Ok(MtpHead {
1095            enorm: load_t(e, &src, &p("nextn.enorm.weight"))?,
1096            hnorm: load_t(e, &src, &p("nextn.hnorm.weight"))?,
1097            eh_proj,
1098            attn_norm: load_t(e, &src, &p("attn_norm.weight"))?,
1099            post_attn_norm: load_opt(e, &src, &p("post_attention_norm.weight"))?
1100                .or(load_opt(e, &src, &p("ffn_norm.weight"))?)
1101                .expect("draft NextN block needs post_attention_norm or ffn_norm"),
1102            mixer: load_mixer_kind(e, &src, n, LayerKind::FullAttention, dcfg.mla.as_ref(),
1103                                   dcfg.attn_gate_separate())?,
1104            ffn: load_ffn(e, &src, &dcfg, n, None, &mut resident)?,
1105            shared_head_norm: head_norm,
1106            shared_head_head: Some(head),
1107            d2t,
1108            geom,
1109            step35,
1110        })
1111    }
1112}
1113
1114/// gemma4 model-level auxiliaries.
1115pub struct GemmaAux {
1116    /// rope_freqs.weight [hd_global/2] freq factors — global layers' RoPE (R9).
1117    pub rope_freqs: Option<CudaSlice<f32>>,
1118    /// all-ones norm weight [512] (max head_dim) — the weightless rms_norms (R7 V-norm).
1119    pub ones: CudaSlice<f32>,
1120    /// tokenizer suppress_tokens uploaded once (None when the model ships none) — masked to
1121    /// -inf on every logits row before argmax/sampling (12B QAT ships two control ids).
1122    pub suppress_d: Option<(CudaSlice<i32>, usize)>,
1123    /// E4B per-layer-embedding model tensors (None on 26B/31B).
1124    pub e4b: Option<Gemma4E4bModel>,
1125}
1126
1127/// step35 model-level auxiliaries. Deliberately NOT folded into `GemmaAux`: every gemma4 path
1128/// does `gemma4_aux.as_ref().unwrap()` and would then also fire on a step35 model.
1129pub struct Step35Aux {
1130    /// `rope_freqs.weight [n_rot_full/2]` llama3-style freq factors. Upstream applies them to
1131    /// FULL-attention layers ONLY (`rope_factors = is_swa ? nullptr : get_rope_factors(...)`,
1132    /// step35.cpp:246) — the SWA layers pass a null factor pointer. Step-3.7-Flash ships [64] F32.
1133    pub rope_freqs: Option<CudaSlice<f32>>,
1134}
1135
1136pub struct HybridModel {
1137    pub cfg: ModelConfig,
1138    pub embd: EmbedHost,
1139    pub output_norm: GpuTensor,
1140    pub output: GpuTensor,
1141    pub layers: Vec<HybridLayer>,
1142    pub mtp: Option<MtpHead>, // NextN spec-decode head (None if nextn_predict_layers == 0)
1143    /// Lazily-uploaded DEVICE copy of the raw embed table (spec/graph hot loops gather rows
1144    /// on-device instead of host-dequant + htod). ~0.5GB; uploaded once on first use.
1145    pub embd_gpu: std::sync::OnceLock<cudarc::driver::CudaSlice<u8>>,
1146    pub gemma4_aux: Option<GemmaAux>,
1147    /// step35 (Step-3.7-Flash) model auxiliaries — `Some` iff `cfg.step35.is_some()`.
1148    pub step35_aux: Option<Step35Aux>,
1149    /// PRIME ACTIVATION SLABS (piecewise-graph foundation, 2026-07-26): the layer loop's
1150    /// seven trunk transients live in RESIDENT per-model buffers instead of per-call pool
1151    /// allocs — kills ~224 alloc/free API calls per prime AND freezes the Lt GEMM operand
1152    /// addresses (nvjet's alignment-variant kernels become run-to-run stable once their
1153    /// pointers stop moving). Sized on first prime to the largest T seen; Mutex = lazy init
1154    /// only (single GPU worker).
1155    pub prime_slabs: std::sync::Mutex<std::collections::HashMap<usize, crate::hybrid_forward::PrimeSlabs>>,
1156}
1157
1158impl HybridModel {
1159    /// Load a hybrid (qwen35) model from GGUF. Thin byte-identical wrapper over `load_from_source`.
1160    pub fn load(e: &Engine, g: &GgufFile) -> Result<Self, Box<dyn std::error::Error>> {
1161        Self::load_from_source(e, &GgufSource(g))
1162    }
1163
1164    /// Plain-generation loader. `run-gen` never calls the optional draft head, so avoid loading
1165    /// its weights and expert bank while preserving the model config and all trunk semantics.
1166    pub fn load_without_mtp(e: &Engine, g: &GgufFile) -> Result<Self, Box<dyn std::error::Error>> {
1167        Self::load_from_source_impl(e, &GgufSource(g), false)
1168    }
1169
1170    /// Load a hybrid model from any `TensorSource` (GGUF or a safetensors HF checkpoint). The whole
1171    /// loop speaks ggml names; the source maps them (and, for safetensors, applies the SSM value
1172    /// transforms via the owned-buffer seam). The forward graph is untouched.
1173    pub fn load_from_source(
1174        e: &Engine,
1175        src: &dyn TensorSource,
1176    ) -> Result<Self, Box<dyn std::error::Error>> {
1177        Self::load_from_source_impl(e, src, true)
1178    }
1179
1180    /// Source-backed twin of `load_without_mtp`, used by the safetensors/repack `run-gen` path.
1181    pub fn load_from_source_without_mtp(
1182        e: &Engine,
1183        src: &dyn TensorSource,
1184    ) -> Result<Self, Box<dyn std::error::Error>> {
1185        Self::load_from_source_impl(e, src, false)
1186    }
1187
1188    fn load_from_source_impl(
1189        e: &Engine,
1190        src: &dyn TensorSource,
1191        load_mtp: bool,
1192    ) -> Result<Self, Box<dyn std::error::Error>> {
1193        let cfg = src.config();
1194        assert!(cfg.arch.is_hybrid(), "not a hybrid arch");
1195        // SPEC-SERVING stream-k key, per model, set at LOAD so it governs the PRIME too
1196        // (2026-07-27; explicit MEMRA_MMQ_SK wins): the sk autotune's per-process kernel
1197        // coin flips knife-edge prime shapes between kernels run-to-run — the 12B depth
1198        // spec cell was BIMODAL (205 @ 0.756 / 260 @ 0.943 identical invocations; tiling
1199        // x6 = stable 263-269 @ 0.953, chat +3%; 31B neutral). The 26B is opposite: its
1200        // drafter accepts BETTER under sk's fold order (depth 328 @ 0.826 vs 293 @ 0.750).
1201        // Big dense (n_embd >= 3500) forces tiling under spec intent; MoE/small keep sk.
1202        // An earlier attempt set this in generate_spec_gemma — too late, the prime's
1203        // GEMMs had already autotuned.
1204        if std::env::var("MEMRA_DRAFT").is_ok() && std::env::var("MEMRA_MMQ_SK").is_err() {
1205            let force = if cfg.n_embd >= 3500 { 0i8 } else { -1i8 };
1206            crate::MMQ_SK_FORCE.store(force, std::sync::atomic::Ordering::Relaxed);
1207        }
1208        // FP8-KV door: OFF for every hybrid-path model (35B: fp8 format-gates its v3
1209        // dp4a lane, −2% measured 2026-07-12; gemma keys its KV formats independently
1210        // of this flag). The 9B dense loader is the only ON site.
1211        crate::KV_FP8_FORCE.store(0, std::sync::atomic::Ordering::Relaxed);
1212
1213        // B0 FIX (hoisted): cfg.n_layer == block_count INCLUDES the MTP/NextN block(s)
1214        // (41 for the 35B-MoE); the trunk is n_layer - nextn. Computed before any tensor
1215        // upload because the M2 sharded loader (crate::pp::layer_engine) places tensors
1216        // by the trunk stage map.
1217        let n_trunk = (cfg.n_layer - cfg.nextn_predict_layers) as usize;
1218        let embd = EmbedHost::from_source(src, "token_embd.weight");
1219        // M2 increment 2 (weight sharding): output_norm + lm head upload through the LAST
1220        // stage's engine — the stage that runs them (outside the pp door / MEMRA_PP_SHARD=0
1221        // this is the primary engine, byte-identical to the M1 loader).
1222        let e_head = crate::pp::layer_engine(e, n_trunk, n_trunk - 1)?;
1223        let output_norm = load_t(e_head, src, "output_norm.weight")?;
1224        // tied embeddings: fall back to tok_embd if output.weight absent.
1225        let mut output = if src.has("output.weight") {
1226            load_t(e_head, src, "output.weight")?
1227        } else {
1228            load_t(e_head, src, "token_embd.weight")?
1229        };
1230        let mut resident = ResidentPlan::pp(e, src, &cfg, n_trunk)?;
1231
1232        // SPILLING-PLAN §2: build the tiered-spill context ONCE, before loading any experts, but
1233        // only for a MoE model with the disk tier forced on (`MEMRA_SPILL_DISK`). It probes free VRAM
1234        // + host RAM at runtime (never hardcoded) and opens one shared GGUF mmap; all expert tensors
1235        // draw down its single pinned-RAM budget (hottest pinned, the rest mmap'd from disk). When
1236        // unset/dense this stays `None` and the load takes the byte-identical all-host path.
1237        // Disk spill is GGUF-only (needs the on-disk file mmap); src.gguf() is None for safetensors.
1238        let gguf: Option<&GgufFile> = src.gguf();
1239        // expert_count > 0: Arch::Gemma4 carries cfg.moe = Some on its DENSE variants too
1240        // (the 2026-07-14 discriminator-bug class) — a dense 31B/E4B under the spill env
1241        // would otherwise probe budgets + open an expert mmap it never consumes.
1242        let mut spill: Option<crate::spill::SpillCtx> =
1243            if cfg.moe.as_ref().is_some_and(|m| m.expert_count > 0)
1244                && crate::spill::disk_tier_enabled() && gguf.is_some() {
1245                let budget = crate::spill::MemBudget::probe(e)?;
1246                let ctx = crate::spill::SpillCtx::open(gguf.unwrap(), &budget)?;
1247                eprintln!("[spill] disk tier ON: free_vram={} MiB  pinnable_ram={} MiB (MemAvailable*frac)",
1248                          budget.free_vram >> 20, budget.free_pinnable_ram >> 20);
1249                Some(ctx)
1250            } else { None };
1251
1252        // Running the MTP block as a trunk layer is wrong; iterate only the trunk layers
1253        // (n_trunk hoisted above). 9B (nextn=0): n_trunk = 32. 35B-MoE (nextn=1): 40.
1254        let mut layers = Vec::with_capacity(n_trunk);
1255        for il in 0..n_trunk as u32 {
1256            let p = |s: &str| format!("blk.{il}.{s}");
1257            // M2 weight sharding: this layer's tensors upload through the OWNING stage's
1258            // engine (shadowed `e`) — the bring-up remote peer-read placement dies here.
1259            // Door shut / MEMRA_PP_SHARD=0: `layer_engine` returns the primary (no change).
1260            let e = crate::pp::layer_engine(e, n_trunk, il as usize)?;
1261            // attn_norm always; post_attention_norm is the pre-FFN norm in qwen35
1262            layers.push(HybridLayer {
1263                attn_norm: load_t(e, src, &p("attn_norm.weight"))?,
1264                post_attn_norm: load_opt(e, src, &p("post_attention_norm.weight"))?
1265                    .or(load_opt(e, src, &p("ffn_norm.weight"))?)
1266                    .expect("need post_attention_norm or ffn_norm"),
1267                mixer: {
1268                    // E4B KV-shared layers ship NO attn_k/attn_v — load the SHARE TARGET's
1269                    // k/v tensors for shape symmetry (forward skips k/v compute there and
1270                    // reads the target layer's cache; see Gemma4E4bLayer::kv_share).
1271                    let g4_shared = cfg.gemma4.as_ref().map(|g| g.shared_kv_layers).unwrap_or(0);
1272                    let kv_from = n_trunk as u32 - g4_shared;
1273                    if g4_shared > 0
1274                        && il >= kv_from
1275                        && !src.has(&format!("blk.{il}.attn_k.weight"))
1276                    {
1277                        let g4 = cfg.gemma4.as_ref().unwrap();
1278                        let swa = g4.swa_pattern.get(il as usize).copied().unwrap_or(true);
1279                        let tgt = kv_from - if swa { 2 } else { 1 };
1280                        let tp = |s: &str| format!("blk.{tgt}.{s}");
1281                        Mixer::Full(FullAttnLayer {
1282                            wq: load_t(e, src, &p("attn_q.weight"))?,
1283                            wk: load_t(e, src, &tp("attn_k.weight"))?,
1284                            wv: load_t(e, src, &tp("attn_v.weight"))?,
1285                            wo: load_t(e, src, &p("attn_output.weight"))?,
1286                            q_norm: load_t(e, src, &p("attn_q_norm.weight"))?,
1287                            k_norm: load_t(e, src, &tp("attn_k_norm.weight"))?,
1288                            attn_gate: None, // gemma4 has no separate head-wise gate
1289                        })
1290                    } else {
1291                        load_mixer_kind(e, src, il, cfg.layer_kind(il), cfg.mla.as_ref(),
1292                                        cfg.attn_gate_separate())?
1293                    }
1294                },
1295                ffn: load_ffn(e, src, &cfg, il,
1296                              spill.as_mut().map(|c| (gguf.unwrap(), c)), &mut resident)?,
1297                gemma4: if cfg.gemma4.is_some() {
1298                    let scalar = |n: &str| -> f32 {
1299                        let t = src.find(&p(n)).unwrap_or_else(|| panic!("missing {n}"));
1300                        memra_gguf::dequant::dequantize(t.ggml_type, &t.bytes, 1)[0]
1301                    };
1302                    let vecf = |n: &str| -> Vec<f32> {
1303                        let t = src.find(&p(n)).unwrap_or_else(|| panic!("missing {n}"));
1304                        memra_gguf::dequant::dequantize(
1305                            t.ggml_type,
1306                            &t.bytes,
1307                            t.ne.iter().product::<u64>() as usize,
1308                        )
1309                    };
1310                    let moe_bits = if src.find(&p("ffn_gate_inp.scale")).is_some() {
1311                        Some(crate::hybrid::Gemma4MoeBits {
1312                            post_ffw_norm_1: load_t(e, src, &p("post_ffw_norm_1.weight"))?,
1313                            pre_ffw_norm_2: load_t(e, src, &p("pre_ffw_norm_2.weight"))?,
1314                            post_ffw_norm_2: load_t(e, src, &p("post_ffw_norm_2.weight"))?,
1315                            shared_gate: load_t(e, src, &p("ffn_gate.weight"))?,
1316                            shared_up: load_t(e, src, &p("ffn_up.weight"))?,
1317                            shared_down: load_t(e, src, &p("ffn_down.weight"))?,
1318                            router_scale_pre: {
1319                                let inv = 1.0 / (cfg.n_embd as f32).sqrt();
1320                                let v: Vec<f32> =
1321                                    vecf("ffn_gate_inp.scale").iter().map(|x| x * inv).collect();
1322                                e.htod(&v)?
1323                            },
1324                            per_expert_scale: vecf("ffn_down_exps.scale"),
1325                            per_expert_scale_d: e.htod(&vecf("ffn_down_exps.scale"))?,
1326                        })
1327                    } else {
1328                        None
1329                    };
1330                    // E4B extras (tensor-presence: blk.N.inp_gate only exists on E4B)
1331                    let e4b = if src.has(&p("inp_gate.weight")) {
1332                        let g4 = cfg.gemma4.as_ref().unwrap();
1333                        let kv_from = n_trunk as u32 - g4.shared_kv_layers;
1334                        let kv_share = if g4.shared_kv_layers > 0 && il >= kv_from {
1335                            let swa = g4.swa_pattern.get(il as usize).copied().unwrap_or(true);
1336                            Some(kv_from - if swa { 2 } else { 1 })
1337                        } else {
1338                            None
1339                        };
1340                        Some(crate::hybrid::Gemma4E4bLayer {
1341                            inp_gate: load_t(e, src, &p("inp_gate.weight"))?,
1342                            proj: load_t(e, src, &p("proj.weight"))?,
1343                            post_norm: load_t(e, src, &p("post_norm.weight"))?,
1344                            kv_share,
1345                            qkv_cat: None,   // built at the mirror hook (wave 4b)
1346                        })
1347                    } else {
1348                        None
1349                    };
1350                    Some(Gemma4LayerBits {
1351                        ffn_norm: load_t(e, src, &p("ffn_norm.weight"))?,
1352                        post_ffw_norm: load_t(e, src, &p("post_ffw_norm.weight"))?,
1353                        moe_bits,
1354                        layer_scale: scalar("layer_output_scale.weight"),
1355                        e4b,
1356                    })
1357                } else {
1358                    None
1359                },
1360            });
1361        }
1362
1363        // MTP/NextN head: load the block the trunk loop drops (il = n_trunk). It is a full
1364        // transformer block PLUS the nextn.{enorm,hnorm,eh_proj} glue. Only when nextn>0 and the
1365        // eh_proj tensor actually exists in the file (some MTP GGUFs ship the draft separately).
1366        let mtp = if load_mtp && cfg.nextn_predict_layers > 0 {
1367            let n = n_trunk as u32;
1368            let p = |s: &str| format!("blk.{n}.{s}");
1369            match src.has(&p("nextn.eh_proj.weight")) {
1370                true => Some(MtpHead {
1371                    enorm: load_t(e, src, &p("nextn.enorm.weight"))?,
1372                    hnorm: load_t(e, src, &p("nextn.hnorm.weight"))?,
1373                    eh_proj: load_t(e, src, &p("nextn.eh_proj.weight"))?,
1374                    attn_norm: load_t(e, src, &p("attn_norm.weight"))?,
1375                    post_attn_norm: load_opt(e, src, &p("post_attention_norm.weight"))?
1376                        .or(load_opt(e, src, &p("ffn_norm.weight"))?)
1377                        .expect("MTP block needs post_attention_norm or ffn_norm"),
1378                    mixer: load_mixer_kind(e, src, n, LayerKind::FullAttention, cfg.mla.as_ref(),
1379                                           cfg.attn_gate_separate())?,
1380                    ffn: load_ffn(e, src, &cfg, n,
1381                                  spill.as_mut().map(|c| (gguf.unwrap(), c)), &mut resident)?,
1382                    shared_head_norm: load_opt(e, src, &p("nextn.shared_head_norm.weight"))?,
1383                    // `nextn.shared_head_head` is the name the convert script and upstream both
1384                    // use (LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD -> "blk.%d.nextn.shared_head_head");
1385                    // `nextn.shared_head` is a name no shipped artifact carries, so this arm was
1386                    // silently always-None and every embedded-MTP model fell back to the trunk
1387                    // `self.output` in `mtp_head_forward_dev` op 12. Harmless for qwen35-family
1388                    // heads that genuinely tie to the trunk head; wrong for any artifact that
1389                    // ships its own — which the StepFun step35 drafter does (see `load_draft`).
1390                    // Keep the old name as a fallback so nothing that did match still does.
1391                    shared_head_head: load_opt(e, src, &p("nextn.shared_head_head.weight"))?
1392                        .or(load_opt(e, src, &p("nextn.shared_head.weight"))?),
1393                    d2t: None,
1394                    geom: None,
1395                    // EMBEDDED MTP block: same file, so its own arrays cover index `n`.
1396                    step35: cfg.step35.as_ref().map(|s| Step35MtpGeom::resolve(s, n)),
1397                }),
1398                false => None, // nextn>0 but no embedded eh_proj (external draft GGUF) -> no head
1399            }
1400        } else {
1401            None
1402        };
1403
1404        // MEMRA_MTP_DRAFT=<path.gguf>: REPLACE the MTP head with one loaded from a standalone
1405        // draft GGUF (e.g. an FR-Spec trimmed-vocab draft). Verify-based spec decode stays exact
1406        // regardless of the draft — a different draft only changes WHICH tokens get proposed.
1407        let mtp = if load_mtp {
1408            match std::env::var("MEMRA_MTP_DRAFT") {
1409                Ok(path) if !path.is_empty() => {
1410                    eprintln!("[mtp-draft] loading external MTP draft: {path}");
1411                    let dg = GgufFile::open(&path)?;
1412                    Some(MtpHead::load_draft(e, &dg, &cfg)?)
1413                }
1414                _ => mtp,
1415            }
1416        } else {
1417            None
1418        };
1419
1420        // MEMRA_FRSPEC_TRIM=<frspec.gguf>: SELF-TRIMMED draft head. Reads ONLY the d2t ranked-token
1421        // list from the given file and gathers those rows from the MAIN model's own output.weight
1422        // bytes (quantized rows are independent — a byte-level row gather, zero requant). The MTP
1423        // block, norms, and head quant all stay main-model, so there is no cross-file quality
1424        // mismatch (the external Q4_K draft file measured -15pts acceptance vs the native block).
1425        // Draft lm_head reads drop vocab/32768-fold; verify stays full-vocab -> exactness unchanged.
1426        // FULL_PREC (MTP-heal ceiling): the self-trim gathers rows into `from_quant_bytes` (Quant
1427        // only) and, more to the point, the full-precision ceiling wants the model's NATURAL full
1428        // head — trimming the draft vocab is a speed lever, not part of the exactness measurement.
1429        // Disable trim under the flag (documented resolution, §item 2).
1430        let trim_env = if load_mtp {
1431            std::env::var("MEMRA_FRSPEC_TRIM")
1432        } else {
1433            Err(std::env::VarError::NotPresent)
1434        };
1435        if crate::model::full_prec_enabled()
1436            && trim_env.as_deref().map(|p| !p.is_empty()).unwrap_or(false)
1437        {
1438            eprintln!(
1439                "[frspec-trim] DISABLED under MEMRA_FULL_PREC — using the natural full MTP head"
1440            );
1441        }
1442        let mtp = match (
1443            if crate::model::full_prec_enabled() {
1444                Err(std::env::VarError::NotPresent)
1445            } else {
1446                trim_env
1447            },
1448            mtp,
1449        ) {
1450            (Ok(path), Some(mut head)) if !path.is_empty() => {
1451                let tg = GgufFile::open(&path)?;
1452                let d2t_t = tg
1453                    .find("d2t")
1454                    .expect("MEMRA_FRSPEC_TRIM file has no d2t tensor");
1455                let d2t_bytes = tg.tensor_data(d2t_t);
1456                let d2t: Vec<u32> = match d2t_t.ggml_type {
1457                    GgmlType::I32 => d2t_bytes
1458                        .chunks_exact(4)
1459                        .map(|c| i32::from_le_bytes(c.try_into().unwrap()) as u32)
1460                        .collect(),
1461                    GgmlType::I64 => d2t_bytes
1462                        .chunks_exact(8)
1463                        .map(|c| i64::from_le_bytes(c.try_into().unwrap()) as u32)
1464                        .collect(),
1465                    other => panic!("d2t must be I32/I64, got {other:?}"),
1466                };
1467                let v = src
1468                    .find("output.weight")
1469                    .or_else(|| src.find("token_embd.weight"))
1470                    .expect("model has no output.weight for FR-Spec trim");
1471                let out_f = v.ne[1] as usize;
1472                let row_bytes = v.bytes.len() / out_f;
1473                assert!(
1474                    d2t.iter().all(|&t| (t as usize) < out_f),
1475                    "d2t token id >= lm_head rows {out_f}"
1476                );
1477                let mut gathered = Vec::with_capacity(d2t.len() * row_bytes);
1478                for &t in &d2t {
1479                    let off = t as usize * row_bytes;
1480                    gathered.extend_from_slice(&v.bytes[off..off + row_bytes]);
1481                }
1482                let trimmed = GpuTensor::from_quant_bytes(
1483                    e,
1484                    &gathered,
1485                    v.ggml_type,
1486                    v.ne[0],
1487                    d2t.len() as u64,
1488                    /*nvfp4 macro-scale*/
1489                    match src.find("output.scale") {
1490                        Some(sv) => f32::from_le_bytes(sv.bytes[..4].try_into().unwrap()),
1491                        None => 1.0,
1492                    },
1493                )?;
1494                eprintln!(
1495                    "[frspec-trim] self-trimmed head: {} rows of main output.weight ({:?})",
1496                    d2t.len(),
1497                    v.ggml_type
1498                );
1499                head.shared_head_head = Some(trimmed);
1500                head.d2t = Some(d2t);
1501                Some(head)
1502            }
1503            (_, m) => m,
1504        };
1505
1506        if let Some(ctx) = spill.as_ref() {
1507            eprintln!(
1508                "[spill] experts placed: {} pinned (Tier 1), {} mmap'd from disk (Tier 2, {} MiB)",
1509                ctx.n_pinned,
1510                ctx.n_mmap,
1511                ctx.mmap_bytes >> 20
1512            );
1513        }
1514
1515        // FA v4 GQA CAPACITY GUARD (2026-08-06, lane/122b-bringup): fa_v4_smem sizes its
1516        // per-warp Q arrays q_ints[8][64]/q_d[8][8] for gqa<=8 — every model before the
1517        // 122B-A10B (32 Q heads / 2 KV heads = gqa 16) fit. At gqa>8 the (32,gqa,1) block's
1518        // warps 8..15 write q_ints[wy] PAST the array into the k_ints/k_d K tile, corrupting
1519        // scores -> all-NaN decode logits (receipts: research/122b-bringup-20260806/, arm
1520        // battery: v4/deep MISMATCH+NaN, v3/v2/smem/reg/scalar all MATCH). The hd512 lane
1521        // already carries its own capacity guard at dispatch ("gqa <= 16 = fa_v4_smem_512's
1522        // q-array capacity"); hd256 v4 never got one. Key FA_V4_MAX_DEFAULT=0 at load so
1523        // EVERY v4 dispatch site (eager, rows-verify, dc, rows_dc, windowed, seqs) flips to
1524        // the v3 lane together — decode/verify stay kernel-family-identical (the parity law).
1525        // Explicit MEMRA_FA_V4_MAX env still wins (diagnostic seam). The real v4 gqa16
1526        // extension is a kernel change gated on its own battery + perf receipts (fix brief
1527        // in research/122b-bringup-20260806/VERDICT.md).
1528        if cfg.n_head_kv > 0 && cfg.n_head / cfg.n_head_kv > 8 {
1529            crate::FA_V4_MAX_DEFAULT.store(0, std::sync::atomic::Ordering::Relaxed);
1530            eprintln!(
1531                "[fa] v4 decode family disabled: gqa {} > fa_v4_smem capacity 8 (v3 lane serves)",
1532                cfg.n_head / cfg.n_head_kv
1533            );
1534        }
1535
1536        if cfg.gemma4.is_some() {
1537            // gemma4 fa-vec crossover default (measured sweep 2026-07-10; env overrides).
1538            crate::FA_VEC_MIN_DEFAULT.store(1, std::sync::atomic::Ordering::Relaxed);
1539            // windowed split per gemma variant (2026-07-12 sweeps): MoE 26B = 32 (grid-limited
1540            // t=1 under the raw-e4m3 sV ceiling), dense 31B = 64 (37.13 vs 36.87 at 1.7k, N=2).
1541            // DISCRIMINATOR FIX (2026-07-14): Arch::Gemma4 is in is_moe(), so cfg.moe is
1542            // Some (expert_count 0) on the DENSE 31B/E4B too — `cfg.moe.is_some()` keyed
1543            // every "per-variant" default to the 26B values and the dense arms of the
1544            // 2026-07-12 sweeps (SPW 64, SP512 32) never actually reached the 31B. Key on
1545            // expert_count instead.
1546            let real_moe = cfg.moe.as_ref().is_some_and(|m| m.expert_count > 0);
1547            crate::FA_SPW_DEFAULT.store(if real_moe { 32 } else { 64 },
1548                                        std::sync::atomic::Ordering::Relaxed);
1549            // hd512 global split per variant (26B=16 landed 2026-07-11; 31B=32 swept 2026-07-12).
1550            crate::FA_SP512_DEFAULT.store(if real_moe { 16 } else { 32 },
1551                                          std::sync::atomic::Ordering::Relaxed);
1552            // gemma4 router w8 RE-ARBITRATED 2026-08-01 (g26 decode dig): the 2026-07-31
1553            // knife-edge that stored false here was single-synthetic-prompt roulette — on 6
1554            // real prompts the w8 twin's gate outcome is IDENTICAL to the lone-warp form
1555            // (5 MATCH/5 MATCH; the one MISMATCH prompt fails both arms with the same
1556            // argmax pair, router-independent). w8 = +13% g26 decode (182->206 tok/s x3
1557            // interleaved, H100). Receipts: research/g26-decode-20260801/. gemma4 now rides
1558            // the global default (true); MEMRA_ROUTER_V2=0 is the rollback seam.
1559            // fused t=1 pair/triple mr1 per variant (2026-07-14 DRAM-duty arc: dense +1.1%
1560            // short / +0.6% depth on 31B; MoE 26B −1.2% — stays mr2).
1561            crate::FUSED_MR1_DEFAULT.store(!real_moe,
1562                                           std::sync::atomic::Ordering::Relaxed);
1563            // gemma4 rms_norm block 1024 (single-row 2816-col norms; battery-arbitrated per model).
1564            crate::RMS_BLOCK_DEFAULT.store(1024, std::sync::atomic::Ordering::Relaxed);
1565            // gemma4 fa split ladder (d1736 sweep; see fa_split_keys).
1566            crate::FA_SP_GEMMA.store(true, std::sync::atomic::Ordering::Relaxed);
1567            // depth fa: PARITY LAW (2026-07-10) — decode and verify share the rows_w/rows_dpl16
1568            // kernel symbols (decode t=1), so lane choice is freely tunable; v4 measured the
1569            // depth winner. Seams: MEMRA_FA_V4_MAX / MEMRA_FA_SMEM_TKV / MEMRA_GEMMA_ROWS_W.
1570        }
1571        // gemma4: the dc serving loop + spec draft gather read the device embed table every
1572        // step — upload it AT LOAD (OnceLock init) so first-use cost never lands in a timed span.
1573        let force_embd_gpu = cfg.gemma4.is_some();
1574        let gemma4_aux = if cfg.gemma4.is_some() {
1575            let rope_freqs = match src.find("rope_freqs.weight") {
1576                Some(t) => Some(e.htod(&memra_gguf::dequant::dequantize(
1577                    t.ggml_type,
1578                    &t.bytes,
1579                    t.ne.iter().product::<u64>() as usize,
1580                ))?),
1581                None => None,
1582            };
1583            // E4B per-layer-embedding model tensors (tensor-presence gated).
1584            let e4b = match src.find("per_layer_token_embd.weight") {
1585                Some(t) => {
1586                    let n_epl = cfg
1587                        .gemma4
1588                        .as_ref()
1589                        .map(|g| g.n_embd_per_layer as usize)
1590                        .unwrap_or(0);
1591                    let row = t.ne[0] as usize; // n_epl * n_layer
1592                    let row_bytes = t.bytes.len() / (t.ne[1] as usize);
1593                    eprintln!(
1594                        "[gemma4-e4b] per-layer-embed model detected (n_epl={n_epl}, row {row}) — \
1595                               first-light forward (eager decode + prime); dc/graph/spec unwired \
1596                               (HANDOVER-E4B.md)"
1597                    );
1598                    Some(crate::hybrid::Gemma4E4bModel {
1599                        tok_tbl_gpu: std::sync::OnceLock::new(),
1600                        tok_embd_bytes: t.bytes.to_vec(),
1601                        tok_embd_qt: match t.ggml_type {
1602                            memra_gguf::GgmlType::Q6_K => crate::QT_Q6_K,
1603                            memra_gguf::GgmlType::Q8_0 => crate::QT_Q8_0,
1604                            other => panic!("e4b per-layer tok embd: unhandled dtype {other:?}"),
1605                        },
1606                        tok_embd_row_bytes: row_bytes,
1607                        model_proj: load_t(e, src, "per_layer_model_proj.weight")?,
1608                        proj_norm: load_t(e, src, "per_layer_proj_norm.weight")?,
1609                        n_epl,
1610                    })
1611                }
1612                None => None,
1613            };
1614            let suppress_d = {
1615                let sup = &cfg.gemma4.as_ref().unwrap().suppress_tokens;
1616                if sup.is_empty() { None } else {
1617                    let ids: Vec<i32> = sup.iter().map(|&x| x as i32).collect();
1618                    eprintln!("[gemma4] suppress_tokens: {} ids masked at sampling", ids.len());
1619                    Some((e.htod_i32(&ids)?, ids.len()))
1620                }
1621            };
1622            Some(GemmaAux {
1623                rope_freqs,
1624                ones: e.htod(&[1.0f32; 512])?,
1625                suppress_d,
1626                e4b,
1627            })
1628        } else {
1629            None
1630        };
1631        // step35: rope_freqs.weight [n_rot_full/2] — FULL-attn layers only (SWA passes null).
1632        // Loaded by tensor presence, not required: the key is absent on a sibling without
1633        // llama3-style scaling, and `None` is the correct "no factors" signal for rope_neox2.
1634        let step35_aux = if cfg.step35.is_some() {
1635            let rope_freqs = match src.find("rope_freqs.weight") {
1636                Some(t) => Some(e.htod(&memra_gguf::dequant::dequantize(
1637                    t.ggml_type,
1638                    &t.bytes,
1639                    t.ne.iter().product::<u64>() as usize,
1640                ))?),
1641                None => None,
1642            };
1643            Some(Step35Aux { rope_freqs })
1644        } else {
1645            None
1646        };
1647        let mut layers = layers;
1648        // Q8_0 SPLIT-PLANE DECODE MIRRORS (2026-07-26, the H100 lane): Q8_0-trunk models
1649        // (Qwen3.5-9B class) stream their whole weight mass through the 34B-stride GGUF
1650        // layout — ncu on H100 held Max Bandwidth at 41-46% (Mem Busy 66-76%) from sector
1651        // overfetch. Mirrors route the m<=16 mmvq/batched decode family to the aligned-16B
1652        // `_rp` twins (bit-identical). VRAM cost == the mirrored trunk (~model size), so
1653        // DEFAULT ON only on the Hopper lane (80GB); MEMRA_Q8RP=1/0 overrides either way.
1654        {
1655            let q8rp_on = match std::env::var("MEMRA_Q8RP").as_deref() {
1656                Ok("0") => false,
1657                Ok(_) => true,
1658                Err(_) => cfg!(memra_hopper_mma),
1659            };
1660            // K-quant split-plane mirrors (q4_K/q6_K, 2026-08-01 H100 coalescing fix) ride
1661            // the same trunk walk under their own seam (MEMRA_KQRP, default = hopper lane).
1662            let kqrp_on = crate::Engine::kqrp_enabled();
1663            if q8rp_on || kqrp_on {
1664                // f16 prefill mirrors, PER-MODEL argmax-gate arbitration (round 45): on the
1665                // qwen Q8_0 dense class the f16-prefill-vs-int8-decode gap (maxdiff ~0.67)
1666                // flips the run-gen argmax gate on real prompts (board-2048: 485 vs 332,
1667                // deterministic x5) — gate-violating defaults don't ship. gemma (Q4_0) and
1668                // the MoE hybrids hold MATCH on the same prompt and keep their mirrors.
1669                // MEMRA_PP_F16=1 forces (diagnostic seam); =0 still kills everywhere.
1670                let f16_model_ok = cfg.gemma4.is_some() || cfg.moe.is_some()
1671                    || std::env::var("MEMRA_PP_F16").as_deref() == Ok("1");
1672                let mut nmir = 0usize;
1673                // M2 weight sharding: mirrors are the DECODE weights on these paths — each
1674                // builds through its layer's OWNING stage engine (`e_ref` param), so the
1675                // mirror lands on the device that dereferences it.
1676                let mut mir = |e_ref: &crate::Engine, w: &mut crate::model::GpuTensor| -> Result<(), Box<dyn std::error::Error>> {
1677                    let before = matches!(w, crate::model::GpuTensor::Quant { rp4: Some(_), .. });
1678                    if q8rp_on { e_ref.build_q8_rp4(w)?; }
1679                    if kqrp_on {
1680                        e_ref.build_q4k_rp4(w)?;
1681                        e_ref.build_q6k_rp4(w)?;
1682                    }
1683                    // Q6_K mirrors are model-CLASS-agnostic (round 47): no MMQ arm exists for
1684                    // Q6_K — the fallback dequant-GEMM is ~10x the f16 lane (q27's prefill
1685                    // wall). The qwen-dense argmax-flip evidence (round 45) was the Q8_0
1686                    // mirror specifically; Q6_K admission is arbitrated by its own gate runs.
1687                    let q6k = matches!(w, crate::model::GpuTensor::Quant { qtype, .. }
1688                                       if *qtype == crate::QT_Q6_K);
1689                    if q8rp_on && crate::f16_ffi::pp_f16_enabled() && (f16_model_ok || q6k) {
1690                        e_ref.build_q8_f16(w)?;
1691                    }
1692                    if !before && matches!(w, crate::model::GpuTensor::Quant { rp4: Some(_), .. }) {
1693                        nmir += 1;
1694                    }
1695                    Ok(())
1696                };
1697                for (il, layer) in layers.iter_mut().enumerate() {
1698                    let el = crate::pp::layer_engine(e, n_trunk, il)?;
1699                    match &mut layer.mixer {
1700                        Mixer::Full(fa) => {
1701                            for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] { mir(el, w)?; }
1702                        }
1703                        Mixer::Linear(la) => {
1704                            for w in [&mut la.wqkv, &mut la.wqkv_gate, &mut la.ssm_beta,
1705                                      &mut la.ssm_alpha, &mut la.ssm_out] { mir(el, w)?; }
1706                        }
1707                        // MLA: no decode mirrors in increment 2 (its kernels arrive in inc 4;
1708                        // mirror admission is arbitrated there with measurements).
1709                        Mixer::Mla(_) => {}
1710                    }
1711                    if let Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &mut layer.ffn {
1712                        for w in [ffn_gate, ffn_up, ffn_down] { mir(el, w)?; }
1713                    }
1714                }
1715                mir(e_head, &mut output)?;
1716                if nmir > 0 {
1717                    eprintln!("[q8rp] split-plane decode mirrors built: {nmir} tensors");
1718                }
1719                // Q4_K f16 prefill mirrors (round 49): Q4_K joins the q6k carve-out —
1720                // model-class-agnostic admission, arbitrated by per-model argmax gates
1721                // (the round-45 flip evidence was the Q8_0 mirror on qwen-dense; the q27
1722                // Q4_K bulk rides mul_mat_q_q45k int8-MMA, which the Lt f16 lane beats at
1723                // large m — campaign-A precedent). SECOND pass over the trunk so the shared
1724                // MEMRA_PP_F16_BUDGET_MB keeps FULL Q6_K coverage as its floor: Q6_K mirrors
1725                // replace a ~10x dequant-GEMM (no MMQ arm exists), Q4_K mirrors upgrade a
1726                // working int8-MMA arm — a joint walk would evict late-layer Q6_K mirrors
1727                // for the weaker lever. Layer-order prefix within the Q4_K class.
1728                // Round 49b: Q5_K (q27's 48 ssm_out — the last mul_mat_q_q45k class) rides
1729                // a THIRD pass strictly after all Q4_K, so the default-budget composition
1730                // (and its banked gates) stays byte-identical: the 32GB default is exhausted
1731                // by the Q4_K pass; Q5_K mirrors only light up under a raised
1732                // MEMRA_PP_F16_BUDGET_MB (machine-specific config).
1733                if q8rp_on && crate::f16_ffi::pp_f16_enabled() {
1734                    for (want, tag) in [(crate::QT_Q4_K, "q4kf16"), (crate::QT_Q5_K, "q5kf16")] {
1735                        let (mut n4, mut b4) = (0usize, 0usize);
1736                        let mut mirk = |e_ref: &crate::Engine, w: &mut crate::model::GpuTensor|
1737                                       -> Result<(), Box<dyn std::error::Error>> {
1738                            if matches!(w, crate::model::GpuTensor::Quant { qtype, f16: None, .. }
1739                                        if *qtype == want) {
1740                                e_ref.build_q8_f16(w)?;
1741                                if let crate::model::GpuTensor::Quant { f16: Some(m), .. } = w {
1742                                    n4 += 1;
1743                                    b4 += m.len();
1744                                }
1745                            }
1746                            Ok(())
1747                        };
1748                        for (il, layer) in layers.iter_mut().enumerate() {
1749                            let el = crate::pp::layer_engine(e, n_trunk, il)?;
1750                            match &mut layer.mixer {
1751                                Mixer::Full(fa) => {
1752                                    for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] { mirk(el, w)?; }
1753                                }
1754                                Mixer::Linear(la) => {
1755                                    for w in [&mut la.wqkv, &mut la.wqkv_gate, &mut la.ssm_beta,
1756                                              &mut la.ssm_alpha, &mut la.ssm_out] { mirk(el, w)?; }
1757                                }
1758                                Mixer::Mla(_) => {} // no mirrors in increment 2 (see above)
1759                            }
1760                            if let Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &mut layer.ffn {
1761                                for w in [ffn_gate, ffn_up, ffn_down] { mirk(el, w)?; }
1762                            }
1763                        }
1764                        mirk(e_head, &mut output)?;
1765                        if n4 > 0 {
1766                            eprintln!("[{tag}] prefill fp16 mirrors built: {n4} tensors \
1767                                       ({} MB)", b4 >> 20);
1768                        }
1769                    }
1770                }
1771            }
1772        }
1773        // Q4_0 SPLIT-PLANE DECODE MIRRORS (2026-07-10, MEMRA_Q4RP seam): gemma-4 MoE-class trunk
1774        // (26B — attn wq/wk/wv/wo + the parallel shared FFN triple). The 18B GGUF block stride
1775        // costs ~25-35% decode bandwidth in sector overfetch (rp_q4_probe: m=1 1.34x, m=3 1.17x,
1776        // bitwise); the mirror (~0.7GB for the 26B) fixes the m<=8 mmvq/batched/fused family.
1777        // Dense 31B is NOT mirrored (its 15GB trunk mirror does not fit 24GB — the full layout
1778        // swap is the follow-up arc); raw bytes stay for prefill/gemm/Stage-A either way.
1779        if cfg.gemma4.is_some() && crate::Engine::q4rp_enabled() {
1780            let mut nmir = 0usize;
1781            for (il, layer) in layers.iter_mut().enumerate() {
1782                // M2 weight sharding: mirrors/concats build through the owning stage engine.
1783                let e = crate::pp::layer_engine(e, n_trunk, il)?;
1784                // 26B MoE-class trunk (moe_bits) OR the E4B dense trunk (e4b bits). E4B mirror
1785                // arithmetic: attn ~7.5MB/layer (shared layers skip wk/wv via build's no-op on
1786                // duplicate mirrors is NOT automatic — they alias the target's tensors as
1787                // separate GpuTensors, so their mirrors double ~1.5MB/shared-layer; acceptable)
1788                // + dense ffn 3 x 2560x10240 Q4_0 ~44MB + inp_gate/proj ~0.75MB => ~2.2GB for
1789                // the 5.2GB model; 24GB card holds model+mirror+KV with >14GB headroom.
1790                // Dense 31B stays unmirrored (15GB mirror does not fit) — its arm is the
1791                // layout-swap follow-up.
1792                let is_moe26 = layer.gemma4.as_ref().is_some_and(|g| g.moe_bits.is_some());
1793                let is_e4b = layer.gemma4.as_ref().is_some_and(|g| g.e4b.is_some());
1794                if !(is_moe26 || is_e4b) {
1795                    continue;
1796                }
1797                if let Mixer::Full(fa) = &mut layer.mixer {
1798                    for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] {
1799                        e.build_q4_rp4(w)?;
1800                        nmir += 1;
1801                    }
1802                }
1803                if is_e4b {
1804                    // wave-4b: own-KV layers get the wq|wk|wv OUT-concat (one matvec at t=1).
1805                    let own_kv = layer.gemma4.as_ref().unwrap().e4b.as_ref()
1806                        .is_some_and(|e4| e4.kv_share.is_none());
1807                    if own_kv {
1808                        if let Mixer::Full(fa) = &layer.mixer {
1809                            if let Some(mut cat) = e.build_q4_out_concat3(&fa.wq, &fa.wk, &fa.wv)? {
1810                                e.build_q4_rp4(&mut cat)?; nmir += 1;
1811                                layer.gemma4.as_mut().unwrap().e4b.as_mut().unwrap()
1812                                    .qkv_cat = Some(cat);
1813                            }
1814                        }
1815                    }
1816                    if let Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &mut layer.ffn {
1817                        for w in [ffn_gate, ffn_up, ffn_down] {
1818                            e.build_q4_rp4(w)?;
1819                            nmir += 1;
1820                        }
1821                    }
1822                    let e4 = layer.gemma4.as_mut().unwrap().e4b.as_mut().unwrap();
1823                    for w in [&mut e4.inp_gate, &mut e4.proj] {
1824                        e.build_q4_rp4(w)?;
1825                        nmir += 1;
1826                    }
1827                }
1828                if let Some(mb) = layer.gemma4.as_mut().unwrap().moe_bits.as_mut() {
1829                    for w in [&mut mb.shared_gate, &mut mb.shared_up, &mut mb.shared_down] {
1830                        e.build_q4_rp4(w)?;
1831                        nmir += 1;
1832                    }
1833                }
1834            }
1835            if nmir > 0 {
1836                eprintln!("[q4rp] split-plane decode mirrors built: {nmir} trunk tensors");
1837            }
1838            // DENSE gemma (31B / E4B trunks): the trunk is too big to MIRROR on 24GB, so the
1839            // split layout replaces the GGUF bytes IN PLACE (zero steady-state VRAM; the 31B
1840            // profile put 76% of decode on the non-rp q4_0 matvecs). Every consumer routes
1841            // off the tensor's rp flag: mmvq/batched `_rp` twins + qmatvec_gemm_q4_0_rp
1842            // prefill. The Stage-A f32 oracle reads GGUF layout, so the swap is gated on the
1843            // fast path being active (MEMRA_FAST=0 keeps GGUF bytes end to end — exact oracle).
1844            let fast_on = std::env::var("MEMRA_FAST").as_deref() != Ok("0");
1845            if fast_on {
1846                let mut nswap = 0usize;
1847                let mut nf16 = 0usize;
1848                // f16 prefill mirrors (campaign A, 2026-07-31): built from the GGUF Q4_0
1849                // bytes BEFORE the in-place rp swap destroys that layout. Same Lt lane and
1850                // budget env as the qwen Q8_0 mirrors (MEMRA_PP_F16 / MEMRA_PP_F16_BUDGET_MB;
1851                // Hopper default ON, sm_120a default OFF — the 24GB card can't carry them).
1852                // Per-model (battery-keyed, 2026-07-31, REAL-prompt gates — the fox-repeat
1853                // family is layout-lottery degenerate and was retired from campaign gates):
1854                // 12B pp1736 8.3k -> 17.1k MATCH; 31B pp1736 4.8k -> 7.6k MATCH but ONLY
1855                // with the full-trunk mirror (420 tensors ~53GB — set
1856                // MEMRA_PP_F16_BUDGET_MB=57344 on 80GB boxes; the default 32GB partial
1857                // mirror measured FLAT there). MEMRA_Q4F16=1|0 forces either way.
1858                let q4f16_model_ok = matches!(cfg.n_embd, 3840 | 5376); // 12B | 31B geometry
1859                let f16_on = match std::env::var("MEMRA_Q4F16").as_deref() {
1860                    Ok("1") => crate::f16_ffi::pp_f16_enabled(),
1861                    Ok("0") => false,
1862                    _ => crate::f16_ffi::pp_f16_enabled() && q4f16_model_ok,
1863                };
1864                for (il, layer) in layers.iter_mut().enumerate() {
1865                    // M2 weight sharding: swap/mirror through the owning stage engine.
1866                    let e = crate::pp::layer_engine(e, n_trunk, il)?;
1867                    let dense_gemma = layer.gemma4.as_ref().is_some_and(|g| g.moe_bits.is_none());
1868                    if !dense_gemma {
1869                        continue;
1870                    }
1871                    if let Mixer::Full(fa) = &mut layer.mixer {
1872                        for w in [&mut fa.wq, &mut fa.wk, &mut fa.wv, &mut fa.wo] {
1873                            if f16_on {
1874                                e.build_q8_f16(w)?;
1875                                if matches!(w, crate::model::GpuTensor::Quant { f16: Some(_), .. }) {
1876                                    nf16 += 1;
1877                                }
1878                            }
1879                            if e.build_q4_rp_swap(w)? {
1880                                nswap += 1;
1881                            }
1882                        }
1883                    }
1884                    if let Ffn::Dense {
1885                        ffn_gate,
1886                        ffn_up,
1887                        ffn_down,
1888                    } = &mut layer.ffn
1889                    {
1890                        for w in [ffn_gate, ffn_up, ffn_down] {
1891                            if f16_on {
1892                                e.build_q8_f16(w)?;
1893                                if matches!(w, crate::model::GpuTensor::Quant { f16: Some(_), .. }) {
1894                                    nf16 += 1;
1895                                }
1896                            }
1897                            if e.build_q4_rp_swap(w)? {
1898                                nswap += 1;
1899                            }
1900                        }
1901                    }
1902                }
1903                if nswap > 0 {
1904                    eprintln!("[q4rp] split-plane IN-PLACE swap: {nswap} dense trunk tensors");
1905                }
1906                if nf16 > 0 {
1907                    eprintln!("[q4f16] prefill fp16 mirrors built: {nf16} dense trunk tensors");
1908                }
1909            }
1910        }
1911        let model = HybridModel {
1912            cfg,
1913            embd,
1914            output_norm,
1915            output,
1916            layers,
1917            mtp,
1918            embd_gpu: std::sync::OnceLock::new(),
1919            gemma4_aux,
1920            step35_aux,
1921            prime_slabs: std::sync::Mutex::new(std::collections::HashMap::new()),
1922        };
1923        e.configure_moe_cache_layout(model.moe_cache_block_sizes());
1924        if force_embd_gpu {
1925            let _ = model
1926                .embd_gpu
1927                .get_or_init(|| e.upload_u8(&model.embd.raw).expect("embed table upload"));
1928        }
1929        // M2 LOAD BARRIER (pp door open at load): uploads + mirror builds above ran on
1930        // the loading engines' worker streams; the first decode consumer runs on OTHER
1931        // streams with no event between them. Synchronize every stage context once so
1932        // no consumer can ever read a half-built tensor (the 2026-08-02 split5 ref=0.0
1933        // head-mirror find). No-op with the door shut.
1934        crate::pp::sync_stages_after_load(e, n_trunk)?;
1935        Ok(model)
1936    }
1937
1938    /// Force the device embed table resident, FALLIBLY (F5 right-size ladder,
1939    /// 2026-08-05). The lazy `embd_gpu.get_or_init(.. expect ..)` sites panic the
1940    /// GPU worker on OOM; on a VRAM-tight rig a right-sized spec session that
1941    /// "fits" can leave too little for this ~hundreds-of-MB upload and die on its
1942    /// first prefill (observed: research/specpool-20260804/server-ladder-miss.log).
1943    /// The server calls this after each ladder landing so the biggest lazy
1944    /// transient surfaces as a catchable Err (shrink further / fall back) instead
1945    /// of a panic. No-op when the host-gather door (MEMRA_EMBED_DEV=0) is open or
1946    /// the table is already resident.
1947    pub fn ensure_embed_resident(&self, e: &Engine) -> Result<(), Box<dyn std::error::Error>> {
1948        if std::env::var("MEMRA_EMBED_DEV").as_deref() == Ok("0") {
1949            return Ok(());
1950        }
1951        if self.embd_gpu.get().is_none() {
1952            let buf = e.upload_u8(&self.embd.raw)?;
1953            let _ = self.embd_gpu.set(buf); // racing set = already resident; fine
1954        }
1955        Ok(())
1956    }
1957
1958    pub fn embed(
1959        &self,
1960        e: &Engine,
1961        tokens: &[u32],
1962    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1963        let n_embd = self.cfg.n_embd as usize;
1964        // DEVICE embed gather (round 30; the gemma4 machinery adopted for every model):
1965        // resident quantized table + gather kernel — replaces the CPU row gather + 31MB
1966        // pageable HtoD (2.2ms at T=2048, the lane's largest host stall). Same d*q
1967        // dequant math as the CPU gather; the greedy-stream A/B arbitrates.
1968        // MEMRA_EMBED_DEV=0 reverts.
1969        if std::env::var("MEMRA_EMBED_DEV").as_deref() != Ok("0") {
1970            let tbl = self
1971                .embd_gpu
1972                .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload"));
1973            let tok_d = e.htod_u32_v(tokens)?;
1974            let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
1975            return e.embed_gather_device_td(tbl, &tok_d, tokens.len(), n_embd, qt, rb);
1976        }
1977        let x = self.embd.gather(n_embd, tokens);
1978        Ok(e.htod(&x)?)
1979    }
1980}
1981
1982#[cfg(test)]
1983mod residency_tests {
1984    use super::residency_bytes_by_device;
1985
1986    #[test]
1987    fn pp_residency_counts_only_each_devices_expert_slice() {
1988        let tensors = [
1989            ("blk.0.ffn_gate_exps.weight", 10usize),
1990            ("blk.0.ffn_up_exps.weight", 20),
1991            ("blk.1.ffn_down_exps.weight", 30),
1992            ("blk.2.ffn_gate_exps.weight", 40),
1993            ("blk.3.ffn_up_exps.weight", 50),
1994            ("blk.0.attn_q.weight", 7),
1995            ("output.weight", 11),
1996        ];
1997        let bytes = residency_bytes_by_device(tensors, &[0, 0, 1, 1], 0);
1998        assert_eq!(bytes.experts.get(&0), Some(&60));
1999        assert_eq!(bytes.experts.get(&1), Some(&90));
2000        assert_eq!(bytes.rest, 18);
2001        assert!(bytes.saw_experts);
2002    }
2003
2004    #[test]
2005    fn pp_residency_combines_stages_that_share_one_device() {
2006        let tensors = [
2007            ("blk.0.ffn_gate_exps.weight", 10usize),
2008            ("blk.1.ffn_gate_exps.weight", 20),
2009            ("blk.2.ffn_gate_exps.weight", 30),
2010            ("blk.3.ffn_gate_exps.weight", 40),
2011        ];
2012        let bytes = residency_bytes_by_device(tensors, &[0, 0, 0, 0], 0);
2013        assert_eq!(bytes.experts.get(&0), Some(&100));
2014        assert_eq!(bytes.experts.len(), 1);
2015    }
2016}
2017
2018#[cfg(test)]
2019mod draft_head_tests {
2020    use super::draft_head_tensor;
2021
2022    /// Names present in the real Step-3.7-Flash MTP drafter (Step3.7-flash-mtp-Q8_0.gguf), as
2023    /// enumerated by the on-disk byte probe in
2024    /// research/step37-p2-20260806/raw/draft-head-tensor-hashes-20260807.txt.
2025    /// Both candidate heads exist in that file with IDENTICAL [4096, 128896] Q8_0 shape, so no
2026    /// shape or dtype check can distinguish them — only the sha256 of the payload could, and it
2027    /// showed them to be different matrices (blk.45 head c90b907b… vs output.weight 3eec5831…).
2028    const STEP37_DRAFTER: &[&str] = &[
2029        "output.weight",
2030        "output_norm.weight",
2031        "token_embd.weight",
2032        "blk.45.nextn.shared_head_norm.weight",
2033        "blk.45.nextn.shared_head_head.weight",
2034        "blk.46.nextn.shared_head_head.weight",
2035        "blk.47.nextn.shared_head_head.weight",
2036    ];
2037
2038    fn present(names: &'static [&'static str]) -> impl Fn(&str) -> bool {
2039        move |t: &str| names.contains(&t)
2040    }
2041
2042    /// THE REGRESSION. Reading `output.weight` off this drafter cost acceptance 0/248 across
2043    /// K=1..8 with self-consistency PASS at every K — correct output, dead speculation, no gate
2044    /// red (raw/mtp-draft-20260806T212902Z.log). The drafter's top-level output stack is a
2045    /// re-quantized COPY OF THE TRUNK'S (its output_norm is byte-identical to the trunk's,
2046    /// d7526f44…), so it is the standalone-decode head, not the MTP head. Preferring
2047    /// blk.45.nextn.shared_head_head took K=1 to 14/18 = 77.8%
2048    /// (raw/mtp-draft-PASS-20260806T215132Z.log).
2049    #[test]
2050    fn step37_drafter_prefers_the_blocks_own_nextn_head_over_file_level_output() {
2051        assert_eq!(
2052            draft_head_tensor(present(STEP37_DRAFTER), 45),
2053            "blk.45.nextn.shared_head_head.weight"
2054        );
2055    }
2056
2057    /// Each NextN block owns a DIFFERENT head (c90b907b / a22d2957 / 4b21e137 — a shared head
2058    /// would have collided), so the name must be built from the block index, never hardcoded.
2059    /// This is what multi-block chaining (45->46->47) will index when it lands.
2060    #[test]
2061    fn each_nextn_block_selects_its_own_head() {
2062        for n in 45..=47u32 {
2063            assert_eq!(
2064                draft_head_tensor(present(STEP37_DRAFTER), n),
2065                format!("blk.{n}.nextn.shared_head_head.weight")
2066            );
2067        }
2068    }
2069
2070    /// FR-Spec / tied-head drafts publish the (possibly vocab-trimmed) head as the file-level
2071    /// `output.weight` and ship no nextn head. They must keep working — hence preference, not
2072    /// replacement.
2073    #[test]
2074    fn draft_without_a_nextn_head_falls_back_to_file_level_output() {
2075        let fr_spec: &[&str] = &["output.weight", "output_norm.weight", "d2t.weight"];
2076        assert_eq!(draft_head_tensor(present(fr_spec), 45), "output.weight");
2077    }
2078
2079    /// The legacy `nextn.shared_head` probe sits between the two: no shipped artifact and no
2080    /// upstream mapping uses it (upstream is LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD ->
2081    /// "blk.%d.nextn.shared_head_head"), but anything that ever matched it still must, and it
2082    /// must never win over the real name.
2083    #[test]
2084    fn legacy_shared_head_is_probed_but_loses_to_shared_head_head() {
2085        let legacy_only: &[&str] = &["output.weight", "blk.45.nextn.shared_head.weight"];
2086        assert_eq!(
2087            draft_head_tensor(present(legacy_only), 45),
2088            "blk.45.nextn.shared_head.weight"
2089        );
2090
2091        let both: &[&str] = &[
2092            "output.weight",
2093            "blk.45.nextn.shared_head.weight",
2094            "blk.45.nextn.shared_head_head.weight",
2095        ];
2096        assert_eq!(
2097            draft_head_tensor(present(both), 45),
2098            "blk.45.nextn.shared_head_head.weight"
2099        );
2100    }
2101
2102    /// A drafter whose nextn head belongs to a DIFFERENT block must not be borrowed: asking for
2103    /// block 45 in a file that only carries 46/47 falls back rather than silently mismatching
2104    /// the geometry the trunk verified against.
2105    #[test]
2106    fn a_different_blocks_nextn_head_is_never_borrowed() {
2107        let wrong_block: &[&str] = &[
2108            "output.weight",
2109            "blk.46.nextn.shared_head_head.weight",
2110            "blk.47.nextn.shared_head_head.weight",
2111        ];
2112        assert_eq!(draft_head_tensor(present(wrong_block), 45), "output.weight");
2113    }
2114}