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