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/// MoE EXPERT dp4a gate (MEMRA_MOE_Q8, default ON; `=0` restores the Stage-A f32-dequant expert
289/// kernels). Applies when gate/up/down expert qtypes are all in the dp4a body set (IQ3_S/IQ4_XS).
290/// FP-order differs from Stage-A (int dp4a + warp tree) — argmax/run-gen/stream-identity gates
291/// arbitrate; the sequential and fused q8 paths ship as a matched pair (MEMRA_MOE_GATE contract).
292fn moe_q8_enabled() -> bool {
293    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
294    *E.get_or_init(|| std::env::var("MEMRA_MOE_Q8").map(|v| v != "0").unwrap_or(true))
295}
296
297/// gemma4 fast-arm gate: qtypes with an `expert_dot_g` dp4a body (superset used by the gelu
298/// dev arm; the qwen q8 arms keep their own battery-gated q8_expert_supported policy).
299fn expert_dp4a_supported(qt: i32) -> bool {
300    qt == crate::QT_Q4_0 || qt == crate::QT_IQ3_S || qt == crate::QT_IQ4_XS
301        || qt == crate::QT_Q3_K || qt == crate::QT_Q4_K || qt == crate::QT_Q6_K
302}
303
304fn q8_expert_supported(qt: i32) -> bool {
305    // k-quant arms added 2026-07-06 (Q3_K/Q4_K/Q6_K bodies for the UD tail layers). Briefly
306    // default-excluded the same day when they appeared to break 35B real-prompt spec — the
307    // ACTUAL culprit was the MoE router's cuBLASLt n-dependence (d994271); with the router
308    // decode-exact at verify t, the k-quant arms pass the full spec battery (p1/p2/p3 + raw
309    // K=1..8) and are DEFAULT ON again (+9 tok/s: 148.9 -> 157.9). MEMRA_MOE_Q8_KQ=0 excludes.
310    static KQ: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
311    let kq = *KQ.get_or_init(|| {
312        std::env::var("MEMRA_MOE_Q8_KQ").map(|v| v != "0").unwrap_or(true)
313    });
314    // NVFP4 experts: DEFAULT ON (2026-07-17). The M3-era "decode-vs-verify MISMATCH 3.4e1"
315    // that had this excluded was the missing per-expert macro-scale fold, fixed in the
316    // dev-kernel epilogues + moe_w_scale_by_expert; the 35B ct-NVFP4 artifact now runs the
317    // q8 arm at parity with the IQ4_XS daily (174-178 tok/s, spec K=1..8 exact). M3/Hy3
318    // never reach the q8 arms regardless (sigmoid-router cfg gates on pairs/dev/gdec).
319    // MEMRA_MOE_Q8_NVFP4=0 restores the f32 arm.
320    let nvfp4_q8 = std::env::var("MEMRA_MOE_Q8_NVFP4").map(|v| v != "0").unwrap_or(true);
321    qt == crate::QT_IQ3_S || qt == crate::QT_IQ4_XS || (nvfp4_q8 && qt == crate::QT_NVFP4)
322        || (kq && (qt == crate::QT_Q3_K || qt == crate::QT_Q4_K || qt == crate::QT_Q6_K))
323}
324
325/// The decode-once (_dec) and IQ-MMA expert kernels dequant via IQ-specific extractors —
326/// k-quant tensors must fall to the _em dot path instead.
327fn q8_expert_dec_supported(qt: i32) -> bool {
328    qt == crate::QT_IQ3_S || qt == crate::QT_IQ4_XS || qt == crate::QT_Q4_0
329}
330
331/// Grouped-f16 door (MEMRA_MOE_F16G) per-projection admission: the qtype has a dequant-to-f16
332/// kernel in cu/moe_f16_grouped.cu AND the projection's k dimension tiles its block size.
333/// Round 49 widened coverage to q35's UD mix (gate/up IQ3_S x39 + Q3_K x1 + IQ4_XS x1; down
334/// IQ4_XS x37 + Q6_K x3 + Q4_K x1) — the round-47 IQ4_XS/Q4_0-only table admitted ~1 of 41
335/// q35 layers, which is why that cell measured FLAT.
336fn f16g_proj_ok(qt: i32, in_f: usize) -> bool {
337    match qt {
338        crate::QT_Q4_0 => in_f % 32 == 0,
339        crate::QT_IQ4_XS | crate::QT_IQ3_S | crate::QT_Q3_K | crate::QT_Q4_K
340        | crate::QT_Q6_K => in_f % 256 == 0,
341        _ => false,
342    }
343}
344
345/// STAGE 3 prewarm gate (MEMRA_MOE_PREWARM, default ON; `=0` leaves residency organic). One-shot
346/// per layer: force-admit every block while FREE slots cover the whole layer (never evicts).
347fn moe_prewarm_enabled() -> bool {
348    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
349    *E.get_or_init(|| std::env::var("MEMRA_MOE_PREWARM").map(|v| v != "0").unwrap_or(true))
350}
351
352/// During a discarded fixed-residency profile, admit CPU-routed misses after their current-token
353/// CPU result is complete. The current result and numeric path are unchanged; later warmup tokens
354/// can then vote for and exercise those experts on GPU before the cache is frozen.
355fn cpu_expert_profile_admit_enabled() -> bool {
356    static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
357    *E.get_or_init(|| std::env::var("MEMRA_CPU_EXPERT_FREEZE_PROFILE_ADMIT").as_deref() == Ok("1"))
358}
359
360/// Minimum prompt length for the BATCHED cache prime (`prime_cache`). Below this the tokenwise
361/// decode loop wins anyway (the batched path's GEMM dispatch needs m>=16, and the stateful conv
362/// kernel needs T >= d_conv-1). Callers: generate / generate_spec.
363pub const PRIME_MIN_T: usize = 16;
364const PRIME_PIPE_MICROBATCHES: usize = 8;
365const PRIME_PIPE_MIN_CHUNK: usize = 128;
366const PRIME_PIPE_EDGE_MIN_CHUNK: usize = 64;
367const PRIME_PIPE_LINEAR_WORK: usize = 8;
368
369fn prime_pp2_auto_geometry(n_layers: usize) -> bool {
370    crate::pp::prime_pp_on()
371        && !crate::pp::pp2_streams_off()
372        && crate::pp::pp_cuts(n_layers).is_some_and(|cuts| cuts.len() == 3)
373}
374
375/// Effective internal prime chunk. An explicit MEMRA_PRIME_CHUNK is authoritative.
376/// Naked PP-2 primes use the measured pipeline geometry: up to eight microchunks, never
377/// below 128 tokens, while the legacy 4096-token cap remains the long-context bound.
378pub fn prime_chunk_tokens(t: usize, n_layers: usize) -> usize {
379    if let Ok(value) = std::env::var("MEMRA_PRIME_CHUNK") {
380        let parsed = value.parse::<usize>().unwrap_or(crate::cache::PRIME_CHUNK_MAX_TOKENS);
381        return if crate::cache::swa_ring_on() {
382            if parsed == 0 {
383                crate::cache::PRIME_CHUNK_MAX_TOKENS
384            } else {
385                parsed.min(crate::cache::PRIME_CHUNK_MAX_TOKENS)
386            }
387        } else {
388            parsed
389        };
390    }
391    let chunk = crate::cache::PRIME_CHUNK_MAX_TOKENS;
392    if prime_pp2_auto_geometry(n_layers) && t >= 2 * PRIME_PIPE_MIN_CHUNK {
393        chunk.min(
394            t.div_ceil(PRIME_PIPE_MICROBATCHES)
395                .max(PRIME_PIPE_MIN_CHUNK),
396        )
397    } else {
398        chunk
399    }
400}
401
402fn fixed_prime_chunk_ranges(t: usize, chunk: usize) -> Vec<(usize, usize)> {
403    fixed_prime_chunk_ranges_for_ring(t, chunk, crate::cache::swa_ring_on())
404}
405
406fn fixed_prime_chunk_ranges_for_ring(t: usize, chunk: usize, ring_on: bool) -> Vec<(usize, usize)> {
407    if chunk == 0 || t <= chunk {
408        return vec![(0, t)];
409    }
410    let mut ranges = Vec::with_capacity(t.div_ceil(chunk));
411    let mut start = 0usize;
412    while start < t {
413        let mut end = (start + chunk).min(t);
414        if t - end > 0 && t - end < PRIME_MIN_T {
415            if ring_on {
416                let shifted = t - PRIME_MIN_T;
417                end = if shifted > start { shifted } else { t };
418            } else {
419                end = t;
420            }
421        }
422        ranges.push((start, end));
423        start = end;
424    }
425    ranges
426}
427
428fn prime_chunk_work(prefix: usize, total: usize) -> u128 {
429    let prefix = prefix as u128;
430    prefix * (prefix + (PRIME_PIPE_LINEAR_WORK as u128) * (total as u128))
431}
432
433fn dynamic_prime_chunk_ranges(
434    t: usize,
435    fixed_chunk: usize,
436    fixed: &[(usize, usize)],
437) -> Vec<(usize, usize)> {
438    let n = fixed.len();
439    if n < 3 {
440        return fixed.to_vec();
441    }
442
443    let max_first = t - (n - 1) * PRIME_MIN_T;
444    let first = fixed_chunk
445        .div_ceil(2)
446        .max(PRIME_PIPE_EDGE_MIN_CHUNK)
447        .min(max_first);
448    let mut ranges = Vec::with_capacity(n);
449    ranges.push((0, first));
450
451    let first_work = prime_chunk_work(first, t);
452    let work_span = prime_chunk_work(t, t) - first_work;
453    let denominator = (n - 1) as u128;
454    let mut previous = first;
455    for boundary in 1..n - 1 {
456        let target = first_work * denominator + work_span * (boundary as u128);
457        let remaining = n - 1 - boundary;
458        let mut low = previous + PRIME_MIN_T;
459        let mut high = t - remaining * PRIME_MIN_T;
460        while low < high {
461            let mid = low + (high - low) / 2;
462            if prime_chunk_work(mid, t) * denominator >= target {
463                high = mid;
464            } else {
465                low = mid + 1;
466            }
467        }
468        ranges.push((previous, low));
469        previous = low;
470    }
471    ranges.push((previous, t));
472    ranges
473}
474
475/// Internal prime ranges. The naked PP-2 pipeline defaults to a short-fill,
476/// equal-modeled-time schedule; MEMRA_PRIME_CHUNK_SCHED=fixed restores the measured
477/// equal-token ranges. An explicit MEMRA_PRIME_CHUNK always retains fixed semantics.
478pub fn prime_chunk_ranges(t: usize, n_layers: usize) -> Vec<(usize, usize)> {
479    let explicit_chunk = std::env::var_os("MEMRA_PRIME_CHUNK").is_some();
480    let chunk = prime_chunk_tokens(t, n_layers);
481    let fixed = fixed_prime_chunk_ranges(t, chunk);
482    let dynamic = match std::env::var("MEMRA_PRIME_CHUNK_SCHED") {
483        Ok(value) => value == "dynamic",
484        Err(_) => true,
485    };
486    if explicit_chunk || !dynamic || !prime_pp2_auto_geometry(n_layers) {
487        fixed
488    } else {
489        dynamic_prime_chunk_ranges(t, chunk, &fixed)
490    }
491}
492
493impl HybridModel {
494    /// CHUNK-INVARIANCE BISECT SEAM (lane/chunk-invariance): `MEMRA_PRIME_TRACE=<path>`
495    /// appends one JSONL row per (chunk, layer) with a hash of that layer's last-row
496    /// post-residual hidden. Diagnostic only — never on in a measured or gated run
497    /// (it forces a dtoh + host hash per layer).
498    fn prime_trace_path() -> Option<&'static str> {
499        static P: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
500        P.get_or_init(|| std::env::var("MEMRA_PRIME_TRACE").ok())
501            .as_deref()
502    }
503
504    /// Prefill forward over `tokens`; returns logits [T, n_vocab] (host f32).
505    pub fn forward(&self, e: &Engine, tokens: &[u32]) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
506        if self.is_gemma4_e4b() { return self.gemma4_e4b_forward(e, tokens, false); }
507        if self.cfg.gemma4.is_some() { return self.gemma4_forward(e, tokens, false); }
508        let cfg = &self.cfg;
509        let n_embd = cfg.n_embd as usize;
510        let t = tokens.len();
511        let eps = cfg.rms_eps;
512        let pos: Vec<i32> = (0..t as i32).collect();
513        let pos_d = e.htod_i32(&pos)?;
514
515        let mut x = self.embed(e, tokens)?;   // [T, n_embd]
516
517        for (il, layer) in self.layers.iter().enumerate() {
518            // attn_norm
519            let mut h = e.uninit(t * n_embd)?;
520            e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
521
522            let mixed = match &layer.mixer {
523                Mixer::Full(fa) => self.full_attn(e, fa, &h, &pos_d, t, il)?,
524                Mixer::Linear(la) => self.linear_attn(e, la, &h, t)?,
525                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
526            };
527
528            // residual 1
529            let mut x1 = e.uninit(t * n_embd)?;
530            e.add(&x, &mixed, &mut x1, t * n_embd)?;
531
532            // pre-FFN norm (post_attention_norm), FFN (Dense or MoE), residual 2
533            let mut z = e.uninit(t * n_embd)?;
534            e.rms_norm(&x1, layer.post_attn_norm.float_data(), &mut z, n_embd, t, eps)?;
535            let ffn_out = match &layer.ffn {
536                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
537                    let n_ff = ffn_gate.out_features();
538                    let mut g2 = e.matmul_group(&[ffn_gate, ffn_up], &z, t)?;
539                    let up = g2.pop().unwrap();
540                    let gate = g2.pop().unwrap();
541                    let mut act = e.uninit(t * n_ff)?;
542                    // A DENSE FFN reads the SHEXP clamp array: upstream's one `build_ffn` serves
543                    // both the dense MLP and the shared expert, and its limit is
544                    // `swiglu_clamp_shexp[il]` (llama-graph.cpp:1751). step35's leading dense
545                    // blocks 0-2 therefore key off clamp_shexp, not clamp_exp.
546                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
547                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
548                    e.matmul(ffn_down, &act, t)?
549                }
550                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_prefill(e, m, &z, t, il as u16)?,
551            };
552            let mut x2 = e.uninit(t * n_embd)?;
553            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
554            x = x2;
555        }
556
557        let mut hn = e.uninit(t * n_embd)?;
558        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
559        let logits = e.matmul(&self.output, &hn, t)?;
560        Ok(e.dtoh(&logits)?)
561    }
562
563    /// Prefill that returns ONLY the last token's logits — the common case (greedy/sample needs
564    /// just the final position to start decode). Runs the trunk over all T, then the lm_head
565    /// (output.weight, the largest matrix — 248320 rows) on the LAST hidden row ONLY, not all T.
566    /// On a 512-token prompt this turns a [512,248320] GEMM into [1,248320] — the dominant prefill
567    /// cost (nsys: ~99ms when done for all T). Bit-identical last-row logits to forward()[last].
568    pub fn forward_last(&self, e: &Engine, tokens: &[u32]) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
569        if self.cfg.gemma4.is_some() { return self.gemma4_forward(e, tokens, true); }
570        let cfg = &self.cfg;
571        let n_embd = cfg.n_embd as usize;
572        let t = tokens.len();
573        let eps = cfg.rms_eps;
574        let pos: Vec<i32> = (0..t as i32).collect();
575        let pos_d = e.htod_i32(&pos)?;
576
577        let mut x = self.embed(e, tokens)?;   // [T, n_embd]
578        // MEMRA_LAYER_PROBE=1: synchronize + print after every stage — bisects an in-graph
579        // ILLEGAL_ADDRESS to (layer, stage) at ~1 line of output per layer (M3 bring-up tool).
580        let probe = std::env::var("MEMRA_LAYER_PROBE").is_ok();
581        for (il, layer) in self.layers.iter().enumerate() {
582            let mut h = e.uninit(t * n_embd)?;
583            e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
584            if probe { e.stream().synchronize()?; eprintln!("[probe] L{il} norm ok"); }
585            let mixed = match &layer.mixer {
586                Mixer::Full(fa) => self.full_attn(e, fa, &h, &pos_d, t, il)?,
587                Mixer::Linear(la) => self.linear_attn(e, la, &h, t)?,
588                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
589            };
590            if probe { e.stream().synchronize()?; eprintln!("[probe] L{il} mixer ok"); }
591            let mut x1 = e.uninit(t * n_embd)?;
592            e.add(&x, &mixed, &mut x1, t * n_embd)?;
593            let mut z = e.uninit(t * n_embd)?;
594            e.rms_norm(&x1, layer.post_attn_norm.float_data(), &mut z, n_embd, t, eps)?;
595            let ffn_out = match &layer.ffn {
596                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
597                    let n_ff = ffn_gate.out_features();
598                    let mut g2 = e.matmul_group(&[ffn_gate, ffn_up], &z, t)?;
599                    let up = g2.pop().unwrap();
600                    let gate = g2.pop().unwrap();
601                    let mut act = e.uninit(t * n_ff)?;
602                    // dense FFN keys off the SHEXP clamp array — see forward()'s note.
603                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
604                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
605                    e.matmul(ffn_down, &act, t)?
606                }
607                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_prefill(e, m, &z, t, il as u16)?,
608            };
609            if probe { e.stream().synchronize()?; eprintln!("[probe] L{il} ffn ok"); }
610            let mut x2 = e.uninit(t * n_embd)?;
611            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
612            x = x2;
613        }
614        // norm over all T, then slice the LAST row and run lm_head on that single row.
615        let mut hn = e.uninit(t * n_embd)?;
616        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
617        let last = e.view(&hn, t * n_embd);            // [T, n_embd]
618        let last_row = last.slice((t - 1) * n_embd..t * n_embd);  // [1, n_embd]
619        let mut hlast = e.uninit(n_embd)?;
620        e.copy_view_into(&mut hlast, 0, &last_row, n_embd)?;
621        let logits = e.matmul(&self.output, &hlast, 1)?;   // [1, n_vocab] — lm_head on ONE row
622        Ok(e.dtoh(&logits)?)
623    }
624
625    /// BATCHED PROMPT PRIME (the measured #1 e2e gap, e2e-image-1): `forward_last`'s batched
626    /// prefill body EXTENDED to leave a DECODE-READY cache behind — vs the tokenwise prime's
627    /// ~102/38 tok/s (9B/27B) decode_step loop, this runs the whole prompt at prefill throughput.
628    ///   (a) full-attn layers append their T post-RoPE K/V rows into `cache.kv[il]` via the SAME
629    ///       per-row quantize kernel as the decode append (bit-identical cache bytes per row);
630    ///   (b) linear layers run STATEFULLY from the cache's current recurrent state (zero at a
631    ///       fresh prime): carried-ring conv (ssm_conv1d_tm_state) + ONE gdn_scan(state_in,
632    ///       state_out) whose internal sequential t-loop equals T chained T=1 steps — but with
633    ///       the NORMAL prefill matmul dispatch (GEMM at m>=16), NOT the decode-exact MMVQ the
634    ///       spec verify uses (prime is a prefill-regime pass; the run-gen prefill==decode
635    ///       argmax gate is the accuracy authority, exactly as for forward_last);
636    ///   (c) `cache.pos`/KV len/len_d advance by T.
637    /// Returns (last-row logits host, h_seed = last-row PRE-output_norm hidden [n_embd],
638    /// hiddens = the full pre-output_norm hidden stack [T, n_embd] — generate_spec's prompt_h).
639    /// FRESH-PROMPT ONLY (cache.pos == 0): the fa_prefill tiles attend within `tokens` alone.
640    /// forward_last itself stays untouched (kernel-check / run-gen gate on it).
641    ///
642    /// `queued_after` (lane/tick-seg, 2026-08-07): the number of prompt tokens of the SAME
643    /// REQUEST that the caller will prime in LATER calls — 0 when this call is the whole
644    /// request (every single-shot caller). Serve splits a long prompt across SEVERAL
645    /// prime_cache calls (one per scheduler tick, plus the prefix-cache LCP split), and the
646    /// request's absolute end position `seq_end = cache.pos + t + queued_after` steers step35's
647    /// SWA prefill arm — computing it per CALL made the arm a function of the tick budget
648    /// (budgets 512/256/64 DIFFER 1.813e0 vs monolithic, greedy diverging at step 6; dark lanes
649    /// default to 256 AND cap by live SLO headroom, so identical judge requests primed
650    /// differently under load — research/tick-seg-20260807, receipt in
651    /// research/step35-chunkfix-20260807 §9). The parameter is what prime_cache structurally
652    /// lacked: it cannot know from `tokens` and `cache` alone whether more of the request is
653    /// coming. A SESSION CONTINUATION (a NEW user turn primed onto a live cache) is a NEW
654    /// request — its arithmetic is keyed to its own extent, so those callers pass 0; only a
655    /// caller that SPLITS one request across calls passes the remainder.
656    pub fn prime_cache(&self, e: &Engine, tokens: &[u32], cache: &mut Cache, queued_after: usize)
657                       -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
658        let n_embd = self.cfg.n_embd as usize;
659        let t = tokens.len();
660        // SESSION CONTINUATION (2026-07-05): cache.pos > 0 = priming a NEW SUFFIX onto a live
661        // session cache — every chunk (including the first) takes the continuation arm
662        // (fa_prefill_view over the quantized past + this chunk). Fresh prime (pos==0) unchanged.
663        assert!(t >= PRIME_MIN_T, "prime_cache needs T >= {PRIME_MIN_T} (caller gates)");
664        assert!(cache.pos + t <= cache.max_ctx, "prime_cache: prompt exceeds cache max_ctx");
665
666        // CHUNKED PRIME (2026-07-05, the long-ctx OOM fix): the monolithic prime allocates
667        // per-layer transients proportional to T (gate/up/act = T*n_ff*4B EACH — 1.5GB apiece at
668        // 16k on the 27B), which OOMs a 24GB card around 16k prompt tokens. Chunk the prompt:
669        // each chunk runs the full layer stack with transients sized to the chunk, appending its
670        // K/V to the resident quantized cache and carrying the GDN conv-ring + recurrent state
671        // through `cache.recur` (linear_attn_prime is already stateful — a chunk boundary is
672        // exactly the state carry it was built for). Full-attn chunks after the first attend to
673        // the QUANTIZED past KV via fa_prefill_view (the spec-verify pattern) — same numeric
674        // class as decode reading the cache. Prompts <= one chunk take the ORIGINAL monolithic
675        // body byte-for-byte (chunk 0 short-circuits to the f32 fa_prefill path).
676        // MEMRA_PRIME_CHUNK sets the chunk size (tokens); 0 disables chunking (monolithic).
677        if self.is_gemma4_e4b() {
678            return self.gemma4_e4b_prime(e, tokens, cache);
679        }
680        if self.cfg.gemma4.is_some() {
681            // gemma4 v0: monolithic fresh-prompt prime (chunked/continuation arms later).
682            return self.gemma4_prime(e, tokens, cache);
683        }
684        let ranges = prime_chunk_ranges(t, self.layers.len());
685        // CHUNK-ORDER INVARIANCE (lane/chunk-invariance, 2026-08-05; vLLM #38561 shape).
686        // MEMRA_PRIME_CHUNK is documented as a memory-transient knob, but it also decides
687        // the prefill's ARITHMETIC, so two rigs with different values produced different
688        // greedy text for the same prompt (research/session-affinity-20260805: 97- and
689        // 149-token prompts). ROOT CAUSE, measured in research/chunk-invariance-20260805
690        // (VERDICT.md) — and it is NOT what docs originally said:
691        //   * NOT trunk GEMM m / reduction order. REFUTED: the prefill GEMM is m-INVARIANT
692        //     (rows [0,32) bit-identical at m=32 vs m=33..80, both quantized wq and the
693        //     output head), so growing a chunk cannot move an existing row's value.
694        //   * NOT the GDN scan segmentation. REFUTED: MEMRA_GDN_CHUNKED=0 (sequential scan,
695        //     no WY segmentation at all) still diverges, so vLLM's mamba-boundary fix does
696        //     not describe our leak.
697        //   * IT IS the attention numeric CLASS edge in full_attn_prime_fa_dispatch, which
698        //     selects on `base_len == 0`: chunk 0 attends over this batch's f32 K/V
699        //     (fa_prefill) while every later chunk attends over the q8_0/q5_1 quantized KV
700        //     cache (fa_prefill_view_ws). The chunk size therefore decides WHERE in the
701        //     prompt that precision edge falls. Signature: per-row maxdiff is exactly 0.0
702        //     before the first boundary and O(1) right after, first_div_pos == chunk size.
703        // The grain-free fix (full_attn_prime_fa_dispatch below) removed that class edge at
704        // the source — every row is in one numeric class, so the chunk size no longer steers
705        // arithmetic and MEMRA_PRIME_CHUNK is a pure memory/transient knob again. The interim
706        // MEMRA_PRIME_INVARIANT/MEMRA_PRIME_GRAIN pin-the-boundary door was superseded by that
707        // fix and KILLED at v0.71 per the flags doctrine (the jsonl + VERDICT.md are the
708        // record); the chunkinv gate asserts byte-identity across chunk sizes naked.
709        // The REQUEST's absolute end position, computed ONCE before the loop: every chunk sees the
710        // same value, whatever the chunk size. step35's SWA arm selects on it so that kernel
711        // selection — and therefore the logits — cannot depend on MEMRA_PRIME_CHUNK
712        // (research/step35-chunkfix-20260807; see step35_attn_pre_wo's doc note).
713        // `+ queued_after` closes the SECOND axis (lane/tick-seg): when serve splits the request
714        // across calls, the request still ends at the same absolute position, whatever the tick
715        // budget or LCP split point. MEMRA_PRIME_CALLLOCAL=1 is the ROLLBACK SEAM to the FULL
716        // pre-fix arithmetic: the per-call value here AND the unaligned FA view offset in
717        // step35_attn_pre_wo. Both halves are required for tickinv35's canary teeth under the FA
718        // default. Read per call, not cached (the probe flips it in-process between arms). Never
719        // on in a measured default run.
720        let legacy_calllocal =
721            std::env::var("MEMRA_PRIME_CALLLOCAL").as_deref() == Ok("1");
722        let seq_end = if legacy_calllocal {
723            cache.pos + t
724        } else {
725            cache.pos + t + queued_after
726        };
727        if ranges.len() == 1 {
728            return self.prime_chunk(e, tokens, cache, seq_end);
729        }
730        // PIPELINED PP-2 PRIME (lane/cx-pipeline-prime, 2026-08-08): overlap stage 0 of
731        // chunk N+1 with stage 1 of chunk N. The serial split stays reachable through
732        // MEMRA_PRIME_PIPE=0 and is the exactness oracle. N>2 keeps the serial walker;
733        // this lane owns the balanced two-stage schedule only.
734        if crate::pp::prime_pipe_on()
735            && crate::pp::prime_pp_on()
736            && !crate::pp::pp2_streams_off()
737        {
738            if let Some(fence) = crate::pp::pp_cuts(self.layers.len()).filter(|f| f.len() == 3) {
739                if crate::pp::pp_multi_stream_same_device() {
740                    return Err(
741                        "prime chunk pipeline refused with 2 stage streams on one device — \
742                         that concurrent-stream placement remains quarantined by the deferred \
743                         pp flake record. Use one device per stage or MEMRA_PRIME_PIPE=0 for \
744                         the serial split."
745                            .into(),
746                    );
747                }
748                return self.prime_cache_pp2_pipelined(
749                    e, tokens, cache, seq_end, &ranges, &fence,
750                );
751            }
752        }
753        let mut hiddens = e.uninit(t * n_embd)?;
754        let mut last: Option<(Vec<f32>, CudaSlice<f32>)> = None;
755        for &(start, end) in &ranges {
756            let (l, hs, x) = self.prime_chunk(e, &tokens[start..end], cache, seq_end)?;
757            e.copy_into(&mut hiddens, start * n_embd, &x, (end - start) * n_embd)?;
758            last = Some((l, hs));
759        }
760        let (logits, h_seed) = last.unwrap();
761        Ok((logits, h_seed, hiddens))
762    }
763
764    /// PP-2 chunk scheduler: stage 1 of chunk N and stage 0 of chunk N+1 are both queued
765    /// before N's epilogue D2H drains the last-stage stream. Arithmetic is unchanged:
766    /// every chunk still runs the same two `prime_layers` ranges, boundary copy, output
767    /// norm, lm head, and caller hidden-stack copy as the serial split.
768    fn prime_cache_pp2_pipelined(
769        &self,
770        e: &Engine,
771        tokens: &[u32],
772        cache: &mut Cache,
773        seq_end: usize,
774        ranges: &[(usize, usize)],
775        fence: &[usize],
776    ) -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
777        debug_assert_eq!(fence.len(), 3);
778        debug_assert!(ranges.len() >= 2);
779        let rt = crate::pp::PpNRt::get(e)?;
780        assert_eq!(rt.n_stages(), 2, "prime pipeline requires exactly two PP stages");
781        let n_embd = self.cfg.n_embd as usize;
782        let t = tokens.len();
783        let initial_base = cache.pos;
784        let caller_stream = e.stream();
785
786        // #87 reverse publication before any new stage allocation, then prewarm both
787        // boundary slots while the stage streams are otherwise empty. Lazy-growing slot B
788        // after stage 1(N) is queued would synchronize that stream and erase the first
789        // overlap on a two-chunk prompt.
790        rt.fence_stages_behind(&caller_stream)?;
791        let max_payload = ranges
792            .iter()
793            .map(|(s, e)| (e - s) * n_embd)
794            .max()
795            .unwrap();
796        rt.prepare_overlap_slots(0, max_payload)?;
797
798        let mut hiddens = e.uninit(t * n_embd)?;
799        let mut last: Option<(Vec<f32>, CudaSlice<f32>)> = None;
800        let mut stage_caches = PrimeCacheStages::new(cache, fence[1]);
801        let (cache0, cache1) = stage_caches.parts();
802        let (first_start, first_end) = ranges[0];
803        let mut slot = self.prime_pp2_stage0_enqueue(
804            e,
805            rt,
806            &tokens[first_start..first_end],
807            cache0,
808            seq_end,
809            fence,
810            initial_base + first_start,
811            true,
812        )?;
813        cache0.pos = initial_base + first_end;
814
815        for (i, &(start, end)) in ranges.iter().enumerate() {
816            let base = initial_base + start;
817            debug_assert_eq!(
818                cache1.pos, base,
819                "stage 1 must drain chunks in original position order"
820            );
821            let (out, next_slot) = if let Some(&(next_start, next_end)) = ranges.get(i + 1) {
822                let next_base = initial_base + next_start;
823                debug_assert_eq!(
824                    cache0.pos, next_base,
825                    "stage 0 must issue chunks in original position order"
826                );
827                let cache0_stage = &mut *cache0;
828                // Step's MoE router readback synchronizes once per layer. Two CUDA streams
829                // on one host thread therefore serialize even if the calls are ordered as
830                // a pipeline. Drive the disjoint stage caches from two scoped host threads:
831                // stage 1 consumes slot N while stage 0 produces slot N+1.
832                std::thread::scope(
833                    |scope| -> Result<_, Box<dyn std::error::Error>> {
834                        let stage0 = scope.spawn(move || -> Result<usize, String> {
835                            let next = self
836                                .prime_pp2_stage0_enqueue(
837                                    e,
838                                    rt,
839                                    &tokens[next_start..next_end],
840                                    cache0_stage,
841                                    seq_end,
842                                    fence,
843                                    next_base,
844                                    true,
845                                )
846                                .map_err(|err| err.to_string())?;
847                            cache0_stage.pos = initial_base + next_end;
848                            Ok(next)
849                        });
850                        let x = self.prime_pp2_stage1_enqueue(
851                            e,
852                            rt,
853                            slot,
854                            end - start,
855                            cache1,
856                            seq_end,
857                            fence,
858                            base,
859                            true,
860                        )?;
861                        let out = {
862                            rt.bind_stage(1)?;
863                            let _st1 = rt.enter(1);
864                            let e1 = rt.engine(1, e);
865                            self.prime_chunk_epilogue(e1, x, end - start, cache1)?
866                        };
867                        let next = stage0
868                            .join()
869                            .map_err(|_| "pipeprime stage-0 host walker panicked")?
870                            .map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
871                        Ok((out, Some(next)))
872                    },
873                )?
874            } else {
875                let x = self.prime_pp2_stage1_enqueue(
876                    e,
877                    rt,
878                    slot,
879                    end - start,
880                    cache1,
881                    seq_end,
882                    fence,
883                    base,
884                    true,
885                )?;
886                let out = {
887                    rt.bind_stage(1)?;
888                    let _st1 = rt.enter(1);
889                    let e1 = rt.engine(1, e);
890                    self.prime_chunk_epilogue(e1, x, end - start, cache1)?
891                };
892                (out, None)
893            };
894
895            rt.publish_to(1, &caller_stream)?;
896            e.copy_into(
897                &mut hiddens,
898                start * n_embd,
899                &out.2,
900                (end - start) * n_embd,
901            )?;
902            last = Some((out.0, out.1));
903            crate::pp::PRIME_SPLIT_CHUNKS
904                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
905
906            if let Some(next) = next_slot {
907                // The caller copy above reads a stage-1 allocation. Before stage 1 of the
908                // next chunk can allocate/reuse blocks, mirror #87's body-entry fence.
909                // Stage 0(N+1) is already queued before this wait is appended, so its
910                // overlap with stage 1(N) is preserved.
911                rt.fence_stages_behind(&caller_stream)?;
912                slot = next;
913            }
914        }
915
916        debug_assert_eq!(cache0.pos, initial_base + t);
917        debug_assert_eq!(cache1.pos, initial_base + t);
918        let (logits, h_seed) = last.unwrap();
919        Ok((logits, h_seed, hiddens))
920    }
921
922    /// One prime chunk: the full layer stack over `tokens`, continuing from the cache's current
923    /// state (`cache.pos` = tokens already primed; 0 = fresh). Positions/RoPE are absolute
924    /// task #21 de-broadcast: the q/k head count PREP must emit so the scan's consumers
925    /// agree. Compact (num_k) ONLY when the scan will take the chunked+mma route AND
926    /// num_k == num_v/2 (the engine-side hint mirrors this exact formula); everything
927    /// else (s128 verify tier, chunked-off, mma-off) keeps the broadcast layout.
928    fn gdn_hk(e: &Engine, t: usize, num_v: usize, num_k: usize) -> usize {
929        if Engine::gdn_db_on()
930            && Engine::gdn_chunked_enabled() && t >= 16
931            && e.gdn_mma_enabled(Engine::gdn_chunk_size())
932            && num_k * 2 == num_v
933        {
934            num_k
935        } else {
936            num_v
937        }
938    }
939
940    /// task #17: gate for the fused fp16-operand epilogues (silu_mul/gated_rmsnorm/sig_mul
941    /// `_f16out` twins). Bit-identical class (the twins emit the cvt kernel's exact halves),
942    /// but seam-gated (MEMRA_F16OUT=0) so a bit-check can arbitrate, and OFF under verify-exact
943    /// (matmul_group skips the f16 lane there; the twins must not resurrect it).
944    fn f16out_on(e: &Engine, t: usize) -> bool {
945        crate::f16_ffi::pp_f16_enabled() && t >= 16 && !e.verify_exact_on()
946            && std::env::var("MEMRA_F16OUT").as_deref() != Ok("0")
947    }
948
949    /// (cache.pos + i). Returns (last-row logits, h_seed, this chunk's hidden stack [T, n_embd]).
950    /// See HybridModel::prime_slabs — the eager prime's resident trunk transients.
951    /// PER-DEVICE since lane/pp-leverb (2026-08-08): the map is keyed by the allocating
952    /// engine's CUDA ordinal — under the prime stage split each stage's range walks through
953    /// its OWN slabs on its own device (a dev0 slab dereferenced by a dev1 kernel would be
954    /// a peer read per GEMM operand, the exact class Lever B removes). Single-device rigs
955    /// see one entry, byte-identical behavior.
956    pub fn prime_slabs_get(
957        &self,
958        e: &Engine,
959        t: usize,
960        n_embd: usize,
961        n_ff_max: usize,
962    ) -> Result<std::sync::Arc<std::sync::Mutex<PrimeSlabs>>, Box<dyn std::error::Error>> {
963        let mut slabs = self.prime_slabs.lock().unwrap();
964        let dev = e.ctx().ordinal();
965        let need_new = match slabs.get(&dev) {
966            None => true,
967            Some(sl) => sl.lock().unwrap().t_cap < t,
968        };
969        if need_new {
970            slabs.insert(dev, std::sync::Arc::new(std::sync::Mutex::new(PrimeSlabs {
971                t_cap: t,
972                h: e.uninit(t * n_embd)?,
973                x1: e.uninit(t * n_embd)?,
974                z: e.uninit(t * n_embd)?,
975                act: e.uninit(t * n_ff_max)?,
976                xa: e.uninit(t * n_embd)?,
977                xb: e.uninit(t * n_embd)?,
978                h16: e.alloc_u8_uninit(t * n_embd * 2)?,
979                z16: e.alloc_u8_uninit(t * n_embd * 2)?,
980                gate: e.uninit(t * n_ff_max)?,
981                up: e.uninit(t * n_ff_max)?,
982                ffn_out: e.uninit(t * n_embd)?,
983                seg_glue: Vec::new(),
984                mixed: e.uninit(t * n_embd)?,
985                seg_mid: Vec::new(),
986                seg_t: 0,
987            })));
988        }
989        Ok(slabs.get(&dev).expect("prime slab inserted").clone())
990    }
991
992    /// `seq_end` = the whole REQUEST's absolute end position (`cache.pos + prompt_len` at
993    /// `prime_cache` entry), NOT this chunk's end. Chunk-size-invariant by construction; step35's
994    /// SWA arm selects on it (see `step35_attn_pre_wo`). Every other arch ignores it.
995    fn prime_chunk(&self, e: &Engine, tokens: &[u32], cache: &mut Cache, seq_end: usize)
996                       -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
997        // LEVER B (lane/pp-leverb, 2026-08-08): the ppN door for the chunked prime. With the
998        // door open + per-stage streams, each chunk walks its layer ranges on the OWNING
999        // stage's engine/device (the anatomy receipt this kills: dev1 ran ZERO prefill
1000        // kernels; stage-1 trunk weights were peer-read = 22% of the pp4096 wall).
1001        // MEMRA_PRIME_PP=0 = the unsplit rollback (also the prime-split-gate's reference
1002        // arm — prime deliberately keeps NO refuse_unsplit_if_remote, see pp.rs). The
1003        // MEMRA_PP_STREAMS=0 seam keeps the unsplit walk too: in that regime the sharded
1004        // loader is off and there is nothing remote to split for.
1005        if self.cfg.gemma4.is_none()
1006            && !crate::pp::pp2_streams_off()
1007            && crate::pp::prime_pp_on()
1008        {
1009            if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
1010                return self.prime_chunk_ppn(e, tokens, cache, seq_end, &fence);
1011            }
1012        }
1013        let t = tokens.len();
1014        let base = cache.pos;
1015        debug_assert!(seq_end >= base + t, "prime_chunk: seq_end must cover this chunk");
1016        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1017        let pos_d = e.htod_i32(&pos)?;
1018
1019        let x_embed = self.embed(e, tokens)?;   // [T, n_embd]
1020        let x = self.prime_layers(
1021            e, x_embed, 0, self.layers.len(), &pos_d, t, base, cache, seq_end,
1022        )?;
1023        self.prime_chunk_epilogue(e, x, t, cache)
1024    }
1025
1026    /// PRIME RANGE SUBGRAPH (lane/pp-leverb, 2026-08-08): layers `[lo, hi)` of the chunked
1027    /// prime walk — `prime_chunk`'s trunk loop extracted verbatim to the
1028    /// `decode_layers_eager(lo, hi)` / `verify_layers(lo, hi)` contract: enters with a
1029    /// MATERIALIZED `[T, n_embd]` residual, exits with the range's final residual
1030    /// materialized (cloned out of the slab). At `lo=0, hi=n_layers` — the unsplit call —
1031    /// the launch sequence is byte-identical to the pre-extraction body. Range semantics:
1032    ///   - the cross-layer [down-add + NEXT attn-norm] fusion is range-LOCAL (`il + 1 < hi`):
1033    ///     layer `hi`'s attn_norm belongs to the NEXT stage's device, so the range ends with
1034    ///     the plain add (materialize) and the next stage hoists its own first norm — the
1035    ///     kernel-check-pinned `add_rms_norm == add then rms_norm` identity, the same law
1036    ///     the decode split rests on (`prime-split-gate` arbitrates end-to-end);
1037    ///   - prime slabs are PER-DEVICE (`prime_slabs_get` keys on the engine ordinal), so
1038    ///     each stage walks through its own resident transients;
1039    ///   - the S-glue/S-mid capture path requires the FULL range (its lookahead fuses
1040    ///     `self.layers[il+1]` unconditionally) — `use_seg` gains `lo == 0 && hi == n_layers`.
1041    #[allow(clippy::too_many_arguments)]
1042    fn prime_layers(&self, e: &Engine, x_in: CudaSlice<f32>, lo: usize, hi: usize,
1043                    pos_d: &CudaSlice<i32>, t: usize, base: usize, cache: &mut Cache,
1044                    seq_end: usize)
1045                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1046        let cfg = &self.cfg;
1047        let n_embd = cfg.n_embd as usize;
1048        let eps = cfg.rms_eps;
1049        // task #14: fuse the fp16 GEMM-operand emission into the trunk norms (kills the
1050        // standalone convert launches). Only when the f16 lane serves and T reaches the
1051        // GEMM tier; bit-identical either way.
1052        let f16fuse = crate::f16_ffi::pp_f16_enabled() && t >= 16;
1053        // PRIME SLABS (piecewise foundation): trunk transients in resident buffers —
1054        // ~224 fewer alloc/free calls per prime and FROZEN Lt operand addresses
1055        // (nvjet's alignment-variant selection becomes run-to-run stable). Every slab is
1056        // fully overwritten before use; x ping-pongs xa<->xb; the hidden-stack return
1057        // clones the final x (the slab cannot leave). Non-slab fallback: MEMRA_PRIME_SLABS=0.
1058        let n_ff_max = self.layers.iter().map(|l| match &l.ffn {
1059            crate::hybrid::Ffn::Dense { ffn_gate, .. } => ffn_gate.out_features(),
1060            _ => n_embd,
1061        }).max().unwrap_or(n_embd).max(n_embd);
1062        let use_slabs = std::env::var("MEMRA_PRIME_SLABS").as_deref() != Ok("0");
1063        let slab = if use_slabs {
1064            Some(self.prime_slabs_get(e, t, n_embd, n_ff_max)?)
1065        } else {
1066            None
1067        };
1068        let mut slab_guard = slab.as_ref().map(|sl| sl.lock().unwrap());
1069        let mut x_own;   // fallback storage when slabs are off
1070        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>);
1071        let (mut x_cur, mut x_nxt, sl): (&mut CudaSlice<f32>, &mut CudaSlice<f32>, Option<SlabRefs>);
1072        let mut seg: Option<(&mut Vec<Option<cudarc::driver::CudaGraph>>, &mut Vec<Option<cudarc::driver::CudaGraph>>, &mut CudaSlice<f32>, &mut usize)> = None;
1073        let mut x_own2;
1074        match slab_guard.as_mut() {
1075            Some(g) => {
1076                let slabs = &mut **g;
1077                e.copy_into(&mut slabs.xa, 0, &x_in, t * n_embd)?;
1078                let PrimeSlabs { xa, xb, h, x1, z, act, h16, z16, gate, up, ffn_out, seg_glue, mixed, seg_mid, seg_t, .. } = slabs;
1079                x_cur = xa;
1080                x_nxt = xb;
1081                seg = Some((seg_glue, seg_mid, mixed, seg_t));
1082                sl = Some((h, x1, z, act, h16, z16, gate, up, ffn_out));
1083            }
1084            None => {
1085                x_own = x_in;
1086                x_own2 = e.uninit(t * n_embd)?;
1087                x_cur = &mut x_own;
1088                x_nxt = &mut x_own2;
1089                sl = None;
1090            }
1091        }
1092        let mut alloc_h; let mut alloc_x1; let mut alloc_z; let mut alloc_act;
1093        let mut alloc_h16; let mut alloc_z16;
1094        let mut alloc_gate; let mut alloc_up; let mut alloc_fo;
1095        let (h, x1, z, act): (&mut CudaSlice<f32>, &mut CudaSlice<f32>, &mut CudaSlice<f32>, &mut CudaSlice<f32>);
1096        let (h16, z16): (&mut CudaSlice<u8>, &mut CudaSlice<u8>);
1097        let (sl_gate, sl_up, sl_fo): (&mut CudaSlice<f32>, &mut CudaSlice<f32>, &mut CudaSlice<f32>);
1098        match sl {
1099            Some((a, b, c, d, e16, f16b, g, u, fo)) => {
1100                h = a; x1 = b; z = c; act = d; h16 = e16; z16 = f16b;
1101                sl_gate = g; sl_up = u; sl_fo = fo;
1102            }
1103            None => {
1104                alloc_h = e.uninit(t * n_embd)?;
1105                alloc_x1 = e.uninit(t * n_embd)?;
1106                alloc_z = e.uninit(t * n_embd)?;
1107                alloc_act = e.uninit(t * n_ff_max)?;
1108                alloc_h16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1109                alloc_z16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1110                alloc_gate = e.uninit(t * n_ff_max)?;
1111                alloc_up = e.uninit(t * n_ff_max)?;
1112                alloc_fo = e.uninit(t * n_embd)?;
1113                h = &mut alloc_h; x1 = &mut alloc_x1; z = &mut alloc_z; act = &mut alloc_act;
1114                h16 = &mut alloc_h16; z16 = &mut alloc_z16;
1115                sl_gate = &mut alloc_gate; sl_up = &mut alloc_up; sl_fo = &mut alloc_fo;
1116            }
1117        }
1118        // piecewise increment 3: layer-0 norm hoisted; the per-layer tail fuses
1119        // [down-add + NEXT layer's attn-norm] into one captured S-glue segment
1120        // (all-slab IO, zero in-graph allocations). Capture happens lazily on the
1121        // first prime at this t (capture does not execute -> launch right after).
1122        let n_layers = self.layers.len();
1123        // OPT-IN (2026-07-26 interleaved verdict): 2-kernel segments measured NET
1124        // -0.7%-to-neutral under the interleaved A/B protocol — one cuGraphLaunch costs
1125        // about what two kernel submissions do. The earlier "+0.9%" was cross-run clock
1126        // drift (the repo's interleaved-A/B law exists for exactly this). Larger segments
1127        // (S-prep/S-attn, 7-9 kernels) remain the open hypothesis; the core-split
1128        // machinery stays (byte-identical) as their foundation.
1129        // step35 is excluded: the core-split path calls `full_attn_prime_core_inner`, which is
1130        // the GENERIC attn core (uniform n_head, rope_dim_count, no window, no head-wise gate).
1131        // step35 rides its own mixer through the normal per-layer arm below.
1132        let use_seg = f16fuse && seg.is_some() && self.cfg.step35.is_none()
1133            && lo == 0 && hi == n_layers
1134            && std::env::var("MEMRA_PRIME_SEG").as_deref() == Ok("1");
1135        if let Some((sg, sm, _, st)) = seg.as_mut() {
1136            if **st != t {
1137                sg.clear();
1138                sg.extend((0..n_layers).map(|_| None));
1139                sm.clear();
1140                sm.extend((0..n_layers).map(|_| None));
1141                **st = t;
1142            }
1143        }
1144        {
1145            let layer_lo = &self.layers[lo];
1146            if f16fuse {
1147                e.rms_norm_f16out(x_cur, layer_lo.attn_norm.float_data(), h, h16, n_embd, t, eps)?;
1148            } else {
1149                e.rms_norm(x_cur, layer_lo.attn_norm.float_data(), h, n_embd, t, eps)?;
1150            }
1151        }
1152        for il in lo..hi {
1153            let layer = &self.layers[il];
1154            let hx16 = if f16fuse { Some(&*h16) } else { None };
1155            if use_seg {
1156                // core-split path: projections -> _inner core -> out-GEMM INTO the mixed
1157                // slab (no copies) -> S-mid segment [add + post-norm] as one graph launch.
1158                let (pre, pre16, w_out) = match &layer.mixer {
1159                    Mixer::Full(fa) => {
1160                        let g3 = match hx16 {
1161                            Some(xh) => e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], h, xh, t)?,
1162                            None => e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?,
1163                        };
1164                        let (pre, pre16) = self.full_attn_prime_core_inner(e, fa, g3, &pos_d, t, cache, il)?;
1165                        (pre, pre16, &fa.wo)
1166                    }
1167                    Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1168                    Mixer::Linear(la) => {
1169                        let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
1170                        let g4 = match hx16 {
1171                            Some(xh) => e.matmul_group_xh(&ws, h, xh, t)?,
1172                            None => e.matmul_group(&ws, h, t)?,
1173                        };
1174                        let (pre, pre16) = self.linear_attn_prime_core_pad_inner(e, la, g4, t, cache, il, None)?;
1175                        (pre, pre16, &la.ssm_out)
1176                    }
1177                };
1178                {
1179                    let (_, sm, mslab, _) = seg.as_mut().unwrap();
1180                    let pre_n = pre.len() / t;
1181                    let xh_pre = match pre16 {
1182                        Some(x) => x,
1183                        None => e.f16_act(&pre, t * pre_n, pre_n)?,
1184                    };
1185                    if !e.try_f16_gemm_pre_into(w_out, &xh_pre, t, mslab)? {
1186                        let y = e.matmul(w_out, &pre, t)?;
1187                        e.copy_into(mslab, 0, &y, t * n_embd)?;
1188                    }
1189                    if sm[il].is_none() {
1190                        use cudarc::driver::sys::{CUgraphInstantiate_flags, CUstreamCaptureMode};
1191                        let w_post = layer.post_attn_norm.float_data();
1192                        e.stream().synchronize()?;
1193                        e.stream().begin_capture(CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_RELAXED)?;
1194                        let r = (|| -> Result<(), Box<dyn std::error::Error>> {
1195                            e.add(x_cur, mslab, x1, t * n_embd)?;
1196                            e.rms_norm_f16out(x1, w_post, z, z16, n_embd, t, eps)?;
1197                            Ok(())
1198                        })();
1199                        let g = e.stream().end_capture(
1200                            CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH);
1201                        r?;
1202                        sm[il] = Some(g?.ok_or("S-mid capture produced no graph")?);
1203                    }
1204                    sm[il].as_ref().unwrap().launch()?;
1205                }
1206            } else {
1207                let mixed = match &layer.mixer {
1208                    Mixer::Full(fa) => self.full_attn_prime(e, fa, h, hx16, &pos_d, t, cache, il,
1209                                                            seq_end)?,
1210                    Mixer::Linear(la) => self.linear_attn_prime(e, la, h, hx16, t, cache, il)?,
1211                    Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1212                };
1213                if f16fuse {
1214                    // round 28: residual+norm in ONE kernel (add_rms_norm precedent,
1215                    // bit-identical) — the standalone add pass disappears.
1216                    e.add_rms_norm_f16out(x_cur, &mixed, layer.post_attn_norm.float_data(),
1217                                          x1, z, z16, n_embd, t, eps)?;
1218                } else {
1219                    e.add(x_cur, &mixed, x1, t * n_embd)?;
1220                    e.rms_norm(x1, layer.post_attn_norm.float_data(), z, n_embd, t, eps)?;
1221                }
1222            }
1223            let zx16 = if f16fuse { Some(&*z16) } else { None };
1224            match &layer.ffn {
1225                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1226                    let n_ff = ffn_gate.out_features();
1227                    // gate/up INTO boundary slabs (piecewise increment 2); fall back to
1228                    // the allocating group + copy when a mirror is missing.
1229                    let mut into_ok = false;
1230                    if let Some(xh) = zx16 {
1231                        into_ok = e.try_f16_gemm_pre_into(ffn_gate, xh, t, sl_gate)?
1232                            && e.try_f16_gemm_pre_into(ffn_up, xh, t, sl_up)?;
1233                    }
1234                    if !into_ok {
1235                        let mut g2 = match zx16 {
1236                            Some(xh) => e.matmul_group_xh(&[ffn_gate, ffn_up], z, xh, t)?,
1237                            None => e.matmul_group(&[ffn_gate, ffn_up], z, t)?,
1238                        };
1239                        let up_y = g2.pop().unwrap();
1240                        let gate_y = g2.pop().unwrap();
1241                        e.copy_into(sl_gate, 0, &gate_y, t * n_ff)?;
1242                        e.copy_into(sl_up, 0, &up_y, t * n_ff)?;
1243                    }
1244                    // task #17: the silu arm's f16out twin emits the down GEMM's fp16
1245                    // operand in-epilogue; non-silu activations keep the standalone convert.
1246                    // silu_mul_f16out is PLAIN silu(gate)*up — a clamped layer (step35 dense
1247                    // blocks under a live swiglu_clamp_shexp) must take the ffn_act_lim arm.
1248                    let d_lim = self.cfg.clamp_shexp_at(il as u32);
1249                    let act16 = if Self::f16out_on(e, t) && self.cfg.m3.is_none()
1250                        && d_lim.is_none() {
1251                        let mut a16 = e.alloc_u8_uninit(t * n_ff * 2)?;
1252                        e.silu_mul_f16out(sl_gate, sl_up, act, &mut a16, t * n_ff)?;
1253                        Some(a16)
1254                    } else {
1255                        Self::ffn_act_lim(e, &self.cfg, sl_gate, sl_up, 1.0, 1.0, d_lim,
1256                                          act, t * n_ff)?;
1257                        None
1258                    };
1259                    // down GEMM into the ffn_out slab (f16 arm; fallback copies)
1260                    let xh_act = match act16 {
1261                        Some(x) => x,
1262                        None => e.f16_act(act, t * n_ff, n_ff)?,
1263                    };
1264                    if !e.try_f16_gemm_pre_into(ffn_down, &xh_act, t, sl_fo)? {
1265                        let y = e.matmul(ffn_down, &*act, t)?;
1266                        e.copy_into(sl_fo, 0, &y, t * n_embd)?;
1267                    }
1268                }
1269                crate::hybrid::Ffn::Moe(m) => {
1270                    let y = self.moe_ffn_il_prefill(e, m, z, t, il as u16)?;
1271                    e.copy_into(sl_fo, 0, &y, t * n_embd)?;
1272                }
1273            }
1274            if use_seg && il + 1 < hi {
1275                // S-glue segment: [add + next attn-norm(+f16out)] — one cuGraphLaunch
1276                let w_next = self.layers[il + 1].attn_norm.float_data();
1277                let (sg, _, _, _) = seg.as_mut().unwrap();
1278                if sg[il].is_none() {
1279                    use cudarc::driver::sys::{CUgraphInstantiate_flags, CUstreamCaptureMode};
1280                    e.stream().synchronize()?;
1281                    e.stream().begin_capture(CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_RELAXED)?;
1282                    let r = (|| -> Result<(), Box<dyn std::error::Error>> {
1283                        e.add(x1, sl_fo, x_nxt, t * n_embd)?;
1284                        e.rms_norm_f16out(x_nxt, w_next, h, h16, n_embd, t, eps)?;
1285                        Ok(())
1286                    })();
1287                    let g = e.stream().end_capture(
1288                        CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH);
1289                    r?;
1290                    sg[il] = Some(g?.ok_or("S-glue capture produced no graph")?);
1291                }
1292                sg[il].as_ref().unwrap().launch()?;
1293            } else {
1294                if il + 1 < hi {
1295                    let w_next = self.layers[il + 1].attn_norm.float_data();
1296                    if f16fuse {
1297                        e.add_rms_norm_f16out(x1, sl_fo, w_next, x_nxt, h, h16, n_embd, t, eps)?;
1298                    } else {
1299                        e.add(x1, sl_fo, x_nxt, t * n_embd)?;
1300                        e.rms_norm(x_nxt, w_next, h, n_embd, t, eps)?;
1301                    }
1302                } else {
1303                    e.add(x1, sl_fo, x_nxt, t * n_embd)?;
1304                }
1305            }
1306            // CHUNK-INVARIANCE BISECT SEAM (lane/chunk-invariance, 2026-08-05): dump the
1307            // per-layer post-residual hidden for the LAST row of this chunk, keyed by
1308            // absolute position, so two runs at different MEMRA_PRIME_CHUNK can be diffed
1309            // layer-by-layer to find the FIRST diverging layer. Diagnostic only —
1310            // unset (the default) costs one OnceLock read per layer.
1311            if let Some(path) = Self::prime_trace_path() {
1312                let row = (base + t - 1) as usize;
1313                let host = e.dtoh(x_nxt)?;
1314                let last = &host[(t - 1) * n_embd..t * n_embd];
1315                use std::io::Write as _;
1316                let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
1317                let mut h64: u64 = 0xcbf29ce484222325;
1318                for v in last {
1319                    h64 ^= v.to_bits() as u64;
1320                    h64 = h64.wrapping_mul(0x100000001b3);
1321                }
1322                writeln!(f, "{{\"pos\":{row},\"layer\":{il},\"t\":{t},\"base\":{base},\
1323                             \"hash\":\"{h64:016x}\",\"v0\":{:.9e},\"v1\":{:.9e},\"v2\":{:.9e}}}",
1324                         last[0], last[1], last[2])?;
1325            }
1326            std::mem::swap(&mut x_cur, &mut x_nxt);
1327        }
1328        // hidden-stack return: clone the final x out of the slab
1329        let mut x = e.uninit(t * n_embd)?;
1330        e.copy_into(&mut x, 0, x_cur, t * n_embd)?;
1331        drop(slab_guard);
1332        Ok(x)
1333    }
1334
1335    /// The prime chunk's tail — h_seed + output_norm + one-row lm head + cache.pos advance —
1336    /// shared verbatim by the unsplit walk and the last stage of the ppN walk (`e` = the
1337    /// engine that produced `x`, i.e. the last stage's under the split; output_norm/output
1338    /// were loaded through that engine by the sharded loader, hybrid.rs `e_head`).
1339    fn prime_chunk_epilogue(&self, e: &Engine, x: CudaSlice<f32>, t: usize, cache: &mut Cache)
1340                            -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1341        let n_embd = self.cfg.n_embd as usize;
1342        let eps = self.cfg.rms_eps;
1343        // h_seed = LAST row of x BEFORE output_norm (MTP-PLAN §A default) or AFTER it
1344        // (MEMRA_SPEC_HPOST — reference convention; hn is computed just below either way, so
1345        // the post-norm copy happens after hn exists).
1346        let mut h_seed = e.uninit(n_embd)?;
1347        if !crate::spec::spec_hpost() {
1348            e.copy_view_into(&mut h_seed, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
1349        }
1350        // last-row logits, exactly like forward_last (norm all T — per-row op — then lm_head on 1 row).
1351        let mut hn = e.uninit(t * n_embd)?;
1352        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1353        if crate::spec::spec_hpost() {
1354            e.copy_view_into(&mut h_seed, 0, &hn.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
1355        }
1356        let last = e.view(&hn, t * n_embd);
1357        let last_row = last.slice((t - 1) * n_embd..t * n_embd);
1358        let mut hlast = e.uninit(n_embd)?;
1359        e.copy_view_into(&mut hlast, 0, &last_row, n_embd)?;
1360        let logits = e.matmul(&self.output, &hlast, 1)?;
1361        cache.pos += t;
1362        // Hidden stack handed to generate_spec as prompt_h: pre-norm x (default) or the full
1363        // post-norm stack hn (MEMRA_SPEC_HPOST).
1364        Ok((e.dtoh(&logits)?, h_seed, if crate::spec::spec_hpost() { hn } else { x }))
1365    }
1366
1367    /// THE PRIME STAGE SPLIT (lane/pp-leverb, 2026-08-08): one prime chunk as N stage
1368    /// subgraphs, each range on ITS OWN engine/stream/device, with the `[T, n_embd]`
1369    /// boundary handoff at every fence cut — the prime twin of `decode_step_h_ppn` /
1370    /// `decode_step_t_core_ppn`, and the kill for the anatomy's two receipts: stage-1 trunk
1371    /// weights stop being peer-read (22% of the pp4096 wall) and dev1 stops running zero
1372    /// prefill kernels. Structure mirrors the verify split exactly:
1373    ///   stage 0        `rt.enter(0)` → per-stage pos_d + embed (the table lives with
1374    ///                  stage 0) → `prime_layers(fence[0], fence[1])` → `rt.tx`
1375    ///   middle stages  `rt.rx` → per-stage pos_d → range → `rt.tx`
1376    ///   last stage     `rt.rx` → range → the shared epilogue (output_norm + head live
1377    ///                  there via the sharded loader) → `publish_to`
1378    /// Laws inherited (not relearned): `fence_stages_behind` at entry (#87 — a previous
1379    /// round's stage-freed buffers must not be reused under the caller's queued reads);
1380    /// per-stage `pos_d` (allocated/consumed/freed on one stream); per-stage Engines from
1381    /// `PpNRt` (shared-scratch race); EXIT PUBLICATION for the device-resident returns
1382    /// (h_seed + hidden stack live on the last stage — the caller's stream must wait).
1383    /// KV/MoE locality falls out: each range's KV appends run on the owning stage
1384    /// (`pp::new_cache` placed the buffers there), each stage engine owns its own SLRU
1385    /// pool (per-Engine `moe_cache`, sized on ITS device — the SGLang #33666 law), and the
1386    /// slab-local MoE arm's `DevExps.dev` gate now matches on stage-1 layers too.
1387    /// EXACTNESS: the split adds zero deviation by construction (same kernels, same bytes,
1388    /// boundary = straight f32 copy); `prime-split-gate` (ppsplit) arbitrates bit-for-bit
1389    /// and its liveness counter is bumped here — the gate goes green with this function.
1390    fn prime_chunk_ppn(&self, e: &Engine, tokens: &[u32], cache: &mut Cache, seq_end: usize,
1391                       fence: &[usize])
1392                       -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1393        let rt = crate::pp::PpNRt::get(e)?;
1394        let n_st = fence.len() - 1;
1395        assert_eq!(
1396            rt.n_stages(), n_st,
1397            "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
1398        );
1399        let n_embd = self.cfg.n_embd as usize;
1400        let t = tokens.len();
1401        let base = cache.pos;
1402        debug_assert!(seq_end >= base + t, "prime_chunk_ppn: seq_end must cover this chunk");
1403        let payload = t * n_embd;
1404        // The caller's ambient stream, captured BEFORE any enter() pushes a stage stream
1405        // (inside a stage scope e.stream() IS the stage stream and the exit wait would
1406        // self-order into a no-op) — the decode_step_t_core_ppn pattern.
1407        let caller_stream = e.stream();
1408        rt.fence_stages_behind(&caller_stream)?;
1409
1410        if n_st == 2 {
1411            let slot = self.prime_pp2_stage0_enqueue(
1412                e, rt, tokens, cache, seq_end, fence, base, false,
1413            )?;
1414            let x = self.prime_pp2_stage1_enqueue(
1415                e, rt, slot, t, cache, seq_end, fence, base, false,
1416            )?;
1417            let out = {
1418                rt.bind_stage(1)?;
1419                let _st1 = rt.enter(1);
1420                let e1 = rt.engine(1, e);
1421                self.prime_chunk_epilogue(e1, x, t, cache)?
1422            };
1423            rt.publish_to(1, &caller_stream)?;
1424            crate::pp::PRIME_SPLIT_CHUNKS
1425                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1426            return Ok(out);
1427        }
1428
1429        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1430
1431        // ---- STAGE 0: embed + layers [0, fence[1]) + boundary-0 TX ----
1432        let mut slot = {
1433            let _st0 = rt.enter(0);
1434            let e0 = rt.engine(0, e);
1435            let pos_d = e0.htod_i32(&pos)?;
1436            let x = self.embed(e0, tokens)?;
1437            let x = self.prime_layers(
1438                e0, x, fence[0], fence[1], &pos_d, t, base, cache, seq_end,
1439            )?;
1440            rt.tx(0, &x, payload)?
1441            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
1442        };
1443
1444        // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
1445        for s in 1..n_st - 1 {
1446            let _st = rt.enter(s);
1447            let es = rt.engine(s, e);
1448            let pos_d = es.htod_i32(&pos)?;
1449            let x = rt.rx(s - 1, slot, payload)?;
1450            let x = self.prime_layers(
1451                es, x, fence[s], fence[s + 1], &pos_d, t, base, cache, seq_end,
1452            )?;
1453            slot = rt.tx(s, &x, payload)?;
1454        }
1455
1456        // ---- LAST STAGE: RX + final range + the shared epilogue ----
1457        let _stl = rt.enter(n_st - 1);
1458        let el = rt.engine(n_st - 1, e);
1459        let pos_d = el.htod_i32(&pos)?;
1460        let x = rt.rx(n_st - 2, slot, payload)?;
1461        let x = self.prime_layers(
1462            el, x, fence[n_st - 1], fence[n_st], &pos_d, t, base, cache, seq_end,
1463        )?;
1464        let out = self.prime_chunk_epilogue(el, x, t, cache)?;
1465        // EXIT PUBLICATION: h_seed + the hidden stack are device-resident on the last
1466        // stage's stream; the caller resumes on its own stream (chunk-loop copy_into /
1467        // generate_spec's prompt_h consumer). The logits dtoh above already drained the
1468        // stage stream host-side, but the law is stated in events, not in a dtoh side
1469        // effect a later deferred form would remove.
1470        rt.publish_to(n_st - 1, &caller_stream)?;
1471        crate::pp::PRIME_SPLIT_CHUNKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1472        Ok(out)
1473    }
1474
1475    fn prime_pp2_stage0_enqueue(
1476        &self,
1477        e: &Engine,
1478        rt: &crate::pp::PpNRt,
1479        tokens: &[u32],
1480        cache: &mut Cache,
1481        seq_end: usize,
1482        fence: &[usize],
1483        base: usize,
1484        pipelined: bool,
1485    ) -> Result<usize, Box<dyn std::error::Error>> {
1486        let t = tokens.len();
1487        let n_embd = self.cfg.n_embd as usize;
1488        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1489        rt.bind_stage(0)?;
1490        let _st0 = rt.enter(0);
1491        let e0 = rt.engine(0, e);
1492        let pos_d = e0.htod_i32(&pos)?;
1493        let x = self.embed(e0, tokens)?;
1494        let _overlap = pipelined.then(crate::pp::enter_prime_pipe_stage);
1495        let x = self.prime_layers(
1496            e0, x, fence[0], fence[1], &pos_d, t, base, cache, seq_end,
1497        )?;
1498        if pipelined {
1499            rt.tx_pipelined(0, &x, t * n_embd)
1500        } else {
1501            rt.tx(0, &x, t * n_embd)
1502        }
1503    }
1504
1505    fn prime_pp2_stage1_enqueue(
1506        &self,
1507        e: &Engine,
1508        rt: &crate::pp::PpNRt,
1509        slot: usize,
1510        t: usize,
1511        cache: &mut Cache,
1512        seq_end: usize,
1513        fence: &[usize],
1514        base: usize,
1515        pipelined: bool,
1516    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1517        let n_embd = self.cfg.n_embd as usize;
1518        let pos: Vec<i32> = (base as i32..(base + t) as i32).collect();
1519        rt.bind_stage(1)?;
1520        let _st1 = rt.enter(1);
1521        let e1 = rt.engine(1, e);
1522        let pos_d = e1.htod_i32(&pos)?;
1523        let x = rt.rx(0, slot, t * n_embd)?;
1524        let _overlap = pipelined.then(crate::pp::enter_prime_pipe_stage);
1525        self.prime_layers(
1526            e1, x, fence[1], fence[2], &pos_d, t, base, cache, seq_end,
1527        )
1528    }
1529
1530    /// CAPTURE-SAFE prime trunk (task #14 increment 1, ARCHITECTURE-H100.md design v2):
1531    /// prime_chunk's layer stack with every capture hazard hoisted — `x` is the
1532    /// PRE-EMBEDDED input in a STABLE graph-input buffer (embed + its 8MB htod stay
1533    /// eager, one launch), `pos_d` is a baked device param (fresh prime = 0..T, constant
1534    /// per bucket), logits/h_seed/hidden stay DEVICE-resident (no dtoh), and cache.pos is
1535    /// NOT advanced (host state — the replay wrapper owns it). Body mirrors prime_chunk
1536    /// (the prime-graph-gate pins them together). KNOWN smoke-scope gap: append host-len
1537    /// bookkeeping still runs on the host per call — the real replay path moves the write
1538    /// slot to the len_d device counter (increment 3).
1539    /// GRAPH-OUTPUT CONTRACT: results are COPIED into caller-provided stable buffers
1540    /// (`logits_out` [n_vocab], `h_seed_out` [n_embd]) — every internal allocation drops
1541    /// INSIDE the capture region (alloc+free node pairs). Retaining an in-capture
1542    /// allocation across end_capture makes instantiate throw INVALID_VALUE (smoke finding
1543    /// 2026-07-26), and under AUTO_FREE_ON_LAUNCH its address wouldn't survive a launch
1544    /// anyway — the decode GraphSession's pre-allocated-output pattern is the law here.
1545    pub fn prime_chunk_captured(&self, e: &Engine, x_in: &CudaSlice<f32>, pos_d: &CudaSlice<i32>,
1546                                t: usize, cache: &mut Cache,
1547                                len_d: &CudaSlice<i32>,
1548                                logits_out: &mut CudaSlice<f32>, h_seed_out: &mut CudaSlice<f32>)
1549                                -> Result<(), Box<dyn std::error::Error>> {
1550        let cfg = &self.cfg;
1551        let n_embd = cfg.n_embd as usize;
1552        let eps = cfg.rms_eps;
1553        let f16fuse = crate::f16_ffi::pp_f16_enabled() && t >= 16;
1554        let mut x = e.uninit(t * n_embd)?;
1555        e.copy_into(&mut x, 0, x_in, t * n_embd)?;
1556        for (il, layer) in self.layers.iter().enumerate() {
1557            let mut h = e.uninit(t * n_embd)?;
1558            let mut hx16: Option<CudaSlice<u8>> = None;
1559            if f16fuse {
1560                let mut b16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1561                e.rms_norm_f16out(&x, layer.attn_norm.float_data(), &mut h, &mut b16, n_embd, t, eps)?;
1562                hx16 = Some(b16);
1563            } else {
1564                e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
1565            }
1566            let mixed = match &layer.mixer {
1567                // The captured prime is ONE unchunked bucket over a FRESH cache (pos == 0), so the
1568                // request ends at t. If bucketed capture ever composes with chunking, seq_end must
1569                // come from the caller (see step35_attn_pre_wo's doc note).
1570                Mixer::Full(fa) => self.full_attn_prime(e, fa, &h, hx16.as_ref(), pos_d, t, cache,
1571                                                        il, t)?,
1572                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1573                Mixer::Linear(la) => {
1574                    let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
1575                    let g4 = match hx16.as_ref() {
1576                        Some(xh) => e.matmul_group_xh(&ws, &h, xh, t)?,
1577                        None => e.matmul_group(&ws, &h, t)?,
1578                    };
1579                    self.linear_attn_prime_core_pad(e, la, g4, t, cache, il, Some(len_d))?
1580                }
1581            };
1582            let mut x1 = e.uninit(t * n_embd)?;
1583            e.add(&x, &mixed, &mut x1, t * n_embd)?;
1584            let mut z = e.uninit(t * n_embd)?;
1585            let mut zx16: Option<CudaSlice<u8>> = None;
1586            if f16fuse {
1587                let mut b16 = e.alloc_u8_uninit(t * n_embd * 2)?;
1588                e.rms_norm_f16out(&x1, layer.post_attn_norm.float_data(), &mut z, &mut b16, n_embd, t, eps)?;
1589                zx16 = Some(b16);
1590            } else {
1591                e.rms_norm(&x1, layer.post_attn_norm.float_data(), &mut z, n_embd, t, eps)?;
1592            }
1593            let ffn_out = match &layer.ffn {
1594                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1595                    let n_ff = ffn_gate.out_features();
1596                    let mut g2 = match &zx16 {
1597                        Some(xh) => e.matmul_group_xh(&[ffn_gate, ffn_up], &z, xh, t)?,
1598                        None => e.matmul_group(&[ffn_gate, ffn_up], &z, t)?,
1599                    };
1600                    let up = g2.pop().unwrap();
1601                    let gate = g2.pop().unwrap();
1602                    let mut act = e.uninit(t * n_ff)?;
1603                    // dense FFN keys off the SHEXP clamp array — see forward()'s note.
1604                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
1605                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
1606                    e.matmul(ffn_down, &act, t)?
1607                }
1608                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_prefill(e, m, &z, t, il as u16)?,
1609            };
1610            let mut x2 = e.uninit(t * n_embd)?;
1611            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
1612            x = x2;
1613        }
1614        // device-indexed TRUE last row (pads sit past it in a bucketed graph)
1615        if !crate::spec::spec_hpost() {
1616            e.row_gather_dev(&x, h_seed_out, len_d, n_embd)?;
1617        }
1618        let mut hn = e.uninit(t * n_embd)?;
1619        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1620        if crate::spec::spec_hpost() {
1621            e.row_gather_dev(&hn, h_seed_out, len_d, n_embd)?;
1622        }
1623        let mut hlast = e.uninit(n_embd)?;
1624        e.row_gather_dev(&hn, &mut hlast, len_d, n_embd)?;
1625        let logits = e.matmul(&self.output, &hlast, 1)?;
1626        let nv = logits.len();
1627        e.copy_into(logits_out, 0, &logits, nv)?;
1628        Ok(())
1629    }
1630
1631    fn step35_prime_batch_on() -> bool {
1632        std::env::var("MEMRA_STEP35_PRIME_BATCH").as_deref() != Ok("0")
1633    }
1634
1635    /// Step35 cross-request prime range: weight-streaming work runs once at `m=sum(T)`;
1636    /// sequence-scoped attention/KV work stays on each request's own cache and positions.
1637    #[allow(clippy::too_many_arguments)]
1638    fn step35_prime_batch_layers(
1639        &self,
1640        e: &Engine,
1641        mut x: CudaSlice<f32>,
1642        lo: usize,
1643        hi: usize,
1644        ts: &[usize],
1645        offs: &[usize],
1646        pos_ds: &[CudaSlice<i32>],
1647        caches: &mut [&mut Cache],
1648    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1649        let cfg = &self.cfg;
1650        let n_embd = cfg.n_embd as usize;
1651        let eps = cfg.rms_eps;
1652        let b = ts.len();
1653        let total: usize = ts.iter().sum();
1654        let f16fuse = crate::f16_ffi::pp_f16_enabled() && total >= 16;
1655
1656        let split = |e: &Engine, y: &CudaSlice<f32>, dim: usize|
1657                     -> Result<Vec<CudaSlice<f32>>, Box<dyn std::error::Error>> {
1658            let mut out = Vec::with_capacity(b);
1659            for s in 0..b {
1660                let mut ys = e.uninit(ts[s] * dim)?;
1661                e.copy_view_into(
1662                    &mut ys,
1663                    0,
1664                    &y.slice(offs[s] * dim..(offs[s] + ts[s]) * dim),
1665                    ts[s] * dim,
1666                )?;
1667                out.push(ys);
1668            }
1669            Ok(out)
1670        };
1671
1672        for il in lo..hi {
1673            let layer = &self.layers[il];
1674            let Mixer::Full(fa) = &layer.mixer else {
1675                return Err(format!("step35 layer {il} is not full-attn — corrupt config").into());
1676            };
1677
1678            let mut h = e.uninit(total * n_embd)?;
1679            let mut hx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
1680            if f16fuse {
1681                e.rms_norm_f16out(
1682                    &x,
1683                    layer.attn_norm.float_data(),
1684                    &mut h,
1685                    &mut hx16,
1686                    n_embd,
1687                    total,
1688                    eps,
1689                )?;
1690            } else {
1691                e.rms_norm(
1692                    &x,
1693                    layer.attn_norm.float_data(),
1694                    &mut h,
1695                    n_embd,
1696                    total,
1697                    eps,
1698                )?;
1699            }
1700
1701            // Q/K/V + gate projections and wo are batched weight streams. The step35 core
1702            // remains per sequence, so its partial RoPE, SWA view, KV append, and gate
1703            // application stay verbatim.
1704            let gate_w = fa
1705                .attn_gate
1706                .as_ref()
1707                .ok_or("step35 layer is missing attn_gate.weight (head-wise attention gate)")?;
1708            let mut g4 = if f16fuse {
1709                e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv, gate_w], &h, &hx16, total)?
1710            } else {
1711                e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv, gate_w], &h, total)?
1712            };
1713            let gate = g4.pop().unwrap();
1714            let mut parts: Vec<Vec<CudaSlice<f32>>> =
1715                (0..b).map(|_| Vec::with_capacity(3)).collect();
1716            for (w, y) in [&fa.wq, &fa.wk, &fa.wv].iter().zip(g4) {
1717                for (s, ys) in split(e, &y, w.out_features())?.into_iter().enumerate() {
1718                    parts[s].push(ys);
1719                }
1720            }
1721            let gates = split(e, &gate, gate_w.out_features())?;
1722            let geometry = self.step35_geom(il);
1723            let hd = geometry.head_dim_k as usize;
1724            let nh = geometry.n_head as usize;
1725            let mut ag_cat = e.uninit(total * nh * hd)?;
1726            for (s, (g3s, gate)) in parts.into_iter().zip(gates).enumerate() {
1727                let ag = self.step35_attn_pre_wo(
1728                    e,
1729                    fa,
1730                    g3s,
1731                    None,
1732                    Some(&gate),
1733                    &pos_ds[s],
1734                    ts[s],
1735                    Some(&mut *caches[s]),
1736                    il,
1737                    ts[s],
1738                )?;
1739                e.copy_into(
1740                    &mut ag_cat,
1741                    offs[s] * nh * hd,
1742                    &ag,
1743                    ts[s] * nh * hd,
1744                )?;
1745            }
1746            let mixed = e.matmul(&fa.wo, &ag_cat, total)?;
1747
1748            let mut x1 = e.uninit(total * n_embd)?;
1749            let mut z = e.uninit(total * n_embd)?;
1750            let mut zx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
1751            if f16fuse {
1752                e.add_rms_norm_f16out(
1753                    &x,
1754                    &mixed,
1755                    layer.post_attn_norm.float_data(),
1756                    &mut x1,
1757                    &mut z,
1758                    &mut zx16,
1759                    n_embd,
1760                    total,
1761                    eps,
1762                )?;
1763            } else {
1764                e.add(&x, &mixed, &mut x1, total * n_embd)?;
1765                e.rms_norm(
1766                    &x1,
1767                    layer.post_attn_norm.float_data(),
1768                    &mut z,
1769                    n_embd,
1770                    total,
1771                    eps,
1772                )?;
1773            }
1774
1775            let ffn_out = match &layer.ffn {
1776                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1777                    let n_ff = ffn_gate.out_features();
1778                    let mut g2 = if f16fuse {
1779                        e.matmul_group_xh(&[ffn_gate, ffn_up], &z, &zx16, total)?
1780                    } else {
1781                        e.matmul_group(&[ffn_gate, ffn_up], &z, total)?
1782                    };
1783                    let up = g2.pop().unwrap();
1784                    let gate = g2.pop().unwrap();
1785                    let mut act = e.uninit(total * n_ff)?;
1786                    let d_lim = cfg.clamp_shexp_at(il as u32);
1787                    if Self::f16out_on(e, total) && cfg.m3.is_none() && d_lim.is_none() {
1788                        let mut a16 = e.alloc_u8_uninit(total * n_ff * 2)?;
1789                        e.silu_mul_f16out(&gate, &up, &mut act, &mut a16, total * n_ff)?;
1790                        match e.try_f16_gemm_pre(ffn_down, &a16, total)? {
1791                            Some(y) => y,
1792                            None => e.matmul(ffn_down, &act, total)?,
1793                        }
1794                    } else {
1795                        Self::ffn_act_lim(
1796                            e,
1797                            cfg,
1798                            &gate,
1799                            &up,
1800                            1.0,
1801                            1.0,
1802                            d_lim,
1803                            &mut act,
1804                            total * n_ff,
1805                        )?;
1806                        e.matmul(ffn_down, &act, total)?
1807                    }
1808                }
1809                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, total, il as u16)?,
1810            };
1811            let mut x2 = e.uninit(total * n_embd)?;
1812            e.add(&x1, &ffn_out, &mut x2, total * n_embd)?;
1813            x = x2;
1814        }
1815        Ok(x)
1816    }
1817
1818    fn step35_prime_batch_epilogue(
1819        &self,
1820        e: &Engine,
1821        x: CudaSlice<f32>,
1822        ts: &[usize],
1823        offs: &[usize],
1824        caches: &mut [&mut Cache],
1825    ) -> Result<Vec<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
1826        let n_embd = self.cfg.n_embd as usize;
1827        let total: usize = ts.iter().sum();
1828        let mut hn = e.uninit(total * n_embd)?;
1829        e.rms_norm(
1830            &x,
1831            self.output_norm.float_data(),
1832            &mut hn,
1833            n_embd,
1834            total,
1835            self.cfg.rms_eps,
1836        )?;
1837
1838        let hidden_src = if crate::spec::spec_hpost() { &hn } else { &x };
1839        let mut out = Vec::with_capacity(ts.len());
1840        for s in 0..ts.len() {
1841            let mut hidden = e.uninit(ts[s] * n_embd)?;
1842            e.copy_view_into(
1843                &mut hidden,
1844                0,
1845                &hidden_src.slice(offs[s] * n_embd..(offs[s] + ts[s]) * n_embd),
1846                ts[s] * n_embd,
1847            )?;
1848            let last0 = (offs[s] + ts[s] - 1) * n_embd;
1849            let mut h_seed = e.uninit(n_embd)?;
1850            e.copy_view_into(
1851                &mut h_seed,
1852                0,
1853                &hidden_src.slice(last0..last0 + n_embd),
1854                n_embd,
1855            )?;
1856            // Exactness-first: the serial reference runs the output head at m=1.
1857            let mut hlast = e.uninit(n_embd)?;
1858            e.copy_view_into(
1859                &mut hlast,
1860                0,
1861                &hn.slice(last0..last0 + n_embd),
1862                n_embd,
1863            )?;
1864            let logits = e.dtoh(&e.matmul(&self.output, &hlast, 1)?)?;
1865            caches[s].pos += ts[s];
1866            out.push((logits, h_seed, hidden));
1867        }
1868        Ok(out)
1869    }
1870
1871    fn step35_prime_cache_batch(
1872        &self,
1873        e: &Engine,
1874        prompts: &[&[u32]],
1875        caches: &mut [&mut Cache],
1876    ) -> Result<Vec<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
1877        if !Self::step35_prime_batch_on() {
1878            return Err("step35 batched prime is disabled (MEMRA_STEP35_PRIME_BATCH=0)".into());
1879        }
1880        if caches.iter().any(|c| c.pos != 0) {
1881            return Err(
1882                "step35 batched prime currently supports complete fresh prompts only; \
1883                 continuation/tick chunks require per-request queued_after"
1884                    .into(),
1885            );
1886        }
1887
1888        let ts: Vec<usize> = prompts.iter().map(|p| p.len()).collect();
1889        for &t in &ts {
1890            assert!(t >= PRIME_MIN_T, "step35 batched prime needs T >= {PRIME_MIN_T}");
1891        }
1892        for (s, c) in caches.iter().enumerate() {
1893            assert!(ts[s] <= c.max_ctx, "step35 batched prime exceeds cache max_ctx");
1894        }
1895        let offs: Vec<usize> = ts
1896            .iter()
1897            .scan(0usize, |a, &t| {
1898                let o = *a;
1899                *a += t;
1900                Some(o)
1901            })
1902            .collect();
1903        let total: usize = ts.iter().sum();
1904        let payload = total * self.cfg.n_embd as usize;
1905        let cat_tokens: Vec<u32> = prompts.iter().flat_map(|p| p.iter().copied()).collect();
1906        let positions: Vec<Vec<i32>> = ts
1907            .iter()
1908            .map(|&t| (0..t as i32).collect())
1909            .collect();
1910        let upload_positions = |e: &Engine|
1911                                -> Result<Vec<CudaSlice<i32>>, Box<dyn std::error::Error>> {
1912            positions
1913                .iter()
1914                .map(|p| e.htod_i32(p))
1915                .collect::<Result<_, _>>()
1916        };
1917
1918        static ONCE: std::sync::Once = std::sync::Once::new();
1919        ONCE.call_once(|| {
1920            eprintln!(
1921                "[step35-prime-batch] first concat prime: B={} tokens={total}",
1922                prompts.len()
1923            );
1924        });
1925
1926        let out = if !crate::pp::pp2_streams_off() && crate::pp::prime_pp_on() {
1927            if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
1928                let rt = crate::pp::PpNRt::get(e)?;
1929                let n_st = fence.len() - 1;
1930                assert_eq!(rt.n_stages(), n_st, "step35 prime batch stage count mismatch");
1931                let caller_stream = e.stream();
1932                rt.fence_stages_behind(&caller_stream)?;
1933
1934                let mut slot = {
1935                    let _st0 = rt.enter(0);
1936                    let e0 = rt.engine(0, e);
1937                    let pos_ds = upload_positions(e0)?;
1938                    let x = self.embed(e0, &cat_tokens)?;
1939                    let x = self.step35_prime_batch_layers(
1940                        e0,
1941                        x,
1942                        fence[0],
1943                        fence[1],
1944                        &ts,
1945                        &offs,
1946                        &pos_ds,
1947                        caches,
1948                    )?;
1949                    rt.tx(0, &x, payload)?
1950                };
1951                for s in 1..n_st - 1 {
1952                    let _st = rt.enter(s);
1953                    let es = rt.engine(s, e);
1954                    let pos_ds = upload_positions(es)?;
1955                    let x = rt.rx(s - 1, slot, payload)?;
1956                    let x = self.step35_prime_batch_layers(
1957                        es,
1958                        x,
1959                        fence[s],
1960                        fence[s + 1],
1961                        &ts,
1962                        &offs,
1963                        &pos_ds,
1964                        caches,
1965                    )?;
1966                    slot = rt.tx(s, &x, payload)?;
1967                }
1968
1969                let _stl = rt.enter(n_st - 1);
1970                let el = rt.engine(n_st - 1, e);
1971                let pos_ds = upload_positions(el)?;
1972                let x = rt.rx(n_st - 2, slot, payload)?;
1973                let x = self.step35_prime_batch_layers(
1974                    el,
1975                    x,
1976                    fence[n_st - 1],
1977                    fence[n_st],
1978                    &ts,
1979                    &offs,
1980                    &pos_ds,
1981                    caches,
1982                )?;
1983                let out = self.step35_prime_batch_epilogue(el, x, &ts, &offs, caches)?;
1984                rt.publish_to(n_st - 1, &caller_stream)?;
1985                crate::pp::STEP35_PRIME_BATCH_SPLITS.fetch_add(
1986                    1,
1987                    std::sync::atomic::Ordering::Relaxed,
1988                );
1989                out
1990            } else {
1991                let pos_ds = upload_positions(e)?;
1992                let x = self.embed(e, &cat_tokens)?;
1993                let x = self.step35_prime_batch_layers(
1994                    e,
1995                    x,
1996                    0,
1997                    self.layers.len(),
1998                    &ts,
1999                    &offs,
2000                    &pos_ds,
2001                    caches,
2002                )?;
2003                self.step35_prime_batch_epilogue(e, x, &ts, &offs, caches)?
2004            }
2005        } else {
2006            let pos_ds = upload_positions(e)?;
2007            let x = self.embed(e, &cat_tokens)?;
2008            let x = self.step35_prime_batch_layers(
2009                e,
2010                x,
2011                0,
2012                self.layers.len(),
2013                &ts,
2014                &offs,
2015                &pos_ds,
2016                caches,
2017            )?;
2018            self.step35_prime_batch_epilogue(e, x, &ts, &offs, caches)?
2019        };
2020        crate::pp::STEP35_PRIME_BATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2021        Ok(out)
2022    }
2023
2024    /// Cross-request BATCHED fresh prime (task #13, design in ARCHITECTURE-H100.md): the
2025    /// trunk's token-parallel ops (embed, norms, adds, ffn, projection GROUPS) run once on
2026    /// the CONCATENATION of B sequences — GEMMs at m = sum_T, the continuous-batching win
2027    /// the serving-lane bench attributed the remaining vLLM gap to. The stateful mixer
2028    /// CORES (QK-norm/RoPE/FA/append, conv/GDN scans) run per sequence on split projection
2029    /// buffers (D2D row copies; the mixers' own out-projections stay per-seq this
2030    /// increment). CONTINUATION primes (increment (b), 2026-07-30): cache.pos > 0 seqs
2031    /// batch the projections/FFN/lm_head exactly like fresh; the mixer cores take the
2032    /// per-seq CONTINUATION arms (Full: core_inner with carried pos_d + fa_prefill_view
2033    /// over the quantized past; Linear: the stateful pad_view twin — the same state
2034    /// carry the chunked single-seq prime rides). The fresh-only favl/gdn-vl fast paths
2035    /// stay byte-identical (gated on !carried). gemma4 models have no continuation
2036    /// prime (v0 monolithic fresh) — carried gemma4 batches return Err (caller falls
2037    /// back to single-chunk serving).
2038    /// NUMERIC CONFIG: a concat GEMM tiles K differently than per-seq GEMMs — same class
2039    /// as every prefill GEMM change; prime_batch_gate arbitrates (argmax + stream battery).
2040    pub fn prime_cache_batch(&self, e: &Engine, prompts: &[&[u32]], caches: &mut [&mut Cache])
2041                             -> Result<Vec<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
2042        let cfg = &self.cfg;
2043        let n_embd = cfg.n_embd as usize;
2044        let eps = cfg.rms_eps;
2045        let b = prompts.len();
2046        assert!(b >= 1 && b == caches.len());
2047        let pos0s: Vec<usize> = caches.iter().map(|c| c.pos).collect();
2048        let carried = pos0s.iter().any(|&p| p > 0);
2049        // gemma4: refuse UNCONDITIONALLY (2026-08-07, lane/gemma4-serve-gaps). The old guard
2050        // covered only `carried` — two concurrent FRESH gemma4 prompts batched into the
2051        // generic concat attn core below (uniform geometry, no per-layer swa window, no
2052        // softcapped head): compiles, runs, wrong logits. Same silent-wrong class as the
2053        // step35 refusal beneath. The per-sequence `gemma4_prime` is the supported prefill.
2054        if cfg.gemma4.is_some() {
2055            return Err("prime_cache_batch: gemma4 has no batched prime core (per-layer \
2056                        swa/global geometry, softcapped head) — use gemma4_prime per sequence".into());
2057        }
2058        // Step35 has a dedicated concat walk: the generic core below cannot express its
2059        // per-layer geometry/SWA/head gate, and under PP the dedicated path is stage-scoped.
2060        if cfg.step35.is_some() {
2061            return self.step35_prime_cache_batch(e, prompts, caches);
2062        }
2063        let ts: Vec<usize> = prompts.iter().map(|p| p.len()).collect();
2064        for &t in &ts { assert!(t >= PRIME_MIN_T, "prime_cache_batch needs T >= {PRIME_MIN_T}"); }
2065        for (s, c) in caches.iter().enumerate() {
2066            assert!(c.pos + ts[s] <= c.max_ctx, "prime_cache_batch: prompt exceeds cache max_ctx");
2067        }
2068        let total: usize = ts.iter().sum();
2069        let offs: Vec<usize> = ts.iter().scan(0usize, |a, &t| { let o = *a; *a += t; Some(o) }).collect();
2070        // per-seq positions (fresh: 0..T_s; continuation: pos0..pos0+T_s)
2071        let pos_ds: Vec<CudaSlice<i32>> = ts.iter().zip(&pos0s)
2072            .map(|(&t, &p0)| e.htod_i32(&(p0 as i32..(p0 + t) as i32).collect::<Vec<_>>()))
2073            .collect::<Result<_, _>>()?;
2074        // split a concat [total, dim] buffer into per-seq copies
2075        let split = |e: &Engine, y: &CudaSlice<f32>, dim: usize|
2076                     -> Result<Vec<CudaSlice<f32>>, Box<dyn std::error::Error>> {
2077            let mut out = Vec::with_capacity(b);
2078            for s in 0..b {
2079                let mut ys = e.uninit(ts[s] * dim)?;
2080                e.copy_view_into(&mut ys, 0, &y.slice(offs[s] * dim..(offs[s] + ts[s]) * dim), ts[s] * dim)?;
2081                out.push(ys);
2082            }
2083            Ok(out)
2084        };
2085
2086        let cat_tokens: Vec<u32> = prompts.iter().flat_map(|p| p.iter().copied()).collect();
2087        let mut x = self.embed(e, &cat_tokens)?;   // [total, n_embd]
2088        for (il, layer) in self.layers.iter().enumerate() {
2089            let mut h = e.uninit(total * n_embd)?;
2090            let mut hx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
2091            e.rms_norm_f16out(&x, layer.attn_norm.float_data(), &mut h, &mut hx16, n_embd, total, eps)?;
2092            // mixer: projection GROUP on the concat (m = total), stateful core per seq
2093            let mut mixed = e.uninit(total * n_embd)?;
2094            match &layer.mixer {
2095                Mixer::Full(fa) => {
2096                    let g3 = e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], &h, &hx16, total)?;
2097                    // task #18 (attn side): the WHOLE attn core is varlen for fresh gated
2098                    // batches — split/QK-norm/RoPE/append (attn_pre_vl8, view inputs: the
2099                    // q/k/v split copies vanish) + ONE varlen FA. Per-block math identical
2100                    // everywhere (bit-gateable); MEMRA_FA_VL=0 or a non-bf16kv config falls
2101                    // back to the per-seq dispatch.
2102                    let geometry = self.cfg.full_attention_geometry_at(il as u32);
2103                    let (n_head, n_head_kv, head_dim) = (
2104                        geometry.n_head as usize,
2105                        geometry.n_head_kv as usize,
2106                        geometry.head_dim_k as usize,
2107                    );
2108                    let fa_scale = geometry.attention_scale();
2109                    let use_favl = !carried
2110                        && (2..=8).contains(&b)
2111                        && (head_dim == 256 || head_dim == 128)
2112                        && geometry.attention_gate
2113                            == memra_gguf::config::AttentionGateKind::FusedQ
2114                        && std::env::var("MEMRA_NOFA").is_err()
2115                        && std::env::var("MEMRA_FA_FLOOR").is_err()
2116                        && std::env::var("MEMRA_FA_PP_W2").as_deref() != Ok("1")
2117                        && std::env::var("MEMRA_FA_BF16KV").as_deref() != Ok("0")
2118                        && std::env::var("MEMRA_FA_VL").as_deref() != Ok("0");
2119                    if use_favl {
2120                        let (qf_w, kf_w, vf_w) =
2121                            (fa.wq.out_features(), fa.wk.out_features(), fa.wv.out_features());
2122                        struct APre {
2123                            q: CudaSlice<f32>, gate: Option<CudaSlice<f32>>,
2124                            qn: CudaSlice<f32>, kn: CudaSlice<f32>,
2125                        }
2126                        let mut aps = Vec::with_capacity(b);
2127                        for &t in ts.iter().take(b) {
2128                            aps.push(APre {
2129                                q: e.uninit(t * n_head * head_dim)?,
2130                                gate: Some(e.uninit(t * n_head * head_dim)?),
2131                                qn: e.uninit(t * n_head * head_dim)?,
2132                                kn: e.uninit(t * n_head_kv * head_dim)?,
2133                            });
2134                        }
2135                        let (kv_dim_k, kv_dim_v, ktb, vtb) = {
2136                            let kvl = caches[0].kv[il].as_ref().unwrap();
2137                            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes)
2138                        };
2139                        let pargs: Vec<crate::AttnPreVl> = (0..b).map(|s| {
2140                            let (o, t) = (offs[s], ts[s]);
2141                            let kvl = caches[s].kv[il].as_ref().unwrap();
2142                            assert!(kvl.len == 0 && kvl.len + t <= caches[s].max_ctx,
2143                                    "prime_cache_batch attn vl: fresh + capacity");
2144                            crate::AttnPreVl {
2145                                qf: e.addr_f32v(&g3[0].slice(o * qf_w..(o + t) * qf_w)),
2146                                kf: e.addr_f32v(&g3[1].slice(o * kf_w..(o + t) * kf_w)),
2147                                vf: e.addr_f32v(&g3[2].slice(o * vf_w..(o + t) * vf_w)),
2148                                q: e.addr_f32(&aps[s].q),
2149                                gate: e.addr_f32(aps[s].gate.as_ref().unwrap()),
2150                                qn: e.addr_f32(&aps[s].qn), kn: e.addr_f32(&aps[s].kn),
2151                                kc: e.addr_u8(&kvl.k), vc: e.addr_u8(&kvl.v),
2152                                t: t as i32, pad: 0,
2153                            }
2154                        }).collect();
2155                        e.attn_pre_vl8(&pargs, fa.q_norm.float_data(), fa.k_norm.float_data(),
2156                                       head_dim, geometry.n_rot as usize, n_head, n_head_kv,
2157                                       self.cfg.rms_eps, geometry.rope_base, 1.0,
2158                                       kv_dim_k, kv_dim_v, ktb, vtb)?;
2159                        for s in 0..b {
2160                            let kvl = caches[s].kv[il].as_mut().unwrap();
2161                            kvl.len += ts[s];
2162                            let new_len = kvl.len as i32;
2163                            e.set_i32_one(&mut kvl.len_d, new_len)?;
2164                        }
2165                        let mut attns = Vec::with_capacity(b);
2166                        let mut mirrors = Vec::with_capacity(b);
2167                        for &t in ts.iter().take(b) {
2168                            attns.push(e.uninit(t * n_head * head_dim)?);
2169                            let n = t * n_head_kv * head_dim;
2170                            mirrors.push((e.alloc_u8_uninit(n * 2)?, e.alloc_u8_uninit(n * 2)?));
2171                        }
2172                        // FA3 batched twin (round 31): TMA-swizzled wgmma vl when the
2173                        // promoted single-seq config is on; else the mma favl.
2174                        let fa3_on = match std::env::var("MEMRA_FA3").as_deref() {
2175                            Ok("0") => false,
2176                            Ok("1") => true,
2177                            _ => cfg!(memra_hopper_mma),
2178                        };
2179                        if fa3_on {
2180                            let mut q16s = Vec::with_capacity(b);
2181                            let mut v16s = Vec::with_capacity(b);
2182                            for s in 0..b {
2183                                let t = ts[s];
2184                                let mut q16 = e.alloc_u8_uninit(t * n_head * head_dim * 2)?;
2185                                e.f32_to_bf16_into(&aps[s].qn, &mut q16, t * n_head * head_dim)?;
2186                                let mut k16 = e.alloc_u8_uninit(t * n_head_kv * head_dim * 2)?;
2187                                e.f32_to_bf16_into(&aps[s].kn, &mut k16, t * n_head_kv * head_dim)?;
2188                                let mut v16 = e.alloc_u8_uninit(t * n_head_kv * head_dim * 2)?;
2189                                e.f32_to_bf16_v(&g3[2].slice(offs[s] * vf_w..(offs[s] + t) * vf_w),
2190                                                &mut v16, t * n_head_kv * head_dim)?;
2191                                q16s.push(q16);
2192                                v16s.push((k16, v16));
2193                            }
2194                            let mut qp = [core::ptr::null::<core::ffi::c_void>(); 8];
2195                            let mut kp = qp;
2196                            let mut vp = qp;
2197                            let mut op = [core::ptr::null_mut::<f32>(); 8];
2198                            let mut tsv = [0i32; 8];
2199                            for s in 0..b {
2200                                qp[s] = e.addr_u8(&q16s[s]) as *const core::ffi::c_void;
2201                                kp[s] = e.addr_u8(&v16s[s].0) as *const core::ffi::c_void;
2202                                vp[s] = e.addr_u8(&v16s[s].1) as *const core::ffi::c_void;
2203                                op[s] = e.addr_f32(&attns[s]) as *mut f32;
2204                                tsv[s] = ts[s] as i32;
2205                            }
2206                            let rc = unsafe {
2207                                crate::fa3_vl_raw(qp.as_ptr(), kp.as_ptr(), vp.as_ptr(), op.as_ptr(),
2208                                                  tsv.as_ptr(), b as i32, n_head as i32,
2209                                                  n_head_kv as i32, head_dim as i32, fa_scale,
2210                                                  e.stream().cu_stream() as *mut core::ffi::c_void)
2211                            };
2212                            if rc != 0 {
2213                                return Err(format!("memra_fa3_vl rc={rc}").into());
2214                            }
2215                        } else {
2216                            let fargs: Vec<crate::FaSeqVl> = (0..b).map(|s| crate::FaSeqVl {
2217                                q: e.addr_f32(&aps[s].qn), k16: e.addr_u8(&mirrors[s].0),
2218                                v16: e.addr_u8(&mirrors[s].1), o: e.addr_f32(&attns[s]),
2219                                kf: e.addr_f32(&aps[s].kn),
2220                                vf: e.addr_f32v(&g3[2].slice(offs[s] * vf_w..(offs[s] + ts[s]) * vf_w)),
2221                                t: ts[s] as i32, pad: 0,
2222                            }).collect();
2223                            e.fa_prefill_vl8(&fargs, head_dim, n_head, n_head_kv, fa_scale)?;
2224                        }
2225                        for (s, attn) in attns.into_iter().enumerate() {
2226                            let (attn_g, ag16) = self.full_attn_prime_post_fa(
2227                                e, attn, &aps[s].gate, ts[s], n_head, head_dim)?;
2228                            let mut done = false;
2229                            if let Some(xh) = &ag16 {
2230                                done = e.try_f16_gemm_pre_into_off(&fa.wo, xh, ts[s], &mut mixed, offs[s] * n_embd)?;
2231                            }
2232                            if !done {
2233                                let m = e.matmul(&fa.wo, &attn_g, ts[s])?;
2234                                e.copy_into(&mut mixed, offs[s] * n_embd, &m, ts[s] * n_embd)?;
2235                            }
2236                        }
2237                    } else {
2238                        let mut parts: Vec<Vec<CudaSlice<f32>>> = (0..b).map(|_| Vec::new()).collect();
2239                        for (w, y) in [&fa.wq, &fa.wk, &fa.wv].iter().zip(g3) {
2240                            for (s, ys) in split(e, &y, w.out_features())?.into_iter().enumerate() {
2241                                parts[s].push(ys);
2242                            }
2243                        }
2244                        for (s, g3s) in parts.into_iter().enumerate() {
2245                            // task #16 gather removal: wo writes into `mixed` at offs[s] directly.
2246                            let (attn_g, ag16) = self.full_attn_prime_core_inner(
2247                                e, fa, g3s, &pos_ds[s], ts[s], caches[s], il)?;
2248                            let mut done = false;
2249                            if let Some(xh) = &ag16 {
2250                                done = e.try_f16_gemm_pre_into_off(&fa.wo, xh, ts[s], &mut mixed, offs[s] * n_embd)?;
2251                            }
2252                            if !done {
2253                                let m = e.matmul(&fa.wo, &attn_g, ts[s])?;
2254                                e.copy_into(&mut mixed, offs[s] * n_embd, &m, ts[s] * n_embd)?;
2255                            }
2256                        }
2257                    }
2258                }
2259                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
2260                Mixer::Linear(la) => {
2261                    // task #16: NO split copies (cores read row-offset views of the concat
2262                    // outputs; out-GEMMs write into `mixed` at offs[s]). task #18: the core
2263                    // itself is BATCHED — per-seq prep/K1-K3, then ONE varlen K4 + ONE
2264                    // varlen K5 launch for all sequences.
2265                    let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
2266                    let g4 = e.matmul_group_xh(&ws, &h, &hx16, total)?;
2267                    let outs = self.linear_attn_prime_core_batch(e, la, &g4, &offs, &ts, caches, il)?;
2268                    for (s, (gn, gn16)) in outs.into_iter().enumerate() {
2269                        let (o, t) = (offs[s], ts[s]);
2270                        let mut done = false;
2271                        if let Some(xh) = &gn16 {
2272                            done = e.try_f16_gemm_pre_into_off(&la.ssm_out, xh, t, &mut mixed, o * n_embd)?;
2273                        }
2274                        if !done {
2275                            let m = e.matmul(&la.ssm_out, &gn, t)?;
2276                            e.copy_into(&mut mixed, o * n_embd, &m, t * n_embd)?;
2277                        }
2278                    }
2279                }
2280            }
2281            let mut x1 = e.uninit(total * n_embd)?;
2282            let mut z = e.uninit(total * n_embd)?;
2283            let mut zx16 = e.alloc_u8_uninit(total * n_embd * 2)?;
2284            e.add_rms_norm_f16out(&x, &mixed, layer.post_attn_norm.float_data(),
2285                                  &mut x1, &mut z, &mut zx16, n_embd, total, eps)?;
2286            let ffn_out = match &layer.ffn {
2287                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
2288                    let n_ff = ffn_gate.out_features();
2289                    let mut g2 = e.matmul_group_xh(&[ffn_gate, ffn_up], &z, &zx16, total)?;
2290                    let up = g2.pop().unwrap();
2291                    let gate = g2.pop().unwrap();
2292                    let mut act = e.uninit(total * n_ff)?;
2293                    // task #17 (batch trunk): silu twin emits the down GEMM's fp16 operand
2294                    // in-epilogue (nsys round-26: this trunk still paid 32 cvt passes).
2295                    // A clamped layer must skip the plain-SiLU twin (see prime_chunk's note).
2296                    let d_lim = self.cfg.clamp_shexp_at(il as u32);
2297                    if Self::f16out_on(e, total) && self.cfg.m3.is_none() && d_lim.is_none() {
2298                        let mut a16 = e.alloc_u8_uninit(total * n_ff * 2)?;
2299                        e.silu_mul_f16out(&gate, &up, &mut act, &mut a16, total * n_ff)?;
2300                        match e.try_f16_gemm_pre(ffn_down, &a16, total)? {
2301                            Some(y) => y,
2302                            None => e.matmul(ffn_down, &act, total)?,
2303                        }
2304                    } else {
2305                        Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0, d_lim,
2306                                          &mut act, total * n_ff)?;
2307                        e.matmul(ffn_down, &act, total)?
2308                    }
2309                }
2310                crate::hybrid::Ffn::Moe(m) => {
2311                    self.moe_ffn_il_prefill(e, m, &z, total, il as u16)?
2312                }
2313            };
2314            let mut x2 = e.uninit(total * n_embd)?;
2315            e.add(&x1, &ffn_out, &mut x2, total * n_embd)?;
2316            x = x2;
2317        }
2318        // epilogue per seq (identical math to prime_chunk: norm all rows, lm_head on last row)
2319        let mut hn = e.uninit(total * n_embd)?;
2320        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, total, eps)?;
2321        // batched lm_head (nsys round-26: B sequential m=1 matvecs re-read the 600MB
2322        // lm_head weight B times — 2.2ms at B=6): gather the B last rows and run ONE
2323        // m=B GEMM (f16 lane; falls back to the per-seq matvec when no mirror). The
2324        // f16-vs-mmvq logits delta is the prefill GEMM numeric class — prime_batch_gate's
2325        // argmax battery arbitrates, same as every other prefill GEMM change.
2326        let mut hcat = e.uninit(b * n_embd)?;
2327        for s in 0..b {
2328            let last0 = (offs[s] + ts[s] - 1) * n_embd;
2329            e.copy_view_into(&mut hcat, s * n_embd, &hn.slice(last0..last0 + n_embd), n_embd)?;
2330        }
2331        let logits_cat = if b >= 2 { e.try_f16_gemm(&self.output, &hcat, b)? } else { None };
2332        let logits_host: Option<Vec<f32>> = match &logits_cat {
2333            Some(lc) => Some(e.dtoh(lc)?),
2334            None => None,
2335        };
2336        let n_vocab = self.output.out_features();
2337        let mut hidden_all = if crate::spec::spec_hpost() {
2338            split(e, &hn, n_embd)?
2339        } else {
2340            split(e, &x, n_embd)?
2341        };
2342        let mut out = Vec::with_capacity(b);
2343        for s in 0..b {
2344            let last0 = (offs[s] + ts[s] - 1) * n_embd;
2345            let mut h_seed = e.uninit(n_embd)?;
2346            if !crate::spec::spec_hpost() {
2347                e.copy_view_into(&mut h_seed, 0, &x.slice(last0..last0 + n_embd), n_embd)?;
2348            } else {
2349                e.copy_view_into(&mut h_seed, 0, &hn.slice(last0..last0 + n_embd), n_embd)?;
2350            }
2351            let logits = match &logits_host {
2352                Some(lh) => lh[s * n_vocab..(s + 1) * n_vocab].to_vec(),
2353                None => {
2354                    let mut hlast = e.uninit(n_embd)?;
2355                    e.copy_view_into(&mut hlast, 0, &hn.slice(last0..last0 + n_embd), n_embd)?;
2356                    e.dtoh(&e.matmul(&self.output, &hlast, 1)?)?
2357                }
2358            };
2359            caches[s].pos += ts[s];
2360            out.push((logits, h_seed, hidden_all.remove(0)));
2361        }
2362        Ok(out)
2363    }
2364
2365    /// `full_attn` (batched prefill mixer) + the cache side-effect: append the T post-RoPE K/V
2366    /// rows into the resident quantized KV cache (q8_0 K / q5_1 V) and advance len/len_d. Row
2367    /// bytes are BIT-IDENTICAL to the decode append (same per-warp quant kernel per row; the
2368    /// batched `append_kv_quantized_rows` runs that exact warp math on a (block, token) grid).
2369    /// The attention itself is unchanged prefill math (fa_prefill over the f32 K/V).
2370    ///
2371    /// `seq_end` = the ABSOLUTE end position of the WHOLE prime request (`cache.pos + prompt_len`
2372    /// measured BEFORE the chunk loop starts), i.e. a chunk-size-invariant property of the request.
2373    /// Only step35's SWA arm reads it (`step35_attn_pre_wo`'s doc note explains why keying on the
2374    /// chunk's own `t_kv` made the output depend on MEMRA_PRIME_CHUNK); every other arch ignores it.
2375    #[allow(clippy::too_many_arguments)]
2376    fn full_attn_prime(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>,
2377                       hx: Option<&CudaSlice<u8>>,
2378                       pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize,
2379                       seq_end: usize)
2380                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2381        if self.cfg.step35.is_some() {
2382            return self.step35_attn_prime(e, fa, h, hx, pos_d, t, cache, il, seq_end);
2383        }
2384        // PROJ/CORE SPLIT (task #13, 2026-07-26): the q/k/v group projection is hoisted so
2385        // the cross-request batch driver can run it at m = sum_T over concatenated tokens;
2386        // this single-seq path composes proj+core identically (byte-for-byte the old body).
2387        // task #14: `hx` = the norm-fused fp16 twin of `h` (skips the convert launch).
2388        let g3 = match hx {
2389            Some(xh) => e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], h, xh, t)?,
2390            None => e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?,
2391        };
2392        self.full_attn_prime_core(e, fa, g3, pos_d, t, cache, il)
2393    }
2394
2395    /// Everything after the q/k/v projections (split/QK-norm/RoPE/FA/gate/append + wo).
2396    /// `g3` = matmul_group([wq, wk, wv]) output rows for THIS sequence.
2397    /// Composes inner + wo (== the pre-split core; every existing caller unchanged).
2398    fn full_attn_prime_core(&self, e: &Engine, fa: &FullAttnLayer, g3: Vec<CudaSlice<f32>>,
2399                            pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize)
2400                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2401        let (attn_g, ag16) = self.full_attn_prime_core_inner(e, fa, g3, pos_d, t, cache, il)?;
2402        if let Some(xh) = &ag16 {
2403            if let Some(y) = e.try_f16_gemm_pre(&fa.wo, xh, t)? {
2404                return Ok(y);
2405            }
2406        }
2407        Ok(e.matmul(&fa.wo, &attn_g, t)?)
2408    }
2409
2410    fn full_attn_prime_core_inner(&self, e: &Engine, fa: &FullAttnLayer, g3: Vec<CudaSlice<f32>>,
2411                            pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize)
2412                            -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2413        let cfg = &self.cfg;
2414        let geometry = cfg.full_attention_geometry_at(il as u32);
2415        let n_head = geometry.n_head as usize;
2416        let n_head_kv = geometry.n_head_kv as usize;
2417        let head_dim = geometry.head_dim_k as usize;
2418        let scale = geometry.attention_scale();
2419        let (pre, base_len) = self.full_attn_prime_pre_fa(e, fa, g3, pos_d, t, cache, il)?;
2420        let AttnPre { q, k, v, gate } = pre;
2421        let mut attn = e.uninit(t * n_head * head_dim)?;
2422        self.full_attn_prime_fa_dispatch(e, &q, &k, &v, &mut attn, base_len, t, cache, il,
2423                                         head_dim, n_head, n_head_kv, scale)?;
2424        self.full_attn_prime_post_fa(e, attn, &gate, t, n_head, head_dim)
2425    }
2426
2427    /// task #18 (attn side): projections tail through KV append — everything before the
2428    /// attention kernel. Returns the post-rope q/k, v, optional out-gate, and the KV rows
2429    /// present BEFORE this chunk's append (base_len; 0 == fresh).
2430    #[allow(clippy::type_complexity)]
2431    fn full_attn_prime_pre_fa(&self, e: &Engine, fa: &FullAttnLayer, mut g3: Vec<CudaSlice<f32>>,
2432                            pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache, il: usize)
2433                            -> Result<(AttnPre, usize), Box<dyn std::error::Error>> {
2434        let cfg = &self.cfg;
2435        let geometry = cfg.full_attention_geometry_at(il as u32);
2436        let n_head = geometry.n_head as usize;
2437        let n_head_kv = geometry.n_head_kv as usize;
2438        let head_dim = geometry.head_dim_k as usize;
2439        let eps = cfg.rms_eps;
2440
2441        // qwen35 fuses [q|gate] per head in wq (2*head_dim stride); M3/Hy3 have NO output gate
2442        // (attention_output_gate=false) — wq out = n_head*head_dim exactly, and q_gate_split
2443        // would read 2x out of bounds. `gated` keys both the split and the sigmoid epilogue.
2444        let gated = geometry.attention_gate
2445            == memra_gguf::config::AttentionGateKind::FusedQ;
2446        let v = g3.pop().unwrap();
2447        let mut k = g3.pop().unwrap();
2448        let qf = g3.pop().unwrap();
2449        let (mut q, gate) = if gated {
2450            let mut q = e.uninit(t * n_head * head_dim)?;
2451            let mut gate = e.uninit(t * n_head * head_dim)?;
2452            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
2453            (q, Some(gate))
2454        } else {
2455            (qf, None)
2456        };
2457
2458        let mut qn = e.uninit(t * n_head * head_dim)?;
2459        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head * t, eps)?;
2460        q = qn;
2461        let mut kn = e.uninit(t * n_head_kv * head_dim)?;
2462        e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, n_head_kv * t, eps)?;
2463        k = kn;
2464        let rope_dims = geometry.n_rot as usize;
2465        e.rope_neox(&mut q, pos_d, head_dim, rope_dims, n_head, t, geometry.rope_base, 1.0)?;
2466        e.rope_neox(&mut k, pos_d, head_dim, rope_dims, n_head_kv, t, geometry.rope_base, 1.0)?;
2467
2468        // CACHE SIDE-EFFECT: append the T post-rope K/V token rows (token-major [T, kv_dim] ==
2469        // the cache row layout) quantized into cache.kv[il], then advance len + device len_d.
2470        {
2471            let kvl = cache.kv[il].as_mut().unwrap();
2472            assert!(kvl.len + t <= cache.max_ctx, "prime_cache: KV overflow");
2473            e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len, t,
2474                                       kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
2475                                       crate::Engine::kv_fp8_on())?;
2476            kvl.len += t;
2477            let new_len = kvl.len as i32;
2478            e.set_i32_one(&mut kvl.len_d, new_len)?;
2479        }
2480
2481        let base_len = {
2482            let kvl = cache.kv[il].as_ref().unwrap();
2483            kvl.len - t   // KV rows present BEFORE this chunk's append above
2484        };
2485        Ok((AttnPre { q, k, v, gate }, base_len))
2486    }
2487
2488    /// batched prefill attention. FRESH prime (no past KV): unchanged forward_last math over
2489    /// the f32 K/V of this batch. CONTINUATION chunk (past KV present): the chunk's queries
2490    /// must attend to [0 .. base+t) — run fa_prefill_view over the resident QUANTIZED cache
2491    /// (the spec-verify pattern; kernel's causal mask offsets by T_kv-T). Numerically this
2492    /// reads q8_0/q5_1-dequantized K/V for the past AND the current chunk — the same class as
2493    /// decode reading the cache; the run-gen/first-16 battery is the accuracy authority.
2494    #[allow(clippy::too_many_arguments)]
2495    fn full_attn_prime_fa_dispatch(&self, e: &Engine, q: &CudaSlice<f32>, k: &CudaSlice<f32>,
2496                            v: &CudaSlice<f32>, attn: &mut CudaSlice<f32>, base_len: usize,
2497                            t: usize, cache: &mut Cache, il: usize,
2498                            head_dim: usize, n_head: usize, n_head_kv: usize, scale: f32)
2499                            -> Result<(), Box<dyn std::error::Error>> {
2500        // GRAIN-FREE CHUNK-INVARIANCE FIX (lane/chunkinv-flip, 2026-08-05): the base_len == 0
2501        // f32 special case (fa_prefill over this batch's f32 K/V) is DROPPED. pre_fa appends
2502        // the chunk's quantized rows into cache.kv[il] BEFORE this dispatch, so chunk 0 can
2503        // attend through the quantized cache exactly like every later chunk (quantize-then-
2504        // attend). One numeric class for every row => the chunk size cannot decide where a
2505        // precision edge falls, so chunked prefill is reduction-order-stable with NO grain
2506        // knob (the stronger fix VERDICT.md filed; supersedes the MEMRA_PRIME_INVARIANT door's
2507        // pin-the-boundary approach).
2508        // MEMRA_PRIME_F32CHUNK0=1 is the ROLLBACK SEAM to the old arithmetic (chunk 0 attends
2509        // f32 K/V) — flags-doctrine rollback door AND the chunkinv gate's canary injection:
2510        // with the fix unconditional, only re-introducing the class edge can prove the gate
2511        // still detects the mechanism. Never on in a measured default run.
2512        if base_len == 0 && std::env::var("MEMRA_PRIME_F32CHUNK0").as_deref() == Ok("1") {
2513            if std::env::var("MEMRA_NOFA").is_ok() || !(head_dim == 256 || head_dim == 128) {
2514                e.sdpa_naive(q, k, v, attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
2515            } else {
2516                e.fa_prefill(q, k, v, attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
2517            }
2518            return Ok(());
2519        }
2520        let kvl = cache.kv[il].as_ref().unwrap();
2521        let t_kv = base_len + t;
2522        let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
2523        let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
2524        // fa_prefill_q/_qw twins are stamped for head_dim 256 (qwen35) and 128 (M3) only;
2525        // other dims (and MEMRA_NOFA) take the naive quantized-view SDPA — SAME cache bytes,
2526        // same numeric class, so the uniform contract holds on the fallback too.
2527        if std::env::var("MEMRA_NOFA").is_ok() || !(head_dim == 256 || head_dim == 128) {
2528            e.sdpa_naive_quantized_view(q, &k_view, &v_view, attn, head_dim, n_head,
2529                                        n_head_kv, t, t_kv, scale, true,
2530                                        kvl.k_tok_bytes, kvl.v_tok_bytes)?;
2531            return Ok(());
2532        }
2533        // ARC B (2026-07-05): dequant-once workspace, DEFAULT ON. fa_prefill_q's inline
2534        // dequant re-reads+re-dequants the whole quantized KV stream from every one of the
2535        // T/64 x n_head CTAs (64x+ redundant at chunk=4096; 30.5% of the 32k prime wall).
2536        // fa_prefill_view_ws dequants K/V ONCE into a resident bf16 workspace then runs the
2537        // bit-identical bf16 twin (fa_prefill_qw) — same staged values, same FP order, token-
2538        // identical output (gate: MEMRA_PRIME_CHUNK=4096 ws-on vs ws-off vs monolithic).
2539        // MEMRA_PRIME_DEQW=0 reverts to the inline-dequant kernel.
2540        let deqw = std::env::var("MEMRA_PRIME_DEQW").map(|v| v != "0").unwrap_or(true);
2541        if deqw {
2542            e.fa_prefill_view_ws(q, &k_view, &v_view, attn, head_dim, n_head, n_head_kv,
2543                                 t, t_kv, scale, true, kvl.k_tok_bytes, kvl.v_tok_bytes,
2544                                 crate::Engine::kv_fp8_on())?;
2545        } else {
2546            e.fa_prefill_view(q, &k_view, &v_view, attn, head_dim, n_head, n_head_kv,
2547                              t, t_kv, scale, true, kvl.k_tok_bytes, kvl.v_tok_bytes,
2548                              crate::Engine::kv_fp8_on())?;
2549        }
2550        Ok(())
2551    }
2552
2553    /// task #17: sig_mul_f16out fuses [sigmoid + mul + f16 convert] into one launch
2554    /// (bit-identical composition) and hands wo its fp16 operand directly.
2555    fn full_attn_prime_post_fa(&self, e: &Engine, attn: CudaSlice<f32>,
2556                            gate: &Option<CudaSlice<f32>>, t: usize,
2557                            n_head: usize, head_dim: usize)
2558                            -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2559        let (attn_g, ag16) = match gate {
2560            Some(gate) => {
2561                let n = t * n_head * head_dim;
2562                let mut ag = e.uninit(n)?;
2563                if Self::f16out_on(e, t) {
2564                    let mut a16 = e.alloc_u8_uninit(n * 2)?;
2565                    e.sig_mul_f16out(&attn, gate, &mut ag, &mut a16, n)?;
2566                    (ag, Some(a16))
2567                } else {
2568                    let mut gsig = e.uninit(n)?;
2569                    e.sigmoid(gate, &mut gsig, n)?;
2570                    e.mul(&attn, &gsig, &mut ag, n)?;
2571                    (ag, None)
2572                }
2573            }
2574            None => (attn, None),
2575        };
2576        Ok((attn_g, ag16))
2577    }
2578
2579    /// STATEFUL batched linear-attention prime: `linear_attn`'s prefill-dispatch pass (normal
2580    /// `e.matmul` — GEMM at m>=16 — plus the prefill repack/L2/glog kernels) but with the state
2581    /// carried THROUGH the cache like the spec verify does: carried-ring conv
2582    /// (ssm_conv1d_tm_state writes the final ring back) + ONE gdn_scan from cache.recur[il]'s
2583    /// current state (zero at a fresh prime) whose final state ping-pongs back into the cache.
2584    /// Wiring mirrors `linear_attn_verify_t` (spec.rs); dispatch mirrors `linear_attn` (prefill).
2585    fn linear_attn_prime(&self, e: &Engine, la: &LinearAttnLayer, h: &CudaSlice<f32>,
2586                         hx: Option<&CudaSlice<u8>>, t: usize,
2587                         cache: &mut Cache, il: usize)
2588                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2589        // PROJ/CORE SPLIT (task #13): see full_attn_prime — same hoist for the GDN 4-tuple.
2590        let ws = [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha];
2591        let g4 = match hx {
2592            Some(xh) => e.matmul_group_xh(&ws, h, xh, t)?,
2593            None => e.matmul_group(&ws, h, t)?,
2594        };
2595        self.linear_attn_prime_core(e, la, g4, t, cache, il)
2596    }
2597
2598    /// Everything after the GDN 4-tuple projections (conv/chunk stack/gated norm + ssm_out).
2599    fn linear_attn_prime_core(&self, e: &Engine, la: &LinearAttnLayer, mut g4: Vec<CudaSlice<f32>>,
2600                              t: usize, cache: &mut Cache, il: usize)
2601                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2602        self.linear_attn_prime_core_pad(e, la, g4.drain(..).collect(), t, cache, il, None)
2603    }
2604
2605    /// task #14: `pad_len` = device true length for PADDED prime graphs. Pads become
2606    /// identity GDN steps (gdn_pad_mask zeroes beta/g_log past the true length) and the
2607    /// conv ring writes back from the true tail. None = classic path, byte-identical.
2608    #[allow(clippy::too_many_arguments)]
2609    fn linear_attn_prime_core_pad_inner(&self, e: &Engine, la: &LinearAttnLayer, mut g4: Vec<CudaSlice<f32>>,
2610                              t: usize, cache: &mut Cache, il: usize,
2611                              pad_len: Option<&CudaSlice<i32>>)
2612                              -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2613        // shim over the view twin (task #16): full-range views of the owned buffers.
2614        let ssm = self.cfg.ssm.as_ref().unwrap();
2615        let d_state = ssm.state_size as usize;
2616        let num_k = ssm.group_count as usize;
2617        let num_v = ssm.time_step_rank as usize;
2618        let key_dim = d_state * num_k;
2619        let value_dim = d_state * num_v;
2620        let conv_dim = key_dim * 2 + value_dim;
2621        let alpha = g4.pop().unwrap();                   // [T, num_v]
2622        let beta_raw = g4.pop().unwrap();                // [T, num_v]
2623        let z = g4.pop().unwrap();                       // [T, value_dim]
2624        let qkv_mixed = g4.pop().unwrap();               // [T, conv_dim] token-major
2625        self.linear_attn_prime_core_pad_view(
2626            e, la,
2627            &qkv_mixed.slice(0..t * conv_dim), &z.slice(0..t * value_dim),
2628            &beta_raw.slice(0..t * num_v), &alpha.slice(0..t * num_v),
2629            t, cache, il, pad_len)
2630    }
2631
2632    /// task #18: the GDN prep stage (conv + repack + l2 x2 + sigmoid + glog + pad-mask) —
2633    /// shared verbatim by the per-seq scan path and the varlen batched path.
2634    #[allow(clippy::too_many_arguments)]
2635    fn linear_attn_gdn_prep(&self, e: &Engine, la: &LinearAttnLayer,
2636                            qkv_mixed: &cudarc::driver::CudaView<f32>,
2637                            beta_raw: &cudarc::driver::CudaView<f32>,
2638                            alpha: &cudarc::driver::CudaView<f32>,
2639                            t: usize, cache: &mut Cache, il: usize,
2640                            pad_len: Option<&CudaSlice<i32>>)
2641                            -> Result<GdnPrep, Box<dyn std::error::Error>> {
2642        let cfg = &self.cfg;
2643        let ssm = cfg.ssm.as_ref().unwrap();
2644        let d_state = ssm.state_size as usize;       // 128
2645        let num_k = ssm.group_count as usize;        // 16
2646        let num_v = ssm.time_step_rank as usize;     // 32
2647        let d_conv = ssm.conv_kernel as usize;       // 4
2648        let key_dim = d_state * num_k;               // 2048
2649        let value_dim = d_state * num_v;             // 4096
2650        let conv_dim = key_dim * 2 + value_dim;      // 8192
2651        let eps = cfg.rms_eps;
2652        debug_assert!(t >= d_conv - 1, "stateful conv needs T >= pad (PRIME_MIN_T gates)");
2653
2654        // conv with CARRIED ring state + ring roll (state read + final-window write-back).
2655        // task #18 conv-fuse (default ON): conv + SiLU + repack in one pass — the 67MB
2656        // conv_out intermediate and its transposed re-read disappear (values bit-identical).
2657        // MEMRA_CONV_FUSE=0 reverts to the two-kernel chain.
2658        let rl = cache.recur[il].as_mut().unwrap();
2659        let hk = Self::gdn_hk(e, t, num_v, num_k);
2660        let conv_fuse = std::env::var("MEMRA_CONV_FUSE").as_deref() != Ok("0");
2661        let hk = if conv_fuse { hk } else { num_v };   // de-broadcast rides the fused conv
2662        let mut q_g = e.uninit(d_state * hk * t)?;
2663        let mut k_g = e.uninit(d_state * hk * t)?;
2664        let mut v_g = e.uninit(d_state * num_v * t)?;
2665        if conv_fuse {
2666            e.ssm_conv1d_gdn_state_pad(qkv_mixed, &mut rl.conv_state, la.ssm_conv1d.float_data(),
2667                                  &mut q_g, &mut k_g, &mut v_g,
2668                                  conv_dim, t, d_conv, d_state, num_v, num_k, key_dim, hk, pad_len)?;
2669        } else {
2670            let mut conv_out = e.uninit(conv_dim * t)?;      // [conv_dim, T] channel-major, SiLU
2671            e.ssm_conv1d_tm_state_pad_v(qkv_mixed, &mut rl.conv_state, la.ssm_conv1d.float_data(),
2672                                  &mut conv_out, conv_dim, t, d_conv, pad_len)?;
2673            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)?;
2674        }
2675        let mut q_l2 = e.uninit(d_state * hk * t)?;
2676        // mirror-fold (round 35): q's bf16 twin (wgmma K45/K2 A-operand) in-epilogue too.
2677        // Emitted only where a consumer exists (the wgmma config) — on other arches the
2678        // alloc + epilogue stores would be pure waste.
2679        let qb16 = if Engine::l2_v2_on(d_state) && e.gdn_wgmma_on(32) {
2680            let mut qb = e.alloc_u8_uninit(d_state * hk * t * 2)?;
2681            e.l2_norm_pp(&q_g, &mut q_l2, Some(&mut qb), d_state, hk * t, eps)?;
2682            Some(qb)
2683        } else {
2684            e.l2_norm_pp(&q_g, &mut q_l2, None, d_state, hk * t, eps)?;
2685            None
2686        };
2687        let mut k_l2 = e.uninit(d_state * hk * t)?;
2688        // mirror-fold: emit k's bf16 twin (the chunked-scan kb16 mirror) in-epilogue
2689        let kb16 = if Engine::l2_v2_on(d_state) {
2690            let mut kb = e.alloc_u8_uninit(d_state * hk * t * 2)?;
2691            e.l2_norm_pp(&k_g, &mut k_l2, Some(&mut kb), d_state, hk * t, eps)?;
2692            Some(kb)
2693        } else {
2694            e.l2_norm_pp(&k_g, &mut k_l2, None, d_state, hk * t, eps)?;
2695            None
2696        };
2697        let mut beta = e.uninit(t * num_v)?;
2698        e.sigmoid_v(beta_raw, &mut beta, t * num_v)?;
2699        let mut g_log = e.uninit(t * num_v)?;
2700        e.gdn_glog_v(alpha, la.ssm_dt.float_data(), la.ssm_a.float_data(), &mut g_log, num_v, t)?;
2701        if let Some(len_d) = pad_len {
2702            e.gdn_pad_mask(&mut beta, &mut g_log, len_d, num_v, t)?;
2703        }
2704        Ok(GdnPrep { hk, q_l2, k_l2, v_g, beta, g_log, kb16, qb16 })
2705    }
2706
2707    /// task #18: batched GDN mixer core — per-seq prep + K1-K3, then ONE varlen K4 and
2708    /// ONE varlen K5 launch for all B sequences (full-machine occupancy vs B underfilled
2709    /// per-seq trains). Per-block math identical to the per-seq path (bit-gateable);
2710    /// MEMRA_GDN_VL=0 or a non-mma/non-C32 config falls back to the per-seq loop.
2711    #[allow(clippy::too_many_arguments)]
2712    fn linear_attn_prime_core_batch(&self, e: &Engine, la: &LinearAttnLayer,
2713                                    g4: &[CudaSlice<f32>], offs: &[usize], ts: &[usize],
2714                                    caches: &mut [&mut Cache], il: usize)
2715                                    -> Result<Vec<(CudaSlice<f32>, Option<CudaSlice<u8>>)>, Box<dyn std::error::Error>> {
2716        let ssm = self.cfg.ssm.as_ref().unwrap();
2717        let d_state = ssm.state_size as usize;
2718        let num_k = ssm.group_count as usize;
2719        let num_v = ssm.time_step_rank as usize;
2720        let key_dim = d_state * num_k;
2721        let value_dim = d_state * num_v;
2722        let conv_dim = key_dim * 2 + value_dim;
2723        let eps = self.cfg.rms_eps;
2724        let scale = 1.0 / (d_state as f32).sqrt();
2725        let b = ts.len();
2726        let c = Engine::gdn_chunk_size();
2727        // CONTINUATION batches (increment (b)) take the per-seq stateful pad_view twin
2728        // below — the varlen K4/K5 chain is fresh-only (zero initial state assumed).
2729        let carried = caches.iter().any(|c| c.pos > 0);
2730        let use_vl = !carried
2731            && (2..=8).contains(&b)
2732            && Engine::gdn_chunked_enabled() && ts.iter().all(|&t| t >= 16)
2733            && e.gdn_mma_enabled(c)
2734            && std::env::var("MEMRA_GDN_VL").as_deref() != Ok("0");
2735        if !use_vl {
2736            return (0..b).map(|s| {
2737                let (o, t) = (offs[s], ts[s]);
2738                self.linear_attn_prime_core_pad_view(
2739                    e, la,
2740                    &g4[0].slice(o * conv_dim..(o + t) * conv_dim),
2741                    &g4[1].slice(o * value_dim..(o + t) * value_dim),
2742                    &g4[2].slice(o * num_v..(o + t) * num_v),
2743                    &g4[3].slice(o * num_v..(o + t) * num_v),
2744                    t, caches[s], il, None)
2745            }).collect();
2746        }
2747        // increment 3: the ENTIRE core is varlen — allocs only per seq, then 13 launches
2748        // total for the whole batch: [conv, ring, repack, l2(q+k), gate-prep] +
2749        // [k-mirror, K1, K2, K3, w-mirror, K4, K5] + [gated-norm tail].
2750        struct SeqBufs {
2751            conv_out: CudaSlice<f32>, q_g: CudaSlice<f32>, k_g: CudaSlice<f32>, v_g: CudaSlice<f32>,
2752            q_l2: CudaSlice<f32>, k_l2: CudaSlice<f32>, beta: CudaSlice<f32>, g_log: CudaSlice<f32>,
2753            gn: CudaSlice<f32>, gn16: CudaSlice<u8>,
2754        }
2755        let d_conv = ssm.conv_kernel as usize;
2756        let f16o = Self::f16out_on(e, 16);
2757        let hk = Self::gdn_hk(e, 16, num_v, num_k);   // vl path is always chunked+mma
2758        let mut sb = Vec::with_capacity(b);
2759        let mut pres = Vec::with_capacity(b);
2760        for &t in ts.iter().take(b) {
2761            sb.push(SeqBufs {
2762                conv_out: e.uninit(conv_dim * t)?,
2763                q_g: e.uninit(d_state * hk * t)?,
2764                k_g: e.uninit(d_state * hk * t)?,
2765                v_g: e.uninit(d_state * num_v * t)?,
2766                q_l2: e.uninit(d_state * hk * t)?,
2767                k_l2: e.uninit(d_state * hk * t)?,
2768                beta: e.uninit(t * num_v)?,
2769                g_log: e.uninit(t * num_v)?,
2770                gn: e.uninit(d_state * num_v * t)?,
2771                gn16: e.alloc_u8_uninit(d_state * num_v * t * 2)?,
2772            });
2773            pres.push(e.gdn_chunk_alloc(num_v, t, c, hk)?);
2774        }
2775        let prep_args: Vec<crate::GdnPrepVl> = (0..b).map(|s| {
2776            let (o, t) = (offs[s], ts[s]);
2777            let rl = caches[s].recur[il].as_ref().unwrap();
2778            crate::GdnPrepVl {
2779                qkv: e.addr_f32v(&g4[0].slice(o * conv_dim..(o + t) * conv_dim)),
2780                conv_state: e.addr_f32(&rl.conv_state),
2781                conv_out: e.addr_f32(&sb[s].conv_out),
2782                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),
2783                q_l2: e.addr_f32(&sb[s].q_l2), k_l2: e.addr_f32(&sb[s].k_l2),
2784                beta_raw: e.addr_f32v(&g4[2].slice(o * num_v..(o + t) * num_v)),
2785                alpha: e.addr_f32v(&g4[3].slice(o * num_v..(o + t) * num_v)),
2786                beta: e.addr_f32(&sb[s].beta), g_log: e.addr_f32(&sb[s].g_log),
2787                o: e.addr_f32(&pres[s].o),
2788                z: e.addr_f32v(&g4[1].slice(o * value_dim..(o + t) * value_dim)),
2789                gn: e.addr_f32(&sb[s].gn), gn16: e.addr_u8(&sb[s].gn16),
2790                kb16: if Engine::l2_v2_on(d_state) { e.addr_u8(&pres[s].kb16) } else { 0 },
2791                qb16: if Engine::l2_v2_on(d_state) && e.gdn_wgmma_on(c) { e.addr_u8(&pres[s].qb16) } else { 0 },
2792                t: t as i32, pad: 0,
2793            }
2794        }).collect();
2795        let args: Vec<crate::GdnSeqVl> = (0..b).map(|s| {
2796            let rl = caches[s].recur[il].as_ref().unwrap();
2797            crate::GdnSeqVl {
2798                kb16: e.addr_u8(&pres[s].kb16), gcum: e.addr_f32(&pres[s].gcum),
2799                beta: e.addr_f32(&sb[s].beta), u: e.addr_f32(&pres[s].u),
2800                wb16: e.addr_u8(&pres[s].wb16), y: e.addr_u8(&pres[s].y16),
2801                ssnap: e.addr_u8(&pres[s].ssnap16),
2802                state_in: e.addr_f32(&rl.ssm_state), state_out: e.addr_f32(&rl.ssm_state_alt),
2803                q: e.addr_f32(&sb[s].q_l2), p: e.addr_f32(&pres[s].p),
2804                o: e.addr_f32(&pres[s].o),
2805                k: e.addr_f32(&sb[s].k_l2), v: e.addr_f32(&sb[s].v_g),
2806                g: e.addr_f32(&sb[s].g_log), a: e.addr_f32(&pres[s].a),
2807                w: e.addr_f32(&pres[s].w),
2808                t: ts[s] as i32, nc: pres[s].nc as i32,
2809            }
2810        }).collect();
2811        e.gdn_prep_vl8(&prep_args, la.ssm_conv1d.float_data(), la.ssm_dt.float_data(),
2812                       la.ssm_a.float_data(), conv_dim, d_conv, d_state, num_v, num_k, key_dim, hk, eps)?;
2813        // mirror-fold (round 27): l2 v2 emits kb16 in-epilogue; K3's store emits wb16 —
2814        // both standalone mirror launches vanish on the default config.
2815        if !Engine::l2_v2_on(d_state) {
2816            e.gdn_mirror_vl8(&args, num_v, 0, hk)?;
2817        }
2818        // task #22: wgmma-fused vl twins — qb16 mirrors + GdnWVl8 side-struct.
2819        let wq8: Option<crate::GdnWVl8> = if e.gdn_wgmma_on(c) {
2820            // qb16 emitted by the vl l2 mirror-fold when l2-v2 serves; bulk cvt otherwise
2821            if !Engine::l2_v2_on(d_state) {
2822                for s in 0..b {
2823                    e.f32_to_bf16_into(&sb[s].q_l2, &mut pres[s].qb16, d_state * hk * ts[s])?;
2824                }
2825            }
2826            let mut wa = [crate::GdnWVl::default(); 8];
2827            for s in 0..b {
2828                wa[s] = crate::GdnWVl { qb16: e.addr_u8(&pres[s].qb16), pb16: e.addr_u8(&pres[s].pb16) };
2829            }
2830            Some(crate::GdnWVl8(wa))
2831        } else { None };
2832        e.gdn_chunk_k123_vl8(&args, num_v, hk, wq8.as_ref())?;
2833        e.gdn_chunk_vl8(&args, num_v, scale, hk, wq8.as_ref())?;
2834        if f16o {
2835            e.gdn_tail_vl8(&prep_args, la.ssm_norm.float_data(), d_state, num_v, eps)?;
2836        }
2837        // per-seq state swap (+ non-f16out tail fallback)
2838        let mut out = Vec::with_capacity(b);
2839        for (s, bufs) in sb.into_iter().enumerate() {
2840            let rl = caches[s].recur[il].as_mut().unwrap();
2841            std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2842            let (o, t) = (offs[s], ts[s]);
2843            let SeqBufs { mut gn, gn16, .. } = bufs;
2844            if f16o {
2845                out.push((gn, Some(gn16)));
2846            } else {
2847                let z_v = g4[1].slice(o * value_dim..(o + t) * value_dim);
2848                e.gated_rmsnorm_zv(&pres[s].o, la.ssm_norm.float_data(), &z_v, &mut gn,
2849                                   d_state, num_v * t, eps)?;
2850                out.push((gn, None));
2851            }
2852        }
2853        Ok(out)
2854    }
2855
2856    /// task #16: view-consuming GDN prime core — the batched prime hands row-offset
2857    /// views of the CONCAT projection outputs directly (no per-seq split copies).
2858    /// Same kernels, same values, byte-identical to the Vec shim above.
2859    #[allow(clippy::too_many_arguments)]
2860    fn linear_attn_prime_core_pad_view(&self, e: &Engine, la: &LinearAttnLayer,
2861                              qkv_mixed: &cudarc::driver::CudaView<f32>,
2862                              z: &cudarc::driver::CudaView<f32>,
2863                              beta_raw: &cudarc::driver::CudaView<f32>,
2864                              alpha: &cudarc::driver::CudaView<f32>,
2865                              t: usize, cache: &mut Cache, il: usize,
2866                              pad_len: Option<&CudaSlice<i32>>)
2867                              -> Result<(CudaSlice<f32>, Option<CudaSlice<u8>>), Box<dyn std::error::Error>> {
2868        let cfg = &self.cfg;
2869        let ssm = cfg.ssm.as_ref().unwrap();
2870        let d_state = ssm.state_size as usize;       // 128
2871        let num_v = ssm.time_step_rank as usize;     // 32
2872        let eps = cfg.rms_eps;
2873        let scale = 1.0 / (d_state as f32).sqrt();
2874
2875        let prep = self.linear_attn_gdn_prep(e, la, qkv_mixed, beta_raw, alpha, t, cache, il, pad_len)?;
2876
2877        // ONE gdn_scan over T from the cache's CURRENT state (zero at fresh prime); the final
2878        // state lands in the spare buffer and ping-pongs back (stable resident pointers, the
2879        // decode-determinism discipline from linear_attn_decode_inner). A4: `gdn_scan_prefill`
2880        // dispatches the chunked WY form under MEMRA_GDN_CHUNKED (prefill-only seam; decode +
2881        // verify keep the sequential kernel).
2882        let mut o = e.uninit(d_state * num_v * t)?;
2883        let rl = cache.recur[il].as_mut().unwrap();
2884        {
2885            let crate::cache::RecurLayer { ssm_state, ssm_state_alt, .. } = rl;
2886            e.gdn_scan_prefill(&prep.q_l2, &prep.k_l2, &prep.v_g, &prep.g_log, &prep.beta,
2887                               prep.kb16.as_ref(), prep.qb16.as_ref(), ssm_state, ssm_state_alt, &mut o, num_v, t, scale,
2888                               prep.hk)?;
2889        }
2890        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2891
2892        // gated RMSNorm + out projection (prefill dispatch). task #17: the f16out twin also
2893        // emits the ssm_out GEMM's fp16 operand in-epilogue (kills the standalone convert).
2894        let mut gn = e.uninit(d_state * num_v * t)?;
2895        let gn16 = if Self::f16out_on(e, t) {
2896            let mut g16 = e.alloc_u8_uninit(d_state * num_v * t * 2)?;
2897            e.gated_rmsnorm_f16out_zv(&o, la.ssm_norm.float_data(), z, &mut gn, &mut g16,
2898                                      d_state, num_v * t, eps)?;
2899            Some(g16)
2900        } else {
2901            e.gated_rmsnorm_zv(&o, la.ssm_norm.float_data(), z, &mut gn, d_state, num_v * t, eps)?;
2902            None
2903        };
2904        Ok((gn, gn16))
2905    }
2906
2907    /// Task #15 core-split wrapper: composes inner + ssm_out (== the old core).
2908    #[allow(clippy::too_many_arguments)]
2909    fn linear_attn_prime_core_pad(&self, e: &Engine, la: &LinearAttnLayer, g4: Vec<CudaSlice<f32>>,
2910                              t: usize, cache: &mut Cache, il: usize,
2911                              pad_len: Option<&CudaSlice<i32>>)
2912                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2913        let (gn, gn16) = self.linear_attn_prime_core_pad_inner(e, la, g4, t, cache, il, pad_len)?;
2914        if let Some(xh) = &gn16 {
2915            if let Some(y) = e.try_f16_gemm_pre(&la.ssm_out, xh, t)? {
2916                return Ok(y);
2917            }
2918        }
2919        Ok(e.matmul(&la.ssm_out, &gn, t)?)
2920    }
2921
2922    /// Full-attention mixer with QK-norm, partial RoPE, sigmoid output gate (qwen35 :257-336).
2923    ///
2924    /// `il` = layer index: step35 needs it (per-layer n_head / rope width / window / gate) and
2925    /// routes to its own mixer. Every other arch ignores it (uniform geometry).
2926    pub fn full_attn(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize, il: usize)
2927                 -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2928        if self.cfg.step35.is_some() {
2929            return self.step35_attn(e, fa, h, pos_d, t, il);
2930        }
2931        let cfg = &self.cfg;
2932        let _n_embd = cfg.n_embd as usize;
2933        let geometry = cfg.full_attention_geometry_at(il as u32);
2934        let n_head = geometry.n_head as usize;
2935        let n_head_kv = geometry.n_head_kv as usize;
2936        let head_dim = geometry.head_dim_k as usize;
2937        let eps = cfg.rms_eps;
2938        let scale = geometry.attention_scale();
2939
2940        // qwen35: wq output = head_dim*2*n_head (fused [q|gate] per head). M3/Hy3: NO output
2941        // gate — wq out = n_head*head_dim, no split (see prime-path note).
2942        let gated = geometry.attention_gate
2943            == memra_gguf::config::AttentionGateKind::FusedQ;
2944        // grouped: one f16 activation convert feeds q/k/v (matmul_group)
2945        let mut g3 = e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?;
2946        let v = g3.pop().unwrap();
2947        let mut k = g3.pop().unwrap();
2948        let qf = g3.pop().unwrap();
2949        let (mut q, gate) = if gated {
2950            let mut q = e.uninit(t * n_head * head_dim)?;
2951            let mut gate = e.uninit(t * n_head * head_dim)?;
2952            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
2953            (q, Some(gate))
2954        } else {
2955            (qf, None)
2956        };
2957
2958        // QK-norm (per head_dim row), then partial RoPE.
2959        let mut qn = e.uninit(t * n_head * head_dim)?;
2960        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head * t, eps)?;
2961        q = qn;
2962        let mut kn = e.uninit(t * n_head_kv * head_dim)?;
2963        e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, n_head_kv * t, eps)?;
2964        k = kn;
2965        let rope_dims = geometry.n_rot as usize;
2966        e.rope_neox(&mut q, pos_d, head_dim, rope_dims, n_head, t, geometry.rope_base, 1.0)?;
2967        e.rope_neox(&mut k, pos_d, head_dim, rope_dims, n_head_kv, t, geometry.rope_base, 1.0)?;
2968
2969        // SDPA
2970        let mut attn = e.uninit(t * n_head * head_dim)?;
2971        // hand-written FlashAttention prefill (head_dim 256/128 stamped twins). MEMRA_NOFA
2972        // falls back to naive sdpa.
2973        if std::env::var("MEMRA_NOFA").is_ok() || !(head_dim == 256 || head_dim == 128) {
2974            // head_dim gate: see prime-path note (fa_prefill is stamped at 256 and 128 only).
2975            e.sdpa_naive(&q, &k, &v, &mut attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
2976        } else {
2977            e.fa_prefill(&q, &k, &v, &mut attn, head_dim, n_head, n_head_kv, t, t, scale, true)?;
2978        }
2979
2980        // output gate: attn * sigmoid(gate) — qwen35 only (M3 has no gate).
2981        let attn_g = match &gate {
2982            Some(gate) => {
2983                let mut gsig = e.uninit(t * n_head * head_dim)?;
2984                e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
2985                let mut ag = e.uninit(t * n_head * head_dim)?;
2986                e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
2987                ag
2988            }
2989            None => attn,
2990        };
2991
2992        // o projection
2993        let o = e.matmul(&fa.wo, &attn_g, t)?;
2994        Ok(o)
2995    }
2996
2997    /// Linear-attention (Gated DeltaNet) mixer (qwen35 :338-470).
2998    pub fn linear_attn(&self, e: &Engine, la: &LinearAttnLayer, h: &CudaSlice<f32>, t: usize)
2999                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3000        let cfg = &self.cfg;
3001        let _n_embd = cfg.n_embd as usize;
3002        let ssm = cfg.ssm.as_ref().unwrap();
3003        let d_state = ssm.state_size as usize;       // 128
3004        let num_k = ssm.group_count as usize;        // 16
3005        let num_v = ssm.time_step_rank as usize;     // 32
3006        let d_conv = ssm.conv_kernel as usize;       // 4
3007        let head_k = d_state; let head_v = d_state;
3008        let key_dim = head_k * num_k;                // 2048
3009        let value_dim = head_v * num_v;              // 4096
3010        let conv_dim = key_dim * 2 + value_dim;      // 8192
3011        let eps = cfg.rms_eps;
3012        let scale = 1.0 / (d_state as f32).sqrt();
3013
3014        // projections
3015        // grouped: one f16 activation convert feeds all four projections (matmul_group)
3016        let mut g4 = e.matmul_group(&[&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha], h, t)?;
3017        let alpha = g4.pop().unwrap();                   // [T, num_v]
3018        let beta_raw = g4.pop().unwrap();                // [T, num_v]
3019        let z = g4.pop().unwrap();                       // [T, value_dim]
3020        let qkv_mixed = g4.pop().unwrap();               // [T, conv_dim] token-major
3021
3022        // conv + GDN repack, FUSED (2026-07-03): ssm_conv1d_gdn reads qkv_mixed [T, conv_dim]
3023        // token-major DIRECTLY (causal window rows t-pad..t, rows<0 = zero prefill state), applies
3024        // the 8-tap conv + SiLU, and scatters straight into the GDN [d_state, num_v, T] q/k/v
3025        // layout with the modulo head-repeat. Replaces transpose + zeros + conv_left_pad +
3026        // ssm_conv1d + qkv_to_gdn_repack (5 launches, conv_in/conv_out scratch + a 16MB@T=512
3027        // round-trip). BIT-IDENTICAL accumulation and scatter mapping.
3028        let _ = (head_k, head_v);
3029        let mut q_g = e.uninit(d_state * num_v * t)?;
3030        let mut k_g = e.uninit(d_state * num_v * t)?;
3031        let mut v_g = e.uninit(d_state * num_v * t)?;
3032        e.ssm_conv1d_gdn(&qkv_mixed, la.ssm_conv1d.float_data(), &mut q_g, &mut k_g, &mut v_g,
3033                         conv_dim, t, d_conv, d_state, num_v, num_k, key_dim)?;
3034        // L2-norm q,k per (head_dim) row — rows are contiguous d_state in q_g.
3035        let mut q_l2 = e.uninit(d_state * num_v * t)?;
3036        e.l2_norm(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
3037        let mut k_l2 = e.uninit(d_state * num_v * t)?;
3038        e.l2_norm(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
3039        let v_gd = v_g;
3040
3041        // beta = sigmoid(beta_raw) ; g_log = a * softplus(alpha + dt). Both need [num_v, T] layout
3042        // (g[t*num_v + h]). beta_raw/alpha are [T, num_v] token-major == that layout already.
3043        let mut beta = e.uninit(t * num_v)?;
3044        e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
3045        // gdn_glog expects alpha [H,T] with alpha[t*H+h] and dt_bias/a [H] — matches token-major [T,num_v].
3046        let mut g_log = e.uninit(t * num_v)?;
3047        e.gdn_glog(&alpha, la.ssm_dt.float_data(), la.ssm_a.float_data(), &mut g_log, num_v, t)?;
3048
3049        // GDN scan (A4: gdn_scan_prefill dispatches chunked WY under MEMRA_GDN_CHUNKED)
3050        let state_in = e.zeros(d_state * d_state * num_v)?;  // zero state (prefill)
3051        let mut state_out = e.zeros(d_state * d_state * num_v)?;
3052        let mut o = e.uninit(d_state * num_v * t)?;
3053        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)?;
3054
3055        // gated RMSNorm: dst = RMSNorm(o, ssm_norm[head_v]) * silu(z). o is [d_state, num_v, T];
3056        // rows of head_v=d_state, nrows = num_v*T. z must match row layout: z is [T, value_dim] token-major
3057        // = [T, num_v*head_v]; per (t, vh) the head_v slice is contiguous -> rows align as (t*num_v+vh).
3058        // o rows are (t*num_v+vh) too. Good.
3059        let mut gn = e.uninit(d_state * num_v * t)?;
3060        e.gated_rmsnorm(&o, la.ssm_norm.float_data(), &z, &mut gn, d_state, num_v * t, eps)?;
3061
3062        // ssm_out projection: gn is [d_state, num_v, T] = [value_dim, T] viewed token-major as [T, value_dim]?
3063        // gn layout: (t*num_v+vh)*d_state + i  == token t, then (vh,i) = channel vh*d_state+i. That's
3064        // token-major [T, value_dim]. linear wants [T, in=value_dim]. Good.
3065        let out = e.matmul(&la.ssm_out, &gn, t)?;
3066        Ok(out)
3067    }
3068}
3069
3070impl HybridModel {
3071    /// MoE FFN (EDGE-1). z: [T, n_embd] (already post-attention-normed). Returns moe_out [T, n_embd].
3072    /// Node-for-node vs llama.cpp build_moe_ffn + qwen35moe::build_layer_ffn.
3073    ///
3074    /// `il` is the trunk layer index — the residency-cache key prefix (a gate-expert of layer 3 is a
3075    /// different 860160-byte block than the same expert of layer 7).
3076    ///
3077    /// Routing: host softmax+sort (default) OR the fused router kernel (MEMRA_FUSED_ROUTER).
3078    /// Dispatch: stage-every-token into 3 scratch slots (default) OR the SLRU residency cache
3079    /// (MEMRA_MOE_CACHE). The cache-HIT weight path is bit-identical to stage-every-token (§B.3).
3080    /// Convenience wrapper used by the hybrid trunk/MTP loops: pulls dims + max-block from `self`.
3081    pub fn moe_ffn_il(&self, e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize, il: u16)
3082               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3083        Self::moe_ffn_inner(e, m, z, None, t, &self.cfg, il, self.max_moe_block(), false)
3084    }
3085
3086    /// Prefill twin: Step35 promotes expert-grouped dispatch by default while decode/spec callers
3087    /// keep `moe_ffn_il` and therefore retain their existing dispatch class.
3088    pub fn moe_ffn_il_prefill(
3089        &self,
3090        e: &Engine,
3091        m: &MoeWeights,
3092        z: &CudaSlice<f32>,
3093        t: usize,
3094        il: u16,
3095    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3096        Self::moe_ffn_inner(e, m, z, None, t, &self.cfg, il, self.max_moe_block(), true)
3097    }
3098
3099    /// Decode-path twin with a PRE-QUANTIZED z (from add_rms_norm_zq8): threads (zq, zd) into the
3100    /// t=1 dev arm so the per-layer standalone quantize_q8_1 launch folds away. Identical bytes
3101    /// (the fused kernel reproduces quantize_q8_1 exactly); every other path ignores the pair.
3102    pub fn moe_ffn_il_zq8(&self, e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>,
3103                          zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>, t: usize, il: u16)
3104               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3105        Self::moe_ffn_inner(
3106            e, m, z, zq8, t, &self.cfg, il, self.max_moe_block(), false,
3107        )
3108    }
3109
3110    /// MoE FFN (EDGE-1), source-/model-agnostic. z: [T, n_embd] (already post-attention-normed).
3111    /// Returns moe_out [T, n_embd]. Node-for-node vs llama.cpp build_moe_ffn. Shared by the hybrid
3112    /// (qwen35moe, shared expert present) and the dense-attention MoE (OLMoE, no shared expert) paths;
3113    /// `cfg.moe` supplies the dims and the optional shexp fields decide whether step 3 runs.
3114    ///
3115    /// `il` is the layer index — the residency-cache key prefix. `max_block` is the global max expert
3116    /// stride (fixed cache-slot size); pass `self.max_moe_block()`.
3117    pub(crate) fn moe_ffn(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize,
3118                          cfg: &ModelConfig, il: u16, max_block: usize)
3119               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3120        Self::moe_ffn_inner(e, m, z, None, t, cfg, il, max_block, false)
3121    }
3122
3123    #[allow(clippy::too_many_arguments)]
3124    pub(crate) fn moe_ffn_inner(
3125        e: &Engine,
3126        m: &MoeWeights,
3127        z: &CudaSlice<f32>,
3128        zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>,
3129        t: usize,
3130        cfg: &ModelConfig,
3131        il: u16,
3132        max_block: usize,
3133        prefill: bool,
3134    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3135        let worker_io = crate::spill_pread::worker_enabled();
3136        let epoch_lfu = std::env::var_os("MEMRA_MOE_LFU_DECAY").is_some();
3137        if Engine::moe_cache_enabled() && (worker_io || epoch_lfu) {
3138            e.with_moe_cache(max_block, |cache, _| {
3139                cache.begin_forward_epoch(il, t);
3140                if worker_io {
3141                    cache.begin_worker_scope();
3142                }
3143                Ok(())
3144            })?;
3145        }
3146        // Expert-grouped dispatch for prefill (T>1). MEMRA_MOE_GROUPED explicitly opts the
3147        // current caller into this research arm; the naked default stays on the established path.
3148        if t > 1 && moe_grouped_enabled(cfg, prefill) {
3149            let grouped_out = Self::moe_ffn_grouped(e, m, z, t, cfg, il, max_block)?;
3150            // MEMRA_MOE_GATE: byte-identity comparison vs sequential path.
3151            // The grouped q8 path uses the same row-wise quantize/dot/activation/FMA programs as
3152            // sequential dispatch; mixed or q8-disabled layouts fall back to the matching f32
3153            // path. A mismatch is therefore a correctness failure, not an accepted numeric class.
3154            if std::env::var("MEMRA_MOE_GATE").is_ok() {
3155                let seq_out = Self::moe_ffn_sequential(e, m, z, t, cfg, il, max_block)?;
3156                let g_host = e.dtoh(&grouped_out)?;
3157                let s_host = e.dtoh(&seq_out)?;
3158                let g_bytes: &[u8] = unsafe { std::slice::from_raw_parts(g_host.as_ptr() as *const u8, g_host.len() * 4) };
3159                let s_bytes: &[u8] = unsafe { std::slice::from_raw_parts(s_host.as_ptr() as *const u8, s_host.len() * 4) };
3160                if g_bytes == s_bytes {
3161                    println!("moe-gate il={il} t={t} BYTE-IDENTICAL");
3162                } else {
3163                    let diffs = g_host.iter().zip(s_host.iter()).enumerate()
3164                        .filter(|(_, (a, b))| a != b).count();
3165                    let maxdiff = g_host.iter().zip(s_host.iter())
3166                        .map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
3167                    panic!("moe-gate il={il} t={t} MISMATCH: {diffs}/{} elems differ, maxdiff={maxdiff:.6e}", g_host.len());
3168                }
3169            }
3170            return Ok(grouped_out);
3171        }
3172        Self::moe_ffn_sequential_zq8(e, m, z, zq8, t, cfg, il, max_block)
3173    }
3174
3175    /// Sequential (per-token) MoE FFN -- the original path. Factored out for the gate comparison.
3176    pub(crate) fn moe_ffn_sequential(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize,
3177                          cfg: &ModelConfig, il: u16, max_block: usize)
3178               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3179        Self::moe_ffn_sequential_zq8(e, m, z, None, t, cfg, il, max_block)
3180    }
3181
3182    /// One router-logit selector shared by sequential and grouped dispatch. Real prefill must use
3183    /// the row-wise GEMV when exact routing is enabled: cuBLASLt's reduction changes with `m`,
3184    /// which makes expert selection depend on the caller's chunk or concat-batch shape.
3185    fn moe_router_logits(
3186        e: &Engine,
3187        m: &MoeWeights,
3188        z: &CudaSlice<f32>,
3189        t: usize,
3190        cfg: &ModelConfig,
3191    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3192        if t < PRIME_MIN_T {
3193            // Decode and speculative verify use one fixed per-row reduction program.
3194            if crate::router_kernel_on() {
3195                e.router_gemv(
3196                    m.gate_inp.float_data(),
3197                    z,
3198                    cfg.n_embd as usize,
3199                    m.gate_exps.n_expert,
3200                    t,
3201                )
3202            } else {
3203                e.matmul_decode_exact(&m.gate_inp, z, t)
3204            }
3205        } else if crate::router_prefill_exact_on() && crate::router_kernel_on() {
3206            e.router_gemv(
3207                m.gate_inp.float_data(),
3208                z,
3209                cfg.n_embd as usize,
3210                m.gate_exps.n_expert,
3211                t,
3212            )
3213        } else {
3214            e.matmul(&m.gate_inp, z, t)
3215        }
3216    }
3217
3218    /// Append the host-visible router selection for one layer/forward when calibration tracing is
3219    /// enabled. Both sequential and expert-grouped prefill must call this after routing so the
3220    /// trace is independent of the dispatch optimization selected for the forward.
3221    fn trace_moe_routes(il: u16, t: usize, sel_all: &[u32], weights: &[f32])
3222                        -> Result<(), Box<dyn std::error::Error>> {
3223        use std::io::Write as _;
3224        if let Ok(path) = std::env::var("MEMRA_MOE_TRACE") {
3225            let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
3226            let ids: Vec<String> = sel_all.iter().map(|s| s.to_string()).collect();
3227            writeln!(f, "{} {} {}", il, t, ids.join(","))?;
3228        }
3229        if let Ok(path) = std::env::var("MEMRA_MOE_WEIGHT_TRACE") {
3230            let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
3231            let pairs: Vec<String> = sel_all.iter().zip(weights)
3232                .map(|(expert, weight)| format!("{expert}:{weight:.9}"))
3233                .collect();
3234            writeln!(f, "{} {} {}", il, t, pairs.join(","))?;
3235        }
3236        Ok(())
3237    }
3238
3239    /// Append the f32 input to one MoE layer for offline, layerwise calibration. This diagnostic
3240    /// intentionally performs a DtoH copy and is therefore disabled unless an explicit fresh trace
3241    /// directory is supplied. Each layer owns one payload file; index.jsonl records byte offsets so
3242    /// a validator can prove request/layer coverage before the trace is used for pruning or healing.
3243    fn trace_moe_input(e: &Engine, il: u16, t: usize, n_embd: usize, z: &CudaSlice<f32>)
3244                       -> Result<(), Box<dyn std::error::Error>> {
3245        use std::io::Write as _;
3246        let Ok(dir) = std::env::var("MEMRA_MOE_INPUT_TRACE_DIR") else { return Ok(()) };
3247        let host = e.dtoh(z)?;
3248        if host.len() != t * n_embd {
3249            return Err(format!(
3250                "MoE input trace shape mismatch at layer {il}: got {} values, expected {}x{}",
3251                host.len(), t, n_embd
3252            ).into());
3253        }
3254        let bytes = unsafe {
3255            std::slice::from_raw_parts(
3256                host.as_ptr().cast::<u8>(), host.len() * std::mem::size_of::<f32>()
3257            )
3258        };
3259        let state = MOE_INPUT_TRACE_WRITER.get_or_init(|| std::sync::Mutex::new(None));
3260        let mut state = state.lock().map_err(|_| "MoE input trace writer lock is poisoned")?;
3261        if state.is_none() {
3262            let dir = std::path::PathBuf::from(&dir);
3263            std::fs::create_dir_all(&dir)?;
3264            let index = std::fs::OpenOptions::new().create(true).append(true)
3265                .open(dir.join("index.jsonl"))?;
3266            *state = Some(MoeInputTraceWriter {
3267                dir,
3268                index,
3269                payloads: std::collections::HashMap::new(),
3270            });
3271        }
3272        let writer = state.as_mut().unwrap();
3273        if writer.dir != std::path::Path::new(&dir) {
3274            return Err("MEMRA_MOE_INPUT_TRACE_DIR changed after capture started".into());
3275        }
3276        let file_name = format!("layer-{il:03}.f32");
3277        if !writer.payloads.contains_key(&il) {
3278            let payload = std::fs::OpenOptions::new().create(true).append(true)
3279                .open(writer.dir.join(&file_name))?;
3280            let offset = payload.metadata()?.len();
3281            writer.payloads.insert(il, (payload, offset));
3282        }
3283        let (payload, offset) = writer.payloads.get_mut(&il).unwrap();
3284        let row_offset = *offset;
3285        payload.write_all(bytes)?;
3286        *offset += bytes.len() as u64;
3287        writeln!(
3288            writer.index,
3289            "{{\"format\":\"memra-moe-input-trace-v1\",\"layer\":{il},\"tokens\":{t},\
3290             \"hidden_size\":{n_embd},\"file\":\"{file_name}\",\"offset\":{row_offset},\
3291             \"payload_bytes\":{}}}",
3292            bytes.len()
3293        )?;
3294        Ok(())
3295    }
3296
3297    #[allow(clippy::too_many_arguments)]
3298    pub(crate) fn moe_ffn_sequential_zq8(
3299        e: &Engine,
3300        m: &MoeWeights,
3301        z: &CudaSlice<f32>,
3302        zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>,
3303        t: usize,
3304        cfg: &ModelConfig,
3305        il: u16,
3306        max_block: usize,
3307    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3308        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
3309        let moe = cfg.moe.as_ref().unwrap();
3310        let n_embd = cfg.n_embd as usize;          // 2048 (gate/up in_f, down out_f)
3311        let n_expert = moe.expert_count as usize;  // 256
3312        let n_used = moe.expert_used_count as usize; // 8
3313        let n_ff_exp = moe.expert_ff_length as usize; // 512 (gate/up out_f, down in_f)
3314
3315        // verify the HostExps dims match cfg (catches a wrong-file / transpose mixup)
3316        debug_assert_eq!(m.gate_exps.in_f, n_embd);
3317        debug_assert_eq!(m.gate_exps.out_f, n_ff_exp);
3318        debug_assert_eq!(m.down_exps.in_f, n_ff_exp);  // down is TRANSPOSED: in=512
3319        debug_assert_eq!(m.down_exps.out_f, n_embd);   //                     out=2048
3320        debug_assert_eq!(m.gate_exps.n_expert, n_expert);
3321
3322        // step35 PER-LAYER SwiGLU clamp (None on every other arch and on every unclamped layer).
3323        // Routed experts and the shared expert read SEPARATE arrays — never share one value.
3324        let lim_exp = cfg.clamp_exp_at(il as u32);
3325        let lim_shexp = cfg.clamp_shexp_at(il as u32);
3326        let use_cache = Engine::moe_cache_enabled();
3327        let uniform_experts = m.has_uniform_expert_layout();
3328        let moe_q8 = uniform_experts && moe_q8_enabled()
3329            && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
3330            && q8_expert_supported(m.down_exps.qtype);
3331        // Experimental secondary backend: complete experts already resident in the SLRU stay on
3332        // CUDA; any expert missing one or more projections runs from the original host GGUF bytes
3333        // through llama.cpp CPU quant dots. Small-t only keeps decode and speculative verification
3334        // in the same numeric/dispatch class; real prefill remains on the established GPU path and
3335        // seeds the residency cache. An explicit library path is the build/runtime gate, so naked
3336        // commands and CI have no llama.cpp or OpenMP dependency.
3337        let cpu_expert_requested = crate::cpu_experts::configured();
3338        if cpu_expert_requested && (cfg.hy3.is_none() || cfg.m3.is_some()) {
3339            return Err(std::io::Error::other(
3340                "MEMRA_CPU_EXPERT_LIB is experimental and currently gated to Hy3",
3341            )
3342            .into());
3343        }
3344        let cpu_hybrid = cpu_expert_requested && t < PRIME_MIN_T && m.dev_exps.is_none();
3345        // A dynamic SLRU changes which complete experts run on CUDA versus llama.cpp CPU dots.
3346        // Those backends are each deterministic but are different numeric configurations, so a
3347        // later prefill eviction can change greedy output. Freeze after the first real prefill;
3348        // decode/spec reads the fixed resident set, while later prefill misses use transient GPU
3349        // staging below and cannot change backend assignment.
3350        let freeze_cpu_residency = cpu_expert_requested
3351            && std::env::var("MEMRA_CPU_EXPERT_FREEZE_CACHE").as_deref() == Ok("1");
3352        let caller_warms_before_freeze = std::env::var("MEMRA_CPU_EXPERT_FREEZE_WARMUP_TOKENS")
3353            .ok()
3354            .and_then(|value| value.parse::<usize>().ok())
3355            .is_some_and(|tokens| tokens > 0);
3356        if cpu_hybrid && freeze_cpu_residency && !caller_warms_before_freeze {
3357            e.freeze_moe_cache();
3358        }
3359        let cache_frozen = use_cache && e.moe_cache_frozen();
3360        let cache_dispatch = use_cache && (!cache_frozen || cpu_hybrid);
3361
3362        // 1. ROUTER: one selector is shared with expert-grouped prefill so changing dispatch
3363        // cannot change logits, selected expert ids, or routing weights.
3364        let logits = Self::moe_router_logits(e, m, z, t, cfg)?;
3365
3366        // LAUNCH-STRUCTURE STAGE 3 (2026-07-05, MEMRA_MOE_DEV default ON, =0 rollback): ZERO-DtoH
3367        // device-dispatch when this layer's expert blocks are ALL cache-resident. The fused
3368        // router's sel/w stay ON DEVICE; the expert weight pointers come from the per-layer
3369        // device table of fixed slot addresses; gate/up/silu + down/fma run as the same TWO
3370        // launches per token as gdec. Removes the per-layer router DtoH + stream sync — the
3371        // per-token host stall that dominated the 35B decode wall after stages 1+2.
3372        // BIT-IDENTITY: the router kernel is selection-exact vs the host oracle (kernel-check
3373        // tie gate) and the _dev matvec twins reproduce the gdec kernels' exact FP chains; the
3374        // only difference is where sel/w/pointers are READ from (device instead of params).
3375        // Residency: one-shot PREWARM force-admits the layer while free slots cover it
3376        // (MEMRA_MOE_PREWARM=0 -> organic residency, dev path fires when the SLRU fills).
3377        // Any non-resident layer falls through to host routing + the gdec/sequential path.
3378        // FITS-VRAM RESIDENT EXPERTS (2026-07-06): the layer's expert slabs are device-resident
3379        // (load-time decision) — fire the zero-DtoH dev path unconditionally with the prebuilt
3380        // pointer row. No cache, no dispatch, no residency check: the llama full-offload regime
3381        // (it measured 169.55 vs the cache path's 28.5 on the local 35B — the residency-gate
3382        // all-or-nothing fallback was the 6x). BIT-IDENTITY: same _dev kernels, same math; only
3383        // the pointer table's provenance differs (slab base+stride vs SLRU slot addresses).
3384        // MoE PREFILL PAIR-BATCH (2026-07-06, the 16x pp hole): t>1 on resident experts — ONE
3385        // launch per proj covers ALL (token,expert) pairs (grid.y=pair, warp-per-row), replacing
3386        // the per-expert loop (256 experts x 3-4 launches x tiny m_e). Scatter is slot-ordered
3387        // per token (the sequential-axpy bit-identity class). Requires q8-supported qtypes +
3388        // resident slabs. MEMRA_MOE_PAIRS=0 rollback.
3389        // t >= PRIME_MIN_T only (2026-07-06 exactness fix, verify-probe proof): spec VERIFY
3390        // batches (t = 2..K+2) previously rode these pairs kernels while T=1 decode rode the
3391        // dev_q8 loop — different FP chains, verify-T2 logit maxdiff 2.6e-1 vs eager -> greedy
3392        // flips at tight margins -> 35B real-prompt spec self-consistency FAIL (the 27B
3393        // "verify must be kernel-DISPATCH-identical to decode" lesson, MoE edition). Small-t
3394        // now rides the dev loop below (same kernels per token as decode); pairs serves real
3395        // prefill (t >= 16, where spec never verifies).
3396        // sigmoid-router archs (M3, Hy3) must NOT enter the pairs/dev arms: those route via the
3397        // fused SOFTMAX device router (moe_router_topk) — silently wrong experts (the M3
3398        // gate-MISMATCH 74602-vs-92 lesson, 2026-07-07). Host sigmoid routing below is correct.
3399        // Per-expert macro-scales (compressed-tensors NVFP4 ST class, e.g. unsloth 35B-A3B):
3400        // the device-dispatch kernels (pairs/dev) do NOT fold them — those checkpoints must
3401        // ride the macro-aware sequential/staged paths below or every expert output is off by
3402        // its global scale (~3e4x, measured garbage 2026-07-16). GGUF experts: macros None.
3403        let no_exp_macros = m.gate_exps.macros.is_none() && m.up_exps.macros.is_none()
3404            && m.down_exps.macros.is_none();
3405        // A clamped-SwiGLU layer (step35 43/44) also cannot ride pairs: moe_pairs_silu_mul's
3406        // epilogue is plain silu(gate)*up with no clamp form, and moe_ffn_pairs takes no `il`
3407        // so it cannot even see the per-layer limit.
3408        if cfg.sigmoid_router().is_none() && cfg.m3.is_none() && cfg.hy3.is_none()
3409            && !cfg.swiglu_clamped_at(il as u32)
3410            && no_exp_macros
3411            && t >= PRIME_MIN_T && m.dev_exps.is_some() && moe_q8_enabled()
3412            && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
3413            && q8_expert_supported(m.down_exps.qtype)
3414            && std::env::var("MEMRA_MOE_PAIRS").map(|v| v != "0").unwrap_or(true)
3415            && std::env::var("MEMRA_MOE_STATS").is_err() {
3416            return Self::moe_ffn_pairs(e, m, z, &logits, t, cfg);
3417        }
3418
3419        // t < PRIME_MIN_T: moe_ffn_dev loops tokens serially (1 launch-pair per token) — the
3420        // decode path AND the spec-verify path (dispatch parity = exactness; see pairs gate
3421        // above). Serial launches are fine at t<=10 (K+2); real prefill never lands here.
3422        // moe_ffn_dev routes via the FUSED SOFTMAX device router (moe_router_topk) — sigmoid
3423        // routing (M3, Hy3: +expert bias) has no device kernel yet, so those arches must NOT
3424        // enter the dev arms: with MOE_CACHE=1 M3 silently routed softmax = wrong experts
3425        // (gate MISMATCH 74602 vs 92, caught 2026-07-07). Host sigmoid path below is correct.
3426        // macro-carrying experts are handled inside the dev path now (epilogue fold + w-scale);
3427        // pairs/gdec/csr keep their macro gates until their kernels grow the fold.
3428        // step35 (2026-08-06) is the third sigmoid-router arch and the deny above was written as
3429        // two arch names, not as the mechanism — so `dev_ok` let it into moe_ffn_dev's
3430        // moe_router_topk (softmax, no exp_probs_b bias, no expert_weights_scale) = silently
3431        // wrong experts, the same failure the pairs gate at :2254 already blocks by predicate.
3432        // Keyed off sigmoid_router() so arch #4 is denied by construction.
3433        // The clamped-SwiGLU layers must also fall through: every moe_ffn_dev kernel's fused
3434        // epilogue is plain silu(gate)*up (moe_gate_up_silu8_dev_*), which has no clamp form.
3435        let dev_ok = uniform_experts && cfg.sigmoid_router().is_none()
3436            && cfg.m3.is_none() && cfg.hy3.is_none()
3437            && !cfg.swiglu_clamped_at(il as u32);
3438        // Observation modes must route through the host-visible selection below. Otherwise a fully
3439        // resident layer returns through device dispatch before its trace/stats row is recorded,
3440        // silently biasing calibration toward only non-resident layers on large-VRAM machines.
3441        let observe_routes = std::env::var("MEMRA_MOE_STATS").is_ok()
3442            || std::env::var("MEMRA_MOE_TRACE").is_ok()
3443            || std::env::var("MEMRA_MOE_WEIGHT_TRACE").is_ok()
3444            || std::env::var("MEMRA_MOE_INPUT_TRACE_DIR").is_ok();
3445        if dev_ok && t < PRIME_MIN_T && m.dev_exps.is_some() && n_used <= 8 && moe_dev_enabled()
3446            && !observe_routes {
3447            return Self::moe_ffn_dev(e, m, z, zq8, &logits, t, cfg, il, max_block);
3448        }
3449        if dev_ok && use_cache && n_used <= 8 && moe_dev_enabled()
3450            && !observe_routes {
3451            let row_ok = e.with_moe_cache(max_block, |c, eng| {
3452                if moe_prewarm_enabled() { c.prewarm_layer(il, m, eng)?; }
3453                Ok(c.layer_dev_row(il, n_expert, eng)?.is_some())
3454            })?;
3455            if row_ok {
3456                return Self::moe_ffn_dev(e, m, z, zq8, &logits, t, cfg, il, max_block);
3457            }
3458        }
3459
3460        // Per-token (sel[8], w[8]) — sigmoid host oracle (M3/Hy3), else fused-router/softmax.
3461        let (sel_all, w_all, routed_cpu_input) = if let Some(sig) = cfg.sigmoid_router() {
3462            if cpu_hybrid {
3463                let (sel, w, input) = Self::moe_route_sigmoid_with_input(
3464                    e,
3465                    &logits,
3466                    z,
3467                    t,
3468                    n_expert,
3469                    n_used,
3470                    m.exp_probs_b.as_deref(),
3471                    sig,
3472                    m.active_experts.as_deref(),
3473                )?;
3474                (sel, w, Some(input))
3475            } else {
3476                let (sel, w) = Self::moe_route_cfg(
3477                    e,
3478                    &logits,
3479                    t,
3480                    n_expert,
3481                    n_used,
3482                    m.exp_probs_b.as_deref(),
3483                    Some(sig),
3484                    m.active_experts.as_deref(),
3485                )?;
3486                (sel, w, None)
3487            }
3488        } else {
3489            let (sel, w) = Self::moe_route_cfg(
3490                e,
3491                &logits,
3492                t,
3493                n_expert,
3494                n_used,
3495                None,
3496                None,
3497                m.active_experts.as_deref(),
3498            )?;
3499            (sel, w, None)
3500        };
3501
3502        // MEMRA_MOE_TRACE=<path>: append one line per (layer, step) with the selected expert ids —
3503        // offline analysis derives the decode working set + step-to-step reuse (the go/no-go
3504        // measurement for resident-expert tiering; see rig5090.jsonl 2026-07-07 pinned-tier row).
3505        Self::trace_moe_routes(il, t, &sel_all, &w_all)?;
3506        Self::trace_moe_input(e, il, t, n_embd, z)?;
3507
3508        // Worker reads ordinarily overlap NVMe with the current expert but leave their H2D copies
3509        // demand-serialized on the compute stream. Hy3 decode already has a safe owner-thread
3510        // boundary here: sigmoid routing read `logits` back to the host, which synchronized all
3511        // earlier-layer compute. Submit the complete selected set first, then reserve only victims
3512        // outside that set and queue its H2D copies on the copy stream. Dispatch inserts an event
3513        // wait for each pending block, so later copies can overlap the earlier expert kernels while
3514        // the selected weights and numerical kernels remain unchanged. Restrict this experiment to
3515        // T=1; batched forwards can have token-local consumers still in flight between selections.
3516        // The CPU backend reads mmap-backed model bytes directly. Positioned-read worker buffers
3517        // are CUDA write-combined staging allocations and are intentionally not CPU-compute inputs;
3518        // do not spend NVMe bandwidth filling them for a layer whose misses go to CPU.
3519        let worker_disk_prefetch =
3520            cache_dispatch && crate::spill_pread::worker_enabled() && !cpu_hybrid;
3521        let promote_worker_h2d =
3522            t == 1 && worker_disk_prefetch && crate::spill_pread::copy_h2d_enabled();
3523        if promote_worker_h2d {
3524            let mut selected_blocks = Vec::with_capacity(n_used * 3);
3525            for &ex in sel_all.iter().take(n_used) {
3526                let ex = ex as u16;
3527                selected_blocks.extend([
3528                    BlockId::new(il, PROJ_GATE, ex),
3529                    BlockId::new(il, PROJ_UP, ex),
3530                    BlockId::new(il, PROJ_DOWN, ex),
3531                ]);
3532            }
3533            for &ex in sel_all.iter().take(n_used) {
3534                Self::moe_prefetch_disk_expert(e, il, ex as usize, m, max_block, &selected_blocks)?;
3535            }
3536            e.with_moe_cache(max_block, |cache, eng| {
3537                cache.promote_worker_reads_at_safe_boundary(
3538                    &selected_blocks,
3539                    &selected_blocks,
3540                    eng,
3541                )?;
3542                Ok(())
3543            })?;
3544        }
3545
3546        // MEMRA_MOE_STATS: per-layer routing stats for the A2 (expert-grouped prefill) baseline —
3547        // per-token expert-id entropy, active-expert coverage, tokens-per-expert group sizes.
3548        if t > 1 && std::env::var("MEMRA_MOE_STATS").is_ok() {
3549            let mut cnt = vec![0u32; n_expert];
3550            for &s in sel_all.iter() { cnt[s as usize] += 1; }
3551            let total = sel_all.len() as f64;
3552            let mut h = 0.0f64;
3553            let mut active = 0usize;
3554            for &c in &cnt { if c > 0 { active += 1; let p = c as f64 / total; h -= p * p.log2(); } }
3555            let maxc = cnt.iter().copied().max().unwrap_or(0);
3556            println!("moe-stats il={} t={} assignments={} active={}/{} entropy={:.3}b (max {:.3}b) mean_tok_per_active={:.2} max_tok_per_expert={}",
3557                     il, t, sel_all.len(), active, n_expert, h, (n_expert as f64).log2(), total / active.max(1) as f64, maxc);
3558        }
3559
3560        // LAUNCH-STRUCTURE STAGE 2 (2026-07-05): moe_out memset elision on the gdec path.
3561        // moe_down8_fma_f32 FULLY overwrites its token row (dst[o] = the in-kernel FMA chain that
3562        // starts at 0.0f — numerically the axpy-into-zeroed-row chain), so when the grouped-decode
3563        // path fires the upfront `e.zeros(t*n_embd)` memset is pure launch churn. Allocate uninit
3564        // when gdec CAN fire (any t — decode t=1 AND the spec verify t=K+1 route here per token)
3565        // and lazily zero ONLY the row of a token that falls through to the sequential axpy loop.
3566        // BIT-IDENTITY: unchanged — every row is either fully overwritten (gdec) or
3567        // zeroed-then-accumulated exactly as before (fallback).
3568        // `!swiglu_clamped_at`: the grouped-decode kernels' fused epilogue is plain
3569        // silu(gate)*up (see the m3 note at the call sites below) — a clamped layer must fall
3570        // through to the sequential loop's ffn_act_lim. Hoisted into the fire predicate so the
3571        // uninit/memset invariant at :2418 stays consistent with what actually dispatches.
3572        let gdec_may_fire = uniform_experts && use_cache && n_used <= 8 && gdec_enabled()
3573            && !cfg.swiglu_clamped_at(il as u32);
3574        // SLAB-LOCAL RESIDENT ARM (lane/pp-leverb 2026-08-08): the fits-VRAM resident slabs
3575        // (`dev_exps`, sized per PP device by cx-503b) were consumed ONLY by the pairs/dev
3576        // arms — every one of which DENIES sigmoid-router archs (step35/M3/Hy3). So on those
3577        // archs the slabs were uploaded but never read, and every expert went through the
3578        // SLRU (37 GB H2D staging per pp4096 prime on the Step SKU; and post-cx-503b the
3579        // dead slabs additionally STARVE the SLRU, which sizes itself on free-VRAM-after-
3580        // residents). This arm reads the slabs through the SAME kernels the SLRU arm runs —
3581        // gdec's fused pair when eligible, the per-expert qmatvec twins otherwise — with the
3582        // slab base + ex*stride as the pointer provenance (the exact bit-identity class
3583        // `moe_ffn_dev` documents for its resident-vs-SLRU arms; bytes are the same HostExps
3584        // bytes either way). LOCALITY GATE: `d.dev == e.ctx().ordinal()` — a slab on another
3585        // device must NOT be dereferenced (m=1 peer reads are the measured 34-150x class,
3586        // strictly worse than staging); under PP-2 without the prime walker this admits
3587        // stage-0 layers on dev0 and leaves stage-1 layers on the SLRU, which is the honest
3588        // interim shape. MEMRA_MOE_SLAB=0 = rollback/A-B seam (read per call).
3589        let slab_local = m.dev_exps.as_ref()
3590            .filter(|d| !d.gu_il && moe_slab_enabled() && d.dev == e.ctx().ordinal());
3591        let slab_bases = slab_local.map(|d| {
3592            use cudarc::driver::DevicePtr;
3593            let s = e.stream();
3594            let (pg, _g0) = d.gate.device_ptr(&s);
3595            let (pu, _g1) = d.up.device_ptr(&s);
3596            let (pd, _g2) = d.down.device_ptr(&s);
3597            (pg as u64, pu as u64, pd as u64)
3598        });
3599        // Fused-pair eligibility mirrors the gdec call sites exactly (plain-SiLU epilogue,
3600        // no macros, m3 clamp excluded, q8-supported qtypes, <=8 experts) — INCLUDING
3601        // `gdec_enabled()`: the pair IS the gdec kernel pair, so MEMRA_MOE_GDEC=0 must
3602        // disable it here too. That seam is also the exactness localizer: with GDEC=0 both
3603        // provenances run the SAME per-expert qmatvec kernels (slab base+stride vs SLRU
3604        // slot) and must be BIT-IDENTICAL — the true provenance-only pair — while GDEC=1
3605        // compares the fused-pair class against the SLRU's hit/miss MIX (gdec for
3606        // all-resident tokens, staged loop for misses), which is a dispatch-class
3607        // comparison, not a provenance one.
3608        let slab_fused_may_fire = slab_bases.is_some() && n_used <= 8 && gdec_enabled()
3609            && !cfg.swiglu_clamped_at(il as u32) && cfg.m3.is_none()
3610            && no_exp_macros && moe_q8;
3611        // moe_out memset elision: BOTH full-row-overwrite arms (gdec + slab fused) allocate
3612        // uninit; a token that falls through to any accumulating loop zeroes its own row.
3613        let mut moe_out = if gdec_may_fire || slab_fused_may_fire {
3614            e.uninit(t * n_embd)?
3615        } else {
3616            e.zeros(t * n_embd)?
3617        };
3618        // The router readback above already established a host boundary. Copy each small-t hidden
3619        // row once so CPU miss experts can start while the owner thread queues resident GPU work.
3620        let cpu_input = if cpu_hybrid {
3621            Some(routed_cpu_input.ok_or("CPU expert routing did not return the MoE input")?)
3622        } else {
3623            None
3624        };
3625
3626        // GPU scratch: one slot per proj, big enough for ONE expert (default stage-every-token path).
3627        // STAGE 2: LAZY — allocated only if the no-cache staging path actually runs (under
3628        // MEMRA_MOE_CACHE they were 3 dead ~1MB alloc_zeros + memset + free per layer per token,
3629        // measured ~123 memsets/token of the decode wall).
3630        let g_len = m.gate_exps.max_expert_bytes();  // 860160 for the uniform 35B gate
3631        let u_len = m.up_exps.max_expert_bytes();    // 860160 for the uniform 35B up
3632        let d_len = m.down_exps.max_expert_bytes();  // 1114112 for the uniform 35B down
3633        let mut scratch_g: Option<CudaSlice<u8>> = None;
3634        let mut scratch_u: Option<CudaSlice<u8>> = None;
3635        let mut scratch_d: Option<CudaSlice<u8>> = None;
3636        // `max_block` (the GLOBAL max expert stride across all layers) is passed in — the cache slots
3637        // are FIXED-ADDRESS and must fit any layer's block (UD/dynamic GGUFs vary quant per layer).
3638
3639        // EDGE-1 §C.2/C.3: the optional pipeline queues the next selected expert's MISS blocks on
3640        // the copy stream before launching the current expert's compute. Pending slots stay invisible
3641        // to cache hits until dispatch inserts the completion-event wait; current gate/up/down ids are
3642        // protected from eviction. This changes scheduling only, never the GGUF bytes or GEMM path.
3643        let page_window = moe_page_prefetch_window();
3644
3645        // 2. PER TOKEN: routed-expert loop. The ONE dispatch change vs Stage-1: a resident slot
3646        //    (cache HIT, no H2D) OR a staged slot (MISS) feeds the SAME unchanged qmatvec_view.
3647        for tok in 0..t {
3648            let sel = &sel_all[tok * n_used..(tok + 1) * n_used];
3649            let w = &w_all[tok * n_used..(tok + 1) * n_used];
3650            let zt = z.slice(tok * n_embd..(tok + 1) * n_embd);  // CudaView<f32>
3651            let mut tok_q8: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
3652
3653            // STAGE-2 GROUPED DECODE (2026-07-04, MEMRA_MOE_GDEC default ON, =0 rollback): fold
3654            // this token's whole routed-expert FFN (8x gate/up/silu + 8x down/axpy = 40 launches)
3655            // into TWO launches via expert-pointer indirection over the fixed-address cache slots.
3656            // Fires only when ALL 3*n_used blocks are ALREADY cache-resident (pure-HIT: zero
3657            // memcpy, zero admission, so no slot can move under the collected pointers) — any
3658            // miss falls through to the sequential loop below, which admits as before. In steady
3659            // state on a fully-resident rig every token-layer takes the grouped path.
3660            // BIT-IDENTITY: each in-kernel dot reproduces qmatvec_f32's exact reduction; SiLU is
3661            // silu_mul_f32's exact expression; the down accumulation is a slot-ordered
3662            // __fmaf_rn chain == the sequential axpy_f32 chain (MEMRA_MOE_GDEC_GATE compares).
3663            // cfg.m3: the grouped kernels' fused epilogues are plain SiLU — M3's swigluoai must
3664            // NOT take them until the kernels grow the clamped variant. NVFP4 experts carry
3665            // per-expert macro-scales the fused kernels don't fold — those fall through too.
3666            let no_macros = m.gate_exps.macros.is_none() && m.up_exps.macros.is_none()
3667                && m.down_exps.macros.is_none();
3668            // SLAB-LOCAL FUSED PAIR (lane/pp-leverb 2026-08-08): the gdec launch pair
3669            // (moe_gate_up_silu8_q8 + moe_down8_fma_q8 — the EXACT kernels, same FP chains)
3670            // with pointers computed from the resident slab base + ex*stride instead of
3671            // collected SLRU slot addresses. No cache lock, no residency predicate — the
3672            // slab holds every expert by construction, so this arm never falls through
3673            // (gdec's P(all 24 resident) ≈ 0.37 coin-flip and the miss path's ~49-launch
3674            // staging both die). Bit-identity class: pointer provenance only, the same
3675            // slab-vs-SLRU equivalence moe_ffn_dev documents. Ordered BEFORE gdec: when a
3676            // slab exists it is strictly better (no lock, no miss).
3677            if slab_fused_may_fire {
3678                let (pg, pu, pd) = slab_bases.unwrap();
3679                let mut gp = [0u64; 8];
3680                let mut up = [0u64; 8];
3681                let mut dp = [0u64; 8];
3682                for (j, &ex) in sel.iter().enumerate() {
3683                    let ex = ex as usize;
3684                    gp[j] = pg + (ex * m.gate_exps.expert_stride) as u64;
3685                    up[j] = pu + (ex * m.up_exps.expert_stride) as u64;
3686                    dp[j] = pd + (ex * m.down_exps.expert_stride) as u64;
3687                }
3688                let mut wv = [0f32; 8];
3689                wv[..n_used].copy_from_slice(w);
3690                if tok_q8.is_none() {
3691                    tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3692                }
3693                let (zq, zd) = tok_q8.as_ref().unwrap();
3694                let act = e.moe_gate_up_silu8_q8(crate::WPtr8(gp), crate::WPtr8(up), zq, zd,
3695                                                 n_embd, n_ff_exp, n_used,
3696                                                 m.gate_exps.qtype, m.up_exps.qtype,
3697                                                 m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
3698                let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
3699                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3700                e.moe_down8_fma_q8(crate::WPtr8(dp), crate::F32x8(wv), &aq2, &ad2, &mut dst,
3701                                   n_ff_exp, n_embd, n_used,
3702                                   m.down_exps.qtype, m.down_exps.row_bytes)?;
3703                continue;
3704            }
3705            if gdec_may_fire && moe_q8 && cfg.m3.is_none() && no_macros {
3706                if tok_q8.is_none() {
3707                    tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3708                }
3709                let (zq, zd) = tok_q8.as_ref().unwrap();
3710                if Self::moe_gdec_token_q8(e, m, il, max_block, zq, zd, sel, w,
3711                                           &mut moe_out, tok, n_embd, n_ff_exp, n_used)? {
3712                    continue;
3713                }
3714            } else if gdec_may_fire && cfg.m3.is_none() && no_macros
3715                && Self::moe_gdec_token(e, m, il, max_block, &zt, sel, w,
3716                                        &mut moe_out, tok, n_embd, n_ff_exp, n_used)? {
3717                continue;
3718            }
3719
3720            // STAGE 2 memset-elision invariant: moe_out was allocated UNINIT when gdec or the
3721            // slab pair could fire. This token fell through to a sequential axpy loop, which
3722            // ACCUMULATES — zero its row first (row-sized memset; other rows are owned by the
3723            // full-overwrite arms). slab_fused_may_fire never actually reaches here (its arm
3724            // has no fallible predicate), included for the allocation invariant's symmetry.
3725            if gdec_may_fire || slab_fused_may_fire {
3726                let mut row = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3727                e.memset_zeros_view(&mut row)?;
3728            }
3729
3730            // Fiddler-style split at whole-expert granularity. Partial residency is deliberately a
3731            // CPU assignment: transferring the missing projection would reintroduce the PCIe/NVMe
3732            // stall this path exists to remove, while mixing projections would require another
3733            // activation round-trip. Weight addresses remain valid until this worker is joined at
3734            // the bottom of the token scope.
3735            let mut cpu_mask = vec![false; sel.len()];
3736            let cpu_worker = if let Some(host_input) = cpu_input.as_ref() {
3737                let gpu_resident = if use_cache {
3738                    e.with_moe_cache(max_block, |cache, _| {
3739                        Ok(sel
3740                            .iter()
3741                            .map(|&expert| {
3742                                let expert = expert as u16;
3743                                [PROJ_GATE, PROJ_UP, PROJ_DOWN]
3744                                    .into_iter()
3745                                    .filter(|&projection| {
3746                                        cache
3747                                            .resident(BlockId::new(il, projection, expert))
3748                                            .is_some()
3749                                    })
3750                                    .count()
3751                            })
3752                            .collect::<Vec<_>>())
3753                    })?
3754                } else {
3755                    vec![0; sel.len()]
3756                };
3757                let mut cpu_selected = Vec::new();
3758                for (index, (&expert, &route_weight)) in sel.iter().zip(w).enumerate() {
3759                    if gpu_resident[index] != 3 {
3760                        cpu_mask[index] = true;
3761                        crate::cpu_experts::record_incomplete_gpu_residency(gpu_resident[index]);
3762                        let expert = expert as usize;
3763                        cpu_selected.push((expert, route_weight));
3764                    }
3765                }
3766                if crate::cpu_experts::predictor_enabled() {
3767                    // Fire-and-forget lookahead: the predictor worker scores layers il+1..
3768                    // from this layer's MoE input and prefetches predicted-and-missing
3769                    // experts into the companion RAM cache. Never blocks this thread.
3770                    let row = &host_input[tok * n_embd..(tok + 1) * n_embd];
3771                    crate::cpu_experts::predictor_submit(il, row);
3772                }
3773                if cpu_selected.is_empty() {
3774                    None
3775                } else {
3776                    let row = &host_input[tok * n_embd..(tok + 1) * n_embd];
3777                    let job = crate::cpu_experts::prepare_job(m, il, &cpu_selected, row)
3778                        .map_err(std::io::Error::other)?;
3779                    Some(crate::cpu_experts::submit(job).map_err(std::io::Error::other)?)
3780                }
3781            } else {
3782                None
3783            };
3784
3785            let worker_window = worker_disk_prefetch
3786                .then(worker_prefetch_window)
3787                .unwrap_or(0);
3788            for (j, &ex) in sel.iter().enumerate() {
3789                if cpu_mask[j] {
3790                    continue;
3791                }
3792                let ex = ex as usize;
3793                // PER-EXPERT SLAB READ (lane/pp-leverb 2026-08-08): the layers the fused
3794                // pair above excludes — step35's CLAMPED layers 43/44 (ffn_act_lim has no
3795                // fused form) and macro-carrying artifacts — still have their bytes in the
3796                // local resident slab. Same kernels as the SLRU arms (`qmatvec_expert_q8` /
3797                // `qmatvec_view`), same ffn_act_lim/macro folds; provenance = slab base +
3798                // ex*stride. No dispatch lock, no admission, no prefetch — nothing to miss.
3799                if let Some(d) = slab_local {
3800                    let gl = m.gate_exps.expert_layout(ex);
3801                    let ul = m.up_exps.expert_layout(ex);
3802                    let dl = m.down_exps.expert_layout(ex);
3803                    let (g0, u0, d0) = (ex * m.gate_exps.expert_stride,
3804                                        ex * m.up_exps.expert_stride,
3805                                        ex * m.down_exps.expert_stride);
3806                    let (gate, up) = if moe_q8 {
3807                        if tok_q8.is_none() {
3808                            tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3809                        }
3810                        let (zq, zd) = tok_q8.as_ref().unwrap();
3811                        (e.qmatvec_expert_q8(&d.gate, g0..g0 + gl.len, zq, zd, 1,
3812                                             m.gate_exps.in_f, m.gate_exps.out_f,
3813                                             gl.qtype, gl.row_bytes)?,
3814                         e.qmatvec_expert_q8(&d.up, u0..u0 + ul.len, zq, zd, 1,
3815                                             m.up_exps.in_f, m.up_exps.out_f,
3816                                             ul.qtype, ul.row_bytes)?)
3817                    } else {
3818                        (e.qmatvec_view(&d.gate, g0..g0 + gl.len, &zt, 1,
3819                                        m.gate_exps.in_f, m.gate_exps.out_f,
3820                                        gl.qtype, gl.row_bytes)?,
3821                         e.qmatvec_view(&d.up, u0..u0 + ul.len, &zt, 1,
3822                                        m.up_exps.in_f, m.up_exps.out_f,
3823                                        ul.qtype, ul.row_bytes)?)
3824                    };
3825                    let mut act = e.uninit(n_ff_exp)?;
3826                    Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
3827                                      m.up_exps.macro_scale(ex), lim_exp, &mut act, n_ff_exp)?;
3828                    let y = if moe_q8 {
3829                        let (aq2, ad2) = e.quantize_q8_1(&act, 1, n_ff_exp)?;
3830                        e.qmatvec_expert_q8(&d.down, d0..d0 + dl.len, &aq2, &ad2, 1,
3831                                            m.down_exps.in_f, m.down_exps.out_f,
3832                                            dl.qtype, dl.row_bytes)?
3833                    } else {
3834                        let actv = act.slice(0..n_ff_exp);
3835                        e.qmatvec_view(&d.down, d0..d0 + dl.len, &actv, 1,
3836                                       m.down_exps.in_f, m.down_exps.out_f,
3837                                       dl.qtype, dl.row_bytes)?
3838                    };
3839                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3840                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
3841                    continue;
3842                }
3843                for next in page_prefetch_positions(j, sel.len(), page_window) {
3844                    Self::moe_prefetch_host_expert(sel[next] as usize, m);
3845                }
3846                let keep = [
3847                    crate::moe_cache::BlockId::new(il, crate::moe_cache::PROJ_GATE, ex as u16),
3848                    crate::moe_cache::BlockId::new(il, crate::moe_cache::PROJ_UP, ex as u16),
3849                    crate::moe_cache::BlockId::new(il, crate::moe_cache::PROJ_DOWN, ex as u16),
3850                ];
3851                if worker_disk_prefetch && worker_window > 0 {
3852                    for next in worker_prefetch_positions(j, sel.len(), worker_window) {
3853                        Self::moe_prefetch_disk_expert(
3854                            e,
3855                            il,
3856                            sel[next] as usize,
3857                            m,
3858                            max_block,
3859                            &keep,
3860                        )?;
3861                    }
3862                } else if cache_dispatch
3863                    && !cpu_hybrid
3864                    && moe_prefetch_enabled()
3865                    && j + 1 < sel.len()
3866                {
3867                    let next = sel[j + 1] as usize;
3868                    Self::moe_prefetch_expert(e, il, next, m, max_block, &keep)?;
3869                }
3870                let [gate_q8, up_q8, down_q8] = [moe_q8; 3];
3871                if cache_dispatch && (gate_q8 || up_q8 || down_q8) {
3872                    // dp4a EXPERT PATH (MEMRA_MOE_Q8): quantize z-row once per token. Mixed expert
3873                    // layouts stay on the metadata-aware f32 path.
3874                    if (gate_q8 || up_q8) && tok_q8.is_none() {
3875                        tok_q8 = Some(e.quantize_q8_1_view(&zt, 1, n_embd)?);
3876                    }
3877                    let gate = if gate_q8 {
3878                        let (zq, zd) = tok_q8.as_ref().unwrap();
3879                        Self::moe_cached_gemm_q8(e, il, PROJ_GATE, ex, m, max_block, zq, zd)?
3880                    } else {
3881                        Self::moe_cached_gemm(e, il, PROJ_GATE, ex, m, max_block, &zt)?
3882                    };
3883                    let up = if up_q8 {
3884                        let (zq, zd) = tok_q8.as_ref().unwrap();
3885                        Self::moe_cached_gemm_q8(e, il, PROJ_UP, ex, m, max_block, zq, zd)?
3886                    } else {
3887                        Self::moe_cached_gemm(e, il, PROJ_UP, ex, m, max_block, &zt)?
3888                    };
3889                    let mut act = e.uninit(n_ff_exp)?;
3890                    Self::ffn_act_lim(
3891                        e,
3892                        cfg,
3893                        &gate,
3894                        &up,
3895                        m.gate_exps.macro_scale(ex),
3896                        m.up_exps.macro_scale(ex),
3897                        lim_exp,
3898                        &mut act,
3899                        n_ff_exp,
3900                    )?;
3901                    let y = if down_q8 {
3902                        let (aq2, ad2) = e.quantize_q8_1(&act, 1, n_ff_exp)?;
3903                        Self::moe_cached_gemm_q8(e, il, PROJ_DOWN, ex, m, max_block, &aq2, &ad2)?
3904                    } else {
3905                        let actv = act.slice(0..n_ff_exp);
3906                        Self::moe_cached_gemm(e, il, PROJ_DOWN, ex, m, max_block, &actv)?
3907                    };
3908                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3909                    // down-proj macro folds into the accumulate weight (1.0 for non-macro archs).
3910                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
3911                } else if cache_dispatch {
3912                    // SLRU residency cache: per-projection, dispatch the block (HIT => resident slot,
3913                    // MISS => staged slot) then run the SAME unchanged qmatvec_view from that slot.
3914                    // The bytes the kernel reads are byte-for-byte the same GGUF block (§B.3); the
3915                    // only difference between HIT and MISS is whether the memcpy_htod ran.
3916                    let gate = Self::moe_cached_gemm(e, il, PROJ_GATE, ex, m, max_block, &zt)?;
3917                    let up   = Self::moe_cached_gemm(e, il, PROJ_UP,   ex, m, max_block, &zt)?;
3918                    let mut act = e.uninit(n_ff_exp)?;  // activation fully overwrites
3919                    Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
3920                        m.up_exps.macro_scale(ex), lim_exp, &mut act, n_ff_exp)?;
3921                    let actv = act.slice(0..n_ff_exp);
3922                    let y = Self::moe_cached_gemm(e, il, PROJ_DOWN, ex, m, max_block, &actv)?;
3923                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3924                    // down-proj macro folds into the accumulate weight (post-matmul linear scale).
3925                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
3926                } else if cache_frozen {
3927                    // A later prompt prime must not change the CPU/GPU assignment frozen after the
3928                    // first prime. Reuse every fixed resident projection directly and stage only a
3929                    // true miss through the ordinary scratch slot. This preserves the established
3930                    // f32-dequant numeric path while avoiding a full-bank reread on every prime.
3931                    let gate = Self::moe_frozen_gemm(
3932                        e,
3933                        il,
3934                        PROJ_GATE,
3935                        ex,
3936                        m,
3937                        max_block,
3938                        &zt,
3939                        &mut scratch_g,
3940                        g_len,
3941                    )?;
3942                    let up = Self::moe_frozen_gemm(
3943                        e,
3944                        il,
3945                        PROJ_UP,
3946                        ex,
3947                        m,
3948                        max_block,
3949                        &zt,
3950                        &mut scratch_u,
3951                        u_len,
3952                    )?;
3953                    let mut act = e.uninit(n_ff_exp)?;
3954                    Self::ffn_act_lim(
3955                        e,
3956                        cfg,
3957                        &gate,
3958                        &up,
3959                        m.gate_exps.macro_scale(ex),
3960                        m.up_exps.macro_scale(ex),
3961                        lim_exp,
3962                        &mut act,
3963                        n_ff_exp,
3964                    )?;
3965                    let actv = act.slice(0..n_ff_exp);
3966                    let y = Self::moe_frozen_gemm(
3967                        e,
3968                        il,
3969                        PROJ_DOWN,
3970                        ex,
3971                        m,
3972                        max_block,
3973                        &actv,
3974                        &mut scratch_d,
3975                        d_len,
3976                    )?;
3977                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
3978                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
3979                } else {
3980                    // Stage-1: stage gate/up/down for expert `ex` into the scratch slots, then GEMM.
3981                    // Lazy scratch: first no-cache expert allocates the 3 slots (uninit — stage_expert
3982                    // fully overwrites the byte range the GEMM reads).
3983                    if scratch_g.is_none() {
3984                        scratch_g = Some(e.alloc_u8_uninit(g_len)?);
3985                        scratch_u = Some(e.alloc_u8_uninit(u_len)?);
3986                        scratch_d = Some(e.alloc_u8_uninit(d_len)?);
3987                    }
3988                    let (sg, su, sd) = (scratch_g.as_mut().unwrap(), scratch_u.as_mut().unwrap(),
3989                                        scratch_d.as_mut().unwrap());
3990                    let gl = m.gate_exps.expert_layout(ex);
3991                    let ul = m.up_exps.expert_layout(ex);
3992                    let dl = m.down_exps.expert_layout(ex);
3993                    e.stage_expert(m.gate_exps.expert_bytes(ex), sg, 0)?;
3994                    let gate = e.qmatvec_view(sg, 0..gl.len, &zt, 1,
3995                        m.gate_exps.in_f, m.gate_exps.out_f, gl.qtype, gl.row_bytes)?;
3996
3997                    e.stage_expert(m.up_exps.expert_bytes(ex), su, 0)?;
3998                    let up = e.qmatvec_view(su, 0..ul.len, &zt, 1,
3999                        m.up_exps.in_f, m.up_exps.out_f, ul.qtype, ul.row_bytes)?;
4000
4001                    let mut act = e.uninit(n_ff_exp)?;  // activation fully overwrites
4002                    Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
4003                        m.up_exps.macro_scale(ex), lim_exp, &mut act, n_ff_exp)?;
4004
4005                    e.stage_expert(m.down_exps.expert_bytes(ex), sd, 0)?;
4006                    let actv = act.slice(0..n_ff_exp);
4007                    let y = e.qmatvec_view(sd, 0..dl.len, &actv, 1,
4008                        m.down_exps.in_f, m.down_exps.out_f, dl.qtype, dl.row_bytes)?;
4009
4010                    let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4011                    e.axpy_into(&y, w[j] * m.down_exps.macro_scale(ex), &mut dst, n_embd)?;
4012                }
4013            }
4014            if let Some(worker) = cpu_worker {
4015                let cpu_output = worker.wait().map_err(std::io::Error::other)?;
4016                let cpu_output = e.htod(&cpu_output)?;
4017                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4018                e.axpy_into(&cpu_output, 1.0, &mut dst, n_embd)?;
4019            }
4020            if cpu_hybrid && !cache_frozen && cpu_expert_profile_admit_enabled() {
4021                for (j, &ex) in sel.iter().enumerate() {
4022                    if cpu_mask[j] {
4023                        Self::moe_profile_admit_expert(e, il, ex as usize, m, max_block)?;
4024                    }
4025                }
4026            }
4027        }
4028
4029        // 3. SHARED EXPERT (ALWAYS-ON, no routing) on the SAME z — qwen35moe only. OLMoE and most
4030        //    vanilla MoE have NO shared expert (the shexp tensors are absent / `None`); skip it then.
4031        // gate_inp_shexp is OPTIONAL: qwen35moe gates the shared expert (sigmoid(gate_inp) x sh);
4032        // MiniMax-M3 (DeepSeek-V3 class) has NO shexp gate — the shared expert adds directly.
4033        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
4034            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
4035        {
4036            let n_ff_sh = gate_shexp.out_features();  // 512
4037            // Q8 TRUNK-FUSION (decode t=1): gate_shexp+up_shexp are Q8_0 same-shape on the 35B —
4038            // ONE fused2 launch (also folds the two per-matmul re-quantizes of z into one).
4039            // Bit-identical per (tensor,row); falls back to the two matmul calls when ineligible.
4040            // Small-t (spec verify 2..15) rides matmul_decode_exact so shexp FP chains match the
4041            // t==1 decode chain per column (cuBLASLt n-dependence + dp4a-vs-mmvq class); real
4042            // prefill keeps the batched matmul. Activation routes through ffn_act (SiLU for
4043            // softmax archs, clamped swigluoai for M3 — identical to silu_mul when cfg.m3 is None).
4044            let verify_t = t > 1 && t < PRIME_MIN_T;
4045            let (sg_gate, sg_up) = if t == 1 {
4046                match e.matmul_q8_fused2_x(gate_shexp, up_shexp, z)? {
4047                    Some(pair) => pair,
4048                    None => (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?),
4049                }
4050            } else if verify_t {
4051                (e.matmul_decode_exact(gate_shexp, z, t)?, e.matmul_decode_exact(up_shexp, z, t)?)
4052            } else {
4053                (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?)   // [T, 512] each
4054            };
4055            let mut sa = e.uninit(t * n_ff_sh)?;  // activation fully overwrites
4056            Self::ffn_act_lim(e, cfg, &sg_gate, &sg_up, 1.0, 1.0, lim_shexp, &mut sa, t * n_ff_sh)?;
4057            let sh = if verify_t { e.matmul_decode_exact(down_shexp, &sa, t)? }
4058                     else { e.matmul(down_shexp, &sa, t)? };     // [T, n_embd]
4059
4060            // shexp gate: qwen35moe sigmoid-gates via ffn_gate_inp_shexp (1-D ne=[n_embd] ->
4061            // out_f=1); M3 has no gate tensor -> weight 1.0. Decode + verify ride the fused
4062            // sigmoid-dot kernel (one fold order for both chains; kills the per-layer
4063            // cuBLASLt m=1 splitK GEMM — 40x/step, ~10% of the H100 q35 decode step).
4064            // SERVE ISOLATION (lane/concat-prime-exact, 2026-08-02): PREFILL rides it too.
4065            // This out_f=1 cuBLASLt GEMV is the SECOND m-dependent op in the trunk (probed:
4066            // rows [0,19) move by 1.07e-4 between m=74 and m=75 while sigmoid_dot_rows is
4067            // BIT-IDENTICAL — allw-shexpgate-o35b.log). The gate multiplies the shared
4068            // expert's contribution into every token's residual, so under cross-request
4069            // concat prefill a session's hidden state depended on its co-arrivals' token
4070            // count. MEMRA_ROUTER_PREFILL_EXACT=0 reverts to the batched cuBLASLt linear.
4071            let g = match &m.gate_inp_shexp {
4072                Some(gate_inp_shexp) => {
4073                    if t < PRIME_MIN_T || crate::router_prefill_exact_on() {
4074                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
4075                    } else {
4076                        let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
4077                        let mut g = e.uninit(t)?;  // sigmoid fully overwrites
4078                        e.sigmoid(&gs, &mut g, t)?;
4079                        g
4080                    }
4081                }
4082                None => e.htod(&vec![1.0f32; t])?,
4083            };
4084            // moe_out[r, :] += sh[r, :] * g[r]   (per-token scalar gate; g=1 ungated)
4085            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
4086        }
4087
4088        Ok(moe_out)
4089    }
4090
4091    /// Stage-1 (no-cache) per-DECODE-TOKEN H2D bytes: every routed block re-staged every layer every
4092    /// token = sum over MoE layers of n_used * (gate+up+down expert_stride). The §D.4 PCIe baseline.
4093    pub fn stage1_h2d_per_token(&self) -> u64 {
4094        use crate::hybrid::Ffn;
4095        let n_used = self.cfg.moe.as_ref().map(|m| m.expert_used_count as u64).unwrap_or(0);
4096        let mut bytes = 0u64;
4097        for l in self.layers.iter() {
4098            if let Ffn::Moe(m) = &l.ffn {
4099                bytes += n_used * (m.gate_exps.max_expert_bytes() + m.up_exps.max_expert_bytes()
4100                                   + m.down_exps.max_expert_bytes()) as u64;
4101            }
4102        }
4103        bytes
4104    }
4105
4106    /// Largest expert block (bytes) across ALL MoE layers + the MTP head — the fixed cache slot size.
4107    /// UD/dynamic GGUFs quant different layers differently, so `expert_stride` varies per layer; the
4108    /// residency cache slots are fixed-address and must fit any block, so size to this global max.
4109    pub(crate) fn max_moe_block(&self) -> usize {
4110        use crate::hybrid::Ffn;
4111        let mut mx = 0usize;
4112        let mut scan = |ffn: &Ffn| {
4113            if let Ffn::Moe(m) = ffn {
4114                mx = mx.max(m.gate_exps.max_expert_bytes())
4115                       .max(m.up_exps.max_expert_bytes())
4116                       .max(m.down_exps.max_expert_bytes());
4117            }
4118        };
4119        for l in self.layers.iter() { scan(&l.ffn); }
4120        if let Some(mtp) = self.mtp.as_ref() { scan(&mtp.ffn); }
4121        mx
4122    }
4123
4124    /// Exact retained projection lengths for cache class sizing. Pruned ids keep router positions
4125    /// but have no bytes and therefore consume no residency slot.
4126    pub(crate) fn moe_cache_block_sizes(&self) -> Vec<usize> {
4127        use crate::hybrid::Ffn;
4128        let mut sizes = Vec::new();
4129        let mut scan = |ffn: &Ffn| {
4130            let Ffn::Moe(m) = ffn else { return };
4131            for ex in 0..m.gate_exps.n_expert {
4132                if m.active_experts.as_ref().is_some_and(|active| !active[ex]) {
4133                    continue;
4134                }
4135                for exps in [&m.gate_exps, &m.up_exps, &m.down_exps] {
4136                    let len = exps.expert_layout(ex).len;
4137                    if len > 0 {
4138                        sizes.push(len);
4139                    }
4140                }
4141            }
4142        };
4143        for layer in &self.layers {
4144            scan(&layer.ffn);
4145        }
4146        if let Some(mtp) = &self.mtp {
4147            scan(&mtp.ffn);
4148        }
4149        sizes
4150    }
4151
4152    /// Persist the frozen residency set so a later process can restage it directly and skip
4153    /// the profiling warmup. Plain text: a versioned header binding slot geometry, then one
4154    /// `layer proj ex` triple per line. A mismatched or stale profile is rejected at load
4155    /// (header check) or degrades to fewer restaged blocks (per-id checks); either way the
4156    /// post-freeze argmax gate still validates the serving assignment.
4157    pub fn save_cpu_expert_residency_profile(
4158        &self,
4159        e: &Engine,
4160        path: &std::path::Path,
4161    ) -> Result<(), Box<dyn std::error::Error>> {
4162        let Some(ids) = e.export_moe_residency() else {
4163            return Err("no MoE residency cache to persist".into());
4164        };
4165        let mut body = format!(
4166            "memra-freeze-profile v1 max_block={} blocks={}\n",
4167            self.max_moe_block(),
4168            ids.len()
4169        );
4170        for (layer, proj, ex) in &ids {
4171            body.push_str(&format!("{layer} {proj} {ex}\n"));
4172        }
4173        let tmp = path.with_extension("tmp");
4174        std::fs::write(&tmp, body)?;
4175        std::fs::rename(&tmp, path)?;
4176        println!(
4177            "[moe-cache] freeze profile saved: {} blocks -> {}",
4178            ids.len(),
4179            path.display()
4180        );
4181        Ok(())
4182    }
4183
4184    /// Restage a saved freeze profile and freeze immediately, skipping the profiling warmup.
4185    /// Returns false (leaving the cache untouched for a normal warmup) when the profile is
4186    /// missing or its header does not match this model's slot geometry.
4187    pub fn restore_cpu_expert_residency_profile(
4188        &self,
4189        e: &Engine,
4190        path: &std::path::Path,
4191    ) -> Result<bool, Box<dyn std::error::Error>> {
4192        use crate::hybrid::Ffn;
4193        use crate::moe_cache::BlockId;
4194        let Ok(content) = std::fs::read_to_string(path) else {
4195            return Ok(false);
4196        };
4197        let mut lines = content.lines();
4198        let Some(header) = lines.next() else { return Ok(false) };
4199        let expected = format!("memra-freeze-profile v1 max_block={}", self.max_moe_block());
4200        if !header.starts_with(&expected) {
4201            println!(
4202                "[moe-cache] freeze profile ignored (geometry mismatch): {}",
4203                path.display()
4204            );
4205            return Ok(false);
4206        }
4207        let mut by_layer: std::collections::HashMap<u16, Vec<BlockId>> =
4208            std::collections::HashMap::new();
4209        for line in lines {
4210            let mut fields = line.split_whitespace();
4211            let (Some(layer), Some(proj), Some(ex)) =
4212                (fields.next(), fields.next(), fields.next())
4213            else {
4214                continue;
4215            };
4216            let (Ok(layer), Ok(proj), Ok(ex)) =
4217                (layer.parse::<u16>(), proj.parse::<u8>(), ex.parse::<u16>())
4218            else {
4219                continue;
4220            };
4221            by_layer
4222                .entry(layer)
4223                .or_default()
4224                .push(BlockId::new(layer, proj, ex));
4225        }
4226        let requested: usize = by_layer.values().map(Vec::len).sum();
4227        if requested == 0 {
4228            return Ok(false);
4229        }
4230        let max_block = self.max_moe_block();
4231        let mut restaged = 0usize;
4232        let mut stage_layer = |layer_index: u16,
4233                               ffn: &Ffn|
4234         -> Result<(), Box<dyn std::error::Error>> {
4235            let Ffn::Moe(m) = ffn else { return Ok(()) };
4236            let Some(ids) = by_layer.get(&layer_index) else {
4237                return Ok(());
4238            };
4239            e.with_moe_cache(max_block, |cache, eng| {
4240                for id in ids {
4241                    if cache.restage_block(*id, m, eng)? {
4242                        restaged += 1;
4243                    }
4244                }
4245                Ok(())
4246            })
4247        };
4248        for (index, layer) in self.layers.iter().enumerate() {
4249            stage_layer(index as u16, &layer.ffn)?;
4250        }
4251        if let Some(mtp) = self.mtp.as_ref() {
4252            stage_layer(u16::MAX, &mtp.ffn)?;
4253        }
4254        e.freeze_moe_cache();
4255        println!(
4256            "[moe-cache] freeze profile restored: {restaged}/{requested} blocks restaged from {}",
4257            path.display()
4258        );
4259        Ok(true)
4260    }
4261
4262    /// Freeze the heterogeneous CPU/GPU split after the caller's discarded profile warmup.
4263    pub fn freeze_cpu_expert_residency(
4264        &self,
4265        e: &Engine,
4266    ) -> Result<(), Box<dyn std::error::Error>> {
4267        e.freeze_moe_cache();
4268        Ok(())
4269    }
4270
4271    /// FFN activation dispatch: swigluoai (clamped, alpha/limit) when cfg.m3 says so, else the
4272    /// standard SiLU*up. One seam so every FFN site (dense, routed expert, shared expert) follows
4273    /// the model's activation exactly.
4274    ///
4275    /// NO-`il` FORM: cannot apply step35's PER-LAYER SwiGLU clamp. Only call it from a site whose
4276    /// layer provably has no live limit (dense-FFN layers, MTP blocks) — `ffn_act_lim` is the
4277    /// form for anything that can land on a clamped layer.
4278    pub fn ffn_act(e: &Engine, cfg: &ModelConfig, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
4279               act: &mut CudaSlice<f32>, n: usize) -> Result<(), Box<dyn std::error::Error>> {
4280        Self::ffn_act_scaled(e, cfg, gate, up, 1.0, 1.0, act, n)
4281    }
4282
4283    /// ffn_act with per-tensor post-matmul macro-scales folded in (gs/us == 1.0 -> identical
4284    /// float ops to ffn_act; used by the ModelOpt NVFP4 expert path where each expert tensor
4285    /// carries a `weight_scale_2`). Same no-`il` contract as `ffn_act`.
4286    #[allow(clippy::too_many_arguments)]
4287    pub(crate) fn ffn_act_scaled(e: &Engine, cfg: &ModelConfig, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
4288               gs: f32, us: f32, act: &mut CudaSlice<f32>, n: usize)
4289               -> Result<(), Box<dyn std::error::Error>> {
4290        Self::ffn_act_lim(e, cfg, gate, up, gs, us, None, act, n)
4291    }
4292
4293    /// ffn_act_scaled + step35's PER-LAYER clamped SwiGLU. `limit`:
4294    ///   * `None`   -> the unclamped dispatch (every arch except step35's layers 43-44).
4295    ///   * `Some(l)`-> `min(silu(gate*gs), l) * clamp(up*us, +-l)` (llama-graph.cpp:2146/1751,
4296    ///                 non-DEEPSEEK4 branch). Callers source it from `cfg.clamp_exp_at(il)`
4297    ///                 (routed experts) or `cfg.clamp_shexp_at(il)` (shared expert) — the two
4298    ///                 arrays are SEPARATE and a layer can have one without the other.
4299    /// The `> 1e-6` eps gate lives in `clamp_exp_at`/`clamp_shexp_at`, so a `Some` here is
4300    /// already known live.
4301    #[allow(clippy::too_many_arguments)]
4302    pub(crate) fn ffn_act_lim(e: &Engine, cfg: &ModelConfig, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
4303               gs: f32, us: f32, limit: Option<f32>, act: &mut CudaSlice<f32>, n: usize)
4304               -> Result<(), Box<dyn std::error::Error>> {
4305        if let Some(m3) = cfg.m3.as_ref() {
4306            debug_assert!(limit.is_none(), "m3 swigluoai and step35 clamp are different archs");
4307            return e.swigluoai_mul_scaled(gate, up, gs, us, m3.swiglu_alpha, m3.swiglu_limit, act, n);
4308        }
4309        if let Some(l) = limit {
4310            return e.swiglu_clamped_mul_scaled(gate, up, gs, us, l, act, n);
4311        }
4312        if gs == 1.0 && us == 1.0 { return e.silu_mul(gate, up, act, n); }
4313        e.silu_mul_scaled(gate, up, gs, us, act, n)
4314    }
4315
4316    /// Routing for the whole batch: returns (sel [T*n_used] expert ids, w [T*n_used] renorm weights),
4317    /// token-major. Default = the Stage-1 host path (dtoh logits, softmax-256, stable DESC top-k,
4318    /// renorm). MEMRA_FUSED_ROUTER = the device kernel (§A) which reproduces the same numerics; we
4319    /// still dtoh the tiny [T,n_used] sel/w buffers (64 B/token vs 1 KB/token) — the host loop
4320    /// indexes HostExps.bytes on the CPU to choose the DMA source (§A.2 output staging).
4321    fn moe_route(e: &Engine, logits: &CudaSlice<f32>, t: usize, n_expert: usize, n_used: usize)
4322                 -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4323        Self::moe_route_cfg(e, logits, t, n_expert, n_used, None, None, None)
4324    }
4325
4326    /// DeepSeek-V3-class sigmoid routing (MiniMax-M3, Hy3), host oracle. Reference:
4327    /// M3/Hy3 modeling code — scores = sigmoid(logits); selection over scores + expert bias
4328    /// (M3 `e_score_correction_bias` / Hy3 `expert_bias`, both surfaced as `exp_probs_b`);
4329    /// weights = un-biased scores of the selected experts, sum-normalized when `route_norm`,
4330    /// x scaling factor (M3 routed_scaling_factor 2.0 / Hy3 router_scaling_factor 2.826).
4331    /// `sig` = (scaling_factor, route_norm) from `cfg.sigmoid_router()`; softmax archs pass
4332    /// None -> the qwen35moe/OLMoE path below.
4333    fn moe_route_cfg(e: &Engine, logits: &CudaSlice<f32>, t: usize, n_expert: usize, n_used: usize,
4334                     bias: Option<&[f32]>, sig: Option<(f32, bool)>, active: Option<&[bool]>)
4335                 -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4336        if let Some((sf, route_norm)) = sig {
4337            // sigmoid routing. Host path only for now (fused-router kernel is softmax-top-k).
4338            let lg = e.dtoh(logits)?;
4339            return Self::moe_route_sigmoid_host(
4340                &lg, t, n_expert, n_used, bias, sf, route_norm, active,
4341            );
4342        }
4343        // LAUNCH-STRUCTURE STAGE 1 (2026-07-05): fused router DEFAULT ON (MEMRA_FUSED_ROUTER=0
4344        // rollback) via the single-sync pinned readback — softmax arch only; the M3 sigmoid arm
4345        // above returns before this (host path until a sigmoid fused-router kernel exists).
4346        if active.is_none() && !matches!(std::env::var("MEMRA_FUSED_ROUTER").as_deref(), Ok("0")) {
4347            return e.moe_router_topk_host(logits, t, n_expert, n_used);
4348        }
4349        // Host oracle (the §D bit-identity reference).
4350        let lg = e.dtoh(logits)?;   // [T*n_expert] host
4351        let mut sel = vec![0u32; t * n_used];
4352        let mut w_out = vec![0f32; t * n_used];
4353        for tok in 0..t {
4354            let row = &lg[tok * n_expert..(tok + 1) * n_expert];
4355            // softmax over ALL n_expert (stable: subtract max)
4356            let maxl = row.iter().enumerate()
4357                .filter(|(i, _)| active.is_none_or(|mask| mask[*i]))
4358                .map(|(_, &x)| x).fold(f32::NEG_INFINITY, f32::max);
4359            let mut probs = vec![0f32; n_expert];
4360            let mut den = 0f32;
4361            for i in 0..n_expert {
4362                if active.is_some_and(|mask| !mask[i]) { continue; }
4363                let x = (row[i] - maxl).exp(); probs[i] = x; den += x;
4364            }
4365            for p in probs.iter_mut() { *p /= den; }
4366            // stable DESC sort: prob DESC, ascending-index tiebreak.
4367            let mut idx: Vec<usize> = (0..n_expert)
4368                .filter(|&i| active.is_none_or(|mask| mask[i])).collect();
4369            idx.sort_by(|&a, &b| probs[b].total_cmp(&probs[a]).then(a.cmp(&b)));
4370            let sl = &idx[..n_used];
4371            let mut wv: Vec<f32> = sl.iter().map(|&i| probs[i]).collect();
4372            let mut ws: f32 = wv.iter().sum();
4373            ws = ws.max(6.103515625e-5_f32);  // F16 smallest normal, clamp BEFORE divide
4374            for x in wv.iter_mut() { *x /= ws; }
4375            for j in 0..n_used {
4376                sel[tok * n_used + j] = sl[j] as u32;
4377                w_out[tok * n_used + j] = wv[j];
4378            }
4379        }
4380        Ok((sel, w_out))
4381    }
4382
4383    #[allow(clippy::too_many_arguments)]
4384    fn moe_route_sigmoid_with_input(
4385        e: &Engine,
4386        logits: &CudaSlice<f32>,
4387        input: &CudaSlice<f32>,
4388        t: usize,
4389        n_expert: usize,
4390        n_used: usize,
4391        bias: Option<&[f32]>,
4392        (sf, route_norm): (f32, bool),
4393        active: Option<&[bool]>,
4394    ) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>), Box<dyn std::error::Error>> {
4395        let (lg, input) = e.dtoh_pair(logits, input)?;
4396        let (sel, w) =
4397            Self::moe_route_sigmoid_host(&lg, t, n_expert, n_used, bias, sf, route_norm, active)?;
4398        Ok((sel, w, input))
4399    }
4400
4401    /// Start the prediction-guided prefetch worker (MEMRA_MOE_PREFETCH=depth). Call after
4402    /// residency freeze: the worker filters against a static snapshot of the frozen HBM set.
4403    /// Builds a fully-owned per-layer table (host router copies via one-time DtoH, bias,
4404    /// active mask, prebuilt projection descriptors) so no model reference escapes.
4405    pub fn start_moe_prefetch_predictor(
4406        &self,
4407        e: &Engine,
4408        cfg: &ModelConfig,
4409    ) -> Result<(), Box<dyn std::error::Error>> {
4410        use crate::hybrid::Ffn;
4411        let Some(sig) = cfg.sigmoid_router() else {
4412            return Err("prefetch predictor requires a sigmoid-router arch".into());
4413        };
4414        let resident: std::collections::HashSet<(u16, u8, u16)> = e
4415            .export_moe_residency()
4416            .ok_or("prefetch predictor needs the frozen MoE residency cache")?
4417            .into_iter()
4418            .collect();
4419        let mut layers = Vec::new();
4420        for (index, layer) in self.layers.iter().enumerate() {
4421            let Ffn::Moe(m) = &layer.ffn else { continue };
4422            let crate::model::GpuTensor::Float { data, .. } = &m.gate_inp else { continue };
4423            let router = e.dtoh(data)?;
4424            let n_expert = m.gate_exps.n_expert;
4425            let n_embd = m.gate_exps.in_f;
4426            if router.len() != n_embd * n_expert {
4427                continue;
4428            }
4429            let build = |exps: &crate::model::HostExps| {
4430                (0..n_expert)
4431                    .map(|expert| crate::cpu_experts::predictor_projection(exps, expert))
4432                    .collect::<Vec<_>>()
4433            };
4434            layers.push((index as u16, crate::cpu_experts::PredictLayerInit {
4435                router,
4436                bias: m.exp_probs_b.clone(),
4437                active: m.active_experts.clone(),
4438                n_embd,
4439                n_used: cfg
4440                    .moe
4441                    .as_ref()
4442                    .map(|moe| moe.expert_used_count as usize)
4443                    .ok_or("prefetch predictor requires MoE config")?,
4444                sig,
4445                weights_n_expert: n_expert,
4446                gate: build(&m.gate_exps),
4447                up: build(&m.up_exps),
4448                down: build(&m.down_exps),
4449            }));
4450        }
4451        crate::cpu_experts::start_prefetch_predictor(layers, resident)
4452            .map_err(|error| error.into())
4453    }
4454
4455    /// Crate-visible sigmoid-routing oracle for the prefetch predictor: identical selection
4456    /// math to the runtime router, applied to host-computed lookahead logits.
4457    #[allow(clippy::too_many_arguments)]
4458    pub(crate) fn moe_route_sigmoid_host_public(
4459        logits: &[f32],
4460        t: usize,
4461        n_expert: usize,
4462        n_used: usize,
4463        bias: Option<&[f32]>,
4464        sf: f32,
4465        route_norm: bool,
4466        active: Option<&[bool]>,
4467    ) -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4468        Self::moe_route_sigmoid_host(logits, t, n_expert, n_used, bias, sf, route_norm, active)
4469    }
4470
4471    #[allow(clippy::too_many_arguments)]
4472    fn moe_route_sigmoid_host(
4473        lg: &[f32],
4474        t: usize,
4475        n_expert: usize,
4476        n_used: usize,
4477        bias: Option<&[f32]>,
4478        sf: f32,
4479        route_norm: bool,
4480        active: Option<&[bool]>,
4481    ) -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
4482        if lg.len() != t * n_expert {
4483            return Err(format!(
4484                "sigmoid router logits length mismatch: got {}, expected {}",
4485                lg.len(),
4486                t * n_expert,
4487            )
4488            .into());
4489        }
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            let scores: Vec<f32> = row.iter().map(|&x| 1.0 / (1.0 + (-x).exp())).collect();
4495            // selection score = sigmoid + bias; weight = plain sigmoid.
4496            let selsc: Vec<f32> = match bias {
4497                Some(b) => scores.iter().zip(b).map(|(s, bb)| s + bb).collect(),
4498                None => scores.clone(),
4499            };
4500            let mut idx: Vec<usize> = (0..n_expert)
4501                .filter(|&i| active.is_none_or(|mask| mask[i]))
4502                .collect();
4503            idx.sort_by(|&a, &b| selsc[b].total_cmp(&selsc[a]).then(a.cmp(&b)));
4504            let sl = &idx[..n_used];
4505            let mut wv: Vec<f32> = sl.iter().map(|&i| scores[i]).collect();
4506            if route_norm {
4507                let ws: f32 = wv.iter().sum::<f32>().max(1e-20);
4508                for x in wv.iter_mut() {
4509                    *x = *x / ws * sf;
4510                }
4511            } else {
4512                for x in wv.iter_mut() {
4513                    *x *= sf;
4514                }
4515            }
4516            for j in 0..n_used {
4517                sel[tok * n_used + j] = sl[j] as u32;
4518                w_out[tok * n_used + j] = wv[j];
4519            }
4520        }
4521        Ok((sel, w_out))
4522    }
4523
4524    /// LAUNCH-STRUCTURE STAGE 3: the ZERO-DtoH fully-resident MoE FFN. Caller guarantees the
4525    /// layer's device pointer row exists (checked under the cache lock). Router top-k runs on
4526    /// device; sel/w are consumed by the `_dev` matvec twins directly; NOTHING crosses PCIe.
4527    /// Same numerics as the fused-router + gdec chain (kernel-level bit-identity, see the
4528    /// MoE PREFILL PAIR-BATCH: host routing (sel/w like the sequential path), then 5 launches
4529    /// TOTAL per layer (quantize z, gate-pairs, up-pairs, silu, act-quantize, down-pairs,
4530    /// scatter) regardless of T or expert count. Bit-identity class: per (pair,row) dot =
4531    /// qmatvec_expert_q8 order; per-token accumulation slot-ordered (scatter kernel).
4532    fn moe_ffn_pairs(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, logits: &CudaSlice<f32>,
4533                     t: usize, cfg: &ModelConfig)
4534                     -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4535        let moe = cfg.moe.as_ref().unwrap();
4536        let n_embd = cfg.n_embd as usize;
4537        let n_expert = moe.expert_count as usize;
4538        let n_used = moe.expert_used_count as usize;
4539        let n_ff_exp = moe.expert_ff_length as usize;
4540        // This arm has no `il` and every kernel in it fuses PLAIN silu(gate)*up, so a clamped
4541        // model must never reach it. The caller's gate at `moe_ffn_sequential_zq8` denies per
4542        // layer via `swiglu_clamped_at(il)`; assert the whole-model form here so a future caller
4543        // that forgets the gate fails loudly in debug instead of returning wrong logits.
4544        debug_assert!(!cfg.swiglu_clamped_anywhere(),
4545                      "moe_ffn_pairs has no per-layer clamp: fused epilogues are plain SiLU");
4546        let dev = m.dev_exps.as_ref().unwrap();
4547        // WALL-GAP ARC: interleaved gate/up slab strides (see moe_ffn_dev).
4548        let (rbg_d, rbu_d) = if dev.gu_il {
4549            let sxx = m.gate_exps.row_bytes + m.up_exps.row_bytes; (sxx, sxx)
4550        } else { (m.gate_exps.row_bytes, m.up_exps.row_bytes) };
4551
4552        let (sel_all, w_all) = Self::moe_route(e, logits, t, n_expert, n_used)?;
4553        let n_pairs = t * n_used;
4554        // pair arrays: pair p = (token p/n_used, slot p%n_used) — ALREADY slot-ordered per token,
4555        // so the CSR is trivial: tok_pair_off[tok] = tok*n_used, ids identity.
4556        let pair_tok: Vec<i32> = (0..n_pairs).map(|p| (p / n_used) as i32).collect();
4557        let pair_ex:  Vec<i32> = sel_all.iter().map(|&x| x as i32).collect();
4558        let pair_w:   Vec<f32> = w_all.clone();
4559        let tok_off:  Vec<i32> = (0..=t).map(|tok| (tok * n_used) as i32).collect();
4560        let tok_ids:  Vec<i32> = (0..n_pairs as i32).collect();
4561        let pt = e.htod_i32(&pair_tok)?;
4562        let px = e.htod_i32(&pair_ex)?;
4563        let pw = e.htod(&pair_w)?;
4564        let toff = e.htod_i32(&tok_off)?;
4565        let tids = e.htod_i32(&tok_ids)?;
4566
4567        // z quantized ONCE for all tokens; gate/up pair matvecs; silu; act quantize; down; scatter.
4568        // EXPERT-MAJOR CSR (rung 2): pairs grouped by expert -> the kernel reuses each weight
4569        // row across the expert's token group (llama-MMQ's core win). Host grouping is O(pairs).
4570        let mut by_ex: Vec<Vec<i32>> = vec![Vec::new(); n_expert];
4571        for p in 0..n_pairs { by_ex[pair_ex[p] as usize].push(p as i32); }
4572        let mut ex_ids: Vec<i32> = Vec::new();
4573        let mut ex_off: Vec<i32> = vec![0];
4574        let mut ex_pairs: Vec<i32> = Vec::with_capacity(n_pairs);
4575        for (ex, list) in by_ex.iter().enumerate() {
4576            if list.is_empty() { continue; }
4577            ex_ids.push(ex as i32);
4578            ex_pairs.extend_from_slice(list);
4579            ex_off.push(ex_pairs.len() as i32);
4580        }
4581        let n_active = ex_ids.len();
4582        let exi = e.htod_i32(&ex_ids)?;
4583        let exo = e.htod_i32(&ex_off)?;
4584        let exp_d = e.htod_i32(&ex_pairs)?;
4585        let _ = &px;   // pair-major twin keeps it; em path uses CSR
4586
4587        // INT8-MMA EXPERT MMQ (MEMRA_MOE_MMA=1, opt-in): the m16n8k16.s8 tensor-core analog of the
4588        // _dec dp4a kernel (cu/mmq_iq_experts.cu). Same CSR grouping; per-expert matvec runs as a
4589        // 128x128-tile int8 MMA GEMM over the expert's token group. Weight IQ nibbles decode to int8
4590        // at tile-load + per-32 float scale; activation is q8_1_mmq (D4, same quant class as dp4a).
4591        // FP-ORDER differs from dp4a (MMA reduction) — logits SHIFT, gated on argmax/spec/closeness,
4592        // NOT byte-identity (like the W4A8 path). Requires IQ3_S/IQ4_XS + in_f % 256 == 0.
4593        // t >= 16 (GEMM_M-class rule): the MMA tile needs token volume (crossover ~200 tok/expert;
4594        // microbench: dp4a wins at tiny groups). ALSO an exactness requirement — spec verify
4595        // batches (t=2..K+2) must ride the dp4a path whose FP order matches the T=1 decode chain,
4596        // else K=1 self-consistency FAILs (caught 2026-07-06: MMA at T=2 flipped a verify argmax).
4597        // DEFAULT ON (2026-07-06, third flip — this time with the real culprit fixed): the
4598        // "MMA prime breaks spec" failure was the ROUTER's cuBLASLt n-dependence (d994271),
4599        // not MMA's own FP order — both this and the k-quant arms were innocent suspects whose
4600        // margin shifts surfaced the router bug. With the router decode-exact at verify t, the
4601        // full battery is green with MMA on (spec p1/p2/p3 PASS, raw K=1..8 PASS, argmax MATCH,
4602        // pp6257 2862 = 2.1x dec). t>=16 floor still required: verify batches must ride dp4a
4603        // (dispatch parity with the T=1 decode chain). MEMRA_MOE_MMA=0 rollback;
4604        // MEMRA_MOE_MMA_T overrides the floor (bisect seam).
4605        static MMA_T: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4606        let mma_t = *MMA_T.get_or_init(|| {
4607            std::env::var("MEMRA_MOE_MMA_T").ok().and_then(|v| v.parse().ok()).unwrap_or(16)
4608        });
4609        let use_mma = std::env::var("MEMRA_MOE_MMA").map(|v| v != "0").unwrap_or(true)
4610            && t >= mma_t
4611            && q8_expert_dec_supported(m.gate_exps.qtype) && q8_expert_dec_supported(m.up_exps.qtype)
4612            && q8_expert_dec_supported(m.down_exps.qtype)
4613            && n_embd % 256 == 0 && n_ff_exp % 256 == 0;
4614        // GROUPED f16 LANE admission (MEMRA_MOE_F16G, rounds 46-49): its own door, no longer a
4615        // subset of the MMQ arm — q35's k-quant stragglers (Q6_K/Q4_K down, one Q3_K gate/up
4616        // layer) fail q8_expert_dec_supported but dequant fine to f16, so f16g must be able to
4617        // take a layer the MMQ arm would reject. Same t >= mma_t floor as MMA: decode and
4618        // spec-verify batches must ride the dp4a path whose FP order matches the T=1 chain.
4619        // MODE 2 (sm_120a naked default, lane/f16g-default-rearb 2026-08-02): every layer
4620        // whose three projections pass f16g_proj_ok rides the sk visitor with direct tile
4621        // loaders — with IQ4_XS/IQ3_S direct coverage the sk arm beats the int8-MMA MMQ
4622        // tiles on the IQ-bank models too (q35 board-2048 +33.9%, KAT pp512 +46.7%).
4623        // AUTO-KQUANT (mode 3, MEMRA_MOE_F16G=3, lane/q4k-expert-prefill): admit f16g ONLY
4624        // where the MMA arm can't take the layer's QTYPES — the k-quant expert class whose
4625        // baseline is the per-pair _em fallback (Ornith-35B Q4_K: board-2048 3.14x). Its
4626        // MMA-capable carve-out (IQ3_S/IQ4_XS/Q4_0 banks on MMQ) was priced pre-IQ-direct;
4627        // it survives as the rollback seam. Keyed on qtype capability, NOT use_mma, so
4628        // MEMRA_MOE_MMA=0 stays a pure dp4a rollback seam.
4629        let mma_capable = q8_expert_dec_supported(m.gate_exps.qtype)
4630            && q8_expert_dec_supported(m.up_exps.qtype)
4631            && q8_expert_dec_supported(m.down_exps.qtype)
4632            && n_embd % 256 == 0 && n_ff_exp % 256 == 0;
4633        let f16g_mode = crate::moe_f16g_mode();
4634        let f16g = f16g_mode != 0 && t >= mma_t
4635            && (f16g_mode != 3 || !mma_capable)
4636            && f16g_proj_ok(m.gate_exps.qtype, n_embd)
4637            && f16g_proj_ok(m.up_exps.qtype, n_embd)
4638            && f16g_proj_ok(m.down_exps.qtype, n_ff_exp);
4639        if use_mma || f16g {
4640            // GROUPED f16 LANE (MEMRA_MOE_F16G, rounds 46-49, experimental door): dequant
4641            // the active experts ONCE per projection to f16 and run one grouped f16 GEMM over
4642            // the CSR groups. f16-mirror numeric class — argmax/spec gated before promotion.
4643            // NOTE: the pair-gather kernel needs pair p ordered EXPERT-MAJOR (ex_pairs order);
4644            // the y rows come back in that same CSR order, so gate/up/down all stay pair-major
4645            // in ex_pairs order — but moe_pairs_silu_mul and the scatter consume PAIR-ID order.
4646            // We therefore gather activations per ex_pairs and scatter y back through ex_pairs.
4647            let y_down = if f16g {
4648                // CSR order end-to-end: gather z rows by the pair's TOKEN (pair p's token is
4649                // p / n_used — the trivial CSR above), silu in CSR order (elementwise), one
4650                // permute at the very end back to pair-id order for the scatter.
4651                let csr_tok: Vec<i32> = ex_pairs.iter().map(|&p| p / n_used as i32).collect();
4652                let csr_tok_d = e.htod_i32(&csr_tok)?;
4653                let (z_f16, z_s) = e.moe_f16g_act(z, Some(&csr_tok_d), n_embd, n_pairs)?;
4654                let g_csr = e.moe_f16_grouped(&dev.ptr_row, 0, n_expert, &exi, &ex_off, &exo,
4655                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
4656                                              m.gate_exps.qtype, rbg_d)?;
4657                let u_csr = e.moe_f16_grouped(&dev.ptr_row, 1, n_expert, &exi, &ex_off, &exo,
4658                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
4659                                              m.up_exps.qtype, rbu_d)?;
4660                let act_csr = e.moe_pairs_silu_mul(&g_csr, &u_csr, n_pairs * n_ff_exp)?;
4661                let (a_f16, a_s) = e.moe_f16g_act(&act_csr, None, n_ff_exp, n_pairs)?;
4662                let d_csr = e.moe_f16_grouped(&dev.ptr_row, 2, n_expert, &exi, &ex_off, &exo,
4663                                              &a_f16, &a_s, n_ff_exp, n_embd, n_active, n_pairs,
4664                                              m.down_exps.qtype, m.down_exps.row_bytes)?;
4665                e.rows_permute(&d_csr, &exp_d, n_pairs, n_embd)?
4666            } else {
4667            // gate/up: activation = z, token-major over t tokens; pair_tok gathers the routed row.
4668            let z_scr = e.mmq_iq_quantize_act(z, n_embd, t)?;
4669            let gate = e.mmq_iq_experts(&dev.ptr_row, 0, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
4670                                        n_embd, n_ff_exp, n_active, n_pairs, t,
4671                                        m.gate_exps.qtype, rbg_d)?;
4672            let up = e.mmq_iq_experts(&dev.ptr_row, 1, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
4673                                      n_embd, n_ff_exp, n_active, n_pairs, t,
4674                                      m.up_exps.qtype, rbu_d)?;
4675            // down: activation = silu(gate)*up, pair-major [n_pairs, n_ff_exp]; pair_tok =
4676            // identity. FUSED ACT-EPILOGUE (default on): one launch computes the activation in
4677            // registers and writes ONLY the quantized scratch — the two-pass chain
4678            // (moe_pairs_silu_mul writes act f32, mmq_iq_quantize_act re-reads it) is the
4679            // MEMRA_MOE_FUSE_ACTQ=0 rollback. Scratch bytes are BYTE-IDENTICAL (kernel-check).
4680            let a_scr = if crate::moe_fuse_actq_on() {
4681                e.mmq_iq_fused_act_quant(&gate, &up, n_ff_exp, n_pairs, 0)?
4682            } else {
4683                let act = e.moe_pairs_silu_mul(&gate, &up, n_pairs * n_ff_exp)?;
4684                e.mmq_iq_quantize_act(&act, n_ff_exp, n_pairs)?
4685            };
4686            let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
4687            let pself = e.htod_i32(&pair_self)?;
4688            e.mmq_iq_experts(&dev.ptr_row, 2, n_expert, &exi, &exo, &exp_d, &pself, &a_scr,
4689                             n_ff_exp, n_embd, n_active, n_pairs, n_pairs,
4690                             m.down_exps.qtype, m.down_exps.row_bytes)?
4691            };
4692            let mut moe_out = e.uninit(t * n_embd)?;
4693            e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
4694            if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
4695                (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
4696            {
4697                let n_ff_sh = gate_shexp.out_features();
4698                let sg_gate = e.matmul(gate_shexp, z, t)?;
4699                let sg_up = e.matmul(up_shexp, z, t)?;
4700                let mut sa = e.uninit(t * n_ff_sh)?;
4701                Self::ffn_act(e, cfg, &sg_gate, &sg_up, &mut sa, t * n_ff_sh)?;
4702                let sh = e.matmul(down_shexp, &sa, t)?;
4703                // shexp gate: qwen35moe sigmoid-gates; M3 has no gate tensor -> weight 1.0.
4704                // SERVE ISOLATION (lane/concat-prime-exact): the fused sigmoid-dot is the
4705                // m-INVARIANT form — see the sequential arm's note. This is the PAIRS arm,
4706                // i.e. the one real prefill actually takes on a resident-expert MoE model,
4707                // so the concat-prime isolation fix has to land here as well.
4708                let g = match &m.gate_inp_shexp {
4709                    Some(gate_inp_shexp) if crate::router_prefill_exact_on() => {
4710                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
4711                    }
4712                    Some(gate_inp_shexp) => {
4713                        let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
4714                        let mut g = e.uninit(t)?;
4715                        e.sigmoid(&gs, &mut g, t)?;
4716                        g
4717                    }
4718                    None => e.htod(&vec![1.0f32; t])?,
4719                };
4720                e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
4721            }
4722            return Ok(moe_out);
4723        }
4724
4725        // DECODE-ONCE MMQ (rung 3, MEMRA_MOE_DEC=1 default-on): dequant each weight group once per
4726        // (row,group) then dp4a across the expert's tokens. _em re-decoded per token (NEUTRAL).
4727        let dec = std::env::var("MEMRA_MOE_DEC").map(|v| v != "0").unwrap_or(true);
4728        let matvec = |proj, exi: &_, exo: &_, exp_d: &_, pt: &_, aq: &_, ad: &_,
4729                      inf, outf, qtype, rb| -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4730            // _dec's decode-once extractors are IQ-only; k-quant expert layers take the _em dot path.
4731            let dec = dec && q8_expert_dec_supported(qtype);
4732            if dec { e.moe_pairs_matvec_q8_dec(&dev.ptr_row, proj, exi, exo, exp_d, pt, aq, ad,
4733                                               inf, outf, n_expert, n_active, n_pairs, qtype, rb) }
4734            else   { e.moe_pairs_matvec_q8_em (&dev.ptr_row, proj, exi, exo, exp_d, pt, aq, ad,
4735                                               inf, outf, n_expert, n_active, n_pairs, qtype, rb) }
4736        };
4737        let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
4738        let gate = matvec(0, &exi, &exo, &exp_d, &pt, &zq, &zd,
4739                          n_embd, n_ff_exp, m.gate_exps.qtype, rbg_d)?;
4740        let up = matvec(1, &exi, &exo, &exp_d, &pt, &zq, &zd,
4741                        n_embd, n_ff_exp, m.up_exps.qtype, rbu_d)?;
4742        let act = e.moe_pairs_silu_mul(&gate, &up, n_pairs * n_ff_exp)?;
4743        let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
4744        // down consumes PAIR-major activation rows: pair_tok = identity.
4745        let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
4746        let pself = e.htod_i32(&pair_self)?;
4747        let y_down = matvec(2, &exi, &exo, &exp_d, &pself, &aq2, &ad2,
4748                            n_ff_exp, n_embd, m.down_exps.qtype, m.down_exps.row_bytes)?;
4749        let mut moe_out = e.uninit(t * n_embd)?;   // scatter fully overwrites per (token,col)
4750        e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
4751
4752        // SHARED EXPERT epilogue — same as the other paths.
4753        // gate_inp_shexp is OPTIONAL: qwen35moe gates the shared expert (sigmoid(gate_inp) x sh);
4754        // MiniMax-M3 (DeepSeek-V3 class) has NO shexp gate — the shared expert adds directly.
4755        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
4756            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
4757        {
4758            let n_ff_sh = gate_shexp.out_features();
4759            let sg_gate = e.matmul(gate_shexp, z, t)?;
4760            let sg_up = e.matmul(up_shexp, z, t)?;
4761            let mut sa = e.uninit(t * n_ff_sh)?;
4762            e.silu_mul(&sg_gate, &sg_up, &mut sa, t * n_ff_sh)?;
4763            let sh = e.matmul(down_shexp, &sa, t)?;
4764            // shexp gate: qwen35moe sigmoid-gates; M3 has no gate tensor -> weight 1.0.
4765            // m-INVARIANT fused sigmoid-dot under router_prefill_exact (serve isolation,
4766            // lane/concat-prime-exact) — every shexp-gate arm shares the same form so a
4767            // dispatch choice cannot change bits.
4768            let g = match &m.gate_inp_shexp {
4769                Some(gate_inp_shexp) if crate::router_prefill_exact_on() => {
4770                    e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
4771                }
4772                Some(gate_inp_shexp) => {
4773                    let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
4774                    let mut g = e.uninit(t)?;
4775                    e.sigmoid(&gs, &mut g, t)?;
4776                    g
4777                }
4778                None => e.htod(&vec![1.0f32; t])?,
4779            };
4780            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
4781        }
4782        Ok(moe_out)
4783    }
4784
4785    /// kernel headers); the shared-expert epilogue is byte-identical to moe_ffn_sequential's.
4786    #[allow(clippy::too_many_arguments)]
4787    #[allow(clippy::too_many_arguments)]
4788    fn moe_ffn_dev(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>,
4789                   zq8: Option<&(CudaSlice<i8>, CudaSlice<f32>)>, logits: &CudaSlice<f32>,
4790                   t: usize, cfg: &ModelConfig, il: u16, max_block: usize)
4791                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4792        let moe = cfg.moe.as_ref().unwrap();
4793        let n_embd = cfg.n_embd as usize;
4794        let n_expert = moe.expert_count as usize;
4795        let n_used = moe.expert_used_count as usize;
4796        let n_ff_exp = moe.expert_ff_length as usize;
4797        // moe_router_topk is SOFTMAX-only (no exp_probs_b bias, no expert_weights_scale) and every
4798        // gate_up kernel here fuses PLAIN silu(gate)*up. `dev_ok` denies sigmoid-router archs and
4799        // clamped layers; assert both so a future caller that skips the gate fails loudly.
4800        debug_assert!(cfg.sigmoid_router().is_none(),
4801                      "moe_ffn_dev routes SOFTMAX: a sigmoid-router arch would pick wrong experts");
4802        debug_assert!(!cfg.swiglu_clamped_at(il as u32),
4803                      "moe_ffn_dev's fused epilogue is plain SiLU: no clamped form");
4804
4805        // device top-k: sel [t, n_used] i32, w [t, n_used] f32 — stays on device.
4806        let (sel_d, mut w_d) = e.moe_router_topk(logits, t, n_expert, n_used)?;
4807        // Down-projection macro fold (compressed-tensors NVFP4 artifacts): one tiny launch,
4808        // skipped entirely for macro-free experts (every k-quant GGUF).
4809        if m.has_macros {
4810            e.moe_w_scale_by_expert(&mut w_d, &sel_d, &m.dev_macros, n_expert, t * n_used)?;
4811        }
4812
4813        // moe_out rows are FULLY overwritten by moe_down8_fma_dev — uninit (stage-2 rule).
4814        let mut moe_out = e.uninit(t * n_embd)?;
4815
4816        // RESIDENT-EXPERTS arm: the pointer row comes from the load-time slab (no cache, no
4817        // lock). Same kernels/loop as the SLRU arm below — only the row's provenance differs.
4818        if let Some(dev) = m.dev_exps.as_ref() {
4819            // WALL-GAP ARC: interleaved gate/up slab (MEMRA_MOE_GU_IL) -> both projections use
4820            // the combined stride; up's base is offset in the ptr table. Down unchanged.
4821            let (rbg_d, rbu_d) = if dev.gu_il {
4822                let sxx = m.gate_exps.row_bytes + m.up_exps.row_bytes; (sxx, sxx)
4823            } else { (m.gate_exps.row_bytes, m.up_exps.row_bytes) };
4824            let q8 = moe_q8_enabled()
4825                && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
4826                && q8_expert_supported(m.down_exps.qtype);
4827            // SMALL-M ROWS ARM (MEMRA_SPEC_M2, lane/spec-m2): batch the verify token loop —
4828            // ONE batched z-quantize + ONE gate_up rows launch + ONE act quantize + ONE down
4829            // rows launch (4 launches/layer, was 4t). BIT-IDENTICAL per token to the serial
4830            // loop below (rows twins = the _v/w8h2v per-token programs on a grid.z token axis;
4831            // quantize_q8_1 is per-32-block row-independent). Gated to the AUTO kernel modes —
4832            // a custom MEMRA_MOE_DEVQ8_GU/DOWN diagnostic run keeps the serial loop so the
4833            // dispatched kernel stays exactly the env-selected one — and to the w8h2v shape
4834            // (n_ff_exp==512, n_used<=8), the same contract the AUTO down dispatch keys on.
4835            let rows_arm = q8 && t > 1 && crate::spec::spec_m2()
4836                && n_ff_exp == 512 && n_used <= 8
4837                && std::env::var("MEMRA_MOE_DEVQ8_GU").map(|v| v.is_empty() || v == "v").unwrap_or(true)
4838                && std::env::var("MEMRA_MOE_DEVQ8_DOWN").map(|v| v.is_empty() || v == "w8h2v").unwrap_or(true);
4839            // CSR EXPERT-DEDUP gate_up (verify-cost target #1, DEFAULT ON 2026-07-10): the
4840            // owner-scan kernel serves every (token, slot) pair of an expert from ONE block,
4841            // deduping the 38-40% duplicated weight-stream+decode the overlap probe measured
4842            // (gate_up 55.0 -> 39.7us/launch; +1.3-2.1% spec e2e p2, +0.6-1.7% p3, all K).
4843            // Bit-identical to the _rows twins (explicit-intrinsic accumulate — the ULP/fmad
4844            // lesson; =2 byte-compare verified zero diffs). down stays on _rows (CSR down
4845            // measured 23.5 -> 37.5us: 16-group rows can't amortize the serial pair loop).
4846            // MEMRA_MOE_CSR=0 rollback; =2 runs BOTH paths and byte-compares (debug).
4847            let csr_mode = std::env::var("MEMRA_MOE_CSR").ok()
4848                .and_then(|v| v.parse::<i32>().ok()).unwrap_or(1);
4849            let csr_qt = |qt: i32| qt == crate::QT_IQ4_XS || qt == crate::QT_IQ3_S;
4850            let csr_arm = rows_arm && csr_mode > 0 && t <= 10
4851                && csr_qt(m.gate_exps.qtype) && csr_qt(m.up_exps.qtype)
4852                && csr_qt(m.down_exps.qtype);
4853            if csr_arm {
4854                if csr_mode == 2 {
4855                    static ENGAGED: std::sync::Once = std::sync::Once::new();
4856                    ENGAGED.call_once(|| eprintln!("[memra] moe CSR byte-compare mode ON (t={t})"));
4857                }
4858                let n_pairs = t * n_used;
4859                let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
4860                let act = e.moe_gate_up_silu8_dev_q8_csr(&dev.ptr_row, &sel_d, &zq, &zd, n_pairs,
4861                                                         n_embd, n_ff_exp, n_used, n_expert,
4862                                                         m.gate_exps.qtype, m.up_exps.qtype,
4863                                                         rbg_d, rbu_d)?;
4864                let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
4865                // down stays on the _rows twin — BOTH CSR down variants measured negative
4866                // (v1 serial pairs 23.5->37.5us; v2 warp-parallel+SMEM -14% e2e, K=8 -37%):
4867                // 16-group rows have too little decode to amortize any dedup structure.
4868                e.moe_down8_fma_dev_q8_rows(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out,
4869                                            t, n_ff_exp, n_embd, n_used, n_expert,
4870                                            m.down_exps.qtype, m.down_exps.row_bytes)?;
4871                if csr_mode == 2 {
4872                    // DEBUG BYTE-COMPARE: run the _rows twins on the same inputs, diff bits.
4873                    let act_r = e.moe_gate_up_silu8_dev_q8_rows(&dev.ptr_row, &sel_d, &zq, &zd, t,
4874                                                                n_embd, n_ff_exp, n_used, n_expert,
4875                                                                m.gate_exps.qtype, m.up_exps.qtype,
4876                                                                rbg_d, rbu_d, &m.dev_macros)?;
4877                    let mut out_r = e.uninit(t * n_embd)?;
4878                    let (aq2r, ad2r) = e.quantize_q8_1(&act_r, n_pairs, n_ff_exp)?;
4879                    e.moe_down8_fma_dev_q8_rows(&dev.ptr_row, &sel_d, &w_d, &aq2r, &ad2r, &mut out_r,
4880                                                t, n_ff_exp, n_embd, n_used, n_expert,
4881                                                m.down_exps.qtype, m.down_exps.row_bytes)?;
4882                    let (a1, a2) = (e.dtoh(&act)?, e.dtoh(&act_r)?);
4883                    let (o1, o2) = (e.dtoh(&moe_out)?, e.dtoh(&out_r)?);
4884                    let ba = a1.iter().zip(&a2).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
4885                    let bo = o1.iter().zip(&o2).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
4886                    if ba + bo > 0 {
4887                        eprintln!("[csr-check] il={il} t={t} ACT diffs={ba}/{} OUT diffs={bo}/{}",
4888                                  a1.len(), o1.len());
4889                        // First 4 differing ACT elements: (pair, o, csr, rows) + that pair's expert
4890                        let sel_h = e.dtoh_i32(&sel_d)?;
4891                        let mut shown = 0;
4892                        for (i, (x, y)) in a1.iter().zip(&a2).enumerate() {
4893                            if x.to_bits() != y.to_bits() && shown < 4 {
4894                                let (p, o) = (i / n_ff_exp, i % n_ff_exp);
4895                                let ex = sel_h[p];
4896                                let npx = sel_h.iter().filter(|&&v| v == ex).count();
4897                                eprintln!("  ACT p={p} ex={ex} np={npx} o={o} csr={x:e} rows={y:e}");
4898                                shown += 1;
4899                            }
4900                        }
4901                        std::process::exit(3);
4902                    }
4903                }
4904            } else if rows_arm {
4905                // TEMP PROBE (MEMRA_MOE_OVERLAP=1): cross-token expert-activation overlap at
4906                // verify — sizes the CSR dedup win (unique experts vs t*n_used pairs).
4907                if std::env::var("MEMRA_MOE_OVERLAP").as_deref() == Ok("1") {
4908                    use std::sync::atomic::{AtomicU64, Ordering};
4909                    static PAIRS: AtomicU64 = AtomicU64::new(0);
4910                    static UNIQ: AtomicU64 = AtomicU64::new(0);
4911                    static CALLS: AtomicU64 = AtomicU64::new(0);
4912                    let sel_h = e.dtoh_i32(&sel_d)?;
4913                    let mut u: Vec<i32> = sel_h.clone(); u.sort_unstable(); u.dedup();
4914                    PAIRS.fetch_add(sel_h.len() as u64, Ordering::Relaxed);
4915                    UNIQ.fetch_add(u.len() as u64, Ordering::Relaxed);
4916                    let c = CALLS.fetch_add(1, Ordering::Relaxed) + 1;
4917                    if c % 480 == 0 {
4918                        let p = PAIRS.load(Ordering::Relaxed); let q = UNIQ.load(Ordering::Relaxed);
4919                        eprintln!("[overlap] calls={c} pairs={p} unique={q} ratio={:.3} (t={t})",
4920                                  q as f64 / p as f64);
4921                    }
4922                }
4923                let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
4924                let act = e.moe_gate_up_silu8_dev_q8_rows(&dev.ptr_row, &sel_d, &zq, &zd, t,
4925                                                          n_embd, n_ff_exp, n_used, n_expert,
4926                                                          m.gate_exps.qtype, m.up_exps.qtype,
4927                                                          rbg_d, rbu_d, &m.dev_macros)?;
4928                let (aq2, ad2) = e.quantize_q8_1(&act, t * n_used, n_ff_exp)?;
4929                e.moe_down8_fma_dev_q8_rows(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out,
4930                                            t, n_ff_exp, n_embd, n_used, n_expert,
4931                                            m.down_exps.qtype, m.down_exps.row_bytes)?;
4932            } else {
4933            for tok in 0..t {
4934                let zt = z.slice(tok * n_embd..(tok + 1) * n_embd);
4935                let selt = sel_d.slice(tok * n_used..(tok + 1) * n_used);
4936                let wt = w_d.slice(tok * n_used..(tok + 1) * n_used);
4937                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4938                if q8 {
4939                    let (zq, zd) = match (t, zq8) {
4940                        (1, Some((q, d))) => (q.clone(), d.clone()),
4941                        _ => e.quantize_q8_1_view(&zt, 1, n_embd)?,
4942                    };
4943                    let act = e.moe_gate_up_silu8_dev_q8(&dev.ptr_row, &selt, &zq, &zd,
4944                                                         n_embd, n_ff_exp, n_used, n_expert,
4945                                                         m.gate_exps.qtype, m.up_exps.qtype,
4946                                                         rbg_d, rbu_d, &m.dev_macros)?;
4947                    let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
4948                    e.moe_down8_fma_dev_q8(&dev.ptr_row, &selt, &wt, &aq2, &ad2, &mut dst,
4949                                           n_ff_exp, n_embd, n_used, n_expert,
4950                                           m.down_exps.qtype, m.down_exps.row_bytes)?;
4951                } else {
4952                    let act = e.moe_gate_up_silu8_dev(&dev.ptr_row, &selt, &zt, n_embd, n_ff_exp,
4953                                                      n_used, n_expert,
4954                                                      m.gate_exps.qtype, m.up_exps.qtype,
4955                                                      rbg_d, rbu_d, &m.dev_macros)?;
4956                    e.moe_down8_fma_dev(&dev.ptr_row, &selt, &wt, &act, &mut dst,
4957                                        n_ff_exp, n_embd, n_used, n_expert,
4958                                        m.down_exps.qtype, m.down_exps.row_bytes)?;
4959                }
4960            }
4961            }
4962        } else {
4963        // Launch under the cache lock: the row borrow lives as long as the closure, and the
4964        // lock covers only launch ISSUE (µs), same policy as moe_cached_gemm.
4965        // Q8 ARM PARITY (2026-07-06): the SLRU arm ran the f32-dequant _dev kernels only —
4966        // 80us/launch vs the q8 twins' 15us on the SAME shapes (fixed-build profile: 228
4967        // f32 launches = 36ms of the 64-tok window). Same q8 gate + kernels as the resident
4968        // arm above; MEMRA_MOE_Q8=0 restores the byte-identical f32 path.
4969        let q8 = moe_q8_enabled()
4970            && q8_expert_supported(m.gate_exps.qtype) && q8_expert_supported(m.up_exps.qtype)
4971            && q8_expert_supported(m.down_exps.qtype);
4972        e.with_moe_cache(max_block, |c, eng| {
4973            let row = c.layer_dev_row(il, n_expert, eng)?
4974                .ok_or("moe_ffn_dev: layer row vanished under the lock")?;
4975            for tok in 0..t {
4976                let zt = z.slice(tok * n_embd..(tok + 1) * n_embd);
4977                let selt = sel_d.slice(tok * n_used..(tok + 1) * n_used);
4978                let wt = w_d.slice(tok * n_used..(tok + 1) * n_used);
4979                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
4980                if q8 {
4981                    let (zq, zd) = match (t, zq8) {
4982                        (1, Some((q, d))) => (q.clone(), d.clone()),
4983                        _ => eng.quantize_q8_1_view(&zt, 1, n_embd)?,
4984                    };
4985                    let act = eng.moe_gate_up_silu8_dev_q8(row, &selt, &zq, &zd,
4986                                                           n_embd, n_ff_exp, n_used, n_expert,
4987                                                           m.gate_exps.qtype, m.up_exps.qtype,
4988                                                           m.gate_exps.row_bytes, m.up_exps.row_bytes,
4989                                                           &m.dev_macros)?;
4990                    let (aq2, ad2) = eng.quantize_q8_1(&act, n_used, n_ff_exp)?;
4991                    eng.moe_down8_fma_dev_q8(row, &selt, &wt, &aq2, &ad2, &mut dst,
4992                                             n_ff_exp, n_embd, n_used, n_expert,
4993                                             m.down_exps.qtype, m.down_exps.row_bytes)?;
4994                } else {
4995                    let act = eng.moe_gate_up_silu8_dev(row, &selt, &zt, n_embd, n_ff_exp,
4996                                                        n_used, n_expert,
4997                                                        m.gate_exps.qtype, m.up_exps.qtype,
4998                                                        m.gate_exps.row_bytes, m.up_exps.row_bytes,
4999                                                        &m.dev_macros)?;
5000                    eng.moe_down8_fma_dev(row, &selt, &wt, &act, &mut dst,
5001                                          n_ff_exp, n_embd, n_used, n_expert,
5002                                          m.down_exps.qtype, m.down_exps.row_bytes)?;
5003                }
5004            }
5005            // instrumentation parity with the host paths (3 blocks/expert-slot, all hits).
5006            c.hits += (t * 3 * n_used) as u64;
5007            Ok(())
5008        })?;
5009        }
5010
5011        // SHARED EXPERT epilogue — byte-identical to moe_ffn_sequential step 3 (incl. its Q8
5012        // TRUNK-FUSION arm: fused2 is bit-identical to the two matmul calls per (tensor,row)).
5013        // gate_inp_shexp is OPTIONAL: qwen35moe gates the shared expert (sigmoid(gate_inp) x sh);
5014        // MiniMax-M3 (DeepSeek-V3 class) has NO shexp gate — the shared expert adds directly.
5015        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
5016            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
5017        {
5018            let n_ff_sh = gate_shexp.out_features();
5019            // verify-t (2..15) decode-exact arm: this fn now serves the spec verify batches
5020            // (pairs gate moved to t>=PRIME_MIN_T), so the shexp chain must match t==1 per col.
5021            let verify_t = t > 1 && t < PRIME_MIN_T;
5022            let (sg_gate, sg_up) = if t == 1 {
5023                match e.matmul_q8_fused2_x(gate_shexp, up_shexp, z)? {
5024                    Some(pair) => pair,
5025                    None => (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?),
5026                }
5027            } else if verify_t {
5028                // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): the shexp gate+up pair
5029                // rides one shared quantize + one fused2 batched launch instead of two
5030                // decode-exact calls. Bit-identical per (tensor,token,row) — see spec_fused_t.
5031                let mut fused = None;
5032                if crate::spec::spec_fused_t() && (2..=4).contains(&t)
5033                    && e.uses_q8_1_fast(gate_shexp) && e.uses_q8_1_fast(up_shexp) {
5034                    let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5035                    fused = e.matmul_q8_fused2_t(gate_shexp, up_shexp, &zq, &zd, t)?;
5036                }
5037                match fused {
5038                    Some(pair) => pair,
5039                    None => (e.matmul_decode_exact(gate_shexp, z, t)?,
5040                             e.matmul_decode_exact(up_shexp, z, t)?),
5041                }
5042            } else {
5043                (e.matmul(gate_shexp, z, t)?, e.matmul(up_shexp, z, t)?)
5044            };
5045            let mut sa = e.uninit(t * n_ff_sh)?;  // silu_mul fully overwrites
5046            e.silu_mul(&sg_gate, &sg_up, &mut sa, t * n_ff_sh)?;
5047            let sh = if verify_t { e.matmul_decode_exact(down_shexp, &sa, t)? }
5048                     else { e.matmul(down_shexp, &sa, t)? };
5049            // shexp gate: qwen35moe sigmoid-gates; M3 has no gate tensor -> weight 1.0.
5050            // Same fused sigmoid-dot as moe_ffn_sequential step 3 (byte-identity contract
5051            // between the two arms; prefill keeps the batched cuBLASLt linear).
5052            let g = match &m.gate_inp_shexp {
5053                Some(gate_inp_shexp) => {
5054                    // router_prefill_exact_on(): the fused sigmoid-dot is m-INVARIANT and
5055                    // serves EVERY t (serve isolation, lane/concat-prime-exact).
5056                    if t < PRIME_MIN_T || crate::router_prefill_exact_on() {
5057                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
5058                    } else {
5059                        let gs = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
5060                        let mut g = e.uninit(t)?;
5061                        e.sigmoid(&gs, &mut g, t)?;
5062                        g
5063                    }
5064                }
5065                None => e.htod(&vec![1.0f32; t])?,
5066            };
5067            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, t)?;
5068        }
5069
5070        Ok(moe_out)
5071    }
5072
5073    /// STAGE-2 GROUPED DECODE (2026-07-04): run ONE token's whole routed-expert FFN in TWO
5074    /// launches when every one of its 3*n_used blocks is ALREADY cache-resident. Returns
5075    /// Ok(true) if the grouped path ran (caller skips the sequential loop for this token);
5076    /// Ok(false) on ANY miss (caller falls through — the sequential loop stages/admits as
5077    /// before, so the NEXT occurrence takes the grouped path). Pointer safety: cache slots are
5078    /// fixed-address for the engine's lifetime and the pure-HIT path performs no admission, so
5079    /// the collected raw pointers cannot move between collection and launch (single-threaded
5080    /// decode; the lock is held only for collection, launches are stream-ordered after any
5081    /// prior same-stream staging writes).
5082    #[allow(clippy::too_many_arguments)]
5083    /// q8 twin of moe_gdec_token (dp4a arc): same residency check + 2-launch shape; the fused
5084    /// kernels consume the pre-quantized z-row and re-quantize act per slot batch.
5085    #[allow(clippy::too_many_arguments)]
5086    fn moe_gdec_token_q8(e: &Engine, m: &MoeWeights, il: u16, max_block: usize,
5087                      zq: &CudaSlice<i8>, zd: &CudaSlice<f32>, sel: &[u32], w: &[f32],
5088                      moe_out: &mut CudaSlice<f32>, tok: usize,
5089                      n_embd: usize, n_ff_exp: usize, n_used: usize)
5090                      -> Result<bool, Box<dyn std::error::Error>> {
5091        use crate::moe_cache::{BlockId, PROJ_GATE, PROJ_UP, PROJ_DOWN};
5092        use cudarc::driver::DevicePtr;
5093        let ptrs = e.with_moe_cache(max_block, |c, eng| {
5094            let mut g = [0u64; 8];
5095            let mut u = [0u64; 8];
5096            let mut d = [0u64; 8];
5097            for (j, &ex) in sel.iter().enumerate() {
5098                let ex = ex as u16;
5099                let (Some(sg), Some(su), Some(sd)) = (c.resident(BlockId::new(il, PROJ_GATE, ex)),
5100                                                      c.resident(BlockId::new(il, PROJ_UP,   ex)),
5101                                                      c.resident(BlockId::new(il, PROJ_DOWN, ex)))
5102                else { return Ok(None); };
5103                let __s = eng.stream();
5104                let (pg, _e0) = c.slot(sg).device_ptr(&__s);
5105                let (pu, _e1) = c.slot(su).device_ptr(&__s);
5106                let (pd, _e2) = c.slot(sd).device_ptr(&__s);
5107                g[j] = pg as u64; u[j] = pu as u64; d[j] = pd as u64;
5108            }
5109            if cpu_expert_profile_admit_enabled() && !c.is_frozen() {
5110                for &ex in sel {
5111                    let ex = ex as u16;
5112                    for proj in [PROJ_GATE, PROJ_UP, PROJ_DOWN] {
5113                        c.note_profile_hit(BlockId::new(il, proj, ex));
5114                    }
5115                }
5116            }
5117            c.hits += (3 * n_used) as u64;
5118            Ok(Some((g, u, d)))
5119        })?;
5120        let Some((g, u, d)) = ptrs else { return Ok(false) };
5121        let mut wv = [0f32; 8];
5122        wv[..n_used].copy_from_slice(w);
5123        let act = e.moe_gate_up_silu8_q8(crate::WPtr8(g), crate::WPtr8(u), zq, zd,
5124                                         n_embd, n_ff_exp, n_used,
5125                                         m.gate_exps.qtype, m.up_exps.qtype,
5126                                         m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
5127        // per-slot act quantize: [n_used, n_ff] rows in one quantize launch.
5128        let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
5129        let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
5130        e.moe_down8_fma_q8(crate::WPtr8(d), crate::F32x8(wv), &aq2, &ad2, &mut dst,
5131                           n_ff_exp, n_embd, n_used,
5132                           m.down_exps.qtype, m.down_exps.row_bytes)?;
5133        Ok(true)
5134    }
5135
5136    fn moe_gdec_token(e: &Engine, m: &MoeWeights, il: u16, max_block: usize,
5137                      zt: &cudarc::driver::CudaView<f32>, sel: &[u32], w: &[f32],
5138                      moe_out: &mut CudaSlice<f32>, tok: usize,
5139                      n_embd: usize, n_ff_exp: usize, n_used: usize)
5140                      -> Result<bool, Box<dyn std::error::Error>> {
5141        use crate::moe_cache::{BlockId, PROJ_GATE, PROJ_UP, PROJ_DOWN};
5142        use cudarc::driver::DevicePtr;
5143        // One lock hold: residency-check all 3*n_used blocks, collect raw slot pointers.
5144        let ptrs = e.with_moe_cache(max_block, |c, eng| {
5145            let mut g = [0u64; 8];
5146            let mut u = [0u64; 8];
5147            let mut d = [0u64; 8];
5148            for (j, &ex) in sel.iter().enumerate() {
5149                let ex = ex as u16;
5150                let (Some(sg), Some(su), Some(sd)) = (c.resident(BlockId::new(il, PROJ_GATE, ex)),
5151                                                      c.resident(BlockId::new(il, PROJ_UP,   ex)),
5152                                                      c.resident(BlockId::new(il, PROJ_DOWN, ex)))
5153                else { return Ok(None); };
5154                let __s = eng.stream();
5155                let (pg, _e0) = c.slot(sg).device_ptr(&__s);
5156                let (pu, _e1) = c.slot(su).device_ptr(&__s);
5157                let (pd, _e2) = c.slot(sd).device_ptr(&__s);
5158                g[j] = pg as u64; u[j] = pu as u64; d[j] = pd as u64;
5159            }
5160            if cpu_expert_profile_admit_enabled() && !c.is_frozen() {
5161                for &ex in sel {
5162                    let ex = ex as u16;
5163                    for proj in [PROJ_GATE, PROJ_UP, PROJ_DOWN] {
5164                        c.note_profile_hit(BlockId::new(il, proj, ex));
5165                    }
5166                }
5167            }
5168            c.hits += (3 * n_used) as u64; // instrumentation parity with dispatch()
5169            Ok(Some((g, u, d)))
5170        })?;
5171        let Some((g, u, d)) = ptrs else { return Ok(false) };
5172        let mut wv = [0f32; 8];
5173        wv[..n_used].copy_from_slice(w);
5174        // 2 launches: (gate+up+silu) x8, then (down + slot-ordered FMA accumulate) x8.
5175        let act = e.moe_gate_up_silu8(crate::WPtr8(g), crate::WPtr8(u), zt,
5176                                      n_embd, n_ff_exp, n_used,
5177                                      m.gate_exps.qtype, m.up_exps.qtype,
5178                                      m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
5179        let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
5180        e.moe_down8_fma_into(crate::WPtr8(d), crate::F32x8(wv), &act, &mut dst,
5181                             n_ff_exp, n_embd, n_used,
5182                             m.down_exps.qtype, m.down_exps.row_bytes)?;
5183        Ok(true)
5184    }
5185
5186    /// EDGE-1 §B.3: dispatch one expert projection through the SLRU cache, then run the SAME
5187    /// `qmatvec_view` from whichever slot it landed in (resident HIT or staged MISS). `x` is the
5188    /// sliced activation row. `proj` selects the gate/up/down HostExps tensor. Returns y = W_expert @ x.
5189    /// q8 twin of moe_cached_gemm: same dispatch/slot mechanics, dp4a expert kernel.
5190    fn moe_cached_gemm_q8(e: &Engine, il: u16, proj: u8, ex: usize, m: &MoeWeights,
5191                          max_block: usize, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>)
5192                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5193        use crate::moe_cache::{BlockId, DispatchSlot, PROJ_GATE, PROJ_UP};
5194        let exps = match proj { PROJ_GATE => &m.gate_exps, PROJ_UP => &m.up_exps, _ => &m.down_exps };
5195        let layout = exps.expert_layout(ex);
5196        let id = BlockId::new(il, proj, ex as u16);
5197        let source = exps.expert_source(ex);
5198        e.with_moe_cache(max_block, |c, eng| {
5199            let slot = c.dispatch_source(id, source, eng)?;
5200            let DispatchSlot::Resident(sl) = slot;
5201            let buf = c.slot(sl);
5202            eng.qmatvec_expert_q8(buf, 0..layout.len, aq, ad, 1, exps.in_f, exps.out_f,
5203                                  layout.qtype, layout.row_bytes)
5204        })
5205    }
5206
5207    fn moe_cached_gemm(e: &Engine, il: u16, proj: u8, ex: usize, m: &MoeWeights,
5208                       max_block: usize, x: &cudarc::driver::CudaView<f32>)
5209                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5210        use crate::moe_cache::{BlockId, DispatchSlot, PROJ_GATE, PROJ_UP};
5211        let exps = match proj { PROJ_GATE => &m.gate_exps, PROJ_UP => &m.up_exps, _ => &m.down_exps };
5212        let layout = exps.expert_layout(ex);
5213        let id = BlockId::new(il, proj, ex as u16);
5214        let source = exps.expert_source(ex);
5215        // dispatch under the lock (lookup/admit/memcpy-issue), then resolve the slot and GEMM.
5216        e.with_moe_cache(max_block, |c, eng| {
5217            let slot = c.dispatch_source(id, source, eng)?;
5218            // resolve the device buffer for this slot; the GEMM is enqueued on the compute stream
5219            // (the same stream the memcpy was issued on, so ordering holds without extra sync).
5220            let DispatchSlot::Resident(sl) = slot;
5221            let buf = c.slot(sl);
5222            eng.qmatvec_view(buf, 0..layout.len, x, 1, exps.in_f, exps.out_f,
5223                             layout.qtype, layout.row_bytes)
5224        })
5225    }
5226
5227    /// Populate the warmup cache for an expert whose current-token output intentionally ran on
5228    /// CPU. No GEMM is launched and callers invoke this only after the CPU result has completed,
5229    /// so the current forward's backend assignment and output remain unchanged.
5230    fn moe_profile_admit_expert(
5231        e: &Engine,
5232        il: u16,
5233        ex: usize,
5234        m: &MoeWeights,
5235        max_block: usize,
5236    ) -> Result<(), Box<dyn std::error::Error>> {
5237        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5238        e.with_moe_cache(max_block, |cache, eng| {
5239            for (proj, exps) in [
5240                (PROJ_GATE, &m.gate_exps),
5241                (PROJ_UP, &m.up_exps),
5242                (PROJ_DOWN, &m.down_exps),
5243            ] {
5244                let id = BlockId::new(il, proj, ex as u16);
5245                let _ = cache.dispatch_source(id, exps.expert_source(ex), eng)?;
5246            }
5247            Ok(())
5248        })
5249    }
5250
5251    /// Read a projection from the immutable residency set when present; otherwise use one
5252    /// transient slot without admitting or evicting anything. Used only by post-freeze prefill.
5253    #[allow(clippy::too_many_arguments)]
5254    fn moe_frozen_gemm(
5255        e: &Engine,
5256        il: u16,
5257        proj: u8,
5258        ex: usize,
5259        m: &MoeWeights,
5260        max_block: usize,
5261        x: &cudarc::driver::CudaView<f32>,
5262        scratch: &mut Option<CudaSlice<u8>>,
5263        scratch_len: usize,
5264    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5265        use crate::moe_cache::{BlockId, PROJ_GATE, PROJ_UP};
5266        let exps = match proj {
5267            PROJ_GATE => &m.gate_exps,
5268            PROJ_UP => &m.up_exps,
5269            _ => &m.down_exps,
5270        };
5271        let layout = exps.expert_layout(ex);
5272        let id = BlockId::new(il, proj, ex as u16);
5273        if let Some(output) = e.with_moe_cache(max_block, |cache, eng| {
5274            let Some(slot) = cache.resident(id) else {
5275                return Ok(None);
5276            };
5277            let buf = cache.slot(slot);
5278            Ok(Some(eng.qmatvec_view(
5279                buf,
5280                0..layout.len,
5281                x,
5282                1,
5283                exps.in_f,
5284                exps.out_f,
5285                layout.qtype,
5286                layout.row_bytes,
5287            )?))
5288        })? {
5289            return Ok(output);
5290        }
5291        if scratch.is_none() {
5292            *scratch = Some(e.alloc_u8_uninit(scratch_len)?);
5293        }
5294        let scratch = scratch.as_mut().unwrap();
5295        e.stage_expert(exps.expert_bytes(ex), scratch, 0)?;
5296        e.qmatvec_view(
5297            scratch,
5298            0..layout.len,
5299            x,
5300            1,
5301            exps.in_f,
5302            exps.out_f,
5303            layout.qtype,
5304            layout.row_bytes,
5305        )
5306    }
5307
5308    fn moe_prefetch_expert(
5309        e: &Engine,
5310        il: u16,
5311        ex: usize,
5312        m: &MoeWeights,
5313        max_block: usize,
5314        keep: &[crate::moe_cache::BlockId],
5315    ) -> Result<(), Box<dyn std::error::Error>> {
5316        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5317        e.with_moe_cache(max_block, |c, eng| {
5318            for (proj, exps) in [(PROJ_GATE, &m.gate_exps), (PROJ_UP, &m.up_exps),
5319                                 (PROJ_DOWN, &m.down_exps)] {
5320                let id = BlockId::new(il, proj, ex as u16);
5321                let _ = c.prefetch_source(id, exps.expert_source(ex), keep, eng)?;
5322            }
5323            Ok(())
5324        })
5325    }
5326
5327    /// Worker-mode disk lookahead for grouped prefill. Memory sources are deliberately skipped so
5328    /// selecting `worker` changes only storage scheduling here; all CUDA work stays in dispatch.
5329    fn moe_prefetch_disk_expert(e: &Engine, il: u16, ex: usize, m: &MoeWeights,
5330                                max_block: usize, keep: &[crate::moe_cache::BlockId])
5331                                -> Result<(), Box<dyn std::error::Error>> {
5332        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5333        e.with_moe_cache(max_block, |c, eng| {
5334            for (proj, exps) in [(PROJ_GATE, &m.gate_exps), (PROJ_UP, &m.up_exps),
5335                                 (PROJ_DOWN, &m.down_exps)] {
5336                let source = exps.expert_source(ex);
5337                if let crate::model::ExpertSource::Disk { .. } = &source {
5338                    let id = BlockId::new(il, proj, ex as u16);
5339                    let _ = c.prefetch_source(id, source, keep, eng)?;
5340                }
5341            }
5342            Ok(())
5343        })
5344    }
5345
5346    #[inline]
5347    fn moe_prefetch_host_expert(ex: usize, m: &MoeWeights) {
5348        let _ = m.gate_exps.prefetch_expert_pages(ex);
5349        let _ = m.up_exps.prefetch_expert_pages(ex);
5350        let _ = m.down_exps.prefetch_expert_pages(ex);
5351    }
5352}
5353
5354// ================================================================================================
5355// A2: EXPERT-GROUPED MoE PREFILL (MEMRA_MOE_GROUPED=1). Resident-case prototype.
5356//
5357// Instead of the per-token loop (T * 8 experts * 3 projections = 12024 individual m=1 matvecs),
5358// this groups tokens by expert and runs ONE matmul per active expert per projection at m=m_e.
5359// On a 501-token prefill with ~170 active experts, that's ~510 matmuls (vs 12024).
5360//
5361// EXACTNESS: per-token accumulation across its 8 experts is reordered (grouped processes experts
5362// in expert-id order, not the router's top-k order). To preserve bit-identity with the sequential
5363// loop, we use an 8-SLOT scheme: expert outputs are scattered into slots keyed by the token's
5364// top-k position (0..7), then reduced in that fixed order. This makes the f32 addition order
5365// identical to the per-token loop regardless of expert processing order.
5366//
5367// Memory: T * 8 * n_embd * 4 = 501 * 8 * 2048 * 4 = ~32 MB (slot buffer). Fine on 96GB.
5368// ================================================================================================
5369
5370impl HybridModel {
5371    /// Resident-slab fast path for host-routed grouped prefill. Unclamped layers batch the
5372    /// sequential fused q8 program over the token axis; clamped layers use the separate
5373    /// expert-major q8 chain so `ffn_act_lim` remains authoritative.
5374    #[allow(clippy::too_many_arguments)]
5375    fn moe_ffn_grouped_resident_q8(
5376        e: &Engine,
5377        m: &MoeWeights,
5378        z: &CudaSlice<f32>,
5379        t: usize,
5380        cfg: &ModelConfig,
5381        il: u16,
5382        sel_all: &[u32],
5383        w_all: &[f32],
5384        table: &CudaSlice<u64>,
5385        gu_il: bool,
5386    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5387        let moe = cfg.moe.as_ref().unwrap();
5388        let n_embd = cfg.n_embd as usize;
5389        let n_expert = moe.expert_count as usize;
5390        let n_used = moe.expert_used_count as usize;
5391        let n_ff_exp = moe.expert_ff_length as usize;
5392        let n_pairs = t * n_used;
5393        debug_assert_eq!(sel_all.len(), n_pairs);
5394        debug_assert_eq!(w_all.len(), n_pairs);
5395        debug_assert!(
5396            m.gate_exps.macros.is_none()
5397                && m.up_exps.macros.is_none()
5398                && m.down_exps.macros.is_none(),
5399            "resident grouped q8 does not fold per-expert macro scales",
5400        );
5401
5402        // The rows twins run the resident sequential program verbatim on grid.z = token:
5403        // fused gate/up/SiLU per slot, batched activation quantization, then the original
5404        // slot-ordered down/FMA chain. Routing remains the host sigmoid oracle above; these
5405        // kernels consume sel/w only and never enter the softmax device router.
5406        if !cfg.swiglu_clamped_at(il as u32) {
5407            let sel: Vec<i32> = sel_all.iter().map(|&expert| expert as i32).collect();
5408            let sel_d = e.htod_i32(&sel)?;
5409            let w_d = e.htod(w_all)?;
5410            let (gate_row_bytes, up_row_bytes) = if gu_il {
5411                let combined = m.gate_exps.row_bytes + m.up_exps.row_bytes;
5412                (combined, combined)
5413            } else {
5414                (m.gate_exps.row_bytes, m.up_exps.row_bytes)
5415            };
5416            let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5417            let act = e.moe_gate_up_silu8_dev_q8_rows(
5418                table,
5419                &sel_d,
5420                &zq,
5421                &zd,
5422                t,
5423                n_embd,
5424                n_ff_exp,
5425                n_used,
5426                n_expert,
5427                m.gate_exps.qtype,
5428                m.up_exps.qtype,
5429                gate_row_bytes,
5430                up_row_bytes,
5431                &m.dev_macros,
5432            )?;
5433            let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
5434            let mut moe_out = e.uninit(t * n_embd)?;
5435            e.moe_down8_fma_dev_q8_rows_g(
5436                table,
5437                &sel_d,
5438                &w_d,
5439                &aq2,
5440                &ad2,
5441                &mut moe_out,
5442                t,
5443                n_ff_exp,
5444                n_embd,
5445                n_used,
5446                n_expert,
5447                m.down_exps.qtype,
5448                m.down_exps.row_bytes,
5449            )?;
5450
5451            if std::env::var("MEMRA_MOE_STATS").is_ok() {
5452                let mut counts = vec![0usize; n_expert];
5453                for &expert in sel_all {
5454                    counts[expert as usize] += 1;
5455                }
5456                let mut sizes: Vec<usize> =
5457                    counts.into_iter().filter(|&count| count != 0).collect();
5458                sizes.sort_unstable();
5459                let mean = sizes.iter().sum::<usize>() as f64 / sizes.len().max(1) as f64;
5460                println!(
5461                    "moe-grouped il={il} t={t} dispatch=resident-q8-rows active={}/{} \
5462                     m_e: min={} median={} mean={mean:.1} max={}",
5463                    sizes.len(),
5464                    n_expert,
5465                    sizes.first().copied().unwrap_or(0),
5466                    sizes.get(sizes.len() / 2).copied().unwrap_or(0),
5467                    sizes.last().copied().unwrap_or(0),
5468                );
5469            }
5470            return Ok(moe_out);
5471        }
5472
5473        // Clamped layers keep gate/up, activation, and down as separate stages. The pair-major
5474        // matvec body is qmatvec_expert_q8 verbatim, while one launch covers every routed pair.
5475        // Pair ids stay in router slot order so scatter preserves the sequential FMA chain.
5476        let pair_tok: Vec<i32> = (0..n_pairs).map(|pair| (pair / n_used) as i32).collect();
5477        let pair_ex: Vec<i32> = sel_all.iter().map(|&expert| expert as i32).collect();
5478        let tok_off: Vec<i32> = (0..=t).map(|tok| (tok * n_used) as i32).collect();
5479        let tok_ids: Vec<i32> = (0..n_pairs as i32).collect();
5480
5481        let mut by_expert: Vec<Vec<i32>> = vec![Vec::new(); n_expert];
5482        for (pair, &expert) in pair_ex.iter().enumerate() {
5483            by_expert[expert as usize].push(pair as i32);
5484        }
5485
5486        let pair_tok_d = e.htod_i32(&pair_tok)?;
5487        let pair_ex_d = e.htod_i32(&pair_ex)?;
5488        let pair_w_d = e.htod(w_all)?;
5489        let tok_off_d = e.htod_i32(&tok_off)?;
5490        let tok_ids_d = e.htod_i32(&tok_ids)?;
5491
5492        let matvec = |
5493            proj: i32,
5494            pair_rows: &CudaSlice<i32>,
5495            aq: &CudaSlice<i8>,
5496            ad: &CudaSlice<f32>,
5497            in_f: usize,
5498            out_f: usize,
5499            qtype: i32,
5500            row_bytes: usize,
5501        | -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5502            e.moe_pairs_matvec_q8(
5503                table,
5504                proj,
5505                pair_rows,
5506                &pair_ex_d,
5507                aq,
5508                ad,
5509                in_f,
5510                out_f,
5511                n_expert,
5512                n_pairs,
5513                qtype,
5514                row_bytes,
5515            )
5516        };
5517
5518        let (gate_row_bytes, up_row_bytes) = if gu_il {
5519            let combined = m.gate_exps.row_bytes + m.up_exps.row_bytes;
5520            (combined, combined)
5521        } else {
5522            (m.gate_exps.row_bytes, m.up_exps.row_bytes)
5523        };
5524        let (zq, zd) = e.quantize_q8_1(z, t, n_embd)?;
5525        let gate = matvec(
5526            0,
5527            &pair_tok_d,
5528            &zq,
5529            &zd,
5530            n_embd,
5531            n_ff_exp,
5532            m.gate_exps.qtype,
5533            gate_row_bytes,
5534        )?;
5535        let up = matvec(
5536            1,
5537            &pair_tok_d,
5538            &zq,
5539            &zd,
5540            n_embd,
5541            n_ff_exp,
5542            m.up_exps.qtype,
5543            up_row_bytes,
5544        )?;
5545        let mut act = e.uninit(n_pairs * n_ff_exp)?;
5546        Self::ffn_act_lim(
5547            e,
5548            cfg,
5549            &gate,
5550            &up,
5551            1.0,
5552            1.0,
5553            cfg.clamp_exp_at(il as u32),
5554            &mut act,
5555            n_pairs * n_ff_exp,
5556        )?;
5557        let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
5558        let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
5559        let pair_self_d = e.htod_i32(&pair_self)?;
5560        let down = matvec(
5561            2,
5562            &pair_self_d,
5563            &aq2,
5564            &ad2,
5565            n_ff_exp,
5566            n_embd,
5567            m.down_exps.qtype,
5568            m.down_exps.row_bytes,
5569        )?;
5570        let mut moe_out = e.uninit(t * n_embd)?;
5571        e.moe_pairs_scatter(
5572            &down,
5573            &pair_w_d,
5574            &tok_off_d,
5575            &tok_ids_d,
5576            &mut moe_out,
5577            t,
5578            n_embd,
5579        )?;
5580
5581        if std::env::var("MEMRA_MOE_STATS").is_ok() {
5582            let mut sizes: Vec<usize> = by_expert
5583                .iter()
5584                .filter_map(|pairs| (!pairs.is_empty()).then_some(pairs.len()))
5585                .collect();
5586            sizes.sort_unstable();
5587            let mean = sizes.iter().sum::<usize>() as f64 / sizes.len().max(1) as f64;
5588            println!(
5589                "moe-grouped il={il} t={t} dispatch=resident-q8-clamped-pairs active={}/{} \
5590                 m_e: min={} median={} mean={mean:.1} max={}",
5591                sizes.len(),
5592                n_expert,
5593                sizes.first().copied().unwrap_or(0),
5594                sizes.get(sizes.len() / 2).copied().unwrap_or(0),
5595                sizes.last().copied().unwrap_or(0),
5596            );
5597        }
5598        Ok(moe_out)
5599    }
5600
5601    fn moe_ffn_grouped_add_shared(
5602        e: &Engine,
5603        m: &MoeWeights,
5604        z: &CudaSlice<f32>,
5605        t: usize,
5606        cfg: &ModelConfig,
5607        il: u16,
5608        moe_out: &mut CudaSlice<f32>,
5609    ) -> Result<(), Box<dyn std::error::Error>> {
5610        let n_embd = cfg.n_embd as usize;
5611        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
5612            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
5613        {
5614            let n_ff_sh = gate_shexp.out_features();
5615            let sg_gate = e.matmul(gate_shexp, z, t)?;
5616            let sg_up = e.matmul(up_shexp, z, t)?;
5617            let mut sa = e.uninit(t * n_ff_sh)?;
5618            Self::ffn_act_lim(
5619                e,
5620                cfg,
5621                &sg_gate,
5622                &sg_up,
5623                1.0,
5624                1.0,
5625                cfg.clamp_shexp_at(il as u32),
5626                &mut sa,
5627                t * n_ff_sh,
5628            )?;
5629            let sh = e.matmul(down_shexp, &sa, t)?;
5630            let gate = match &m.gate_inp_shexp {
5631                Some(gate_inp_shexp) => {
5632                    if t < PRIME_MIN_T || crate::router_prefill_exact_on() {
5633                        e.sigmoid_dot_rows(z, gate_inp_shexp.float_data(), n_embd, t)?
5634                    } else {
5635                        let raw = e.linear(z, gate_inp_shexp.float_data(), t, n_embd, 1)?;
5636                        let mut gate = e.uninit(t)?;
5637                        e.sigmoid(&raw, &mut gate, t)?;
5638                        gate
5639                    }
5640                }
5641                None => e.htod(&vec![1.0f32; t])?,
5642            };
5643            e.add_scaled_rows(&sh, &gate, moe_out, n_embd, t)?;
5644        }
5645        Ok(())
5646    }
5647
5648    /// A2 expert-grouped MoE FFN (prefill path, MEMRA_MOE_GROUPED=1). Same semantics as moe_ffn:
5649    /// z [T, n_embd] -> moe_out [T, n_embd]. BIT-IDENTICAL to moe_ffn when using the slot scheme.
5650    pub(crate) fn moe_ffn_grouped(e: &Engine, m: &MoeWeights, z: &CudaSlice<f32>, t: usize,
5651                                  cfg: &ModelConfig, il: u16, max_block: usize)
5652                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5653        let moe = cfg.moe.as_ref().unwrap();
5654        let n_embd = cfg.n_embd as usize;
5655        let n_expert = moe.expert_count as usize;
5656        let n_used = moe.expert_used_count as usize;
5657        let n_ff_exp = moe.expert_ff_length as usize;
5658        // step35 per-layer SwiGLU clamp; None on every other arch / unclamped layer.
5659        let lim_exp = cfg.clamp_exp_at(il as u32);
5660
5661        // 1. ROUTER: exactly the same m-invariant selector and host sigmoid oracle as the
5662        // sequential path. The grouped dispatch never enters the softmax-only pairs/dev router.
5663        let logits = Self::moe_router_logits(e, m, z, t, cfg)?;
5664        let (sel_all, w_all) = if let Some(sig) = cfg.sigmoid_router() {
5665            Self::moe_route_cfg(e, &logits, t, n_expert, n_used,
5666                                m.exp_probs_b.as_deref(), Some(sig), m.active_experts.as_deref())?
5667        } else {
5668            Self::moe_route_cfg(e, &logits, t, n_expert, n_used,
5669                                None, None, m.active_experts.as_deref())?
5670        };
5671        Self::trace_moe_routes(il, t, &sel_all, &w_all)?;
5672        Self::trace_moe_input(e, il, t, n_embd, z)?;
5673
5674        // Fits-VRAM Step35 under the PP stage split: use the expert-major q8 arithmetic directly
5675        // from the owning device's uniform resident slab. This is not `moe_ffn_pairs`: routing
5676        // already happened above and the activation is clamp-aware. Mixed layouts, remote slabs,
5677        // macro-scaled experts, q8-disabled configs, and spill fall through to metadata-aware A2.
5678        let no_exp_macros = m.gate_exps.macros.is_none()
5679            && m.up_exps.macros.is_none()
5680            && m.down_exps.macros.is_none();
5681        let resident_q8 = m.dev_exps.as_ref().filter(|dev| {
5682            m.has_uniform_expert_layout()
5683                && no_exp_macros
5684                && moe_q8_enabled()
5685                && q8_expert_supported(m.gate_exps.qtype)
5686                && q8_expert_supported(m.up_exps.qtype)
5687                && q8_expert_supported(m.down_exps.qtype)
5688                && moe_slab_enabled()
5689                && dev.dev == e.ctx().ordinal()
5690        });
5691        if let Some(dev) = resident_q8 {
5692            let mut moe_out = Self::moe_ffn_grouped_resident_q8(
5693                e,
5694                m,
5695                z,
5696                t,
5697                cfg,
5698                il,
5699                &sel_all,
5700                &w_all,
5701                &dev.ptr_row,
5702                dev.gu_il,
5703            )?;
5704            Self::moe_ffn_grouped_add_shared(e, m, z, t, cfg, il, &mut moe_out)?;
5705            return Ok(moe_out);
5706        }
5707
5708        // 2. BUILD PER-EXPERT TOKEN LISTS (host-side grouping).
5709        // For each expert e, we need: which tokens use it, their positions in z, their top-k
5710        // slot index (for bit-identical accumulation), and their weights.
5711        struct ExpertGroup {
5712            tok_indices: Vec<i32>,   // indices into z rows (0..T-1)
5713            slot_indices: Vec<i32>,  // top-k slot (0..n_used-1) for that token-expert pair
5714            weights: Vec<f32>,       // renormalized weight for that token-expert pair
5715        }
5716        let mut groups: Vec<ExpertGroup> = (0..n_expert).map(|_| ExpertGroup {
5717            tok_indices: Vec::new(), slot_indices: Vec::new(), weights: Vec::new(),
5718        }).collect();
5719
5720        for tok in 0..t {
5721            for j in 0..n_used {
5722                let ex = sel_all[tok * n_used + j] as usize;
5723                let w = w_all[tok * n_used + j];
5724                groups[ex].tok_indices.push(tok as i32);
5725                groups[ex].slot_indices.push(j as i32);
5726                groups[ex].weights.push(w);
5727            }
5728        }
5729
5730        // 3. ALLOCATE SLOT BUFFER: [T, n_used, n_embd] f32, zero-initialized.
5731        // Each token's 8 expert contributions land in their respective slots.
5732        let mut slot_buf = e.zeros(t * n_used * n_embd)?;
5733        let mut wbuf = e.zeros(t * n_used)?;  // [T, n_used] weight buffer for FMA reduce
5734
5735        // Expert weight dimensions (used in both cache and staging paths).
5736        let g_len = m.gate_exps.max_expert_bytes();
5737        let u_len = m.up_exps.max_expert_bytes();
5738        let d_len = m.down_exps.max_expert_bytes();
5739        let moe_q8 = m.has_uniform_expert_layout()
5740            && moe_q8_enabled()
5741            && q8_expert_supported(m.gate_exps.qtype)
5742            && q8_expert_supported(m.up_exps.qtype)
5743            && q8_expert_supported(m.down_exps.qtype);
5744        // The per-expert slab view is legal only for the ordinary contiguous uniform layout.
5745        // Interleaved GU slabs require the pointer-table fast path above.
5746        let slab_local = m.dev_exps.as_ref().filter(|dev| {
5747            !dev.gu_il && moe_slab_enabled() && dev.dev == e.ctx().ordinal()
5748        });
5749        let use_cache =
5750            slab_local.is_none() && Engine::moe_cache_enabled() && !e.moe_cache_frozen();
5751        // The sequential no-cache/frozen staging oracle is f32. Use q8 only where sequential
5752        // also does: a local resident slab or a live SLRU dispatch.
5753        let grouped_q8 = moe_q8 && (slab_local.is_some() || use_cache);
5754
5755        // GPU scratch for staging (only allocated without a local slab or cache).
5756        let (mut scratch_g, mut scratch_u, mut scratch_d) = if slab_local.is_none() && !use_cache {
5757            (Some(e.alloc_u8(g_len)?), Some(e.alloc_u8(u_len)?), Some(e.alloc_u8(d_len)?))
5758        } else {
5759            (None, None, None)
5760        };
5761
5762        // 4. PER ACTIVE EXPERT: gather, compute, scatter.
5763        // Processing ORDER: DESCENDING m_e (biggest token batches first) — the concluded winner
5764        // (rig5090 2026-07-04, the ascending-id arm and its MEMRA_MOE_ORDER seam removed): desc is
5765        // a first-forward win at partial cache capacity — the hot (big-m_e) experts are admitted
5766        // to the SLRU before the small-m_e tail can pollute it, so residency converges in ONE
5767        // forward instead of several: auto-cache T=501 126.9 -> 169.9 tok/s (1.34x), cap512
5768        // 119.6 -> 160.8 (and kills the rep-to-rep bimodal); wash (<2%) at cap64 pure-spill and
5769        // at long prompts where every expert stages regardless. Order is FREE to change without
5770        // breaking the byte-identity gate: the slot scheme pins each token's accumulation order
5771        // regardless of expert processing order (the whole point of the slots).
5772        let mut order: Vec<usize> =
5773            (0..n_expert).filter(|&ex| !groups[ex].tok_indices.is_empty()).collect();
5774        order.sort_by(|&a, &b| groups[b].tok_indices.len()
5775            .cmp(&groups[a].tok_indices.len()).then(a.cmp(&b)));
5776        let mut m_dist: Vec<usize> = Vec::new();  // for stats
5777        let page_window = moe_page_prefetch_window();
5778        let worker_disk_prefetch = use_cache && crate::spill_pread::worker_enabled();
5779        if worker_disk_prefetch {
5780            if let Some(first) = grouped_worker_prefetch_position(order.len(), None) {
5781                Self::moe_prefetch_disk_expert(e, il, order[first], m, max_block, &[])?;
5782            }
5783        }
5784        for (order_pos, &ex) in order.iter().enumerate() {
5785            for next in page_prefetch_positions(order_pos, order.len(), page_window) {
5786                Self::moe_prefetch_host_expert(order[next], m);
5787            }
5788            if worker_disk_prefetch {
5789                if let Some(next) = grouped_worker_prefetch_position(order.len(), Some(order_pos)) {
5790                    use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5791                    let keep = [
5792                        BlockId::new(il, PROJ_GATE, ex as u16),
5793                        BlockId::new(il, PROJ_UP, ex as u16),
5794                        BlockId::new(il, PROJ_DOWN, ex as u16),
5795                    ];
5796                    Self::moe_prefetch_disk_expert(e, il, order[next], m, max_block, &keep)?;
5797                }
5798            }
5799            let grp = &groups[ex];
5800            let m_e = grp.tok_indices.len();
5801            m_dist.push(m_e);
5802            let gl = m.gate_exps.expert_layout(ex);
5803            let ul = m.up_exps.expert_layout(ex);
5804            let dl = m.down_exps.expert_layout(ex);
5805
5806            // Upload index/weight arrays to device. The down-proj per-expert macro-scale
5807            // (ModelOpt weight_scale_2) folds into the scatter weights — post-matmul linear,
5808            // same fold as the sequential loop's `w[j] * macro_scale(ex)`. 1.0 for GGUF experts.
5809            let tok_idx_d = e.htod_i32(&grp.tok_indices)?;
5810            let slot_idx_d = e.htod_i32(&grp.slot_indices)?;
5811            let dmac = m.down_exps.macro_scale(ex);
5812            let weight_d = if dmac == 1.0 { e.htod(&grp.weights)? } else {
5813                let scaled: Vec<f32> = grp.weights.iter().map(|&w| w * dmac).collect();
5814                e.htod(&scaled)?
5815            };
5816
5817            // GATHER: collect m_e activation rows from z into a contiguous buffer.
5818            let mut gathered = e.zeros(m_e * n_embd)?;
5819            e.gather_rows(z, &tok_idx_d, &mut gathered, n_embd, m_e)?;
5820            let gv = gathered.slice(0..m_e * n_embd);
5821
5822            // Compute gate/up/down from the local slab, metadata-aware cache, or staging. The q8
5823            // form keeps each gathered row in the sequential arithmetic class at `m=m_e`.
5824            let y = if let Some(dev) = slab_local {
5825                let gate_start = ex * m.gate_exps.expert_stride;
5826                let up_start = ex * m.up_exps.expert_stride;
5827                let down_start = ex * m.down_exps.expert_stride;
5828                if grouped_q8 {
5829                    let (zq, zd) = e.quantize_q8_1(&gathered, m_e, n_embd)?;
5830                    let gate = e.qmatvec_expert_q8(
5831                        &dev.gate,
5832                        gate_start..gate_start + gl.len,
5833                        &zq,
5834                        &zd,
5835                        m_e,
5836                        m.gate_exps.in_f,
5837                        m.gate_exps.out_f,
5838                        gl.qtype,
5839                        gl.row_bytes,
5840                    )?;
5841                    let up = e.qmatvec_expert_q8(
5842                        &dev.up,
5843                        up_start..up_start + ul.len,
5844                        &zq,
5845                        &zd,
5846                        m_e,
5847                        m.up_exps.in_f,
5848                        m.up_exps.out_f,
5849                        ul.qtype,
5850                        ul.row_bytes,
5851                    )?;
5852                    let mut act = e.uninit(m_e * n_ff_exp)?;
5853                    Self::ffn_act_lim(
5854                        e,
5855                        cfg,
5856                        &gate,
5857                        &up,
5858                        m.gate_exps.macro_scale(ex),
5859                        m.up_exps.macro_scale(ex),
5860                        lim_exp,
5861                        &mut act,
5862                        m_e * n_ff_exp,
5863                    )?;
5864                    let (aq2, ad2) = e.quantize_q8_1(&act, m_e, n_ff_exp)?;
5865                    e.qmatvec_expert_q8(
5866                        &dev.down,
5867                        down_start..down_start + dl.len,
5868                        &aq2,
5869                        &ad2,
5870                        m_e,
5871                        m.down_exps.in_f,
5872                        m.down_exps.out_f,
5873                        dl.qtype,
5874                        dl.row_bytes,
5875                    )?
5876                } else {
5877                    let gate = e.qmatvec_view(
5878                        &dev.gate,
5879                        gate_start..gate_start + gl.len,
5880                        &gv,
5881                        m_e,
5882                        m.gate_exps.in_f,
5883                        m.gate_exps.out_f,
5884                        gl.qtype,
5885                        gl.row_bytes,
5886                    )?;
5887                    let up = e.qmatvec_view(
5888                        &dev.up,
5889                        up_start..up_start + ul.len,
5890                        &gv,
5891                        m_e,
5892                        m.up_exps.in_f,
5893                        m.up_exps.out_f,
5894                        ul.qtype,
5895                        ul.row_bytes,
5896                    )?;
5897                    let mut act = e.uninit(m_e * n_ff_exp)?;
5898                    Self::ffn_act_lim(
5899                        e,
5900                        cfg,
5901                        &gate,
5902                        &up,
5903                        m.gate_exps.macro_scale(ex),
5904                        m.up_exps.macro_scale(ex),
5905                        lim_exp,
5906                        &mut act,
5907                        m_e * n_ff_exp,
5908                    )?;
5909                    let actv = act.slice(0..m_e * n_ff_exp);
5910                    e.qmatvec_view(
5911                        &dev.down,
5912                        down_start..down_start + dl.len,
5913                        &actv,
5914                        m_e,
5915                        m.down_exps.in_f,
5916                        m.down_exps.out_f,
5917                        dl.qtype,
5918                        dl.row_bytes,
5919                    )?
5920                }
5921            } else if use_cache {
5922                use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
5923                if grouped_q8 {
5924                    let (zq, zd) = e.quantize_q8_1(&gathered, m_e, n_embd)?;
5925                    let gate = e.with_moe_cache(max_block, |cache, eng| {
5926                        let id = BlockId::new(il, PROJ_GATE, ex as u16);
5927                        let slot =
5928                            cache.dispatch_source(id, m.gate_exps.expert_source(ex), eng)?;
5929                        eng.qmatvec_expert_q8(
5930                            cache.buf(slot),
5931                            0..gl.len,
5932                            &zq,
5933                            &zd,
5934                            m_e,
5935                            m.gate_exps.in_f,
5936                            m.gate_exps.out_f,
5937                            gl.qtype,
5938                            gl.row_bytes,
5939                        )
5940                    })?;
5941                    let up = e.with_moe_cache(max_block, |cache, eng| {
5942                        let id = BlockId::new(il, PROJ_UP, ex as u16);
5943                        let slot =
5944                            cache.dispatch_source(id, m.up_exps.expert_source(ex), eng)?;
5945                        eng.qmatvec_expert_q8(
5946                            cache.buf(slot),
5947                            0..ul.len,
5948                            &zq,
5949                            &zd,
5950                            m_e,
5951                            m.up_exps.in_f,
5952                            m.up_exps.out_f,
5953                            ul.qtype,
5954                            ul.row_bytes,
5955                        )
5956                    })?;
5957                    let mut act = e.uninit(m_e * n_ff_exp)?;
5958                    Self::ffn_act_lim(
5959                        e,
5960                        cfg,
5961                        &gate,
5962                        &up,
5963                        m.gate_exps.macro_scale(ex),
5964                        m.up_exps.macro_scale(ex),
5965                        lim_exp,
5966                        &mut act,
5967                        m_e * n_ff_exp,
5968                    )?;
5969                    let (aq2, ad2) = e.quantize_q8_1(&act, m_e, n_ff_exp)?;
5970                    e.with_moe_cache(max_block, |cache, eng| {
5971                        let id = BlockId::new(il, PROJ_DOWN, ex as u16);
5972                        let slot =
5973                            cache.dispatch_source(id, m.down_exps.expert_source(ex), eng)?;
5974                        eng.qmatvec_expert_q8(
5975                            cache.buf(slot),
5976                            0..dl.len,
5977                            &aq2,
5978                            &ad2,
5979                            m_e,
5980                            m.down_exps.in_f,
5981                            m.down_exps.out_f,
5982                            dl.qtype,
5983                            dl.row_bytes,
5984                        )
5985                    })?
5986                } else {
5987                    let gate = e.with_moe_cache(max_block, |cache, eng| {
5988                        let id = BlockId::new(il, PROJ_GATE, ex as u16);
5989                        let slot =
5990                            cache.dispatch_source(id, m.gate_exps.expert_source(ex), eng)?;
5991                        eng.qmatvec_view(
5992                            cache.buf(slot),
5993                            0..gl.len,
5994                            &gv,
5995                            m_e,
5996                            m.gate_exps.in_f,
5997                            m.gate_exps.out_f,
5998                            gl.qtype,
5999                            gl.row_bytes,
6000                        )
6001                    })?;
6002                    let up = e.with_moe_cache(max_block, |cache, eng| {
6003                        let id = BlockId::new(il, PROJ_UP, ex as u16);
6004                        let slot =
6005                            cache.dispatch_source(id, m.up_exps.expert_source(ex), eng)?;
6006                        eng.qmatvec_view(
6007                            cache.buf(slot),
6008                            0..ul.len,
6009                            &gv,
6010                            m_e,
6011                            m.up_exps.in_f,
6012                            m.up_exps.out_f,
6013                            ul.qtype,
6014                            ul.row_bytes,
6015                        )
6016                    })?;
6017                    let mut act = e.uninit(m_e * n_ff_exp)?;
6018                    Self::ffn_act_lim(
6019                        e,
6020                        cfg,
6021                        &gate,
6022                        &up,
6023                        m.gate_exps.macro_scale(ex),
6024                        m.up_exps.macro_scale(ex),
6025                        lim_exp,
6026                        &mut act,
6027                        m_e * n_ff_exp,
6028                    )?;
6029                    let actv = act.slice(0..m_e * n_ff_exp);
6030                    e.with_moe_cache(max_block, |cache, eng| {
6031                        let id = BlockId::new(il, PROJ_DOWN, ex as u16);
6032                        let slot =
6033                            cache.dispatch_source(id, m.down_exps.expert_source(ex), eng)?;
6034                        eng.qmatvec_view(
6035                            cache.buf(slot),
6036                            0..dl.len,
6037                            &actv,
6038                            m_e,
6039                            m.down_exps.in_f,
6040                            m.down_exps.out_f,
6041                            dl.qtype,
6042                            dl.row_bytes,
6043                        )
6044                    })?
6045                }
6046            } else {
6047                let sg = scratch_g.as_mut().unwrap();
6048                let su = scratch_u.as_mut().unwrap();
6049                let sd = scratch_d.as_mut().unwrap();
6050                e.stage_expert(m.gate_exps.expert_bytes(ex), sg, 0)?;
6051                e.stage_expert(m.up_exps.expert_bytes(ex), su, 0)?;
6052                e.stage_expert(m.down_exps.expert_bytes(ex), sd, 0)?;
6053                if grouped_q8 {
6054                    let (zq, zd) = e.quantize_q8_1(&gathered, m_e, n_embd)?;
6055                    let gate = e.qmatvec_expert_q8(
6056                        sg,
6057                        0..gl.len,
6058                        &zq,
6059                        &zd,
6060                        m_e,
6061                        m.gate_exps.in_f,
6062                        m.gate_exps.out_f,
6063                        gl.qtype,
6064                        gl.row_bytes,
6065                    )?;
6066                    let up = e.qmatvec_expert_q8(
6067                        su,
6068                        0..ul.len,
6069                        &zq,
6070                        &zd,
6071                        m_e,
6072                        m.up_exps.in_f,
6073                        m.up_exps.out_f,
6074                        ul.qtype,
6075                        ul.row_bytes,
6076                    )?;
6077                    let mut act = e.uninit(m_e * n_ff_exp)?;
6078                    Self::ffn_act_lim(
6079                        e,
6080                        cfg,
6081                        &gate,
6082                        &up,
6083                        m.gate_exps.macro_scale(ex),
6084                        m.up_exps.macro_scale(ex),
6085                        lim_exp,
6086                        &mut act,
6087                        m_e * n_ff_exp,
6088                    )?;
6089                    let (aq2, ad2) = e.quantize_q8_1(&act, m_e, n_ff_exp)?;
6090                    e.qmatvec_expert_q8(
6091                        sd,
6092                        0..dl.len,
6093                        &aq2,
6094                        &ad2,
6095                        m_e,
6096                        m.down_exps.in_f,
6097                        m.down_exps.out_f,
6098                        dl.qtype,
6099                        dl.row_bytes,
6100                    )?
6101                } else {
6102                    let gate = e.qmatvec_view(
6103                        sg,
6104                        0..gl.len,
6105                        &gv,
6106                        m_e,
6107                        m.gate_exps.in_f,
6108                        m.gate_exps.out_f,
6109                        gl.qtype,
6110                        gl.row_bytes,
6111                    )?;
6112                    let up = e.qmatvec_view(
6113                        su,
6114                        0..ul.len,
6115                        &gv,
6116                        m_e,
6117                        m.up_exps.in_f,
6118                        m.up_exps.out_f,
6119                        ul.qtype,
6120                        ul.row_bytes,
6121                    )?;
6122                    let mut act = e.uninit(m_e * n_ff_exp)?;
6123                    Self::ffn_act_lim(
6124                        e,
6125                        cfg,
6126                        &gate,
6127                        &up,
6128                        m.gate_exps.macro_scale(ex),
6129                        m.up_exps.macro_scale(ex),
6130                        lim_exp,
6131                        &mut act,
6132                        m_e * n_ff_exp,
6133                    )?;
6134                    let actv = act.slice(0..m_e * n_ff_exp);
6135                    e.qmatvec_view(
6136                        sd,
6137                        0..dl.len,
6138                        &actv,
6139                        m_e,
6140                        m.down_exps.in_f,
6141                        m.down_exps.out_f,
6142                        dl.qtype,
6143                        dl.row_bytes,
6144                    )?
6145                }
6146            };
6147
6148            // SCATTER into slot buffer: each row goes to slot_buf[tok, slot, :].
6149            e.scatter_slot(&y, &tok_idx_d, &slot_idx_d, &weight_d,
6150                           &mut slot_buf, &mut wbuf, n_embd, n_used, m_e)?;
6151        }
6152
6153        // 5. REDUCE SLOTS: sum the 8 slots per token into the final moe_out.
6154        let mut moe_out = e.zeros(t * n_embd)?;
6155        e.reduce_slots(&slot_buf, &wbuf, &mut moe_out, n_embd, n_used, t)?;
6156
6157        // STATS: print m-distribution when MEMRA_MOE_STATS is set.
6158        if std::env::var("MEMRA_MOE_STATS").is_ok() && !m_dist.is_empty() {
6159            m_dist.sort_unstable();
6160            let active = m_dist.len();
6161            let mean = m_dist.iter().sum::<usize>() as f64 / active as f64;
6162            let median = m_dist[active / 2];
6163            let max_m = *m_dist.last().unwrap();
6164            let min_m = m_dist[0];
6165            let above16 = m_dist.iter().filter(|&&x| x >= 16).count();
6166            println!("moe-grouped il={il} t={t} active={active}/{n_expert} \
6167                      m_e: min={min_m} median={median} mean={mean:.1} max={max_m} \
6168                      above_gemm_threshold(>=16)={above16}/{active}");
6169        }
6170
6171        Self::moe_ffn_grouped_add_shared(e, m, z, t, cfg, il, &mut moe_out)?;
6172        Ok(moe_out)
6173    }
6174
6175    /// Lane-3 M2: cross-stream MoE for lockstep decode. Routes all m stream rows in one
6176    /// batch, executes fully-HBM-resident experts through the grouped gather/GEMM/scatter
6177    /// machinery at m_e>1 (weight reads amortized across streams), and assigns any expert
6178    /// with a missing projection to that row's CPU companion call (whole-expert granularity,
6179    /// same rule as the sequential frozen path). Slot-pinned accumulation keeps each row's
6180    /// expert-sum order identical to the sequential path.
6181    pub(crate) fn moe_ffn_lockstep(
6182        &self,
6183        e: &Engine,
6184        m: &MoeWeights,
6185        zbatch: &CudaSlice<f32>,
6186        mrows: usize,
6187        il: u16,
6188        max_block: usize,
6189    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6190        use crate::moe_cache::{BlockId, PROJ_DOWN, PROJ_GATE, PROJ_UP};
6191        let cfg = &self.cfg;
6192        let moe = cfg.moe.as_ref().unwrap();
6193        let n_embd = cfg.n_embd as usize;
6194        let n_expert = moe.expert_count as usize;
6195        let n_used = moe.expert_used_count as usize;
6196        let n_ff_exp = moe.expert_ff_length as usize;
6197        // step35 per-layer SwiGLU clamp; None on every other arch / unclamped layer.
6198        let lim_exp = cfg.clamp_exp_at(il as u32);
6199        let lim_shexp = cfg.clamp_shexp_at(il as u32);
6200
6201        let logits = e.matmul(&m.gate_inp, zbatch, mrows)?;
6202        let (sel_all, w_all) = if let Some(sig) = cfg.sigmoid_router() {
6203            Self::moe_route_cfg(e, &logits, mrows, n_expert, n_used,
6204                                m.exp_probs_b.as_deref(), Some(sig), m.active_experts.as_deref())?
6205        } else {
6206            Self::moe_route_cfg(e, &logits, mrows, n_expert, n_used,
6207                                None, None, m.active_experts.as_deref())?
6208        };
6209        Self::trace_moe_routes(il, mrows, &sel_all, &w_all)?;
6210
6211        // Residency split at whole-expert granularity against the (frozen) cache.
6212        let resident_expert: Vec<bool> = e.with_moe_cache(max_block, |c, _| {
6213            Ok((0..n_expert)
6214                .map(|ex| {
6215                    [PROJ_GATE, PROJ_UP, PROJ_DOWN].into_iter().all(|p| {
6216                        c.resident(BlockId::new(il, p, ex as u16)).is_some()
6217                    })
6218                })
6219                .collect())
6220        })?;
6221
6222        struct Group {
6223            rows: Vec<i32>,
6224            slots: Vec<i32>,
6225            weights: Vec<f32>,
6226        }
6227        let mut groups: std::collections::HashMap<usize, Group> = Default::default();
6228        let mut cpu_rows: Vec<Vec<(usize, f32)>> = vec![Vec::new(); mrows];
6229        let mut cpu_by_expert: std::collections::HashMap<usize, Vec<(usize, f32)>> =
6230            Default::default();
6231        for row in 0..mrows {
6232            for j in 0..n_used {
6233                let ex = sel_all[row * n_used + j] as usize;
6234                let w = w_all[row * n_used + j];
6235                if resident_expert[ex] {
6236                    let group = groups.entry(ex).or_insert_with(|| Group {
6237                        rows: Vec::new(),
6238                        slots: Vec::new(),
6239                        weights: Vec::new(),
6240                    });
6241                    group.rows.push(row as i32);
6242                    group.slots.push(j as i32);
6243                    group.weights.push(w);
6244                } else {
6245                    crate::cpu_experts::record_incomplete_gpu_residency(0);
6246                    cpu_rows[row].push((ex, w));
6247                    cpu_by_expert.entry(ex).or_default().push((row, w));
6248                }
6249            }
6250        }
6251
6252        // CPU tickets first: reads/compute overlap the GPU grouped work below. Experts routed
6253        // by >=2 streams go through the multi-row ABI (weight decode amortized across rows);
6254        // each row's remaining experts stay one ordinary per-row call. Contribution FP-sum
6255        // order per row differs from the sequential single-call chunk — part of the
6256        // documented lockstep numeric class.
6257        let host_rows = e.dtoh(zbatch)?;
6258        let rows_ok = crate::cpu_experts::rows_supported();
6259        enum CpuPart {
6260            Single { row: usize },
6261            Rows { rows: Vec<usize> },
6262        }
6263        let mut tickets: Vec<(CpuPart, crate::cpu_experts::CpuExpertTicket)> = Vec::new();
6264        let mut rows_served: std::collections::HashSet<(usize, usize)> = Default::default();
6265        if rows_ok {
6266            let mut shared: Vec<(usize, Vec<(usize, f32)>)> = cpu_by_expert
6267                .into_iter()
6268                .filter(|(_, rows)| rows.len() >= 2)
6269                .collect();
6270            shared.sort_by_key(|(ex, _)| *ex);
6271            for (ex, mut row_weights) in shared {
6272                row_weights.sort_by_key(|(row, _)| *row);
6273                let inputs: Vec<(&[f32], f32)> = row_weights
6274                    .iter()
6275                    .map(|&(row, w)| (&host_rows[row * n_embd..(row + 1) * n_embd], w))
6276                    .collect();
6277                let job = crate::cpu_experts::prepare_rows_job(m, ex, &inputs)
6278                    .map_err(std::io::Error::other)?;
6279                for &(row, _) in &row_weights {
6280                    rows_served.insert((row, ex));
6281                }
6282                tickets.push((
6283                    CpuPart::Rows {
6284                        rows: row_weights.iter().map(|&(row, _)| row).collect(),
6285                    },
6286                    crate::cpu_experts::submit_rows(job).map_err(std::io::Error::other)?,
6287                ));
6288            }
6289        }
6290        for (row, selected) in cpu_rows.iter().enumerate() {
6291            let leftover: Vec<(usize, f32)> = selected
6292                .iter()
6293                .copied()
6294                .filter(|&(ex, _)| !rows_served.contains(&(row, ex)))
6295                .collect();
6296            if leftover.is_empty() {
6297                continue;
6298            }
6299            let host_row = &host_rows[row * n_embd..(row + 1) * n_embd];
6300            let job = crate::cpu_experts::prepare_job(m, il, &leftover, host_row)
6301                .map_err(std::io::Error::other)?;
6302            tickets.push((
6303                CpuPart::Single { row },
6304                crate::cpu_experts::submit(job).map_err(std::io::Error::other)?,
6305            ));
6306        }
6307
6308        let mut slot_buf = e.zeros(mrows * n_used * n_embd)?;
6309        let mut wbuf = e.zeros(mrows * n_used)?;
6310        let mut order: Vec<usize> = groups.keys().copied().collect();
6311        order.sort_by(|&a, &b| {
6312            groups[&b].rows.len().cmp(&groups[&a].rows.len()).then(a.cmp(&b))
6313        });
6314        for &ex in &order {
6315            let group = &groups[&ex];
6316            let m_e = group.rows.len();
6317            let gl = m.gate_exps.expert_layout(ex);
6318            let ul = m.up_exps.expert_layout(ex);
6319            let dl = m.down_exps.expert_layout(ex);
6320            let row_idx_d = e.htod_i32(&group.rows)?;
6321            let slot_idx_d = e.htod_i32(&group.slots)?;
6322            let dmac = m.down_exps.macro_scale(ex);
6323            let weight_d = if dmac == 1.0 {
6324                e.htod(&group.weights)?
6325            } else {
6326                let scaled: Vec<f32> = group.weights.iter().map(|&w| w * dmac).collect();
6327                e.htod(&scaled)?
6328            };
6329            let mut gathered = e.zeros(m_e * n_embd)?;
6330            e.gather_rows(zbatch, &row_idx_d, &mut gathered, n_embd, m_e)?;
6331            let gv = gathered.slice(0..m_e * n_embd);
6332            let gate = e.with_moe_cache(max_block, |c, eng| {
6333                let slot = c
6334                    .resident(BlockId::new(il, PROJ_GATE, ex as u16))
6335                    .ok_or("lockstep resident expert vanished (cache not frozen?)")?;
6336                eng.qmatvec_view(c.buf(crate::moe_cache::DispatchSlot::Resident(slot)), 0..gl.len, &gv, m_e,
6337                    m.gate_exps.in_f, m.gate_exps.out_f, gl.qtype, gl.row_bytes)
6338            })?;
6339            let up = e.with_moe_cache(max_block, |c, eng| {
6340                let slot = c
6341                    .resident(BlockId::new(il, PROJ_UP, ex as u16))
6342                    .ok_or("lockstep resident expert vanished (cache not frozen?)")?;
6343                eng.qmatvec_view(c.buf(crate::moe_cache::DispatchSlot::Resident(slot)), 0..ul.len, &gv, m_e,
6344                    m.up_exps.in_f, m.up_exps.out_f, ul.qtype, ul.row_bytes)
6345            })?;
6346            let mut act = e.zeros(m_e * n_ff_exp)?;
6347            Self::ffn_act_lim(e, cfg, &gate, &up, m.gate_exps.macro_scale(ex),
6348                m.up_exps.macro_scale(ex), lim_exp, &mut act, m_e * n_ff_exp)?;
6349            let actv = act.slice(0..m_e * n_ff_exp);
6350            let y = e.with_moe_cache(max_block, |c, eng| {
6351                let slot = c
6352                    .resident(BlockId::new(il, PROJ_DOWN, ex as u16))
6353                    .ok_or("lockstep resident expert vanished (cache not frozen?)")?;
6354                eng.qmatvec_view(c.buf(crate::moe_cache::DispatchSlot::Resident(slot)), 0..dl.len, &actv, m_e,
6355                    m.down_exps.in_f, m.down_exps.out_f, dl.qtype, dl.row_bytes)
6356            })?;
6357            e.scatter_slot(&y, &row_idx_d, &slot_idx_d, &weight_d,
6358                           &mut slot_buf, &mut wbuf, n_embd, n_used, m_e)?;
6359        }
6360        let mut moe_out = e.zeros(mrows * n_embd)?;
6361        e.reduce_slots(&slot_buf, &wbuf, &mut moe_out, n_embd, n_used, mrows)?;
6362
6363        // CPU contributions join BEFORE the shared expert (the sequential path's placement).
6364        let mut row_sums: Vec<Option<Vec<f32>>> = vec![None; mrows];
6365        for (part, ticket) in tickets {
6366            let cpu_output = ticket.wait().map_err(std::io::Error::other)?;
6367            let mut add_row = |row: usize, chunk: &[f32]| {
6368                let sum = row_sums[row].get_or_insert_with(|| vec![0.0f32; n_embd]);
6369                for (accumulator, value) in sum.iter_mut().zip(chunk) {
6370                    *accumulator += value;
6371                }
6372            };
6373            match part {
6374                CpuPart::Single { row } => add_row(row, &cpu_output),
6375                CpuPart::Rows { rows } => {
6376                    for (slot, row) in rows.into_iter().enumerate() {
6377                        add_row(row, &cpu_output[slot * n_embd..(slot + 1) * n_embd]);
6378                    }
6379                }
6380            }
6381        }
6382        for (row, sum) in row_sums.into_iter().enumerate() {
6383            let Some(sum) = sum else { continue };
6384            let cpu_output = e.htod(&sum)?;
6385            let mut dst = moe_out.slice_mut(row * n_embd..(row + 1) * n_embd);
6386            e.axpy_into(&cpu_output, 1.0, &mut dst, n_embd)?;
6387        }
6388
6389        if let (Some(gate_shexp), Some(up_shexp), Some(down_shexp)) =
6390            (&m.gate_shexp, &m.up_shexp, &m.down_shexp)
6391        {
6392            let n_ff_sh = gate_shexp.out_features();
6393            let sg_gate = e.matmul(gate_shexp, zbatch, mrows)?;
6394            let sg_up = e.matmul(up_shexp, zbatch, mrows)?;
6395            let mut sa = e.zeros(mrows * n_ff_sh)?;
6396            Self::ffn_act_lim(e, cfg, &sg_gate, &sg_up, 1.0, 1.0, lim_shexp,
6397                              &mut sa, mrows * n_ff_sh)?;
6398            let sh = e.matmul(down_shexp, &sa, mrows)?;
6399            // lockstep rows ARE decode tokens: fused sigmoid-dot per row so batched serving
6400            // decode matches the single-sequence decode chain bit-for-bit.
6401            let g = match &m.gate_inp_shexp {
6402                Some(gate_inp_shexp) => {
6403                    e.sigmoid_dot_rows(zbatch, gate_inp_shexp.float_data(), n_embd, mrows)?
6404                }
6405                None => e.htod(&vec![1.0f32; mrows])?,
6406            };
6407            e.add_scaled_rows(&sh, &g, &mut moe_out, n_embd, mrows)?;
6408        }
6409
6410        Ok(moe_out)
6411    }
6412}
6413
6414// ============================ gemma4 (R8 verified wiring) ==================================
6415// Node-for-node vs llama.cpp src/models/gemma4.cpp:180-405 (HANDOVER "R8 VERIFIED WIRING").
6416// v0 bring-up: full attention everywhere (exact for prompts < sliding_window 1024 — R6 masking
6417// later), sdpa_naive (hd 512 has no FA stamp), sequential host-staged MoE (the perf arms grow
6418// gemma variants after the correctness gate).
6419impl HybridModel {
6420    /// Per-layer attention geometry (R5): (head_dim, n_kv, n_head, rope_base, scale, is_swa).
6421    pub(crate) fn gemma4_geom(&self, il: usize) -> (usize, usize, usize, f32, f32, bool) {
6422        let g = self.cfg.gemma4.as_ref().unwrap();
6423        let swa = g.swa_pattern[il];
6424        let hd = if swa { g.key_length_swa } else { g.key_length_global } as usize;
6425        // attention scale = 1.0 (llama gemma4.cpp:11 "Gemma4 uses self.scaling = 1.0" — q/k are
6426        // per-head rms-normed; NOT the 1/sqrt(hd) default. Bring-up bug: 1/sqrt(hd) left token-0
6427        // rows exact (softmax over one element) while every later position drifted).
6428        (hd, g.head_count_kv[il] as usize, self.cfg.n_head as usize,
6429         if swa { g.rope_base_swa } else { g.rope_base_global },
6430         1.0, swa)
6431    }
6432
6433    /// Suppress-token mask over t logits rows (tokenizer.ggml.suppress_tokens; no-op when the
6434    /// model ships none). NOT monotonic like softcap — must run before every argmax/sample, so
6435    /// every gemma4 logits tail (forward/prime/decode/dc/verify/e4b) calls this on device ld.
6436    fn gemma4_suppress(&self, e: &Engine, ld: &mut CudaSlice<f32>, t: usize)
6437                       -> Result<(), Box<dyn std::error::Error>> {
6438        if let Some((ids, n)) = self.gemma4_aux.as_ref().and_then(|a| a.suppress_d.as_ref()) {
6439            e.mask_ids_rows(ld, ids, *n, self.output.out_features(), t)?;
6440        }
6441        Ok(())
6442    }
6443
6444    /// gemma4 attention (R5 geometry, R7 weightless V-norm on the RAW K projection, R9 dual rope).
6445    /// `cache`: Some => PRIME mode — append the T post-rope K / normed V rows into the quantized
6446    /// KV cache (same per-row quantize math as the decode append) and advance len. Fresh-prompt
6447    /// only (v0): attends within `tokens` via the f32 sdpa.
6448    fn gemma4_attn_prime(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
6449                         h: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize,
6450                         cache: Option<&mut Cache>)
6451                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6452        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
6453        let eps = self.cfg.rms_eps;
6454        let aux = self.gemma4_aux.as_ref().unwrap();
6455
6456        // quantize-once window: q/k/v share `h` — the MMQ D4 activation quantizes once
6457        // (h stays borrowed across the triple, so the cache key can't go stale).
6458        e.mmq_act_begin();
6459        let q0 = e.matmul(&fa.wq, h, t)?;   // [t, nh*hd]
6460        let k0 = e.matmul(&fa.wk, h, t)?;   // [t, nkv*hd]
6461        // globals ship no v_proj (wv := wk at load) — V input is the SAME projection output;
6462        // reuse k0 instead of re-running the identical matmul (K=V dedup, 5 layers).
6463        let v0 = if swa { e.matmul(&fa.wv, h, t)? } else { e.clone_dtod(&k0)? };
6464
6465        let mut q = e.uninit(t * nh * hd)?;
6466        let mut k = e.uninit(t * nkv * hd)?;
6467        // R7: V = weightless rms_norm of the raw projection; NEVER roped.
6468        let mut v = e.uninit(t * nkv * hd)?;
6469        // 31B glue lane: producers emit the bf16 FA operands (norm emits vb; rope emits qb/kb
6470        // post-rope) — kills 3 f32->bf16 converts + re-reads per layer. Bit-identical operands
6471        // (same __float2bfloat16); MEMRA_FA_EMIT=0 reverts to the convert-in-FA path.
6472        static EMIT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6473        let emit = t >= 16 && crate::Engine::qkvnorm_w_on_prefill(nh * t + 2 * nkv * t, hd)
6474            && *EMIT.get_or_init(|| std::env::var("MEMRA_FA_EMIT").map(|s| s != "0").unwrap_or(true));
6475        let mut qb = e.alloc_uninit::<u8>(if emit { t * nh * hd * 2 } else { 1 })?;
6476        let mut kb = e.alloc_uninit::<u8>(if emit { t * nkv * hd * 2 } else { 1 })?;
6477        let mut vb = e.alloc_uninit::<u8>(if emit { t * nkv * hd * 2 } else { 1 })?;
6478        // f16-P/V door: emit V as f16 straight from the norm when this layer's FA consumer
6479        // reads f16 — kills the per-layer bf16->f16 re-encode (1.4GB/pass on 31B SWA).
6480        let v_f16 = emit && crate::fa_f16pv_on() && match hd {
6481            512 => true,
6482            256 => swa && crate::faw_hp_on() && nh % 2 == 0 && (nh / nkv) % 2 == 0,
6483            _ => false,
6484        };
6485        if emit {
6486            e.rms_norm_qkv_w4b(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
6487                               &aux.ones, &mut q, &mut k, &mut v, &mut vb,
6488                               hd, nh * t, nkv * t, eps, v_f16)?;
6489        } else {
6490            e.rms_norm_qkv(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
6491                           &aux.ones, &mut q, &mut k, &mut v, hd, nh * t, nkv * t, eps)?;
6492        }
6493
6494        let ff = if swa { None } else {
6495            Some(aux.rope_freqs.as_ref().expect("gemma4 global rope needs rope_freqs.weight"))
6496        };
6497        if emit {
6498            e.rope_neox2_bf16e(&mut q, &mut k, &mut qb, &mut kb, pos_d, hd, hd, nh, nkv, t,
6499                               base, 1.0, ff)?;
6500        } else {
6501            e.rope_neox2(&mut q, &mut k, pos_d, hd, hd, nh, nkv, t, base, 1.0, ff)?;
6502        }
6503
6504        if let Some(cache) = cache {
6505            let kvl = cache.kv[il].as_mut().unwrap();
6506            assert_eq!(kvl.len, 0, "gemma4 prime is fresh-prompt only (v0)");
6507            e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len, t,
6508                                       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()))?;
6509            kvl.len += t;
6510        }
6511        let mut attn = e.zeros(t * nh * hd)?;
6512        // R6: SWA layers mask keys older than sliding_window once the prompt exceeds it
6513        // (windowed naive twin; fa windowed stamps later). Under the window, full attention
6514        // is exact — SWA rides fa_prefill (hd-256 stamp), the hd-512 globals stay naive.
6515        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
6516        if swa && t > win {
6517            if hd == 256 && std::env::var("MEMRA_NOFA").is_err() {
6518                if emit { e.fa_prefill_w_pre(&qb, &kb, &vb, &mut attn, hd, nh, nkv, t, t,
6519                                             scale, true, win, v_f16)?; }
6520                else { e.fa_prefill_w(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true,
6521                                      win)?; }
6522            } else {
6523                e.sdpa_naive_w(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true, win)?;
6524            }
6525        } else if hd == 256 && std::env::var("MEMRA_NOFA").is_err() {
6526            e.fa_prefill(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
6527        } else if hd == 512 && std::env::var("MEMRA_NOFA").is_err() {
6528            if emit { e.fa_prefill_hd512_pre(&qb, &kb, &vb, &mut attn, hd, nh, nkv, t, t,
6529                                             scale, true, v_f16)?; }
6530            else { e.fa_prefill_hd512(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?; }
6531        } else {
6532            e.sdpa_naive(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
6533        }
6534        Ok(e.matmul(&fa.wo, &attn, t)?)
6535    }
6536
6537    /// Back-compat wrapper (pure prefill, no cache).
6538    fn gemma4_attn(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
6539                   h: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize)
6540                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6541        self.gemma4_attn_prime(e, fa, il, h, pos_d, t, None)
6542    }
6543
6544    /// gemma4 MoE with the expert input PRE-QUANTIZED (the q8z tail fusion). Caller guarantees
6545    /// the fast-arm conditions (resident dev slabs + dp4a qtypes) — decode t=1 and verify rows
6546    /// arms only, per-token kernel chains identical to the f32-input path (same quantize bytes:
6547    /// the q8z epilogue is quantize_q8_1 verbatim).
6548    fn gemma4_moe_q8(&self, e: &Engine, m: &crate::hybrid::MoeWeights,
6549                     bits: &crate::hybrid::Gemma4MoeBits,
6550                     mq: &(CudaSlice<i8>, CudaSlice<f32>),
6551                     router_in: &CudaSlice<f32>, t: usize)
6552                     -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6553        let cfg = &self.cfg;
6554        let moe = cfg.moe.as_ref().unwrap();
6555        let n_embd = cfg.n_embd as usize;
6556        let n_expert = moe.expert_count as usize;
6557        let n_used = moe.expert_used_count as usize;
6558        let n_ff_exp = moe.expert_ff_length as usize;
6559        // router stays the two-launch pair: THREE fuse variants measured worse (serial-dot
6560        // -50%, 1024-thread warp-parallel -12% on topk sync overhead — jsonl 2026-07-11);
6561        // the pair's 12us is kernel time, not launch gaps.
6562        let logits = if crate::router_kernel_on() {
6563            e.router_gemv(m.gate_inp.float_data(), router_in, n_embd, n_expert, t)?
6564        } else {
6565            e.matmul(&m.gate_inp, router_in, t)?
6566        };
6567        let dev = m.dev_exps.as_ref().unwrap();
6568        let (sel_d, w_d) = e.moe_router_topk_scaled(&logits, t, n_expert, n_used,
6569                                                    &bits.per_expert_scale_d)?;
6570        let (zq, zd) = mq;
6571        if t == 1 {
6572            let selv = sel_d.slice(0..n_used);
6573            let wv = w_d.slice(0..n_used);
6574            let act = e.moe_gate_up_gelu8_dev_q8(&dev.ptr_row, &selv, zq, zd,
6575                                                 n_embd, n_ff_exp, n_used, n_expert,
6576                                                 m.gate_exps.qtype, m.up_exps.qtype,
6577                                                 m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
6578            let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
6579            let mut moe_out = e.uninit(n_embd)?;
6580            e.moe_down8_fma_dev_q8(&dev.ptr_row, &selv, &wv, &aq2, &ad2,
6581                                   &mut moe_out.slice_mut(0..n_embd), n_ff_exp, n_embd,
6582                                   n_used, n_expert, m.down_exps.qtype, m.down_exps.row_bytes)?;
6583            return Ok(moe_out);
6584        }
6585        let csr = t <= 10 && std::env::var("MEMRA_GEMMA_CSR").as_deref() != Ok("0");
6586        let act = if csr {
6587            e.moe_gate_up_gelu8_dev_q8_csr(&dev.ptr_row, &sel_d, zq, zd, t * n_used,
6588                                           n_embd, n_ff_exp, n_used, n_expert,
6589                                           m.gate_exps.qtype, m.up_exps.qtype,
6590                                           m.gate_exps.row_bytes, m.up_exps.row_bytes)?
6591        } else {
6592            e.moe_gate_up_gelu8_dev_q8_rows(&dev.ptr_row, &sel_d, zq, zd, t,
6593                                            n_embd, n_ff_exp, n_used, n_expert,
6594                                            m.gate_exps.qtype, m.up_exps.qtype,
6595                                            m.gate_exps.row_bytes, m.up_exps.row_bytes)?
6596        };
6597        let (aq2, ad2) = e.quantize_q8_1(&act, t * n_used, n_ff_exp)?;
6598        let mut moe_out = e.uninit(t * n_embd)?;
6599        // down stays rows_g: the CSR dedup twin measured NEGATIVE at nsb=22 too (189.4 vs
6600        // 207.0 depth spec, bitwise-exact — jsonl 2026-07-10; qwen nsb=16 same verdict).
6601        e.moe_down8_fma_dev_q8_rows_g(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out, t,
6602                                      n_ff_exp, n_embd, n_used, n_expert,
6603                                      m.down_exps.qtype, m.down_exps.row_bytes)?;
6604        Ok(moe_out)
6605    }
6606
6607    /// gemma4 MoE (R2 router prologue input supplied by caller, R3 per-expert output scale).
6608    /// Sequential host-staged v0 — softmax gating + renorm (moe_route, the qwen recipe), GELU
6609    /// experts, scale folded into the accumulate weight (post-matmul linear scale, exact fold).
6610    fn gemma4_moe(&self, e: &Engine, m: &crate::hybrid::MoeWeights,
6611                  bits: &crate::hybrid::Gemma4MoeBits, moe_in: &CudaSlice<f32>,
6612                  router_in: &CudaSlice<f32>, t: usize)
6613                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6614        let cfg = &self.cfg;
6615        let moe = cfg.moe.as_ref().unwrap();
6616        let n_embd = cfg.n_embd as usize;
6617        let n_expert = moe.expert_count as usize;
6618        let n_used = moe.expert_used_count as usize;
6619        let n_ff_exp = moe.expert_ff_length as usize;
6620
6621        // Router: the in-house GEMV for ALL small t (decode AND verify ride the same per-column
6622        // kernel — the cuBLASLt n-dependence flipped top-k at verify t on the 27B, d994271);
6623        // batched matmul only at real prefill.
6624        let logits = if t < PRIME_MIN_T && crate::router_kernel_on() {
6625            e.router_gemv(m.gate_inp.float_data(), router_in, n_embd, n_expert, t)?
6626        } else {
6627            e.matmul(&m.gate_inp, router_in, t)?
6628        };
6629
6630        // FAST SMALL-T ARM (decode t=1 AND spec verify t=2..15): device softmax-topk router,
6631        // then PER TOKEN the same fused gate_up GELU + down8 FMA launch pair over the resident
6632        // dev slabs — verify rides the EXACT decode kernel chain per token (dispatch-parity
6633        // law; the qwen "verify must be kernel-dispatch-identical to decode" lesson).
6634        if t < PRIME_MIN_T && m.dev_exps.as_ref().is_some_and(|d| !d.gu_il)
6635            && expert_dp4a_supported(m.gate_exps.qtype) && expert_dp4a_supported(m.up_exps.qtype)
6636            && expert_dp4a_supported(m.down_exps.qtype)
6637            && std::env::var("MEMRA_GEMMA_MOE_FAST").as_deref() != Ok("0") {
6638            let dev = m.dev_exps.as_ref().unwrap();
6639            let (sel_d, w_d) = e.moe_router_topk_scaled(&logits, t, n_expert, n_used,
6640                                                        &bits.per_expert_scale_d)?;
6641            if t == 1 {
6642                let (zq, zd) = e.quantize_q8_1(moe_in, 1, n_embd)?;
6643                let selv = sel_d.slice(0..n_used);
6644                let wv = w_d.slice(0..n_used);
6645                let act = e.moe_gate_up_gelu8_dev_q8(&dev.ptr_row, &selv, &zq, &zd,
6646                                                     n_embd, n_ff_exp, n_used, n_expert,
6647                                                     m.gate_exps.qtype, m.up_exps.qtype,
6648                                                     m.gate_exps.row_bytes, m.up_exps.row_bytes)?;
6649                let (aq2, ad2) = e.quantize_q8_1(&act, n_used, n_ff_exp)?;
6650                let mut moe_out = e.uninit(n_embd)?;
6651                e.moe_down8_fma_dev_q8(&dev.ptr_row, &selv, &wv, &aq2, &ad2,
6652                                       &mut moe_out.slice_mut(0..n_embd), n_ff_exp, n_embd,
6653                                       n_used, n_expert, m.down_exps.qtype, m.down_exps.row_bytes)?;
6654                return Ok(moe_out);
6655            }
6656            // VERIFY ROWS TWINS (t=2..15): ONE launch pair for all tokens; per (token,row,slot)
6657            // bodies are the t=1 kernels VERBATIM (bit-identical to the per-token loop).
6658            // gate_up rides the CSR owner-scan dedup when t <= 10 (each duplicated expert's
6659            // weight stream decoded once; the qwen CSR class). MEMRA_GEMMA_CSR=0 -> rows.
6660            let (zq, zd) = e.quantize_q8_1(moe_in, t, n_embd)?;
6661            let csr = t <= 10 && std::env::var("MEMRA_GEMMA_CSR").as_deref() != Ok("0");
6662            let act = if csr {
6663                e.moe_gate_up_gelu8_dev_q8_csr(&dev.ptr_row, &sel_d, &zq, &zd, t * n_used,
6664                                               n_embd, n_ff_exp, n_used, n_expert,
6665                                               m.gate_exps.qtype, m.up_exps.qtype,
6666                                               m.gate_exps.row_bytes, m.up_exps.row_bytes)?
6667            } else {
6668                e.moe_gate_up_gelu8_dev_q8_rows(&dev.ptr_row, &sel_d, &zq, &zd, t,
6669                                                n_embd, n_ff_exp, n_used, n_expert,
6670                                                m.gate_exps.qtype, m.up_exps.qtype,
6671                                                m.gate_exps.row_bytes, m.up_exps.row_bytes)?
6672            };
6673            let (aq2, ad2) = e.quantize_q8_1(&act, t * n_used, n_ff_exp)?;
6674            let mut moe_out = e.uninit(t * n_embd)?;
6675            e.moe_down8_fma_dev_q8_rows_g(&dev.ptr_row, &sel_d, &w_d, &aq2, &ad2, &mut moe_out, t,
6676                                          n_ff_exp, n_embd, n_used, n_expert,
6677                                          m.down_exps.qtype, m.down_exps.row_bytes)?;
6678            return Ok(moe_out);
6679        }
6680
6681        let (sel_all, mut w_all) = Self::moe_route(e, &logits, t, n_expert, n_used)?;
6682        for (i, &sx) in sel_all.iter().enumerate() {
6683            w_all[i] *= bits.per_expert_scale[sx as usize];
6684        }
6685
6686        // PREFILL PAIRS ARM (t >= 16): expert-major CSR over the resident slabs — ONE launch per
6687        // projection covers ALL (token,expert) pairs (the qwen pairs recipe, _em dot = expert_dot_g
6688        // which has the Q4_0 body; GELU pairs epilogue; R3 scale folded into pair_w).
6689        if t >= PRIME_MIN_T && m.dev_exps.as_ref().is_some_and(|d| !d.gu_il)
6690            && expert_dp4a_supported(m.gate_exps.qtype) && expert_dp4a_supported(m.up_exps.qtype)
6691            && expert_dp4a_supported(m.down_exps.qtype)
6692            && std::env::var("MEMRA_GEMMA_MOE_PAIRS").as_deref() != Ok("0") {
6693            let dev = m.dev_exps.as_ref().unwrap();
6694            let n_pairs = t * n_used;
6695            let pair_ex: Vec<i32> = sel_all.iter().map(|&x| x as i32).collect();
6696            let pair_tok: Vec<i32> = (0..n_pairs).map(|p| (p / n_used) as i32).collect();
6697            let tok_off: Vec<i32> = (0..=t).map(|tok| (tok * n_used) as i32).collect();
6698            let tok_ids: Vec<i32> = (0..n_pairs as i32).collect();
6699            let pt = e.htod_i32(&pair_tok)?;
6700            let pw = e.htod(&w_all)?;
6701            let toff = e.htod_i32(&tok_off)?;
6702            let tids = e.htod_i32(&tok_ids)?;
6703            let mut by_ex: Vec<Vec<i32>> = vec![Vec::new(); n_expert];
6704            for p in 0..n_pairs { by_ex[pair_ex[p] as usize].push(p as i32); }
6705            let mut ex_ids: Vec<i32> = Vec::new();
6706            let mut ex_off: Vec<i32> = vec![0];
6707            let mut ex_pairs: Vec<i32> = Vec::with_capacity(n_pairs);
6708            for (ex, list) in by_ex.iter().enumerate() {
6709                if list.is_empty() { continue; }
6710                ex_ids.push(ex as i32);
6711                ex_pairs.extend_from_slice(list);
6712                ex_off.push(ex_pairs.len() as i32);
6713            }
6714            let n_active = ex_ids.len();
6715            let exi = e.htod_i32(&ex_ids)?;
6716            let exo = e.htod_i32(&ex_off)?;
6717            let exp_d = e.htod_i32(&ex_pairs)?;
6718            // GROUPED f16 LANE (MEMRA_MOE_F16G=1, round 46 arc 2): dequant active experts to
6719            // f16 once per projection + one grouped f16 GEMM over the CSR groups; CSR order
6720            // end-to-end (gelu is elementwise), one row permute before the scatter. The
6721            // ragged down k (704) needs no padding here — cublas takes any k.
6722            // f16-mirror numeric class, argmax/spec gated. PER-MODEL default OFF (round 50):
6723            // the gelu class regressed g26 board-2048 prefill -8.3% under the round-49
6724            // Hopper default — see moe_f16g_gemma_on.
6725            if crate::moe_f16g_gemma_on()
6726                && f16g_proj_ok(m.gate_exps.qtype, n_embd)
6727                && f16g_proj_ok(m.up_exps.qtype, n_embd)
6728                && f16g_proj_ok(m.down_exps.qtype, n_ff_exp) {
6729                let csr_tok: Vec<i32> = ex_pairs.iter().map(|&p| p / n_used as i32).collect();
6730                let csr_tok_d = e.htod_i32(&csr_tok)?;
6731                let (z_f16, z_s) = e.moe_f16g_act(moe_in, Some(&csr_tok_d), n_embd, n_pairs)?;
6732                let g_csr = e.moe_f16_grouped(&dev.ptr_row, 0, n_expert, &exi, &ex_off, &exo,
6733                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
6734                                              m.gate_exps.qtype, m.gate_exps.row_bytes)?;
6735                let u_csr = e.moe_f16_grouped(&dev.ptr_row, 1, n_expert, &exi, &ex_off, &exo,
6736                                              &z_f16, &z_s, n_embd, n_ff_exp, n_active, n_pairs,
6737                                              m.up_exps.qtype, m.up_exps.row_bytes)?;
6738                let act_csr = e.moe_pairs_gelu_mul(&g_csr, &u_csr, n_pairs * n_ff_exp)?;
6739                let (a_f16, a_s) = e.moe_f16g_act(&act_csr, None, n_ff_exp, n_pairs)?;
6740                let d_csr = e.moe_f16_grouped(&dev.ptr_row, 2, n_expert, &exi, &ex_off, &exo,
6741                                              &a_f16, &a_s, n_ff_exp, n_embd, n_active, n_pairs,
6742                                              m.down_exps.qtype, m.down_exps.row_bytes)?;
6743                let y_down = e.rows_permute(&d_csr, &exp_d, n_pairs, n_embd)?;
6744                let mut moe_out = e.uninit(t * n_embd)?;
6745                e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
6746                if std::env::var("MEMRA_F16G_DEBUG").is_ok() {
6747                    let scan = |v: &[f32]| v.iter().filter(|x| !x.is_finite()).count();
6748                    let (yd, mo) = (e.dtoh(&y_down)?, e.dtoh(&moe_out)?);
6749                    eprintln!("[f16g-debug] post-permute bad={} post-scatter bad={}",
6750                              scan(&yd), scan(&mo));
6751                }
6752                return Ok(moe_out);
6753            }
6754            // gate/up: int8-MMA expert GEMM (in_f = n_embd 2816 = 11x256 tiles ok); down keeps
6755            // the decode-once dp4a (in_f 704 fails the 256-superblock tiling).
6756            let mma = n_embd % 256 == 0
6757                && std::env::var("MEMRA_GEMMA_MOE_MMA").as_deref() != Ok("0");
6758            let (gate, up) = if mma {
6759                let z_scr = e.mmq_iq_quantize_act(moe_in, n_embd, t)?;
6760                (e.mmq_iq_experts(&dev.ptr_row, 0, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
6761                                  n_embd, n_ff_exp, n_active, n_pairs, t,
6762                                  m.gate_exps.qtype, m.gate_exps.row_bytes)?,
6763                 e.mmq_iq_experts(&dev.ptr_row, 1, n_expert, &exi, &exo, &exp_d, &pt, &z_scr,
6764                                  n_embd, n_ff_exp, n_active, n_pairs, t,
6765                                  m.up_exps.qtype, m.up_exps.row_bytes)?)
6766            } else {
6767                let (zq, zd) = e.quantize_q8_1(moe_in, t, n_embd)?;
6768                (e.moe_pairs_matvec_q8_dec(&dev.ptr_row, 0, &exi, &exo, &exp_d, &pt, &zq, &zd,
6769                                           n_embd, n_ff_exp, n_expert, n_active, n_pairs,
6770                                           m.gate_exps.qtype, m.gate_exps.row_bytes)?,
6771                 e.moe_pairs_matvec_q8_dec(&dev.ptr_row, 1, &exi, &exo, &exp_d, &pt, &zq, &zd,
6772                                           n_embd, n_ff_exp, n_expert, n_active, n_pairs,
6773                                           m.up_exps.qtype, m.up_exps.row_bytes)?)
6774            };
6775            let pair_self: Vec<i32> = (0..n_pairs as i32).collect();
6776            let pself = e.htod_i32(&pair_self)?;
6777            // DOWN through the int8-MMA expert GEMM (2026-07-31, g26 prefill lever): the
6778            // ragged k (n_ff_exp=704 on the 26B) rides a PADDED k-walk — in_f rounds up
6779            // to the 256-val superblock (768) while the act quantizer's zero padding
6780            // makes every padded-k product exactly zero (weight overread bytes multiply
6781            // zero int8 act values; the dev slab carries 144B tail slack for the OOB).
6782            // The old dp4a matvec was 11.3ms/call at m=T (the 0.07x prefill wall).
6783            // MEMRA_GEMMA_MOE_MMA=0 reverts down together with gate/up.
6784            // FUSED ACT-EPILOGUE (default on): gelu_tanh(gate)*up + D4 quantize in one
6785            // launch — no f32 act buffer (the fused kernel zero-pads the ragged tail
6786            // exactly like the two-pass quantizer). MEMRA_MOE_FUSE_ACTQ=0 rollback.
6787            // Scratch bytes are BYTE-IDENTICAL (kernel-check gated).
6788            let y_down = if mma {
6789                let in_pad = n_ff_exp.div_ceil(256) * 256;
6790                let a_scr = if crate::moe_fuse_actq_on() {
6791                    e.mmq_iq_fused_act_quant(&gate, &up, n_ff_exp, n_pairs, 1)?
6792                } else {
6793                    let act = e.moe_pairs_gelu_mul(&gate, &up, n_pairs * n_ff_exp)?;
6794                    e.mmq_iq_quantize_act(&act, n_ff_exp, n_pairs)?
6795                };
6796                e.mmq_iq_experts(&dev.ptr_row, 2, n_expert, &exi, &exo, &exp_d, &pself, &a_scr,
6797                                 in_pad, n_embd, n_active, n_pairs, n_pairs,
6798                                 m.down_exps.qtype, m.down_exps.row_bytes)?
6799            } else {
6800                let act = e.moe_pairs_gelu_mul(&gate, &up, n_pairs * n_ff_exp)?;
6801                let (aq2, ad2) = e.quantize_q8_1(&act, n_pairs, n_ff_exp)?;
6802                e.moe_pairs_matvec_q8_dec(&dev.ptr_row, 2, &exi, &exo, &exp_d, &pself, &aq2, &ad2,
6803                                          n_ff_exp, n_embd, n_expert, n_active, n_pairs,
6804                                          m.down_exps.qtype, m.down_exps.row_bytes)?
6805            };
6806            let mut moe_out = e.uninit(t * n_embd)?;
6807            e.moe_pairs_scatter(&y_down, &pw, &toff, &tids, &mut moe_out, t, n_embd)?;
6808            return Ok(moe_out);
6809        }
6810
6811        let g_len = m.gate_exps.expert_stride;
6812        let u_len = m.up_exps.expert_stride;
6813        let d_len = m.down_exps.expert_stride;
6814        // Resident dev slabs (fits-VRAM regime): read each expert straight from the device slab
6815        // at ex*stride — zero H2D, SAME qmatvec_view kernel/bytes as the staged path. Staging is
6816        // the spill fallback.
6817        let dev = m.dev_exps.as_ref().filter(|d| !d.gu_il);
6818        let (mut sg, mut su, mut sd) = if dev.is_some() { (None, None, None) } else {
6819            (Some(e.alloc_u8_uninit(g_len)?), Some(e.alloc_u8_uninit(u_len)?), Some(e.alloc_u8_uninit(d_len)?))
6820        };
6821        let mut moe_out = e.zeros(t * n_embd)?;
6822        for tok in 0..t {
6823            let sel = &sel_all[tok * n_used..(tok + 1) * n_used];
6824            let w = &w_all[tok * n_used..(tok + 1) * n_used];
6825            let zt = moe_in.slice(tok * n_embd..(tok + 1) * n_embd);
6826            for (j, &ex) in sel.iter().enumerate() {
6827                let ex = ex as usize;
6828                let gate = match dev {
6829                    Some(d) => e.qmatvec_view(&d.gate, ex * g_len..(ex + 1) * g_len, &zt, 1,
6830                        m.gate_exps.in_f, m.gate_exps.out_f, m.gate_exps.qtype, m.gate_exps.row_bytes)?,
6831                    None => {
6832                        let sg = sg.as_mut().unwrap();
6833                        e.stage_expert(m.gate_exps.expert_bytes(ex), sg, 0)?;
6834                        e.qmatvec_view(sg, 0..g_len, &zt, 1,
6835                            m.gate_exps.in_f, m.gate_exps.out_f, m.gate_exps.qtype, m.gate_exps.row_bytes)?
6836                    }
6837                };
6838                let up = match dev {
6839                    Some(d) => e.qmatvec_view(&d.up, ex * u_len..(ex + 1) * u_len, &zt, 1,
6840                        m.up_exps.in_f, m.up_exps.out_f, m.up_exps.qtype, m.up_exps.row_bytes)?,
6841                    None => {
6842                        let su = su.as_mut().unwrap();
6843                        e.stage_expert(m.up_exps.expert_bytes(ex), su, 0)?;
6844                        e.qmatvec_view(su, 0..u_len, &zt, 1,
6845                            m.up_exps.in_f, m.up_exps.out_f, m.up_exps.qtype, m.up_exps.row_bytes)?
6846                    }
6847                };
6848                let mut act = e.uninit(n_ff_exp)?;
6849                e.gelu_tanh_mul(&gate, &up, &mut act, n_ff_exp)?;
6850                let actv = act.slice(0..n_ff_exp);
6851                let y = match dev {
6852                    Some(d) => e.qmatvec_view(&d.down, ex * d_len..(ex + 1) * d_len, &actv, 1,
6853                        m.down_exps.in_f, m.down_exps.out_f, m.down_exps.qtype, m.down_exps.row_bytes)?,
6854                    None => {
6855                        let sd = sd.as_mut().unwrap();
6856                        e.stage_expert(m.down_exps.expert_bytes(ex), sd, 0)?;
6857                        e.qmatvec_view(sd, 0..d_len, &actv, 1,
6858                            m.down_exps.in_f, m.down_exps.out_f, m.down_exps.qtype, m.down_exps.row_bytes)?
6859                    }
6860                };
6861                let mut dst = moe_out.slice_mut(tok * n_embd..(tok + 1) * n_embd);
6862                e.axpy_into(&y, w[j], &mut dst, n_embd)?;
6863            }
6864        }
6865        Ok(moe_out)
6866    }
6867
6868    /// One gemma4 trunk layer (R8): x -> x_next.
6869    fn gemma4_layer(&self, e: &Engine, il: usize, layer: &crate::hybrid::HybridLayer,
6870                    x: &CudaSlice<f32>, pos_d: &CudaSlice<i32>, t: usize)
6871                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6872        let n_embd = self.cfg.n_embd as usize;
6873        let eps = self.cfg.rms_eps;
6874
6875        let mut h = e.zeros(t * n_embd)?;
6876        e.rms_norm(x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
6877        let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
6878        let o = self.gemma4_attn(e, fa, il, &h, pos_d, t)?;
6879        // gemma order: post_attention_norm applies to the ATTENTION OUTPUT, then the residual.
6880        let mut cur = e.zeros(t * n_embd)?;
6881        e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
6882        self.gemma4_layer_tail_add(e, layer, &cur, x, t)
6883    }
6884
6885    /// Everything after the attention output in a gemma4 layer: the residual add (cur + x ->
6886    /// attn_out) FUSED with the three attn_out norms, then shared FFN + router + MoE + combine +
6887    /// layer scale — shared verbatim by the prefill, decode and verify paths.
6888    fn gemma4_layer_tail_add(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
6889                             cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize)
6890                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6891        Ok(self.gemma4_layer_tail_add_n(e, layer, cur, x, t, None)?.0)
6892    }
6893
6894    /// tail_add with the NEXT layer's attn_norm fused into the closing add+scale (one launch
6895    /// produces both x_next and h_next — the cross-layer fusion). `next_norm` None = last layer.
6896    fn gemma4_layer_tail_add_n(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
6897                               cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize,
6898                               next_norm: Option<&CudaSlice<f32>>)
6899                               -> Result<(CudaSlice<f32>, Option<CudaSlice<f32>>), Box<dyn std::error::Error>> {
6900        let n_embd = self.cfg.n_embd as usize;
6901        let bits = layer.gemma4.as_ref().unwrap();
6902        let (sn, attn_out) = self.gemma4_layer_tail_core(e, layer, cur, x, t)?;
6903        let mut xn = e.uninit(t * n_embd)?;
6904        match next_norm {
6905            Some(w) => {
6906                let mut hn = e.uninit(t * n_embd)?;
6907                e.add_scale_rms_norm(&sn, &attn_out, bits.layer_scale, w, &mut xn, &mut hn,
6908                                     n_embd, t, self.cfg.rms_eps)?;
6909                Ok((xn, Some(hn)))
6910            }
6911            None => {
6912                e.add_scale(&sn, &attn_out, bits.layer_scale, &mut xn, t * n_embd)?;
6913                Ok((xn, None))
6914            }
6915        }
6916    }
6917
6918    /// Tail core: attn_out = cur+x (fused with the 3 norms), both FFN branches, the combine
6919    /// norm — returns (sn, attn_out) for the closing add+scale variants.
6920    fn gemma4_layer_tail_core(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
6921                              cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize)
6922                              -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6923        self.gemma4_layer_tail_core_pn(e, layer, cur, x, t, None, false)
6924    }
6925
6926    /// tail_core with an optional PRE-NORM fold (glue-fusion lane): `pre_norm = Some(wa)`
6927    /// means `cur` is the RAW attention output and the dense entry runs
6928    /// rms(cur, wa) + residual-add + ffn_norm as ONE launch (E4B's post-attn norm fold).
6929    /// `defer_post_norm`: dense-arm exit returns RAW f0 (ffn_down output) instead of
6930    /// sn = rms(f0, post_ffw) — the caller fuses the post-norm into its residual emit
6931    /// (rms_pre_add_q8_1, E4B glue wave 5). MoE arm ignores it.
6932    fn gemma4_layer_tail_core_pn(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
6933                                 cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize,
6934                                 pre_norm: Option<&CudaSlice<f32>>, defer_post_norm: bool)
6935                                 -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6936        let n_embd = self.cfg.n_embd as usize;
6937        let eps = self.cfg.rms_eps;
6938        let bits = layer.gemma4.as_ref().unwrap();
6939
6940        // DENSE gemma4 variants (31B/E4B — no MoE, no parallel branch): attn_out = cur + x
6941        // fused with the single ffn_norm; GELU_PAR ffn; post_ffw_norm.
6942        let Some(mbits) = bits.moe_bits.as_ref() else {
6943            let crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &layer.ffn
6944            else { panic!("gemma4 dense layer without Dense ffn") };
6945            let mut attn_out = e.uninit(t * n_embd)?;
6946            let mut zsh = e.uninit(t * n_embd)?;
6947            // wave-2: with the pre-norm fold active the entry ALSO emits zsh q8_1 — the
6948            // t=1 fused2 gate/up consume the pair with no standalone quantize launch.
6949            let mut zpair: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
6950            match pre_norm {
6951                Some(wa) if t == 1 => {
6952                    zpair = Some(e.rms_pre_add_rms_norm_q8z(cur, wa, x,
6953                                                            bits.ffn_norm.float_data(),
6954                                                            &mut attn_out, &mut zsh,
6955                                                            n_embd, t, eps)?);
6956                }
6957                Some(wa) => e.rms_pre_add_rms_norm(cur, wa, x, bits.ffn_norm.float_data(),
6958                                                   &mut attn_out, &mut zsh, n_embd, t, eps)?,
6959                None => e.add_rms_norm(cur, x, bits.ffn_norm.float_data(), &mut attn_out,
6960                                       &mut zsh, n_embd, t, eps)?,
6961            }
6962            let n_ff = ffn_gate.out_features();
6963            // FFN persistent slab (counter-barrier form) FALSIFIED here 2026-07-14
6964            // (falsification #7, jsonl row): PDL glue already hides the launch boundaries
6965            // it fused; barrier + worst-segment occupancy net −0.3% (31B depth) / −2.3%
6966            // (E4B spec). Down's act dependency is all-to-all, so sentinel sync cannot
6967            // rescue segment C — the megakernel front is closed for the dense tail.
6968            let (gate, up) = if t == 1 {
6969                let (zq, zd) = match zpair {
6970                    Some(p) => p,
6971                    None => e.quantize_q8_1(&zsh, 1, n_embd)?,
6972                };
6973                match e.matmul_q4_fused2(ffn_gate, ffn_up, &zq, &zd)? {
6974                    Some(p) => p,
6975                    None => (e.matmul_pre(ffn_gate, &zq, &zd, &zsh, 1)?,
6976                             e.matmul_pre(ffn_up, &zq, &zd, &zsh, 1)?),
6977                }
6978            } else {
6979                // BATCHED FUSED2 (DEFAULT ON 2026-07-13, MEMRA_F2B=0 seam): one segmented
6980                // launch for the verify's gate+up — the up segment's blocks fill SMs as
6981                // the gate segment drains (the launch-tail mechanism behind the b-tier
6982                // plateau; first positive after six falsified in-kernel variants).
6983                static F2B: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6984                let f2b = *F2B.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0"));
6985                let fused = if f2b {
6986                    let (zq, zd) = e.quantize_q8_1(&zsh, t, n_embd)?;
6987                    e.matmul_q4_fused2_batched(ffn_gate, ffn_up, &zq, &zd, t)?
6988                } else { None };
6989                match fused {
6990                    Some(p) => p,
6991                    None => {
6992                        // quantize-once window: gate/up share `zsh` (borrowed across the pair).
6993                        e.mmq_act_begin();
6994                        (e.matmul(ffn_gate, &zsh, t)?, e.matmul(ffn_up, &zsh, t)?)
6995                    }
6996                }
6997            };
6998            let mut act = e.uninit(t * n_ff)?;
6999            // act quantize folds into the GELU epilogue (bit-identical q8_1 rounding);
7000            // ffn_down rides matmul_pre — one quantize launch fewer per layer.
7001            let f0 = if e.uses_q8_1_fast(ffn_down) {
7002                let upv = e.view(&up, t * n_ff);
7003                let up_all = upv.slice(0..t * n_ff);
7004                let (aq, ad) = e.gelu_tanh_mul_q8_1(&gate, &up_all, &mut act, n_ff, t)?;
7005                e.matmul_pre(ffn_down, &aq, &ad, &act, t)?
7006            } else {
7007                e.gelu_tanh_mul(&gate, &up, &mut act, t * n_ff)?;
7008                e.matmul(ffn_down, &act, t)?
7009            };
7010            if defer_post_norm { return Ok((f0, attn_out)); }
7011            let mut sn = e.uninit(t * n_embd)?;
7012            e.rms_norm(&f0, bits.post_ffw_norm.float_data(), &mut sn, n_embd, t, eps)?;
7013            return Ok((sn, attn_out));
7014        };
7015
7016        assert!(pre_norm.is_none(), "pre-norm fold is dense-entry only");
7017        // MoE variant (26B): attn_out = cur + x fused with the three attn_out norms
7018        // (ffn_norm + router-scale + pre_ffw_norm_2): ONE launch, chains verbatim. At small t
7019        // (decode + verify) the zsh and moe_in outputs are EMITTED q8_1 (both consumers are
7020        // quantized matmuls — two quantize launches + two f32 round-trips fold away).
7021        let mut attn_out = e.uninit(t * n_embd)?;
7022        let mut router_in = e.uninit(t * n_embd)?;
7023        let fast_moe = match &layer.ffn {
7024            crate::hybrid::Ffn::Moe(m) => m.dev_exps.as_ref().is_some_and(|d| !d.gu_il)
7025                && expert_dp4a_supported(m.gate_exps.qtype)
7026                && expert_dp4a_supported(m.up_exps.qtype)
7027                && expert_dp4a_supported(m.down_exps.qtype)
7028                && std::env::var("MEMRA_GEMMA_MOE_FAST").as_deref() != Ok("0"),
7029            _ => false,
7030        };
7031        let q8z = t < PRIME_MIN_T && fast_moe;
7032        let (zsh_f32, zsh_q8, moe_q8) = if q8z {
7033            let (z0, m2) = e.add_rms_norm3_q8z(cur, x, bits.ffn_norm.float_data(),
7034                                               &mbits.router_scale_pre,
7035                                               mbits.pre_ffw_norm_2.float_data(),
7036                                               &mut attn_out, &mut router_in, n_embd, t, eps)?;
7037            (None, Some(z0), Some(m2))
7038        } else {
7039            let mut zsh = e.uninit(t * n_embd)?;
7040            let mut moe_in = e.uninit(t * n_embd)?;
7041            e.add_rms_norm3(cur, x, bits.ffn_norm.float_data(), &mbits.router_scale_pre,
7042                            mbits.pre_ffw_norm_2.float_data(), &mut attn_out, &mut zsh,
7043                            &mut router_in, &mut moe_in, n_embd, t, eps)?;
7044            (Some((zsh, moe_in)), None, None)
7045        };
7046        let attn_out2 = attn_out;
7047        #[allow(unused_variables)]
7048        let attn_out = &attn_out2;
7049        let n_ff = mbits.shared_gate.out_features();
7050        let (gate, up) = if let Some((zq, zd)) = zsh_q8.as_ref() {
7051            if t == 1 {
7052                match e.matmul_q4_fused2(&mbits.shared_gate, &mbits.shared_up, zq, zd)? {
7053                    Some(p) => p,
7054                    None => {
7055                        let h0 = e.zeros(0)?;
7056                        (e.matmul_pre(&mbits.shared_gate, zq, zd, &h0, 1)?,
7057                         e.matmul_pre(&mbits.shared_up, zq, zd, &h0, 1)?)
7058                    }
7059                }
7060            } else {
7061                // verify t 2..15: the batched mmvq twins consume the pre-quantized pair.
7062                let h0 = e.zeros(0)?;
7063                (e.matmul_pre(&mbits.shared_gate, zq, zd, &h0, t)?,
7064                 e.matmul_pre(&mbits.shared_up, zq, zd, &h0, t)?)
7065            }
7066        } else {
7067            let (zsh, _) = zsh_f32.as_ref().unwrap();
7068            (e.matmul(&mbits.shared_gate, zsh, t)?, e.matmul(&mbits.shared_up, zsh, t)?)
7069        };
7070        let mut act = e.uninit(t * n_ff)?;
7071        e.gelu_tanh_mul(&gate, &up, &mut act, t * n_ff)?;
7072        let mlp0 = e.matmul(&mbits.shared_down, &act, t)?;
7073        let crate::hybrid::Ffn::Moe(m) = &layer.ffn else { panic!("gemma4 layer not MoE") };
7074        let moe0 = match (&moe_q8, &zsh_f32) {
7075            (Some(mq), _) => self.gemma4_moe_q8(e, m, mbits, mq, &router_in, t)?,
7076            (None, Some((_, moe_in))) => self.gemma4_moe(e, m, mbits, moe_in, &router_in, t)?,
7077            _ => unreachable!(),
7078        };
7079        // post_ffw_norm_1(mlp0) + post_ffw_norm_2(moe0): one fused launch, per-row verbatim.
7080        let mut mlp = e.uninit(t * n_embd)?;
7081        let mut moe = e.uninit(t * n_embd)?;
7082        e.rms_norm2x(&mlp0, &moe0, mbits.post_ffw_norm_1.float_data(),
7083                     mbits.post_ffw_norm_2.float_data(), &mut mlp, &mut moe, n_embd, t, eps)?;
7084
7085        // combine: rms_norm(mlp + moe, post_ffw_norm) + attn_out, then the layer output scalar.
7086        // add+norm fused (add_rms_norm == add then rms_norm, kernel-check-pinned identity).
7087        let mut sum = e.uninit(t * n_embd)?;
7088        let mut sn = e.uninit(t * n_embd)?;
7089        e.add_rms_norm(&mlp, &moe, bits.post_ffw_norm.float_data(), &mut sum, &mut sn,
7090                       n_embd, t, eps)?;
7091        Ok((sn, attn_out2))
7092    }
7093
7094    /// tail_add with the next attn_norm emitted PRE-QUANTIZED q8_1 (decode/verify loops).
7095    fn gemma4_layer_tail_add_nq(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7096                                cur: &CudaSlice<f32>, x: &CudaSlice<f32>, t: usize,
7097                                next_norm: Option<&CudaSlice<f32>>)
7098                                -> Result<(CudaSlice<f32>, Option<(CudaSlice<i8>, CudaSlice<f32>)>), Box<dyn std::error::Error>> {
7099        let n_embd = self.cfg.n_embd as usize;
7100        let bits = layer.gemma4.as_ref().unwrap();
7101        let (sn, attn_out) = self.gemma4_layer_tail_core(e, layer, cur, x, t)?;
7102        let mut xn = e.uninit(t * n_embd)?;
7103        match next_norm {
7104            Some(w) => {
7105                let pair = e.add_scale_rms_norm_q8_1(&sn, &attn_out, bits.layer_scale, w, &mut xn,
7106                                                     n_embd, t, self.cfg.rms_eps)?;
7107                Ok((xn, Some(pair)))
7108            }
7109            None => {
7110                e.add_scale(&sn, &attn_out, bits.layer_scale, &mut xn, t * n_embd)?;
7111                Ok((xn, None))
7112            }
7113        }
7114    }
7115
7116    /// gemma4 prefill: `last_only` = forward_last semantics (lm_head on the final row only).
7117    /// R4: final logits softcapped 30*tanh(l/30) on host (monotonic — argmax unaffected).
7118    fn gemma4_forward(&self, e: &Engine, tokens: &[u32], last_only: bool)
7119                      -> Result<Vec<f32>, Box<dyn std::error::Error>> {
7120        // E4B routes to its own forward regardless of the caller's entry point (forward /
7121        // forward_last / prime paths all funnel here for gemma4).
7122        if self.is_gemma4_e4b() { return self.gemma4_e4b_forward(e, tokens, last_only); }
7123        let n_embd = self.cfg.n_embd as usize;
7124        let t = tokens.len();
7125        let pos: Vec<i32> = (0..t as i32).collect();
7126        let pos_d = e.htod_i32(&pos)?;
7127
7128        let mut x = self.embed(e, tokens)?;
7129        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
7130        // MEMRA_GEMMA_PROBE=1: per-layer trunk stats (host rms + max of the LAST token row) —
7131        // the bring-up bisect vs llama-eval-callback node stats.
7132        let probe = std::env::var("MEMRA_GEMMA_PROBE").is_ok();
7133        let stat = |e: &Engine, x: &CudaSlice<f32>, tag: &str| -> Result<(), Box<dyn std::error::Error>> {
7134            let h = e.dtoh(x)?;
7135            let bad = h.iter().filter(|v| !v.is_finite()).count();
7136            let mx = h.iter().filter(|v| v.is_finite()).fold(0.0f32, |m, v| m.max(v.abs()));
7137            eprintln!("[gemma-probe] {tag}: tok0_first3={:?} bad={bad} max={mx:.3e}", &h[..3]);
7138            Ok(())
7139        };
7140        if probe { stat(e, &x, "embed")?; }
7141        for (il, layer) in self.layers.iter().enumerate() {
7142            x = self.gemma4_layer(e, il, layer, &x, &pos_d, t)?;
7143            if probe { stat(e, &x, &format!("L{il}"))?; }
7144        }
7145        let mut hn = e.zeros(t * n_embd)?;
7146        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, self.cfg.rms_eps)?;
7147        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
7148        let n_vocab = self.output.out_features();
7149        let logits = if last_only {
7150            let hv = e.view(&hn, t * n_embd);
7151            let last_row = hv.slice((t - 1) * n_embd..t * n_embd);
7152            let mut hlast = e.zeros(n_embd)?;
7153            e.copy_view_into(&mut hlast, 0, &last_row, n_embd)?;
7154            let mut ld = e.matmul(&self.output, &hlast, 1)?;
7155            e.softcap(&mut ld, cap, n_vocab)?;
7156            self.gemma4_suppress(e, &mut ld, 1)?;
7157            e.dtoh(&ld)?
7158        } else {
7159            let mut ld = e.matmul(&self.output, &hn, t)?;
7160            e.softcap(&mut ld, cap, t * n_vocab)?;
7161            self.gemma4_suppress(e, &mut ld, t)?;
7162            e.dtoh(&ld)?
7163        };
7164        Ok(logits)
7165    }
7166
7167    /// gemma4 BATCHED PROMPT PRIME v0 (fresh cache only): the prefill graph over the whole
7168    /// prompt with each layer's post-rope K / weightless-normed V appended into the quantized
7169    /// KV cache (decode-append row math). Returns (last-row softcapped logits, h_seed = last
7170    /// pre-output_norm hidden, hiddens = full pre-output_norm stack [T, n_embd]).
7171    pub(crate) fn gemma4_prime(&self, e: &Engine, tokens: &[u32], cache: &mut Cache)
7172                               -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7173        // Err, not assert (2026-08-07, lane/gemma4-serve-gaps): a served gemma4 prompt longer
7174        // than the worker's prefill tick used to chunk here, and chunk 2 (pos > 0) killed the
7175        // whole worker process on this line. The worker now primes gemma4 monolithically and
7176        // routes continuation suffixes tokenwise; this is the per-request backstop.
7177        if cache.pos != 0 {
7178            return Err("gemma4 prime v0 is fresh-prompt only (no continuation/chunked prime) \
7179                        — prime the full prompt in one call or decode tokenwise".into());
7180        }
7181        let n_embd = self.cfg.n_embd as usize;
7182        let eps = self.cfg.rms_eps;
7183        let t = tokens.len();
7184        let pos: Vec<i32> = (0..t as i32).collect();
7185        let pos_d = e.htod_i32(&pos)?;
7186        let mut x = self.embed(e, tokens)?;
7187        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
7188        for (il, layer) in self.layers.iter().enumerate() {
7189            let mut h = e.zeros(t * n_embd)?;
7190            e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7191            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer not full-attn") };
7192            let o = self.gemma4_attn_prime(e, fa, il, &h, &pos_d, t, Some(cache))?;
7193            let mut cur = e.zeros(t * n_embd)?;
7194            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
7195            x = self.gemma4_layer_tail_add(e, layer, &cur, &x, t)?;
7196            self.dflash_tap(e, cache, il, &x, t)?;
7197        }
7198        cache.pos += t;
7199        let hiddens = e.clone_dtod(&x)?;
7200        let xv = e.view(&x, t * n_embd);
7201        let last_row = xv.slice((t - 1) * n_embd..t * n_embd);
7202        let mut h_seed = e.zeros(n_embd)?;
7203        e.copy_view_into(&mut h_seed, 0, &last_row, n_embd)?;
7204        let mut hn = e.uninit(n_embd)?;
7205        e.rms_norm(&h_seed, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
7206        let mut ld = e.matmul(&self.output, &hn, 1)?;
7207        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
7208        e.softcap(&mut ld, cap, self.output.out_features())?;
7209        self.gemma4_suppress(e, &mut ld, 1)?;
7210        let logits = e.dtoh(&ld)?;
7211        Ok((logits, h_seed, hiddens))
7212    }
7213
7214    /// gemma4 T=1 decode attention: per-layer geometry, quantized-KV append + fa_decode
7215    /// (vec kernels at hd 256, generic scalar at the globals' hd 512), weightless V-norm,
7216    /// dual rope, scale 1.0. Takes the attn-normed input PRE-QUANTIZED (the cross-layer
7217    /// fused norm emits q8 directly — the f32 h never materializes).
7218    fn gemma4_decode_attn(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
7219                          hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
7220                          pos_d: &CudaSlice<i32>, cache: &mut Cache)
7221                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7222        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
7223        let eps = self.cfg.rms_eps;
7224        let aux = self.gemma4_aux.as_ref().unwrap();
7225        let (hq, hdq) = (hq, hdq);
7226        let h0 = e.zeros(0)?;
7227        let h = &h0;
7228        let (q0, k0, v0) = if swa {
7229            match e.matmul_q4_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
7230                Some(t3) => t3,
7231                None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
7232                         e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
7233                         e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?),
7234            }
7235        } else {
7236            let (q0, k0) = match e.matmul_q4_fused2(&fa.wq, &fa.wk, &hq, &hdq)? {
7237                Some(p) => p,
7238                None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
7239                         e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?),
7240            };
7241            let v0 = e.clone_dtod(&k0)?;
7242            (q0, k0, v0)
7243        };
7244        let mut q = e.uninit(nh * hd)?;
7245        let mut k = e.uninit(nkv * hd)?;
7246        let mut v = e.uninit(nkv * hd)?;
7247        // E4B wave-3 fold, m=1 completion (2026-07-23): the rows arms took this fold at
7248        // 550fcfa5; the decode-step trio kept 2 launches/layer it doesn't need.
7249        let ff = if swa { None } else {
7250            Some(aux.rope_freqs.as_ref().expect("gemma4 global rope needs rope_freqs.weight"))
7251        };
7252        e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
7253                            &aux.ones, &mut q, &mut k, &mut v, hd, nh, nkv,
7254                            pos_d, nh, nkv, base, 1.0, ff, eps)?;
7255        let kvl = cache.kv[il].as_mut().unwrap();
7256        e.append_kv_quantized(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len,
7257                              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()))?;
7258        kvl.len += 1;
7259        // R6 decode: SWA layers attend only the last `sliding_window` keys — a token-aligned
7260        // VIEW OFFSET into the quantized cache (keys carry absolute rope; the mask is purely
7261        // positional). Globals attend the full history.
7262        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
7263        let mut attn = e.uninit(nh * hd)?;
7264        // global layers: SAME hd512 rows twin as verify with t=1 (parity law).
7265        if !swa && hd == 512 && kvl.len >= crate::fa512_min_tkv()
7266            && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
7267            let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
7268            let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
7269            // device-len: eager syncs the counter (async arg-store), dc keeps it live.
7270            let base = kvl.len as i32;
7271            e.i32_set_k(&mut kvl.len_d, base)?;
7272            e.fa_decode_rows(&q, &kp, &vp, &mut attn, hd, nh, nkv, kvl.len - 1, 1, scale,
7273                             kvl.k_tok_bytes, kvl.v_tok_bytes, Some((&kvl.len_d, -1)), false,
7274                             false, None)?;
7275            return Ok(e.matmul(&fa.wo, &attn, 1)?);
7276        }
7277        // windowed regime: SAME rows_w kernel as verify with t=1 (parity law — see verify_attn).
7278        if swa && kvl.len > win && hd == 256
7279            && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
7280            let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
7281            let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
7282            let base = kvl.len as i32;
7283            e.i32_set_k(&mut kvl.len_d, base)?;
7284            e.fa_decode_rows_w(&q, &kp, &vp, &mut attn, hd, nh, nkv, &kvl.len_d, -1, 1, scale,
7285                               win, kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
7286            return Ok(e.matmul(&fa.wo, &attn, 1)?);
7287        }
7288        let (off_tok, t_kv) = if swa && kvl.len > win { (kvl.len - win, win) } else { (0, kvl.len) };
7289        let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
7290                                     (off_tok + t_kv) * kvl.k_tok_bytes);
7291        let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
7292                                     (off_tok + t_kv) * kvl.v_tok_bytes);
7293        e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
7294                    kvl.k_tok_bytes, kvl.v_tok_bytes, swa && crate::Engine::wkv_on())?;
7295        Ok(e.matmul(&fa.wo, &attn, 1)?)
7296    }
7297
7298    /// gemma4 DEVICE-COUNTER decode step (graph arc): token id + rope pos + KV lengths live in
7299    /// device counters; ZERO varying host kernel args. `cap_bucket_max` = Some(bucket) for graph
7300    /// capture (host mirrors untouched, n_splits from bucket, full-buffer KV views) / None for
7301    /// the eager-dc gate path (host mirrors advanced, live geometry — bit-identical target =
7302    /// gemma4_decode_step_h's token stream). V1 scope: t_kv <= sliding_window (no window views
7303    /// in-graph; the driver gates).
7304    #[allow(clippy::too_many_arguments)]
7305    pub fn gemma4_decode_step_dc(&self, e: &Engine, token_d: &CudaSlice<u32>,
7306                                 pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
7307                                 embd_qt: i32, embd_rb: usize, cache: &mut Cache,
7308                                 n_vocab: usize, cap_bucket_max: Option<(usize, usize)>)
7309                                 -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
7310        let mut tok_out = e.stream().alloc_zeros::<u32>(1)?;
7311        self.gemma4_decode_step_dc_into(e, token_d, pos_d, embd_gpu, embd_qt, embd_rb, cache,
7312                                        n_vocab, cap_bucket_max, &mut tok_out)?;
7313        Ok(tok_out)
7314    }
7315
7316    /// CAPTURE body: argmax lands in the PERSISTENT `tok_out` (same buffer = same address on
7317    /// every replay; pass `token_d` itself for the self-feeding graph loop).
7318    #[allow(clippy::too_many_arguments)]
7319    pub fn gemma4_decode_step_dc_into(&self, e: &Engine, token_d: &CudaSlice<u32>,
7320                                      pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
7321                                      embd_qt: i32, embd_rb: usize, cache: &mut Cache,
7322                                      n_vocab: usize, cap_bucket_max: Option<(usize, usize)>,
7323                                      tok_out: &mut CudaSlice<u32>)
7324                                      -> Result<(), Box<dyn std::error::Error>> {
7325        let n_embd = self.cfg.n_embd as usize;
7326        let eps = self.cfg.rms_eps;
7327        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_rb)?;
7328        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
7329        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
7330        let n_layers = self.layers.len();
7331        for (il, layer) in self.layers.iter().enumerate() {
7332            let (hq, hdq) = match h_carry.take() {
7333                Some(p) => p,
7334                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, 1, eps)?,
7335            };
7336            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
7337            let o = self.gemma4_decode_attn_dc(e, fa, il, &hq, &hdq, pos_d, cache, cap_bucket_max)?;
7338            let mut cur = e.uninit(n_embd)?;
7339            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, 1, eps)?;
7340            let next_norm = if il + 1 < n_layers {
7341                Some(self.layers[il + 1].attn_norm.float_data())
7342            } else { None };
7343            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, 1, next_norm)?;
7344            x = xn;
7345            h_carry = hn;
7346        }
7347        let mut hn = e.uninit(n_embd)?;
7348        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
7349        let mut logits = e.matmul(&self.output, &hn, 1)?;
7350        self.gemma4_suppress(e, &mut logits, 1)?;   // cap skipped (monotonic); the mask is not
7351        e.argmax_token_device_into(&logits, tok_out, n_vocab)?;
7352        e.inc_seqlen(pos_d)?;
7353        if cap_bucket_max.is_none() { cache.pos += 1; }
7354        Ok(())
7355    }
7356
7357    /// Persistent transient slots for the ALLOC-FREE captured dc step (the graph door):
7358    /// every buffer the step produces per token lives here, allocated ONCE pre-capture, so
7359    /// the captured graph carries zero cuMemAllocAsync/Free nodes (the 226us/launch tax,
7360    /// osrt 2026-07-23). Sized for the model's max per-layer shapes.
7361
7362    /// Build the slot set (call OUTSIDE any capture).
7363    pub fn g4_dc_slots(&self, e: &Engine) -> Result<G4DcSlots, Box<dyn std::error::Error>> {
7364        let n_embd = self.cfg.n_embd as usize;
7365        let n_vocab = self.output.out_features();
7366        let n_layers = self.layers.len();
7367        let (mut qmax, mut kvmax, mut ffmax) = (0usize, 0usize, 0usize);
7368        for il in 0..n_layers {
7369            let (hd, nkv, nh, _b, _s, _w) = self.gemma4_geom(il);
7370            qmax = qmax.max(nh * hd);
7371            kvmax = kvmax.max(nkv * hd);
7372            if let crate::hybrid::Ffn::Dense { ffn_gate, .. } = &self.layers[il].ffn {
7373                ffmax = ffmax.max(ffn_gate.out_features());
7374            }
7375        }
7376        Ok(G4DcSlots {
7377            x: e.uninit(n_embd)?, xn: e.uninit(n_embd)?, cur: e.uninit(n_embd)?,
7378            hq: e.alloc_i8_uninit(n_embd)?, hd_: e.uninit(n_embd / 32)?,
7379            q0: e.uninit(qmax)?, k0: e.uninit(kvmax)?, v0: e.uninit(kvmax)?,
7380            q: e.uninit(qmax)?, k: e.uninit(kvmax)?, v: e.uninit(kvmax)?,
7381            attn: e.uninit(qmax)?, o: e.uninit(n_embd)?,
7382            attn_out: e.uninit(n_embd)?, zsh: e.uninit(n_embd)?,
7383            // zq/zd feed the wo matvec (nh*hd rows — 4096 on hd512 globals > n_embd),
7384            // the ffn entry (n_embd) and the lm_head (n_embd): size for the max.
7385            zq: e.alloc_i8_uninit(n_embd.max(qmax))?, zd: e.uninit(n_embd.max(qmax) / 32)?,
7386            gate: e.uninit(ffmax)?, up: e.uninit(ffmax)?,
7387            act: e.uninit(ffmax)?, actq: e.alloc_i8_uninit(ffmax)?, actd: e.uninit(ffmax / 32)?,
7388            f0: e.uninit(n_embd)?, sn: e.uninit(n_embd)?,
7389            hn: e.uninit(n_embd)?, logits: e.uninit(n_vocab)?,
7390        })
7391    }
7392
7393    /// m=1 pre-quantized matvec into a slot — mirrors matmul_pre's m=1 mmvq route exactly
7394    /// (rp4-mirror bytes; mmvq_supports guaranteed for gemma4 q4_0/q6_K).
7395    fn g4_matvec_m1_into(&self, e: &Engine, w: &crate::model::GpuTensor,
7396                         aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, y: &mut CudaSlice<f32>)
7397                         -> Result<(), Box<dyn std::error::Error>> {
7398        use crate::model::GpuTensor;
7399        let (bytes, qtype, row_bytes, scale, rp) = match w {
7400            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } =>
7401                (bytes, *qtype, *row_bytes, *scale, *rp),
7402            _ => return Err("g4_matvec_m1_into: non-quant tensor".into()),
7403        };
7404        let (mbytes, mrp) = match w {
7405            GpuTensor::Quant { rp4: Some(m4), .. } => (m4, true),
7406            _ => (bytes, rp),
7407        };
7408        e.qmatvec_mmvq_into(mbytes, aq, ad, 1, w.in_features(), w.out_features(),
7409                            qtype, row_bytes, scale, mrp, y)
7410    }
7411
7412    /// ALLOC-FREE dc step (capture body): kernel-for-kernel mirror of
7413    /// `gemma4_decode_step_dc_into` at t=1 with every transient slot-fed. Dense gemma4 only
7414    /// (12B/31B; uniform q4_0 trunk guarantees the fused2/3 arms).
7415    #[allow(clippy::too_many_arguments)]
7416    pub fn gemma4_decode_step_dc_slotted(&self, e: &Engine, token_d: &CudaSlice<u32>,
7417                                         pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
7418                                         embd_qt: i32, embd_rb: usize, cache: &mut Cache,
7419                                         n_vocab: usize, cap_bucket_max: Option<(usize, usize)>,
7420                                         sl: &mut G4DcSlots, tok_out: &mut CudaSlice<u32>,
7421                                         ring: Option<(&mut CudaSlice<u32>, usize)>)
7422                                         -> Result<(), Box<dyn std::error::Error>> {
7423        let n_embd = self.cfg.n_embd as usize;
7424        let eps = self.cfg.rms_eps;
7425        e.embed_gather_device_into(embd_gpu, token_d, &mut sl.x, n_embd, embd_qt, embd_rb)?;
7426        e.scale_inplace(&mut sl.x, (n_embd as f32).sqrt(), n_embd)?;
7427        let n_layers = self.layers.len();
7428        let mut has_carry = false;
7429        for il in 0..n_layers {
7430            if !has_carry {
7431                e.rms_norm_q8_1_into(&sl.x, self.layers[il].attn_norm.float_data(), n_embd, 1,
7432                                     eps, &mut sl.hq, &mut sl.hd_)?;
7433            }
7434            has_carry = true;
7435            let layer = &self.layers[il];
7436            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
7437            self.gemma4_decode_attn_dc_slotted(e, fa, il, pos_d, cache, cap_bucket_max, sl)?;
7438            e.rms_norm(&sl.o, layer.post_attn_norm.float_data(), &mut sl.cur, n_embd, 1, eps)?;
7439            let next_norm = if il + 1 < n_layers {
7440                Some(self.layers[il + 1].attn_norm.float_data())
7441            } else { None };
7442            self.gemma4_layer_tail_slotted(e, layer, next_norm, sl)?;
7443            std::mem::swap(&mut sl.x, &mut sl.xn);
7444        }
7445        e.rms_norm(&sl.x, self.output_norm.float_data(), &mut sl.hn, n_embd, 1, eps)?;
7446        e.quantize_q8_1_into(&sl.hn, 1, n_embd, &mut sl.zq, &mut sl.zd)?;
7447        // lm_head via the same m=1 mmvq route as matmul (q6_K on the gemma4 family).
7448        {
7449            let (zq, zd) = (&sl.zq, &sl.zd);
7450            let zq = unsafe { &*(zq as *const CudaSlice<i8>) };
7451            let zd = unsafe { &*(zd as *const CudaSlice<f32>) };
7452            self.g4_matvec_m1_into(e, &self.output, zq, zd, &mut sl.logits)?;
7453        }
7454        self.gemma4_suppress(e, &mut sl.logits, 1)?;
7455        e.argmax_token_device_into(&sl.logits, tok_out, n_vocab)?;
7456        if let Some((ring, base)) = ring {
7457            // in-graph token parking: slot = (pos - base) % ring.len(); the door drains
7458            // with ONE sync per chunk instead of a per-token dtoh (the launch-serialization
7459            // fix — llama's 885us/launch overlaps GPU work because nothing waits per token).
7460            e.plain_tok_ring(tok_out, pos_d, base, ring)?;
7461        }
7462        e.inc_seqlen(pos_d)?;
7463        if cap_bucket_max.is_none() { cache.pos += 1; }
7464        Ok(())
7465    }
7466
7467    /// Slot-fed dc attention: mirrors gemma4_decode_attn_dc's CAPTURE arm kernel-for-kernel.
7468    #[allow(clippy::too_many_arguments)]
7469    fn gemma4_decode_attn_dc_slotted(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer,
7470                                     il: usize, pos_d: &CudaSlice<i32>, cache: &mut Cache,
7471                                     cap_bucket_max: Option<(usize, usize)>, sl: &mut G4DcSlots)
7472                                     -> Result<(), Box<dyn std::error::Error>> {
7473        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
7474        let eps = self.cfg.rms_eps;
7475        let aux = self.gemma4_aux.as_ref().unwrap();
7476        {
7477            let hq = unsafe { &*(&sl.hq as *const CudaSlice<i8>) };
7478            let hdq = unsafe { &*(&sl.hd_ as *const CudaSlice<f32>) };
7479            if swa {
7480                if !e.matmul_q4_fused3_into(&fa.wq, &fa.wk, &fa.wv, hq, hdq,
7481                                            &mut sl.q0, &mut sl.k0, &mut sl.v0)? {
7482                    return Err("slotted step: fused3 unavailable (non-uniform trunk)".into());
7483                }
7484            } else {
7485                if !e.matmul_q4_fused2_into(&fa.wq, &fa.wk, hq, hdq, &mut sl.q0, &mut sl.k0)? {
7486                    return Err("slotted step: fused2 unavailable".into());
7487                }
7488                let k0r = unsafe { &*(&sl.k0 as *const CudaSlice<f32>) };
7489                e.copy_into(&mut sl.v0, 0, k0r, nkv * hd)?;
7490            }
7491        }
7492        // E4B wave-3 fold, m=1 completion (2026-07-23) — MUST mirror the dc_into arm
7493        // kernel-for-kernel (graph stream-identity gate).
7494        let ff = if swa { None } else {
7495            Some(aux.rope_freqs.as_ref().expect("gemma4 global rope needs rope_freqs.weight"))
7496        };
7497        let kvl = cache.kv[il].as_mut().unwrap();
7498        let kv_fp8 = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
7499        if crate::Engine::qkv_append_on() {
7500            // append fold (2026-07-23): mirrors dc_into.
7501            e.rms_norm_qkv_rope_append_dc(&sl.q0, &sl.k0, &sl.v0, fa.q_norm.float_data(),
7502                fa.k_norm.float_data(), &aux.ones, &mut sl.q, &mut sl.k, &mut sl.v, hd, nh, nkv,
7503                pos_d, nh, nkv, base, 1.0, ff, eps,
7504                &mut kvl.k, &mut kvl.v, &kvl.len_d, kvl.k_tok_bytes, kvl.v_tok_bytes, kv_fp8)?;
7505        } else {
7506            e.rms_norm_qkv_rope(&sl.q0, &sl.k0, &sl.v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
7507                                &aux.ones, &mut sl.q, &mut sl.k, &mut sl.v, hd, nh, nkv,
7508                                pos_d, nh, nkv, base, 1.0, ff, eps)?;
7509            e.append_kv_quantized_dc(&sl.k, &sl.v, &mut kvl.k, &mut kvl.v, &kvl.len_d,
7510                                     kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
7511                                     kv_fp8)?;
7512        }
7513        e.inc_seqlen(&mut kvl.len_d)?;
7514        let (b_swa, b_glob) = cap_bucket_max.expect("slotted step is capture-only");
7515        let k_view = e.view_u8(&kvl.k, kvl.k.len());
7516        let v_view = e.view_u8(&kvl.v, kvl.v.len());
7517        let rows_on = std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0");
7518        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
7519        // combine-q8 emit (wave-5b m=1 port): the rows arms quantize inside the combine —
7520        // the standalone quantize launch runs only on the non-rows fallback. MUST mirror
7521        // the dc_into arm branch-for-branch (stream gate).
7522        let mut fa_q8 = false;
7523        if !swa && hd == 512 && b_glob >= crate::fa512_min_tkv() && rows_on {
7524            e.fa_decode_rows(&sl.q, &k_view, &v_view, &mut sl.attn, hd, nh, nkv, b_glob - 1,
7525                             1, scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
7526                             Some((&kvl.len_d, -1)), false, false,
7527                             Some((&mut sl.zq, &mut sl.zd)))?;
7528            fa_q8 = true;
7529        } else if swa && b_swa > win && hd == 256 && rows_on {
7530            e.fa_decode_rows_w(&sl.q, &k_view, &v_view, &mut sl.attn, hd, nh, nkv,
7531                               &kvl.len_d, -1, 1, scale, win,
7532                               kvl.k_tok_bytes, kvl.v_tok_bytes,
7533                               Some((&mut sl.zq, &mut sl.zd)))?;
7534            fa_q8 = true;
7535        } else {
7536            let b = if swa { b_swa } else { b_glob };
7537            e.fa_decode_dc(&sl.q, &k_view, &v_view, &mut sl.attn, hd, nh, nkv, &kvl.len_d, b,
7538                           scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
7539                           swa && crate::Engine::wkv_on())?;
7540        }
7541        if !fa_q8 {
7542            let aq = unsafe { &*(&sl.attn as *const CudaSlice<f32>) };
7543            e.quantize_q8_1_into(aq, 1, nh * hd, &mut sl.zq, &mut sl.zd)?;
7544        }
7545        {
7546            let zq = unsafe { &*(&sl.zq as *const CudaSlice<i8>) };
7547            let zd = unsafe { &*(&sl.zd as *const CudaSlice<f32>) };
7548            self.g4_matvec_m1_into(e, &fa.wo, zq, zd, &mut sl.o)?;
7549        }
7550        Ok(())
7551    }
7552
7553    /// Slot-fed dense layer tail: mirrors gemma4_layer_tail_core (t=1, no pre-norm fold) +
7554    /// tail_add_nq kernel-for-kernel; the next layer's (hq, hd_) carry lands in the slots.
7555    fn gemma4_layer_tail_slotted(&self, e: &Engine, layer: &crate::hybrid::HybridLayer,
7556                                 next_norm: Option<&CudaSlice<f32>>, sl: &mut G4DcSlots)
7557                                 -> Result<(), Box<dyn std::error::Error>> {
7558        let n_embd = self.cfg.n_embd as usize;
7559        let eps = self.cfg.rms_eps;
7560        let bits = layer.gemma4.as_ref().unwrap();
7561        let crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } = &layer.ffn
7562        else { return Err("slotted tail: dense ffn only".into()) };
7563        e.add_rms_norm(&sl.cur, &sl.x, bits.ffn_norm.float_data(), &mut sl.attn_out,
7564                       &mut sl.zsh, n_embd, 1, eps)?;
7565        let n_ff = ffn_gate.out_features();
7566        {
7567            let zshr = unsafe { &*(&sl.zsh as *const CudaSlice<f32>) };
7568            e.quantize_q8_1_into(zshr, 1, n_embd, &mut sl.zq, &mut sl.zd)?;
7569        }
7570        {
7571            let zq = unsafe { &*(&sl.zq as *const CudaSlice<i8>) };
7572            let zd = unsafe { &*(&sl.zd as *const CudaSlice<f32>) };
7573            if !e.matmul_q4_fused2_into(ffn_gate, ffn_up, zq, zd, &mut sl.gate, &mut sl.up)? {
7574                return Err("slotted tail: ffn fused2 unavailable".into());
7575            }
7576        }
7577        debug_assert!(e.uses_q8_1_fast(ffn_down));
7578        {
7579            let upr = unsafe { &*(&sl.up as *const CudaSlice<f32>) };
7580            let upv = e.view(upr, n_ff);
7581            let up_all = upv.slice(0..n_ff);
7582            let gr = unsafe { &*(&sl.gate as *const CudaSlice<f32>) };
7583            e.gelu_tanh_mul_q8_1_into(gr, &up_all, &mut sl.act, n_ff, 1,
7584                                      &mut sl.actq, &mut sl.actd)?;
7585        }
7586        {
7587            let aq = unsafe { &*(&sl.actq as *const CudaSlice<i8>) };
7588            let ad = unsafe { &*(&sl.actd as *const CudaSlice<f32>) };
7589            self.g4_matvec_m1_into(e, ffn_down, aq, ad, &mut sl.f0)?;
7590        }
7591        e.rms_norm(&sl.f0, bits.post_ffw_norm.float_data(), &mut sl.sn, n_embd, 1, eps)?;
7592        match next_norm {
7593            Some(w) => {
7594                e.add_scale_rms_norm_q8_1_into(&sl.sn, &sl.attn_out, bits.layer_scale, w,
7595                                               &mut sl.xn, n_embd, 1, eps,
7596                                               &mut sl.hq, &mut sl.hd_)?;
7597            }
7598            None => {
7599                e.add_scale(&sl.sn, &sl.attn_out, bits.layer_scale, &mut sl.xn, n_embd)?;
7600            }
7601        }
7602        Ok(())
7603    }
7604
7605    /// dc attention: same math as gemma4_decode_attn, KV slot/lengths from device counters.
7606    #[allow(clippy::too_many_arguments)]
7607    fn gemma4_decode_attn_dc(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
7608                             hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
7609                             pos_d: &CudaSlice<i32>, cache: &mut Cache,
7610                             cap_bucket_max: Option<(usize, usize)>)
7611                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7612        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
7613        let eps = self.cfg.rms_eps;
7614        let aux = self.gemma4_aux.as_ref().unwrap();
7615        let (q0, k0, v0) = if swa {
7616            match e.matmul_q4_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hdq)? {
7617                Some(t3) => t3,
7618                None => {
7619                    let h0 = e.zeros(0)?;
7620                    (e.matmul_pre(&fa.wq, hq, hdq, &h0, 1)?,
7621                     e.matmul_pre(&fa.wk, hq, hdq, &h0, 1)?,
7622                     e.matmul_pre(&fa.wv, hq, hdq, &h0, 1)?)
7623                }
7624            }
7625        } else {
7626            let (q0, k0) = match e.matmul_q4_fused2(&fa.wq, &fa.wk, hq, hdq)? {
7627                Some(p) => p,
7628                None => {
7629                    let h0 = e.zeros(0)?;
7630                    (e.matmul_pre(&fa.wq, hq, hdq, &h0, 1)?,
7631                     e.matmul_pre(&fa.wk, hq, hdq, &h0, 1)?)
7632                }
7633            };
7634            let v0 = e.clone_dtod(&k0)?;
7635            (q0, k0, v0)
7636        };
7637        let mut q = e.uninit(nh * hd)?;
7638        let mut k = e.uninit(nkv * hd)?;
7639        let mut v = e.uninit(nkv * hd)?;
7640        // E4B wave-3 fold, m=1 completion (2026-07-23): mirrored by the slotted arm.
7641        let ff = if swa { None } else {
7642            Some(aux.rope_freqs.as_ref().expect("gemma4 global rope needs rope_freqs.weight"))
7643        };
7644        let kvl = cache.kv[il].as_mut().unwrap();
7645        let kv_fp8 = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
7646        if crate::Engine::qkv_append_on() {
7647            // append fold (2026-07-23): norm+rope+cache-append in ONE launch.
7648            e.rms_norm_qkv_rope_append_dc(&q0, &k0, &v0, fa.q_norm.float_data(),
7649                fa.k_norm.float_data(), &aux.ones, &mut q, &mut k, &mut v, hd, nh, nkv,
7650                pos_d, nh, nkv, base, 1.0, ff, eps,
7651                &mut kvl.k, &mut kvl.v, &kvl.len_d, kvl.k_tok_bytes, kvl.v_tok_bytes, kv_fp8)?;
7652        } else {
7653            e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
7654                                &aux.ones, &mut q, &mut k, &mut v, hd, nh, nkv,
7655                                pos_d, nh, nkv, base, 1.0, ff, eps)?;
7656            e.append_kv_quantized_dc(&k, &v, &mut kvl.k, &mut kvl.v, &kvl.len_d,
7657                                     kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes, kv_fp8)?;
7658        }
7659        e.inc_seqlen(&mut kvl.len_d)?;
7660        let mut attn = e.uninit(nh * hd)?;
7661        // combine-q8 emit carrier (wave-5b m=1 port): rows arms fill this; the tail then
7662        // rides g4_matvec_m1_into instead of matmul's internal quantize.
7663        let mut fa_q8: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
7664        // Weight prefetch NOT wired here (26B/31B/qwen probes 2026-07-13: 26B flat
7665        // 196.6/196.0 vs 196.4/196.1 — MoE ffn dilutes wo; 31B −0.2% — dense decode sits
7666        // at the DRAM wall, no idle window to front-load into). E4B keeps the arm
7667        // (gemma4_e4b_attn, +0.65% valid window).
7668        match cap_bucket_max {
7669            None => {
7670                // dc-EAGER: host knows the length — R6 window views EXACTLY like the eager
7671                // decode (SWA layers attend the last `sliding_window` keys); the device
7672                // counters carry only the append slot + the graph seam.
7673                kvl.len += 1;
7674                let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
7675                if !swa && hd == 512 && kvl.len >= crate::fa512_min_tkv()
7676                    && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
7677                    // global layers: SAME hd512 rows twin as verify, t=1 (parity law).
7678                    // dc: len_d is live (inc_seqlen) — device-len rides it, plus=-1.
7679                    let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
7680                    let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
7681                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
7682                    e.fa_decode_rows(&q, &kp, &vp, &mut attn, hd, nh, nkv, kvl.len - 1, 1,
7683                                     scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
7684                                     Some((&kvl.len_d, -1)), false, false,
7685                                     Some((&mut aq8, &mut ad8)))?;
7686                    fa_q8 = Some((aq8, ad8));
7687                } else if swa && kvl.len > win && hd == 256
7688                    && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
7689                    // windowed regime: SAME rows_w kernel as verify, t=1 (parity law).
7690                    let kp = e.view_u8(&kvl.k, kvl.len * kvl.k_tok_bytes);
7691                    let vp = e.view_u8(&kvl.v, kvl.len * kvl.v_tok_bytes);
7692                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
7693                    e.fa_decode_rows_w(&q, &kp, &vp, &mut attn, hd, nh, nkv, &kvl.len_d, -1,
7694                                       1, scale, win, kvl.k_tok_bytes, kvl.v_tok_bytes,
7695                                       Some((&mut aq8, &mut ad8)))?;
7696                    fa_q8 = Some((aq8, ad8));
7697                } else {
7698                    let (off_tok, t_kv) = if swa && kvl.len > win { (kvl.len - win, win) }
7699                                          else { (0, kvl.len) };
7700                    let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
7701                                                 (off_tok + t_kv) * kvl.k_tok_bytes);
7702                    let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
7703                                                 (off_tok + t_kv) * kvl.v_tok_bytes);
7704                    e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
7705                                kvl.k_tok_bytes, kvl.v_tok_bytes, swa && crate::Engine::wkv_on())?;
7706                }
7707            }
7708            Some((b_swa, b_glob)) => {
7709                // capture: full-buffer views + device length. PARITY LAW port (graph arc step
7710                // 3): the SAME regime branches as dc-eager, pinned per arm — b_swa is the
7711                // exact-key t_kv for the dc family (n_splits constant per bucket), b_glob is
7712                // the RUNG max for the rows family (kernels derive per-replay splits from
7713                // kvl.len_d; grid/partials sized for the rung end, excess splits exit).
7714                let k_view = e.view_u8(&kvl.k, kvl.k.len());
7715                let v_view = e.view_u8(&kvl.v, kvl.v.len());
7716                let rows_on = std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0");
7717                let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
7718                if !swa && hd == 512 && b_glob >= crate::fa512_min_tkv() && rows_on {
7719                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
7720                    e.fa_decode_rows(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, b_glob - 1,
7721                                     1, scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
7722                                     Some((&kvl.len_d, -1)), false, false,
7723                                     Some((&mut aq8, &mut ad8)))?;
7724                    fa_q8 = Some((aq8, ad8));
7725                } else if swa && b_swa > win && hd == 256 && rows_on {
7726                    let (mut aq8, mut ad8) = e.uninit_q8_pair(nh * hd)?;
7727                    e.fa_decode_rows_w(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
7728                                       &kvl.len_d, -1, 1, scale, win,
7729                                       kvl.k_tok_bytes, kvl.v_tok_bytes,
7730                                       Some((&mut aq8, &mut ad8)))?;
7731                    fa_q8 = Some((aq8, ad8));
7732                } else {
7733                    let b = if swa { b_swa } else { b_glob };
7734                    e.fa_decode_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, &kvl.len_d, b,
7735                                   scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
7736                                   swa && crate::Engine::wkv_on())?;
7737                }
7738            }
7739        }
7740        // combine-q8 emit (wave-5b m=1 port): the rows arms produced the wo activation pair
7741        // in-combine — ride the slotted arm's exact matvec route (parity by construction).
7742        if let Some((aq8, ad8)) = fa_q8 {
7743            let mut y = e.uninit(fa.wo.out_features())?;
7744            self.g4_matvec_m1_into(e, &fa.wo, &aq8, &ad8, &mut y)?;
7745            return Ok(y);
7746        }
7747        Ok(e.matmul(&fa.wo, &attn, 1)?)
7748    }
7749
7750    /// gemma4 GRAPH-REPLAY greedy loop: per (swa-key, global-key) fa bucket, capture ONE full
7751    /// dc step (self-feeding: argmax writes token_d in-graph) and replay it — one graph launch
7752    /// per token, one 4B dtoh. V1 scope: whole generation under the sliding window (no window
7753    /// views in-graph); caller gates and falls back to the dc-eager loop.
7754    pub fn gemma4_generate_graph(&self, e: &Engine, prompt_pos: usize, first_token: u32,
7755                                 cache: &mut Cache, max_new: usize, eos: &[u32],
7756                                 mut on_token: impl FnMut(u32) -> bool)
7757                                 -> Result<(Vec<u32>, crate::decode::StopReason), Box<dyn std::error::Error>> {
7758        if self.is_gemma4_e4b() {
7759            return Err("E4B graph serving is unwired (HANDOVER-E4B.md) — dc-eager is the serving arm".into());
7760        }
7761        use crate::decode::StopReason;
7762        let n_vocab = self.output.out_features();
7763        let n_embd = self.cfg.n_embd as usize;
7764        let embd_gpu = self.embd_gpu.get_or_init(|| {
7765            e.upload_u8(&self.embd.raw).expect("embed table upload")
7766        });
7767        let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
7768        for kvl in cache.kv.iter_mut().flatten() {
7769            e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
7770        }
7771        let mut token_d = e.stream().clone_htod(&[first_token])?;
7772        let mut pos_d = e.htod_i32(&[prompt_pos as i32])?;
7773        let g4 = self.cfg.gemma4.as_ref().unwrap();
7774        let (hd_s, hd_g) = (g4.key_length_swa as usize, g4.key_length_global as usize);
7775        // per-layer nkv: swa vs global counts from the pattern (uniform within class).
7776        let nkv_s = g4.head_count_kv.iter().zip(g4.swa_pattern.iter())
7777            .find(|p| *p.1).map(|p| *p.0 as usize).unwrap_or(8);
7778        let nkv_g = g4.head_count_kv.iter().zip(g4.swa_pattern.iter())
7779            .find(|p| !*p.1).map(|p| *p.0 as usize).unwrap_or(2);
7780        let mut graphs: std::collections::HashMap<((bool, usize), (bool, usize), bool, bool),
7781                                                  (cudarc::driver::CudaGraph,
7782                                                   Vec<Box<dyn std::any::Any + Send>>)> = Default::default();
7783        // ALLOC-FREE capture: persistent transient slots — the captured graph carries zero
7784        // mem nodes (the 226us/launch tax). Slots must outlive every cached graph.
7785        let mut slots = self.g4_dc_slots(e)?;
7786        // Chunked replay ring: tokens park on-device; ONE drain sync per chunk. ring_base is
7787        // baked at the door entry (the modulo keeps every capture valid indefinitely).
7788        const RING: usize = 64;
7789        // DRAIN pinned at 1 (2026-07-23): relaunching the SAME graph exec before its prior
7790        // launch completes is ILLEGAL (chunk=4 -> ILLEGAL_ADDRESS; chunk=1 clean). Pipelining
7791        // needs alternating exec instances — and the measured payoff was ~0 (the ~200us
7792        // cuGraphLaunch host cost already overlaps its own launch's GPU work; llama pays
7793        // 885us/launch the same way). MEMRA_GRAPH_DRAIN raises it only for experiments.
7794        const DRAIN: usize = 1;
7795        let mut ring = e.stream().alloc_zeros::<u32>(RING)?;
7796        let ring_base = prompt_pos;
7797        let mut out = Vec::with_capacity(max_new);
7798        let mut reason = StopReason::MaxNew;
7799        let mut next = first_token;
7800        let mut captures = 0usize;
7801        for _ in 0..max_new {
7802            out.push(next);
7803            if eos.contains(&next) { reason = StopReason::Eos; break; }
7804            if !on_token(next) { reason = StopReason::Callback; break; }
7805            let t_kv = cache.pos + 1;
7806            // Bucket key per ARM (graph arc step 3):
7807            //  - swa component: dc family under the window (exact (fa_vec, n_splits) key —
7808            //    n_splits must be constant per bucket); rows_w above it (window-constant, so
7809            //    the component collapses to a single marker).
7810            //  - global component: dc family under the fa512 floor (exact key); rows_dpl16
7811            //    at/above it — the kernel derives splits from len_d per replay, so buckets
7812            //    are power-of-2 RUNGS (one capture per doubling; grid sized for the rung end).
7813            let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
7814            let f512 = crate::fa512_min_tkv();
7815            let key_s = if t_kv > win { (true, usize::MAX) }
7816                        else { e.fa_bucket_key(t_kv, hd_s, nkv_s, crate::Engine::wkv_on()) };
7817            let (key_g, rung_end) = if t_kv >= f512 {
7818                // strict upper bound: the rung must ROLL at exact powers (t_kv==1024 starts
7819                // the [1024,2048) bucket) — sizing covers every replayed T_kv < end.
7820                let end = (t_kv + 1).next_power_of_two().max(f512 * 2);
7821                ((true, end), end)
7822            } else { (e.fa_bucket_key(t_kv, hd_g, nkv_g, false), t_kv) };
7823            let key = (key_s, key_g, t_kv >= f512, t_kv > win);
7824            if !graphs.contains_key(&key) {
7825                let bucket_max = (t_kv, rung_end);
7826                // snapshot device+host state (the 3 capture-warmup runs leave no residue).
7827                let snap = cache.snapshot(e)?;
7828                let pos_save = e.dtoh_i32_one(&pos_d)?;
7829                let len_save: Vec<Option<i32>> = cache.kv.iter()
7830                    .map(|k| k.as_ref().map(|kvl| e.dtoh_i32_one(&kvl.len_d).unwrap())).collect();
7831                let tok_save = e.dtoh_u32_one(&token_d)?;
7832                // RETAINED capture (2026-07-23): the plain capture_graph left pool-transient
7833                // clones as dead COPY NODES replayed every launch — the E4B 0.74ms/token
7834                // regression class, and this door's measured -8.8%. The keeper pins warmup
7835                // transients so the captured graph holds kernel nodes only.
7836                let graph = {
7837                    let tok_ref = &mut token_d;
7838                    let pos_ref = &mut pos_d;
7839                    let cache_ref = &mut *cache;
7840                    let slots_ref = &mut slots;
7841                    let ring_ref = &mut ring;
7842                    e.capture_graph_retained_flags(
7843                        cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY,
7844                        |e| {
7845                        // self-feeding: the argmax writes token_d itself.
7846                        let tok_in = unsafe { &*(tok_ref as *const CudaSlice<u32>) };
7847                        let sl = unsafe { &mut *(slots_ref as *mut G4DcSlots) };
7848                        let rg = unsafe { &mut *(ring_ref as *mut CudaSlice<u32>) };
7849                        self.gemma4_decode_step_dc_slotted(e, tok_in, pos_ref, embd_gpu, qt, rb,
7850                                                           cache_ref, n_vocab, Some(bucket_max),
7851                                                           sl, tok_ref, Some((rg, ring_base)))
7852                    })?
7853                };
7854                cache.rollback(e, &snap, 0)?;
7855                e.set_i32_one(&mut pos_d, pos_save)?;
7856                for (il, ls) in len_save.iter().enumerate() {
7857                    if let (Some(kvl), Some(v)) = (cache.kv[il].as_mut(), ls) {
7858                        e.set_i32_one(&mut kvl.len_d, *v)?;
7859                    }
7860                }
7861                e.set_u32_one(&mut token_d, tok_save)?;
7862                if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
7863                    if let Ok(c) = crate::graph_update::node_census(&graph.0) {
7864                        eprintln!("[graph-census] {c:?}");
7865                    }
7866                }
7867                graphs.insert(key, graph);
7868                captures += 1;
7869            }
7870            // CHUNKED REPLAY: enqueue up to DRAIN launches back-to-back (the ~200us host
7871            // cost of each cuGraphLaunch overlaps the PREVIOUS launch's ~11ms GPU work),
7872            // then ONE sync + ring drain. The chunk must stay inside this bucket key and
7873            // the budget; capture warmups already emitted their tokens through the ring.
7874            let mut chunk = 1usize;
7875            let drain_cap: usize = std::env::var("MEMRA_GRAPH_DRAIN").ok()
7876                .and_then(|v| v.parse().ok()).unwrap_or(DRAIN);
7877            while chunk < drain_cap && out.len() + chunk < max_new {
7878                let t_next = cache.pos + 1 + chunk;
7879                let key_s2 = if t_next > win { (true, usize::MAX) }
7880                             else { e.fa_bucket_key(t_next, hd_s, nkv_s, crate::Engine::wkv_on()) };
7881                let key_g2 = if t_next >= f512 {
7882                    (true, (t_next + 1).next_power_of_two().max(f512 * 2))
7883                } else { e.fa_bucket_key(t_next, hd_g, nkv_g, false) };
7884                if (key_s2, key_g2, t_next >= f512, t_next > win) != key { break; }
7885                chunk += 1;
7886            }
7887            let g = &graphs.get(&key).unwrap().0;
7888            for _ in 0..chunk { g.launch()?; }
7889            e.stream().synchronize()?;
7890            let ringh = e.dtoh_u32(&ring)?;
7891            for j in 0..chunk {
7892                let pos_j = cache.pos + j;
7893                let tok_j = ringh[(pos_j - ring_base) % RING];
7894                cache.pos += 0; // advanced below in one shot
7895                if j + 1 == chunk { next = tok_j; }
7896                else {
7897                    out.push(tok_j);
7898                    if eos.contains(&tok_j) || !on_token(tok_j) {
7899                        reason = if eos.contains(&tok_j) { StopReason::Eos }
7900                                 else { StopReason::Callback };
7901                        // roll device/host state back to the stop point.
7902                        let keep = cache.pos + j + 1;
7903                        e.set_i32_one(&mut pos_d, keep as i32)?;
7904                        for kvl in cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
7905                            e.set_i32_one(&mut kvl.len_d, keep as i32)?;
7906                            kvl.len = keep;
7907                        }
7908                        cache.pos = keep;
7909                        if std::env::var("MEMRA_GRAPH_STATS").is_ok() {
7910                            eprintln!("[gemma-graph] captures={captures} buckets={}", graphs.len());
7911                        }
7912                        return Ok((out, reason));
7913                    }
7914                }
7915            }
7916            cache.pos += chunk;
7917            for kvl in cache.kv.iter_mut().filter_map(|k| k.as_mut()) { kvl.len += chunk; }
7918        }
7919        if std::env::var("MEMRA_GRAPH_STATS").is_ok() {
7920            eprintln!("[gemma-graph] captures={captures} buckets={}", graphs.len());
7921        }
7922        Ok((out, reason))
7923    }
7924
7925    /// gemma4 VERIFY step (spec decode): t tokens batched through the trunk at positions
7926    /// pos0..pos0+t-1, K/V rows appended to the quantized cache (caller rolls back rejected
7927    /// rows via kvl.len), per-token causal windowed attend (fa_decode per token — the same
7928    /// kernel family as T=1 decode at each token's t_kv). Returns [t, n_vocab] softcapped
7929    /// logits (host) + advances cache.pos by t.
7930    pub(crate) fn gemma4_decode_step_t(&self, e: &Engine, tokens: &[u32], pos0: usize,
7931                                       cache: &mut Cache)
7932                                       -> Result<Vec<f32>, Box<dyn std::error::Error>> {
7933        Ok(self.gemma4_decode_step_t_h(e, tokens, pos0, cache)?.0)
7934    }
7935
7936    /// GREEDY verify: per-row DEVICE argmax (t x 4B host traffic instead of the t x 1MB logits
7937    /// stack — softcap skipped: tanh is monotonic, per-row argmax unaffected). Returns
7938    /// (argmax ids [t], post-output_norm hidden stack [t, n_embd]).
7939    pub(crate) fn gemma4_decode_step_t_am(&self, e: &Engine, tokens: &[u32], pos0: usize,
7940                                          cache: &mut Cache)
7941                                          -> Result<(Vec<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7942        let (ld, hn) = self.gemma4_verify_trunk(e, tokens, pos0, cache, None)?;
7943        let t = tokens.len();
7944        let n_vocab = self.output.out_features();
7945        let mut toks = e.stream().alloc_zeros::<u32>(t)?;
7946        for i in 0..t {
7947            e.argmax_token_device_col(&ld, i, n_vocab, &mut toks, i)?;
7948        }
7949        Ok((e.dtoh_u32(&toks)?, hn))
7950    }
7951
7952    /// Device-token verify (async spec round): tokens live in tok_d[0..t]; per-row argmax
7953    /// lands in a DEVICE buffer (no host logits). Returns (vam_d [t] u32 device, hn stack).
7954    pub(crate) fn gemma4_decode_step_t_am_dev(&self, e: &Engine, tok_d: &CudaSlice<u32>, t: usize,
7955                                              pos0: usize, cache: &mut Cache)
7956                                              -> Result<(CudaSlice<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7957        let (ld, hn) = self.gemma4_verify_trunk(e, &vec![0u32; t], pos0, cache, Some(tok_d))?;
7958        let n_vocab = self.output.out_features();
7959        let mut vam = e.stream().alloc_zeros::<u32>(t)?;
7960        for i in 0..t {
7961            e.argmax_token_device_col(&ld, i, n_vocab, &mut vam, i)?;
7962        }
7963        Ok((vam, hn))
7964    }
7965
7966    /// gemma4 verify + the POST-output_norm hidden stack [t, n_embd] (the drafter's h input —
7967    /// llama's h_nextn convention).
7968    pub(crate) fn gemma4_decode_step_t_h(&self, e: &Engine, tokens: &[u32], pos0: usize,
7969                                         cache: &mut Cache)
7970                                         -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7971        let (mut ld, hn) = self.gemma4_verify_trunk(e, tokens, pos0, cache, None)?;
7972        let t = tokens.len();
7973        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
7974        e.softcap(&mut ld, cap, t * self.output.out_features())?;
7975        Ok((e.dtoh(&ld)?, hn))
7976    }
7977
7978    /// Persistent device scratch for the BURST verify stream (one per generation): rope pos
7979    /// rows [cap] + per-row t_kv counters (device-filled from the round counter, zero H2D).
7980    pub(crate) fn verify_stream_scratch(&self, e: &Engine, cap: usize)
7981                                        -> Result<VerifyStreamScratch, Box<dyn std::error::Error>> {
7982        Ok(VerifyStreamScratch {
7983            pos_d: e.htod_i32(&vec![0i32; cap])?,
7984            row_ctrs: (0..cap).map(|_| e.htod_i32(&[0])).collect::<Result<_, _>>()?,
7985        })
7986    }
7987
7988    /// BURST verify trunk (device-slot twin): tokens from a device buffer, rope positions
7989    /// iota'd from `ctr`, appends/attention at the layers' len_d counters (verify_attn_stream),
7990    /// NO host cache.pos/len advance. Returns (per-row device argmaxes [t], post-norm hidden
7991    /// stack [t, n_embd]) — the burst's accept/seed inputs, zero host readbacks.
7992    /// `scr` = PERSISTENT per-gen scratch (pos rows + per-row t_kv counters): the first cut
7993    /// htod_i32-allocated these per call — 9 pageable H2D copies per round, each a stream
7994    /// sync, exactly the turnaround the burst exists to remove.
7995    pub(crate) fn gemma4_verify_t_am_stream(&self, e: &Engine, tok_d: &CudaSlice<u32>, t: usize,
7996                                            ctr: &CudaSlice<i32>, hint: usize,
7997                                            cache: &mut Cache,
7998                                            scr: &mut VerifyStreamScratch)
7999                                            -> Result<(CudaSlice<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8000        let n_embd = self.cfg.n_embd as usize;
8001        let eps = self.cfg.rms_eps;
8002        assert!(t <= scr.row_ctrs.len() && t <= 64);
8003        e.i32_iota_from(ctr, &mut scr.pos_d, t)?;
8004        for i in 0..t {
8005            e.i32_copy_add(ctr, &mut scr.row_ctrs[i], (i + 1) as i32)?;
8006        }
8007        let (pos_d, row_ctrs) = (&scr.pos_d, &scr.row_ctrs);
8008        let embd_gpu = self.embd_gpu.get_or_init(|| {
8009            e.upload_u8(&self.embd.raw).expect("embed table upload")
8010        });
8011        let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
8012        let mut x = e.embed_gather_device_td(embd_gpu, tok_d, t, n_embd, qt, rb)?;
8013        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
8014        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8015        let n_layers = self.layers.len();
8016        for (il, layer) in self.layers.iter().enumerate() {
8017            let (hq, hdq) = match h_carry.take() {
8018                Some(p) => p,
8019                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, t, eps)?,
8020            };
8021            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8022            let o = self.gemma4_verify_attn_stream(e, fa, il, &hq, &hdq, pos_d, t, cache,
8023                                                    hint, row_ctrs)?;
8024            let mut cur = e.uninit(t * n_embd)?;
8025            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
8026            let next_norm = if il + 1 < n_layers {
8027                Some(self.layers[il + 1].attn_norm.float_data())
8028            } else { None };
8029            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, t, next_norm)?;
8030            x = xn;
8031            h_carry = hn;
8032            self.dflash_tap(e, cache, il, &x, t)?;
8033        }
8034        let mut hn = e.uninit(t * n_embd)?;
8035        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
8036        let ld = e.matmul(&self.output, &hn, t)?;
8037        let n_vocab = self.output.out_features();
8038        let mut vam = e.stream().alloc_zeros::<u32>(t)?;
8039        for i in 0..t {
8040            e.argmax_token_device_col(&ld, i, n_vocab, &mut vam, i)?;
8041        }
8042        Ok((vam, hn))
8043    }
8044
8045    /// Verify trunk core: returns (UN-softcapped logits device [t, n_vocab], post-output_norm
8046    /// hidden stack [t, n_embd]); appends KV rows + advances cache.pos.
8047    /// DFlash tap write (dflash lane): copy the post-layer residual rows of `x` into the
8048    /// armed sink at the tap slot for `il` (row-major [t, n_taps*hidden]). Per-row D2D
8049    /// copies — t <= block_size on verify; prime pays t*n_taps once per prompt (dedicated
8050    /// kernel later if it shows in the profile).
8051    fn dflash_tap(&self, e: &Engine, cache: &mut Cache, il: usize, x: &CudaSlice<f32>, t: usize)
8052                  -> Result<(), Box<dyn std::error::Error>> {
8053        let Some(taps) = cache.dflash_taps.as_mut() else { return Ok(()) };
8054        let Some(slot) = taps.layer_ids.iter().position(|&l| l == il) else { return Ok(()) };
8055        let h = taps.hidden;
8056        let n_taps = taps.layer_ids.len();
8057        debug_assert_eq!(taps.t, t);
8058        let xv = e.view(x, t * h);
8059        for r in 0..t {
8060            let row = xv.slice(r * h..(r + 1) * h);
8061            e.copy_view_into(&mut taps.buf, r * n_taps * h + slot * h, &row, h)?;
8062        }
8063        Ok(())
8064    }
8065
8066    fn gemma4_verify_trunk(&self, e: &Engine, tokens: &[u32], pos0: usize, cache: &mut Cache,
8067                           tok_dev: Option<&CudaSlice<u32>>)
8068                           -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8069        let n_embd = self.cfg.n_embd as usize;
8070        let eps = self.cfg.rms_eps;
8071        let t = tokens.len();
8072        let pos: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
8073        let pos_d = e.htod_i32(&pos)?;
8074        let mut x = match tok_dev {
8075            Some(td) => {
8076                let embd_gpu = self.embd_gpu.get_or_init(|| {
8077                    e.upload_u8(&self.embd.raw).expect("embed table upload")
8078                });
8079                let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
8080                e.embed_gather_device_td(embd_gpu, td, t, n_embd, qt, rb)?
8081            }
8082            None => e.htod(&self.embd.gather(n_embd, tokens))?,
8083        };
8084        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
8085        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8086        let n_layers = self.layers.len();
8087        for (il, layer) in self.layers.iter().enumerate() {
8088            let (hq, hdq) = match h_carry.take() {
8089                Some(p) => p,
8090                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, t, eps)?,
8091            };
8092            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8093            let o = self.gemma4_verify_attn(e, fa, il, &hq, &hdq, &pos_d, t, cache)?;
8094            let mut cur = e.uninit(t * n_embd)?;
8095            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, t, eps)?;
8096            let next_norm = if il + 1 < n_layers {
8097                Some(self.layers[il + 1].attn_norm.float_data())
8098            } else { None };
8099            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, t, next_norm)?;
8100            x = xn;
8101            h_carry = hn;
8102            self.dflash_tap(e, cache, il, &x, t)?;
8103        }
8104        let mut hn = e.uninit(t * n_embd)?;
8105        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
8106        let mut ld = e.matmul(&self.output, &hn, t)?;
8107        self.gemma4_suppress(e, &mut ld, t)?;   // before the per-row argmax consumers
8108        cache.pos += t;
8109        Ok((ld, hn))
8110    }
8111
8112    /// Verify attention: project/norm/rope t rows, append them to the cache, then attend each
8113    /// row causally over [win_off_i .. base+i] via the SAME fa_decode dispatch as T=1 decode.
8114    /// BURST verify attention (device-slot twin of `gemma4_verify_attn`): the append lands
8115    /// at the layer's len_d counter (rows_dc), attention bases ride the counter (rows /
8116    /// rows_w with base_dev), and NO host len is read or bumped — `hint` is a host UPPER
8117    /// bound on base_len used only for split sizing and arm gating (the burst loop passes
8118    /// pos0 + burst slack). Host len mirrors re-sync at the burst drain.
8119    #[allow(clippy::too_many_arguments)]
8120    fn gemma4_verify_attn_stream(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
8121                                 hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
8122                                 pos_d: &CudaSlice<i32>, t: usize,
8123                                 cache: &mut Cache, hint: usize,
8124                                 row_ctrs: &[CudaSlice<i32>])
8125                                 -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8126        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
8127        let eps = self.cfg.rms_eps;
8128        let aux = self.gemma4_aux.as_ref().unwrap();
8129        let h0 = e.zeros(0)?;
8130        let h = &h0;
8131        // BATCHED FUSED qkv (MEMRA_F2B=1, megakernel microcosm): swa layers fuse all three,
8132        // globals fuse q,k (v := k clone). Bit-identical per row; segments tail-fill.
8133        static F2B_QKV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8134        let f2b = *F2B_QKV.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0"));
8135        let fused_qkv = if f2b {
8136            if swa {
8137                e.matmul_q4_fused3_batched(&fa.wq, &fa.wk, &fa.wv, hq, hdq, t)?
8138                    .map(|(a, b, c)| (a, b, Some(c)))
8139            } else {
8140                e.matmul_q4_fused2_batched(&fa.wq, &fa.wk, hq, hdq, t)?
8141                    .map(|(a, b)| (a, b, None))
8142            }
8143        } else { None };
8144        let (q0, k0, v0) = match fused_qkv {
8145            Some((a, b, cv)) => {
8146                let v = match cv { Some(c) => c, None => e.clone_dtod(&b)? };
8147                (a, b, v)
8148            }
8149            None => {
8150                let q0 = e.matmul_pre(&fa.wq, hq, hdq, h, t)?;
8151                let k0 = e.matmul_pre(&fa.wk, hq, hdq, h, t)?;
8152                let v0 = if swa { e.matmul_pre(&fa.wv, hq, hdq, h, t)? }
8153                         else { e.clone_dtod(&k0)? };
8154                (q0, k0, v0)
8155            }
8156        };
8157        let mut q = e.uninit(t * nh * hd)?;
8158        let mut k = e.uninit(t * nkv * hd)?;
8159        let mut v = e.uninit(t * nkv * hd)?;
8160        // E4B wave-3 fold (2026-07-23 decode-dust port): q/k/v norms + q/k rope in ONE
8161        // launch — rope math verbatim on the normed rows; V ones-rms, never roped.
8162        let ff = if swa { None } else {
8163            Some(aux.rope_freqs.as_ref().expect("gemma4 global rope needs rope_freqs.weight"))
8164        };
8165        e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
8166                            &aux.ones, &mut q, &mut k, &mut v, hd, nh * t, nkv * t,
8167                            pos_d, nh, nkv, base, 1.0, ff, eps)?;
8168        let kvl = cache.kv[il].as_mut().unwrap();
8169        // append at the DEVICE slot; the counter advances by t on-device.
8170        e.append_kv_quantized_rows_dc(&k, &v, &mut kvl.k, &mut kvl.v, &kvl.len_d, t,
8171                                      kvl.kv_dim_k, kvl.kv_dim_v,
8172                                      kvl.k_tok_bytes, kvl.v_tok_bytes,
8173                                      (!swa && crate::Engine::gkv_on())
8174                                          || (swa && crate::Engine::wkv_on()))?;
8175        // len_d is NOT advanced here: the burst's device rollback (spec_rollback_stream) is
8176        // the sole len writer after this round's attention (base stays = old len, plus = 0).
8177        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
8178        let mut attn = e.uninit(t * nh * hd)?;
8179        let k_view = e.view_u8(&kvl.k, kvl.k.len());
8180        let v_view = e.view_u8(&kvl.v, kvl.v.len());
8181        // arm gating on the host HINT (upper bound; burst entry guards hint >= the vec floor
8182        // and a stable window regime — the same rung/regime keys as the draft graph).
8183        if swa && hint + 1 >= win {
8184            // fully-windowed rows: per-row window geometry from the counter (plus = 0: len_d
8185            // still holds the pre-append len; row r's T_kv = ctr + r + 1).
8186            e.fa_decode_rows_w(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8187                               &kvl.len_d, 0, t, scale, win,
8188                               kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
8189        } else if hd == 512 && hint + t < crate::fa512_min_tkv() {
8190            // globals UNDER the fa512 crossover: eager runs the per-row fa_decode_kvmod
8191            // fallback there (parity with t=1 decode) — mirror it with per-row fa_decode_dc
8192            // (bit-correct for any t_kv <= bucket; the drafter dc arc proved the pairing).
8193            // Burst entry gates the horizon onto one side of the crossover, so hint decides
8194            // for every row.
8195            // NO .max(512): fa_decode_dc gates its hd512 dpl16-vs-scalar pick on bucket_max
8196            // (mirroring eager's fa512 floor) — forcing 512 here flipped the arm to dpl16
8197            // while eager ran scalar (il=5 KV drift, the burst's 4/128). SAME LAW capped
8198            // from above (2026-07-13): a regime-pinned hint near the floor (round-graph
8199            // captures use f512-1) pow2-rounds PAST it — clamp under the floor, or the arm
8200            // re-flips to dpl16 (the round-graph 4/64). The scalar unified self-splits, so
8201            // any bucket >= the live length is exact.
8202            let bucket = (hint + t + 2).next_power_of_two()
8203                .min(crate::fa512_min_tkv().saturating_sub(1));
8204            let qv = e.view(&q, t * nh * hd);
8205            for i in 0..t {
8206                let q_row = qv.slice(i * nh * hd..(i + 1) * nh * hd);
8207                let mut q_one = e.uninit(nh * hd)?;
8208                e.copy_view_into(&mut q_one, 0, &q_row, nh * hd)?;
8209                let mut a_one = e.uninit(nh * hd)?;
8210                e.fa_decode_dc(&q_one, &k_view, &v_view, &mut a_one, hd, nh, nkv,
8211                               &row_ctrs[i], bucket, scale,
8212                               kvl.k_tok_bytes, kvl.v_tok_bytes, false)?;
8213                e.copy_into(&mut attn, i * nh * hd, &a_one, nh * hd)?;
8214            }
8215        } else if hd == 512 {
8216            // globals past the crossover: dpl16 dc twin via the shared rows wrapper (hint
8217            // sizes splits — upper bound; splits beyond the device len exit in-kernel).
8218            e.fa_decode_rows(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, hint, t, scale,
8219                             kvl.k_tok_bytes, kvl.v_tok_bytes,
8220                             Some((&kvl.len_d, 0)), false, false, None)?;
8221        } else {
8222            // hd256 under-window: v4 device-len rows twin.
8223            e.fa_decode_rows_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8224                                &kvl.len_d, hint + t, t, scale,
8225                                kvl.k_tok_bytes, kvl.v_tok_bytes, 0,
8226                                swa && crate::Engine::wkv_on())?;
8227        }
8228        Ok(e.matmul(&fa.wo, &attn, t)?)
8229    }
8230
8231    fn gemma4_verify_attn(&self, e: &Engine, fa: &crate::hybrid::FullAttnLayer, il: usize,
8232                          hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
8233                          pos_d: &CudaSlice<i32>, t: usize,
8234                          cache: &mut Cache)
8235                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8236        let (hd, nkv, nh, base, scale, swa) = self.gemma4_geom(il);
8237        let eps = self.cfg.rms_eps;
8238        let aux = self.gemma4_aux.as_ref().unwrap();
8239        let n_embd = self.cfg.n_embd as usize;
8240        let _ = n_embd;
8241
8242        let h0 = e.zeros(0)?;
8243        let h = &h0;
8244        // BATCHED FUSED qkv (MEMRA_F2B=1, megakernel microcosm): swa layers fuse all three,
8245        // globals fuse q,k (v := k clone). Bit-identical per row; segments tail-fill.
8246        static F2B_QKV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8247        let f2b = *F2B_QKV.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0"));
8248        let fused_qkv = if f2b {
8249            if swa {
8250                e.matmul_q4_fused3_batched(&fa.wq, &fa.wk, &fa.wv, hq, hdq, t)?
8251                    .map(|(a, b, c)| (a, b, Some(c)))
8252            } else {
8253                e.matmul_q4_fused2_batched(&fa.wq, &fa.wk, hq, hdq, t)?
8254                    .map(|(a, b)| (a, b, None))
8255            }
8256        } else { None };
8257        let (q0, k0, v0) = match fused_qkv {
8258            Some((a, b, cv)) => {
8259                let v = match cv { Some(c) => c, None => e.clone_dtod(&b)? };
8260                (a, b, v)
8261            }
8262            None => {
8263                let q0 = e.matmul_pre(&fa.wq, hq, hdq, h, t)?;
8264                let k0 = e.matmul_pre(&fa.wk, hq, hdq, h, t)?;
8265                let v0 = if swa { e.matmul_pre(&fa.wv, hq, hdq, h, t)? }
8266                         else { e.clone_dtod(&k0)? };
8267                (q0, k0, v0)
8268            }
8269        };
8270        let mut q = e.uninit(t * nh * hd)?;
8271        let mut k = e.uninit(t * nkv * hd)?;
8272        let mut v = e.uninit(t * nkv * hd)?;
8273        // E4B wave-3 fold (2026-07-23 decode-dust port): q/k/v norms + q/k rope in ONE
8274        // launch — rope math verbatim on the normed rows; V ones-rms, never roped.
8275        let ff = if swa { None } else {
8276            Some(aux.rope_freqs.as_ref().expect("gemma4 global rope needs rope_freqs.weight"))
8277        };
8278        e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(), fa.k_norm.float_data(),
8279                            &aux.ones, &mut q, &mut k, &mut v, hd, nh * t, nkv * t,
8280                            pos_d, nh, nkv, base, 1.0, ff, eps)?;
8281        let kvl = cache.kv[il].as_mut().unwrap();
8282        let base_len = kvl.len;
8283        e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, base_len, t,
8284                                   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()))?;
8285        kvl.len += t;
8286        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
8287        let mut attn = e.uninit(t * nh * hd)?;
8288        // ROWS twin when no window offset is in play (globals are hd512-ineligible; SWA rows
8289        // under the window need no offset): ONE launch, per-row causal == the per-token loop.
8290        let rows_ok = (hd == 256 && base_len + 1 >= crate::fa_vec_min_tkv())
8291            // gemma globals: hd512 rows twin in the dpl16 vec regime (row 0 gates the batch);
8292            // decode rides the SAME symbol at t=1 (parity law).
8293            || (hd == 512 && !swa && base_len + 1 >= crate::fa512_min_tkv());
8294        if rows_ok && (!swa || base_len + t <= win) {
8295            let k_view = e.view_u8(&kvl.k, (base_len + t) * kvl.k_tok_bytes);
8296            let v_view = e.view_u8(&kvl.v, (base_len + t) * kvl.v_tok_bytes);
8297            if hd == 512 {
8298                // device-len twin: sync the counter to the verify base (async arg-store).
8299                e.i32_set_k(&mut kvl.len_d, base_len as i32)?;
8300                e.fa_decode_rows(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, base_len, t,
8301                                 scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
8302                                 Some((&kvl.len_d, 0)), false,
8303                                 swa && crate::Engine::wkv_on(), None)?;
8304            } else {
8305                // hd256: the SAME v4_dc symbol the burst verify launches (PARITY LAW — the
8306                // host-base rows_v4 twin compiles apart from v4_dc and the two-symbol split
8307                // drifted the burst's persisted KV at il=8; one symbol, counter arg-stored).
8308                e.i32_set_k(&mut kvl.len_d, base_len as i32)?;
8309                e.fa_decode_rows_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8310                                    &kvl.len_d, base_len + t, t, scale,
8311                                    kvl.k_tok_bytes, kvl.v_tok_bytes, 0,
8312                                    swa && crate::Engine::wkv_on())?;
8313            }
8314            return Ok(e.matmul(&fa.wo, &attn, t)?);
8315        }
8316        // WINDOWED rows twin (deep ctx, every row fully windowed): one launch, ABSOLUTE-index
8317        // per-row geometry over the prefix view. PARITY LAW (2026-07-10 root-cause): textually
8318        // identical kernels do NOT compile bit-identically (nvcc unrolls fa_decode_vec_q 2x vs
8319        // its rows_w clone — SASS-proven; the unpinned score `+=` chain then rounds apart), so
8320        // decode-vs-verify parity comes from BOTH sides launching THIS SAME rows_w kernel
8321        // (decode passes t=1) — bitwise equal per position by symbol identity, any lane.
8322        // MEMRA_GEMMA_ROWS_W=0 -> per-token loop (decode falls back to fa_decode views too).
8323        if hd == 256 && swa && base_len + 1 >= win
8324            && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8325            let k_view = e.view_u8(&kvl.k, (base_len + t) * kvl.k_tok_bytes);
8326            let v_view = e.view_u8(&kvl.v, (base_len + t) * kvl.v_tok_bytes);
8327            e.i32_set_k(&mut kvl.len_d, base_len as i32)?;
8328            e.fa_decode_rows_w(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, &kvl.len_d, 0,
8329                               t, scale, win, kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
8330            return Ok(e.matmul(&fa.wo, &attn, t)?);
8331        }
8332        for i in 0..t {
8333            let avail = base_len + i + 1;
8334            let (off_tok, t_kv) = if swa && avail > win { (avail - win, win) } else { (0, avail) };
8335            let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
8336                                         (off_tok + t_kv) * kvl.k_tok_bytes);
8337            let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
8338                                         (off_tok + t_kv) * kvl.v_tok_bytes);
8339            let qi = e.view(&q, t * nh * hd);
8340            let q_row = qi.slice(i * nh * hd..(i + 1) * nh * hd);
8341            let mut q_one = e.uninit(nh * hd)?;
8342            e.copy_view_into(&mut q_one, 0, &q_row, nh * hd)?;
8343            let mut a_one = e.uninit(nh * hd)?;
8344            // straddle rounds: windowed rows must ride the SAME rows_w kernel decode uses
8345            // (parity law above); global hd512 rows past the fa512 floor likewise ride the
8346            // rows_dpl16 twin; remaining rows keep the gated fa_decode pair.
8347            if swa && avail > win && hd == 256
8348                && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8349                let kp = e.view_u8(&kvl.k, avail * kvl.k_tok_bytes);
8350                let vp = e.view_u8(&kvl.v, avail * kvl.v_tok_bytes);
8351                e.i32_set_k(&mut kvl.len_d, (avail - 1) as i32)?;
8352                e.fa_decode_rows_w(&q_one, &kp, &vp, &mut a_one, hd, nh, nkv, &kvl.len_d, 0,
8353                                   1, scale, win, kvl.k_tok_bytes, kvl.v_tok_bytes, None)?;
8354            } else if !swa && hd == 512 && avail >= crate::fa512_min_tkv()
8355                && std::env::var("MEMRA_GEMMA_ROWS_W").as_deref() != Ok("0") {
8356                let kp = e.view_u8(&kvl.k, avail * kvl.k_tok_bytes);
8357                let vp = e.view_u8(&kvl.v, avail * kvl.v_tok_bytes);
8358                e.i32_set_k(&mut kvl.len_d, (avail - 1) as i32)?;
8359                e.fa_decode_rows(&q_one, &kp, &vp, &mut a_one, hd, nh, nkv, avail - 1, 1,
8360                                 scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
8361                                 Some((&kvl.len_d, 0)), false, false, None)?;
8362            } else {
8363                e.fa_decode_kvmod(&q_one, &k_view, &v_view, &mut a_one, hd, nh, nkv, t_kv, scale,
8364                            kvl.k_tok_bytes, kvl.v_tok_bytes, swa && crate::Engine::wkv_on())?;
8365            }
8366            e.copy_into(&mut attn, i * nh * hd, &a_one, nh * hd)?;
8367        }
8368        Ok(e.matmul(&fa.wo, &attn, t)?)
8369    }
8370
8371    /// gemma4 T=1 decode step: R8 layer graph over the cache; returns (softcapped logits host,
8372    /// h_seed = pre-output_norm hidden). Advances cache.pos.
8373    pub(crate) fn gemma4_decode_step_h(&self, e: &Engine, token: u32, cache: &mut Cache)
8374                                       -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8375        // M1-PP2 door (crate::pp): 2-stage split with an explicit activation handoff.
8376        // Default OFF — unset env means this branch is never taken. The gemma4 arm stays
8377        // 2-stage in M2 (the N-stage gate model is the generic-arm 9B); N>2 warns + runs
8378        // unsplit rather than guessing a fence.
8379        if let Some(split) = crate::pp::pp2_split(self.layers.len()) {
8380            return self.gemma4_decode_step_h_pp2(e, token, cache, split);
8381        }
8382        if crate::pp::pp_cuts(self.layers.len()).is_some() {
8383            crate::pp::warn_unwired_once("gemma4 eager decode (N>2)");
8384        }
8385        let n_embd = self.cfg.n_embd as usize;
8386        let eps = self.cfg.rms_eps;
8387        let pos_d = e.htod_i32(&[cache.pos as i32])?;
8388        let mut x = e.htod(&self.embd.gather(n_embd, &[token]))?;
8389        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
8390        // cross-layer fusion: each tail's closing add+scale also EMITS the next layer's
8391        // attn-normed input pre-quantized q8_1 (the mixer consumes only quantized matmuls).
8392        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8393        let n_layers = self.layers.len();
8394        for (il, layer) in self.layers.iter().enumerate() {
8395            let (hq, hdq) = match h_carry.take() {
8396                Some(p) => p,
8397                None => e.rms_norm_q8_1(&x, self.layers[0].attn_norm.float_data(), n_embd, 1, eps)?,
8398            };
8399            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8400            let o = self.gemma4_decode_attn(e, fa, il, &hq, &hdq, &pos_d, cache)?;
8401            let mut cur = e.uninit(n_embd)?;
8402            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, 1, eps)?;
8403            let next_norm = if il + 1 < n_layers {
8404                Some(self.layers[il + 1].attn_norm.float_data())
8405            } else { None };
8406            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, 1, next_norm)?;
8407            x = xn;
8408            h_carry = hn;
8409        }
8410        let mut hn = e.uninit(n_embd)?;
8411        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
8412        let h_seed = e.clone_dtod(&x)?;
8413        let mut ld = e.matmul(&self.output, &hn, 1)?;
8414        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
8415        e.softcap(&mut ld, cap, self.output.out_features())?;   // R4 on device (262k host tanh ~ms/step)
8416        self.gemma4_suppress(e, &mut ld, 1)?;
8417        let logits = e.dtoh(&ld)?;
8418        cache.pos += 1;
8419        Ok((logits, h_seed))
8420    }
8421
8422    /// M1-PP2 stage subgraph (gemma4 arm): layers [lo, hi) of the gemma4 T=1 walk with the
8423    /// pre-quantized next-norm carry LOCAL to the range. Enters with a materialized residual
8424    /// `x` (the range head runs its own `rms_norm_q8_1` against ITS layer's attn_norm — for
8425    /// lo == 0 that is exactly the unsplit loop's il==0 arm); exits with the residual
8426    /// materialized (range tail passes next_norm = None, exactly the unsplit last-layer arm).
8427    /// Bit-identity of the cut relies on the kernel-check-pinned `add_scale_rms_norm_q8_1 ==
8428    /// add_scale then rms_norm_q8_1` identity (`pp2-gate` verifies end-to-end).
8429    fn gemma4_decode_layers(&self, e: &Engine, mut x: CudaSlice<f32>, lo: usize, hi: usize,
8430                            pos_d: &CudaSlice<i32>, cache: &mut Cache)
8431                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8432        let n_embd = self.cfg.n_embd as usize;
8433        let eps = self.cfg.rms_eps;
8434        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
8435        for il in lo..hi {
8436            let layer = &self.layers[il];
8437            let (hq, hdq) = match h_carry.take() {
8438                Some(p) => p,
8439                // range head: il == lo — norm against THIS layer's attn_norm.
8440                None => e.rms_norm_q8_1(&x, self.layers[il].attn_norm.float_data(), n_embd, 1, eps)?,
8441            };
8442            let Mixer::Full(fa) = &layer.mixer else { panic!("gemma4 layer {il} not full-attn") };
8443            let o = self.gemma4_decode_attn(e, fa, il, &hq, &hdq, pos_d, cache)?;
8444            let mut cur = e.uninit(n_embd)?;
8445            e.rms_norm(&o, layer.post_attn_norm.float_data(), &mut cur, n_embd, 1, eps)?;
8446            let next_norm = if il + 1 < hi {
8447                Some(self.layers[il + 1].attn_norm.float_data())
8448            } else { None };
8449            let (xn, hn) = self.gemma4_layer_tail_add_nq(e, layer, &cur, &x, 1, next_norm)?;
8450            x = xn;
8451            h_carry = hn;
8452        }
8453        Ok(x)
8454    }
8455
8456    /// M1-PP2 (increment 2): `gemma4_decode_step_h` as TWO stage subgraphs, each on its
8457    /// own stream (and device, under MEMRA_PP_DEVICES) with the transport-selected
8458    /// boundary handoff — same choreography as the generic arm (decode.rs), same
8459    /// ownership contract (crate::pp). Stage 0 = embed+scale + layers [0, split);
8460    /// stage 1 = layers [split, n) + output_norm + softcapped head.
8461    /// MEMRA_PP_STREAMS=0 = the increment-1 same-stream seam. Gate: `pp2-gate`.
8462    fn gemma4_decode_step_h_pp2(&self, e: &Engine, token: u32, cache: &mut Cache, split: usize)
8463                                -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8464        if crate::pp::pp2_streams_off() {
8465            return self.gemma4_decode_step_h_pp2_samestream(e, token, cache, split);
8466        }
8467        let rt = crate::pp::Pp2Rt::get(e)?;
8468        let e0 = rt.engine(0, e);
8469        let e1 = rt.engine(1, e);
8470        let n_embd = self.cfg.n_embd as usize;
8471        let eps = self.cfg.rms_eps;
8472
8473        // ---- STAGE 0 (its own stream): embed + sqrt(n_embd) scale + layers [0, split) ----
8474        let (pos_d, slot) = {
8475            let _st0 = rt.enter(0);
8476            let pos_d = e0.htod_i32(&[cache.pos as i32])?;
8477            let mut x = e0.htod(&self.embd.gather(n_embd, &[token]))?;
8478            e0.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
8479            let x = self.gemma4_decode_layers(e0, x, 0, split, &pos_d, cache)?;
8480            let slot = rt.tx(0, &x, n_embd)?;
8481            (pos_d, slot)
8482        };
8483
8484        // ---- STAGE 1 (its own stream): RX + layers [split, n) + softcapped head ----
8485        let _st1 = rt.enter(1);
8486        let x = rt.rx(0, slot, n_embd)?;
8487        let x = self.gemma4_decode_layers(e1, x, split, self.layers.len(), &pos_d, cache)?;
8488
8489        let mut hn = e1.uninit(n_embd)?;
8490        e1.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
8491        let h_seed = e1.clone_dtod(&x)?;
8492        let mut ld = e1.matmul(&self.output, &hn, 1)?;
8493        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
8494        e1.softcap(&mut ld, cap, self.output.out_features())?;
8495        self.gemma4_suppress(e1, &mut ld, 1)?;
8496        let logits = e1.dtoh(&ld)?;
8497        cache.pos += 1;
8498        Ok((logits, h_seed))
8499    }
8500
8501    /// MEMRA_PP_STREAMS=0 rollback seam: the increment-1 gemma4 pp2 body verbatim — both
8502    /// stage subgraphs on the ambient compute stream, boundary = two plain dtod copies.
8503    fn gemma4_decode_step_h_pp2_samestream(&self, e: &Engine, token: u32, cache: &mut Cache,
8504                                           split: usize)
8505                                           -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8506        let n_embd = self.cfg.n_embd as usize;
8507        let eps = self.cfg.rms_eps;
8508        let pos_d = e.htod_i32(&[cache.pos as i32])?;
8509
8510        // ---- STAGE 0: embed + sqrt(n_embd) scale + layers [0, split) ----
8511        let mut x = e.htod(&self.embd.gather(n_embd, &[token]))?;
8512        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
8513        let x = self.gemma4_decode_layers(e, x, 0, split, &pos_d, cache)?;
8514
8515        // ---- STAGE BOUNDARY: explicit [n_embd] activation handoff (TX copy, RX copy) ----
8516        let boundary_tx = e.clone_dtod(&x)?;
8517        let boundary_rx = e.clone_dtod(&boundary_tx)?;
8518
8519        // ---- STAGE 1: layers [split, n) + output_norm + softcapped head ----
8520        let x = self.gemma4_decode_layers(e, boundary_rx, split, self.layers.len(), &pos_d, cache)?;
8521
8522        let mut hn = e.uninit(n_embd)?;
8523        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
8524        let h_seed = e.clone_dtod(&x)?;
8525        let mut ld = e.matmul(&self.output, &hn, 1)?;
8526        let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
8527        e.softcap(&mut ld, cap, self.output.out_features())?;
8528        self.gemma4_suppress(e, &mut ld, 1)?;
8529        let logits = e.dtoh(&ld)?;
8530        cache.pos += 1;
8531        Ok((logits, h_seed))
8532    }
8533}
8534
8535// ============================ step35 (Step-3.7-Flash) ==================================
8536// Node-for-node vs llama.cpp src/models/step35.cpp:216-300. WHY THIS IS A DEDICATED MIXER
8537// FAMILY and not a few branches inside the generic `full_attn*` chain:
8538//
8539//   1. `n_head` IS PER LAYER (`step35.attention.head_count` is an ARRAY: 64 on full-attn
8540//      layers, 96 on SWA). Every generic site reads the `cfg.n_head` scalar, so wq/wo/attn_gate
8541//      shapes and the FA head counts would be wrong on 33 of 45 layers.
8542//   2. `cfg.rope_dim_count` is 128 for this arch, but FULL-attn layers rotate only 64 dims
8543//      (upstream halves `n_rot_full` after the generic loader defaults it). A generic mixer
8544//      would rotate 128 dims on the full layers — silently wrong, plausible-looking logits.
8545//   3. Dual rope base (5e6 full / 1e4 SWA) + `rope_freqs.weight` on FULL layers ONLY.
8546//   4. SWA 3:1 (`sliding_window` 512, pattern [false,true,true,true]).
8547//   5. The head-wise gate is a SEPARATE `attn_gate.weight [n_embd, n_head_l]` (one pre-sigmoid
8548//      scalar per head, broadcast over head_dim) applied to the attention output BEFORE wo —
8549//      not the qwen35 fused-in-wq per-DIM gate that `attn_out_gate()`/`q_gate_split` handle.
8550//      Its input is the POST-attn_norm hidden (`cur`), not the residual.
8551//
8552// Attention scale is the DEFAULT 1/sqrt(n_embd_head_k) (step35.cpp:255) — NOT gemma4's 1.0.
8553impl HybridModel {
8554    /// Step35's declarative geometry row. Missing rows are artifact/config errors; never
8555    /// synthesize a drafter or trunk layer from a neighboring class.
8556    pub(crate) fn step35_geom(&self, il: usize) -> memra_gguf::config::LayerGeometry {
8557        let geometry = self.cfg.layer_geometry(il as u32)
8558            .unwrap_or_else(|| panic!("step35 layer {il} has no geometry-table row"));
8559        debug_assert_eq!(
8560            geometry.attention_gate,
8561            memra_gguf::config::AttentionGateKind::SeparateHead
8562        );
8563        geometry
8564    }
8565
8566    /// step35 attention core: everything from the q/k/v projection outputs through the head-wise
8567    /// gate, returning the GATED attention output PRE-`wo` (the caller runs wo, so this composes
8568    /// with both the plain `matmul(&fa.wo, ..)` sites and the f16/into-slab GEMM sites).
8569    ///
8570    /// `hg` = the POST-attn_norm hidden state (upstream's `cur`) — the gate projection's input
8571    /// on single-sequence paths. `gt_pre` supplies the already-projected per-head gate for a
8572    /// cross-request batch; exactly one of `hg` or `gt_pre` must be present.
8573    /// `cache`:
8574    ///   * `Some` => PRIME mode: append this chunk's post-rope K / raw V rows into the resident
8575    ///     quantized cache and attend THROUGH the cache view, exactly like the generic
8576    ///     `full_attn_prime_fa_dispatch` (quantize-then-attend on chunk 0 too, so chunk size
8577    ///     cannot decide where a precision edge falls — the grain-free chunk-invariance
8578    ///     contract, lane/chunkinv-flip).
8579    ///   * `None` => pure prefill (forward/forward_last/t2probe): attend over this batch's f32
8580    ///     q/k/v, no cache side effect.
8581    ///
8582    /// SWA WINDOW, and why prefill needs `sdpa_naive_w_quantized_view`: the view is trimmed to
8583    /// the oldest key ANY query in this chunk can reach (`off = base_len - (win-1)`), which
8584    /// bounds the view at `win-1+t` rows, but the mask is still required — inside the chunk,
8585    /// query `qt` may only see view keys `[qt, qt+win-1]`, so the earlier keys the trimmed view
8586    /// still contains must be masked per query. memra's window convention
8587    /// (`sdpa_naive_w_f32`: mask `t < q_pos-(window-1)`, `q_pos = (T_kv-T)+qt`) is bit-for-bit
8588    /// upstream's `LLAMA_SWA_TYPE_STANDARD` (`llama-hparams.h:359`: mask `p1-p0 >= n_swa`), and
8589    /// step35.cpp:6 sets exactly that swa_type — verified verbatim on both sides.
8590    ///
8591    /// Note the f32 `sdpa_naive_w` floor's shared memory is `t_kv*4` bytes, so the SWA arm needs
8592    /// `t_kv = win-1+t <= 12287` — i.e. it relies on chunked prefill (MEMRA_PRIME_CHUNK, default
8593    /// 4096). A monolithic 32k prime would exceed the 48 KiB dynamic-smem default.
8594    ///
8595    /// SWA ARM SELECTION IS KEYED ON `seq_end`, NOT ON THE CHUNK'S OWN `t_kv` (lane/step35-chunkfix,
8596    /// 2026-08-07). `seq_end` = the ABSOLUTE end position of the whole prime call
8597    /// (`cache.pos + prompt_len` at entry; `t` on the cacheless prefill path) — a property of the
8598    /// REQUEST, identical at every MEMRA_PRIME_CHUNK value. The old predicate `swa && t_kv > win`
8599    /// read the chunk's own extent, which made kernel selection — and therefore the logits, the
8600    /// hidden rows, and the generated text — a function of the chunk size:
8601    ///   a chunk [b,e) has off = max(0, b-(win-1)), t_kv = e-off, so b <= win-1 => off=0 => FA iff
8602    ///   e <= win, while every later chunk has t_kv = t+(win-1) > win. The FA rows were therefore a
8603    ///   contiguous PREFIX [0,P) with P = c*floor(win/c) for c <= win (else 0), and the output
8604    ///   depended only on P. Measured (research/step37-p2-20260806, closed-form receipt
8605    ///   `raw/chunkinv-step35-GAP2-CONFIRMED-20260807.txt`): at T=4883, c=512 and c=64 (P=512) are
8606    ///   byte-identical to each other but DIFFER from the c=4096 default (P=0) by maxdiff 1.813e0
8607    ///   with greedy text diverging at step 6; c=513 (P=0) is bit-identical to the default. A
8608    ///   one-token change in a documented machine-config knob changed the answer.
8609    /// So the pre-fix comment "same cache bytes, same numeric class" was false as written: same
8610    /// bytes, DIFFERENT numeric class — swapping `fa_prefill_view_ws` for the f32 windowed floor on
8611    /// the same rows moves the logits by ~1.8.
8612    ///
8613    /// Keying on `seq_end` makes P identically 0 for every chunk size, so MEMRA_PRIME_CHUNK is a
8614    /// pure memory/transient knob again (research/step35-chunkfix-20260807). It is
8615    /// correct-by-construction rather than a tolerance argument — the windowed kernel computes the
8616    /// same masked attention the FA arm computed (for e <= win the window mask is a no-op under
8617    /// causal, which is exactly why FA was legal there), it is now simply the ONLY arm used once
8618    /// the request passes the window. It also cannot move the shipped default: at chunk=4096 every
8619    /// chunk of a `seq_end > win` prime ALREADY had t_kv > win (chunk 0 has t_kv = min(chunk,
8620    /// seq_end) > win; every later chunk has t_kv >= t+win-1 > win since `PRIME_MIN_T` keeps
8621    /// t >= 16), and a `seq_end <= win` prime keeps every chunk on FA exactly as before — so this
8622    /// is a no-op on both default regimes and only removes the FA prefix at small chunk values.
8623    /// The `t_kv <= 12287` smem ceiling is respected: the chunks whose arm changes are precisely
8624    /// those with t_kv <= win = 512.
8625    #[allow(clippy::too_many_arguments)]
8626    fn step35_attn_pre_wo(&self, e: &Engine, fa: &FullAttnLayer, mut g3: Vec<CudaSlice<f32>>,
8627                          hg: Option<&CudaSlice<f32>>, gt_pre: Option<&CudaSlice<f32>>,
8628                          pos_d: &CudaSlice<i32>, t: usize,
8629                          cache: Option<&mut Cache>, il: usize, seq_end: usize)
8630                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8631        let geometry = self.step35_geom(il);
8632        let hd = geometry.head_dim_k as usize;
8633        let nkv = geometry.n_head_kv as usize;
8634        let nh = geometry.n_head as usize;
8635        let rbase = geometry.rope_base;
8636        let scale = geometry.attention_scale();
8637        let swa = geometry.window.is_some();
8638        let eps = self.cfg.rms_eps;
8639        let win = geometry.window.unwrap_or(0) as usize;
8640        let n_rot = geometry.n_rot as usize;
8641
8642        let v = g3.pop().unwrap();
8643        let k0 = g3.pop().unwrap();
8644        let q0 = g3.pop().unwrap();
8645
8646        // q/k RMSNorm over head_dim rows (attn_q_norm/attn_k_norm [128] F32), then the
8647        // per-layer PARTIAL NEOX rope: n_rot = 64 on full layers (dims 64..127 pass through
8648        // unrotated), 128 on SWA. rope_freqs (llama3-style per-dim factors) on FULL only.
8649        let mut q = e.uninit(t * nh * hd)?;
8650        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh * t, eps)?;
8651        let mut k = e.uninit(t * nkv * hd)?;
8652        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv * t, eps)?;
8653        let ff = if geometry.rope_factors {
8654            self.step35_aux.as_ref().and_then(|a| a.rope_freqs.as_ref())
8655        } else {
8656            None
8657        };
8658        e.rope_neox2(&mut q, &mut k, pos_d, hd, n_rot, nh, nkv, t, rbase, 1.0, ff)?;
8659
8660        let mut attn = e.uninit(t * nh * hd)?;
8661        match cache {
8662            Some(cache) => {
8663                let base_len = cache.kv[il].as_ref().unwrap().len;
8664                // Read per layer call, never in a measured default.
8665                let legacy_tkv = std::env::var("MEMRA_STEP35_SWA_TKV").as_deref() == Ok("1");
8666                let legacy_calllocal =
8667                    std::env::var("MEMRA_PRIME_CALLLOCAL").as_deref() == Ok("1");
8668                let off = if swa {
8669                    let raw = base_len.saturating_sub(win - 1);
8670                    if legacy_tkv || legacy_calllocal { raw } else { raw & !31usize }
8671                } else {
8672                    0
8673                };
8674                {
8675                    let kvl = cache.kv[il].as_mut().unwrap();
8676                    assert!(kvl.len + t <= cache.max_ctx, "step35 prime: KV overflow");
8677                    let write_row = e.prepare_kv_append(kvl, off, t)?;
8678                    e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, write_row, t,
8679                                               kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes,
8680                                               kvl.v_tok_bytes, crate::Engine::kv_fp8_on())?;
8681                    kvl.len += t;
8682                    let new_len = kvl.len as i32;
8683                    e.set_i32_one(&mut kvl.len_d, new_len)?;
8684                }
8685                let kvl = cache.kv[il].as_ref().unwrap();
8686                // Both segmentation seams restore the FULL pre-fix arithmetic: their legacy
8687                // arm predicate (`t_kv` below, per-call `seq_end` in prime_cache) AND the
8688                // unaligned view offset here. Both halves are load-bearing for the canaries:
8689                // on the FA default the predicate arms agree bitwise wherever they can differ
8690                // (a t_kv<=win view has no maskable key, so windowed==unwindowed FA bit-for-bit).
8691                // That made predicate-only seams INERT under Lever A — first chunkinv35c, then
8692                // tickinv35c. The raw offset restores the live segmentation-variant mechanism
8693                // on the current FA path: its tile grid starts at the chunk/call boundary.
8694                // SWA: trim the view to the oldest key any query in this chunk can reach —
8695                // ALIGNED DOWN to the FA tile size (BK=32). The raw trim is chunk-DEPENDENT
8696                // (off = base_len-(win-1), and base_len is a chunk boundary), and the FA
8697                // kernel's online-softmax recurrence groups keys into BK tiles relative to
8698                // the VIEW START — so an unaligned off regroups the same absolute keys into
8699                // different tiles at different chunk sizes = different (m,l) rounding =
8700                // chunk-dependent bits. chunkinv35 caught exactly this on the first FA-arm
8701                // battery (first_div == chunk size; raw/leverA-gates-20260807T135541Z.log).
8702                // Aligning off to 32 pins tiles to ABSOLUTE key positions for every chunk
8703                // size; the <=31 extra leading keys are older than EVERY query's window
8704                // (all queries sit at >= base_len, so keys < base_len-(win-1) are masked
8705                // for all of them) and a fully-masked key is an exact-0.0 no-op in both
8706                // kernels (NEG_INF -> p=0.0; l+=0.0 and O+=0.0 are bitwise identity), so
8707                // the floor arm's bits do not move either (gated: G2f, battery 2).
8708                let t_kv = base_len + t - off;
8709                let physical = kvl.physical_rows(off, off + t_kv)?;
8710                let k_view = e.view_u8_range(&kvl.k, physical.start * kvl.k_tok_bytes,
8711                                             physical.end * kvl.k_tok_bytes);
8712                let v_view = e.view_u8_range(&kvl.v, physical.start * kvl.v_tok_bytes,
8713                                             physical.end * kvl.v_tok_bytes);
8714                // CHUNK-INVARIANT PREDICATE: `seq_end` (the request's absolute end position), not
8715                // this chunk's `t_kv`. See the doc note — keying on t_kv made P = c*floor(win/c)
8716                // rows take FA and the output a function of MEMRA_PRIME_CHUNK.
8717                // MEMRA_STEP35_SWA_TKV=1 is the ROLLBACK SEAM to the pre-fix arithmetic — BOTH
8718                // halves: this predicate AND the unaligned view offset above (`legacy_tkv`).
8719                // It is what gives the step35 chunkinv gate its canary teeth: chunk-VARIANT by
8720                // construction, so the invariance assertion MUST break under it (the seam whose
8721                // absence made the original canary inert — GAP 1 in research/step37-p2-20260806;
8722                // and a predicate-only seam went inert AGAIN under the FA default, battery 2's
8723                // CANARY UNEXPECTEDLY MATCHED — see the offset comment). Read per call, not
8724                // cached (probes flip it in-process). Never on in a measured default run.
8725                let swa_naive = if legacy_tkv { t_kv > win } else { seq_end > win };
8726                if swa && swa_naive {
8727                    // Windowed mask needed (see the doc note). DEFAULT since lane/pp-prefill
8728                    // 2026-08-07: the windowed hd128 FA stamp (`fa_prefill_view_ws_w_hd128`) —
8729                    // the anatomy profile measured the f32 floor at 565 ms/layer on a pp4096
8730                    // (41% of the whole prime) while the unwindowed hd128 FA family did the
8731                    // strictly harder causal-4096 in 3.3 ms. NOTE t_kv can be <= win here
8732                    // (a chunk-0 view on a small chunk); the windowed kernel handles that
8733                    // identically to the unwindowed one modulo the mask, which is the point.
8734                    // NEW NUMERIC CLASS vs the floor (bf16-MMA online softmax vs f32 serial),
8735                    // selected on `seq_end` like every arm here, so the class is uniform for
8736                    // the whole request at every MEMRA_PRIME_CHUNK — chunkinv holds by the
8737                    // same construction as the chunkfix. MEMRA_STEP35_SWA_FA=0 = rollback to
8738                    // the f32 floor (the previous numeric config, kept as the A/B seam).
8739                    if std::env::var("MEMRA_STEP35_SWA_FA").as_deref() == Ok("0") {
8740                        e.sdpa_naive_w_quantized_view(&q, &k_view, &v_view, &mut attn, hd, nh,
8741                                                      nkv, t, t_kv, scale, true, win,
8742                                                      kvl.k_tok_bytes, kvl.v_tok_bytes)?;
8743                    } else {
8744                        e.fa_prefill_view_ws_w_hd128(&q, &k_view, &v_view, &mut attn, hd, nh,
8745                                                     nkv, t, t_kv, scale, true, win,
8746                                                     kvl.k_tok_bytes, kvl.v_tok_bytes)?;
8747                    }
8748                } else if std::env::var("MEMRA_NOFA").is_ok() {
8749                    e.sdpa_naive_quantized_view(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8750                                                t, t_kv, scale, true,
8751                                                kvl.k_tok_bytes, kvl.v_tok_bytes)?;
8752                } else {
8753                    // seq_end <= win (or a full-attn layer): no query in the WHOLE request can
8754                    // reach past the window, so the window mask is a no-op under causal and every
8755                    // chunk rides the hd128 dequant-once FA prefill — one arm for the whole
8756                    // request either way, which is what makes the chunk size arithmetic-free.
8757                    e.fa_prefill_view_ws(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
8758                                         t, t_kv, scale, true,
8759                                         kvl.k_tok_bytes, kvl.v_tok_bytes,
8760                                         crate::Engine::kv_fp8_on())?;
8761                }
8762            }
8763            None => {
8764                // Cacheless prefill (forward/forward_last/t2probe) is MONOLITHIC — there is no
8765                // chunk loop on this path, so seq_end == t and the predicate is unchanged. The
8766                // assert pins that: if a chunked cacheless prefill is ever added, it must thread
8767                // seq_end here too or it re-opens the same door.
8768                debug_assert_eq!(seq_end, t, "step35 cacheless prefill is monolithic (seq_end == t)");
8769                if swa && seq_end > win {
8770                    e.sdpa_naive_w(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true, win)?;
8771                } else if std::env::var("MEMRA_NOFA").is_ok() {
8772                    e.sdpa_naive(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
8773                } else {
8774                    e.fa_prefill(&q, &k, &v, &mut attn, hd, nh, nkv, t, t, scale, true)?;
8775                }
8776            }
8777        }
8778
8779        // HEAD-WISE GATE (step35.cpp:267-285): gate = attn_gate(cur) -> [t, n_head_l];
8780        // attn *= sigmoid(gate) broadcast over head_dim. BEFORE wo.
8781        let gw = fa.attn_gate.as_ref()
8782            .ok_or("step35 layer is missing attn_gate.weight (head-wise attention gate)")?;
8783        let gt_owned = if gt_pre.is_none() {
8784            Some(e.matmul(
8785                gw,
8786                hg.ok_or("step35 attention needs hg when gt_pre is absent")?,
8787                t,
8788            )?)
8789        } else {
8790            None
8791        };
8792        let gt = gt_pre.or(gt_owned.as_ref()).unwrap();
8793        let mut ag = e.uninit(t * nh * hd)?;
8794        e.attn_head_gate(&attn, gt, &mut ag, None, hd, nh, t)?;
8795        Ok(ag)
8796    }
8797
8798    /// step35 PREFILL mixer, no cache side effect (the `full_attn` contract: `forward`,
8799    /// `forward_last`, t2probe). Post-`wo`.
8800    pub(crate) fn step35_attn(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>,
8801                              pos_d: &CudaSlice<i32>, t: usize, il: usize)
8802                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8803        let g3 = e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?;
8804        // Monolithic path: the request ends at t (no chunk loop). See step35_attn_pre_wo's note.
8805        let ag = self.step35_attn_pre_wo(e, fa, g3, Some(h), None, pos_d, t, None, il, t)?;
8806        Ok(e.matmul(&fa.wo, &ag, t)?)
8807    }
8808
8809    /// step35 PRIME mixer (the `full_attn_prime` contract: append this chunk's K/V into the
8810    /// resident quantized cache, attend through the cache view). Post-`wo`.
8811    ///
8812    /// `seq_end` = the ABSOLUTE end position of the whole prime request (chunk-invariant); it
8813    /// selects the SWA arm. See `step35_attn_pre_wo`'s doc note for why it cannot be this chunk's
8814    /// own extent.
8815    #[allow(clippy::too_many_arguments)]
8816    pub(crate) fn step35_attn_prime(&self, e: &Engine, fa: &FullAttnLayer, h: &CudaSlice<f32>,
8817                                    hx: Option<&CudaSlice<u8>>, pos_d: &CudaSlice<i32>, t: usize,
8818                                    cache: &mut Cache, il: usize, seq_end: usize)
8819                                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8820        let g3 = match hx {
8821            Some(xh) => e.matmul_group_xh(&[&fa.wq, &fa.wk, &fa.wv], h, xh, t)?,
8822            None => e.matmul_group(&[&fa.wq, &fa.wk, &fa.wv], h, t)?,
8823        };
8824        let ag = self.step35_attn_pre_wo(
8825            e,
8826            fa,
8827            g3,
8828            Some(h),
8829            None,
8830            pos_d,
8831            t,
8832            Some(cache),
8833            il,
8834            seq_end,
8835        )?;
8836        Ok(e.matmul(&fa.wo, &ag, t)?)
8837    }
8838
8839    /// step35 T=1 decode attention (post-`wo`, matching `full_attn_decode_pre`'s contract).
8840    /// `pre_q` = the attn-input norm's q8_1 pair when the caller took the norm-fusion lever
8841    /// (then `h` is a zero-length placeholder and EVERY projection here — including the gate —
8842    /// must be on the q8_1 fast path; `mixer_in_q8_1_fast` enforces that for step35 by also
8843    /// requiring `attn_gate`).
8844    ///
8845    /// SWA decode is a token-aligned VIEW OFFSET into the quantized cache (the gemma4 R6
8846    /// pattern): keys carry absolute rope and the mask is purely positional, so the single
8847    /// query at `len-1` attending the last `win` rows IS the windowed result — no mask kernel.
8848    #[allow(clippy::too_many_arguments)]
8849    pub(crate) fn step35_decode_attn(&self, e: &Engine, fa: &FullAttnLayer, il: usize,
8850                          h: &CudaSlice<f32>,
8851                          pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
8852                          pos_d: &CudaSlice<i32>, cache: &mut Cache)
8853                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8854        let geometry = self.step35_geom(il);
8855        let hd = geometry.head_dim_k as usize;
8856        let nkv = geometry.n_head_kv as usize;
8857        let nh = geometry.n_head as usize;
8858        let rbase = geometry.rope_base;
8859        let scale = geometry.attention_scale();
8860        let swa = geometry.window.is_some();
8861        let eps = self.cfg.rms_eps;
8862        let win = geometry.window.unwrap_or(0) as usize;
8863        let n_rot = geometry.n_rot as usize;
8864        let n_embd = self.cfg.n_embd as usize;
8865        let gw = fa.attn_gate.as_ref()
8866            .ok_or("step35 layer is missing attn_gate.weight (head-wise attention gate)")?;
8867
8868        let (q0, k0, v0, gt) = match pre_q {
8869            Some((hq, hdq)) => {
8870                debug_assert!(e.uses_q8_1_fast(gw),
8871                    "step35 pre-quantized decode requires attn_gate on the q8_1 fast path \
8872                     (h is a zero-length placeholder here) — see mixer_in_q8_1_fast");
8873                let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hdq)? {
8874                    Some(t3) => t3,
8875                    None => (e.matmul_pre(&fa.wq, hq, hdq, h, 1)?,
8876                             e.matmul_pre(&fa.wk, hq, hdq, h, 1)?,
8877                             e.matmul_pre(&fa.wv, hq, hdq, h, 1)?),
8878                };
8879                let gt = e.matmul_pre(gw, hq, hdq, h, 1)?;
8880                (a, b, c, gt)
8881            }
8882            None => {
8883                if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk)
8884                    && e.uses_q8_1_fast(&fa.wv) && e.uses_q8_1_fast(gw) {
8885                    let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
8886                    let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
8887                        Some(t3) => t3,
8888                        None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
8889                                 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
8890                                 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?),
8891                    };
8892                    let gt = e.matmul_pre(gw, &hq, &hdq, h, 1)?;
8893                    (a, b, c, gt)
8894                } else {
8895                    (e.matmul(&fa.wq, h, 1)?, e.matmul(&fa.wk, h, 1)?,
8896                     e.matmul(&fa.wv, h, 1)?, e.matmul(gw, h, 1)?)
8897                }
8898            }
8899        };
8900
8901        let mut q = e.uninit(nh * hd)?;
8902        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
8903        let mut k = e.uninit(nkv * hd)?;
8904        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
8905        let ff = if swa { None } else {
8906            self.step35_aux.as_ref().and_then(|a| a.rope_freqs.as_ref())
8907        };
8908        e.rope_neox2(&mut q, &mut k, pos_d, hd, n_rot, nh, nkv, 1, rbase, 1.0, ff)?;
8909
8910        if std::env::var("MEMRA_NOFA").is_ok() {
8911            return Err("MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV \
8912                        cache; unset MEMRA_NOFA to use fa_decode".into());
8913        }
8914        let kvl = cache.kv[il].as_mut().unwrap();
8915        let next_len = kvl.len + 1;
8916        let (off, t_kv) = if swa && next_len > win { (next_len - win, win) } else { (0, next_len) };
8917        let write_row = e.prepare_kv_append(kvl, off & !31usize, 1)?;
8918        e.append_kv_quantized(&k, &v0, &mut kvl.k, &mut kvl.v, write_row,
8919                              kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
8920                              crate::Engine::kv_fp8_on())?;
8921        kvl.len = next_len;
8922        let physical = kvl.physical_rows(off, off + t_kv)?;
8923        let k_view = e.view_u8_range(&kvl.k, physical.start * kvl.k_tok_bytes,
8924                                     physical.end * kvl.k_tok_bytes);
8925        let v_view = e.view_u8_range(&kvl.v, physical.start * kvl.v_tok_bytes,
8926                                     physical.end * kvl.v_tok_bytes);
8927        let mut attn = e.uninit(nh * hd)?;
8928        e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
8929                          kvl.k_tok_bytes, kvl.v_tok_bytes, crate::Engine::kv_fp8_on())?;
8930
8931        let mut ag = e.uninit(nh * hd)?;
8932        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
8933        Ok(e.matmul(&fa.wo, &ag, 1)?)
8934    }
8935}
8936
8937// ===================================================================================== //
8938//  gemma-4 E4B (per-layer embeddings + KV-sharing) — FIRST-LIGHT forward.               //
8939//  Dedicated simple path (Stage-B matmuls, per-row causal attention over the quantized  //
8940//  cache) so the tuned 26B/31B paths stay untouched. Arch: research/gemma4-bringup/     //
8941//  e4b-arch-map.md; llama reference: src/models/gemma4.cpp (E4B arms). Wired: forward   //
8942//  (prefill logits), prime (tokenwise-equivalent batched trunk), eager decode_step_h.   //
8943//  NOT wired: dc/graph serving arms, verify/spec, chunked prime (HANDOVER-E4B.md).      //
8944// ===================================================================================== //
8945impl HybridModel {
8946    pub fn is_gemma4_e4b(&self) -> bool {
8947        self.gemma4_aux.as_ref().is_some_and(|a| a.e4b.is_some())
8948    }
8949
8950    /// E4B per-layer geometry: nh/nkv derive from the layer's OWN tensor shapes (the E4B GGUF
8951    /// ships a scalar head_count_kv; swa q 8x256 / kv 2x256, global q 4x512 / kv 1x512).
8952    /// KV-shared layers report the SHARE TARGET's kv count (their wk IS the target's tensor).
8953    fn gemma4_e4b_geom(&self, il: usize) -> (usize, usize, usize, f32, f32, bool) {
8954        let g = self.cfg.gemma4.as_ref().unwrap();
8955        let swa = g.swa_pattern[il];
8956        let hd = if swa { g.key_length_swa } else { g.key_length_global } as usize;
8957        let Mixer::Full(fa) = &self.layers[il].mixer else { panic!("e4b layer {il} not full-attn") };
8958        let nh = fa.wq.out_features() / hd;
8959        let nkv = fa.wk.out_features() / hd;
8960        (hd, nkv, nh, if swa { g.rope_base_swa } else { g.rope_base_global }, 1.0, swa)
8961    }
8962
8963    /// E4B KV-share target: Some(target) for the trailing shared layers, None = own cache.
8964    fn gemma4_e4b_kv_target(&self, il: usize) -> Option<usize> {
8965        self.layers[il].gemma4.as_ref()
8966            .and_then(|b| b.e4b.as_ref())
8967            .and_then(|e4| e4.kv_share.map(|t| t as usize))
8968    }
8969
8970    /// E4B prologue: inp_pl [t][n_layer][n_epl] =
8971    ///   ( gather(per_layer_tok_embd, tok)*sqrt(n_epl)
8972    ///   + rms_norm(model_proj . x_scaled * 1/sqrt(n_embd), proj_norm) ) * 1/sqrt(2)
8973    /// (llama gemma4.cpp build_inp_per_layer + project_per_layer_inputs, exact order).
8974    fn gemma4_e4b_inp_pl(&self, e: &Engine, tokens: &[u32], x_scaled: &CudaSlice<f32>, t: usize)
8975                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8976        let tok_d = e.stream().clone_htod(&tokens.to_vec())?;
8977        self.gemma4_e4b_inp_pl_dev(e, &tok_d, x_scaled, t)
8978    }
8979
8980    /// Device-token prologue core (dc arm shares it: token ids never touch the host).
8981    fn gemma4_e4b_inp_pl_dev(&self, e: &Engine, tok_d: &CudaSlice<u32>,
8982                             x_scaled: &CudaSlice<f32>, t: usize)
8983                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8984        let aux = self.gemma4_aux.as_ref().unwrap();
8985        let m = aux.e4b.as_ref().unwrap();
8986        let n_embd = self.cfg.n_embd as usize;
8987        let n_layer = self.layers.len();
8988        let width = m.n_epl * n_layer;
8989        let tbl = m.tok_tbl_gpu.get_or_init(|| {
8990            e.upload_u8(&m.tok_embd_bytes).expect("e4b per-layer token table upload")
8991        });
8992        let mut a = e.embed_gather_device_td(tbl, tok_d, t, width, m.tok_embd_qt,
8993                                             m.tok_embd_row_bytes)?;
8994        e.scale_inplace(&mut a, (m.n_epl as f32).sqrt(), t * width)?;
8995        let mut p = e.matmul(&m.model_proj, x_scaled, t)?;
8996        e.scale_inplace(&mut p, 1.0 / (n_embd as f32).sqrt(), t * width)?;
8997        let mut pn = e.uninit(t * width)?;
8998        e.rms_norm(&p, m.proj_norm.float_data(), &mut pn, m.n_epl, t * n_layer,
8999                   self.cfg.rms_eps)?;
9000        let mut out = e.uninit(t * width)?;
9001        e.add_scale(&a, &pn, 1.0 / 2f32.sqrt(), &mut out, t * width)?;
9002        Ok(out)
9003    }
9004
9005    /// E4B attention (t-wide, causal, per-row fa over the QUANTIZED cache — first-light
9006    /// correctness path; the fa rows arms come later). Own-KV layers project+norm+rope k/v
9007    /// and append t rows; KV-shared layers are Q-only over the target layer's cache (which
9008    /// already holds this forward's rows — the target runs earlier in the stack).
9009    #[allow(clippy::too_many_arguments)]
9010    fn gemma4_e4b_attn(&self, e: &Engine, il: usize,
9011                       hq: &CudaSlice<i8>, hdq: &CudaSlice<f32>,
9012                       pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache,
9013                       dc_bucket: Option<usize>)
9014                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9015        let (hd, nkv, nh, base, scale, swa) = self.gemma4_e4b_geom(il);
9016        let eps = self.cfg.rms_eps;
9017        let aux = self.gemma4_aux.as_ref().unwrap();
9018        let Mixer::Full(fa) = &self.layers[il].mixer else { unreachable!() };
9019        // pre-quantized layer input (E4B fusion port, 2026-07-12): ONE norm+quant feeds
9020        // wq/wk/wv via matmul_pre — the first-light path quantized the same h three times
9021        // (the profile's 342 quantize_q8_1/token; glue = 26% of the 6.1ms token).
9022        let h0 = e.zeros(0)?;
9023        let h = &h0;
9024
9025        let ff = if swa { None } else {
9026            Some(aux.rope_freqs.as_ref().expect("e4b global rope needs rope_freqs.weight"))
9027        };
9028        let share = self.gemma4_e4b_kv_target(il);
9029        // Own-KV arms keep the f32 (k, v) alive for the prime fa arm below.
9030        let mut kv_f32: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
9031        let mut q;
9032        if let Some(_tgt) = share {
9033            let q0 = e.matmul_pre(&fa.wq, hq, hdq, h, t)?;
9034            q = e.uninit(t * nh * hd)?;
9035            // Q-only through the same fused norm+rope kernel (rk = 0: the k/v segments are
9036            // empty; q0 stands in for the unused k/v pointers).
9037            let mut kdummy = e.uninit(1)?;
9038            let mut vdummy = e.uninit(1)?;
9039            e.rms_norm_qkv_rope(&q0, &q0, &q0, fa.q_norm.float_data(),
9040                                fa.q_norm.float_data(), &aux.ones,
9041                                &mut q, &mut kdummy, &mut vdummy, hd, nh * t, 0,
9042                                pos_d, nh, 1, base, 1.0, ff, eps)?;
9043        } else {
9044            // wave-4b: ONE concat matvec (wq|wk|wv) at t == 1 when the cat tensor exists;
9045            // else the fused3 grid launch; else per-matvec. The cat output is contiguous
9046            // q|k|v rows — the cat norm+rope twin consumes it directly.
9047            let e4bits = self.layers[il].gemma4.as_ref().and_then(|g| g.e4b.as_ref());
9048            let cat = e4bits.and_then(|e4| e4.qkv_cat.as_ref());
9049            q = e.uninit(t * nh * hd)?;
9050            let mut k = e.uninit(t * nkv * hd)?;
9051            let mut v = e.uninit(t * nkv * hd)?;
9052            if t == 1 && cat.is_some() {
9053                let qkv0 = e.matmul_pre(cat.unwrap(), hq, hdq, h, 1)?;
9054                e.rms_norm_qkv_rope_cat(&qkv0, fa.q_norm.float_data(), fa.k_norm.float_data(),
9055                                        &aux.ones, &mut q, &mut k, &mut v, hd, nh, nkv,
9056                                        pos_d, nh, nkv, base, 1.0, ff, eps)?;
9057            } else {
9058                let (q0, k0, v0) = match if t == 1 {
9059                    e.matmul_q4_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hdq)?
9060                } else {
9061                    // E4B verify f3 port (2026-07-14): the 31B segmented-grid batched qkv
9062                    // on E4B's real-V triple — same MEMRA_F2B seam, bit-identical per row.
9063                    static F2B_QKV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
9064                    if *F2B_QKV.get_or_init(|| std::env::var("MEMRA_F2B").as_deref() != Ok("0")) {
9065                        e.matmul_q4_fused3_batched(&fa.wq, &fa.wk, &fa.wv, hq, hdq, t)?
9066                    } else { None }
9067                } {
9068                    Some(triple) => triple,
9069                    None => (e.matmul_pre(&fa.wq, hq, hdq, h, t)?,
9070                             e.matmul_pre(&fa.wk, hq, hdq, h, t)?,
9071                             e.matmul_pre(&fa.wv, hq, hdq, h, t)?),   // E4B: real v (K != V)
9072                };
9073                // wave-3 fold: q/k/v norms + q/k rope in ONE launch (rope math verbatim on
9074                // the normed rows; V ones-rms, never roped).
9075                e.rms_norm_qkv_rope(&q0, &k0, &v0, fa.q_norm.float_data(),
9076                                    fa.k_norm.float_data(), &aux.ones, &mut q, &mut k, &mut v,
9077                                    hd, nh * t, nkv * t, pos_d, nh, nkv, base, 1.0, ff, eps)?;
9078            }
9079            let kvl = cache.kv[il].as_mut().unwrap();
9080            // class flag must match the cache dims (the g-threading sweep hardcoded `false`
9081            // here and the wkv default corrupted E4B: q8_0 bytes into an e4m3 cache — the
9082            // degenerate tok-0 stream, 2026-07-12).
9083            let cls = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
9084            if dc_bucket.is_some() {
9085                // DC arm (graph serving): append at the len_d slot, advance the counter
9086                // in-stream — replay-correct, no host len in the launch args. Host mirrors
9087                // are NOT touched here (the replay loop owns them; a bump at capture-record
9088                // time would double-count the capture iteration).
9089                debug_assert!(t == 1);
9090                // wave 5c: append + len_d inc fused (one launch; single-block ordering).
9091                e.append_kv_quantized_row_dc_inc(&k, &v, &mut kvl.k, &mut kvl.v,
9092                                                 &mut kvl.len_d, kvl.kv_dim_k, kvl.kv_dim_v,
9093                                                 kvl.k_tok_bytes, kvl.v_tok_bytes, cls)?;
9094            } else {
9095                e.append_kv_quantized_rows(&k, &v, &mut kvl.k, &mut kvl.v, kvl.len, t,
9096                                           kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes,
9097                                           kvl.v_tok_bytes, cls)?;
9098                kvl.len += t;
9099            }
9100            kv_f32 = Some((k, v));
9101        }
9102        // attention: per-row causal fa over the (own or target) quantized cache. The cache
9103        // already contains this forward's rows in both arms; row i attends [.., base+i].
9104        let kvl_idx = share.unwrap_or(il);
9105        let kvl = cache.kv[kvl_idx].as_ref().unwrap();
9106        let base_len = kvl.len - t;   // pre-append length (target appended this forward too)
9107        let win = self.cfg.gemma4.as_ref().unwrap().sliding_window as usize;
9108        let mut attn = e.uninit(t * nh * hd)?;
9109        // PRIME FA ARMS (perf lane 3, completed 2026-07-31 — the H100 board pinned E4B
9110        // prefill at 482 tok/s: the per-row loop ran the DECODE kernel once per token per
9111        // layer). Fresh-prompt (base_len == 0) batched attention, one launch per layer:
9112        //   - own-KV hd256 under the window: f32 fa_prefill (full causal exact — 26B pattern)
9113        //   - own-KV hd256 above the window (swa): fa_prefill_w windowed twin (12B pattern)
9114        //   - own-KV hd512 globals: fa_prefill_hd512 (12B/31B globals pattern)
9115        //   - KV-shared layers (no f32 k/v): fa_prefill_view over the target's QUANTIZED
9116        //     rows (the T=K verify kernel; the target appended this forward's rows already).
9117        //     swa-shared above the window keeps the per-row loop (no windowed view twin).
9118        // Same numeric class split as the 26B prime (f32/batched prefill vs per-row
9119        // quantized decode); run-gen argmax + chat gates arbitrate. MEMRA_NOFA=1 reverts all.
9120        if t > 1 && base_len == 0 && std::env::var("MEMRA_NOFA").is_err() {
9121            if let Some((kf, vf)) = &kv_f32 {
9122                if hd == 256 && t <= win {
9123                    e.fa_prefill(&q, kf, vf, &mut attn, hd, nh, nkv, t, t, scale, true)?;
9124                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9125                }
9126                if hd == 256 && swa && t > win {
9127                    e.fa_prefill_w(&q, kf, vf, &mut attn, hd, nh, nkv, t, t, scale, true,
9128                                   win)?;
9129                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9130                }
9131                if hd == 512 && !swa {
9132                    e.fa_prefill_hd512(&q, kf, vf, &mut attn, hd, nh, nkv, t, t, scale,
9133                                       true)?;
9134                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9135                }
9136            } else if share.is_some() {
9137                let g = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
9138                let k_view = e.view_u8(&kvl.k, kvl.k.len());
9139                let v_view = e.view_u8(&kvl.v, kvl.v.len());
9140                if hd == 256 && (!swa || t <= win) {
9141                    // inline-dequant quantized-view prefill (fa_prefill_q stamps 256/128)
9142                    e.fa_prefill_view(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t, t,
9143                                      scale, true, kvl.k_tok_bytes, kvl.v_tok_bytes, g)?;
9144                    return Ok(e.matmul(&fa.wo, &attn, t)?);
9145                }
9146                // remaining shared classes (swa above the window; hd512 globals): dequant
9147                // the target's t rows ONCE to f32, then the same f32 twins as own-KV.
9148                let kv_dim = nkv * hd;
9149                let mut kf = e.uninit(t * kv_dim)?;
9150                let mut vf = e.uninit(t * kv_dim)?;
9151                e.fa_dequant_kv_view_f32(&k_view, &v_view, &mut kf, &mut vf, kv_dim, kv_dim,
9152                                         t, kvl.k_tok_bytes, kvl.v_tok_bytes, g)?;
9153                if hd == 512 {
9154                    e.fa_prefill_hd512(&q, &kf, &vf, &mut attn, hd, nh, nkv, t, t, scale,
9155                                       true)?;
9156                } else {
9157                    e.fa_prefill_w(&q, &kf, &vf, &mut attn, hd, nh, nkv, t, t, scale, true,
9158                                   win)?;
9159                }
9160                return Ok(e.matmul(&fa.wo, &attn, t)?);
9161            }
9162        }
9163        if let Some(bucket) = dc_bucket {
9164            // DC arm (t == 1, under-window regime — the generate gate enforces it): ONE
9165            // fa_decode_dc over the live counter. len_d already advanced past this token
9166            // (t_kv = len_d[0], the cache.rs contract). KV-shared layers read the target's
9167            // counter (advanced when the target ran earlier in the stack).
9168            assert!(t == 1);
9169            // hd512 globals: eager (kvmod) picks the SCALAR unified below the fa512 floor,
9170            // and under the window every live t_kv sits below it — cap the capture bucket
9171            // under the floor so fa_decode_dc bakes the same scalar symbol, or the graph
9172            // rides the dpl16 twin and its numeric class diverges from the dc-eager stream
9173            // (E4B-GRAPH-GATE 2/64, 2026-07-12).
9174            let bucket = if hd == 512 && win <= crate::fa512_min_tkv() {
9175                bucket.min(crate::fa512_min_tkv().saturating_sub(1))
9176            } else { bucket };
9177            let k_view = e.view_u8(&kvl.k, kvl.k.len());
9178            let v_view = e.view_u8(&kvl.v, kvl.v.len());
9179            let g = (!swa && crate::Engine::gkv_on()) || (swa && crate::Engine::wkv_on());
9180            // Weight prefetch (SOTA item 3, 2026-07-13): wo's decode plane prefetched into
9181            // L2 across the fa window — fa reads KV only, the weight DRAM lanes are idle
9182            // there (E4B valid window +0.65%: 196.8 vs 195.6). Value-free scheduling op,
9183            // captured into the dc graph like any other launch. Extending the cascade to
9184            // the ffn gate/up planes measured NEGATIVE (193.9 vs 195.8 — 29MB/layer floods
9185            // the fill path and evicts still-hot lines); wo-only is the shipped shape.
9186            // MEMRA_WPF=0 rollback seam.
9187            if crate::Engine::wpf_level() >= 1 {
9188                e.prefetch_weight_l2(&fa.wo)?;
9189            }
9190            // wave 5b: the combine emits the wo input q8 pair directly — the standalone
9191            // quantize launch + the f32 attn round-trip fold away (t=1 fast path only).
9192            if e.uses_q8_1_fast(&fa.wo) {
9193                let mut oq = e.alloc_i8_uninit(nh * hd)?;
9194                let mut od = e.zeros(nh * hd / 32)?;
9195                e.fa_decode_dc_q8(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
9196                                  &kvl.len_d, bucket, scale,
9197                                  kvl.k_tok_bytes, kvl.v_tok_bytes, g,
9198                                  Some((&mut oq, &mut od)))?;
9199                return Ok(e.matmul_pre(&fa.wo, &oq, &od, &attn, t)?);
9200            }
9201            e.fa_decode_dc(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
9202                           &kvl.len_d, bucket, scale,
9203                           kvl.k_tok_bytes, kvl.v_tok_bytes, g)?;
9204            return Ok(e.matmul(&fa.wo, &attn, t)?);
9205        }
9206        for i in 0..t {
9207            let avail = base_len + i + 1;
9208            let (off_tok, t_kv) = if swa && avail > win { (avail - win, win) } else { (0, avail) };
9209            let k_view = e.view_u8_range(&kvl.k, off_tok * kvl.k_tok_bytes,
9210                                         (off_tok + t_kv) * kvl.k_tok_bytes);
9211            let v_view = e.view_u8_range(&kvl.v, off_tok * kvl.v_tok_bytes,
9212                                         (off_tok + t_kv) * kvl.v_tok_bytes);
9213            let qv = e.view(&q, t * nh * hd);
9214            let q_row = qv.slice(i * nh * hd..(i + 1) * nh * hd);
9215            let mut q_one = e.uninit(nh * hd)?;
9216            e.copy_view_into(&mut q_one, 0, &q_row, nh * hd)?;
9217            let mut a_one = e.uninit(nh * hd)?;
9218            // read class MUST match the append class (globals are e4m3 under gkv): the
9219            // swa-only flag decoded global-layer e4m3 bytes as q8_0/q5_1 — attention over
9220            // garbage on EVERY E4B global layer, the cross-mode maxdiff-30 root (2026-07-12).
9221            e.fa_decode_kvmod(&q_one, &k_view, &v_view, &mut a_one, hd, nh, nkv, t_kv, scale,
9222                        kvl.k_tok_bytes, kvl.v_tok_bytes,
9223                        (!swa && crate::Engine::gkv_on())
9224                            || (swa && crate::Engine::wkv_on()))?;
9225            e.copy_into(&mut attn, i * nh * hd, &a_one, nh * hd)?;
9226        }
9227        Ok(e.matmul(&fa.wo, &attn, t)?)
9228    }
9229
9230    /// E4B trunk: embed -> prologue -> layers (attn + dense ffn via the 31B tail_core + the
9231    /// per-layer-embedding tail + layer scale) -> output_norm. Returns (softcapped logits
9232    /// device [t, n_vocab], pre-output_norm hidden [t, n_embd]). Appends t rows per own-KV
9233    /// layer; does NOT advance cache.pos (caller owns pos).
9234    fn gemma4_e4b_trunk(&self, e: &Engine, tokens: &[u32], pos0: usize, cache: &mut Cache,
9235                        head_last: bool)
9236                        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9237        let n_embd = self.cfg.n_embd as usize;
9238        let t = tokens.len();
9239        let pos: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
9240        let pos_d = e.htod_i32(&pos)?;
9241        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
9242        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
9243        let inp_pl = self.gemma4_e4b_inp_pl(e, tokens, &x, t)?;
9244        self.gemma4_e4b_trunk_core(e, x, inp_pl, &pos_d, t, cache, None, true, head_last)
9245    }
9246
9247    /// Layer stack + head over prebuilt (x_scaled, inp_pl, device pos) — everything below
9248    /// here is device-driven, so the dc arm shares it verbatim (stream identity with the
9249    /// eager chain by construction: SAME functions, not twins).
9250    fn gemma4_e4b_trunk_core(&self, e: &Engine, x_in: CudaSlice<f32>, inp_pl: CudaSlice<f32>,
9251                             pos_d: &CudaSlice<i32>, t: usize, cache: &mut Cache,
9252                             dc_bucket: Option<usize>, cap_logits: bool, head_last: bool)
9253                             -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9254        let n_embd = self.cfg.n_embd as usize;
9255        let eps = self.cfg.rms_eps;
9256        let n_layer = self.layers.len();
9257        let mut x = x_in;
9258        let aux_e4b = self.gemma4_aux.as_ref().unwrap().e4b.as_ref().unwrap();
9259        let n_epl = aux_e4b.n_epl;
9260
9261        // cross-layer fusion (2026-07-12 port of the 26B/31B trunk structure): each layer's
9262        // closing add_scale also EMITS the next layer's attn-normed input pre-quantized
9263        // q8_1 (add_scale_rms_norm_q8_1); the LAST layer emits through output_norm so the
9264        // head rides matmul_pre too. First layer's pair comes from a standalone fused
9265        // norm+quant.
9266        let mut h_carry: Option<(CudaSlice<i8>, CudaSlice<f32>)> = None;
9267        for il in 0..n_layer {
9268            let layer = &self.layers[il];
9269            let (hq, hdq) = match h_carry.take() {
9270                Some(p) => p,
9271                None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
9272            };
9273            let o = self.gemma4_e4b_attn(e, il, &hq, &hdq, pos_d, t, cache, dc_bucket)?;
9274            // dense ffn tail with the post-attn norm FOLDED into its entry (one launch for
9275            // rms(o, post_attn_norm) + residual add + ffn_norm — glue-fusion lane).
9276            let bits = layer.gemma4.as_ref().unwrap();
9277            let e4b = bits.e4b.as_ref().expect("e4b layer bits");
9278            // glue wave 5: the tail DEFERS its post_ffw norm — the FFN exit fuses
9279            // rms(f0, post_ffw) + residual add + q8 emit into ONE launch (rms_pre_add_q8_1),
9280            // killing the rms_norm + add_q8_1 pair per layer. T-GENERIC since 2026-07-13:
9281            // the fused single-phase reduction is NOT FP-order-identical to the unfused
9282            // rms_norm+add pair (the original "bit-identical chain" claim was FALSE — the
9283            // t==1 gate left the batched VERIFY on the unfused chain and split E4B verify
9284            // from decode by logit maxdiff ~0.45, the greedy tie-flip at depth: gate 135/256.
9285            // NOFUSE bisect: disabling ONLY this fusion -> verify maxdiff 0.000e0). With the
9286            // gate dropped, decode AND verify ride the same fused chain — parity by
9287            // construction, VERIFY-GATE 0.000e0.
9288            let fuse_exit = e.uses_q8_1_fast(&e4b.inp_gate);
9289            let (sn, attn_out) = self.gemma4_layer_tail_core_pn(
9290                e, layer, &o, &x, t, Some(layer.post_attn_norm.float_data()), fuse_exit)?;
9291            let mut resid = e.uninit(t * n_embd)?;
9292            // per-layer-embedding tail: resid += rms(proj . (gelu(inp_gate . resid) * inp_pl[il]))
9293            // wave-2: the residual add emits q8_1 alongside — inp_gate rides matmul_pre.
9294            // (PLE one-block mega-fusion PROBED NEGATIVE 2026-07-13: argmax-correct but
9295            // 126 vs 189 tok/s — one SM pulling 0.74MB of weights loses to the multi-block
9296            // launch chain it replaced; jsonl row. Kernel deleted per doctrine.)
9297            let g = if fuse_exit {
9298                // sn here = RAW f0 (post_ffw deferred).
9299                let (rq, rd) = e.rms_pre_add_q8_1(&sn, bits.post_ffw_norm.float_data(),
9300                                                  &attn_out, &mut resid, n_embd, t,
9301                                                  self.cfg.rms_eps)?;
9302                e.matmul_pre(&e4b.inp_gate, &rq, &rd, &resid, t)?
9303            } else {
9304                e.add(&sn, &attn_out, &mut resid, t * n_embd)?;
9305                e.matmul(&e4b.inp_gate, &resid, t)?
9306            };
9307            let mut act = e.uninit(t * n_epl)?;
9308            let y = if t == 1 && e.uses_q8_1_fast(&e4b.proj) {
9309                let ipv = e.view(&inp_pl, n_epl * n_layer);
9310                let row = ipv.slice(il * n_epl..(il + 1) * n_epl);
9311                let (aq, ad) = e.gelu_tanh_mul_q8_1(&g, &row, &mut act, n_epl, 1)?;
9312                e.matmul_pre(&e4b.proj, &aq, &ad, &act, t)?
9313            } else {
9314                let mut inp_this = e.uninit(t * n_epl)?;
9315                e.copy_rows_strided(&inp_pl, &mut inp_this, n_epl, t, n_epl * n_layer,
9316                                    il * n_epl)?;
9317                e.gelu_tanh_mul(&g, &inp_this, &mut act, t * n_epl)?;
9318                e.matmul(&e4b.proj, &act, t)?
9319            };
9320            // rms(y, post_norm) + (yn + resid)*layer_scale + next-layer norm+quant emit,
9321            // ONE launch (glue-fusion lane; last layer emits through output_norm).
9322            let next_norm = if il + 1 < n_layer {
9323                self.layers[il + 1].attn_norm.float_data()
9324            } else {
9325                self.output_norm.float_data()
9326            };
9327            let mut xn = e.uninit(t * n_embd)?;
9328            let pair = e.rms_pre_add_scale_rms_norm_q8_1(&y, e4b.post_norm.float_data(),
9329                                                         &resid, bits.layer_scale, next_norm,
9330                                                         &mut xn, n_embd, t, eps)?;
9331            h_carry = Some(pair);
9332            x = xn;
9333        }
9334        // the head consumes the last layer's fused (output_norm) emit. head_last callers
9335        // (prime, last_only forward) need only the final row's logits — the all-T head is
9336        // t*n_vocab of discarded work (E4B prime: ~134ms GEMM + a 2.26GB dtoh kept 1 row).
9337        let (oq, odq) = h_carry.take().unwrap();
9338        let h0 = e.zeros(0)?;
9339        let hm = if head_last { 1 } else { t };
9340        let (hq, hd) = if head_last && t > 1 {
9341            let mut q1 = e.uninit_i8(n_embd)?;
9342            e.dtod_copy_view_i8(&oq.slice((t - 1) * n_embd..t * n_embd), &mut q1)?;
9343            let nb = n_embd / 32;
9344            let mut d1 = e.uninit(nb)?;
9345            e.dtod_copy_view(&odq.slice((t - 1) * nb..t * nb), &mut d1)?;
9346            (q1, d1)
9347        } else {
9348            (oq, odq)
9349        };
9350        let mut ld = e.matmul_pre(&self.output, &hq, &hd, &h0, hm)?;
9351        // softcap is strictly monotonic — greedy (argmax-only) consumers skip it, matching
9352        // the 26B/31B dc precedent (their dc head goes matmul -> argmax with no cap).
9353        // Logit-returning callers (host logits / spec prime) keep the capped emit.
9354        if cap_logits {
9355            let cap = self.cfg.gemma4.as_ref().unwrap().final_logit_softcapping;
9356            e.softcap(&mut ld, cap, hm * self.output.out_features())?;
9357        }
9358        self.gemma4_suppress(e, &mut ld, hm)?;  // mask both capped and argmax-only consumers
9359        Ok((ld, x))
9360    }
9361
9362    /// E4B batched VERIFY (device tokens, the spec round's t=K+1 step): t rows through the
9363    /// e4b trunk (per-row causal attention; own-KV layers append t rows host-len, KV-shared
9364    /// layers ride their targets), per-row device argmax + the POST-output_norm hidden
9365    /// stack (the drafter's h convention). Advances cache.pos/kvl.len by t — the spec
9366    /// round rolls back rejected rows (shared layers have no KvLayer, so the plain rewind
9367    /// covers exactly the layers that appended).
9368    pub fn gemma4_e4b_decode_step_t_am_dev(&self, e: &Engine, tok_d: &CudaSlice<u32>,
9369                                                  t: usize, pos0: usize, cache: &mut Cache)
9370                                                  -> Result<(CudaSlice<u32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9371        let n_embd = self.cfg.n_embd as usize;
9372        let eps = self.cfg.rms_eps;
9373        let pos: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
9374        let pos_d = e.htod_i32(&pos)?;
9375        let embd_gpu = self.embd_gpu.get_or_init(|| {
9376            e.upload_u8(&self.embd.raw).expect("embed table upload")
9377        });
9378        let (qt, rb) = self.embd.qt_and_row_bytes(n_embd);
9379        let mut x = e.embed_gather_device_td(embd_gpu, tok_d, t, n_embd, qt, rb)?;
9380        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), t * n_embd)?;
9381        let inp_pl = self.gemma4_e4b_inp_pl_dev(e, tok_d, &x, t)?;
9382        let (ld, xp) = self.gemma4_e4b_trunk_core(e, x, inp_pl, &pos_d, t, cache, None, true,
9383                                                  false)?;
9384        // softcap is monotonic — the per-row argmax is invariant to it (the trunk's head
9385        // emit is already capped, matching the eager chain bit-for-bit).
9386        let n_vocab = self.output.out_features();
9387        let mut vam = e.stream().alloc_zeros::<u32>(t)?;
9388        for i in 0..t {
9389            e.argmax_token_device_col(&ld, i, n_vocab, &mut vam, i)?;
9390        }
9391        let mut hn = e.uninit(t * n_embd)?;
9392        e.rms_norm(&xp, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
9393        cache.pos += t;
9394        Ok((vam, hn))
9395    }
9396
9397    /// E4B verify + host logits + POST-output_norm hidden stack (the short-prompt spec
9398    /// prime path — mirror of `gemma4_decode_step_t_h`).
9399    pub(crate) fn gemma4_e4b_decode_step_t_h(&self, e: &Engine, tokens: &[u32], pos0: usize,
9400                                             cache: &mut Cache)
9401                                             -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9402        let n_embd = self.cfg.n_embd as usize;
9403        let eps = self.cfg.rms_eps;
9404        let t = tokens.len();
9405        let (ld, xp) = self.gemma4_e4b_trunk(e, tokens, pos0, cache, false)?;
9406        let mut hn = e.uninit(t * n_embd)?;
9407        e.rms_norm(&xp, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
9408        cache.pos += t;
9409        Ok((e.dtoh(&ld)?, hn))
9410    }
9411
9412    /// E4B GRAPH-CAPTURABLE dc step: same trunk as the dc step but token_d is updated IN
9413    /// PLACE (self-feeding replay) and every launch arg is a device counter — pos from
9414    /// pos_d (inc'd in-stream), KV slots from len_d (advanced in-stream), attention from
9415    /// fa_decode_dc at `bucket`. Host mirrors (cache.pos / kvl.len) advance in the caller's
9416    /// replay loop. UNDER-WINDOW regime only (the caller gates pos + budget < window).
9417    pub fn gemma4_e4b_decode_step_dcg(&self, e: &Engine, token_d: &mut CudaSlice<u32>,
9418                                      pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
9419                                      embd_qt: i32, embd_rb: usize, cache: &mut Cache,
9420                                      n_vocab: usize, bucket: usize)
9421                                      -> Result<(), Box<dyn std::error::Error>> {
9422        let n_embd = self.cfg.n_embd as usize;
9423        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_rb)?;
9424        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
9425        let inp_pl = self.gemma4_e4b_inp_pl_dev(e, token_d, &x, 1)?;
9426        let (ld, _x) = self.gemma4_e4b_trunk_core(e, x, inp_pl, pos_d, 1, cache, Some(bucket),
9427                                                  false, false)?;
9428        e.argmax_token_device_into(&ld, token_d, n_vocab)?;
9429        e.inc_seqlen(pos_d)?;
9430        Ok(())
9431    }
9432
9433    /// E4B DEVICE-COUNTER decode step (the dc serving arm): token id rides `token_d`, the
9434    /// greedy argmax lands in the returned device buffer — 4B/token host traffic. The layer
9435    /// stack is gemma4_e4b_trunk_core, i.e. the SAME functions the eager chain runs (stream
9436    /// identity by construction, not by twin-kernel parity). Host KV mirrors advance like the
9437    /// 26B dc-eager arm (window views are host math); len_d stays synced by the caller's
9438    /// entry sync + the appends here don't read it. Graph capture is NOT wired (no
9439    /// cap_bucket_max) — the E4B graph arc comes after the perf gates.
9440    #[allow(clippy::too_many_arguments)]
9441    pub fn gemma4_e4b_decode_step_dc(&self, e: &Engine, token_d: &CudaSlice<u32>,
9442                                     pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>,
9443                                     embd_qt: i32, embd_rb: usize, cache: &mut Cache,
9444                                     n_vocab: usize)
9445                                     -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
9446        let n_embd = self.cfg.n_embd as usize;
9447        let eps = self.cfg.rms_eps;
9448        let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_rb)?;
9449        e.scale_inplace(&mut x, (n_embd as f32).sqrt(), n_embd)?;
9450        let inp_pl = self.gemma4_e4b_inp_pl_dev(e, token_d, &x, 1)?;
9451        let (ld, _x) = self.gemma4_e4b_trunk_core(e, x, inp_pl, pos_d, 1, cache, None, false,
9452                                                  false)?;
9453        let mut tok_out = e.stream().alloc_zeros::<u32>(1)?;
9454        e.argmax_token_device_into(&ld, &mut tok_out, n_vocab)?;
9455        e.inc_seqlen(pos_d)?;
9456        cache.pos += 1;
9457        let _ = eps;
9458        Ok(tok_out)
9459    }
9460
9461    /// E4B eager T=1 decode step (decode_step_h contract): returns (softcapped logits host,
9462    /// pre-output_norm hidden). Advances cache.pos.
9463    pub(crate) fn gemma4_e4b_decode_step_h(&self, e: &Engine, token: u32, cache: &mut Cache)
9464                                           -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9465        let (ld, x) = self.gemma4_e4b_trunk(e, &[token], cache.pos, cache, false)?;
9466        let logits = e.dtoh(&ld)?;
9467        cache.pos += 1;
9468        Ok((logits, x))
9469    }
9470
9471    /// E4B batched prime (prime_cache contract: (last-row logits host, h_seed pre-norm last
9472    /// row, hidden stack)). First-light: the t-wide trunk (per-row attention) — correct, not
9473    /// fast; the prefill fa arms come later.
9474    pub(crate) fn gemma4_e4b_prime(&self, e: &Engine, tokens: &[u32], cache: &mut Cache)
9475                                   -> Result<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9476        // Err, not assert (2026-08-07, lane/gemma4-serve-gaps): same served-chunked-prompt
9477        // process-kill as gemma4_prime — refuse per-request.
9478        if cache.pos != 0 {
9479            return Err("e4b prime is fresh-prompt only (v0) — prime the full prompt in one \
9480                        call or decode tokenwise".into());
9481        }
9482        let n_embd = self.cfg.n_embd as usize;
9483        let t = tokens.len();
9484        let (ld, x) = self.gemma4_e4b_trunk(e, tokens, 0, cache, true)?;
9485        cache.pos += t;
9486        let last = e.dtoh(&ld)?;   // head_last: ld is already the final row only
9487        let xv = e.view(&x, t * n_embd);
9488        let row = xv.slice((t - 1) * n_embd..t * n_embd);
9489        let mut h_seed = e.uninit(n_embd)?;
9490        e.copy_view_into(&mut h_seed, 0, &row, n_embd)?;
9491        Ok((last, h_seed, x))
9492    }
9493
9494    /// E4B prefill logits (forward contract — no persistent cache; scratch cache internally).
9495    pub(crate) fn gemma4_e4b_forward(&self, e: &Engine, tokens: &[u32], last_only: bool)
9496                                     -> Result<Vec<f32>, Box<dyn std::error::Error>> {
9497        let mut cache = Cache::new(e, &self.cfg, tokens.len() + 8)?;
9498        let (ld, _x) = self.gemma4_e4b_trunk(e, tokens, 0, &mut cache, last_only)?;
9499        Ok(e.dtoh(&ld)?)   // head_last already reduced to the final row when last_only
9500    }
9501}
9502
9503#[cfg(test)]
9504mod prime_chunk_schedule_tests {
9505    use super::{
9506        dynamic_prime_chunk_ranges, fixed_prime_chunk_ranges, fixed_prime_chunk_ranges_for_ring,
9507        PRIME_MIN_T,
9508        PRIME_PIPE_MIN_CHUNK,
9509    };
9510
9511    fn sizes(ranges: &[(usize, usize)]) -> Vec<usize> {
9512        ranges.iter().map(|(start, end)| end - start).collect()
9513    }
9514
9515    fn auto_chunk(t: usize) -> usize {
9516        t.div_ceil(8).max(PRIME_PIPE_MIN_CHUNK).min(4096)
9517    }
9518
9519    #[test]
9520    fn fixed_schedule_retains_measured_geometry() {
9521        assert_eq!(
9522            sizes(&fixed_prime_chunk_ranges(461, 128)),
9523            vec![128, 128, 128, 77]
9524        );
9525        assert_eq!(
9526            sizes(&fixed_prime_chunk_ranges(1833, 230)),
9527            vec![230, 230, 230, 230, 230, 230, 230, 223]
9528        );
9529        assert_eq!(
9530            sizes(&fixed_prime_chunk_ranges(4096, 512)),
9531            vec![512; 8]
9532        );
9533        let capped = sizes(&fixed_prime_chunk_ranges_for_ring(8200, 4096, true));
9534        assert_eq!(capped, vec![4096, 4088, 16]);
9535        assert!(capped.iter().all(|&rows| rows <= 4096));
9536        assert_eq!(
9537            sizes(&fixed_prime_chunk_ranges_for_ring(4100, 4096, false)),
9538            vec![4100],
9539            "flag-off schedule remains byte-for-byte the legacy monolithic tail",
9540        );
9541    }
9542
9543    #[test]
9544    fn dynamic_schedule_matches_registered_shapes() {
9545        let cases = [
9546            (461, vec![64, 141, 132, 124]),
9547            (1833, vec![115, 269, 260, 252, 244, 237, 231, 225]),
9548            (4096, vec![256, 602, 580, 563, 545, 531, 516, 503]),
9549        ];
9550        for (t, expected) in cases {
9551            let chunk = auto_chunk(t);
9552            let fixed = fixed_prime_chunk_ranges(t, chunk);
9553            assert_eq!(
9554                sizes(&dynamic_prime_chunk_ranges(t, chunk, &fixed)),
9555                expected
9556            );
9557        }
9558    }
9559
9560    #[test]
9561    fn dynamic_schedule_covers_exactly_and_shrinks_after_fill() {
9562        for t in 256..=8192 {
9563            let chunk = auto_chunk(t);
9564            let fixed = fixed_prime_chunk_ranges(t, chunk);
9565            let dynamic = dynamic_prime_chunk_ranges(t, chunk, &fixed);
9566            assert_eq!(dynamic.len(), fixed.len(), "T={t}");
9567            assert_eq!(dynamic.first().unwrap().0, 0, "T={t}");
9568            assert_eq!(dynamic.last().unwrap().1, t, "T={t}");
9569            for pair in dynamic.windows(2) {
9570                assert_eq!(pair[0].1, pair[1].0, "T={t}");
9571            }
9572            assert!(
9573                dynamic
9574                    .iter()
9575                    .all(|(start, end)| end - start >= PRIME_MIN_T),
9576                "T={t} sizes={:?}",
9577                sizes(&dynamic)
9578            );
9579            if dynamic.len() >= 3 {
9580                let chunk_sizes = sizes(&dynamic);
9581                assert!(
9582                    chunk_sizes[0] < chunk_sizes[1],
9583                    "T={t} sizes={chunk_sizes:?}"
9584                );
9585                assert!(
9586                    chunk_sizes[1..].windows(2).all(|pair| pair[0] >= pair[1]),
9587                    "T={t} sizes={chunk_sizes:?}"
9588                );
9589            }
9590        }
9591    }
9592}
9593
9594#[cfg(test)]
9595mod page_prefetch_tests {
9596    use super::{
9597        grouped_worker_prefetch_position, page_prefetch_positions,
9598        page_prefetch_window_from_values, worker_prefetch_positions,
9599    };
9600
9601    #[test]
9602    fn page_prefetch_window_keeps_existing_opt_in_default() {
9603        assert_eq!(page_prefetch_window_from_values(false, None), 0);
9604        assert_eq!(page_prefetch_window_from_values(false, Some("8")), 0);
9605        assert_eq!(page_prefetch_window_from_values(true, None), 1);
9606        assert_eq!(page_prefetch_window_from_values(true, Some("bad")), 1);
9607        assert_eq!(page_prefetch_window_from_values(true, Some("0")), 0);
9608        assert_eq!(page_prefetch_window_from_values(true, Some("8")), 8);
9609    }
9610
9611    #[test]
9612    fn rolling_page_prefetch_advises_each_future_expert_once() {
9613        let advised: Vec<_> = (0..7)
9614            .flat_map(|position| page_prefetch_positions(position, 7, 3))
9615            .collect();
9616        assert_eq!(advised, vec![1, 2, 3, 4, 5, 6]);
9617
9618        let one_ahead: Vec<_> = (0..4)
9619            .flat_map(|position| page_prefetch_positions(position, 4, 1))
9620            .collect();
9621        assert_eq!(one_ahead, vec![1, 2, 3]);
9622        assert!(page_prefetch_positions(0, 4, 0).is_empty());
9623    }
9624
9625    #[test]
9626    fn grouped_worker_prefetch_primes_first_then_each_known_next_once() {
9627        assert_eq!(grouped_worker_prefetch_position(0, None), None);
9628        let positions: Vec<_> = std::iter::once(grouped_worker_prefetch_position(4, None).unwrap())
9629            .chain((0..4).filter_map(|position| {
9630                grouped_worker_prefetch_position(4, Some(position))
9631            }))
9632            .collect();
9633        assert_eq!(positions, vec![0, 1, 2, 3]);
9634        assert_eq!(grouped_worker_prefetch_position(1, Some(0)), None);
9635    }
9636
9637    #[test]
9638    fn rolling_worker_prefetch_primes_current_and_each_future_expert_once() {
9639        let queued: Vec<_> = (0..8)
9640            .flat_map(|position| worker_prefetch_positions(position, 8, 5))
9641            .collect();
9642        assert_eq!(queued, (0..8).collect::<Vec<_>>());
9643
9644        let one_at_a_time: Vec<_> = (0..4)
9645            .flat_map(|position| worker_prefetch_positions(position, 4, 1))
9646            .collect();
9647        assert_eq!(one_at_a_time, vec![0, 1, 2, 3]);
9648        assert!(worker_prefetch_positions(0, 4, 0).is_empty());
9649    }
9650}
9651
9652pub struct G4DcSlots {
9653    x: CudaSlice<f32>, xn: CudaSlice<f32>, cur: CudaSlice<f32>,
9654    hq: CudaSlice<i8>, hd_: CudaSlice<f32>,
9655    q0: CudaSlice<f32>, k0: CudaSlice<f32>, v0: CudaSlice<f32>,
9656    q: CudaSlice<f32>, k: CudaSlice<f32>, v: CudaSlice<f32>,
9657    attn: CudaSlice<f32>, o: CudaSlice<f32>,
9658    attn_out: CudaSlice<f32>, zsh: CudaSlice<f32>,
9659    zq: CudaSlice<i8>, zd: CudaSlice<f32>,
9660    gate: CudaSlice<f32>, up: CudaSlice<f32>,
9661    act: CudaSlice<f32>, actq: CudaSlice<i8>, actd: CudaSlice<f32>,
9662    f0: CudaSlice<f32>, sn: CudaSlice<f32>,
9663    hn: CudaSlice<f32>, logits: CudaSlice<f32>,
9664}