Skip to main content

memra_engine/
decode.rs

1//! Incremental decode (T=1) with the dual cache + greedy generation loop. Serves end-to-end.
2//! Reuses the validated kernels; threads KV (full-attn) and conv/SSM state (linear-attn) across steps.
3
4use crate::Engine;
5use crate::cache::{Cache, RecurLayer};
6use crate::forward::argmax;
7use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer};
8use cudarc::driver::CudaSlice;
9use memra_gguf::config::SwigluClamp;
10use std::collections::HashMap;
11
12/// Persistent CUDA-graph decode state (CUDA-GRAPH-PLAN Phase 3). Holds the device-resident counters
13/// the captured graph reads/writes (`token_d` = current/next token id, `pos_d` = rope position) — both
14/// at FIXED addresses baked into every captured graph — plus the per-`t_kv`-bucket graph cache. The
15/// bucket key is the eager `(fa_vec, n_splits)` pair (see `Engine::fa_bucket_key`): every t_kv that
16/// maps to the same key reproduces eager's split geometry, so one captured graph replays bit-identically
17/// for the whole bucket. A new key triggers a re-capture (n_splits changes ~every 64 tokens).
18pub struct GraphDecodeState {
19    pub token_d: CudaSlice<u32>, // [1] resident next-token id (argmax writes, embed reads)
20    pub pos_d: CudaSlice<i32>,   // [1] resident rope position counter
21    pub graphs: HashMap<(bool, usize), cudarc::driver::CudaGraph>,
22    pub bucket_max: HashMap<(bool, usize), usize>, // bucket key -> bucket_max fed to the capture
23    pub captures: usize,                           // count of (re)captures, for reporting
24}
25
26/// Long-lived step-wise CUDA-graph decode session (see HybridModel::graph_session_new).
27/// One replay per step(); the only steady-state D2H is the 4-byte next-token read.
28pub struct GraphSession {
29    pub gs: GraphDecodeState,
30    pub cache: Cache,
31    /// LOAD-BEARING hold: the captured graph's embed-gather node references this
32    /// allocation — dropping it would free memory the graph still reads.
33    #[allow(dead_code)]
34    embd_gpu: CudaSlice<u8>,
35    graph: cudarc::driver::CudaGraph,
36    plan: Vec<crate::graph_update::FaMain>,
37    /// session budget: last valid t_kv (pos + max_new + 1 at creation).
38    pub bucket_max: usize,
39    /// current capture's kernel-class segment end — step() recaptures past it
40    /// (round 45: exec-update retunes splits, it cannot swap kernels; see
41    /// graph_decode_loop's SEGMENTS note).
42    seg_end: usize,
43    qt: i32,
44    row_bytes: usize,
45    n_vocab: usize,
46    /// GRAMMAR MASK (constrained decoding, 2026-08-03): packed llguidance bitset the
47    /// captured graph reads (mask_logits_f32 between lm_head and the in-graph argmax).
48    /// STABLE POINTER — baked at capture, carried across recaptures; the caller uploads
49    /// fresh contents (upload_mask) before every step. None = no mask node captured.
50    mask_dev: Option<CudaSlice<u32>>,
51    mask_words: usize,
52}
53
54impl GraphSession {
55    /// One graph-replay decode step. Returns the next token (already fed back into the
56    /// resident token_d — the following step consumes it). Errors past bucket_max
57    /// (the caller sized max_new at capture). Transparently recaptures when the eager
58    /// kernel class changes (fa_vec floor / v4 max / fa512 floor crossings).
59    pub fn step(
60        &mut self,
61        e: &Engine,
62        m: &crate::hybrid::HybridModel,
63    ) -> Result<u32, Box<dyn std::error::Error>> {
64        if self.cache.pos + 1 >= self.bucket_max {
65            return Err("GraphSession: past bucket_max (generation budget exceeded)".into());
66        }
67        // GRAPH-LAUNCH HEADROOM GUARD (see spec::GRAPH_LAUNCH_MIN_FREE): a captured
68        // session has NO per-tick eager twin — the session IS the graph — so below the
69        // driver-free floor the step refuses RECOVERABLY. The worker ends THIS session
70        // with an error event and every peer session (and the process) lives; unguarded,
71        // cuGraphLaunch segfaults inside libcuda with zero log lines
72        // (lane/graph-launch-guard-sweep-20260831, extending step37 defect 3).
73        if !crate::spec::graph_launch_headroom_ok(e) {
74            static NOTED: std::sync::Once = std::sync::Once::new();
75            NOTED.call_once(|| crate::spec::graph_replay_suspended_note("graph-session"));
76            return Err(format!(
77                "graph-session replay refused: driver free below the {}MB launch floor \
78                 (no eager twin for a captured session; ending the session recoverably \
79                 instead of segfaulting cuGraphLaunch)",
80                crate::spec::GRAPH_LAUNCH_MIN_FREE >> 20
81            )
82            .into());
83        }
84        if self.cache.pos + 1 > self.seg_end {
85            m.graph_session_recapture(e, self)?;
86        }
87        crate::graph_update::fa_apply(
88            &self.graph,
89            &mut self.plan,
90            self.cache.pos + 1,
91            crate::fa_split_keys,
92        )?;
93        self.graph.launch()?;
94        self.cache.pos += 1;
95        for kvl in self.cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
96            kvl.len += 1;
97        }
98        e.dtoh_u32_one(&self.gs.token_d)
99    }
100
101    /// GRAMMAR MASK upload (constrained graph sessions): fresh packed-bitset contents into
102    /// the STABLE buffer the captured graph reads — call before every step(). The word
103    /// count is a capture-time kernel arg (constant per model: the tokenizer vocab is
104    /// fixed), so the length must match the capture exactly.
105    pub fn upload_mask(
106        &mut self,
107        e: &Engine,
108        words: &[u32],
109    ) -> Result<(), Box<dyn std::error::Error>> {
110        let Some(d) = self.mask_dev.as_mut() else {
111            return Err("upload_mask: session captured without a mask node".into());
112        };
113        if words.len() != self.mask_words {
114            return Err(format!(
115                "upload_mask: {} words != captured {}",
116                words.len(),
117                self.mask_words
118            )
119            .into());
120        }
121        e.htod_u32_into(d, words)
122    }
123
124    /// Profiling decomposition of step() (graph-session-gate MEMRA_GS_PROF): the three
125    /// phases exposed separately. prof_launch is ASYNC (no sync) — prof_read carries the
126    /// sync+D2H. Advances the session exactly like step().
127    pub fn prof_apply(&mut self, _e: &Engine) -> Result<(), Box<dyn std::error::Error>> {
128        crate::graph_update::fa_apply(
129            &self.graph,
130            &mut self.plan,
131            self.cache.pos + 1,
132            crate::fa_split_keys,
133        )
134    }
135    pub fn prof_launch(&mut self) -> Result<(), Box<dyn std::error::Error>> {
136        self.graph.launch()?;
137        self.cache.pos += 1;
138        for kvl in self.cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
139            kvl.len += 1;
140        }
141        Ok(())
142    }
143    pub fn prof_read(&mut self, e: &Engine) -> Result<u32, Box<dyn std::error::Error>> {
144        e.dtoh_u32_one(&self.gs.token_d)
145    }
146}
147
148impl GraphDecodeState {
149    pub fn new(e: &Engine) -> Result<Self, Box<dyn std::error::Error>> {
150        Ok(GraphDecodeState {
151            token_d: e.stream().clone_htod(&[0u32])?,
152            pos_d: e.htod_i32(&[0])?,
153            graphs: HashMap::new(),
154            bucket_max: HashMap::new(),
155            captures: 0,
156        })
157    }
158}
159
160/// Generation parameters for the reusable serving API (`generate_with`).
161#[derive(Clone, Debug)]
162pub struct GenParams {
163    pub max_new: usize,         // hard cap on generated tokens
164    pub max_ctx: Option<usize>, // context-length guard; None => prompt+max_new+8
165    pub eos: Vec<u32>,          // stop on any of these token ids (eos/eog + specials)
166}
167impl Default for GenParams {
168    fn default() -> Self {
169        GenParams {
170            max_new: 128,
171            max_ctx: None,
172            eos: Vec::new(),
173        }
174    }
175}
176
177/// Why generation stopped.
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
179pub enum StopReason {
180    Eos,
181    MaxNew,
182    ContextFull,
183    Callback,
184}
185
186/// Result of `generate_with`: the generated token ids + why it stopped.
187pub struct GenOutput {
188    pub tokens: Vec<u32>,
189    pub stop_reason: StopReason,
190}
191
192/// Diagnostic-only snapshots of Hy3 layer 0 in the eager T=1 serving path.
193/// Each buffer is one residual-width device row captured before the next stage can reuse it.
194pub struct Hy3Layer0Stages {
195    pub attention_output: CudaSlice<f32>,
196    pub after_attention: CudaSlice<f32>,
197    pub mlp_output: CudaSlice<f32>,
198    pub residual: CudaSlice<f32>,
199}
200
201impl HybridModel {
202    /// Device embed table for the dc fast loops (lazy ~0.5GB upload). On OOM — tight fits
203    /// where resident experts + KV leave no headroom (35B ct-NVFP4 artifact at default
204    /// budget, 2026-07-17) — returns None and the caller stays on the host-embd eager loop
205    /// instead of panicking. Double-init race is benign (identical bytes, loser dropped).
206    pub(crate) fn embd_gpu_try(&self, e: &Engine) -> Option<&cudarc::driver::CudaSlice<u8>> {
207        if let Some(v) = self.embd_gpu.get() {
208            return Some(v);
209        }
210        match e.upload_u8(&self.embd.raw) {
211            Ok(buf) => Some(self.embd_gpu.get_or_init(|| buf)),
212            Err(err) => {
213                eprintln!(
214                    "[embd-gpu] upload failed ({err}); dc loop disabled, host-embd eager loop serves"
215                );
216                None
217            }
218        }
219    }
220}
221
222impl HybridModel {
223    /// One decode step for `token` at cache.pos; returns logits [n_vocab] (host f32). Advances cache.
224    pub fn decode_step(
225        &self,
226        e: &Engine,
227        token: u32,
228        cache: &mut Cache,
229    ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
230        Ok(self.decode_step_h(e, token, cache)?.0)
231    }
232
233    /// Dense-FFN SwiGLU (T=1 decode): `down @ (silu(gate@z) * (up@z))`. Two fused levers stack here:
234    ///  - RANK3 LEVER 2: gate+up NVFP4 macro-scales fold into ONE `silu_mul_scaled*` launch (via
235    ///    `matmul_pre_noscale`), saving the two separate `scale_inplace` launches.
236    ///  - RANK2 LEVER (q8_1 quant-fold): when ffn_down is ALSO on the q8_1 fast path, the SwiGLU
237    ///    epilogue EMITS the q8_1 quantization of `act` directly (`silu_mul_scaled_q8_1`) and feeds
238    ///    ffn_down via `matmul_pre`, removing ffn_down's standalone `quantize_q8_1` launch (the
239    ///    down-proj activation has one consumer, so the quant folds into its producer for free).
240    ///    BIT-IDENTICAL to matmul_pre(gate)+matmul_pre(up)+silu_mul+quantize_q8_1+matmul(down): same
241    ///    float silu*mul, same amax/127 q8_1 rounding, same dp4a/mmvq dot. Falls back to the f32 `act`
242    /// + plain matmul(down) path whenever any of the three is off the fast path.
243    #[allow(clippy::too_many_arguments)]
244    pub(crate) fn ffn_swiglu_decode(
245        &self,
246        e: &Engine,
247        ffn_gate: &crate::model::GpuTensor,
248        ffn_up: &crate::model::GpuTensor,
249        ffn_down: &crate::model::GpuTensor,
250        z: &CudaSlice<f32>,
251        n_embd: usize,
252        n_ff: usize,
253        lim: Option<SwigluClamp>,
254    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
255        // M3 dense layers use swigluoai (clamped) — the silu_mul fused fast paths below encode
256        // plain SiLU; route through ffn_act (macro-scales folded via matmul_pre) until clamped
257        // fused twins exist. step35's per-layer `lim` is the same problem, same escape hatch:
258        // silu_mul_scaled / silu_mul_scaled_q8_1 have no clamped twin.
259        if self.cfg.m3.is_some() || lim.is_some() {
260            let (zq, zd) = e.quantize_q8_1(z, 1, n_embd)?;
261            let gate = e.matmul_pre(ffn_gate, &zq, &zd, z, 1)?;
262            let up = e.matmul_pre(ffn_up, &zq, &zd, z, 1)?;
263            let mut act = e.uninit(n_ff)?;
264            Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0, lim, &mut act, n_ff)?;
265            return e.matmul(ffn_down, &act, 1);
266        }
267        if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
268            let (zq, zd) = e.quantize_q8_1(z, 1, n_embd)?;
269            // DUAL mm-fusion first (NVFP4 gate+up in ONE launch), else two noscale launches.
270            let pair = match e.matmul_pre_dual_noscale(ffn_gate, ffn_up, &zq, &zd, 1)? {
271                Some((g, u)) => (Some(g), Some(u)),
272                None => (
273                    e.matmul_pre_noscale(ffn_gate, &zq, &zd, 1)?,
274                    e.matmul_pre_noscale(ffn_up, &zq, &zd, 1)?,
275                ),
276            };
277            match pair {
278                (Some((gate, gs)), Some((up, us))) => {
279                    // RANK2 fold: if ffn_down is q8_1-fast, emit act PRE-QUANTIZED and skip the
280                    // standalone quantize_q8_1 before ffn_down.
281                    if e.uses_q8_1_fast(ffn_down) {
282                        let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, n_ff)?;
283                        return e.matmul_pre(
284                            ffn_down, &aq, &ad, /*x_fallback unused on fast path*/ &gate, 1,
285                        );
286                    }
287                    let mut act = e.uninit(n_ff)?;
288                    e.silu_mul_scaled(&gate, &up, gs, us, &mut act, n_ff)?;
289                    return e.matmul(ffn_down, &act, 1);
290                }
291                _ => {
292                    // one (or both) not on the separable-scale fast path: scaled matmul + plain silu_mul.
293                    let gate = e.matmul_pre(ffn_gate, &zq, &zd, z, 1)?;
294                    let up = e.matmul_pre(ffn_up, &zq, &zd, z, 1)?;
295                    let mut act = e.uninit(n_ff)?;
296                    Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
297                    return e.matmul(ffn_down, &act, 1);
298                }
299            }
300        }
301        let gate = e.matmul(ffn_gate, z, 1)?;
302        let up = e.matmul(ffn_up, z, 1)?;
303        let mut act = e.uninit(n_ff)?;
304        Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
305        e.matmul(ffn_down, &act, 1)
306    }
307
308    /// Like `ffn_swiglu_decode` but the input is ALREADY q8_1-quantized `(zq, zd)` — used by the
309    /// DECODE NORM-FUSION lever where `add_rms_norm_q8_1` emits the post-attn-normed activation
310    /// pre-quantized (no f32 `z` materialized, no standalone quantize_q8_1 launch). Caller GUARANTEES
311    /// ffn_gate and ffn_up are q8_1-fast (so `matmul_pre_noscale` returns Some at m=1). BIT-IDENTICAL
312    /// to ffn_swiglu_decode(z) when (zq,zd) == quantize_q8_1(z): same matmul_pre_noscale, same
313    /// silu_mul_scaled_q8_1 / silu_mul_scaled, same ffn_down dot.
314    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
315    fn ffn_swiglu_decode_pre(
316        &self,
317        e: &Engine,
318        ffn_gate: &crate::model::GpuTensor,
319        ffn_up: &crate::model::GpuTensor,
320        ffn_down: &crate::model::GpuTensor,
321        zq: &CudaSlice<i8>,
322        zd: &CudaSlice<f32>,
323        n_ff: usize,
324    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
325        let pair = match e.matmul_pre_dual_noscale(ffn_gate, ffn_up, zq, zd, 1)? {
326            Some((g, u)) => (Some(g), Some(u)),
327            None => (
328                e.matmul_pre_noscale(ffn_gate, zq, zd, 1)?,
329                e.matmul_pre_noscale(ffn_up, zq, zd, 1)?,
330            ),
331        };
332        match pair {
333            (Some((gate, gs)), Some((up, us))) => {
334                if e.uses_q8_1_fast(ffn_down) {
335                    let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, n_ff)?;
336                    Ok(e.matmul_pre(ffn_down, &aq, &ad, &gate, 1)?)
337                } else {
338                    let mut act = e.uninit(n_ff)?;
339                    e.silu_mul_scaled(&gate, &up, gs, us, &mut act, n_ff)?;
340                    Ok(e.matmul(ffn_down, &act, 1)?)
341                }
342            }
343            // Unreachable when the caller's q8_1-fast guarantee holds (m==1 + fast => Some). Guard
344            // anyway: re-quant from the dequantized pair would need f32; surface a clear error.
345            _ => Err("ffn_swiglu_decode_pre: gate/up not separable-scale at m=1 (caller must guarantee q8_1-fast)".into()),
346        }
347    }
348
349    /// Shared post-attention residual + post-attn-norm + FFN for ONE decode layer, routed by ALL
350    /// decode loops (eager + dc + dc_cap) so they stay bit-identical by construction. DECODE
351    /// NORM-FUSION LEVER: when the layer is Dense AND ffn_gate/ffn_up are q8_1-fast (the daily NVFP4
352    /// case), fuses residual-add + post_attn_norm + q8_1-quantize into ONE `add_rms_norm_q8_1` launch
353    /// and feeds the FFN the pre-quantized activation (skipping its internal quantize_q8_1) — removing
354    /// 1-2 launches + the f32 `z` HBM round-trip per layer. BIT-IDENTICAL to the unfused
355    /// add_rms_norm(or add+rms_norm) + quantize_q8_1 + ffn (all proven bit-identical in kernel_check).
356    /// MEMRA_NO_FUSE_NORMQ forces the unfused f32 path. Returns (x1 residual f32, ffn_out f32).
357    /// True when ALL of a mixer's input projections are on the q8_1 fast path (so the attn-input
358    /// rms_norm can emit q8_1 directly and the mixer skips its internal quantize_q8_1).
359    pub(crate) fn mixer_in_q8_1_fast(&self, e: &Engine, mixer: &Mixer) -> bool {
360        match mixer {
361            Mixer::Full(fa) => {
362                if fa.step_tp_qkv.is_some() {
363                    return false;
364                }
365                // step35 also projects its head-wise GATE from the same attn-normed input, so
366                // the fused (h-less) arm requires attn_gate on the q8_1 fast path too — without
367                // this the gate matmul would get a zero-length `h`.
368                let gate_ok = match &fa.attn_gate {
369                    Some(g) => e.uses_q8_1_fast(g),
370                    None => true,
371                };
372                gate_ok
373                    && e.uses_q8_1_fast(&fa.wq)
374                    && e.uses_q8_1_fast(&fa.wk)
375                    && e.uses_q8_1_fast(&fa.wv)
376            }
377            Mixer::Linear(la) => {
378                e.uses_q8_1_fast(&la.wqkv)
379                    && e.uses_q8_1_fast(&la.wqkv_gate)
380                    && e.uses_q8_1_fast(&la.ssm_beta)
381                    && e.uses_q8_1_fast(&la.ssm_alpha)
382            }
383            // MLA: the forward exists (increment 4) but deliberately does NOT claim the fused
384            // norm+quantize chain — its first GEMM is wq_a/wkv_a off an f32 hidden, and no MLA
385            // parity gate has covered a q8_1 activation path. Keeping this false routes every
386            // MLA decode through the unfused arm, which is the gated one.
387            Mixer::Mla(_) => false,
388            // KDA projects through matmul_group, never the pre-quantized (hq,hd) pair, so the
389            // fused norm+quantize chain has no KDA consumer to claim.
390            Mixer::Kda(_) => false,
391        }
392    }
393
394    /// attn_norm + mixer for the EAGER loop, with the attn-input NORM-FUSION. MEMRA_NO_FUSE_NORMQ
395    /// forces the unfused (separate rms_norm + mixer-internal quantize) path.
396    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
397    fn attn_in_norm_mixer(
398        &self,
399        e: &Engine,
400        layer: &crate::hybrid::HybridLayer,
401        x: &CudaSlice<f32>,
402        pos_d: &CudaSlice<i32>,
403        pos: usize,
404        cache: &mut Cache,
405        il: usize,
406        n_embd: usize,
407        eps: f32,
408    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
409        let anorm = layer.attn_norm.float_data();
410        let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
411            && self.mixer_in_q8_1_fast(e, &layer.mixer);
412        if fuse {
413            let (hq, hd) = e.rms_norm_q8_1(x, anorm, n_embd, 1, eps)?;
414            // h is unused on the fast path (matmul_pre x_fallback only used at m>=16); pass a zero-len.
415            let h0 = e.zeros(0)?;
416            match &layer.mixer {
417                Mixer::Full(fa) => {
418                    self.full_attn_decode_pre(e, fa, &h0, Some((&hq, &hd)), pos_d, pos, cache, il)
419                }
420                Mixer::Linear(la) => {
421                    self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)
422                }
423                Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("norm-fused decode"),
424                Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("norm-fused eager decode"),
425            }
426        } else {
427            let mut h = e.uninit(n_embd)?;
428            e.rms_norm(x, anorm, &mut h, n_embd, 1, eps)?;
429            match &layer.mixer {
430                Mixer::Full(fa) => self.full_attn_decode(e, fa, &h, pos_d, pos, cache, il),
431                Mixer::Linear(la) => self.linear_attn_decode(e, la, &h, cache, il),
432                Mixer::Mla(mla) => self.mla_attn_cached(e, mla, &h, pos_d, 1, il, cache),
433                Mixer::Kda(la) => crate::kda::kda_decode_cached(e, la, &h, eps, cache, il),
434            }
435        }
436    }
437
438    /// attn_norm + mixer for the DEVICE-COUNTER loop (decode_step_dc). Full-attn uses the dc path;
439    /// linear uses the eager-state path (persistent=false), same as decode_step_dc. NORM-FUSED.
440    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
441    fn attn_in_norm_mixer_dc(
442        &self,
443        e: &Engine,
444        layer: &crate::hybrid::HybridLayer,
445        x: &CudaSlice<f32>,
446        pos_d: &CudaSlice<i32>,
447        cache: &mut Cache,
448        il: usize,
449        n_embd: usize,
450        eps: f32,
451    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
452        let anorm = layer.attn_norm.float_data();
453        let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
454            && self.mixer_in_q8_1_fast(e, &layer.mixer);
455        if fuse {
456            let (hq, hd) = e.rms_norm_q8_1(x, anorm, n_embd, 1, eps)?;
457            let h0 = e.zeros(0)?;
458            match &layer.mixer {
459                Mixer::Full(fa) => {
460                    self.full_attn_decode_dc_pre(e, fa, &h0, &hq, &hd, pos_d, cache, il)
461                }
462                Mixer::Linear(la) => {
463                    self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)
464                }
465                Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("device-counter decode"),
466                Mixer::Kda(_) => {
467                    crate::hybrid::kda_path_unimplemented("norm-fused device-counter decode")
468                }
469            }
470        } else {
471            let mut h = e.uninit(n_embd)?;
472            e.rms_norm(x, anorm, &mut h, n_embd, 1, eps)?;
473            match &layer.mixer {
474                Mixer::Full(fa) => self.full_attn_decode_dc(e, fa, &h, pos_d, cache, il),
475                Mixer::Linear(la) => self.linear_attn_decode(e, la, &h, cache, il),
476                Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("device-counter decode"),
477                Mixer::Kda(la) => crate::kda::kda_decode_cached(e, la, &h, eps, cache, il),
478            }
479        }
480    }
481
482    /// attn_norm + mixer for the CAPTURE loop (decode_step_dc_cap). Full-attn uses the dc_cap path
483    /// (fixed bucket_max); linear uses the persistent-state path. NORM-FUSED; capture-safe (rms_norm_q8_1
484    /// + the *_pre mixers enqueue the same kernels every replay, stable buffers).
485    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
486    fn attn_in_norm_mixer_dc_cap(
487        &self,
488        e: &Engine,
489        layer: &crate::hybrid::HybridLayer,
490        x: &CudaSlice<f32>,
491        pos_d: &CudaSlice<i32>,
492        cache: &mut Cache,
493        il: usize,
494        bucket_max: usize,
495        n_embd: usize,
496        eps: f32,
497    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
498        let anorm = layer.attn_norm.float_data();
499        let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
500            && self.mixer_in_q8_1_fast(e, &layer.mixer);
501        if fuse {
502            let (hq, hd) = e.rms_norm_q8_1(x, anorm, n_embd, 1, eps)?;
503            let h0 = e.zeros(0)?;
504            match &layer.mixer {
505                Mixer::Full(fa) => self.full_attn_decode_dc_cap_pre(
506                    e, fa, &h0, &hq, &hd, pos_d, cache, il, bucket_max,
507                ),
508                Mixer::Linear(la) => {
509                    self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, true)
510                }
511                Mixer::Mla(_) => {
512                    crate::hybrid::mla_path_unimplemented("captured device-counter decode")
513                }
514                Mixer::Kda(_) => {
515                    crate::hybrid::kda_path_unimplemented("norm-fused captured decode")
516                }
517            }
518        } else {
519            let mut h = e.uninit(n_embd)?;
520            e.rms_norm(x, anorm, &mut h, n_embd, 1, eps)?;
521            match &layer.mixer {
522                Mixer::Full(fa) => {
523                    self.full_attn_decode_dc_cap(e, fa, &h, pos_d, cache, il, bucket_max)
524                }
525                Mixer::Linear(la) => self.linear_attn_decode_cap(e, la, &h, cache, il),
526                Mixer::Mla(_) => {
527                    crate::hybrid::mla_path_unimplemented("captured device-counter decode")
528                }
529                Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("captured decode"),
530            }
531        }
532    }
533
534    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
535    pub(crate) fn residual_norm_ffn(
536        &self,
537        e: &Engine,
538        layer: &crate::hybrid::HybridLayer,
539        x: &CudaSlice<f32>,
540        mixed: &CudaSlice<f32>,
541        n_embd: usize,
542        il: usize,
543        eps: f32,
544    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
545        let pnorm = layer.post_attn_norm.float_data();
546        match &layer.ffn {
547            crate::hybrid::Ffn::Dense {
548                ffn_gate,
549                ffn_up,
550                ffn_down,
551            } => {
552                let n_ff = ffn_gate.out_features();
553                // cfg.m3: the fused-pre chain's silu_mul_scaled* epilogues are plain SiLU —
554                // M3's swigluoai must route through ffn_swiglu_decode's m3 arm (FAST-gate
555                // MISMATCH root cause #2, 2026-07-07: L0 dense FFN clamp skipped under FAST).
556                // step35: SAME failure shape, per LAYER. A dense FFN's limit is the SHEXP array
557                // (upstream's one build_ffn serves dense + shared expert, llama-graph.cpp:1751).
558                let lim = self.cfg.clamp_shexp_at(il as u32);
559                let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
560                    && self.cfg.m3.is_none()
561                    && lim.is_none()
562                    && e.uses_q8_1_fast(ffn_gate)
563                    && e.uses_q8_1_fast(ffn_up);
564                if fuse {
565                    // M2 safety: this q8 arm predates the deferred join and is never taken
566                    // in the step37 config — refuse loudly rather than read unwritten mixed.
567                    if crate::tp::take_oproj_tail().is_some() {
568                        return Err(
569                            "oproj tail handoff reached the q8 residual arm — unwired".into()
570                        );
571                    }
572                    let mut x1 = e.uninit(n_embd)?;
573                    let (zq, zd) = e.add_rms_norm_q8_1(x, mixed, pnorm, &mut x1, n_embd, 1, eps)?;
574                    let ffn_out =
575                        self.ffn_swiglu_decode_pre(e, ffn_gate, ffn_up, ffn_down, &zq, &zd, n_ff)?;
576                    Ok((x1, ffn_out))
577                } else {
578                    let mut x1 = e.uninit(n_embd)?;
579                    let mut z = e.uninit(n_embd)?;
580                    if let Some((a0, a1)) = crate::tp::take_oproj_tail() {
581                        e.join_add_rms_norm_raw(a0, a1, x, pnorm, &mut x1, &mut z, n_embd, eps)?;
582                    } else {
583                        e.add_rms_norm(x, mixed, pnorm, &mut x1, &mut z, n_embd, 1, eps)?;
584                    }
585                    let ffn_out = self
586                        .ffn_swiglu_decode(e, ffn_gate, ffn_up, ffn_down, &z, n_embd, n_ff, lim)?;
587                    Ok((x1, ffn_out))
588                }
589            }
590            crate::hybrid::Ffn::Moe(m) => {
591                let mut x1 = e.uninit(n_embd)?;
592                let mut z = e.uninit(n_embd)?;
593                // z-quantize fuse (add_rms_norm_zq8) measured NEGATIVE here (158.8 vs 160.6:
594                // the fused warp-per-block quantize pass re-reads z slower than the dedicated
595                // coalesced quantize_q8_1). Kernel + threading kept for graph-capture use where
596                // launch count matters more; eager default = unfused (no gain = no change).
597                // O-PROJ TAIL FUSION M2: when the direct join deferred its add, compose
598                // mixed = a0+a1 in-register inside the norm (verbatim program).
599                if let Some((a0, a1)) = crate::tp::take_oproj_tail() {
600                    e.join_add_rms_norm_raw(a0, a1, x, pnorm, &mut x1, &mut z, n_embd, eps)?;
601                } else {
602                    e.add_rms_norm(x, mixed, pnorm, &mut x1, &mut z, n_embd, 1, eps)?;
603                }
604                // Feed the zq8 seam (orndecode B2): two consumers now share this quantize —
605                // the dev expert arm (clones at t==1) and the shexp fused2 pair — so the
606                // caller-side launch replaces two arm-side ones. Same kernel, same input,
607                // byte-identical per the (1, Some) clone contract.
608                let zq8 = e.quantize_q8_1(&z, 1, n_embd)?;
609                let ffn_out = self.moe_ffn_il_zq8(e, m, &z, Some(&zq8), 1, il as u16)?;
610                Ok((x1, ffn_out))
611            }
612        }
613    }
614
615    /// EAGLE3 aux-hidden capture (EAGLE-PLAN N1): one decode step that ALSO returns the trunk
616    /// residual-stream `x` taken AFTER each of the blocks in `aux_layers` (the EAGLE3 encoder feeds
617    /// these 3 layer hiddens through `fc`). Returns (logits[n_vocab] host, aux: Vec<[n_embd] dev>),
618    /// one device buffer per requested aux layer, in `aux_layers` order. The captured tensor is the
619    /// residual `x` produced by that block (`x2` at the loop tail), cloned before the next block
620    /// overwrites it — cheap (one clone_dtod of [n_embd] per aux layer). T=1 decode regime.
621    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
622    pub fn decode_step_aux(
623        &self,
624        e: &Engine,
625        token: u32,
626        cache: &mut Cache,
627        aux_layers: &[usize],
628    ) -> Result<(Vec<f32>, Vec<CudaSlice<f32>>), Box<dyn std::error::Error>> {
629        self.refuse_hyper("decode_step_aux")?;
630        cache.ensure_usable("decode_step_aux")?;
631        let (logits, aux, _) = self.decode_step_aux_inner(e, token, cache, aux_layers, false)?;
632        Ok((logits, aux))
633    }
634
635    /// Diagnostic-only Hy3 layer-0 trace through the real eager T=1 serving path. Besides the
636    /// final block residual, this captures the attention output before its residual add, the
637    /// after-attention residual, and the dense-MLP output before the final residual add.
638    pub fn decode_step_hy3_layer0_stages(
639        &self,
640        e: &Engine,
641        token: u32,
642        cache: &mut Cache,
643    ) -> Result<(Vec<f32>, Hy3Layer0Stages), Box<dyn std::error::Error>> {
644        self.refuse_hyper("decode_step_hy3_layer0_stages")?;
645        cache.ensure_usable("decode_step_hy3_layer0_stages")?;
646        if self.cfg.hy3.is_none() {
647            return Err("decode_step_hy3_layer0_stages requires a Hy3 model".into());
648        }
649        if !matches!(
650            self.layers.first().map(|layer| &layer.ffn),
651            Some(crate::hybrid::Ffn::Dense { .. })
652        ) {
653            return Err("Hy3 diagnostic expected layer 0 to use a dense MLP".into());
654        }
655        let (logits, _, stages) = self.decode_step_aux_inner(e, token, cache, &[], true)?;
656        Ok((
657            logits,
658            stages.ok_or("Hy3 layer-0 stages were not captured")?,
659        ))
660    }
661
662    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
663    fn decode_step_aux_inner(
664        &self,
665        e: &Engine,
666        token: u32,
667        cache: &mut Cache,
668        aux_layers: &[usize],
669        capture_hy3_layer0: bool,
670    ) -> Result<(Vec<f32>, Vec<CudaSlice<f32>>, Option<Hy3Layer0Stages>), Box<dyn std::error::Error>>
671    {
672        let cfg = &self.cfg;
673        let n_embd = cfg.n_embd as usize;
674        let eps = cfg.rms_eps;
675        let pos = cache.pos;
676        let pos_d = e.htod_i32(&[pos as i32])?;
677
678        let mut x = e.htod(&self.embd.try_gather(n_embd, &[token])?)?;
679        let mut aux: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
680        let mut hy3_layer0 = None;
681
682        for (il, layer) in self.layers.iter().enumerate() {
683            // attn-input NORM-FUSION (eager); shared with decode_step_h.
684            let mixed =
685                self.attn_in_norm_mixer(e, layer, &x, &pos_d, pos, cache, il, n_embd, eps)?;
686            // DECODE NORM-FUSION LEVER (residual_norm_ffn): residual add + post_attn RMSNorm +
687            // q8_1-quantize fused into ONE add_rms_norm_q8_1 launch on the Dense q8_1-fast path, then
688            // the FFN consumes the pre-quantized activation. Bit-identical to the unfused path.
689            let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
690            // MEMRA_TG_PROBE_LAYER diagnostics (token-graph bisection): dump layer K's
691            // attention output and post-FFN residual through the real eager path.
692            if std::env::var("MEMRA_TG_PROBE_LAYER")
693                .ok()
694                .and_then(|v| v.parse::<usize>().ok())
695                == Some(il)
696            {
697                use std::io::Write;
698                let mut xp = e.uninit(n_embd)?;
699                e.add(&x1, &ffn_out, &mut xp, n_embd)?;
700                let (pm, px) = (e.dtoh(&mixed)?, e.dtoh(&xp)?);
701                for (path, data) in [
702                    ("/root/eager-probe-mixed.bin", &pm),
703                    ("/root/eager-probe-x.bin", &px),
704                ] {
705                    let mut fo = std::fs::OpenOptions::new()
706                        .create(true)
707                        .append(true)
708                        .open(path)?;
709                    for v in data {
710                        fo.write_all(&v.to_le_bytes())?;
711                    }
712                }
713            }
714            let mut x2 = e.uninit(n_embd)?;
715            e.add(&x1, &ffn_out, &mut x2, n_embd)?;
716            if capture_hy3_layer0 && il == 0 {
717                hy3_layer0 = Some(Hy3Layer0Stages {
718                    attention_output: e.clone_dtod(&mixed)?,
719                    after_attention: e.clone_dtod(&x1)?,
720                    mlp_output: e.clone_dtod(&ffn_out)?,
721                    residual: e.clone_dtod(&x2)?,
722                });
723            }
724            // EAGLE3 N1: capture this block's residual output if it is an aux layer.
725            if aux_layers.contains(&il) {
726                aux.push(e.clone_dtod(&x2)?);
727            }
728            x = x2;
729        }
730        // re-order aux to match aux_layers order (contains() pushes in il order; aux_layers is the
731        // canonical order the encoder concats in — they coincide since aux_layers is ascending).
732        let mut hn = e.uninit(n_embd)?;
733        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
734        let logits = e.matmul(&self.output, &hn, 1)?;
735        let host = e.dtoh(&logits)?;
736        cache.pos += 1;
737        Ok((host, aux, hy3_layer0))
738    }
739
740    /// Like `decode_step`, but ALSO returns the trunk's hidden state `x` taken BEFORE the final
741    /// `output_norm` (MTP-PLAN §A: this is `h_seed` for the NextN head). Device buffer [n_embd].
742    pub fn decode_step_h(
743        &self,
744        e: &Engine,
745        token: u32,
746        cache: &mut Cache,
747    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
748        cache.ensure_usable("decode_step_h")?;
749        if self.hyper.is_some() {
750            return self.decode_step_hyper(e, token, cache);
751        }
752        if self.is_gemma4_e4b() {
753            crate::pp::warn_unwired_once("gemma4-e4b eager decode");
754            return self.gemma4_e4b_decode_step_h(e, token, cache);
755        }
756        if self.uses_gemma_program() {
757            // pp2 door for the gemma4 arm lives inside gemma4_decode_step_h.
758            return self.gemma4_decode_step_h(e, token, cache);
759        }
760        // M2 ppN door (crate::pp): N-stage split of this walk with an explicit activation
761        // handoff at each boundary. Default OFF — unset env means this branch never taken.
762        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
763            if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::Pipeline) {
764                return Err("pipeline rewrite is not qualified for this ModelPlan".into());
765            }
766            let rt = crate::pp::PpNRt::get(e)?;
767            let _walk = rt.acquire_walk("decode_step_h_ppn")?;
768            return self.decode_step_h_ppn(e, token, cache, &fence);
769        }
770        // Whole-token decode graph (step TP graph increment B, MEMRA_STEP_TP_GRAPH=1 +
771        // the dcw/fused/router doors): one stitched multi-device launch per token.
772        if self.uses_sliding_gated_moe_program()
773            && let Some(result) = self.step35_token_graph_step(e, token, cache)?
774        {
775            return Ok(result);
776        }
777        let cfg = &self.cfg;
778        let n_embd = cfg.n_embd as usize;
779        let eps = cfg.rms_eps;
780        let pos = cache.pos;
781        let pos_d = e.htod_i32(&[pos as i32])?;
782        // O-PROJ TAIL deferral eligibility: this walk flows into residual_norm_ffn.
783        let _oproj_tail_scope = crate::tp::oproj_tail_scope();
784        // RANK0 STREAM MERGE (MEMRA_RANK0_MERGE=1): rank0 shares dev0's PRIMARY context
785        // with e (cudarc primary_ctx::retain), so its per-layer work can ride e's stream —
786        // every e<->rank0 event hop becomes program order. Scheduling-only: BIT-IDENTICAL.
787        let _r0merge = if crate::tp::rank0_merge_on() && self.uses_sliding_gated_moe_program() {
788            Some(memra_runtime::rank0_redirect_scope(
789                e.ctx().ordinal(),
790                e.gpu.main_stream().clone(),
791                e.gpu.blas(),
792            ))
793        } else {
794            None
795        };
796
797        // embed the single token -> [1, n_embd]
798        let mut x = e.htod(&self.embd.try_gather(n_embd, &[token])?)?;
799
800        // CROSS-LAYER ADD+NORM FUSION (launch-arc 2026-07-07): layer il's post-FFN residual add
801        // (x2 = x1 + ffn_out) and layer il+1's attn_norm+quantize are consecutive row-wise ops —
802        // add_rms_norm_q8_1 does all three in ONE launch (bit-identity proven in kernel_check:
803        // add_rms_norm == add then rms_norm; _q8_1 == then quantize_q8_1). Carry the un-added
804        // (x1, ffn_out) pair into the next iteration; the fused launch materializes x2 (the
805        // residual this layer needs) as its `res` output. Falls back to the separate add when
806        // the next mixer is off the q8_1 fast path.
807        // MEMRA_STEP_TP_TIMING=1: whole-token bucket split of the eager decode walk — mixer vs
808        // FFN totals, the EP-tail layers (>= trunk-2) separated, plus the head. Each lap syncs
809        // e's stream, so async work bills to the section that queued it. Diagnostic only.
810        static B_MIX: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
811        static B_FFN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
812        static B_MIX_TAIL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
813        static B_FFN_TAIL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
814        static B_HEAD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
815        static B_TOKENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
816        let timing = std::env::var("MEMRA_STEP_TP_TIMING").as_deref() == Ok("1");
817        let lap = |timer: &std::sync::atomic::AtomicU64,
818                   started: &mut Option<std::time::Instant>|
819         -> Result<(), Box<dyn std::error::Error>> {
820            let Some(start) = started.as_mut() else {
821                return Ok(());
822            };
823            e.stream().synchronize()?;
824            timer.fetch_add(
825                start.elapsed().as_nanos() as u64,
826                std::sync::atomic::Ordering::Relaxed,
827            );
828            *start = std::time::Instant::now();
829            Ok(())
830        };
831        let mut lap_start = timing.then(std::time::Instant::now);
832        let tail_from = self.layers.len().saturating_sub(2);
833        let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
834        for (il, layer) in self.layers.iter().enumerate() {
835            let anorm = layer.attn_norm.float_data();
836            let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
837                && self.mixer_in_q8_1_fast(e, &layer.mixer);
838            // NOTE: take() FIRST, branch on fuse after — a tuple pattern like
839            // `if let (Some(p), true) = (pending.take(), fuse)` DROPS the taken pair when
840            // fuse is false (pattern fails post-take) and silently loses the residual add.
841            let taken = pending.take();
842            // FUSION #2f (bf16-mixer decode): off the q8_1 fast path the residual add and this
843            // layer's attn_norm ride one add_rms_norm launch (kernel_check identity:
844            // add_rms_norm == add then rms_norm; same rms_block()), then the mixer takes the
845            // pre-normed h directly.
846            let mixed = match (taken, fuse) {
847                (Some((x1, f1)), false) => {
848                    let mut x2 = e.uninit(n_embd)?;
849                    let mut h = e.uninit(n_embd)?;
850                    e.add_rms_norm(&x1, &f1, anorm, &mut x2, &mut h, n_embd, 1, eps)?;
851                    x = x2;
852                    match &layer.mixer {
853                        Mixer::Full(fa) => {
854                            self.full_attn_decode(e, fa, &h, &pos_d, pos, cache, il)?
855                        }
856                        Mixer::Linear(la) => self.linear_attn_decode(e, la, &h, cache, il)?,
857                        Mixer::Mla(mla) => {
858                            self.mla_attn_cached(e, mla, &h, &pos_d, 1, il, cache)?
859                        }
860                        Mixer::Kda(la) => crate::kda::kda_decode_cached(e, la, &h, eps, cache, il)?,
861                    }
862                }
863                (Some((x1, f1)), true) => {
864                    // fused add + attn_norm + q8_1 (this layer's mixer input), res -> x2
865                    let mut x2 = e.uninit(n_embd)?;
866                    let (hq, hd) = e.add_rms_norm_q8_1(&x1, &f1, anorm, &mut x2, n_embd, 1, eps)?;
867                    x = x2;
868                    let h0 = e.zeros(0)?;
869                    match &layer.mixer {
870                        Mixer::Full(fa) => self.full_attn_decode_pre(
871                            e,
872                            fa,
873                            &h0,
874                            Some((&hq, &hd)),
875                            &pos_d,
876                            pos,
877                            cache,
878                            il,
879                        )?,
880                        Mixer::Linear(la) => {
881                            self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)?
882                        }
883                        Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("decode_step_h"),
884                        Mixer::Kda(_) => {
885                            crate::hybrid::kda_path_unimplemented("norm-fused decode_step_h")
886                        }
887                    }
888                }
889                (None, _) => {
890                    self.attn_in_norm_mixer(e, layer, &x, &pos_d, pos, cache, il, n_embd, eps)?
891                }
892            };
893
894            lap(
895                if il >= tail_from { &B_MIX_TAIL } else { &B_MIX },
896                &mut lap_start,
897            )?;
898
899            // DECODE NORM-FUSION LEVER (residual_norm_ffn): add+post_attn_norm+q8_1 fused on the Dense
900            // fast path. Bit-identical to add + rms_norm + ffn (add_rms_norm == add then rms_norm,
901            // proven in kernel_check; add_rms_norm_q8_1 == add_rms_norm then quantize_q8_1).
902            let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
903            // MEMRA_TG_PROBE_LAYER diagnostics (token-graph bisection): dump layer K's
904            // attention output and post-FFN residual through the real eager path.
905            if std::env::var("MEMRA_TG_PROBE_LAYER")
906                .ok()
907                .and_then(|v| v.parse::<usize>().ok())
908                == Some(il)
909            {
910                use std::io::Write;
911                let mut xp = e.uninit(n_embd)?;
912                e.add(&x1, &ffn_out, &mut xp, n_embd)?;
913                let (pm, px) = (e.dtoh(&mixed)?, e.dtoh(&xp)?);
914                for (path, data) in [
915                    ("/root/eager-probe-mixed.bin", &pm),
916                    ("/root/eager-probe-x.bin", &px),
917                ] {
918                    let mut fo = std::fs::OpenOptions::new()
919                        .create(true)
920                        .append(true)
921                        .open(path)?;
922                    for v in data {
923                        fo.write_all(&v.to_le_bytes())?;
924                    }
925                }
926            }
927            lap(
928                if il >= tail_from { &B_FFN_TAIL } else { &B_FFN },
929                &mut lap_start,
930            )?;
931            pending = Some((x1, ffn_out));
932        }
933        // final layer's add (no next norm to fuse with — output_norm is f32-out)
934        if let Some((x1, f1)) = pending.take() {
935            let mut x2 = e.uninit(n_embd)?;
936            e.add(&x1, &f1, &mut x2, n_embd)?;
937            x = x2;
938        }
939
940        let mut hn = e.uninit(n_embd)?;
941        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
942        // h_seed = trunk hidden BEFORE output_norm (default, §A) or AFTER it (MEMRA_SPEC_HPOST,
943        // the reference engines' convention — see spec::spec_hpost).
944        let h_seed = if crate::spec::spec_hpost() {
945            e.clone_dtod(&hn)?
946        } else {
947            e.clone_dtod(&x)?
948        };
949        // head-MIPS feasibility probe (MEMRA_DUMP_HN=<path>): append pre-head hiddens for
950        // offline bound analysis. Diagnostic only.
951        if let Ok(path) = std::env::var("MEMRA_DUMP_HN") {
952            let hh = e.dtoh(&hn)?;
953            use std::io::Write;
954            let mut fo = std::fs::OpenOptions::new()
955                .create(true)
956                .append(true)
957                .open(path)?;
958            for v in &hh {
959                fo.write_all(&v.to_le_bytes())?;
960            }
961        }
962        // MEMRA_HEAD_SPLIT=1 (step TP only): split the lm-head rows across both devices —
963        // dev1 idles at the token tail, rows are independent, and the per-row program is the
964        // same matvec_bf16 kernel, so the concatenated logits are BIT-IDENTICAL to the
965        // single-device head. Falls through to the plain matmul when ineligible.
966        let host = 'head: {
967            let split_on = {
968                static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
969                *ON.get_or_init(|| std::env::var("MEMRA_HEAD_SPLIT").as_deref() == Ok("1"))
970            };
971            if split_on
972                && self.uses_sliding_gated_moe_program()
973                && let Some(host) = self.head_split_matvec(e, &hn)?
974            {
975                break 'head host;
976            }
977            let logits = e.matmul(&self.output, &hn, 1)?;
978            e.dtoh(&logits)?
979        };
980        lap(&B_HEAD, &mut lap_start)?;
981        if timing {
982            use std::sync::atomic::Ordering;
983            let tokens = B_TOKENS.fetch_add(1, Ordering::Relaxed) + 1;
984            if tokens.is_multiple_of(10) {
985                let per = |t: &std::sync::atomic::AtomicU64| {
986                    t.load(Ordering::Relaxed) as f64 / tokens as f64 / 1.0e6
987                };
988                eprintln!(
989                    "[decode-bucket-timing] tokens={tokens} ms/token mix={:.2} ffn={:.2} \
990                     mix_tail={:.2} ffn_tail={:.2} head={:.2}",
991                    per(&B_MIX),
992                    per(&B_FFN),
993                    per(&B_MIX_TAIL),
994                    per(&B_FFN_TAIL),
995                    per(&B_HEAD),
996                );
997            }
998        }
999        cache.pos += 1;
1000        Ok((host, h_seed))
1001    }
1002
1003    /// ASYNC-AHEAD DEVICE-CHAINED greedy or sampled decode (MEMRA_ASYNC_CHAIN=K): run up to `k`
1004    /// tokens with NO host sync inside the chain — the tail argmax writes the resident
1005    /// token_d on-device (host-identical tie-break, argmax_gate receipt), the next
1006    /// iteration embeds straight from it (embed_gather_device, bit-identical rows), and
1007    /// the host reads the id history ring ONCE per chunk. Unlike the graph chunk this
1008    /// keeps EAGER kernels and streams (full stream concurrency); the host submit runs
1009    /// ahead of the GPU, so the per-token host wall overlaps device work instead of
1010    /// serializing after it.
1011    /// Contract: consumes `token` (already emitted by
1012    /// the caller) as launch 0's input and returns (hist[0..k], last token's logits).
1013    /// The caller emits hist[..k-1]. On a greedy chain, hist[k-1] == argmax(logits); on a
1014    /// sampled chain it is the device-drawn boundary id and MUST be fed directly instead
1015    /// of re-derived greedily from the returned row. When `MEMRA_HEAD_SPLIT=1`, both the
1016    /// greedy argmax and sampled draw consume the split path's materialized concatenated
1017    /// logits on device; the host reads that persistent row only once at chunk end.
1018    /// SAMPLED chain (owner rule: "we dont serve greedy, for real benchmarking we use
1019    /// sampling"). `samp` carries the serving sampler; the draw happens ON DEVICE inside the
1020    /// chain — `filter_stats` -> `gumbel_perturb_filtered_col` -> `argmax` into the resident
1021    /// `token_d` — so a sampled stream keeps the chain's whole point, which is that no host
1022    /// sync happens between tokens. The per-step counter advances so each token draws its own
1023    /// Gumbel noise. Without `MEMRA_HEAD_SPLIT`, the same draw runs on the plain head row.
1024    pub fn device_chain_plan_eligible(&self) -> bool {
1025        self.hyper.is_none()
1026            && !self.is_gemma4_e4b()
1027            && !self.uses_gemma_program()
1028            && crate::pp::pp_cuts(self.layers.len()).is_none()
1029            && self
1030                .layers
1031                .iter()
1032                .all(|layer| matches!(layer.mixer, Mixer::Full(_) | Mixer::Linear(_)))
1033    }
1034
1035    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
1036    pub fn decode_step_chain(
1037        &self,
1038        e: &Engine,
1039        token: u32,
1040        k_target: usize,
1041        cache: &mut Cache,
1042        samp: Option<&crate::decode_batch::DevSamp>,
1043    ) -> Result<Option<(Vec<u32>, Vec<f32>)>, Box<dyn std::error::Error>> {
1044        self.refuse_hyper("decode_step_chain")?;
1045        cache.ensure_usable("decode_step_chain")?;
1046        if !self.device_chain_plan_eligible() {
1047            return Ok(None);
1048        }
1049        let k = k_target.min(16);
1050        if k < 2 {
1051            return Ok(None);
1052        }
1053        let Some(embd_gpu) = self.embd_gpu_try(e) else {
1054            return Ok(None);
1055        };
1056        let cfg = &self.cfg;
1057        let n_embd = cfg.n_embd as usize;
1058        let n_vocab = cfg.n_vocab as usize;
1059        let eps = cfg.rms_eps;
1060        let n_layers = self.layers.len();
1061        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
1062
1063        // Resident chain state (token id, id history ring, ring index), one set per device.
1064        #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
1065        static CHAIN: std::sync::Mutex<
1066            Option<(usize, CudaSlice<u32>, CudaSlice<u32>, CudaSlice<i32>)>,
1067        > = std::sync::Mutex::new(None);
1068        let mut guard = CHAIN.lock().map_err(|_| "chain state lock is poisoned")?;
1069        if guard.as_ref().is_none_or(|(d, ..)| *d != e.ctx().ordinal()) {
1070            *guard = Some((
1071                e.ctx().ordinal(),
1072                e.stream().clone_htod(&[0u32])?,
1073                e.stream().clone_htod(&[0u32; 16])?,
1074                e.htod_i32(&[0])?,
1075            ));
1076        }
1077        let (_, token_d, hist, hist_idx) = guard.as_mut().expect("armed above");
1078
1079        // O-PROJ TAIL deferral eligibility (see decode_step_h).
1080        let _oproj_tail_scope = crate::tp::oproj_tail_scope();
1081        // RANK0 STREAM MERGE (see decode_step_h).
1082        let _r0merge = if crate::tp::rank0_merge_on() {
1083            Some(memra_runtime::rank0_redirect_scope(
1084                e.ctx().ordinal(),
1085                e.gpu.main_stream().clone(),
1086                e.gpu.blas(),
1087            ))
1088        } else {
1089            None
1090        };
1091        // Per-token pos buffers staged BEFORE the chain (the only H2D the chain needs).
1092        let mut pos_bufs = Vec::with_capacity(k);
1093        for step in 0..k {
1094            pos_bufs.push(e.htod_i32(&[(cache.pos + step) as i32])?);
1095        }
1096        e.set_u32_one(token_d, token)?;
1097        e.set_i32_one(hist_idx, 0)?;
1098
1099        // MEMRA_CHAIN_PHASE=1 (P0 CEILING PROBE — WRONG OUTPUT BY DESIGN): alternate
1100        // tokens ride disjoint phase streams with NO cross-token event edges yet, so the
1101        // schedule shows the token-pipeline overlap ceiling while the ids race. Timing
1102        // receipts only; never gate a tape under this door.
1103        static PHASE_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1104        let phase_on =
1105            *PHASE_ON.get_or_init(|| std::env::var("MEMRA_CHAIN_PHASE").as_deref() == Ok("1"));
1106
1107        let mut last_logits: Option<Option<CudaSlice<f32>>> = None;
1108        #[allow(clippy::needless_range_loop)]
1109        // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
1110        for step in 0..k {
1111            let _phase_ov = if phase_on {
1112                let (ps, pb) = e.gpu.phase_pair(step & 1)?;
1113                memra_runtime::set_decode_phase(Some(step & 1));
1114                Some(memra_runtime::push_stream_override(ps, pb))
1115            } else {
1116                None
1117            };
1118            let pos = cache.pos;
1119            let step_r = (|| -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
1120                let x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_rb)?;
1121                let x = self.decode_layers_eager(e, x, 0, n_layers, &pos_bufs[step], pos, cache)?;
1122                let mut hn = e.uninit(n_embd)?;
1123                e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1124                // Split head when armed (MEMRA_HEAD_SPLIT env + eligibility): identical
1125                // concatenated logits, device argmax, no per-token readback.
1126                static HS_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1127                let hs =
1128                    *HS_ON.get_or_init(|| std::env::var("MEMRA_HEAD_SPLIT").as_deref() == Ok("1"));
1129                let sampling = samp.filter(|s| s.temp > 0.0);
1130                let split_done = if hs && self.uses_sliding_gated_moe_program() {
1131                    match sampling {
1132                        // Sampling keeps HEAD_SPLIT: the split path materializes the full
1133                        // concatenated row, so the device draw reads it instead of an argmax.
1134                        Some(s) => self.head_split_sample_device(
1135                            e,
1136                            &hn,
1137                            token_d,
1138                            s,
1139                            s.ctr.wrapping_add(step as u32),
1140                        )?,
1141                        None => self.head_split_argmax_device(e, &hn, token_d)?,
1142                    }
1143                } else {
1144                    false
1145                };
1146                let logits = if split_done {
1147                    None
1148                } else {
1149                    let logits = e.matmul(&self.output, &hn, 1)?;
1150                    match samp.filter(|s| s.temp > 0.0) {
1151                        None => e.argmax_token_device_into(&logits, token_d, n_vocab)?,
1152                        Some(s) => {
1153                            // Device draw, no host sync: thresholds for this row, Gumbel
1154                            // perturbation of the filtered row, argmax into token_d. Same
1155                            // kernels and the same (seed, ctr) draw the serve tick uses.
1156                            let ctr = s.ctr.wrapping_add(step as u32);
1157                            // Persistent per-chain scratch: allocating these per token cost
1158                            // more than the split head saved when this arm was first measured.
1159                            let filtered = s.top_k > 0 || s.top_p < 1.0 || s.min_p > 0.0;
1160                            if filtered {
1161                                let rows_d = e.htod_i32(&[0i32])?;
1162                                let mut th = e.zeros(1)?;
1163                                let mut z = e.zeros(1)?;
1164                                let mut mx = e.zeros(1)?;
1165                                e.filter_stats(
1166                                    &logits, n_vocab, &rows_d, &mut th, &mut z, &mut mx, n_vocab,
1167                                    1, s.temp, s.top_k, s.top_p, s.min_p,
1168                                )?;
1169                                let mut pb = e.zeros(n_vocab)?;
1170                                e.gumbel_perturb_filtered_col(
1171                                    &logits, 0, &mut pb, n_vocab, s.seed, ctr, s.temp, &mx, &th, 0,
1172                                )?;
1173                                e.argmax_token_device_col(&pb, 0, n_vocab, token_d, 0)?;
1174                            } else {
1175                                let mut pb = e.zeros(n_vocab)?;
1176                                e.gumbel_perturb_col(
1177                                    &logits, 0, &mut pb, n_vocab, s.seed, ctr, s.temp,
1178                                )?;
1179                                e.argmax_token_device_col(&pb, 0, n_vocab, token_d, 0)?;
1180                            }
1181                        }
1182                    }
1183                    Some(logits)
1184                };
1185                e.u32_hist_append(token_d, hist, hist_idx)?;
1186                Ok(logits)
1187            })();
1188            if phase_on {
1189                memra_runtime::set_decode_phase(None);
1190            }
1191            let logits = step_r?;
1192            cache.pos += 1;
1193            last_logits = Some(logits);
1194            // (None = split-head path; the persistent row holds this token's logits.)
1195        }
1196        if phase_on {
1197            // Drain both phases on every engine before the host readback.
1198            for p in 0..2 {
1199                e.gpu.phase_pair(p)?.0.synchronize()?;
1200            }
1201            if let Some(tp) = self.layers.first().and_then(|l| match &l.mixer {
1202                Mixer::Full(fa) => fa.step_tp_qkv.as_ref(),
1203                _ => None,
1204            }) {
1205                for rank in 0..tp.runtime.devices().len() {
1206                    if let Some(engine) = tp.runtime.rank_engine(rank) {
1207                        let _main = engine.gpu.enter_main()?;
1208                        for p in 0..2 {
1209                            engine.gpu.phase_pair(p)?.0.synchronize()?;
1210                        }
1211                    }
1212                }
1213            }
1214        }
1215        let hist_h = e.dtoh_u32(hist)?;
1216        let logits_h = match last_logits.expect("k >= 2") {
1217            Some(row) => e.dtoh(&row)?,
1218            None => self.head_split_logits_dtoh(e)?,
1219        };
1220        Ok(Some((hist_h[..k].to_vec(), logits_h)))
1221    }
1222
1223    /// M1-PP2 stage subgraph: run layers [lo, hi) of the generic eager walk. Enters with a
1224    /// MATERIALIZED residual `x` (no pending fusion pair from outside the range) and exits
1225    /// with the range's final residual materialized (the trailing add executed, exactly like
1226    /// the last layer of an unsplit walk). Body is the `decode_step_h` loop verbatim with the
1227    /// cross-layer add+norm fusion carry LOCAL to the range — so the only state a stage
1228    /// boundary has to move is the [n_embd] hidden state. Bit-identity of the cut relies on
1229    /// the kernel-check-pinned `add_rms_norm_q8_1 == add then rms_norm_q8_1` identity
1230    /// (`pp2-gate` verifies end-to-end on real weights).
1231    /// `pub(crate)`: also the B=1 serve fast-path's trunk (decode_batch.rs
1232    /// `decode_step_b1_fast`, H3) — shared verbatim so the serve path inherits every m=1
1233    /// fusion instead of needing a batched twin per lever.
1234    #[allow(clippy::too_many_arguments)]
1235    pub(crate) fn decode_layers_eager(
1236        &self,
1237        e: &Engine,
1238        mut x: CudaSlice<f32>,
1239        lo: usize,
1240        hi: usize,
1241        pos_d: &CudaSlice<i32>,
1242        pos: usize,
1243        cache: &mut Cache,
1244    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1245        let n_embd = self.cfg.n_embd as usize;
1246        let eps = self.cfg.rms_eps;
1247        let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
1248        for il in lo..hi {
1249            let layer = &self.layers[il];
1250            let anorm = layer.attn_norm.float_data();
1251            let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
1252                && self.mixer_in_q8_1_fast(e, &layer.mixer);
1253            // take() FIRST, branch on fuse after (see decode_step_h: a tuple pattern drops
1254            // the taken pair when fuse is false and silently loses the residual add).
1255            let taken = pending.take();
1256            // FUSION #2f (as decode_step_h): off the q8_1 fast path, the residual add and this
1257            // layer's attn_norm ride one add_rms_norm launch.
1258            let mixed = match (taken, fuse) {
1259                (Some((x1, f1)), false) => {
1260                    let mut x2 = e.uninit(n_embd)?;
1261                    let mut h = e.uninit(n_embd)?;
1262                    e.add_rms_norm(&x1, &f1, anorm, &mut x2, &mut h, n_embd, 1, eps)?;
1263                    x = x2;
1264                    match &layer.mixer {
1265                        Mixer::Full(fa) => {
1266                            self.full_attn_decode(e, fa, &h, pos_d, pos, cache, il)?
1267                        }
1268                        Mixer::Linear(la) => self.linear_attn_decode(e, la, &h, cache, il)?,
1269                        Mixer::Mla(mla) => self.mla_attn_cached(e, mla, &h, pos_d, 1, il, cache)?,
1270                        Mixer::Kda(la) => crate::kda::kda_decode_cached(e, la, &h, eps, cache, il)?,
1271                    }
1272                }
1273                (Some((x1, f1)), true) => {
1274                    let mut x2 = e.uninit(n_embd)?;
1275                    let (hq, hd) = e.add_rms_norm_q8_1(&x1, &f1, anorm, &mut x2, n_embd, 1, eps)?;
1276                    x = x2;
1277                    let h0 = e.zeros(0)?;
1278                    match &layer.mixer {
1279                        Mixer::Full(fa) => self.full_attn_decode_pre(
1280                            e,
1281                            fa,
1282                            &h0,
1283                            Some((&hq, &hd)),
1284                            pos_d,
1285                            pos,
1286                            cache,
1287                            il,
1288                        )?,
1289                        Mixer::Linear(la) => {
1290                            self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)?
1291                        }
1292                        Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("decode_step_chain"),
1293                        Mixer::Kda(_) => {
1294                            crate::hybrid::kda_path_unimplemented("norm-fused decode_layers_eager")
1295                        }
1296                    }
1297                }
1298                (None, _) => {
1299                    self.attn_in_norm_mixer(e, layer, &x, pos_d, pos, cache, il, n_embd, eps)?
1300                }
1301            };
1302            let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
1303            // MEMRA_TG_PROBE_LAYER diagnostics (token-graph bisection): dump layer K's
1304            // attention output and post-FFN residual through the real eager path.
1305            if std::env::var("MEMRA_TG_PROBE_LAYER")
1306                .ok()
1307                .and_then(|v| v.parse::<usize>().ok())
1308                == Some(il)
1309            {
1310                use std::io::Write;
1311                let mut xp = e.uninit(n_embd)?;
1312                e.add(&x1, &ffn_out, &mut xp, n_embd)?;
1313                let (pm, px) = (e.dtoh(&mixed)?, e.dtoh(&xp)?);
1314                for (path, data) in [
1315                    ("/root/eager-probe-mixed.bin", &pm),
1316                    ("/root/eager-probe-x.bin", &px),
1317                ] {
1318                    let mut fo = std::fs::OpenOptions::new()
1319                        .create(true)
1320                        .append(true)
1321                        .open(path)?;
1322                    for v in data {
1323                        fo.write_all(&v.to_le_bytes())?;
1324                    }
1325                }
1326            }
1327            pending = Some((x1, ffn_out));
1328        }
1329        // range's final add (no next norm inside the range to fuse with)
1330        if let Some((x1, f1)) = pending.take() {
1331            let mut x2 = e.uninit(n_embd)?;
1332            e.add(&x1, &f1, &mut x2, n_embd)?;
1333            x = x2;
1334        }
1335        Ok(x)
1336    }
1337
1338    /// M2: `decode_step_h` as N stage subgraphs, each on ITS OWN CUDA stream (and, under
1339    /// MEMRA_PP_DEVICES, its own device/engine), with the transport-selected boundary
1340    /// handoff at each fence cut. Stage 0 = embed + its layer range; each middle stage
1341    /// RXes boundary s-1 (waits its ev_tx), runs its range, TXes boundary s; the last
1342    /// stage adds output_norm + lm head. Per-layer KV/linear state stays owned by the
1343    /// stage that runs the layer; `cache.pos` is snapshotted once and advanced once.
1344    /// MEMRA_PP_STREAMS=0 = the increment-1 same-stream seam.
1345    /// Gate: `ppn-gate` (bit-identical logits vs unsplit at every N/knob combination).
1346    fn decode_step_h_ppn(
1347        &self,
1348        e: &Engine,
1349        token: u32,
1350        cache: &mut Cache,
1351        fence: &[usize],
1352    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1353        if crate::pp::pp2_streams_off() {
1354            return self.decode_step_h_ppn_samestream(e, token, cache, fence);
1355        }
1356        let rt = crate::pp::PpNRt::get(e)?;
1357        let n_st = fence.len() - 1;
1358        assert_eq!(
1359            rt.n_stages(),
1360            n_st,
1361            "PpNRt stage count {} != fence stages {n_st}",
1362            rt.n_stages()
1363        );
1364        // #87 REVERSE PUBLICATION (lane/pp2spec-crash): this body's stage-stream
1365        // allocations may reuse pool blocks freed from a PREVIOUS ppn call's outputs
1366        // (h_seed, verify vx/ckpt) whose primary-stream consumers are still queued —
1367        // the reuse-write races the queued read. Order every stage stream behind the
1368        // caller's stream before the first stage allocation. Full anatomy:
1369        // `PpNRt::fence_stages_behind`.
1370        rt.fence_stages_behind(&e.stream())?;
1371        let cfg = &self.cfg;
1372        let n_embd = cfg.n_embd as usize;
1373        let eps = cfg.rms_eps;
1374        let pos = cache.pos;
1375
1376        // PER-STAGE pos_d (M2 pipelining law): every stage uploads its OWN copy of the
1377        // step's pos scalar on ITS stream, so the buffer is allocated, consumed, and
1378        // freed on one stream (a shared stage-0 pos_d freed at fn return breaks under
1379        // deferred readback: the free enqueues on stream 0 while stages 1..N-1 still
1380        // dereference it — the 2026-08-02 pipelined-gate all-logits divergence).
1381
1382        // ---- STAGE 0 (its own stream): embed + layers [0, fence[1]) + boundary-0 TX ----
1383        let mut slot = {
1384            let _st0 = rt.enter(0);
1385            let e0 = rt.engine(0, e);
1386            let pos_d = e0.htod_i32(&[pos as i32])?;
1387            let x = e0.htod(&self.embd.try_gather(n_embd, &[token])?)?;
1388            let x = self.decode_layers_eager(e0, x, fence[0], fence[1], &pos_d, pos, cache)?;
1389            rt.tx(0, &x, n_embd)?
1390            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
1391        };
1392
1393        // ---- MIDDLE STAGES s in [1, n_st-1): RX boundary s-1 -> range -> TX boundary s ----
1394        for s in 1..n_st - 1 {
1395            let _st = rt.enter(s);
1396            let es = rt.engine(s, e);
1397            let pos_d = es.htod_i32(&[pos as i32])?;
1398            let x = rt.rx(s - 1, slot, n_embd)?;
1399            let x = self.decode_layers_eager(es, x, fence[s], fence[s + 1], &pos_d, pos, cache)?;
1400            slot = rt.tx(s, &x, n_embd)?;
1401        }
1402
1403        // ---- LAST STAGE: RX + layers [fence[n_st-1], n) + output_norm + lm head ----
1404        let _stl = rt.enter(n_st - 1);
1405        let el = rt.engine(n_st - 1, e);
1406        let pos_d = el.htod_i32(&[pos as i32])?;
1407        let x = rt.rx(n_st - 2, slot, n_embd)?;
1408        let x =
1409            self.decode_layers_eager(el, x, fence[n_st - 1], fence[n_st], &pos_d, pos, cache)?;
1410        let e = el; // head runs through the last stage's engine on its stream
1411
1412        let mut hn = e.uninit(n_embd)?;
1413        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1414        let h_seed = if crate::spec::spec_hpost() {
1415            e.clone_dtod(&hn)?
1416        } else {
1417            e.clone_dtod(&x)?
1418        };
1419        // same diagnostics door as decode_step_h (MEMRA_DUMP_HN) so the arms stay observably
1420        // interchangeable.
1421        if let Ok(path) = std::env::var("MEMRA_DUMP_HN") {
1422            let hh = e.dtoh(&hn)?;
1423            use std::io::Write;
1424            let mut fo = std::fs::OpenOptions::new()
1425                .create(true)
1426                .append(true)
1427                .open(path)?;
1428            for v in &hh {
1429                fo.write_all(&v.to_le_bytes())?;
1430            }
1431        }
1432        let logits = e.matmul(&self.output, &hn, 1)?;
1433        let host = e.dtoh(&logits)?;
1434        cache.pos += 1;
1435        Ok((host, h_seed))
1436    }
1437
1438    /// MEMRA_PP_STREAMS=0 rollback seam: the increment-1 body generalized to N — every
1439    /// stage subgraph on the ambient compute stream, each boundary = two plain dtod copies.
1440    fn decode_step_h_ppn_samestream(
1441        &self,
1442        e: &Engine,
1443        token: u32,
1444        cache: &mut Cache,
1445        fence: &[usize],
1446    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1447        let cfg = &self.cfg;
1448        let n_embd = cfg.n_embd as usize;
1449        let eps = cfg.rms_eps;
1450        let pos = cache.pos;
1451        let pos_d = e.htod_i32(&[pos as i32])?;
1452
1453        // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) ----
1454        let x = e.htod(&self.embd.try_gather(n_embd, &[token])?)?;
1455        let mut x = self.decode_layers_eager(e, x, fence[0], fence[1], &pos_d, pos, cache)?;
1456
1457        // ---- each later stage: explicit [n_embd] handoff (TX copy, RX copy) + range ----
1458        for s in 1..fence.len() - 1 {
1459            let boundary_tx = e.clone_dtod(&x)?;
1460            let boundary_rx = e.clone_dtod(&boundary_tx)?;
1461            x = self.decode_layers_eager(
1462                e,
1463                boundary_rx,
1464                fence[s],
1465                fence[s + 1],
1466                &pos_d,
1467                pos,
1468                cache,
1469            )?;
1470        }
1471
1472        let mut hn = e.uninit(n_embd)?;
1473        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1474        let h_seed = if crate::spec::spec_hpost() {
1475            e.clone_dtod(&hn)?
1476        } else {
1477            e.clone_dtod(&x)?
1478        };
1479        if let Ok(path) = std::env::var("MEMRA_DUMP_HN") {
1480            let hh = e.dtoh(&hn)?;
1481            use std::io::Write;
1482            let mut fo = std::fs::OpenOptions::new()
1483                .create(true)
1484                .append(true)
1485                .open(path)?;
1486            for v in &hh {
1487                fo.write_all(&v.to_le_bytes())?;
1488            }
1489        }
1490        let logits = e.matmul(&self.output, &hn, 1)?;
1491        let host = e.dtoh(&logits)?;
1492        cache.pos += 1;
1493        Ok((host, h_seed))
1494    }
1495
1496    /// M2 increment 3 (DEFERRED READBACK — the pipelining seed): the ppN step WITHOUT the
1497    /// terminal logits D2H. Returns `PendingLogits` (device logits + completion event +
1498    /// the runtime's dedicated readback stream); the caller keeps 2+ tokens in flight by
1499    /// enqueueing step t+1 BEFORE waiting step t (with MEMRA_PP_OVERLAP=1 the
1500    /// double-buffered boundary slots actually alternate, so stage 0 of t+1 runs under
1501    /// stage 1..N-1 of t; the slot ev_tx/ev_rx chain keeps each token's math fully
1502    /// event-ordered either way — enqueueing deeper than 2 is CORRECT, the slots simply
1503    /// serialize device-side).
1504    ///
1505    /// EXACTNESS CONTRACT: per-token logits are BIT-IDENTICAL to the serial arm — same
1506    /// kernels, same per-token event order; only the host-side wait moves (scheduling
1507    /// change, never math). The pipelined replay arm of `ppn-gate` proves it per step.
1508    ///
1509    /// NOT produced here (both are trunk COPIES — no math feeding the logits changes):
1510    /// h_seed and the MEMRA_DUMP_HN diagnostic tap. The serving loop decides their
1511    /// deferred form when it adopts this API.
1512    ///
1513    /// The caller advances the token stream, so `cache.pos` advances at ENQUEUE (host
1514    /// state; device work is event-ordered regardless).
1515    pub fn decode_step_h_ppn_deferred(
1516        &self,
1517        e: &Engine,
1518        token: u32,
1519        cache: &mut Cache,
1520    ) -> Result<crate::pp::PendingLogits, Box<dyn std::error::Error>> {
1521        self.refuse_hyper("decode_step_h_ppn_deferred")?;
1522        cache.ensure_usable("decode_step_h_ppn_deferred")?;
1523        let fence = crate::pp::pp_cuts(self.layers.len())
1524            .ok_or("ppn deferred: pp door closed (MEMRA_PP_STAGES unset)")?;
1525        if crate::pp::pp2_streams_off() {
1526            return Err("ppn deferred needs per-stage streams (MEMRA_PP_STREAMS=0 set)".into());
1527        }
1528        if self.uses_gemma_program() {
1529            return Err("ppn deferred: generic eager arm only (gemma4 is 2-stage serial)".into());
1530        }
1531        if crate::pp::pp_multi_stream_same_device()
1532            && std::env::var("MEMRA_PP_FORCE_SAME_DEV_PIPELINED").as_deref() != Ok("1")
1533        {
1534            return Err(
1535                "ppn deferred: refused with 2+ stage streams on one device — repro'd \
1536                 nondeterministic logits (35% flake, 2026-08-02 x20 soak, root cause open: \
1537                 shared-Engine kernels concurrent on co-located streams). Use one device \
1538                 per stage (MEMRA_PP_DEVICES) or the serial arm. \
1539                 MEMRA_PP_FORCE_SAME_DEV_PIPELINED=1 overrides for soak/bisect measurement."
1540                    .into(),
1541            );
1542        }
1543        let rt = crate::pp::PpNRt::get(e)?;
1544        let walk = rt.acquire_deferred_walk("decode_step_h_ppn_deferred")?;
1545        let n_st = fence.len() - 1;
1546        assert_eq!(
1547            rt.n_stages(),
1548            n_st,
1549            "PpNRt stage count {} != fence stages {n_st}",
1550            rt.n_stages()
1551        );
1552        let cfg = &self.cfg;
1553        let n_embd = cfg.n_embd as usize;
1554        let eps = cfg.rms_eps;
1555        let pos = cache.pos;
1556
1557        // Per-stage pos_d — see decode_step_h_ppn: under deferred readback a shared
1558        // pos_d's fn-end free races stages 1..N-1 (the free enqueues on stream 0 at
1559        // ENQUEUE time here, no terminal D2H to drain first). Each stage owns its copy.
1560        let mut slot = {
1561            let _st0 = rt.enter(0);
1562            let e0 = rt.engine(0, e);
1563            let pos_d = e0.htod_i32(&[pos as i32])?;
1564            let x = e0.htod(&self.embd.try_gather(n_embd, &[token])?)?;
1565            let x = self.decode_layers_eager(e0, x, fence[0], fence[1], &pos_d, pos, cache)?;
1566            rt.tx(0, &x, n_embd)?
1567        };
1568        for s in 1..n_st - 1 {
1569            let _st = rt.enter(s);
1570            let es = rt.engine(s, e);
1571            let pos_d = es.htod_i32(&[pos as i32])?;
1572            let x = rt.rx(s - 1, slot, n_embd)?;
1573            let x = self.decode_layers_eager(es, x, fence[s], fence[s + 1], &pos_d, pos, cache)?;
1574            slot = rt.tx(s, &x, n_embd)?;
1575        }
1576        let _stl = rt.enter(n_st - 1);
1577        let el = rt.engine(n_st - 1, e);
1578        let pos_d = el.htod_i32(&[pos as i32])?;
1579        let x = rt.rx(n_st - 2, slot, n_embd)?;
1580        let x =
1581            self.decode_layers_eager(el, x, fence[n_st - 1], fence[n_st], &pos_d, pos, cache)?;
1582
1583        let mut hn = el.uninit(n_embd)?;
1584        el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1585        let logits = el.matmul(&self.output, &hn, 1)?;
1586        let ev = rt.record_done()?;
1587        cache.pos += 1;
1588        Ok(crate::pp::PendingLogits::new(
1589            logits,
1590            ev,
1591            rt.readback_stream().clone(),
1592            walk,
1593        ))
1594    }
1595
1596    /// LOCKSTEP MULTI-STREAM decode (lane-3 M1): m independent streams advance one token each
1597    /// through a single per-layer walk. Per-stream math is identical to `decode_step_h` (same
1598    /// fusion chain, same mixer and FFN calls against that stream's own `Cache`), so each
1599    /// stream's token sequence is bit-identical to its single-stream run. The lockstep order
1600    /// puts the m streams' layer-il MoE calls adjacent in time, so one stream's expert-cache
1601    /// fill serves its siblings within the step — the measured cross-stream io amortization
1602    /// (1.12x/1.32x/1.66x at m=2/4/8) lands without batching attention or the CPU ABI.
1603    pub fn decode_step_lockstep(
1604        &self,
1605        e: &Engine,
1606        tokens: &[u32],
1607        caches: &mut [Cache],
1608    ) -> Result<Vec<Vec<f32>>, Box<dyn std::error::Error>> {
1609        self.refuse_hyper("decode_step_lockstep")?;
1610        for cache in caches.iter() {
1611            cache.ensure_usable("decode_step_lockstep")?;
1612        }
1613        if tokens.len() != caches.len() || tokens.is_empty() {
1614            return Err("lockstep needs one token per stream cache".into());
1615        }
1616        if self.uses_gemma_program() {
1617            return Err("lockstep decode does not support the gemma4 paths".into());
1618        }
1619        let cfg = &self.cfg;
1620        let n_embd = cfg.n_embd as usize;
1621        let eps = cfg.rms_eps;
1622        let m = tokens.len();
1623
1624        let mut pos_d = Vec::with_capacity(m);
1625        let mut x: Vec<CudaSlice<f32>> = Vec::with_capacity(m);
1626        for (s, &token) in tokens.iter().enumerate() {
1627            pos_d.push(e.htod_i32(&[caches[s].pos as i32])?);
1628            x.push(e.htod(&self.embd.try_gather(n_embd, &[token])?)?);
1629        }
1630        let mut pending: Vec<Option<(CudaSlice<f32>, CudaSlice<f32>)>> =
1631            (0..m).map(|_| None).collect();
1632
1633        // M2 (MEMRA_LOCKSTEP_GROUPED=1): MoE layers batch all m rows through
1634        // moe_ffn_lockstep — resident experts amortize weight reads across streams via the
1635        // grouped GEMM machinery; CPU-assigned experts keep per-row companion calls.
1636        let grouped = match std::env::var("MEMRA_LOCKSTEP_GROUPED").as_deref() {
1637            Ok("1") => true,
1638            Ok("0") => false,
1639            // Auto: grouped wins from m>=3 under the default q8 lanes (M2 gate 2026-07-23:
1640            // m=2 6.17 base vs 5.85 grouped; m=3 6.31 grouped; m=4 5.66 vs 5.34).
1641            _ => m >= 3,
1642        };
1643        let n_embd_total = n_embd * m;
1644        for (il, layer) in self.layers.iter().enumerate() {
1645            let anorm = layer.attn_norm.float_data();
1646            let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
1647                && self.mixer_in_q8_1_fast(e, &layer.mixer);
1648            let mut mixed_rows: Vec<Option<CudaSlice<f32>>> = (0..m).map(|_| None).collect();
1649            for s in 0..m {
1650                let pos = caches[s].pos;
1651                let taken = pending[s].take();
1652                let mixed = match (taken, fuse) {
1653                    (Some((x1, f1)), true) => {
1654                        let mut x2 = e.uninit(n_embd)?;
1655                        let (hq, hd) =
1656                            e.add_rms_norm_q8_1(&x1, &f1, anorm, &mut x2, n_embd, 1, eps)?;
1657                        x[s] = x2;
1658                        let h0 = e.zeros(0)?;
1659                        match &layer.mixer {
1660                            Mixer::Full(fa) => self.full_attn_decode_pre(
1661                                e,
1662                                fa,
1663                                &h0,
1664                                Some((&hq, &hd)),
1665                                &pos_d[s],
1666                                pos,
1667                                &mut caches[s],
1668                                il,
1669                            )?,
1670                            Mixer::Linear(la) => self.linear_attn_decode_pre(
1671                                e,
1672                                la,
1673                                &h0,
1674                                &hq,
1675                                &hd,
1676                                &mut caches[s],
1677                                il,
1678                                false,
1679                            )?,
1680                            Mixer::Mla(_) => {
1681                                crate::hybrid::mla_path_unimplemented("lockstep decode")
1682                            }
1683                            Mixer::Kda(_) => {
1684                                crate::hybrid::kda_path_unimplemented("lockstep decode")
1685                            }
1686                        }
1687                    }
1688                    (taken, _) => {
1689                        if let Some((x1, f1)) = taken {
1690                            let mut x2 = e.uninit(n_embd)?;
1691                            e.add(&x1, &f1, &mut x2, n_embd)?;
1692                            x[s] = x2;
1693                        }
1694                        self.attn_in_norm_mixer(
1695                            e,
1696                            layer,
1697                            &x[s],
1698                            &pos_d[s],
1699                            pos,
1700                            &mut caches[s],
1701                            il,
1702                            n_embd,
1703                            eps,
1704                        )?
1705                    }
1706                };
1707                if grouped && matches!(&layer.ffn, crate::hybrid::Ffn::Moe(_)) {
1708                    mixed_rows[s] = Some(mixed);
1709                } else {
1710                    let (x1, ffn_out) =
1711                        self.residual_norm_ffn(e, layer, &x[s], &mixed, n_embd, il, eps)?;
1712                    pending[s] = Some((x1, ffn_out));
1713                }
1714            }
1715            if grouped && let crate::hybrid::Ffn::Moe(moe_weights) = &layer.ffn {
1716                // Per-stream add+norm (identical math to residual_norm_ffn's MoE arm),
1717                // rows batched for the cross-stream MoE stage, outputs split back.
1718                let pnorm = layer.post_attn_norm.float_data();
1719                let mut zbatch = e.uninit(n_embd_total)?;
1720                let mut x1s: Vec<CudaSlice<f32>> = Vec::with_capacity(m);
1721                for s in 0..m {
1722                    let mixed = mixed_rows[s].take().expect("grouped MoE row missing");
1723                    let mut x1 = e.uninit(n_embd)?;
1724                    let mut z = e.uninit(n_embd)?;
1725                    e.add_rms_norm(&x[s], &mixed, pnorm, &mut x1, &mut z, n_embd, 1, eps)?;
1726                    e.copy_view_into(&mut zbatch, s * n_embd, &z.slice(0..n_embd), n_embd)?;
1727                    x1s.push(x1);
1728                }
1729                let max_block = self.max_moe_block();
1730                let ffn_all =
1731                    self.moe_ffn_lockstep(e, moe_weights, &zbatch, m, il as u16, max_block)?;
1732                for (s, x1) in x1s.into_iter().enumerate() {
1733                    let mut out = e.uninit(n_embd)?;
1734                    e.copy_view_into(
1735                        &mut out,
1736                        0,
1737                        &ffn_all.slice(s * n_embd..(s + 1) * n_embd),
1738                        n_embd,
1739                    )?;
1740                    pending[s] = Some((x1, out));
1741                }
1742            }
1743        }
1744
1745        let mut logits_host = Vec::with_capacity(m);
1746        for s in 0..m {
1747            if let Some((x1, f1)) = pending[s].take() {
1748                let mut x2 = e.uninit(n_embd)?;
1749                e.add(&x1, &f1, &mut x2, n_embd)?;
1750                x[s] = x2;
1751            }
1752            let mut hn = e.uninit(n_embd)?;
1753            e.rms_norm(
1754                &x[s],
1755                self.output_norm.float_data(),
1756                &mut hn,
1757                n_embd,
1758                1,
1759                eps,
1760            )?;
1761            let logits = e.matmul(&self.output, &hn, 1)?;
1762            logits_host.push(e.dtoh(&logits)?);
1763            caches[s].pos += 1;
1764        }
1765        Ok(logits_host)
1766    }
1767
1768    /// DEVICE-COUNTER decode step (CUDA-GRAPH-PLAN Phase 2). A clone of `decode_step_h` that removes
1769    /// the two per-step VARYING host kernel-args by reading them from device counters:
1770    ///   1. the KV-append write slot  -> per-layer `kvl.len_d` (device i32[1])
1771    ///   2. the fa_decode t_kv bound   -> the same `kvl.len_d` after `inc_seqlen`
1772    ///      plus it keeps the token id + rope pos DEVICE-RESIDENT (embed_gather_device, device rope pos,
1773    ///      argmax_token_device). NO graph capture yet — runs the kernels eagerly through the counter
1774    ///      path. Must be BIT-IDENTICAL to `decode_step_h`'s token stream (the gate).
1775    ///
1776    /// Args: `token_d` = resident device token id [1] (this step's input token); `pos_d` = resident
1777    /// device rope pos i32[1] (== cache.pos at entry; INCREMENTED in-path); `embd_gpu` = resident embed
1778    /// table; (qt,row_bytes) from EmbedHost::qt_and_row_bytes. Returns the NEXT token id device buffer.
1779    /// `cache.pos` and each `kvl.len`/`kvl.len_d` are advanced to match `decode_step_h`.
1780    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
1781    pub fn decode_step_dc(
1782        &self,
1783        e: &Engine,
1784        token_d: &CudaSlice<u32>,
1785        pos_d: &mut CudaSlice<i32>,
1786        embd_gpu: &CudaSlice<u8>,
1787        embd_qt: i32,
1788        embd_row_bytes: usize,
1789        cache: &mut Cache,
1790        n_vocab: usize,
1791    ) -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
1792        self.refuse_hyper("decode_step_dc")?;
1793        cache.ensure_usable("decode_step_dc")?;
1794        // Route gemma4 to ITS dc twin (mirrors decode_step_h): the generic walk below is the
1795        // qwen-class layer stack — running gemma weights through it produced the argmax-INIT
1796        // passthrough the round-45 g12 gate caught (first Hopper gating of this lane).
1797        if self.is_gemma4_e4b() {
1798            return Err("e4b has no device-counter decode step (dc/graph unwired)".into());
1799        }
1800        // PP DOOR: fail closed (pp2-hardening 2026-08-06). Same hole the batched path had —
1801        // the dc walk below is `for (il, layer) in self.layers.iter().enumerate()` on one
1802        // stream, with no stage split, so a sharded cross-device placement would peer-read
1803        // every remote layer's weights per step. Sits BEFORE the gemma4 delegate because
1804        // that twin has the same unsplit shape. The graph-capture path (`decode_step_dc_cap*`)
1805        // is covered transitively: it captures this same kernel chain, and its drivers reach
1806        // dc first — but a future capture path that does NOT is why the guard is a shared
1807        // helper (`pp::refuse_unsplit_if_remote`) rather than four copies.
1808        crate::pp::refuse_unsplit_if_remote(
1809            "decode_step_dc",
1810            "use the eager pp arm (decode_step_h), which IS stage-split",
1811        )?;
1812        if self.uses_gemma_program() {
1813            return self.gemma4_decode_step_dc(
1814                e,
1815                token_d,
1816                pos_d,
1817                embd_gpu,
1818                embd_qt,
1819                embd_row_bytes,
1820                cache,
1821                n_vocab,
1822                None,
1823            );
1824        }
1825        let cfg = &self.cfg;
1826        let n_embd = cfg.n_embd as usize;
1827        let eps = cfg.rms_eps;
1828
1829        // embed the single (DEVICE-resident) token -> [1, n_embd], no host round-trip of the id.
1830        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_row_bytes)?;
1831
1832        for (il, layer) in self.layers.iter().enumerate() {
1833            // attn-input NORM-FUSION (dc path); bit-identical to decode_step_h (Phase-2 gate).
1834            let mixed = self.attn_in_norm_mixer_dc(e, layer, &x, pos_d, cache, il, n_embd, eps)?;
1835
1836            // DECODE NORM-FUSION LEVER (residual_norm_ffn): see decode_step_h. Shared helper -> dc
1837            // path stays bit-identical to decode_step_h's token stream (the Phase-2 gate).
1838            let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
1839            // MEMRA_TG_PROBE_LAYER diagnostics (token-graph bisection): dump layer K's
1840            // attention output and post-FFN residual through the real eager path.
1841            if std::env::var("MEMRA_TG_PROBE_LAYER")
1842                .ok()
1843                .and_then(|v| v.parse::<usize>().ok())
1844                == Some(il)
1845            {
1846                use std::io::Write;
1847                let mut xp = e.uninit(n_embd)?;
1848                e.add(&x1, &ffn_out, &mut xp, n_embd)?;
1849                let (pm, px) = (e.dtoh(&mixed)?, e.dtoh(&xp)?);
1850                for (path, data) in [
1851                    ("/root/eager-probe-mixed.bin", &pm),
1852                    ("/root/eager-probe-x.bin", &px),
1853                ] {
1854                    let mut fo = std::fs::OpenOptions::new()
1855                        .create(true)
1856                        .append(true)
1857                        .open(path)?;
1858                    for v in data {
1859                        fo.write_all(&v.to_le_bytes())?;
1860                    }
1861                }
1862            }
1863            let mut x2 = e.uninit(n_embd)?;
1864            e.add(&x1, &ffn_out, &mut x2, n_embd)?;
1865            x = x2;
1866        }
1867
1868        let mut hn = e.uninit(n_embd)?;
1869        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1870        let logits = e.matmul(&self.output, &hn, 1)?;
1871        // device argmax -> next token id stays resident (no logits dtoh).
1872        let next_tok = e.argmax_token_device(&logits, n_vocab)?;
1873        // advance rope pos counter on-device (replaces the per-step htod_i32(&[pos])).
1874        e.inc_seqlen(pos_d)?;
1875        cache.pos += 1;
1876        Ok(next_tok)
1877    }
1878
1879    /// CAPTURE body for CUDA-graph replay (CUDA-GRAPH-PLAN Phase 3). One full decode step enqueued
1880    /// entirely on `e.stream()` with ZERO host sync and ZERO per-step varying host kernel-args:
1881    ///   - embed reads the PERSISTENT device `token_d` (last step's argmax), writes scratch `x`.
1882    ///   - full-attn layers size n_splits from `bucket_max` (fixed for this capture); the kernel reads
1883    ///     the ACTUAL t_kv from the device counter `kvl.len_d`. KV append + device-counter inc happen
1884    ///     in-graph. The host `kvl.len`/`cache.pos` are NOT advanced here (the driver advances the host
1885    ///     mirrors once per replay; only the DEVICE counters advance inside the graph).
1886    ///   - linear-attn layers use the persistent-state variant (copy-back, stable pointers).
1887    ///   - lm_head -> parallel 2-pass argmax (`argmax_partial_f32`+`argmax_final_f32`) writes the
1888    ///     next id into the PERSISTENT `token_d`.
1889    ///   - `inc_seqlen(pos_d)` advances the rope-pos device counter in-graph.
1890    ///     Captured ONCE per `bucket_max`; replayed for every t_kv in that bucket. Bit-identical to eager
1891    ///     when `bucket_max` reproduces eager's n_splits for the replayed t_kv (the bucket-key contract).
1892    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
1893    pub fn decode_step_dc_cap(
1894        &self,
1895        e: &Engine,
1896        token_d: &mut CudaSlice<u32>,
1897        pos_d: &mut CudaSlice<i32>,
1898        embd_gpu: &CudaSlice<u8>,
1899        embd_qt: i32,
1900        embd_row_bytes: usize,
1901        cache: &mut Cache,
1902        n_vocab: usize,
1903        bucket_max: usize,
1904    ) -> Result<(), Box<dyn std::error::Error>> {
1905        self.refuse_hyper("decode_step_dc_cap")?;
1906        self.decode_step_dc_cap_masked(
1907            e,
1908            token_d,
1909            pos_d,
1910            embd_gpu,
1911            embd_qt,
1912            embd_row_bytes,
1913            cache,
1914            n_vocab,
1915            bucket_max,
1916            None,
1917        )
1918    }
1919
1920    /// `decode_step_dc_cap` + GRAMMAR MASK (constrained decoding): with `mask =
1921    /// Some((buf, words))`, mask_logits_f32 bans the packed bitset's unset ids IN the
1922    /// captured graph — a stable-pointer read between lm_head and the in-graph argmax
1923    /// (the KV-pointer pattern: contents change per step, address is baked). `None` is
1924    /// bit-for-bit the unmasked capture.
1925    #[allow(clippy::too_many_arguments)]
1926    pub fn decode_step_dc_cap_masked(
1927        &self,
1928        e: &Engine,
1929        token_d: &mut CudaSlice<u32>,
1930        pos_d: &mut CudaSlice<i32>,
1931        embd_gpu: &CudaSlice<u8>,
1932        embd_qt: i32,
1933        embd_row_bytes: usize,
1934        cache: &mut Cache,
1935        n_vocab: usize,
1936        bucket_max: usize,
1937        mask: Option<(&CudaSlice<u32>, usize)>,
1938    ) -> Result<(), Box<dyn std::error::Error>> {
1939        self.refuse_hyper("decode_step_dc_cap_masked")?;
1940        cache.ensure_usable("decode_step_dc_cap")?;
1941        let cfg = &self.cfg;
1942        let n_embd = cfg.n_embd as usize;
1943        let eps = cfg.rms_eps;
1944
1945        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_row_bytes)?;
1946
1947        for (il, layer) in self.layers.iter().enumerate() {
1948            // attn-input NORM-FUSION (capture path); capture-safe + bit-identical to eager.
1949            let mixed = self.attn_in_norm_mixer_dc_cap(
1950                e, layer, &x, pos_d, cache, il, bucket_max, n_embd, eps,
1951            )?;
1952            // DECODE NORM-FUSION LEVER (residual_norm_ffn): see decode_step_aux. Shared helper keeps
1953            // the capture path bit-identical to eager by construction.
1954            let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
1955            // MEMRA_TG_PROBE_LAYER diagnostics (token-graph bisection): dump layer K's
1956            // attention output and post-FFN residual through the real eager path.
1957            if std::env::var("MEMRA_TG_PROBE_LAYER")
1958                .ok()
1959                .and_then(|v| v.parse::<usize>().ok())
1960                == Some(il)
1961            {
1962                use std::io::Write;
1963                let mut xp = e.uninit(n_embd)?;
1964                e.add(&x1, &ffn_out, &mut xp, n_embd)?;
1965                let (pm, px) = (e.dtoh(&mixed)?, e.dtoh(&xp)?);
1966                for (path, data) in [
1967                    ("/root/eager-probe-mixed.bin", &pm),
1968                    ("/root/eager-probe-x.bin", &px),
1969                ] {
1970                    let mut fo = std::fs::OpenOptions::new()
1971                        .create(true)
1972                        .append(true)
1973                        .open(path)?;
1974                    for v in data {
1975                        fo.write_all(&v.to_le_bytes())?;
1976                    }
1977                }
1978            }
1979            let mut x2 = e.uninit(n_embd)?;
1980            e.add(&x1, &ffn_out, &mut x2, n_embd)?;
1981            x = x2;
1982        }
1983
1984        let mut hn = e.uninit(n_embd)?;
1985        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1986        let mut logits = e.matmul(&self.output, &hn, 1)?;
1987        // GRAMMAR MASK: ban before the argmax reads the row (masked argmax == host
1988        // masked-argmax — -FLT_MAX is the argmax kernels' init sentinel).
1989        if let Some((m, words)) = mask {
1990            e.mask_logits_col(&mut logits, m, 0, n_vocab, words)?;
1991        }
1992        // argmax into the PERSISTENT token_d (next step's embed reads it) — same buffer pointer baked
1993        // at capture, written each replay, so the token id never round-trips to host in steady state.
1994        e.argmax_token_device_into(&logits, token_d, n_vocab)?;
1995        e.inc_seqlen(pos_d)?;
1996        Ok(())
1997    }
1998
1999    /// CUDA-GRAPH decode driver (CUDA-GRAPH-PLAN Phase 3). Primes the prompt EAGERLY (device-counter
2000    /// `decode_step_dc`, advancing host + device counters together), then generates `max_new` tokens by
2001    /// CUDA-graph REPLAY: per step it picks the t_kv bucket key, captures a graph on first sight of that
2002    /// key (re-using the SAME persistent counters/cache so replays continue the sequence), and replays.
2003    /// The argmax-written next token stays device-resident in `gs.token_d`; we read back only the [1]
2004    /// u32 after each launch (the gate compares it; a real server can defer this). Returns the generated
2005    /// token ids. Greedy. Bit-identical to eager `decode_step` (the gate).
2006    ///
2007    /// CAPTURE STATE HYGIENE: `capture_graph` runs the step body 3x (2 warmup + 1 capture), each of
2008    /// which mutates the device KV/conv/ssm/counter state. We SNAPSHOT the cache + device counters +
2009    /// token id before capturing and RESTORE them after, so the 3 throwaway runs leave zero residue and
2010    /// replay resumes from the true pre-capture state.
2011    pub fn generate_graph(
2012        &self,
2013        e: &Engine,
2014        gs: &mut GraphDecodeState,
2015        prompt: &[u32],
2016        max_new: usize,
2017    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
2018        self.refuse_hyper("generate_graph")?;
2019        if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::DecodeGraph) {
2020            if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::DecodeEager) {
2021                return Err("neither graph nor eager decode rewrite is qualified".into());
2022            }
2023            static ONCE: std::sync::Once = std::sync::Once::new();
2024            ONCE.call_once(|| {
2025                eprintln!(
2026                    "[rewrite] decode-graph.v1 unqualified; using receipt-backed native eager decode"
2027                );
2028            });
2029            return self.generate(e, prompt, max_new);
2030        }
2031        let n_embd = self.cfg.n_embd as usize;
2032        let head_dim = self.cfg.head_dim_k as usize;
2033        let (qt, row_bytes) = self.embd.qt_and_row_bytes(n_embd);
2034
2035        // EVENT TRACKING OFF for the WHOLE graph-decode session. cudarc records a per-CudaSlice event
2036        // (the Engine is in multi-stream mode via copy_stream) and inserts `stream.wait(event)` on every
2037        // kernel arg whose buffer was touched — those waits are illegal inside a capture region. The
2038        // captured decode step is strictly single-stream, so this tracking is unnecessary. Disable it
2039        // BEFORE allocating ANY buffer the captured graph will reference (cache, embd, counters,
2040        // scratch) so none of them carry events. SAFETY: decode-dc touches only gpu.stream.
2041        let was_tracking = e.ctx().is_event_tracking();
2042        if was_tracking {
2043            unsafe {
2044                e.ctx().disable_event_tracking();
2045            }
2046        }
2047        let r = self.generate_graph_inner(e, gs, prompt, max_new, n_embd, head_dim, qt, row_bytes);
2048        if was_tracking {
2049            unsafe {
2050                e.ctx().enable_event_tracking();
2051            }
2052        }
2053        r
2054    }
2055
2056    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
2057    fn generate_graph_inner(
2058        &self,
2059        e: &Engine,
2060        gs: &mut GraphDecodeState,
2061        prompt: &[u32],
2062        max_new: usize,
2063        n_embd: usize,
2064        head_dim: usize,
2065        qt: i32,
2066        row_bytes: usize,
2067    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
2068        let _ = n_embd;
2069        let embd_gpu = e.upload_u8(&self.embd.raw)?;
2070        let max_ctx = prompt.len() + max_new + 8;
2071        let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
2072
2073        // (Re)create the persistent counters tracking-OFF so they carry no events (the caller's
2074        // GraphDecodeState::new may have allocated them with tracking on).
2075        gs.pos_d = e.htod_i32(&[0])?;
2076        gs.token_d = e.stream().clone_htod(&[0u32])?;
2077        // PRIME eagerly: feed each prompt token; advance host + device counters together.
2078        let mut next_in = 0u32;
2079        for &tok in prompt {
2080            e.set_u32_one(&mut gs.token_d, tok)?;
2081            let nt = self.decode_step_dc(
2082                e,
2083                &gs.token_d,
2084                &mut gs.pos_d,
2085                &embd_gpu,
2086                qt,
2087                row_bytes,
2088                &mut cache,
2089                /*n_vocab*/ self.output.out_features(),
2090            )?;
2091            next_in = e.dtoh_u32_one(&nt)?;
2092        }
2093        // gs.token_d now must hold the first generated INPUT token (= argmax of the last prime step).
2094        e.set_u32_one(&mut gs.token_d, next_in)?;
2095
2096        // gemma4 rides ITS graph machinery (per-bucket captures + alloc-free slots; same token
2097        // stream convention: first generated token is out[0]) — graph_decode_loop below captures
2098        // the qwen-class dc step (the round-45 g12 illegal-address find).
2099        if self.uses_gemma_program() {
2100            let (toks, _reason) = self.gemma4_generate_graph(
2101                e,
2102                cache.pos,
2103                next_in,
2104                &mut cache,
2105                max_new,
2106                &[],
2107                |_| true,
2108            )?;
2109            gs.captures += 1;
2110            return Ok(toks);
2111        }
2112
2113        let mut out = Vec::with_capacity(max_new);
2114        self.graph_decode_loop(
2115            e,
2116            gs,
2117            &mut cache,
2118            &embd_gpu,
2119            qt,
2120            row_bytes,
2121            head_dim,
2122            max_new,
2123            |tok| {
2124                out.push(tok);
2125                None
2126            },
2127        )?;
2128        Ok(out)
2129    }
2130
2131    /// The CUDA-graph EXEC-UPDATE replay loop over an already-primed cache (2026-07-15,
2132    /// the E4B graph-exec pattern generalized): capture the dc step per KERNEL-CLASS
2133    /// SEGMENT, classify its fa nodes (`graph_update::fa_plan` — symbol list is
2134    /// model-generic), then per token retune the fa split geometry to the LIVE eager
2135    /// ladder (`fa_apply` keeps graph and eager in FP lockstep — bit-exact) and replay.
2136    /// The previous per-bucket-key capture map recaptured on every ladder rung
2137    /// (32 recaptures/256 tokens = 97 vs 128 tok/s eager; decode-bench 2026-07-15).
2138    ///
2139    /// SEGMENTS (round 45, the q35 graph-gate dig): exec-update can retune split counts
2140    /// but can NOT swap kernels — a session spanning an eager KERNEL-CLASS boundary
2141    /// (fa_vec floor, the v4 max, the fa512 floor) replayed the capture-time kernel
2142    /// against a different eager kernel below the boundary: valid softmax, different
2143    /// fold order, and the first near-tie flips the stream (q35: deterministic 144/256
2144    /// from step 110, exactly the scalar->vec crossing; regime pinned either way =
2145    /// BIT-IDENTICAL 256/256). One capture per crossed class boundary (2-3/session,
2146    /// not per rung) keeps graph and eager on the SAME kernel at every t_kv.
2147    ///
2148    /// Callers must have synced gs.token_d (= the FIRST generated token), gs.pos_d
2149    /// (= cache.pos) and every kvl.len_d (= kvl.len). Event tracking must be OFF.
2150    #[allow(clippy::too_many_arguments)]
2151    pub(crate) fn graph_decode_loop(
2152        &self,
2153        e: &Engine,
2154        gs: &mut GraphDecodeState,
2155        cache: &mut Cache,
2156        embd_gpu: &CudaSlice<u8>,
2157        qt: i32,
2158        row_bytes: usize,
2159        head_dim: usize,
2160        max_new: usize,
2161        mut emit: impl FnMut(u32) -> Option<StopReason>,
2162    ) -> Result<StopReason, Box<dyn std::error::Error>> {
2163        let _ = head_dim;
2164        let n_vocab = self.output.out_features();
2165        let final_max = cache.pos + max_new + 1;
2166
2167        // first generated token = argmax of the last prime step (emit before replay 1).
2168        let first = e.dtoh_u32_one(&gs.token_d)?;
2169        if let Some(r) = emit(first) {
2170            return Ok(r);
2171        }
2172        let mut done = 1usize;
2173        while done < max_new {
2174            let (graph, mut plan, seg_end) = self
2175                .graph_capture_segment(e, cache, gs, embd_gpu, qt, row_bytes, n_vocab, final_max)?;
2176
2177            #[allow(clippy::int_plus_one)]
2178            // allow: the +1 form states the documented boundary, not an off-by-one
2179            while done < max_new && cache.pos + 1 <= seg_end {
2180                // retune fa geometry to the live t_kv AFTER this replay's in-graph append.
2181                crate::graph_update::fa_apply(
2182                    &graph,
2183                    &mut plan,
2184                    cache.pos + 1,
2185                    crate::fa_split_keys,
2186                )?;
2187                graph.launch()?;
2188                cache.pos += 1;
2189                for kvl in cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
2190                    kvl.len += 1;
2191                }
2192                // read back the [1] u32 next token (the only D2H in steady state).
2193                let tok = e.dtoh_u32_one(&gs.token_d)?;
2194                done += 1;
2195                if let Some(r) = emit(tok) {
2196                    return Ok(r);
2197                }
2198            }
2199        }
2200        Ok(StopReason::MaxNew)
2201    }
2202
2203    /// Step-wise CUDA-graph decode session (ARCHITECTURE-H100.md graph-serving lane,
2204    /// 2026-07-26): generate_graph's prime+capture lifted into a long-lived session so a
2205    /// SERVING scheduler can replay ONE step per tick instead of blocking a whole
2206    /// generation. Serving policy (measured): graphs win only at B=1 (214 solo vs 425
2207    /// aggregate batched-eager at B=4) — this is the single-interactive-session path.
2208    /// Capture discipline is generate_graph's verbatim: event tracking must be OFF for
2209    /// every buffer the graph references (new() toggles it), capture at bucket_max =
2210    /// pos + max_new + 1, fa geometry retuned per step (fa_apply, FP lockstep with eager).
2211    pub fn graph_session_new(
2212        &self,
2213        e: &Engine,
2214        prompt: &[u32],
2215        max_new: usize,
2216    ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
2217        self.refuse_hyper("graph_session_new")?;
2218        let n_embd = self.cfg.n_embd as usize;
2219        let (qt, row_bytes) = self.embd.qt_and_row_bytes(n_embd);
2220        let was_tracking = e.ctx().is_event_tracking();
2221        if was_tracking {
2222            unsafe {
2223                e.ctx().disable_event_tracking();
2224            }
2225        }
2226        let r = self.graph_session_new_inner(e, prompt, max_new, qt, row_bytes);
2227        if was_tracking {
2228            unsafe {
2229                e.ctx().enable_event_tracking();
2230            }
2231        }
2232        r
2233    }
2234
2235    fn graph_session_new_inner(
2236        &self,
2237        e: &Engine,
2238        prompt: &[u32],
2239        max_new: usize,
2240        qt: i32,
2241        row_bytes: usize,
2242    ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
2243        let n_vocab = self.output.out_features();
2244        let embd_gpu = e.upload_u8(&self.embd.raw)?;
2245        let max_ctx = prompt.len() + max_new + 8;
2246        let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
2247        let mut gs = GraphDecodeState::new(e)?;
2248        gs.pos_d = e.htod_i32(&[0])?;
2249        gs.token_d = e.stream().clone_htod(&[0u32])?;
2250        // prime (dc path — device counters advance with the host)
2251        let mut next_in = 0u32;
2252        for &tok in prompt {
2253            e.set_u32_one(&mut gs.token_d, tok)?;
2254            let nt = self.decode_step_dc(
2255                e,
2256                &gs.token_d,
2257                &mut gs.pos_d,
2258                &embd_gpu,
2259                qt,
2260                row_bytes,
2261                &mut cache,
2262                n_vocab,
2263            )?;
2264            next_in = e.dtoh_u32_one(&nt)?;
2265        }
2266        e.set_u32_one(&mut gs.token_d, next_in)?;
2267        self.graph_session_capture(
2268            e, cache, gs, embd_gpu, max_new, qt, row_bytes, n_vocab, None, 0,
2269        )
2270    }
2271
2272    /// GraphSession over an ALREADY-PRIMED cache (round 35): keeps the chunked-prefill
2273    /// TTFT. graph_session_new's token-wise re-prime made solo long-prompt promotion a
2274    /// net ~3x END-TO-END LOSS (measured live: 871-tok prompt + 400 gen = 6.4s vs ~2.2s
2275    /// eager). Device counters sync from host state; capture recipe unchanged.
2276    /// Requires event tracking OFF (engine default; MEMRA_EVT=1 callers must not use this
2277    /// — the primed cache's buffers would carry events, illegal inside capture).
2278    pub fn graph_session_from_cache(
2279        &self,
2280        e: &Engine,
2281        cache: Cache,
2282        first_token: u32,
2283        max_new: usize,
2284    ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
2285        self.graph_session_from_cache_masked(e, cache, first_token, max_new, None)
2286    }
2287
2288    /// `graph_session_from_cache` + GRAMMAR MASK (constrained decoding, 2026-08-03):
2289    /// `mask_init = Some(packed bitset)` allocates the session's stable mask buffer
2290    /// (tracking is OFF here — capture-legal), seeds it with the FIRST step's mask, and
2291    /// captures mask_logits_f32 into the graphed step. The caller re-uploads contents
2292    /// per step via `GraphSession::upload_mask` — same stable-pointer discipline as the
2293    /// KV len_d counters. `None` = the unmasked session, byte-identical.
2294    pub fn graph_session_from_cache_masked(
2295        &self,
2296        e: &Engine,
2297        mut cache: Cache,
2298        first_token: u32,
2299        max_new: usize,
2300        mask_init: Option<&[u32]>,
2301    ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
2302        cache.ensure_usable("graph_session_from_cache")?;
2303        if e.ctx().is_event_tracking() {
2304            return Err(
2305                "graph_session_from_cache requires event tracking OFF (MEMRA_EVT unset)".into(),
2306            );
2307        }
2308        let n_embd = self.cfg.n_embd as usize;
2309        let (qt, row_bytes) = self.embd.qt_and_row_bytes(n_embd);
2310        let n_vocab = self.output.out_features();
2311        let embd_gpu = e.upload_u8(&self.embd.raw)?;
2312        let mut gs = GraphDecodeState::new(e)?;
2313        gs.pos_d = e.htod_i32(&[cache.pos as i32])?;
2314        gs.token_d = e.stream().clone_htod(&[first_token])?;
2315        for kvl in cache.kv.iter_mut().flatten() {
2316            e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2317        }
2318        let mask_dev = match mask_init {
2319            Some(w) => Some(e.htod_u32_v(w)?),
2320            None => None,
2321        };
2322        let mask_words = mask_init.map(|w| w.len()).unwrap_or(0);
2323        self.graph_session_capture(
2324            e, cache, gs, embd_gpu, max_new, qt, row_bytes, n_vocab, mask_dev, mask_words,
2325        )
2326    }
2327
2328    /// Eager fa kernel-class fingerprint at a given t_kv: the fa_vec pick plus the
2329    /// intra-vec variant switches (v4 max, fa512 floor) plus the split-ladder rung.
2330    /// fa_apply handles split-count changes WITHIN a rung; anything that changes this
2331    /// tuple needs a fresh capture (bucket_max drives the capture-time kernel pick).
2332    /// Round 45; LADDER RUNG ADDED 2026-08-02 (lane/ladder-3072): the dc kernels derive
2333    /// their in-kernel partition from the CAPTURED split_keys arg (ns_eff =
2334    /// ceil(T_kv/split_keys) — the ONE-PARTITION law), and fa_apply retunes only
2335    /// n_splits/grid. A capture whose segment straddled a ladder rung therefore replayed
2336    /// the far side's partition against eager's near side — same math, different FP fold
2337    /// order, and the first near-tie flips the stream (latent at the old 3072 rung: kat
2338    /// P=3000 passed on logit margins; exposed by the 512 rung: kat P=400 flipped 97/160).
2339    /// With the rung in the fingerprint a capture never straddles it, so the captured
2340    /// split_keys equals the live ladder on every replay — bit-exact at every t_kv.
2341    pub(crate) fn fa_class_of(&self, e: &Engine, t_kv: usize) -> (bool, bool, bool, usize) {
2342        let head_dim = self.cfg.head_dim_k as usize;
2343        let nkv = self.cfg.n_head_kv as usize;
2344        (
2345            e.fa_geom_eager(t_kv, head_dim, nkv, false).0,
2346            crate::fa_v4_at_pub(t_kv),
2347            head_dim == 512 && t_kv >= crate::fa512_min_tkv(),
2348            crate::fa_split_keys_pub(t_kv, nkv),
2349        )
2350    }
2351
2352    /// Last t_kv (clamped to `final_max`) sharing `start`'s eager kernel class.
2353    pub(crate) fn fa_segment_end(&self, e: &Engine, start: usize, final_max: usize) -> usize {
2354        let cls = self.fa_class_of(e, start);
2355        let mut end = start;
2356        while end < final_max && self.fa_class_of(e, end + 1) == cls {
2357            end += 1;
2358        }
2359        end
2360    }
2361
2362    /// Capture one kernel-class segment: snapshot/rollback the warmup runs, capture the
2363    /// dc step at bucket_max = the segment's last t_kv, fa_plan. Shared by the session
2364    /// creation, the session's recapture-on-cross, and graph_decode_loop.
2365    #[allow(clippy::too_many_arguments)]
2366    pub(crate) fn graph_capture_segment(
2367        &self,
2368        e: &Engine,
2369        cache: &mut Cache,
2370        gs: &mut GraphDecodeState,
2371        embd_gpu: &CudaSlice<u8>,
2372        qt: i32,
2373        row_bytes: usize,
2374        n_vocab: usize,
2375        final_max: usize,
2376    ) -> Result<
2377        (
2378            cudarc::driver::CudaGraph,
2379            Vec<crate::graph_update::FaMain>,
2380            usize,
2381        ),
2382        Box<dyn std::error::Error>,
2383    > {
2384        self.graph_capture_segment_masked(
2385            e, cache, gs, embd_gpu, qt, row_bytes, n_vocab, final_max, None,
2386        )
2387    }
2388
2389    /// `graph_capture_segment` + optional in-graph grammar mask (see decode_step_dc_cap_masked).
2390    #[allow(clippy::too_many_arguments)]
2391    pub(crate) fn graph_capture_segment_masked(
2392        &self,
2393        e: &Engine,
2394        cache: &mut Cache,
2395        gs: &mut GraphDecodeState,
2396        embd_gpu: &CudaSlice<u8>,
2397        qt: i32,
2398        row_bytes: usize,
2399        n_vocab: usize,
2400        final_max: usize,
2401        mask: Option<(&CudaSlice<u32>, usize)>,
2402    ) -> Result<
2403        (
2404            cudarc::driver::CudaGraph,
2405            Vec<crate::graph_update::FaMain>,
2406            usize,
2407        ),
2408        Box<dyn std::error::Error>,
2409    > {
2410        let t0 = cache.pos + 1;
2411        let seg_end = self.fa_segment_end(e, t0, final_max);
2412        let bucket_max = seg_end;
2413        let snap = cache.snapshot(e)?;
2414        let pos_save = e.dtoh_i32_one(&gs.pos_d)?;
2415        let len_save: Vec<Option<i32>> = cache
2416            .kv
2417            .iter()
2418            .map(|k| k.as_ref().map(|kvl| e.dtoh_i32_one(&kvl.len_d).unwrap()))
2419            .collect();
2420        let tok_save = e.dtoh_u32_one(&gs.token_d)?;
2421        let graph = {
2422            let GraphDecodeState { token_d, pos_d, .. } = gs;
2423            let token_d: &mut CudaSlice<u32> = token_d;
2424            let pos_d: &mut CudaSlice<i32> = pos_d;
2425            let cache_ref = &mut *cache;
2426            e.capture_graph(|e| {
2427                self.decode_step_dc_cap_masked(
2428                    e, token_d, pos_d, embd_gpu, qt, row_bytes, cache_ref, n_vocab, bucket_max,
2429                    mask,
2430                )
2431            })?
2432        };
2433        gs.captures += 1;
2434        cache.rollback(e, &snap, 0)?;
2435        e.set_i32_one(&mut gs.pos_d, pos_save)?;
2436        for (il, ls) in len_save.iter().enumerate() {
2437            if let (Some(kvl), Some(v)) = (cache.kv[il].as_mut(), ls) {
2438                e.set_i32_one(&mut kvl.len_d, *v)?;
2439            }
2440        }
2441        e.set_u32_one(&mut gs.token_d, tok_save)?;
2442        let plan = crate::graph_update::fa_plan(&graph)?;
2443        if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
2444            eprintln!(
2445                "[graph-census] segment t_kv {t0}..={seg_end} fa_plan mains: {}",
2446                plan.len()
2447            );
2448            if let Ok(c) = crate::graph_update::node_census(&graph) {
2449                eprintln!("[graph-census] {c:?}");
2450            }
2451        }
2452        Ok((graph, plan, seg_end))
2453    }
2454
2455    /// Measurement door for `graph_session_recapture` (graph-allocfree-probe): the capture
2456    /// path timed WITHOUT the prompt prime. Same call the live step() makes at a
2457    /// kernel-class crossing.
2458    pub fn graph_session_recapture_pub(
2459        &self,
2460        e: &Engine,
2461        sess: &mut GraphSession,
2462    ) -> Result<(), Box<dyn std::error::Error>> {
2463        self.graph_session_recapture(e, sess)
2464    }
2465
2466    /// Session recapture at a kernel-class boundary (called by GraphSession::step).
2467    /// The mask node (when present) re-bakes the SAME stable buffer — contents carry over.
2468    pub(crate) fn graph_session_recapture(
2469        &self,
2470        e: &Engine,
2471        sess: &mut GraphSession,
2472    ) -> Result<(), Box<dyn std::error::Error>> {
2473        let mask = sess.mask_dev.take();
2474        let (graph, plan, seg_end) = self.graph_capture_segment_masked(
2475            e,
2476            &mut sess.cache,
2477            &mut sess.gs,
2478            &sess.embd_gpu,
2479            sess.qt,
2480            sess.row_bytes,
2481            sess.n_vocab,
2482            sess.bucket_max,
2483            mask.as_ref().map(|d| (d, sess.mask_words)),
2484        )?;
2485        sess.mask_dev = mask;
2486        sess.graph = graph;
2487        sess.plan = plan;
2488        sess.seg_end = seg_end;
2489        Ok(())
2490    }
2491
2492    /// Shared capture tail: capture the FIRST kernel-class segment, build the session.
2493    #[allow(clippy::too_many_arguments)]
2494    fn graph_session_capture(
2495        &self,
2496        e: &Engine,
2497        mut cache: Cache,
2498        mut gs: GraphDecodeState,
2499        embd_gpu_owned: CudaSlice<u8>,
2500        max_new: usize,
2501        qt: i32,
2502        row_bytes: usize,
2503        n_vocab: usize,
2504        mask_dev: Option<CudaSlice<u32>>,
2505        mask_words: usize,
2506    ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
2507        let embd_gpu = embd_gpu_owned;
2508        let bucket_max = cache.pos + max_new + 1;
2509        let (graph, plan, seg_end) = self.graph_capture_segment_masked(
2510            e,
2511            &mut cache,
2512            &mut gs,
2513            &embd_gpu,
2514            qt,
2515            row_bytes,
2516            n_vocab,
2517            bucket_max,
2518            mask_dev.as_ref().map(|d| (d, mask_words)),
2519        )?;
2520        let first = e.dtoh_u32_one(&gs.token_d)?;
2521        Ok((
2522            GraphSession {
2523                gs,
2524                cache,
2525                embd_gpu,
2526                graph,
2527                plan,
2528                bucket_max,
2529                seg_end,
2530                qt,
2531                row_bytes,
2532                n_vocab,
2533                mask_dev,
2534                mask_words,
2535            },
2536            first,
2537        ))
2538    }
2539
2540    /// Device-counter full-attention decode (CUDA-GRAPH-PLAN Phase 2): clone of `full_attn_decode`
2541    /// using the `_dc` KV-append (write slot from `kvl.len_d`) + `_dc` fa_decode (t_kv from `kvl.len_d`
2542    /// after inc), and the resident device rope `pos_d`. Bit-identical to `full_attn_decode` (the
2543    /// `_dc` kernels reproduce the same math; fa_decode_dc with bucket_max==t_kv reproduces the same
2544    /// n_splits/per/combine). Advances `kvl.len`/`kvl.len_d`.
2545    pub(crate) fn full_attn_decode_dc(
2546        &self,
2547        e: &Engine,
2548        fa: &FullAttnLayer,
2549        h: &CudaSlice<f32>,
2550        pos_d: &CudaSlice<i32>,
2551        cache: &mut Cache,
2552        il: usize,
2553    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2554        // eager-mirror path: advance host counters and size n_splits from the live t_kv (bit-identical
2555        // to fa_decode). The capture path uses full_attn_decode_dc_cap (fixed bucket_max, no host
2556        // advance, full-buffer K/V view).
2557        self.full_attn_decode_dc_inner(e, fa, h, None, pos_d, cache, il, None)
2558    }
2559
2560    /// PRE-QUANTIZED-INPUT dc full-attn (device-counter path). See full_attn_decode_pre. BIT-IDENTICAL.
2561    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
2562    pub(crate) fn full_attn_decode_dc_pre(
2563        &self,
2564        e: &Engine,
2565        fa: &FullAttnLayer,
2566        h: &CudaSlice<f32>,
2567        hq: &CudaSlice<i8>,
2568        hd: &CudaSlice<f32>,
2569        pos_d: &CudaSlice<i32>,
2570        cache: &mut Cache,
2571        il: usize,
2572    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2573        self.full_attn_decode_dc_inner(e, fa, h, Some((hq, hd)), pos_d, cache, il, None)
2574    }
2575
2576    /// PRE-QUANTIZED-INPUT CAPTURE dc full-attn (graph path, fixed bucket_max). BIT-IDENTICAL.
2577    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
2578    pub(crate) fn full_attn_decode_dc_cap_pre(
2579        &self,
2580        e: &Engine,
2581        fa: &FullAttnLayer,
2582        h: &CudaSlice<f32>,
2583        hq: &CudaSlice<i8>,
2584        hd: &CudaSlice<f32>,
2585        pos_d: &CudaSlice<i32>,
2586        cache: &mut Cache,
2587        il: usize,
2588        bucket_max: usize,
2589    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2590        self.full_attn_decode_dc_inner(e, fa, h, Some((hq, hd)), pos_d, cache, il, Some(bucket_max))
2591    }
2592
2593    /// CAPTURE variant of `full_attn_decode_dc` (CUDA-GRAPH-PLAN Phase 3). `bucket_max` sizes the
2594    /// fa_decode_dc grid (n_splits) at capture time; the kernel reads the ACTUAL t_kv from the device
2595    /// counter `kvl.len_d`. Does NOT advance the host `kvl.len` (only the DEVICE counter via inc_seqlen,
2596    /// which is captured and replays each launch). Views the FULL K/V cache buffer so the kernel may
2597    /// safely read up to any t_kv within the bucket on replay. Bit-identical to eager when
2598    /// `bucket_max` yields the same n_splits as eager for the replayed t_kv (the bucket-key contract).
2599    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
2600    pub(crate) fn full_attn_decode_dc_cap(
2601        &self,
2602        e: &Engine,
2603        fa: &FullAttnLayer,
2604        h: &CudaSlice<f32>,
2605        pos_d: &CudaSlice<i32>,
2606        cache: &mut Cache,
2607        il: usize,
2608        bucket_max: usize,
2609    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2610        self.full_attn_decode_dc_inner(e, fa, h, None, pos_d, cache, il, Some(bucket_max))
2611    }
2612
2613    #[allow(clippy::too_many_arguments)]
2614    // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
2615    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
2616    fn full_attn_decode_dc_inner(
2617        &self,
2618        e: &Engine,
2619        fa: &FullAttnLayer,
2620        h: &CudaSlice<f32>,
2621        pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2622        pos_d: &CudaSlice<i32>,
2623        cache: &mut Cache,
2624        il: usize,
2625        cap_bucket_max: Option<usize>,
2626    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2627        // step35 has no device-counter twin yet: the `_dc` family needs a windowed dc fa_decode
2628        // (SWA layers read a token-OFFSET view, which the dc kernels' len_d-derived t_kv cannot
2629        // express) plus a per-layer-n_head capture. Refuse loudly instead of silently running
2630        // the generic geometry. The eager arm (`step35_decode_attn`) is the supported decode.
2631        if self.uses_sliding_gated_moe_program() {
2632            return Err(
2633                "step35 has no device-counter/graph decode arm (SWA needs an offset KV \
2634                        view the dc kernels cannot express) — use the eager decode"
2635                    .into(),
2636            );
2637        }
2638        let cfg = &self.cfg;
2639        let geometry = cfg.full_attention_geometry_at(il as u32);
2640        let n_head = geometry.n_head as usize;
2641        let n_head_kv = geometry.n_head_kv as usize;
2642        let head_dim = geometry.head_dim_k as usize;
2643        let eps = cfg.rms_eps;
2644        let scale = geometry.attention_scale();
2645
2646        let n_embd = cfg.n_embd as usize;
2647        // Q8 TRUNK-FUSION (2026-07-05): wq+wk+wv share input h — on the 35B every full-attn
2648        // projection is Q8_0, so ONE fused3 launch (block-offset split, out_f 8192/512/512)
2649        // replaces three launch-latency-class m=1 launches. BIT-IDENTICAL per (tensor,row) to
2650        // the three matmul_pre MMVQ dispatches (same kernel body). MEMRA_Q8_DUAL=0 rollback.
2651        let qkv_fused = |e: &Engine,
2652                         hq: &CudaSlice<i8>,
2653                         hd: &CudaSlice<f32>|
2654         -> Result<
2655            (CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>),
2656            Box<dyn std::error::Error>,
2657        > {
2658            if let Some((qf, k, v)) = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)? {
2659                return Ok((qf, k, v));
2660            }
2661            Ok((
2662                e.matmul_pre(&fa.wq, hq, hd, h, 1)?,
2663                e.matmul_pre(&fa.wk, hq, hd, h, 1)?,
2664                e.matmul_pre(&fa.wv, hq, hd, h, 1)?,
2665            ))
2666        };
2667        let (qf, mut k, v) = if let Some(mut qkv) = self.full_attn_tp_qkv(e, fa, h, 1)? {
2668            let v = qkv.pop().ok_or("full-attention TP QKV omitted V")?;
2669            let k = qkv.pop().ok_or("full-attention TP QKV omitted K")?;
2670            let q = qkv.pop().ok_or("full-attention TP QKV omitted Q")?;
2671            if !qkv.is_empty() {
2672                return Err("full-attention TP QKV returned extra projections".into());
2673            }
2674            (q, k, v)
2675        } else if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
2676            match pre_q {
2677                Some((hq, hd)) => qkv_fused(e, hq, hd)?,
2678                None => {
2679                    let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
2680                    qkv_fused(e, &hq, &hd)?
2681                }
2682            }
2683        } else {
2684            (
2685                e.matmul(&fa.wq, h, 1)?,
2686                e.matmul(&fa.wk, h, 1)?,
2687                e.matmul(&fa.wv, h, 1)?,
2688            )
2689        };
2690        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2691        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
2692        let (mut q, gate) = if gated {
2693            let mut q = e.uninit(n_head * head_dim)?;
2694            let mut gate = e.uninit(n_head * head_dim)?;
2695            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
2696            (q, Some(gate))
2697        } else {
2698            (qf, None)
2699        };
2700
2701        let mut qn = e.uninit(n_head * head_dim)?;
2702        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
2703        q = qn;
2704        let mut kn = e.uninit(n_head_kv * head_dim)?;
2705        e.rms_norm(
2706            &k,
2707            fa.k_norm.float_data(),
2708            &mut kn,
2709            head_dim,
2710            n_head_kv,
2711            eps,
2712        )?;
2713        k = kn;
2714        let rope_dims = geometry.n_rot as usize;
2715        // rope pos from the resident device counter (no per-step host upload).
2716        e.rope_neox(
2717            &mut q,
2718            pos_d,
2719            head_dim,
2720            rope_dims,
2721            n_head,
2722            1,
2723            geometry.rope_base,
2724            1.0,
2725        )?;
2726        e.rope_neox(
2727            &mut k,
2728            pos_d,
2729            head_dim,
2730            rope_dims,
2731            n_head_kv,
2732            1,
2733            geometry.rope_base,
2734            1.0,
2735        )?;
2736
2737        let kvl = cache.kv[il].as_mut().unwrap();
2738        // (1) append at the device write slot kvl.len_d (== old len).
2739        e.append_kv_quantized_dc(
2740            &k,
2741            &v,
2742            &mut kvl.k,
2743            &mut kvl.v,
2744            &kvl.len_d,
2745            kvl.kv_dim_k,
2746            kvl.kv_dim_v,
2747            kvl.k_tok_bytes,
2748            kvl.v_tok_bytes,
2749            false,
2750        )?;
2751        // (2) advance the device counter: kvl.len_d now holds new len == t_kv.
2752        e.inc_seqlen(&mut kvl.len_d)?;
2753        // n_splits sizing + K/V view extent:
2754        //  - eager path (cap_bucket_max==None): advance host len; size from live t_kv == bit-identical
2755        //    to fa_decode; view exactly t_kv*tok_bytes.
2756        //  - capture path (Some(bucket_max)): DO NOT touch host len (replay advances only the device
2757        //    counter); size n_splits from bucket_max; view the FULL cache buffer so any in-bucket t_kv
2758        //    is in range on replay.
2759        let (bucket_max, k_view, v_view) = match cap_bucket_max {
2760            None => {
2761                kvl.len += 1;
2762                let t_kv = kvl.len;
2763                (
2764                    t_kv,
2765                    e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes),
2766                    e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes),
2767                )
2768            }
2769            Some(bm) => (
2770                bm,
2771                e.view_u8(&kvl.k, kvl.k.len()),
2772                e.view_u8(&kvl.v, kvl.v.len()),
2773            ),
2774        };
2775        let (ktb, vtb) = (kvl.k_tok_bytes, kvl.v_tok_bytes);
2776        let mut attn = e.uninit(n_head * head_dim)?;
2777        if std::env::var("MEMRA_NOFA").is_ok() {
2778            return Err(
2779                "MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV cache; \
2780                        unset MEMRA_NOFA to use fa_decode_dc"
2781                    .into(),
2782            );
2783        }
2784        // (3) fa_decode reads t_kv from kvl.len_d; bucket_max yields the eager n_splits -> bit-identical.
2785        e.fa_decode_dc(
2786            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kvl.len_d, bucket_max,
2787            scale, ktb, vtb, false,
2788        )?;
2789
2790        let attn_g = match &gate {
2791            Some(gate) => {
2792                let mut gsig = e.uninit(n_head * head_dim)?;
2793                e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2794                let mut ag = e.uninit(n_head * head_dim)?;
2795                e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2796                ag
2797            }
2798            None => attn,
2799        };
2800        match self.full_attn_tp_o(e, fa, &attn_g, 1)? {
2801            Some(output) => Ok(output),
2802            None => Ok(e.matmul(&fa.wo, &attn_g, 1)?),
2803        }
2804    }
2805
2806    /// Greedy generation: prime with prompt tokens (decode them in sequence to build state),
2807    /// then generate `max_new` tokens. Returns the generated token ids. (Back-compat: greedy,
2808    /// no EOS/stop — used by the decode==prefill validation gate. New code uses `generate_with`.)
2809    pub fn generate(
2810        &self,
2811        e: &Engine,
2812        prompt: &[u32],
2813        max_new: usize,
2814    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
2815        let max_ctx = prompt.len() + max_new + 8;
2816        let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
2817        let mut last_logits = Vec::new();
2818        // prime: BATCHED cache prime (prime_cache — the prefill-throughput path, the measured #1
2819        // e2e gap: tokenwise primed at ~102/38 tok/s vs ~2000-5900 tok/s batched). Prompts below
2820        // PRIME_MIN_T, MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the
2821        // tokenwise loop. Frozen mixed residency would otherwise transiently stage the missing
2822        // expert bank through the GPU on every prompt replay.
2823        let t_prime = std::time::Instant::now();
2824        let batched_prime = prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
2825            && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
2826            && !e.frozen_cpu_experts_prefer_tokenwise_prime();
2827        if batched_prime {
2828            let (l, _h_seed, _hiddens) = self.prime_cache(e, prompt, &mut cache, 0)?;
2829            last_logits = l;
2830        } else {
2831            for &tok in prompt {
2832                last_logits = self.decode_step(e, tok, &mut cache)?;
2833            }
2834        }
2835        e.stream().synchronize()?;
2836        // Harness timing contract: prime wall time published for gen-only throughput math
2837        // (bench binaries read this right after the call; subtraction-from-total breaks down
2838        // when prime >> gen — measured ±80% error at 6k-token prompts).
2839        crate::PRIME_NANOS.store(
2840            t_prime.elapsed().as_nanos() as u64,
2841            std::sync::atomic::Ordering::Relaxed,
2842        );
2843        let mut out = Vec::with_capacity(max_new);
2844        if self.uses_gemma_program()
2845            && let Some(embd_gpu) = self.embd_gpu_try(e)
2846        {
2847            // Graph serving probed FLAT vs this dc loop (2026-07-12, 1.7k N=2: 174.6/174.2 vs
2848            // 174.5/174.3) — the GRAPH-GATE's +2.5% is over the plain-eager loop, and the dc
2849            // arc already banked that; the gate (IDENTICAL at every ctx since the wkv
2850            // capture-arm fix) stays as the correctness harness.
2851            // DEVICE-COUNTER greedy loop (the dc arc): stream-identical to eager (DC-GATE).
2852            // E4B rides its own dc step (same trunk fns as its eager chain).
2853            let n_vocab = self.output.out_features();
2854            let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2855            for kvl in cache.kv.iter_mut().flatten() {
2856                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2857            }
2858            let e4b = self.is_gemma4_e4b();
2859            let mut token_d = e.stream().clone_htod(&[argmax(&last_logits) as u32])?;
2860            let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2861            // E4B GRAPH-EXEC-UPDATE SERVING: one capture at bucket=win, per-token fa
2862            // geometry retune, replay. The 2026-07-12 park ("flat 173.5, stream 64/64") did
2863            // NOT reproduce — the capture warmups are real self-feeding steps and the old
2864            // door dropped their 2 tokens (E4B-GRAPH-GATE 3/64). Snapshot/rollback (the 26B
2865            // graph-loop pattern) fixes the stream; the exec-update kills the bucket-split
2866            // tax (42 fa launches at 64 splits vs eager's ~ceil(t_kv/8)).
2867            // DEFAULT: budget-gated ON (2026-07-13 valid-window A/B: steady-state replay
2868            // beats eager but the one-time capture ~30ms crosses over near 200 tokens —
2869            // 128tok −1.3%, 400tok +0.9%). MEMRA_E4B_GRAPH=1 forces, =0 kills.
2870            let win = self
2871                .cfg
2872                .gemma4
2873                .as_ref()
2874                .map(|g| g.sliding_window as usize)
2875                .unwrap_or(0);
2876            let e4b_graph = match std::env::var("MEMRA_E4B_GRAPH").as_deref() {
2877                Ok("1") => true,
2878                Ok("0") => false,
2879                _ => max_new >= 256,
2880            };
2881            if e4b && cache.pos + max_new + 2 < win && e4b_graph {
2882                self.gemma4_e4b_graph_exec_loop(
2883                    e,
2884                    &mut cache,
2885                    &mut token_d,
2886                    &mut pos_d,
2887                    embd_gpu,
2888                    qt,
2889                    rb,
2890                    n_vocab,
2891                    win,
2892                    max_new,
2893                    usize::MAX,
2894                    |tok| {
2895                        out.push(tok);
2896                        None
2897                    },
2898                )?;
2899                return Ok(out);
2900            }
2901            for _ in 0..max_new {
2902                out.push(e.dtoh_u32(&token_d)?[0]);
2903                token_d = if e4b {
2904                    self.gemma4_e4b_decode_step_dc(
2905                        e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
2906                    )?
2907                } else {
2908                    self.gemma4_decode_step_dc(
2909                        e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab, None,
2910                    )?
2911                };
2912            }
2913            return Ok(out);
2914        }
2915        // QWEN DC-EAGER route (2026-07-15, MEMRA_QWEN_DC=0 seam — mirror of generate_with's
2916        // serving loop; see the note there. The graph route probed −11% first.)
2917        // step35 is EXCLUDED: this route calls `decode_step_dc`, whose full-attn arm refuses
2918        // step35 by design (SWA layers need a token-OFFSET KV view the dc kernels' len_d-derived
2919        // t_kv cannot express). Without this gate the door opens for any greedy model and the
2920        // refusal surfaces as a user-visible generate() error — the first PP-2 boot of
2921        // Step-3.7-Flash died exactly there, AFTER a clean load and an argmax MATCH.
2922        static QWEN_DC2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2923        let qwen_dc =
2924            *QWEN_DC2.get_or_init(|| std::env::var("MEMRA_QWEN_DC").as_deref() != Ok("0"));
2925        if qwen_dc
2926            && max_new > 0
2927            && !self.uses_sliding_gated_moe_program()
2928            && let Some(embd_gpu) = self.embd_gpu_try(e)
2929        {
2930            let n_vocab = self.output.out_features();
2931            let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2932            for kvl in cache.kv.iter_mut().flatten() {
2933                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2934            }
2935            let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2936            let mut token_d = e.stream().clone_htod(&[argmax(&last_logits) as u32])?;
2937            for _ in 0..max_new {
2938                out.push(e.dtoh_u32(&token_d)?[0]);
2939                token_d = self.decode_step_dc(
2940                    e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
2941                )?;
2942            }
2943            return Ok(out);
2944        }
2945        for _ in 0..max_new {
2946            let next = argmax(&last_logits) as u32;
2947            out.push(next);
2948            last_logits = self.decode_step(e, next, &mut cache)?;
2949        }
2950        Ok(out)
2951    }
2952
2953    /// E4B whole-token GRAPH-EXEC-UPDATE serving loop (shared by `generate` and
2954    /// `generate_with`): capture ONE self-feeding dcg step at bucket=`win`, then per token
2955    /// retune the fa nodes' split geometry to the live eager counts
2956    /// (`graph_update::fa_apply`) before replaying the instantiated exec.
2957    ///
2958    /// The capture's two warmup runs are REAL executions (self-feeding: they consume two
2959    /// tokens and advance KV/counters) — snapshot/rollback around the capture (the 26B
2960    /// graph-loop pattern) restores device+host state, or the stream drops those tokens
2961    /// (E4B-GRAPH-GATE 3/64 break, 2026-07-12). `emit` sees each token BEFORE its
2962    /// successor's replay; returning `Some(reason)` stops the loop. Caller owns the
2963    /// under-window gate (`cache.pos + budget + 2 < win`).
2964    #[allow(clippy::too_many_arguments)]
2965    fn gemma4_e4b_graph_exec_loop(
2966        &self,
2967        e: &Engine,
2968        cache: &mut Cache,
2969        token_d: &mut CudaSlice<u32>,
2970        pos_d: &mut CudaSlice<i32>,
2971        embd_gpu: &CudaSlice<u8>,
2972        qt: i32,
2973        rb: usize,
2974        n_vocab: usize,
2975        win: usize,
2976        budget: usize,
2977        ctx_cap: usize,
2978        mut emit: impl FnMut(u32) -> Option<StopReason>,
2979    ) -> Result<StopReason, Box<dyn std::error::Error>> {
2980        // BISECT ARM (MEMRA_E4B_DCG_EAGER=1): run the dcg step EAGERLY per token at the
2981        // exact live bucket — no capture/replay/exec-update. Separates "the dc-bucket path
2982        // diverges from dc-eager numerically" from "the replay/update mechanism is wrong".
2983        if let Ok(m) = std::env::var("MEMRA_E4B_DCG_EAGER") {
2984            // =1: exact live bucket per token; =2: the capture's fixed win bucket.
2985            let mut reason = StopReason::MaxNew;
2986            for _ in 0..budget {
2987                let tok = e.dtoh_u32_one(token_d)?;
2988                if let Some(r) = emit(tok) {
2989                    reason = r;
2990                    break;
2991                }
2992                if cache.pos >= ctx_cap {
2993                    reason = StopReason::ContextFull;
2994                    break;
2995                }
2996                let b = if m == "2" { win } else { cache.pos + 1 };
2997                self.gemma4_e4b_decode_step_dcg(
2998                    e, token_d, pos_d, embd_gpu, qt, rb, cache, n_vocab, b,
2999                )?;
3000                cache.pos += 1;
3001                for kvl in cache.kv.iter_mut().flatten() {
3002                    kvl.len += 1;
3003                }
3004            }
3005            return Ok(reason);
3006        }
3007        // snapshot device+host state (the 2 capture-warmup runs must leave no residue).
3008        let snap = cache.snapshot(e)?;
3009        let pos_save = e.dtoh_i32_one(pos_d)?;
3010        let len_save: Vec<Option<i32>> = cache
3011            .kv
3012            .iter()
3013            .map(|k| k.as_ref().map(|kvl| e.dtoh_i32_one(&kvl.len_d).unwrap()))
3014            .collect();
3015        let tok_save = e.dtoh_u32_one(token_d)?;
3016        let (graph, keeper) = e.capture_graph_retained(|e| {
3017            self.gemma4_e4b_decode_step_dcg(
3018                e, token_d, pos_d, embd_gpu, qt, rb, cache, n_vocab, win,
3019            )
3020        })?;
3021        cache.rollback(e, &snap, 0)?;
3022        e.set_i32_one(pos_d, pos_save)?;
3023        for (il, ls) in len_save.iter().enumerate() {
3024            if let (Some(kvl), Some(v)) = (cache.kv[il].as_mut(), ls) {
3025                e.set_i32_one(&mut kvl.len_d, *v)?;
3026            }
3027        }
3028        e.set_u32_one(token_d, tok_save)?;
3029        let mut plan = crate::graph_update::fa_plan(&graph)?;
3030        if std::env::var("MEMRA_GRAPH_NODES_DUMP").as_deref() == Ok("1") {
3031            let nodes = crate::graph_update::kernel_nodes(&graph)?;
3032            let mut counts: std::collections::BTreeMap<String, (usize, (u32, u32, u32))> =
3033                std::collections::BTreeMap::new();
3034            for n in &nodes {
3035                counts
3036                    .entry(n.name.clone())
3037                    .or_insert((0, (n.params.gridDimX, n.params.gridDimY, n.params.gridDimZ)))
3038                    .0 += 1;
3039            }
3040            eprintln!(
3041                "[graph-nodes] {} kernel nodes, {} fa update units (bucket={win})",
3042                nodes.len(),
3043                plan.len()
3044            );
3045            for (name, (c, grid)) in &counts {
3046                eprintln!("[graph-nodes]   {c:4}x {name} grid={grid:?}");
3047            }
3048        }
3049        let mut reason = StopReason::MaxNew;
3050        let timing = std::env::var("MEMRA_E4B_GRAPH_TIMING").as_deref() == Ok("1");
3051        let (mut t_dtoh, mut t_apply, mut t_launch) = (
3052            std::time::Duration::ZERO,
3053            std::time::Duration::ZERO,
3054            std::time::Duration::ZERO,
3055        );
3056        for _ in 0..budget {
3057            let t0 = std::time::Instant::now();
3058            let tok = e.dtoh_u32_one(token_d)?;
3059            let t1 = std::time::Instant::now();
3060            if let Some(r) = emit(tok) {
3061                reason = r;
3062                break;
3063            }
3064            if cache.pos >= ctx_cap {
3065                reason = StopReason::ContextFull;
3066                break;
3067            }
3068            // live t_kv AFTER this replay's in-graph append = pos + 1.
3069            crate::graph_update::fa_apply(&graph, &mut plan, cache.pos + 1, crate::fa_split_keys)?;
3070            let t2 = std::time::Instant::now();
3071            graph.launch()?;
3072            if timing {
3073                let t3 = std::time::Instant::now();
3074                t_dtoh += t1 - t0;
3075                t_apply += t2 - t1;
3076                t_launch += t3 - t2;
3077            }
3078            cache.pos += 1;
3079            for kvl in cache.kv.iter_mut().flatten() {
3080                kvl.len += 1;
3081            }
3082        }
3083        if timing {
3084            eprintln!(
3085                "[e4b-graph timing] dtoh(sync-wait) {:?} apply {:?} launch {:?}",
3086                t_dtoh, t_apply, t_launch
3087            );
3088        }
3089        drop(keeper); // capture-retained transients must outlive every replay
3090        Ok(reason)
3091    }
3092
3093    /// The reusable serving generation API (BASE-3). Primes the prompt, then samples up to
3094    /// `params.max_new` tokens, stopping on EOS, any stop-token, or the context-length guard.
3095    /// Calls `on_token(id)` after each emitted token (for streaming; return `false` to stop early).
3096    /// Returns `GenOutput { tokens, stop_reason }`. Does NOT detokenize — the caller (which owns
3097    /// the tokenizer) handles text + stop-STRING matching on the detokenized tail.
3098    pub fn generate_with<F: FnMut(u32) -> bool>(
3099        &self,
3100        e: &Engine,
3101        prompt: &[u32],
3102        params: &GenParams,
3103        sampler: &mut crate::sampler::Sampler,
3104        mut on_token: F,
3105    ) -> Result<GenOutput, Box<dyn std::error::Error>> {
3106        // Context guard: prompt + generated must fit max_ctx (caller-supplied or model default).
3107        let ctx_cap = params.max_ctx.unwrap_or(prompt.len() + params.max_new + 8);
3108        if prompt.len() >= ctx_cap {
3109            return Ok(GenOutput {
3110                tokens: Vec::new(),
3111                stop_reason: StopReason::ContextFull,
3112            });
3113        }
3114        let room = ctx_cap - prompt.len();
3115        let budget = params.max_new.min(room);
3116
3117        let mut cache = Cache::new(e, &self.cfg, ctx_cap)?;
3118        let mut last_logits = Vec::new();
3119        // BATCHED PRIME (2026-07-06 fix — generate_with was still tokenwise! run-gen's "decode"
3120        // numbers folded a ~40-100 tok/s tokenwise prime into the rate) + PRIME_NANOS contract.
3121        // Frozen Hy3 CPU/GPU expert serving is the deliberate exception: its batched MoE path
3122        // bypasses the CPU tier and rereads the spilled expert bank.
3123        let t_prime = std::time::Instant::now();
3124        let batched = prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
3125            && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
3126            && !e.frozen_cpu_experts_prefer_tokenwise_prime();
3127        if batched {
3128            let (l, _h, _x) = self.prime_cache(e, prompt, &mut cache, 0)?;
3129            last_logits = l;
3130            for &tok in prompt {
3131                sampler.accept(tok);
3132            }
3133        } else {
3134            for &tok in prompt {
3135                last_logits = self.decode_step(e, tok, &mut cache)?;
3136                sampler.accept(tok);
3137            }
3138        }
3139        e.stream().synchronize()?;
3140        crate::PRIME_NANOS.store(
3141            t_prime.elapsed().as_nanos() as u64,
3142            std::sync::atomic::Ordering::Relaxed,
3143        );
3144        let mut out = Vec::with_capacity(budget);
3145        let mut reason = StopReason::MaxNew;
3146        // gemma4 DEVICE-COUNTER greedy serving loop (the dc arc): token/pos/kv-lens live in
3147        // device counters, argmax on device — host sees 4B/token. Stream-identical to the
3148        // eager chain (DC-GATE). Penalties/temp fall through to the host-logits loop.
3149        if self.uses_gemma_program()
3150            && sampler.is_greedy()
3151            && sampler.penalty_last_n() == 0
3152            && let Some(embd_gpu) = self.embd_gpu_try(e)
3153        {
3154            let n_vocab = self.output.out_features();
3155            let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
3156            for kvl in cache.kv.iter_mut().flatten() {
3157                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
3158            }
3159            let first = crate::forward::argmax(&last_logits) as u32;
3160            let e4b = self.is_gemma4_e4b();
3161            let mut token_d = e.stream().clone_htod(&[first])?;
3162            let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
3163            // E4B GRAPH-EXEC-UPDATE serving door (under-window regime) — mirror of the
3164            // `generate` door incl the budget-gated default; run-gen/serving measure here.
3165            let win = self
3166                .cfg
3167                .gemma4
3168                .as_ref()
3169                .map(|g| g.sliding_window as usize)
3170                .unwrap_or(0);
3171            let e4b_graph = match std::env::var("MEMRA_E4B_GRAPH").as_deref() {
3172                Ok("1") => true,
3173                Ok("0") => false,
3174                _ => budget >= 256,
3175            };
3176            if e4b && cache.pos + budget + 2 < win && e4b_graph {
3177                let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
3178                let reason = self.gemma4_e4b_graph_exec_loop(
3179                    e,
3180                    &mut cache,
3181                    &mut token_d,
3182                    &mut pos_d,
3183                    embd_gpu,
3184                    qt,
3185                    rb,
3186                    n_vocab,
3187                    win,
3188                    budget,
3189                    ctx_cap,
3190                    |tok| {
3191                        sampler_cell.accept(tok);
3192                        out_cell.push(tok);
3193                        if params.eos.contains(&tok) {
3194                            return Some(StopReason::Eos);
3195                        }
3196                        if !on_token(tok) {
3197                            return Some(StopReason::Callback);
3198                        }
3199                        None
3200                    },
3201                )?;
3202                return Ok(GenOutput {
3203                    tokens: out,
3204                    stop_reason: reason,
3205                });
3206            }
3207            let mut next = first;
3208            for _ in 0..budget {
3209                sampler.accept(next);
3210                out.push(next);
3211                if params.eos.contains(&next) {
3212                    reason = StopReason::Eos;
3213                    break;
3214                }
3215                if !on_token(next) {
3216                    reason = StopReason::Callback;
3217                    break;
3218                }
3219                if cache.pos >= ctx_cap {
3220                    reason = StopReason::ContextFull;
3221                    break;
3222                }
3223                token_d = if e4b {
3224                    self.gemma4_e4b_decode_step_dc(
3225                        e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
3226                    )?
3227                } else {
3228                    self.gemma4_decode_step_dc(
3229                        e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab, None,
3230                    )?
3231                };
3232                next = e.dtoh_u32(&token_d)?[0];
3233            }
3234            return Ok(GenOutput {
3235                tokens: out,
3236                stop_reason: reason,
3237            });
3238        }
3239        // QWEN DC-EAGER serving loop (2026-07-15, MEMRA_QWEN_DC=0 seam — the gemma dc-arc
3240        // pattern): the eager tail dtoh'd the FULL VOCAB logits + host-argmax'd every
3241        // token (the duty map's 10.3%-of-wall gap at 13% DRAM duty). decode_step_dc keeps
3242        // the token id + argmax device-resident — 4B/token host traffic, same tuned eager
3243        // kernels. Greedy + no-penalty only (sampling needs host logits).
3244        // (The CUDA-graph route was probed first and read −11%: the replay's dc-fa family
3245        // + capture rungs lag the tuned eager lanes; jsonl 2026-07-15.)
3246        // step35 is EXCLUDED here for the same reason as the `generate` mirror above: every route
3247        // inside this door (`decode_step_dc` and the `graph_decode_loop` capture) reaches
3248        // `full_attn_decode_dc_inner`, which refuses step35 because its SWA layers read a
3249        // token-OFFSET KV view the dc kernels cannot express. step35 takes the host-logits eager
3250        // loop at the bottom of this function (`decode_step` -> `step35_decode_attn`), which is
3251        // the supported decode for this arch. Removing this gate requires a windowed dc fa_decode
3252        // plus a per-layer-n_head capture, not a flag.
3253        static QWEN_DC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3254        let qwen_dc = *QWEN_DC.get_or_init(|| std::env::var("MEMRA_QWEN_DC").as_deref() != Ok("0"));
3255        if qwen_dc
3256            && sampler.is_greedy()
3257            && sampler.penalty_last_n() == 0
3258            && budget > 0
3259            && !self.uses_sliding_gated_moe_program()
3260            && let Some(embd_gpu) = self.embd_gpu_try(e)
3261        {
3262            let n_vocab = self.output.out_features();
3263            let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
3264            for kvl in cache.kv.iter_mut().flatten() {
3265                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
3266            }
3267            let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
3268            let mut token_d = e
3269                .stream()
3270                .clone_htod(&[crate::forward::argmax(&last_logits) as u32])?;
3271            // HYBRID GRAPH DOOR (round 35): graph_decode_loop over the batched-prime
3272            // cache — the E4B graph-exec door's hybrid mirror. Counters (pos_d/token_d/
3273            // len_d) synced above; event tracking is engine-default-OFF so capture over
3274            // these buffers is legal. PROMOTED default-ON at budget >= 256 (the E4B
3275            // door's amortization rule): official-shape A/B interleaved x5 = eager 190.3
3276            // -> graph 220.7 tok/s (+16.0%, 5/5, spread ±0.1); 128-tok stream IDENTICAL;
3277            // graph-decode-gate 256 steps x 16 buckets BIT-IDENTICAL. This REFUTES the
3278            // 2026-07-15 "-11%" qwen-graph verdict — it predated the exec-update rework
3279            // and the 07-26 FA family (stale-verdict law, round 35). =0 reverts.
3280            // Default ON at budget >= 256 on BOTH arches (unified-merge resolution,
3281            // 2026-07-30): main shipped this door budget-keyed on sm_120a (52222ddd,
3282            // E4B graph door) and every 5090 board row since measured with it; the H100
3283            // lane measured +16% x5. The branch-era arch-gate (79395a3e) cited the
3284            // stale 2026-07-15 "-11%" verdict, which predates main's promotion — the
3285            // rig-divergence law protects main's SHIPPED default, so the gate came off.
3286            // MEMRA_GEN_GRAPH=1 opts in anywhere; =0 reverts anywhere.
3287            //
3288            // KEY LOWERED 256 -> 48 (q27 deep dive, 2026-08-05, pro6000wk-runpod-community).
3289            // The 256 key was set by the E4B amortization rule, never by a measured crossover,
3290            // so every <=128-token generation — including the whole published board, which runs
3291            // --max-tokens 128 — was silently EAGER. Swept the actual crossover on TWO models
3292            // (the key is a cross-model default, so one artifact is not enough), interleaved
3293            // arms with the order alternated per rep, N=3, all runs argmax MATCH:
3294            //   Qwen3.6-27B-Q8_0     : n=16 -7.47% | n=32 -1.35% | n=48 +0.90% | n=64 +1.93%
3295            //                          n=128 +3.80% | n=512 +5.50%
3296            //   Qwen3.6-27B-NVFP4-MTP: n=16 -15.27% | n=32 +0.22% | n=48 +3.45%
3297            //                          n=64 +5.09% | n=128 +7.72%
3298            // Both models: clearly negative at 16, no reliable gain at 32, positive from 48 up,
3299            // monotone in budget from 48 on. 48 is the first budget where BOTH are positive, so
3300            // it is the key — the capture cost needs ~32 steps to amortize, not ~256. The n=32
3301            // nvfp4 cell is NOISY, not flat (graph arm 79.02/78.91/77.09, spread 1.93 vs an
3302            // eager spread of 0.04): it is not evidence of a win, and it is why the key sits at
3303            // 48 rather than 32. Exactness at the new key:
3304            // graph-decode-gate 256 steps BIT-IDENTICAL (buckets=16, captures=2),
3305            // graph-session-gate 96 tokens PASS, kernel-check ALL GREEN, run-spec K=1..8
3306            // self-consistency PASS. Board caveat: community board, RELATIVE deltas only.
3307            //
3308            // SM-GATED (5090-arbiter gate, 2026-08-05, research/q27-deepdive-20260805/local5090/):
3309            // the 48 key does NOT transfer to the 82-SM local rig. Same A/B protocol there
3310            // (tg128 d512, N=3 interleaved, order alternated, warmup discarded): q27-NVFP4-MTP
3311            // graph arm at n=128 = -1.61% (eager 45.86 / graph 45.12 median, 3/3 pairs lose),
3312            // and the crossover sweep stays negative through n=256 (-1.07%) and n=512 (-0.59%)
3313            // — on few-SM silicon the replay's fixed kernel forms lag the tuned eager lanes and
3314            // the launch-gap tax the graph amortizes is proportionally smaller. Key on SM count
3315            // (the fa_split_keys big_rig pattern, lib.rs fa_sm_count), threshold 180: the 48
3316            // crossover is MEASURED only at 188 SM (PRO 6000) and refuted at 82 SM; the 132-SM
3317            // H100 board and the 170-SM desktop 5090 are UNMEASURED at sub-256 budgets, so they
3318            // keep the shipped 256 key their board rows were measured with (rig-divergence +
3319            // stale-verdict laws). Widening the gate below 180 requires an on-box crossover
3320            // sweep on that silicon, not an inference from this comment.
3321            let big_rig = e.sm_count() >= 180;
3322            let gen_graph = match std::env::var("MEMRA_GEN_GRAPH").as_deref() {
3323                Ok("1") => true,
3324                Ok("0") => false,
3325                _ => budget >= if big_rig { 48 } else { 256 },
3326            };
3327            // SLRU expert cache is capture-ILLEGAL: a cache miss drains/H2Ds on the compute
3328            // stream mid-decode, which CUDA forbids while capturing (Ornith-35B Q4_K_M on the
3329            // 24GB rig died with CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED, 2026-08-01 — any MoE
3330            // model whose experts overflow the residency budget hit this at budget >= 256).
3331            // The door only opens with every MoE layer's experts device-resident; =1 cannot
3332            // legalize a capture, so this closes the forced door too.
3333            let moe_resident = self.layers.iter().all(|l| match &l.ffn {
3334                crate::hybrid::Ffn::Moe(m) => m.dev_exps.is_some(),
3335                _ => true,
3336            });
3337            if gen_graph && !moe_resident {
3338                static NOTICE: std::sync::Once = std::sync::Once::new();
3339                NOTICE.call_once(|| {
3340                    eprintln!(
3341                        "[gen-graph] door CLOSED: MoE experts on the SLRU cache path \
3342                     (capture-illegal) — eager decode"
3343                    )
3344                });
3345            }
3346            if gen_graph && moe_resident && budget > 0 {
3347                let head_dim = self.cfg.head_dim_k as usize;
3348                let mut gs = GraphDecodeState::new(e)?;
3349                gs.pos_d = pos_d;
3350                gs.token_d = token_d;
3351                let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
3352                let reason = self.graph_decode_loop(
3353                    e,
3354                    &mut gs,
3355                    &mut cache,
3356                    embd_gpu,
3357                    qt,
3358                    rb,
3359                    head_dim,
3360                    budget,
3361                    |tok| {
3362                        sampler_cell.accept(tok);
3363                        out_cell.push(tok);
3364                        if params.eos.contains(&tok) {
3365                            return Some(StopReason::Eos);
3366                        }
3367                        if !on_token(tok) {
3368                            return Some(StopReason::Callback);
3369                        }
3370                        None
3371                    },
3372                )?;
3373                return Ok(GenOutput {
3374                    tokens: out,
3375                    stop_reason: reason,
3376                });
3377            }
3378            let mut next = e.dtoh_u32(&token_d)?[0];
3379            for _ in 0..budget {
3380                sampler.accept(next);
3381                out.push(next);
3382                if params.eos.contains(&next) {
3383                    reason = StopReason::Eos;
3384                    break;
3385                }
3386                if !on_token(next) {
3387                    reason = StopReason::Callback;
3388                    break;
3389                }
3390                if cache.pos >= ctx_cap {
3391                    reason = StopReason::ContextFull;
3392                    break;
3393                }
3394                token_d = self.decode_step_dc(
3395                    e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
3396                )?;
3397                next = e.dtoh_u32(&token_d)?[0];
3398            }
3399            return Ok(GenOutput {
3400                tokens: out,
3401                stop_reason: reason,
3402            });
3403        }
3404        for _ in 0..budget {
3405            let next = sampler.sample(&last_logits);
3406            sampler.accept(next);
3407            out.push(next);
3408            if params.eos.contains(&next) {
3409                reason = StopReason::Eos;
3410                break;
3411            }
3412            if !on_token(next) {
3413                reason = StopReason::Callback;
3414                break;
3415            }
3416            if cache.pos >= ctx_cap {
3417                reason = StopReason::ContextFull;
3418                break;
3419            }
3420            last_logits = self.decode_step(e, next, &mut cache)?;
3421        }
3422        Ok(GenOutput {
3423            tokens: out,
3424            stop_reason: reason,
3425        })
3426    }
3427
3428    /// Full-attention decode: project q/gate/k/v for the new token, QK-norm, RoPE at pos,
3429    /// append k,v to the layer KV cache, attend over the full [0..=pos] context.
3430    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
3431    pub(crate) fn full_attn_decode(
3432        &self,
3433        e: &Engine,
3434        fa: &FullAttnLayer,
3435        h: &CudaSlice<f32>,
3436        pos_d: &CudaSlice<i32>,
3437        pos: usize,
3438        cache: &mut Cache,
3439        il: usize,
3440    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3441        self.full_attn_decode_pre(e, fa, h, None, pos_d, pos, cache, il)
3442    }
3443
3444    /// PRE-QUANTIZED-INPUT eager full-attn (attn-input NORM-FUSION lever): caller passes the
3445    /// attn-normed activation already q8_1 `(hq,hd)` (rms_norm_q8_1) -> skips internal quantize_q8_1.
3446    /// `None` = quantize h here (the spec / non-fused path). BIT-IDENTICAL.
3447    #[allow(clippy::too_many_arguments)]
3448    // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
3449    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
3450    pub(crate) fn full_attn_decode_pre(
3451        &self,
3452        e: &Engine,
3453        fa: &FullAttnLayer,
3454        h: &CudaSlice<f32>,
3455        pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
3456        pos_d: &CudaSlice<i32>,
3457        pos: usize,
3458        cache: &mut Cache,
3459        il: usize,
3460    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3461        if self.uses_sliding_gated_moe_program() {
3462            return self.step35_decode_attn(e, fa, il, h, pre_q, pos_d, cache);
3463        }
3464        let cfg = &self.cfg;
3465        let geometry = cfg.full_attention_geometry_at(il as u32);
3466        if fa
3467            .step_tp_qkv
3468            .as_ref()
3469            .is_some_and(|tp| tp.attention.is_some())
3470        {
3471            if pre_q.is_some() {
3472                return Err(
3473                    "rank-local generic TP attention preserves BF16 activations and refuses the \
3474                     q8_1 pre-quantized decode path"
3475                        .into(),
3476                );
3477            }
3478            if geometry.attention_gate != memra_gguf::config::AttentionGateKind::None {
3479                return Err(
3480                    "rank-local generic TP attention currently requires an ungated attention \
3481                     plan; fused-Q and separate-head gates retain their existing qualified paths"
3482                        .into(),
3483                );
3484            }
3485            if !crate::tp::step_tp_decode_v2_enabled()? {
3486                return Err(
3487                    "MEMRA_PARALLEL_TP_ATTENTION=1 requires MEMRA_STEP_TP_DECODE_V2=1 for \
3488                     generic decode; the v1 driver is Step-gate-specific"
3489                        .into(),
3490                );
3491            }
3492            return self.step35_tp_decode_attn_resident_v2(e, fa, il, h, pos_d, cache);
3493        }
3494        let n_head = geometry.n_head as usize;
3495        let n_head_kv = geometry.n_head_kv as usize;
3496        let head_dim = geometry.head_dim_k as usize;
3497        let eps = cfg.rms_eps;
3498        let scale = geometry.attention_scale();
3499
3500        // wq|wk|wv all take the same input `h` (in_f = n_embd) — quantize q8_1 ONCE, feed all three.
3501        // Q8 TRUNK-FUSION: on Q8_0 trunks (35B) the three fold into ONE fused3 launch (same MMVQ
3502        // body per (tensor,row) — bit-identical; see full_attn_decode_dc_inner). MEMRA_Q8_DUAL=0 off.
3503        let n_embd = cfg.n_embd as usize;
3504        let qkv_fused = |e: &Engine,
3505                         hq: &CudaSlice<i8>,
3506                         hd: &CudaSlice<f32>|
3507         -> Result<
3508            (CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>),
3509            Box<dyn std::error::Error>,
3510        > {
3511            if let Some((qf, k, v)) = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)? {
3512                return Ok((qf, k, v));
3513            }
3514            Ok((
3515                e.matmul_pre(&fa.wq, hq, hd, h, 1)?,
3516                e.matmul_pre(&fa.wk, hq, hd, h, 1)?,
3517                e.matmul_pre(&fa.wv, hq, hd, h, 1)?,
3518            ))
3519        };
3520        let (qf, mut k, v) =
3521            if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
3522                match pre_q {
3523                    Some((hq, hd)) => qkv_fused(e, hq, hd)?,
3524                    None => {
3525                        let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
3526                        qkv_fused(e, &hq, &hd)?
3527                    }
3528                }
3529            } else {
3530                (
3531                    e.matmul(&fa.wq, h, 1)?,
3532                    e.matmul(&fa.wk, h, 1)?,
3533                    e.matmul(&fa.wv, h, 1)?,
3534                )
3535            };
3536        // q|gate fused: [2*head_dim per head]. Split on-device (no dtoh/host-loop/htod).
3537        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
3538        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
3539        let (mut q, gate) = if gated {
3540            let mut q = e.uninit(n_head * head_dim)?;
3541            let mut gate = e.uninit(n_head * head_dim)?;
3542            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
3543            (q, Some(gate))
3544        } else {
3545            (qf, None)
3546        };
3547
3548        // QK-norm + RoPE at position `pos`
3549        let mut qn = e.uninit(n_head * head_dim)?;
3550        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
3551        q = qn;
3552        let mut kn = e.uninit(n_head_kv * head_dim)?;
3553        e.rms_norm(
3554            &k,
3555            fa.k_norm.float_data(),
3556            &mut kn,
3557            head_dim,
3558            n_head_kv,
3559            eps,
3560        )?;
3561        k = kn;
3562        let rope_dims = geometry.n_rot as usize;
3563        e.rope_neox(
3564            &mut q,
3565            pos_d,
3566            head_dim,
3567            rope_dims,
3568            n_head,
3569            1,
3570            geometry.rope_base,
3571            1.0,
3572        )?;
3573        e.rope_neox(
3574            &mut k,
3575            pos_d,
3576            head_dim,
3577            rope_dims,
3578            n_head_kv,
3579            1,
3580            geometry.rope_base,
3581            1.0,
3582        )?;
3583
3584        // append k,v into the RESIDENT GPU QUANTIZED KV cache at the current position (q8_0 K /
3585        // q5_1 V, on-device append-quantize kernel; no host round-trip). KVQUANT-PLAN §C/E2.
3586        let kvl = cache.kv[il].as_mut().unwrap();
3587        e.append_kv_quantized(
3588            &k,
3589            &v,
3590            &mut kvl.k,
3591            &mut kvl.v,
3592            kvl.len,
3593            kvl.kv_dim_k,
3594            kvl.kv_dim_v,
3595            kvl.k_tok_bytes,
3596            kvl.v_tok_bytes,
3597            false,
3598        )?;
3599        kvl.len += 1;
3600        let t_kv = kvl.len;
3601
3602        // attend: q[hd,nh,1] over the resident byte K/V (view first t_kv*tok_bytes BYTES).
3603        let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
3604        let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
3605        let (ktb, vtb) = (kvl.k_tok_bytes, kvl.v_tok_bytes);
3606        let mut attn = e.uninit(n_head * head_dim)?;
3607        if std::env::var("MEMRA_NOFA").is_ok() {
3608            return Err(
3609                "MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV cache; \
3610                        unset MEMRA_NOFA to use fa_decode"
3611                    .into(),
3612            );
3613        }
3614        e.fa_decode_kvmod(
3615            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, t_kv, scale, ktb, vtb,
3616            false,
3617        )?;
3618        let _ = pos;
3619
3620        // output gate: attn * sigmoid(gate), then o-proj
3621        let attn_g = match &gate {
3622            Some(gate) => {
3623                let mut gsig = e.uninit(n_head * head_dim)?;
3624                e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
3625                let mut ag = e.uninit(n_head * head_dim)?;
3626                e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
3627                ag
3628            }
3629            None => attn,
3630        };
3631        e.matmul(&fa.wo, &attn_g, 1)
3632    }
3633
3634    /// Linear-attention decode: conv with ring-buffer state, GDN scan carrying SSM state.
3635    pub fn linear_attn_decode(
3636        &self,
3637        e: &Engine,
3638        la: &LinearAttnLayer,
3639        h: &CudaSlice<f32>,
3640        cache: &mut Cache,
3641        il: usize,
3642    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3643        self.linear_attn_decode_inner(e, la, h, None, cache, il, false)
3644    }
3645
3646    /// PRE-QUANTIZED-INPUT variant (DECODE attn-input NORM-FUSION lever): the caller passes the
3647    /// post-attn-norm activation ALREADY q8_1-quantized `(hq,hd)` (produced by rms_norm_q8_1, fusing
3648    /// the attn_norm + the mixer's internal quantize_q8_1). Skips the internal quantize. Caller
3649    /// GUARANTEES the projections are q8_1-fast. `persistent` selects the capture-safe state plumbing.
3650    /// BIT-IDENTICAL to linear_attn_decode(h) when (hq,hd)==quantize_q8_1(rms_norm(x)*w).
3651    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
3652    pub fn linear_attn_decode_pre(
3653        &self,
3654        e: &Engine,
3655        la: &LinearAttnLayer,
3656        h: &CudaSlice<f32>,
3657        hq: &CudaSlice<i8>,
3658        hd: &CudaSlice<f32>,
3659        cache: &mut Cache,
3660        il: usize,
3661        persistent: bool,
3662    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3663        self.linear_attn_decode_inner(e, la, h, Some((hq, hd)), cache, il, persistent)
3664    }
3665
3666    /// CAPTURE variant of `linear_attn_decode` (CUDA-GRAPH-PLAN Phase 3). The GDN scan needs distinct
3667    /// in/out SSM-state buffers; the eager path SWAPS a fresh scratch into `rl.ssm_state` (new pointer
3668    /// each step), which is a CAPTURE HAZARD — the graph bakes capture-time pointers and never re-runs
3669    /// the host swap, so replay would read a stale state buffer. Here we instead COPY the scratch back
3670    /// into the STABLE `rl.ssm_state` buffer (memcpy_dtod, captured, same pointers every replay). Math
3671    /// is identical; only the buffer plumbing differs. `conv_state` is already mutated in place (no
3672    /// pointer change) so it is capture-safe as-is.
3673    pub(crate) fn linear_attn_decode_cap(
3674        &self,
3675        e: &Engine,
3676        la: &LinearAttnLayer,
3677        h: &CudaSlice<f32>,
3678        cache: &mut Cache,
3679        il: usize,
3680    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3681        self.linear_attn_decode_inner(e, la, h, None, cache, il, true)
3682    }
3683
3684    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
3685    fn linear_attn_decode_inner(
3686        &self,
3687        e: &Engine,
3688        la: &LinearAttnLayer,
3689        h: &CudaSlice<f32>,
3690        pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
3691        cache: &mut Cache,
3692        il: usize,
3693        persistent_state: bool,
3694    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3695        let cfg = &self.cfg;
3696        let geometry = la.geometry;
3697        let d_state = geometry.key_head_dim as usize;
3698        let num_k = geometry.key_heads as usize;
3699        let num_v = geometry.value_heads as usize;
3700        let d_conv = geometry.conv_kernel as usize;
3701        let head_k = d_state;
3702        let key_dim = head_k * num_k;
3703        let value_dim = geometry.value_head_dim as usize * num_v;
3704        let conv_dim = key_dim * 2 + value_dim;
3705        let eps = cfg.rms_eps;
3706        let scale = 1.0 / (d_state as f32).sqrt();
3707
3708        // projections (T=1): wqkv, wqkv_gate, ssm_beta, ssm_alpha ALL take input `h` (in_f = n_embd)
3709        // -> quantize q8_1 ONCE, feed all four (was 4x redundant quantize_q8_1 of the same row).
3710        let n_embd = cfg.n_embd as usize;
3711        let all_fast = e.uses_q8_1_fast(&la.wqkv)
3712            && e.uses_q8_1_fast(&la.wqkv_gate)
3713            && e.uses_q8_1_fast(&la.ssm_beta)
3714            && e.uses_q8_1_fast(&la.ssm_alpha);
3715        // beta+alpha DUAL fuse (2026-07-05): ssm_beta and ssm_alpha are the same tiny shape
3716        // ([n_embd -> num_v=32]) — out_f=32 launches are pure launch latency (15-16us each,
3717        // HANDOVER b4-headroom note). The existing dual mr2 kernel (FFN gate+up) folds them into
3718        // ONE launch. Bit-identical per row: same MMVQ warp-per-row body, blockIdx.y picks the
3719        // weight; the separable macro-scale multiply is the same single f32 mul as matmul_pre's
3720        // in-kernel scale. Falls back to two matmul_pre when ineligible (Float layers 1/2/4 etc).
3721        let beta_alpha =
3722            |e: &Engine,
3723             hq: &CudaSlice<i8>,
3724             hd: &CudaSlice<f32>|
3725             -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3726                if let Some(((mut b, bs), (mut a, as_))) =
3727                    e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, hq, hd, 1)?
3728                {
3729                    if bs != 1.0 {
3730                        e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
3731                    }
3732                    if as_ != 1.0 {
3733                        e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
3734                    }
3735                    return Ok((b, a));
3736                }
3737                // Q8_0 twin of the NVFP4 dual (9B GGUFs store ssm_beta/alpha as Q8_0 on most layers):
3738                // one fused2 launch, bit-identical per row, no macro-scale (q8_0 scale==1.0).
3739                if let Some((b, a)) = e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, hq, hd)? {
3740                    return Ok((b, a));
3741                }
3742                Ok((
3743                    e.matmul_pre(&la.ssm_beta, hq, hd, h, 1)?,
3744                    e.matmul_pre(&la.ssm_alpha, hq, hd, h, 1)?,
3745                ))
3746            };
3747        // Q8 TRUNK-FUSION (2026-07-05): wqkv+wqkv_gate share (hq,hd) and in_f — on the 35B both
3748        // are Q8_0 (out_f 8192/4096), so ONE fused2 launch replaces the two biggest
3749        // launch-latency-class m=1 launches of every linear layer. BIT-IDENTICAL per (tensor,row)
3750        // (same MMVQ body, block-offset split). Falls back per-tensor when ineligible.
3751        let qkv_pair =
3752            |e: &Engine,
3753             hq: &CudaSlice<i8>,
3754             hd: &CudaSlice<f32>|
3755             -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3756                if let Some((qkv, z)) = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, hq, hd)? {
3757                    return Ok((qkv, z));
3758                }
3759                Ok((
3760                    e.matmul_pre(&la.wqkv, hq, hd, h, 1)?,
3761                    e.matmul_pre(&la.wqkv_gate, hq, hd, h, 1)?,
3762                ))
3763            };
3764        let (qkv_mixed, z, beta_raw, alpha) = if all_fast {
3765            // attn-input NORM-FUSION: use the caller's pre-quantized (hq,hd) when provided (the
3766            // attn_norm already emitted q8_1 via rms_norm_q8_1), else quantize h here. Bit-identical.
3767            match pre_q {
3768                Some((hq, hd)) => {
3769                    let (b, a) = beta_alpha(e, hq, hd)?;
3770                    let (qkv, z) = qkv_pair(e, hq, hd)?;
3771                    (qkv, z, b, a)
3772                }
3773                None => {
3774                    let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
3775                    let (b, a) = beta_alpha(e, &hq, &hd)?;
3776                    let (qkv, z) = qkv_pair(e, &hq, &hd)?;
3777                    (qkv, z, b, a)
3778                }
3779            }
3780        } else {
3781            // 35B trunk lands HERE: wqkv/wqkv_gate are Q8_0 but ssm_beta/alpha are F32, so
3782            // all_fast is false. Still fuse the two Q8_0 projections (one quantize + ONE launch
3783            // instead of two matmuls each re-quantizing h) — matmul_q8_fused2_x is bit-identical
3784            // to the two m=1 MMVQ dispatches. beta/alpha keep the Float cuBLAS path.
3785            let (qm, zg) = match e.matmul_q8_fused2_x(&la.wqkv, &la.wqkv_gate, h)? {
3786                Some(pair) => pair,
3787                None => (e.matmul(&la.wqkv, h, 1)?, e.matmul(&la.wqkv_gate, h, 1)?),
3788            };
3789            (
3790                qm,
3791                zg,
3792                e.matmul(&la.ssm_beta, h, 1)?,
3793                e.matmul(&la.ssm_alpha, h, 1)?,
3794            )
3795        };
3796
3797        // RANK3 LEVER (conv fuse): assemble [conv_state | new col], depthwise causal conv + SiLU, and
3798        // roll the ring — ALL in ONE kernel (`ssm_conv1d_fused_decode`), never materializing conv_in
3799        // to HBM. Replaces conv_assemble_and_roll + ssm_conv1d. Bit-identical (same accumulation order).
3800        let rl = cache.recur[il].as_mut().unwrap();
3801        let mut conv_out = e.uninit(conv_dim)?; // [conv_dim, 1] channel-major, SiLU
3802        e.ssm_conv1d_fused_decode(
3803            &qkv_mixed,
3804            &mut rl.conv_state,
3805            la.ssm_conv1d.float_data(),
3806            &mut conv_out,
3807            conv_dim,
3808            d_conv,
3809        )?;
3810
3811        // GDN scan: SSM state stays RESIDENT on GPU. gdn needs DISTINCT in/out state buffers.
3812        // DECODE DETERMINISM FIX: write the new state into the PERSISTENT spare buffer
3813        // (`ssm_state_alt`) and PING-PONG the two owned buffers in place — instead of allocating a
3814        // fresh `state_scratch` via `e.uninit` each step and swapping its pointer in. The old
3815        // per-step alloc/free churned the stream-ordered async pool; the freed prior state block was
3816        // recycled by a later step's scratch while a kernel still referenced the swapped-in state,
3817        // a use-after-reuse that made decode RUN-TO-RUN nondeterministic (two identical primes
3818        // diverged). With two stable resident buffers there is no per-step alloc/free and no pool
3819        // churn; the math is byte-identical. `o` is a true per-step output (consumed immediately by
3820        // gated_rmsnorm below) so it stays a normal scratch.
3821        let mut o = e.uninit(d_state * num_v)?;
3822        let n_state = d_state * d_state * num_v;
3823        let _ = head_k; // head_k == d_state; the kernels use head_k = d_state internally.
3824        // GDN PREP, FUSED (2026-07-03): repack + q/k L2-norm + beta sigmoid + g_log in ONE
3825        // gdn_prep_decode launch (was 5 tiny serialized kernels: qkv_to_gdn_repack, 2x l2_norm,
3826        // sigmoid, gdn_glog). Same math; the L2 reduce runs a 32-lane warp tree instead of the
3827        // 256-thread two-level tree (different FP sum order) — gates: argmax + run-spec exactness.
3828        // (A prep+scan single-launch fusion — lane/gdnfuse, MEMRA_GDN_FUSE — measured NEUTRAL on
3829        // eager decode 2026-07-08 and was removed in the flag audit; rig5090.jsonl holds the record.)
3830        {
3831            let mut q_l2 = e.uninit(d_state * num_v)?;
3832            let mut k_l2 = e.uninit(d_state * num_v)?;
3833            let mut v_gd = e.uninit(d_state * num_v)?;
3834            let mut beta = e.uninit(num_v)?;
3835            let mut g_log = e.uninit(num_v)?;
3836            e.gdn_prep_decode(
3837                &conv_out,
3838                &beta_raw,
3839                &alpha,
3840                la.ssm_dt.float_data(),
3841                la.ssm_a.float_data(),
3842                &mut q_l2,
3843                &mut k_l2,
3844                &mut v_gd,
3845                &mut beta,
3846                &mut g_log,
3847                d_state,
3848                num_v,
3849                num_k,
3850                key_dim,
3851                eps,
3852            )?;
3853            // gdn reads ssm_state, writes the spare ssm_state_alt (disjoint resident fields).
3854            let RecurLayer {
3855                ssm_state,
3856                ssm_state_alt,
3857                ..
3858            } = rl;
3859            e.gdn_scan_s128(
3860                &q_l2,
3861                &k_l2,
3862                &v_gd,
3863                &g_log,
3864                &beta,
3865                ssm_state,
3866                ssm_state_alt,
3867                &mut o,
3868                num_v,
3869                1,
3870                scale,
3871            )?;
3872        }
3873        if persistent_state {
3874            // CAPTURE-safe (graph replay): the canonical state every replay reads must stay at a
3875            // FIXED pointer (baked into the captured graph). Copy the freshly-written spare BACK
3876            // into ssm_state (captured, replays each launch). No host pointer swap.
3877            let alt = std::mem::replace(&mut rl.ssm_state_alt, e.zeros(0)?);
3878            e.copy_into(&mut rl.ssm_state, 0, &alt, n_state)?;
3879            rl.ssm_state_alt = alt;
3880        } else {
3881            // EAGER: swap the two OWNED resident buffers in place (stable pointers, no alloc/free).
3882            std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3883        }
3884
3885        // gated RMSNorm + ssm_out. FUSED-QUANTIZE ARM (launch-arc): when ssm_out rides the
3886        // q8_1 fast path, emit q8_1 straight from the gated norm (bit-identical bytes to
3887        // gated_rmsnorm + quantize_q8_1) and feed matmul_pre — one launch instead of three
3888        // (norm, quantize, scale all fold away). Fallback = the original f32 chain.
3889        if e.uses_q8_1_fast(&la.ssm_out) {
3890            // norm is PER d_state-ROW (num_v rows), exactly like the f32 twin's grid; the q8_1
3891            // block stream is row-major so the flat bytes feed the matvec unchanged.
3892            let (gq, gd) =
3893                e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v, eps)?;
3894            let g0 = e.zeros(0)?;
3895            return e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, 1);
3896        }
3897        let mut gn = e.uninit(d_state * num_v)?;
3898        e.gated_rmsnorm(
3899            &o,
3900            la.ssm_norm.float_data(),
3901            &z,
3902            &mut gn,
3903            d_state,
3904            num_v,
3905            eps,
3906        )?;
3907        e.matmul(&la.ssm_out, &gn, 1)
3908    }
3909}