Skip to main content

memra_engine/
hybrid_forward.rs

1//! Hybrid forward pass (Stage-1, f32, prefill, single sequence). Per layer dispatches to a
2//! linear-attention (Gated DeltaNet) or full-attention mixer, then SwiGLU FFN. Matches
3//! llama.cpp src/models/qwen35.cpp node-for-node.
4
5use cudarc::driver::CudaSlice;
6use memra_gguf::config::ModelConfig;
7use crate::Engine;
8use crate::cache::Cache;
9
10/// Resident trunk transients for the eager prime (piecewise-graph foundation; see
11/// HybridModel::prime_slabs). Every buffer is fully overwritten before use per prime.
12pub struct PrimeSlabs {
13    pub t_cap: usize,
14    pub h: CudaSlice<f32>,
15    pub x1: CudaSlice<f32>,
16    pub z: CudaSlice<f32>,
17    pub act: CudaSlice<f32>,
18    pub xa: CudaSlice<f32>,
19    pub xb: CudaSlice<f32>,
20    pub h16: CudaSlice<u8>,
21    pub z16: CudaSlice<u8>,
22    /// piecewise boundary slabs (increment 2): GEMM outputs land here so the
23    /// downstream captured segments see fixed addresses.
24    pub gate: CudaSlice<f32>,     // t * n_ff_max
25    pub up: CudaSlice<f32>,       // t * n_ff_max
26    pub ffn_out: CudaSlice<f32>,  // t * n_embd
27    /// piecewise increment 3: per-layer S-glue segment graphs (down-add + next
28    /// attn-norm, ALL-slab IO, zero in-graph allocations -> keeperless capture is
29    /// clean). Baked at this t_cap; replay only when t == t_cap. seg_glue[il] fires
30    /// between layer il and il+1 (ping-pong parity is deterministic per il).
31    pub seg_glue: Vec<Option<cudarc::driver::CudaGraph>>,
32    /// increment 5 (core-split edition): the mixer out-GEMM writes _into_ `mixed`
33    /// directly (no staging copy — the increment-4 copy route was refuted), making
34    /// S-mid [add + post-norm] all-slab and capturable.
35    pub mixed: CudaSlice<f32>,
36    pub seg_mid: Vec<Option<cudarc::driver::CudaGraph>>,
37    pub seg_t: usize,
38}
39
40// Split prime ranges cannot enter the full-range segment-graph arm, and every slab access
41// is serialized by its device mutex after binding that device's CUDA context on the thread.
42unsafe impl Send for PrimeSlabs {}
43
44fn empty_cache_layers<T>(n: usize) -> Vec<Option<T>> {
45    std::iter::repeat_with(|| None).take(n).collect()
46}
47
48/// Temporarily move a PP-2 cache's layer state into two independently-owned cache shells.
49/// The stage walkers then receive disjoint `&mut Cache` values and can run on separate host
50/// threads without aliasing. GPU buffers are moved, not copied; Drop restores every layer
51/// and publishes the last position completed by both stages.
52struct PrimeCacheStages<'a> {
53    parent: &'a mut Cache,
54    cut: usize,
55    stage0: Cache,
56    stage1: Cache,
57}
58
59impl<'a> PrimeCacheStages<'a> {
60    fn new(parent: &'a mut Cache, cut: usize) -> Self {
61        let n = parent.kv.len();
62        assert_eq!(parent.recur.len(), n, "cache layer vectors disagree");
63        assert!(cut <= n, "PP-2 cache cut {cut} exceeds {n} layers");
64        let mut kv0 = empty_cache_layers(n);
65        let mut kv1 = empty_cache_layers(n);
66        let mut recur0 = empty_cache_layers(n);
67        let mut recur1 = empty_cache_layers(n);
68        for i in 0..cut {
69            kv0[i] = parent.kv[i].take();
70            recur0[i] = parent.recur[i].take();
71        }
72        for i in cut..n {
73            kv1[i] = parent.kv[i].take();
74            recur1[i] = parent.recur[i].take();
75        }
76        let pos = parent.pos;
77        let max_ctx = parent.max_ctx;
78        Self {
79            parent,
80            cut,
81            stage0: Cache {
82                kv: kv0,
83                recur: recur0,
84                pos,
85                max_ctx,
86                last_logits_dev: None,
87                dflash_taps: None,
88            },
89            stage1: Cache {
90                kv: kv1,
91                recur: recur1,
92                pos,
93                max_ctx,
94                last_logits_dev: None,
95                dflash_taps: None,
96            },
97        }
98    }
99
100    fn parts(&mut self) -> (&mut Cache, &mut Cache) {
101        (&mut self.stage0, &mut self.stage1)
102    }
103}
104
105impl Drop for PrimeCacheStages<'_> {
106    fn drop(&mut self) {
107        let n = self.parent.kv.len();
108        for i in 0..n {
109            let source = if i < self.cut {
110                &mut self.stage0
111            } else {
112                &mut self.stage1
113            };
114            debug_assert!(self.parent.kv[i].is_none());
115            debug_assert!(self.parent.recur[i].is_none());
116            self.parent.kv[i] = source.kv[i].take();
117            self.parent.recur[i] = source.recur[i].take();
118        }
119        self.parent.pos = self.stage0.pos.min(self.stage1.pos);
120    }
121}
122
123
124/// task #18 (attn side): one sequence's pre-attention outputs (post-rope q/k, v, out-gate).
125pub(crate) struct AttnPre {
126    pub q: cudarc::driver::CudaSlice<f32>,
127    pub k: cudarc::driver::CudaSlice<f32>,
128    pub v: cudarc::driver::CudaSlice<f32>,
129    pub gate: Option<cudarc::driver::CudaSlice<f32>>,
130}
131
132/// task #18: one sequence's GDN prep outputs (the scan inputs).
133pub(crate) struct GdnPrep {
134    pub hk: usize,
135    pub q_l2: cudarc::driver::CudaSlice<f32>,
136    pub k_l2: cudarc::driver::CudaSlice<f32>,
137    pub v_g: cudarc::driver::CudaSlice<f32>,
138    pub beta: cudarc::driver::CudaSlice<f32>,
139    pub g_log: cudarc::driver::CudaSlice<f32>,
140    pub kb16: Option<cudarc::driver::CudaSlice<u8>>,
141    pub qb16: Option<cudarc::driver::CudaSlice<u8>>,
142}
143
144/// Device scratch for the burst verify stream (see `verify_stream_scratch`).
145pub(crate) struct VerifyStreamScratch {
146    pub pos_d: CudaSlice<i32>,
147    pub row_ctrs: Vec<CudaSlice<i32>>,
148}
149use crate::hybrid::{HybridModel, Mixer, FullAttnLayer, LinearAttnLayer, MoeWeights};
150
151struct MoeInputTraceWriter {
152    dir: std::path::PathBuf,
153    index: std::fs::File,
154    payloads: std::collections::HashMap<u16, (std::fs::File, u64)>,
155}
156
157static MOE_INPUT_TRACE_WRITER: std::sync::OnceLock<
158    std::sync::Mutex<Option<MoeInputTraceWriter>>,
159> = std::sync::OnceLock::new();
160
161/// STAGE-2 GROUPED DECODE gate (MEMRA_MOE_GDEC, default ON; `=0` restores the sequential
162/// per-expert launch chain). See `moe_gdec_token`.
163fn gdec_enabled() -> bool {
164    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
165    *E.get_or_init(|| std::env::var("MEMRA_MOE_GDEC").map(|v| v != "0").unwrap_or(true))
166}
167
168/// SLAB-LOCAL RESIDENT ARM gate (lane/pp-leverb 2026-08-08, MEMRA_MOE_SLAB, default ON;
169/// `=0` restores the SLRU dispatch even when resident slabs exist). Read PER CALL, never
170/// memoized — probes A/B the two provenances in one process (the MEMRA_PRIME_PP pattern).
171/// See `moe_ffn_sequential_zq8`'s slab_local arm: the sigmoid-router archs (step35/M3/Hy3)
172/// are denied every `dev_exps` consumer (pairs/dev route softmax), so before this arm the
173/// fits-VRAM resident slabs were UPLOADED for them but never READ — the SLRU kept staging
174/// the same bytes beside a dead copy (37 GB H2D per pp4096 prime on the Step SKU, anatomy
175/// receipt). The arm reads the SAME bytes through the SAME kernels; only the pointer
176/// PROVENANCE changes (slab base + ex*stride vs SLRU slot address) — the bit-identity class
177/// `moe_ffn_dev`'s resident arm already documents against its SLRU arm.
178fn moe_slab_enabled() -> bool {
179    std::env::var("MEMRA_MOE_SLAB").as_deref() != Ok("0")
180}
181
182/// Expert-grouped dispatch remains opt-in after the local 5090 transfer gate rejected the
183/// default flip. `=0` selects the established path, while any other explicit value enables the
184/// grouped research arm for the current call.
185fn moe_grouped_enabled(_cfg: &ModelConfig, _prefill: bool) -> bool {
186    std::env::var("MEMRA_MOE_GROUPED")
187        .map(|value| value != "0")
188        .unwrap_or(false)
189}
190
191/// Deterministic in-token expert prefetch. `MEMRA_MOE_PREFETCH=1` overlaps memory-source H2D on the
192/// copy stream; selecting the opt-in worker spill backend enables the same known-next hook for disk.
193fn moe_prefetch_enabled() -> bool {
194    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
195    *E.get_or_init(|| std::env::var("MEMRA_MOE_PREFETCH").as_deref() == Ok("1")
196        || crate::spill_pread::worker_enabled())
197}
198
199/// Best-effort OS page-cache prefetch distance for mmap-backed expert ranges. Independent of the
200/// H2D copy-stream experiment so storage->RAM and RAM->HBM overlap can be measured separately.
201/// The opt-in default stays one expert to preserve the original experiment; spill rigs can widen
202/// it with `MEMRA_MOE_PAGE_PREFETCH_WINDOW` to cover NVMe latency.
203fn moe_page_prefetch_window() -> usize {
204    static W: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
205    *W.get_or_init(|| page_prefetch_window_from_values(
206        std::env::var("MEMRA_MOE_PAGE_PREFETCH").as_deref() == Ok("1"),
207        std::env::var("MEMRA_MOE_PAGE_PREFETCH_WINDOW").ok().as_deref(),
208    ))
209}
210
211fn page_prefetch_window_from_values(enabled: bool, raw_window: Option<&str>) -> usize {
212    if !enabled {
213        return 0;
214    }
215    raw_window
216        .and_then(|value| value.parse().ok())
217        .unwrap_or(1)
218}
219
220/// Return only the newly exposed positions in a rolling lookahead window. Position zero seeds the
221/// full window; each later position adds one expert at the far edge. Thus widening the window does
222/// not repeatedly issue `MADV_WILLNEED` for the same range.
223fn page_prefetch_positions(
224    position: usize,
225    len: usize,
226    window: usize,
227) -> std::ops::Range<usize> {
228    if window == 0 || position >= len {
229        return len..len;
230    }
231    let (start, count) = if position == 0 {
232        (1, window)
233    } else {
234        (position.saturating_add(window), 1)
235    };
236    let start = start.min(len);
237    start..start.saturating_add(count).min(len)
238}
239
240/// Grouped worker-I/O schedule: prime the first active expert before the loop, then queue exactly
241/// one known-next expert at each iteration. Returning positions keeps expert ordering authoritative.
242fn grouped_worker_prefetch_position(order_len: usize, current: Option<usize>) -> Option<usize> {
243    let position = current.map_or(0, |position| position.saturating_add(1));
244    (position < order_len).then_some(position)
245}
246
247/// Fill the worker ring with complete experts, retaining one pinned buffer for an unexpected
248/// demand miss. Each expert has gate/up/down extents, so depth 16 admits a rolling five-expert
249/// window. Position zero primes the current expert too: its three independent reads can run in
250/// parallel instead of demand-serializing gate, up, and down before any useful GPU work exists.
251fn worker_prefetch_window() -> usize {
252    static WINDOW: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
253    *WINDOW.get_or_init(|| {
254        let automatic = crate::spill_pread::configured_depth().saturating_sub(1) / 3;
255        std::env::var("MEMRA_SPILL_WORKER_EXPERT_WINDOW")
256            .ok()
257            .and_then(|value| value.parse::<usize>().ok())
258            .unwrap_or(automatic.max(1))
259    })
260}
261
262/// Return only positions newly exposed by a rolling worker-I/O window. Unlike mmap page advice,
263/// this includes the current expert when the window is seeded so all three current projections
264/// enter the CPU pool together.
265fn worker_prefetch_positions(position: usize, len: usize, window: usize) -> std::ops::Range<usize> {
266    if window == 0 || position >= len {
267        return len..len;
268    }
269    let (start, count) = if position == 0 {
270        (0, window)
271    } else {
272        (position.saturating_add(window).saturating_sub(1), 1)
273    };
274    let start = start.min(len);
275    start..start.saturating_add(count).min(len)
276}
277
278/// LAUNCH-STRUCTURE STAGE 3 gate (MEMRA_MOE_DEV, default ON; `=0` restores host routing). The
279/// zero-DtoH device-dispatch path for fully-resident layers: router top-k output stays on device,
280/// expert weight pointers come from the per-layer device table. Requires the fused router (the
281/// dev path consumes the device sel/w directly), so MEMRA_FUSED_ROUTER=0 also disables it.
282fn moe_dev_enabled() -> bool {
283    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
284    *E.get_or_init(|| std::env::var("MEMRA_MOE_DEV").map(|v| v != "0").unwrap_or(true)
285        && !matches!(std::env::var("MEMRA_FUSED_ROUTER").as_deref(), Ok("0")))
286}
287
288/// Device sigmoid top-k is the default for Step-3.7 / M3 / Hy3 / GLM-DSA. `MEMRA_SIG_ROUTER=0` restores
289/// the full-logit DtoH plus `moe_route_sigmoid_host` oracle without changing expert dispatch.
290fn sigmoid_router_enabled() -> bool {
291    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
292    *E.get_or_init(|| std::env::var("MEMRA_SIG_ROUTER").map(|v| v != "0").unwrap_or(true))
293}
294
295/// MoE EXPERT dp4a gate (MEMRA_MOE_Q8, default ON; `=0` restores the Stage-A f32-dequant expert
296/// kernels). Applies when gate/up/down expert qtypes are all in the dp4a body set (IQ3_S/IQ4_XS).
297/// FP-order differs from Stage-A (int dp4a + warp tree) — argmax/run-gen/stream-identity gates
298/// arbitrate; the sequential and fused q8 paths ship as a matched pair (MEMRA_MOE_GATE contract).
299fn moe_q8_enabled() -> bool {
300    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
301    *E.get_or_init(|| std::env::var("MEMRA_MOE_Q8").map(|v| v != "0").unwrap_or(true))
302}
303
304/// gemma4 fast-arm gate: qtypes with an `expert_dot_g` dp4a body (superset used by the gelu
305/// dev arm; the qwen q8 arms keep their own battery-gated q8_expert_supported policy).
306fn expert_dp4a_supported(qt: i32) -> bool {
307    qt == crate::QT_Q4_0 || qt == crate::QT_IQ3_S || qt == crate::QT_IQ4_XS
308        || qt == crate::QT_Q3_K || qt == crate::QT_Q4_K || qt == crate::QT_Q6_K
309}
310
311fn q8_expert_supported(qt: i32) -> bool {
312    // k-quant arms added 2026-07-06 (Q3_K/Q4_K/Q6_K bodies for the UD tail layers). Briefly
313    // default-excluded the same day when they appeared to break 35B real-prompt spec — the
314    // ACTUAL culprit was the MoE router's cuBLASLt n-dependence (d994271); with the router
315    // decode-exact at verify t, the k-quant arms pass the full spec battery (p1/p2/p3 + raw
316    // K=1..8) and are DEFAULT ON again (+9 tok/s: 148.9 -> 157.9). MEMRA_MOE_Q8_KQ=0 excludes.
317    static KQ: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
318    let kq = *KQ.get_or_init(|| {
319        std::env::var("MEMRA_MOE_Q8_KQ").map(|v| v != "0").unwrap_or(true)
320    });
321    // NVFP4 experts: DEFAULT ON (2026-07-17). The M3-era "decode-vs-verify MISMATCH 3.4e1"
322    // that had this excluded was the missing per-expert macro-scale fold, fixed in the
323    // dev-kernel epilogues + moe_w_scale_by_expert; the 35B ct-NVFP4 artifact now runs the
324    // q8 arm at parity with the IQ4_XS daily (174-178 tok/s, spec K=1..8 exact). M3/Hy3
325    // never reach the q8 arms regardless (sigmoid-router cfg gates on pairs/dev/gdec).
326    // MEMRA_MOE_Q8_NVFP4=0 restores the f32 arm.
327    let nvfp4_q8 = std::env::var("MEMRA_MOE_Q8_NVFP4").map(|v| v != "0").unwrap_or(true);
328    qt == crate::QT_IQ3_S || qt == crate::QT_IQ4_XS || (nvfp4_q8 && qt == crate::QT_NVFP4)
329        || (kq && (qt == crate::QT_Q3_K || qt == crate::QT_Q4_K || qt == crate::QT_Q6_K))
330}
331
332/// The decode-once (_dec) and IQ-MMA expert kernels dequant via IQ-specific extractors —
333/// k-quant tensors must fall to the _em dot path instead.
334fn q8_expert_dec_supported(qt: i32) -> bool {
335    qt == crate::QT_IQ3_S || qt == crate::QT_IQ4_XS || qt == crate::QT_Q4_0
336}
337
338/// Grouped-f16 door (MEMRA_MOE_F16G) per-projection admission: the qtype has a dequant-to-f16
339/// kernel in cu/moe_f16_grouped.cu AND the projection's k dimension tiles its block size.
340/// Round 49 widened coverage to q35's UD mix (gate/up IQ3_S x39 + Q3_K x1 + IQ4_XS x1; down
341/// IQ4_XS x37 + Q6_K x3 + Q4_K x1) — the round-47 IQ4_XS/Q4_0-only table admitted ~1 of 41
342/// q35 layers, which is why that cell measured FLAT.
343fn f16g_proj_ok(qt: i32, in_f: usize) -> bool {
344    match qt {
345        crate::QT_Q4_0 => in_f % 32 == 0,
346        crate::QT_IQ4_XS | crate::QT_IQ3_S | crate::QT_Q3_K | crate::QT_Q4_K
347        | crate::QT_Q6_K => in_f % 256 == 0,
348        _ => false,
349    }
350}
351
352/// STAGE 3 prewarm gate (MEMRA_MOE_PREWARM, default ON; `=0` leaves residency organic). One-shot
353/// per layer: force-admit every block while FREE slots cover the whole layer (never evicts).
354fn moe_prewarm_enabled() -> bool {
355    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
356    *E.get_or_init(|| std::env::var("MEMRA_MOE_PREWARM").map(|v| v != "0").unwrap_or(true))
357}
358
359/// During a discarded fixed-residency profile, admit CPU-routed misses after their current-token
360/// CPU result is complete. The current result and numeric path are unchanged; later warmup tokens
361/// can then vote for and exercise those experts on GPU before the cache is frozen.
362fn cpu_expert_profile_admit_enabled() -> bool {
363    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
364    *E.get_or_init(|| std::env::var("MEMRA_CPU_EXPERT_FREEZE_PROFILE_ADMIT").as_deref() == Ok("1"))
365}
366
367/// Minimum prompt length for the BATCHED cache prime (`prime_cache`). Below this the tokenwise
368/// decode loop wins anyway (the batched path's GEMM dispatch needs m>=16, and the stateful conv
369/// kernel needs T >= d_conv-1). Callers: generate / generate_spec.
370pub const PRIME_MIN_T: usize = 16;
371const PRIME_PIPE_MICROBATCHES: usize = 8;
372const PRIME_PIPE_MIN_CHUNK: usize = 128;
373const PRIME_PIPE_EDGE_MIN_CHUNK: usize = 64;
374const PRIME_PIPE_LINEAR_WORK: usize = 8;
375
376fn prime_pp2_auto_geometry(n_layers: usize) -> bool {
377    crate::pp::prime_pp_on()
378        && !crate::pp::pp2_streams_off()
379        && crate::pp::pp_cuts(n_layers).is_some_and(|cuts| cuts.len() == 3)
380}
381
382/// Effective internal prime chunk. An explicit MEMRA_PRIME_CHUNK is authoritative.
383/// Naked PP-2 primes use the measured pipeline geometry: up to eight microchunks, never
384/// below 128 tokens, while the legacy 4096-token cap remains the long-context bound.
385pub fn prime_chunk_tokens(t: usize, n_layers: usize) -> usize {
386    if let Ok(value) = std::env::var("MEMRA_PRIME_CHUNK") {
387        let parsed = value.parse::<usize>().unwrap_or(crate::cache::PRIME_CHUNK_MAX_TOKENS);
388        return if crate::cache::swa_ring_on() {
389            if parsed == 0 {
390                crate::cache::PRIME_CHUNK_MAX_TOKENS
391            } else {
392                parsed.min(crate::cache::PRIME_CHUNK_MAX_TOKENS)
393            }
394        } else {
395            parsed
396        };
397    }
398    let chunk = crate::cache::PRIME_CHUNK_MAX_TOKENS;
399    if prime_pp2_auto_geometry(n_layers) && t >= 2 * PRIME_PIPE_MIN_CHUNK {
400        chunk.min(
401            t.div_ceil(PRIME_PIPE_MICROBATCHES)
402                .max(PRIME_PIPE_MIN_CHUNK),
403        )
404    } else {
405        chunk
406    }
407}
408
409fn fixed_prime_chunk_ranges(t: usize, chunk: usize) -> Vec<(usize, usize)> {
410    fixed_prime_chunk_ranges_for_ring(t, chunk, crate::cache::swa_ring_on())
411}
412
413fn fixed_prime_chunk_ranges_for_ring(t: usize, chunk: usize, ring_on: bool) -> Vec<(usize, usize)> {
414    if chunk == 0 || t <= chunk {
415        return vec![(0, t)];
416    }
417    let mut ranges = Vec::with_capacity(t.div_ceil(chunk));
418    let mut start = 0usize;
419    while start < t {
420        let mut end = (start + chunk).min(t);
421        if t - end > 0 && t - end < PRIME_MIN_T {
422            if ring_on {
423                let shifted = t - PRIME_MIN_T;
424                end = if shifted > start { shifted } else { t };
425            } else {
426                end = t;
427            }
428        }
429        ranges.push((start, end));
430        start = end;
431    }
432    ranges
433}
434
435fn prime_chunk_work(prefix: usize, total: usize) -> u128 {
436    let prefix = prefix as u128;
437    prefix * (prefix + (PRIME_PIPE_LINEAR_WORK as u128) * (total as u128))
438}
439
440fn dynamic_prime_chunk_ranges(
441    t: usize,
442    fixed_chunk: usize,
443    fixed: &[(usize, usize)],
444) -> Vec<(usize, usize)> {
445    let n = fixed.len();
446    if n < 3 {
447        return fixed.to_vec();
448    }
449
450    let max_first = t - (n - 1) * PRIME_MIN_T;
451    let first = fixed_chunk
452        .div_ceil(2)
453        .max(PRIME_PIPE_EDGE_MIN_CHUNK)
454        .min(max_first);
455    let mut ranges = Vec::with_capacity(n);
456    ranges.push((0, first));
457
458    let first_work = prime_chunk_work(first, t);
459    let work_span = prime_chunk_work(t, t) - first_work;
460    let denominator = (n - 1) as u128;
461    let mut previous = first;
462    for boundary in 1..n - 1 {
463        let target = first_work * denominator + work_span * (boundary as u128);
464        let remaining = n - 1 - boundary;
465        let mut low = previous + PRIME_MIN_T;
466        let mut high = t - remaining * PRIME_MIN_T;
467        while low < high {
468            let mid = low + (high - low) / 2;
469            if prime_chunk_work(mid, t) * denominator >= target {
470                high = mid;
471            } else {
472                low = mid + 1;
473            }
474        }
475        ranges.push((previous, low));
476        previous = low;
477    }
478    ranges.push((previous, t));
479    ranges
480}
481
482/// Internal prime ranges. The naked PP-2 pipeline defaults to a short-fill,
483/// equal-modeled-time schedule; MEMRA_PRIME_CHUNK_SCHED=fixed restores the measured
484/// equal-token ranges. An explicit MEMRA_PRIME_CHUNK always retains fixed semantics.
485pub fn prime_chunk_ranges(t: usize, n_layers: usize) -> Vec<(usize, usize)> {
486    let explicit_chunk = std::env::var_os("MEMRA_PRIME_CHUNK").is_some();
487    let chunk = prime_chunk_tokens(t, n_layers);
488    let fixed = fixed_prime_chunk_ranges(t, chunk);
489    let dynamic = match std::env::var("MEMRA_PRIME_CHUNK_SCHED") {
490        Ok(value) => value == "dynamic",
491        Err(_) => true,
492    };
493    if explicit_chunk || !dynamic || !prime_pp2_auto_geometry(n_layers) {
494        fixed
495    } else {
496        dynamic_prime_chunk_ranges(t, chunk, &fixed)
497    }
498}
499
500impl HybridModel {
501    /// CHUNK-INVARIANCE BISECT SEAM (lane/chunk-invariance): `MEMRA_PRIME_TRACE=<path>`
502    /// appends one JSONL row per (chunk, layer) with a hash of that layer's last-row
503    /// post-residual hidden. Diagnostic only — never on in a measured or gated run
504    /// (it forces a dtoh + host hash per layer).
505    fn prime_trace_path() -> Option<&'static str> {
506        static P: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
507        P.get_or_init(|| std::env::var("MEMRA_PRIME_TRACE").ok())
508            .as_deref()
509    }
510
511    /// Prefill forward over `tokens`; returns logits [T, n_vocab] (host f32).
512    pub fn forward(&self, e: &Engine, tokens: &[u32]) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
513        if self.is_gemma4_e4b() { return self.gemma4_e4b_forward(e, tokens, false); }
514        if self.cfg.gemma4.is_some() { return self.gemma4_forward(e, tokens, false); }
515        let cfg = &self.cfg;
516        let n_embd = cfg.n_embd as usize;
517        let t = tokens.len();
518        let eps = cfg.rms_eps;
519        let pos: Vec<i32> = (0..t as i32).collect();
520        let pos_d = e.htod_i32(&pos)?;
521
522        let mut x = self.embed(e, tokens)?;   // [T, n_embd]
523
524        for (il, layer) in self.layers.iter().enumerate() {
525            // attn_norm
526            let mut h = e.uninit(t * n_embd)?;
527            e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
528
529            let mixed = match &layer.mixer {
530                Mixer::Full(fa) => self.full_attn(e, fa, &h, &pos_d, t, il)?,
531                Mixer::Linear(la) => self.linear_attn(e, la, &h, t)?,
532                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
533            };
534
535            // residual 1
536            let mut x1 = e.uninit(t * n_embd)?;
537            e.add(&x, &mixed, &mut x1, t * n_embd)?;
538
539            // pre-FFN norm (post_attention_norm), FFN (Dense or MoE), residual 2
540            let mut z = e.uninit(t * n_embd)?;
541            e.rms_norm(&x1, layer.post_attn_norm.float_data(), &mut z, n_embd, t, eps)?;
542            let ffn_out = match &layer.ffn {
543                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
544                    let n_ff = ffn_gate.out_features();
545                    let mut g2 = e.matmul_group(&[ffn_gate, ffn_up], &z, t)?;
546                    let up = g2.pop().unwrap();
547                    let gate = g2.pop().unwrap();
548                    let mut act = e.uninit(t * n_ff)?;
549                    // A DENSE FFN reads the SHEXP clamp array: upstream's one `build_ffn` serves
550                    // both the dense MLP and the shared expert, and its limit is
551                    // `swiglu_clamp_shexp[il]` (llama-graph.cpp:1751). step35's leading dense
552                    // blocks 0-2 therefore key off clamp_shexp, not clamp_exp.
553                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
554                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
555                    e.matmul(ffn_down, &act, t)?
556                }
557                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_prefill(e, m, &z, t, il as u16)?,
558            };
559            let mut x2 = e.uninit(t * n_embd)?;
560            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
561            x = x2;
562        }
563
564        let mut hn = e.uninit(t * n_embd)?;
565        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
566        let logits = e.matmul(&self.output, &hn, t)?;
567        Ok(e.dtoh(&logits)?)
568    }
569
570    /// Prefill that returns ONLY the last token's logits — the common case (greedy/sample needs
571    /// just the final position to start decode). Runs the trunk over all T, then the lm_head
572    /// (output.weight, the largest matrix — 248320 rows) on the LAST hidden row ONLY, not all T.
573    /// On a 512-token prompt this turns a [512,248320] GEMM into [1,248320] — the dominant prefill
574    /// cost (nsys: ~99ms when done for all T). Bit-identical last-row logits to forward()[last].
575    pub fn forward_last(&self, e: &Engine, tokens: &[u32]) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
576        if self.cfg.gemma4.is_some() { return self.gemma4_forward(e, tokens, true); }
577        let cfg = &self.cfg;
578        let n_embd = cfg.n_embd as usize;
579        let t = tokens.len();
580        let eps = cfg.rms_eps;
581        let pos: Vec<i32> = (0..t as i32).collect();
582        let pos_d = e.htod_i32(&pos)?;
583
584        let mut x = self.embed(e, tokens)?;   // [T, n_embd]
585        // MEMRA_LAYER_PROBE=1: synchronize + print after every stage — bisects an in-graph
586        // ILLEGAL_ADDRESS to (layer, stage) at ~1 line of output per layer (M3 bring-up tool).
587        let probe = std::env::var("MEMRA_LAYER_PROBE").is_ok();
588        for (il, layer) in self.layers.iter().enumerate() {
589            let mut h = e.uninit(t * n_embd)?;
590            e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
591            if probe { e.stream().synchronize()?; eprintln!("[probe] L{il} norm ok"); }
592            let mixed = match &layer.mixer {
593                Mixer::Full(fa) => self.full_attn(e, fa, &h, &pos_d, t, il)?,
594                Mixer::Linear(la) => self.linear_attn(e, la, &h, t)?,
595                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
596            };
597            if probe { e.stream().synchronize()?; eprintln!("[probe] L{il} mixer ok"); }
598            let mut x1 = e.uninit(t * n_embd)?;
599            e.add(&x, &mixed, &mut x1, t * n_embd)?;
600            let mut z = e.uninit(t * n_embd)?;
601            e.rms_norm(&x1, layer.post_attn_norm.float_data(), &mut z, n_embd, t, eps)?;
602            let ffn_out = match &layer.ffn {
603                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
604                    let n_ff = ffn_gate.out_features();
605                    let mut g2 = e.matmul_group(&[ffn_gate, ffn_up], &z, t)?;
606                    let up = g2.pop().unwrap();
607                    let gate = g2.pop().unwrap();
608                    let mut act = e.uninit(t * n_ff)?;
609                    // dense FFN keys off the SHEXP clamp array — see forward()'s note.
610                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
611                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
612                    e.matmul(ffn_down, &act, t)?
613                }
614                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_prefill(e, m, &z, t, il as u16)?,
615            };
616            if probe { e.stream().synchronize()?; eprintln!("[probe] L{il} ffn ok"); }
617            let mut x2 = e.uninit(t * n_embd)?;
618            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
619            x = x2;
620        }
621        // norm over all T, then slice the LAST row and run lm_head on that single row.
622        let mut hn = e.uninit(t * n_embd)?;
623        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
624        let last = e.view(&hn, t * n_embd);            // [T, n_embd]
625        let last_row = last.slice((t - 1) * n_embd..t * n_embd);  // [1, n_embd]
626        let mut hlast = e.uninit(n_embd)?;
627        e.copy_view_into(&mut hlast, 0, &last_row, n_embd)?;
628        let logits = e.matmul(&self.output, &hlast, 1)?;   // [1, n_vocab] — lm_head on ONE row
629        Ok(e.dtoh(&logits)?)
630    }
631
632    /// BATCHED PROMPT PRIME (the measured #1 e2e gap, e2e-image-1): `forward_last`'s batched
633    /// prefill body EXTENDED to leave a DECODE-READY cache behind — vs the tokenwise prime's
634    /// ~102/38 tok/s (9B/27B) decode_step loop, this runs the whole prompt at prefill throughput.
635    ///   (a) full-attn layers append their T post-RoPE K/V rows into `cache.kv[il]` via the SAME
636    ///       per-row quantize kernel as the decode append (bit-identical cache bytes per row);
637    ///   (b) linear layers run STATEFULLY from the cache's current recurrent state (zero at a
638    ///       fresh prime): carried-ring conv (ssm_conv1d_tm_state) + ONE gdn_scan(state_in,
639    ///       state_out) whose internal sequential t-loop equals T chained T=1 steps — but with
640    ///       the NORMAL prefill matmul dispatch (GEMM at m>=16), NOT the decode-exact MMVQ the
641    ///       spec verify uses (prime is a prefill-regime pass; the run-gen prefill==decode
642    ///       argmax gate is the accuracy authority, exactly as for forward_last);
643    ///   (c) `cache.pos`/KV len/len_d advance by T.
644    /// Returns (last-row logits host, h_seed = last-row PRE-output_norm hidden [n_embd],
645    /// hiddens = the full pre-output_norm hidden stack [T, n_embd] — generate_spec's prompt_h).
646    /// FRESH-PROMPT ONLY (cache.pos == 0): the fa_prefill tiles attend within `tokens` alone.
647    /// forward_last itself stays untouched (kernel-check / run-gen gate on it).
648    ///
649    /// `queued_after` (lane/tick-seg, 2026-08-07): the number of prompt tokens of the SAME
650    /// REQUEST that the caller will prime in LATER calls — 0 when this call is the whole
651    /// request (every single-shot caller). Serve splits a long prompt across SEVERAL
652    /// prime_cache calls (one per scheduler tick, plus the prefix-cache LCP split), and the
653    /// request's absolute end position `seq_end = cache.pos + t + queued_after` steers step35's
654    /// SWA prefill arm — computing it per CALL made the arm a function of the tick budget
655    /// (budgets 512/256/64 DIFFER 1.813e0 vs monolithic, greedy diverging at step 6; dark lanes
656    /// default to 256 AND cap by live SLO headroom, so identical judge requests primed
657    /// differently under load — research/tick-seg-20260807, receipt in
658    /// research/step35-chunkfix-20260807 §9). The parameter is what prime_cache structurally
659    /// lacked: it cannot know from `tokens` and `cache` alone whether more of the request is
660    /// coming. A SESSION CONTINUATION (a NEW user turn primed onto a live cache) is a NEW
661    /// request — its arithmetic is keyed to its own extent, so those callers pass 0; only a
662    /// caller that SPLITS one request across calls passes the remainder.
663    pub fn prime_cache(&self, e: &Engine, tokens: &[u32], cache: &mut Cache, queued_after: usize)
664                       -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
665        let n_embd = self.cfg.n_embd as usize;
666        let t = tokens.len();
667        // SESSION CONTINUATION (2026-07-05): cache.pos > 0 = priming a NEW SUFFIX onto a live
668        // session cache — every chunk (including the first) takes the continuation arm
669        // (fa_prefill_view over the quantized past + this chunk). Fresh prime (pos==0) unchanged.
670        assert!(t >= PRIME_MIN_T, "prime_cache needs T >= {PRIME_MIN_T} (caller gates)");
671        assert!(cache.pos + t <= cache.max_ctx, "prime_cache: prompt exceeds cache max_ctx");
672
673        // CHUNKED PRIME (2026-07-05, the long-ctx OOM fix): the monolithic prime allocates
674        // per-layer transients proportional to T (gate/up/act = T*n_ff*4B EACH — 1.5GB apiece at
675        // 16k on the 27B), which OOMs a 24GB card around 16k prompt tokens. Chunk the prompt:
676        // each chunk runs the full layer stack with transients sized to the chunk, appending its
677        // K/V to the resident quantized cache and carrying the GDN conv-ring + recurrent state
678        // through `cache.recur` (linear_attn_prime is already stateful — a chunk boundary is
679        // exactly the state carry it was built for). Full-attn chunks after the first attend to
680        // the QUANTIZED past KV via fa_prefill_view (the spec-verify pattern) — same numeric
681        // class as decode reading the cache. Prompts <= one chunk take the ORIGINAL monolithic
682        // body byte-for-byte (chunk 0 short-circuits to the f32 fa_prefill path).
683        // MEMRA_PRIME_CHUNK sets the chunk size (tokens); 0 disables chunking (monolithic).
684        if self.is_gemma4_e4b() {
685            return self.gemma4_e4b_prime(e, tokens, cache);
686        }
687        if self.cfg.gemma4.is_some() {
688            // gemma4 v0: monolithic fresh-prompt prime (chunked/continuation arms later).
689            return self.gemma4_prime(e, tokens, cache);
690        }
691        let ranges = prime_chunk_ranges(t, self.layers.len());
692        // CHUNK-ORDER INVARIANCE (lane/chunk-invariance, 2026-08-05; vLLM #38561 shape).
693        // MEMRA_PRIME_CHUNK is documented as a memory-transient knob, but it also decides
694        // the prefill's ARITHMETIC, so two rigs with different values produced different
695        // greedy text for the same prompt (research/session-affinity-20260805: 97- and
696        // 149-token prompts). ROOT CAUSE, measured in research/chunk-invariance-20260805
697        // (VERDICT.md) — and it is NOT what docs originally said:
698        //   * NOT trunk GEMM m / reduction order. REFUTED: the prefill GEMM is m-INVARIANT
699        //     (rows [0,32) bit-identical at m=32 vs m=33..80, both quantized wq and the
700        //     output head), so growing a chunk cannot move an existing row's value.
701        //   * NOT the GDN scan segmentation. REFUTED: MEMRA_GDN_CHUNKED=0 (sequential scan,
702        //     no WY segmentation at all) still diverges, so vLLM's mamba-boundary fix does
703        //     not describe our leak.
704        //   * IT IS the attention numeric CLASS edge in full_attn_prime_fa_dispatch, which
705        //     selects on `base_len == 0`: chunk 0 attends over this batch's f32 K/V
706        //     (fa_prefill) while every later chunk attends over the q8_0/q5_1 quantized KV
707        //     cache (fa_prefill_view_ws). The chunk size therefore decides WHERE in the
708        //     prompt that precision edge falls. Signature: per-row maxdiff is exactly 0.0
709        //     before the first boundary and O(1) right after, first_div_pos == chunk size.
710        // The grain-free fix (full_attn_prime_fa_dispatch below) removed that class edge at
711        // the source — every row is in one numeric class, so the chunk size no longer steers
712        // arithmetic and MEMRA_PRIME_CHUNK is a pure memory/transient knob again. The interim
713        // MEMRA_PRIME_INVARIANT/MEMRA_PRIME_GRAIN pin-the-boundary door was superseded by that
714        // fix and KILLED at v0.71 per the flags doctrine (the jsonl + VERDICT.md are the
715        // record); the chunkinv gate asserts byte-identity across chunk sizes naked.
716        // The REQUEST's absolute end position, computed ONCE before the loop: every chunk sees the
717        // same value, whatever the chunk size. step35's SWA arm selects on it so that kernel
718        // selection — and therefore the logits — cannot depend on MEMRA_PRIME_CHUNK
719        // (research/step35-chunkfix-20260807; see step35_attn_pre_wo's doc note).
720        // `+ queued_after` closes the SECOND axis (lane/tick-seg): when serve splits the request
721        // across calls, the request still ends at the same absolute position, whatever the tick
722        // budget or LCP split point. MEMRA_PRIME_CALLLOCAL=1 is the ROLLBACK SEAM to the FULL
723        // pre-fix arithmetic: the per-call value here AND the unaligned FA view offset in
724        // step35_attn_pre_wo. Both halves are required for tickinv35's canary teeth under the FA
725        // default. Read per call, not cached (the probe flips it in-process between arms). Never
726        // on in a measured default run.
727        let legacy_calllocal =
728            std::env::var("MEMRA_PRIME_CALLLOCAL").as_deref() == Ok("1");
729        let seq_end = if legacy_calllocal {
730            cache.pos + t
731        } else {
732            cache.pos + t + queued_after
733        };
734        if ranges.len() == 1 {
735            return self.prime_chunk(e, tokens, cache, seq_end);
736        }
737        // PIPELINED PP-2 PRIME (lane/cx-pipeline-prime, 2026-08-08): overlap stage 0 of
738        // chunk N+1 with stage 1 of chunk N. The serial split stays reachable through
739        // MEMRA_PRIME_PIPE=0 and is the exactness oracle. N>2 keeps the serial walker;
740        // this lane owns the balanced two-stage schedule only.
741        if crate::pp::prime_pipe_on()
742            && crate::pp::prime_pp_on()
743            && !crate::pp::pp2_streams_off()
744        {
745            if let Some(fence) = crate::pp::pp_cuts(self.layers.len()).filter(|f| f.len() == 3) {
746                if crate::pp::pp_multi_stream_same_device() {
747                    return Err(
748                        "prime chunk pipeline refused with 2 stage streams on one device — \
749                         that concurrent-stream placement remains quarantined by the deferred \
750                         pp flake record. Use one device per stage or MEMRA_PRIME_PIPE=0 for \
751                         the serial split."
752                            .into(),
753                    );
754                }
755                return self.prime_cache_pp2_pipelined(
756                    e, tokens, cache, seq_end, &ranges, &fence,
757                );
758            }
759        }
760        let mut hiddens = e.uninit(t * n_embd)?;
761        let mut last: Option<(Vec<f32>, CudaSlice<f32>)> = None;
762        for &(start, end) in &ranges {
763            let (l, hs, x) = self.prime_chunk(e, &tokens[start..end], cache, seq_end)?;
764            e.copy_into(&mut hiddens, start * n_embd, &x, (end - start) * n_embd)?;
765            last = Some((l, hs));
766        }
767        let (logits, h_seed) = last.unwrap();
768        Ok((logits, h_seed, hiddens))
769    }
770
771    /// PP-2 chunk scheduler: stage 1 of chunk N and stage 0 of chunk N+1 are both queued
772    /// before N's epilogue D2H drains the last-stage stream. Arithmetic is unchanged:
773    /// every chunk still runs the same two `prime_layers` ranges, boundary copy, output
774    /// norm, lm head, and caller hidden-stack copy as the serial split.
775    fn prime_cache_pp2_pipelined(
776        &self,
777        e: &Engine,
778        tokens: &[u32],
779        cache: &mut Cache,
780        seq_end: usize,
781        ranges: &[(usize, usize)],
782        fence: &[usize],
783    ) -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
784        debug_assert_eq!(fence.len(), 3);
785        debug_assert!(ranges.len() >= 2);
786        let rt = crate::pp::PpNRt::get(e)?;
787        assert_eq!(rt.n_stages(), 2, "prime pipeline requires exactly two PP stages");
788        let n_embd = self.cfg.n_embd as usize;
789        let t = tokens.len();
790        let initial_base = cache.pos;
791        let caller_stream = e.stream();
792
793        // #87 reverse publication before any new stage allocation, then prewarm both
794        // boundary slots while the stage streams are otherwise empty. Lazy-growing slot B
795        // after stage 1(N) is queued would synchronize that stream and erase the first
796        // overlap on a two-chunk prompt.
797        rt.fence_stages_behind(&caller_stream)?;
798        let max_payload = ranges
799            .iter()
800            .map(|(s, e)| (e - s) * n_embd)
801            .max()
802            .unwrap();
803        rt.prepare_overlap_slots(0, max_payload)?;
804
805        let mut hiddens = e.uninit(t * n_embd)?;
806        let mut last: Option<(Vec<f32>, CudaSlice<f32>)> = None;
807        let mut stage_caches = PrimeCacheStages::new(cache, fence[1]);
808        let (cache0, cache1) = stage_caches.parts();
809        let (first_start, first_end) = ranges[0];
810        let mut slot = self.prime_pp2_stage0_enqueue(
811            e,
812            rt,
813            &tokens[first_start..first_end],
814            cache0,
815            seq_end,
816            fence,
817            initial_base + first_start,
818            true,
819        )?;
820        cache0.pos = initial_base + first_end;
821
822        for (i, &(start, end)) in ranges.iter().enumerate() {
823            let base = initial_base + start;
824            debug_assert_eq!(
825                cache1.pos, base,
826                "stage 1 must drain chunks in original position order"
827            );
828            let (out, next_slot) = if let Some(&(next_start, next_end)) = ranges.get(i + 1) {
829                let next_base = initial_base + next_start;
830                debug_assert_eq!(
831                    cache0.pos, next_base,
832                    "stage 0 must issue chunks in original position order"
833                );
834                let cache0_stage = &mut *cache0;
835                // Step's MoE router readback synchronizes once per layer. Two CUDA streams
836                // on one host thread therefore serialize even if the calls are ordered as
837                // a pipeline. Drive the disjoint stage caches from two scoped host threads:
838                // stage 1 consumes slot N while stage 0 produces slot N+1.
839                std::thread::scope(
840                    |scope| -> Result<_, Box<dyn std::error::Error>> {
841                        let stage0 = scope.spawn(move || -> Result<usize, String> {
842                            let next = self
843                                .prime_pp2_stage0_enqueue(
844                                    e,
845                                    rt,
846                                    &tokens[next_start..next_end],
847                                    cache0_stage,
848                                    seq_end,
849                                    fence,
850                                    next_base,
851                                    true,
852                                )
853                                .map_err(|err| err.to_string())?;
854                            cache0_stage.pos = initial_base + next_end;
855                            Ok(next)
856                        });
857                        let x = self.prime_pp2_stage1_enqueue(
858                            e,
859                            rt,
860                            slot,
861                            end - start,
862                            cache1,
863                            seq_end,
864                            fence,
865                            base,
866                            true,
867                        )?;
868                        let out = {
869                            rt.bind_stage(1)?;
870                            let _st1 = rt.enter(1);
871                            let e1 = rt.engine(1, e);
872                            self.prime_chunk_epilogue(e1, x, end - start, cache1)?
873                        };
874                        let next = stage0
875                            .join()
876                            .map_err(|_| "pipeprime stage-0 host walker panicked")?
877                            .map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
878                        Ok((out, Some(next)))
879                    },
880                )?
881            } else {
882                let x = self.prime_pp2_stage1_enqueue(
883                    e,
884                    rt,
885                    slot,
886                    end - start,
887                    cache1,
888                    seq_end,
889                    fence,
890                    base,
891                    true,
892                )?;
893                let out = {
894                    rt.bind_stage(1)?;
895                    let _st1 = rt.enter(1);
896                    let e1 = rt.engine(1, e);
897                    self.prime_chunk_epilogue(e1, x, end - start, cache1)?
898                };
899                (out, None)
900            };
901
902            rt.publish_to(1, &caller_stream)?;
903            e.copy_into(
904                &mut hiddens,
905                start * n_embd,
906                &out.2,
907                (end - start) * n_embd,
908            )?;
909            last = Some((out.0, out.1));
910            crate::pp::PRIME_SPLIT_CHUNKS
911                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
912
913            if let Some(next) = next_slot {
914                // The caller copy above reads a stage-1 allocation. Before stage 1 of the
915                // next chunk can allocate/reuse blocks, mirror #87's body-entry fence.
916                // Stage 0(N+1) is already queued before this wait is appended, so its
917                // overlap with stage 1(N) is preserved.
918                rt.fence_stages_behind(&caller_stream)?;
919                slot = next;
920            }
921        }
922
923        debug_assert_eq!(cache0.pos, initial_base + t);
924        debug_assert_eq!(cache1.pos, initial_base + t);
925        let (logits, h_seed) = last.unwrap();
926        Ok((logits, h_seed, hiddens))
927    }
928
929    /// One prime chunk: the full layer stack over `tokens`, continuing from the cache's current
930    /// state (`cache.pos` = tokens already primed; 0 = fresh). Positions/RoPE are absolute
931    /// task #21 de-broadcast: the q/k head count PREP must emit so the scan's consumers
932    /// agree. Compact (num_k) ONLY when the scan will take the chunked+mma route AND
933    /// num_k == num_v/2 (the engine-side hint mirrors this exact formula); everything
934    /// else (s128 verify tier, chunked-off, mma-off) keeps the broadcast layout.
935    fn gdn_hk(e: &Engine, t: usize, num_v: usize, num_k: usize) -> usize {
936        if Engine::gdn_db_on()
937            && Engine::gdn_chunked_enabled() && t >= 16
938            && e.gdn_mma_enabled(Engine::gdn_chunk_size())
939            && num_k * 2 == num_v
940        {
941            num_k
942        } else {
943            num_v
944        }
945    }
946
947    /// task #17: gate for the fused fp16-operand epilogues (silu_mul/gated_rmsnorm/sig_mul
948    /// `_f16out` twins). Bit-identical class (the twins emit the cvt kernel's exact halves),
949    /// but seam-gated (MEMRA_F16OUT=0) so a bit-check can arbitrate, and OFF under verify-exact
950    /// (matmul_group skips the f16 lane there; the twins must not resurrect it).
951    fn f16out_on(e: &Engine, t: usize) -> bool {
952        crate::f16_ffi::pp_f16_enabled() && t >= 16 && !e.verify_exact_on()
953            && std::env::var("MEMRA_F16OUT").as_deref() != Ok("0")
954    }
955
956    /// (cache.pos + i). Returns (last-row logits, h_seed, this chunk's hidden stack [T, n_embd]).
957    /// See HybridModel::prime_slabs — the eager prime's resident trunk transients.
958    /// PER-DEVICE since lane/pp-leverb (2026-08-08): the map is keyed by the allocating
959    /// engine's CUDA ordinal — under the prime stage split each stage's range walks through
960    /// its OWN slabs on its own device (a dev0 slab dereferenced by a dev1 kernel would be
961    /// a peer read per GEMM operand, the exact class Lever B removes). Single-device rigs
962    /// see one entry, byte-identical behavior.
963    pub fn prime_slabs_get(
964        &self,
965        e: &Engine,
966        t: usize,
967        n_embd: usize,
968        n_ff_max: usize,
969    ) -> Result<std::sync::Arc<std::sync::Mutex<PrimeSlabs>>, Box<dyn std::error::Error>> {
970        let mut slabs = self.prime_slabs.lock().unwrap();
971        let dev = e.ctx().ordinal();
972        let need_new = match slabs.get(&dev) {
973            None => true,
974            Some(sl) => sl.lock().unwrap().t_cap < t,
975        };
976        if need_new {
977            slabs.insert(dev, std::sync::Arc::new(std::sync::Mutex::new(PrimeSlabs {
978                t_cap: t,
979                h: e.uninit(t * n_embd)?,
980                x1: e.uninit(t * n_embd)?,
981                z: e.uninit(t * n_embd)?,
982                act: e.uninit(t * n_ff_max)?,
983                xa: e.uninit(t * n_embd)?,
984                xb: e.uninit(t * n_embd)?,
985                h16: e.alloc_u8_uninit(t * n_embd * 2)?,
986                z16: e.alloc_u8_uninit(t * n_embd * 2)?,
987                gate: e.uninit(t * n_ff_max)?,
988                up: e.uninit(t * n_ff_max)?,
989                ffn_out: e.uninit(t * n_embd)?,
990                seg_glue: Vec::new(),
991                mixed: e.uninit(t * n_embd)?,
992                seg_mid: Vec::new(),
993                seg_t: 0,
994            })));
995        }
996        Ok(slabs.get(&dev).expect("prime slab inserted").clone())
997    }
998
999    /// `seq_end` = the whole REQUEST's absolute end position (`cache.pos + prompt_len` at
1000    /// `prime_cache` entry), NOT this chunk's end. Chunk-size-invariant by construction; step35's
1001    /// SWA arm selects on it (see `step35_attn_pre_wo`). Every other arch ignores it.
1002    fn prime_chunk(&self, e: &Engine, tokens: &[u32], cache: &mut Cache, seq_end: usize)
1003                       -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1004        if crate::pp::pp_host_bounce_active()
1005            && (self.cfg.gemma4.is_some() || !crate::pp::prime_pp_on())
1006        {
1007            return Err(
1008                "prime_chunk: refused with MEMRA_PP_HOST_BOUNCE=1 because this configuration \
1009                 has no active prime stage split and would peer-read remote weights; keep \
1010                 MEMRA_PRIME_PP enabled and use a PP-prime-supported model"
1011                    .into(),
1012            );
1013        }
1014        // LEVER B (lane/pp-leverb, 2026-08-08): the ppN door for the chunked prime. With the
1015        // door open + per-stage streams, each chunk walks its layer ranges on the OWNING
1016        // stage's engine/device (the anatomy receipt this kills: dev1 ran ZERO prefill
1017        // kernels; stage-1 trunk weights were peer-read = 22% of the pp4096 wall).
1018        // MEMRA_PRIME_PP=0 = the unsplit rollback (also the prime-split-gate's reference
1019        // arm — prime deliberately keeps NO refuse_unsplit_if_remote, see pp.rs). The
1020        // MEMRA_PP_STREAMS=0 seam keeps the unsplit walk too: in that regime the sharded
1021        // loader is off and there is nothing remote to split for.
1022        if self.cfg.gemma4.is_none()
1023            && !crate::pp::pp2_streams_off()
1024            && crate::pp::prime_pp_on()
1025        {
1026            if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
1027                return self.prime_chunk_ppn(e, tokens, cache, seq_end, &fence);
1028            }
1029        }
1030        if crate::pp::pp_host_bounce_active() {
1031            return Err(
1032                "prime_chunk: MEMRA_PP_HOST_BOUNCE=1 found no valid prime stage split; \
1033                 refusing an unsplit remote-weight walk"
1034                    .into(),
1035            );
1036        }
1037        let t = tokens.len();
1038        let base = cache.pos;
1039        debug_assert!(seq_end >= base + t, "prime_chunk: seq_end must cover this chunk");
1040        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1041        let pos_d = e.htod_i32(&pos)?;
1042
1043        let x_embed = self.embed(e, tokens)?;   // [T, n_embd]
1044        let x = self.prime_layers(
1045            e, x_embed, 0, self.layers.len(), &pos_d, t, base, cache, seq_end,
1046        )?;
1047        self.prime_chunk_epilogue(e, x, t, cache)
1048    }
1049
1050    /// PRIME RANGE SUBGRAPH (lane/pp-leverb, 2026-08-08): layers `[lo, hi)` of the chunked
1051    /// prime walk — `prime_chunk`'s trunk loop extracted verbatim to the
1052    /// `decode_layers_eager(lo, hi)` / `verify_layers(lo, hi)` contract: enters with a
1053    /// MATERIALIZED `[T, n_embd]` residual, exits with the range's final residual
1054    /// materialized (cloned out of the slab). At `lo=0, hi=n_layers` — the unsplit call —
1055    /// the launch sequence is byte-identical to the pre-extraction body. Range semantics:
1056    ///   - the cross-layer [down-add + NEXT attn-norm] fusion is range-LOCAL (`il + 1 < hi`):
1057    ///     layer `hi`'s attn_norm belongs to the NEXT stage's device, so the range ends with
1058    ///     the plain add (materialize) and the next stage hoists its own first norm — the
1059    ///     kernel-check-pinned `add_rms_norm == add then rms_norm` identity, the same law
1060    ///     the decode split rests on (`prime-split-gate` arbitrates end-to-end);
1061    ///   - prime slabs are PER-DEVICE (`prime_slabs_get` keys on the engine ordinal), so
1062    ///     each stage walks through its own resident transients;
1063    ///   - the S-glue/S-mid capture path requires the FULL range (its lookahead fuses
1064    ///     `self.layers[il+1]` unconditionally) — `use_seg` gains `lo == 0 && hi == n_layers`.
1065    #[allow(clippy::too_many_arguments)]
1066    fn prime_layers(&self, e: &Engine, x_in: CudaSlice<f32>, lo: usize, hi: usize,
1067                    pos_d: &CudaSlice<i32>, t: usize, base: usize, cache: &mut Cache,
1068                    seq_end: usize)
1069                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1070        let cfg = &self.cfg;
1071        let n_embd = cfg.n_embd as usize;
1072        let eps = cfg.rms_eps;
1073        // task #14: fuse the fp16 GEMM-operand emission into the trunk norms (kills the
1074        // standalone convert launches). Only when the f16 lane serves and T reaches the
1075        // GEMM tier; bit-identical either way.
1076        let f16fuse = crate::f16_ffi::pp_f16_enabled() && t >= 16;
1077        // PRIME SLABS (piecewise foundation): trunk transients in resident buffers —
1078        // ~224 fewer alloc/free calls per prime and FROZEN Lt operand addresses
1079        // (nvjet's alignment-variant selection becomes run-to-run stable). Every slab is
1080        // fully overwritten before use; x ping-pongs xa<->xb; the hidden-stack return
1081        // clones the final x (the slab cannot leave). Non-slab fallback: MEMRA_PRIME_SLABS=0.
1082        let n_ff_max = self.layers.iter().map(|l| match &l.ffn {
1083            crate::hybrid::Ffn::Dense { ffn_gate, .. } => ffn_gate.out_features(),
1084            _ => n_embd,
1085        }).max().unwrap_or(n_embd).max(n_embd);
1086        let use_slabs = std::env::var("MEMRA_PRIME_SLABS").as_deref() != Ok("0");
1087        let slab = if use_slabs {
1088            Some(self.prime_slabs_get(e, t, n_embd, n_ff_max)?)
1089        } else {
1090            None
1091        };
1092        let mut slab_guard = slab.as_ref().map(|sl| sl.lock().unwrap());
1093        let mut x_own;   // fallback storage when slabs are off
1094        type SlabRefs<'a> = (&'a mut CudaSlice<f32>, &'a mut CudaSlice<f32>, &'a mut CudaSlice<f32>, &'a mut CudaSlice<f32>, &'a mut CudaSlice<u8>, &'a mut CudaSlice<u8>, &'a mut CudaSlice<f32>, &'a mut CudaSlice<f32>, &'a mut CudaSlice<f32>);
1095        let (mut x_cur, mut x_nxt, sl): (&mut CudaSlice<f32>, &mut CudaSlice<f32>, Option<SlabRefs>);
1096        let mut seg: Option<(&mut Vec<Option<cudarc::driver::CudaGraph>>, &mut Vec<Option<cudarc::driver::CudaGraph>>, &mut CudaSlice<f32>, &mut usize)> = None;
1097        let mut x_own2;
1098        match slab_guard.as_mut() {
1099            Some(g) => {
1100                let slabs = &mut **g;
1101                e.copy_into(&mut slabs.xa, 0, &x_in, t * n_embd)?;
1102                let PrimeSlabs { xa, xb, h, x1, z, act, h16, z16, gate, up, ffn_out, seg_glue, mixed, seg_mid, seg_t, .. } = slabs;
1103                x_cur = xa;
1104                x_nxt = xb;
1105                seg = Some((seg_glue, seg_mid, mixed, seg_t));
1106                sl = Some((h, x1, z, act, h16, z16, gate, up, ffn_out));
1107            }
1108            None => {
1109                x_own = x_in;
1110                x_own2 = e.uninit(t * n_embd)?;
1111                x_cur = &mut x_own;
1112                x_nxt = &mut x_own2;
1113                sl = None;
1114            }
1115        }
1116        let mut alloc_h; let mut alloc_x1; let mut alloc_z; let mut alloc_act;
1117        let mut alloc_h16; let mut alloc_z16;
1118        let mut alloc_gate; let mut alloc_up; let mut alloc_fo;
1119        let (h, x1, z, act): (&mut CudaSlice<f32>, &mut CudaSlice<f32>, &mut CudaSlice<f32>, &mut CudaSlice<f32>);
1120        let (h16, z16): (&mut CudaSlice<u8>, &mut CudaSlice<u8>);
1121        let (sl_gate, sl_up, sl_fo): (&mut CudaSlice<f32>, &mut CudaSlice<f32>, &mut CudaSlice<f32>);
1122        match sl {
1123            Some((a, b, c, d, e16, f16b, g, u, fo)) => {
1124                h = a; x1 = b; z = c; act = d; h16 = e16; z16 = f16b;
1125                sl_gate = g; sl_up = u; sl_fo = fo;
1126            }
1127            None => {
1128                alloc_h = e.uninit(t * n_embd)?;
1129                alloc_x1 = e.uninit(t * n_embd)?;
1130                alloc_z = e.uninit(t * n_embd)?;
1131                alloc_act = e.uninit(t * n_ff_max)?;
1132                alloc_h16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1133                alloc_z16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1134                alloc_gate = e.uninit(t * n_ff_max)?;
1135                alloc_up = e.uninit(t * n_ff_max)?;
1136                alloc_fo = e.uninit(t * n_embd)?;
1137                h = &mut alloc_h; x1 = &mut alloc_x1; z = &mut alloc_z; act = &mut alloc_act;
1138                h16 = &mut alloc_h16; z16 = &mut alloc_z16;
1139                sl_gate = &mut alloc_gate; sl_up = &mut alloc_up; sl_fo = &mut alloc_fo;
1140            }
1141        }
1142        // piecewise increment 3: layer-0 norm hoisted; the per-layer tail fuses
1143        // [down-add + NEXT layer's attn-norm] into one captured S-glue segment
1144        // (all-slab IO, zero in-graph allocations). Capture happens lazily on the
1145        // first prime at this t (capture does not execute -> launch right after).
1146        let n_layers = self.layers.len();
1147        // OPT-IN (2026-07-26 interleaved verdict): 2-kernel segments measured NET
1148        // -0.7%-to-neutral under the interleaved A/B protocol — one cuGraphLaunch costs
1149        // about what two kernel submissions do. The earlier "+0.9%" was cross-run clock
1150        // drift (the repo's interleaved-A/B law exists for exactly this). Larger segments
1151        // (S-prep/S-attn, 7-9 kernels) remain the open hypothesis; the core-split
1152        // machinery stays (byte-identical) as their foundation.
1153        // step35 is excluded: the core-split path calls `full_attn_prime_core_inner`, which is
1154        // the GENERIC attn core (uniform n_head, rope_dim_count, no window, no head-wise gate).
1155        // step35 rides its own mixer through the normal per-layer arm below.
1156        let use_seg = f16fuse && seg.is_some() && self.cfg.step35.is_none()
1157            && lo == 0 && hi == n_layers
1158            && std::env::var("MEMRA_PRIME_SEG").as_deref() == Ok("1");
1159        if let Some((sg, sm, _, st)) = seg.as_mut() {
1160            if **st != t {
1161                sg.clear();
1162                sg.extend((0..n_layers).map(|_| None));
1163                sm.clear();
1164                sm.extend((0..n_layers).map(|_| None));
1165                **st = t;
1166            }
1167        }
1168        {
1169            let layer_lo = &self.layers[lo];
1170            if f16fuse {
1171                e.rms_norm_f16out(x_cur, layer_lo.attn_norm.float_data(), h, h16, n_embd, t, eps)?;
1172            } else {
1173                e.rms_norm(x_cur, layer_lo.attn_norm.float_data(), h, n_embd, t, eps)?;
1174            }
1175        }
1176        for il in lo..hi {
1177            let layer = &self.layers[il];
1178            let hx16 = if f16fuse { Some(&*h16) } else { None };
1179            if use_seg {
1180                // core-split path: projections -> _inner core -> out-GEMM INTO the mixed
1181                // slab (no copies) -> S-mid segment [add + post-norm] as one graph launch.
1182                let (pre, pre16, w_out) = match &layer.mixer {
1183                    Mixer::Full(fa) => {
1184                        let g3 = match hx16 {
1185                            Some(xh) => e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], h, xh, t)?,
1186                            None => e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?,
1187                        };
1188                        let (pre, pre16) = self.full_attn_prime_core_inner(e, fa, g3, &pos_d, t, cache, il)?;
1189                        (pre, pre16, &fa.wo)
1190                    }
1191                    Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1192                    Mixer::Linear(la) => {
1193                        let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
1194                        let g4 = match hx16 {
1195                            Some(xh) => e.matmul_group_xh(&ws, h, xh, t)?,
1196                            None => e.matmul_group(&ws, h, t)?,
1197                        };
1198                        let (pre, pre16) = self.linear_attn_prime_core_pad_inner(e, la, g4, t, cache, il, None)?;
1199                        (pre, pre16, &la.ssm_out)
1200                    }
1201                };
1202                {
1203                    let (_, sm, mslab, _) = seg.as_mut().unwrap();
1204                    let pre_n = pre.len() / t;
1205                    let xh_pre = match pre16 {
1206                        Some(x) => x,
1207                        None => e.f16_act(&pre, t * pre_n, pre_n)?,
1208                    };
1209                    if !e.try_f16_gemm_pre_into(w_out, &xh_pre, t, mslab)? {
1210                        let y = e.matmul(w_out, &pre, t)?;
1211                        e.copy_into(mslab, 0, &y, t * n_embd)?;
1212                    }
1213                    if sm[il].is_none() {
1214                        use cudarc::driver::sys::{CUgraphInstantiate_flags, CUstreamCaptureMode};
1215                        let w_post = layer.post_attn_norm.float_data();
1216                        e.stream().synchronize()?;
1217                        e.stream().begin_capture(CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_RELAXED)?;
1218                        let r = (|| -> Result<(), Box<dyn std::error::Error>> {
1219                            e.add(x_cur, mslab, x1, t * n_embd)?;
1220                            e.rms_norm_f16out(x1, w_post, z, z16, n_embd, t, eps)?;
1221                            Ok(())
1222                        })();
1223                        let g = e.stream().end_capture(
1224                            CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH);
1225                        r?;
1226                        sm[il] = Some(g?.ok_or("S-mid capture produced no graph")?);
1227                    }
1228                    sm[il].as_ref().unwrap().launch()?;
1229                }
1230            } else {
1231                let mixed = match &layer.mixer {
1232                    Mixer::Full(fa) => self.full_attn_prime(e, fa, h, hx16, &pos_d, t, cache, il,
1233                                                            seq_end)?,
1234                    Mixer::Linear(la) => self.linear_attn_prime(e, la, h, hx16, t, cache, il)?,
1235                    Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1236                };
1237                if f16fuse {
1238                    // round 28: residual+norm in ONE kernel (add_rms_norm precedent,
1239                    // bit-identical) — the standalone add pass disappears.
1240                    e.add_rms_norm_f16out(x_cur, &mixed, layer.post_attn_norm.float_data(),
1241                                          x1, z, z16, n_embd, t, eps)?;
1242                } else {
1243                    e.add(x_cur, &mixed, x1, t * n_embd)?;
1244                    e.rms_norm(x1, layer.post_attn_norm.float_data(), z, n_embd, t, eps)?;
1245                }
1246            }
1247            let zx16 = if f16fuse { Some(&*z16) } else { None };
1248            match &layer.ffn {
1249                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1250                    let n_ff = ffn_gate.out_features();
1251                    // gate/up INTO boundary slabs (piecewise increment 2); fall back to
1252                    // the allocating group + copy when a mirror is missing.
1253                    let mut into_ok = false;
1254                    if let Some(xh) = zx16 {
1255                        into_ok = e.try_f16_gemm_pre_into(ffn_gate, xh, t, sl_gate)?
1256                            && e.try_f16_gemm_pre_into(ffn_up, xh, t, sl_up)?;
1257                    }
1258                    if !into_ok {
1259                        let mut g2 = match zx16 {
1260                            Some(xh) => e.matmul_group_xh(&[ffn_gate, ffn_up], z, xh, t)?,
1261                            None => e.matmul_group(&[ffn_gate, ffn_up], z, t)?,
1262                        };
1263                        let up_y = g2.pop().unwrap();
1264                        let gate_y = g2.pop().unwrap();
1265                        e.copy_into(sl_gate, 0, &gate_y, t * n_ff)?;
1266                        e.copy_into(sl_up, 0, &up_y, t * n_ff)?;
1267                    }
1268                    // task #17: the silu arm's f16out twin emits the down GEMM's fp16
1269                    // operand in-epilogue; non-silu activations keep the standalone convert.
1270                    // silu_mul_f16out is PLAIN silu(gate)*up — a clamped layer (step35 dense
1271                    // blocks under a live swiglu_clamp_shexp) must take the ffn_act_lim arm.
1272                    let d_lim = self.cfg.clamp_shexp_at(il as u32);
1273                    let act16 = if Self::f16out_on(e, t) && self.cfg.m3.is_none()
1274                        && d_lim.is_none() {
1275                        let mut a16 = e.alloc_u8_uninit(t * n_ff * 2)?;
1276                        e.silu_mul_f16out(sl_gate, sl_up, act, &mut a16, t * n_ff)?;
1277                        Some(a16)
1278                    } else {
1279                        Self::ffn_act_lim(e, &self.cfg, sl_gate, sl_up, 1.0, 1.0, d_lim,
1280                                          act, t * n_ff)?;
1281                        None
1282                    };
1283                    // down GEMM into the ffn_out slab (f16 arm; fallback copies)
1284                    let xh_act = match act16 {
1285                        Some(x) => x,
1286                        None => e.f16_act(act, t * n_ff, n_ff)?,
1287                    };
1288                    if !e.try_f16_gemm_pre_into(ffn_down, &xh_act, t, sl_fo)? {
1289                        let y = e.matmul(ffn_down, &*act, t)?;
1290                        e.copy_into(sl_fo, 0, &y, t * n_embd)?;
1291                    }
1292                }
1293                crate::hybrid::Ffn::Moe(m) => {
1294                    let y = self.moe_ffn_il_prefill(e, m, z, t, il as u16)?;
1295                    e.copy_into(sl_fo, 0, &y, t * n_embd)?;
1296                }
1297            }
1298            if use_seg && il + 1 < hi {
1299                // S-glue segment: [add + next attn-norm(+f16out)] — one cuGraphLaunch
1300                let w_next = self.layers[il + 1].attn_norm.float_data();
1301                let (sg, _, _, _) = seg.as_mut().unwrap();
1302                if sg[il].is_none() {
1303                    use cudarc::driver::sys::{CUgraphInstantiate_flags, CUstreamCaptureMode};
1304                    e.stream().synchronize()?;
1305                    e.stream().begin_capture(CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_RELAXED)?;
1306                    let r = (|| -> Result<(), Box<dyn std::error::Error>> {
1307                        e.add(x1, sl_fo, x_nxt, t * n_embd)?;
1308                        e.rms_norm_f16out(x_nxt, w_next, h, h16, n_embd, t, eps)?;
1309                        Ok(())
1310                    })();
1311                    let g = e.stream().end_capture(
1312                        CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH);
1313                    r?;
1314                    sg[il] = Some(g?.ok_or("S-glue capture produced no graph")?);
1315                }
1316                sg[il].as_ref().unwrap().launch()?;
1317            } else {
1318                if il + 1 < hi {
1319                    let w_next = self.layers[il + 1].attn_norm.float_data();
1320                    if f16fuse {
1321                        e.add_rms_norm_f16out(x1, sl_fo, w_next, x_nxt, h, h16, n_embd, t, eps)?;
1322                    } else {
1323                        e.add(x1, sl_fo, x_nxt, t * n_embd)?;
1324                        e.rms_norm(x_nxt, w_next, h, n_embd, t, eps)?;
1325                    }
1326                } else {
1327                    e.add(x1, sl_fo, x_nxt, t * n_embd)?;
1328                }
1329            }
1330            // CHUNK-INVARIANCE BISECT SEAM (lane/chunk-invariance, 2026-08-05): dump the
1331            // per-layer post-residual hidden for the LAST row of this chunk, keyed by
1332            // absolute position, so two runs at different MEMRA_PRIME_CHUNK can be diffed
1333            // layer-by-layer to find the FIRST diverging layer. Diagnostic only —
1334            // unset (the default) costs one OnceLock read per layer.
1335            if let Some(path) = Self::prime_trace_path() {
1336                let row = (base + t - 1) as usize;
1337                let host = e.dtoh(x_nxt)?;
1338                let last = &host[(t - 1) * n_embd..t * n_embd];
1339                use std::io::Write as _;
1340                let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
1341                let mut h64: u64 = 0xcbf29ce484222325;
1342                for v in last {
1343                    h64 ^= v.to_bits() as u64;
1344                    h64 = h64.wrapping_mul(0x100000001b3);
1345                }
1346                writeln!(f, "{{\"pos\":{row},\"layer\":{il},\"t\":{t},\"base\":{base},\
1347                             \"hash\":\"{h64:016x}\",\"v0\":{:.9e},\"v1\":{:.9e},\"v2\":{:.9e}}}",
1348                         last[0], last[1], last[2])?;
1349            }
1350            std::mem::swap(&mut x_cur, &mut x_nxt);
1351        }
1352        // hidden-stack return: clone the final x out of the slab
1353        let mut x = e.uninit(t * n_embd)?;
1354        e.copy_into(&mut x, 0, x_cur, t * n_embd)?;
1355        drop(slab_guard);
1356        Ok(x)
1357    }
1358
1359    /// The prime chunk's tail — h_seed + output_norm + one-row lm head + cache.pos advance —
1360    /// shared verbatim by the unsplit walk and the last stage of the ppN walk (`e` = the
1361    /// engine that produced `x`, i.e. the last stage's under the split; output_norm/output
1362    /// were loaded through that engine by the sharded loader, hybrid.rs `e_head`).
1363    fn prime_chunk_epilogue(&self, e: &Engine, x: CudaSlice<f32>, t: usize, cache: &mut Cache)
1364                            -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1365        let n_embd = self.cfg.n_embd as usize;
1366        let eps = self.cfg.rms_eps;
1367        // h_seed = LAST row of x BEFORE output_norm (MTP-PLAN §A default) or AFTER it
1368        // (MEMRA_SPEC_HPOST — reference convention; hn is computed just below either way, so
1369        // the post-norm copy happens after hn exists).
1370        let mut h_seed = e.uninit(n_embd)?;
1371        if !crate::spec::spec_hpost() {
1372            e.copy_view_into(&mut h_seed, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
1373        }
1374        // last-row logits, exactly like forward_last (norm all T — per-row op — then lm_head on 1 row).
1375        let mut hn = e.uninit(t * n_embd)?;
1376        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1377        if crate::spec::spec_hpost() {
1378            e.copy_view_into(&mut h_seed, 0, &hn.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
1379        }
1380        let last = e.view(&hn, t * n_embd);
1381        let last_row = last.slice((t - 1) * n_embd..t * n_embd);
1382        let mut hlast = e.uninit(n_embd)?;
1383        e.copy_view_into(&mut hlast, 0, &last_row, n_embd)?;
1384        let logits = e.matmul(&self.output, &hlast, 1)?;
1385        cache.pos += t;
1386        // Hidden stack handed to generate_spec as prompt_h: pre-norm x (default) or the full
1387        // post-norm stack hn (MEMRA_SPEC_HPOST).
1388        Ok((e.dtoh(&logits)?, h_seed, if crate::spec::spec_hpost() { hn } else { x }))
1389    }
1390
1391    /// THE PRIME STAGE SPLIT (lane/pp-leverb, 2026-08-08): one prime chunk as N stage
1392    /// subgraphs, each range on ITS OWN engine/stream/device, with the `[T, n_embd]`
1393    /// boundary handoff at every fence cut — the prime twin of `decode_step_h_ppn` /
1394    /// `decode_step_t_core_ppn`, and the kill for the anatomy's two receipts: stage-1 trunk
1395    /// weights stop being peer-read (22% of the pp4096 wall) and dev1 stops running zero
1396    /// prefill kernels. Structure mirrors the verify split exactly:
1397    ///   stage 0        `rt.enter(0)` → per-stage pos_d + embed (the table lives with
1398    ///                  stage 0) → `prime_layers(fence[0], fence[1])` → `rt.tx`
1399    ///   middle stages  `rt.rx` → per-stage pos_d → range → `rt.tx`
1400    ///   last stage     `rt.rx` → range → the shared epilogue (output_norm + head live
1401    ///                  there via the sharded loader) → `publish_to`
1402    /// Laws inherited (not relearned): `fence_stages_behind` at entry (#87 — a previous
1403    /// round's stage-freed buffers must not be reused under the caller's queued reads);
1404    /// per-stage `pos_d` (allocated/consumed/freed on one stream); per-stage Engines from
1405    /// `PpNRt` (shared-scratch race); EXIT PUBLICATION for the device-resident returns
1406    /// (h_seed + hidden stack live on the last stage — the caller's stream must wait).
1407    /// KV/MoE locality falls out: each range's KV appends run on the owning stage
1408    /// (`pp::new_cache` placed the buffers there), each stage engine owns its own SLRU
1409    /// pool (per-Engine `moe_cache`, sized on ITS device — the SGLang #33666 law), and the
1410    /// slab-local MoE arm's `DevExps.dev` gate now matches on stage-1 layers too.
1411    /// EXACTNESS: the split adds zero deviation by construction (same kernels, same bytes,
1412    /// boundary = straight f32 copy); `prime-split-gate` (ppsplit) arbitrates bit-for-bit
1413    /// and its liveness counter is bumped here — the gate goes green with this function.
1414    fn prime_chunk_ppn(&self, e: &Engine, tokens: &[u32], cache: &mut Cache, seq_end: usize,
1415                       fence: &[usize])
1416                       -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1417        let rt = crate::pp::PpNRt::get(e)?;
1418        let n_st = fence.len() - 1;
1419        assert_eq!(
1420            rt.n_stages(), n_st,
1421            "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
1422        );
1423        let n_embd = self.cfg.n_embd as usize;
1424        let t = tokens.len();
1425        let base = cache.pos;
1426        debug_assert!(seq_end >= base + t, "prime_chunk_ppn: seq_end must cover this chunk");
1427        let payload = t * n_embd;
1428        // The caller's ambient stream, captured BEFORE any enter() pushes a stage stream
1429        // (inside a stage scope e.stream() IS the stage stream and the exit wait would
1430        // self-order into a no-op) — the decode_step_t_core_ppn pattern.
1431        let caller_stream = e.stream();
1432        rt.fence_stages_behind(&caller_stream)?;
1433
1434        if n_st == 2 {
1435            let slot = self.prime_pp2_stage0_enqueue(
1436                e, rt, tokens, cache, seq_end, fence, base, false,
1437            )?;
1438            let x = self.prime_pp2_stage1_enqueue(
1439                e, rt, slot, t, cache, seq_end, fence, base, false,
1440            )?;
1441            let out = {
1442                rt.bind_stage(1)?;
1443                let _st1 = rt.enter(1);
1444                let e1 = rt.engine(1, e);
1445                self.prime_chunk_epilogue(e1, x, t, cache)?
1446            };
1447            rt.publish_to(1, &caller_stream)?;
1448            crate::pp::PRIME_SPLIT_CHUNKS
1449                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1450            return Ok(out);
1451        }
1452
1453        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1454
1455        // ---- STAGE 0: embed + layers [0, fence[1]) + boundary-0 TX ----
1456        let mut slot = {
1457            let _st0 = rt.enter(0);
1458            let e0 = rt.engine(0, e);
1459            let pos_d = e0.htod_i32(&pos)?;
1460            let x = self.embed(e0, tokens)?;
1461            let x = self.prime_layers(
1462                e0, x, fence[0], fence[1], &pos_d, t, base, cache, seq_end,
1463            )?;
1464            rt.tx(0, &x, payload)?
1465            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
1466        };
1467
1468        // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
1469        for s in 1..n_st - 1 {
1470            let _st = rt.enter(s);
1471            let es = rt.engine(s, e);
1472            let pos_d = es.htod_i32(&pos)?;
1473            let x = rt.rx(s - 1, slot, payload)?;
1474            let x = self.prime_layers(
1475                es, x, fence[s], fence[s + 1], &pos_d, t, base, cache, seq_end,
1476            )?;
1477            slot = rt.tx(s, &x, payload)?;
1478        }
1479
1480        // ---- LAST STAGE: RX + final range + the shared epilogue ----
1481        let _stl = rt.enter(n_st - 1);
1482        let el = rt.engine(n_st - 1, e);
1483        let pos_d = el.htod_i32(&pos)?;
1484        let x = rt.rx(n_st - 2, slot, payload)?;
1485        let x = self.prime_layers(
1486            el, x, fence[n_st - 1], fence[n_st], &pos_d, t, base, cache, seq_end,
1487        )?;
1488        let out = self.prime_chunk_epilogue(el, x, t, cache)?;
1489        // EXIT PUBLICATION: h_seed + the hidden stack are device-resident on the last
1490        // stage's stream; the caller resumes on its own stream (chunk-loop copy_into /
1491        // generate_spec's prompt_h consumer). The logits dtoh above already drained the
1492        // stage stream host-side, but the law is stated in events, not in a dtoh side
1493        // effect a later deferred form would remove.
1494        rt.publish_to(n_st - 1, &caller_stream)?;
1495        crate::pp::PRIME_SPLIT_CHUNKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1496        Ok(out)
1497    }
1498
1499    fn prime_pp2_stage0_enqueue(
1500        &self,
1501        e: &Engine,
1502        rt: &crate::pp::PpNRt,
1503        tokens: &[u32],
1504        cache: &mut Cache,
1505        seq_end: usize,
1506        fence: &[usize],
1507        base: usize,
1508        pipelined: bool,
1509    ) -> Result<usize, Box<dyn std::error::Error>> {
1510        let t = tokens.len();
1511        let n_embd = self.cfg.n_embd as usize;
1512        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1513        rt.bind_stage(0)?;
1514        let _st0 = rt.enter(0);
1515        let e0 = rt.engine(0, e);
1516        let pos_d = e0.htod_i32(&pos)?;
1517        let x = self.embed(e0, tokens)?;
1518        let _overlap = pipelined.then(crate::pp::enter_prime_pipe_stage);
1519        let x = self.prime_layers(
1520            e0, x, fence[0], fence[1], &pos_d, t, base, cache, seq_end,
1521        )?;
1522        if pipelined {
1523            rt.tx_pipelined(0, &x, t * n_embd)
1524        } else {
1525            rt.tx(0, &x, t * n_embd)
1526        }
1527    }
1528
1529    fn prime_pp2_stage1_enqueue(
1530        &self,
1531        e: &Engine,
1532        rt: &crate::pp::PpNRt,
1533        slot: usize,
1534        t: usize,
1535        cache: &mut Cache,
1536        seq_end: usize,
1537        fence: &[usize],
1538        base: usize,
1539        pipelined: bool,
1540    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1541        let n_embd = self.cfg.n_embd as usize;
1542        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1543        rt.bind_stage(1)?;
1544        let _st1 = rt.enter(1);
1545        let e1 = rt.engine(1, e);
1546        let pos_d = e1.htod_i32(&pos)?;
1547        let x = rt.rx(0, slot, t * n_embd)?;
1548        let _overlap = pipelined.then(crate::pp::enter_prime_pipe_stage);
1549        self.prime_layers(
1550            e1, x, fence[1], fence[2], &pos_d, t, base, cache, seq_end,
1551        )
1552    }
1553
1554    /// CAPTURE-SAFE prime trunk (task #14 increment 1, ARCHITECTURE-H100.md design v2):
1555    /// prime_chunk's layer stack with every capture hazard hoisted — `x` is the
1556    /// PRE-EMBEDDED input in a STABLE graph-input buffer (embed + its 8MB htod stay
1557    /// eager, one launch), `pos_d` is a baked device param (fresh prime = 0..T, constant
1558    /// per bucket), logits/h_seed/hidden stay DEVICE-resident (no dtoh), and cache.pos is
1559    /// NOT advanced (host state — the replay wrapper owns it). Body mirrors prime_chunk
1560    /// (the prime-graph-gate pins them together). KNOWN smoke-scope gap: append host-len
1561    /// bookkeeping still runs on the host per call — the real replay path moves the write
1562    /// slot to the len_d device counter (increment 3).
1563    /// GRAPH-OUTPUT CONTRACT: results are COPIED into caller-provided stable buffers
1564    /// (`logits_out` [n_vocab], `h_seed_out` [n_embd]) — every internal allocation drops
1565    /// INSIDE the capture region (alloc+free node pairs). Retaining an in-capture
1566    /// allocation across end_capture makes instantiate throw INVALID_VALUE (smoke finding
1567    /// 2026-07-26), and under AUTO_FREE_ON_LAUNCH its address wouldn't survive a launch
1568    /// anyway — the decode GraphSession's pre-allocated-output pattern is the law here.
1569    pub fn prime_chunk_captured(&self, e: &Engine, x_in: &CudaSlice<f32>, pos_d: &CudaSlice<i32>,
1570                                t: usize, cache: &mut Cache,
1571                                len_d: &CudaSlice<i32>,
1572                                logits_out: &mut CudaSlice<f32>, h_seed_out: &mut CudaSlice<f32>)
1573                                -> Result<(), Box<dyn std::error::Error>> {
1574        let cfg = &self.cfg;
1575        let n_embd = cfg.n_embd as usize;
1576        let eps = cfg.rms_eps;
1577        let f16fuse = crate::f16_ffi::pp_f16_enabled() && t >= 16;
1578        let mut x = e.uninit(t * n_embd)?;
1579        e.copy_into(&mut x, 0, x_in, t * n_embd)?;
1580        for (il, layer) in self.layers.iter().enumerate() {
1581            let mut h = e.uninit(t * n_embd)?;
1582            let mut hx16: Option<CudaSlice<u8>> = None;
1583            if f16fuse {
1584                let mut b16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1585                e.rms_norm_f16out(&x, layer.attn_norm.float_data(), &mut h, &mut b16, n_embd, t, eps)?;
1586                hx16 = Some(b16);
1587            } else {
1588                e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
1589            }
1590            let mixed = match &layer.mixer {
1591                // The captured prime is ONE unchunked bucket over a FRESH cache (pos == 0), so the
1592                // request ends at t. If bucketed capture ever composes with chunking, seq_end must
1593                // come from the caller (see step35_attn_pre_wo's doc note).
1594                Mixer::Full(fa) => self.full_attn_prime(e, fa, &h, hx16.as_ref(), pos_d, t, cache,
1595                                                        il, t)?,
1596                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1597                Mixer::Linear(la) => {
1598                    let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
1599                    let g4 = match hx16.as_ref() {
1600                        Some(xh) => e.matmul_group_xh(&ws, &h, xh, t)?,
1601                        None => e.matmul_group(&ws, &h, t)?,
1602                    };
1603                    self.linear_attn_prime_core_pad(e, la, g4, t, cache, il, Some(len_d))?
1604                }
1605            };
1606            let mut x1 = e.uninit(t * n_embd)?;
1607            e.add(&x, &mixed, &mut x1, t * n_embd)?;
1608            let mut z = e.uninit(t * n_embd)?;
1609            let mut zx16: Option<CudaSlice<u8>> = None;
1610            if f16fuse {
1611                let mut b16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1612                e.rms_norm_f16out(&x1, layer.post_attn_norm.float_data(), &mut z, &mut b16, n_embd, t, eps)?;
1613                zx16 = Some(b16);
1614            } else {
1615                e.rms_norm(&x1, layer.post_attn_norm.float_data(), &mut z, n_embd, t, eps)?;
1616            }
1617            let ffn_out = match &layer.ffn {
1618                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1619                    let n_ff = ffn_gate.out_features();
1620                    let mut g2 = match &zx16 {
1621                        Some(xh) => e.matmul_group_xh(&[ffn_gate, ffn_up], &z, xh, t)?,
1622                        None => e.matmul_group(&[ffn_gate, ffn_up], &z, t)?,
1623                    };
1624                    let up = g2.pop().unwrap();
1625                    let gate = g2.pop().unwrap();
1626                    let mut act = e.uninit(t * n_ff)?;
1627                    // dense FFN keys off the SHEXP clamp array — see forward()'s note.
1628                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
1629                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
1630                    e.matmul(ffn_down, &act, t)?
1631                }
1632                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_prefill(e, m, &z, t, il as u16)?,
1633            };
1634            let mut x2 = e.uninit(t * n_embd)?;
1635            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
1636            x = x2;
1637        }
1638        // device-indexed TRUE last row (pads sit past it in a bucketed graph)
1639        if !crate::spec::spec_hpost() {
1640            e.row_gather_dev(&x, h_seed_out, len_d, n_embd)?;
1641        }
1642        let mut hn = e.uninit(t * n_embd)?;
1643        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1644        if crate::spec::spec_hpost() {
1645            e.row_gather_dev(&hn, h_seed_out, len_d, n_embd)?;
1646        }
1647        let mut hlast = e.uninit(n_embd)?;
1648        e.row_gather_dev(&hn, &mut hlast, len_d, n_embd)?;
1649        let logits = e.matmul(&self.output, &hlast, 1)?;
1650        let nv = logits.len();
1651        e.copy_into(logits_out, 0, &logits, nv)?;
1652        Ok(())
1653    }
1654
1655    fn step35_prime_batch_on() -> bool {
1656        std::env::var("MEMRA_STEP35_PRIME_BATCH").as_deref() != Ok("0")
1657    }
1658
1659    /// Step35 cross-request prime range: weight-streaming work runs once at `m=sum(T)`;
1660    /// sequence-scoped attention/KV work stays on each request's own cache and positions.
1661    #[allow(clippy::too_many_arguments)]
1662    fn step35_prime_batch_layers(
1663        &self,
1664        e: &Engine,
1665        mut x: CudaSlice<f32>,
1666        lo: usize,
1667        hi: usize,
1668        ts: &[usize],
1669        offs: &[usize],
1670        pos_ds: &[CudaSlice<i32>],
1671        caches: &mut [&mut Cache],
1672    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1673        let cfg = &self.cfg;
1674        let n_embd = cfg.n_embd as usize;
1675        let eps = cfg.rms_eps;
1676        let b = ts.len();
1677        let total: usize = ts.iter().sum();
1678        let f16fuse = crate::f16_ffi::pp_f16_enabled() && total >= 16;
1679
1680        let split = |e: &Engine, y: &CudaSlice<f32>, dim: usize|
1681                     -> Result<Vec<CudaSlice<f32>>, Box<dyn std::error::Error>> {
1682            let mut out = Vec::with_capacity(b);
1683            for s in 0..b {
1684                let mut ys = e.uninit(ts[s] * dim)?;
1685                e.copy_view_into(
1686                    &mut ys,
1687                    0,
1688                    &y.slice(offs[s] * dim..(offs[s] + ts[s]) * dim),
1689                    ts[s] * dim,
1690                )?;
1691                out.push(ys);
1692            }
1693            Ok(out)
1694        };
1695
1696        for il in lo..hi {
1697            let layer = &self.layers[il];
1698            let Mixer::Full(fa) = &layer.mixer else {
1699                return Err(format!("step35 layer {il} is not full-attn — corrupt config").into());
1700            };
1701
1702            let mut h = e.uninit(total * n_embd)?;
1703            let mut hx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
1704            if f16fuse {
1705                e.rms_norm_f16out(
1706                    &x,
1707                    layer.attn_norm.float_data(),
1708                    &mut h,
1709                    &mut hx16,
1710                    n_embd,
1711                    total,
1712                    eps,
1713                )?;
1714            } else {
1715                e.rms_norm(
1716                    &x,
1717                    layer.attn_norm.float_data(),
1718                    &mut h,
1719                    n_embd,
1720                    total,
1721                    eps,
1722                )?;
1723            }
1724
1725            // Q/K/V + gate projections and wo are batched weight streams. The step35 core
1726            // remains per sequence, so its partial RoPE, SWA view, KV append, and gate
1727            // application stay verbatim.
1728            let gate_w = fa
1729                .attn_gate
1730                .as_ref()
1731                .ok_or("step35 layer is missing attn_gate.weight (head-wise attention gate)")?;
1732            let mut g4 = if f16fuse {
1733                e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv, gate_w], &h, &hx16, total)?
1734            } else {
1735                e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv, gate_w], &h, total)?
1736            };
1737            let gate = g4.pop().unwrap();
1738            let mut parts: Vec<Vec<CudaSlice<f32>>> =
1739                (0..b).map(|_| Vec::with_capacity(3)).collect();
1740            for (w, y) in [&fa.wq, &fa.wk, &fa.wv].iter().zip(g4) {
1741                for (s, ys) in split(e, &y, w.out_features())?.into_iter().enumerate() {
1742                    parts[s].push(ys);
1743                }
1744            }
1745            let gates = split(e, &gate, gate_w.out_features())?;
1746            let geometry = self.step35_geom(il);
1747            let hd = geometry.head_dim_k as usize;
1748            let nh = geometry.n_head as usize;
1749            let mut ag_cat = e.uninit(total * nh * hd)?;
1750            for (s, (g3s, gate)) in parts.into_iter().zip(gates).enumerate() {
1751                let ag = self.step35_attn_pre_wo(
1752                    e,
1753                    fa,
1754                    g3s,
1755                    None,
1756                    Some(&gate),
1757                    &pos_ds[s],
1758                    ts[s],
1759                    Some(&mut *caches[s]),
1760                    il,
1761                    ts[s],
1762                )?;
1763                e.copy_into(
1764                    &mut ag_cat,
1765                    offs[s] * nh * hd,
1766                    &ag,
1767                    ts[s] * nh * hd,
1768                )?;
1769            }
1770            let mixed = e.matmul(&fa.wo, &ag_cat, total)?;
1771
1772            let mut x1 = e.uninit(total * n_embd)?;
1773            let mut z = e.uninit(total * n_embd)?;
1774            let mut zx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
1775            if f16fuse {
1776                e.add_rms_norm_f16out(
1777                    &x,
1778                    &mixed,
1779                    layer.post_attn_norm.float_data(),
1780                    &mut x1,
1781                    &mut z,
1782                    &mut zx16,
1783                    n_embd,
1784                    total,
1785                    eps,
1786                )?;
1787            } else {
1788                e.add(&x, &mixed, &mut x1, total * n_embd)?;
1789                e.rms_norm(
1790                    &x1,
1791                    layer.post_attn_norm.float_data(),
1792                    &mut z,
1793                    n_embd,
1794                    total,
1795                    eps,
1796                )?;
1797            }
1798
1799            let ffn_out = match &layer.ffn {
1800                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1801                    let n_ff = ffn_gate.out_features();
1802                    let mut g2 = if f16fuse {
1803                        e.matmul_group_xh(&[ffn_gate, ffn_up], &z, &zx16, total)?
1804                    } else {
1805                        e.matmul_group(&[ffn_gate, ffn_up], &z, total)?
1806                    };
1807                    let up = g2.pop().unwrap();
1808                    let gate = g2.pop().unwrap();
1809                    let mut act = e.uninit(total * n_ff)?;
1810                    let d_lim = cfg.clamp_shexp_at(il as u32);
1811                    if Self::f16out_on(e, total) && cfg.m3.is_none() && d_lim.is_none() {
1812                        let mut a16 = e.alloc_u8_uninit(total * n_ff * 2)?;
1813                        e.silu_mul_f16out(&gate, &up, &mut act, &mut a16, total * n_ff)?;
1814                        match e.try_f16_gemm_pre(ffn_down, &a16, total)? {
1815                            Some(y) => y,
1816                            None => e.matmul(ffn_down, &act, total)?,
1817                        }
1818                    } else {
1819                        Self::ffn_act_lim(
1820                            e,
1821                            cfg,
1822                            &gate,
1823                            &up,
1824                            1.0,
1825                            1.0,
1826                            d_lim,
1827                            &mut act,
1828                            total * n_ff,
1829                        )?;
1830                        e.matmul(ffn_down, &act, total)?
1831                    }
1832                }
1833                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, total, il as u16)?,
1834            };
1835            let mut x2 = e.uninit(total * n_embd)?;
1836            e.add(&x1, &ffn_out, &mut x2, total * n_embd)?;
1837            x = x2;
1838        }
1839        Ok(x)
1840    }
1841
1842    fn step35_prime_batch_epilogue(
1843        &self,
1844        e: &Engine,
1845        x: CudaSlice<f32>,
1846        ts: &[usize],
1847        offs: &[usize],
1848        caches: &mut [&mut Cache],
1849    ) -> Result<Vec<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
1850        let n_embd = self.cfg.n_embd as usize;
1851        let total: usize = ts.iter().sum();
1852        let mut hn = e.uninit(total * n_embd)?;
1853        e.rms_norm(
1854            &x,
1855            self.output_norm.float_data(),
1856            &mut hn,
1857            n_embd,
1858            total,
1859            self.cfg.rms_eps,
1860        )?;
1861
1862        let hidden_src = if crate::spec::spec_hpost() { &hn } else { &x };
1863        let mut out = Vec::with_capacity(ts.len());
1864        for s in 0..ts.len() {
1865            let mut hidden = e.uninit(ts[s] * n_embd)?;
1866            e.copy_view_into(
1867                &mut hidden,
1868                0,
1869                &hidden_src.slice(offs[s] * n_embd..(offs[s] + ts[s]) * n_embd),
1870                ts[s] * n_embd,
1871            )?;
1872            let last0 = (offs[s] + ts[s] - 1) * n_embd;
1873            let mut h_seed = e.uninit(n_embd)?;
1874            e.copy_view_into(
1875                &mut h_seed,
1876                0,
1877                &hidden_src.slice(last0..last0 + n_embd),
1878                n_embd,
1879            )?;
1880            // Exactness-first: the serial reference runs the output head at m=1.
1881            let mut hlast = e.uninit(n_embd)?;
1882            e.copy_view_into(
1883                &mut hlast,
1884                0,
1885                &hn.slice(last0..last0 + n_embd),
1886                n_embd,
1887            )?;
1888            let logits = e.dtoh(&e.matmul(&self.output, &hlast, 1)?)?;
1889            caches[s].pos += ts[s];
1890            out.push((logits, h_seed, hidden));
1891        }
1892        Ok(out)
1893    }
1894
1895    fn step35_prime_cache_batch(
1896        &self,
1897        e: &Engine,
1898        prompts: &[&[u32]],
1899        caches: &mut [&mut Cache],
1900    ) -> Result<Vec<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
1901        if crate::pp::pp_host_bounce_active()
1902            && (!crate::pp::prime_pp_on()
1903                || crate::pp::pp_cuts(self.layers.len()).is_none())
1904        {
1905            return Err(
1906                "step35_prime_cache_batch: MEMRA_PP_HOST_BOUNCE=1 requires a valid prime \
1907                 stage split; refusing an unsplit remote-weight walk"
1908                    .into(),
1909            );
1910        }
1911        if !Self::step35_prime_batch_on() {
1912            return Err("step35 batched prime is disabled (MEMRA_STEP35_PRIME_BATCH=0)".into());
1913        }
1914        if caches.iter().any(|c| c.pos != 0) {
1915            return Err(
1916                "step35 batched prime currently supports complete fresh prompts only; \
1917                 continuation/tick chunks require per-request queued_after"
1918                    .into(),
1919            );
1920        }
1921
1922        let ts: Vec<usize> = prompts.iter().map(|p| p.len()).collect();
1923        for &t in &ts {
1924            assert!(t >= PRIME_MIN_T, "step35 batched prime needs T >= {PRIME_MIN_T}");
1925        }
1926        for (s, c) in caches.iter().enumerate() {
1927            assert!(ts[s] <= c.max_ctx, "step35 batched prime exceeds cache max_ctx");
1928        }
1929        let offs: Vec<usize> = ts
1930            .iter()
1931            .scan(0usize, |a, &t| {
1932                let o = *a;
1933                *a += t;
1934                Some(o)
1935            })
1936            .collect();
1937        let total: usize = ts.iter().sum();
1938        let payload = total * self.cfg.n_embd as usize;
1939        let cat_tokens: Vec<u32> = prompts.iter().flat_map(|p| p.iter().copied()).collect();
1940        let positions: Vec<Vec<i32>> = ts
1941            .iter()
1942            .map(|&t| (0..t as i32).collect())
1943            .collect();
1944        let upload_positions = |e: &Engine|
1945                                -> Result<Vec<CudaSlice<i32>>, Box<dyn std::error::Error>> {
1946            positions
1947                .iter()
1948                .map(|p| e.htod_i32(p))
1949                .collect::<Result<_, _>>()
1950        };
1951
1952        static ONCE: std::sync::Once = std::sync::Once::new();
1953        ONCE.call_once(|| {
1954            eprintln!(
1955                "[step35-prime-batch] first concat prime: B={} tokens={total}",
1956                prompts.len()
1957            );
1958        });
1959
1960        let out = if !crate::pp::pp2_streams_off() && crate::pp::prime_pp_on() {
1961            if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
1962                let rt = crate::pp::PpNRt::get(e)?;
1963                let n_st = fence.len() - 1;
1964                assert_eq!(rt.n_stages(), n_st, "step35 prime batch stage count mismatch");
1965                let caller_stream = e.stream();
1966                rt.fence_stages_behind(&caller_stream)?;
1967
1968                let mut slot = {
1969                    let _st0 = rt.enter(0);
1970                    let e0 = rt.engine(0, e);
1971                    let pos_ds = upload_positions(e0)?;
1972                    let x = self.embed(e0, &cat_tokens)?;
1973                    let x = self.step35_prime_batch_layers(
1974                        e0,
1975                        x,
1976                        fence[0],
1977                        fence[1],
1978                        &ts,
1979                        &offs,
1980                        &pos_ds,
1981                        caches,
1982                    )?;
1983                    rt.tx(0, &x, payload)?
1984                };
1985                for s in 1..n_st - 1 {
1986                    let _st = rt.enter(s);
1987                    let es = rt.engine(s, e);
1988                    let pos_ds = upload_positions(es)?;
1989                    let x = rt.rx(s - 1, slot, payload)?;
1990                    let x = self.step35_prime_batch_layers(
1991                        es,
1992                        x,
1993                        fence[s],
1994                        fence[s + 1],
1995                        &ts,
1996                        &offs,
1997                        &pos_ds,
1998                        caches,
1999                    )?;
2000                    slot = rt.tx(s, &x, payload)?;
2001                }
2002
2003                let _stl = rt.enter(n_st - 1);
2004                let el = rt.engine(n_st - 1, e);
2005                let pos_ds = upload_positions(el)?;
2006                let x = rt.rx(n_st - 2, slot, payload)?;
2007                let x = self.step35_prime_batch_layers(
2008                    el,
2009                    x,
2010                    fence[n_st - 1],
2011                    fence[n_st],
2012                    &ts,
2013                    &offs,
2014                    &pos_ds,
2015                    caches,
2016                )?;
2017                let out = self.step35_prime_batch_epilogue(el, x, &ts, &offs, caches)?;
2018                rt.publish_to(n_st - 1, &caller_stream)?;
2019                crate::pp::STEP35_PRIME_BATCH_SPLITS.fetch_add(
2020                    1,
2021                    std::sync::atomic::Ordering::Relaxed,
2022                );
2023                out
2024            } else {
2025                let pos_ds = upload_positions(e)?;
2026                let x = self.embed(e, &cat_tokens)?;
2027                let x = self.step35_prime_batch_layers(
2028                    e,
2029                    x,
2030                    0,
2031                    self.layers.len(),
2032                    &ts,
2033                    &offs,
2034                    &pos_ds,
2035                    caches,
2036                )?;
2037                self.step35_prime_batch_epilogue(e, x, &ts, &offs, caches)?
2038            }
2039        } else {
2040            let pos_ds = upload_positions(e)?;
2041            let x = self.embed(e, &cat_tokens)?;
2042            let x = self.step35_prime_batch_layers(
2043                e,
2044                x,
2045                0,
2046                self.layers.len(),
2047                &ts,
2048                &offs,
2049                &pos_ds,
2050                caches,
2051            )?;
2052            self.step35_prime_batch_epilogue(e, x, &ts, &offs, caches)?
2053        };
2054        crate::pp::STEP35_PRIME_BATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2055        Ok(out)
2056    }
2057
2058    /// Cross-request BATCHED fresh prime (task #13, design in ARCHITECTURE-H100.md): the
2059    /// trunk's token-parallel ops (embed, norms, adds, ffn, projection GROUPS) run once on
2060    /// the CONCATENATION of B sequences — GEMMs at m = sum_T, the continuous-batching win
2061    /// the serving-lane bench attributed the remaining vLLM gap to. The stateful mixer
2062    /// CORES (QK-norm/RoPE/FA/append, conv/GDN scans) run per sequence on split projection
2063    /// buffers (D2D row copies; the mixers' own out-projections stay per-seq this
2064    /// increment). CONTINUATION primes (increment (b), 2026-07-30): cache.pos > 0 seqs
2065    /// batch the projections/FFN/lm_head exactly like fresh; the mixer cores take the
2066    /// per-seq CONTINUATION arms (Full: core_inner with carried pos_d + fa_prefill_view
2067    /// over the quantized past; Linear: the stateful pad_view twin — the same state
2068    /// carry the chunked single-seq prime rides). The fresh-only favl/gdn-vl fast paths
2069    /// stay byte-identical (gated on !carried). gemma4 models have no continuation
2070    /// prime (v0 monolithic fresh) — carried gemma4 batches return Err (caller falls
2071    /// back to single-chunk serving).
2072    /// NUMERIC CONFIG: a concat GEMM tiles K differently than per-seq GEMMs — same class
2073    /// as every prefill GEMM change; prime_batch_gate arbitrates (argmax + stream battery).
2074    pub fn prime_cache_batch(&self, e: &Engine, prompts: &[&[u32]], caches: &mut [&mut Cache])
2075                             -> Result<Vec<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
2076        let cfg = &self.cfg;
2077        let n_embd = cfg.n_embd as usize;
2078        let eps = cfg.rms_eps;
2079        let b = prompts.len();
2080        assert!(b >= 1 && b == caches.len());
2081        let pos0s: Vec<usize> = caches.iter().map(|c| c.pos).collect();
2082        let carried = pos0s.iter().any(|&p| p > 0);
2083        // gemma4: refuse UNCONDITIONALLY (2026-08-07, lane/gemma4-serve-gaps). The old guard
2084        // covered only `carried` — two concurrent FRESH gemma4 prompts batched into the
2085        // generic concat attn core below (uniform geometry, no per-layer swa window, no
2086        // softcapped head): compiles, runs, wrong logits. Same silent-wrong class as the
2087        // step35 refusal beneath. The per-sequence `gemma4_prime` is the supported prefill.
2088        if cfg.gemma4.is_some() {
2089            return Err("prime_cache_batch: gemma4 has no batched prime core (per-layer \
2090                        swa/global geometry, softcapped head) — use gemma4_prime per sequence".into());
2091        }
2092        // Step35 has a dedicated concat walk: the generic core below cannot express its
2093        // per-layer geometry/SWA/head gate, and under PP the dedicated path is stage-scoped.
2094        if cfg.step35.is_some() {
2095            return self.step35_prime_cache_batch(e, prompts, caches);
2096        }
2097        let ts: Vec<usize> = prompts.iter().map(|p| p.len()).collect();
2098        for &t in &ts { assert!(t >= PRIME_MIN_T, "prime_cache_batch needs T >= {PRIME_MIN_T}"); }
2099        for (s, c) in caches.iter().enumerate() {
2100            assert!(c.pos + ts[s] <= c.max_ctx, "prime_cache_batch: prompt exceeds cache max_ctx");
2101        }
2102        let total: usize = ts.iter().sum();
2103        let offs: Vec<usize> = ts.iter().scan(0usize, |a, &t| { let o = *a; *a += t; Some(o) }).collect();
2104        // per-seq positions (fresh: 0..T_s; continuation: pos0..pos0+T_s)
2105        let pos_ds: Vec<CudaSlice<i32>> = ts.iter().zip(&pos0s)
2106            .map(|(&t, &p0)| e.htod_i32(&(p0 as i32..(p0 + t) as i32).collect::<Vec<_>>()))
2107            .collect::<Result<_, _>>()?;
2108        // split a concat [total, dim] buffer into per-seq copies
2109        let split = |e: &Engine, y: &CudaSlice<f32>, dim: usize|
2110                     -> Result<Vec<CudaSlice<f32>>, Box<dyn std::error::Error>> {
2111            let mut out = Vec::with_capacity(b);
2112            for s in 0..b {
2113                let mut ys = e.uninit(ts[s] * dim)?;
2114                e.copy_view_into(&mut ys, 0, &y.slice(offs[s] * dim..(offs[s] + ts[s]) * dim), ts[s] * dim)?;
2115                out.push(ys);
2116            }
2117            Ok(out)
2118        };
2119
2120        let cat_tokens: Vec<u32> = prompts.iter().flat_map(|p| p.iter().copied()).collect();
2121        let mut x = self.embed(e, &cat_tokens)?;   // [total, n_embd]
2122        for (il, layer) in self.layers.iter().enumerate() {
2123            let mut h = e.uninit(total * n_embd)?;
2124            let mut hx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
2125            e.rms_norm_f16out(&x, layer.attn_norm.float_data(), &mut h, &mut hx16, n_embd, total, eps)?;
2126            // mixer: projection GROUP on the concat (m = total), stateful core per seq
2127            let mut mixed = e.uninit(total * n_embd)?;
2128            match &layer.mixer {
2129                Mixer::Full(fa) => {
2130                    let g3 = e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], &h, &hx16, total)?;
2131                    // task #18 (attn side): the WHOLE attn core is varlen for fresh gated
2132                    // batches — split/QK-norm/RoPE/append (attn_pre_vl8, view inputs: the
2133                    // q/k/v split copies vanish) + ONE varlen FA. Per-block math identical
2134                    // everywhere (bit-gateable); MEMRA_FA_VL=0 or a non-bf16kv config falls
2135                    // back to the per-seq dispatch.
2136                    let geometry = self.cfg.full_attention_geometry_at(il as u32);
2137                    let (n_head, n_head_kv, head_dim) = (
2138                        geometry.n_head as usize,
2139                        geometry.n_head_kv as usize,
2140                        geometry.head_dim_k as usize,
2141                    );
2142                    let fa_scale = geometry.attention_scale();
2143                    let use_favl = !carried
2144                        && (2..=8).contains(&b)
2145                        && (head_dim == 256 || head_dim == 128)
2146                        && geometry.attention_gate
2147                            == memra_gguf::config::AttentionGateKind::FusedQ
2148                        && std::env::var("MEMRA_NOFA").is_err()
2149                        && std::env::var("MEMRA_FA_FLOOR").is_err()
2150                        && std::env::var("MEMRA_FA_PP_W2").as_deref() != Ok("1")
2151                        && std::env::var("MEMRA_FA_BF16KV").as_deref() != Ok("0")
2152                        && std::env::var("MEMRA_FA_VL").as_deref() != Ok("0");
2153                    if use_favl {
2154                        let (qf_w, kf_w, vf_w) =
2155                            (fa.wq.out_features(), fa.wk.out_features(), fa.wv.out_features());
2156                        struct APre {
2157                            q: CudaSlice<f32>, gate: Option<CudaSlice<f32>>,
2158                            qn: CudaSlice<f32>, kn: CudaSlice<f32>,
2159                        }
2160                        let mut aps = Vec::with_capacity(b);
2161                        for &t in ts.iter().take(b) {
2162                            aps.push(APre {
2163                                q: e.uninit(t * n_head * head_dim)?,
2164                                gate: Some(e.uninit(t * n_head * head_dim)?),
2165                                qn: e.uninit(t * n_head * head_dim)?,
2166                                kn: e.uninit(t * n_head_kv * head_dim)?,
2167                            });
2168                        }
2169                        let (kv_dim_k, kv_dim_v, ktb, vtb) = {
2170                            let kvl = caches[0].kv[il].as_ref().unwrap();
2171                            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes)
2172                        };
2173                        let pargs: Vec<crate::AttnPreVl> = (0..b).map(|s| {
2174                            let (o, t) = (offs[s], ts[s]);
2175                            let kvl = caches[s].kv[il].as_ref().unwrap();
2176                            assert!(kvl.len == 0 && kvl.len + t <= caches[s].max_ctx,
2177                                    "prime_cache_batch attn vl: fresh + capacity");
2178                            crate::AttnPreVl {
2179                                qf: e.addr_f32v(&g3[0].slice(o * qf_w..(o + t) * qf_w)),
2180                                kf: e.addr_f32v(&g3[1].slice(o * kf_w..(o + t) * kf_w)),
2181                                vf: e.addr_f32v(&g3[2].slice(o * vf_w..(o + t) * vf_w)),
2182                                q: e.addr_f32(&aps[s].q),
2183                                gate: e.addr_f32(aps[s].gate.as_ref().unwrap()),
2184                                qn: e.addr_f32(&aps[s].qn), kn: e.addr_f32(&aps[s].kn),
2185                                kc: e.addr_u8(&kvl.k), vc: e.addr_u8(&kvl.v),
2186                                t: t as i32, pad: 0,
2187                            }
2188                        }).collect();
2189                        e.attn_pre_vl8(&pargs, fa.q_norm.float_data(), fa.k_norm.float_data(),
2190                                       head_dim, geometry.n_rot as usize, n_head, n_head_kv,
2191                                       self.cfg.rms_eps, geometry.rope_base, 1.0,
2192                                       kv_dim_k, kv_dim_v, ktb, vtb)?;
2193                        for s in 0..b {
2194                            let kvl = caches[s].kv[il].as_mut().unwrap();
2195                            kvl.len += ts[s];
2196                            let new_len = kvl.len as i32;
2197                            e.set_i32_one(&mut kvl.len_d, new_len)?;
2198                        }
2199                        let mut attns = Vec::with_capacity(b);
2200                        let mut mirrors = Vec::with_capacity(b);
2201                        for &t in ts.iter().take(b) {
2202                            attns.push(e.uninit(t * n_head * head_dim)?);
2203                            let n = t * n_head_kv * head_dim;
2204                            mirrors.push((e.alloc_u8_uninit(n * 2)?, e.alloc_u8_uninit(n * 2)?));
2205                        }
2206                        // FA3 batched twin (round 31): TMA-swizzled wgmma vl when the
2207                        // promoted single-seq config is on; else the mma favl.
2208                        let fa3_on = match std::env::var("MEMRA_FA3").as_deref() {
2209                            Ok("0") => false,
2210                            Ok("1") => true,
2211                            _ => cfg!(memra_hopper_mma),
2212                        };
2213                        if fa3_on {
2214                            let mut q16s = Vec::with_capacity(b);
2215                            let mut v16s = Vec::with_capacity(b);
2216                            for s in 0..b {
2217                                let t = ts[s];
2218                                let mut q16 = e.alloc_u8_uninit(t * n_head * head_dim * 2)?;
2219                                e.f32_to_bf16_into(&aps[s].qn, &mut q16, t * n_head * head_dim)?;
2220                                let mut k16 = e.alloc_u8_uninit(t * n_head_kv * head_dim * 2)?;
2221                                e.f32_to_bf16_into(&aps[s].kn, &mut k16, t * n_head_kv * head_dim)?;
2222                                let mut v16 = e.alloc_u8_uninit(t * n_head_kv * head_dim * 2)?;
2223                                e.f32_to_bf16_v(&g3[2].slice(offs[s] * vf_w..(offs[s] + t) * vf_w),
2224                                                &mut v16, t * n_head_kv * head_dim)?;
2225                                q16s.push(q16);
2226                                v16s.push((k16, v16));
2227                            }
2228                            let mut qp = [core::ptr::null::<core::ffi::c_void>(); 8];
2229                            let mut kp = qp;
2230                            let mut vp = qp;
2231                            let mut op = [core::ptr::null_mut::<f32>(); 8];
2232                            let mut tsv = [0i32; 8];
2233                            for s in 0..b {
2234                                qp[s] = e.addr_u8(&q16s[s]) as *const core::ffi::c_void;
2235                                kp[s] = e.addr_u8(&v16s[s].0) as *const core::ffi::c_void;
2236                                vp[s] = e.addr_u8(&v16s[s].1) as *const core::ffi::c_void;
2237                                op[s] = e.addr_f32(&attns[s]) as *mut f32;
2238                                tsv[s] = ts[s] as i32;
2239                            }
2240                            let rc = unsafe {
2241                                crate::fa3_vl_raw(qp.as_ptr(), kp.as_ptr(), vp.as_ptr(), op.as_ptr(),
2242                                                  tsv.as_ptr(), b as i32, n_head as i32,
2243                                                  n_head_kv as i32, head_dim as i32, fa_scale,
2244                                                  e.stream().cu_stream() as *mut core::ffi::c_void)
2245                            };
2246                            if rc != 0 {
2247                                return Err(format!("memra_fa3_vl rc={rc}").into());
2248                            }
2249                        } else {
2250                            let fargs: Vec<crate::FaSeqVl> = (0..b).map(|s| crate::FaSeqVl {
2251                                q: e.addr_f32(&aps[s].qn), k16: e.addr_u8(&mirrors[s].0),
2252                                v16: e.addr_u8(&mirrors[s].1), o: e.addr_f32(&attns[s]),
2253                                kf: e.addr_f32(&aps[s].kn),
2254                                vf: e.addr_f32v(&g3[2].slice(offs[s] * vf_w..(offs[s] + ts[s]) * vf_w)),
2255                                t: ts[s] as i32, pad: 0,
2256                            }).collect();
2257                            e.fa_prefill_vl8(&fargs, head_dim, n_head, n_head_kv, fa_scale)?;
2258                        }
2259                        for (s, attn) in attns.into_iter().enumerate() {
2260                            let (attn_g, ag16) = self.full_attn_prime_post_fa(
2261                                e, attn, &aps[s].gate, ts[s], n_head, head_dim)?;
2262                            let mut done = false;
2263                            if let Some(xh) = &ag16 {
2264                                done = e.try_f16_gemm_pre_into_off(&fa.wo, xh, ts[s], &mut mixed, offs[s] * n_embd)?;
2265                            }
2266                            if !done {
2267                                let m = e.matmul(&fa.wo, &attn_g, ts[s])?;
2268                                e.copy_into(&mut mixed, offs[s] * n_embd, &m, ts[s] * n_embd)?;
2269                            }
2270                        }
2271                    } else {
2272                        let mut parts: Vec<Vec<CudaSlice<f32>>> = (0..b).map(|_| Vec::new()).collect();
2273                        for (w, y) in [&fa.wq, &fa.wk, &fa.wv].iter().zip(g3) {
2274                            for (s, ys) in split(e, &y, w.out_features())?.into_iter().enumerate() {
2275                                parts[s].push(ys);
2276                            }
2277                        }
2278                        for (s, g3s) in parts.into_iter().enumerate() {
2279                            // task #16 gather removal: wo writes into `mixed` at offs[s] directly.
2280                            let (attn_g, ag16) = self.full_attn_prime_core_inner(
2281                                e, fa, g3s, &pos_ds[s], ts[s], caches[s], il)?;
2282                            let mut done = false;
2283                            if let Some(xh) = &ag16 {
2284                                done = e.try_f16_gemm_pre_into_off(&fa.wo, xh, ts[s], &mut mixed, offs[s] * n_embd)?;
2285                            }
2286                            if !done {
2287                                let m = e.matmul(&fa.wo, &attn_g, ts[s])?;
2288                                e.copy_into(&mut mixed, offs[s] * n_embd, &m, ts[s] * n_embd)?;
2289                            }
2290                        }
2291                    }
2292                }
2293                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
2294                Mixer::Linear(la) => {
2295                    // task #16: NO split copies (cores read row-offset views of the concat
2296                    // outputs; out-GEMMs write into `mixed` at offs[s]). task #18: the core
2297                    // itself is BATCHED — per-seq prep/K1-K3, then ONE varlen K4 + ONE
2298                    // varlen K5 launch for all sequences.
2299                    let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
2300                    let g4 = e.matmul_group_xh(&ws, &h, &hx16, total)?;
2301                    let outs = self.linear_attn_prime_core_batch(e, la, &g4, &offs, &ts, caches, il)?;
2302                    for (s, (gn, gn16)) in outs.into_iter().enumerate() {
2303                        let (o, t) = (offs[s], ts[s]);
2304                        let mut done = false;
2305                        if let Some(xh) = &gn16 {
2306                            done = e.try_f16_gemm_pre_into_off(&la.ssm_out, xh, t, &mut mixed, o * n_embd)?;
2307                        }
2308                        if !done {
2309                            let m = e.matmul(&la.ssm_out, &gn, t)?;
2310                            e.copy_into(&mut mixed, o * n_embd, &m, t * n_embd)?;
2311                        }
2312                    }
2313                }
2314            }
2315            let mut x1 = e.uninit(total * n_embd)?;
2316            let mut z = e.uninit(total * n_embd)?;
2317            let mut zx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
2318            e.add_rms_norm_f16out(&x, &mixed, layer.post_attn_norm.float_data(),
2319                                  &mut x1, &mut z, &mut zx16, n_embd, total, eps)?;
2320            let ffn_out = match &layer.ffn {
2321                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
2322                    let n_ff = ffn_gate.out_features();
2323                    let mut g2 = e.matmul_group_xh(&[ffn_gate, ffn_up], &z, &zx16, total)?;
2324                    let up = g2.pop().unwrap();
2325                    let gate = g2.pop().unwrap();
2326                    let mut act = e.uninit(total * n_ff)?;
2327                    // task #17 (batch trunk): silu twin emits the down GEMM's fp16 operand
2328                    // in-epilogue (nsys round-26: this trunk still paid 32 cvt passes).
2329                    // A clamped layer must skip the plain-SiLU twin (see prime_chunk's note).
2330                    let d_lim = self.cfg.clamp_shexp_at(il as u32);
2331                    if Self::f16out_on(e, total) && self.cfg.m3.is_none() && d_lim.is_none() {
2332                        let mut a16 = e.alloc_u8_uninit(total * n_ff * 2)?;
2333                        e.silu_mul_f16out(&gate, &up, &mut act, &mut a16, total * n_ff)?;
2334                        match e.try_f16_gemm_pre(ffn_down, &a16, total)? {
2335                            Some(y) => y,
2336                            None => e.matmul(ffn_down, &act, total)?,
2337                        }
2338                    } else {
2339                        Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0, d_lim,
2340                                          &mut act, total * n_ff)?;
2341                        e.matmul(ffn_down, &act, total)?
2342                    }
2343                }
2344                crate::hybrid::Ffn::Moe(m) => {
2345                    self.moe_ffn_il_prefill(e, m, &z, total, il as u16)?
2346                }
2347            };
2348            let mut x2 = e.uninit(total * n_embd)?;
2349            e.add(&x1, &ffn_out, &mut x2, total * n_embd)?;
2350            x = x2;
2351        }
2352        // epilogue per seq (identical math to prime_chunk: norm all rows, lm_head on last row)
2353        let mut hn = e.uninit(total * n_embd)?;
2354        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, total, eps)?;
2355        // batched lm_head (nsys round-26: B sequential m=1 matvecs re-read the 600MB
2356        // lm_head weight B times — 2.2ms at B=6): gather the B last rows and run ONE
2357        // m=B GEMM (f16 lane; falls back to the per-seq matvec when no mirror). The
2358        // f16-vs-mmvq logits delta is the prefill GEMM numeric class — prime_batch_gate's
2359        // argmax battery arbitrates, same as every other prefill GEMM change.
2360        let mut hcat = e.uninit(b * n_embd)?;
2361        for s in 0..b {
2362            let last0 = (offs[s] + ts[s] - 1) * n_embd;
2363            e.copy_view_into(&mut hcat, s * n_embd, &hn.slice(last0..last0 + n_embd), n_embd)?;
2364        }
2365        let logits_cat = if b >= 2 { e.try_f16_gemm(&self.output, &hcat, b)? } else { None };
2366        let logits_host: Option<Vec<f32>> = match &logits_cat {
2367            Some(lc) => Some(e.dtoh(lc)?),
2368            None => None,
2369        };
2370        let n_vocab = self.output.out_features();
2371        let mut hidden_all = if crate::spec::spec_hpost() {
2372            split(e, &hn, n_embd)?
2373        } else {
2374            split(e, &x, n_embd)?
2375        };
2376        let mut out = Vec::with_capacity(b);
2377        for s in 0..b {
2378            let last0 = (offs[s] + ts[s] - 1) * n_embd;
2379            let mut h_seed = e.uninit(n_embd)?;
2380            if !crate::spec::spec_hpost() {
2381                e.copy_view_into(&mut h_seed, 0, &x.slice(last0..last0 + n_embd), n_embd)?;
2382            } else {
2383                e.copy_view_into(&mut h_seed, 0, &hn.slice(last0..last0 + n_embd), n_embd)?;
2384            }
2385            let logits = match &logits_host {
2386                Some(lh) => lh[s * n_vocab..(s + 1) * n_vocab].to_vec(),
2387                None => {
2388                    let mut hlast = e.uninit(n_embd)?;
2389                    e.copy_view_into(&mut hlast, 0, &hn.slice(last0..last0 + n_embd), n_embd)?;
2390                    e.dtoh(&e.matmul(&self.output, &hlast, 1)?)?
2391                }
2392            };
2393            caches[s].pos += ts[s];
2394            out.push((logits, h_seed, hidden_all.remove(0)));
2395        }
2396        Ok(out)
2397    }
2398
2399    /// `full_attn` (batched prefill mixer) + the cache side-effect: append the T post-RoPE K/V
2400    /// rows into the resident quantized KV cache (q8_0 K / q5_1 V) and advance len/len_d. Row
2401    /// bytes are BIT-IDENTICAL to the decode append (same per-warp quant kernel per row; the
2402    /// batched `append_kv_quantized_rows` runs that exact warp math on a (block, token) grid).
2403    /// The attention itself is unchanged prefill math (fa_prefill over the f32 K/V).
2404    ///
2405    /// `seq_end` = the ABSOLUTE end position of the WHOLE prime request (`cache.pos + prompt_len`
2406    /// measured BEFORE the chunk loop starts), i.e. a chunk-size-invariant property of the request.
2407    /// Only step35's SWA arm reads it (`step35_attn_pre_wo`'s doc note explains why keying on the
2408    /// chunk's own `t_kv` made the output depend on MEMRA_PRIME_CHUNK); every other arch ignores it.
2409    #[allow(clippy::too_many_arguments)]
2410    fn full_attn_prime(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>,
2411                       hx: Option<&CudaSlice<u8>>,
2412                       pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize,
2413                       seq_end: usize)
2414                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2415        if self.cfg.step35.is_some() {
2416            return self.step35_attn_prime(e, fa, h, hx, pos_d, t, cache, il, seq_end);
2417        }
2418        // PROJ/CORE SPLIT (task #13, 2026-07-26): the q/k/v group projection is hoisted so
2419        // the cross-request batch driver can run it at m = sum_T over concatenated tokens;
2420        // this single-seq path composes proj+core identically (byte-for-byte the old body).
2421        // task #14: `hx` = the norm-fused fp16 twin of `h` (skips the convert launch).
2422        let g3 = match hx {
2423            Some(xh) => e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], h, xh, t)?,
2424            None => e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?,
2425        };
2426        self.full_attn_prime_core(e, fa, g3, pos_d, t, cache, il)
2427    }
2428
2429    /// Everything after the q/k/v projections (split/QK-norm/RoPE/FA/gate/append + wo).
2430    /// `g3` = matmul_group([wq, wk, wv]) output rows for THIS sequence.
2431    /// Composes inner + wo (== the pre-split core; every existing caller unchanged).
2432    fn full_attn_prime_core(&self, e: &Engine, fa: &FullAttnLayer, g3: Vec<CudaSlice<f32>>,
2433                            pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize)
2434                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2435        let (attn_g, ag16) = self.full_attn_prime_core_inner(e, fa, g3, pos_d, t, cache, il)?;
2436        if let Some(xh) = &ag16 {
2437            if let Some(y) = e.try_f16_gemm_pre(&fa.wo, xh, t)? {
2438                return Ok(y);
2439            }
2440        }
2441        Ok(e.matmul(&fa.wo, &attn_g, t)?)
2442    }
2443
2444    fn full_attn_prime_core_inner(&self, e: &Engine, fa: &FullAttnLayer, g3: Vec<CudaSlice<f32>>,
2445                            pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize)
2446                            -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2447        let cfg = &self.cfg;
2448        let geometry = cfg.full_attention_geometry_at(il as u32);
2449        let n_head = geometry.n_head as usize;
2450        let n_head_kv = geometry.n_head_kv as usize;
2451        let head_dim = geometry.head_dim_k as usize;
2452        let scale = geometry.attention_scale();
2453        let (pre, base_len) = self.full_attn_prime_pre_fa(e, fa, g3, pos_d, t, cache, il)?;
2454        let AttnPre { q, k, v, gate } = pre;
2455        let mut attn = e.uninit(t * n_head * head_dim)?;
2456        self.full_attn_prime_fa_dispatch(e, &q, &k, &v, &mut attn, base_len, t, cache, il,
2457                                         head_dim, n_head, n_head_kv, scale)?;
2458        self.full_attn_prime_post_fa(e, attn, &gate, t, n_head, head_dim)
2459    }
2460
2461    /// task #18 (attn side): projections tail through KV append — everything before the
2462    /// attention kernel. Returns the post-rope q/k, v, optional out-gate, and the KV rows
2463    /// present BEFORE this chunk's append (base_len; 0 == fresh).
2464    #[allow(clippy::type_complexity)]
2465    fn full_attn_prime_pre_fa(&self, e: &Engine, fa: &FullAttnLayer, mut g3: Vec<CudaSlice<f32>>,
2466                            pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize)
2467                            -> Result<(AttnPre, usize), Box<dyn std::error::Error>> {
2468        let cfg = &self.cfg;
2469        let geometry = cfg.full_attention_geometry_at(il as u32);
2470        let n_head = geometry.n_head as usize;
2471        let n_head_kv = geometry.n_head_kv as usize;
2472        let head_dim = geometry.head_dim_k as usize;
2473        let eps = cfg.rms_eps;
2474
2475        // qwen35 fuses [q|gate] per head in wq (2*head_dim stride); M3/Hy3 have NO output gate
2476        // (attention_output_gate=false) — wq out = n_head*head_dim exactly, and q_gate_split
2477        // would read 2x out of bounds. `gated` keys both the split and the sigmoid epilogue.
2478        let gated = geometry.attention_gate
2479            == memra_gguf::config::AttentionGateKind::FusedQ;
2480        let v = g3.pop().unwrap();
2481        let mut k = g3.pop().unwrap();
2482        let qf = g3.pop().unwrap();
2483        let (mut q, gate) = if gated {
2484            let mut q = e.uninit(t * n_head * head_dim)?;
2485            let mut gate = e.uninit(t * n_head * head_dim)?;
2486            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
2487            (q, Some(gate))
2488        } else {
2489            (qf, None)
2490        };
2491
2492        let mut qn = e.uninit(t * n_head * head_dim)?;
2493        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head * t, eps)?;
2494        q = qn;
2495        let mut kn = e.uninit(t * n_head_kv * head_dim)?;
2496        e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, n_head_kv * t, eps)?;
2497        k = kn;
2498        let rope_dims = geometry.n_rot as usize;
2499        e.rope_neox(&mut q, pos_d, head_dim, rope_dims, n_head, t, geometry.rope_base, 1.0)?;
2500        e.rope_neox(&mut k, pos_d, head_dim, rope_dims, n_head_kv, t, geometry.rope_base, 1.0)?;
2501
2502        // CACHE SIDE-EFFECT: append the T post-rope K/V token rows (token-major [T, kv_dim] ==
2503        // the cache row layout) quantized into cache.kv[il], then advance len + device len_d.
2504        {
2505            let kvl = cache.kv[il].as_mut().unwrap();
2506            assert!(kvl.len + t <= cache.max_ctx, "prime_cache: KV overflow");
2507            e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len, t,
2508                                       kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
2509                                       crate::Engine::kv_fp8_on())?;
2510            kvl.len += t;
2511            let new_len = kvl.len as i32;
2512            e.set_i32_one(&mut kvl.len_d, new_len)?;
2513        }
2514
2515        let base_len = {
2516            let kvl = cache.kv[il].as_ref().unwrap();
2517            kvl.len - t   // KV rows present BEFORE this chunk's append above
2518        };
2519        Ok((AttnPre { q, k, v, gate }, base_len))
2520    }
2521
2522    /// batched prefill attention. FRESH prime (no past KV): unchanged forward_last math over
2523    /// the f32 K/V of this batch. CONTINUATION chunk (past KV present): the chunk's queries
2524    /// must attend to [0 .. base+t) — run fa_prefill_view over the resident QUANTIZED cache
2525    /// (the spec-verify pattern; kernel's causal mask offsets by T_kv-T). Numerically this
2526    /// reads q8_0/q5_1-dequantized K/V for the past AND the current chunk — the same class as
2527    /// decode reading the cache; the run-gen/first-16 battery is the accuracy authority.
2528    #[allow(clippy::too_many_arguments)]
2529    fn full_attn_prime_fa_dispatch(&self, e: &Engine, q: &CudaSlice<f32>, k: &CudaSlice<f32>,
2530                            v: &CudaSlice<f32>, attn: &mut CudaSlice<f32>, base_len: usize,
2531                            t: usize, cache: &mut Cache, il: usize,
2532                            head_dim: usize, n_head: usize, n_head_kv: usize, scale: f32)
2533                            -> Result<(), Box<dyn std::error::Error>> {
2534        // GRAIN-FREE CHUNK-INVARIANCE FIX (lane/chunkinv-flip, 2026-08-05): the base_len == 0
2535        // f32 special case (fa_prefill over this batch's f32 K/V) is DROPPED. pre_fa appends
2536        // the chunk's quantized rows into cache.kv[il] BEFORE this dispatch, so chunk 0 can
2537        // attend through the quantized cache exactly like every later chunk (quantize-then-
2538        // attend). One numeric class for every row => the chunk size cannot decide where a
2539        // precision edge falls, so chunked prefill is reduction-order-stable with NO grain
2540        // knob (the stronger fix VERDICT.md filed; supersedes the MEMRA_PRIME_INVARIANT door's
2541        // pin-the-boundary approach).
2542        // MEMRA_PRIME_F32CHUNK0=1 is the ROLLBACK SEAM to the old arithmetic (chunk 0 attends
2543        // f32 K/V) — flags-doctrine rollback door AND the chunkinv gate's canary injection:
2544        // with the fix unconditional, only re-introducing the class edge can prove the gate
2545        // still detects the mechanism. Never on in a measured default run.
2546        if base_len == 0 && std::env::var("MEMRA_PRIME_F32CHUNK0").as_deref() == Ok("1") {
2547            if std::env::var("MEMRA_NOFA").is_ok() || !(head_dim == 256 || head_dim == 128) {
2548                e.sdpa_naive(q, k, v, attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
2549            } else {
2550                e.fa_prefill(q, k, v, attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
2551            }
2552            return Ok(());
2553        }
2554        let kvl = cache.kv[il].as_ref().unwrap();
2555        let t_kv = base_len + t;
2556        let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
2557        let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
2558        // fa_prefill_q/_qw twins are stamped for head_dim 256 (qwen35) and 128 (M3) only;
2559        // other dims (and MEMRA_NOFA) take the naive quantized-view SDPA — SAME cache bytes,
2560        // same numeric class, so the uniform contract holds on the fallback too.
2561        if std::env::var("MEMRA_NOFA").is_ok() || !(head_dim == 256 || head_dim == 128) {
2562            e.sdpa_naive_quantized_view(q, &k_view, &v_view, attn, head_dim, n_head,
2563                                        n_head_kv, t, t_kv, scale, true,
2564                                        kvl.k_tok_bytes, kvl.v_tok_bytes)?;
2565            return Ok(());
2566        }
2567        // ARC B (2026-07-05): dequant-once workspace, DEFAULT ON. fa_prefill_q's inline
2568        // dequant re-reads+re-dequants the whole quantized KV stream from every one of the
2569        // T/64 x n_head CTAs (64x+ redundant at chunk=4096; 30.5% of the 32k prime wall).
2570        // fa_prefill_view_ws dequants K/V ONCE into a resident bf16 workspace then runs the
2571        // bit-identical bf16 twin (fa_prefill_qw) — same staged values, same FP order, token-
2572        // identical output (gate: MEMRA_PRIME_CHUNK=4096 ws-on vs ws-off vs monolithic).
2573        // MEMRA_PRIME_DEQW=0 reverts to the inline-dequant kernel.
2574        let deqw = std::env::var("MEMRA_PRIME_DEQW").map(|v| v != "0").unwrap_or(true);
2575        if deqw {
2576            e.fa_prefill_view_ws(q, &k_view, &v_view, attn, head_dim, n_head, n_head_kv,
2577                                 t, t_kv, scale, true, kvl.k_tok_bytes, kvl.v_tok_bytes,
2578                                 crate::Engine::kv_fp8_on())?;
2579        } else {
2580            e.fa_prefill_view(q, &k_view, &v_view, attn, head_dim, n_head, n_head_kv,
2581                              t, t_kv, scale, true, kvl.k_tok_bytes, kvl.v_tok_bytes,
2582                              crate::Engine::kv_fp8_on())?;
2583        }
2584        Ok(())
2585    }
2586
2587    /// task #17: sig_mul_f16out fuses [sigmoid + mul + f16 convert] into one launch
2588    /// (bit-identical composition) and hands wo its fp16 operand directly.
2589    fn full_attn_prime_post_fa(&self, e: &Engine, attn: CudaSlice<f32>,
2590                            gate: &Option<CudaSlice<f32>>, t: usize,
2591                            n_head: usize, head_dim: usize)
2592                            -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2593        let (attn_g, ag16) = match gate {
2594            Some(gate) => {
2595                let n = t * n_head * head_dim;
2596                let mut ag = e.uninit(n)?;
2597                if Self::f16out_on(e, t) {
2598                    let mut a16 = e.alloc_u8_uninit(n * 2)?;
2599                    e.sig_mul_f16out(&attn, gate, &mut ag, &mut a16, n)?;
2600                    (ag, Some(a16))
2601                } else {
2602                    let mut gsig = e.uninit(n)?;
2603                    e.sigmoid(gate, &mut gsig, n)?;
2604                    e.mul(&attn, &gsig, &mut ag, n)?;
2605                    (ag, None)
2606                }
2607            }
2608            None => (attn, None),
2609        };
2610        Ok((attn_g, ag16))
2611    }
2612
2613    /// STATEFUL batched linear-attention prime: `linear_attn`'s prefill-dispatch pass (normal
2614    /// `e.matmul` — GEMM at m>=16 — plus the prefill repack/L2/glog kernels) but with the state
2615    /// carried THROUGH the cache like the spec verify does: carried-ring conv
2616    /// (ssm_conv1d_tm_state writes the final ring back) + ONE gdn_scan from cache.recur[il]'s
2617    /// current state (zero at a fresh prime) whose final state ping-pongs back into the cache.
2618    /// Wiring mirrors `linear_attn_verify_t` (spec.rs); dispatch mirrors `linear_attn` (prefill).
2619    fn linear_attn_prime(&self, e: &Engine, la: &LinearAttnLayer, h: &CudaSlice<f32>,
2620                         hx: Option<&CudaSlice<u8>>, t: usize,
2621                         cache: &mut Cache, il: usize)
2622                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2623        // PROJ/CORE SPLIT (task #13): see full_attn_prime — same hoist for the GDN 4-tuple.
2624        let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
2625        let g4 = match hx {
2626            Some(xh) => e.matmul_group_xh(&ws, h, xh, t)?,
2627            None => e.matmul_group(&ws, h, t)?,
2628        };
2629        self.linear_attn_prime_core(e, la, g4, t, cache, il)
2630    }
2631
2632    /// Everything after the GDN 4-tuple projections (conv/chunk stack/gated norm + ssm_out).
2633    fn linear_attn_prime_core(&self, e: &Engine, la: &LinearAttnLayer, mut g4: Vec<CudaSlice<f32>>,
2634                              t: usize, cache: &mut Cache, il: usize)
2635                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2636        self.linear_attn_prime_core_pad(e, la, g4.drain(..).collect(), t, cache, il, None)
2637    }
2638
2639    /// task #14: `pad_len` = device true length for PADDED prime graphs. Pads become
2640    /// identity GDN steps (gdn_pad_mask zeroes beta/g_log past the true length) and the
2641    /// conv ring writes back from the true tail. None = classic path, byte-identical.
2642    #[allow(clippy::too_many_arguments)]
2643    fn linear_attn_prime_core_pad_inner(&self, e: &Engine, la: &LinearAttnLayer, mut g4: Vec<CudaSlice<f32>>,
2644                              t: usize, cache: &mut Cache, il: usize,
2645                              pad_len: Option<&CudaSlice<i32>>)
2646                              -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2647        // shim over the view twin (task #16): full-range views of the owned buffers.
2648        let ssm = self.cfg.ssm.as_ref().unwrap();
2649        let d_state = ssm.state_size as usize;
2650        let num_k = ssm.group_count as usize;
2651        let num_v = ssm.time_step_rank as usize;
2652        let key_dim = d_state * num_k;
2653        let value_dim = d_state * num_v;
2654        let conv_dim = key_dim * 2 + value_dim;
2655        let alpha = g4.pop().unwrap();                   // [T, num_v]
2656        let beta_raw = g4.pop().unwrap();                // [T, num_v]
2657        let z = g4.pop().unwrap();                       // [T, value_dim]
2658        let qkv_mixed = g4.pop().unwrap();               // [T, conv_dim] token-major
2659        self.linear_attn_prime_core_pad_view(
2660            e, la,
2661            &qkv_mixed.slice(0..t * conv_dim), &z.slice(0..t * value_dim),
2662            &beta_raw.slice(0..t * num_v), &alpha.slice(0..t * num_v),
2663            t, cache, il, pad_len)
2664    }
2665
2666    /// task #18: the GDN prep stage (conv + repack + l2 x2 + sigmoid + glog + pad-mask) —
2667    /// shared verbatim by the per-seq scan path and the varlen batched path.
2668    #[allow(clippy::too_many_arguments)]
2669    fn linear_attn_gdn_prep(&self, e: &Engine, la: &LinearAttnLayer,
2670                            qkv_mixed: &cudarc::driver::CudaView<f32>,
2671                            beta_raw: &cudarc::driver::CudaView<f32>,
2672                            alpha: &cudarc::driver::CudaView<f32>,
2673                            t: usize, cache: &mut Cache, il: usize,
2674                            pad_len: Option<&CudaSlice<i32>>)
2675                            -> Result<GdnPrep, Box<dyn std::error::Error>> {
2676        let cfg = &self.cfg;
2677        let ssm = cfg.ssm.as_ref().unwrap();
2678        let d_state = ssm.state_size as usize;       // 128
2679        let num_k = ssm.group_count as usize;        // 16
2680        let num_v = ssm.time_step_rank as usize;     // 32
2681        let d_conv = ssm.conv_kernel as usize;       // 4
2682        let key_dim = d_state * num_k;               // 2048
2683        let value_dim = d_state * num_v;             // 4096
2684        let conv_dim = key_dim * 2 + value_dim;      // 8192
2685        let eps = cfg.rms_eps;
2686        debug_assert!(t >= d_conv - 1, "stateful conv needs T >= pad (PRIME_MIN_T gates)");
2687
2688        // conv with CARRIED ring state + ring roll (state read + final-window write-back).
2689        // task #18 conv-fuse (default ON): conv + SiLU + repack in one pass — the 67MB
2690        // conv_out intermediate and its transposed re-read disappear (values bit-identical).
2691        // MEMRA_CONV_FUSE=0 reverts to the two-kernel chain.
2692        let rl = cache.recur[il].as_mut().unwrap();
2693        let hk = Self::gdn_hk(e, t, num_v, num_k);
2694        let conv_fuse = std::env::var("MEMRA_CONV_FUSE").as_deref() != Ok("0");
2695        let hk = if conv_fuse { hk } else { num_v };   // de-broadcast rides the fused conv
2696        let mut q_g = e.uninit(d_state * hk * t)?;
2697        let mut k_g = e.uninit(d_state * hk * t)?;
2698        let mut v_g = e.uninit(d_state * num_v * t)?;
2699        if conv_fuse {
2700            e.ssm_conv1d_gdn_state_pad(qkv_mixed, &mut rl.conv_state, la.ssm_conv1d.float_data(),
2701                                  &mut q_g, &mut k_g, &mut v_g,
2702                                  conv_dim, t, d_conv, d_state, num_v, num_k, key_dim, hk, pad_len)?;
2703        } else {
2704            let mut conv_out = e.uninit(conv_dim * t)?;      // [conv_dim, T] channel-major, SiLU
2705            e.ssm_conv1d_tm_state_pad_v(qkv_mixed, &mut rl.conv_state, la.ssm_conv1d.float_data(),
2706                                  &mut conv_out, conv_dim, t, d_conv, pad_len)?;
2707            e.qkv_to_gdn_repack(&conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t)?;
2708        }
2709        let mut q_l2 = e.uninit(d_state * hk * t)?;
2710        // mirror-fold (round 35): q's bf16 twin (wgmma K45/K2 A-operand) in-epilogue too.
2711        // Emitted only where a consumer exists (the wgmma config) — on other arches the
2712        // alloc + epilogue stores would be pure waste.
2713        let qb16 = if Engine::l2_v2_on(d_state) && e.gdn_wgmma_on(32) {
2714            let mut qb = e.alloc_u8_uninit(d_state * hk * t * 2)?;
2715            e.l2_norm_pp(&q_g, &mut q_l2, Some(&mut qb), d_state, hk * t, eps)?;
2716            Some(qb)
2717        } else {
2718            e.l2_norm_pp(&q_g, &mut q_l2, None, d_state, hk * t, eps)?;
2719            None
2720        };
2721        let mut k_l2 = e.uninit(d_state * hk * t)?;
2722        // mirror-fold: emit k's bf16 twin (the chunked-scan kb16 mirror) in-epilogue
2723        let kb16 = if Engine::l2_v2_on(d_state) {
2724            let mut kb = e.alloc_u8_uninit(d_state * hk * t * 2)?;
2725            e.l2_norm_pp(&k_g, &mut k_l2, Some(&mut kb), d_state, hk * t, eps)?;
2726            Some(kb)
2727        } else {
2728            e.l2_norm_pp(&k_g, &mut k_l2, None, d_state, hk * t, eps)?;
2729            None
2730        };
2731        let mut beta = e.uninit(t * num_v)?;
2732        e.sigmoid_v(beta_raw, &mut beta, t * num_v)?;
2733        let mut g_log = e.uninit(t * num_v)?;
2734        e.gdn_glog_v(alpha, la.ssm_dt.float_data(), la.ssm_a.float_data(), &mut g_log, num_v, t)?;
2735        if let Some(len_d) = pad_len {
2736            e.gdn_pad_mask(&mut beta, &mut g_log, len_d, num_v, t)?;
2737        }
2738        Ok(GdnPrep { hk, q_l2, k_l2, v_g, beta, g_log, kb16, qb16 })
2739    }
2740
2741    /// task #18: batched GDN mixer core — per-seq prep + K1-K3, then ONE varlen K4 and
2742    /// ONE varlen K5 launch for all B sequences (full-machine occupancy vs B underfilled
2743    /// per-seq trains). Per-block math identical to the per-seq path (bit-gateable);
2744    /// MEMRA_GDN_VL=0 or a non-mma/non-C32 config falls back to the per-seq loop.
2745    #[allow(clippy::too_many_arguments)]
2746    fn linear_attn_prime_core_batch(&self, e: &Engine, la: &LinearAttnLayer,
2747                                    g4: &[CudaSlice<f32>], offs: &[usize], ts: &[usize],
2748                                    caches: &mut [&mut Cache], il: usize)
2749                                    -> Result<Vec<(CudaSlice<f32>, Option<CudaSlice<u8>>)>, Box<dyn std::error::Error>> {
2750        let ssm = self.cfg.ssm.as_ref().unwrap();
2751        let d_state = ssm.state_size as usize;
2752        let num_k = ssm.group_count as usize;
2753        let num_v = ssm.time_step_rank as usize;
2754        let key_dim = d_state * num_k;
2755        let value_dim = d_state * num_v;
2756        let conv_dim = key_dim * 2 + value_dim;
2757        let eps = self.cfg.rms_eps;
2758        let scale = 1.0 / (d_state as f32).sqrt();
2759        let b = ts.len();
2760        let c = Engine::gdn_chunk_size();
2761        // CONTINUATION batches (increment (b)) take the per-seq stateful pad_view twin
2762        // below — the varlen K4/K5 chain is fresh-only (zero initial state assumed).
2763        let carried = caches.iter().any(|c| c.pos > 0);
2764        let use_vl = !carried
2765            && (2..=8).contains(&b)
2766            && Engine::gdn_chunked_enabled() && ts.iter().all(|&t| t >= 16)
2767            && e.gdn_mma_enabled(c)
2768            && std::env::var("MEMRA_GDN_VL").as_deref() != Ok("0");
2769        if !use_vl {
2770            return (0..b).map(|s| {
2771                let (o, t) = (offs[s], ts[s]);
2772                self.linear_attn_prime_core_pad_view(
2773                    e, la,
2774                    &g4[0].slice(o * conv_dim..(o + t) * conv_dim),
2775                    &g4[1].slice(o * value_dim..(o + t) * value_dim),
2776                    &g4[2].slice(o * num_v..(o + t) * num_v),
2777                    &g4[3].slice(o * num_v..(o + t) * num_v),
2778                    t, caches[s], il, None)
2779            }).collect();
2780        }
2781        // increment 3: the ENTIRE core is varlen — allocs only per seq, then 13 launches
2782        // total for the whole batch: [conv, ring, repack, l2(q+k), gate-prep] +
2783        // [k-mirror, K1, K2, K3, w-mirror, K4, K5] + [gated-norm tail].
2784        struct SeqBufs {
2785            conv_out: CudaSlice<f32>, q_g: CudaSlice<f32>, k_g: CudaSlice<f32>, v_g: CudaSlice<f32>,
2786            q_l2: CudaSlice<f32>, k_l2: CudaSlice<f32>, beta: CudaSlice<f32>, g_log: CudaSlice<f32>,
2787            gn: CudaSlice<f32>, gn16: CudaSlice<u8>,
2788        }
2789        let d_conv = ssm.conv_kernel as usize;
2790        let f16o = Self::f16out_on(e, 16);
2791        let hk = Self::gdn_hk(e, 16, num_v, num_k);   // vl path is always chunked+mma
2792        let mut sb = Vec::with_capacity(b);
2793        let mut pres = Vec::with_capacity(b);
2794        for &t in ts.iter().take(b) {
2795            sb.push(SeqBufs {
2796                conv_out: e.uninit(conv_dim * t)?,
2797                q_g: e.uninit(d_state * hk * t)?,
2798                k_g: e.uninit(d_state * hk * t)?,
2799                v_g: e.uninit(d_state * num_v * t)?,
2800                q_l2: e.uninit(d_state * hk * t)?,
2801                k_l2: e.uninit(d_state * hk * t)?,
2802                beta: e.uninit(t * num_v)?,
2803                g_log: e.uninit(t * num_v)?,
2804                gn: e.uninit(d_state * num_v * t)?,
2805                gn16: e.alloc_u8_uninit(d_state * num_v * t * 2)?,
2806            });
2807            pres.push(e.gdn_chunk_alloc(num_v, t, c, hk)?);
2808        }
2809        let prep_args: Vec<crate::GdnPrepVl> = (0..b).map(|s| {
2810            let (o, t) = (offs[s], ts[s]);
2811            let rl = caches[s].recur[il].as_ref().unwrap();
2812            crate::GdnPrepVl {
2813                qkv: e.addr_f32v(&g4[0].slice(o * conv_dim..(o + t) * conv_dim)),
2814                conv_state: e.addr_f32(&rl.conv_state),
2815                conv_out: e.addr_f32(&sb[s].conv_out),
2816                q_g: e.addr_f32(&sb[s].q_g), k_g: e.addr_f32(&sb[s].k_g), v_g: e.addr_f32(&sb[s].v_g),
2817                q_l2: e.addr_f32(&sb[s].q_l2), k_l2: e.addr_f32(&sb[s].k_l2),
2818                beta_raw: e.addr_f32v(&g4[2].slice(o * num_v..(o + t) * num_v)),
2819                alpha: e.addr_f32v(&g4[3].slice(o * num_v..(o + t) * num_v)),
2820                beta: e.addr_f32(&sb[s].beta), g_log: e.addr_f32(&sb[s].g_log),
2821                o: e.addr_f32(&pres[s].o),
2822                z: e.addr_f32v(&g4[1].slice(o * value_dim..(o + t) * value_dim)),
2823                gn: e.addr_f32(&sb[s].gn), gn16: e.addr_u8(&sb[s].gn16),
2824                kb16: if Engine::l2_v2_on(d_state) { e.addr_u8(&pres[s].kb16) } else { 0 },
2825                qb16: if Engine::l2_v2_on(d_state) && e.gdn_wgmma_on(c) { e.addr_u8(&pres[s].qb16) } else { 0 },
2826                t: t as i32, pad: 0,
2827            }
2828        }).collect();
2829        let args: Vec<crate::GdnSeqVl> = (0..b).map(|s| {
2830            let rl = caches[s].recur[il].as_ref().unwrap();
2831            crate::GdnSeqVl {
2832                kb16: e.addr_u8(&pres[s].kb16), gcum: e.addr_f32(&pres[s].gcum),
2833                beta: e.addr_f32(&sb[s].beta), u: e.addr_f32(&pres[s].u),
2834                wb16: e.addr_u8(&pres[s].wb16), y: e.addr_u8(&pres[s].y16),
2835                ssnap: e.addr_u8(&pres[s].ssnap16),
2836                state_in: e.addr_f32(&rl.ssm_state), state_out: e.addr_f32(&rl.ssm_state_alt),
2837                q: e.addr_f32(&sb[s].q_l2), p: e.addr_f32(&pres[s].p),
2838                o: e.addr_f32(&pres[s].o),
2839                k: e.addr_f32(&sb[s].k_l2), v: e.addr_f32(&sb[s].v_g),
2840                g: e.addr_f32(&sb[s].g_log), a: e.addr_f32(&pres[s].a),
2841                w: e.addr_f32(&pres[s].w),
2842                t: ts[s] as i32, nc: pres[s].nc as i32,
2843            }
2844        }).collect();
2845        e.gdn_prep_vl8(&prep_args, la.ssm_conv1d.float_data(), la.ssm_dt.float_data(),
2846                       la.ssm_a.float_data(), conv_dim, d_conv, d_state, num_v, num_k, key_dim, hk, eps)?;
2847        // mirror-fold (round 27): l2 v2 emits kb16 in-epilogue; K3's store emits wb16 —
2848        // both standalone mirror launches vanish on the default config.
2849        if !Engine::l2_v2_on(d_state) {
2850            e.gdn_mirror_vl8(&args, num_v, 0, hk)?;
2851        }
2852        // task #22: wgmma-fused vl twins — qb16 mirrors + GdnWVl8 side-struct.
2853        let wq8: Option<crate::GdnWVl8> = if e.gdn_wgmma_on(c) {
2854            // qb16 emitted by the vl l2 mirror-fold when l2-v2 serves; bulk cvt otherwise
2855            if !Engine::l2_v2_on(d_state) {
2856                for s in 0..b {
2857                    e.f32_to_bf16_into(&sb[s].q_l2, &mut pres[s].qb16, d_state * hk * ts[s])?;
2858                }
2859            }
2860            let mut wa = [crate::GdnWVl::default(); 8];
2861            for s in 0..b {
2862                wa[s] = crate::GdnWVl { qb16: e.addr_u8(&pres[s].qb16), pb16: e.addr_u8(&pres[s].pb16) };
2863            }
2864            Some(crate::GdnWVl8(wa))
2865        } else { None };
2866        e.gdn_chunk_k123_vl8(&args, num_v, hk, wq8.as_ref())?;
2867        e.gdn_chunk_vl8(&args, num_v, scale, hk, wq8.as_ref())?;
2868        if f16o {
2869            e.gdn_tail_vl8(&prep_args, la.ssm_norm.float_data(), d_state, num_v, eps)?;
2870        }
2871        // per-seq state swap (+ non-f16out tail fallback)
2872        let mut out = Vec::with_capacity(b);
2873        for (s, bufs) in sb.into_iter().enumerate() {
2874            let rl = caches[s].recur[il].as_mut().unwrap();
2875            std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2876            let (o, t) = (offs[s], ts[s]);
2877            let SeqBufs { mut gn, gn16, .. } = bufs;
2878            if f16o {
2879                out.push((gn, Some(gn16)));
2880            } else {
2881                let z_v = g4[1].slice(o * value_dim..(o + t) * value_dim);
2882                e.gated_rmsnorm_zv(&pres[s].o, la.ssm_norm.float_data(), &z_v, &mut gn,
2883                                   d_state, num_v * t, eps)?;
2884                out.push((gn, None));
2885            }
2886        }
2887        Ok(out)
2888    }
2889
2890    /// task #16: view-consuming GDN prime core — the batched prime hands row-offset
2891    /// views of the CONCAT projection outputs directly (no per-seq split copies).
2892    /// Same kernels, same values, byte-identical to the Vec shim above.
2893    #[allow(clippy::too_many_arguments)]
2894    fn linear_attn_prime_core_pad_view(&self, e: &Engine, la: &LinearAttnLayer,
2895                              qkv_mixed: &cudarc::driver::CudaView<f32>,
2896                              z: &cudarc::driver::CudaView<f32>,
2897                              beta_raw: &cudarc::driver::CudaView<f32>,
2898                              alpha: &cudarc::driver::CudaView<f32>,
2899                              t: usize, cache: &mut Cache, il: usize,
2900                              pad_len: Option<&CudaSlice<i32>>)
2901                              -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2902        let cfg = &self.cfg;
2903        let ssm = cfg.ssm.as_ref().unwrap();
2904        let d_state = ssm.state_size as usize;       // 128
2905        let num_v = ssm.time_step_rank as usize;     // 32
2906        let eps = cfg.rms_eps;
2907        let scale = 1.0 / (d_state as f32).sqrt();
2908
2909        let prep = self.linear_attn_gdn_prep(e, la, qkv_mixed, beta_raw, alpha, t, cache, il, pad_len)?;
2910
2911        // ONE gdn_scan over T from the cache's CURRENT state (zero at fresh prime); the final
2912        // state lands in the spare buffer and ping-pongs back (stable resident pointers, the
2913        // decode-determinism discipline from linear_attn_decode_inner). A4: `gdn_scan_prefill`
2914        // dispatches the chunked WY form under MEMRA_GDN_CHUNKED (prefill-only seam; decode +
2915        // verify keep the sequential kernel).
2916        let mut o = e.uninit(d_state * num_v * t)?;
2917        let rl = cache.recur[il].as_mut().unwrap();
2918        {
2919            let crate::cache::RecurLayer { ssm_state, ssm_state_alt, .. } = rl;
2920            e.gdn_scan_prefill(&prep.q_l2, &prep.k_l2, &prep.v_g, &prep.g_log, &prep.beta,
2921                               prep.kb16.as_ref(), prep.qb16.as_ref(), ssm_state, ssm_state_alt, &mut o, num_v, t, scale,
2922                               prep.hk)?;
2923        }
2924        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2925
2926        // gated RMSNorm + out projection (prefill dispatch). task #17: the f16out twin also
2927        // emits the ssm_out GEMM's fp16 operand in-epilogue (kills the standalone convert).
2928        let mut gn = e.uninit(d_state * num_v * t)?;
2929        let gn16 = if Self::f16out_on(e, t) {
2930            let mut g16 = e.alloc_u8_uninit(d_state * num_v * t * 2)?;
2931            e.gated_rmsnorm_f16out_zv(&o, la.ssm_norm.float_data(), z, &mut gn, &mut g16,
2932                                      d_state, num_v * t, eps)?;
2933            Some(g16)
2934        } else {
2935            e.gated_rmsnorm_zv(&o, la.ssm_norm.float_data(), z, &mut gn, d_state, num_v * t, eps)?;
2936            None
2937        };
2938        Ok((gn, gn16))
2939    }
2940
2941    /// Task #15 core-split wrapper: composes inner + ssm_out (== the old core).
2942    #[allow(clippy::too_many_arguments)]
2943    fn linear_attn_prime_core_pad(&self, e: &Engine, la: &LinearAttnLayer, g4: Vec<CudaSlice<f32>>,
2944                              t: usize, cache: &mut Cache, il: usize,
2945                              pad_len: Option<&CudaSlice<i32>>)
2946                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2947        let (gn, gn16) = self.linear_attn_prime_core_pad_inner(e, la, g4, t, cache, il, pad_len)?;
2948        if let Some(xh) = &gn16 {
2949            if let Some(y) = e.try_f16_gemm_pre(&la.ssm_out, xh, t)? {
2950                return Ok(y);
2951            }
2952        }
2953        Ok(e.matmul(&la.ssm_out, &gn, t)?)
2954    }
2955
2956    /// Full-attention mixer with QK-norm, partial RoPE, sigmoid output gate (qwen35 :257-336).
2957    ///
2958    /// `il` = layer index: step35 needs it (per-layer n_head / rope width / window / gate) and
2959    /// routes to its own mixer. Every other arch ignores it (uniform geometry).
2960    pub fn full_attn(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize, il: usize)
2961                 -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2962        if self.cfg.step35.is_some() {
2963            return self.step35_attn(e, fa, h, pos_d, t, il);
2964        }
2965        let cfg = &self.cfg;
2966        let _n_embd = cfg.n_embd as usize;
2967        let geometry = cfg.full_attention_geometry_at(il as u32);
2968        let n_head = geometry.n_head as usize;
2969        let n_head_kv = geometry.n_head_kv as usize;
2970        let head_dim = geometry.head_dim_k as usize;
2971        let eps = cfg.rms_eps;
2972        let scale = geometry.attention_scale();
2973
2974        // qwen35: wq output = head_dim*2*n_head (fused [q|gate] per head). M3/Hy3: NO output
2975        // gate — wq out = n_head*head_dim, no split (see prime-path note).
2976        let gated = geometry.attention_gate
2977            == memra_gguf::config::AttentionGateKind::FusedQ;
2978        // grouped: one f16 activation convert feeds q/k/v (matmul_group)
2979        let mut g3 = e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?;
2980        let v = g3.pop().unwrap();
2981        let mut k = g3.pop().unwrap();
2982        let qf = g3.pop().unwrap();
2983        let (mut q, gate) = if gated {
2984            let mut q = e.uninit(t * n_head * head_dim)?;
2985            let mut gate = e.uninit(t * n_head * head_dim)?;
2986            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
2987            (q, Some(gate))
2988        } else {
2989            (qf, None)
2990        };
2991
2992        // QK-norm (per head_dim row), then partial RoPE.
2993        let mut qn = e.uninit(t * n_head * head_dim)?;
2994        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head * t, eps)?;
2995        q = qn;
2996        let mut kn = e.uninit(t * n_head_kv * head_dim)?;
2997        e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, n_head_kv * t, eps)?;
2998        k = kn;
2999        let rope_dims = geometry.n_rot as usize;
3000        e.rope_neox(&mut q, pos_d, head_dim, rope_dims, n_head, t, geometry.rope_base, 1.0)?;
3001        e.rope_neox(&mut k, pos_d, head_dim, rope_dims, n_head_kv, t, geometry.rope_base, 1.0)?;
3002
3003        // SDPA
3004        let mut attn = e.uninit(t * n_head * head_dim)?;
3005        // hand-written FlashAttention prefill (head_dim 256/128 stamped twins). MEMRA_NOFA
3006        // falls back to naive sdpa.
3007        if std::env::var("MEMRA_NOFA").is_ok() || !(head_dim == 256 || head_dim == 128) {
3008            // head_dim gate: see prime-path note (fa_prefill is stamped at 256 and 128 only).
3009            e.sdpa_naive(&q, &k, &v, &mut attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
3010        } else {
3011            e.fa_prefill(&q, &k, &v, &mut attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
3012        }
3013
3014        // output gate: attn * sigmoid(gate) — qwen35 only (M3 has no gate).
3015        let attn_g = match &gate {
3016            Some(gate) => {
3017                let mut gsig = e.uninit(t * n_head * head_dim)?;
3018                e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
3019                let mut ag = e.uninit(t * n_head * head_dim)?;
3020                e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
3021                ag
3022            }
3023            None => attn,
3024        };
3025
3026        // o projection
3027        let o = e.matmul(&fa.wo, &attn_g, t)?;
3028        Ok(o)
3029    }
3030
3031    /// Linear-attention (Gated DeltaNet) mixer (qwen35 :338-470).
3032    pub fn linear_attn(&self, e: &Engine, la: &LinearAttnLayer, h: &CudaSlice<f32>, t: usize)
3033                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3034        let cfg = &self.cfg;
3035        let _n_embd = cfg.n_embd as usize;
3036        let ssm = cfg.ssm.as_ref().unwrap();
3037        let d_state = ssm.state_size as usize;       // 128
3038        let num_k = ssm.group_count as usize;        // 16
3039        let num_v = ssm.time_step_rank as usize;     // 32
3040        let d_conv = ssm.conv_kernel as usize;       // 4
3041        let head_k = d_state; let head_v = d_state;
3042        let key_dim = head_k * num_k;                // 2048
3043        let value_dim = head_v * num_v;              // 4096
3044        let conv_dim = key_dim * 2 + value_dim;      // 8192
3045        let eps = cfg.rms_eps;
3046        let scale = 1.0 / (d_state as f32).sqrt();
3047
3048        // projections
3049        // grouped: one f16 activation convert feeds all four projections (matmul_group)
3050        let mut g4 = e.matmul_group(&[&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha], h, t)?;
3051        let alpha = g4.pop().unwrap();                   // [T, num_v]
3052        let beta_raw = g4.pop().unwrap();                // [T, num_v]
3053        let z = g4.pop().unwrap();                       // [T, value_dim]
3054        let qkv_mixed = g4.pop().unwrap();               // [T, conv_dim] token-major
3055
3056        // conv + GDN repack, FUSED (2026-07-03): ssm_conv1d_gdn reads qkv_mixed [T, conv_dim]
3057        // token-major DIRECTLY (causal window rows t-pad..t, rows<0 = zero prefill state), applies
3058        // the 8-tap conv + SiLU, and scatters straight into the GDN [d_state, num_v, T] q/k/v
3059        // layout with the modulo head-repeat. Replaces transpose + zeros + conv_left_pad +
3060        // ssm_conv1d + qkv_to_gdn_repack (5 launches, conv_in/conv_out scratch + a 16MB@T=512
3061        // round-trip). BIT-IDENTICAL accumulation and scatter mapping.
3062        let _ = (head_k, head_v);
3063        let mut q_g = e.uninit(d_state * num_v * t)?;
3064        let mut k_g = e.uninit(d_state * num_v * t)?;
3065        let mut v_g = e.uninit(d_state * num_v * t)?;
3066        e.ssm_conv1d_gdn(&qkv_mixed, la.ssm_conv1d.float_data(), &mut q_g, &mut k_g, &mut v_g,
3067                         conv_dim, t, d_conv, d_state, num_v, num_k, key_dim)?;
3068        // L2-norm q,k per (head_dim) row — rows are contiguous d_state in q_g.
3069        let mut q_l2 = e.uninit(d_state * num_v * t)?;
3070        e.l2_norm(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
3071        let mut k_l2 = e.uninit(d_state * num_v * t)?;
3072        e.l2_norm(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
3073        let v_gd = v_g;
3074
3075        // beta = sigmoid(beta_raw) ; g_log = a * softplus(alpha + dt). Both need [num_v, T] layout
3076        // (g[t*num_v + h]). beta_raw/alpha are [T, num_v] token-major == that layout already.
3077        let mut beta = e.uninit(t * num_v)?;
3078        e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
3079        // gdn_glog expects alpha [H,T] with alpha[t*H+h] and dt_bias/a [H] — matches token-major [T,num_v].
3080        let mut g_log = e.uninit(t * num_v)?;
3081        e.gdn_glog(&alpha, la.ssm_dt.float_data(), la.ssm_a.float_data(), &mut g_log, num_v, t)?;
3082
3083        // GDN scan (A4: gdn_scan_prefill dispatches chunked WY under MEMRA_GDN_CHUNKED)
3084        let state_in = e.zeros(d_state * d_state * num_v)?;  // zero state (prefill)
3085        let mut state_out = e.zeros(d_state * d_state * num_v)?;
3086        let mut o = e.uninit(d_state * num_v * t)?;
3087        e.gdn_scan_prefill(&q_l2, &k_l2, &v_gd, &g_log, &beta, None, None, &state_in, &mut state_out, &mut o, num_v, t, scale, num_v)?;
3088
3089        // gated RMSNorm: dst = RMSNorm(o, ssm_norm[head_v]) * silu(z). o is [d_state, num_v, T];
3090        // rows of head_v=d_state, nrows = num_v*T. z must match row layout: z is [T, value_dim] token-major
3091        // = [T, num_v*head_v]; per (t, vh) the head_v slice is contiguous -> rows align as (t*num_v+vh).
3092        // o rows are (t*num_v+vh) too. Good.
3093        let mut gn = e.uninit(d_state * num_v * t)?;
3094        e.gated_rmsnorm(&o, la.ssm_norm.float_data(), &z, &mut gn, d_state, num_v * t, eps)?;
3095
3096        // ssm_out projection: gn is [d_state, num_v, T] = [value_dim, T] viewed token-major as [T, value_dim]?
3097        // gn layout: (t*num_v+vh)*d_state + i  == token t, then (vh,i) = channel vh*d_state+i. That's
3098        // token-major [T, value_dim]. linear wants [T, in=value_dim]. Good.
3099        let out = e.matmul(&la.ssm_out, &gn, t)?;
3100        Ok(out)
3101    }
3102}
3103
3104impl HybridModel {
3105    /// MoE FFN (EDGE-1). z: [T, n_embd] (already post-attention-normed). Returns moe_out [T, n_embd].
3106    /// Node-for-node vs llama.cpp build_moe_ffn + qwen35moe::build_layer_ffn.
3107    ///
3108    /// `il` is the trunk layer index — the residency-cache key prefix (a gate-expert of layer 3 is a
3109    /// different 860160-byte block than the same expert of layer 7).
3110    ///
3111    /// Routing: host softmax+sort (default) OR the fused router kernel (MEMRA_FUSED_ROUTER).
3112    /// Dispatch: stage-every-token into 3 scratch slots (default) OR the SLRU residency cache
3113    /// (MEMRA_MOE_CACHE). The cache-HIT weight path is bit-identical to stage-every-token (§B.3).
3114    /// Convenience wrapper used by the hybrid trunk/MTP loops: pulls dims + max-block from `self`.
3115    pub fn moe_ffn_il(&self, e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize, il: u16)
3116               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3117        Self::moe_ffn_inner(e, m, z, None, t, &self.cfg, il, self.max_moe_block(), false)
3118    }
3119
3120    /// Prefill twin: Step35 promotes expert-grouped dispatch by default while decode/spec callers
3121    /// keep `moe_ffn_il` and therefore retain their existing dispatch class.
3122    pub fn moe_ffn_il_prefill(
3123        &self,
3124        e: &Engine,
3125        m: &MoeWeights,
3126        z: &CudaSlice<f32>,
3127        t: usize,
3128        il: u16,
3129    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3130        Self::moe_ffn_inner(e, m, z, None, t, &self.cfg, il, self.max_moe_block(), true)
3131    }
3132
3133    /// Decode-path twin with a PRE-QUANTIZED z (from add_rms_norm_zq8): threads (zq, zd) into the
3134    /// t=1 dev arm so the per-layer standalone quantize_q8_1 launch folds away. Identical bytes
3135    /// (the fused kernel reproduces quantize_q8_1 exactly); every other path ignores the pair.
3136    pub fn moe_ffn_il_zq8(&self, e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>,
3137                          zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>, t: usize, il: u16)
3138               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3139        Self::moe_ffn_inner(
3140            e, m, z, zq8, t, &self.cfg, il, self.max_moe_block(), false,
3141        )
3142    }
3143
3144    /// MoE FFN (EDGE-1), source-/model-agnostic. z: [T, n_embd] (already post-attention-normed).
3145    /// Returns moe_out [T, n_embd]. Node-for-node vs llama.cpp build_moe_ffn. Shared by the hybrid
3146    /// (qwen35moe, shared expert present) and the dense-attention MoE (OLMoE, no shared expert) paths;
3147    /// `cfg.moe` supplies the dims and the optional shexp fields decide whether step 3 runs.
3148    ///
3149    /// `il` is the layer index — the residency-cache key prefix. `max_block` is the global max expert
3150    /// stride (fixed cache-slot size); pass `self.max_moe_block()`.
3151    pub(crate) fn moe_ffn(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize,
3152                          cfg: &ModelConfig, il: u16, max_block: usize)
3153               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3154        Self::moe_ffn_inner(e, m, z, None, t, cfg, il, max_block, false)
3155    }
3156
3157    #[allow(clippy::too_many_arguments)]
3158    pub(crate) fn moe_ffn_inner(
3159        e: &Engine,
3160        m: &MoeWeights,
3161        z: &CudaSlice<f32>,
3162        zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>,
3163        t: usize,
3164        cfg: &ModelConfig,
3165        il: u16,
3166        max_block: usize,
3167        prefill: bool,
3168    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3169        let worker_io = crate::spill_pread::worker_enabled();
3170        let epoch_lfu = std::env::var_os("MEMRA_MOE_LFU_DECAY").is_some();
3171        if Engine::moe_cache_enabled() && (worker_io || epoch_lfu) {
3172            e.with_moe_cache(max_block, |cache, _| {
3173                cache.begin_forward_epoch(il, t);
3174                if worker_io {
3175                    cache.begin_worker_scope();
3176                }
3177                Ok(())
3178            })?;
3179        }
3180        if Self::sigmoid_resident_dev_eligible(e, m, cfg) {
3181            let moe = cfg.moe.as_ref().unwrap();
3182            let n_expert = moe.expert_count as usize;
3183            let n_used = moe.expert_used_count as usize;
3184            let sigmoid = cfg.sigmoid_router().unwrap();
3185            let logits = Self::moe_router_logits(e, m, z, t, cfg)?;
3186            Self::trace_sigmoid_router_logits(
3187                e, il, t, n_expert, n_used, &logits, m, sigmoid,
3188            )?;
3189            return Self::moe_ffn_sigmoid_dev(
3190                e, m, z, zq8, &logits, t, cfg, il, sigmoid,
3191            );
3192        }
3193        // Expert-grouped dispatch for prefill (T>1). MEMRA_MOE_GROUPED explicitly opts the
3194        // current caller into this research arm; the naked default stays on the established path.
3195        if t > 1 && moe_grouped_enabled(cfg, prefill) {
3196            let grouped_out = Self::moe_ffn_grouped(e, m, z, t, cfg, il, max_block)?;
3197            // MEMRA_MOE_GATE: byte-identity comparison vs sequential path.
3198            // The grouped q8 path uses the same row-wise quantize/dot/activation/FMA programs as
3199            // sequential dispatch; mixed or q8-disabled layouts fall back to the matching f32
3200            // path. A mismatch is therefore a correctness failure, not an accepted numeric class.
3201            if std::env::var("MEMRA_MOE_GATE").is_ok() {
3202                let seq_out = Self::moe_ffn_sequential(e, m, z, t, cfg, il, max_block)?;
3203                let g_host = e.dtoh(&grouped_out)?;
3204                let s_host = e.dtoh(&seq_out)?;
3205                let g_bytes: &[u8] = unsafe { std::slice::from_raw_parts(g_host.as_ptr() as *const u8, g_host.len() * 4) };
3206                let s_bytes: &[u8] = unsafe { std::slice::from_raw_parts(s_host.as_ptr() as *const u8, s_host.len() * 4) };
3207                if g_bytes == s_bytes {
3208                    println!("moe-gate il={il} t={t} BYTE-IDENTICAL");
3209                } else {
3210                    let diffs = g_host.iter().zip(s_host.iter()).enumerate()
3211                        .filter(|(_, (a, b))| a != b).count();
3212                    let maxdiff = g_host.iter().zip(s_host.iter())
3213                        .map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
3214                    panic!("moe-gate il={il} t={t} MISMATCH: {diffs}/{} elems differ, maxdiff={maxdiff:.6e}", g_host.len());
3215                }
3216            }
3217            return Ok(grouped_out);
3218        }
3219        Self::moe_ffn_sequential_zq8(e, m, z, zq8, t, cfg, il, max_block)
3220    }
3221
3222    fn sigmoid_resident_dev_eligible(
3223        e: &Engine,
3224        m: &MoeWeights,
3225        cfg: &ModelConfig,
3226    ) -> bool {
3227        let Some(moe) = cfg.moe.as_ref() else { return false };
3228        // Cached once per process: this predicate runs per MoE layer per decode step, and five
3229        // uncached env reads were ~300+ environ scans/step on the exact path this arm de-hosts.
3230        static OBSERVATION_MODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3231        let observation_mode = *OBSERVATION_MODE.get_or_init(|| {
3232            std::env::var("MEMRA_MOE_STATS").is_ok()
3233                || std::env::var("MEMRA_MOE_TRACE").is_ok()
3234                || std::env::var("MEMRA_MOE_WEIGHT_TRACE").is_ok()
3235                || std::env::var("MEMRA_MOE_INPUT_TRACE_DIR").is_ok()
3236                || std::env::var("MEMRA_MOE_GATE").is_ok()
3237        });
3238        cfg.step35.is_some()
3239            && sigmoid_router_enabled()
3240            && moe_dev_enabled()
3241            && moe_slab_enabled()
3242            && !observation_mode
3243            && moe.expert_used_count <= 8
3244            && m.has_uniform_expert_layout()
3245            && m.gate_exps.macros.is_none()
3246            && m.up_exps.macros.is_none()
3247            && m.down_exps.macros.is_none()
3248            && !m.has_macros
3249            && moe_q8_enabled()
3250            && q8_expert_supported(m.gate_exps.qtype)
3251            && q8_expert_supported(m.up_exps.qtype)
3252            && q8_expert_supported(m.down_exps.qtype)
3253            && m.dev_exps
3254                .as_ref()
3255                .is_some_and(|dev| dev.dev == e.ctx().ordinal())
3256    }
3257
3258    /// Sequential (per-token) MoE FFN -- the original path. Factored out for the gate comparison.
3259    pub(crate) fn moe_ffn_sequential(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize,
3260                          cfg: &ModelConfig, il: u16, max_block: usize)
3261               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3262        Self::moe_ffn_sequential_zq8(e, m, z, None, t, cfg, il, max_block)
3263    }
3264
3265    /// One router-logit selector shared by sequential and grouped dispatch. Real prefill must use
3266    /// the row-wise GEMV when exact routing is enabled: cuBLASLt's reduction changes with `m`,
3267    /// which makes expert selection depend on the caller's chunk or concat-batch shape.
3268    fn moe_router_logits(
3269        e: &Engine,
3270        m: &MoeWeights,
3271        z: &CudaSlice<f32>,
3272        t: usize,
3273        cfg: &ModelConfig,
3274    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3275        if t < PRIME_MIN_T {
3276            // Decode and speculative verify use one fixed per-row reduction program.
3277            if crate::router_kernel_on() {
3278                e.router_gemv(
3279                    m.gate_inp.float_data(),
3280                    z,
3281                    cfg.n_embd as usize,
3282                    m.gate_exps.n_expert,
3283                    t,
3284                )
3285            } else {
3286                e.matmul_decode_exact(&m.gate_inp, z, t)
3287            }
3288        } else if crate::router_prefill_exact_on() && crate::router_kernel_on() {
3289            e.router_gemv(
3290                m.gate_inp.float_data(),
3291                z,
3292                cfg.n_embd as usize,
3293                m.gate_exps.n_expert,
3294                t,
3295            )
3296        } else {
3297            e.matmul(&m.gate_inp, z, t)
3298        }
3299    }
3300
3301    /// Append the host-visible router selection for one layer/forward when calibration tracing is
3302    /// enabled. Both sequential and expert-grouped prefill must call this after routing so the
3303    /// trace is independent of the dispatch optimization selected for the forward.
3304    fn trace_moe_routes(il: u16, t: usize, sel_all: &[u32], weights: &[f32])
3305                        -> Result<(), Box<dyn std::error::Error>> {
3306        use std::io::Write as _;
3307        if let Ok(path) = std::env::var("MEMRA_MOE_TRACE") {
3308            let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
3309            let ids: Vec<String> = sel_all.iter().map(|s| s.to_string()).collect();
3310            writeln!(f, "{} {} {}", il, t, ids.join(","))?;
3311        }
3312        if let Ok(path) = std::env::var("MEMRA_MOE_WEIGHT_TRACE") {
3313            let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
3314            let pairs: Vec<String> = sel_all.iter().zip(weights)
3315                .map(|(expert, weight)| format!("{expert}:{weight:.9}"))
3316                .collect();
3317            writeln!(f, "{} {} {}", il, t, pairs.join(","))?;
3318        }
3319        Ok(())
3320    }
3321
3322    #[allow(clippy::too_many_arguments)]
3323    fn trace_sigmoid_router_logits(
3324        e: &Engine,
3325        il: u16,
3326        t: usize,
3327        n_expert: usize,
3328        n_used: usize,
3329        logits: &CudaSlice<f32>,
3330        m: &MoeWeights,
3331        (scaling_factor, route_norm): (f32, bool),
3332    ) -> Result<(), Box<dyn std::error::Error>> {
3333        if !crate::sigrouter_contract::served_logit_trace_enabled() || t != 1 {
3334            return Ok(());
3335        }
3336        let logits = e.dtoh(logits)?;
3337        let active: Vec<u8> = m
3338            .active_experts
3339            .as_ref()
3340            .map(|mask| mask.iter().map(|&enabled| u8::from(enabled)).collect())
3341            .unwrap_or_else(|| vec![1; n_expert]);
3342        let bias = m.exp_probs_b.clone().unwrap_or_else(|| vec![0.0; n_expert]);
3343        crate::sigrouter_contract::capture_served_logits(
3344            il as u32,
3345            t,
3346            n_expert,
3347            n_used,
3348            scaling_factor,
3349            route_norm,
3350            &active,
3351            &bias,
3352            &logits,
3353        )?;
3354        Ok(())
3355    }
3356
3357    /// Append the f32 input to one MoE layer for offline, layerwise calibration. This diagnostic
3358    /// intentionally performs a DtoH copy and is therefore disabled unless an explicit fresh trace
3359    /// directory is supplied. Each layer owns one payload file; index.jsonl records byte offsets so
3360    /// a validator can prove request/layer coverage before the trace is used for pruning or healing.
3361    fn trace_moe_input(e: &Engine, il: u16, t: usize, n_embd: usize, z: &CudaSlice<f32>)
3362                       -> Result<(), Box<dyn std::error::Error>> {
3363        use std::io::Write as _;
3364        let Ok(dir) = std::env::var("MEMRA_MOE_INPUT_TRACE_DIR") else { return Ok(()) };
3365        let host = e.dtoh(z)?;
3366        if host.len() != t * n_embd {
3367            return Err(format!(
3368                "MoE input trace shape mismatch at layer {il}: got {} values, expected {}x{}",
3369                host.len(), t, n_embd
3370            ).into());
3371        }
3372        let bytes = unsafe {
3373            std::slice::from_raw_parts(
3374                host.as_ptr().cast::<u8>(), host.len() * std::mem::size_of::<f32>()
3375            )
3376        };
3377        let state = MOE_INPUT_TRACE_WRITER.get_or_init(|| std::sync::Mutex::new(None));
3378        let mut state = state.lock().map_err(|_| "MoE input trace writer lock is poisoned")?;
3379        if state.is_none() {
3380            let dir = std::path::PathBuf::from(&dir);
3381            std::fs::create_dir_all(&dir)?;
3382            let index = std::fs::OpenOptions::new().create(true).append(true)
3383                .open(dir.join("index.jsonl"))?;
3384            *state = Some(MoeInputTraceWriter {
3385                dir,
3386                index,
3387                payloads: std::collections::HashMap::new(),
3388            });
3389        }
3390        let writer = state.as_mut().unwrap();
3391        if writer.dir != std::path::Path::new(&dir) {
3392            return Err("MEMRA_MOE_INPUT_TRACE_DIR changed after capture started".into());
3393        }
3394        let file_name = format!("layer-{il:03}.f32");
3395        if !writer.payloads.contains_key(&il) {
3396            let payload = std::fs::OpenOptions::new().create(true).append(true)
3397                .open(writer.dir.join(&file_name))?;
3398            let offset = payload.metadata()?.len();
3399            writer.payloads.insert(il, (payload, offset));
3400        }
3401        let (payload, offset) = writer.payloads.get_mut(&il).unwrap();
3402        let row_offset = *offset;
3403        payload.write_all(bytes)?;
3404        *offset += bytes.len() as u64;
3405        writeln!(
3406            writer.index,
3407            "{{\"format\":\"memra-moe-input-trace-v1\",\"layer\":{il},\"tokens\":{t},\
3408             \"hidden_size\":{n_embd},\"file\":\"{file_name}\",\"offset\":{row_offset},\
3409             \"payload_bytes\":{}}}",
3410            bytes.len()
3411        )?;
3412        Ok(())
3413    }
3414
3415    #[allow(clippy::too_many_arguments)]
3416    pub(crate) fn moe_ffn_sequential_zq8(
3417        e: &Engine,
3418        m: &MoeWeights,
3419        z: &CudaSlice<f32>,
3420        zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>,
3421        t: usize,
3422        cfg: &ModelConfig,
3423        il: u16,
3424        max_block: usize,
3425    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3426        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
3427        let moe = cfg.moe.as_ref().unwrap();
3428        let n_embd = cfg.n_embd as usize;          // 2048 (gate/up in_f, down out_f)
3429        let n_expert = moe.expert_count as usize;  // 256
3430        let n_used = moe.expert_used_count as usize; // 8
3431        let n_ff_exp = moe.expert_ff_length as usize; // 512 (gate/up out_f, down in_f)
3432
3433        // verify the HostExps dims match cfg (catches a wrong-file / transpose mixup)
3434        debug_assert_eq!(m.gate_exps.in_f, n_embd);
3435        debug_assert_eq!(m.gate_exps.out_f, n_ff_exp);
3436        debug_assert_eq!(m.down_exps.in_f, n_ff_exp);  // down is TRANSPOSED: in=512
3437        debug_assert_eq!(m.down_exps.out_f, n_embd);   //                     out=2048
3438        debug_assert_eq!(m.gate_exps.n_expert, n_expert);
3439
3440        // step35 PER-LAYER SwiGLU clamp (None on every other arch and on every unclamped layer).
3441        // Routed experts and the shared expert read SEPARATE arrays — never share one value.
3442        let lim_exp = cfg.clamp_exp_at(il as u32);
3443        let lim_shexp = cfg.clamp_shexp_at(il as u32);
3444        let use_cache = Engine::moe_cache_enabled();
3445        let uniform_experts = m.has_uniform_expert_layout();
3446        let moe_q8 = uniform_experts && moe_q8_enabled()
3447            && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
3448            && q8_expert_supported(m.down_exps.qtype);
3449        // Experimental secondary backend: complete experts already resident in the SLRU stay on
3450        // CUDA; any expert missing one or more projections runs from the original host GGUF bytes
3451        // through llama.cpp CPU quant dots. Small-t only keeps decode and speculative verification
3452        // in the same numeric/dispatch class; real prefill remains on the established GPU path and
3453        // seeds the residency cache. An explicit library path is the build/runtime gate, so naked
3454        // commands and CI have no llama.cpp or OpenMP dependency.
3455        let cpu_expert_requested = crate::cpu_experts::configured();
3456        if cpu_expert_requested && (cfg.hy3.is_none() || cfg.m3.is_some()) {
3457            return Err(std::io::Error::other(
3458                "MEMRA_CPU_EXPERT_LIB is experimental and currently gated to Hy3",
3459            )
3460            .into());
3461        }
3462        let cpu_hybrid = cpu_expert_requested && t < PRIME_MIN_T && m.dev_exps.is_none();
3463        // A dynamic SLRU changes which complete experts run on CUDA versus llama.cpp CPU dots.
3464        // Those backends are each deterministic but are different numeric configurations, so a
3465        // later prefill eviction can change greedy output. Freeze after the first real prefill;
3466        // decode/spec reads the fixed resident set, while later prefill misses use transient GPU
3467        // staging below and cannot change backend assignment.
3468        let freeze_cpu_residency = cpu_expert_requested
3469            && std::env::var("MEMRA_CPU_EXPERT_FREEZE_CACHE").as_deref() == Ok("1");
3470        let caller_warms_before_freeze = std::env::var("MEMRA_CPU_EXPERT_FREEZE_WARMUP_TOKENS")
3471            .ok()
3472            .and_then(|value| value.parse::<usize>().ok())
3473            .is_some_and(|tokens| tokens > 0);
3474        if cpu_hybrid && freeze_cpu_residency && !caller_warms_before_freeze {
3475            e.freeze_moe_cache();
3476        }
3477        let cache_frozen = use_cache && e.moe_cache_frozen();
3478        let cache_dispatch = use_cache && (!cache_frozen || cpu_hybrid);
3479
3480        // 1. ROUTER: one selector is shared with expert-grouped prefill so changing dispatch
3481        // cannot change logits, selected expert ids, or routing weights.
3482        let logits = Self::moe_router_logits(e, m, z, t, cfg)?;
3483        if let Some(sig) = cfg.sigmoid_router() {
3484            Self::trace_sigmoid_router_logits(e, il, t, n_expert, n_used, &logits, m, sig)?;
3485        }
3486
3487        // LAUNCH-STRUCTURE STAGE 3 (2026-07-05, MEMRA_MOE_DEV default ON, =0 rollback): ZERO-DtoH
3488        // device-dispatch when this layer's expert blocks are ALL cache-resident. The fused
3489        // router's sel/w stay ON DEVICE; the expert weight pointers come from the per-layer
3490        // device table of fixed slot addresses; gate/up/silu + down/fma run as the same TWO
3491        // launches per token as gdec. Removes the per-layer router DtoH + stream sync — the
3492        // per-token host stall that dominated the 35B decode wall after stages 1+2.
3493        // BIT-IDENTITY: the router kernel is selection-exact vs the host oracle (kernel-check
3494        // tie gate) and the _dev matvec twins reproduce the gdec kernels' exact FP chains; the
3495        // only difference is where sel/w/pointers are READ from (device instead of params).
3496        // Residency: one-shot PREWARM force-admits the layer while free slots cover it
3497        // (MEMRA_MOE_PREWARM=0 -> organic residency, dev path fires when the SLRU fills).
3498        // Any non-resident layer falls through to host routing + the gdec/sequential path.
3499        // FITS-VRAM RESIDENT EXPERTS (2026-07-06): the layer's expert slabs are device-resident
3500        // (load-time decision) — fire the zero-DtoH dev path unconditionally with the prebuilt
3501        // pointer row. No cache, no dispatch, no residency check: the llama full-offload regime
3502        // (it measured 169.55 vs the cache path's 28.5 on the local 35B — the residency-gate
3503        // all-or-nothing fallback was the 6x). BIT-IDENTITY: same _dev kernels, same math; only
3504        // the pointer table's provenance differs (slab base+stride vs SLRU slot addresses).
3505        // MoE PREFILL PAIR-BATCH (2026-07-06, the 16x pp hole): t>1 on resident experts — ONE
3506        // launch per proj covers ALL (token,expert) pairs (grid.y=pair, warp-per-row), replacing
3507        // the per-expert loop (256 experts x 3-4 launches x tiny m_e). Scatter is slot-ordered
3508        // per token (the sequential-axpy bit-identity class). Requires q8-supported qtypes +
3509        // resident slabs. MEMRA_MOE_PAIRS=0 rollback.
3510        // t >= PRIME_MIN_T only (2026-07-06 exactness fix, verify-probe proof): spec VERIFY
3511        // batches (t = 2..K+2) previously rode these pairs kernels while T=1 decode rode the
3512        // dev_q8 loop — different FP chains, verify-T2 logit maxdiff 2.6e-1 vs eager -> greedy
3513        // flips at tight margins -> 35B real-prompt spec self-consistency FAIL (the 27B
3514        // "verify must be kernel-DISPATCH-identical to decode" lesson, MoE edition). Small-t
3515        // now rides the dev loop below (same kernels per token as decode); pairs serves real
3516        // prefill (t >= 16, where spec never verifies).
3517        // sigmoid-router archs must NOT enter the pairs/dev arms: those dispatch arms still route
3518        // via the fused SOFTMAX device router (moe_router_topk) — silently wrong experts (the
3519        // M3 gate-MISMATCH 74602-vs-92 lesson, 2026-07-07). Sigmoid routing has its own device
3520        // top-k kernel; MEMRA_SIG_ROUTER=0 selects the host sigmoid oracle instead.
3521        // Per-expert macro-scales (compressed-tensors NVFP4 ST class, e.g. unsloth 35B-A3B):
3522        // the device-dispatch kernels (pairs/dev) do NOT fold them — those checkpoints must
3523        // ride the macro-aware sequential/staged paths below or every expert output is off by
3524        // its global scale (~3e4x, measured garbage 2026-07-16). GGUF experts: macros None.
3525        let no_exp_macros = m.gate_exps.macros.is_none() && m.up_exps.macros.is_none()
3526            && m.down_exps.macros.is_none();
3527        // A clamped-SwiGLU layer (step35 43/44) also cannot ride pairs: moe_pairs_silu_mul's
3528        // epilogue is plain silu(gate)*up with no clamp form, and moe_ffn_pairs takes no `il`
3529        // so it cannot even see the per-layer limit.
3530        if cfg.sigmoid_router().is_none() && cfg.m3.is_none() && cfg.hy3.is_none()
3531            && !cfg.swiglu_clamped_at(il as u32)
3532            && no_exp_macros
3533            && t >= PRIME_MIN_T && m.dev_exps.is_some() && moe_q8_enabled()
3534            && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
3535            && q8_expert_supported(m.down_exps.qtype)
3536            && std::env::var("MEMRA_MOE_PAIRS").map(|v| v != "0").unwrap_or(true)
3537            && std::env::var("MEMRA_MOE_STATS").is_err() {
3538            return Self::moe_ffn_pairs(e, m, z, &logits, t, cfg);
3539        }
3540
3541        // t < PRIME_MIN_T: moe_ffn_dev loops tokens serially (1 launch-pair per token) — the
3542        // decode path AND the spec-verify path (dispatch parity = exactness; see pairs gate
3543        // above). Serial launches are fine at t<=10 (K+2); real prefill never lands here.
3544        // moe_ffn_dev routes via the FUSED SOFTMAX device router (moe_router_topk). Sigmoid
3545        // routing has a separate device top-k kernel, but this dev arm cannot consume its sel/w
3546        // contract, so sigmoid-router arches must NOT enter it: with MOE_CACHE=1 M3 silently
3547        // routed softmax = wrong experts (gate MISMATCH 74602 vs 92, caught 2026-07-07).
3548        // MEMRA_SIG_ROUTER=0 selects the host sigmoid oracle for the supported sigmoid path.
3549        // macro-carrying experts are handled inside the dev path now (epilogue fold + w-scale);
3550        // pairs/gdec/csr keep their macro gates until their kernels grow the fold.
3551        // step35 (2026-08-06) is the third sigmoid-router arch and the deny above was written as
3552        // two arch names, not as the mechanism — so `dev_ok` let it into moe_ffn_dev's
3553        // moe_router_topk (softmax, no exp_probs_b bias, no expert_weights_scale) = silently
3554        // wrong experts, the same failure the pairs gate at :2254 already blocks by predicate.
3555        // Keyed off sigmoid_router() so arch #4 is denied by construction.
3556        // The clamped-SwiGLU layers must also fall through: every moe_ffn_dev kernel's fused
3557        // epilogue is plain silu(gate)*up (moe_gate_up_silu8_dev_*), which has no clamp form.
3558        let dev_ok = uniform_experts && cfg.sigmoid_router().is_none()
3559            && cfg.m3.is_none() && cfg.hy3.is_none()
3560            && !cfg.swiglu_clamped_at(il as u32);
3561        // Observation modes must route through the host-visible selection below. Otherwise a fully
3562        // resident layer returns through device dispatch before its trace/stats row is recorded,
3563        // silently biasing calibration toward only non-resident layers on large-VRAM machines.
3564        let observe_routes = std::env::var("MEMRA_MOE_STATS").is_ok()
3565            || std::env::var("MEMRA_MOE_TRACE").is_ok()
3566            || std::env::var("MEMRA_MOE_WEIGHT_TRACE").is_ok()
3567            || std::env::var("MEMRA_MOE_INPUT_TRACE_DIR").is_ok();
3568        if dev_ok && t < PRIME_MIN_T && m.dev_exps.is_some() && n_used <= 8 && moe_dev_enabled()
3569            && !observe_routes {
3570            return Self::moe_ffn_dev(e, m, z, zq8, &logits, t, cfg, il, max_block);
3571        }
3572        if dev_ok && use_cache && n_used <= 8 && moe_dev_enabled()
3573            && !observe_routes {
3574            let row_ok = e.with_moe_cache(max_block, |c, eng| {
3575                if moe_prewarm_enabled() { c.prewarm_layer(il, m, eng)?; }
3576                Ok(c.layer_dev_row(il, n_expert, eng)?.is_some())
3577            })?;
3578            if row_ok {
3579                return Self::moe_ffn_dev(e, m, z, zq8, &logits, t, cfg, il, max_block);
3580            }
3581        }
3582
3583        // Per-token (sel[8], w[8]) — sigmoid host oracle (M3/Hy3), else fused-router/softmax.
3584        let (sel_all, w_all, routed_cpu_input) = if let Some(sig) = cfg.sigmoid_router() {
3585            if cpu_hybrid {
3586                let (sel, w, input) = Self::moe_route_sigmoid_with_input(
3587                    e,
3588                    &logits,
3589                    z,
3590                    t,
3591                    n_expert,
3592                    n_used,
3593                    m.exp_probs_b.as_deref(),
3594                    sig,
3595                    m.active_experts.as_deref(),
3596                )?;
3597                (sel, w, Some(input))
3598            } else {
3599                let (sel, w) = Self::moe_route_sigmoid_cfg(
3600                    e, &logits, t, n_expert, n_used, m, sig,
3601                )?;
3602                (sel, w, None)
3603            }
3604        } else {
3605            let (sel, w) = Self::moe_route_cfg(
3606                e, &logits, t, n_expert, n_used, m.active_experts.as_deref(),
3607            )?;
3608            (sel, w, None)
3609        };
3610
3611        // MEMRA_MOE_TRACE=<path>: append one line per (layer, step) with the selected expert ids —
3612        // offline analysis derives the decode working set + step-to-step reuse (the go/no-go
3613        // measurement for resident-expert tiering; see rig5090.jsonl 2026-07-07 pinned-tier row).
3614        Self::trace_moe_routes(il, t, &sel_all, &w_all)?;
3615        Self::trace_moe_input(e, il, t, n_embd, z)?;
3616
3617        // Worker reads ordinarily overlap NVMe with the current expert but leave their H2D copies
3618        // demand-serialized on the compute stream. Hy3 decode already has a safe owner-thread
3619        // boundary here: sigmoid routing read `logits` back to the host, which synchronized all
3620        // earlier-layer compute. Submit the complete selected set first, then reserve only victims
3621        // outside that set and queue its H2D copies on the copy stream. Dispatch inserts an event
3622        // wait for each pending block, so later copies can overlap the earlier expert kernels while
3623        // the selected weights and numerical kernels remain unchanged. Restrict this experiment to
3624        // T=1; batched forwards can have token-local consumers still in flight between selections.
3625        // The CPU backend reads mmap-backed model bytes directly. Positioned-read worker buffers
3626        // are CUDA write-combined staging allocations and are intentionally not CPU-compute inputs;
3627        // do not spend NVMe bandwidth filling them for a layer whose misses go to CPU.
3628        let worker_disk_prefetch =
3629            cache_dispatch && crate::spill_pread::worker_enabled() && !cpu_hybrid;
3630        let promote_worker_h2d =
3631            t == 1 && worker_disk_prefetch && crate::spill_pread::copy_h2d_enabled();
3632        if promote_worker_h2d {
3633            let mut selected_blocks = Vec::with_capacity(n_used * 3);
3634            for &ex in sel_all.iter().take(n_used) {
3635                let ex = ex as u16;
3636                selected_blocks.extend([
3637                    BlockId::new(il, PROJ_GATE, ex),
3638                    BlockId::new(il, PROJ_UP, ex),
3639                    BlockId::new(il, PROJ_DOWN, ex),
3640                ]);
3641            }
3642            for &ex in sel_all.iter().take(n_used) {
3643                Self::moe_prefetch_disk_expert(e, il, ex as usize, m, max_block, &selected_blocks)?;
3644            }
3645            e.with_moe_cache(max_block, |cache, eng| {
3646                cache.promote_worker_reads_at_safe_boundary(
3647                    &selected_blocks,
3648                    &selected_blocks,
3649                    eng,
3650                )?;
3651                Ok(())
3652            })?;
3653        }
3654
3655        // MEMRA_MOE_STATS: per-layer routing stats for the A2 (expert-grouped prefill) baseline —
3656        // per-token expert-id entropy, active-expert coverage, tokens-per-expert group sizes.
3657        if t > 1 && std::env::var("MEMRA_MOE_STATS").is_ok() {
3658            let mut cnt = vec![0u32; n_expert];
3659            for &s in sel_all.iter() { cnt[s as usize] += 1; }
3660            let total = sel_all.len() as f64;
3661            let mut h = 0.0f64;
3662            let mut active = 0usize;
3663            for &c in &cnt { if c > 0 { active += 1; let p = c as f64 / total; h -= p * p.log2(); } }
3664            let maxc = cnt.iter().copied().max().unwrap_or(0);
3665            println!("moe-stats il={} t={} assignments={} active={}/{} entropy={:.3}b (max {:.3}b) mean_tok_per_active={:.2} max_tok_per_expert={}",
3666                     il, t, sel_all.len(), active, n_expert, h, (n_expert as f64).log2(), total / active.max(1) as f64, maxc);
3667        }
3668
3669        // LAUNCH-STRUCTURE STAGE 2 (2026-07-05): moe_out memset elision on the gdec path.
3670        // moe_down8_fma_f32 FULLY overwrites its token row (dst[o] = the in-kernel FMA chain that
3671        // starts at 0.0f — numerically the axpy-into-zeroed-row chain), so when the grouped-decode
3672        // path fires the upfront `e.zeros(t*n_embd)` memset is pure launch churn. Allocate uninit
3673        // when gdec CAN fire (any t — decode t=1 AND the spec verify t=K+1 route here per token)
3674        // and lazily zero ONLY the row of a token that falls through to the sequential axpy loop.
3675        // BIT-IDENTITY: unchanged — every row is either fully overwritten (gdec) or
3676        // zeroed-then-accumulated exactly as before (fallback).
3677        // `!swiglu_clamped_at`: the grouped-decode kernels' fused epilogue is plain
3678        // silu(gate)*up (see the m3 note at the call sites below) — a clamped layer must fall
3679        // through to the sequential loop's ffn_act_lim. Hoisted into the fire predicate so the
3680        // uninit/memset invariant at :2418 stays consistent with what actually dispatches.
3681        let gdec_may_fire = uniform_experts && use_cache && n_used <= 8 && gdec_enabled()
3682            && !cfg.swiglu_clamped_at(il as u32);
3683        // SLAB-LOCAL RESIDENT ARM (lane/pp-leverb 2026-08-08): the fits-VRAM resident slabs
3684        // (`dev_exps`, sized per PP device by cx-503b) were consumed ONLY by the pairs/dev
3685        // arms — every one of which DENIES sigmoid-router archs (step35/M3/Hy3). So on those
3686        // archs the slabs were uploaded but never read, and every expert went through the
3687        // SLRU (37 GB H2D staging per pp4096 prime on the Step SKU; and post-cx-503b the
3688        // dead slabs additionally STARVE the SLRU, which sizes itself on free-VRAM-after-
3689        // residents). This arm reads the slabs through the SAME kernels the SLRU arm runs —
3690        // gdec's fused pair when eligible, the per-expert qmatvec twins otherwise — with the
3691        // slab base + ex*stride as the pointer provenance (the exact bit-identity class
3692        // `moe_ffn_dev` documents for its resident-vs-SLRU arms; bytes are the same HostExps
3693        // bytes either way). LOCALITY GATE: `d.dev == e.ctx().ordinal()` — a slab on another
3694        // device must NOT be dereferenced (m=1 peer reads are the measured 34-150x class,
3695        // strictly worse than staging); under PP-2 without the prime walker this admits
3696        // stage-0 layers on dev0 and leaves stage-1 layers on the SLRU, which is the honest
3697        // interim shape. MEMRA_MOE_SLAB=0 = rollback/A-B seam (read per call).
3698        let slab_local = m.dev_exps.as_ref()
3699            .filter(|d| !d.gu_il && moe_slab_enabled() && d.dev == e.ctx().ordinal());
3700        let slab_bases = slab_local.map(|d| {
3701            use cudarc::driver::DevicePtr;
3702            let s = e.stream();
3703            let (pg, _g0) = d.gate.device_ptr(&s);
3704            let (pu, _g1) = d.up.device_ptr(&s);
3705            let (pd, _g2) = d.down.device_ptr(&s);
3706            (pg as u64, pu as u64, pd as u64)
3707        });
3708        // Fused-pair eligibility mirrors the gdec call sites exactly (plain-SiLU epilogue,
3709        // no macros, m3 clamp excluded, q8-supported qtypes, <=8 experts) — INCLUDING
3710        // `gdec_enabled()`: the pair IS the gdec kernel pair, so MEMRA_MOE_GDEC=0 must
3711        // disable it here too. That seam is also the exactness localizer: with GDEC=0 both
3712        // provenances run the SAME per-expert qmatvec kernels (slab base+stride vs SLRU
3713        // slot) and must be BIT-IDENTICAL — the true provenance-only pair — while GDEC=1
3714        // compares the fused-pair class against the SLRU's hit/miss MIX (gdec for
3715        // all-resident tokens, staged loop for misses), which is a dispatch-class
3716        // comparison, not a provenance one.
3717        let slab_fused_may_fire = slab_bases.is_some() && n_used <= 8 && gdec_enabled()
3718            && !cfg.swiglu_clamped_at(il as u32) && cfg.m3.is_none()
3719            && no_exp_macros && moe_q8;
3720        // moe_out memset elision: BOTH full-row-overwrite arms (gdec + slab fused) allocate
3721        // uninit; a token that falls through to any accumulating loop zeroes its own row.
3722        let mut moe_out = if gdec_may_fire || slab_fused_may_fire {
3723            e.uninit(t * n_embd)?
3724        } else {
3725            e.zeros(t * n_embd)?
3726        };
3727        // The router readback above already established a host boundary. Copy each small-t hidden
3728        // row once so CPU miss experts can start while the owner thread queues resident GPU work.
3729        let cpu_input = if cpu_hybrid {
3730            Some(routed_cpu_input.ok_or("CPU expert routing did not return the MoE input")?)
3731        } else {
3732            None
3733        };
3734
3735        // GPU scratch: one slot per proj, big enough for ONE expert (default stage-every-token path).
3736        // STAGE 2: LAZY — allocated only if the no-cache staging path actually runs (under
3737        // MEMRA_MOE_CACHE they were 3 dead ~1MB alloc_zeros + memset + free per layer per token,
3738        // measured ~123 memsets/token of the decode wall).
3739        let g_len = m.gate_exps.max_expert_bytes();  // 860160 for the uniform 35B gate
3740        let u_len = m.up_exps.max_expert_bytes();    // 860160 for the uniform 35B up
3741        let d_len = m.down_exps.max_expert_bytes();  // 1114112 for the uniform 35B down
3742        let mut scratch_g: Option<CudaSlice<u8>> = None;
3743        let mut scratch_u: Option<CudaSlice<u8>> = None;
3744        let mut scratch_d: Option<CudaSlice<u8>> = None;
3745        // `max_block` (the GLOBAL max expert stride across all layers) is passed in — the cache slots
3746        // are FIXED-ADDRESS and must fit any layer's block (UD/dynamic GGUFs vary quant per layer).
3747
3748        // EDGE-1 §C.2/C.3: the optional pipeline queues the next selected expert's MISS blocks on
3749        // the copy stream before launching the current expert's compute. Pending slots stay invisible
3750        // to cache hits until dispatch inserts the completion-event wait; current gate/up/down ids are
3751        // protected from eviction. This changes scheduling only, never the GGUF bytes or GEMM path.
3752        let page_window = moe_page_prefetch_window();
3753
3754        // 2. PER TOKEN: routed-expert loop. The ONE dispatch change vs Stage-1: a resident slot
3755        //    (cache HIT, no H2D) OR a staged slot (MISS) feeds the SAME unchanged qmatvec_view.
3756        for tok in 0..t {
3757            let sel = &sel_all[tok * n_used..(tok + 1) * n_used];
3758            let w = &w_all[tok * n_used..(tok + 1) * n_used];
3759            let zt = z.slice(tok * n_embd..(tok + 1) * n_embd);  // CudaView<f32>
3760            let mut tok_q8: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
3761
3762            // STAGE-2 GROUPED DECODE (2026-07-04, MEMRA_MOE_GDEC default ON, =0 rollback): fold
3763            // this token's whole routed-expert FFN (8x gate/up/silu + 8x down/axpy = 40 launches)
3764            // into TWO launches via expert-pointer indirection over the fixed-address cache slots.
3765            // Fires only when ALL 3*n_used blocks are ALREADY cache-resident (pure-HIT: zero
3766            // memcpy, zero admission, so no slot can move under the collected pointers) — any
3767            // miss falls through to the sequential loop below, which admits as before. In steady
3768            // state on a fully-resident rig every token-layer takes the grouped path.
3769            // BIT-IDENTITY: each in-kernel dot reproduces qmatvec_f32's exact reduction; SiLU is
3770            // silu_mul_f32's exact expression; the down accumulation is a slot-ordered
3771            // __fmaf_rn chain == the sequential axpy_f32 chain (MEMRA_MOE_GDEC_GATE compares).
3772            // cfg.m3: the grouped kernels' fused epilogues are plain SiLU — M3's swigluoai must
3773            // NOT take them until the kernels grow the clamped variant. NVFP4 experts carry
3774            // per-expert macro-scales the fused kernels don't fold — those fall through too.
3775            let no_macros = m.gate_exps.macros.is_none() && m.up_exps.macros.is_none()
3776                && m.down_exps.macros.is_none();
3777            // SLAB-LOCAL FUSED PAIR (lane/pp-leverb 2026-08-08): the gdec launch pair
3778            // (moe_gate_up_silu8_q8 + moe_down8_fma_q8 — the EXACT kernels, same FP chains)
3779            // with pointers computed from the resident slab base + ex*stride instead of
3780            // collected SLRU slot addresses. No cache lock, no residency predicate — the
3781            // slab holds every expert by construction, so this arm never falls through
3782            // (gdec's P(all 24 resident) ≈ 0.37 coin-flip and the miss path's ~49-launch
3783            // staging both die). Bit-identity class: pointer provenance only, the same
3784            // slab-vs-SLRU equivalence moe_ffn_dev documents. Ordered BEFORE gdec: when a
3785            // slab exists it is strictly better (no lock, no miss).
3786            if slab_fused_may_fire {
3787                let (pg, pu, pd) = slab_bases.unwrap();
3788                let mut gp = [0u64; 8];
3789                let mut up = [0u64; 8];
3790                let mut dp = [0u64; 8];
3791                for (j, &ex) in sel.iter().enumerate() {
3792                    let ex = ex as usize;
3793                    gp[j] = pg + (ex * m.gate_exps.expert_stride) as u64;
3794                    up[j] = pu + (ex * m.up_exps.expert_stride) as u64;
3795                    dp[j] = pd + (ex * m.down_exps.expert_stride) as u64;
3796                }
3797                let mut wv = [0f32; 8];
3798                wv[..n_used].copy_from_slice(w);
3799                if tok_q8.is_none() {
3800                    tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3801                }
3802                let (zq, zd) = tok_q8.as_ref().unwrap();
3803                let act = e.moe_gate_up_silu8_q8(crate::WPtr8(gp), crate::WPtr8(up), zq, zd,
3804                                                 n_embd, n_ff_exp, n_used,
3805                                                 m.gate_exps.qtype, m.up_exps.qtype,
3806                                                 m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
3807                let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
3808                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3809                e.moe_down8_fma_q8(crate::WPtr8(dp), crate::F32x8(wv), &aq2, &ad2, &mut dst,
3810                                   n_ff_exp, n_embd, n_used,
3811                                   m.down_exps.qtype, m.down_exps.row_bytes)?;
3812                continue;
3813            }
3814            if gdec_may_fire && moe_q8 && cfg.m3.is_none() && no_macros {
3815                if tok_q8.is_none() {
3816                    tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3817                }
3818                let (zq, zd) = tok_q8.as_ref().unwrap();
3819                if Self::moe_gdec_token_q8(e, m, il, max_block, zq, zd, sel, w,
3820                                           &mut moe_out, tok, n_embd, n_ff_exp, n_used)? {
3821                    continue;
3822                }
3823            } else if gdec_may_fire && cfg.m3.is_none() && no_macros
3824                && Self::moe_gdec_token(e, m, il, max_block, &zt, sel, w,
3825                                        &mut moe_out, tok, n_embd, n_ff_exp, n_used)? {
3826                continue;
3827            }
3828
3829            // STAGE 2 memset-elision invariant: moe_out was allocated UNINIT when gdec or the
3830            // slab pair could fire. This token fell through to a sequential axpy loop, which
3831            // ACCUMULATES — zero its row first (row-sized memset; other rows are owned by the
3832            // full-overwrite arms). slab_fused_may_fire never actually reaches here (its arm
3833            // has no fallible predicate), included for the allocation invariant's symmetry.
3834            if gdec_may_fire || slab_fused_may_fire {
3835                let mut row = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3836                e.memset_zeros_view(&mut row)?;
3837            }
3838
3839            // Fiddler-style split at whole-expert granularity. Partial residency is deliberately a
3840            // CPU assignment: transferring the missing projection would reintroduce the PCIe/NVMe
3841            // stall this path exists to remove, while mixing projections would require another
3842            // activation round-trip. Weight addresses remain valid until this worker is joined at
3843            // the bottom of the token scope.
3844            let mut cpu_mask = vec![false; sel.len()];
3845            let cpu_worker = if let Some(host_input) = cpu_input.as_ref() {
3846                let gpu_resident = if use_cache {
3847                    e.with_moe_cache(max_block, |cache, _| {
3848                        Ok(sel
3849                            .iter()
3850                            .map(|&expert| {
3851                                let expert = expert as u16;
3852                                [PROJ_GATE, PROJ_UP, PROJ_DOWN]
3853                                    .into_iter()
3854                                    .filter(|&projection| {
3855                                        cache
3856                                            .resident(BlockId::new(il, projection, expert))
3857                                            .is_some()
3858                                    })
3859                                    .count()
3860                            })
3861                            .collect::<Vec<_>>())
3862                    })?
3863                } else {
3864                    vec![0; sel.len()]
3865                };
3866                let mut cpu_selected = Vec::new();
3867                for (index, (&expert, &route_weight)) in sel.iter().zip(w).enumerate() {
3868                    if gpu_resident[index] != 3 {
3869                        cpu_mask[index] = true;
3870                        crate::cpu_experts::record_incomplete_gpu_residency(gpu_resident[index]);
3871                        let expert = expert as usize;
3872                        cpu_selected.push((expert, route_weight));
3873                    }
3874                }
3875                if crate::cpu_experts::predictor_enabled() {
3876                    // Fire-and-forget lookahead: the predictor worker scores layers il+1..
3877                    // from this layer's MoE input and prefetches predicted-and-missing
3878                    // experts into the companion RAM cache. Never blocks this thread.
3879                    let row = &host_input[tok * n_embd..(tok + 1) * n_embd];
3880                    crate::cpu_experts::predictor_submit(il, row);
3881                }
3882                if cpu_selected.is_empty() {
3883                    None
3884                } else {
3885                    let row = &host_input[tok * n_embd..(tok + 1) * n_embd];
3886                    let job = crate::cpu_experts::prepare_job(m, il, &cpu_selected, row)
3887                        .map_err(std::io::Error::other)?;
3888                    Some(crate::cpu_experts::submit(job).map_err(std::io::Error::other)?)
3889                }
3890            } else {
3891                None
3892            };
3893
3894            let worker_window = worker_disk_prefetch
3895                .then(worker_prefetch_window)
3896                .unwrap_or(0);
3897            for (j, &ex) in sel.iter().enumerate() {
3898                if cpu_mask[j] {
3899                    continue;
3900                }
3901                let ex = ex as usize;
3902                // PER-EXPERT SLAB READ (lane/pp-leverb 2026-08-08): the layers the fused
3903                // pair above excludes — step35's CLAMPED layers 43/44 (ffn_act_lim has no
3904                // fused form) and macro-carrying artifacts — still have their bytes in the
3905                // local resident slab. Same kernels as the SLRU arms (`qmatvec_expert_q8` /
3906                // `qmatvec_view`), same ffn_act_lim/macro folds; provenance = slab base +
3907                // ex*stride. No dispatch lock, no admission, no prefetch — nothing to miss.
3908                if let Some(d) = slab_local {
3909                    let gl = m.gate_exps.expert_layout(ex);
3910                    let ul = m.up_exps.expert_layout(ex);
3911                    let dl = m.down_exps.expert_layout(ex);
3912                    let (g0, u0, d0) = (ex * m.gate_exps.expert_stride,
3913                                        ex * m.up_exps.expert_stride,
3914                                        ex * m.down_exps.expert_stride);
3915                    let (gate, up) = if moe_q8 {
3916                        if tok_q8.is_none() {
3917                            tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3918                        }
3919                        let (zq, zd) = tok_q8.as_ref().unwrap();
3920                        (e.qmatvec_expert_q8(&d.gate, g0..g0 + gl.len, zq, zd, 1,
3921                                             m.gate_exps.in_f, m.gate_exps.out_f,
3922                                             gl.qtype, gl.row_bytes)?,
3923                         e.qmatvec_expert_q8(&d.up, u0..u0 + ul.len, zq, zd, 1,
3924                                             m.up_exps.in_f, m.up_exps.out_f,
3925                                             ul.qtype, ul.row_bytes)?)
3926                    } else {
3927                        (e.qmatvec_view(&d.gate, g0..g0 + gl.len, &zt, 1,
3928                                        m.gate_exps.in_f, m.gate_exps.out_f,
3929                                        gl.qtype, gl.row_bytes)?,
3930                         e.qmatvec_view(&d.up, u0..u0 + ul.len, &zt, 1,
3931                                        m.up_exps.in_f, m.up_exps.out_f,
3932                                        ul.qtype, ul.row_bytes)?)
3933                    };
3934                    let mut act = e.uninit(n_ff_exp)?;
3935                    Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
3936                                      m.up_exps.macro_scale(ex), lim_exp, &mut act, n_ff_exp)?;
3937                    let y = if moe_q8 {
3938                        let (aq2, ad2) = e.quantize_q8_1(&act, 1, n_ff_exp)?;
3939                        e.qmatvec_expert_q8(&d.down, d0..d0 + dl.len, &aq2, &ad2, 1,
3940                                            m.down_exps.in_f, m.down_exps.out_f,
3941                                            dl.qtype, dl.row_bytes)?
3942                    } else {
3943                        let actv = act.slice(0..n_ff_exp);
3944                        e.qmatvec_view(&d.down, d0..d0 + dl.len, &actv, 1,
3945                                       m.down_exps.in_f, m.down_exps.out_f,
3946                                       dl.qtype, dl.row_bytes)?
3947                    };
3948                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3949                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
3950                    continue;
3951                }
3952                for next in page_prefetch_positions(j, sel.len(), page_window) {
3953                    Self::moe_prefetch_host_expert(sel[next] as usize, m);
3954                }
3955                let keep = [
3956                    crate::moe_cache::BlockId::new(il, crate::moe_cache::PROJ_GATE, ex as u16),
3957                    crate::moe_cache::BlockId::new(il, crate::moe_cache::PROJ_UP, ex as u16),
3958                    crate::moe_cache::BlockId::new(il, crate::moe_cache::PROJ_DOWN, ex as u16),
3959                ];
3960                if worker_disk_prefetch && worker_window > 0 {
3961                    for next in worker_prefetch_positions(j, sel.len(), worker_window) {
3962                        Self::moe_prefetch_disk_expert(
3963                            e,
3964                            il,
3965                            sel[next] as usize,
3966                            m,
3967                            max_block,
3968                            &keep,
3969                        )?;
3970                    }
3971                } else if cache_dispatch
3972                    && !cpu_hybrid
3973                    && moe_prefetch_enabled()
3974                    && j + 1 < sel.len()
3975                {
3976                    let next = sel[j + 1] as usize;
3977                    Self::moe_prefetch_expert(e, il, next, m, max_block, &keep)?;
3978                }
3979                let [gate_q8, up_q8, down_q8] = [moe_q8; 3];
3980                if cache_dispatch && (gate_q8 || up_q8 || down_q8) {
3981                    // dp4a EXPERT PATH (MEMRA_MOE_Q8): quantize z-row once per token. Mixed expert
3982                    // layouts stay on the metadata-aware f32 path.
3983                    if (gate_q8 || up_q8) && tok_q8.is_none() {
3984                        tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3985                    }
3986                    let gate = if gate_q8 {
3987                        let (zq, zd) = tok_q8.as_ref().unwrap();
3988                        Self::moe_cached_gemm_q8(e, il, PROJ_GATE, ex, m, max_block, zq, zd)?
3989                    } else {
3990                        Self::moe_cached_gemm(e, il, PROJ_GATE, ex, m, max_block, &zt)?
3991                    };
3992                    let up = if up_q8 {
3993                        let (zq, zd) = tok_q8.as_ref().unwrap();
3994                        Self::moe_cached_gemm_q8(e, il, PROJ_UP, ex, m, max_block, zq, zd)?
3995                    } else {
3996                        Self::moe_cached_gemm(e, il, PROJ_UP, ex, m, max_block, &zt)?
3997                    };
3998                    let mut act = e.uninit(n_ff_exp)?;
3999                    Self::ffn_act_lim(
4000                        e,
4001                        cfg,
4002                        &gate,
4003                        &up,
4004                        m.gate_exps.macro_scale(ex),
4005                        m.up_exps.macro_scale(ex),
4006                        lim_exp,
4007                        &mut act,
4008                        n_ff_exp,
4009                    )?;
4010                    let y = if down_q8 {
4011                        let (aq2, ad2) = e.quantize_q8_1(&act, 1, n_ff_exp)?;
4012                        Self::moe_cached_gemm_q8(e, il, PROJ_DOWN, ex, m, max_block, &aq2, &ad2)?
4013                    } else {
4014                        let actv = act.slice(0..n_ff_exp);
4015                        Self::moe_cached_gemm(e, il, PROJ_DOWN, ex, m, max_block, &actv)?
4016                    };
4017                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4018                    // down-proj macro folds into the accumulate weight (1.0 for non-macro archs).
4019                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
4020                } else if cache_dispatch {
4021                    // SLRU residency cache: per-projection, dispatch the block (HIT => resident slot,
4022                    // MISS => staged slot) then run the SAME unchanged qmatvec_view from that slot.
4023                    // The bytes the kernel reads are byte-for-byte the same GGUF block (§B.3); the
4024                    // only difference between HIT and MISS is whether the memcpy_htod ran.
4025                    let gate = Self::moe_cached_gemm(e, il, PROJ_GATE, ex, m, max_block, &zt)?;
4026                    let up   = Self::moe_cached_gemm(e, il, PROJ_UP,   ex, m, max_block, &zt)?;
4027                    let mut act = e.uninit(n_ff_exp)?;  // activation fully overwrites
4028                    Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
4029                        m.up_exps.macro_scale(ex), lim_exp, &mut act, n_ff_exp)?;
4030                    let actv = act.slice(0..n_ff_exp);
4031                    let y = Self::moe_cached_gemm(e, il, PROJ_DOWN, ex, m, max_block, &actv)?;
4032                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4033                    // down-proj macro folds into the accumulate weight (post-matmul linear scale).
4034                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
4035                } else if cache_frozen {
4036                    // A later prompt prime must not change the CPU/GPU assignment frozen after the
4037                    // first prime. Reuse every fixed resident projection directly and stage only a
4038                    // true miss through the ordinary scratch slot. This preserves the established
4039                    // f32-dequant numeric path while avoiding a full-bank reread on every prime.
4040                    let gate = Self::moe_frozen_gemm(
4041                        e,
4042                        il,
4043                        PROJ_GATE,
4044                        ex,
4045                        m,
4046                        max_block,
4047                        &zt,
4048                        &mut scratch_g,
4049                        g_len,
4050                    )?;
4051                    let up = Self::moe_frozen_gemm(
4052                        e,
4053                        il,
4054                        PROJ_UP,
4055                        ex,
4056                        m,
4057                        max_block,
4058                        &zt,
4059                        &mut scratch_u,
4060                        u_len,
4061                    )?;
4062                    let mut act = e.uninit(n_ff_exp)?;
4063                    Self::ffn_act_lim(
4064                        e,
4065                        cfg,
4066                        &gate,
4067                        &up,
4068                        m.gate_exps.macro_scale(ex),
4069                        m.up_exps.macro_scale(ex),
4070                        lim_exp,
4071                        &mut act,
4072                        n_ff_exp,
4073                    )?;
4074                    let actv = act.slice(0..n_ff_exp);
4075                    let y = Self::moe_frozen_gemm(
4076                        e,
4077                        il,
4078                        PROJ_DOWN,
4079                        ex,
4080                        m,
4081                        max_block,
4082                        &actv,
4083                        &mut scratch_d,
4084                        d_len,
4085                    )?;
4086                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4087                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
4088                } else {
4089                    // Stage-1: stage gate/up/down for expert `ex` into the scratch slots, then GEMM.
4090                    // Lazy scratch: first no-cache expert allocates the 3 slots (uninit — stage_expert
4091                    // fully overwrites the byte range the GEMM reads).
4092                    if scratch_g.is_none() {
4093                        scratch_g = Some(e.alloc_u8_uninit(g_len)?);
4094                        scratch_u = Some(e.alloc_u8_uninit(u_len)?);
4095                        scratch_d = Some(e.alloc_u8_uninit(d_len)?);
4096                    }
4097                    let (sg, su, sd) = (scratch_g.as_mut().unwrap(), scratch_u.as_mut().unwrap(),
4098                                        scratch_d.as_mut().unwrap());
4099                    let gl = m.gate_exps.expert_layout(ex);
4100                    let ul = m.up_exps.expert_layout(ex);
4101                    let dl = m.down_exps.expert_layout(ex);
4102                    e.stage_expert(m.gate_exps.expert_bytes(ex), sg, 0)?;
4103                    let gate = e.qmatvec_view(sg, 0..gl.len, &zt, 1,
4104                        m.gate_exps.in_f, m.gate_exps.out_f, gl.qtype, gl.row_bytes)?;
4105
4106                    e.stage_expert(m.up_exps.expert_bytes(ex), su, 0)?;
4107                    let up = e.qmatvec_view(su, 0..ul.len, &zt, 1,
4108                        m.up_exps.in_f, m.up_exps.out_f, ul.qtype, ul.row_bytes)?;
4109
4110                    let mut act = e.uninit(n_ff_exp)?;  // activation fully overwrites
4111                    Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
4112                        m.up_exps.macro_scale(ex), lim_exp, &mut act, n_ff_exp)?;
4113
4114                    e.stage_expert(m.down_exps.expert_bytes(ex), sd, 0)?;
4115                    let actv = act.slice(0..n_ff_exp);
4116                    let y = e.qmatvec_view(sd, 0..dl.len, &actv, 1,
4117                        m.down_exps.in_f, m.down_exps.out_f, dl.qtype, dl.row_bytes)?;
4118
4119                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4120                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
4121                }
4122            }
4123            if let Some(worker) = cpu_worker {
4124                let cpu_output = worker.wait().map_err(std::io::Error::other)?;
4125                let cpu_output = e.htod(&cpu_output)?;
4126                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4127                e.axpy_into(&cpu_output, 1.0, &mut dst, n_embd)?;
4128            }
4129            if cpu_hybrid && !cache_frozen && cpu_expert_profile_admit_enabled() {
4130                for (j, &ex) in sel.iter().enumerate() {
4131                    if cpu_mask[j] {
4132                        Self::moe_profile_admit_expert(e, il, ex as usize, m, max_block)?;
4133                    }
4134                }
4135            }
4136        }
4137
4138        // 3. SHARED EXPERT (ALWAYS-ON, no routing) on the SAME z — qwen35moe only. OLMoE and most
4139        //    vanilla MoE have NO shared expert (the shexp tensors are absent / `None`); skip it then.
4140        // gate_inp_shexp is OPTIONAL: qwen35moe gates the shared expert (sigmoid(gate_inp) x sh);
4141        // MiniMax-M3 (DeepSeek-V3 class) has NO shexp gate — the shared expert adds directly.
4142        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
4143            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
4144        {
4145            let n_ff_sh = gate_shexp.out_features();  // 512
4146            // Q8 TRUNK-FUSION (decode t=1): gate_shexp+up_shexp are Q8_0 same-shape on the 35B —
4147            // ONE fused2 launch (also folds the two per-matmul re-quantizes of z into one).
4148            // Bit-identical per (tensor,row); falls back to the two matmul calls when ineligible.
4149            // Small-t (spec verify 2..15) rides matmul_decode_exact so shexp FP chains match the
4150            // t==1 decode chain per column (cuBLASLt n-dependence + dp4a-vs-mmvq class); real
4151            // prefill keeps the batched matmul. Activation routes through ffn_act (SiLU for
4152            // softmax archs, clamped swigluoai for M3 — identical to silu_mul when cfg.m3 is None).
4153            let verify_t = t > 1 && t < PRIME_MIN_T;
4154            let (sg_gate, sg_up) = if t == 1 {
4155                match e.matmul_q8_fused2_x(gate_shexp, up_shexp, z)? {
4156                    Some(pair) => pair,
4157                    None => (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?),
4158                }
4159            } else if verify_t {
4160                (e.matmul_decode_exact(gate_shexp, z, t)?, e.matmul_decode_exact(up_shexp, z, t)?)
4161            } else {
4162                (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?)   // [T, 512] each
4163            };
4164            let mut sa = e.uninit(t * n_ff_sh)?;  // activation fully overwrites
4165            Self::ffn_act_lim(e, cfg, &sg_gate, &sg_up, 1.0, 1.0, lim_shexp, &mut sa, t * n_ff_sh)?;
4166            let sh = if verify_t { e.matmul_decode_exact(down_shexp, &sa, t)? }
4167                     else { e.matmul(down_shexp, &sa, t)? };     // [T, n_embd]
4168
4169            // shexp gate: qwen35moe sigmoid-gates via ffn_gate_inp_shexp (1-D ne=[n_embd] ->
4170            // out_f=1); M3 has no gate tensor -> weight 1.0. Decode + verify ride the fused
4171            // sigmoid-dot kernel (one fold order for both chains; kills the per-layer
4172            // cuBLASLt m=1 splitK GEMM — 40x/step, ~10% of the H100 q35 decode step).
4173            // SERVE ISOLATION (lane/concat-prime-exact, 2026-08-02): PREFILL rides it too.
4174            // This out_f=1 cuBLASLt GEMV is the SECOND m-dependent op in the trunk (probed:
4175            // rows [0,19) move by 1.07e-4 between m=74 and m=75 while sigmoid_dot_rows is
4176            // BIT-IDENTICAL — allw-shexpgate-o35b.log). The gate multiplies the shared
4177            // expert's contribution into every token's residual, so under cross-request
4178            // concat prefill a session's hidden state depended on its co-arrivals' token
4179            // count. MEMRA_ROUTER_PREFILL_EXACT=0 reverts to the batched cuBLASLt linear.
4180            let g = match &m.gate_inp_shexp {
4181                Some(gate_inp_shexp) => {
4182                    if t < PRIME_MIN_T || crate::router_prefill_exact_on() {
4183                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
4184                    } else {
4185                        let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
4186                        let mut g = e.uninit(t)?;  // sigmoid fully overwrites
4187                        e.sigmoid(&gs, &mut g, t)?;
4188                        g
4189                    }
4190                }
4191                None => e.htod(&vec![1.0f32; t])?,
4192            };
4193            // moe_out[r, :] += sh[r, :] * g[r]   (per-token scalar gate; g=1 ungated)
4194            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
4195        }
4196
4197        Ok(moe_out)
4198    }
4199
4200    /// Stage-1 (no-cache) per-DECODE-TOKEN H2D bytes: every routed block re-staged every layer every
4201    /// token = sum over MoE layers of n_used * (gate+up+down expert_stride). The §D.4 PCIe baseline.
4202    pub fn stage1_h2d_per_token(&self) -> u64 {
4203        use crate::hybrid::Ffn;
4204        let n_used = self.cfg.moe.as_ref().map(|m| m.expert_used_count as u64).unwrap_or(0);
4205        let mut bytes = 0u64;
4206        for l in self.layers.iter() {
4207            if let Ffn::Moe(m) = &l.ffn {
4208                bytes += n_used * (m.gate_exps.max_expert_bytes() + m.up_exps.max_expert_bytes()
4209                                   + m.down_exps.max_expert_bytes()) as u64;
4210            }
4211        }
4212        bytes
4213    }
4214
4215    /// Largest expert block (bytes) across ALL MoE layers + the MTP head — the fixed cache slot size.
4216    /// UD/dynamic GGUFs quant different layers differently, so `expert_stride` varies per layer; the
4217    /// residency cache slots are fixed-address and must fit any block, so size to this global max.
4218    pub(crate) fn max_moe_block(&self) -> usize {
4219        use crate::hybrid::Ffn;
4220        let mut mx = 0usize;
4221        let mut scan = |ffn: &Ffn| {
4222            if let Ffn::Moe(m) = ffn {
4223                mx = mx.max(m.gate_exps.max_expert_bytes())
4224                       .max(m.up_exps.max_expert_bytes())
4225                       .max(m.down_exps.max_expert_bytes());
4226            }
4227        };
4228        for l in self.layers.iter() { scan(&l.ffn); }
4229        if let Some(mtp) = self.mtp.as_ref() { scan(&mtp.ffn); }
4230        mx
4231    }
4232
4233    /// Exact retained projection lengths for cache class sizing. Pruned ids keep router positions
4234    /// but have no bytes and therefore consume no residency slot.
4235    pub(crate) fn moe_cache_block_sizes(&self) -> Vec<usize> {
4236        use crate::hybrid::Ffn;
4237        let mut sizes = Vec::new();
4238        let mut scan = |ffn: &Ffn| {
4239            let Ffn::Moe(m) = ffn else { return };
4240            for ex in 0..m.gate_exps.n_expert {
4241                if m.active_experts.as_ref().is_some_and(|active| !active[ex]) {
4242                    continue;
4243                }
4244                for exps in [&m.gate_exps, &m.up_exps, &m.down_exps] {
4245                    let len = exps.expert_layout(ex).len;
4246                    if len > 0 {
4247                        sizes.push(len);
4248                    }
4249                }
4250            }
4251        };
4252        for layer in &self.layers {
4253            scan(&layer.ffn);
4254        }
4255        if let Some(mtp) = &self.mtp {
4256            scan(&mtp.ffn);
4257        }
4258        sizes
4259    }
4260
4261    /// Persist the frozen residency set so a later process can restage it directly and skip
4262    /// the profiling warmup. Plain text: a versioned header binding slot geometry, then one
4263    /// `layer proj ex` triple per line. A mismatched or stale profile is rejected at load
4264    /// (header check) or degrades to fewer restaged blocks (per-id checks); either way the
4265    /// post-freeze argmax gate still validates the serving assignment.
4266    pub fn save_cpu_expert_residency_profile(
4267        &self,
4268        e: &Engine,
4269        path: &std::path::Path,
4270    ) -> Result<(), Box<dyn std::error::Error>> {
4271        let Some(ids) = e.export_moe_residency() else {
4272            return Err("no MoE residency cache to persist".into());
4273        };
4274        let mut body = format!(
4275            "memra-freeze-profile v1 max_block={} blocks={}\n",
4276            self.max_moe_block(),
4277            ids.len()
4278        );
4279        for (layer, proj, ex) in &ids {
4280            body.push_str(&format!("{layer} {proj} {ex}\n"));
4281        }
4282        let tmp = path.with_extension("tmp");
4283        std::fs::write(&tmp, body)?;
4284        std::fs::rename(&tmp, path)?;
4285        println!(
4286            "[moe-cache] freeze profile saved: {} blocks -> {}",
4287            ids.len(),
4288            path.display()
4289        );
4290        Ok(())
4291    }
4292
4293    /// Restage a saved freeze profile and freeze immediately, skipping the profiling warmup.
4294    /// Returns false (leaving the cache untouched for a normal warmup) when the profile is
4295    /// missing or its header does not match this model's slot geometry.
4296    pub fn restore_cpu_expert_residency_profile(
4297        &self,
4298        e: &Engine,
4299        path: &std::path::Path,
4300    ) -> Result<bool, Box<dyn std::error::Error>> {
4301        use crate::hybrid::Ffn;
4302        use crate::moe_cache::BlockId;
4303        let Ok(content) = std::fs::read_to_string(path) else {
4304            return Ok(false);
4305        };
4306        let mut lines = content.lines();
4307        let Some(header) = lines.next() else { return Ok(false) };
4308        let expected = format!("memra-freeze-profile v1 max_block={}", self.max_moe_block());
4309        if !header.starts_with(&expected) {
4310            println!(
4311                "[moe-cache] freeze profile ignored (geometry mismatch): {}",
4312                path.display()
4313            );
4314            return Ok(false);
4315        }
4316        let mut by_layer: std::collections::HashMap<u16, Vec<BlockId>> =
4317            std::collections::HashMap::new();
4318        for line in lines {
4319            let mut fields = line.split_whitespace();
4320            let (Some(layer), Some(proj), Some(ex)) =
4321                (fields.next(), fields.next(), fields.next())
4322            else {
4323                continue;
4324            };
4325            let (Ok(layer), Ok(proj), Ok(ex)) =
4326                (layer.parse::<u16>(), proj.parse::<u8>(), ex.parse::<u16>())
4327            else {
4328                continue;
4329            };
4330            by_layer
4331                .entry(layer)
4332                .or_default()
4333                .push(BlockId::new(layer, proj, ex));
4334        }
4335        let requested: usize = by_layer.values().map(Vec::len).sum();
4336        if requested == 0 {
4337            return Ok(false);
4338        }
4339        let max_block = self.max_moe_block();
4340        let mut restaged = 0usize;
4341        let mut stage_layer = |layer_index: u16,
4342                               ffn: &Ffn|
4343         -> Result<(), Box<dyn std::error::Error>> {
4344            let Ffn::Moe(m) = ffn else { return Ok(()) };
4345            let Some(ids) = by_layer.get(&layer_index) else {
4346                return Ok(());
4347            };
4348            e.with_moe_cache(max_block, |cache, eng| {
4349                for id in ids {
4350                    if cache.restage_block(*id, m, eng)? {
4351                        restaged += 1;
4352                    }
4353                }
4354                Ok(())
4355            })
4356        };
4357        for (index, layer) in self.layers.iter().enumerate() {
4358            stage_layer(index as u16, &layer.ffn)?;
4359        }
4360        if let Some(mtp) = self.mtp.as_ref() {
4361            stage_layer(u16::MAX, &mtp.ffn)?;
4362        }
4363        e.freeze_moe_cache();
4364        println!(
4365            "[moe-cache] freeze profile restored: {restaged}/{requested} blocks restaged from {}",
4366            path.display()
4367        );
4368        Ok(true)
4369    }
4370
4371    /// Freeze the heterogeneous CPU/GPU split after the caller's discarded profile warmup.
4372    pub fn freeze_cpu_expert_residency(
4373        &self,
4374        e: &Engine,
4375    ) -> Result<(), Box<dyn std::error::Error>> {
4376        e.freeze_moe_cache();
4377        Ok(())
4378    }
4379
4380    /// FFN activation dispatch: swigluoai (clamped, alpha/limit) when cfg.m3 says so, else the
4381    /// standard SiLU*up. One seam so every FFN site (dense, routed expert, shared expert) follows
4382    /// the model's activation exactly.
4383    ///
4384    /// NO-`il` FORM: cannot apply step35's PER-LAYER SwiGLU clamp. Only call it from a site whose
4385    /// layer provably has no live limit (dense-FFN layers, MTP blocks) — `ffn_act_lim` is the
4386    /// form for anything that can land on a clamped layer.
4387    pub fn ffn_act(e: &Engine, cfg: &ModelConfig, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
4388               act: &mut CudaSlice<f32>, n: usize) -> Result<(), Box<dyn std::error::Error>> {
4389        Self::ffn_act_scaled(e, cfg, gate, up, 1.0, 1.0, act, n)
4390    }
4391
4392    /// ffn_act with per-tensor post-matmul macro-scales folded in (gs/us == 1.0 -> identical
4393    /// float ops to ffn_act; used by the ModelOpt NVFP4 expert path where each expert tensor
4394    /// carries a `weight_scale_2`). Same no-`il` contract as `ffn_act`.
4395    #[allow(clippy::too_many_arguments)]
4396    pub(crate) fn ffn_act_scaled(e: &Engine, cfg: &ModelConfig, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
4397               gs: f32, us: f32, act: &mut CudaSlice<f32>, n: usize)
4398               -> Result<(), Box<dyn std::error::Error>> {
4399        Self::ffn_act_lim(e, cfg, gate, up, gs, us, None, act, n)
4400    }
4401
4402    /// ffn_act_scaled + step35's PER-LAYER clamped SwiGLU. `limit`:
4403    ///   * `None`   -> the unclamped dispatch (every arch except step35's layers 43-44).
4404    ///   * `Some(l)`-> `min(silu(gate*gs), l) * clamp(up*us, +-l)` (llama-graph.cpp:2146/1751,
4405    ///                 non-DEEPSEEK4 branch). Callers source it from `cfg.clamp_exp_at(il)`
4406    ///                 (routed experts) or `cfg.clamp_shexp_at(il)` (shared expert) — the two
4407    ///                 arrays are SEPARATE and a layer can have one without the other.
4408    /// The `> 1e-6` eps gate lives in `clamp_exp_at`/`clamp_shexp_at`, so a `Some` here is
4409    /// already known live.
4410    #[allow(clippy::too_many_arguments)]
4411    pub(crate) fn ffn_act_lim(e: &Engine, cfg: &ModelConfig, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
4412               gs: f32, us: f32, limit: Option<f32>, act: &mut CudaSlice<f32>, n: usize)
4413               -> Result<(), Box<dyn std::error::Error>> {
4414        if let Some(m3) = cfg.m3.as_ref() {
4415            debug_assert!(limit.is_none(), "m3 swigluoai and step35 clamp are different archs");
4416            return e.swigluoai_mul_scaled(gate, up, gs, us, m3.swiglu_alpha, m3.swiglu_limit, act, n);
4417        }
4418        if let Some(l) = limit {
4419            return e.swiglu_clamped_mul_scaled(gate, up, gs, us, l, act, n);
4420        }
4421        if gs == 1.0 && us == 1.0 { return e.silu_mul(gate, up, act, n); }
4422        e.silu_mul_scaled(gate, up, gs, us, act, n)
4423    }
4424
4425    /// Routing for the whole batch: returns (sel [T*n_used] expert ids, w [T*n_used] renorm weights),
4426    /// token-major. Default = the Stage-1 host path (dtoh logits, softmax-256, stable DESC top-k,
4427    /// renorm). MEMRA_FUSED_ROUTER = the device kernel (§A) which reproduces the same numerics; we
4428    /// still dtoh the tiny [T,n_used] sel/w buffers (64 B/token vs 1 KB/token) — the host loop
4429    /// indexes HostExps.bytes on the CPU to choose the DMA source (§A.2 output staging).
4430    fn moe_route(e: &Engine, logits: &CudaSlice<f32>, t: usize, n_expert: usize, n_used: usize)
4431                 -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4432        Self::moe_route_cfg(e, logits, t, n_expert, n_used, None)
4433    }
4434
4435    /// DeepSeek-V3-class sigmoid routing (Step-3.7, MiniMax-M3, Hy3, GLM-DSA). Reference:
4436    /// M3/Hy3 modeling code — scores = sigmoid(logits); selection over scores + expert bias
4437    /// (M3 `e_score_correction_bias` / Hy3 `expert_bias`, both surfaced as `exp_probs_b`);
4438    /// weights = un-biased scores of the selected experts, sum-normalized when `route_norm`,
4439    /// x scaling factor (M3 routed_scaling_factor 2.0 / Hy3 router_scaling_factor 2.826).
4440    /// Default uses one device kernel plus the same pinned sel/w readback contract as the fused
4441    /// softmax router. `MEMRA_SIG_ROUTER=0` restores the full-logit DtoH host oracle.
4442    #[allow(clippy::too_many_arguments)]
4443    fn moe_route_sigmoid_cfg(
4444        e: &Engine,
4445        logits: &CudaSlice<f32>,
4446        t: usize,
4447        n_expert: usize,
4448        n_used: usize,
4449        m: &MoeWeights,
4450        (sf, route_norm): (f32, bool),
4451    ) -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4452        if sigmoid_router_enabled() {
4453            return e.moe_router_sigmoid_topk_host(
4454                logits,
4455                t,
4456                n_expert,
4457                n_used,
4458                m.active_count(),
4459                &m.exp_probs_b_dev,
4460                &m.active_experts_dev,
4461                sf,
4462                route_norm,
4463            );
4464        }
4465        let lg = e.dtoh(logits)?;
4466        Self::moe_route_sigmoid_host(
4467            &lg,
4468            t,
4469            n_expert,
4470            n_used,
4471            m.exp_probs_b.as_deref(),
4472            sf,
4473            route_norm,
4474            m.active_experts.as_deref(),
4475        )
4476    }
4477
4478    /// Softmax router for qwen35moe/OLMoE. An active-mask overlay retains the host oracle because
4479    /// the existing softmax device kernel has no mask input.
4480    fn moe_route_cfg(e: &Engine, logits: &CudaSlice<f32>, t: usize, n_expert: usize, n_used: usize,
4481                     active: Option<&[bool]>)
4482                 -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4483        // LAUNCH-STRUCTURE STAGE 1 (2026-07-05): fused router DEFAULT ON (MEMRA_FUSED_ROUTER=0
4484        // rollback) via the single-sync pinned readback — softmax arch only.
4485        if active.is_none() && !matches!(std::env::var("MEMRA_FUSED_ROUTER").as_deref(), Ok("0")) {
4486            return e.moe_router_topk_host(logits, t, n_expert, n_used);
4487        }
4488        // Host oracle (the §D bit-identity reference).
4489        let lg = e.dtoh(logits)?;   // [T*n_expert] host
4490        let mut sel = vec![0u32; t * n_used];
4491        let mut w_out = vec![0f32; t * n_used];
4492        for tok in 0..t {
4493            let row = &lg[tok * n_expert..(tok + 1) * n_expert];
4494            // softmax over ALL n_expert (stable: subtract max)
4495            let maxl = row.iter().enumerate()
4496                .filter(|(i, _)| active.is_none_or(|mask| mask[*i]))
4497                .map(|(_, &x)| x).fold(f32::NEG_INFINITY, f32::max);
4498            let mut probs = vec![0f32; n_expert];
4499            let mut den = 0f32;
4500            for i in 0..n_expert {
4501                if active.is_some_and(|mask| !mask[i]) { continue; }
4502                let x = (row[i] - maxl).exp(); probs[i] = x; den += x;
4503            }
4504            for p in probs.iter_mut() { *p /= den; }
4505            // stable DESC sort: prob DESC, ascending-index tiebreak.
4506            let mut idx: Vec<usize> = (0..n_expert)
4507                .filter(|&i| active.is_none_or(|mask| mask[i])).collect();
4508            idx.sort_by(|&a, &b| probs[b].total_cmp(&probs[a]).then(a.cmp(&b)));
4509            let sl = &idx[..n_used];
4510            let mut wv: Vec<f32> = sl.iter().map(|&i| probs[i]).collect();
4511            let mut ws: f32 = wv.iter().sum();
4512            ws = ws.max(6.103515625e-5_f32);  // F16 smallest normal, clamp BEFORE divide
4513            for x in wv.iter_mut() { *x /= ws; }
4514            for j in 0..n_used {
4515                sel[tok * n_used + j] = sl[j] as u32;
4516                w_out[tok * n_used + j] = wv[j];
4517            }
4518        }
4519        Ok((sel, w_out))
4520    }
4521
4522    #[allow(clippy::too_many_arguments)]
4523    fn moe_route_sigmoid_with_input(
4524        e: &Engine,
4525        logits: &CudaSlice<f32>,
4526        input: &CudaSlice<f32>,
4527        t: usize,
4528        n_expert: usize,
4529        n_used: usize,
4530        bias: Option<&[f32]>,
4531        (sf, route_norm): (f32, bool),
4532        active: Option<&[bool]>,
4533    ) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>), Box<dyn std::error::Error>> {
4534        let (lg, input) = e.dtoh_pair(logits, input)?;
4535        let (sel, w) =
4536            Self::moe_route_sigmoid_host(&lg, t, n_expert, n_used, bias, sf, route_norm, active)?;
4537        Ok((sel, w, input))
4538    }
4539
4540    /// Start the prediction-guided prefetch worker (MEMRA_MOE_PREFETCH=depth). Call after
4541    /// residency freeze: the worker filters against a static snapshot of the frozen HBM set.
4542    /// Builds a fully-owned per-layer table (host router copies via one-time DtoH, bias,
4543    /// active mask, prebuilt projection descriptors) so no model reference escapes.
4544    pub fn start_moe_prefetch_predictor(
4545        &self,
4546        e: &Engine,
4547        cfg: &ModelConfig,
4548    ) -> Result<(), Box<dyn std::error::Error>> {
4549        use crate::hybrid::Ffn;
4550        let Some(sig) = cfg.sigmoid_router() else {
4551            return Err("prefetch predictor requires a sigmoid-router arch".into());
4552        };
4553        let resident: std::collections::HashSet<(u16, u8, u16)> = e
4554            .export_moe_residency()
4555            .ok_or("prefetch predictor needs the frozen MoE residency cache")?
4556            .into_iter()
4557            .collect();
4558        let mut layers = Vec::new();
4559        for (index, layer) in self.layers.iter().enumerate() {
4560            let Ffn::Moe(m) = &layer.ffn else { continue };
4561            let crate::model::GpuTensor::Float { data, .. } = &m.gate_inp else { continue };
4562            let router = e.dtoh(data)?;
4563            let n_expert = m.gate_exps.n_expert;
4564            let n_embd = m.gate_exps.in_f;
4565            if router.len() != n_embd * n_expert {
4566                continue;
4567            }
4568            let build = |exps: &crate::model::HostExps| {
4569                (0..n_expert)
4570                    .map(|expert| crate::cpu_experts::predictor_projection(exps, expert))
4571                    .collect::<Vec<_>>()
4572            };
4573            layers.push((index as u16, crate::cpu_experts::PredictLayerInit {
4574                router,
4575                bias: m.exp_probs_b.clone(),
4576                active: m.active_experts.clone(),
4577                n_embd,
4578                n_used: cfg
4579                    .moe
4580                    .as_ref()
4581                    .map(|moe| moe.expert_used_count as usize)
4582                    .ok_or("prefetch predictor requires MoE config")?,
4583                sig,
4584                weights_n_expert: n_expert,
4585                gate: build(&m.gate_exps),
4586                up: build(&m.up_exps),
4587                down: build(&m.down_exps),
4588            }));
4589        }
4590        crate::cpu_experts::start_prefetch_predictor(layers, resident)
4591            .map_err(|error| error.into())
4592    }
4593
4594    /// Sigmoid-routing oracle shared by the prefetch predictor and `kernel-check`: identical
4595    /// selection math to the rollback runtime, applied to host-computed logits.
4596    #[allow(clippy::too_many_arguments)]
4597    pub fn moe_route_sigmoid_host_public(
4598        logits: &[f32],
4599        t: usize,
4600        n_expert: usize,
4601        n_used: usize,
4602        bias: Option<&[f32]>,
4603        sf: f32,
4604        route_norm: bool,
4605        active: Option<&[bool]>,
4606    ) -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4607        Self::moe_route_sigmoid_host(logits, t, n_expert, n_used, bias, sf, route_norm, active)
4608    }
4609
4610    #[allow(clippy::too_many_arguments)]
4611    fn moe_route_sigmoid_host(
4612        lg: &[f32],
4613        t: usize,
4614        n_expert: usize,
4615        n_used: usize,
4616        bias: Option<&[f32]>,
4617        sf: f32,
4618        route_norm: bool,
4619        active: Option<&[bool]>,
4620    ) -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4621        let active_count = active
4622            .map(|mask| mask.iter().filter(|&&enabled| enabled).count())
4623            .unwrap_or(n_expert);
4624        crate::sigrouter_contract::validate_active_count(n_used, active_count)?;
4625        if lg.len() != t * n_expert {
4626            return Err(format!(
4627                "sigmoid router logits length mismatch: got {}, expected {}",
4628                lg.len(),
4629                t * n_expert,
4630            )
4631            .into());
4632        }
4633        let mut sel = vec![0u32; t * n_used];
4634        let mut w_out = vec![0f32; t * n_used];
4635        for tok in 0..t {
4636            let row = &lg[tok * n_expert..(tok + 1) * n_expert];
4637            let scores: Vec<f32> = row.iter().map(|&x| 1.0 / (1.0 + (-x).exp())).collect();
4638            // selection score = sigmoid + bias; weight = plain sigmoid.
4639            let selsc: Vec<f32> = match bias {
4640                Some(b) => scores.iter().zip(b).map(|(s, bb)| s + bb).collect(),
4641                None => scores.clone(),
4642            };
4643            let mut idx: Vec<usize> = (0..n_expert)
4644                .filter(|&i| active.is_none_or(|mask| mask[i]))
4645                .collect();
4646            idx.sort_by(|&a, &b| selsc[b].total_cmp(&selsc[a]).then(a.cmp(&b)));
4647            let sl = &idx[..n_used];
4648            let mut wv: Vec<f32> = sl.iter().map(|&i| scores[i]).collect();
4649            if route_norm {
4650                let ws: f32 = wv.iter().sum::<f32>().max(1e-20);
4651                for x in wv.iter_mut() {
4652                    *x = *x / ws * sf;
4653                }
4654            } else {
4655                for x in wv.iter_mut() {
4656                    *x *= sf;
4657                }
4658            }
4659            for j in 0..n_used {
4660                sel[tok * n_used + j] = sl[j] as u32;
4661                w_out[tok * n_used + j] = wv[j];
4662            }
4663        }
4664        Ok((sel, w_out))
4665    }
4666
4667    /// Step-3.7 resident-slab dispatch: sigmoid top-k outputs remain on device and feed the
4668    /// existing slot-ordered q8 expert kernels directly. Mixed layouts, spill, remote slabs,
4669    /// macro-scaled experts, and observation modes are denied by the caller.
4670    #[allow(clippy::too_many_arguments)]
4671    fn moe_ffn_sigmoid_dev(
4672        e: &Engine,
4673        m: &MoeWeights,
4674        z: &CudaSlice<f32>,
4675        zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>,
4676        logits: &CudaSlice<f32>,
4677        t: usize,
4678        cfg: &ModelConfig,
4679        il: u16,
4680        (scaling_factor, route_norm): (f32, bool),
4681    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4682        let moe = cfg.moe.as_ref().unwrap();
4683        let n_embd = cfg.n_embd as usize;
4684        let n_expert = moe.expert_count as usize;
4685        let n_used = moe.expert_used_count as usize;
4686        let n_ff_exp = moe.expert_ff_length as usize;
4687        let dev = m.dev_exps.as_ref().unwrap();
4688        debug_assert!(cfg.step35.is_some());
4689        debug_assert_eq!(dev.dev, e.ctx().ordinal());
4690        debug_assert!(m.has_uniform_expert_layout());
4691        debug_assert!(!m.has_macros);
4692
4693        let (sel_d, w_d) = e.moe_router_sigmoid_topk(
4694            logits,
4695            t,
4696            n_expert,
4697            n_used,
4698            m.active_count(),
4699            &m.exp_probs_b_dev,
4700            &m.active_experts_dev,
4701            scaling_factor,
4702            route_norm,
4703        )?;
4704        let (gate_row_bytes, up_row_bytes) = if dev.gu_il {
4705            let combined = m.gate_exps.row_bytes + m.up_exps.row_bytes;
4706            (combined, combined)
4707        } else {
4708            (m.gate_exps.row_bytes, m.up_exps.row_bytes)
4709        };
4710        let (zq, zd) = match (t, zq8) {
4711            (1, Some((q, d))) => (q.clone(), d.clone()),
4712            _ => e.quantize_q8_1(z, t, n_embd)?,
4713        };
4714        let n_pairs = t * n_used;
4715        let mut moe_out = if cfg.clamp_exp_at(il as u32).is_some() {
4716            // The final Step layers retain the established separate gate/up -> clamp -> down
4717            // arithmetic. Pair rows are derived from token position; selected expert ids and
4718            // routing weights remain the device router's buffers throughout.
4719            let pair_tok: Vec<i32> = (0..n_pairs)
4720                .map(|pair| (pair / n_used) as i32)
4721                .collect();
4722            let pair_tok_d = e.htod_i32(&pair_tok)?;
4723            let gate = e.moe_pairs_matvec_q8(
4724                &dev.ptr_row,
4725                0,
4726                &pair_tok_d,
4727                &sel_d,
4728                &zq,
4729                &zd,
4730                n_embd,
4731                n_ff_exp,
4732                n_expert,
4733                n_pairs,
4734                m.gate_exps.qtype,
4735                gate_row_bytes,
4736            )?;
4737            let up = e.moe_pairs_matvec_q8(
4738                &dev.ptr_row,
4739                1,
4740                &pair_tok_d,
4741                &sel_d,
4742                &zq,
4743                &zd,
4744                n_embd,
4745                n_ff_exp,
4746                n_expert,
4747                n_pairs,
4748                m.up_exps.qtype,
4749                up_row_bytes,
4750            )?;
4751            let mut act = e.uninit(n_pairs * n_ff_exp)?;
4752            Self::ffn_act_lim(
4753                e,
4754                cfg,
4755                &gate,
4756                &up,
4757                1.0,
4758                1.0,
4759                cfg.clamp_exp_at(il as u32),
4760                &mut act,
4761                n_pairs * n_ff_exp,
4762            )?;
4763            let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
4764            let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
4765            let pair_self_d = e.htod_i32(&pair_self)?;
4766            let down = e.moe_pairs_matvec_q8(
4767                &dev.ptr_row,
4768                2,
4769                &pair_self_d,
4770                &sel_d,
4771                &aq2,
4772                &ad2,
4773                n_ff_exp,
4774                n_embd,
4775                n_expert,
4776                n_pairs,
4777                m.down_exps.qtype,
4778                m.down_exps.row_bytes,
4779            )?;
4780            let tok_off: Vec<i32> = (0..=t).map(|tok| (tok * n_used) as i32).collect();
4781            let tok_ids: Vec<i32> = (0..n_pairs as i32).collect();
4782            let tok_off_d = e.htod_i32(&tok_off)?;
4783            let tok_ids_d = e.htod_i32(&tok_ids)?;
4784            let mut output = e.uninit(t * n_embd)?;
4785            e.moe_pairs_scatter(
4786                &down,
4787                &w_d,
4788                &tok_off_d,
4789                &tok_ids_d,
4790                &mut output,
4791                t,
4792                n_embd,
4793            )?;
4794            output
4795        } else {
4796            let act = e.moe_gate_up_silu8_dev_q8_rows(
4797                &dev.ptr_row,
4798                &sel_d,
4799                &zq,
4800                &zd,
4801                t,
4802                n_embd,
4803                n_ff_exp,
4804                n_used,
4805                n_expert,
4806                m.gate_exps.qtype,
4807                m.up_exps.qtype,
4808                gate_row_bytes,
4809                up_row_bytes,
4810                &m.dev_macros,
4811            )?;
4812            let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
4813            let mut output = e.uninit(t * n_embd)?;
4814            e.moe_down8_fma_dev_q8_rows_g(
4815                &dev.ptr_row,
4816                &sel_d,
4817                &w_d,
4818                &aq2,
4819                &ad2,
4820                &mut output,
4821                t,
4822                n_ff_exp,
4823                n_embd,
4824                n_used,
4825                n_expert,
4826                m.down_exps.qtype,
4827                m.down_exps.row_bytes,
4828            )?;
4829            output
4830        };
4831
4832        if std::env::var("MEMRA_SIG_ROUTER_DISPATCH_TRACE").as_deref() == Ok("1") {
4833            eprintln!(
4834                "[sigrouter-dev] layer={il} tokens={t} experts={n_expert} used={n_used} clamp={} gu_il={}",
4835                cfg.clamp_exp_at(il as u32).is_some(),
4836                dev.gu_il,
4837            );
4838        }
4839        Self::moe_ffn_grouped_add_shared(e, m, z, t, cfg, il, &mut moe_out)?;
4840        Ok(moe_out)
4841    }
4842
4843    /// LAUNCH-STRUCTURE STAGE 3: the ZERO-DtoH fully-resident MoE FFN. Caller guarantees the
4844    /// layer's device pointer row exists (checked under the cache lock). Router top-k runs on
4845    /// device; sel/w are consumed by the `_dev` matvec twins directly; NOTHING crosses PCIe.
4846    /// Same numerics as the fused-router + gdec chain (kernel-level bit-identity, see the
4847    /// MoE PREFILL PAIR-BATCH: host routing (sel/w like the sequential path), then 5 launches
4848    /// TOTAL per layer (quantize z, gate-pairs, up-pairs, silu, act-quantize, down-pairs,
4849    /// scatter) regardless of T or expert count. Bit-identity class: per (pair,row) dot =
4850    /// qmatvec_expert_q8 order; per-token accumulation slot-ordered (scatter kernel).
4851    fn moe_ffn_pairs(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, logits: &CudaSlice<f32>,
4852                     t: usize, cfg: &ModelConfig)
4853                     -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4854        let moe = cfg.moe.as_ref().unwrap();
4855        let n_embd = cfg.n_embd as usize;
4856        let n_expert = moe.expert_count as usize;
4857        let n_used = moe.expert_used_count as usize;
4858        let n_ff_exp = moe.expert_ff_length as usize;
4859        // This arm has no `il` and every kernel in it fuses PLAIN silu(gate)*up, so a clamped
4860        // model must never reach it. The caller's gate at `moe_ffn_sequential_zq8` denies per
4861        // layer via `swiglu_clamped_at(il)`; assert the whole-model form here so a future caller
4862        // that forgets the gate fails loudly in debug instead of returning wrong logits.
4863        debug_assert!(!cfg.swiglu_clamped_anywhere(),
4864                      "moe_ffn_pairs has no per-layer clamp: fused epilogues are plain SiLU");
4865        let dev = m.dev_exps.as_ref().unwrap();
4866        // WALL-GAP ARC: interleaved gate/up slab strides (see moe_ffn_dev).
4867        let (rbg_d, rbu_d) = if dev.gu_il {
4868            let sxx = m.gate_exps.row_bytes + m.up_exps.row_bytes; (sxx, sxx)
4869        } else { (m.gate_exps.row_bytes, m.up_exps.row_bytes) };
4870
4871        let (sel_all, w_all) = Self::moe_route(e, logits, t, n_expert, n_used)?;
4872        let n_pairs = t * n_used;
4873        // pair arrays: pair p = (token p/n_used, slot p%n_used) — ALREADY slot-ordered per token,
4874        // so the CSR is trivial: tok_pair_off[tok] = tok*n_used, ids identity.
4875        let pair_tok: Vec<i32> = (0..n_pairs).map(|p| (p / n_used) as i32).collect();
4876        let pair_ex:  Vec<i32> = sel_all.iter().map(|&x| x as i32).collect();
4877        let pair_w:   Vec<f32> = w_all.clone();
4878        let tok_off:  Vec<i32> = (0..=t).map(|tok| (tok * n_used) as i32).collect();
4879        let tok_ids:  Vec<i32> = (0..n_pairs as i32).collect();
4880        let pt = e.htod_i32(&pair_tok)?;
4881        let px = e.htod_i32(&pair_ex)?;
4882        let pw = e.htod(&pair_w)?;
4883        let toff = e.htod_i32(&tok_off)?;
4884        let tids = e.htod_i32(&tok_ids)?;
4885
4886        // z quantized ONCE for all tokens; gate/up pair matvecs; silu; act quantize; down; scatter.
4887        // EXPERT-MAJOR CSR (rung 2): pairs grouped by expert -> the kernel reuses each weight
4888        // row across the expert's token group (llama-MMQ's core win). Host grouping is O(pairs).
4889        let mut by_ex: Vec<Vec<i32>> = vec![Vec::new(); n_expert];
4890        for p in 0..n_pairs { by_ex[pair_ex[p] as usize].push(p as i32); }
4891        let mut ex_ids: Vec<i32> = Vec::new();
4892        let mut ex_off: Vec<i32> = vec![0];
4893        let mut ex_pairs: Vec<i32> = Vec::with_capacity(n_pairs);
4894        for (ex, list) in by_ex.iter().enumerate() {
4895            if list.is_empty() { continue; }
4896            ex_ids.push(ex as i32);
4897            ex_pairs.extend_from_slice(list);
4898            ex_off.push(ex_pairs.len() as i32);
4899        }
4900        let n_active = ex_ids.len();
4901        let exi = e.htod_i32(&ex_ids)?;
4902        let exo = e.htod_i32(&ex_off)?;
4903        let exp_d = e.htod_i32(&ex_pairs)?;
4904        let _ = &px;   // pair-major twin keeps it; em path uses CSR
4905
4906        // INT8-MMA EXPERT MMQ (MEMRA_MOE_MMA=1, opt-in): the m16n8k16.s8 tensor-core analog of the
4907        // _dec dp4a kernel (cu/mmq_iq_experts.cu). Same CSR grouping; per-expert matvec runs as a
4908        // 128x128-tile int8 MMA GEMM over the expert's token group. Weight IQ nibbles decode to int8
4909        // at tile-load + per-32 float scale; activation is q8_1_mmq (D4, same quant class as dp4a).
4910        // FP-ORDER differs from dp4a (MMA reduction) — logits SHIFT, gated on argmax/spec/closeness,
4911        // NOT byte-identity (like the W4A8 path). Requires IQ3_S/IQ4_XS + in_f % 256 == 0.
4912        // t >= 16 (GEMM_M-class rule): the MMA tile needs token volume (crossover ~200 tok/expert;
4913        // microbench: dp4a wins at tiny groups). ALSO an exactness requirement — spec verify
4914        // batches (t=2..K+2) must ride the dp4a path whose FP order matches the T=1 decode chain,
4915        // else K=1 self-consistency FAILs (caught 2026-07-06: MMA at T=2 flipped a verify argmax).
4916        // DEFAULT ON (2026-07-06, third flip — this time with the real culprit fixed): the
4917        // "MMA prime breaks spec" failure was the ROUTER's cuBLASLt n-dependence (d994271),
4918        // not MMA's own FP order — both this and the k-quant arms were innocent suspects whose
4919        // margin shifts surfaced the router bug. With the router decode-exact at verify t, the
4920        // full battery is green with MMA on (spec p1/p2/p3 PASS, raw K=1..8 PASS, argmax MATCH,
4921        // pp6257 2862 = 2.1x dec). t>=16 floor still required: verify batches must ride dp4a
4922        // (dispatch parity with the T=1 decode chain). MEMRA_MOE_MMA=0 rollback;
4923        // MEMRA_MOE_MMA_T overrides the floor (bisect seam).
4924        static MMA_T: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4925        let mma_t = *MMA_T.get_or_init(|| {
4926            std::env::var("MEMRA_MOE_MMA_T").ok().and_then(|v| v.parse().ok()).unwrap_or(16)
4927        });
4928        let use_mma = std::env::var("MEMRA_MOE_MMA").map(|v| v != "0").unwrap_or(true)
4929            && t >= mma_t
4930            && q8_expert_dec_supported(m.gate_exps.qtype) && q8_expert_dec_supported(m.up_exps.qtype)
4931            && q8_expert_dec_supported(m.down_exps.qtype)
4932            && n_embd % 256 == 0 && n_ff_exp % 256 == 0;
4933        // GROUPED f16 LANE admission (MEMRA_MOE_F16G, rounds 46-49): its own door, no longer a
4934        // subset of the MMQ arm — q35's k-quant stragglers (Q6_K/Q4_K down, one Q3_K gate/up
4935        // layer) fail q8_expert_dec_supported but dequant fine to f16, so f16g must be able to
4936        // take a layer the MMQ arm would reject. Same t >= mma_t floor as MMA: decode and
4937        // spec-verify batches must ride the dp4a path whose FP order matches the T=1 chain.
4938        // MODE 2 (sm_120a naked default, lane/f16g-default-rearb 2026-08-02): every layer
4939        // whose three projections pass f16g_proj_ok rides the sk visitor with direct tile
4940        // loaders — with IQ4_XS/IQ3_S direct coverage the sk arm beats the int8-MMA MMQ
4941        // tiles on the IQ-bank models too (q35 board-2048 +33.9%, KAT pp512 +46.7%).
4942        // AUTO-KQUANT (mode 3, MEMRA_MOE_F16G=3, lane/q4k-expert-prefill): admit f16g ONLY
4943        // where the MMA arm can't take the layer's QTYPES — the k-quant expert class whose
4944        // baseline is the per-pair _em fallback (Ornith-35B Q4_K: board-2048 3.14x). Its
4945        // MMA-capable carve-out (IQ3_S/IQ4_XS/Q4_0 banks on MMQ) was priced pre-IQ-direct;
4946        // it survives as the rollback seam. Keyed on qtype capability, NOT use_mma, so
4947        // MEMRA_MOE_MMA=0 stays a pure dp4a rollback seam.
4948        let mma_capable = q8_expert_dec_supported(m.gate_exps.qtype)
4949            && q8_expert_dec_supported(m.up_exps.qtype)
4950            && q8_expert_dec_supported(m.down_exps.qtype)
4951            && n_embd % 256 == 0 && n_ff_exp % 256 == 0;
4952        let f16g_mode = crate::moe_f16g_mode();
4953        let f16g = f16g_mode != 0 && t >= mma_t
4954            && (f16g_mode != 3 || !mma_capable)
4955            && f16g_proj_ok(m.gate_exps.qtype, n_embd)
4956            && f16g_proj_ok(m.up_exps.qtype, n_embd)
4957            && f16g_proj_ok(m.down_exps.qtype, n_ff_exp);
4958        if use_mma || f16g {
4959            // GROUPED f16 LANE (MEMRA_MOE_F16G, rounds 46-49, experimental door): dequant
4960            // the active experts ONCE per projection to f16 and run one grouped f16 GEMM over
4961            // the CSR groups. f16-mirror numeric class — argmax/spec gated before promotion.
4962            // NOTE: the pair-gather kernel needs pair p ordered EXPERT-MAJOR (ex_pairs order);
4963            // the y rows come back in that same CSR order, so gate/up/down all stay pair-major
4964            // in ex_pairs order — but moe_pairs_silu_mul and the scatter consume PAIR-ID order.
4965            // We therefore gather activations per ex_pairs and scatter y back through ex_pairs.
4966            let y_down = if f16g {
4967                // CSR order end-to-end: gather z rows by the pair's TOKEN (pair p's token is
4968                // p / n_used — the trivial CSR above), silu in CSR order (elementwise), one
4969                // permute at the very end back to pair-id order for the scatter.
4970                let csr_tok: Vec<i32> = ex_pairs.iter().map(|&p| p / n_used as i32).collect();
4971                let csr_tok_d = e.htod_i32(&csr_tok)?;
4972                let (z_f16, z_s) = e.moe_f16g_act(z, Some(&csr_tok_d), n_embd, n_pairs)?;
4973                let g_csr = e.moe_f16_grouped(&dev.ptr_row, 0, n_expert, &exi, &ex_off, &exo,
4974                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
4975                                              m.gate_exps.qtype, rbg_d)?;
4976                let u_csr = e.moe_f16_grouped(&dev.ptr_row, 1, n_expert, &exi, &ex_off, &exo,
4977                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
4978                                              m.up_exps.qtype, rbu_d)?;
4979                let act_csr = e.moe_pairs_silu_mul(&g_csr, &u_csr, n_pairs * n_ff_exp)?;
4980                let (a_f16, a_s) = e.moe_f16g_act(&act_csr, None, n_ff_exp, n_pairs)?;
4981                let d_csr = e.moe_f16_grouped(&dev.ptr_row, 2, n_expert, &exi, &ex_off, &exo,
4982                                              &a_f16, &a_s, n_ff_exp, n_embd, n_active, n_pairs,
4983                                              m.down_exps.qtype, m.down_exps.row_bytes)?;
4984                e.rows_permute(&d_csr, &exp_d, n_pairs, n_embd)?
4985            } else {
4986            // gate/up: activation = z, token-major over t tokens; pair_tok gathers the routed row.
4987            let z_scr = e.mmq_iq_quantize_act(z, n_embd, t)?;
4988            let gate = e.mmq_iq_experts(&dev.ptr_row, 0, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
4989                                        n_embd, n_ff_exp, n_active, n_pairs, t,
4990                                        m.gate_exps.qtype, rbg_d)?;
4991            let up = e.mmq_iq_experts(&dev.ptr_row, 1, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
4992                                      n_embd, n_ff_exp, n_active, n_pairs, t,
4993                                      m.up_exps.qtype, rbu_d)?;
4994            // down: activation = silu(gate)*up, pair-major [n_pairs, n_ff_exp]; pair_tok =
4995            // identity. FUSED ACT-EPILOGUE (default on): one launch computes the activation in
4996            // registers and writes ONLY the quantized scratch — the two-pass chain
4997            // (moe_pairs_silu_mul writes act f32, mmq_iq_quantize_act re-reads it) is the
4998            // MEMRA_MOE_FUSE_ACTQ=0 rollback. Scratch bytes are BYTE-IDENTICAL (kernel-check).
4999            let a_scr = if crate::moe_fuse_actq_on() {
5000                e.mmq_iq_fused_act_quant(&gate, &up, n_ff_exp, n_pairs, 0)?
5001            } else {
5002                let act = e.moe_pairs_silu_mul(&gate, &up, n_pairs * n_ff_exp)?;
5003                e.mmq_iq_quantize_act(&act, n_ff_exp, n_pairs)?
5004            };
5005            let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
5006            let pself = e.htod_i32(&pair_self)?;
5007            e.mmq_iq_experts(&dev.ptr_row, 2, n_expert, &exi, &exo, &exp_d, &pself, &a_scr,
5008                             n_ff_exp, n_embd, n_active, n_pairs, n_pairs,
5009                             m.down_exps.qtype, m.down_exps.row_bytes)?
5010            };
5011            let mut moe_out = e.uninit(t * n_embd)?;
5012            e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
5013            if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
5014                (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
5015            {
5016                let n_ff_sh = gate_shexp.out_features();
5017                let sg_gate = e.matmul(gate_shexp, z, t)?;
5018                let sg_up = e.matmul(up_shexp, z, t)?;
5019                let mut sa = e.uninit(t * n_ff_sh)?;
5020                Self::ffn_act(e, cfg, &sg_gate, &sg_up, &mut sa, t * n_ff_sh)?;
5021                let sh = e.matmul(down_shexp, &sa, t)?;
5022                // shexp gate: qwen35moe sigmoid-gates; M3 has no gate tensor -> weight 1.0.
5023                // SERVE ISOLATION (lane/concat-prime-exact): the fused sigmoid-dot is the
5024                // m-INVARIANT form — see the sequential arm's note. This is the PAIRS arm,
5025                // i.e. the one real prefill actually takes on a resident-expert MoE model,
5026                // so the concat-prime isolation fix has to land here as well.
5027                let g = match &m.gate_inp_shexp {
5028                    Some(gate_inp_shexp) if crate::router_prefill_exact_on() => {
5029                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
5030                    }
5031                    Some(gate_inp_shexp) => {
5032                        let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
5033                        let mut g = e.uninit(t)?;
5034                        e.sigmoid(&gs, &mut g, t)?;
5035                        g
5036                    }
5037                    None => e.htod(&vec![1.0f32; t])?,
5038                };
5039                e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
5040            }
5041            return Ok(moe_out);
5042        }
5043
5044        // DECODE-ONCE MMQ (rung 3, MEMRA_MOE_DEC=1 default-on): dequant each weight group once per
5045        // (row,group) then dp4a across the expert's tokens. _em re-decoded per token (NEUTRAL).
5046        let dec = std::env::var("MEMRA_MOE_DEC").map(|v| v != "0").unwrap_or(true);
5047        let matvec = |proj, exi: &_, exo: &_, exp_d: &_, pt: &_, aq: &_, ad: &_,
5048                      inf, outf, qtype, rb| -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5049            // _dec's decode-once extractors are IQ-only; k-quant expert layers take the _em dot path.
5050            let dec = dec && q8_expert_dec_supported(qtype);
5051            if dec { e.moe_pairs_matvec_q8_dec(&dev.ptr_row, proj, exi, exo, exp_d, pt, aq, ad,
5052                                               inf, outf, n_expert, n_active, n_pairs, qtype, rb) }
5053            else   { e.moe_pairs_matvec_q8_em (&dev.ptr_row, proj, exi, exo, exp_d, pt, aq, ad,
5054                                               inf, outf, n_expert, n_active, n_pairs, qtype, rb) }
5055        };
5056        let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5057        let gate = matvec(0, &exi, &exo, &exp_d, &pt, &zq, &zd,
5058                          n_embd, n_ff_exp, m.gate_exps.qtype, rbg_d)?;
5059        let up = matvec(1, &exi, &exo, &exp_d, &pt, &zq, &zd,
5060                        n_embd, n_ff_exp, m.up_exps.qtype, rbu_d)?;
5061        let act = e.moe_pairs_silu_mul(&gate, &up, n_pairs * n_ff_exp)?;
5062        let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
5063        // down consumes PAIR-major activation rows: pair_tok = identity.
5064        let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
5065        let pself = e.htod_i32(&pair_self)?;
5066        let y_down = matvec(2, &exi, &exo, &exp_d, &pself, &aq2, &ad2,
5067                            n_ff_exp, n_embd, m.down_exps.qtype, m.down_exps.row_bytes)?;
5068        let mut moe_out = e.uninit(t * n_embd)?;   // scatter fully overwrites per (token,col)
5069        e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
5070
5071        // SHARED EXPERT epilogue — same as the other paths.
5072        // gate_inp_shexp is OPTIONAL: qwen35moe gates the shared expert (sigmoid(gate_inp) x sh);
5073        // MiniMax-M3 (DeepSeek-V3 class) has NO shexp gate — the shared expert adds directly.
5074        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
5075            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
5076        {
5077            let n_ff_sh = gate_shexp.out_features();
5078            // These decode-exact forms are required by the new Step resident arm. Keep the
5079            // established grouped shared-expert program for every other architecture: widening
5080            // this to Gemma changed its speculative acceptance despite green argmax gates.
5081            let step_exact = cfg.step35.is_some();
5082            let verify_t = step_exact && t > 1 && t < PRIME_MIN_T;
5083            let (sg_gate, sg_up) = if step_exact && t == 1 {
5084                match e.matmul_q8_fused2_x(gate_shexp, up_shexp, z)? {
5085                    Some(pair) => pair,
5086                    None => (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?),
5087                }
5088            } else if verify_t {
5089                let mut fused = None;
5090                if crate::spec::spec_fused_t() && (2..=4).contains(&t)
5091                    && e.uses_q8_1_fast(gate_shexp) && e.uses_q8_1_fast(up_shexp)
5092                {
5093                    let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5094                    fused = e.matmul_q8_fused2_t(gate_shexp, up_shexp, &zq, &zd, t)?;
5095                }
5096                match fused {
5097                    Some(pair) => pair,
5098                    None => (
5099                        e.matmul_decode_exact(gate_shexp, z, t)?,
5100                        e.matmul_decode_exact(up_shexp, z, t)?,
5101                    ),
5102                }
5103            } else {
5104                (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?)
5105            };
5106            let mut sa = e.uninit(t * n_ff_sh)?;
5107            e.silu_mul(&sg_gate, &sg_up, &mut sa, t * n_ff_sh)?;
5108            let sh = if verify_t {
5109                e.matmul_decode_exact(down_shexp, &sa, t)?
5110            } else {
5111                e.matmul(down_shexp, &sa, t)?
5112            };
5113            // shexp gate: qwen35moe sigmoid-gates; M3 has no gate tensor -> weight 1.0.
5114            // m-INVARIANT fused sigmoid-dot under router_prefill_exact (serve isolation,
5115            // lane/concat-prime-exact) — every shexp-gate arm shares the same form so a
5116            // dispatch choice cannot change bits.
5117            let g = match &m.gate_inp_shexp {
5118                Some(gate_inp_shexp) if crate::router_prefill_exact_on() => {
5119                    e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
5120                }
5121                Some(gate_inp_shexp) => {
5122                    let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
5123                    let mut g = e.uninit(t)?;
5124                    e.sigmoid(&gs, &mut g, t)?;
5125                    g
5126                }
5127                None => e.htod(&vec![1.0f32; t])?,
5128            };
5129            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
5130        }
5131        Ok(moe_out)
5132    }
5133
5134    /// kernel headers); the shared-expert epilogue is byte-identical to moe_ffn_sequential's.
5135    #[allow(clippy::too_many_arguments)]
5136    #[allow(clippy::too_many_arguments)]
5137    fn moe_ffn_dev(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>,
5138                   zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>, logits: &CudaSlice<f32>,
5139                   t: usize, cfg: &ModelConfig, il: u16, max_block: usize)
5140                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5141        let moe = cfg.moe.as_ref().unwrap();
5142        let n_embd = cfg.n_embd as usize;
5143        let n_expert = moe.expert_count as usize;
5144        let n_used = moe.expert_used_count as usize;
5145        let n_ff_exp = moe.expert_ff_length as usize;
5146        // moe_router_topk is SOFTMAX-only (no exp_probs_b bias, no expert_weights_scale) and every
5147        // gate_up kernel here fuses PLAIN silu(gate)*up. `dev_ok` denies sigmoid-router archs and
5148        // clamped layers; assert both so a future caller that skips the gate fails loudly.
5149        debug_assert!(cfg.sigmoid_router().is_none(),
5150                      "moe_ffn_dev routes SOFTMAX: a sigmoid-router arch would pick wrong experts");
5151        debug_assert!(!cfg.swiglu_clamped_at(il as u32),
5152                      "moe_ffn_dev's fused epilogue is plain SiLU: no clamped form");
5153
5154        // device top-k: sel [t, n_used] i32, w [t, n_used] f32 — stays on device.
5155        let (sel_d, mut w_d) = e.moe_router_topk(logits, t, n_expert, n_used)?;
5156        // Down-projection macro fold (compressed-tensors NVFP4 artifacts): one tiny launch,
5157        // skipped entirely for macro-free experts (every k-quant GGUF).
5158        if m.has_macros {
5159            e.moe_w_scale_by_expert(&mut w_d, &sel_d, &m.dev_macros, n_expert, t * n_used)?;
5160        }
5161
5162        // moe_out rows are FULLY overwritten by moe_down8_fma_dev — uninit (stage-2 rule).
5163        let mut moe_out = e.uninit(t * n_embd)?;
5164
5165        // RESIDENT-EXPERTS arm: the pointer row comes from the load-time slab (no cache, no
5166        // lock). Same kernels/loop as the SLRU arm below — only the row's provenance differs.
5167        if let Some(dev) = m.dev_exps.as_ref() {
5168            // WALL-GAP ARC: interleaved gate/up slab (MEMRA_MOE_GU_IL) -> both projections use
5169            // the combined stride; up's base is offset in the ptr table. Down unchanged.
5170            let (rbg_d, rbu_d) = if dev.gu_il {
5171                let sxx = m.gate_exps.row_bytes + m.up_exps.row_bytes; (sxx, sxx)
5172            } else { (m.gate_exps.row_bytes, m.up_exps.row_bytes) };
5173            let q8 = moe_q8_enabled()
5174                && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
5175                && q8_expert_supported(m.down_exps.qtype);
5176            // SMALL-M ROWS ARM (MEMRA_SPEC_M2, lane/spec-m2): batch the verify token loop —
5177            // ONE batched z-quantize + ONE gate_up rows launch + ONE act quantize + ONE down
5178            // rows launch (4 launches/layer, was 4t). BIT-IDENTICAL per token to the serial
5179            // loop below (rows twins = the _v/w8h2v per-token programs on a grid.z token axis;
5180            // quantize_q8_1 is per-32-block row-independent). Gated to the AUTO kernel modes —
5181            // a custom MEMRA_MOE_DEVQ8_GU/DOWN diagnostic run keeps the serial loop so the
5182            // dispatched kernel stays exactly the env-selected one — and to the w8h2v shape
5183            // (n_ff_exp==512, n_used<=8), the same contract the AUTO down dispatch keys on.
5184            let rows_arm = q8 && t > 1 && crate::spec::spec_m2()
5185                && n_ff_exp == 512 && n_used <= 8
5186                && std::env::var("MEMRA_MOE_DEVQ8_GU").map(|v| v.is_empty() || v == "v").unwrap_or(true)
5187                && std::env::var("MEMRA_MOE_DEVQ8_DOWN").map(|v| v.is_empty() || v == "w8h2v").unwrap_or(true);
5188            // CSR EXPERT-DEDUP gate_up (verify-cost target #1, DEFAULT ON 2026-07-10): the
5189            // owner-scan kernel serves every (token, slot) pair of an expert from ONE block,
5190            // deduping the 38-40% duplicated weight-stream+decode the overlap probe measured
5191            // (gate_up 55.0 -> 39.7us/launch; +1.3-2.1% spec e2e p2, +0.6-1.7% p3, all K).
5192            // Bit-identical to the _rows twins (explicit-intrinsic accumulate — the ULP/fmad
5193            // lesson; =2 byte-compare verified zero diffs). down stays on _rows (CSR down
5194            // measured 23.5 -> 37.5us: 16-group rows can't amortize the serial pair loop).
5195            // MEMRA_MOE_CSR=0 rollback; =2 runs BOTH paths and byte-compares (debug).
5196            let csr_mode = std::env::var("MEMRA_MOE_CSR").ok()
5197                .and_then(|v| v.parse::<i32>().ok()).unwrap_or(1);
5198            let csr_qt = |qt: i32| qt == crate::QT_IQ4_XS || qt == crate::QT_IQ3_S;
5199            let csr_arm = rows_arm && csr_mode > 0 && t <= 10
5200                && csr_qt(m.gate_exps.qtype) && csr_qt(m.up_exps.qtype)
5201                && csr_qt(m.down_exps.qtype);
5202            if csr_arm {
5203                if csr_mode == 2 {
5204                    static ENGAGED: std::sync::Once = std::sync::Once::new();
5205                    ENGAGED.call_once(|| eprintln!("[memra] moe CSR byte-compare mode ON (t={t})"));
5206                }
5207                let n_pairs = t * n_used;
5208                let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5209                let act = e.moe_gate_up_silu8_dev_q8_csr(&dev.ptr_row, &sel_d, &zq, &zd, n_pairs,
5210                                                         n_embd, n_ff_exp, n_used, n_expert,
5211                                                         m.gate_exps.qtype, m.up_exps.qtype,
5212                                                         rbg_d, rbu_d)?;
5213                let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
5214                // down stays on the _rows twin — BOTH CSR down variants measured negative
5215                // (v1 serial pairs 23.5->37.5us; v2 warp-parallel+SMEM -14% e2e, K=8 -37%):
5216                // 16-group rows have too little decode to amortize any dedup structure.
5217                e.moe_down8_fma_dev_q8_rows(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out,
5218                                            t, n_ff_exp, n_embd, n_used, n_expert,
5219                                            m.down_exps.qtype, m.down_exps.row_bytes)?;
5220                if csr_mode == 2 {
5221                    // DEBUG BYTE-COMPARE: run the _rows twins on the same inputs, diff bits.
5222                    let act_r = e.moe_gate_up_silu8_dev_q8_rows(&dev.ptr_row, &sel_d, &zq, &zd, t,
5223                                                                n_embd, n_ff_exp, n_used, n_expert,
5224                                                                m.gate_exps.qtype, m.up_exps.qtype,
5225                                                                rbg_d, rbu_d, &m.dev_macros)?;
5226                    let mut out_r = e.uninit(t * n_embd)?;
5227                    let (aq2r, ad2r) = e.quantize_q8_1(&act_r, n_pairs, n_ff_exp)?;
5228                    e.moe_down8_fma_dev_q8_rows(&dev.ptr_row, &sel_d, &w_d, &aq2r, &ad2r, &mut out_r,
5229                                                t, n_ff_exp, n_embd, n_used, n_expert,
5230                                                m.down_exps.qtype, m.down_exps.row_bytes)?;
5231                    let (a1, a2) = (e.dtoh(&act)?, e.dtoh(&act_r)?);
5232                    let (o1, o2) = (e.dtoh(&moe_out)?, e.dtoh(&out_r)?);
5233                    let ba = a1.iter().zip(&a2).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
5234                    let bo = o1.iter().zip(&o2).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
5235                    if ba + bo > 0 {
5236                        eprintln!("[csr-check] il={il} t={t} ACT diffs={ba}/{} OUT diffs={bo}/{}",
5237                                  a1.len(), o1.len());
5238                        // First 4 differing ACT elements: (pair, o, csr, rows) + that pair's expert
5239                        let sel_h = e.dtoh_i32(&sel_d)?;
5240                        let mut shown = 0;
5241                        for (i, (x, y)) in a1.iter().zip(&a2).enumerate() {
5242                            if x.to_bits() != y.to_bits() && shown < 4 {
5243                                let (p, o) = (i / n_ff_exp, i % n_ff_exp);
5244                                let ex = sel_h[p];
5245                                let npx = sel_h.iter().filter(|&&v| v == ex).count();
5246                                eprintln!("  ACT p={p} ex={ex} np={npx} o={o} csr={x:e} rows={y:e}");
5247                                shown += 1;
5248                            }
5249                        }
5250                        std::process::exit(3);
5251                    }
5252                }
5253            } else if rows_arm {
5254                // TEMP PROBE (MEMRA_MOE_OVERLAP=1): cross-token expert-activation overlap at
5255                // verify — sizes the CSR dedup win (unique experts vs t*n_used pairs).
5256                if std::env::var("MEMRA_MOE_OVERLAP").as_deref() == Ok("1") {
5257                    use std::sync::atomic::{AtomicU64, Ordering};
5258                    static PAIRS: AtomicU64 = AtomicU64::new(0);
5259                    static UNIQ: AtomicU64 = AtomicU64::new(0);
5260                    static CALLS: AtomicU64 = AtomicU64::new(0);
5261                    let sel_h = e.dtoh_i32(&sel_d)?;
5262                    let mut u: Vec<i32> = sel_h.clone(); u.sort_unstable(); u.dedup();
5263                    PAIRS.fetch_add(sel_h.len() as u64, Ordering::Relaxed);
5264                    UNIQ.fetch_add(u.len() as u64, Ordering::Relaxed);
5265                    let c = CALLS.fetch_add(1, Ordering::Relaxed) + 1;
5266                    if c % 480 == 0 {
5267                        let p = PAIRS.load(Ordering::Relaxed); let q = UNIQ.load(Ordering::Relaxed);
5268                        eprintln!("[overlap] calls={c} pairs={p} unique={q} ratio={:.3} (t={t})",
5269                                  q as f64 / p as f64);
5270                    }
5271                }
5272                let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5273                let act = e.moe_gate_up_silu8_dev_q8_rows(&dev.ptr_row, &sel_d, &zq, &zd, t,
5274                                                          n_embd, n_ff_exp, n_used, n_expert,
5275                                                          m.gate_exps.qtype, m.up_exps.qtype,
5276                                                          rbg_d, rbu_d, &m.dev_macros)?;
5277                let (aq2, ad2) = e.quantize_q8_1(&act, t * n_used, n_ff_exp)?;
5278                e.moe_down8_fma_dev_q8_rows(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out,
5279                                            t, n_ff_exp, n_embd, n_used, n_expert,
5280                                            m.down_exps.qtype, m.down_exps.row_bytes)?;
5281            } else {
5282            for tok in 0..t {
5283                let zt = z.slice(tok * n_embd..(tok + 1) * n_embd);
5284                let selt = sel_d.slice(tok * n_used..(tok + 1) * n_used);
5285                let wt = w_d.slice(tok * n_used..(tok + 1) * n_used);
5286                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
5287                if q8 {
5288                    let (zq, zd) = match (t, zq8) {
5289                        (1, Some((q, d))) => (q.clone(), d.clone()),
5290                        _ => e.quantize_q8_1_view(&zt, 1, n_embd)?,
5291                    };
5292                    let act = e.moe_gate_up_silu8_dev_q8(&dev.ptr_row, &selt, &zq, &zd,
5293                                                         n_embd, n_ff_exp, n_used, n_expert,
5294                                                         m.gate_exps.qtype, m.up_exps.qtype,
5295                                                         rbg_d, rbu_d, &m.dev_macros)?;
5296                    let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
5297                    e.moe_down8_fma_dev_q8(&dev.ptr_row, &selt, &wt, &aq2, &ad2, &mut dst,
5298                                           n_ff_exp, n_embd, n_used, n_expert,
5299                                           m.down_exps.qtype, m.down_exps.row_bytes)?;
5300                } else {
5301                    let act = e.moe_gate_up_silu8_dev(&dev.ptr_row, &selt, &zt, n_embd, n_ff_exp,
5302                                                      n_used, n_expert,
5303                                                      m.gate_exps.qtype, m.up_exps.qtype,
5304                                                      rbg_d, rbu_d, &m.dev_macros)?;
5305                    e.moe_down8_fma_dev(&dev.ptr_row, &selt, &wt, &act, &mut dst,
5306                                        n_ff_exp, n_embd, n_used, n_expert,
5307                                        m.down_exps.qtype, m.down_exps.row_bytes)?;
5308                }
5309            }
5310            }
5311        } else {
5312        // Launch under the cache lock: the row borrow lives as long as the closure, and the
5313        // lock covers only launch ISSUE (µs), same policy as moe_cached_gemm.
5314        // Q8 ARM PARITY (2026-07-06): the SLRU arm ran the f32-dequant _dev kernels only —
5315        // 80us/launch vs the q8 twins' 15us on the SAME shapes (fixed-build profile: 228
5316        // f32 launches = 36ms of the 64-tok window). Same q8 gate + kernels as the resident
5317        // arm above; MEMRA_MOE_Q8=0 restores the byte-identical f32 path.
5318        let q8 = moe_q8_enabled()
5319            && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
5320            && q8_expert_supported(m.down_exps.qtype);
5321        e.with_moe_cache(max_block, |c, eng| {
5322            let row = c.layer_dev_row(il, n_expert, eng)?
5323                .ok_or("moe_ffn_dev: layer row vanished under the lock")?;
5324            for tok in 0..t {
5325                let zt = z.slice(tok * n_embd..(tok + 1) * n_embd);
5326                let selt = sel_d.slice(tok * n_used..(tok + 1) * n_used);
5327                let wt = w_d.slice(tok * n_used..(tok + 1) * n_used);
5328                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
5329                if q8 {
5330                    let (zq, zd) = match (t, zq8) {
5331                        (1, Some((q, d))) => (q.clone(), d.clone()),
5332                        _ => eng.quantize_q8_1_view(&zt, 1, n_embd)?,
5333                    };
5334                    let act = eng.moe_gate_up_silu8_dev_q8(row, &selt, &zq, &zd,
5335                                                           n_embd, n_ff_exp, n_used, n_expert,
5336                                                           m.gate_exps.qtype, m.up_exps.qtype,
5337                                                           m.gate_exps.row_bytes, m.up_exps.row_bytes,
5338                                                           &m.dev_macros)?;
5339                    let (aq2, ad2) = eng.quantize_q8_1(&act, n_used, n_ff_exp)?;
5340                    eng.moe_down8_fma_dev_q8(row, &selt, &wt, &aq2, &ad2, &mut dst,
5341                                             n_ff_exp, n_embd, n_used, n_expert,
5342                                             m.down_exps.qtype, m.down_exps.row_bytes)?;
5343                } else {
5344                    let act = eng.moe_gate_up_silu8_dev(row, &selt, &zt, n_embd, n_ff_exp,
5345                                                        n_used, n_expert,
5346                                                        m.gate_exps.qtype, m.up_exps.qtype,
5347                                                        m.gate_exps.row_bytes, m.up_exps.row_bytes,
5348                                                        &m.dev_macros)?;
5349                    eng.moe_down8_fma_dev(row, &selt, &wt, &act, &mut dst,
5350                                          n_ff_exp, n_embd, n_used, n_expert,
5351                                          m.down_exps.qtype, m.down_exps.row_bytes)?;
5352                }
5353            }
5354            // instrumentation parity with the host paths (3 blocks/expert-slot, all hits).
5355            c.hits += (t * 3 * n_used) as u64;
5356            Ok(())
5357        })?;
5358        }
5359
5360        // SHARED EXPERT epilogue — byte-identical to moe_ffn_sequential step 3 (incl. its Q8
5361        // TRUNK-FUSION arm: fused2 is bit-identical to the two matmul calls per (tensor,row)).
5362        // gate_inp_shexp is OPTIONAL: qwen35moe gates the shared expert (sigmoid(gate_inp) x sh);
5363        // MiniMax-M3 (DeepSeek-V3 class) has NO shexp gate — the shared expert adds directly.
5364        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
5365            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
5366        {
5367            let n_ff_sh = gate_shexp.out_features();
5368            // verify-t (2..15) decode-exact arm: this fn now serves the spec verify batches
5369            // (pairs gate moved to t>=PRIME_MIN_T), so the shexp chain must match t==1 per col.
5370            let verify_t = t > 1 && t < PRIME_MIN_T;
5371            let (sg_gate, sg_up) = if t == 1 {
5372                match e.matmul_q8_fused2_x(gate_shexp, up_shexp, z)? {
5373                    Some(pair) => pair,
5374                    None => (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?),
5375                }
5376            } else if verify_t {
5377                // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): the shexp gate+up pair
5378                // rides one shared quantize + one fused2 batched launch instead of two
5379                // decode-exact calls. Bit-identical per (tensor,token,row) — see spec_fused_t.
5380                let mut fused = None;
5381                if crate::spec::spec_fused_t() && (2..=4).contains(&t)
5382                    && e.uses_q8_1_fast(gate_shexp) && e.uses_q8_1_fast(up_shexp) {
5383                    let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5384                    fused = e.matmul_q8_fused2_t(gate_shexp, up_shexp, &zq, &zd, t)?;
5385                }
5386                match fused {
5387                    Some(pair) => pair,
5388                    None => (e.matmul_decode_exact(gate_shexp, z, t)?,
5389                             e.matmul_decode_exact(up_shexp, z, t)?),
5390                }
5391            } else {
5392                (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?)
5393            };
5394            let mut sa = e.uninit(t * n_ff_sh)?;  // silu_mul fully overwrites
5395            e.silu_mul(&sg_gate, &sg_up, &mut sa, t * n_ff_sh)?;
5396            let sh = if verify_t { e.matmul_decode_exact(down_shexp, &sa, t)? }
5397                     else { e.matmul(down_shexp, &sa, t)? };
5398            // shexp gate: qwen35moe sigmoid-gates; M3 has no gate tensor -> weight 1.0.
5399            // Same fused sigmoid-dot as moe_ffn_sequential step 3 (byte-identity contract
5400            // between the two arms; prefill keeps the batched cuBLASLt linear).
5401            let g = match &m.gate_inp_shexp {
5402                Some(gate_inp_shexp) => {
5403                    // router_prefill_exact_on(): the fused sigmoid-dot is m-INVARIANT and
5404                    // serves EVERY t (serve isolation, lane/concat-prime-exact).
5405                    if t < PRIME_MIN_T || crate::router_prefill_exact_on() {
5406                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
5407                    } else {
5408                        let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
5409                        let mut g = e.uninit(t)?;
5410                        e.sigmoid(&gs, &mut g, t)?;
5411                        g
5412                    }
5413                }
5414                None => e.htod(&vec![1.0f32; t])?,
5415            };
5416            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
5417        }
5418
5419        Ok(moe_out)
5420    }
5421
5422    /// STAGE-2 GROUPED DECODE (2026-07-04): run ONE token's whole routed-expert FFN in TWO
5423    /// launches when every one of its 3*n_used blocks is ALREADY cache-resident. Returns
5424    /// Ok(true) if the grouped path ran (caller skips the sequential loop for this token);
5425    /// Ok(false) on ANY miss (caller falls through — the sequential loop stages/admits as
5426    /// before, so the NEXT occurrence takes the grouped path). Pointer safety: cache slots are
5427    /// fixed-address for the engine's lifetime and the pure-HIT path performs no admission, so
5428    /// the collected raw pointers cannot move between collection and launch (single-threaded
5429    /// decode; the lock is held only for collection, launches are stream-ordered after any
5430    /// prior same-stream staging writes).
5431    #[allow(clippy::too_many_arguments)]
5432    /// q8 twin of moe_gdec_token (dp4a arc): same residency check + 2-launch shape; the fused
5433    /// kernels consume the pre-quantized z-row and re-quantize act per slot batch.
5434    #[allow(clippy::too_many_arguments)]
5435    fn moe_gdec_token_q8(e: &Engine, m: &MoeWeights, il: u16, max_block: usize,
5436                      zq: &CudaSlice<i8>, zd: &CudaSlice<f32>, sel: &[u32], w: &[f32],
5437                      moe_out: &mut CudaSlice<f32>, tok: usize,
5438                      n_embd: usize, n_ff_exp: usize, n_used: usize)
5439                      -> Result<bool, Box<dyn std::error::Error>> {
5440        use crate::moe_cache::{BlockId, PROJ_GATE, PROJ_UP, PROJ_DOWN};
5441        use cudarc::driver::DevicePtr;
5442        let ptrs = e.with_moe_cache(max_block, |c, eng| {
5443            let mut g = [0u64; 8];
5444            let mut u = [0u64; 8];
5445            let mut d = [0u64; 8];
5446            for (j, &ex) in sel.iter().enumerate() {
5447                let ex = ex as u16;
5448                let (Some(sg), Some(su), Some(sd)) = (c.resident(BlockId::new(il, PROJ_GATE, ex)),
5449                                                      c.resident(BlockId::new(il, PROJ_UP,   ex)),
5450                                                      c.resident(BlockId::new(il, PROJ_DOWN, ex)))
5451                else { return Ok(None); };
5452                let __s = eng.stream();
5453                let (pg, _e0) = c.slot(sg).device_ptr(&__s);
5454                let (pu, _e1) = c.slot(su).device_ptr(&__s);
5455                let (pd, _e2) = c.slot(sd).device_ptr(&__s);
5456                g[j] = pg as u64; u[j] = pu as u64; d[j] = pd as u64;
5457            }
5458            if cpu_expert_profile_admit_enabled() && !c.is_frozen() {
5459                for &ex in sel {
5460                    let ex = ex as u16;
5461                    for proj in [PROJ_GATE, PROJ_UP, PROJ_DOWN] {
5462                        c.note_profile_hit(BlockId::new(il, proj, ex));
5463                    }
5464                }
5465            }
5466            c.hits += (3 * n_used) as u64;
5467            Ok(Some((g, u, d)))
5468        })?;
5469        let Some((g, u, d)) = ptrs else { return Ok(false) };
5470        let mut wv = [0f32; 8];
5471        wv[..n_used].copy_from_slice(w);
5472        let act = e.moe_gate_up_silu8_q8(crate::WPtr8(g), crate::WPtr8(u), zq, zd,
5473                                         n_embd, n_ff_exp, n_used,
5474                                         m.gate_exps.qtype, m.up_exps.qtype,
5475                                         m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
5476        // per-slot act quantize: [n_used, n_ff] rows in one quantize launch.
5477        let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
5478        let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
5479        e.moe_down8_fma_q8(crate::WPtr8(d), crate::F32x8(wv), &aq2, &ad2, &mut dst,
5480                           n_ff_exp, n_embd, n_used,
5481                           m.down_exps.qtype, m.down_exps.row_bytes)?;
5482        Ok(true)
5483    }
5484
5485    fn moe_gdec_token(e: &Engine, m: &MoeWeights, il: u16, max_block: usize,
5486                      zt: &cudarc::driver::CudaView<f32>, sel: &[u32], w: &[f32],
5487                      moe_out: &mut CudaSlice<f32>, tok: usize,
5488                      n_embd: usize, n_ff_exp: usize, n_used: usize)
5489                      -> Result<bool, Box<dyn std::error::Error>> {
5490        use crate::moe_cache::{BlockId, PROJ_GATE, PROJ_UP, PROJ_DOWN};
5491        use cudarc::driver::DevicePtr;
5492        // One lock hold: residency-check all 3*n_used blocks, collect raw slot pointers.
5493        let ptrs = e.with_moe_cache(max_block, |c, eng| {
5494            let mut g = [0u64; 8];
5495            let mut u = [0u64; 8];
5496            let mut d = [0u64; 8];
5497            for (j, &ex) in sel.iter().enumerate() {
5498                let ex = ex as u16;
5499                let (Some(sg), Some(su), Some(sd)) = (c.resident(BlockId::new(il, PROJ_GATE, ex)),
5500                                                      c.resident(BlockId::new(il, PROJ_UP,   ex)),
5501                                                      c.resident(BlockId::new(il, PROJ_DOWN, ex)))
5502                else { return Ok(None); };
5503                let __s = eng.stream();
5504                let (pg, _e0) = c.slot(sg).device_ptr(&__s);
5505                let (pu, _e1) = c.slot(su).device_ptr(&__s);
5506                let (pd, _e2) = c.slot(sd).device_ptr(&__s);
5507                g[j] = pg as u64; u[j] = pu as u64; d[j] = pd as u64;
5508            }
5509            if cpu_expert_profile_admit_enabled() && !c.is_frozen() {
5510                for &ex in sel {
5511                    let ex = ex as u16;
5512                    for proj in [PROJ_GATE, PROJ_UP, PROJ_DOWN] {
5513                        c.note_profile_hit(BlockId::new(il, proj, ex));
5514                    }
5515                }
5516            }
5517            c.hits += (3 * n_used) as u64; // instrumentation parity with dispatch()
5518            Ok(Some((g, u, d)))
5519        })?;
5520        let Some((g, u, d)) = ptrs else { return Ok(false) };
5521        let mut wv = [0f32; 8];
5522        wv[..n_used].copy_from_slice(w);
5523        // 2 launches: (gate+up+silu) x8, then (down + slot-ordered FMA accumulate) x8.
5524        let act = e.moe_gate_up_silu8(crate::WPtr8(g), crate::WPtr8(u), zt,
5525                                      n_embd, n_ff_exp, n_used,
5526                                      m.gate_exps.qtype, m.up_exps.qtype,
5527                                      m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
5528        let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
5529        e.moe_down8_fma_into(crate::WPtr8(d), crate::F32x8(wv), &act, &mut dst,
5530                             n_ff_exp, n_embd, n_used,
5531                             m.down_exps.qtype, m.down_exps.row_bytes)?;
5532        Ok(true)
5533    }
5534
5535    /// EDGE-1 §B.3: dispatch one expert projection through the SLRU cache, then run the SAME
5536    /// `qmatvec_view` from whichever slot it landed in (resident HIT or staged MISS). `x` is the
5537    /// sliced activation row. `proj` selects the gate/up/down HostExps tensor. Returns y = W_expert @ x.
5538    /// q8 twin of moe_cached_gemm: same dispatch/slot mechanics, dp4a expert kernel.
5539    fn moe_cached_gemm_q8(e: &Engine, il: u16, proj: u8, ex: usize, m: &MoeWeights,
5540                          max_block: usize, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>)
5541                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5542        use crate::moe_cache::{BlockId, DispatchSlot, PROJ_GATE, PROJ_UP};
5543        let exps = match proj { PROJ_GATE => &m.gate_exps, PROJ_UP => &m.up_exps, _ => &m.down_exps };
5544        let layout = exps.expert_layout(ex);
5545        let id = BlockId::new(il, proj, ex as u16);
5546        let source = exps.expert_source(ex);
5547        e.with_moe_cache(max_block, |c, eng| {
5548            let slot = c.dispatch_source(id, source, eng)?;
5549            let DispatchSlot::Resident(sl) = slot;
5550            let buf = c.slot(sl);
5551            eng.qmatvec_expert_q8(buf, 0..layout.len, aq, ad, 1, exps.in_f, exps.out_f,
5552                                  layout.qtype, layout.row_bytes)
5553        })
5554    }
5555
5556    fn moe_cached_gemm(e: &Engine, il: u16, proj: u8, ex: usize, m: &MoeWeights,
5557                       max_block: usize, x: &cudarc::driver::CudaView<f32>)
5558                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5559        use crate::moe_cache::{BlockId, DispatchSlot, PROJ_GATE, PROJ_UP};
5560        let exps = match proj { PROJ_GATE => &m.gate_exps, PROJ_UP => &m.up_exps, _ => &m.down_exps };
5561        let layout = exps.expert_layout(ex);
5562        let id = BlockId::new(il, proj, ex as u16);
5563        let source = exps.expert_source(ex);
5564        // dispatch under the lock (lookup/admit/memcpy-issue), then resolve the slot and GEMM.
5565        e.with_moe_cache(max_block, |c, eng| {
5566            let slot = c.dispatch_source(id, source, eng)?;
5567            // resolve the device buffer for this slot; the GEMM is enqueued on the compute stream
5568            // (the same stream the memcpy was issued on, so ordering holds without extra sync).
5569            let DispatchSlot::Resident(sl) = slot;
5570            let buf = c.slot(sl);
5571            eng.qmatvec_view(buf, 0..layout.len, x, 1, exps.in_f, exps.out_f,
5572                             layout.qtype, layout.row_bytes)
5573        })
5574    }
5575
5576    /// Populate the warmup cache for an expert whose current-token output intentionally ran on
5577    /// CPU. No GEMM is launched and callers invoke this only after the CPU result has completed,
5578    /// so the current forward's backend assignment and output remain unchanged.
5579    fn moe_profile_admit_expert(
5580        e: &Engine,
5581        il: u16,
5582        ex: usize,
5583        m: &MoeWeights,
5584        max_block: usize,
5585    ) -> Result<(), Box<dyn std::error::Error>> {
5586        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5587        e.with_moe_cache(max_block, |cache, eng| {
5588            for (proj, exps) in [
5589                (PROJ_GATE, &m.gate_exps),
5590                (PROJ_UP, &m.up_exps),
5591                (PROJ_DOWN, &m.down_exps),
5592            ] {
5593                let id = BlockId::new(il, proj, ex as u16);
5594                let _ = cache.dispatch_source(id, exps.expert_source(ex), eng)?;
5595            }
5596            Ok(())
5597        })
5598    }
5599
5600    /// Read a projection from the immutable residency set when present; otherwise use one
5601    /// transient slot without admitting or evicting anything. Used only by post-freeze prefill.
5602    #[allow(clippy::too_many_arguments)]
5603    fn moe_frozen_gemm(
5604        e: &Engine,
5605        il: u16,
5606        proj: u8,
5607        ex: usize,
5608        m: &MoeWeights,
5609        max_block: usize,
5610        x: &cudarc::driver::CudaView<f32>,
5611        scratch: &mut Option<CudaSlice<u8>>,
5612        scratch_len: usize,
5613    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5614        use crate::moe_cache::{BlockId, PROJ_GATE, PROJ_UP};
5615        let exps = match proj {
5616            PROJ_GATE => &m.gate_exps,
5617            PROJ_UP => &m.up_exps,
5618            _ => &m.down_exps,
5619        };
5620        let layout = exps.expert_layout(ex);
5621        let id = BlockId::new(il, proj, ex as u16);
5622        if let Some(output) = e.with_moe_cache(max_block, |cache, eng| {
5623            let Some(slot) = cache.resident(id) else {
5624                return Ok(None);
5625            };
5626            let buf = cache.slot(slot);
5627            Ok(Some(eng.qmatvec_view(
5628                buf,
5629                0..layout.len,
5630                x,
5631                1,
5632                exps.in_f,
5633                exps.out_f,
5634                layout.qtype,
5635                layout.row_bytes,
5636            )?))
5637        })? {
5638            return Ok(output);
5639        }
5640        if scratch.is_none() {
5641            *scratch = Some(e.alloc_u8_uninit(scratch_len)?);
5642        }
5643        let scratch = scratch.as_mut().unwrap();
5644        e.stage_expert(exps.expert_bytes(ex), scratch, 0)?;
5645        e.qmatvec_view(
5646            scratch,
5647            0..layout.len,
5648            x,
5649            1,
5650            exps.in_f,
5651            exps.out_f,
5652            layout.qtype,
5653            layout.row_bytes,
5654        )
5655    }
5656
5657    fn moe_prefetch_expert(
5658        e: &Engine,
5659        il: u16,
5660        ex: usize,
5661        m: &MoeWeights,
5662        max_block: usize,
5663        keep: &[crate::moe_cache::BlockId],
5664    ) -> Result<(), Box<dyn std::error::Error>> {
5665        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5666        e.with_moe_cache(max_block, |c, eng| {
5667            for (proj, exps) in [(PROJ_GATE, &m.gate_exps), (PROJ_UP, &m.up_exps),
5668                                 (PROJ_DOWN, &m.down_exps)] {
5669                let id = BlockId::new(il, proj, ex as u16);
5670                let _ = c.prefetch_source(id, exps.expert_source(ex), keep, eng)?;
5671            }
5672            Ok(())
5673        })
5674    }
5675
5676    /// Worker-mode disk lookahead for grouped prefill. Memory sources are deliberately skipped so
5677    /// selecting `worker` changes only storage scheduling here; all CUDA work stays in dispatch.
5678    fn moe_prefetch_disk_expert(e: &Engine, il: u16, ex: usize, m: &MoeWeights,
5679                                max_block: usize, keep: &[crate::moe_cache::BlockId])
5680                                -> Result<(), Box<dyn std::error::Error>> {
5681        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5682        e.with_moe_cache(max_block, |c, eng| {
5683            for (proj, exps) in [(PROJ_GATE, &m.gate_exps), (PROJ_UP, &m.up_exps),
5684                                 (PROJ_DOWN, &m.down_exps)] {
5685                let source = exps.expert_source(ex);
5686                if let crate::model::ExpertSource::Disk { .. } = &source {
5687                    let id = BlockId::new(il, proj, ex as u16);
5688                    let _ = c.prefetch_source(id, source, keep, eng)?;
5689                }
5690            }
5691            Ok(())
5692        })
5693    }
5694
5695    #[inline]
5696    fn moe_prefetch_host_expert(ex: usize, m: &MoeWeights) {
5697        let _ = m.gate_exps.prefetch_expert_pages(ex);
5698        let _ = m.up_exps.prefetch_expert_pages(ex);
5699        let _ = m.down_exps.prefetch_expert_pages(ex);
5700    }
5701}
5702
5703// ================================================================================================
5704// A2: EXPERT-GROUPED MoE PREFILL (MEMRA_MOE_GROUPED=1). Resident-case prototype.
5705//
5706// Instead of the per-token loop (T * 8 experts * 3 projections = 12024 individual m=1 matvecs),
5707// this groups tokens by expert and runs ONE matmul per active expert per projection at m=m_e.
5708// On a 501-token prefill with ~170 active experts, that's ~510 matmuls (vs 12024).
5709//
5710// EXACTNESS: per-token accumulation across its 8 experts is reordered (grouped processes experts
5711// in expert-id order, not the router's top-k order). To preserve bit-identity with the sequential
5712// loop, we use an 8-SLOT scheme: expert outputs are scattered into slots keyed by the token's
5713// top-k position (0..7), then reduced in that fixed order. This makes the f32 addition order
5714// identical to the per-token loop regardless of expert processing order.
5715//
5716// Memory: T * 8 * n_embd * 4 = 501 * 8 * 2048 * 4 = ~32 MB (slot buffer). Fine on 96GB.
5717// ================================================================================================
5718
5719impl HybridModel {
5720    /// Resident-slab fast path for host-routed grouped prefill. Unclamped layers batch the
5721    /// sequential fused q8 program over the token axis; clamped layers use the separate
5722    /// expert-major q8 chain so `ffn_act_lim` remains authoritative.
5723    #[allow(clippy::too_many_arguments)]
5724    fn moe_ffn_grouped_resident_q8(
5725        e: &Engine,
5726        m: &MoeWeights,
5727        z: &CudaSlice<f32>,
5728        t: usize,
5729        cfg: &ModelConfig,
5730        il: u16,
5731        sel_all: &[u32],
5732        w_all: &[f32],
5733        table: &CudaSlice<u64>,
5734        gu_il: bool,
5735    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5736        let moe = cfg.moe.as_ref().unwrap();
5737        let n_embd = cfg.n_embd as usize;
5738        let n_expert = moe.expert_count as usize;
5739        let n_used = moe.expert_used_count as usize;
5740        let n_ff_exp = moe.expert_ff_length as usize;
5741        let n_pairs = t * n_used;
5742        debug_assert_eq!(sel_all.len(), n_pairs);
5743        debug_assert_eq!(w_all.len(), n_pairs);
5744        debug_assert!(
5745            m.gate_exps.macros.is_none()
5746                && m.up_exps.macros.is_none()
5747                && m.down_exps.macros.is_none(),
5748            "resident grouped q8 does not fold per-expert macro scales",
5749        );
5750
5751        // The rows twins run the resident sequential program verbatim on grid.z = token:
5752        // fused gate/up/SiLU per slot, batched activation quantization, then the original
5753        // slot-ordered down/FMA chain. Routing remains the sigmoid selector above (device by
5754        // default; MEMRA_SIG_ROUTER=0 is the host oracle); these kernels consume sel/w only and
5755        // never enter the softmax router.
5756        if !cfg.swiglu_clamped_at(il as u32) {
5757            let sel: Vec<i32> = sel_all.iter().map(|&expert| expert as i32).collect();
5758            let sel_d = e.htod_i32(&sel)?;
5759            let w_d = e.htod(w_all)?;
5760            let (gate_row_bytes, up_row_bytes) = if gu_il {
5761                let combined = m.gate_exps.row_bytes + m.up_exps.row_bytes;
5762                (combined, combined)
5763            } else {
5764                (m.gate_exps.row_bytes, m.up_exps.row_bytes)
5765            };
5766            let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5767            let act = e.moe_gate_up_silu8_dev_q8_rows(
5768                table,
5769                &sel_d,
5770                &zq,
5771                &zd,
5772                t,
5773                n_embd,
5774                n_ff_exp,
5775                n_used,
5776                n_expert,
5777                m.gate_exps.qtype,
5778                m.up_exps.qtype,
5779                gate_row_bytes,
5780                up_row_bytes,
5781                &m.dev_macros,
5782            )?;
5783            let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
5784            let mut moe_out = e.uninit(t * n_embd)?;
5785            e.moe_down8_fma_dev_q8_rows_g(
5786                table,
5787                &sel_d,
5788                &w_d,
5789                &aq2,
5790                &ad2,
5791                &mut moe_out,
5792                t,
5793                n_ff_exp,
5794                n_embd,
5795                n_used,
5796                n_expert,
5797                m.down_exps.qtype,
5798                m.down_exps.row_bytes,
5799            )?;
5800
5801            if std::env::var("MEMRA_MOE_STATS").is_ok() {
5802                let mut counts = vec![0usize; n_expert];
5803                for &expert in sel_all {
5804                    counts[expert as usize] += 1;
5805                }
5806                let mut sizes: Vec<usize> =
5807                    counts.into_iter().filter(|&count| count != 0).collect();
5808                sizes.sort_unstable();
5809                let mean = sizes.iter().sum::<usize>() as f64 / sizes.len().max(1) as f64;
5810                println!(
5811                    "moe-grouped il={il} t={t} dispatch=resident-q8-rows active={}/{} \
5812                     m_e: min={} median={} mean={mean:.1} max={}",
5813                    sizes.len(),
5814                    n_expert,
5815                    sizes.first().copied().unwrap_or(0),
5816                    sizes.get(sizes.len() / 2).copied().unwrap_or(0),
5817                    sizes.last().copied().unwrap_or(0),
5818                );
5819            }
5820            return Ok(moe_out);
5821        }
5822
5823        // Clamped layers keep gate/up, activation, and down as separate stages. The pair-major
5824        // matvec body is qmatvec_expert_q8 verbatim, while one launch covers every routed pair.
5825        // Pair ids stay in router slot order so scatter preserves the sequential FMA chain.
5826        let pair_tok: Vec<i32> = (0..n_pairs).map(|pair| (pair / n_used) as i32).collect();
5827        let pair_ex: Vec<i32> = sel_all.iter().map(|&expert| expert as i32).collect();
5828        let tok_off: Vec<i32> = (0..=t).map(|tok| (tok * n_used) as i32).collect();
5829        let tok_ids: Vec<i32> = (0..n_pairs as i32).collect();
5830
5831        let mut by_expert: Vec<Vec<i32>> = vec![Vec::new(); n_expert];
5832        for (pair, &expert) in pair_ex.iter().enumerate() {
5833            by_expert[expert as usize].push(pair as i32);
5834        }
5835
5836        let pair_tok_d = e.htod_i32(&pair_tok)?;
5837        let pair_ex_d = e.htod_i32(&pair_ex)?;
5838        let pair_w_d = e.htod(w_all)?;
5839        let tok_off_d = e.htod_i32(&tok_off)?;
5840        let tok_ids_d = e.htod_i32(&tok_ids)?;
5841
5842        let matvec = |
5843            proj: i32,
5844            pair_rows: &CudaSlice<i32>,
5845            aq: &CudaSlice<i8>,
5846            ad: &CudaSlice<f32>,
5847            in_f: usize,
5848            out_f: usize,
5849            qtype: i32,
5850            row_bytes: usize,
5851        | -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5852            e.moe_pairs_matvec_q8(
5853                table,
5854                proj,
5855                pair_rows,
5856                &pair_ex_d,
5857                aq,
5858                ad,
5859                in_f,
5860                out_f,
5861                n_expert,
5862                n_pairs,
5863                qtype,
5864                row_bytes,
5865            )
5866        };
5867
5868        let (gate_row_bytes, up_row_bytes) = if gu_il {
5869            let combined = m.gate_exps.row_bytes + m.up_exps.row_bytes;
5870            (combined, combined)
5871        } else {
5872            (m.gate_exps.row_bytes, m.up_exps.row_bytes)
5873        };
5874        let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5875        let gate = matvec(
5876            0,
5877            &pair_tok_d,
5878            &zq,
5879            &zd,
5880            n_embd,
5881            n_ff_exp,
5882            m.gate_exps.qtype,
5883            gate_row_bytes,
5884        )?;
5885        let up = matvec(
5886            1,
5887            &pair_tok_d,
5888            &zq,
5889            &zd,
5890            n_embd,
5891            n_ff_exp,
5892            m.up_exps.qtype,
5893            up_row_bytes,
5894        )?;
5895        let mut act = e.uninit(n_pairs * n_ff_exp)?;
5896        Self::ffn_act_lim(
5897            e,
5898            cfg,
5899            &gate,
5900            &up,
5901            1.0,
5902            1.0,
5903            cfg.clamp_exp_at(il as u32),
5904            &mut act,
5905            n_pairs * n_ff_exp,
5906        )?;
5907        let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
5908        let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
5909        let pair_self_d = e.htod_i32(&pair_self)?;
5910        let down = matvec(
5911            2,
5912            &pair_self_d,
5913            &aq2,
5914            &ad2,
5915            n_ff_exp,
5916            n_embd,
5917            m.down_exps.qtype,
5918            m.down_exps.row_bytes,
5919        )?;
5920        let mut moe_out = e.uninit(t * n_embd)?;
5921        e.moe_pairs_scatter(
5922            &down,
5923            &pair_w_d,
5924            &tok_off_d,
5925            &tok_ids_d,
5926            &mut moe_out,
5927            t,
5928            n_embd,
5929        )?;
5930
5931        if std::env::var("MEMRA_MOE_STATS").is_ok() {
5932            let mut sizes: Vec<usize> = by_expert
5933                .iter()
5934                .filter_map(|pairs| (!pairs.is_empty()).then_some(pairs.len()))
5935                .collect();
5936            sizes.sort_unstable();
5937            let mean = sizes.iter().sum::<usize>() as f64 / sizes.len().max(1) as f64;
5938            println!(
5939                "moe-grouped il={il} t={t} dispatch=resident-q8-clamped-pairs active={}/{} \
5940                 m_e: min={} median={} mean={mean:.1} max={}",
5941                sizes.len(),
5942                n_expert,
5943                sizes.first().copied().unwrap_or(0),
5944                sizes.get(sizes.len() / 2).copied().unwrap_or(0),
5945                sizes.last().copied().unwrap_or(0),
5946            );
5947        }
5948        Ok(moe_out)
5949    }
5950
5951    fn moe_ffn_grouped_add_shared(
5952        e: &Engine,
5953        m: &MoeWeights,
5954        z: &CudaSlice<f32>,
5955        t: usize,
5956        cfg: &ModelConfig,
5957        il: u16,
5958        moe_out: &mut CudaSlice<f32>,
5959    ) -> Result<(), Box<dyn std::error::Error>> {
5960        let n_embd = cfg.n_embd as usize;
5961        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
5962            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
5963        {
5964            let n_ff_sh = gate_shexp.out_features();
5965            let sg_gate = e.matmul(gate_shexp, z, t)?;
5966            let sg_up = e.matmul(up_shexp, z, t)?;
5967            let mut sa = e.uninit(t * n_ff_sh)?;
5968            Self::ffn_act_lim(
5969                e,
5970                cfg,
5971                &sg_gate,
5972                &sg_up,
5973                1.0,
5974                1.0,
5975                cfg.clamp_shexp_at(il as u32),
5976                &mut sa,
5977                t * n_ff_sh,
5978            )?;
5979            let sh = e.matmul(down_shexp, &sa, t)?;
5980            let gate = match &m.gate_inp_shexp {
5981                Some(gate_inp_shexp) => {
5982                    if t < PRIME_MIN_T || crate::router_prefill_exact_on() {
5983                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
5984                    } else {
5985                        let raw = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
5986                        let mut gate = e.uninit(t)?;
5987                        e.sigmoid(&raw, &mut gate, t)?;
5988                        gate
5989                    }
5990                }
5991                None => e.htod(&vec![1.0f32; t])?,
5992            };
5993            e.add_scaled_rows(&sh, &gate, moe_out, n_embd, t)?;
5994        }
5995        Ok(())
5996    }
5997
5998    /// A2 expert-grouped MoE FFN (prefill path, MEMRA_MOE_GROUPED=1). Same semantics as moe_ffn:
5999    /// z [T, n_embd] -> moe_out [T, n_embd]. BIT-IDENTICAL to moe_ffn when using the slot scheme.
6000    pub(crate) fn moe_ffn_grouped(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize,
6001                                  cfg: &ModelConfig, il: u16, max_block: usize)
6002                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6003        let moe = cfg.moe.as_ref().unwrap();
6004        let n_embd = cfg.n_embd as usize;
6005        let n_expert = moe.expert_count as usize;
6006        let n_used = moe.expert_used_count as usize;
6007        let n_ff_exp = moe.expert_ff_length as usize;
6008        // step35 per-layer SwiGLU clamp; None on every other arch / unclamped layer.
6009        let lim_exp = cfg.clamp_exp_at(il as u32);
6010
6011        // 1. ROUTER: exactly the same m-invariant sigmoid selector as the sequential path
6012        // (device by default; MEMRA_SIG_ROUTER=0 is the host oracle). The grouped dispatch never
6013        // enters the softmax-only pairs/dev router.
6014        let logits = Self::moe_router_logits(e, m, z, t, cfg)?;
6015        if let Some(sig) = cfg.sigmoid_router() {
6016            Self::trace_sigmoid_router_logits(e, il, t, n_expert, n_used, &logits, m, sig)?;
6017        }
6018        let (sel_all, w_all) = if let Some(sig) = cfg.sigmoid_router() {
6019            Self::moe_route_sigmoid_cfg(e, &logits, t, n_expert, n_used, m, sig)?
6020        } else {
6021            Self::moe_route_cfg(e, &logits, t, n_expert, n_used,
6022                                m.active_experts.as_deref())?
6023        };
6024        Self::trace_moe_routes(il, t, &sel_all, &w_all)?;
6025        Self::trace_moe_input(e, il, t, n_embd, z)?;
6026
6027        // Fits-VRAM Step35 under the PP stage split: use the expert-major q8 arithmetic directly
6028        // from the owning device's uniform resident slab. This is not `moe_ffn_pairs`: routing
6029        // already happened above and the activation is clamp-aware. Mixed layouts, remote slabs,
6030        // macro-scaled experts, q8-disabled configs, and spill fall through to metadata-aware A2.
6031        let no_exp_macros = m.gate_exps.macros.is_none()
6032            && m.up_exps.macros.is_none()
6033            && m.down_exps.macros.is_none();
6034        let resident_q8 = m.dev_exps.as_ref().filter(|dev| {
6035            m.has_uniform_expert_layout()
6036                && no_exp_macros
6037                && moe_q8_enabled()
6038                && q8_expert_supported(m.gate_exps.qtype)
6039                && q8_expert_supported(m.up_exps.qtype)
6040                && q8_expert_supported(m.down_exps.qtype)
6041                && moe_slab_enabled()
6042                && dev.dev == e.ctx().ordinal()
6043        });
6044        if let Some(dev) = resident_q8 {
6045            let mut moe_out = Self::moe_ffn_grouped_resident_q8(
6046                e,
6047                m,
6048                z,
6049                t,
6050                cfg,
6051                il,
6052                &sel_all,
6053                &w_all,
6054                &dev.ptr_row,
6055                dev.gu_il,
6056            )?;
6057            Self::moe_ffn_grouped_add_shared(e, m, z, t, cfg, il, &mut moe_out)?;
6058            return Ok(moe_out);
6059        }
6060
6061        // 2. BUILD PER-EXPERT TOKEN LISTS (host-side grouping).
6062        // For each expert e, we need: which tokens use it, their positions in z, their top-k
6063        // slot index (for bit-identical accumulation), and their weights.
6064        struct ExpertGroup {
6065            tok_indices: Vec<i32>,   // indices into z rows (0..T-1)
6066            slot_indices: Vec<i32>,  // top-k slot (0..n_used-1) for that token-expert pair
6067            weights: Vec<f32>,       // renormalized weight for that token-expert pair
6068        }
6069        let mut groups: Vec<ExpertGroup> = (0..n_expert).map(|_| ExpertGroup {
6070            tok_indices: Vec::new(), slot_indices: Vec::new(), weights: Vec::new(),
6071        }).collect();
6072
6073        for tok in 0..t {
6074            for j in 0..n_used {
6075                let ex = sel_all[tok * n_used + j] as usize;
6076                let w = w_all[tok * n_used + j];
6077                groups[ex].tok_indices.push(tok as i32);
6078                groups[ex].slot_indices.push(j as i32);
6079                groups[ex].weights.push(w);
6080            }
6081        }
6082
6083        // 3. ALLOCATE SLOT BUFFER: [T, n_used, n_embd] f32, zero-initialized.
6084        // Each token's 8 expert contributions land in their respective slots.
6085        let mut slot_buf = e.zeros(t * n_used * n_embd)?;
6086        let mut wbuf = e.zeros(t * n_used)?;  // [T, n_used] weight buffer for FMA reduce
6087
6088        // Expert weight dimensions (used in both cache and staging paths).
6089        let g_len = m.gate_exps.max_expert_bytes();
6090        let u_len = m.up_exps.max_expert_bytes();
6091        let d_len = m.down_exps.max_expert_bytes();
6092        let moe_q8 = m.has_uniform_expert_layout()
6093            && moe_q8_enabled()
6094            && q8_expert_supported(m.gate_exps.qtype)
6095            && q8_expert_supported(m.up_exps.qtype)
6096            && q8_expert_supported(m.down_exps.qtype);
6097        // The per-expert slab view is legal only for the ordinary contiguous uniform layout.
6098        // Interleaved GU slabs require the pointer-table fast path above.
6099        let slab_local = m.dev_exps.as_ref().filter(|dev| {
6100            !dev.gu_il && moe_slab_enabled() && dev.dev == e.ctx().ordinal()
6101        });
6102        let use_cache =
6103            slab_local.is_none() && Engine::moe_cache_enabled() && !e.moe_cache_frozen();
6104        // The sequential no-cache/frozen staging oracle is f32. Use q8 only where sequential
6105        // also does: a local resident slab or a live SLRU dispatch.
6106        let grouped_q8 = moe_q8 && (slab_local.is_some() || use_cache);
6107
6108        // GPU scratch for staging (only allocated without a local slab or cache).
6109        let (mut scratch_g, mut scratch_u, mut scratch_d) = if slab_local.is_none() && !use_cache {
6110            (Some(e.alloc_u8(g_len)?), Some(e.alloc_u8(u_len)?), Some(e.alloc_u8(d_len)?))
6111        } else {
6112            (None, None, None)
6113        };
6114
6115        // 4. PER ACTIVE EXPERT: gather, compute, scatter.
6116        // Processing ORDER: DESCENDING m_e (biggest token batches first) — the concluded winner
6117        // (rig5090 2026-07-04, the ascending-id arm and its MEMRA_MOE_ORDER seam removed): desc is
6118        // a first-forward win at partial cache capacity — the hot (big-m_e) experts are admitted
6119        // to the SLRU before the small-m_e tail can pollute it, so residency converges in ONE
6120        // forward instead of several: auto-cache T=501 126.9 -> 169.9 tok/s (1.34x), cap512
6121        // 119.6 -> 160.8 (and kills the rep-to-rep bimodal); wash (<2%) at cap64 pure-spill and
6122        // at long prompts where every expert stages regardless. Order is FREE to change without
6123        // breaking the byte-identity gate: the slot scheme pins each token's accumulation order
6124        // regardless of expert processing order (the whole point of the slots).
6125        let mut order: Vec<usize> =
6126            (0..n_expert).filter(|&ex| !groups[ex].tok_indices.is_empty()).collect();
6127        order.sort_by(|&a, &b| groups[b].tok_indices.len()
6128            .cmp(&groups[a].tok_indices.len()).then(a.cmp(&b)));
6129        let mut m_dist: Vec<usize> = Vec::new();  // for stats
6130        let page_window = moe_page_prefetch_window();
6131        let worker_disk_prefetch = use_cache && crate::spill_pread::worker_enabled();
6132        if worker_disk_prefetch {
6133            if let Some(first) = grouped_worker_prefetch_position(order.len(), None) {
6134                Self::moe_prefetch_disk_expert(e, il, order[first], m, max_block, &[])?;
6135            }
6136        }
6137        for (order_pos, &ex) in order.iter().enumerate() {
6138            for next in page_prefetch_positions(order_pos, order.len(), page_window) {
6139                Self::moe_prefetch_host_expert(order[next], m);
6140            }
6141            if worker_disk_prefetch {
6142                if let Some(next) = grouped_worker_prefetch_position(order.len(), Some(order_pos)) {
6143                    use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
6144                    let keep = [
6145                        BlockId::new(il, PROJ_GATE, ex as u16),
6146                        BlockId::new(il, PROJ_UP, ex as u16),
6147                        BlockId::new(il, PROJ_DOWN, ex as u16),
6148                    ];
6149                    Self::moe_prefetch_disk_expert(e, il, order[next], m, max_block, &keep)?;
6150                }
6151            }
6152            let grp = &groups[ex];
6153            let m_e = grp.tok_indices.len();
6154            m_dist.push(m_e);
6155            let gl = m.gate_exps.expert_layout(ex);
6156            let ul = m.up_exps.expert_layout(ex);
6157            let dl = m.down_exps.expert_layout(ex);
6158
6159            // Upload index/weight arrays to device. The down-proj per-expert macro-scale
6160            // (ModelOpt weight_scale_2) folds into the scatter weights — post-matmul linear,
6161            // same fold as the sequential loop's `w[j] * macro_scale(ex)`. 1.0 for GGUF experts.
6162            let tok_idx_d = e.htod_i32(&grp.tok_indices)?;
6163            let slot_idx_d = e.htod_i32(&grp.slot_indices)?;
6164            let dmac = m.down_exps.macro_scale(ex);
6165            let weight_d = if dmac == 1.0 { e.htod(&grp.weights)? } else {
6166                let scaled: Vec<f32> = grp.weights.iter().map(|&w| w * dmac).collect();
6167                e.htod(&scaled)?
6168            };
6169
6170            // GATHER: collect m_e activation rows from z into a contiguous buffer.
6171            let mut gathered = e.zeros(m_e * n_embd)?;
6172            e.gather_rows(z, &tok_idx_d, &mut gathered, n_embd, m_e)?;
6173            let gv = gathered.slice(0..m_e * n_embd);
6174
6175            // Compute gate/up/down from the local slab, metadata-aware cache, or staging. The q8
6176            // form keeps each gathered row in the sequential arithmetic class at `m=m_e`.
6177            let y = if let Some(dev) = slab_local {
6178                let gate_start = ex * m.gate_exps.expert_stride;
6179                let up_start = ex * m.up_exps.expert_stride;
6180                let down_start = ex * m.down_exps.expert_stride;
6181                if grouped_q8 {
6182                    let (zq, zd) = e.quantize_q8_1(&gathered, m_e, n_embd)?;
6183                    let gate = e.qmatvec_expert_q8(
6184                        &dev.gate,
6185                        gate_start..gate_start + gl.len,
6186                        &zq,
6187                        &zd,
6188                        m_e,
6189                        m.gate_exps.in_f,
6190                        m.gate_exps.out_f,
6191                        gl.qtype,
6192                        gl.row_bytes,
6193                    )?;
6194                    let up = e.qmatvec_expert_q8(
6195                        &dev.up,
6196                        up_start..up_start + ul.len,
6197                        &zq,
6198                        &zd,
6199                        m_e,
6200                        m.up_exps.in_f,
6201                        m.up_exps.out_f,
6202                        ul.qtype,
6203                        ul.row_bytes,
6204                    )?;
6205                    let mut act = e.uninit(m_e * n_ff_exp)?;
6206                    Self::ffn_act_lim(
6207                        e,
6208                        cfg,
6209                        &gate,
6210                        &up,
6211                        m.gate_exps.macro_scale(ex),
6212                        m.up_exps.macro_scale(ex),
6213                        lim_exp,
6214                        &mut act,
6215                        m_e * n_ff_exp,
6216                    )?;
6217                    let (aq2, ad2) = e.quantize_q8_1(&act, m_e, n_ff_exp)?;
6218                    e.qmatvec_expert_q8(
6219                        &dev.down,
6220                        down_start..down_start + dl.len,
6221                        &aq2,
6222                        &ad2,
6223                        m_e,
6224                        m.down_exps.in_f,
6225                        m.down_exps.out_f,
6226                        dl.qtype,
6227                        dl.row_bytes,
6228                    )?
6229                } else {
6230                    let gate = e.qmatvec_view(
6231                        &dev.gate,
6232                        gate_start..gate_start + gl.len,
6233                        &gv,
6234                        m_e,
6235                        m.gate_exps.in_f,
6236                        m.gate_exps.out_f,
6237                        gl.qtype,
6238                        gl.row_bytes,
6239                    )?;
6240                    let up = e.qmatvec_view(
6241                        &dev.up,
6242                        up_start..up_start + ul.len,
6243                        &gv,
6244                        m_e,
6245                        m.up_exps.in_f,
6246                        m.up_exps.out_f,
6247                        ul.qtype,
6248                        ul.row_bytes,
6249                    )?;
6250                    let mut act = e.uninit(m_e * n_ff_exp)?;
6251                    Self::ffn_act_lim(
6252                        e,
6253                        cfg,
6254                        &gate,
6255                        &up,
6256                        m.gate_exps.macro_scale(ex),
6257                        m.up_exps.macro_scale(ex),
6258                        lim_exp,
6259                        &mut act,
6260                        m_e * n_ff_exp,
6261                    )?;
6262                    let actv = act.slice(0..m_e * n_ff_exp);
6263                    e.qmatvec_view(
6264                        &dev.down,
6265                        down_start..down_start + dl.len,
6266                        &actv,
6267                        m_e,
6268                        m.down_exps.in_f,
6269                        m.down_exps.out_f,
6270                        dl.qtype,
6271                        dl.row_bytes,
6272                    )?
6273                }
6274            } else if use_cache {
6275                use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
6276                if grouped_q8 {
6277                    let (zq, zd) = e.quantize_q8_1(&gathered, m_e, n_embd)?;
6278                    let gate = e.with_moe_cache(max_block, |cache, eng| {
6279                        let id = BlockId::new(il, PROJ_GATE, ex as u16);
6280                        let slot =
6281                            cache.dispatch_source(id, m.gate_exps.expert_source(ex), eng)?;
6282                        eng.qmatvec_expert_q8(
6283                            cache.buf(slot),
6284                            0..gl.len,
6285                            &zq,
6286                            &zd,
6287                            m_e,
6288                            m.gate_exps.in_f,
6289                            m.gate_exps.out_f,
6290                            gl.qtype,
6291                            gl.row_bytes,
6292                        )
6293                    })?;
6294                    let up = e.with_moe_cache(max_block, |cache, eng| {
6295                        let id = BlockId::new(il, PROJ_UP, ex as u16);
6296                        let slot =
6297                            cache.dispatch_source(id, m.up_exps.expert_source(ex), eng)?;
6298                        eng.qmatvec_expert_q8(
6299                            cache.buf(slot),
6300                            0..ul.len,
6301                            &zq,
6302                            &zd,
6303                            m_e,
6304                            m.up_exps.in_f,
6305                            m.up_exps.out_f,
6306                            ul.qtype,
6307                            ul.row_bytes,
6308                        )
6309                    })?;
6310                    let mut act = e.uninit(m_e * n_ff_exp)?;
6311                    Self::ffn_act_lim(
6312                        e,
6313                        cfg,
6314                        &gate,
6315                        &up,
6316                        m.gate_exps.macro_scale(ex),
6317                        m.up_exps.macro_scale(ex),
6318                        lim_exp,
6319                        &mut act,
6320                        m_e * n_ff_exp,
6321                    )?;
6322                    let (aq2, ad2) = e.quantize_q8_1(&act, m_e, n_ff_exp)?;
6323                    e.with_moe_cache(max_block, |cache, eng| {
6324                        let id = BlockId::new(il, PROJ_DOWN, ex as u16);
6325                        let slot =
6326                            cache.dispatch_source(id, m.down_exps.expert_source(ex), eng)?;
6327                        eng.qmatvec_expert_q8(
6328                            cache.buf(slot),
6329                            0..dl.len,
6330                            &aq2,
6331                            &ad2,
6332                            m_e,
6333                            m.down_exps.in_f,
6334                            m.down_exps.out_f,
6335                            dl.qtype,
6336                            dl.row_bytes,
6337                        )
6338                    })?
6339                } else {
6340                    let gate = e.with_moe_cache(max_block, |cache, eng| {
6341                        let id = BlockId::new(il, PROJ_GATE, ex as u16);
6342                        let slot =
6343                            cache.dispatch_source(id, m.gate_exps.expert_source(ex), eng)?;
6344                        eng.qmatvec_view(
6345                            cache.buf(slot),
6346                            0..gl.len,
6347                            &gv,
6348                            m_e,
6349                            m.gate_exps.in_f,
6350                            m.gate_exps.out_f,
6351                            gl.qtype,
6352                            gl.row_bytes,
6353                        )
6354                    })?;
6355                    let up = e.with_moe_cache(max_block, |cache, eng| {
6356                        let id = BlockId::new(il, PROJ_UP, ex as u16);
6357                        let slot =
6358                            cache.dispatch_source(id, m.up_exps.expert_source(ex), eng)?;
6359                        eng.qmatvec_view(
6360                            cache.buf(slot),
6361                            0..ul.len,
6362                            &gv,
6363                            m_e,
6364                            m.up_exps.in_f,
6365                            m.up_exps.out_f,
6366                            ul.qtype,
6367                            ul.row_bytes,
6368                        )
6369                    })?;
6370                    let mut act = e.uninit(m_e * n_ff_exp)?;
6371                    Self::ffn_act_lim(
6372                        e,
6373                        cfg,
6374                        &gate,
6375                        &up,
6376                        m.gate_exps.macro_scale(ex),
6377                        m.up_exps.macro_scale(ex),
6378                        lim_exp,
6379                        &mut act,
6380                        m_e * n_ff_exp,
6381                    )?;
6382                    let actv = act.slice(0..m_e * n_ff_exp);
6383                    e.with_moe_cache(max_block, |cache, eng| {
6384                        let id = BlockId::new(il, PROJ_DOWN, ex as u16);
6385                        let slot =
6386                            cache.dispatch_source(id, m.down_exps.expert_source(ex), eng)?;
6387                        eng.qmatvec_view(
6388                            cache.buf(slot),
6389                            0..dl.len,
6390                            &actv,
6391                            m_e,
6392                            m.down_exps.in_f,
6393                            m.down_exps.out_f,
6394                            dl.qtype,
6395                            dl.row_bytes,
6396                        )
6397                    })?
6398                }
6399            } else {
6400                let sg = scratch_g.as_mut().unwrap();
6401                let su = scratch_u.as_mut().unwrap();
6402                let sd = scratch_d.as_mut().unwrap();
6403                e.stage_expert(m.gate_exps.expert_bytes(ex), sg, 0)?;
6404                e.stage_expert(m.up_exps.expert_bytes(ex), su, 0)?;
6405                e.stage_expert(m.down_exps.expert_bytes(ex), sd, 0)?;
6406                if grouped_q8 {
6407                    let (zq, zd) = e.quantize_q8_1(&gathered, m_e, n_embd)?;
6408                    let gate = e.qmatvec_expert_q8(
6409                        sg,
6410                        0..gl.len,
6411                        &zq,
6412                        &zd,
6413                        m_e,
6414                        m.gate_exps.in_f,
6415                        m.gate_exps.out_f,
6416                        gl.qtype,
6417                        gl.row_bytes,
6418                    )?;
6419                    let up = e.qmatvec_expert_q8(
6420                        su,
6421                        0..ul.len,
6422                        &zq,
6423                        &zd,
6424                        m_e,
6425                        m.up_exps.in_f,
6426                        m.up_exps.out_f,
6427                        ul.qtype,
6428                        ul.row_bytes,
6429                    )?;
6430                    let mut act = e.uninit(m_e * n_ff_exp)?;
6431                    Self::ffn_act_lim(
6432                        e,
6433                        cfg,
6434                        &gate,
6435                        &up,
6436                        m.gate_exps.macro_scale(ex),
6437                        m.up_exps.macro_scale(ex),
6438                        lim_exp,
6439                        &mut act,
6440                        m_e * n_ff_exp,
6441                    )?;
6442                    let (aq2, ad2) = e.quantize_q8_1(&act, m_e, n_ff_exp)?;
6443                    e.qmatvec_expert_q8(
6444                        sd,
6445                        0..dl.len,
6446                        &aq2,
6447                        &ad2,
6448                        m_e,
6449                        m.down_exps.in_f,
6450                        m.down_exps.out_f,
6451                        dl.qtype,
6452                        dl.row_bytes,
6453                    )?
6454                } else {
6455                    let gate = e.qmatvec_view(
6456                        sg,
6457                        0..gl.len,
6458                        &gv,
6459                        m_e,
6460                        m.gate_exps.in_f,
6461                        m.gate_exps.out_f,
6462                        gl.qtype,
6463                        gl.row_bytes,
6464                    )?;
6465                    let up = e.qmatvec_view(
6466                        su,
6467                        0..ul.len,
6468                        &gv,
6469                        m_e,
6470                        m.up_exps.in_f,
6471                        m.up_exps.out_f,
6472                        ul.qtype,
6473                        ul.row_bytes,
6474                    )?;
6475                    let mut act = e.uninit(m_e * n_ff_exp)?;
6476                    Self::ffn_act_lim(
6477                        e,
6478                        cfg,
6479                        &gate,
6480                        &up,
6481                        m.gate_exps.macro_scale(ex),
6482                        m.up_exps.macro_scale(ex),
6483                        lim_exp,
6484                        &mut act,
6485                        m_e * n_ff_exp,
6486                    )?;
6487                    let actv = act.slice(0..m_e * n_ff_exp);
6488                    e.qmatvec_view(
6489                        sd,
6490                        0..dl.len,
6491                        &actv,
6492                        m_e,
6493                        m.down_exps.in_f,
6494                        m.down_exps.out_f,
6495                        dl.qtype,
6496                        dl.row_bytes,
6497                    )?
6498                }
6499            };
6500
6501            // SCATTER into slot buffer: each row goes to slot_buf[tok, slot, :].
6502            e.scatter_slot(&y, &tok_idx_d, &slot_idx_d, &weight_d,
6503                           &mut slot_buf, &mut wbuf, n_embd, n_used, m_e)?;
6504        }
6505
6506        // 5. REDUCE SLOTS: sum the 8 slots per token into the final moe_out.
6507        let mut moe_out = e.zeros(t * n_embd)?;
6508        e.reduce_slots(&slot_buf, &wbuf, &mut moe_out, n_embd, n_used, t)?;
6509
6510        // STATS: print m-distribution when MEMRA_MOE_STATS is set.
6511        if std::env::var("MEMRA_MOE_STATS").is_ok() && !m_dist.is_empty() {
6512            m_dist.sort_unstable();
6513            let active = m_dist.len();
6514            let mean = m_dist.iter().sum::<usize>() as f64 / active as f64;
6515            let median = m_dist[active / 2];
6516            let max_m = *m_dist.last().unwrap();
6517            let min_m = m_dist[0];
6518            let above16 = m_dist.iter().filter(|&&x| x >= 16).count();
6519            println!("moe-grouped il={il} t={t} active={active}/{n_expert} \
6520                      m_e: min={min_m} median={median} mean={mean:.1} max={max_m} \
6521                      above_gemm_threshold(>=16)={above16}/{active}");
6522        }
6523
6524        Self::moe_ffn_grouped_add_shared(e, m, z, t, cfg, il, &mut moe_out)?;
6525        Ok(moe_out)
6526    }
6527
6528    /// Lane-3 M2: cross-stream MoE for lockstep decode. Routes all m stream rows in one
6529    /// batch, executes fully-HBM-resident experts through the grouped gather/GEMM/scatter
6530    /// machinery at m_e>1 (weight reads amortized across streams), and assigns any expert
6531    /// with a missing projection to that row's CPU companion call (whole-expert granularity,
6532    /// same rule as the sequential frozen path). Slot-pinned accumulation keeps each row's
6533    /// expert-sum order identical to the sequential path.
6534    pub(crate) fn moe_ffn_lockstep(
6535        &self,
6536        e: &Engine,
6537        m: &MoeWeights,
6538        zbatch: &CudaSlice<f32>,
6539        mrows: usize,
6540        il: u16,
6541        max_block: usize,
6542    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6543        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
6544        let cfg = &self.cfg;
6545        let moe = cfg.moe.as_ref().unwrap();
6546        let n_embd = cfg.n_embd as usize;
6547        let n_expert = moe.expert_count as usize;
6548        let n_used = moe.expert_used_count as usize;
6549        let n_ff_exp = moe.expert_ff_length as usize;
6550        // step35 per-layer SwiGLU clamp; None on every other arch / unclamped layer.
6551        let lim_exp = cfg.clamp_exp_at(il as u32);
6552        let lim_shexp = cfg.clamp_shexp_at(il as u32);
6553
6554        let logits = e.matmul(&m.gate_inp, zbatch, mrows)?;
6555        if let Some(sig) = cfg.sigmoid_router() {
6556            Self::trace_sigmoid_router_logits(
6557                e, il, mrows, n_expert, n_used, &logits, m, sig,
6558            )?;
6559        }
6560        let (sel_all, w_all) = if let Some(sig) = cfg.sigmoid_router() {
6561            Self::moe_route_sigmoid_cfg(e, &logits, mrows, n_expert, n_used, m, sig)?
6562        } else {
6563            Self::moe_route_cfg(e, &logits, mrows, n_expert, n_used,
6564                                m.active_experts.as_deref())?
6565        };
6566        Self::trace_moe_routes(il, mrows, &sel_all, &w_all)?;
6567
6568        // Residency split at whole-expert granularity against the (frozen) cache.
6569        let resident_expert: Vec<bool> = e.with_moe_cache(max_block, |c, _| {
6570            Ok((0..n_expert)
6571                .map(|ex| {
6572                    [PROJ_GATE, PROJ_UP, PROJ_DOWN].into_iter().all(|p| {
6573                        c.resident(BlockId::new(il, p, ex as u16)).is_some()
6574                    })
6575                })
6576                .collect())
6577        })?;
6578
6579        struct Group {
6580            rows: Vec<i32>,
6581            slots: Vec<i32>,
6582            weights: Vec<f32>,
6583        }
6584        let mut groups: std::collections::HashMap<usize, Group> = Default::default();
6585        let mut cpu_rows: Vec<Vec<(usize, f32)>> = vec![Vec::new(); mrows];
6586        let mut cpu_by_expert: std::collections::HashMap<usize, Vec<(usize, f32)>> =
6587            Default::default();
6588        for row in 0..mrows {
6589            for j in 0..n_used {
6590                let ex = sel_all[row * n_used + j] as usize;
6591                let w = w_all[row * n_used + j];
6592                if resident_expert[ex] {
6593                    let group = groups.entry(ex).or_insert_with(|| Group {
6594                        rows: Vec::new(),
6595                        slots: Vec::new(),
6596                        weights: Vec::new(),
6597                    });
6598                    group.rows.push(row as i32);
6599                    group.slots.push(j as i32);
6600                    group.weights.push(w);
6601                } else {
6602                    crate::cpu_experts::record_incomplete_gpu_residency(0);
6603                    cpu_rows[row].push((ex, w));
6604                    cpu_by_expert.entry(ex).or_default().push((row, w));
6605                }
6606            }
6607        }
6608
6609        // CPU tickets first: reads/compute overlap the GPU grouped work below. Experts routed
6610        // by >=2 streams go through the multi-row ABI (weight decode amortized across rows);
6611        // each row's remaining experts stay one ordinary per-row call. Contribution FP-sum
6612        // order per row differs from the sequential single-call chunk — part of the
6613        // documented lockstep numeric class.
6614        let host_rows = e.dtoh(zbatch)?;
6615        let rows_ok = crate::cpu_experts::rows_supported();
6616        enum CpuPart {
6617            Single { row: usize },
6618            Rows { rows: Vec<usize> },
6619        }
6620        let mut tickets: Vec<(CpuPart, crate::cpu_experts::CpuExpertTicket)> = Vec::new();
6621        let mut rows_served: std::collections::HashSet<(usize, usize)> = Default::default();
6622        if rows_ok {
6623            let mut shared: Vec<(usize, Vec<(usize, f32)>)> = cpu_by_expert
6624                .into_iter()
6625                .filter(|(_, rows)| rows.len() >= 2)
6626                .collect();
6627            shared.sort_by_key(|(ex, _)| *ex);
6628            for (ex, mut row_weights) in shared {
6629                row_weights.sort_by_key(|(row, _)| *row);
6630                let inputs: Vec<(&[f32], f32)> = row_weights
6631                    .iter()
6632                    .map(|&(row, w)| (&host_rows[row * n_embd..(row + 1) * n_embd], w))
6633                    .collect();
6634                let job = crate::cpu_experts::prepare_rows_job(m, ex, &inputs)
6635                    .map_err(std::io::Error::other)?;
6636                for &(row, _) in &row_weights {
6637                    rows_served.insert((row, ex));
6638                }
6639                tickets.push((
6640                    CpuPart::Rows {
6641                        rows: row_weights.iter().map(|&(row, _)| row).collect(),
6642                    },
6643                    crate::cpu_experts::submit_rows(job).map_err(std::io::Error::other)?,
6644                ));
6645            }
6646        }
6647        for (row, selected) in cpu_rows.iter().enumerate() {
6648            let leftover: Vec<(usize, f32)> = selected
6649                .iter()
6650                .copied()
6651                .filter(|&(ex, _)| !rows_served.contains(&(row, ex)))
6652                .collect();
6653            if leftover.is_empty() {
6654                continue;
6655            }
6656            let host_row = &host_rows[row * n_embd..(row + 1) * n_embd];
6657            let job = crate::cpu_experts::prepare_job(m, il, &leftover, host_row)
6658                .map_err(std::io::Error::other)?;
6659            tickets.push((
6660                CpuPart::Single { row },
6661                crate::cpu_experts::submit(job).map_err(std::io::Error::other)?,
6662            ));
6663        }
6664
6665        let mut slot_buf = e.zeros(mrows * n_used * n_embd)?;
6666        let mut wbuf = e.zeros(mrows * n_used)?;
6667        let mut order: Vec<usize> = groups.keys().copied().collect();
6668        order.sort_by(|&a, &b| {
6669            groups[&b].rows.len().cmp(&groups[&a].rows.len()).then(a.cmp(&b))
6670        });
6671        for &ex in &order {
6672            let group = &groups[&ex];
6673            let m_e = group.rows.len();
6674            let gl = m.gate_exps.expert_layout(ex);
6675            let ul = m.up_exps.expert_layout(ex);
6676            let dl = m.down_exps.expert_layout(ex);
6677            let row_idx_d = e.htod_i32(&group.rows)?;
6678            let slot_idx_d = e.htod_i32(&group.slots)?;
6679            let dmac = m.down_exps.macro_scale(ex);
6680            let weight_d = if dmac == 1.0 {
6681                e.htod(&group.weights)?
6682            } else {
6683                let scaled: Vec<f32> = group.weights.iter().map(|&w| w * dmac).collect();
6684                e.htod(&scaled)?
6685            };
6686            let mut gathered = e.zeros(m_e * n_embd)?;
6687            e.gather_rows(zbatch, &row_idx_d, &mut gathered, n_embd, m_e)?;
6688            let gv = gathered.slice(0..m_e * n_embd);
6689            let gate = e.with_moe_cache(max_block, |c, eng| {
6690                let slot = c
6691                    .resident(BlockId::new(il, PROJ_GATE, ex as u16))
6692                    .ok_or("lockstep resident expert vanished (cache not frozen?)")?;
6693                eng.qmatvec_view(c.buf(crate::moe_cache::DispatchSlot::Resident(slot)), 0..gl.len, &gv, m_e,
6694                    m.gate_exps.in_f, m.gate_exps.out_f, gl.qtype, gl.row_bytes)
6695            })?;
6696            let up = e.with_moe_cache(max_block, |c, eng| {
6697                let slot = c
6698                    .resident(BlockId::new(il, PROJ_UP, ex as u16))
6699                    .ok_or("lockstep resident expert vanished (cache not frozen?)")?;
6700                eng.qmatvec_view(c.buf(crate::moe_cache::DispatchSlot::Resident(slot)), 0..ul.len, &gv, m_e,
6701                    m.up_exps.in_f, m.up_exps.out_f, ul.qtype, ul.row_bytes)
6702            })?;
6703            let mut act = e.zeros(m_e * n_ff_exp)?;
6704            Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
6705                m.up_exps.macro_scale(ex), lim_exp, &mut act, m_e * n_ff_exp)?;
6706            let actv = act.slice(0..m_e * n_ff_exp);
6707            let y = e.with_moe_cache(max_block, |c, eng| {
6708                let slot = c
6709                    .resident(BlockId::new(il, PROJ_DOWN, ex as u16))
6710                    .ok_or("lockstep resident expert vanished (cache not frozen?)")?;
6711                eng.qmatvec_view(c.buf(crate::moe_cache::DispatchSlot::Resident(slot)), 0..dl.len, &actv, m_e,
6712                    m.down_exps.in_f, m.down_exps.out_f, dl.qtype, dl.row_bytes)
6713            })?;
6714            e.scatter_slot(&y, &row_idx_d, &slot_idx_d, &weight_d,
6715                           &mut slot_buf, &mut wbuf, n_embd, n_used, m_e)?;
6716        }
6717        let mut moe_out = e.zeros(mrows * n_embd)?;
6718        e.reduce_slots(&slot_buf, &wbuf, &mut moe_out, n_embd, n_used, mrows)?;
6719
6720        // CPU contributions join BEFORE the shared expert (the sequential path's placement).
6721        let mut row_sums: Vec<Option<Vec<f32>>> = vec![None; mrows];
6722        for (part, ticket) in tickets {
6723            let cpu_output = ticket.wait().map_err(std::io::Error::other)?;
6724            let mut add_row = |row: usize, chunk: &[f32]| {
6725                let sum = row_sums[row].get_or_insert_with(|| vec![0.0f32; n_embd]);
6726                for (accumulator, value) in sum.iter_mut().zip(chunk) {
6727                    *accumulator += value;
6728                }
6729            };
6730            match part {
6731                CpuPart::Single { row } => add_row(row, &cpu_output),
6732                CpuPart::Rows { rows } => {
6733                    for (slot, row) in rows.into_iter().enumerate() {
6734                        add_row(row, &cpu_output[slot * n_embd..(slot + 1) * n_embd]);
6735                    }
6736                }
6737            }
6738        }
6739        for (row, sum) in row_sums.into_iter().enumerate() {
6740            let Some(sum) = sum else { continue };
6741            let cpu_output = e.htod(&sum)?;
6742            let mut dst = moe_out.slice_mut(row * n_embd..(row + 1) * n_embd);
6743            e.axpy_into(&cpu_output, 1.0, &mut dst, n_embd)?;
6744        }
6745
6746        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
6747            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
6748        {
6749            let n_ff_sh = gate_shexp.out_features();
6750            let sg_gate = e.matmul(gate_shexp, zbatch, mrows)?;
6751            let sg_up = e.matmul(up_shexp, zbatch, mrows)?;
6752            let mut sa = e.zeros(mrows * n_ff_sh)?;
6753            Self::ffn_act_lim(e, cfg, &sg_gate, &sg_up, 1.0, 1.0, lim_shexp,
6754                              &mut sa, mrows * n_ff_sh)?;
6755            let sh = e.matmul(down_shexp, &sa, mrows)?;
6756            // lockstep rows ARE decode tokens: fused sigmoid-dot per row so batched serving
6757            // decode matches the single-sequence decode chain bit-for-bit.
6758            let g = match &m.gate_inp_shexp {
6759                Some(gate_inp_shexp) => {
6760                    e.sigmoid_dot_rows(zbatch, gate_inp_shexp.float_data(), n_embd, mrows)?
6761                }
6762                None => e.htod(&vec![1.0f32; mrows])?,
6763            };
6764            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, mrows)?;
6765        }
6766
6767        Ok(moe_out)
6768    }
6769}
6770
6771// ============================ gemma4 (R8 verified wiring) ==================================
6772// Node-for-node vs llama.cpp src/models/gemma4.cpp:180-405 (HANDOVER "R8 VERIFIED WIRING").
6773// v0 bring-up: full attention everywhere (exact for prompts < sliding_window 1024 — R6 masking
6774// later), sdpa_naive (hd 512 has no FA stamp), sequential host-staged MoE (the perf arms grow
6775// gemma variants after the correctness gate).
6776impl HybridModel {
6777    /// Per-layer attention geometry (R5): (head_dim, n_kv, n_head, rope_base, scale, is_swa).
6778    pub(crate) fn gemma4_geom(&self, il: usize) -> (usize, usize, usize, f32, f32, bool) {
6779        let g = self.cfg.gemma4.as_ref().unwrap();
6780        let swa = g.swa_pattern[il];
6781        let hd = if swa { g.key_length_swa } else { g.key_length_global } as usize;
6782        // attention scale = 1.0 (llama gemma4.cpp:11 "Gemma4 uses self.scaling = 1.0" — q/k are
6783        // per-head rms-normed; NOT the 1/sqrt(hd) default. Bring-up bug: 1/sqrt(hd) left token-0
6784        // rows exact (softmax over one element) while every later position drifted).
6785        (hd, g.head_count_kv[il] as usize, self.cfg.n_head as usize,
6786         if swa { g.rope_base_swa } else { g.rope_base_global },
6787         1.0, swa)
6788    }
6789
6790    /// Suppress-token mask over t logits rows (tokenizer.ggml.suppress_tokens; no-op when the
6791    /// model ships none). NOT monotonic like softcap — must run before every argmax/sample, so
6792    /// every gemma4 logits tail (forward/prime/decode/dc/verify/e4b) calls this on device ld.
6793    fn gemma4_suppress(&self, e: &Engine, ld: &mut CudaSlice<f32>, t: usize)
6794                       -> Result<(), Box<dyn std::error::Error>> {
6795        if let Some((ids, n)) = self.gemma4_aux.as_ref().and_then(|a| a.suppress_d.as_ref()) {
6796            // suppress_d is primary-owned by the audited invariant (serving picks the last/head
6797            // stage as primary, and this tail runs only after the last stage). The assert turns
6798            // that argued invariant into a checked one: any topology violating primary==head
6799            // trips here in debug instead of silently peer-reading a device-0 buffer.
6800            #[cfg(debug_assertions)]
6801            crate::debug_assert_tensor_stream_device(ids, &e.stream(),
6802                                                     "gemma4_suppress.suppress_d");
6803            e.mask_ids_rows(ld, ids, *n, self.output.out_features(), t)?;
6804        }
6805        Ok(())
6806    }
6807
6808    /// gemma4 attention (R5 geometry, R7 weightless V-norm on the RAW K projection, R9 dual rope).
6809    /// `cache`: Some => PRIME mode — append the T post-rope K / normed V rows into the quantized
6810    /// KV cache (same per-row quantize math as the decode append) and advance len. Fresh-prompt
6811    /// only (v0): attends within `tokens` via the f32 sdpa.
6812    fn gemma4_attn_prime(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
6813                         h: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize,
6814                         cache: Option<&mut Cache>)
6815                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6816        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
6817        let eps = self.cfg.rms_eps;
6818        let aux = self.gemma4_aux.as_ref().unwrap();
6819        let ones = aux.ones(e);
6820        #[cfg(debug_assertions)]
6821        crate::debug_assert_tensor_stream_device(ones, &e.stream(),
6822                                                   "gemma4_attn_prime.ones");
6823
6824        // quantize-once window: q/k/v share `h` — the MMQ D4 activation quantizes once
6825        // (h stays borrowed across the triple, so the cache key can't go stale).
6826        e.mmq_act_begin();
6827        let q0 = e.matmul(&fa.wq, h, t)?;   // [t, nh*hd]
6828        let k0 = e.matmul(&fa.wk, h, t)?;   // [t, nkv*hd]
6829        // globals ship no v_proj (wv := wk at load) — V input is the SAME projection output;
6830        // reuse k0 instead of re-running the identical matmul (K=V dedup, 5 layers).
6831        let v0 = if swa { e.matmul(&fa.wv, h, t)? } else { e.clone_dtod(&k0)? };
6832
6833        let mut q = e.uninit(t * nh * hd)?;
6834        let mut k = e.uninit(t * nkv * hd)?;
6835        // R7: V = weightless rms_norm of the raw projection; NEVER roped.
6836        let mut v = e.uninit(t * nkv * hd)?;
6837        // 31B glue lane: producers emit the bf16 FA operands (norm emits vb; rope emits qb/kb
6838        // post-rope) — kills 3 f32->bf16 converts + re-reads per layer. Bit-identical operands
6839        // (same __float2bfloat16); MEMRA_FA_EMIT=0 reverts to the convert-in-FA path.
6840        static EMIT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6841        let emit = t >= 16 && crate::Engine::qkvnorm_w_on_prefill(nh * t + 2 * nkv * t, hd)
6842            && *EMIT.get_or_init(|| std::env::var("MEMRA_FA_EMIT").map(|s| s != "0").unwrap_or(true));
6843        let mut qb = e.alloc_uninit::<u8>(if emit { t * nh * hd * 2 } else { 1 })?;
6844        let mut kb = e.alloc_uninit::<u8>(if emit { t * nkv * hd * 2 } else { 1 })?;
6845        let mut vb = e.alloc_uninit::<u8>(if emit { t * nkv * hd * 2 } else { 1 })?;
6846        // f16-P/V door: emit V as f16 straight from the norm when this layer's FA consumer
6847        // reads f16 — kills the per-layer bf16->f16 re-encode (1.4GB/pass on 31B SWA).
6848        let v_f16 = emit && crate::fa_f16pv_on() && match hd {
6849            512 => true,
6850            256 => swa && crate::faw_hp_on() && nh % 2 == 0 && (nh / nkv) % 2 == 0,
6851            _ => false,
6852        };
6853        if emit {
6854            e.rms_norm_qkv_w4b(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
6855                               ones, &mut q, &mut k, &mut v, &mut vb,
6856                               hd, nh * t, nkv * t, eps, v_f16)?;
6857        } else {
6858            e.rms_norm_qkv(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
6859                           ones, &mut q, &mut k, &mut v, hd, nh * t, nkv * t, eps)?;
6860        }
6861
6862        let ff = if swa { None } else {
6863            Some(aux.rope_freqs(e).expect("gemma4 global rope needs rope_freqs.weight"))
6864        };
6865        #[cfg(debug_assertions)]
6866        if let Some(ff) = ff {
6867            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
6868                                                       "gemma4_attn_prime.rope_freqs");
6869        }
6870        if emit {
6871            e.rope_neox2_bf16e(&mut q, &mut k, &mut qb, &mut kb, pos_d, hd, hd, nh, nkv, t,
6872                               base, 1.0, ff)?;
6873        } else {
6874            e.rope_neox2(&mut q, &mut k, pos_d, hd, hd, nh, nkv, t, base, 1.0, ff)?;
6875        }
6876
6877        if let Some(cache) = cache {
6878            let kvl = cache.kv[il].as_mut().unwrap();
6879            assert_eq!(kvl.len, 0, "gemma4 prime is fresh-prompt only (v0)");
6880            e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len, t,
6881                                       kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes, (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on()))?;
6882            kvl.len += t;
6883        }
6884        let mut attn = e.zeros(t * nh * hd)?;
6885        // R6: SWA layers mask keys older than sliding_window once the prompt exceeds it
6886        // (windowed naive twin; fa windowed stamps later). Under the window, full attention
6887        // is exact — SWA rides fa_prefill (hd-256 stamp), the hd-512 globals stay naive.
6888        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
6889        if swa && t > win {
6890            if hd == 256 && std::env::var("MEMRA_NOFA").is_err() {
6891                if emit { e.fa_prefill_w_pre(&qb, &kb, &vb, &mut attn, hd, nh, nkv, t, t,
6892                                             scale, true, win, v_f16)?; }
6893                else { e.fa_prefill_w(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true,
6894                                      win)?; }
6895            } else {
6896                e.sdpa_naive_w(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true, win)?;
6897            }
6898        } else if hd == 256 && std::env::var("MEMRA_NOFA").is_err() {
6899            e.fa_prefill(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
6900        } else if hd == 512 && std::env::var("MEMRA_NOFA").is_err() {
6901            if emit { e.fa_prefill_hd512_pre(&qb, &kb, &vb, &mut attn, hd, nh, nkv, t, t,
6902                                             scale, true, v_f16)?; }
6903            else { e.fa_prefill_hd512(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?; }
6904        } else {
6905            e.sdpa_naive(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
6906        }
6907        Ok(e.matmul(&fa.wo, &attn, t)?)
6908    }
6909
6910    /// Back-compat wrapper (pure prefill, no cache).
6911    fn gemma4_attn(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
6912                   h: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize)
6913                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6914        self.gemma4_attn_prime(e, fa, il, h, pos_d, t, None)
6915    }
6916
6917    /// gemma4 MoE with the expert input PRE-QUANTIZED (the q8z tail fusion). Caller guarantees
6918    /// the fast-arm conditions (resident dev slabs + dp4a qtypes) — decode t=1 and verify rows
6919    /// arms only, per-token kernel chains identical to the f32-input path (same quantize bytes:
6920    /// the q8z epilogue is quantize_q8_1 verbatim).
6921    fn gemma4_moe_q8(&self, e: &Engine, m: &crate::hybrid::MoeWeights,
6922                     bits: &crate::hybrid::Gemma4MoeBits,
6923                     mq: &(CudaSlice<i8>, CudaSlice<f32>),
6924                     router_in: &CudaSlice<f32>, t: usize)
6925                     -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6926        let cfg = &self.cfg;
6927        let moe = cfg.moe.as_ref().unwrap();
6928        let n_embd = cfg.n_embd as usize;
6929        let n_expert = moe.expert_count as usize;
6930        let n_used = moe.expert_used_count as usize;
6931        let n_ff_exp = moe.expert_ff_length as usize;
6932        // router stays the two-launch pair: THREE fuse variants measured worse (serial-dot
6933        // -50%, 1024-thread warp-parallel -12% on topk sync overhead — jsonl 2026-07-11);
6934        // the pair's 12us is kernel time, not launch gaps.
6935        let logits = if crate::router_kernel_on() {
6936            e.router_gemv(m.gate_inp.float_data(), router_in, n_embd, n_expert, t)?
6937        } else {
6938            e.matmul(&m.gate_inp, router_in, t)?
6939        };
6940        let dev = m.dev_exps.as_ref().unwrap();
6941        let (sel_d, w_d) = e.moe_router_topk_scaled(&logits, t, n_expert, n_used,
6942                                                    &bits.per_expert_scale_d)?;
6943        let (zq, zd) = mq;
6944        if t == 1 {
6945            let selv = sel_d.slice(0..n_used);
6946            let wv = w_d.slice(0..n_used);
6947            let act = e.moe_gate_up_gelu8_dev_q8(&dev.ptr_row, &selv, zq, zd,
6948                                                 n_embd, n_ff_exp, n_used, n_expert,
6949                                                 m.gate_exps.qtype, m.up_exps.qtype,
6950                                                 m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
6951            let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
6952            let mut moe_out = e.uninit(n_embd)?;
6953            e.moe_down8_fma_dev_q8(&dev.ptr_row, &selv, &wv, &aq2, &ad2,
6954                                   &mut moe_out.slice_mut(0..n_embd), n_ff_exp, n_embd,
6955                                   n_used, n_expert, m.down_exps.qtype, m.down_exps.row_bytes)?;
6956            return Ok(moe_out);
6957        }
6958        let csr = t <= 10 && std::env::var("MEMRA_GEMMA_CSR").as_deref() != Ok("0");
6959        let act = if csr {
6960            e.moe_gate_up_gelu8_dev_q8_csr(&dev.ptr_row, &sel_d, zq, zd, t * n_used,
6961                                           n_embd, n_ff_exp, n_used, n_expert,
6962                                           m.gate_exps.qtype, m.up_exps.qtype,
6963                                           m.gate_exps.row_bytes, m.up_exps.row_bytes)?
6964        } else {
6965            e.moe_gate_up_gelu8_dev_q8_rows(&dev.ptr_row, &sel_d, zq, zd, t,
6966                                            n_embd, n_ff_exp, n_used, n_expert,
6967                                            m.gate_exps.qtype, m.up_exps.qtype,
6968                                            m.gate_exps.row_bytes, m.up_exps.row_bytes)?
6969        };
6970        let (aq2, ad2) = e.quantize_q8_1(&act, t * n_used, n_ff_exp)?;
6971        let mut moe_out = e.uninit(t * n_embd)?;
6972        // down stays rows_g: the CSR dedup twin measured NEGATIVE at nsb=22 too (189.4 vs
6973        // 207.0 depth spec, bitwise-exact — jsonl 2026-07-10; qwen nsb=16 same verdict).
6974        e.moe_down8_fma_dev_q8_rows_g(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out, t,
6975                                      n_ff_exp, n_embd, n_used, n_expert,
6976                                      m.down_exps.qtype, m.down_exps.row_bytes)?;
6977        Ok(moe_out)
6978    }
6979
6980    /// gemma4 MoE (R2 router prologue input supplied by caller, R3 per-expert output scale).
6981    /// Sequential host-staged v0 — softmax gating + renorm (moe_route, the qwen recipe), GELU
6982    /// experts, scale folded into the accumulate weight (post-matmul linear scale, exact fold).
6983    fn gemma4_moe(&self, e: &Engine, m: &crate::hybrid::MoeWeights,
6984                  bits: &crate::hybrid::Gemma4MoeBits, moe_in: &CudaSlice<f32>,
6985                  router_in: &CudaSlice<f32>, t: usize)
6986                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6987        let cfg = &self.cfg;
6988        let moe = cfg.moe.as_ref().unwrap();
6989        let n_embd = cfg.n_embd as usize;
6990        let n_expert = moe.expert_count as usize;
6991        let n_used = moe.expert_used_count as usize;
6992        let n_ff_exp = moe.expert_ff_length as usize;
6993
6994        // Router: the in-house GEMV for ALL small t (decode AND verify ride the same per-column
6995        // kernel — the cuBLASLt n-dependence flipped top-k at verify t on the 27B, d994271);
6996        // batched matmul only at real prefill.
6997        let logits = if t < PRIME_MIN_T && crate::router_kernel_on() {
6998            e.router_gemv(m.gate_inp.float_data(), router_in, n_embd, n_expert, t)?
6999        } else {
7000            e.matmul(&m.gate_inp, router_in, t)?
7001        };
7002
7003        // FAST SMALL-T ARM (decode t=1 AND spec verify t=2..15): device softmax-topk router,
7004        // then PER TOKEN the same fused gate_up GELU + down8 FMA launch pair over the resident
7005        // dev slabs — verify rides the EXACT decode kernel chain per token (dispatch-parity
7006        // law; the qwen "verify must be kernel-dispatch-identical to decode" lesson).
7007        if t < PRIME_MIN_T && m.dev_exps.as_ref().is_some_and(|d| !d.gu_il)
7008            && expert_dp4a_supported(m.gate_exps.qtype) && expert_dp4a_supported(m.up_exps.qtype)
7009            && expert_dp4a_supported(m.down_exps.qtype)
7010            && std::env::var("MEMRA_GEMMA_MOE_FAST").as_deref() != Ok("0") {
7011            let dev = m.dev_exps.as_ref().unwrap();
7012            let (sel_d, w_d) = e.moe_router_topk_scaled(&logits, t, n_expert, n_used,
7013                                                        &bits.per_expert_scale_d)?;
7014            if t == 1 {
7015                let (zq, zd) = e.quantize_q8_1(moe_in, 1, n_embd)?;
7016                let selv = sel_d.slice(0..n_used);
7017                let wv = w_d.slice(0..n_used);
7018                let act = e.moe_gate_up_gelu8_dev_q8(&dev.ptr_row, &selv, &zq, &zd,
7019                                                     n_embd, n_ff_exp, n_used, n_expert,
7020                                                     m.gate_exps.qtype, m.up_exps.qtype,
7021                                                     m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
7022                let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
7023                let mut moe_out = e.uninit(n_embd)?;
7024                e.moe_down8_fma_dev_q8(&dev.ptr_row, &selv, &wv, &aq2, &ad2,
7025                                       &mut moe_out.slice_mut(0..n_embd), n_ff_exp, n_embd,
7026                                       n_used, n_expert, m.down_exps.qtype, m.down_exps.row_bytes)?;
7027                return Ok(moe_out);
7028            }
7029            // VERIFY ROWS TWINS (t=2..15): ONE launch pair for all tokens; per (token,row,slot)
7030            // bodies are the t=1 kernels VERBATIM (bit-identical to the per-token loop).
7031            // gate_up rides the CSR owner-scan dedup when t <= 10 (each duplicated expert's
7032            // weight stream decoded once; the qwen CSR class). MEMRA_GEMMA_CSR=0 -> rows.
7033            let (zq, zd) = e.quantize_q8_1(moe_in, t, n_embd)?;
7034            let csr = t <= 10 && std::env::var("MEMRA_GEMMA_CSR").as_deref() != Ok("0");
7035            let act = if csr {
7036                e.moe_gate_up_gelu8_dev_q8_csr(&dev.ptr_row, &sel_d, &zq, &zd, t * n_used,
7037                                               n_embd, n_ff_exp, n_used, n_expert,
7038                                               m.gate_exps.qtype, m.up_exps.qtype,
7039                                               m.gate_exps.row_bytes, m.up_exps.row_bytes)?
7040            } else {
7041                e.moe_gate_up_gelu8_dev_q8_rows(&dev.ptr_row, &sel_d, &zq, &zd, t,
7042                                                n_embd, n_ff_exp, n_used, n_expert,
7043                                                m.gate_exps.qtype, m.up_exps.qtype,
7044                                                m.gate_exps.row_bytes, m.up_exps.row_bytes)?
7045            };
7046            let (aq2, ad2) = e.quantize_q8_1(&act, t * n_used, n_ff_exp)?;
7047            let mut moe_out = e.uninit(t * n_embd)?;
7048            e.moe_down8_fma_dev_q8_rows_g(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out, t,
7049                                          n_ff_exp, n_embd, n_used, n_expert,
7050                                          m.down_exps.qtype, m.down_exps.row_bytes)?;
7051            return Ok(moe_out);
7052        }
7053
7054        let (sel_all, mut w_all) = Self::moe_route(e, &logits, t, n_expert, n_used)?;
7055        for (i, &sx) in sel_all.iter().enumerate() {
7056            w_all[i] *= bits.per_expert_scale[sx as usize];
7057        }
7058
7059        // PREFILL PAIRS ARM (t >= 16): expert-major CSR over the resident slabs — ONE launch per
7060        // projection covers ALL (token,expert) pairs (the qwen pairs recipe, _em dot = expert_dot_g
7061        // which has the Q4_0 body; GELU pairs epilogue; R3 scale folded into pair_w).
7062        if t >= PRIME_MIN_T && m.dev_exps.as_ref().is_some_and(|d| !d.gu_il)
7063            && expert_dp4a_supported(m.gate_exps.qtype) && expert_dp4a_supported(m.up_exps.qtype)
7064            && expert_dp4a_supported(m.down_exps.qtype)
7065            && std::env::var("MEMRA_GEMMA_MOE_PAIRS").as_deref() != Ok("0") {
7066            let dev = m.dev_exps.as_ref().unwrap();
7067            let n_pairs = t * n_used;
7068            let pair_ex: Vec<i32> = sel_all.iter().map(|&x| x as i32).collect();
7069            let pair_tok: Vec<i32> = (0..n_pairs).map(|p| (p / n_used) as i32).collect();
7070            let tok_off: Vec<i32> = (0..=t).map(|tok| (tok * n_used) as i32).collect();
7071            let tok_ids: Vec<i32> = (0..n_pairs as i32).collect();
7072            let pt = e.htod_i32(&pair_tok)?;
7073            let pw = e.htod(&w_all)?;
7074            let toff = e.htod_i32(&tok_off)?;
7075            let tids = e.htod_i32(&tok_ids)?;
7076            let mut by_ex: Vec<Vec<i32>> = vec![Vec::new(); n_expert];
7077            for p in 0..n_pairs { by_ex[pair_ex[p] as usize].push(p as i32); }
7078            let mut ex_ids: Vec<i32> = Vec::new();
7079            let mut ex_off: Vec<i32> = vec![0];
7080            let mut ex_pairs: Vec<i32> = Vec::with_capacity(n_pairs);
7081            for (ex, list) in by_ex.iter().enumerate() {
7082                if list.is_empty() { continue; }
7083                ex_ids.push(ex as i32);
7084                ex_pairs.extend_from_slice(list);
7085                ex_off.push(ex_pairs.len() as i32);
7086            }
7087            let n_active = ex_ids.len();
7088            let exi = e.htod_i32(&ex_ids)?;
7089            let exo = e.htod_i32(&ex_off)?;
7090            let exp_d = e.htod_i32(&ex_pairs)?;
7091            // GROUPED f16 LANE (MEMRA_MOE_F16G=1, round 46 arc 2): dequant active experts to
7092            // f16 once per projection + one grouped f16 GEMM over the CSR groups; CSR order
7093            // end-to-end (gelu is elementwise), one row permute before the scatter. The
7094            // ragged down k (704) needs no padding here — cublas takes any k.
7095            // f16-mirror numeric class, argmax/spec gated. PER-MODEL default OFF (round 50):
7096            // the gelu class regressed g26 board-2048 prefill -8.3% under the round-49
7097            // Hopper default — see moe_f16g_gemma_on.
7098            if crate::moe_f16g_gemma_on()
7099                && f16g_proj_ok(m.gate_exps.qtype, n_embd)
7100                && f16g_proj_ok(m.up_exps.qtype, n_embd)
7101                && f16g_proj_ok(m.down_exps.qtype, n_ff_exp) {
7102                let csr_tok: Vec<i32> = ex_pairs.iter().map(|&p| p / n_used as i32).collect();
7103                let csr_tok_d = e.htod_i32(&csr_tok)?;
7104                let (z_f16, z_s) = e.moe_f16g_act(moe_in, Some(&csr_tok_d), n_embd, n_pairs)?;
7105                let g_csr = e.moe_f16_grouped(&dev.ptr_row, 0, n_expert, &exi, &ex_off, &exo,
7106                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
7107                                              m.gate_exps.qtype, m.gate_exps.row_bytes)?;
7108                let u_csr = e.moe_f16_grouped(&dev.ptr_row, 1, n_expert, &exi, &ex_off, &exo,
7109                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
7110                                              m.up_exps.qtype, m.up_exps.row_bytes)?;
7111                let act_csr = e.moe_pairs_gelu_mul(&g_csr, &u_csr, n_pairs * n_ff_exp)?;
7112                let (a_f16, a_s) = e.moe_f16g_act(&act_csr, None, n_ff_exp, n_pairs)?;
7113                let d_csr = e.moe_f16_grouped(&dev.ptr_row, 2, n_expert, &exi, &ex_off, &exo,
7114                                              &a_f16, &a_s, n_ff_exp, n_embd, n_active, n_pairs,
7115                                              m.down_exps.qtype, m.down_exps.row_bytes)?;
7116                let y_down = e.rows_permute(&d_csr, &exp_d, n_pairs, n_embd)?;
7117                let mut moe_out = e.uninit(t * n_embd)?;
7118                e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
7119                if std::env::var("MEMRA_F16G_DEBUG").is_ok() {
7120                    let scan = |v: &[f32]| v.iter().filter(|x| !x.is_finite()).count();
7121                    let (yd, mo) = (e.dtoh(&y_down)?, e.dtoh(&moe_out)?);
7122                    eprintln!("[f16g-debug] post-permute bad={} post-scatter bad={}",
7123                              scan(&yd), scan(&mo));
7124                }
7125                return Ok(moe_out);
7126            }
7127            // gate/up: int8-MMA expert GEMM (in_f = n_embd 2816 = 11x256 tiles ok); down keeps
7128            // the decode-once dp4a (in_f 704 fails the 256-superblock tiling).
7129            let mma = n_embd % 256 == 0
7130                && std::env::var("MEMRA_GEMMA_MOE_MMA").as_deref() != Ok("0");
7131            let (gate, up) = if mma {
7132                let z_scr = e.mmq_iq_quantize_act(moe_in, n_embd, t)?;
7133                (e.mmq_iq_experts(&dev.ptr_row, 0, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
7134                                  n_embd, n_ff_exp, n_active, n_pairs, t,
7135                                  m.gate_exps.qtype, m.gate_exps.row_bytes)?,
7136                 e.mmq_iq_experts(&dev.ptr_row, 1, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
7137                                  n_embd, n_ff_exp, n_active, n_pairs, t,
7138                                  m.up_exps.qtype, m.up_exps.row_bytes)?)
7139            } else {
7140                let (zq, zd) = e.quantize_q8_1(moe_in, t, n_embd)?;
7141                (e.moe_pairs_matvec_q8_dec(&dev.ptr_row, 0, &exi, &exo, &exp_d, &pt, &zq, &zd,
7142                                           n_embd, n_ff_exp, n_expert, n_active, n_pairs,
7143                                           m.gate_exps.qtype, m.gate_exps.row_bytes)?,
7144                 e.moe_pairs_matvec_q8_dec(&dev.ptr_row, 1, &exi, &exo, &exp_d, &pt, &zq, &zd,
7145                                           n_embd, n_ff_exp, n_expert, n_active, n_pairs,
7146                                           m.up_exps.qtype, m.up_exps.row_bytes)?)
7147            };
7148            let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
7149            let pself = e.htod_i32(&pair_self)?;
7150            // DOWN through the int8-MMA expert GEMM (2026-07-31, g26 prefill lever): the
7151            // ragged k (n_ff_exp=704 on the 26B) rides a PADDED k-walk — in_f rounds up
7152            // to the 256-val superblock (768) while the act quantizer's zero padding
7153            // makes every padded-k product exactly zero (weight overread bytes multiply
7154            // zero int8 act values; the dev slab carries 144B tail slack for the OOB).
7155            // The old dp4a matvec was 11.3ms/call at m=T (the 0.07x prefill wall).
7156            // MEMRA_GEMMA_MOE_MMA=0 reverts down together with gate/up.
7157            // FUSED ACT-EPILOGUE (default on): gelu_tanh(gate)*up + D4 quantize in one
7158            // launch — no f32 act buffer (the fused kernel zero-pads the ragged tail
7159            // exactly like the two-pass quantizer). MEMRA_MOE_FUSE_ACTQ=0 rollback.
7160            // Scratch bytes are BYTE-IDENTICAL (kernel-check gated).
7161            let y_down = if mma {
7162                let in_pad = n_ff_exp.div_ceil(256) * 256;
7163                let a_scr = if crate::moe_fuse_actq_on() {
7164                    e.mmq_iq_fused_act_quant(&gate, &up, n_ff_exp, n_pairs, 1)?
7165                } else {
7166                    let act = e.moe_pairs_gelu_mul(&gate, &up, n_pairs * n_ff_exp)?;
7167                    e.mmq_iq_quantize_act(&act, n_ff_exp, n_pairs)?
7168                };
7169                e.mmq_iq_experts(&dev.ptr_row, 2, n_expert, &exi, &exo, &exp_d, &pself, &a_scr,
7170                                 in_pad, n_embd, n_active, n_pairs, n_pairs,
7171                                 m.down_exps.qtype, m.down_exps.row_bytes)?
7172            } else {
7173                let act = e.moe_pairs_gelu_mul(&gate, &up, n_pairs * n_ff_exp)?;
7174                let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
7175                e.moe_pairs_matvec_q8_dec(&dev.ptr_row, 2, &exi, &exo, &exp_d, &pself, &aq2, &ad2,
7176                                          n_ff_exp, n_embd, n_expert, n_active, n_pairs,
7177                                          m.down_exps.qtype, m.down_exps.row_bytes)?
7178            };
7179            let mut moe_out = e.uninit(t * n_embd)?;
7180            e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
7181            return Ok(moe_out);
7182        }
7183
7184        let g_len = m.gate_exps.expert_stride;
7185        let u_len = m.up_exps.expert_stride;
7186        let d_len = m.down_exps.expert_stride;
7187        // Resident dev slabs (fits-VRAM regime): read each expert straight from the device slab
7188        // at ex*stride — zero H2D, SAME qmatvec_view kernel/bytes as the staged path. Staging is
7189        // the spill fallback.
7190        let dev = m.dev_exps.as_ref().filter(|d| !d.gu_il);
7191        let (mut sg, mut su, mut sd) = if dev.is_some() { (None, None, None) } else {
7192            (Some(e.alloc_u8_uninit(g_len)?), Some(e.alloc_u8_uninit(u_len)?), Some(e.alloc_u8_uninit(d_len)?))
7193        };
7194        let mut moe_out = e.zeros(t * n_embd)?;
7195        for tok in 0..t {
7196            let sel = &sel_all[tok * n_used..(tok + 1) * n_used];
7197            let w = &w_all[tok * n_used..(tok + 1) * n_used];
7198            let zt = moe_in.slice(tok * n_embd..(tok + 1) * n_embd);
7199            for (j, &ex) in sel.iter().enumerate() {
7200                let ex = ex as usize;
7201                let gate = match dev {
7202                    Some(d) => e.qmatvec_view(&d.gate, ex * g_len..(ex + 1) * g_len, &zt, 1,
7203                        m.gate_exps.in_f, m.gate_exps.out_f, m.gate_exps.qtype, m.gate_exps.row_bytes)?,
7204                    None => {
7205                        let sg = sg.as_mut().unwrap();
7206                        e.stage_expert(m.gate_exps.expert_bytes(ex), sg, 0)?;
7207                        e.qmatvec_view(sg, 0..g_len, &zt, 1,
7208                            m.gate_exps.in_f, m.gate_exps.out_f, m.gate_exps.qtype, m.gate_exps.row_bytes)?
7209                    }
7210                };
7211                let up = match dev {
7212                    Some(d) => e.qmatvec_view(&d.up, ex * u_len..(ex + 1) * u_len, &zt, 1,
7213                        m.up_exps.in_f, m.up_exps.out_f, m.up_exps.qtype, m.up_exps.row_bytes)?,
7214                    None => {
7215                        let su = su.as_mut().unwrap();
7216                        e.stage_expert(m.up_exps.expert_bytes(ex), su, 0)?;
7217                        e.qmatvec_view(su, 0..u_len, &zt, 1,
7218                            m.up_exps.in_f, m.up_exps.out_f, m.up_exps.qtype, m.up_exps.row_bytes)?
7219                    }
7220                };
7221                let mut act = e.uninit(n_ff_exp)?;
7222                e.gelu_tanh_mul(&gate, &up, &mut act, n_ff_exp)?;
7223                let actv = act.slice(0..n_ff_exp);
7224                let y = match dev {
7225                    Some(d) => e.qmatvec_view(&d.down, ex * d_len..(ex + 1) * d_len, &actv, 1,
7226                        m.down_exps.in_f, m.down_exps.out_f, m.down_exps.qtype, m.down_exps.row_bytes)?,
7227                    None => {
7228                        let sd = sd.as_mut().unwrap();
7229                        e.stage_expert(m.down_exps.expert_bytes(ex), sd, 0)?;
7230                        e.qmatvec_view(sd, 0..d_len, &actv, 1,
7231                            m.down_exps.in_f, m.down_exps.out_f, m.down_exps.qtype, m.down_exps.row_bytes)?
7232                    }
7233                };
7234                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
7235                e.axpy_into(&y, w[j], &mut dst, n_embd)?;
7236            }
7237        }
7238        Ok(moe_out)
7239    }
7240
7241    /// One gemma4 trunk layer (R8): x -> x_next.
7242    fn gemma4_layer(&self, e: &Engine, il: usize, layer: &crate::hybrid::HybridLayer,
7243                    x: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize)
7244                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7245        let n_embd = self.cfg.n_embd as usize;
7246        let eps = self.cfg.rms_eps;
7247
7248        let mut h = e.zeros(t * n_embd)?;
7249        e.rms_norm(x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7250        let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
7251        let o = self.gemma4_attn(e, fa, il, &h, pos_d, t)?;
7252        // gemma order: post_attention_norm applies to the ATTENTION OUTPUT, then the residual.
7253        let mut cur = e.zeros(t * n_embd)?;
7254        e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
7255        self.gemma4_layer_tail_add(e, layer, &cur, x, t)
7256    }
7257
7258    /// Everything after the attention output in a gemma4 layer: the residual add (cur + x ->
7259    /// attn_out) FUSED with the three attn_out norms, then shared FFN + router + MoE + combine +
7260    /// layer scale — shared verbatim by the prefill, decode and verify paths.
7261    fn gemma4_layer_tail_add(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7262                             cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize)
7263                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7264        Ok(self.gemma4_layer_tail_add_n(e, layer, cur, x, t, None)?.0)
7265    }
7266
7267    /// tail_add with the NEXT layer's attn_norm fused into the closing add+scale (one launch
7268    /// produces both x_next and h_next — the cross-layer fusion). `next_norm` None = last layer.
7269    fn gemma4_layer_tail_add_n(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7270                               cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize,
7271                               next_norm: Option<&CudaSlice<f32>>)
7272                               -> Result<(CudaSlice<f32>, Option<CudaSlice<f32>>), Box<dyn std::error::Error>> {
7273        let n_embd = self.cfg.n_embd as usize;
7274        let bits = layer.gemma4.as_ref().unwrap();
7275        let (sn, attn_out) = self.gemma4_layer_tail_core(e, layer, cur, x, t)?;
7276        let mut xn = e.uninit(t * n_embd)?;
7277        match next_norm {
7278            Some(w) => {
7279                let mut hn = e.uninit(t * n_embd)?;
7280                e.add_scale_rms_norm(&sn, &attn_out, bits.layer_scale, w, &mut xn, &mut hn,
7281                                     n_embd, t, self.cfg.rms_eps)?;
7282                Ok((xn, Some(hn)))
7283            }
7284            None => {
7285                e.add_scale(&sn, &attn_out, bits.layer_scale, &mut xn, t * n_embd)?;
7286                Ok((xn, None))
7287            }
7288        }
7289    }
7290
7291    /// Tail core: attn_out = cur+x (fused with the 3 norms), both FFN branches, the combine
7292    /// norm — returns (sn, attn_out) for the closing add+scale variants.
7293    fn gemma4_layer_tail_core(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7294                              cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize)
7295                              -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7296        self.gemma4_layer_tail_core_pn(e, layer, cur, x, t, None, false)
7297    }
7298
7299    /// tail_core with an optional PRE-NORM fold (glue-fusion lane): `pre_norm = Some(wa)`
7300    /// means `cur` is the RAW attention output and the dense entry runs
7301    /// rms(cur, wa) + residual-add + ffn_norm as ONE launch (E4B's post-attn norm fold).
7302    /// `defer_post_norm`: dense-arm exit returns RAW f0 (ffn_down output) instead of
7303    /// sn = rms(f0, post_ffw) — the caller fuses the post-norm into its residual emit
7304    /// (rms_pre_add_q8_1, E4B glue wave 5). MoE arm ignores it.
7305    fn gemma4_layer_tail_core_pn(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7306                                 cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize,
7307                                 pre_norm: Option<&CudaSlice<f32>>, defer_post_norm: bool)
7308                                 -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7309        let n_embd = self.cfg.n_embd as usize;
7310        let eps = self.cfg.rms_eps;
7311        let bits = layer.gemma4.as_ref().unwrap();
7312
7313        // DENSE gemma4 variants (31B/E4B — no MoE, no parallel branch): attn_out = cur + x
7314        // fused with the single ffn_norm; GELU_PAR ffn; post_ffw_norm.
7315        let Some(mbits) = bits.moe_bits.as_ref() else {
7316            let crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &layer.ffn
7317            else { panic!("gemma4 dense layer without Dense ffn") };
7318            let mut attn_out = e.uninit(t * n_embd)?;
7319            let mut zsh = e.uninit(t * n_embd)?;
7320            // wave-2: with the pre-norm fold active the entry ALSO emits zsh q8_1 — the
7321            // t=1 fused2 gate/up consume the pair with no standalone quantize launch.
7322            let mut zpair: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
7323            match pre_norm {
7324                Some(wa) if t == 1 => {
7325                    zpair = Some(e.rms_pre_add_rms_norm_q8z(cur, wa, x,
7326                                                            bits.ffn_norm.float_data(),
7327                                                            &mut attn_out, &mut zsh,
7328                                                            n_embd, t, eps)?);
7329                }
7330                Some(wa) => e.rms_pre_add_rms_norm(cur, wa, x, bits.ffn_norm.float_data(),
7331                                                   &mut attn_out, &mut zsh, n_embd, t, eps)?,
7332                None => e.add_rms_norm(cur, x, bits.ffn_norm.float_data(), &mut attn_out,
7333                                       &mut zsh, n_embd, t, eps)?,
7334            }
7335            let n_ff = ffn_gate.out_features();
7336            // FFN persistent slab (counter-barrier form) FALSIFIED here 2026-07-14
7337            // (falsification #7, jsonl row): PDL glue already hides the launch boundaries
7338            // it fused; barrier + worst-segment occupancy net −0.3% (31B depth) / −2.3%
7339            // (E4B spec). Down's act dependency is all-to-all, so sentinel sync cannot
7340            // rescue segment C — the megakernel front is closed for the dense tail.
7341            let (gate, up) = if t == 1 {
7342                let (zq, zd) = match zpair {
7343                    Some(p) => p,
7344                    None => e.quantize_q8_1(&zsh, 1, n_embd)?,
7345                };
7346                match e.matmul_q4_fused2(ffn_gate, ffn_up, &zq, &zd)? {
7347                    Some(p) => p,
7348                    None => (e.matmul_pre(ffn_gate, &zq, &zd, &zsh, 1)?,
7349                             e.matmul_pre(ffn_up, &zq, &zd, &zsh, 1)?),
7350                }
7351            } else {
7352                // BATCHED FUSED2 (DEFAULT ON 2026-07-13, MEMRA_F2B=0 seam): one segmented
7353                // launch for the verify's gate+up — the up segment's blocks fill SMs as
7354                // the gate segment drains (the launch-tail mechanism behind the b-tier
7355                // plateau; first positive after six falsified in-kernel variants).
7356                static F2B: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7357                let f2b = *F2B.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0"));
7358                let fused = if f2b {
7359                    let (zq, zd) = e.quantize_q8_1(&zsh, t, n_embd)?;
7360                    e.matmul_q4_fused2_batched(ffn_gate, ffn_up, &zq, &zd, t)?
7361                } else { None };
7362                match fused {
7363                    Some(p) => p,
7364                    None => {
7365                        // quantize-once window: gate/up share `zsh` (borrowed across the pair).
7366                        e.mmq_act_begin();
7367                        (e.matmul(ffn_gate, &zsh, t)?, e.matmul(ffn_up, &zsh, t)?)
7368                    }
7369                }
7370            };
7371            let mut act = e.uninit(t * n_ff)?;
7372            // act quantize folds into the GELU epilogue (bit-identical q8_1 rounding);
7373            // ffn_down rides matmul_pre — one quantize launch fewer per layer.
7374            let f0 = if e.uses_q8_1_fast(ffn_down) {
7375                let upv = e.view(&up, t * n_ff);
7376                let up_all = upv.slice(0..t * n_ff);
7377                let (aq, ad) = e.gelu_tanh_mul_q8_1(&gate, &up_all, &mut act, n_ff, t)?;
7378                e.matmul_pre(ffn_down, &aq, &ad, &act, t)?
7379            } else {
7380                e.gelu_tanh_mul(&gate, &up, &mut act, t * n_ff)?;
7381                e.matmul(ffn_down, &act, t)?
7382            };
7383            if defer_post_norm { return Ok((f0, attn_out)); }
7384            let mut sn = e.uninit(t * n_embd)?;
7385            e.rms_norm(&f0, bits.post_ffw_norm.float_data(), &mut sn, n_embd, t, eps)?;
7386            return Ok((sn, attn_out));
7387        };
7388
7389        assert!(pre_norm.is_none(), "pre-norm fold is dense-entry only");
7390        // MoE variant (26B): attn_out = cur + x fused with the three attn_out norms
7391        // (ffn_norm + router-scale + pre_ffw_norm_2): ONE launch, chains verbatim. At small t
7392        // (decode + verify) the zsh and moe_in outputs are EMITTED q8_1 (both consumers are
7393        // quantized matmuls — two quantize launches + two f32 round-trips fold away).
7394        let mut attn_out = e.uninit(t * n_embd)?;
7395        let mut router_in = e.uninit(t * n_embd)?;
7396        let fast_moe = match &layer.ffn {
7397            crate::hybrid::Ffn::Moe(m) => m.dev_exps.as_ref().is_some_and(|d| !d.gu_il)
7398                && expert_dp4a_supported(m.gate_exps.qtype)
7399                && expert_dp4a_supported(m.up_exps.qtype)
7400                && expert_dp4a_supported(m.down_exps.qtype)
7401                && std::env::var("MEMRA_GEMMA_MOE_FAST").as_deref() != Ok("0"),
7402            _ => false,
7403        };
7404        let q8z = t < PRIME_MIN_T && fast_moe;
7405        let (zsh_f32, zsh_q8, moe_q8) = if q8z {
7406            let (z0, m2) = e.add_rms_norm3_q8z(cur, x, bits.ffn_norm.float_data(),
7407                                               &mbits.router_scale_pre,
7408                                               mbits.pre_ffw_norm_2.float_data(),
7409                                               &mut attn_out, &mut router_in, n_embd, t, eps)?;
7410            (None, Some(z0), Some(m2))
7411        } else {
7412            let mut zsh = e.uninit(t * n_embd)?;
7413            let mut moe_in = e.uninit(t * n_embd)?;
7414            e.add_rms_norm3(cur, x, bits.ffn_norm.float_data(), &mbits.router_scale_pre,
7415                            mbits.pre_ffw_norm_2.float_data(), &mut attn_out, &mut zsh,
7416                            &mut router_in, &mut moe_in, n_embd, t, eps)?;
7417            (Some((zsh, moe_in)), None, None)
7418        };
7419        let attn_out2 = attn_out;
7420        #[allow(unused_variables)]
7421        let attn_out = &attn_out2;
7422        let n_ff = mbits.shared_gate.out_features();
7423        let (gate, up) = if let Some((zq, zd)) = zsh_q8.as_ref() {
7424            if t == 1 {
7425                match e.matmul_q4_fused2(&mbits.shared_gate, &mbits.shared_up, zq, zd)? {
7426                    Some(p) => p,
7427                    None => {
7428                        let h0 = e.zeros(0)?;
7429                        (e.matmul_pre(&mbits.shared_gate, zq, zd, &h0, 1)?,
7430                         e.matmul_pre(&mbits.shared_up, zq, zd, &h0, 1)?)
7431                    }
7432                }
7433            } else {
7434                // verify t 2..15: the batched mmvq twins consume the pre-quantized pair.
7435                let h0 = e.zeros(0)?;
7436                (e.matmul_pre(&mbits.shared_gate, zq, zd, &h0, t)?,
7437                 e.matmul_pre(&mbits.shared_up, zq, zd, &h0, t)?)
7438            }
7439        } else {
7440            let (zsh, _) = zsh_f32.as_ref().unwrap();
7441            (e.matmul(&mbits.shared_gate, zsh, t)?, e.matmul(&mbits.shared_up, zsh, t)?)
7442        };
7443        let mut act = e.uninit(t * n_ff)?;
7444        e.gelu_tanh_mul(&gate, &up, &mut act, t * n_ff)?;
7445        let mlp0 = e.matmul(&mbits.shared_down, &act, t)?;
7446        let crate::hybrid::Ffn::Moe(m) = &layer.ffn else { panic!("gemma4 layer not MoE") };
7447        let moe0 = match (&moe_q8, &zsh_f32) {
7448            (Some(mq), _) => self.gemma4_moe_q8(e, m, mbits, mq, &router_in, t)?,
7449            (None, Some((_, moe_in))) => self.gemma4_moe(e, m, mbits, moe_in, &router_in, t)?,
7450            _ => unreachable!(),
7451        };
7452        // post_ffw_norm_1(mlp0) + post_ffw_norm_2(moe0): one fused launch, per-row verbatim.
7453        let mut mlp = e.uninit(t * n_embd)?;
7454        let mut moe = e.uninit(t * n_embd)?;
7455        e.rms_norm2x(&mlp0, &moe0, mbits.post_ffw_norm_1.float_data(),
7456                     mbits.post_ffw_norm_2.float_data(), &mut mlp, &mut moe, n_embd, t, eps)?;
7457
7458        // combine: rms_norm(mlp + moe, post_ffw_norm) + attn_out, then the layer output scalar.
7459        // add+norm fused (add_rms_norm == add then rms_norm, kernel-check-pinned identity).
7460        let mut sum = e.uninit(t * n_embd)?;
7461        let mut sn = e.uninit(t * n_embd)?;
7462        e.add_rms_norm(&mlp, &moe, bits.post_ffw_norm.float_data(), &mut sum, &mut sn,
7463                       n_embd, t, eps)?;
7464        Ok((sn, attn_out2))
7465    }
7466
7467    /// tail_add with the next attn_norm emitted PRE-QUANTIZED q8_1 (decode/verify loops).
7468    fn gemma4_layer_tail_add_nq(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7469                                cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize,
7470                                next_norm: Option<&CudaSlice<f32>>)
7471                                -> Result<(CudaSlice<f32>, Option<(CudaSlice<i8>, CudaSlice<f32>)>), Box<dyn std::error::Error>> {
7472        let n_embd = self.cfg.n_embd as usize;
7473        let bits = layer.gemma4.as_ref().unwrap();
7474        let (sn, attn_out) = self.gemma4_layer_tail_core(e, layer, cur, x, t)?;
7475        let mut xn = e.uninit(t * n_embd)?;
7476        match next_norm {
7477            Some(w) => {
7478                let pair = e.add_scale_rms_norm_q8_1(&sn, &attn_out, bits.layer_scale, w, &mut xn,
7479                                                     n_embd, t, self.cfg.rms_eps)?;
7480                Ok((xn, Some(pair)))
7481            }
7482            None => {
7483                e.add_scale(&sn, &attn_out, bits.layer_scale, &mut xn, t * n_embd)?;
7484                Ok((xn, None))
7485            }
7486        }
7487    }
7488
7489    /// gemma4 prefill: `last_only` = forward_last semantics (lm_head on the final row only).
7490    /// R4: final logits softcapped 30*tanh(l/30) on host (monotonic — argmax unaffected).
7491    fn gemma4_forward(&self, e: &Engine, tokens: &[u32], last_only: bool)
7492                      -> Result<Vec<f32>, Box<dyn std::error::Error>> {
7493        // E4B routes to its own forward regardless of the caller's entry point (forward /
7494        // forward_last / prime paths all funnel here for gemma4).
7495        if self.is_gemma4_e4b() { return self.gemma4_e4b_forward(e, tokens, last_only); }
7496        let n_embd = self.cfg.n_embd as usize;
7497        let t = tokens.len();
7498        let pos: Vec<i32> = (0..t as i32).collect();
7499        let pos_d = e.htod_i32(&pos)?;
7500
7501        let mut x = self.embed(e, tokens)?;
7502        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
7503        // MEMRA_GEMMA_PROBE=1: per-layer trunk stats (host rms + max of the LAST token row) —
7504        // the bring-up bisect vs llama-eval-callback node stats.
7505        let probe = std::env::var("MEMRA_GEMMA_PROBE").is_ok();
7506        let stat = |e: &Engine, x: &CudaSlice<f32>, tag: &str| -> Result<(), Box<dyn std::error::Error>> {
7507            let h = e.dtoh(x)?;
7508            let bad = h.iter().filter(|v| !v.is_finite()).count();
7509            let mx = h.iter().filter(|v| v.is_finite()).fold(0.0f32, |m, v| m.max(v.abs()));
7510            eprintln!("[gemma-probe] {tag}: tok0_first3={:?} bad={bad} max={mx:.3e}", &h[..3]);
7511            Ok(())
7512        };
7513        if probe { stat(e, &x, "embed")?; }
7514        for (il, layer) in self.layers.iter().enumerate() {
7515            x = self.gemma4_layer(e, il, layer, &x, &pos_d, t)?;
7516            if probe { stat(e, &x, &format!("L{il}"))?; }
7517        }
7518        let mut hn = e.zeros(t * n_embd)?;
7519        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, self.cfg.rms_eps)?;
7520        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
7521        let n_vocab = self.output.out_features();
7522        let logits = if last_only {
7523            let hv = e.view(&hn, t * n_embd);
7524            let last_row = hv.slice((t - 1) * n_embd..t * n_embd);
7525            let mut hlast = e.zeros(n_embd)?;
7526            e.copy_view_into(&mut hlast, 0, &last_row, n_embd)?;
7527            let mut ld = e.matmul(&self.output, &hlast, 1)?;
7528            e.softcap(&mut ld, cap, n_vocab)?;
7529            self.gemma4_suppress(e, &mut ld, 1)?;
7530            e.dtoh(&ld)?
7531        } else {
7532            let mut ld = e.matmul(&self.output, &hn, t)?;
7533            e.softcap(&mut ld, cap, t * n_vocab)?;
7534            self.gemma4_suppress(e, &mut ld, t)?;
7535            e.dtoh(&ld)?
7536        };
7537        Ok(logits)
7538    }
7539
7540    /// gemma4 BATCHED PROMPT PRIME v0 (fresh cache only): the prefill graph over the whole
7541    /// prompt with each layer's post-rope K / weightless-normed V appended into the quantized
7542    /// KV cache (decode-append row math). Returns (last-row softcapped logits, h_seed = last
7543    /// pre-output_norm hidden, hiddens = full pre-output_norm stack [T, n_embd]).
7544    pub(crate) fn gemma4_prime(&self, e: &Engine, tokens: &[u32], cache: &mut Cache)
7545                               -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7546        // Err, not assert (2026-08-07, lane/gemma4-serve-gaps): a served gemma4 prompt longer
7547        // than the worker's prefill tick used to chunk here, and chunk 2 (pos > 0) killed the
7548        // whole worker process on this line. The worker now primes gemma4 monolithically and
7549        // routes continuation suffixes tokenwise; this is the per-request backstop.
7550        if cache.pos != 0 {
7551            return Err("gemma4 prime v0 is fresh-prompt only (no continuation/chunked prime) \
7552                        — prime the full prompt in one call or decode tokenwise".into());
7553        }
7554        let n_embd = self.cfg.n_embd as usize;
7555        let eps = self.cfg.rms_eps;
7556        let t = tokens.len();
7557        let pos: Vec<i32> = (0..t as i32).collect();
7558        let pos_d = e.htod_i32(&pos)?;
7559        let mut x = self.embed(e, tokens)?;
7560        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
7561        for (il, layer) in self.layers.iter().enumerate() {
7562            let mut h = e.zeros(t * n_embd)?;
7563            e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7564            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer not full-attn") };
7565            let o = self.gemma4_attn_prime(e, fa, il, &h, &pos_d, t, Some(cache))?;
7566            let mut cur = e.zeros(t * n_embd)?;
7567            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
7568            x = self.gemma4_layer_tail_add(e, layer, &cur, &x, t)?;
7569            self.dflash_tap(e, cache, il, &x, t)?;
7570        }
7571        cache.pos += t;
7572        let hiddens = e.clone_dtod(&x)?;
7573        let xv = e.view(&x, t * n_embd);
7574        let last_row = xv.slice((t - 1) * n_embd..t * n_embd);
7575        let mut h_seed = e.zeros(n_embd)?;
7576        e.copy_view_into(&mut h_seed, 0, &last_row, n_embd)?;
7577        let mut hn = e.uninit(n_embd)?;
7578        e.rms_norm(&h_seed, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
7579        let mut ld = e.matmul(&self.output, &hn, 1)?;
7580        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
7581        e.softcap(&mut ld, cap, self.output.out_features())?;
7582        self.gemma4_suppress(e, &mut ld, 1)?;
7583        let logits = e.dtoh(&ld)?;
7584        Ok((logits, h_seed, hiddens))
7585    }
7586
7587    /// gemma4 T=1 decode attention: per-layer geometry, quantized-KV append + fa_decode
7588    /// (vec kernels at hd 256, generic scalar at the globals' hd 512), weightless V-norm,
7589    /// dual rope, scale 1.0. Takes the attn-normed input PRE-QUANTIZED (the cross-layer
7590    /// fused norm emits q8 directly — the f32 h never materializes).
7591    fn gemma4_decode_attn(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
7592                          hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
7593                          pos_d: &CudaSlice<i32>, cache: &mut Cache)
7594                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7595        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
7596        let eps = self.cfg.rms_eps;
7597        let aux = self.gemma4_aux.as_ref().unwrap();
7598        let ones = aux.ones(e);
7599        #[cfg(debug_assertions)]
7600        crate::debug_assert_tensor_stream_device(ones, &e.stream(),
7601                                                   "gemma4_decode_attn.ones");
7602        let (hq, hdq) = (hq, hdq);
7603        let h0 = e.zeros(0)?;
7604        let h = &h0;
7605        let (q0, k0, v0) = if swa {
7606            match e.matmul_q4_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
7607                Some(t3) => t3,
7608                None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
7609                         e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
7610                         e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?),
7611            }
7612        } else {
7613            let (q0, k0) = match e.matmul_q4_fused2(&fa.wq, &fa.wk, &hq, &hdq)? {
7614                Some(p) => p,
7615                None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
7616                         e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?),
7617            };
7618            let v0 = e.clone_dtod(&k0)?;
7619            (q0, k0, v0)
7620        };
7621        let mut q = e.uninit(nh * hd)?;
7622        let mut k = e.uninit(nkv * hd)?;
7623        let mut v = e.uninit(nkv * hd)?;
7624        // E4B wave-3 fold, m=1 completion (2026-07-23): the rows arms took this fold at
7625        // 550fcfa5; the decode-step trio kept 2 launches/layer it doesn't need.
7626        let ff = if swa { None } else {
7627            Some(aux.rope_freqs(e).expect("gemma4 global rope needs rope_freqs.weight"))
7628        };
7629        #[cfg(debug_assertions)]
7630        if let Some(ff) = ff {
7631            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
7632                                                       "gemma4_decode_attn.rope_freqs");
7633        }
7634        e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
7635                            ones, &mut q, &mut k, &mut v, hd, nh, nkv,
7636                            pos_d, nh, nkv, base, 1.0, ff, eps)?;
7637        let kvl = cache.kv[il].as_mut().unwrap();
7638        e.append_kv_quantized(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len,
7639                              kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes, (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on()))?;
7640        kvl.len += 1;
7641        // R6 decode: SWA layers attend only the last `sliding_window` keys — a token-aligned
7642        // VIEW OFFSET into the quantized cache (keys carry absolute rope; the mask is purely
7643        // positional). Globals attend the full history.
7644        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
7645        let mut attn = e.uninit(nh * hd)?;
7646        // global layers: SAME hd512 rows twin as verify with t=1 (parity law).
7647        if !swa && hd == 512 && kvl.len >= crate::fa512_min_tkv()
7648            && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
7649            let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
7650            let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
7651            // device-len: eager syncs the counter (async arg-store), dc keeps it live.
7652            let base = kvl.len as i32;
7653            e.i32_set_k(&mut kvl.len_d, base)?;
7654            e.fa_decode_rows(&q, &kp, &vp, &mut attn, hd, nh, nkv, kvl.len - 1, 1, scale,
7655                             kvl.k_tok_bytes, kvl.v_tok_bytes, Some((&kvl.len_d, -1)), false,
7656                             false, None)?;
7657            return Ok(e.matmul(&fa.wo, &attn, 1)?);
7658        }
7659        // windowed regime: SAME rows_w kernel as verify with t=1 (parity law — see verify_attn).
7660        if swa && kvl.len > win && hd == 256
7661            && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
7662            let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
7663            let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
7664            let base = kvl.len as i32;
7665            e.i32_set_k(&mut kvl.len_d, base)?;
7666            e.fa_decode_rows_w(&q, &kp, &vp, &mut attn, hd, nh, nkv, &kvl.len_d, -1, 1, scale,
7667                               win, kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
7668            return Ok(e.matmul(&fa.wo, &attn, 1)?);
7669        }
7670        let (off_tok, t_kv) = if swa && kvl.len > win { (kvl.len - win, win) } else { (0, kvl.len) };
7671        let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
7672                                     (off_tok + t_kv) * kvl.k_tok_bytes);
7673        let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
7674                                     (off_tok + t_kv) * kvl.v_tok_bytes);
7675        e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
7676                    kvl.k_tok_bytes, kvl.v_tok_bytes, swa && crate::Engine::wkv_on())?;
7677        Ok(e.matmul(&fa.wo, &attn, 1)?)
7678    }
7679
7680    /// gemma4 DEVICE-COUNTER decode step (graph arc): token id + rope pos + KV lengths live in
7681    /// device counters; ZERO varying host kernel args. `cap_bucket_max` = Some(bucket) for graph
7682    /// capture (host mirrors untouched, n_splits from bucket, full-buffer KV views) / None for
7683    /// the eager-dc gate path (host mirrors advanced, live geometry — bit-identical target =
7684    /// gemma4_decode_step_h's token stream). V1 scope: t_kv <= sliding_window (no window views
7685    /// in-graph; the driver gates).
7686    #[allow(clippy::too_many_arguments)]
7687    pub fn gemma4_decode_step_dc(&self, e: &Engine, token_d: &CudaSlice<u32>,
7688                                 pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
7689                                 embd_qt: i32, embd_rb: usize, cache: &mut Cache,
7690                                 n_vocab: usize, cap_bucket_max: Option<(usize, usize)>)
7691                                 -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
7692        let mut tok_out = e.stream().alloc_zeros::<u32>(1)?;
7693        self.gemma4_decode_step_dc_into(e, token_d, pos_d, embd_gpu, embd_qt, embd_rb, cache,
7694                                        n_vocab, cap_bucket_max, &mut tok_out)?;
7695        Ok(tok_out)
7696    }
7697
7698    /// CAPTURE body: argmax lands in the PERSISTENT `tok_out` (same buffer = same address on
7699    /// every replay; pass `token_d` itself for the self-feeding graph loop).
7700    #[allow(clippy::too_many_arguments)]
7701    pub fn gemma4_decode_step_dc_into(&self, e: &Engine, token_d: &CudaSlice<u32>,
7702                                      pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
7703                                      embd_qt: i32, embd_rb: usize, cache: &mut Cache,
7704                                      n_vocab: usize, cap_bucket_max: Option<(usize, usize)>,
7705                                      tok_out: &mut CudaSlice<u32>)
7706                                      -> Result<(), Box<dyn std::error::Error>> {
7707        let n_embd = self.cfg.n_embd as usize;
7708        let eps = self.cfg.rms_eps;
7709        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_rb)?;
7710        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
7711        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
7712        let n_layers = self.layers.len();
7713        for (il, layer) in self.layers.iter().enumerate() {
7714            let (hq, hdq) = match h_carry.take() {
7715                Some(p) => p,
7716                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, 1, eps)?,
7717            };
7718            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
7719            let o = self.gemma4_decode_attn_dc(e, fa, il, &hq, &hdq, pos_d, cache, cap_bucket_max)?;
7720            let mut cur = e.uninit(n_embd)?;
7721            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, 1, eps)?;
7722            let next_norm = if il + 1 < n_layers {
7723                Some(self.layers[il + 1].attn_norm.float_data())
7724            } else { None };
7725            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, 1, next_norm)?;
7726            x = xn;
7727            h_carry = hn;
7728        }
7729        let mut hn = e.uninit(n_embd)?;
7730        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
7731        let mut logits = e.matmul(&self.output, &hn, 1)?;
7732        self.gemma4_suppress(e, &mut logits, 1)?;   // cap skipped (monotonic); the mask is not
7733        e.argmax_token_device_into(&logits, tok_out, n_vocab)?;
7734        e.inc_seqlen(pos_d)?;
7735        if cap_bucket_max.is_none() { cache.pos += 1; }
7736        Ok(())
7737    }
7738
7739    /// Persistent transient slots for the ALLOC-FREE captured dc step (the graph door):
7740    /// every buffer the step produces per token lives here, allocated ONCE pre-capture, so
7741    /// the captured graph carries zero cuMemAllocAsync/Free nodes (the 226us/launch tax,
7742    /// osrt 2026-07-23). Sized for the model's max per-layer shapes.
7743
7744    /// Build the slot set (call OUTSIDE any capture).
7745    pub fn g4_dc_slots(&self, e: &Engine) -> Result<G4DcSlots, Box<dyn std::error::Error>> {
7746        let n_embd = self.cfg.n_embd as usize;
7747        let n_vocab = self.output.out_features();
7748        let n_layers = self.layers.len();
7749        let (mut qmax, mut kvmax, mut ffmax) = (0usize, 0usize, 0usize);
7750        for il in 0..n_layers {
7751            let (hd, nkv, nh, _b, _s, _w) = self.gemma4_geom(il);
7752            qmax = qmax.max(nh * hd);
7753            kvmax = kvmax.max(nkv * hd);
7754            if let crate::hybrid::Ffn::Dense { ffn_gate, .. } = &self.layers[il].ffn {
7755                ffmax = ffmax.max(ffn_gate.out_features());
7756            }
7757        }
7758        Ok(G4DcSlots {
7759            x: e.uninit(n_embd)?, xn: e.uninit(n_embd)?, cur: e.uninit(n_embd)?,
7760            hq: e.alloc_i8_uninit(n_embd)?, hd_: e.uninit(n_embd / 32)?,
7761            q0: e.uninit(qmax)?, k0: e.uninit(kvmax)?, v0: e.uninit(kvmax)?,
7762            q: e.uninit(qmax)?, k: e.uninit(kvmax)?, v: e.uninit(kvmax)?,
7763            attn: e.uninit(qmax)?, o: e.uninit(n_embd)?,
7764            attn_out: e.uninit(n_embd)?, zsh: e.uninit(n_embd)?,
7765            // zq/zd feed the wo matvec (nh*hd rows — 4096 on hd512 globals > n_embd),
7766            // the ffn entry (n_embd) and the lm_head (n_embd): size for the max.
7767            zq: e.alloc_i8_uninit(n_embd.max(qmax))?, zd: e.uninit(n_embd.max(qmax) / 32)?,
7768            gate: e.uninit(ffmax)?, up: e.uninit(ffmax)?,
7769            act: e.uninit(ffmax)?, actq: e.alloc_i8_uninit(ffmax)?, actd: e.uninit(ffmax / 32)?,
7770            f0: e.uninit(n_embd)?, sn: e.uninit(n_embd)?,
7771            hn: e.uninit(n_embd)?, logits: e.uninit(n_vocab)?,
7772        })
7773    }
7774
7775    /// m=1 pre-quantized matvec into a slot — mirrors matmul_pre's m=1 mmvq route exactly
7776    /// (rp4-mirror bytes; mmvq_supports guaranteed for gemma4 q4_0/q6_K).
7777    fn g4_matvec_m1_into(&self, e: &Engine, w: &crate::model::GpuTensor,
7778                         aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, y: &mut CudaSlice<f32>)
7779                         -> Result<(), Box<dyn std::error::Error>> {
7780        use crate::model::GpuTensor;
7781        let (bytes, qtype, row_bytes, scale, rp) = match w {
7782            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } =>
7783                (bytes, *qtype, *row_bytes, *scale, *rp),
7784            _ => return Err("g4_matvec_m1_into: non-quant tensor".into()),
7785        };
7786        let (mbytes, mrp) = match w {
7787            GpuTensor::Quant { rp4: Some(m4), .. } => (m4, true),
7788            _ => (bytes, rp),
7789        };
7790        e.qmatvec_mmvq_into(mbytes, aq, ad, 1, w.in_features(), w.out_features(),
7791                            qtype, row_bytes, scale, mrp, y)
7792    }
7793
7794    /// ALLOC-FREE dc step (capture body): kernel-for-kernel mirror of
7795    /// `gemma4_decode_step_dc_into` at t=1 with every transient slot-fed. Dense gemma4 only
7796    /// (12B/31B; uniform q4_0 trunk guarantees the fused2/3 arms).
7797    #[allow(clippy::too_many_arguments)]
7798    pub fn gemma4_decode_step_dc_slotted(&self, e: &Engine, token_d: &CudaSlice<u32>,
7799                                         pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
7800                                         embd_qt: i32, embd_rb: usize, cache: &mut Cache,
7801                                         n_vocab: usize, cap_bucket_max: Option<(usize, usize)>,
7802                                         sl: &mut G4DcSlots, tok_out: &mut CudaSlice<u32>,
7803                                         ring: Option<(&mut CudaSlice<u32>, usize)>)
7804                                         -> Result<(), Box<dyn std::error::Error>> {
7805        let n_embd = self.cfg.n_embd as usize;
7806        let eps = self.cfg.rms_eps;
7807        e.embed_gather_device_into(embd_gpu, token_d, &mut sl.x, n_embd, embd_qt, embd_rb)?;
7808        e.scale_inplace(&mut sl.x, (n_embd as f32).sqrt(), n_embd)?;
7809        let n_layers = self.layers.len();
7810        let mut has_carry = false;
7811        for il in 0..n_layers {
7812            if !has_carry {
7813                e.rms_norm_q8_1_into(&sl.x, self.layers[il].attn_norm.float_data(), n_embd, 1,
7814                                     eps, &mut sl.hq, &mut sl.hd_)?;
7815            }
7816            has_carry = true;
7817            let layer = &self.layers[il];
7818            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
7819            self.gemma4_decode_attn_dc_slotted(e, fa, il, pos_d, cache, cap_bucket_max, sl)?;
7820            e.rms_norm(&sl.o, layer.post_attn_norm.float_data(), &mut sl.cur, n_embd, 1, eps)?;
7821            let next_norm = if il + 1 < n_layers {
7822                Some(self.layers[il + 1].attn_norm.float_data())
7823            } else { None };
7824            self.gemma4_layer_tail_slotted(e, layer, next_norm, sl)?;
7825            std::mem::swap(&mut sl.x, &mut sl.xn);
7826        }
7827        e.rms_norm(&sl.x, self.output_norm.float_data(), &mut sl.hn, n_embd, 1, eps)?;
7828        e.quantize_q8_1_into(&sl.hn, 1, n_embd, &mut sl.zq, &mut sl.zd)?;
7829        // lm_head via the same m=1 mmvq route as matmul (q6_K on the gemma4 family).
7830        {
7831            let (zq, zd) = (&sl.zq, &sl.zd);
7832            let zq = unsafe { &*(zq as *const CudaSlice<i8>) };
7833            let zd = unsafe { &*(zd as *const CudaSlice<f32>) };
7834            self.g4_matvec_m1_into(e, &self.output, zq, zd, &mut sl.logits)?;
7835        }
7836        self.gemma4_suppress(e, &mut sl.logits, 1)?;
7837        e.argmax_token_device_into(&sl.logits, tok_out, n_vocab)?;
7838        if let Some((ring, base)) = ring {
7839            // in-graph token parking: slot = (pos - base) % ring.len(); the door drains
7840            // with ONE sync per chunk instead of a per-token dtoh (the launch-serialization
7841            // fix — llama's 885us/launch overlaps GPU work because nothing waits per token).
7842            e.plain_tok_ring(tok_out, pos_d, base, ring)?;
7843        }
7844        e.inc_seqlen(pos_d)?;
7845        if cap_bucket_max.is_none() { cache.pos += 1; }
7846        Ok(())
7847    }
7848
7849    /// Slot-fed dc attention: mirrors gemma4_decode_attn_dc's CAPTURE arm kernel-for-kernel.
7850    #[allow(clippy::too_many_arguments)]
7851    fn gemma4_decode_attn_dc_slotted(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer,
7852                                     il: usize, pos_d: &CudaSlice<i32>, cache: &mut Cache,
7853                                     cap_bucket_max: Option<(usize, usize)>, sl: &mut G4DcSlots)
7854                                     -> Result<(), Box<dyn std::error::Error>> {
7855        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
7856        let eps = self.cfg.rms_eps;
7857        let aux = self.gemma4_aux.as_ref().unwrap();
7858        let ones = aux.ones(e);
7859        #[cfg(debug_assertions)]
7860        crate::debug_assert_tensor_stream_device(ones, &e.stream(),
7861                                                   "gemma4_decode_attn_dc_slotted.ones");
7862        {
7863            let hq = unsafe { &*(&sl.hq as *const CudaSlice<i8>) };
7864            let hdq = unsafe { &*(&sl.hd_ as *const CudaSlice<f32>) };
7865            if swa {
7866                if !e.matmul_q4_fused3_into(&fa.wq, &fa.wk, &fa.wv, hq, hdq,
7867                                            &mut sl.q0, &mut sl.k0, &mut sl.v0)? {
7868                    return Err("slotted step: fused3 unavailable (non-uniform trunk)".into());
7869                }
7870            } else {
7871                if !e.matmul_q4_fused2_into(&fa.wq, &fa.wk, hq, hdq, &mut sl.q0, &mut sl.k0)? {
7872                    return Err("slotted step: fused2 unavailable".into());
7873                }
7874                let k0r = unsafe { &*(&sl.k0 as *const CudaSlice<f32>) };
7875                e.copy_into(&mut sl.v0, 0, k0r, nkv * hd)?;
7876            }
7877        }
7878        // E4B wave-3 fold, m=1 completion (2026-07-23) — MUST mirror the dc_into arm
7879        // kernel-for-kernel (graph stream-identity gate).
7880        let ff = if swa { None } else {
7881            Some(aux.rope_freqs(e).expect("gemma4 global rope needs rope_freqs.weight"))
7882        };
7883        #[cfg(debug_assertions)]
7884        if let Some(ff) = ff {
7885            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
7886                                                       "gemma4_decode_attn_dc_slotted.rope_freqs");
7887        }
7888        let kvl = cache.kv[il].as_mut().unwrap();
7889        let kv_fp8 = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
7890        if crate::Engine::qkv_append_on() {
7891            // append fold (2026-07-23): mirrors dc_into.
7892            e.rms_norm_qkv_rope_append_dc(&sl.q0, &sl.k0, &sl.v0, fa.q_norm.float_data(),
7893                fa.k_norm.float_data(), ones, &mut sl.q, &mut sl.k, &mut sl.v, hd, nh, nkv,
7894                pos_d, nh, nkv, base, 1.0, ff, eps,
7895                &mut kvl.k, &mut kvl.v, &kvl.len_d, kvl.k_tok_bytes, kvl.v_tok_bytes, kv_fp8)?;
7896        } else {
7897            e.rms_norm_qkv_rope(&sl.q0, &sl.k0, &sl.v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
7898                                ones, &mut sl.q, &mut sl.k, &mut sl.v, hd, nh, nkv,
7899                                pos_d, nh, nkv, base, 1.0, ff, eps)?;
7900            e.append_kv_quantized_dc(&sl.k, &sl.v, &mut kvl.k, &mut kvl.v, &kvl.len_d,
7901                                     kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
7902                                     kv_fp8)?;
7903        }
7904        e.inc_seqlen(&mut kvl.len_d)?;
7905        let (b_swa, b_glob) = cap_bucket_max.expect("slotted step is capture-only");
7906        let k_view = e.view_u8(&kvl.k, kvl.k.len());
7907        let v_view = e.view_u8(&kvl.v, kvl.v.len());
7908        let rows_on = std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0");
7909        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
7910        // combine-q8 emit (wave-5b m=1 port): the rows arms quantize inside the combine —
7911        // the standalone quantize launch runs only on the non-rows fallback. MUST mirror
7912        // the dc_into arm branch-for-branch (stream gate).
7913        let mut fa_q8 = false;
7914        if !swa && hd == 512 && b_glob >= crate::fa512_min_tkv() && rows_on {
7915            e.fa_decode_rows(&sl.q, &k_view, &v_view, &mut sl.attn, hd, nh, nkv, b_glob - 1,
7916                             1, scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
7917                             Some((&kvl.len_d, -1)), false, false,
7918                             Some((&mut sl.zq, &mut sl.zd)))?;
7919            fa_q8 = true;
7920        } else if swa && b_swa > win && hd == 256 && rows_on {
7921            e.fa_decode_rows_w(&sl.q, &k_view, &v_view, &mut sl.attn, hd, nh, nkv,
7922                               &kvl.len_d, -1, 1, scale, win,
7923                               kvl.k_tok_bytes, kvl.v_tok_bytes,
7924                               Some((&mut sl.zq, &mut sl.zd)))?;
7925            fa_q8 = true;
7926        } else {
7927            let b = if swa { b_swa } else { b_glob };
7928            e.fa_decode_dc(&sl.q, &k_view, &v_view, &mut sl.attn, hd, nh, nkv, &kvl.len_d, b,
7929                           scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
7930                           swa && crate::Engine::wkv_on())?;
7931        }
7932        if !fa_q8 {
7933            let aq = unsafe { &*(&sl.attn as *const CudaSlice<f32>) };
7934            e.quantize_q8_1_into(aq, 1, nh * hd, &mut sl.zq, &mut sl.zd)?;
7935        }
7936        {
7937            let zq = unsafe { &*(&sl.zq as *const CudaSlice<i8>) };
7938            let zd = unsafe { &*(&sl.zd as *const CudaSlice<f32>) };
7939            self.g4_matvec_m1_into(e, &fa.wo, zq, zd, &mut sl.o)?;
7940        }
7941        Ok(())
7942    }
7943
7944    /// Slot-fed dense layer tail: mirrors gemma4_layer_tail_core (t=1, no pre-norm fold) +
7945    /// tail_add_nq kernel-for-kernel; the next layer's (hq, hd_) carry lands in the slots.
7946    fn gemma4_layer_tail_slotted(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7947                                 next_norm: Option<&CudaSlice<f32>>, sl: &mut G4DcSlots)
7948                                 -> Result<(), Box<dyn std::error::Error>> {
7949        let n_embd = self.cfg.n_embd as usize;
7950        let eps = self.cfg.rms_eps;
7951        let bits = layer.gemma4.as_ref().unwrap();
7952        let crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &layer.ffn
7953        else { return Err("slotted tail: dense ffn only".into()) };
7954        e.add_rms_norm(&sl.cur, &sl.x, bits.ffn_norm.float_data(), &mut sl.attn_out,
7955                       &mut sl.zsh, n_embd, 1, eps)?;
7956        let n_ff = ffn_gate.out_features();
7957        {
7958            let zshr = unsafe { &*(&sl.zsh as *const CudaSlice<f32>) };
7959            e.quantize_q8_1_into(zshr, 1, n_embd, &mut sl.zq, &mut sl.zd)?;
7960        }
7961        {
7962            let zq = unsafe { &*(&sl.zq as *const CudaSlice<i8>) };
7963            let zd = unsafe { &*(&sl.zd as *const CudaSlice<f32>) };
7964            if !e.matmul_q4_fused2_into(ffn_gate, ffn_up, zq, zd, &mut sl.gate, &mut sl.up)? {
7965                return Err("slotted tail: ffn fused2 unavailable".into());
7966            }
7967        }
7968        debug_assert!(e.uses_q8_1_fast(ffn_down));
7969        {
7970            let upr = unsafe { &*(&sl.up as *const CudaSlice<f32>) };
7971            let upv = e.view(upr, n_ff);
7972            let up_all = upv.slice(0..n_ff);
7973            let gr = unsafe { &*(&sl.gate as *const CudaSlice<f32>) };
7974            e.gelu_tanh_mul_q8_1_into(gr, &up_all, &mut sl.act, n_ff, 1,
7975                                      &mut sl.actq, &mut sl.actd)?;
7976        }
7977        {
7978            let aq = unsafe { &*(&sl.actq as *const CudaSlice<i8>) };
7979            let ad = unsafe { &*(&sl.actd as *const CudaSlice<f32>) };
7980            self.g4_matvec_m1_into(e, ffn_down, aq, ad, &mut sl.f0)?;
7981        }
7982        e.rms_norm(&sl.f0, bits.post_ffw_norm.float_data(), &mut sl.sn, n_embd, 1, eps)?;
7983        match next_norm {
7984            Some(w) => {
7985                e.add_scale_rms_norm_q8_1_into(&sl.sn, &sl.attn_out, bits.layer_scale, w,
7986                                               &mut sl.xn, n_embd, 1, eps,
7987                                               &mut sl.hq, &mut sl.hd_)?;
7988            }
7989            None => {
7990                e.add_scale(&sl.sn, &sl.attn_out, bits.layer_scale, &mut sl.xn, n_embd)?;
7991            }
7992        }
7993        Ok(())
7994    }
7995
7996    /// dc attention: same math as gemma4_decode_attn, KV slot/lengths from device counters.
7997    #[allow(clippy::too_many_arguments)]
7998    fn gemma4_decode_attn_dc(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
7999                             hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
8000                             pos_d: &CudaSlice<i32>, cache: &mut Cache,
8001                             cap_bucket_max: Option<(usize, usize)>)
8002                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8003        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
8004        let eps = self.cfg.rms_eps;
8005        let aux = self.gemma4_aux.as_ref().unwrap();
8006        let ones = aux.ones(e);
8007        #[cfg(debug_assertions)]
8008        crate::debug_assert_tensor_stream_device(ones, &e.stream(),
8009                                                   "gemma4_decode_attn_dc.ones");
8010        let (q0, k0, v0) = if swa {
8011            match e.matmul_q4_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hdq)? {
8012                Some(t3) => t3,
8013                None => {
8014                    let h0 = e.zeros(0)?;
8015                    (e.matmul_pre(&fa.wq, hq, hdq, &h0, 1)?,
8016                     e.matmul_pre(&fa.wk, hq, hdq, &h0, 1)?,
8017                     e.matmul_pre(&fa.wv, hq, hdq, &h0, 1)?)
8018                }
8019            }
8020        } else {
8021            let (q0, k0) = match e.matmul_q4_fused2(&fa.wq, &fa.wk, hq, hdq)? {
8022                Some(p) => p,
8023                None => {
8024                    let h0 = e.zeros(0)?;
8025                    (e.matmul_pre(&fa.wq, hq, hdq, &h0, 1)?,
8026                     e.matmul_pre(&fa.wk, hq, hdq, &h0, 1)?)
8027                }
8028            };
8029            let v0 = e.clone_dtod(&k0)?;
8030            (q0, k0, v0)
8031        };
8032        let mut q = e.uninit(nh * hd)?;
8033        let mut k = e.uninit(nkv * hd)?;
8034        let mut v = e.uninit(nkv * hd)?;
8035        // E4B wave-3 fold, m=1 completion (2026-07-23): mirrored by the slotted arm.
8036        let ff = if swa { None } else {
8037            Some(aux.rope_freqs(e).expect("gemma4 global rope needs rope_freqs.weight"))
8038        };
8039        #[cfg(debug_assertions)]
8040        if let Some(ff) = ff {
8041            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
8042                                                       "gemma4_decode_attn_dc.rope_freqs");
8043        }
8044        let kvl = cache.kv[il].as_mut().unwrap();
8045        let kv_fp8 = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
8046        if crate::Engine::qkv_append_on() {
8047            // append fold (2026-07-23): norm+rope+cache-append in ONE launch.
8048            e.rms_norm_qkv_rope_append_dc(&q0, &k0, &v0, fa.q_norm.float_data(),
8049                fa.k_norm.float_data(), ones, &mut q, &mut k, &mut v, hd, nh, nkv,
8050                pos_d, nh, nkv, base, 1.0, ff, eps,
8051                &mut kvl.k, &mut kvl.v, &kvl.len_d, kvl.k_tok_bytes, kvl.v_tok_bytes, kv_fp8)?;
8052        } else {
8053            e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
8054                                ones, &mut q, &mut k, &mut v, hd, nh, nkv,
8055                                pos_d, nh, nkv, base, 1.0, ff, eps)?;
8056            e.append_kv_quantized_dc(&k, &v, &mut kvl.k, &mut kvl.v, &kvl.len_d,
8057                                     kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes, kv_fp8)?;
8058        }
8059        e.inc_seqlen(&mut kvl.len_d)?;
8060        let mut attn = e.uninit(nh * hd)?;
8061        // combine-q8 emit carrier (wave-5b m=1 port): rows arms fill this; the tail then
8062        // rides g4_matvec_m1_into instead of matmul's internal quantize.
8063        let mut fa_q8: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8064        // Weight prefetch NOT wired here (26B/31B/qwen probes 2026-07-13: 26B flat
8065        // 196.6/196.0 vs 196.4/196.1 — MoE ffn dilutes wo; 31B −0.2% — dense decode sits
8066        // at the DRAM wall, no idle window to front-load into). E4B keeps the arm
8067        // (gemma4_e4b_attn, +0.65% valid window).
8068        match cap_bucket_max {
8069            None => {
8070                // dc-EAGER: host knows the length — R6 window views EXACTLY like the eager
8071                // decode (SWA layers attend the last `sliding_window` keys); the device
8072                // counters carry only the append slot + the graph seam.
8073                kvl.len += 1;
8074                let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
8075                if !swa && hd == 512 && kvl.len >= crate::fa512_min_tkv()
8076                    && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8077                    // global layers: SAME hd512 rows twin as verify, t=1 (parity law).
8078                    // dc: len_d is live (inc_seqlen) — device-len rides it, plus=-1.
8079                    let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
8080                    let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
8081                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
8082                    e.fa_decode_rows(&q, &kp, &vp, &mut attn, hd, nh, nkv, kvl.len - 1, 1,
8083                                     scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
8084                                     Some((&kvl.len_d, -1)), false, false,
8085                                     Some((&mut aq8, &mut ad8)))?;
8086                    fa_q8 = Some((aq8, ad8));
8087                } else if swa && kvl.len > win && hd == 256
8088                    && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8089                    // windowed regime: SAME rows_w kernel as verify, t=1 (parity law).
8090                    let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
8091                    let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
8092                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
8093                    e.fa_decode_rows_w(&q, &kp, &vp, &mut attn, hd, nh, nkv, &kvl.len_d, -1,
8094                                       1, scale, win, kvl.k_tok_bytes, kvl.v_tok_bytes,
8095                                       Some((&mut aq8, &mut ad8)))?;
8096                    fa_q8 = Some((aq8, ad8));
8097                } else {
8098                    let (off_tok, t_kv) = if swa && kvl.len > win { (kvl.len - win, win) }
8099                                          else { (0, kvl.len) };
8100                    let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
8101                                                 (off_tok + t_kv) * kvl.k_tok_bytes);
8102                    let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
8103                                                 (off_tok + t_kv) * kvl.v_tok_bytes);
8104                    e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
8105                                kvl.k_tok_bytes, kvl.v_tok_bytes, swa && crate::Engine::wkv_on())?;
8106                }
8107            }
8108            Some((b_swa, b_glob)) => {
8109                // capture: full-buffer views + device length. PARITY LAW port (graph arc step
8110                // 3): the SAME regime branches as dc-eager, pinned per arm — b_swa is the
8111                // exact-key t_kv for the dc family (n_splits constant per bucket), b_glob is
8112                // the RUNG max for the rows family (kernels derive per-replay splits from
8113                // kvl.len_d; grid/partials sized for the rung end, excess splits exit).
8114                let k_view = e.view_u8(&kvl.k, kvl.k.len());
8115                let v_view = e.view_u8(&kvl.v, kvl.v.len());
8116                let rows_on = std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0");
8117                let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
8118                if !swa && hd == 512 && b_glob >= crate::fa512_min_tkv() && rows_on {
8119                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
8120                    e.fa_decode_rows(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, b_glob - 1,
8121                                     1, scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
8122                                     Some((&kvl.len_d, -1)), false, false,
8123                                     Some((&mut aq8, &mut ad8)))?;
8124                    fa_q8 = Some((aq8, ad8));
8125                } else if swa && b_swa > win && hd == 256 && rows_on {
8126                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
8127                    e.fa_decode_rows_w(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8128                                       &kvl.len_d, -1, 1, scale, win,
8129                                       kvl.k_tok_bytes, kvl.v_tok_bytes,
8130                                       Some((&mut aq8, &mut ad8)))?;
8131                    fa_q8 = Some((aq8, ad8));
8132                } else {
8133                    let b = if swa { b_swa } else { b_glob };
8134                    e.fa_decode_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, &kvl.len_d, b,
8135                                   scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
8136                                   swa && crate::Engine::wkv_on())?;
8137                }
8138            }
8139        }
8140        // combine-q8 emit (wave-5b m=1 port): the rows arms produced the wo activation pair
8141        // in-combine — ride the slotted arm's exact matvec route (parity by construction).
8142        if let Some((aq8, ad8)) = fa_q8 {
8143            let mut y = e.uninit(fa.wo.out_features())?;
8144            self.g4_matvec_m1_into(e, &fa.wo, &aq8, &ad8, &mut y)?;
8145            return Ok(y);
8146        }
8147        Ok(e.matmul(&fa.wo, &attn, 1)?)
8148    }
8149
8150    /// gemma4 GRAPH-REPLAY greedy loop: per (swa-key, global-key) fa bucket, capture ONE full
8151    /// dc step (self-feeding: argmax writes token_d in-graph) and replay it — one graph launch
8152    /// per token, one 4B dtoh. V1 scope: whole generation under the sliding window (no window
8153    /// views in-graph); caller gates and falls back to the dc-eager loop.
8154    pub fn gemma4_generate_graph(&self, e: &Engine, prompt_pos: usize, first_token: u32,
8155                                 cache: &mut Cache, max_new: usize, eos: &[u32],
8156                                 mut on_token: impl FnMut(u32) -> bool)
8157                                 -> Result<(Vec<u32>, crate::decode::StopReason), Box<dyn std::error::Error>> {
8158        if self.is_gemma4_e4b() {
8159            return Err("E4B graph serving is unwired (HANDOVER-E4B.md) — dc-eager is the serving arm".into());
8160        }
8161        use crate::decode::StopReason;
8162        let n_vocab = self.output.out_features();
8163        let n_embd = self.cfg.n_embd as usize;
8164        let embd_gpu = self.embd_gpu.get_or_init(|| {
8165            e.upload_u8(&self.embd.raw).expect("embed table upload")
8166        });
8167        let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
8168        for kvl in cache.kv.iter_mut().flatten() {
8169            e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
8170        }
8171        let mut token_d = e.stream().clone_htod(&[first_token])?;
8172        let mut pos_d = e.htod_i32(&[prompt_pos as i32])?;
8173        let g4 = self.cfg.gemma4.as_ref().unwrap();
8174        let (hd_s, hd_g) = (g4.key_length_swa as usize, g4.key_length_global as usize);
8175        // per-layer nkv: swa vs global counts from the pattern (uniform within class).
8176        let nkv_s = g4.head_count_kv.iter().zip(g4.swa_pattern.iter())
8177            .find(|p| *p.1).map(|p| *p.0 as usize).unwrap_or(8);
8178        let nkv_g = g4.head_count_kv.iter().zip(g4.swa_pattern.iter())
8179            .find(|p| !*p.1).map(|p| *p.0 as usize).unwrap_or(2);
8180        let mut graphs: std::collections::HashMap<((bool, usize), (bool, usize), bool, bool),
8181                                                  (cudarc::driver::CudaGraph,
8182                                                   Vec<Box<dyn std::any::Any + Send>>)> = Default::default();
8183        // ALLOC-FREE capture: persistent transient slots — the captured graph carries zero
8184        // mem nodes (the 226us/launch tax). Slots must outlive every cached graph.
8185        let mut slots = self.g4_dc_slots(e)?;
8186        // Chunked replay ring: tokens park on-device; ONE drain sync per chunk. ring_base is
8187        // baked at the door entry (the modulo keeps every capture valid indefinitely).
8188        const RING: usize = 64;
8189        // DRAIN pinned at 1 (2026-07-23): relaunching the SAME graph exec before its prior
8190        // launch completes is ILLEGAL (chunk=4 -> ILLEGAL_ADDRESS; chunk=1 clean). Pipelining
8191        // needs alternating exec instances — and the measured payoff was ~0 (the ~200us
8192        // cuGraphLaunch host cost already overlaps its own launch's GPU work; llama pays
8193        // 885us/launch the same way). MEMRA_GRAPH_DRAIN raises it only for experiments.
8194        const DRAIN: usize = 1;
8195        let mut ring = e.stream().alloc_zeros::<u32>(RING)?;
8196        let ring_base = prompt_pos;
8197        let mut out = Vec::with_capacity(max_new);
8198        let mut reason = StopReason::MaxNew;
8199        let mut next = first_token;
8200        let mut captures = 0usize;
8201        for _ in 0..max_new {
8202            out.push(next);
8203            if eos.contains(&next) { reason = StopReason::Eos; break; }
8204            if !on_token(next) { reason = StopReason::Callback; break; }
8205            let t_kv = cache.pos + 1;
8206            // Bucket key per ARM (graph arc step 3):
8207            //  - swa component: dc family under the window (exact (fa_vec, n_splits) key —
8208            //    n_splits must be constant per bucket); rows_w above it (window-constant, so
8209            //    the component collapses to a single marker).
8210            //  - global component: dc family under the fa512 floor (exact key); rows_dpl16
8211            //    at/above it — the kernel derives splits from len_d per replay, so buckets
8212            //    are power-of-2 RUNGS (one capture per doubling; grid sized for the rung end).
8213            let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
8214            let f512 = crate::fa512_min_tkv();
8215            let key_s = if t_kv > win { (true, usize::MAX) }
8216                        else { e.fa_bucket_key(t_kv, hd_s, nkv_s, crate::Engine::wkv_on()) };
8217            let (key_g, rung_end) = if t_kv >= f512 {
8218                // strict upper bound: the rung must ROLL at exact powers (t_kv==1024 starts
8219                // the [1024,2048) bucket) — sizing covers every replayed T_kv < end.
8220                let end = (t_kv + 1).next_power_of_two().max(f512 * 2);
8221                ((true, end), end)
8222            } else { (e.fa_bucket_key(t_kv, hd_g, nkv_g, false), t_kv) };
8223            let key = (key_s, key_g, t_kv >= f512, t_kv > win);
8224            if !graphs.contains_key(&key) {
8225                let bucket_max = (t_kv, rung_end);
8226                // snapshot device+host state (the 3 capture-warmup runs leave no residue).
8227                let snap = cache.snapshot(e)?;
8228                let pos_save = e.dtoh_i32_one(&pos_d)?;
8229                let len_save: Vec<Option<i32>> = cache.kv.iter()
8230                    .map(|k| k.as_ref().map(|kvl| e.dtoh_i32_one(&kvl.len_d).unwrap())).collect();
8231                let tok_save = e.dtoh_u32_one(&token_d)?;
8232                // RETAINED capture (2026-07-23): the plain capture_graph left pool-transient
8233                // clones as dead COPY NODES replayed every launch — the E4B 0.74ms/token
8234                // regression class, and this door's measured -8.8%. The keeper pins warmup
8235                // transients so the captured graph holds kernel nodes only.
8236                let graph = {
8237                    let tok_ref = &mut token_d;
8238                    let pos_ref = &mut pos_d;
8239                    let cache_ref = &mut *cache;
8240                    let slots_ref = &mut slots;
8241                    let ring_ref = &mut ring;
8242                    e.capture_graph_retained_flags(
8243                        cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY,
8244                        |e| {
8245                        // self-feeding: the argmax writes token_d itself.
8246                        let tok_in = unsafe { &*(tok_ref as *const CudaSlice<u32>) };
8247                        let sl = unsafe { &mut *(slots_ref as *mut G4DcSlots) };
8248                        let rg = unsafe { &mut *(ring_ref as *mut CudaSlice<u32>) };
8249                        self.gemma4_decode_step_dc_slotted(e, tok_in, pos_ref, embd_gpu, qt, rb,
8250                                                           cache_ref, n_vocab, Some(bucket_max),
8251                                                           sl, tok_ref, Some((rg, ring_base)))
8252                    })?
8253                };
8254                cache.rollback(e, &snap, 0)?;
8255                e.set_i32_one(&mut pos_d, pos_save)?;
8256                for (il, ls) in len_save.iter().enumerate() {
8257                    if let (Some(kvl), Some(v)) = (cache.kv[il].as_mut(), ls) {
8258                        e.set_i32_one(&mut kvl.len_d, *v)?;
8259                    }
8260                }
8261                e.set_u32_one(&mut token_d, tok_save)?;
8262                if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
8263                    if let Ok(c) = crate::graph_update::node_census(&graph.0) {
8264                        eprintln!("[graph-census] {c:?}");
8265                    }
8266                }
8267                graphs.insert(key, graph);
8268                captures += 1;
8269            }
8270            // CHUNKED REPLAY: enqueue up to DRAIN launches back-to-back (the ~200us host
8271            // cost of each cuGraphLaunch overlaps the PREVIOUS launch's ~11ms GPU work),
8272            // then ONE sync + ring drain. The chunk must stay inside this bucket key and
8273            // the budget; capture warmups already emitted their tokens through the ring.
8274            let mut chunk = 1usize;
8275            let drain_cap: usize = std::env::var("MEMRA_GRAPH_DRAIN").ok()
8276                .and_then(|v| v.parse().ok()).unwrap_or(DRAIN);
8277            while chunk < drain_cap && out.len() + chunk < max_new {
8278                let t_next = cache.pos + 1 + chunk;
8279                let key_s2 = if t_next > win { (true, usize::MAX) }
8280                             else { e.fa_bucket_key(t_next, hd_s, nkv_s, crate::Engine::wkv_on()) };
8281                let key_g2 = if t_next >= f512 {
8282                    (true, (t_next + 1).next_power_of_two().max(f512 * 2))
8283                } else { e.fa_bucket_key(t_next, hd_g, nkv_g, false) };
8284                if (key_s2, key_g2, t_next >= f512, t_next > win) != key { break; }
8285                chunk += 1;
8286            }
8287            let g = &graphs.get(&key).unwrap().0;
8288            for _ in 0..chunk { g.launch()?; }
8289            e.stream().synchronize()?;
8290            let ringh = e.dtoh_u32(&ring)?;
8291            for j in 0..chunk {
8292                let pos_j = cache.pos + j;
8293                let tok_j = ringh[(pos_j - ring_base) % RING];
8294                cache.pos += 0; // advanced below in one shot
8295                if j + 1 == chunk { next = tok_j; }
8296                else {
8297                    out.push(tok_j);
8298                    if eos.contains(&tok_j) || !on_token(tok_j) {
8299                        reason = if eos.contains(&tok_j) { StopReason::Eos }
8300                                 else { StopReason::Callback };
8301                        // roll device/host state back to the stop point.
8302                        let keep = cache.pos + j + 1;
8303                        e.set_i32_one(&mut pos_d, keep as i32)?;
8304                        for kvl in cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
8305                            e.set_i32_one(&mut kvl.len_d, keep as i32)?;
8306                            kvl.len = keep;
8307                        }
8308                        cache.pos = keep;
8309                        if std::env::var("MEMRA_GRAPH_STATS").is_ok() {
8310                            eprintln!("[gemma-graph] captures={captures} buckets={}", graphs.len());
8311                        }
8312                        return Ok((out, reason));
8313                    }
8314                }
8315            }
8316            cache.pos += chunk;
8317            for kvl in cache.kv.iter_mut().filter_map(|k| k.as_mut()) { kvl.len += chunk; }
8318        }
8319        if std::env::var("MEMRA_GRAPH_STATS").is_ok() {
8320            eprintln!("[gemma-graph] captures={captures} buckets={}", graphs.len());
8321        }
8322        Ok((out, reason))
8323    }
8324
8325    /// gemma4 VERIFY step (spec decode): t tokens batched through the trunk at positions
8326    /// pos0..pos0+t-1, K/V rows appended to the quantized cache (caller rolls back rejected
8327    /// rows via kvl.len), per-token causal windowed attend (fa_decode per token — the same
8328    /// kernel family as T=1 decode at each token's t_kv). Returns [t, n_vocab] softcapped
8329    /// logits (host) + advances cache.pos by t.
8330    pub(crate) fn gemma4_decode_step_t(&self, e: &Engine, tokens: &[u32], pos0: usize,
8331                                       cache: &mut Cache)
8332                                       -> Result<Vec<f32>, Box<dyn std::error::Error>> {
8333        Ok(self.gemma4_decode_step_t_h(e, tokens, pos0, cache)?.0)
8334    }
8335
8336    /// GREEDY verify: per-row DEVICE argmax (t x 4B host traffic instead of the t x 1MB logits
8337    /// stack — softcap skipped: tanh is monotonic, per-row argmax unaffected). Returns
8338    /// (argmax ids [t], post-output_norm hidden stack [t, n_embd]).
8339    pub(crate) fn gemma4_decode_step_t_am(&self, e: &Engine, tokens: &[u32], pos0: usize,
8340                                          cache: &mut Cache)
8341                                          -> Result<(Vec<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8342        let (ld, hn) = self.gemma4_verify_trunk(e, tokens, pos0, cache, None)?;
8343        let t = tokens.len();
8344        let n_vocab = self.output.out_features();
8345        let mut toks = e.stream().alloc_zeros::<u32>(t)?;
8346        for i in 0..t {
8347            e.argmax_token_device_col(&ld, i, n_vocab, &mut toks, i)?;
8348        }
8349        Ok((e.dtoh_u32(&toks)?, hn))
8350    }
8351
8352    /// Device-token verify (async spec round): tokens live in tok_d[0..t]; per-row argmax
8353    /// lands in a DEVICE buffer (no host logits). Returns (vam_d [t] u32 device, hn stack).
8354    pub(crate) fn gemma4_decode_step_t_am_dev(&self, e: &Engine, tok_d: &CudaSlice<u32>, t: usize,
8355                                              pos0: usize, cache: &mut Cache)
8356                                              -> Result<(CudaSlice<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8357        let (ld, hn) = self.gemma4_verify_trunk(e, &vec![0u32; t], pos0, cache, Some(tok_d))?;
8358        let n_vocab = self.output.out_features();
8359        let mut vam = e.stream().alloc_zeros::<u32>(t)?;
8360        for i in 0..t {
8361            e.argmax_token_device_col(&ld, i, n_vocab, &mut vam, i)?;
8362        }
8363        Ok((vam, hn))
8364    }
8365
8366    /// gemma4 verify + the POST-output_norm hidden stack [t, n_embd] (the drafter's h input —
8367    /// llama's h_nextn convention).
8368    pub(crate) fn gemma4_decode_step_t_h(&self, e: &Engine, tokens: &[u32], pos0: usize,
8369                                         cache: &mut Cache)
8370                                         -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8371        let (mut ld, hn) = self.gemma4_verify_trunk(e, tokens, pos0, cache, None)?;
8372        let t = tokens.len();
8373        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
8374        e.softcap(&mut ld, cap, t * self.output.out_features())?;
8375        Ok((e.dtoh(&ld)?, hn))
8376    }
8377
8378    /// Persistent device scratch for the BURST verify stream (one per generation): rope pos
8379    /// rows [cap] + per-row t_kv counters (device-filled from the round counter, zero H2D).
8380    pub(crate) fn verify_stream_scratch(&self, e: &Engine, cap: usize)
8381                                        -> Result<VerifyStreamScratch, Box<dyn std::error::Error>> {
8382        Ok(VerifyStreamScratch {
8383            pos_d: e.htod_i32(&vec![0i32; cap])?,
8384            row_ctrs: (0..cap).map(|_| e.htod_i32(&[0])).collect::<Result<_, _>>()?,
8385        })
8386    }
8387
8388    /// BURST verify trunk (device-slot twin): tokens from a device buffer, rope positions
8389    /// iota'd from `ctr`, appends/attention at the layers' len_d counters (verify_attn_stream),
8390    /// NO host cache.pos/len advance. Returns (per-row device argmaxes [t], post-norm hidden
8391    /// stack [t, n_embd]) — the burst's accept/seed inputs, zero host readbacks.
8392    /// `scr` = PERSISTENT per-gen scratch (pos rows + per-row t_kv counters): the first cut
8393    /// htod_i32-allocated these per call — 9 pageable H2D copies per round, each a stream
8394    /// sync, exactly the turnaround the burst exists to remove.
8395    pub(crate) fn gemma4_verify_t_am_stream(&self, e: &Engine, tok_d: &CudaSlice<u32>, t: usize,
8396                                            ctr: &CudaSlice<i32>, hint: usize,
8397                                            cache: &mut Cache,
8398                                            scr: &mut VerifyStreamScratch)
8399                                            -> Result<(CudaSlice<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8400        let n_embd = self.cfg.n_embd as usize;
8401        let eps = self.cfg.rms_eps;
8402        assert!(t <= scr.row_ctrs.len() && t <= 64);
8403        e.i32_iota_from(ctr, &mut scr.pos_d, t)?;
8404        for i in 0..t {
8405            e.i32_copy_add(ctr, &mut scr.row_ctrs[i], (i + 1) as i32)?;
8406        }
8407        let (pos_d, row_ctrs) = (&scr.pos_d, &scr.row_ctrs);
8408        let embd_gpu = self.embd_gpu.get_or_init(|| {
8409            e.upload_u8(&self.embd.raw).expect("embed table upload")
8410        });
8411        let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
8412        let mut x = e.embed_gather_device_td(embd_gpu, tok_d, t, n_embd, qt, rb)?;
8413        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
8414        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8415        let n_layers = self.layers.len();
8416        for (il, layer) in self.layers.iter().enumerate() {
8417            let (hq, hdq) = match h_carry.take() {
8418                Some(p) => p,
8419                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, t, eps)?,
8420            };
8421            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8422            let o = self.gemma4_verify_attn_stream(e, fa, il, &hq, &hdq, pos_d, t, cache,
8423                                                    hint, row_ctrs)?;
8424            let mut cur = e.uninit(t * n_embd)?;
8425            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
8426            let next_norm = if il + 1 < n_layers {
8427                Some(self.layers[il + 1].attn_norm.float_data())
8428            } else { None };
8429            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, t, next_norm)?;
8430            x = xn;
8431            h_carry = hn;
8432            self.dflash_tap(e, cache, il, &x, t)?;
8433        }
8434        let mut hn = e.uninit(t * n_embd)?;
8435        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
8436        let ld = e.matmul(&self.output, &hn, t)?;
8437        let n_vocab = self.output.out_features();
8438        let mut vam = e.stream().alloc_zeros::<u32>(t)?;
8439        for i in 0..t {
8440            e.argmax_token_device_col(&ld, i, n_vocab, &mut vam, i)?;
8441        }
8442        Ok((vam, hn))
8443    }
8444
8445    /// Verify trunk core: returns (UN-softcapped logits device [t, n_vocab], post-output_norm
8446    /// hidden stack [t, n_embd]); appends KV rows + advances cache.pos.
8447    /// DFlash tap write (dflash lane): copy the post-layer residual rows of `x` into the
8448    /// armed sink at the tap slot for `il` (row-major [t, n_taps*hidden]). Per-row D2D
8449    /// copies — t <= block_size on verify; prime pays t*n_taps once per prompt (dedicated
8450    /// kernel later if it shows in the profile).
8451    fn dflash_tap(&self, e: &Engine, cache: &mut Cache, il: usize, x: &CudaSlice<f32>, t: usize)
8452                  -> Result<(), Box<dyn std::error::Error>> {
8453        let Some(taps) = cache.dflash_taps.as_mut() else { return Ok(()) };
8454        let Some(slot) = taps.layer_ids.iter().position(|&l| l == il) else { return Ok(()) };
8455        let h = taps.hidden;
8456        let n_taps = taps.layer_ids.len();
8457        debug_assert_eq!(taps.t, t);
8458        let xv = e.view(x, t * h);
8459        for r in 0..t {
8460            let row = xv.slice(r * h..(r + 1) * h);
8461            e.copy_view_into(&mut taps.buf, r * n_taps * h + slot * h, &row, h)?;
8462        }
8463        Ok(())
8464    }
8465
8466    fn gemma4_verify_trunk(&self, e: &Engine, tokens: &[u32], pos0: usize, cache: &mut Cache,
8467                           tok_dev: Option<&CudaSlice<u32>>)
8468                           -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8469        let n_embd = self.cfg.n_embd as usize;
8470        let eps = self.cfg.rms_eps;
8471        let t = tokens.len();
8472        let pos: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
8473        let pos_d = e.htod_i32(&pos)?;
8474        let mut x = match tok_dev {
8475            Some(td) => {
8476                let embd_gpu = self.embd_gpu.get_or_init(|| {
8477                    e.upload_u8(&self.embd.raw).expect("embed table upload")
8478                });
8479                let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
8480                e.embed_gather_device_td(embd_gpu, td, t, n_embd, qt, rb)?
8481            }
8482            None => e.htod(&self.embd.gather(n_embd, tokens))?,
8483        };
8484        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
8485        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8486        let n_layers = self.layers.len();
8487        for (il, layer) in self.layers.iter().enumerate() {
8488            let (hq, hdq) = match h_carry.take() {
8489                Some(p) => p,
8490                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, t, eps)?,
8491            };
8492            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8493            let o = self.gemma4_verify_attn(e, fa, il, &hq, &hdq, &pos_d, t, cache)?;
8494            let mut cur = e.uninit(t * n_embd)?;
8495            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
8496            let next_norm = if il + 1 < n_layers {
8497                Some(self.layers[il + 1].attn_norm.float_data())
8498            } else { None };
8499            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, t, next_norm)?;
8500            x = xn;
8501            h_carry = hn;
8502            self.dflash_tap(e, cache, il, &x, t)?;
8503        }
8504        let mut hn = e.uninit(t * n_embd)?;
8505        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
8506        let mut ld = e.matmul(&self.output, &hn, t)?;
8507        self.gemma4_suppress(e, &mut ld, t)?;   // before the per-row argmax consumers
8508        cache.pos += t;
8509        Ok((ld, hn))
8510    }
8511
8512    /// Verify attention: project/norm/rope t rows, append them to the cache, then attend each
8513    /// row causally over [win_off_i .. base+i] via the SAME fa_decode dispatch as T=1 decode.
8514    /// BURST verify attention (device-slot twin of `gemma4_verify_attn`): the append lands
8515    /// at the layer's len_d counter (rows_dc), attention bases ride the counter (rows /
8516    /// rows_w with base_dev), and NO host len is read or bumped — `hint` is a host UPPER
8517    /// bound on base_len used only for split sizing and arm gating (the burst loop passes
8518    /// pos0 + burst slack). Host len mirrors re-sync at the burst drain.
8519    #[allow(clippy::too_many_arguments)]
8520    fn gemma4_verify_attn_stream(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
8521                                 hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
8522                                 pos_d: &CudaSlice<i32>, t: usize,
8523                                 cache: &mut Cache, hint: usize,
8524                                 row_ctrs: &[CudaSlice<i32>])
8525                                 -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8526        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
8527        let eps = self.cfg.rms_eps;
8528        let aux = self.gemma4_aux.as_ref().unwrap();
8529        let ones = aux.ones(e);
8530        #[cfg(debug_assertions)]
8531        crate::debug_assert_tensor_stream_device(ones, &e.stream(),
8532                                                   "gemma4_verify_attn_stream.ones");
8533        let h0 = e.zeros(0)?;
8534        let h = &h0;
8535        // BATCHED FUSED qkv (MEMRA_F2B=1, megakernel microcosm): swa layers fuse all three,
8536        // globals fuse q,k (v := k clone). Bit-identical per row; segments tail-fill.
8537        static F2B_QKV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8538        let f2b = *F2B_QKV.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0"));
8539        let fused_qkv = if f2b {
8540            if swa {
8541                e.matmul_q4_fused3_batched(&fa.wq, &fa.wk, &fa.wv, hq, hdq, t)?
8542                    .map(|(a, b, c)| (a, b, Some(c)))
8543            } else {
8544                e.matmul_q4_fused2_batched(&fa.wq, &fa.wk, hq, hdq, t)?
8545                    .map(|(a, b)| (a, b, None))
8546            }
8547        } else { None };
8548        let (q0, k0, v0) = match fused_qkv {
8549            Some((a, b, cv)) => {
8550                let v = match cv { Some(c) => c, None => e.clone_dtod(&b)? };
8551                (a, b, v)
8552            }
8553            None => {
8554                let q0 = e.matmul_pre(&fa.wq, hq, hdq, h, t)?;
8555                let k0 = e.matmul_pre(&fa.wk, hq, hdq, h, t)?;
8556                let v0 = if swa { e.matmul_pre(&fa.wv, hq, hdq, h, t)? }
8557                         else { e.clone_dtod(&k0)? };
8558                (q0, k0, v0)
8559            }
8560        };
8561        let mut q = e.uninit(t * nh * hd)?;
8562        let mut k = e.uninit(t * nkv * hd)?;
8563        let mut v = e.uninit(t * nkv * hd)?;
8564        // E4B wave-3 fold (2026-07-23 decode-dust port): q/k/v norms + q/k rope in ONE
8565        // launch — rope math verbatim on the normed rows; V ones-rms, never roped.
8566        let ff = if swa { None } else {
8567            Some(aux.rope_freqs(e).expect("gemma4 global rope needs rope_freqs.weight"))
8568        };
8569        #[cfg(debug_assertions)]
8570        if let Some(ff) = ff {
8571            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
8572                                                       "gemma4_verify_attn_stream.rope_freqs");
8573        }
8574        e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
8575                            ones, &mut q, &mut k, &mut v, hd, nh * t, nkv * t,
8576                            pos_d, nh, nkv, base, 1.0, ff, eps)?;
8577        let kvl = cache.kv[il].as_mut().unwrap();
8578        // append at the DEVICE slot; the counter advances by t on-device.
8579        e.append_kv_quantized_rows_dc(&k, &v, &mut kvl.k, &mut kvl.v, &kvl.len_d, t,
8580                                      kvl.kv_dim_k, kvl.kv_dim_v,
8581                                      kvl.k_tok_bytes, kvl.v_tok_bytes,
8582                                      (!swa && crate::Engine::gkv_on())
8583                                          || (swa && crate::Engine::wkv_on()))?;
8584        // len_d is NOT advanced here: the burst's device rollback (spec_rollback_stream) is
8585        // the sole len writer after this round's attention (base stays = old len, plus = 0).
8586        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
8587        let mut attn = e.uninit(t * nh * hd)?;
8588        let k_view = e.view_u8(&kvl.k, kvl.k.len());
8589        let v_view = e.view_u8(&kvl.v, kvl.v.len());
8590        // arm gating on the host HINT (upper bound; burst entry guards hint >= the vec floor
8591        // and a stable window regime — the same rung/regime keys as the draft graph).
8592        if swa && hint + 1 >= win {
8593            // fully-windowed rows: per-row window geometry from the counter (plus = 0: len_d
8594            // still holds the pre-append len; row r's T_kv = ctr + r + 1).
8595            e.fa_decode_rows_w(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8596                               &kvl.len_d, 0, t, scale, win,
8597                               kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
8598        } else if hd == 512 && hint + t < crate::fa512_min_tkv() {
8599            // globals UNDER the fa512 crossover: eager runs the per-row fa_decode_kvmod
8600            // fallback there (parity with t=1 decode) — mirror it with per-row fa_decode_dc
8601            // (bit-correct for any t_kv <= bucket; the drafter dc arc proved the pairing).
8602            // Burst entry gates the horizon onto one side of the crossover, so hint decides
8603            // for every row.
8604            // NO .max(512): fa_decode_dc gates its hd512 dpl16-vs-scalar pick on bucket_max
8605            // (mirroring eager's fa512 floor) — forcing 512 here flipped the arm to dpl16
8606            // while eager ran scalar (il=5 KV drift, the burst's 4/128). SAME LAW capped
8607            // from above (2026-07-13): a regime-pinned hint near the floor (round-graph
8608            // captures use f512-1) pow2-rounds PAST it — clamp under the floor, or the arm
8609            // re-flips to dpl16 (the round-graph 4/64). The scalar unified self-splits, so
8610            // any bucket >= the live length is exact.
8611            let bucket = (hint + t + 2).next_power_of_two()
8612                .min(crate::fa512_min_tkv().saturating_sub(1));
8613            let qv = e.view(&q, t * nh * hd);
8614            for i in 0..t {
8615                let q_row = qv.slice(i * nh * hd..(i + 1) * nh * hd);
8616                let mut q_one = e.uninit(nh * hd)?;
8617                e.copy_view_into(&mut q_one, 0, &q_row, nh * hd)?;
8618                let mut a_one = e.uninit(nh * hd)?;
8619                e.fa_decode_dc(&q_one, &k_view, &v_view, &mut a_one, hd, nh, nkv,
8620                               &row_ctrs[i], bucket, scale,
8621                               kvl.k_tok_bytes, kvl.v_tok_bytes, false)?;
8622                e.copy_into(&mut attn, i * nh * hd, &a_one, nh * hd)?;
8623            }
8624        } else if hd == 512 {
8625            // globals past the crossover: dpl16 dc twin via the shared rows wrapper (hint
8626            // sizes splits — upper bound; splits beyond the device len exit in-kernel).
8627            e.fa_decode_rows(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, hint, t, scale,
8628                             kvl.k_tok_bytes, kvl.v_tok_bytes,
8629                             Some((&kvl.len_d, 0)), false, false, None)?;
8630        } else {
8631            // hd256 under-window: v4 device-len rows twin.
8632            e.fa_decode_rows_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8633                                &kvl.len_d, hint + t, t, scale,
8634                                kvl.k_tok_bytes, kvl.v_tok_bytes, 0,
8635                                swa && crate::Engine::wkv_on())?;
8636        }
8637        Ok(e.matmul(&fa.wo, &attn, t)?)
8638    }
8639
8640    fn gemma4_verify_attn(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
8641                          hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
8642                          pos_d: &CudaSlice<i32>, t: usize,
8643                          cache: &mut Cache)
8644                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8645        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
8646        let eps = self.cfg.rms_eps;
8647        let aux = self.gemma4_aux.as_ref().unwrap();
8648        let ones = aux.ones(e);
8649        #[cfg(debug_assertions)]
8650        crate::debug_assert_tensor_stream_device(ones, &e.stream(),
8651                                                   "gemma4_verify_attn.ones");
8652        let n_embd = self.cfg.n_embd as usize;
8653        let _ = n_embd;
8654
8655        let h0 = e.zeros(0)?;
8656        let h = &h0;
8657        // BATCHED FUSED qkv (MEMRA_F2B=1, megakernel microcosm): swa layers fuse all three,
8658        // globals fuse q,k (v := k clone). Bit-identical per row; segments tail-fill.
8659        static F2B_QKV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8660        let f2b = *F2B_QKV.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0"));
8661        let fused_qkv = if f2b {
8662            if swa {
8663                e.matmul_q4_fused3_batched(&fa.wq, &fa.wk, &fa.wv, hq, hdq, t)?
8664                    .map(|(a, b, c)| (a, b, Some(c)))
8665            } else {
8666                e.matmul_q4_fused2_batched(&fa.wq, &fa.wk, hq, hdq, t)?
8667                    .map(|(a, b)| (a, b, None))
8668            }
8669        } else { None };
8670        let (q0, k0, v0) = match fused_qkv {
8671            Some((a, b, cv)) => {
8672                let v = match cv { Some(c) => c, None => e.clone_dtod(&b)? };
8673                (a, b, v)
8674            }
8675            None => {
8676                let q0 = e.matmul_pre(&fa.wq, hq, hdq, h, t)?;
8677                let k0 = e.matmul_pre(&fa.wk, hq, hdq, h, t)?;
8678                let v0 = if swa { e.matmul_pre(&fa.wv, hq, hdq, h, t)? }
8679                         else { e.clone_dtod(&k0)? };
8680                (q0, k0, v0)
8681            }
8682        };
8683        let mut q = e.uninit(t * nh * hd)?;
8684        let mut k = e.uninit(t * nkv * hd)?;
8685        let mut v = e.uninit(t * nkv * hd)?;
8686        // E4B wave-3 fold (2026-07-23 decode-dust port): q/k/v norms + q/k rope in ONE
8687        // launch — rope math verbatim on the normed rows; V ones-rms, never roped.
8688        let ff = if swa { None } else {
8689            Some(aux.rope_freqs(e).expect("gemma4 global rope needs rope_freqs.weight"))
8690        };
8691        #[cfg(debug_assertions)]
8692        if let Some(ff) = ff {
8693            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
8694                                                       "gemma4_verify_attn.rope_freqs");
8695        }
8696        e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
8697                            ones, &mut q, &mut k, &mut v, hd, nh * t, nkv * t,
8698                            pos_d, nh, nkv, base, 1.0, ff, eps)?;
8699        let kvl = cache.kv[il].as_mut().unwrap();
8700        let base_len = kvl.len;
8701        e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, base_len, t,
8702                                   kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes, (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on()))?;
8703        kvl.len += t;
8704        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
8705        let mut attn = e.uninit(t * nh * hd)?;
8706        // ROWS twin when no window offset is in play (globals are hd512-ineligible; SWA rows
8707        // under the window need no offset): ONE launch, per-row causal == the per-token loop.
8708        let rows_ok = (hd == 256 && base_len + 1 >= crate::fa_vec_min_tkv())
8709            // gemma globals: hd512 rows twin in the dpl16 vec regime (row 0 gates the batch);
8710            // decode rides the SAME symbol at t=1 (parity law).
8711            || (hd == 512 && !swa && base_len + 1 >= crate::fa512_min_tkv());
8712        if rows_ok && (!swa || base_len + t <= win) {
8713            let k_view = e.view_u8(&kvl.k, (base_len + t) * kvl.k_tok_bytes);
8714            let v_view = e.view_u8(&kvl.v, (base_len + t) * kvl.v_tok_bytes);
8715            if hd == 512 {
8716                // device-len twin: sync the counter to the verify base (async arg-store).
8717                e.i32_set_k(&mut kvl.len_d, base_len as i32)?;
8718                e.fa_decode_rows(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, base_len, t,
8719                                 scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
8720                                 Some((&kvl.len_d, 0)), false,
8721                                 swa && crate::Engine::wkv_on(), None)?;
8722            } else {
8723                // hd256: the SAME v4_dc symbol the burst verify launches (PARITY LAW — the
8724                // host-base rows_v4 twin compiles apart from v4_dc and the two-symbol split
8725                // drifted the burst's persisted KV at il=8; one symbol, counter arg-stored).
8726                e.i32_set_k(&mut kvl.len_d, base_len as i32)?;
8727                e.fa_decode_rows_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8728                                    &kvl.len_d, base_len + t, t, scale,
8729                                    kvl.k_tok_bytes, kvl.v_tok_bytes, 0,
8730                                    swa && crate::Engine::wkv_on())?;
8731            }
8732            return Ok(e.matmul(&fa.wo, &attn, t)?);
8733        }
8734        // WINDOWED rows twin (deep ctx, every row fully windowed): one launch, ABSOLUTE-index
8735        // per-row geometry over the prefix view. PARITY LAW (2026-07-10 root-cause): textually
8736        // identical kernels do NOT compile bit-identically (nvcc unrolls fa_decode_vec_q 2x vs
8737        // its rows_w clone — SASS-proven; the unpinned score `+=` chain then rounds apart), so
8738        // decode-vs-verify parity comes from BOTH sides launching THIS SAME rows_w kernel
8739        // (decode passes t=1) — bitwise equal per position by symbol identity, any lane.
8740        // MEMRA_GEMMA_ROWS_W=0 -> per-token loop (decode falls back to fa_decode views too).
8741        if hd == 256 && swa && base_len + 1 >= win
8742            && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8743            let k_view = e.view_u8(&kvl.k, (base_len + t) * kvl.k_tok_bytes);
8744            let v_view = e.view_u8(&kvl.v, (base_len + t) * kvl.v_tok_bytes);
8745            e.i32_set_k(&mut kvl.len_d, base_len as i32)?;
8746            e.fa_decode_rows_w(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, &kvl.len_d, 0,
8747                               t, scale, win, kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
8748            return Ok(e.matmul(&fa.wo, &attn, t)?);
8749        }
8750        for i in 0..t {
8751            let avail = base_len + i + 1;
8752            let (off_tok, t_kv) = if swa && avail > win { (avail - win, win) } else { (0, avail) };
8753            let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
8754                                         (off_tok + t_kv) * kvl.k_tok_bytes);
8755            let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
8756                                         (off_tok + t_kv) * kvl.v_tok_bytes);
8757            let qi = e.view(&q, t * nh * hd);
8758            let q_row = qi.slice(i * nh * hd..(i + 1) * nh * hd);
8759            let mut q_one = e.uninit(nh * hd)?;
8760            e.copy_view_into(&mut q_one, 0, &q_row, nh * hd)?;
8761            let mut a_one = e.uninit(nh * hd)?;
8762            // straddle rounds: windowed rows must ride the SAME rows_w kernel decode uses
8763            // (parity law above); global hd512 rows past the fa512 floor likewise ride the
8764            // rows_dpl16 twin; remaining rows keep the gated fa_decode pair.
8765            if swa && avail > win && hd == 256
8766                && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8767                let kp = e.view_u8(&kvl.k, avail * kvl.k_tok_bytes);
8768                let vp = e.view_u8(&kvl.v, avail * kvl.v_tok_bytes);
8769                e.i32_set_k(&mut kvl.len_d, (avail - 1) as i32)?;
8770                e.fa_decode_rows_w(&q_one, &kp, &vp, &mut a_one, hd, nh, nkv, &kvl.len_d, 0,
8771                                   1, scale, win, kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
8772            } else if !swa && hd == 512 && avail >= crate::fa512_min_tkv()
8773                && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8774                let kp = e.view_u8(&kvl.k, avail * kvl.k_tok_bytes);
8775                let vp = e.view_u8(&kvl.v, avail * kvl.v_tok_bytes);
8776                e.i32_set_k(&mut kvl.len_d, (avail - 1) as i32)?;
8777                e.fa_decode_rows(&q_one, &kp, &vp, &mut a_one, hd, nh, nkv, avail - 1, 1,
8778                                 scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
8779                                 Some((&kvl.len_d, 0)), false, false, None)?;
8780            } else {
8781                e.fa_decode_kvmod(&q_one, &k_view, &v_view, &mut a_one, hd, nh, nkv, t_kv, scale,
8782                            kvl.k_tok_bytes, kvl.v_tok_bytes, swa && crate::Engine::wkv_on())?;
8783            }
8784            e.copy_into(&mut attn, i * nh * hd, &a_one, nh * hd)?;
8785        }
8786        Ok(e.matmul(&fa.wo, &attn, t)?)
8787    }
8788
8789    /// gemma4 T=1 decode step: R8 layer graph over the cache; returns (softcapped logits host,
8790    /// h_seed = pre-output_norm hidden). Advances cache.pos.
8791    pub(crate) fn gemma4_decode_step_h(&self, e: &Engine, token: u32, cache: &mut Cache)
8792                                       -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8793        // M1-PP2 door (crate::pp): 2-stage split with an explicit activation handoff.
8794        // Default OFF — unset env means this branch is never taken. The gemma4 arm stays
8795        // 2-stage in M2 (the N-stage gate model is the generic-arm 9B); N>2 warns + runs
8796        // unsplit rather than guessing a fence.
8797        if let Some(split) = crate::pp::pp2_split(self.layers.len()) {
8798            return self.gemma4_decode_step_h_pp2(e, token, cache, split);
8799        }
8800        if crate::pp::pp_cuts(self.layers.len()).is_some() {
8801            crate::pp::warn_unwired_once("gemma4 eager decode (N>2)");
8802        }
8803        let n_embd = self.cfg.n_embd as usize;
8804        let eps = self.cfg.rms_eps;
8805        let pos_d = e.htod_i32(&[cache.pos as i32])?;
8806        let mut x = e.htod(&self.embd.gather(n_embd, &[token]))?;
8807        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
8808        // cross-layer fusion: each tail's closing add+scale also EMITS the next layer's
8809        // attn-normed input pre-quantized q8_1 (the mixer consumes only quantized matmuls).
8810        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8811        let n_layers = self.layers.len();
8812        for (il, layer) in self.layers.iter().enumerate() {
8813            let (hq, hdq) = match h_carry.take() {
8814                Some(p) => p,
8815                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, 1, eps)?,
8816            };
8817            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8818            let o = self.gemma4_decode_attn(e, fa, il, &hq, &hdq, &pos_d, cache)?;
8819            let mut cur = e.uninit(n_embd)?;
8820            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, 1, eps)?;
8821            let next_norm = if il + 1 < n_layers {
8822                Some(self.layers[il + 1].attn_norm.float_data())
8823            } else { None };
8824            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, 1, next_norm)?;
8825            x = xn;
8826            h_carry = hn;
8827        }
8828        let mut hn = e.uninit(n_embd)?;
8829        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
8830        let h_seed = e.clone_dtod(&x)?;
8831        let mut ld = e.matmul(&self.output, &hn, 1)?;
8832        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
8833        e.softcap(&mut ld, cap, self.output.out_features())?;   // R4 on device (262k host tanh ~ms/step)
8834        self.gemma4_suppress(e, &mut ld, 1)?;
8835        let logits = e.dtoh(&ld)?;
8836        cache.pos += 1;
8837        Ok((logits, h_seed))
8838    }
8839
8840    /// M1-PP2 stage subgraph (gemma4 arm): layers [lo, hi) of the gemma4 T=1 walk with the
8841    /// pre-quantized next-norm carry LOCAL to the range. Enters with a materialized residual
8842    /// `x` (the range head runs its own `rms_norm_q8_1` against ITS layer's attn_norm — for
8843    /// lo == 0 that is exactly the unsplit loop's il==0 arm); exits with the residual
8844    /// materialized (range tail passes next_norm = None, exactly the unsplit last-layer arm).
8845    /// Bit-identity of the cut relies on the kernel-check-pinned `add_scale_rms_norm_q8_1 ==
8846    /// add_scale then rms_norm_q8_1` identity (`pp2-gate` verifies end-to-end).
8847    fn gemma4_decode_layers(&self, e: &Engine, mut x: CudaSlice<f32>, lo: usize, hi: usize,
8848                            pos_d: &CudaSlice<i32>, cache: &mut Cache)
8849                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8850        let n_embd = self.cfg.n_embd as usize;
8851        let eps = self.cfg.rms_eps;
8852        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8853        for il in lo..hi {
8854            let layer = &self.layers[il];
8855            let (hq, hdq) = match h_carry.take() {
8856                Some(p) => p,
8857                // range head: il == lo — norm against THIS layer's attn_norm.
8858                None => e.rms_norm_q8_1(&x, self.layers[il].attn_norm.float_data(), n_embd, 1, eps)?,
8859            };
8860            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8861            let o = self.gemma4_decode_attn(e, fa, il, &hq, &hdq, pos_d, cache)?;
8862            let mut cur = e.uninit(n_embd)?;
8863            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, 1, eps)?;
8864            let next_norm = if il + 1 < hi {
8865                Some(self.layers[il + 1].attn_norm.float_data())
8866            } else { None };
8867            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, 1, next_norm)?;
8868            x = xn;
8869            h_carry = hn;
8870        }
8871        Ok(x)
8872    }
8873
8874    /// M1-PP2 (increment 2): `gemma4_decode_step_h` as TWO stage subgraphs, each on its
8875    /// own stream (and device, under MEMRA_PP_DEVICES) with the transport-selected
8876    /// boundary handoff — same choreography as the generic arm (decode.rs), same
8877    /// ownership contract (crate::pp). Stage 0 = embed+scale + layers [0, split);
8878    /// stage 1 = layers [split, n) + output_norm + softcapped head.
8879    /// Each stage uploads its own copy of the step's position scalar on its own stream.
8880    /// MEMRA_PP_STREAMS=0 = the increment-1 same-stream seam. Gate: `pp2-gate`.
8881    fn gemma4_decode_step_h_pp2(&self, e: &Engine, token: u32, cache: &mut Cache, split: usize)
8882                                -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8883        if crate::pp::pp2_streams_off() {
8884            return self.gemma4_decode_step_h_pp2_samestream(e, token, cache, split);
8885        }
8886        let rt = crate::pp::Pp2Rt::get(e)?;
8887        let e0 = rt.engine(0, e);
8888        let e1 = rt.engine(1, e);
8889        let n_embd = self.cfg.n_embd as usize;
8890        let eps = self.cfg.rms_eps;
8891        let pos = cache.pos as i32;
8892
8893        // ---- STAGE 0 (its own stream): embed + sqrt(n_embd) scale + layers [0, split) ----
8894        let slot = {
8895            let _st0 = rt.enter(0);
8896            let pos_d = e0.htod_i32(&[pos])?;
8897            #[cfg(debug_assertions)]
8898            crate::debug_assert_tensor_stream_device(&pos_d, &e0.stream(),
8899                                                       "gemma4_decode_step_h_pp2.stage0.pos_d");
8900            let mut x = e0.htod(&self.embd.gather(n_embd, &[token]))?;
8901            e0.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
8902            let x = self.gemma4_decode_layers(e0, x, 0, split, &pos_d, cache)?;
8903            rt.tx(0, &x, n_embd)?
8904        };
8905
8906        // ---- STAGE 1 (its own stream): RX + layers [split, n) + softcapped head ----
8907        let _st1 = rt.enter(1);
8908        let pos_d = e1.htod_i32(&[pos])?;
8909        #[cfg(debug_assertions)]
8910        crate::debug_assert_tensor_stream_device(&pos_d, &e1.stream(),
8911                                                   "gemma4_decode_step_h_pp2.stage1.pos_d");
8912        let x = rt.rx(0, slot, n_embd)?;
8913        let x = self.gemma4_decode_layers(e1, x, split, self.layers.len(), &pos_d, cache)?;
8914
8915        let mut hn = e1.uninit(n_embd)?;
8916        e1.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
8917        let h_seed = e1.clone_dtod(&x)?;
8918        let mut ld = e1.matmul(&self.output, &hn, 1)?;
8919        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
8920        e1.softcap(&mut ld, cap, self.output.out_features())?;
8921        self.gemma4_suppress(e1, &mut ld, 1)?;
8922        let logits = e1.dtoh(&ld)?;
8923        cache.pos += 1;
8924        Ok((logits, h_seed))
8925    }
8926
8927    /// MEMRA_PP_STREAMS=0 rollback seam: the increment-1 gemma4 pp2 body verbatim — both
8928    /// stage subgraphs on the ambient compute stream, boundary = two plain dtod copies.
8929    fn gemma4_decode_step_h_pp2_samestream(&self, e: &Engine, token: u32, cache: &mut Cache,
8930                                           split: usize)
8931                                           -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8932        let n_embd = self.cfg.n_embd as usize;
8933        let eps = self.cfg.rms_eps;
8934        let pos_d = e.htod_i32(&[cache.pos as i32])?;
8935
8936        // ---- STAGE 0: embed + sqrt(n_embd) scale + layers [0, split) ----
8937        let mut x = e.htod(&self.embd.gather(n_embd, &[token]))?;
8938        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
8939        let x = self.gemma4_decode_layers(e, x, 0, split, &pos_d, cache)?;
8940
8941        // ---- STAGE BOUNDARY: explicit [n_embd] activation handoff (TX copy, RX copy) ----
8942        let boundary_tx = e.clone_dtod(&x)?;
8943        let boundary_rx = e.clone_dtod(&boundary_tx)?;
8944
8945        // ---- STAGE 1: layers [split, n) + output_norm + softcapped head ----
8946        let x = self.gemma4_decode_layers(e, boundary_rx, split, self.layers.len(), &pos_d, cache)?;
8947
8948        let mut hn = e.uninit(n_embd)?;
8949        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
8950        let h_seed = e.clone_dtod(&x)?;
8951        let mut ld = e.matmul(&self.output, &hn, 1)?;
8952        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
8953        e.softcap(&mut ld, cap, self.output.out_features())?;
8954        self.gemma4_suppress(e, &mut ld, 1)?;
8955        let logits = e.dtoh(&ld)?;
8956        cache.pos += 1;
8957        Ok((logits, h_seed))
8958    }
8959}
8960
8961// ============================ step35 (Step-3.7-Flash) ==================================
8962// Node-for-node vs llama.cpp src/models/step35.cpp:216-300. WHY THIS IS A DEDICATED MIXER
8963// FAMILY and not a few branches inside the generic `full_attn*` chain:
8964//
8965//   1. `n_head` IS PER LAYER (`step35.attention.head_count` is an ARRAY: 64 on full-attn
8966//      layers, 96 on SWA). Every generic site reads the `cfg.n_head` scalar, so wq/wo/attn_gate
8967//      shapes and the FA head counts would be wrong on 33 of 45 layers.
8968//   2. `cfg.rope_dim_count` is 128 for this arch, but FULL-attn layers rotate only 64 dims
8969//      (upstream halves `n_rot_full` after the generic loader defaults it). A generic mixer
8970//      would rotate 128 dims on the full layers — silently wrong, plausible-looking logits.
8971//   3. Dual rope base (5e6 full / 1e4 SWA) + `rope_freqs.weight` on FULL layers ONLY.
8972//   4. SWA 3:1 (`sliding_window` 512, pattern [false,true,true,true]).
8973//   5. The head-wise gate is a SEPARATE `attn_gate.weight [n_embd, n_head_l]` (one pre-sigmoid
8974//      scalar per head, broadcast over head_dim) applied to the attention output BEFORE wo —
8975//      not the qwen35 fused-in-wq per-DIM gate that `attn_out_gate()`/`q_gate_split` handle.
8976//      Its input is the POST-attn_norm hidden (`cur`), not the residual.
8977//
8978// Attention scale is the DEFAULT 1/sqrt(n_embd_head_k) (step35.cpp:255) — NOT gemma4's 1.0.
8979impl HybridModel {
8980    /// Step35's declarative geometry row. Missing rows are artifact/config errors; never
8981    /// synthesize a drafter or trunk layer from a neighboring class.
8982    pub(crate) fn step35_geom(&self, il: usize) -> memra_gguf::config::LayerGeometry {
8983        let geometry = self.cfg.layer_geometry(il as u32)
8984            .unwrap_or_else(|| panic!("step35 layer {il} has no geometry-table row"));
8985        debug_assert_eq!(
8986            geometry.attention_gate,
8987            memra_gguf::config::AttentionGateKind::SeparateHead
8988        );
8989        geometry
8990    }
8991
8992    /// step35 attention core: everything from the q/k/v projection outputs through the head-wise
8993    /// gate, returning the GATED attention output PRE-`wo` (the caller runs wo, so this composes
8994    /// with both the plain `matmul(&fa.wo, ..)` sites and the f16/into-slab GEMM sites).
8995    ///
8996    /// `hg` = the POST-attn_norm hidden state (upstream's `cur`) — the gate projection's input
8997    /// on single-sequence paths. `gt_pre` supplies the already-projected per-head gate for a
8998    /// cross-request batch; exactly one of `hg` or `gt_pre` must be present.
8999    /// `cache`:
9000    ///   * `Some` => PRIME mode: append this chunk's post-rope K / raw V rows into the resident
9001    ///     quantized cache and attend THROUGH the cache view, exactly like the generic
9002    ///     `full_attn_prime_fa_dispatch` (quantize-then-attend on chunk 0 too, so chunk size
9003    ///     cannot decide where a precision edge falls — the grain-free chunk-invariance
9004    ///     contract, lane/chunkinv-flip).
9005    ///   * `None` => pure prefill (forward/forward_last/t2probe): attend over this batch's f32
9006    ///     q/k/v, no cache side effect.
9007    ///
9008    /// SWA WINDOW, and why prefill needs `sdpa_naive_w_quantized_view`: the view is trimmed to
9009    /// the oldest key ANY query in this chunk can reach (`off = base_len - (win-1)`), which
9010    /// bounds the view at `win-1+t` rows, but the mask is still required — inside the chunk,
9011    /// query `qt` may only see view keys `[qt, qt+win-1]`, so the earlier keys the trimmed view
9012    /// still contains must be masked per query. memra's window convention
9013    /// (`sdpa_naive_w_f32`: mask `t < q_pos-(window-1)`, `q_pos = (T_kv-T)+qt`) is bit-for-bit
9014    /// upstream's `LLAMA_SWA_TYPE_STANDARD` (`llama-hparams.h:359`: mask `p1-p0 >= n_swa`), and
9015    /// step35.cpp:6 sets exactly that swa_type — verified verbatim on both sides.
9016    ///
9017    /// Note the f32 `sdpa_naive_w` floor's shared memory is `t_kv*4` bytes, so the SWA arm needs
9018    /// `t_kv = win-1+t <= 12287` — i.e. it relies on chunked prefill (MEMRA_PRIME_CHUNK, default
9019    /// 4096). A monolithic 32k prime would exceed the 48 KiB dynamic-smem default.
9020    ///
9021    /// SWA ARM SELECTION IS KEYED ON `seq_end`, NOT ON THE CHUNK'S OWN `t_kv` (lane/step35-chunkfix,
9022    /// 2026-08-07). `seq_end` = the ABSOLUTE end position of the whole prime call
9023    /// (`cache.pos + prompt_len` at entry; `t` on the cacheless prefill path) — a property of the
9024    /// REQUEST, identical at every MEMRA_PRIME_CHUNK value. The old predicate `swa && t_kv > win`
9025    /// read the chunk's own extent, which made kernel selection — and therefore the logits, the
9026    /// hidden rows, and the generated text — a function of the chunk size:
9027    ///   a chunk [b,e) has off = max(0, b-(win-1)), t_kv = e-off, so b <= win-1 => off=0 => FA iff
9028    ///   e <= win, while every later chunk has t_kv = t+(win-1) > win. The FA rows were therefore a
9029    ///   contiguous PREFIX [0,P) with P = c*floor(win/c) for c <= win (else 0), and the output
9030    ///   depended only on P. Measured (research/step37-p2-20260806, closed-form receipt
9031    ///   `raw/chunkinv-step35-GAP2-CONFIRMED-20260807.txt`): at T=4883, c=512 and c=64 (P=512) are
9032    ///   byte-identical to each other but DIFFER from the c=4096 default (P=0) by maxdiff 1.813e0
9033    ///   with greedy text diverging at step 6; c=513 (P=0) is bit-identical to the default. A
9034    ///   one-token change in a documented machine-config knob changed the answer.
9035    /// So the pre-fix comment "same cache bytes, same numeric class" was false as written: same
9036    /// bytes, DIFFERENT numeric class — swapping `fa_prefill_view_ws` for the f32 windowed floor on
9037    /// the same rows moves the logits by ~1.8.
9038    ///
9039    /// Keying on `seq_end` makes P identically 0 for every chunk size, so MEMRA_PRIME_CHUNK is a
9040    /// pure memory/transient knob again (research/step35-chunkfix-20260807). It is
9041    /// correct-by-construction rather than a tolerance argument — the windowed kernel computes the
9042    /// same masked attention the FA arm computed (for e <= win the window mask is a no-op under
9043    /// causal, which is exactly why FA was legal there), it is now simply the ONLY arm used once
9044    /// the request passes the window. It also cannot move the shipped default: at chunk=4096 every
9045    /// chunk of a `seq_end > win` prime ALREADY had t_kv > win (chunk 0 has t_kv = min(chunk,
9046    /// seq_end) > win; every later chunk has t_kv >= t+win-1 > win since `PRIME_MIN_T` keeps
9047    /// t >= 16), and a `seq_end <= win` prime keeps every chunk on FA exactly as before — so this
9048    /// is a no-op on both default regimes and only removes the FA prefix at small chunk values.
9049    /// The `t_kv <= 12287` smem ceiling is respected: the chunks whose arm changes are precisely
9050    /// those with t_kv <= win = 512.
9051    #[allow(clippy::too_many_arguments)]
9052    fn step35_attn_pre_wo(&self, e: &Engine, fa: &FullAttnLayer, mut g3: Vec<CudaSlice<f32>>,
9053                          hg: Option<&CudaSlice<f32>>, gt_pre: Option<&CudaSlice<f32>>,
9054                          pos_d: &CudaSlice<i32>, t: usize,
9055                          cache: Option<&mut Cache>, il: usize, seq_end: usize)
9056                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9057        let geometry = self.step35_geom(il);
9058        let hd = geometry.head_dim_k as usize;
9059        let nkv = geometry.n_head_kv as usize;
9060        let nh = geometry.n_head as usize;
9061        let rbase = geometry.rope_base;
9062        let scale = geometry.attention_scale();
9063        let swa = geometry.window.is_some();
9064        let eps = self.cfg.rms_eps;
9065        let win = geometry.window.unwrap_or(0) as usize;
9066        let n_rot = geometry.n_rot as usize;
9067
9068        let v = g3.pop().unwrap();
9069        let k0 = g3.pop().unwrap();
9070        let q0 = g3.pop().unwrap();
9071
9072        // q/k RMSNorm over head_dim rows (attn_q_norm/attn_k_norm [128] F32), then the
9073        // per-layer PARTIAL NEOX rope: n_rot = 64 on full layers (dims 64..127 pass through
9074        // unrotated), 128 on SWA. rope_freqs (llama3-style per-dim factors) on FULL only.
9075        let mut q = e.uninit(t * nh * hd)?;
9076        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh * t, eps)?;
9077        let mut k = e.uninit(t * nkv * hd)?;
9078        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv * t, eps)?;
9079        let ff = if geometry.rope_factors {
9080            self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
9081        } else {
9082            None
9083        };
9084        #[cfg(debug_assertions)]
9085        if let Some(ff) = ff {
9086            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
9087                                                       "step35_attn_pre_wo.rope_freqs");
9088        }
9089        e.rope_neox2(&mut q, &mut k, pos_d, hd, n_rot, nh, nkv, t, rbase, 1.0, ff)?;
9090
9091        let mut attn = e.uninit(t * nh * hd)?;
9092        match cache {
9093            Some(cache) => {
9094                let base_len = cache.kv[il].as_ref().unwrap().len;
9095                // Read per layer call, never in a measured default.
9096                let legacy_tkv = std::env::var("MEMRA_STEP35_SWA_TKV").as_deref() == Ok("1");
9097                let legacy_calllocal =
9098                    std::env::var("MEMRA_PRIME_CALLLOCAL").as_deref() == Ok("1");
9099                let off = if swa {
9100                    let raw = base_len.saturating_sub(win - 1);
9101                    if legacy_tkv || legacy_calllocal { raw } else { raw & !31usize }
9102                } else {
9103                    0
9104                };
9105                {
9106                    let kvl = cache.kv[il].as_mut().unwrap();
9107                    assert!(kvl.len + t <= cache.max_ctx, "step35 prime: KV overflow");
9108                    let write_row = e.prepare_kv_append(kvl, off, t)?;
9109                    e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, write_row, t,
9110                                               kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes,
9111                                               kvl.v_tok_bytes, crate::Engine::kv_fp8_on())?;
9112                    kvl.len += t;
9113                    let new_len = kvl.len as i32;
9114                    e.set_i32_one(&mut kvl.len_d, new_len)?;
9115                }
9116                let kvl = cache.kv[il].as_ref().unwrap();
9117                // Both segmentation seams restore the FULL pre-fix arithmetic: their legacy
9118                // arm predicate (`t_kv` below, per-call `seq_end` in prime_cache) AND the
9119                // unaligned view offset here. Both halves are load-bearing for the canaries:
9120                // on the FA default the predicate arms agree bitwise wherever they can differ
9121                // (a t_kv<=win view has no maskable key, so windowed==unwindowed FA bit-for-bit).
9122                // That made predicate-only seams INERT under Lever A — first chunkinv35c, then
9123                // tickinv35c. The raw offset restores the live segmentation-variant mechanism
9124                // on the current FA path: its tile grid starts at the chunk/call boundary.
9125                // SWA: trim the view to the oldest key any query in this chunk can reach —
9126                // ALIGNED DOWN to the FA tile size (BK=32). The raw trim is chunk-DEPENDENT
9127                // (off = base_len-(win-1), and base_len is a chunk boundary), and the FA
9128                // kernel's online-softmax recurrence groups keys into BK tiles relative to
9129                // the VIEW START — so an unaligned off regroups the same absolute keys into
9130                // different tiles at different chunk sizes = different (m,l) rounding =
9131                // chunk-dependent bits. chunkinv35 caught exactly this on the first FA-arm
9132                // battery (first_div == chunk size; raw/leverA-gates-20260807T135541Z.log).
9133                // Aligning off to 32 pins tiles to ABSOLUTE key positions for every chunk
9134                // size; the <=31 extra leading keys are older than EVERY query's window
9135                // (all queries sit at >= base_len, so keys < base_len-(win-1) are masked
9136                // for all of them) and a fully-masked key is an exact-0.0 no-op in both
9137                // kernels (NEG_INF -> p=0.0; l+=0.0 and O+=0.0 are bitwise identity), so
9138                // the floor arm's bits do not move either (gated: G2f, battery 2).
9139                let t_kv = base_len + t - off;
9140                let physical = kvl.physical_rows(off, off + t_kv)?;
9141                let k_view = e.view_u8_range(&kvl.k, physical.start * kvl.k_tok_bytes,
9142                                             physical.end * kvl.k_tok_bytes);
9143                let v_view = e.view_u8_range(&kvl.v, physical.start * kvl.v_tok_bytes,
9144                                             physical.end * kvl.v_tok_bytes);
9145                // CHUNK-INVARIANT PREDICATE: `seq_end` (the request's absolute end position), not
9146                // this chunk's `t_kv`. See the doc note — keying on t_kv made P = c*floor(win/c)
9147                // rows take FA and the output a function of MEMRA_PRIME_CHUNK.
9148                // MEMRA_STEP35_SWA_TKV=1 is the ROLLBACK SEAM to the pre-fix arithmetic — BOTH
9149                // halves: this predicate AND the unaligned view offset above (`legacy_tkv`).
9150                // It is what gives the step35 chunkinv gate its canary teeth: chunk-VARIANT by
9151                // construction, so the invariance assertion MUST break under it (the seam whose
9152                // absence made the original canary inert — GAP 1 in research/step37-p2-20260806;
9153                // and a predicate-only seam went inert AGAIN under the FA default, battery 2's
9154                // CANARY UNEXPECTEDLY MATCHED — see the offset comment). Read per call, not
9155                // cached (probes flip it in-process). Never on in a measured default run.
9156                let swa_naive = if legacy_tkv { t_kv > win } else { seq_end > win };
9157                if swa && swa_naive {
9158                    // Windowed mask needed (see the doc note). DEFAULT since lane/pp-prefill
9159                    // 2026-08-07: the windowed hd128 FA stamp (`fa_prefill_view_ws_w_hd128`) —
9160                    // the anatomy profile measured the f32 floor at 565 ms/layer on a pp4096
9161                    // (41% of the whole prime) while the unwindowed hd128 FA family did the
9162                    // strictly harder causal-4096 in 3.3 ms. NOTE t_kv can be <= win here
9163                    // (a chunk-0 view on a small chunk); the windowed kernel handles that
9164                    // identically to the unwindowed one modulo the mask, which is the point.
9165                    // NEW NUMERIC CLASS vs the floor (bf16-MMA online softmax vs f32 serial),
9166                    // selected on `seq_end` like every arm here, so the class is uniform for
9167                    // the whole request at every MEMRA_PRIME_CHUNK — chunkinv holds by the
9168                    // same construction as the chunkfix. MEMRA_STEP35_SWA_FA=0 = rollback to
9169                    // the f32 floor (the previous numeric config, kept as the A/B seam).
9170                    if std::env::var("MEMRA_STEP35_SWA_FA").as_deref() == Ok("0") {
9171                        e.sdpa_naive_w_quantized_view(&q, &k_view, &v_view, &mut attn, hd, nh,
9172                                                      nkv, t, t_kv, scale, true, win,
9173                                                      kvl.k_tok_bytes, kvl.v_tok_bytes)?;
9174                    } else {
9175                        e.fa_prefill_view_ws_w_hd128(&q, &k_view, &v_view, &mut attn, hd, nh,
9176                                                     nkv, t, t_kv, scale, true, win,
9177                                                     kvl.k_tok_bytes, kvl.v_tok_bytes)?;
9178                    }
9179                } else if std::env::var("MEMRA_NOFA").is_ok() {
9180                    e.sdpa_naive_quantized_view(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
9181                                                t, t_kv, scale, true,
9182                                                kvl.k_tok_bytes, kvl.v_tok_bytes)?;
9183                } else {
9184                    // seq_end <= win (or a full-attn layer): no query in the WHOLE request can
9185                    // reach past the window, so the window mask is a no-op under causal and every
9186                    // chunk rides the hd128 dequant-once FA prefill — one arm for the whole
9187                    // request either way, which is what makes the chunk size arithmetic-free.
9188                    e.fa_prefill_view_ws(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
9189                                         t, t_kv, scale, true,
9190                                         kvl.k_tok_bytes, kvl.v_tok_bytes,
9191                                         crate::Engine::kv_fp8_on())?;
9192                }
9193            }
9194            None => {
9195                // Cacheless prefill (forward/forward_last/t2probe) is MONOLITHIC — there is no
9196                // chunk loop on this path, so seq_end == t and the predicate is unchanged. The
9197                // assert pins that: if a chunked cacheless prefill is ever added, it must thread
9198                // seq_end here too or it re-opens the same door.
9199                debug_assert_eq!(seq_end, t, "step35 cacheless prefill is monolithic (seq_end == t)");
9200                if swa && seq_end > win {
9201                    e.sdpa_naive_w(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true, win)?;
9202                } else if std::env::var("MEMRA_NOFA").is_ok() {
9203                    e.sdpa_naive(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
9204                } else {
9205                    e.fa_prefill(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
9206                }
9207            }
9208        }
9209
9210        // HEAD-WISE GATE (step35.cpp:267-285): gate = attn_gate(cur) -> [t, n_head_l];
9211        // attn *= sigmoid(gate) broadcast over head_dim. BEFORE wo.
9212        let gw = fa.attn_gate.as_ref()
9213            .ok_or("step35 layer is missing attn_gate.weight (head-wise attention gate)")?;
9214        let gt_owned = if gt_pre.is_none() {
9215            Some(e.matmul(
9216                gw,
9217                hg.ok_or("step35 attention needs hg when gt_pre is absent")?,
9218                t,
9219            )?)
9220        } else {
9221            None
9222        };
9223        let gt = gt_pre.or(gt_owned.as_ref()).unwrap();
9224        let mut ag = e.uninit(t * nh * hd)?;
9225        e.attn_head_gate(&attn, gt, &mut ag, None, hd, nh, t)?;
9226        Ok(ag)
9227    }
9228
9229    /// step35 PREFILL mixer, no cache side effect (the `full_attn` contract: `forward`,
9230    /// `forward_last`, t2probe). Post-`wo`.
9231    pub(crate) fn step35_attn(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>,
9232                              pos_d: &CudaSlice<i32>, t: usize, il: usize)
9233                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9234        let g3 = e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?;
9235        // Monolithic path: the request ends at t (no chunk loop). See step35_attn_pre_wo's note.
9236        let ag = self.step35_attn_pre_wo(e, fa, g3, Some(h), None, pos_d, t, None, il, t)?;
9237        Ok(e.matmul(&fa.wo, &ag, t)?)
9238    }
9239
9240    /// step35 PRIME mixer (the `full_attn_prime` contract: append this chunk's K/V into the
9241    /// resident quantized cache, attend through the cache view). Post-`wo`.
9242    ///
9243    /// `seq_end` = the ABSOLUTE end position of the whole prime request (chunk-invariant); it
9244    /// selects the SWA arm. See `step35_attn_pre_wo`'s doc note for why it cannot be this chunk's
9245    /// own extent.
9246    #[allow(clippy::too_many_arguments)]
9247    pub(crate) fn step35_attn_prime(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>,
9248                                    hx: Option<&CudaSlice<u8>>, pos_d: &CudaSlice<i32>, t: usize,
9249                                    cache: &mut Cache, il: usize, seq_end: usize)
9250                                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9251        let g3 = match hx {
9252            Some(xh) => e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], h, xh, t)?,
9253            None => e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?,
9254        };
9255        let ag = self.step35_attn_pre_wo(
9256            e,
9257            fa,
9258            g3,
9259            Some(h),
9260            None,
9261            pos_d,
9262            t,
9263            Some(cache),
9264            il,
9265            seq_end,
9266        )?;
9267        Ok(e.matmul(&fa.wo, &ag, t)?)
9268    }
9269
9270    /// step35 T=1 decode attention (post-`wo`, matching `full_attn_decode_pre`'s contract).
9271    /// `pre_q` = the attn-input norm's q8_1 pair when the caller took the norm-fusion lever
9272    /// (then `h` is a zero-length placeholder and EVERY projection here — including the gate —
9273    /// must be on the q8_1 fast path; `mixer_in_q8_1_fast` enforces that for step35 by also
9274    /// requiring `attn_gate`).
9275    ///
9276    /// SWA decode is a token-aligned VIEW OFFSET into the quantized cache (the gemma4 R6
9277    /// pattern): keys carry absolute rope and the mask is purely positional, so the single
9278    /// query at `len-1` attending the last `win` rows IS the windowed result — no mask kernel.
9279    #[allow(clippy::too_many_arguments)]
9280    pub(crate) fn step35_decode_attn(&self, e: &Engine, fa: &FullAttnLayer, il: usize,
9281                          h: &CudaSlice<f32>,
9282                          pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
9283                          pos_d: &CudaSlice<i32>, cache: &mut Cache)
9284                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9285        let geometry = self.step35_geom(il);
9286        let hd = geometry.head_dim_k as usize;
9287        let nkv = geometry.n_head_kv as usize;
9288        let nh = geometry.n_head as usize;
9289        let rbase = geometry.rope_base;
9290        let scale = geometry.attention_scale();
9291        let swa = geometry.window.is_some();
9292        let eps = self.cfg.rms_eps;
9293        let win = geometry.window.unwrap_or(0) as usize;
9294        let n_rot = geometry.n_rot as usize;
9295        let n_embd = self.cfg.n_embd as usize;
9296        let gw = fa.attn_gate.as_ref()
9297            .ok_or("step35 layer is missing attn_gate.weight (head-wise attention gate)")?;
9298
9299        let (q0, k0, v0, gt) = match pre_q {
9300            Some((hq, hdq)) => {
9301                debug_assert!(e.uses_q8_1_fast(gw),
9302                    "step35 pre-quantized decode requires attn_gate on the q8_1 fast path \
9303                     (h is a zero-length placeholder here) — see mixer_in_q8_1_fast");
9304                let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hdq)? {
9305                    Some(t3) => t3,
9306                    None => (e.matmul_pre(&fa.wq, hq, hdq, h, 1)?,
9307                             e.matmul_pre(&fa.wk, hq, hdq, h, 1)?,
9308                             e.matmul_pre(&fa.wv, hq, hdq, h, 1)?),
9309                };
9310                let gt = e.matmul_pre(gw, hq, hdq, h, 1)?;
9311                (a, b, c, gt)
9312            }
9313            None => {
9314                if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk)
9315                    && e.uses_q8_1_fast(&fa.wv) && e.uses_q8_1_fast(gw) {
9316                    let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
9317                    let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
9318                        Some(t3) => t3,
9319                        None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
9320                                 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
9321                                 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?),
9322                    };
9323                    let gt = e.matmul_pre(gw, &hq, &hdq, h, 1)?;
9324                    (a, b, c, gt)
9325                } else {
9326                    (e.matmul(&fa.wq, h, 1)?, e.matmul(&fa.wk, h, 1)?,
9327                     e.matmul(&fa.wv, h, 1)?, e.matmul(gw, h, 1)?)
9328                }
9329            }
9330        };
9331
9332        let mut q = e.uninit(nh * hd)?;
9333        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
9334        let mut k = e.uninit(nkv * hd)?;
9335        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
9336        let ff = if swa { None } else {
9337            self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
9338        };
9339        #[cfg(debug_assertions)]
9340        if let Some(ff) = ff {
9341            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
9342                                                       "step35_decode_attn.rope_freqs");
9343        }
9344        e.rope_neox2(&mut q, &mut k, pos_d, hd, n_rot, nh, nkv, 1, rbase, 1.0, ff)?;
9345
9346        if std::env::var("MEMRA_NOFA").is_ok() {
9347            return Err("MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV \
9348                        cache; unset MEMRA_NOFA to use fa_decode".into());
9349        }
9350        let kvl = cache.kv[il].as_mut().unwrap();
9351        let next_len = kvl.len + 1;
9352        let (off, t_kv) = if swa && next_len > win { (next_len - win, win) } else { (0, next_len) };
9353        let write_row = e.prepare_kv_append(kvl, off & !31usize, 1)?;
9354        e.append_kv_quantized(&k, &v0, &mut kvl.k, &mut kvl.v, write_row,
9355                              kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
9356                              crate::Engine::kv_fp8_on())?;
9357        kvl.len = next_len;
9358        let physical = kvl.physical_rows(off, off + t_kv)?;
9359        let k_view = e.view_u8_range(&kvl.k, physical.start * kvl.k_tok_bytes,
9360                                     physical.end * kvl.k_tok_bytes);
9361        let v_view = e.view_u8_range(&kvl.v, physical.start * kvl.v_tok_bytes,
9362                                     physical.end * kvl.v_tok_bytes);
9363        let mut attn = e.uninit(nh * hd)?;
9364        e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
9365                          kvl.k_tok_bytes, kvl.v_tok_bytes, crate::Engine::kv_fp8_on())?;
9366
9367        let mut ag = e.uninit(nh * hd)?;
9368        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
9369        Ok(e.matmul(&fa.wo, &ag, 1)?)
9370    }
9371}
9372
9373// ===================================================================================== //
9374//  gemma-4 E4B (per-layer embeddings + KV-sharing) — FIRST-LIGHT forward.               //
9375//  Dedicated simple path (Stage-B matmuls, per-row causal attention over the quantized  //
9376//  cache) so the tuned 26B/31B paths stay untouched. Arch: research/gemma4-bringup/     //
9377//  e4b-arch-map.md; llama reference: src/models/gemma4.cpp (E4B arms). Wired: forward   //
9378//  (prefill logits), prime (tokenwise-equivalent batched trunk), eager decode_step_h.   //
9379//  NOT wired: dc/graph serving arms, verify/spec, chunked prime (HANDOVER-E4B.md).      //
9380// ===================================================================================== //
9381impl HybridModel {
9382    pub fn is_gemma4_e4b(&self) -> bool {
9383        self.gemma4_aux.as_ref().is_some_and(|a| a.e4b.is_some())
9384    }
9385
9386    /// E4B per-layer geometry: nh/nkv derive from the layer's OWN tensor shapes (the E4B GGUF
9387    /// ships a scalar head_count_kv; swa q 8x256 / kv 2x256, global q 4x512 / kv 1x512).
9388    /// KV-shared layers report the SHARE TARGET's kv count (their wk IS the target's tensor).
9389    fn gemma4_e4b_geom(&self, il: usize) -> (usize, usize, usize, f32, f32, bool) {
9390        let g = self.cfg.gemma4.as_ref().unwrap();
9391        let swa = g.swa_pattern[il];
9392        let hd = if swa { g.key_length_swa } else { g.key_length_global } as usize;
9393        let Mixer::Full(fa) = &self.layers[il].mixer else { panic!("e4b layer {il} not full-attn") };
9394        let nh = fa.wq.out_features() / hd;
9395        let nkv = fa.wk.out_features() / hd;
9396        (hd, nkv, nh, if swa { g.rope_base_swa } else { g.rope_base_global }, 1.0, swa)
9397    }
9398
9399    /// E4B KV-share target: Some(target) for the trailing shared layers, None = own cache.
9400    fn gemma4_e4b_kv_target(&self, il: usize) -> Option<usize> {
9401        self.layers[il].gemma4.as_ref()
9402            .and_then(|b| b.e4b.as_ref())
9403            .and_then(|e4| e4.kv_share.map(|t| t as usize))
9404    }
9405
9406    /// E4B prologue: inp_pl [t][n_layer][n_epl] =
9407    ///   ( gather(per_layer_tok_embd, tok)*sqrt(n_epl)
9408    ///   + rms_norm(model_proj . x_scaled * 1/sqrt(n_embd), proj_norm) ) * 1/sqrt(2)
9409    /// (llama gemma4.cpp build_inp_per_layer + project_per_layer_inputs, exact order).
9410    fn gemma4_e4b_inp_pl(&self, e: &Engine, tokens: &[u32], x_scaled: &CudaSlice<f32>, t: usize)
9411                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9412        let tok_d = e.stream().clone_htod(&tokens.to_vec())?;
9413        self.gemma4_e4b_inp_pl_dev(e, &tok_d, x_scaled, t)
9414    }
9415
9416    /// Device-token prologue core (dc arm shares it: token ids never touch the host).
9417    fn gemma4_e4b_inp_pl_dev(&self, e: &Engine, tok_d: &CudaSlice<u32>,
9418                             x_scaled: &CudaSlice<f32>, t: usize)
9419                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9420        let aux = self.gemma4_aux.as_ref().unwrap();
9421        let m = aux.e4b.as_ref().unwrap();
9422        let n_embd = self.cfg.n_embd as usize;
9423        let n_layer = self.layers.len();
9424        let width = m.n_epl * n_layer;
9425        let tbl = m.tok_tbl_gpu.get_or_init(|| {
9426            e.upload_u8(&m.tok_embd_bytes).expect("e4b per-layer token table upload")
9427        });
9428        let mut a = e.embed_gather_device_td(tbl, tok_d, t, width, m.tok_embd_qt,
9429                                             m.tok_embd_row_bytes)?;
9430        e.scale_inplace(&mut a, (m.n_epl as f32).sqrt(), t * width)?;
9431        let mut p = e.matmul(&m.model_proj, x_scaled, t)?;
9432        e.scale_inplace(&mut p, 1.0 / (n_embd as f32).sqrt(), t * width)?;
9433        let mut pn = e.uninit(t * width)?;
9434        e.rms_norm(&p, m.proj_norm.float_data(), &mut pn, m.n_epl, t * n_layer,
9435                   self.cfg.rms_eps)?;
9436        let mut out = e.uninit(t * width)?;
9437        e.add_scale(&a, &pn, 1.0 / 2f32.sqrt(), &mut out, t * width)?;
9438        Ok(out)
9439    }
9440
9441    /// E4B attention (t-wide, causal, per-row fa over the QUANTIZED cache — first-light
9442    /// correctness path; the fa rows arms come later). Own-KV layers project+norm+rope k/v
9443    /// and append t rows; KV-shared layers are Q-only over the target layer's cache (which
9444    /// already holds this forward's rows — the target runs earlier in the stack).
9445    #[allow(clippy::too_many_arguments)]
9446    fn gemma4_e4b_attn(&self, e: &Engine, il: usize,
9447                       hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
9448                       pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache,
9449                       dc_bucket: Option<usize>)
9450                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9451        let (hd, nkv, nh, base, scale, swa) = self.gemma4_e4b_geom(il);
9452        let eps = self.cfg.rms_eps;
9453        let aux = self.gemma4_aux.as_ref().unwrap();
9454        let ones = aux.ones(e);
9455        #[cfg(debug_assertions)]
9456        crate::debug_assert_tensor_stream_device(ones, &e.stream(),
9457                                                   "gemma4_e4b_attn.ones");
9458        let Mixer::Full(fa) = &self.layers[il].mixer else { unreachable!() };
9459        // pre-quantized layer input (E4B fusion port, 2026-07-12): ONE norm+quant feeds
9460        // wq/wk/wv via matmul_pre — the first-light path quantized the same h three times
9461        // (the profile's 342 quantize_q8_1/token; glue = 26% of the 6.1ms token).
9462        let h0 = e.zeros(0)?;
9463        let h = &h0;
9464
9465        let ff = if swa { None } else {
9466            Some(aux.rope_freqs(e).expect("e4b global rope needs rope_freqs.weight"))
9467        };
9468        #[cfg(debug_assertions)]
9469        if let Some(ff) = ff {
9470            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
9471                                                       "gemma4_e4b_attn.rope_freqs");
9472        }
9473        let share = self.gemma4_e4b_kv_target(il);
9474        // Own-KV arms keep the f32 (k, v) alive for the prime fa arm below.
9475        let mut kv_f32: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
9476        let mut q;
9477        if let Some(_tgt) = share {
9478            let q0 = e.matmul_pre(&fa.wq, hq, hdq, h, t)?;
9479            q = e.uninit(t * nh * hd)?;
9480            // Q-only through the same fused norm+rope kernel (rk = 0: the k/v segments are
9481            // empty; q0 stands in for the unused k/v pointers).
9482            let mut kdummy = e.uninit(1)?;
9483            let mut vdummy = e.uninit(1)?;
9484            e.rms_norm_qkv_rope(&q0, &q0, &q0, fa.q_norm.float_data(),
9485                                fa.q_norm.float_data(), ones,
9486                                &mut q, &mut kdummy, &mut vdummy, hd, nh * t, 0,
9487                                pos_d, nh, 1, base, 1.0, ff, eps)?;
9488        } else {
9489            // wave-4b: ONE concat matvec (wq|wk|wv) at t == 1 when the cat tensor exists;
9490            // else the fused3 grid launch; else per-matvec. The cat output is contiguous
9491            // q|k|v rows — the cat norm+rope twin consumes it directly.
9492            let e4bits = self.layers[il].gemma4.as_ref().and_then(|g| g.e4b.as_ref());
9493            let cat = e4bits.and_then(|e4| e4.qkv_cat.as_ref());
9494            q = e.uninit(t * nh * hd)?;
9495            let mut k = e.uninit(t * nkv * hd)?;
9496            let mut v = e.uninit(t * nkv * hd)?;
9497            if t == 1 && cat.is_some() {
9498                let qkv0 = e.matmul_pre(cat.unwrap(), hq, hdq, h, 1)?;
9499                e.rms_norm_qkv_rope_cat(&qkv0, fa.q_norm.float_data(), fa.k_norm.float_data(),
9500                                        ones, &mut q, &mut k, &mut v, hd, nh, nkv,
9501                                        pos_d, nh, nkv, base, 1.0, ff, eps)?;
9502            } else {
9503                let (q0, k0, v0) = match if t == 1 {
9504                    e.matmul_q4_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hdq)?
9505                } else {
9506                    // E4B verify f3 port (2026-07-14): the 31B segmented-grid batched qkv
9507                    // on E4B's real-V triple — same MEMRA_F2B seam, bit-identical per row.
9508                    static F2B_QKV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
9509                    if *F2B_QKV.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0")) {
9510                        e.matmul_q4_fused3_batched(&fa.wq, &fa.wk, &fa.wv, hq, hdq, t)?
9511                    } else { None }
9512                } {
9513                    Some(triple) => triple,
9514                    None => (e.matmul_pre(&fa.wq, hq, hdq, h, t)?,
9515                             e.matmul_pre(&fa.wk, hq, hdq, h, t)?,
9516                             e.matmul_pre(&fa.wv, hq, hdq, h, t)?),   // E4B: real v (K != V)
9517                };
9518                // wave-3 fold: q/k/v norms + q/k rope in ONE launch (rope math verbatim on
9519                // the normed rows; V ones-rms, never roped).
9520                e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(),
9521                                    fa.k_norm.float_data(), ones, &mut q, &mut k, &mut v,
9522                                    hd, nh * t, nkv * t, pos_d, nh, nkv, base, 1.0, ff, eps)?;
9523            }
9524            let kvl = cache.kv[il].as_mut().unwrap();
9525            // class flag must match the cache dims (the g-threading sweep hardcoded `false`
9526            // here and the wkv default corrupted E4B: q8_0 bytes into an e4m3 cache — the
9527            // degenerate tok-0 stream, 2026-07-12).
9528            let cls = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
9529            if dc_bucket.is_some() {
9530                // DC arm (graph serving): append at the len_d slot, advance the counter
9531                // in-stream — replay-correct, no host len in the launch args. Host mirrors
9532                // are NOT touched here (the replay loop owns them; a bump at capture-record
9533                // time would double-count the capture iteration).
9534                debug_assert!(t == 1);
9535                // wave 5c: append + len_d inc fused (one launch; single-block ordering).
9536                e.append_kv_quantized_row_dc_inc(&k, &v, &mut kvl.k, &mut kvl.v,
9537                                                 &mut kvl.len_d, kvl.kv_dim_k, kvl.kv_dim_v,
9538                                                 kvl.k_tok_bytes, kvl.v_tok_bytes, cls)?;
9539            } else {
9540                e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len, t,
9541                                           kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes,
9542                                           kvl.v_tok_bytes, cls)?;
9543                kvl.len += t;
9544            }
9545            kv_f32 = Some((k, v));
9546        }
9547        // attention: per-row causal fa over the (own or target) quantized cache. The cache
9548        // already contains this forward's rows in both arms; row i attends [.., base+i].
9549        let kvl_idx = share.unwrap_or(il);
9550        let kvl = cache.kv[kvl_idx].as_ref().unwrap();
9551        let base_len = kvl.len - t;   // pre-append length (target appended this forward too)
9552        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
9553        let mut attn = e.uninit(t * nh * hd)?;
9554        // PRIME FA ARMS (perf lane 3, completed 2026-07-31 — the H100 board pinned E4B
9555        // prefill at 482 tok/s: the per-row loop ran the DECODE kernel once per token per
9556        // layer). Fresh-prompt (base_len == 0) batched attention, one launch per layer:
9557        //   - own-KV hd256 under the window: f32 fa_prefill (full causal exact — 26B pattern)
9558        //   - own-KV hd256 above the window (swa): fa_prefill_w windowed twin (12B pattern)
9559        //   - own-KV hd512 globals: fa_prefill_hd512 (12B/31B globals pattern)
9560        //   - KV-shared layers (no f32 k/v): fa_prefill_view over the target's QUANTIZED
9561        //     rows (the T=K verify kernel; the target appended this forward's rows already).
9562        //     swa-shared above the window keeps the per-row loop (no windowed view twin).
9563        // Same numeric class split as the 26B prime (f32/batched prefill vs per-row
9564        // quantized decode); run-gen argmax + chat gates arbitrate. MEMRA_NOFA=1 reverts all.
9565        if t > 1 && base_len == 0 && std::env::var("MEMRA_NOFA").is_err() {
9566            if let Some((kf, vf)) = &kv_f32 {
9567                if hd == 256 && t <= win {
9568                    e.fa_prefill(&q, kf, vf, &mut attn, hd, nh, nkv, t, t, scale, true)?;
9569                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9570                }
9571                if hd == 256 && swa && t > win {
9572                    e.fa_prefill_w(&q, kf, vf, &mut attn, hd, nh, nkv, t, t, scale, true,
9573                                   win)?;
9574                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9575                }
9576                if hd == 512 && !swa {
9577                    e.fa_prefill_hd512(&q, kf, vf, &mut attn, hd, nh, nkv, t, t, scale,
9578                                       true)?;
9579                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9580                }
9581            } else if share.is_some() {
9582                let g = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
9583                let k_view = e.view_u8(&kvl.k, kvl.k.len());
9584                let v_view = e.view_u8(&kvl.v, kvl.v.len());
9585                if hd == 256 && (!swa || t <= win) {
9586                    // inline-dequant quantized-view prefill (fa_prefill_q stamps 256/128)
9587                    e.fa_prefill_view(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t, t,
9588                                      scale, true, kvl.k_tok_bytes, kvl.v_tok_bytes, g)?;
9589                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9590                }
9591                // remaining shared classes (swa above the window; hd512 globals): dequant
9592                // the target's t rows ONCE to f32, then the same f32 twins as own-KV.
9593                let kv_dim = nkv * hd;
9594                let mut kf = e.uninit(t * kv_dim)?;
9595                let mut vf = e.uninit(t * kv_dim)?;
9596                e.fa_dequant_kv_view_f32(&k_view, &v_view, &mut kf, &mut vf, kv_dim, kv_dim,
9597                                         t, kvl.k_tok_bytes, kvl.v_tok_bytes, g)?;
9598                if hd == 512 {
9599                    e.fa_prefill_hd512(&q, &kf, &vf, &mut attn, hd, nh, nkv, t, t, scale,
9600                                       true)?;
9601                } else {
9602                    e.fa_prefill_w(&q, &kf, &vf, &mut attn, hd, nh, nkv, t, t, scale, true,
9603                                   win)?;
9604                }
9605                return Ok(e.matmul(&fa.wo, &attn, t)?);
9606            }
9607        }
9608        if let Some(bucket) = dc_bucket {
9609            // DC arm (t == 1, under-window regime — the generate gate enforces it): ONE
9610            // fa_decode_dc over the live counter. len_d already advanced past this token
9611            // (t_kv = len_d[0], the cache.rs contract). KV-shared layers read the target's
9612            // counter (advanced when the target ran earlier in the stack).
9613            assert!(t == 1);
9614            // hd512 globals: eager (kvmod) picks the SCALAR unified below the fa512 floor,
9615            // and under the window every live t_kv sits below it — cap the capture bucket
9616            // under the floor so fa_decode_dc bakes the same scalar symbol, or the graph
9617            // rides the dpl16 twin and its numeric class diverges from the dc-eager stream
9618            // (E4B-GRAPH-GATE 2/64, 2026-07-12).
9619            let bucket = if hd == 512 && win <= crate::fa512_min_tkv() {
9620                bucket.min(crate::fa512_min_tkv().saturating_sub(1))
9621            } else { bucket };
9622            let k_view = e.view_u8(&kvl.k, kvl.k.len());
9623            let v_view = e.view_u8(&kvl.v, kvl.v.len());
9624            let g = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
9625            // Weight prefetch (SOTA item 3, 2026-07-13): wo's decode plane prefetched into
9626            // L2 across the fa window — fa reads KV only, the weight DRAM lanes are idle
9627            // there (E4B valid window +0.65%: 196.8 vs 195.6). Value-free scheduling op,
9628            // captured into the dc graph like any other launch. Extending the cascade to
9629            // the ffn gate/up planes measured NEGATIVE (193.9 vs 195.8 — 29MB/layer floods
9630            // the fill path and evicts still-hot lines); wo-only is the shipped shape.
9631            // MEMRA_WPF=0 rollback seam.
9632            if crate::Engine::wpf_level() >= 1 {
9633                e.prefetch_weight_l2(&fa.wo)?;
9634            }
9635            // wave 5b: the combine emits the wo input q8 pair directly — the standalone
9636            // quantize launch + the f32 attn round-trip fold away (t=1 fast path only).
9637            if e.uses_q8_1_fast(&fa.wo) {
9638                let mut oq = e.alloc_i8_uninit(nh * hd)?;
9639                let mut od = e.zeros(nh * hd / 32)?;
9640                e.fa_decode_dc_q8(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
9641                                  &kvl.len_d, bucket, scale,
9642                                  kvl.k_tok_bytes, kvl.v_tok_bytes, g,
9643                                  Some((&mut oq, &mut od)))?;
9644                return Ok(e.matmul_pre(&fa.wo, &oq, &od, &attn, t)?);
9645            }
9646            e.fa_decode_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
9647                           &kvl.len_d, bucket, scale,
9648                           kvl.k_tok_bytes, kvl.v_tok_bytes, g)?;
9649            return Ok(e.matmul(&fa.wo, &attn, t)?);
9650        }
9651        for i in 0..t {
9652            let avail = base_len + i + 1;
9653            let (off_tok, t_kv) = if swa && avail > win { (avail - win, win) } else { (0, avail) };
9654            let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
9655                                         (off_tok + t_kv) * kvl.k_tok_bytes);
9656            let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
9657                                         (off_tok + t_kv) * kvl.v_tok_bytes);
9658            let qv = e.view(&q, t * nh * hd);
9659            let q_row = qv.slice(i * nh * hd..(i + 1) * nh * hd);
9660            let mut q_one = e.uninit(nh * hd)?;
9661            e.copy_view_into(&mut q_one, 0, &q_row, nh * hd)?;
9662            let mut a_one = e.uninit(nh * hd)?;
9663            // read class MUST match the append class (globals are e4m3 under gkv): the
9664            // swa-only flag decoded global-layer e4m3 bytes as q8_0/q5_1 — attention over
9665            // garbage on EVERY E4B global layer, the cross-mode maxdiff-30 root (2026-07-12).
9666            e.fa_decode_kvmod(&q_one, &k_view, &v_view, &mut a_one, hd, nh, nkv, t_kv, scale,
9667                        kvl.k_tok_bytes, kvl.v_tok_bytes,
9668                        (!swa && crate::Engine::gkv_on())
9669                            || (swa && crate::Engine::wkv_on()))?;
9670            e.copy_into(&mut attn, i * nh * hd, &a_one, nh * hd)?;
9671        }
9672        Ok(e.matmul(&fa.wo, &attn, t)?)
9673    }
9674
9675    /// E4B trunk: embed -> prologue -> layers (attn + dense ffn via the 31B tail_core + the
9676    /// per-layer-embedding tail + layer scale) -> output_norm. Returns (softcapped logits
9677    /// device [t, n_vocab], pre-output_norm hidden [t, n_embd]). Appends t rows per own-KV
9678    /// layer; does NOT advance cache.pos (caller owns pos).
9679    fn gemma4_e4b_trunk(&self, e: &Engine, tokens: &[u32], pos0: usize, cache: &mut Cache,
9680                        head_last: bool)
9681                        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9682        let n_embd = self.cfg.n_embd as usize;
9683        let t = tokens.len();
9684        let pos: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
9685        let pos_d = e.htod_i32(&pos)?;
9686        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
9687        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
9688        let inp_pl = self.gemma4_e4b_inp_pl(e, tokens, &x, t)?;
9689        self.gemma4_e4b_trunk_core(e, x, inp_pl, &pos_d, t, cache, None, true, head_last)
9690    }
9691
9692    /// Layer stack + head over prebuilt (x_scaled, inp_pl, device pos) — everything below
9693    /// here is device-driven, so the dc arm shares it verbatim (stream identity with the
9694    /// eager chain by construction: SAME functions, not twins).
9695    fn gemma4_e4b_trunk_core(&self, e: &Engine, x_in: CudaSlice<f32>, inp_pl: CudaSlice<f32>,
9696                             pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache,
9697                             dc_bucket: Option<usize>, cap_logits: bool, head_last: bool)
9698                             -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9699        let n_embd = self.cfg.n_embd as usize;
9700        let eps = self.cfg.rms_eps;
9701        let n_layer = self.layers.len();
9702        let mut x = x_in;
9703        let aux_e4b = self.gemma4_aux.as_ref().unwrap().e4b.as_ref().unwrap();
9704        let n_epl = aux_e4b.n_epl;
9705
9706        // cross-layer fusion (2026-07-12 port of the 26B/31B trunk structure): each layer's
9707        // closing add_scale also EMITS the next layer's attn-normed input pre-quantized
9708        // q8_1 (add_scale_rms_norm_q8_1); the LAST layer emits through output_norm so the
9709        // head rides matmul_pre too. First layer's pair comes from a standalone fused
9710        // norm+quant.
9711        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
9712        for il in 0..n_layer {
9713            let layer = &self.layers[il];
9714            let (hq, hdq) = match h_carry.take() {
9715                Some(p) => p,
9716                None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
9717            };
9718            let o = self.gemma4_e4b_attn(e, il, &hq, &hdq, pos_d, t, cache, dc_bucket)?;
9719            // dense ffn tail with the post-attn norm FOLDED into its entry (one launch for
9720            // rms(o, post_attn_norm) + residual add + ffn_norm — glue-fusion lane).
9721            let bits = layer.gemma4.as_ref().unwrap();
9722            let e4b = bits.e4b.as_ref().expect("e4b layer bits");
9723            // glue wave 5: the tail DEFERS its post_ffw norm — the FFN exit fuses
9724            // rms(f0, post_ffw) + residual add + q8 emit into ONE launch (rms_pre_add_q8_1),
9725            // killing the rms_norm + add_q8_1 pair per layer. T-GENERIC since 2026-07-13:
9726            // the fused single-phase reduction is NOT FP-order-identical to the unfused
9727            // rms_norm+add pair (the original "bit-identical chain" claim was FALSE — the
9728            // t==1 gate left the batched VERIFY on the unfused chain and split E4B verify
9729            // from decode by logit maxdiff ~0.45, the greedy tie-flip at depth: gate 135/256.
9730            // NOFUSE bisect: disabling ONLY this fusion -> verify maxdiff 0.000e0). With the
9731            // gate dropped, decode AND verify ride the same fused chain — parity by
9732            // construction, VERIFY-GATE 0.000e0.
9733            let fuse_exit = e.uses_q8_1_fast(&e4b.inp_gate);
9734            let (sn, attn_out) = self.gemma4_layer_tail_core_pn(
9735                e, layer, &o, &x, t, Some(layer.post_attn_norm.float_data()), fuse_exit)?;
9736            let mut resid = e.uninit(t * n_embd)?;
9737            // per-layer-embedding tail: resid += rms(proj . (gelu(inp_gate . resid) * inp_pl[il]))
9738            // wave-2: the residual add emits q8_1 alongside — inp_gate rides matmul_pre.
9739            // (PLE one-block mega-fusion PROBED NEGATIVE 2026-07-13: argmax-correct but
9740            // 126 vs 189 tok/s — one SM pulling 0.74MB of weights loses to the multi-block
9741            // launch chain it replaced; jsonl row. Kernel deleted per doctrine.)
9742            let g = if fuse_exit {
9743                // sn here = RAW f0 (post_ffw deferred).
9744                let (rq, rd) = e.rms_pre_add_q8_1(&sn, bits.post_ffw_norm.float_data(),
9745                                                  &attn_out, &mut resid, n_embd, t,
9746                                                  self.cfg.rms_eps)?;
9747                e.matmul_pre(&e4b.inp_gate, &rq, &rd, &resid, t)?
9748            } else {
9749                e.add(&sn, &attn_out, &mut resid, t * n_embd)?;
9750                e.matmul(&e4b.inp_gate, &resid, t)?
9751            };
9752            let mut act = e.uninit(t * n_epl)?;
9753            let y = if t == 1 && e.uses_q8_1_fast(&e4b.proj) {
9754                let ipv = e.view(&inp_pl, n_epl * n_layer);
9755                let row = ipv.slice(il * n_epl..(il + 1) * n_epl);
9756                let (aq, ad) = e.gelu_tanh_mul_q8_1(&g, &row, &mut act, n_epl, 1)?;
9757                e.matmul_pre(&e4b.proj, &aq, &ad, &act, t)?
9758            } else {
9759                let mut inp_this = e.uninit(t * n_epl)?;
9760                e.copy_rows_strided(&inp_pl, &mut inp_this, n_epl, t, n_epl * n_layer,
9761                                    il * n_epl)?;
9762                e.gelu_tanh_mul(&g, &inp_this, &mut act, t * n_epl)?;
9763                e.matmul(&e4b.proj, &act, t)?
9764            };
9765            // rms(y, post_norm) + (yn + resid)*layer_scale + next-layer norm+quant emit,
9766            // ONE launch (glue-fusion lane; last layer emits through output_norm).
9767            let next_norm = if il + 1 < n_layer {
9768                self.layers[il + 1].attn_norm.float_data()
9769            } else {
9770                self.output_norm.float_data()
9771            };
9772            let mut xn = e.uninit(t * n_embd)?;
9773            let pair = e.rms_pre_add_scale_rms_norm_q8_1(&y, e4b.post_norm.float_data(),
9774                                                         &resid, bits.layer_scale, next_norm,
9775                                                         &mut xn, n_embd, t, eps)?;
9776            h_carry = Some(pair);
9777            x = xn;
9778        }
9779        // the head consumes the last layer's fused (output_norm) emit. head_last callers
9780        // (prime, last_only forward) need only the final row's logits — the all-T head is
9781        // t*n_vocab of discarded work (E4B prime: ~134ms GEMM + a 2.26GB dtoh kept 1 row).
9782        let (oq, odq) = h_carry.take().unwrap();
9783        let h0 = e.zeros(0)?;
9784        let hm = if head_last { 1 } else { t };
9785        let (hq, hd) = if head_last && t > 1 {
9786            let mut q1 = e.uninit_i8(n_embd)?;
9787            e.dtod_copy_view_i8(&oq.slice((t - 1) * n_embd..t * n_embd), &mut q1)?;
9788            let nb = n_embd / 32;
9789            let mut d1 = e.uninit(nb)?;
9790            e.dtod_copy_view(&odq.slice((t - 1) * nb..t * nb), &mut d1)?;
9791            (q1, d1)
9792        } else {
9793            (oq, odq)
9794        };
9795        let mut ld = e.matmul_pre(&self.output, &hq, &hd, &h0, hm)?;
9796        // softcap is strictly monotonic — greedy (argmax-only) consumers skip it, matching
9797        // the 26B/31B dc precedent (their dc head goes matmul -> argmax with no cap).
9798        // Logit-returning callers (host logits / spec prime) keep the capped emit.
9799        if cap_logits {
9800            let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
9801            e.softcap(&mut ld, cap, hm * self.output.out_features())?;
9802        }
9803        self.gemma4_suppress(e, &mut ld, hm)?;  // mask both capped and argmax-only consumers
9804        Ok((ld, x))
9805    }
9806
9807    /// E4B batched VERIFY (device tokens, the spec round's t=K+1 step): t rows through the
9808    /// e4b trunk (per-row causal attention; own-KV layers append t rows host-len, KV-shared
9809    /// layers ride their targets), per-row device argmax + the POST-output_norm hidden
9810    /// stack (the drafter's h convention). Advances cache.pos/kvl.len by t — the spec
9811    /// round rolls back rejected rows (shared layers have no KvLayer, so the plain rewind
9812    /// covers exactly the layers that appended).
9813    pub fn gemma4_e4b_decode_step_t_am_dev(&self, e: &Engine, tok_d: &CudaSlice<u32>,
9814                                                  t: usize, pos0: usize, cache: &mut Cache)
9815                                                  -> Result<(CudaSlice<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9816        let n_embd = self.cfg.n_embd as usize;
9817        let eps = self.cfg.rms_eps;
9818        let pos: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
9819        let pos_d = e.htod_i32(&pos)?;
9820        let embd_gpu = self.embd_gpu.get_or_init(|| {
9821            e.upload_u8(&self.embd.raw).expect("embed table upload")
9822        });
9823        let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
9824        let mut x = e.embed_gather_device_td(embd_gpu, tok_d, t, n_embd, qt, rb)?;
9825        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
9826        let inp_pl = self.gemma4_e4b_inp_pl_dev(e, tok_d, &x, t)?;
9827        let (ld, xp) = self.gemma4_e4b_trunk_core(e, x, inp_pl, &pos_d, t, cache, None, true,
9828                                                  false)?;
9829        // softcap is monotonic — the per-row argmax is invariant to it (the trunk's head
9830        // emit is already capped, matching the eager chain bit-for-bit).
9831        let n_vocab = self.output.out_features();
9832        let mut vam = e.stream().alloc_zeros::<u32>(t)?;
9833        for i in 0..t {
9834            e.argmax_token_device_col(&ld, i, n_vocab, &mut vam, i)?;
9835        }
9836        let mut hn = e.uninit(t * n_embd)?;
9837        e.rms_norm(&xp, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
9838        cache.pos += t;
9839        Ok((vam, hn))
9840    }
9841
9842    /// E4B verify + host logits + POST-output_norm hidden stack (the short-prompt spec
9843    /// prime path — mirror of `gemma4_decode_step_t_h`).
9844    pub(crate) fn gemma4_e4b_decode_step_t_h(&self, e: &Engine, tokens: &[u32], pos0: usize,
9845                                             cache: &mut Cache)
9846                                             -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9847        let n_embd = self.cfg.n_embd as usize;
9848        let eps = self.cfg.rms_eps;
9849        let t = tokens.len();
9850        let (ld, xp) = self.gemma4_e4b_trunk(e, tokens, pos0, cache, false)?;
9851        let mut hn = e.uninit(t * n_embd)?;
9852        e.rms_norm(&xp, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
9853        cache.pos += t;
9854        Ok((e.dtoh(&ld)?, hn))
9855    }
9856
9857    /// E4B GRAPH-CAPTURABLE dc step: same trunk as the dc step but token_d is updated IN
9858    /// PLACE (self-feeding replay) and every launch arg is a device counter — pos from
9859    /// pos_d (inc'd in-stream), KV slots from len_d (advanced in-stream), attention from
9860    /// fa_decode_dc at `bucket`. Host mirrors (cache.pos / kvl.len) advance in the caller's
9861    /// replay loop. UNDER-WINDOW regime only (the caller gates pos + budget < window).
9862    pub fn gemma4_e4b_decode_step_dcg(&self, e: &Engine, token_d: &mut CudaSlice<u32>,
9863                                      pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
9864                                      embd_qt: i32, embd_rb: usize, cache: &mut Cache,
9865                                      n_vocab: usize, bucket: usize)
9866                                      -> Result<(), Box<dyn std::error::Error>> {
9867        let n_embd = self.cfg.n_embd as usize;
9868        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_rb)?;
9869        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
9870        let inp_pl = self.gemma4_e4b_inp_pl_dev(e, token_d, &x, 1)?;
9871        let (ld, _x) = self.gemma4_e4b_trunk_core(e, x, inp_pl, pos_d, 1, cache, Some(bucket),
9872                                                  false, false)?;
9873        e.argmax_token_device_into(&ld, token_d, n_vocab)?;
9874        e.inc_seqlen(pos_d)?;
9875        Ok(())
9876    }
9877
9878    /// E4B DEVICE-COUNTER decode step (the dc serving arm): token id rides `token_d`, the
9879    /// greedy argmax lands in the returned device buffer — 4B/token host traffic. The layer
9880    /// stack is gemma4_e4b_trunk_core, i.e. the SAME functions the eager chain runs (stream
9881    /// identity by construction, not by twin-kernel parity). Host KV mirrors advance like the
9882    /// 26B dc-eager arm (window views are host math); len_d stays synced by the caller's
9883    /// entry sync + the appends here don't read it. Graph capture is NOT wired (no
9884    /// cap_bucket_max) — the E4B graph arc comes after the perf gates.
9885    #[allow(clippy::too_many_arguments)]
9886    pub fn gemma4_e4b_decode_step_dc(&self, e: &Engine, token_d: &CudaSlice<u32>,
9887                                     pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
9888                                     embd_qt: i32, embd_rb: usize, cache: &mut Cache,
9889                                     n_vocab: usize)
9890                                     -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
9891        let n_embd = self.cfg.n_embd as usize;
9892        let eps = self.cfg.rms_eps;
9893        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_rb)?;
9894        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
9895        let inp_pl = self.gemma4_e4b_inp_pl_dev(e, token_d, &x, 1)?;
9896        let (ld, _x) = self.gemma4_e4b_trunk_core(e, x, inp_pl, pos_d, 1, cache, None, false,
9897                                                  false)?;
9898        let mut tok_out = e.stream().alloc_zeros::<u32>(1)?;
9899        e.argmax_token_device_into(&ld, &mut tok_out, n_vocab)?;
9900        e.inc_seqlen(pos_d)?;
9901        cache.pos += 1;
9902        let _ = eps;
9903        Ok(tok_out)
9904    }
9905
9906    /// E4B eager T=1 decode step (decode_step_h contract): returns (softcapped logits host,
9907    /// pre-output_norm hidden). Advances cache.pos.
9908    pub(crate) fn gemma4_e4b_decode_step_h(&self, e: &Engine, token: u32, cache: &mut Cache)
9909                                           -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9910        let (ld, x) = self.gemma4_e4b_trunk(e, &[token], cache.pos, cache, false)?;
9911        let logits = e.dtoh(&ld)?;
9912        cache.pos += 1;
9913        Ok((logits, x))
9914    }
9915
9916    /// E4B batched prime (prime_cache contract: (last-row logits host, h_seed pre-norm last
9917    /// row, hidden stack)). First-light: the t-wide trunk (per-row attention) — correct, not
9918    /// fast; the prefill fa arms come later.
9919    pub(crate) fn gemma4_e4b_prime(&self, e: &Engine, tokens: &[u32], cache: &mut Cache)
9920                                   -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9921        // Err, not assert (2026-08-07, lane/gemma4-serve-gaps): same served-chunked-prompt
9922        // process-kill as gemma4_prime — refuse per-request.
9923        if cache.pos != 0 {
9924            return Err("e4b prime is fresh-prompt only (v0) — prime the full prompt in one \
9925                        call or decode tokenwise".into());
9926        }
9927        let n_embd = self.cfg.n_embd as usize;
9928        let t = tokens.len();
9929        let (ld, x) = self.gemma4_e4b_trunk(e, tokens, 0, cache, true)?;
9930        cache.pos += t;
9931        let last = e.dtoh(&ld)?;   // head_last: ld is already the final row only
9932        let xv = e.view(&x, t * n_embd);
9933        let row = xv.slice((t - 1) * n_embd..t * n_embd);
9934        let mut h_seed = e.uninit(n_embd)?;
9935        e.copy_view_into(&mut h_seed, 0, &row, n_embd)?;
9936        Ok((last, h_seed, x))
9937    }
9938
9939    /// E4B prefill logits (forward contract — no persistent cache; scratch cache internally).
9940    pub(crate) fn gemma4_e4b_forward(&self, e: &Engine, tokens: &[u32], last_only: bool)
9941                                     -> Result<Vec<f32>, Box<dyn std::error::Error>> {
9942        let mut cache = Cache::new(e, &self.cfg, tokens.len() + 8)?;
9943        let (ld, _x) = self.gemma4_e4b_trunk(e, tokens, 0, &mut cache, last_only)?;
9944        Ok(e.dtoh(&ld)?)   // head_last already reduced to the final row when last_only
9945    }
9946}
9947
9948#[cfg(test)]
9949mod prime_chunk_schedule_tests {
9950    use super::{
9951        dynamic_prime_chunk_ranges, fixed_prime_chunk_ranges, fixed_prime_chunk_ranges_for_ring,
9952        PRIME_MIN_T,
9953        PRIME_PIPE_MIN_CHUNK,
9954    };
9955
9956    fn sizes(ranges: &[(usize, usize)]) -> Vec<usize> {
9957        ranges.iter().map(|(start, end)| end - start).collect()
9958    }
9959
9960    fn auto_chunk(t: usize) -> usize {
9961        t.div_ceil(8).max(PRIME_PIPE_MIN_CHUNK).min(4096)
9962    }
9963
9964    #[test]
9965    fn fixed_schedule_retains_measured_geometry() {
9966        assert_eq!(
9967            sizes(&fixed_prime_chunk_ranges(461, 128)),
9968            vec![128, 128, 128, 77]
9969        );
9970        assert_eq!(
9971            sizes(&fixed_prime_chunk_ranges(1833, 230)),
9972            vec![230, 230, 230, 230, 230, 230, 230, 223]
9973        );
9974        assert_eq!(
9975            sizes(&fixed_prime_chunk_ranges(4096, 512)),
9976            vec![512; 8]
9977        );
9978        let capped = sizes(&fixed_prime_chunk_ranges_for_ring(8200, 4096, true));
9979        assert_eq!(capped, vec![4096, 4088, 16]);
9980        assert!(capped.iter().all(|&rows| rows <= 4096));
9981        assert_eq!(
9982            sizes(&fixed_prime_chunk_ranges_for_ring(4100, 4096, false)),
9983            vec![4100],
9984            "flag-off schedule remains byte-for-byte the legacy monolithic tail",
9985        );
9986    }
9987
9988    #[test]
9989    fn dynamic_schedule_matches_registered_shapes() {
9990        let cases = [
9991            (461, vec![64, 141, 132, 124]),
9992            (1833, vec![115, 269, 260, 252, 244, 237, 231, 225]),
9993            (4096, vec![256, 602, 580, 563, 545, 531, 516, 503]),
9994        ];
9995        for (t, expected) in cases {
9996            let chunk = auto_chunk(t);
9997            let fixed = fixed_prime_chunk_ranges(t, chunk);
9998            assert_eq!(
9999                sizes(&dynamic_prime_chunk_ranges(t, chunk, &fixed)),
10000                expected
10001            );
10002        }
10003    }
10004
10005    #[test]
10006    fn dynamic_schedule_covers_exactly_and_shrinks_after_fill() {
10007        for t in 256..=8192 {
10008            let chunk = auto_chunk(t);
10009            let fixed = fixed_prime_chunk_ranges(t, chunk);
10010            let dynamic = dynamic_prime_chunk_ranges(t, chunk, &fixed);
10011            assert_eq!(dynamic.len(), fixed.len(), "T={t}");
10012            assert_eq!(dynamic.first().unwrap().0, 0, "T={t}");
10013            assert_eq!(dynamic.last().unwrap().1, t, "T={t}");
10014            for pair in dynamic.windows(2) {
10015                assert_eq!(pair[0].1, pair[1].0, "T={t}");
10016            }
10017            assert!(
10018                dynamic
10019                    .iter()
10020                    .all(|(start, end)| end - start >= PRIME_MIN_T),
10021                "T={t} sizes={:?}",
10022                sizes(&dynamic)
10023            );
10024            if dynamic.len() >= 3 {
10025                let chunk_sizes = sizes(&dynamic);
10026                assert!(
10027                    chunk_sizes[0] < chunk_sizes[1],
10028                    "T={t} sizes={chunk_sizes:?}"
10029                );
10030                assert!(
10031                    chunk_sizes[1..].windows(2).all(|pair| pair[0] >= pair[1]),
10032                    "T={t} sizes={chunk_sizes:?}"
10033                );
10034            }
10035        }
10036    }
10037}
10038
10039#[cfg(test)]
10040mod page_prefetch_tests {
10041    use super::{
10042        grouped_worker_prefetch_position, page_prefetch_positions,
10043        page_prefetch_window_from_values, worker_prefetch_positions,
10044    };
10045
10046    #[test]
10047    fn page_prefetch_window_keeps_existing_opt_in_default() {
10048        assert_eq!(page_prefetch_window_from_values(false, None), 0);
10049        assert_eq!(page_prefetch_window_from_values(false, Some("8")), 0);
10050        assert_eq!(page_prefetch_window_from_values(true, None), 1);
10051        assert_eq!(page_prefetch_window_from_values(true, Some("bad")), 1);
10052        assert_eq!(page_prefetch_window_from_values(true, Some("0")), 0);
10053        assert_eq!(page_prefetch_window_from_values(true, Some("8")), 8);
10054    }
10055
10056    #[test]
10057    fn rolling_page_prefetch_advises_each_future_expert_once() {
10058        let advised: Vec<_> = (0..7)
10059            .flat_map(|position| page_prefetch_positions(position, 7, 3))
10060            .collect();
10061        assert_eq!(advised, vec![1, 2, 3, 4, 5, 6]);
10062
10063        let one_ahead: Vec<_> = (0..4)
10064            .flat_map(|position| page_prefetch_positions(position, 4, 1))
10065            .collect();
10066        assert_eq!(one_ahead, vec![1, 2, 3]);
10067        assert!(page_prefetch_positions(0, 4, 0).is_empty());
10068    }
10069
10070    #[test]
10071    fn grouped_worker_prefetch_primes_first_then_each_known_next_once() {
10072        assert_eq!(grouped_worker_prefetch_position(0, None), None);
10073        let positions: Vec<_> = std::iter::once(grouped_worker_prefetch_position(4, None).unwrap())
10074            .chain((0..4).filter_map(|position| {
10075                grouped_worker_prefetch_position(4, Some(position))
10076            }))
10077            .collect();
10078        assert_eq!(positions, vec![0, 1, 2, 3]);
10079        assert_eq!(grouped_worker_prefetch_position(1, Some(0)), None);
10080    }
10081
10082    #[test]
10083    fn rolling_worker_prefetch_primes_current_and_each_future_expert_once() {
10084        let queued: Vec<_> = (0..8)
10085            .flat_map(|position| worker_prefetch_positions(position, 8, 5))
10086            .collect();
10087        assert_eq!(queued, (0..8).collect::<Vec<_>>());
10088
10089        let one_at_a_time: Vec<_> = (0..4)
10090            .flat_map(|position| worker_prefetch_positions(position, 4, 1))
10091            .collect();
10092        assert_eq!(one_at_a_time, vec![0, 1, 2, 3]);
10093        assert!(worker_prefetch_positions(0, 4, 0).is_empty());
10094    }
10095}
10096
10097pub struct G4DcSlots {
10098    x: CudaSlice<f32>, xn: CudaSlice<f32>, cur: CudaSlice<f32>,
10099    hq: CudaSlice<i8>, hd_: CudaSlice<f32>,
10100    q0: CudaSlice<f32>, k0: CudaSlice<f32>, v0: CudaSlice<f32>,
10101    q: CudaSlice<f32>, k: CudaSlice<f32>, v: CudaSlice<f32>,
10102    attn: CudaSlice<f32>, o: CudaSlice<f32>,
10103    attn_out: CudaSlice<f32>, zsh: CudaSlice<f32>,
10104    zq: CudaSlice<i8>, zd: CudaSlice<f32>,
10105    gate: CudaSlice<f32>, up: CudaSlice<f32>,
10106    act: CudaSlice<f32>, actq: CudaSlice<i8>, actd: CudaSlice<f32>,
10107    f0: CudaSlice<f32>, sn: CudaSlice<f32>,
10108    hn: CudaSlice<f32>, logits: CudaSlice<f32>,
10109}