Skip to main content

memra_engine/
lib.rs

1//! memra engine: Stage-1 correctness-first forward-pass kernels + ops, on sm_120 via cudarc.
2
3use std::sync::{Arc, Mutex};
4use cudarc::driver::{CudaContext, CudaStream, CudaModule, CudaFunction, CudaSlice, LaunchConfig, PushKernelArg};
5use cudarc::nvrtc::Ptx;
6
7pub use memra_gguf;
8pub use memra_runtime;
9
10pub mod model;
11pub mod forward;
12pub mod hybrid;
13pub mod hybrid_forward;
14/// The dual cache lives in the shared `memra-kv` crate (Phase D extraction); this
15/// re-export keeps every `crate::cache::` / `memra_engine::cache::` path unchanged.
16pub mod cache {
17    pub use memra_kv::*;
18}
19pub mod decode;
20pub mod decode_batch;
21/// MLA (multi-head latent attention) CPU f32 reference — GLM-5.2 bring-up lane increment 1.
22/// Naive vs absorbed decode forms + NORM/NEOX rope permutation, unit-tested; the permanent
23/// oracle for the MLA kernel family (`research/mla-bringup-20260801/DESIGN.md`). No CUDA deps.
24pub mod mla;
25pub mod pp;
26pub mod spec;
27pub mod gemma_spec;
28pub mod round_stream;
29pub mod graph_update;
30pub mod dflash;
31pub mod eagle;
32pub use memra_sampling as sampler;
33
34/// In-house MoE router GEMV on the spec-verify small-t path (DEFAULT ON since 2026-07-10:
35/// battery green on 35B p2/p3 K=1..8, acceptance bit-identical, +2-4% spec e2e — replaces
36/// ~240 per-column cuBLAS gemv launches/round). MEMRA_ROUTER_KERNEL=0 is the rollback seam.
37/// MoE grouped f16 GEMM door (experimental until gated), f16-mirror numeric class:
38/// per-layer expert dequant to f16 + one grouped f16 GEMM over the CSR groups.
39///   MEMRA_MOE_F16G=1  cublasGemmGroupedBatchedEx (round 46 arc 2). The grouped API issues
40///                     through cublas-internal streams NOT ordered with ours — v1 pays a full
41///                     stream sync per projection (round-47 ledgered defect).
42///   MEMRA_MOE_F16G=2  single-kernel grouped GEMM on the engine stream (round 49): ordered by
43///                     construction, zero syncs, f32 C with the act row-scale folded in.
44/// DEFAULT (2026-08-01, round 49 promotion): mode 1 on the Hopper lane — with the 41/41
45/// dequant coverage fix the q35 board-2048 prime measured 5490 (MMQ) / 8380 (mode 1,
46/// +53%) / 7990 (mode 2) x3 interleaved on the H100, argmax MATCH — the last board loss
47/// flips. The 5090 measured FLAT (858GB/s makes the dequant-workspace traffic cancel the
48/// GEMM win) — but that verdict is for expert banks the int8-MMA MMQ arm can take
49/// (IQ3_S/IQ4_XS/Q4_0). MEMRA_MOE_F16G=0 kills anywhere.
50///
51/// HOPPER RE-VERDICT (2026-08-02, lane/h100-flip-full): mode 2 with full direct coverage
52/// (Q4_K/Q6_K/IQ4_XS/IQ3_S tile loaders, lane/iq-direct-loaders) + the deep tail
53/// (lane/sk-tail-form) FLIPS past cublas mode 1 on the H100 — q35 board-2048 prime
54/// 13163.6 (mode 2, cross=32) vs 8626.5 (mode 1) vs 8073.4 (round-51 sk form), +52.6%,
55/// interleaved x5 zero overlap, argmax MATCH 30/30. The round-54 NO-FLIP (8547 vs 8112)
56/// was coverage-priced at 5.2% direct; ~100% coverage kills the workspace pass and the
57/// verdict inverts. Hopper naked default -> mode 2 (this arm); the gemma (gelu) site
58/// stays env-explicit-only via moe_f16g_gemma_on (Err => closed, unaffected by this arm).
59///
60/// MODE-2 DEFAULT (sm_120a naked, 2026-08-02, lane/f16g-default-rearb): with the direct
61/// tile loaders covering Q4_K/Q6_K/IQ4_XS/IQ3_S, the sk visitor beats the int8-MMA MMQ
62/// tiles on the IQ-bank models too (q35 board-2048 +33.9%, KAT pp512 +46.7% / pp2048
63/// +30.6% — research/iq-direct-loaders-20260802 §3-5, confirmed + full battery in
64/// research/f16g-default-rearb-20260802/), so every f16g-admitted expert layer rides
65/// mode 2 naked. Decode/verify stay on dp4a (t >= 16 floor). f16-mirror numeric class
66/// for naked q35/KAT prefill+prime — new token-sha anchors stamped in the rearb lane.
67///
68/// AUTO-KQUANT (mode 3, 2026-08-02, lane/q4k-expert-prefill): the previous sm_120a
69/// default, kept reachable via MEMRA_MOE_F16G=3. The mode-2 sk form is admitted ONLY for
70/// layers the MMA MMQ arm rejects (k-quant expert projections — Q3_K/Q4_K/Q6_K), i.e.
71/// exactly where the baseline is the per-pair moe_pairs_matvec_q8_em fallback with zero
72/// token reuse (Ornith-35B Q4_K_M board-2048 1098.2 -> 3453.7, 3.14x,
73/// research/q4k-expert-prefill-20260802/). Its "IQ banks keep their measured-faster MMQ
74/// tiles" ruling was priced BEFORE the IQ direct loaders and is refuted on the 5090 —
75/// the k-quant-only admission survives as the rollback seam, not the default.
76/// The gemma (gelu) site stays env-explicit-only (moe_f16g_gemma_on).
77pub fn moe_f16g_mode() -> u8 {
78    static M: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
79    *M.get_or_init(|| match std::env::var("MEMRA_MOE_F16G").as_deref() {
80        Ok("0") => 0,
81        Ok("2") => 2,
82        Ok("3") => 3,
83        Ok(_) => 1,
84        // Both arches independently re-arbitrated to mode 2 on 2026-08-02
85        // (5090: lane/f16g-default-rearb; H100: lane/h100-flip-full) — unset = 2 everywhere.
86        Err(_) => 2,
87    })
88}
89/// Mode-2 sk kernel form policy (round 51, lane/sk-bm128): the single-kernel grouped GEMM runs
90/// as a persistent problem-visitor over the real CSR tiles with two tile forms. Returns
91/// (shape_sel, cross) for the FFI:
92///   MEMRA_F16G_SK=0    -> (-1, _): the round-49 grid-scan kernel (rollback seam).
93///   MEMRA_F16G_SK=32   -> all groups on the 32x64x32 2-stage form (cross = i32::MAX).
94///   MEMRA_F16G_SK=128  -> all groups on the 128x64x64 3-stage form (cross = 1; groups fall
95///                         back to 32x64 in-launcher when the device/in_f can't take it).
96///   unset              -> hybrid split: groups with m_e >= MEMRA_F16G_SK_CROSS ride the 128
97///                         form. Default cross = 64 (5090 sweep 2026-08-01, receipts
98///                         research/sk-bm128-20260801/; H100 re-swept on the direct+tail
99///                         form 2026-08-02, lane/h100-flip-full: {16,32,64} ->
100///                         12868/13192/13225 — 64 wins there too, the pre-direct 32
101///                         verdict was stale).
102pub fn moe_f16g_sk_params() -> (i32, i32) {
103    static P: std::sync::OnceLock<(i32, i32)> = std::sync::OnceLock::new();
104    *P.get_or_init(|| match std::env::var("MEMRA_F16G_SK").as_deref() {
105        Ok("0") => (-1, 0),
106        Ok("32") => (0, i32::MAX),
107        Ok("128") => (0, 1),
108        _ => {
109            let cross = std::env::var("MEMRA_F16G_SK_CROSS").ok()
110                .and_then(|v| v.parse().ok()).unwrap_or(64);
111            (0, cross)
112        }
113    })
114}
115/// DIRECT-FROM-QUANT sk tile loaders (lane/kquant-tile-loaders, 2026-08-02; IQ classes added
116/// by lane/iq-direct-loaders): Q4_K/Q6_K/IQ4_XS/IQ3_S expert projections on the mode-2/3 sk
117/// visitor forms dequant their weight tiles in-register from the quant superblocks instead of
118/// running the per-(layer,projection) dequant pass into an f16 workspace (41.8% of Ornith-35B
119/// t=512 kernel time — the pp512 wall, research/q4k-expert-prefill-20260802 §5; the IQ classes
120/// are 94.8% of q35's bank bytes — the h100-sk-direct coverage pricing). Bit-identical to the
121/// workspace path by construction (kernel-check "f16g-kq-direct" gates it bitwise) — a
122/// data-movement change, not a numeric-class change. Default ON; MEMRA_F16G_DIRECT=0 reverts
123/// to the workspace path everywhere; MEMRA_F16G_DIRECT=kq keeps the k-quant loaders and
124/// reverts only the IQ classes (the iq-direct-loaders A/B seam — the pre-lane shipped config).
125pub fn moe_f16g_direct_on(qtype: i32) -> bool {
126    static M: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
127    let m = *M.get_or_init(|| match std::env::var("MEMRA_F16G_DIRECT").as_deref() {
128        Ok("0") => 0,
129        Ok("kq") => 1,
130        _ => 2,
131    });
132    match m {
133        0 => false,
134        1 => qtype == QT_Q4_K || qtype == QT_Q6_K,
135        _ => true,
136    }
137}
138/// DEEP-TAIL sk form (lane/sk-tail-form, 2026-08-02): groups below the visitor crossover ride
139/// a 32x64x64 3-STAGE cp.async tile instead of the round-51 32x64x32 2-stage — the same 32-row
140/// tile (zero extra padding), 2 k-blocks in flight instead of 1 and half the syncs per k. The
141/// H100 ncu pricing (research/sk-bm128-20260801) put the 2-stage tail at 31% of the sk GEMM
142/// stage under q35's routing skew. Bit-identical to every other sk form by construction
143/// (kernel-check "f16g-sk" gates all tail arms maxdiff==0); exists in both the workspace-f16
144/// and direct-from-quant variants. Default ON; MEMRA_F16G_TAIL=0 = rollback to the 2-stage
145/// tail. in_f % 64 != 0 falls back in-launcher.
146pub fn moe_f16g_tail_on() -> bool {
147    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
148    *ON.get_or_init(|| std::env::var("MEMRA_F16G_TAIL").as_deref() != Ok("0"))
149}
150
151/// Per-model door for the gemma-MoE (gelu) grouped path: round 49's Hopper default
152/// REGRESSED g26 board-2048 prefill -8.3% interleaved x5 on-box (def median 10380,
153/// wild 8.9k-11.7k spread; off 11317, ±0.13%) — the +6-15% probe verdict didn't
154/// survive the board workload (stale-verdict law, round 50). The silu/qwen class
155/// keeps the round-49 default (q35 +53% board-2048). Explicit MEMRA_MOE_F16G=1/2
156/// still opens this door for A/B.
157pub fn moe_f16g_gemma_on() -> bool {
158    static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
159    *M.get_or_init(|| !matches!(std::env::var("MEMRA_MOE_F16G").as_deref(), Ok("0") | Err(_)))
160}
161
162/// Fused act-epilogue (silu/gelu-mul + q8_1_mmq quantize in one launch) for the MoE prefill
163/// MMA arms. Byte-identical to the two-pass path (kernel-check gated) — default ON.
164/// MEMRA_MOE_FUSE_ACTQ=0 is the rollback/A-B seam.
165pub fn moe_fuse_actq_on() -> bool {
166    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
167    *ON.get_or_init(|| std::env::var("MEMRA_MOE_FUSE_ACTQ").as_deref() != Ok("0"))
168}
169
170/// PREFILL router m-invariance (lane/concat-prime-exact, 2026-08-02). The batched cuBLASLt
171/// router GEMM changes a row's logits when OTHER rows join the call (probed: first change at
172/// m=65 on the Ornith-35B router, 3.9e-3 — while the MMQ/f16 trunk GEMMs are bit-identical
173/// across m). Feeding a top-k discontinuity, that made a served request's expert selection a
174/// function of its CO-ARRIVALS under cross-request prime batching. The in-house router GEMV
175/// is m-invariant, so prefill uses it too and routing depends on a session's own tokens only.
176/// DEFAULT ON: it is the serving isolation contract, and it is the same kernel decode and spec
177/// verify already use (dispatch parity, one router kernel for every t).
178/// MEMRA_ROUTER_PREFILL_EXACT=0 reverts to the batched GEMM.
179pub fn router_prefill_exact_on() -> bool {
180    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
181    *ON.get_or_init(|| std::env::var("MEMRA_ROUTER_PREFILL_EXACT").as_deref() != Ok("0"))
182}
183
184pub fn router_kernel_on() -> bool {
185    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
186    *ON.get_or_init(|| {
187        let on = std::env::var("MEMRA_ROUTER_KERNEL").as_deref() != Ok("0");
188        if !on { eprintln!("[memra] router kernel OFF (rollback: per-column cuBLAS gemv)"); }
189        on
190    })
191}
192
193/// FAST-ROUTER batch twin (lane/fast-router, 2026-08-02). The concat-prime exactness fix
194/// (router_prefill_exact_on) routes prefill through router_gemv — m-invariant, but a
195/// per-(expert,token) GEMV program with zero operand reuse, so q35 board-2048 prefill paid
196/// -10% on the 5090. router_gemv_f32_w8_batch register-tiles (8x8 expert-x-token) the same
197/// per-row FP chains (BIT-IDENTICAL per row — kernel-check sweeps m=1..2048 on real router
198/// weights), so the t crossover below is pure perf, not a numeric config. Swept on-box
199/// (research/fast-router-20260802/crossover-router*.jsonl): plain wins t<=4, batch +7-9%
200/// at t=8, 1.9x at t=16 rising to 3.45x at t=2048 — MIN_T=8. Decode t=1 and spec verify
201/// t<8 keep the plain w8 form. MEMRA_ROUTER_BATCH=0 forces plain at every t (rollback
202/// seam, perf-only: bits are equal by the kernel-check gate).
203/// Killed arms (same sweep, JSONL is the record): the 8x16 tile lost to 8x8 at every t
204/// (128-accumulator register pressure beats the halved w-traffic), and the same-shape
205/// sigmoid_dot_rows twin (out_f=1) measured 0.62-0.89x at every prefill t
206/// (launch-latency-bound, ~7us/layer at m=2048) — both bit-identity-PASSED before dying.
207pub const ROUTER_BATCH_MIN_T: usize = 8;
208pub fn router_batch_on() -> bool {
209    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
210    *ON.get_or_init(|| std::env::var("MEMRA_ROUTER_BATCH").as_deref() != Ok("0"))
211}
212mod cpu_experts;
213pub mod moe_cache;
214pub mod spill;
215mod spill_pread;
216#[cfg(memra_cutlass)]
217pub mod cutlass_ffi;
218pub mod mmq_ffi;
219pub mod f16_ffi;
220pub mod prime_graph;
221pub mod fp8_ffi;
222
223// Fatbins are EMBEDDED (crates-release lane, 2026-08-04): build.rs still writes them to
224// OUT_DIR, but the bytes ship inside the binary via include_bytes! and load through
225// cuModuleLoadData. Distribution contract: a prebuilt or cargo-installed binary must be
226// self-contained — the old baked OUT_DIR *paths* pointed at the builder's temp dir and
227// broke every machine that wasn't the build machine. Same bytes, same module image;
228// the runtime MEMRA_GEMM_FATBIN tune-seam override below is preserved.
229const FATBIN: &[u8] = include_bytes!(env!("MEMRA_ENGINE_FATBIN"));
230const HYBRID_FATBIN: &[u8] = include_bytes!(env!("MEMRA_HYBRID_FATBIN"));
231const QMATVEC_FATBIN: &[u8] = include_bytes!(env!("MEMRA_QMATVEC_FATBIN"));
232const FLASH_FATBIN: &[u8] = include_bytes!(env!("MEMRA_FLASH_FATBIN"));
233const GEMM_FATBIN: &[u8] = include_bytes!(env!("MEMRA_GEMM_FATBIN"));
234const ROUTER_FATBIN: &[u8] = include_bytes!(env!("MEMRA_ROUTER_FATBIN"));
235/// spec_sample.cu: sampled-spec primitives (Philox Gumbel-max / softmax gather / residual sampler).
236const SAMPLE_FATBIN: &[u8] = include_bytes!(env!("MEMRA_SAMPLE_FATBIN"));
237
238/// TUNE SEAM (tools/sweep): a RUNTIME `MEMRA_GEMM_FATBIN=<path>` overrides the baked-in
239/// qmatvec_gemm.cu fatbin path (build.rs bakes the same name at COMPILE time via
240/// cargo:rustc-env — that constant is the default). Lets the sweep harness swap in a
241/// `-D`-tuned fatbin per process with NO rust rebuild. Unset at runtime => the
242/// compile-time default (zero behavior change).
243fn gemm_fatbin_bytes() -> std::borrow::Cow<'static, [u8]> {
244    assert!(!(portable_mma_gated() && std::env::var_os("MEMRA_GEMM_FATBIN").is_some()),
245            "MEMRA_GEMM_FATBIN overrides are not allowed in the portable CUDA lane");
246    match std::env::var("MEMRA_GEMM_FATBIN") {
247        Ok(path) => std::borrow::Cow::Owned(
248            std::fs::read(&path).unwrap_or_else(|e| panic!("MEMRA_GEMM_FATBIN read {path}: {e}"))),
249        Err(_) => std::borrow::Cow::Borrowed(GEMM_FATBIN),
250    }
251}
252
253/// Phase A (ARCHITECTURE-H100.md): sm_90a re-enables the portable-PTX tensor-core paths
254/// (int8 mma.m16n8k32/k16.s8, bf16 m16n8k16, ldmatrix, cp.async — all sm_80-class, native
255/// on Hopper) that the portable boot lane gates off. Dispatch guards that used to test
256/// `cfg!(memra_portable_cuda)` test this instead; sm_89 keeps the pure-portable behavior.
257/// The sm_120a/sm_100a-only MMA kinds (mxf4nvf4, kind::f8f6f4) are NOT covered — their
258/// launchers stay fail-closed stubs on 90a and their dispatch arms stay arch-gated.
259pub(crate) const fn portable_mma_gated() -> bool {
260    cfg!(memra_portable_cuda) && !cfg!(memra_hopper_mma)
261}
262
263/// The legacy quantized prefill GEMMs are tuned and validated for sm_120a; sm_90a re-admits
264/// them through the Hopper-MMA lane (int8 m16n8k32.s8 is sm_80-class PTX).  Keep the policy
265/// in a pure helper so the dispatch guard can be regression-tested without constructing an
266/// Engine or allocating a GPU tensor.
267const fn legacy_quant_gemm_allowed(portable_cuda: bool, hopper_mma: bool, no_gemm: bool) -> bool {
268    (!portable_cuda || hopper_mma) && !no_gemm
269}
270
271// ---- KV-cache format selection (kvbytes lane, 2026-07-08; default OFF = daily config) ----
272// `MEMRA_KV_K` = q8_0 (default, 34 B/32elem) | fp8 (raw e4m3, 32 B — the -6% K-bytes arm)
273// `MEMRA_KV_V` = q5_1 (default, 24 B/32elem) | q4_0 (18 B, -25% V bytes) | fp8 (32 B, +33%)
274// A non-default format is a NEW NUMERIC CONFIG: its own run-gen argmax baseline is legal,
275// but the gate battery (kernel-check, run-spec self-consistency) must pass WITHIN it and
276// the choice is explicit env, never silent. flash_attn.cu is compiled once per format pair
277// (build.rs); the kernels keep their names — Engine::new just loads the matching fatbin.
278const FLASH_FATBIN_VQ4: &[u8] = include_bytes!(env!("MEMRA_FLASH_FATBIN_VQ4"));
279const FLASH_FATBIN_VF8: &[u8] = include_bytes!(env!("MEMRA_FLASH_FATBIN_VF8"));
280const FLASH_FATBIN_KF8: &[u8] = include_bytes!(env!("MEMRA_FLASH_FATBIN_KF8"));
281const FLASH_FATBIN_KF8VQ4: &[u8] = include_bytes!(env!("MEMRA_FLASH_FATBIN_KF8VQ4"));
282const FLASH_FATBIN_KF8VF8: &[u8] = include_bytes!(env!("MEMRA_FLASH_FATBIN_KF8VF8"));
283
284/// KV format policy moved to the shared `memra-kv` crate (Phase D); re-exported so the
285/// fatbin router below and every existing `crate::kv_blk_bytes()` call site is unchanged.
286pub use memra_kv::{kv_blk_bytes, kv_cache_formats};
287
288/// The flash_attn fatbin matching the selected KV formats.
289fn flash_fatbin_bytes() -> &'static [u8] {
290    match kv_cache_formats() {
291        ("q8_0", "q5_1") => FLASH_FATBIN,
292        ("q8_0", "q4_0") => FLASH_FATBIN_VQ4,
293        ("q8_0", "fp8")  => FLASH_FATBIN_VF8,
294        ("fp8",  "q5_1") => FLASH_FATBIN_KF8,
295        ("fp8",  "q4_0") => FLASH_FATBIN_KF8VQ4,
296        ("fp8",  "fp8")  => FLASH_FATBIN_KF8VF8,
297        other => unreachable!("kv_cache_formats returned {other:?}"),
298    }
299}
300
301/// TUNE SEAM (tools/sweep): kernel1 (Q8_0/Q4_K/Q5_K) launch-tile override,
302/// `MEMRA_GEMM_K1_LAUNCH="BM,BN,NWARP"`. MUST match the `-D K1_BM/K1_BN/NWARP` the swept
303/// fatbin was compiled with (the .cu tile and the host launch grid/block have to agree —
304/// the hardcoded (128,128,8) in qmatvec_gemm/qmatvec_gemm_raw is the shipped default).
305/// Kernel2 (Q6_K/NVFP4) launch is untouched. Unset or malformed => None => shipped
306/// defaults (zero behavior change).
307fn k1_launch_override() -> Option<(u32, u32, u32)> {
308    static K1: std::sync::OnceLock<Option<(u32, u32, u32)>> = std::sync::OnceLock::new();
309    *K1.get_or_init(|| {
310        let v = std::env::var("MEMRA_GEMM_K1_LAUNCH").ok()?;
311        let p: Vec<u32> = v.split(',').filter_map(|s| s.trim().parse().ok()).collect();
312        match p.as_slice() { [bm, bn, w] => Some((*bm, *bn, *w)), _ => None }
313    })
314}
315
316/// H100 wgmma prefill-GEMM seam (task 8, ARCHITECTURE-H100.md): OPT-IN (MEMRA_WGMMA=1).
317/// v0 verdict (2026-07-26, N=5 pp512 9B-Q8_0): wgmma 3845 tok/s vs MMQ 8692 — the
318/// standalone harness's "688us MMQ ref" was a pp2048-shape figure, so v0 (unpipelined,
319/// 64x64 tile, wait_group<0> every 32-K step) is ~3x SLOWER per launch at m=512 model
320/// shapes. Default stays MMQ until the pipelined version beats it N=5 (repo law).
321/// Correctness stays pinned regardless: kernel-check's wgmma case is cfg-gated, not env-gated.
322pub(crate) fn wgmma_gemm_enabled() -> bool {
323    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
324    *V.get_or_init(|| std::env::var("MEMRA_WGMMA").as_deref() == Ok("1"))
325}
326
327/// TUNE SEAM: keys per FA-decode split (`MEMRA_FA_SPLIT` forces a fixed size; default 64). Smaller
328/// splits raise grid.y so grid = n_head_kv * n_splits fills the 82 SMs at short/mid ctx (vec path
329/// launches only n_head_kv=8 CTAs per split). Swept clock-locked 2026-07-03 (graph tg128): 32 beat
330/// 64 at ctx 128/512 (+0.5/+1.2%) and lost at 2048 (-3%) — BUT the adaptive 32/64 default BROKE the
331/// MTP spec-decode exact-match gate (run-spec K=1/2 self-consistency FAIL with 32; PASS with 64):
332/// the split count changes the combine's FP summation order, and the spec verify's batched forward
333/// only argmax-matches single-step decode under the 64-split order on real prompts. Spec exactness
334/// (the bigger lever) outranks a <=1.2% decode win -> default stays FIXED 64; sweeps use the env.
335/// Takes t_kv so eager, _dc capture, and fa_geom_eager stay signature-compatible for future
336/// adaptive retries (any retry MUST pass run-spec self-consistency first).
337/// Minimum t_kv for the warp-per-token vec FA path (below it the scalar path's 4x-more-blocks
338/// hides latency better — measured crossover, see `fa_decode`). Shared by fa_decode / fa_decode_dc /
339/// fa_geom_eager / fa_decode_rows-eligibility (spec verify) so the kernel pick NEVER diverges
340/// between eager decode and the verify (the spec-exactness law).
341pub const FA_VEC_MIN_TKV: usize = 96;
342/// Env-overridable crossover (MEMRA_FA_VEC_MIN, default FA_VEC_MIN_TKV). The 96 floor was
343/// measured on the qwen geometry (nkv=2); gemma4 SWA layers run nkv=8 = 4x the vec grid,
344/// which moves the crossover — sweep per model, adopt per the battery.
345pub fn fa_vec_min_tkv() -> usize {
346    static V: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
347    *V.get_or_init(|| std::env::var("MEMRA_FA_VEC_MIN").ok()
348        .and_then(|v| v.parse().ok())
349        .unwrap_or_else(|| FA_VEC_MIN_DEFAULT.load(std::sync::atomic::Ordering::Relaxed)))
350}
351
352/// f16-P/V class (DEFAULT since 2026-07-23 stamp v4; MEMRA_FA_F16PV=0 = f32-class rollback):
353/// llama-fa=1-style f16 P + f16 P@V accumulation on the hd512/SWA prefill stamps
354/// (KQ/softmax/normalize stay f32). Laptop stamp: 12B 1.045x, 31B 0.979x vs llama.
355///
356/// SPEC-SERVING FLIP (2026-07-26, the wkv acceptance-law pattern): with MEMRA_DRAFT set the
357/// default is OFF. f16 P/V shifts the PRIME's hidden states/KV in the sub-argmax logit
358/// space the drafter feeds on — argmax gates stay MATCH while depth acceptance falls off a
359/// cliff (26B d1736 0.883 -> 0.405, -40% e2e; f16pv-off alone restores 0.846/314 tok/s —
360/// the perf-ci acceptance battery is the only gate that sees this class). Explicit
361/// MEMRA_FA_F16PV always wins; plain serving keeps the f16 prefill win.
362pub fn fa_f16pv_on() -> bool {
363    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
364    *ON.get_or_init(|| std::env::var("MEMRA_FA_F16PV").map(|v| v != "0")
365        .unwrap_or_else(|_| std::env::var("MEMRA_DRAFT").is_err()))
366}
367
368/// hd512 head-pair arm (DEFAULT since stamp v4; MEMRA_FA512_HP=0 reverts to sp16): GQA
369/// ncols2=2 — 2 heads per CTA share each staged K/V tile, Q register-resident. Engages
370/// when n_head is even and the GQA group (n_head/n_head_kv) is even.
371pub fn fa512_hp_on() -> bool {
372    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
373    *ON.get_or_init(|| std::env::var("MEMRA_FA512_HP").as_deref() != Ok("0"))
374}
375
376/// SWA head-pair arm (DEFAULT since stamp v4; MEMRA_FAW_HP=0 reverts to p1): llama-class
377/// windowed geometry — 32 q-rows x 2 heads per CTA sharing staged K/V, f16 P@V
378/// accumulation. Even n_head and even GQA group required (guarded per call).
379pub fn faw_hp_on() -> bool {
380    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
381    *ON.get_or_init(|| std::env::var("MEMRA_FAW_HP").as_deref() != Ok("0"))
382}
383
384/// 4-warp sp16 experiment arm (MEMRA_FA512_W4=1, requires the f16pv door): GEMM0 split-K
385/// 4-way + GEMM1 4x128 O-dims. Own partial-sum order — oracle-band gated. Returns warp
386/// count (2 = base sp16). 8-warp arm measured NEGATIVE 2026-07-23 (jsonl) and removed.
387pub fn fa512_wide_warps() -> usize {
388    static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
389    *N.get_or_init(|| match std::env::var("MEMRA_FA512_W4").as_deref() {
390        Ok("1") => 4, _ => 2,
391    })
392}
393
394/// hd-512 vec crossover floor (MEMRA_FA512_MIN, default 512) — shared by fa_decode dispatch
395/// and the gemma global-layer rows/parity call sites.
396pub fn fa512_min_tkv() -> usize {
397    static FA512_MIN: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
398    *FA512_MIN.get_or_init(|| std::env::var("MEMRA_FA512_MIN").ok()
399        .and_then(|v| v.parse().ok()).unwrap_or(512))
400}
401/// Per-model crossover default, set at model load BEFORE the first decode (per-model
402/// numeric-config adoption law). qwen keeps the measured 96; gemma4 (nkv=8 SWA) measured
403/// vec-always fastest: 119.9 (96) / 130.0 (48) / 133.2 (1) tok/s tg128-regime, 2026-07-10.
404pub static FA_VEC_MIN_DEFAULT: std::sync::atomic::AtomicUsize =
405    std::sync::atomic::AtomicUsize::new(FA_VEC_MIN_TKV);
406/// Per-model windowed-split default (MEMRA_FA_SPW overrides): gemma MoE (26B, nkv=8) measured
407/// 32 (grid-limited t=1 under the raw-e4m3 sV ceiling, 2026-07-12); dense gemma (31B)
408/// measured 64 (37.13/37.12 vs 36.87/36.86 at 1.7k, N=2 — different attention geometry).
409pub static FA_SPW_DEFAULT: std::sync::atomic::AtomicUsize =
410    std::sync::atomic::AtomicUsize::new(32);
411/// Per-model hd512 (gemma globals) split default (MEMRA_FA_SP512 overrides): 26B measured 16
412/// (2026-07-11 N=2), dense 31B measured 32 (36.86/36.93 vs 36.73/36.73 at 1.7k, 2026-07-12).
413/// fused t=1 q4_0 pair/triple row mapping: true = mr1 (one row/warp). Per-model default
414/// (dense gemma wins +1.1% short / +0.6% depth on the 31B; MoE 26B REGRESSES −1.2% —
415/// its shared-expert fused2 shapes lose to the finer grid). MEMRA_Q40_MR env still wins.
416pub static FUSED_MR1_DEFAULT: std::sync::atomic::AtomicBool =
417    std::sync::atomic::AtomicBool::new(false);
418/// Per-model router-GEMV form (2026-07-31): the 8-warp twin is +8.8% on the H100 q35
419/// decode step (router was 14.8% of it) with argmax + spec self-consistency green on
420/// qwen-class MoE both rigs. The gemma-4 26B knife-edge block (2026-07-31, single
421/// synthetic prompt) was RE-ARBITRATED 2026-08-01 on 6 real prompts — gate outcomes
422/// identical to the lone-warp arm, +13% g26 decode — so gemma4 rides the default too
423/// (research/g26-decode-20260801/). MEMRA_ROUTER_V2 env overrides either way.
424pub static ROUTER_W8_DEFAULT: std::sync::atomic::AtomicBool =
425    std::sync::atomic::AtomicBool::new(true);
426pub static FA_SP512_DEFAULT: std::sync::atomic::AtomicUsize =
427    std::sync::atomic::AtomicUsize::new(16);
428/// Per-model rms_norm block size (per-model numeric-config law: the per-thread partial-sum
429/// split changes with blockDim -> different FP order -> battery-arbitrated per model).
430/// qwen keeps the shipped 256; gemma4 adopts 1024 (single-row 2816-col norms are one-block
431/// latency-bound at 256 threads — 7us/launch measured).
432pub static RMS_BLOCK_DEFAULT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(256);
433/// gemma4 fa split ladder switch (set at model load; see fa_split_keys).
434pub static FA_SP_GEMMA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
435/// Per-model stream-k override for SPEC serving (-1 = unset → env/default; 0 = force
436/// tiling; 1 = force sk). Set by generate_spec_gemma per model tier — the sk autotune's
437/// per-process kernel coin made 12B-class spec cells bimodal, while the 26B's drafter
438/// measures BETTER under sk's fold order (2026-07-27). mmq_ffi reads this before the env.
439pub static MMQ_SK_FORCE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
440/// Per-model FP8-KV door — lives in memra-kv next to the format policy it drives
441/// (re-export keeps `crate::KV_FP8_FORCE` setters in model.rs/hybrid.rs working).
442pub use memra_kv::KV_FP8_FORCE;
443pub(crate) fn rms_block() -> u32 {
444    static V: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
445    *V.get_or_init(|| std::env::var("MEMRA_RMS_BLOCK").ok()
446        .and_then(|v| v.parse().ok())
447        .unwrap_or_else(|| RMS_BLOCK_DEFAULT.load(std::sync::atomic::Ordering::Relaxed)))
448}
449
450pub(crate) fn fa_split_keys(t_kv: usize, n_head_kv: usize) -> usize {
451    static S: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
452    if let Some(forced) = *S.get_or_init(|| {
453        std::env::var("MEMRA_FA_SPLIT").ok().and_then(|v| v.parse().ok())
454            .filter(|&s: &usize| s >= 8 && s % 8 == 0)
455    }) { return forced; }
456    // CTX-ADAPTIVE default (2026-07-05 40k sweep: sp32 24.5 vs sp128 26.0 tok/s = +5.8% — at
457    // deep ctx the n_splits count explodes (40k/32 = 1265 splits x 8 kv-heads) and the combine
458    // + partial-buffer cost dominates; at short ctx small splits fill the SMs). Exactness: split
459    // size only changes the PARTITION of keys; the rows/combine order per split is fixed and the
460    // gate battery (kernel-check + run-spec K=1..8) arbitrates every default change.
461    //
462    // SM-AWARE SHORT-CTX RUNG (2026-07-06 g7e): the 32-key rung was tuned on the 82-SM 5090.
463    // On 188 SMs the vec grid (n_head_kv x n_splits CTAs) starves at short ctx — the 35B has
464    // n_head_kv=2, so ctx128/split32 = 8 CTAs on 188 SMs. Measured on g7e (N=1 sweep + N=3
465    // interleaved confirm): 35B ctx128 sp16 179 vs sp32 161 (+11%), ctx512 178 vs 158, ctx2048
466    // flat, ctx>=4096 sp64 edges sp16 by ~3%; 27B ctx128 70.9 vs 66.3 (+7%); 9B 177 vs 163
467    // (+9%). Rigs <=100 SMs keep the validated 5090 ladder EXACTLY (default unchanged there —
468    // rig-divergence law: this branch is measured on 188 SMs only).
469    // gemma4 all-16 ladder probe REVERTED (2026-07-10): +1.3 plain at d1736 (157.5 vs 156.2)
470    // but depth VERIFY collapsed (spec 203.5 -> 169 — the windowed rows' per-row combine over
471    // 64 splits). The mixed default (swa nkv=8 -> 32, globals nkv=2 -> 8-ladder) stays; a
472    // caller-split policy would break row-vs-decode split parity. FA_SP_GEMMA kept as a seam.
473    if FA_SP_GEMMA.load(std::sync::atomic::Ordering::Relaxed)
474        && std::env::var("MEMRA_FA_SP16").as_deref() == Ok("1") {
475        return if t_kv <= 8192 { 16 } else if t_kv <= 16384 { 64 } else { 128 };
476    }
477    let big_rig = fa_sm_count() >= 128;
478    if big_rig {
479        let _ = n_head_kv;
480        if t_kv <= 2048 { 16 } else if t_kv <= 16384 { 64 } else { 128 }
481    } else if n_head_kv <= 4 {
482        // KV-HEAD-AWARE RUNG (2026-07-08, 5090): the 8192->32 rung was validated on kv=8 models
483        // (27B/9B: 8 heads x n_splits fills 82 SMs). The 35B has n_head_kv=2 — at ctx512/sp32
484        // the vec grid is 2 x 20 = 40 CTAs on 82 SMs (half idle). Measured (35B, run-gen 128tok
485        // N=1 sweep + N=3 confirm): sp8 162.1 / sp16 161.3 / sp32 159.4 at short ctx.
486        // DEPTH TAPER (same day, the deep-ctx lesson re-learned on this rung): sp8 at d6257 =
487        // 782 splits -> combine + partial-buffer cost dominates (141.2 tok/s); the d6257 sweep
488        // says sp64 = 153.0 (sp16/32 147, sp96 147.6, sp128 141). Few-kv-head models need the
489        // taper EARLIER than kv=8 (per-split grid 4x thinner, same per-split combine cost).
490        // Crossover hunt: sp8 vs sp64 = 156.7/155.9 at d3072, 151.7/155.6 at d4096 -> boundary 3072.
491        // RUNG RE-SWEPT UNDER THE DEEP KERNEL (2026-08-02, lane/ladder-3072 — the stale-verdict
492        // law: the 3072 boundary was calibrated on the conflicted v4 core; the deep rewrite cut
493        // vec cost ~1.2-1.4x while combine scales with n_splits, so sp8's combine bill
494        // dominates far earlier). Kernel receipts (quiet-rig nsys, deep vec + combine us):
495        // d1024 sp8 17.1 vs sp64 10.6; d2048 31.0 vs 12.2; d3072 44.0 vs 18.3. e2e run-gen
496        // tg128 N=3 interleaved (KAT + q35, research/ladder-3072-20260802/): sp8 loses at
497        // EVERY depth >= 1024 (KAT d2048 182.6 vs 188.0 = -2.9%, d3072 175.9 vs 186.4 =
498        // -5.6%; q35 d4096 169.2 vs 182.6 = -7.4%); d512 flat (+-0.2%, inside noise). sp32
499        // ties sp64 within noise in the mid band and loses at d4096 -> no extra rung.
500        // Boundary 3072 -> 512: sp8 keeps only the short-ctx band it was validated on
501        // (ctx128-512); sp64 takes over where the deep kernel made combine the bill.
502        if t_kv <= 512 { 8 } else if t_kv <= 16384 { 64 } else { 128 }
503    } else {
504        if t_kv <= 8192 { 32 } else if t_kv <= 16384 { 64 } else { 128 }
505    }
506}
507
508/// SM count of device 0, cached (used by fa_split_keys' rig-size rung; primary-context query,
509/// same attribute Engine::batched_variant reads).
510fn fa_sm_count() -> i32 {
511    static N: std::sync::OnceLock<i32> = std::sync::OnceLock::new();
512    *N.get_or_init(|| {
513        cudarc::driver::result::init().ok();
514        cudarc::driver::result::device::get(0)
515            .and_then(|d| unsafe { cudarc::driver::result::device::get_attribute(
516                d, cudarc::driver::sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT) })
517            .unwrap_or(82)
518    })
519}
520
521/// FA-prefill kernel-name suffix for a head_dim (the template-stamped twins in flash_attn.cu):
522/// 256 = the original names (qwen35 class, dispatch unchanged), 128 = `_hd128` (MiniMax-M3).
523/// Any other dim errors — callers gate to sdpa_naive before dispatching FA.
524fn fa_hd_suffix(head_dim: usize) -> Result<&'static str, Box<dyn std::error::Error>> {
525    match head_dim {
526        256 => Ok(""),
527        128 => Ok("_hd128"),
528        d => Err(format!("fa_prefill: no kernel stamped for head_dim={d} (only 256/128); \
529                          callers must gate to sdpa_naive").into()),
530    }
531}
532
533/// Quant type codes matching qmatvec.cu QType enum.
534pub const QT_Q8_0: i32 = 0;
535pub const QT_Q4_K: i32 = 1;
536pub const QT_Q6_K: i32 = 2;
537pub const QT_Q5_K: i32 = 3;
538pub const QT_Q3_K: i32 = 4;
539pub const QT_IQ4_XS: i32 = 5;
540pub const QT_IQ3_S: i32 = 6;
541pub const QT_NVFP4: i32 = 7;
542/// Checkpoint-native FP8-E4M3 (MEMRA_ST_E4M3, lane e4m3dec): raw safetensors e4m3 weight bytes
543/// [out_f, in_f] row-major (row_bytes == in_f), per-tensor f32 weight_scale in GpuTensor `scale`
544/// (fused at the mmvq write / post-matmul scale_inplace). Decode = qmatvec_e4m3_mmvq (+ _b2/_b4/_b8
545/// batched twins); prefill (m>=16) = the cuBLASLt FP8 GEMM on the SAME resident bytes (fp8_ffi.rs)
546/// — ONE weight copy total, no Q8_0 re-encode duplicate.
547pub const QT_F8_E4M3: i32 = 10;
548/// Device-side tag for the A6 SPLIT-PLANE repacked NVFP4 layout (Stage-A generic kernel only;
549/// GpuTensor keeps qtype=QT_NVFP4 + an `rp` flag — this tag never lives in a GpuTensor).
550pub const QT_NVFP4_RP: i32 = 9;
551/// Unquantized f32 weight (safetensors MoE Path A: experts dequantized to f32 host-resident).
552pub const QT_F32: i32 = 8;
553pub const QT_BF16: i32 = 11;
554pub const QT_Q4_0: i32 = 12; // gemma-4 QAT GGUF weight format (18B/32: fp16 d + nibbles)
555/// GGUF Q2_K. Appended after the existing Q4_0 code so kernel ABI values do not move.
556/// Mixed-expert artifacts use the generic f32-dequant staged kernel until a target-rig-gated
557/// dp4a/MMQ implementation exists.
558pub const QT_Q2_K: i32 = 13;
559/// Checkpoint-native FP8-E4M3 with a BLOCK-128 weight-scale GRID (lane/fp8-blk128-decode,
560/// 2026-08-05) — the Qwen-official FP8 / DeepSeek-V3 scale class. Same raw e4m3 bytes as
561/// `QT_F8_E4M3` ([out_f, in_f] row-major, row_bytes == in_f), but the dequant scale is
562/// `GpuTensor::Quant.blk` (`Fp8BlockScales`, [ceil(out_f/128), ceil(in_f/128)] f32) and the
563/// scalar `scale` field is 1.0 by the layout contract.
564///
565/// WHY A DISTINCT CODE rather than `QT_F8_E4M3` + a `blk` flag: every existing QT_F8_E4M3
566/// consumer (qmatvec_e4m3_mmvq and its batched/fused twins, e4m3_fused_params,
567/// matmul_pre_dual_noscale's F8 arm, try_fp8_gemm) threads exactly ONE scalar weight scale. Under
568/// a shared code, any consumer that was not taught the grid would still MATCH and would dequant
569/// every tile at scale 1.0 — a silent numeric corruption. Under a distinct code every untaught
570/// consumer refuses loudly instead (`mmvq_supports`/`gemm_supports`/`mmq_supports` return false;
571/// the mmvq name match panics), so a missed dispatch site is a crash or a refusal receipt, never
572/// wrong numbers. Decode = `qmatvec_e4m3_blk_mmvq`; prefill (m>=16) = the per-block FP8 MMQ tile
573/// on the SAME resident bytes+grid (fp8_ffi::try_fp8_blk_mmq) — ONE weight copy total.
574pub const QT_F8_E4M3_BLK: i32 = 14;
575
576/// Engine device context: CUDA context, stream, loaded kernel modules, cuBLASLt (via runtime::Gpu).
577pub struct Engine {
578    pub gpu: memra_runtime::Gpu,
579    module: Arc<CudaModule>,
580    hybrid: Arc<CudaModule>,
581    qmatvec: Arc<CudaModule>,
582    flash: Arc<CudaModule>,
583    /// FP8-GLOBALS module (2026-07-11): the kf8vf8 fatbin loaded ALONGSIDE the default —
584    /// gemma GLOBAL layers (hd512) append + attend in e4m3 (dequant-latency arc, HANDOVER).
585    /// Lazy: loaded on first global-format use; None until then.
586    flash_g: std::sync::OnceLock<Arc<CudaModule>>,
587    gemm: Arc<CudaModule>,
588    router: Arc<CudaModule>,
589    /// Sampled-spec kernels (research/sampled-spec-impl-map.md piece A).
590    sample: Arc<CudaModule>,
591    /// EDGE-1 §B: one shared SLRU expert-residency cache, lazily built on first MoE dispatch under
592        /// MEMRA_MOE_CACHE. `Mutex` makes it multi-agent safe (§E.2); the lock covers only lookup/admit/
593    /// memcpy-issue (µs), NOT the GEMM, so streams still overlap. `None` => cache disabled.
594    moe_cache: Mutex<Option<crate::moe_cache::MoeSlotCache>>,
595    /// Exact retained expert-block lengths collected after model load. Mixed-layout models use
596    /// this inventory to preallocate fixed-address size classes instead of sizing every slot to
597    /// the single largest block. The cache still owns every address for its full lifetime.
598    moe_cache_layout: Mutex<Option<Vec<usize>>>,
599    /// CAPTURE-RETAIN mode (graph arc, 2026-07-12): while a graph capture (and its allocator
600    /// warmups) runs, every Engine allocation is ALSO kept alive here — a captured graph's
601    /// transient buffers must never return to the pool, or later allocations (e.g. the spec
602    /// verify between replays) reuse their addresses and the replay reads/writes live memory
603    /// (the draft-graph corruption root cause). Fast-path cost when off: one relaxed atomic.
604    capture_keep_on: std::sync::atomic::AtomicBool,
605    /// VERIFY-EXACT scope (dflash lane, 2026-07-13): when set, matmul/matmul_pre skip the
606    /// m>=16 prefill-GEMM branches so a t>=16 batched VERIFY rides the decode-exact b-tier
607    /// class (the parity law). The t=16 dflash verify tripped the GEMM threshold — 770us/
608    /// matmul (54% of the round) AND a different FP order than decode (issue-10 landmine).
609    verify_exact: std::sync::atomic::AtomicBool,
610    capture_keep: Mutex<Vec<Box<dyn std::any::Any + Send>>>,
611    /// EDGE-1 §C.2: dedicated H2D copy stream for async prefetch (event-synced to the compute stream).
612    pub copy_stream: Arc<CudaStream>,
613    /// Resident CUTLASS NVFP4 prefill scratch (workspace + a_packed + sfa_linear + sfa_sw + y + alpha),
614    /// allocated ONCE and grown to the largest prefill GEMM shape, then reused per-call. Removes the
615    /// 6 fresh allocations + alpha htod that `cutlass_fp4_gemm` did every prefill matmul (~200/prefill).
616    /// Safe as a single shared buffer because all GPU compute serializes on the one `gpu.stream` worker
617    /// thread (the server runs one GPU worker; no concurrent CUTLASS GEMMs share this scratch). `None`
618    /// until the first CUTLASS FP4 GEMM. Mutex guards lazy build/grow only (matches `moe_cache`).
619    #[cfg(memra_cutlass)]
620    cutlass_scratch: Mutex<Option<crate::cutlass_ffi::CutlassScratch>>,
621    /// FP8-ACT PREFILL scratch (MEMRA_PP_FP8): quantized-activation buffer + scale block + cuBLASLt
622    /// workspace, allocated once and grown to the largest prefill m*k (see fp8_ffi.rs). `None`
623    /// until the first FP8 prefill GEMM; Mutex guards lazy build/grow only (matches cutlass_scratch).
624    fp8_scratch: Mutex<Option<crate::fp8_ffi::Fp8Scratch>>,
625    /// f16-P/V door: pooled V re-encode buffer (bf16->f16) for the hd512 _pre path. Lazy-grow;
626    /// per-call cudaMalloc was a laptop-regression suspect (VRAM pressure, 31B nkv=4 = 4x bytes).
627    fa_vf16_scratch: Mutex<Option<CudaSlice<u8>>>,
628    /// Pooled fa-decode split partials (part_o, part_m, part_l): per-call zeros() was 3
629    /// alloc+memset pairs per fa launch (~144 mem nodes per decode token — the graph door's
630    /// residual launch tax) — lazy-grow, memset-prefix per use, stream-ordered reuse.
631    fa_part_pool: Mutex<Option<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>)>>,
632    /// Retired fa-part pool generations (#68): old buffers whose addresses captured graphs may
633    /// have baked — kept alive for the Engine's lifetime instead of returning to the async pool
634    /// (see the RETIRE-ON-GROW comment at the realloc sites). Doubling growth bounds the total.
635    fa_part_retired: Mutex<Vec<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>)>>,
636    /// name -> resolved CudaFunction (capture-safe lookups; see `func`).
637    fn_cache: Mutex<std::collections::HashMap<String, CudaFunction>>,
638    f16_scratch: Mutex<Option<crate::f16_ffi::F16Scratch>>,
639    /// RANK1 LEVER (parallel argmax): resident pass-1 partials scratch (part_v[NB] f32, part_i[NB] i32),
640    /// allocated ONCE on first parallel-argmax call and reused. Stable pointers so the 2-pass argmax
641    /// is CUDA-graph-capturable (the buffer is referenced by both captured passes; lazy-allocated
642    /// before capture under the generate_graph tracking-off window so it carries no events).
643    argmax_partials: Mutex<Option<(CudaSlice<f32>, CudaSlice<i32>)>>,
644    /// ARC B (chunk-prime dequant-once): resident bf16 K/V workspace for `fa_prefill_view_ws`
645    /// ((K bytes, V bytes) u8 buffers holding [t_kv, kv_dim] bf16). Grown lazily to the largest
646    /// (t_kv, kv_dim) seen, REUSED across layers/chunks/calls (contents rewritten per launch —
647    /// safe because all compute serializes on the one gpu.stream). ~82MB at 40k ctx on the 27B.
648    prime_deqw_ws: Mutex<Option<(CudaSlice<u8>, CudaSlice<u8>)>>,
649    /// LAUNCH-STRUCTURE STAGE 1: persistent PINNED (cacheable, flags=0) host staging buffer for the
650    /// fused-router sel/w readback — one async DtoH pair + ONE sync instead of two synced dtohs.
651    /// Grown lazily; reused every MoE layer (single-threaded decode serializes on the sync).
652    router_stage: Mutex<Option<PinnedStage>>,
653}
654
655/// FAVENDOR lane env gate (2026-07-08): MEMRA_FA_V2=1 dispatches the llama-fattn-vec-mechanism
656/// decode kernels (fa_decode_vec_q_v2 / fa_decode_vec_q_rows_v2 / fa_decode_vec_q_v2_dc):
657/// tile-batched online softmax (one alpha rescale per 32-key tile instead of per key) + wide-load
658/// block dequant in the staging phase. NOTE rev2: llama's register streaming (no smem) was ALSO
659/// tried and measured 2x WORSE at depth in our gqa-warps frame — the smem KV-tile broadcast stays
660/// (see the kernel comment). NEW NUMERIC CONFIG (tile-level softmax regrouping changes FP order vs
661/// the per-key twins) — own argmax baseline; eager decode, the spec-verify rows path AND the
662/// graph _dc path switch TOGETHER (the spec-exactness law). Default OFF. Read per call (not
663/// OnceLock) so the gate battery can A/B within one process, matching the MEMRA_NO_FA_VEC pattern.
664fn fa_v2_on() -> bool {
665    // DEFAULT ON since 2026-07-08 (MEMRA_FA_V2=0 reverts): tile-batched online softmax, e2e
666    // measured across every model x depth — 35B 168.7->173.4 (d512) / 153.1->158.5 (d6257),
667    // 9B 131.2->132.7 / 108.4->124.5 (+15% — the engine-wide depth-slope fix), 27B 47.2->47.7 /
668    // 42.2->44.9. One-time numeric-config change; kernel-check + argmax + spec self-consistency
669    // + graph bit-identity green on all three models.
670    std::env::var("MEMRA_FA_V2").map(|v| v != "0").unwrap_or(true)
671}
672
673/// FA v3 gate (default ON since 2026-07-09; MEMRA_FA_V3=0 reverts to v2 — research/fa/fa_v3_design.md):
674/// HYBRID decode twins (fa_decode_vec_q_v3 / _rows_v3 / _v3_dc): llama's int8-dp4a K.Q with
675/// register-quantized Q (no K dequant, no K smem) + OUR CTA-shared staged bf16 V tile + OUR
676/// split partition/combine. NEW NUMERIC CONFIG (int8 Q quantization changes the K.Q accumulation
677/// vs the bf16-roundtrip FMA chain) — own argmax baseline; eager decode, the spec-verify rows
678/// path AND the graph _dc path switch TOGETHER (the spec-exactness law). Read per call so the
679/// gate battery can A/B within one process (the MEMRA_FA_V2 pattern).
680fn fa_v3_on() -> bool {
681    // DEFAULT ON since 2026-07-09 (MEMRA_FA_V3=0 reverts to v2): dp4a-K hybrid FA decode —
682    // fa kernel -21-23% at depth (micro), 35B spec p3 +5% (190->200, the last spec cell),
683    // d6257 +1.7%. Own numeric config; full battery green on 35B+9B incl graph bit-identity.
684    std::env::var("MEMRA_FA_V3").map(|v| v != "0").unwrap_or(true)
685}
686
687/// The v3 dp4a K path reads RAW q8_0 bytes (34B blocks) and stages q5_1 V verbatim — it is only
688/// correct on the DEFAULT KV formats — and needs dpl % 4 == 0 consecutive quants per lane
689/// (head_dim % 128 == 0; both daily models are hd256). All three dispatch sites share this
690/// predicate so the twins can never diverge.
691fn fa_v4_mode() -> &'static str {
692    static M: std::sync::OnceLock<String> = std::sync::OnceLock::new();
693    M.get_or_init(|| std::env::var("MEMRA_FA_V4").unwrap_or_default())
694}
695fn fa_v4_on() -> bool { fa_v4_mode() != "0" }   // DEFAULT ON 2026-07-10 (MEMRA_FA_V4=0 rollback)
696/// t_kv-conditional v4 pick (gemma depth lesson 2026-07-10: v4's key-per-lane pipeline starves
697/// at the 1024-window with short splits — MEMRA_FA_V4=0 measured depth plain 158.0 vs 156.7).
698/// Threshold MEMRA_FA_V4_MAX (default usize::MAX = unchanged behavior; gemma sets 1024 at load
699/// via FA_V4_MAX_DEFAULT). Applied at EVERY dispatch site (eager, rows, rows_w, dc) so verify
700/// stays kernel-family-identical to decode at the same t_kv.
701/// Per-model deep-ctx smem floor default (MEMRA_FA_SMEM_TKV env overrides): gemma pushes it
702/// above the 1024 window so the windowed decode + verify rows share the REGISTER family.
703pub static FA_SMEM_TKV_DEFAULT: std::sync::atomic::AtomicUsize =
704    std::sync::atomic::AtomicUsize::new(1024);
705pub static FA_V4_MAX_DEFAULT: std::sync::atomic::AtomicUsize =
706    std::sync::atomic::AtomicUsize::new(usize::MAX);
707pub fn fa_v4_at_pub(t_kv: usize) -> bool { fa_v4_at(t_kv) }
708fn fa_v4_at(t_kv: usize) -> bool {
709    static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
710    let mx = *M.get_or_init(|| std::env::var("MEMRA_FA_V4_MAX").ok()
711        .and_then(|v| v.parse().ok())
712        .unwrap_or_else(|| FA_V4_MAX_DEFAULT.load(std::sync::atomic::Ordering::Relaxed)));
713    fa_v4_on() && t_kv < mx
714}
715/// FA-DEEP gate (2026-08-02, lane fa-decode-deep): deep-ctx v4 twins
716/// (fa_decode_vec_q_v4_deep / _deep_dc) — the depth-decode lane's priced fix. Unlike
717/// v2/v3/v4 this is NOT a numeric config: the deep twins run the v4 program VERBATIM
718/// (same split partition, same softmax/accumulation order, same partials/combine) and only
719/// move the smem physical layout (bank de-conflict row pads) + the load schedule (next-tile
720/// L2 prefetch) — kernel-check pins bitdiff==0 vs the v4 twins across depths, so eager /
721/// rows-verify / graph / seqs stay mutually bit-identical wherever the threshold falls.
722/// Engages at t_kv >= MEMRA_FA_DEEP_MIN. The swept floor is 0 = ALWAYS ON where v4 ran
723/// (fa-deep-bench fine grid 96..6144, 2026-08-02: deep flat-or-better at EVERY depth,
724/// 1.01-1.26x, no losing cell — so there is no engagement boundary and no new
725/// capture-recapture edge; the env stays as a sweep/diagnostic seam only).
726/// MEMRA_FA_DEEP=0 is the rollback seam. Read per call so the battery + bench can A/B
727/// within one process (the v2/v3 pattern).
728pub const FA_DEEP_MIN_DEFAULT: usize = 0;
729fn fa_deep_at(t_kv: usize) -> bool {
730    if std::env::var("MEMRA_FA_DEEP").as_deref() == Ok("0") { return false; }
731    let min = std::env::var("MEMRA_FA_DEEP_MIN").ok().and_then(|v| v.parse().ok())
732        .unwrap_or(FA_DEEP_MIN_DEFAULT);
733    t_kv >= min
734}
735/// Public twin (kernel-check builds the deep-vs-v4 bit pin; bench sweeps the floor).
736pub fn fa_deep_at_pub(t_kv: usize) -> bool { fa_deep_at(t_kv) }
737
738fn fa_v3_active(head_dim: usize) -> bool {
739    // v3's dp4a-K walk reads raw q8_0 K bytes — no e4m3 arm; the fp8-KV arm (MEMRA_KV_FP8)
740    // must fall back like any non-default KV format (the rows_dc stream path asserts on it).
741    fa_v3_on() && head_dim % 128 == 0 && kv_cache_formats() == ("q8_0", "q5_1")
742        && !Engine::kv_fp8_on()
743}
744
745/// BATCHED-TICK increment 2 (2026-08-01): true iff a row at this t_kv would take the v4
746/// eager arm in `fa_decode_kvmod`'s dispatch — the exact precondition for the z-batched
747/// `fa_decode_vec_q_seqs_v4` twin to reproduce its per-seq program bit-identically.
748/// Mirrors the kvmod predicates: vec on + above the vec floor + hd256 + inside the v4
749/// window + the PRODUCTION v4 body (the noB3/stage phase probes are wrong-output) + the
750/// default flash module (no fp8-KV g-module). Callers must ALSO group rows on one
751/// `fa_split_keys` rung (the rows-twins' straddle law) before batching.
752pub fn fa_seqs_eligible(t_kv: usize, head_dim: usize) -> bool {
753    std::env::var("MEMRA_NO_FA_VEC").is_err()
754        && t_kv >= fa_vec_min_tkv()
755        && head_dim == 256
756        && fa_v4_at(t_kv)
757        && !matches!(fa_v4_mode(), "noB3" | "stage")
758        && !Engine::kv_fp8_on()
759}
760/// Public twin of the crate-private split ladder (kernel-check builds the seqs-vs-loop pin).
761pub fn fa_split_keys_pub(t_kv: usize, n_head_kv: usize) -> usize { fa_split_keys(t_kv, n_head_kv) }
762
763/// A raw pinned (page-locked, CACHEABLE — flags=0, not write-combined) host allocation for
764/// DtoH staging. cudarc's `alloc_pinned` uses CU_MEMHOSTALLOC_WRITECOMBINED, which is right for
765/// HtoD streams but pathologically slow for host READS — the router readback is host-read-heavy,
766/// so we allocate through `result::malloc_host` with flags=0 directly.
767struct PinnedStage {
768    ptr: *mut u8,
769    cap: usize,
770}
771unsafe impl Send for PinnedStage {}
772impl PinnedStage {
773    fn new(cap: usize) -> Result<Self, Box<dyn std::error::Error>> {
774        let ptr = unsafe { cudarc::driver::result::malloc_host(cap, 0)? } as *mut u8;
775        Ok(PinnedStage { ptr, cap })
776    }
777}
778impl Drop for PinnedStage {
779    fn drop(&mut self) {
780        let _ = unsafe { cudarc::driver::result::free_host(self.ptr as _) };
781    }
782}
783
784/// Number of pass-1 blocks for the parallel argmax (fan-out across SMs to saturate HBM). 256 blocks
785/// x 256 threads = 65536 threads covering the 248K-vocab scan in ~4 strided loads/thread.
786pub const ARGMAX_NB: usize = 256;
787
788/// crate-visible alias for the batched FA3 shim entry (hybrid_forward's batch arm).
789pub(crate) use memra_fa3_vl as fa3_vl_raw;
790
791unsafe extern "C" {
792    /// FA3 v10 shim (cu/fa3_prefill.cu): TMA-swizzled wgmma FA, fresh causal hd256.
793    fn memra_fa3_prefill(q16: *const core::ffi::c_void, k16: *const core::ffi::c_void,
794                        v16: *const core::ffi::c_void, o: *mut f32,
795                        t: i32, h: i32, hkv: i32, d: i32, scale: f32,
796                        stream: *mut core::ffi::c_void) -> i32;
797    /// batched varlen twin: host arrays of device pointers per seq (B <= 8).
798    pub(crate) fn memra_fa3_vl(q16s: *const *const core::ffi::c_void, k16s: *const *const core::ffi::c_void,
799                   v16s: *const *const core::ffi::c_void, os: *const *mut f32,
800                   ts: *const i32, b: i32, h: i32, hkv: i32, d: i32, scale: f32,
801                   stream: *mut core::ffi::c_void) -> i32;
802}
803
804/// STAGE-2 GROUPED DECODE: 8 expert weight-block device pointers passed BY VALUE as one kernel
805/// param (matches the CUDA `wptr8_t` struct: 8x 64-bit pointers, `#[repr(C)]` => identical
806/// layout). The pointers are SLRU cache-slot base addresses — fixed for the engine's lifetime
807/// (slots are never re-allocated), so passing raw values is stable across the launch.
808#[repr(C)]
809#[derive(Clone, Copy)]
810pub struct WPtr8(pub [u64; 8]);
811unsafe impl cudarc::driver::DeviceRepr for WPtr8 {}
812
813/// task #18 varlen GDN: per-seq args for gdn_chunk_{state,output}_mma_vl — one launch
814/// runs all B<=8 sequences' K4/K5 (CUDA `gdnseq_t`/`gdnvl_t`, layout-identical repr(C)).
815/// Raw addresses are valid for the launch: every referenced buffer outlives the call and
816/// all work is on the single compute stream (same discipline as the f16 GEMM FFI).
817#[repr(C)]
818#[derive(Clone, Copy, Default)]
819pub struct GdnSeqVl {
820    pub kb16: u64, pub gcum: u64, pub beta: u64, pub u: u64, pub wb16: u64,
821    pub y: u64, pub ssnap: u64, pub state_in: u64, pub state_out: u64,
822    pub q: u64, pub p: u64, pub o: u64,
823    pub k: u64, pub v: u64, pub g: u64, pub a: u64, pub w: u64,
824    pub t: i32, pub nc: i32,
825}
826unsafe impl cudarc::driver::DeviceRepr for GdnSeqVl {}
827#[repr(C)]
828#[derive(Clone, Copy)]
829pub struct GdnVl8(pub [GdnSeqVl; 8]);
830unsafe impl cudarc::driver::DeviceRepr for GdnVl8 {}
831
832/// task #22: per-seq wgmma-fused extras (CUDA `gdnw_t`/`gdnwvl_t`) — qb16 mirror +
833/// pre-masked Pb16, riding NEXT TO GdnSeqVl so the base struct stays untouched.
834#[repr(C)]
835#[derive(Clone, Copy, Default)]
836pub struct GdnWVl { pub qb16: u64, pub pb16: u64 }
837unsafe impl cudarc::driver::DeviceRepr for GdnWVl {}
838#[repr(C)]
839#[derive(Clone, Copy)]
840pub struct GdnWVl8(pub [GdnWVl; 8]);
841unsafe impl cudarc::driver::DeviceRepr for GdnWVl8 {}
842
843/// task #18 increment 3: per-seq PREP/TAIL args (CUDA `gdnprep_t`/`gdnprepvl_t`).
844#[repr(C)]
845#[derive(Clone, Copy, Default)]
846pub struct GdnPrepVl {
847    pub qkv: u64, pub conv_state: u64, pub conv_out: u64,
848    pub q_g: u64, pub k_g: u64, pub v_g: u64,
849    pub q_l2: u64, pub k_l2: u64,
850    pub beta_raw: u64, pub alpha: u64, pub beta: u64, pub g_log: u64,
851    pub o: u64, pub z: u64, pub gn: u64, pub gn16: u64,
852    pub kb16: u64,
853    pub qb16: u64,
854    pub t: i32, pub pad: i32,
855}
856unsafe impl cudarc::driver::DeviceRepr for GdnPrepVl {}
857#[repr(C)]
858#[derive(Clone, Copy)]
859pub struct GdnPrepVl8(pub [GdnPrepVl; 8]);
860unsafe impl cudarc::driver::DeviceRepr for GdnPrepVl8 {}
861
862/// task #18 (attn side): per-seq varlen FA args (CUDA `faseq_t`/`favl_t`).
863#[repr(C)]
864#[derive(Clone, Copy, Default)]
865pub struct FaSeqVl {
866    pub q: u64, pub k16: u64, pub v16: u64, pub o: u64, pub kf: u64, pub vf: u64,
867    pub t: i32, pub pad: i32,
868}
869unsafe impl cudarc::driver::DeviceRepr for FaSeqVl {}
870#[repr(C)]
871#[derive(Clone, Copy)]
872pub struct FaVl8(pub [FaSeqVl; 8]);
873unsafe impl cudarc::driver::DeviceRepr for FaVl8 {}
874
875/// task #18 (attn pre-FA): per-seq split/norm/rope/append args (CUDA `attnpre_t`).
876#[repr(C)]
877#[derive(Clone, Copy, Default)]
878pub struct AttnPreVl {
879    pub qf: u64, pub kf: u64, pub vf: u64,
880    pub q: u64, pub gate: u64, pub qn: u64, pub kn: u64,
881    pub kc: u64, pub vc: u64,
882    pub t: i32, pub pad: i32,
883}
884unsafe impl cudarc::driver::DeviceRepr for AttnPreVl {}
885#[repr(C)]
886#[derive(Clone, Copy)]
887pub struct AttnPreVl8(pub [AttnPreVl; 8]);
888unsafe impl cudarc::driver::DeviceRepr for AttnPreVl8 {}
889
890/// task #18 increment 2: one sequence's FULL chunk-buffer set (alloc-only; the
891/// varlen K1-K5 chain fills them).
892pub struct GdnChunkBufs {
893    pub gcum: CudaSlice<f32>,
894    pub a: CudaSlice<f32>,
895    pub p: CudaSlice<f32>,
896    pub u: CudaSlice<f32>,
897    pub w: CudaSlice<f32>,
898    pub kb16: CudaSlice<u8>,
899    pub wb16: CudaSlice<u8>,
900    pub y16: CudaSlice<u8>,
901    pub ssnap16: CudaSlice<u8>,
902    pub qb16: CudaSlice<u8>,
903    pub pb16: CudaSlice<u8>,
904    pub o: CudaSlice<f32>,
905    pub t: usize,
906    pub nc: usize,
907}
908
909/// STAGE-2 GROUPED DECODE: the 8 routed-expert weights by value (CUDA `f32x8_t`).
910#[repr(C)]
911#[derive(Clone, Copy)]
912pub struct F32x8(pub [f32; 8]);
913unsafe impl cudarc::driver::DeviceRepr for F32x8 {}
914
915/// Harness timing contract: wall nanos of the LAST generate/generate_spec prompt prime on this
916/// process. Bench binaries read it right after the call to print gen-only throughput without the
917/// prime-subtraction hack (which amplifies prime jitter into the gen number at long prompts).
918pub static PRIME_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
919
920impl Engine {
921    pub fn new(ordinal: usize) -> Result<Self, Box<dyn std::error::Error>> {
922        let gpu = memra_runtime::Gpu::new(ordinal)?;
923        // ARCH GUARD (unified dual-arch engine): the fatbins carry single-arch SASS, so a
924        // binary/device mismatch otherwise dies at first module load with an opaque CUDA
925        // error. Fail early with the rebuild hint instead. MEMRA_ARCH_CHECK=0 skips.
926        if std::env::var("MEMRA_ARCH_CHECK").as_deref() != Ok("0") {
927            use cudarc::driver::sys::CUdevice_attribute_enum as A;
928            let (maj, min) = cudarc::driver::result::device::get(ordinal as i32)
929                .and_then(|d| unsafe { Ok((
930                    cudarc::driver::result::device::get_attribute(d, A::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR)?,
931                    cudarc::driver::result::device::get_attribute(d, A::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR)?)) })
932                .unwrap_or((0, 0));
933            let built = env!("MEMRA_BUILT_CUDA_ARCH");
934            let ok = matches!((built, maj, min),
935                ("120a", 12, 0) | ("120a", 12, 1) | ("100a", 10, 0) | ("90a", 9, 0) | ("89", 8, 9));
936            if !ok {
937                return Err(format!(
938                    "memra was built for sm_{built} but device {ordinal} reports compute \
939                     capability {maj}.{min}. Rebuild on this machine (MEMRA_CUDA_ARCH \
940                     auto-detects the GPU) or set MEMRA_ARCH_CHECK=0 to bypass.").into());
941            }
942        }
943        // Default async-pool RELEASE_THRESHOLD is 0: freed blocks return to the OS at every
944        // sync, so cuMemAllocAsync NODES inside captured graphs re-map memory on EVERY
945        // cuGraphLaunch (measured 226us/launch on the gemma graph door, 2026-07-23 osrt).
946        // Pinning the threshold keeps the pool cached -> alloc nodes become pointer bumps.
947        unsafe {
948            use cudarc::driver::sys;
949            let dev: sys::CUdevice = ordinal as sys::CUdevice;
950            let mut pool: sys::CUmemoryPool = std::ptr::null_mut();
951            if sys::cuDeviceGetDefaultMemPool(&mut pool, dev) == sys::CUresult::CUDA_SUCCESS {
952                let mut thresh: u64 = u64::MAX;
953                let _ = sys::cuMemPoolSetAttribute(
954                    pool,
955                    sys::CUmemPool_attribute_enum::CU_MEMPOOL_ATTR_RELEASE_THRESHOLD,
956                    &mut thresh as *mut u64 as *mut core::ffi::c_void,
957                );
958            }
959        }
960        let module = gpu.ctx.load_module(Ptx::from_binary(FATBIN.to_vec()))?;
961        let hybrid = gpu.ctx.load_module(Ptx::from_binary(HYBRID_FATBIN.to_vec()))?;
962        let qmatvec = gpu.ctx.load_module(Ptx::from_binary(QMATVEC_FATBIN.to_vec()))?;
963        let flash = gpu.ctx.load_module(Ptx::from_binary(flash_fatbin_bytes().to_vec()))?;
964        let gemm = gpu.ctx.load_module(Ptx::from_binary(gemm_fatbin_bytes().into_owned()))?;
965        let router = gpu.ctx.load_module(Ptx::from_binary(ROUTER_FATBIN.to_vec()))?;
966        let sample = gpu.ctx.load_module(Ptx::from_binary(SAMPLE_FATBIN.to_vec()))?;
967        let copy_stream = gpu.ctx.new_stream()?;
968        // DECODE EVENT-TRACKING ELISION — DEFAULT ON (2026-07-05; MEMRA_EVT=1 = escape hatch).
969        // cudarc is in multi-stream mode (main stream +
970        // copy_stream are both created streams), so with tracking on EVERY launch arg records a
971        // read/write CudaEvent and inserts cuStreamWaitEvent on prior events. On the 35B MoE decode
972        // that is ~19k cuStreamWaitEvent + ~9k cuEventRecord + ~6k event create/destroy per token
973        // (~7 ms/tok host time, measured nsys 2026-07-04 g7e), and +4.6% measured on 27B decode —
974        // protecting NOTHING: every hot-path kernel/memcpy runs on the ONE gpu.stream.
975        // CROSS-STREAM HAZARD AUDIT: MoeSlotCache in-memory prefetch uses copy_stream. Every
976        // overwrite explicitly records the prior compute point and makes copy_stream wait; every
977        // consumer explicitly waits for the copy completion event. The opt-in positioned-read
978        // proof stays on gpu.stream and retains an explicit event solely to guard pinned-source
979        // reuse. Graph-capture sites use only gpu.stream, so these handoffs never rely on cudarc's
980        // implicit event tracking.
981        // SAFETY: single-stream ordering is total; the runtime mem-pool is configured with
982        // internal-dependency reuse (memra-runtime), so alloc reuse is stream-ordered too.
983        if std::env::var("MEMRA_EVT").map(|v| v == "1").unwrap_or(false) {
984            // escape hatch: keep cudarc's implicit cross-stream event tracking.
985        } else {
986            unsafe { gpu.ctx.disable_event_tracking(); }
987        }
988        Ok(Self { gpu, module, hybrid, qmatvec, flash, flash_g: std::sync::OnceLock::new(), gemm, router, sample,
989                  moe_cache: Mutex::new(None),
990                  moe_cache_layout: Mutex::new(None),
991                  copy_stream,
992                  capture_keep_on: std::sync::atomic::AtomicBool::new(false),
993                  verify_exact: std::sync::atomic::AtomicBool::new(false),
994                  capture_keep: Mutex::new(Vec::new()),
995                  argmax_partials: Mutex::new(None),
996                  prime_deqw_ws: Mutex::new(None),
997                  router_stage: Mutex::new(None),
998                  fp8_scratch: Mutex::new(None),
999                  fa_vf16_scratch: Mutex::new(None),
1000                  fa_part_pool: Mutex::new(None),
1001                  fa_part_retired: Mutex::new(Vec::new()),
1002                  fn_cache: Mutex::new(Default::default()),
1003                  f16_scratch: Mutex::new(None),
1004                  #[cfg(memra_cutlass)]
1005                  cutlass_scratch: Mutex::new(None) })
1006    }
1007
1008    pub fn ctx(&self) -> &Arc<CudaContext> { &self.gpu.ctx }
1009
1010    /// Bytes the async pool holds MAPPED but NOT LIVE (reserved - used), i.e. freed blocks
1011    /// parked in the pool because `Engine::new` pins RELEASE_THRESHOLD to u64::MAX above.
1012    ///
1013    /// Why this is a public engine surface: `mem_get_info`'s `free` DOES NOT SEE these bytes —
1014    /// they are mapped to this process, so `free` counts them as gone, yet the very next
1015    /// `alloc_u8` is satisfied from them without touching `free` at all. Any admission or
1016    /// budget decision that reads `free` alone therefore under-counts real headroom by exactly
1017    /// this amount. Effective allocatable headroom is `free + pool_cached_bytes()`.
1018    ///
1019    /// MEASURED SIZE (c=64 serve burst, 9B NVFP4 + draft, 24GB card, 2026-08-06): 34-89 MB
1020    /// during the burst — SMALL. The admission gate adds it because a term that can only ever
1021    /// under-count headroom does not belong in a gate that queues real work, but the honest
1022    /// reading of this number is that pool caching is NOT where a long-running server's VRAM
1023    /// hides on this path: reserved ~= used throughout, so the memory the driver reports as
1024    /// gone is genuinely LIVE (see `pool_reserved_used` for the diagnostic pair).
1025    ///
1026    /// Returns 0 if the pool cannot be queried (never a false-positive headroom claim).
1027    pub fn pool_cached_bytes(&self) -> usize {
1028        let (reserved, used) = self.pool_reserved_used();
1029        reserved.saturating_sub(used)
1030    }
1031
1032    /// Raw async-pool occupancy: (RESERVED_MEM_CURRENT, USED_MEM_CURRENT) in bytes. Reserved is
1033    /// what the pool has mapped from the driver; used is what is live inside it. Exposed for
1034    /// admission/VRAM diagnostics — the pair distinguishes "memory is parked in the pool and
1035    /// `free` cannot see it" (reserved >> used) from "memory is genuinely held live by some
1036    /// owner" (reserved ~= used), which are opposite bugs with opposite fixes.
1037    /// (0, 0) if the pool cannot be queried.
1038    pub fn pool_reserved_used(&self) -> (usize, usize) {
1039        use cudarc::driver::sys;
1040        unsafe {
1041            let mut pool: sys::CUmemoryPool = std::ptr::null_mut();
1042            if sys::cuDeviceGetDefaultMemPool(&mut pool, self.gpu.ctx.ordinal() as sys::CUdevice)
1043                != sys::CUresult::CUDA_SUCCESS
1044            {
1045                return (0, 0);
1046            }
1047            let (mut reserved, mut used) = (0u64, 0u64);
1048            if sys::cuMemPoolGetAttribute(
1049                pool,
1050                sys::CUmemPool_attribute_enum::CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT,
1051                &mut reserved as *mut u64 as *mut core::ffi::c_void,
1052            ) != sys::CUresult::CUDA_SUCCESS {
1053                return (0, 0);
1054            }
1055            if sys::cuMemPoolGetAttribute(
1056                pool,
1057                sys::CUmemPool_attribute_enum::CU_MEMPOOL_ATTR_USED_MEM_CURRENT,
1058                &mut used as *mut u64 as *mut core::ffi::c_void,
1059            ) != sys::CUresult::CUDA_SUCCESS {
1060                return (0, 0);
1061            }
1062            (reserved as usize, used as usize)
1063        }
1064    }
1065
1066    /// Ambient stream (by value since M1-PP2 increment 2): the thread's pp2 stage stream
1067    /// when a stage scope is active, else the main compute stream — see `Gpu::stream`.
1068    pub fn stream(&self) -> Arc<CudaStream> { self.gpu.stream() }
1069    /// FP8-GLOBALS switch (MEMRA_GEMMA_GKV, default ON): gemma global (hd512) layers keep
1070    /// their KV in e4m3 — the dequant-latency arc (HANDOVER). Windowed layers stay q8_0/q5_1.
1071    pub fn gkv_on() -> bool {
1072        memra_kv::gkv_on()
1073    }
1074
1075    /// FP8-WINDOWED switch (MEMRA_GEMMA_WKV — measured 2026-07-12 in a validity-gated
1076    /// window: 1.7k 174.1-174.4 vs 168.6-169.4 default (+3%), 4.9k 158.7-160.4; vs llama
1077    /// same-window 159.5-160.2 / 140.6 = 1.09x / 1.13x): gemma windowed (hd256 SWA)
1078    /// layers hold e4m3 KV and ride the format-aware v4 lane from the kf8vf8 module.
1079    /// SERVING-MODE DEFAULT (2026-07-12, the 31B spec unlock): fp8-windowed KV GUTS the
1080    /// MTP drafter's acceptance — its single swa attention reads the windowed cache and
1081    /// e4m3 noise flips its argmaxes (31B short accept .758 -> 1.000 with q8/q5, spec 88
1082    /// -> 122.7 vs llama-mtp 112; depth .59 -> .78; 26B depth .57 -> .89). So the default
1083    /// keys on serving intent: SPEC serving (MEMRA_DRAFT set) -> OFF, plain -> ON (its
1084    /// depth-plain +3% stands). Explicit MEMRA_GEMMA_WKV always wins. GKV (globals) stays
1085    /// ON for both — no acceptance cost measured.
1086    pub fn wkv_on() -> bool {
1087        memra_kv::wkv_on()
1088    }
1089
1090    /// QWEN FP8-KV switch (MEMRA_KV_FP8 explicit; else the per-model KV_FP8_FORCE door set
1091    /// at model load; else OFF). Non-gemma full-attn layers hold e4m3 K/V via the kf8vf8
1092    /// module. Per-model verdict 2026-07-12: 9B +0.7-4% scaling with depth, 27B flat,
1093    /// 35B −2% (fp8 format-gates its v3 dp4a lane) — so the 9B class defaults ON
1094    /// (adopted 2026-07-28 with the deferred acceptance battery), others stay OFF.
1095    pub fn kv_fp8_on() -> bool {
1096        memra_kv::kv_fp8_on()
1097    }
1098
1099    /// fa kernel routed by head_dim: hd512 (gemma globals) resolves from the kf8vf8 module
1100    /// when the fp8-globals arm is on; everything else from the default flash module.
1101    fn fa_func(&self, name: &str, head_dim: usize) -> CudaFunction {
1102        if head_dim == 512 && Self::gkv_on() { self.func_g(name) } else { self.func(name) }
1103    }
1104
1105    /// Kernel from the FP8-GLOBALS (kf8vf8) flash module — gemma global-layer arm only.
1106    /// Format-AGNOSTIC kernels (e.g. fa_decode_combine_f32) are not compiled into the
1107    /// per-format fatbins; fall back to the base modules for those.
1108    fn func_g(&self, name: &str) -> CudaFunction {
1109        let m = self.flash_g.get_or_init(|| {
1110            self.gpu.ctx.load_module(cudarc::nvrtc::Ptx::from_binary(FLASH_FATBIN_KF8VF8.to_vec()))
1111                .expect("load kf8vf8 flash fatbin (fp8-globals arm)")
1112        });
1113        let key = format!("g:{name}");
1114        if let Some(f) = self.fn_cache.lock().unwrap().get(&key) { return f.clone(); }
1115        let f = match m.load_function(name) {
1116            Ok(f) => f,
1117            Err(_) => self.func(name),
1118        };
1119        self.fn_cache.lock().unwrap().insert(key, f.clone());
1120        f
1121    }
1122
1123    fn func(&self, name: &str) -> CudaFunction {
1124        // Resolution cache: cuModuleGetFunction fails inside a CUDA-graph capture region,
1125        // so capture-time lookups MUST be host-memory hits (warmups populate the cache).
1126        if let Some(f) = self.fn_cache.lock().unwrap().get(name) { return f.clone(); }
1127        let f = self.module.load_function(name)
1128            .or_else(|_| self.hybrid.load_function(name))
1129            .or_else(|_| self.qmatvec.load_function(name))
1130            .or_else(|_| self.flash.load_function(name))
1131            .or_else(|_| self.gemm.load_function(name))
1132            .or_else(|_| self.router.load_function(name))
1133            .or_else(|_| self.sample.load_function(name))
1134            .unwrap_or_else(|_| panic!("kernel {name} not in any fatbin"));
1135        self.fn_cache.lock().unwrap().insert(name.to_string(), f.clone());
1136        f
1137    }
1138
1139    /// Scatter trimmed draft logits into full-vocab space: dst = -inf everywhere, then
1140    /// dst[d2t[i]] = src[i]. Two launches (fill, scatter) — no grid-wide sync needed.
1141    pub fn scatter_trim_logits(&self, src: &CudaSlice<f32>, d2t: &CudaSlice<u32>,
1142                               dst: &mut CudaSlice<f32>, d_vocab: usize, n_vocab: usize)
1143                               -> Result<(), Box<dyn std::error::Error>> {
1144        let f1 = self.func("scatter_trim_logits_f32");
1145        let f2 = self.func("scatter_trim_logits_pass2_f32");
1146        let (dv, nv) = (d_vocab as i32, n_vocab as i32);
1147        let cfg1 = LaunchConfig { grid_dim: (256, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1148        let __s_b1 = self.gpu.stream();
1149        let mut b1 = __s_b1.launch_builder(&f1);
1150        b1.arg(src).arg(d2t).arg(&mut *dst).arg(&dv).arg(&nv);
1151        unsafe { b1.launch(cfg1)?; }
1152        let cfg2 = LaunchConfig { grid_dim: (d_vocab.div_ceil(256) as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1153        let __s_b2 = self.gpu.stream();
1154        let mut b2 = __s_b2.launch_builder(&f2);
1155        b2.arg(src).arg(d2t).arg(&mut *dst).arg(&dv);
1156        unsafe { b2.launch(cfg2)?; }
1157        Ok(())
1158    }
1159
1160    // ---- FILTERED-SPEC (feat/filtered-spec): top-k/p/min-p transforms applied symmetrically
1161    // to p and q — rejection sampling stays distribution-exact for the filtered target. ----
1162
1163    /// Per-row filtered-softmax stats: out[r] = (threshold_e, renorm_mass_e, row_max) for the
1164    /// filter (top_k, top_p, min_p) at `temp`. Rows index into x with row_stride f32s.
1165    #[allow(clippy::too_many_arguments)]
1166    pub fn filter_stats(&self, x: &CudaSlice<f32>, row_stride: usize, rows: &CudaSlice<i32>,
1167                        out_th: &mut CudaSlice<f32>, out_z: &mut CudaSlice<f32>,
1168                        out_max: &mut CudaSlice<f32>, n: usize, nrow: usize,
1169                        temp: f32, top_k: i32, top_p: f32, min_p: f32)
1170                        -> Result<(), Box<dyn std::error::Error>> {
1171        let f = self.func("filter_stats_f32");
1172        let (ni, nr, rs) = (n as i32, nrow as i32, row_stride as i64);
1173        let cfg = LaunchConfig { grid_dim: (nrow as u32, 1, 1), block_dim: (1024, 1, 1), shared_mem_bytes: 0 };
1174        let __s_b = self.gpu.stream();
1175        let mut b = __s_b.launch_builder(&f);
1176        b.arg(x).arg(&rs).arg(rows).arg(&mut *out_th).arg(&mut *out_z).arg(&mut *out_max)
1177         .arg(&ni).arg(&nr).arg(&temp).arg(&top_k).arg(&top_p).arg(&min_p);
1178        unsafe { b.launch(cfg)?; }
1179        Ok(())
1180    }
1181
1182    /// out[pair] = filtered-softmax prob of ids[pair] in row rows[pair] (th/z per PAIR).
1183    #[allow(clippy::too_many_arguments)]
1184    pub fn softmax_gather_filtered(&self, x: &CudaSlice<f32>, row_stride: usize,
1185                                   ids: &CudaSlice<u32>, rows: &CudaSlice<i32>,
1186                                   th: &CudaSlice<f32>, z: &CudaSlice<f32>,
1187                                   out: &mut CudaSlice<f32>, n: usize, npair: usize, temp: f32)
1188                                   -> Result<(), Box<dyn std::error::Error>> {
1189        let f = self.func("softmax_gather_filtered_f32");
1190        let (ni, np, rs) = (n as i32, npair as i32, row_stride as i64);
1191        let cfg = LaunchConfig { grid_dim: (npair as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1192        let __s_b = self.gpu.stream();
1193        let mut b = __s_b.launch_builder(&f);
1194        b.arg(x).arg(&rs).arg(ids).arg(rows).arg(th).arg(z).arg(&mut *out).arg(&ni).arg(&np).arg(&temp);
1195        unsafe { b.launch(cfg)?; }
1196        Ok(())
1197    }
1198
1199    /// Filtered residual sample: token ~ norm(max(0, fp - fq)) with fp/fq the filtered softmaxes.
1200    #[allow(clippy::too_many_arguments)]
1201    pub fn residual_sample_filtered(&self, p: &CudaSlice<f32>, q: Option<&CudaSlice<f32>>, n: usize,
1202                                    temp: f32, seed: u64, stream_pos: u32,
1203                                    p_stats: (f32, f32, f32), q_stats: (f32, f32, f32),
1204                                    out_tok: &mut CudaSlice<u32>)
1205                                    -> Result<(), Box<dyn std::error::Error>> {
1206        let f = self.func("residual_sample_filtered_f32");
1207        let (ni, slo, shi) = (n as i32, (seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
1208        let has_q: i32 = q.is_some() as i32;
1209        let qbuf = q.unwrap_or(p);
1210        let (pm, pth, pz) = p_stats; let (qm, qth, qz) = q_stats;
1211        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (1024, 1, 1), shared_mem_bytes: 0 };
1212        let __s_b = self.gpu.stream();
1213        let mut b = __s_b.launch_builder(&f);
1214        b.arg(p).arg(qbuf).arg(&has_q).arg(&ni).arg(&temp).arg(&slo).arg(&shi).arg(&stream_pos)
1215         .arg(&pm).arg(&pth).arg(&pz).arg(&qm).arg(&qth).arg(&qz).arg(&mut *out_tok);
1216        unsafe { b.launch(cfg)?; }
1217        Ok(())
1218    }
1219
1220    /// Gumbel-max draw from the FILTERED distribution (masked perturb; argmax after).
1221    #[allow(clippy::too_many_arguments)]
1222    pub fn gumbel_perturb_filtered(&self, x: &CudaSlice<f32>, y: &mut CudaSlice<f32>, n: usize,
1223                                   seed: u64, stream_pos: u32, temp: f32, row_max: f32, th: f32)
1224                                   -> Result<(), Box<dyn std::error::Error>> {
1225        let f = self.func("gumbel_perturb_filtered_f32");
1226        let (ni, slo, shi) = (n as i32, (seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
1227        let cfg = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1228        let __s_b = self.gpu.stream();
1229        let mut b = __s_b.launch_builder(&f);
1230        b.arg(x).arg(&mut *y).arg(&ni).arg(&slo).arg(&shi).arg(&stream_pos).arg(&temp).arg(&row_max).arg(&th);
1231        unsafe { b.launch(cfg)?; }
1232        Ok(())
1233    }
1234
1235    /// Keskar penalties applied IN PLACE to a logits buffer: history token ids get
1236    /// rep-divided/multiplied + freq*count + presence subtracted. Symmetric p/q usage keeps
1237    /// filtered rejection sampling exact for the penalized target.
1238    #[allow(clippy::too_many_arguments)]
1239    pub fn penalize_logits(&self, x: &mut CudaSlice<f32>, hist: &CudaSlice<u32>, n_hist: usize,
1240                           rep: f32, freq: f32, present: f32, n: usize)
1241                           -> Result<(), Box<dyn std::error::Error>> {
1242        if n_hist == 0 { return Ok(()); }
1243        let f = self.func("penalize_logits_f32");
1244        let (nh, ni) = (n_hist as i32, n as i32);
1245        let cfg = LaunchConfig { grid_dim: (n_hist.div_ceil(128) as u32, 1, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
1246        let __s_b = self.gpu.stream();
1247        let mut b = __s_b.launch_builder(&f);
1248        b.arg(&mut *x).arg(hist).arg(&nh).arg(&rep).arg(&freq).arg(&present).arg(&ni);
1249        unsafe { b.launch(cfg)?; }
1250        Ok(())
1251    }
1252
1253    /// Rows variant: penalize `nrow` contiguous rows of length n in one launch.
1254    #[allow(clippy::too_many_arguments)]
1255    pub fn penalize_logits_rows(&self, x: &mut CudaSlice<f32>, hist: &CudaSlice<u32>, n_hist: usize,
1256                                rep: f32, freq: f32, present: f32, n: usize, nrow: usize)
1257                                -> Result<(), Box<dyn std::error::Error>> {
1258        if n_hist == 0 || nrow == 0 { return Ok(()); }
1259        let f = self.func("penalize_logits_rows_f32");
1260        let (nh, ni, nr) = (n_hist as i32, n as i32, nrow as i32);
1261        let cfg = LaunchConfig { grid_dim: (n_hist.div_ceil(128) as u32, nrow as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
1262        let __s_b = self.gpu.stream();
1263        let mut b = __s_b.launch_builder(&f);
1264        b.arg(&mut *x).arg(hist).arg(&nh).arg(&rep).arg(&freq).arg(&present).arg(&ni).arg(&nr);
1265        unsafe { b.launch(cfg)?; }
1266        Ok(())
1267    }
1268
1269    /// WEIGHT PREFETCH (SOTA item 3, 2026-07-13, DEFAULT ON): during a bandwidth-idle
1270    /// window (the fa launch reads KV, not weights) prefetch the NEXT matvec's
1271    /// decode-plane bytes into L2 so it reads L2-warm. Value-free scheduling op — same
1272    /// class as prefetch_l2 (numerics untouched by construction). Wired only where it
1273    /// measured positive: the E4B dc attn arm (+0.65%). 26B (flat — MoE ffn dominates),
1274    /// 31B (−0.2% — decode at the DRAM wall) and the ffn gate/up cascade (−1% — 29MB/layer
1275    /// floods the fill path) all probed and NOT wired. MEMRA_WPF=0 rollback seam.
1276    pub fn wpf_level() -> u32 {
1277        static ON: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
1278        *ON.get_or_init(|| std::env::var("MEMRA_WPF").ok()
1279            .and_then(|v| v.parse().ok()).unwrap_or(1))
1280    }
1281
1282    /// PDL launch arm (SOTA item 2, 2026-07-13, DEFAULT ON): the six MEMRA_PDL_ENTRY glue
1283    /// kernels launch through cuLaunchKernelEx with PROGRAMMATIC_STREAM_SERIALIZATION — the
1284    /// grid launches while the predecessor drains (~120ns/kernel back, pdl_probe), the
1285    /// kernels' entry grid-dep sync restores read order (SASS-audited: ACQBULK precedes
1286    /// every LDG in all six). Valid windows: E4B +1.0-1.2% (128 AND 384-tok gens);
1287    /// 26B/31B/qwen flat no-harm. Battery: kernel-check GREEN, run-gen tokens IDENTICAL x3
1288    /// gemma, spec 64/64 E4B K=1/4/8 + 26B/31B K=4 + qwen PASS. Works eager AND under
1289    /// capture (capture encodes native programmatic edges — the post-capture edge-REWRITE
1290    /// arm died: engine graphs hold cuMemAllocAsync alloc nodes, edge edits on those return
1291    /// CUDA_ERROR_NOT_SUPPORTED). MEMRA_PDL=0 rollback seam.
1292    /// See the `verify_exact` field. Scoped by the dflash round around its t=16 verify.
1293    pub fn set_verify_exact(&self, on: bool) {
1294        self.verify_exact.store(on, std::sync::atomic::Ordering::Relaxed);
1295    }
1296    pub(crate) fn verify_exact_on(&self) -> bool {
1297        self.verify_exact.load(std::sync::atomic::Ordering::Relaxed)
1298    }
1299
1300    /// m=1 norm+rope+append fold seam (2026-07-23): MEMRA_QKV_APPEND=0 reverts to the
1301    /// fused-norm-rope + standalone-append pair (the exact-oracle bisect arm).
1302    pub fn qkv_append_on() -> bool {
1303        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1304        *ON.get_or_init(|| std::env::var("MEMRA_QKV_APPEND").map(|v| v != "0").unwrap_or(true))
1305    }
1306
1307    /// PDL wave-B1a seam: the four dense-glue kernels (rms_norm_f32, add_rms_norm_f32,
1308    /// add_scale_rms_norm_q8_1, quantize_q8_1). MEMRA_PDL_WB=0 reverts alone.
1309    pub fn pdl_wb_on() -> bool {
1310        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1311        *ON.get_or_init(|| std::env::var("MEMRA_PDL_WB").map(|v| v != "0").unwrap_or(true))
1312    }
1313
1314    /// PDL wave-A seam: the mmvq matvec PDL launches only (the six glue kernels keep
1315    /// their own MEMRA_PDL master seam). MEMRA_PDL_MMVQ=0 reverts wave-A alone — the
1316    /// per-model no-harm bisect knob.
1317    pub fn pdl_mmvq_on() -> bool {
1318        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1319        *ON.get_or_init(|| std::env::var("MEMRA_PDL_MMVQ").map(|v| v != "0").unwrap_or(true))
1320    }
1321
1322    pub fn pdl_on() -> bool {
1323        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1324        *ON.get_or_init(|| std::env::var("MEMRA_PDL").map(|v| v != "0").unwrap_or(true))
1325    }
1326
1327    /// Raw CUfunction for a PDL-attributed launch: the SAME kernels.fatbin loaded once more
1328    /// through the raw driver API (cudarc hides its CUfunction handles; a duplicate module
1329    /// of tiny glue kernels is free). Resolved lazily per name, cached process-wide.
1330    /// Fused t=1 q4_0 mr policy: env MEMRA_Q40_MR wins (1/2); else the per-model
1331    /// FUSED_MR1_DEFAULT (dense gemma = mr1, MoE = mr2 — see the static's doc).
1332    fn q40_mr1_on() -> bool {
1333        static Q40MR: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
1334        match *Q40MR.get_or_init(|| std::env::var("MEMRA_Q40_MR").ok()
1335            .and_then(|v| v.parse().ok())) {
1336            Some(v) => v == 1,
1337            None => crate::FUSED_MR1_DEFAULT.load(std::sync::atomic::Ordering::Relaxed),
1338        }
1339    }
1340
1341    /// PDL wave-B2: flash-module PDL functions. `g` selects the kf8vf8 flavor — the
1342    /// caller MUST pass the SAME flavor its builder launch would resolve (fa_func/func_g
1343    /// mirror); the flavors differ semantically (KV byte formats), a wrong-module launch
1344    /// writes wrong bytes silently.
1345    fn pdl_func_flash(&self, g: bool, name: &'static str)
1346        -> Result<cudarc::driver::sys::CUfunction, Box<dyn std::error::Error>> {
1347        use cudarc::driver::sys as cu;
1348        // PER-CONTEXT caches (M1-PP2 cross-device fix, 8x box 2026-08-02): CUmodule and
1349        // CUfunction handles are CONTEXT-scoped, and a remote-stage Engine
1350        // (MEMRA_PP_DEVICES=a,b) lives in the other device's primary context. The old
1351        // process-wide OnceLock cache handed stage 1 the dev-a handles, so every stage-1
1352        // launch_pdl* died CUDA_ERROR_INVALID_HANDLE. Key module + function caches by
1353        // this engine's CUcontext; single-context runs behave exactly as before.
1354        static MODS: std::sync::Mutex<Option<std::collections::HashMap<(usize, bool), usize>>> =
1355            std::sync::Mutex::new(None);
1356        static FNS: std::sync::Mutex<Option<std::collections::HashMap<(usize, bool, &'static str), usize>>> =
1357            std::sync::Mutex::new(None);
1358        let ctx_key = self.ctx().cu_ctx() as usize;
1359        if let Some(&f) = FNS.lock().unwrap().get_or_insert_with(Default::default)
1360            .get(&(ctx_key, g, name)) { return Ok(f as cu::CUfunction); }
1361        let module = {
1362            let mut mods = MODS.lock().unwrap();
1363            let map = mods.get_or_insert_with(Default::default);
1364            match map.get(&(ctx_key, g)) {
1365                Some(&m) => m,
1366                None => {
1367                    let m = self.pdl_load_module_in_ctx(
1368                        if g { FLASH_FATBIN_KF8VF8 } else { FLASH_FATBIN })?;
1369                    map.insert((ctx_key, g), m);
1370                    m
1371                }
1372            }
1373        };
1374        let cname = std::ffi::CString::new(name)?;
1375        let mut f: cu::CUfunction = std::ptr::null_mut();
1376        let r = unsafe { cu::cuModuleGetFunction(&mut f, module as cu::CUmodule, cname.as_ptr()) };
1377        if r != cu::CUresult::CUDA_SUCCESS { return Err(format!("pdl_func_flash {name} (g={g}): {r:?}").into()); }
1378        FNS.lock().unwrap().get_or_insert_with(Default::default)
1379            .insert((ctx_key, g, name), f as usize);
1380        Ok(f)
1381    }
1382
1383    /// Load a fatbin as a raw CUmodule IN THIS ENGINE'S CONTEXT. `cuModuleLoadData` binds
1384    /// the module to the thread's CURRENT context — a remote-stage engine must not
1385    /// inherit the primary's (the INVALID_HANDLE class above). Restores the caller's
1386    /// current context before returning.
1387    fn pdl_load_module_in_ctx(&self, bytes: &[u8]) -> Result<usize, Box<dyn std::error::Error>> {
1388        use cudarc::driver::sys as cu;
1389        let mut prev: cu::CUcontext = std::ptr::null_mut();
1390        unsafe { cu::cuCtxGetCurrent(&mut prev).result()?; }
1391        self.ctx().bind_to_thread()?;
1392        let mut m: cu::CUmodule = std::ptr::null_mut();
1393        let r = unsafe { cu::cuModuleLoadData(&mut m, bytes.as_ptr() as *const std::ffi::c_void) };
1394        let restore = if prev.is_null() { cu::CUresult::CUDA_SUCCESS }
1395                      else { unsafe { cu::cuCtxSetCurrent(prev) } };
1396        if r != cu::CUresult::CUDA_SUCCESS {
1397            return Err(format!("pdl module load: {r:?}").into());
1398        }
1399        if restore != cu::CUresult::CUDA_SUCCESS {
1400            return Err(format!("pdl module load: ctx restore {restore:?}").into());
1401        }
1402        Ok(m as usize)
1403    }
1404
1405    fn pdl_func(&self, name: &'static str) -> Result<cudarc::driver::sys::CUfunction, Box<dyn std::error::Error>> {
1406        use cudarc::driver::sys as cu;
1407        // PER-CONTEXT caches — same M1-PP2 cross-device fix as pdl_func_flash (handles
1408        // are context-scoped; key everything by this engine's CUcontext).
1409        static MODULES: std::sync::Mutex<Option<std::collections::HashMap<usize, usize>>> =
1410            std::sync::Mutex::new(None);
1411        // PDL wave-A: the mmvq kernels live in the qmatvec fatbin, not kernels.cu — second
1412        // duplicate module, loaded lazily on the first kernels-module miss.
1413        static QMODULES: std::sync::Mutex<Option<std::collections::HashMap<usize, usize>>> =
1414            std::sync::Mutex::new(None);
1415        static FNS: std::sync::Mutex<Option<std::collections::HashMap<(usize, &'static str), usize>>> =
1416            std::sync::Mutex::new(None);
1417        let ctx_key = self.ctx().cu_ctx() as usize;
1418        if let Some(&f) = FNS.lock().unwrap().get_or_insert_with(Default::default)
1419            .get(&(ctx_key, name)) { return Ok(f as cu::CUfunction); }
1420        let module = {
1421            let mut mods = MODULES.lock().unwrap();
1422            let map = mods.get_or_insert_with(Default::default);
1423            match map.get(&ctx_key) {
1424                Some(&m) => m,
1425                None => {
1426                    let m = self.pdl_load_module_in_ctx(FATBIN)?;
1427                    map.insert(ctx_key, m);
1428                    m
1429                }
1430            }
1431        };
1432        let cname = std::ffi::CString::new(name)?;
1433        let mut f: cu::CUfunction = std::ptr::null_mut();
1434        let mut r = unsafe { cu::cuModuleGetFunction(&mut f, module as cu::CUmodule, cname.as_ptr()) };
1435        if r == cu::CUresult::CUDA_ERROR_NOT_FOUND {
1436            let qmodule = {
1437                let mut mods = QMODULES.lock().unwrap();
1438                let map = mods.get_or_insert_with(Default::default);
1439                match map.get(&ctx_key) {
1440                    Some(&m) => m,
1441                    None => {
1442                        let m = self.pdl_load_module_in_ctx(QMATVEC_FATBIN)?;
1443                        map.insert(ctx_key, m);
1444                        m
1445                    }
1446                }
1447            };
1448            r = unsafe { cu::cuModuleGetFunction(&mut f, qmodule as cu::CUmodule, cname.as_ptr()) };
1449        }
1450        if r != cu::CUresult::CUDA_SUCCESS { return Err(format!("pdl_func {name}: {r:?}").into()); }
1451        FNS.lock().unwrap().get_or_insert_with(Default::default)
1452            .insert((ctx_key, name), f as usize);
1453        Ok(f)
1454    }
1455
1456    /// cuLaunchKernelEx with CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION on the
1457    /// compute stream. ONLY legal for kernels whose entry carries MEMRA_PDL_ENTRY.
1458    ///
1459    /// # Safety
1460    /// `params` must match the kernel's exact parameter list (order, types, count) —
1461    /// a mismatch corrupts the launch silently.
1462    /// Flash-module twin of `launch_pdl` — `g` picks the kf8vf8 flavor (must mirror the
1463    /// builder path's fa_func/func_g choice exactly).
1464    ///
1465    /// # Safety
1466    /// Same contract as `launch_pdl`.
1467    unsafe fn launch_pdl_flash(&self, g: bool, name: &'static str, grid: (u32, u32, u32),
1468                               block: (u32, u32, u32), smem: u32,
1469                               params: &mut [*mut std::ffi::c_void])
1470                               -> Result<(), Box<dyn std::error::Error>> {
1471        use cudarc::driver::sys as cu;
1472        let f = self.pdl_func_flash(g, name)?;
1473        if smem > 0 {
1474            // mirror the builder path's opt-in ceiling (idempotent host-side set).
1475            let r = unsafe { cu::cuFuncSetAttribute(f,
1476                cu::CUfunction_attribute_enum::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
1477                smem as i32) };
1478            if r != cu::CUresult::CUDA_SUCCESS {
1479                return Err(format!("pdl smem attr {name}: {r:?}").into());
1480            }
1481        }
1482        let mut attr = cu::CUlaunchAttribute {
1483            id: cu::CUlaunchAttributeID::CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION,
1484            pad: [0; 4],
1485            value: cu::CUlaunchAttributeValue { programmaticStreamSerializationAllowed: 1 },
1486        };
1487        let cfg = cu::CUlaunchConfig {
1488            gridDimX: grid.0, gridDimY: grid.1, gridDimZ: grid.2,
1489            blockDimX: block.0, blockDimY: block.1, blockDimZ: block.2,
1490            sharedMemBytes: smem, hStream: self.gpu.stream().cu_stream(),
1491            attrs: &mut attr, numAttrs: 1,
1492        };
1493        let r = unsafe { cu::cuLaunchKernelEx(&cfg, f, params.as_mut_ptr(), std::ptr::null_mut()) };
1494        if r != cu::CUresult::CUDA_SUCCESS { return Err(format!("launch_pdl_flash {name}: {r:?}").into()); }
1495        Ok(())
1496    }
1497
1498    unsafe fn launch_pdl(&self, name: &'static str, grid: (u32, u32, u32), block: (u32, u32, u32),
1499                         params: &mut [*mut std::ffi::c_void])
1500                         -> Result<(), Box<dyn std::error::Error>> {
1501        use cudarc::driver::sys as cu;
1502        let f = self.pdl_func(name)?;
1503        let mut attr = cu::CUlaunchAttribute {
1504            id: cu::CUlaunchAttributeID::CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION,
1505            pad: [0; 4],
1506            value: cu::CUlaunchAttributeValue { programmaticStreamSerializationAllowed: 1 },
1507        };
1508        let cfg = cu::CUlaunchConfig {
1509            gridDimX: grid.0, gridDimY: grid.1, gridDimZ: grid.2,
1510            blockDimX: block.0, blockDimY: block.1, blockDimZ: block.2,
1511            sharedMemBytes: 0, hStream: self.gpu.stream().cu_stream(),
1512            attrs: &mut attr, numAttrs: 1,
1513        };
1514        let r = unsafe { cu::cuLaunchKernelEx(&cfg, f, params.as_mut_ptr(), std::ptr::null_mut()) };
1515        if r != cu::CUresult::CUDA_SUCCESS { return Err(format!("launch_pdl {name}: {r:?}").into()); }
1516        Ok(())
1517    }
1518
1519    /// L2-prefetch a quant weight's DECODE plane (the rp4 split-plane mirror when present —
1520    /// that is what the m<=8 dispatch reads — else the raw block bytes). No-op on float arms.
1521    pub fn prefetch_weight_l2(&self, w: &crate::model::GpuTensor)
1522                              -> Result<(), Box<dyn std::error::Error>> {
1523        if let crate::model::GpuTensor::Quant { bytes, rp4, .. } = w {
1524            let p = rp4.as_ref().unwrap_or(bytes);
1525            self.prefetch_l2(p, p.len())?;
1526        }
1527        Ok(())
1528    }
1529
1530    /// DSpark markov chain ops (dflash lane): gather one bf16 row of a [V, rank] table
1531    /// by the DEVICE token id at tok[idx] into f32.
1532    pub fn gather_row_bf16(&self, table: &CudaSlice<u8>, tok: &CudaSlice<u32>, idx: usize,
1533                           dst: &mut CudaSlice<f32>, ncols: usize)
1534                           -> Result<(), Box<dyn std::error::Error>> {
1535        let f = self.func("gather_row_bf16_f32");
1536        let cfg = LaunchConfig { grid_dim: (ncols.div_ceil(256) as u32, 1, 1),
1537                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1538        let (nc, ix) = (ncols as i32, idx as i32);
1539        let __s_b = self.gpu.stream();
1540        let mut b = __s_b.launch_builder(&f);
1541        b.arg(table).arg(tok).arg(&ix).arg(dst).arg(&nc);
1542        unsafe { b.launch(cfg)?; }
1543        Ok(())
1544    }
1545
1546    /// logits[row_off .. row_off+n] += bias[0..n] (in place, one row).
1547    pub fn add_row_inplace(&self, logits: &mut CudaSlice<f32>, bias: &CudaSlice<f32>,
1548                           n: usize, row_off: usize)
1549                           -> Result<(), Box<dyn std::error::Error>> {
1550        let f = self.func("add_row_inplace_f32");
1551        let cfg = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, 1, 1),
1552                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1553        let (ni, off) = (n as i32, row_off as i64);
1554        let __s_b = self.gpu.stream();
1555        let mut b = __s_b.launch_builder(&f);
1556        b.arg(logits).arg(bias).arg(&ni).arg(&off);
1557        unsafe { b.launch(cfg)?; }
1558        Ok(())
1559    }
1560
1561    /// L2 prefetch of a device byte range (latency-hiding arc; value-free scheduling op).
1562    pub fn prefetch_l2(&self, p: &CudaSlice<u8>, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1563        let f = self.func("prefetch_l2_bytes");
1564        let lines = n.div_ceil(128);
1565        let ni = n as i64;
1566        let cfg = LaunchConfig { grid_dim: (lines.div_ceil(256) as u32, 1, 1),
1567                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1568        let __s_b = self.gpu.stream();
1569        let mut b = __s_b.launch_builder(&f);
1570        b.arg(p).arg(&ni);
1571        unsafe { b.launch(cfg)?; }
1572        Ok(())
1573    }
1574
1575    /// MoE router GEMV (MEMRA_ROUTER_KERNEL): deterministic warp-per-(expert,token) f32 dot.
1576    /// Different FP order than the cuBLAS path it replaces — battery-gated numeric config.
1577    pub fn router_gemv(&self, w: &CudaSlice<f32>, x: &CudaSlice<f32>, n_embd: usize,
1578                       n_experts: usize, t: usize)
1579                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1580        // float4 v2 probed 2026-07-14: +0.25% but flips near-tie routing (new FP order,
1581        // stream differs) — too small to justify a numeric config change; deleted.
1582        // w8 twin (2026-07-31): on the 132-SM H100 the lone-warp form is 14.8% of the q35
1583        // decode step (latency-bound) — the calculus flipped. MEMRA_ROUTER_V2=0 reverts to
1584        // the warp form (rollback seam; new FP order, battery-arbitrated per model).
1585        let w8 = match std::env::var("MEMRA_ROUTER_V2").as_deref() {
1586            Ok("0") => false,
1587            Ok(_) => true,
1588            Err(_) => ROUTER_W8_DEFAULT.load(std::sync::atomic::Ordering::Relaxed),
1589        };
1590        // FAST-ROUTER batch twin (lane/fast-router, 2026-08-02): at prefill m the per-(e,tok)
1591        // w8 form re-streams both operand rows per output (GEMV program at GEMM shape — the
1592        // concat-prime exactness fix paid -10% q35 board-2048 prefill through it). The batch
1593        // twin (8x8 expert-x-token register tile) is BIT-IDENTICAL per row (same k order,
1594        // same tree, same fold — kernel-check sweeps m=1..2048 on real router weights), so
1595        // the crossover is pure perf, not a numeric config. MIN_T from the on-box sweep
1596        // (research/fast-router-20260802/crossover-router*.jsonl); decode t=1 and small-t
1597        // spec verify keep the plain w8 form. MEMRA_ROUTER_BATCH=0: rollback seam
1598        // (perf-only, bits equal).
1599        let batch = w8 && t >= ROUTER_BATCH_MIN_T && router_batch_on();
1600        self.router_gemv_form(w, x, n_embd, n_experts, t, w8, batch)
1601    }
1602
1603    /// Form-explicit router GEMV launch (kernel-check bit-identity gate + crossover bench
1604    /// force both forms; `batch` requires `w8`).
1605    pub fn router_gemv_form(&self, w: &CudaSlice<f32>, x: &CudaSlice<f32>, n_embd: usize,
1606                            n_experts: usize, t: usize, w8: bool, batch: bool)
1607                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1608        debug_assert!(!batch || w8, "batch twin exists for the w8 form only");
1609        let mut y = self.alloc_uninit::<f32>(t * n_experts)?;
1610        let f = if batch { self.func("router_gemv_f32_w8_batch") }
1611                else if w8 { self.func("router_gemv_f32_w8") }
1612                else { self.func("router_gemv_f32") };
1613        let (ne, nx, ti) = (n_embd as i32, n_experts as i32, t as i32);
1614        let cfg = if batch {
1615            LaunchConfig { grid_dim: (n_experts.div_ceil(8) as u32, t.div_ceil(8) as u32, 1),
1616                           block_dim: (32, 8, 1), shared_mem_bytes: 0 }
1617        } else {
1618            LaunchConfig { grid_dim: (n_experts as u32, t as u32, 1),
1619                           block_dim: (32, if w8 { 8 } else { 1 }, 1), shared_mem_bytes: 0 }
1620        };
1621        let __s_b = self.gpu.stream();
1622        let mut b = __s_b.launch_builder(&f);
1623        b.arg(w).arg(x).arg(&mut y).arg(&ne).arg(&nx).arg(&ti);
1624        unsafe { b.launch(cfg)?; }
1625        Ok(y)
1626    }
1627
1628    /// f32 row permute: dst[idx[i], :] = src[i, :] (grouped-GEMM CSR -> pair-id reorder).
1629    pub fn rows_permute(&self, src: &CudaSlice<f32>, idx: &CudaSlice<i32>, nrows: usize,
1630                        ncols: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1631        let mut dst = self.alloc_uninit::<f32>(nrows * ncols)?;
1632        let f = self.func("rows_permute_f32");
1633        let (nc, nr) = (ncols as i32, nrows as i32);
1634        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (256, 1, 1),
1635                                 shared_mem_bytes: 0 };
1636        let __s_b = self.gpu.stream();
1637        let mut b = __s_b.launch_builder(&f);
1638        b.arg(src).arg(idx).arg(&mut dst).arg(&nc).arg(&nr);
1639        unsafe { b.launch(cfg)?; }
1640        Ok(dst)
1641    }
1642
1643    /// shexp gate fused dot: g[tok] = sigmoid(dot(x[tok,:], w)) — replaces the per-layer
1644    /// cuBLASLt m=1 GEMM + separate sigmoid launch on the qwen35moe decode path (the
1645    /// splitKreduce x40/step dig, 2026-07-31). One fold order for every t, so the t=1
1646    /// decode chain and the small-t spec-verify chain match per row by construction.
1647    pub fn sigmoid_dot_rows(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, n_embd: usize,
1648                            t: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1649        // MEMRA_SHEXP_DOT=0: rollback seam to the cuBLASLt linear + sigmoid pair (numeric
1650        // config; same class as MEMRA_ROUTER_V2).
1651        static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1652        if *OFF.get_or_init(|| std::env::var("MEMRA_SHEXP_DOT").as_deref() == Ok("0")) {
1653            let gs = self.linear(x, w, t, n_embd, 1)?;
1654            let mut g = self.uninit(t)?;
1655            self.sigmoid(&gs, &mut g, t)?;
1656            return Ok(g);
1657        }
1658        // FAST-ROUTER lane note (2026-08-02): a register-tiled 8-token batch twin of this
1659        // kernel was built, proven bit-identical, and measured SLOWER at every prefill t on
1660        // the 5090 (0.62-0.89x — launch-latency-bound op, ~7us/layer at m=2048;
1661        // research/fast-router-20260802/crossover-router.jsonl). Dispatch arm killed per
1662        // flags doctrine; this per-token form serves every t.
1663        let mut g = self.alloc_uninit::<f32>(t)?;
1664        let f = self.func("sigmoid_dot_rows_f32");
1665        let (ne, ti) = (n_embd as i32, t as i32);
1666        let cfg = LaunchConfig { grid_dim: (t as u32, 1, 1), block_dim: (32, 8, 1),
1667                                 shared_mem_bytes: 0 };
1668        let __s_b = self.gpu.stream();
1669        let mut b = __s_b.launch_builder(&f);
1670        b.arg(x).arg(w).arg(&mut g).arg(&ne).arg(&ti);
1671        unsafe { b.launch(cfg)?; }
1672        Ok(g)
1673    }
1674
1675    /// ROUND-STREAM stream rollback: all counters <- pos_start + base + n_acc.
1676    pub fn spec_rollback_stream(&self, len_ptrs: &CudaSlice<u64>, pos_start: &CudaSlice<i32>,
1677                                acc: &CudaSlice<u32>, base: usize, n_rows: usize)
1678                                -> Result<(), Box<dyn std::error::Error>> {
1679        let f = self.func("spec_rollback_stream");
1680        let (b, nr) = (base as i32, n_rows as i32);
1681        let cfg = LaunchConfig { grid_dim: (n_rows.div_ceil(64) as u32, 1, 1),
1682                                 block_dim: (64, 1, 1), shared_mem_bytes: 0 };
1683        let __s_bl = self.gpu.stream();
1684        let mut bl = __s_bl.launch_builder(&f);
1685        bl.arg(len_ptrs).arg(pos_start).arg(acc).arg(&b).arg(&nr);
1686        unsafe { bl.launch(cfg)?; }
1687        Ok(())
1688    }
1689
1690    /// PLAIN-DECODE GRAPH ring store: ring[(pos_start - base) % cap] = vam[0].
1691    pub fn plain_tok_ring(&self, vam: &CudaSlice<u32>, pos_start: &CudaSlice<i32>,
1692                          base: usize, ring: &mut CudaSlice<u32>)
1693                          -> Result<(), Box<dyn std::error::Error>> {
1694        let f = self.func("plain_tok_ring");
1695        let (b, cap) = (base as i32, ring.len() as i32);
1696        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1697        let __s_bl = self.gpu.stream();
1698        let mut bl = __s_bl.launch_builder(&f);
1699        bl.arg(vam).arg(pos_start).arg(&b).arg(&mut *ring).arg(&cap);
1700        unsafe { bl.launch(cfg)?; }
1701        Ok(())
1702    }
1703
1704    /// ROUND-STREAM stage (c) 4 epilogue: ring commit + tiny counter copies.
1705    pub fn spec_ring_commit(&self, vtok: &CudaSlice<u32>, acc: &CudaSlice<u32>,
1706                            brk: &CudaSlice<u32>, ring: &mut CudaSlice<u32>,
1707                            pend: &mut CudaSlice<u32>)
1708                            -> Result<(), Box<dyn std::error::Error>> {
1709        let f = self.func("spec_ring_commit");
1710        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1711        let __s_b = self.gpu.stream();
1712        let mut b = __s_b.launch_builder(&f);
1713        b.arg(vtok).arg(acc).arg(brk).arg(ring).arg(pend);
1714        unsafe { b.launch(cfg)?; }
1715        Ok(())
1716    }
1717    pub fn i32_copy_add(&self, src: &CudaSlice<i32>, dst: &mut CudaSlice<i32>, delta: i32)
1718                        -> Result<(), Box<dyn std::error::Error>> {
1719        let f = self.func("i32_copy_add");
1720        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1721        let __s_b = self.gpu.stream();
1722        let mut b = __s_b.launch_builder(&f);
1723        b.arg(src).arg(dst).arg(&delta);
1724        unsafe { b.launch(cfg)?; }
1725        Ok(())
1726    }
1727    pub fn u32_copy(&self, src: &CudaSlice<u32>, dst: &mut CudaSlice<u32>)
1728                    -> Result<(), Box<dyn std::error::Error>> {
1729        let f = self.func("u32_copy");
1730        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1731        let __s_b = self.gpu.stream();
1732        let mut b = __s_b.launch_builder(&f);
1733        b.arg(src).arg(dst);
1734        unsafe { b.launch(cfg)?; }
1735        Ok(())
1736    }
1737
1738    /// ROUND-GRAPH adaptive depth: brk[0] <- clamp(acc[0] + 1, floor, cap) — the host
1739    /// adaptive policy as a captured device op (policy-identical: the accept walk depth
1740    /// caps acceptance exactly like drafting fewer tokens).
1741    pub fn spec_adapt_k(&self, acc: &CudaSlice<u32>, brk: &mut CudaSlice<u32>,
1742                        floor: usize, cap: usize)
1743                        -> Result<(), Box<dyn std::error::Error>> {
1744        let f = self.func("spec_adapt_k");
1745        let (fl, cp) = (floor as i32, cap as i32);
1746        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1747        let __s_b = self.gpu.stream();
1748        let mut b = __s_b.launch_builder(&f);
1749        b.arg(acc).arg(brk).arg(&fl).arg(&cp);
1750        unsafe { b.launch(cfg)?; }
1751        Ok(())
1752    }
1753
1754    /// ROUND-STREAM stage (c) 3: accept walk fully device-driven (brk + assembled vtok).
1755    pub fn spec_accept_greedy_dc(&self, preds: &CudaSlice<u32>, vtok: &CudaSlice<u32>,
1756                                 last_pred: &CudaSlice<u32>, brk: &CudaSlice<u32>,
1757                                 out: &mut CudaSlice<u32>)
1758                                 -> Result<(), Box<dyn std::error::Error>> {
1759        let f = self.func("spec_accept_greedy_dc");
1760        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1761        let __s_b = self.gpu.stream();
1762        let mut b = __s_b.launch_builder(&f);
1763        b.arg(preds).arg(vtok).arg(last_pred).arg(brk).arg(out);
1764        unsafe { b.launch(cfg)?; }
1765        Ok(())
1766    }
1767
1768    /// ROUND-STREAM stage (c) 2: verify-chain device-pos entries.
1769    pub fn pos_iota(&self, pos0: &CudaSlice<i32>, out: &mut CudaSlice<i32>, t: usize)
1770                    -> Result<(), Box<dyn std::error::Error>> {
1771        let f = self.func("pos_iota_i32");
1772        let ti = t as i32;
1773        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (t.max(1) as u32, 1, 1),
1774                                 shared_mem_bytes: 0 };
1775        let __s_b = self.gpu.stream();
1776        let mut b = __s_b.launch_builder(&f);
1777        b.arg(pos0).arg(out).arg(&ti);
1778        unsafe { b.launch(cfg)?; }
1779        Ok(())
1780    }
1781    #[allow(clippy::too_many_arguments)]
1782    pub fn append_kv_quantized_rows_dc(&self, k_rows: &CudaSlice<f32>, v_rows: &CudaSlice<f32>,
1783                                       kc: &mut CudaSlice<u8>, vc: &mut CudaSlice<u8>,
1784                                       t0_dev: &CudaSlice<i32>, t: usize,
1785                                       kv_dim_k: usize, kv_dim_v: usize,
1786                                       k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
1787                                       -> Result<(), Box<dyn std::error::Error>> {
1788        let f = if g { self.func_g("append_quantize_kv_q8_0_q5_1_rows_dc") }
1789                else { self.func("append_quantize_kv_q8_0_q5_1_rows_dc") };
1790        let nblk = (kv_dim_k.max(kv_dim_v) / 32) as u32;
1791        let cfg = LaunchConfig { grid_dim: (nblk, t as u32, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1792        let (kdk, kdv) = (kv_dim_k as i32, kv_dim_v as i32);
1793        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
1794        let __s_b = self.gpu.stream();
1795        let mut b = __s_b.launch_builder(&f);
1796        b.arg(k_rows).arg(v_rows).arg(kc).arg(vc).arg(t0_dev).arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
1797        unsafe { b.launch(cfg)?; }
1798        Ok(())
1799    }
1800
1801    /// t=1 dc append with a FUSED len_d increment (wave 5c) — one launch replaces
1802    /// append_rows_dc + inc_seqlen. Single block (read-before-inc ordering).
1803    #[allow(clippy::too_many_arguments)]
1804    pub fn append_kv_quantized_row_dc_inc(&self, k_row: &CudaSlice<f32>, v_row: &CudaSlice<f32>,
1805                                          kc: &mut CudaSlice<u8>, vc: &mut CudaSlice<u8>,
1806                                          t0_dev: &mut CudaSlice<i32>,
1807                                          kv_dim_k: usize, kv_dim_v: usize,
1808                                          k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
1809                                          -> Result<(), Box<dyn std::error::Error>> {
1810        let f = if g { self.func_g("append_quantize_kv_q8_0_q5_1_dc_inc") }
1811                else { self.func("append_quantize_kv_q8_0_q5_1_dc_inc") };
1812        let nthreads = ((kv_dim_k.max(kv_dim_v) / 32) * 32).min(1024) as u32;
1813        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (nthreads, 1, 1),
1814                                 shared_mem_bytes: 0 };
1815        let (kdk, kdv) = (kv_dim_k as i32, kv_dim_v as i32);
1816        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
1817        let __s_b = self.gpu.stream();
1818        let mut b = __s_b.launch_builder(&f);
1819        b.arg(k_row).arg(v_row).arg(kc).arg(vc).arg(t0_dev).arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
1820        unsafe { b.launch(cfg)?; }
1821        Ok(())
1822    }
1823
1824    /// ROUND-STREAM: draft-chain pack + in-graph d2t remap (see kernels.cu headers).
1825    pub fn pack_tok_p(&self, tok: &CudaSlice<u32>, p: &CudaSlice<f32>, out: &mut CudaSlice<u32>,
1826                      slot: usize) -> Result<(), Box<dyn std::error::Error>> {
1827        let f = self.func("pack_tok_p");
1828        let sl = slot as i32;
1829        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1830        let __s_b = self.gpu.stream();
1831        let mut b = __s_b.launch_builder(&f);
1832        b.arg(tok).arg(p).arg(out).arg(&sl);
1833        unsafe { b.launch(cfg)?; }
1834        Ok(())
1835    }
1836    pub fn tok_map_u32(&self, tok: &mut CudaSlice<u32>, map: &CudaSlice<u32>)
1837                       -> Result<(), Box<dyn std::error::Error>> {
1838        let f = self.func("tok_map_u32");
1839        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1840        let __s_b = self.gpu.stream();
1841        let mut b = __s_b.launch_builder(&f);
1842        b.arg(tok).arg(map);
1843        unsafe { b.launch(cfg)?; }
1844        Ok(())
1845    }
1846
1847    /// ROUND-STREAM stage (c) 1: device verify-token assembly + p-min break derivation.
1848    #[allow(clippy::too_many_arguments)]
1849    pub fn spec_assemble_verify(&self, tokp: &CudaSlice<u32>, pend: &CudaSlice<u32>,
1850                                d2t: Option<&CudaSlice<u32>>, vtok: &mut CudaSlice<u32>,
1851                                brk: &mut CudaSlice<u32>, p_min: f32, k: usize, pmin0: bool)
1852                                -> Result<(), Box<dyn std::error::Error>> {
1853        let f = self.func("spec_assemble_verify");
1854        let (ki, pm) = (k as i32, if pmin0 { 1i32 } else { 0i32 });
1855        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1856        let __s_b = self.gpu.stream();
1857        let mut b = __s_b.launch_builder(&f);
1858        match d2t {
1859            Some(m) => { b.arg(tokp).arg(pend).arg(m).arg(vtok).arg(brk).arg(&p_min).arg(&ki).arg(&pm);
1860                         unsafe { b.launch(cfg)?; } }
1861            None => { let null: u64 = 0;
1862                      b.arg(tokp).arg(pend).arg(&null).arg(vtok).arg(brk).arg(&p_min).arg(&ki).arg(&pm);
1863                      unsafe { b.launch(cfg)?; } }
1864        }
1865        Ok(())
1866    }
1867
1868    /// ROUND-STREAM stage (b) 3b: recur-restore twins with device-j (see hybrid.cu headers).
1869    #[allow(clippy::too_many_arguments)]
1870    pub fn ssm_conv_ring_rebuild_dc(&self, qkv_tm: &CudaSlice<f32>, ring_old: &CudaSlice<f32>,
1871                                    conv_state: &mut CudaSlice<f32>, conv_dim: usize,
1872                                    acc: &CudaSlice<u32>, base: usize, t_v: usize, d_conv: usize)
1873                                    -> Result<(), Box<dyn std::error::Error>> {
1874        let f = self.func("ssm_conv_ring_rebuild_f32_dc");
1875        let n = conv_dim * (d_conv - 1);
1876        let cfg = LaunchConfig::for_num_elems(n as u32);
1877        let (cd, b0, tv, dc) = (conv_dim as i32, base as i32, t_v as i32, d_conv as i32);
1878        let __s_b = self.gpu.stream();
1879        let mut b = __s_b.launch_builder(&f);
1880        b.arg(qkv_tm).arg(ring_old).arg(conv_state).arg(&cd).arg(acc).arg(&b0).arg(&tv).arg(&dc);
1881        unsafe { b.launch(cfg)?; }
1882        Ok(())
1883    }
1884    #[allow(clippy::too_many_arguments)]
1885    pub fn gdn_scan_s128_dc(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
1886                            g: &CudaSlice<f32>, beta: &CudaSlice<f32>, state_in: &CudaSlice<f32>,
1887                            state_out: &mut CudaSlice<f32>, o: &mut CudaSlice<f32>,
1888                            n_head: usize, acc: &CudaSlice<u32>, base: usize, t_v: usize,
1889                            scale: f32)
1890                            -> Result<(), Box<dyn std::error::Error>> {
1891        let f = self.func("gdn_scan_s128_dc");
1892        const S_V: u32 = 128; const WARP: u32 = 32; const COLS_PER_BLOCK: u32 = 4;
1893        let cfg = LaunchConfig {
1894            grid_dim: (n_head as u32, 1, S_V / COLS_PER_BLOCK),
1895            block_dim: (WARP, COLS_PER_BLOCK, 1),
1896            shared_mem_bytes: 0,
1897        };
1898        let (h, b0, tv) = (n_head as i32, base as i32, t_v as i32);
1899        let __s_b = self.gpu.stream();
1900        let mut b = __s_b.launch_builder(&f);
1901        b.arg(q).arg(k).arg(v).arg(g).arg(beta).arg(state_in).arg(state_out).arg(o)
1902         .arg(&h).arg(acc).arg(&b0).arg(&tv).arg(&scale);
1903        unsafe { b.launch(cfg)?; }
1904        Ok(())
1905    }
1906
1907    /// ROUND-STREAM stage (b) 3a: device per-layer KV-len rollback (see spec_rollback_kv).
1908    pub fn spec_rollback_kv(&self, len_ptrs: &CudaSlice<u64>, saved: &CudaSlice<i32>,
1909                            acc: &CudaSlice<u32>, base: usize, n_layer: usize)
1910                            -> Result<(), Box<dyn std::error::Error>> {
1911        let f = self.func("spec_rollback_kv");
1912        let (b, nl) = (base as i32, n_layer as i32);
1913        let cfg = LaunchConfig { grid_dim: (n_layer.div_ceil(64) as u32, 1, 1),
1914                                 block_dim: (64, 1, 1), shared_mem_bytes: 0 };
1915        let __s_bl = self.gpu.stream();
1916        let mut bl = __s_bl.launch_builder(&f);
1917        bl.arg(len_ptrs).arg(saved).arg(acc).arg(&b).arg(&nl);
1918        unsafe { bl.launch(cfg)?; }
1919        Ok(())
1920    }
1921
1922    /// ROUND-STREAM stage (b): device next-round seed gather (see spec_seed_gather header).
1923    /// Caller D2Ds h_seed into fill_prev after (both slots carry the same value in every arm).
1924    pub fn spec_seed_gather(&self, vx: &CudaSlice<f32>, fill_prev: &CudaSlice<f32>,
1925                            acc: &CudaSlice<u32>, h_seed: &mut CudaSlice<f32>,
1926                            base: usize, n_embd: usize)
1927                            -> Result<(), Box<dyn std::error::Error>> {
1928        let f = self.func("spec_seed_gather");
1929        let (b, ne) = (base as i32, n_embd as i32);
1930        let cfg = LaunchConfig { grid_dim: (n_embd.div_ceil(256) as u32, 1, 1),
1931                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1932        let __s_bl = self.gpu.stream();
1933        let mut bl = __s_bl.launch_builder(&f);
1934        bl.arg(vx).arg(fill_prev).arg(acc).arg(h_seed).arg(&b).arg(&ne);
1935        unsafe { bl.launch(cfg)?; }
1936        Ok(())
1937    }
1938
1939
1940    /// ROUND-STREAM stage (a): device greedy accept walk (see spec_accept_greedy header).
1941    pub fn spec_accept_greedy(&self, preds: &CudaSlice<u32>, draft: &CudaSlice<u32>,
1942                              last_pred: u32, base: usize, k_round: usize,
1943                              out: &mut CudaSlice<u32>)
1944                              -> Result<(), Box<dyn std::error::Error>> {
1945        let f = self.func("spec_accept_greedy");
1946        let (b, k) = (base as i32, k_round as i32);
1947        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
1948        let __s_bl = self.gpu.stream();
1949        let mut bl = __s_bl.launch_builder(&f);
1950        bl.arg(preds).arg(draft).arg(&last_pred).arg(&b).arg(&k).arg(out);
1951        unsafe { bl.launch(cfg)?; }
1952        Ok(())
1953    }
1954
1955    // ================= SAMPLED-SPEC PRIMITIVES (spec_sample.cu, piece A) =================
1956    // Counter-based randomness: every call takes (seed, stream_pos) — the caller owns the
1957    // event counter (one per sampled token). temp <= 0 arms are exact greedy limits.
1958
1959    /// y = x/temp + Gumbel(Philox(seed, stream_pos)) over n logits (then run device argmax on y
1960    /// = one categorical sample at temperature `temp`). temp<=0: y = x (pure copy).
1961    pub fn gumbel_perturb(&self, x: &CudaSlice<f32>, y: &mut CudaSlice<f32>, n: usize,
1962                          seed: u64, stream_pos: u32, temp: f32)
1963                          -> Result<(), Box<dyn std::error::Error>> {
1964        let f = self.func("gumbel_perturb_f32");
1965        let (ni, slo, shi) = (n as i32, (seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
1966        let cfg = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1967        let __s_b = self.gpu.stream();
1968        let mut b = __s_b.launch_builder(&f);
1969        b.arg(x).arg(&mut *y).arg(&ni).arg(&slo).arg(&shi).arg(&stream_pos).arg(&temp);
1970        unsafe { b.launch(cfg)?; }
1971        Ok(())
1972    }
1973
1974    /// GRAMMAR TOKEN MASK (constrained decoding, lane/constrained-full): ban every vocab id
1975    /// whose bit is unset in the packed llguidance bitset, IN PLACE on row `col` of a stacked
1976    /// [B, n_vocab] logits buffer. `mask` = the SimpleVob u32 words H2D'd verbatim
1977    /// (~n_vocab/8 bytes/step — trivial on PCIe); ids >= 32*mask_words (padded lm_head tail)
1978    /// are banned too, the device twin of constrained::apply_mask. Banned value -FLT_MAX ==
1979    /// the argmax/gumbel kernels' init sentinel, so a fully-banned tail can never win and
1980    /// ordering matches the host -inf mask bit-for-bit for every finite logit.
1981    pub fn mask_logits_col(&self, logits: &mut CudaSlice<f32>, mask: &CudaSlice<u32>,
1982                           col: usize, n: usize, mask_words: usize)
1983                           -> Result<(), Box<dyn std::error::Error>> {
1984        let f = self.func("mask_logits_f32");
1985        let (ci, ni, mw) = (col as i32, n as i32, mask_words as i32);
1986        let cfg = LaunchConfig { grid_dim: (n.div_ceil(256).min(1024) as u32, 1, 1),
1987                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
1988        let __s_b = self.gpu.stream();
1989        let mut b = __s_b.launch_builder(&f);
1990        b.arg(&mut *logits).arg(mask).arg(&ci).arg(&ni).arg(&mw);
1991        unsafe { b.launch(cfg)?; }
1992        Ok(())
1993    }
1994
1995    /// Column-`col` twin of `gumbel_perturb` over stacked logits [B, n_vocab] (the batched
1996    /// serving tick's device sampler): y = x[col]/temp + gumbel(seed, stream_pos, lane).
1997    /// SAME kernel/Philox mapping as `gumbel_perturb` — bit-identical perturbation for the
1998    /// same (seed, stream_pos, temp) regardless of which batch column the row sits in
1999    /// (the lane index is the in-row position; `col` only moves the input pointer). That
2000    /// pointer-invariance IS the serving isolation contract for sampled rows.
2001    pub fn gumbel_perturb_col(&self, x: &CudaSlice<f32>, col: usize, y: &mut CudaSlice<f32>,
2002                              n: usize, seed: u64, stream_pos: u32, temp: f32)
2003                              -> Result<(), Box<dyn std::error::Error>> {
2004        let f = self.func("gumbel_perturb_f32");
2005        let (ni, slo, shi) = (n as i32, (seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
2006        let col_view = x.slice(col * n..(col + 1) * n);
2007        let cfg = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2008        let __s_b = self.gpu.stream();
2009        let mut b = __s_b.launch_builder(&f);
2010        b.arg(&col_view).arg(&mut *y).arg(&ni).arg(&slo).arg(&shi).arg(&stream_pos).arg(&temp);
2011        unsafe { b.launch(cfg)?; }
2012        Ok(())
2013    }
2014
2015    /// In-graph sampling-event counter bump (spec_sample.cu kernel 5): ctr[0] += 1. The sampled
2016    /// graph-draft chain replays with FIXED kernel args, so the Philox event counter must be
2017    /// DEVICE data — the host seeds it once per round; every replay bumps it before the perturb
2018    /// reads it (counter is data, not state — graph-replay-safe).
2019    pub fn sctr_inc(&self, ctr: &mut CudaSlice<u32>) -> Result<(), Box<dyn std::error::Error>> {
2020        let f = self.func("memra_sctr_inc");
2021        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (1, 1, 1), shared_mem_bytes: 0 };
2022        let __s_b = self.gpu.stream();
2023        let mut b = __s_b.launch_builder(&f);
2024        b.arg(&mut *ctr);
2025        unsafe { b.launch(cfg)?; }
2026        Ok(())
2027    }
2028
2029    /// Graph-capturable `gumbel_perturb`: the sampling-event counter comes from DEVICE memory
2030    /// (`ctr[0]`) instead of a host scalar. Identical math to `gumbel_perturb` at
2031    /// stream_pos == ctr[0] (same Philox call, same lane mapping) — the eager and graph sampled
2032    /// chains produce bit-identical perturbations for the same (seed, counter, temp).
2033    pub fn gumbel_perturb_ctr(&self, x: &CudaSlice<f32>, y: &mut CudaSlice<f32>, n: usize,
2034                              seed: u64, ctr: &CudaSlice<u32>, temp: f32)
2035                              -> Result<(), Box<dyn std::error::Error>> {
2036        let f = self.func("gumbel_perturb_ctr_f32");
2037        let (ni, slo, shi) = (n as i32, (seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
2038        let cfg = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2039        let __s_b = self.gpu.stream();
2040        let mut b = __s_b.launch_builder(&f);
2041        b.arg(x).arg(&mut *y).arg(&ni).arg(&slo).arg(&shi).arg(ctr).arg(&temp);
2042        unsafe { b.launch(cfg)?; }
2043        Ok(())
2044    }
2045
2046    /// out[pair] = softmax_temp(x[rows[pair]])[ids[pair]] for npair (row, id) pairs; rows index
2047    /// into x with `row_stride` f32s per row. temp<=0: out = 1.0 iff id is the row argmax
2048    /// (smallest-index tie-break — matches the argmax-gate contract).
2049    pub fn softmax_gather(&self, x: &CudaSlice<f32>, row_stride: usize,
2050                          ids: &CudaSlice<u32>, rows: &CudaSlice<i32>,
2051                          out: &mut CudaSlice<f32>, n: usize, npair: usize, temp: f32)
2052                          -> Result<(), Box<dyn std::error::Error>> {
2053        let f = self.func("softmax_gather_f32");
2054        let (ni, rs) = (n as i32, row_stride as i64);
2055        let np = npair as i32;
2056        let cfg = LaunchConfig { grid_dim: (npair as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2057        let __s_b = self.gpu.stream();
2058        let mut b = __s_b.launch_builder(&f);
2059        b.arg(x).arg(&rs).arg(ids).arg(rows).arg(&mut *out).arg(&ni).arg(&np).arg(&temp);
2060        unsafe { b.launch(cfg)?; }
2061        Ok(())
2062    }
2063
2064    /// Sample token from norm(max(0, softmax_temp(p) - softmax_temp(q))) (q = None -> plain
2065    /// categorical from softmax_temp(p)). Row stats (max, sumexp at temp) must be precomputed
2066    /// (softmax_gather's pass-1 values; see spec.rs caller). Deterministic fixed-order CDF walk.
2067    pub fn residual_sample(&self, p: &CudaSlice<f32>, q: Option<&CudaSlice<f32>>, n: usize,
2068                           temp: f32, seed: u64, stream_pos: u32,
2069                           out_tok: &mut CudaSlice<u32>)
2070                           -> Result<(), Box<dyn std::error::Error>> {
2071        let f = self.func("residual_sample_f32");
2072        let (ni, slo, shi) = (n as i32, (seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
2073        let nth = 1024u32;
2074        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (nth, 1, 1), shared_mem_bytes: 0 };
2075        let has_q: i32 = q.is_some() as i32;
2076        let qbuf = q.unwrap_or(p);   // dummy when absent; kernel gates on has_q
2077        let __s_b = self.gpu.stream();
2078        let mut b = __s_b.launch_builder(&f);
2079        b.arg(p).arg(qbuf).arg(&has_q).arg(&ni).arg(&temp).arg(&slo).arg(&shi).arg(&stream_pos)
2080         .arg(&mut *out_tok);
2081        unsafe { b.launch(cfg)?; }
2082        Ok(())
2083    }
2084
2085    /// Access the shared MoE residency cache (EDGE-1 §B), building it on first use under
2086    /// MEMRA_MOE_CACHE. The closure runs while the lock is held — keep it to lookup/admit/issue, not
2087    /// the GEMM. `max_block_bytes` sizes the slots (largest of gate/up/down). Returns the closure's
2088    /// result. If MEMRA_MOE_CACHE is unset this is never called (the caller checks the env first).
2089    pub fn with_moe_cache<R>(&self, max_block_bytes: usize,
2090                             f: impl FnOnce(&mut crate::moe_cache::MoeSlotCache, &Engine) -> Result<R, Box<dyn std::error::Error>>)
2091                             -> Result<R, Box<dyn std::error::Error>> {
2092        let mut guard = self.moe_cache.lock().unwrap();
2093        if guard.is_none() {
2094            *guard = Some(crate::moe_cache::MoeSlotCache::new(self, max_block_bytes)?);
2095        }
2096        let cache = guard.as_mut().unwrap();
2097                f(cache, self)
2098    }
2099
2100    /// Freeze the already-built MoE residency set. This never constructs a cache: callers use it
2101    /// only after a real prefill has populated the machine-specific CPU/GPU working set.
2102    pub fn freeze_moe_cache(&self) {
2103        if let Some(cache) = self.moe_cache.lock().unwrap().as_mut() {
2104            cache.freeze();
2105        }
2106    }
2107
2108    /// The current residency set as (layer, proj, ex) triples, or None if no cache was built.
2109    /// Never constructs a cache.
2110    pub fn export_moe_residency(&self) -> Option<Vec<(u16, u8, u16)>> {
2111        self.moe_cache
2112            .lock()
2113            .unwrap()
2114            .as_ref()
2115            .map(crate::moe_cache::MoeSlotCache::export_residency)
2116    }
2117
2118    pub(crate) fn moe_cache_frozen(&self) -> bool {
2119        self.moe_cache
2120            .lock()
2121            .unwrap()
2122            .as_ref()
2123            .is_some_and(crate::moe_cache::MoeSlotCache::is_frozen)
2124    }
2125
2126    /// A frozen heterogeneous CPU/GPU expert split cannot use Hy3's ordinary batched prefill
2127    /// efficiently: T>=PRIME_MIN_T bypasses the CPU backend and transiently rereads every missing
2128    /// expert through the GPU spill path. Replay the short prompt through decode after freezing,
2129    /// while leaving the profiling warmup's established batched behavior untouched.
2130    /// (`pub`: run-gen's #46 batched-prime gate skips itself when generation will take the
2131    /// tokenwise arm anyway.)
2132    pub fn frozen_cpu_experts_prefer_tokenwise_prime(&self) -> bool {
2133        crate::cpu_experts::configured()
2134            && self.moe_cache_frozen()
2135            && std::env::var("MEMRA_CPU_EXPERT_BATCHED_PRIME").as_deref() != Ok("1")
2136    }
2137
2138    /// Install the loaded model's exact retained expert-block inventory before lazy cache build.
2139    pub(crate) fn configure_moe_cache_layout(&self, block_bytes: Vec<usize>) {
2140        assert!(
2141            self.moe_cache.lock().unwrap().is_none(),
2142            "MoE cache layout configured after cache construction"
2143        );
2144        *self.moe_cache_layout.lock().unwrap() = Some(block_bytes);
2145    }
2146
2147    pub(crate) fn moe_cache_layout(&self) -> Option<Vec<usize>> {
2148        self.moe_cache_layout.lock().unwrap().clone()
2149    }
2150
2151    /// True if the MoE residency cache is enabled (MEMRA_MOE_CACHE set).
2152    pub fn moe_cache_enabled() -> bool {
2153        std::env::var("MEMRA_MOE_CACHE").as_deref() != Ok("0")
2154 }
2155
2156    /// Snapshot the MoE cache counters (hits, misses, staged_bytes, n_slots) for the §D.4 PCIe gate.
2157    /// Returns None if the cache was never built (disabled or no MoE forward ran).
2158    pub fn moe_cache_stats(&self) -> Option<(u64, u64, u64, usize)> {
2159        let guard = self.moe_cache.lock().unwrap();
2160        guard.as_ref()            .map(|c| (c.hits, c.misses, c.staged_bytes, c.n_slots()))
2161    }
2162
2163    /// Experimental CPU expert backend counters: completed layer calls, experts served, and the
2164    /// sum of backend wall nanoseconds. The timer includes explicit disk->RAM fills on cache misses;
2165    /// callers compare a before/after snapshot around a decode window.
2166    pub fn cpu_expert_stats(
2167        &self,
2168    ) -> Option<(u64, u64, u64, u64, u64, u64, u64, u64, u64, u64, u64)> {
2169        crate::cpu_experts::configured().then(crate::cpu_experts::stats)
2170    }
2171
2172    /// Caller-blocked nanoseconds at CPU expert joins. Compare before/after snapshots to measure
2173    /// the backend tail that resident-GPU expert work did not hide.
2174    pub fn cpu_expert_predictor_stats(&self) -> (u64, u64) {
2175        crate::cpu_experts::predictor_stats()
2176    }
2177
2178    pub fn cpu_expert_exposed_wait_ns(&self) -> Option<u64> {
2179        crate::cpu_experts::configured().then(crate::cpu_experts::exposed_wait_ns)
2180    }
2181
2182    /// CPU-routed expert selections grouped by how many of their three projections were already
2183    /// resident in HBM. This makes otherwise-stranded partial residency visible to tuning runs.
2184    pub fn cpu_expert_gpu_residency_stats(&self) -> Option<(u64, u64, u64)> {
2185        crate::cpu_experts::configured().then(crate::cpu_experts::incomplete_gpu_residency_stats)
2186    }
2187
2188    /// Positioned-read proof-backend counters:
2189    /// `(reads, bytes, read_errors, short_reads, mmap_fallbacks, buffer_waits, ring_full)`.
2190    pub fn moe_pread_stats(&self) -> Option<(u64, u64, u64, u64, u64, u64, u64)> {
2191
2192        let guard = self.moe_cache.lock().unwrap();
2193        guard.as_ref().and_then(|cache| cache.pread_stats()).map(|stats| (
2194            stats.reads,
2195            stats.bytes,
2196            stats.read_errors,
2197            stats.short_reads,
2198            stats.fallbacks,
2199            stats.buffer_waits,
2200            stats.ring_full,
2201        ))
2202    }
2203
2204    /// Reset the MoE cache perf counters (to separate warmup from steady-state windows).
2205    pub fn moe_cache_reset_counters(&self) {
2206        if let Some(c) = self.moe_cache.lock().unwrap().as_mut() { c.reset_counters(); }
2207    }
2208
2209    pub fn htod_bytes(&self, v: &[u8]) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
2210        Ok(self.gpu.stream().clone_htod(v)?)
2211    }
2212
2213    /// `htod_bytes` with a mapped (uninit) tail pad: the wide-load expert dots read up to 6B
2214    /// past the final q4_0 block through their aligned window — the bytes never reach a
2215    /// result (funnelshift discards them) but must be mapped memory.
2216    pub fn htod_bytes_padded(&self, v: &[u8], pad: usize)
2217                             -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
2218        let mut d = self.alloc_u8_uninit(v.len() + pad)?;
2219        {
2220            let mut view = d.slice_mut(0..v.len());
2221            self.gpu.stream().memcpy_htod(v, &mut view)?;
2222        }
2223        Ok(d)
2224    }
2225
2226    /// Device-to-device copy of `src` into `dst[off..off+len]` (f32). For in-place KV append.
2227    pub fn copy_into(&self, dst: &mut CudaSlice<f32>, off: usize, src: &CudaSlice<f32>, len: usize)
2228                     -> Result<(), Box<dyn std::error::Error>> {
2229        let mut view = dst.slice_mut(off..off + len);
2230        self.gpu.stream().memcpy_dtod(&src.slice(0..len), &mut view)?;
2231        Ok(())
2232    }
2233
2234    /// View a sub-range of a device buffer (for attending over [0..len) of a KV cache).
2235    /// u8 twin of copy_into (D2D byte-range copy at an offset).
2236    pub fn copy_u8_into(&self, dst: &mut CudaSlice<u8>, off: usize, src: &CudaSlice<u8>, len: usize)
2237                        -> Result<(), Box<dyn std::error::Error>> {
2238        let mut view = dst.slice_mut(off..off + len);
2239        self.gpu.stream().memcpy_dtod(&src.slice(0..len), &mut view)?;
2240        Ok(())
2241    }
2242
2243    /// D2D byte-range copy with explicit source and destination offsets.
2244    pub fn copy_u8_range_into(
2245        &self,
2246        dst: &mut CudaSlice<u8>,
2247        dst_off: usize,
2248        src: &CudaSlice<u8>,
2249        src_off: usize,
2250        len: usize,
2251    ) -> Result<(), Box<dyn std::error::Error>> {
2252        let mut dst_view = dst.slice_mut(dst_off..dst_off + len);
2253        self.gpu
2254            .stream()
2255            .memcpy_dtod(&src.slice(src_off..src_off + len), &mut dst_view)?;
2256        Ok(())
2257    }
2258
2259    /// Resolve an absolute append slot to the Step35 SWA layer's physical rows. At wrap, copy
2260    /// only the aligned live prefix through temporary device storage and rebase it at row zero,
2261    /// keeping the audited attention range contiguous without changing its absolute start.
2262    pub fn prepare_kv_append(
2263        &self,
2264        kv: &mut crate::cache::KvLayer,
2265        retain_from: usize,
2266        append_rows: usize,
2267    ) -> Result<usize, Box<dyn std::error::Error>> {
2268        let Some(plan) = kv
2269            .ring
2270            .as_ref()
2271            .map(|ring| ring.append_plan(kv.len, retain_from, append_rows))
2272            .transpose()?
2273        else {
2274            return Ok(kv.len);
2275        };
2276        match plan {
2277            crate::cache::KvRingAppend::Contiguous { write_row } => Ok(write_row),
2278            crate::cache::KvRingAppend::Rebase {
2279                src_row,
2280                keep_rows,
2281                new_base,
2282                write_row,
2283            } => {
2284                if keep_rows > 0 {
2285                    let k_len = keep_rows * kv.k_tok_bytes;
2286                    let v_len = keep_rows * kv.v_tok_bytes;
2287                    let mut k_tmp = self.alloc_u8_uninit(k_len)?;
2288                    let mut v_tmp = self.alloc_u8_uninit(v_len)?;
2289                    self.copy_u8_range_into(
2290                        &mut k_tmp,
2291                        0,
2292                        &kv.k,
2293                        src_row * kv.k_tok_bytes,
2294                        k_len,
2295                    )?;
2296                    self.copy_u8_range_into(
2297                        &mut v_tmp,
2298                        0,
2299                        &kv.v,
2300                        src_row * kv.v_tok_bytes,
2301                        v_len,
2302                    )?;
2303                    self.copy_u8_into(&mut kv.k, 0, &k_tmp, k_len)?;
2304                    self.copy_u8_into(&mut kv.v, 0, &v_tmp, v_len)?;
2305                }
2306                kv.ring.as_mut().unwrap().apply_rebase(new_base);
2307                Ok(write_row)
2308            }
2309        }
2310    }
2311
2312    /// H2D write of `src` into `dst[off..off+src.len()]` (u8). In-place row updates for the
2313    /// adaptive trim head: no realloc, so captured graphs keep their baked addresses.
2314    pub fn htod_u8_into(&self, dst: &mut CudaSlice<u8>, off: usize, src: &[u8])
2315                        -> Result<(), Box<dyn std::error::Error>> {
2316        let mut view = dst.slice_mut(off..off + src.len());
2317        self.gpu.stream().memcpy_htod(src, &mut view)?;
2318        Ok(())
2319    }
2320
2321    pub fn view<'a>(&self, b: &'a CudaSlice<f32>, len: usize) -> cudarc::driver::CudaView<'a, f32> {
2322        b.slice(0..len)
2323    }
2324
2325    /// View the first `len` BYTES of a u8 device buffer (quantized KV cache: [0..t_kv*tok_bytes)).
2326    /// Byte-range view (gemma4 R6 window offset into the quantized KV stream).
2327    pub fn view_u8_range<'a>(&self, b: &'a CudaSlice<u8>, start: usize, end: usize)
2328                             -> cudarc::driver::CudaView<'a, u8> {
2329        b.slice(start..end)
2330    }
2331    pub fn view_u8<'a>(&self, b: &'a CudaSlice<u8>, len: usize) -> cudarc::driver::CudaView<'a, u8> {
2332        b.slice(0..len)
2333    }
2334
2335    /// Append-quantize ONE token's post-RoPE K (q8_0) and V (q5_1) into the resident byte caches at
2336    /// token index `t` (KVQUANT-PLAN §C). One CTA (one warp) per 32-element block; the kernel writes
2337    /// the f16 scale(s) + packed quants for K and V. k_row/v_row are f32 [kv_dim_k]/[kv_dim_v].
2338    pub fn append_kv_quantized(&self, k_row: &CudaSlice<f32>, v_row: &CudaSlice<f32>,
2339                               kc: &mut CudaSlice<u8>, vc: &mut CudaSlice<u8>, t: usize,
2340                               kv_dim_k: usize, kv_dim_v: usize,
2341                               k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
2342                               -> Result<(), Box<dyn std::error::Error>> {
2343        let f = if g { self.func_g("append_quantize_kv_q8_0_q5_1") } else { self.func("append_quantize_kv_q8_0_q5_1") };
2344        let nblk = (kv_dim_k.max(kv_dim_v) / 32) as u32;
2345        let cfg = LaunchConfig { grid_dim: (nblk, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2346        let (ti, kdk, kdv) = (t as i32, kv_dim_k as i32, kv_dim_v as i32);
2347        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
2348        let __s_b = self.gpu.stream();
2349        let mut b = __s_b.launch_builder(&f);
2350        b.arg(k_row).arg(v_row).arg(kc).arg(vc).arg(&ti).arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
2351        unsafe { b.launch(cfg)?; }
2352        Ok(())
2353    }
2354
2355    /// Device-counter variant of `append_kv_quantized` (CUDA-GRAPH-PLAN Phase 2): the write slot
2356    /// `t` is read from `t_dev[0]` (a resident device i32[1]) instead of a host int arg, so the
2357    /// launch args are FIXED across decode steps (graph-capturable). Identical quant math.
2358    pub fn append_kv_quantized_dc(&self, k_row: &CudaSlice<f32>, v_row: &CudaSlice<f32>,
2359                                  kc: &mut CudaSlice<u8>, vc: &mut CudaSlice<u8>, t_dev: &CudaSlice<i32>,
2360                                  kv_dim_k: usize, kv_dim_v: usize,
2361                                  k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
2362                               -> Result<(), Box<dyn std::error::Error>> {
2363        let nblk = (kv_dim_k.max(kv_dim_v) / 32) as u32;
2364        let (kdk, kdv) = (kv_dim_k as i32, kv_dim_v as i32);
2365        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
2366        // PDL wave-B2: flash-module flavor mirrors the builder path's g flag exactly.
2367        if Self::pdl_on() && Self::pdl_wb_on() {
2368            use cudarc::driver::{DevicePtr, DevicePtrMut};
2369            let s = &self.gpu.stream();
2370            let (pk, _g0) = k_row.device_ptr(s); let (pv, _g1) = v_row.device_ptr(s);
2371            let (pkc, _g2) = kc.device_ptr_mut(s); let (pvc, _g3) = vc.device_ptr_mut(s);
2372            let (pt, _g4) = t_dev.device_ptr(s);
2373            let mut ps = [
2374                &pk as *const _ as *mut std::ffi::c_void, &pv as *const _ as *mut _,
2375                &pkc as *const _ as *mut _, &pvc as *const _ as *mut _,
2376                &pt as *const _ as *mut _, &kdk as *const _ as *mut _,
2377                &kdv as *const _ as *mut _, &ktb as *const _ as *mut _,
2378                &vtb as *const _ as *mut _,
2379            ];
2380            unsafe { self.launch_pdl_flash(g, "append_quantize_kv_q8_0_q5_1_dc",
2381                                           (nblk, 1, 1), (32, 1, 1), 0, &mut ps)?; }
2382            return Ok(());
2383        }
2384        let f = if g { self.func_g("append_quantize_kv_q8_0_q5_1_dc") } else { self.func("append_quantize_kv_q8_0_q5_1_dc") };
2385        let cfg = LaunchConfig { grid_dim: (nblk, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2386        let __s_b = self.gpu.stream();
2387        let mut b = __s_b.launch_builder(&f);
2388        b.arg(k_row).arg(v_row).arg(kc).arg(vc).arg(t_dev).arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
2389        unsafe { b.launch(cfg)?; }
2390        Ok(())
2391    }
2392
2393    /// Append-quantize T token rows in one shot (BATCHED PROMPT PRIME). k_rows/v_rows are
2394    /// token-major [T, kv_dim] post-RoPE f32; rows land at cache slots t0..t0+T. Default = the
2395    /// batched `_rows` kernel: one (nblk, T) launch whose per-(block,token) warp program is the
2396    /// per-token append kernel verbatim -> every written row is BIT-IDENTICAL to T sequential
2397    /// `append_kv_quantized_view` calls (kernel_check pins the bytes). MEMRA_PRIME_APPEND_LOOP=1
2398    /// forces the T-launch per-row loop (the A/B seam that measured the launch overhead).
2399    #[allow(clippy::too_many_arguments)]
2400    pub fn append_kv_quantized_rows(&self, k_rows: &CudaSlice<f32>, v_rows: &CudaSlice<f32>,
2401                                    kc: &mut CudaSlice<u8>, vc: &mut CudaSlice<u8>,
2402                                    t0: usize, t: usize, kv_dim_k: usize, kv_dim_v: usize,
2403                                    k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
2404                               -> Result<(), Box<dyn std::error::Error>> {
2405        if std::env::var("MEMRA_PRIME_APPEND_LOOP").is_ok() {
2406            for i in 0..t {
2407                let k_row = k_rows.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
2408                let v_row = v_rows.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
2409                self.append_kv_quantized_view(&k_row, &v_row, kc, vc, t0 + i,
2410                                              kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes, g)?;
2411            }
2412            return Ok(());
2413        }
2414        let f = if g { self.func_g("append_quantize_kv_q8_0_q5_1_rows") } else { self.func("append_quantize_kv_q8_0_q5_1_rows") };
2415        let nblk = (kv_dim_k.max(kv_dim_v) / 32) as u32;
2416        let cfg = LaunchConfig { grid_dim: (nblk, t as u32, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2417        let (t0i, kdk, kdv) = (t0 as i32, kv_dim_k as i32, kv_dim_v as i32);
2418        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
2419        let __s_b = self.gpu.stream();
2420        let mut b = __s_b.launch_builder(&f);
2421        b.arg(k_rows).arg(v_rows).arg(kc).arg(vc).arg(&t0i).arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
2422        unsafe { b.launch(cfg)?; }
2423        Ok(())
2424    }
2425
2426    /// Increment a device i32[1] counter in place (p[0] += 1) via the resident `inc_i32` kernel.
2427    /// Used to advance the device-resident seqlen/pos counters inside the decode-dc path (and,
2428    /// later, inside a captured graph) without a host round-trip.
2429    pub fn inc_seqlen(&self, p: &mut CudaSlice<i32>) -> Result<(), Box<dyn std::error::Error>> {
2430        let f = self.func("inc_i32");
2431        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (1, 1, 1), shared_mem_bytes: 0 };
2432        let __s_b = self.gpu.stream();
2433        let mut b = __s_b.launch_builder(&f);
2434        b.arg(p);
2435        unsafe { b.launch(cfg)?; }
2436        Ok(())
2437    }
2438
2439    /// Like `append_kv_quantized` but k_row/v_row are CudaViews (one token's row sliced out of a
2440    /// token-major [T, kv_dim] activation buffer — the MTP verify path appends T tokens).
2441    pub fn append_kv_quantized_view(&self, k_row: &cudarc::driver::CudaView<f32>,
2442                                    v_row: &cudarc::driver::CudaView<f32>,
2443                                    kc: &mut CudaSlice<u8>, vc: &mut CudaSlice<u8>, t: usize,
2444                                    kv_dim_k: usize, kv_dim_v: usize,
2445                                    k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
2446                                    -> Result<(), Box<dyn std::error::Error>> {
2447        let f = if g { self.func_g("append_quantize_kv_q8_0_q5_1") }
2448                else { self.func("append_quantize_kv_q8_0_q5_1") };
2449        let nblk = (kv_dim_k.max(kv_dim_v) / 32) as u32;
2450        let cfg = LaunchConfig { grid_dim: (nblk, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2451        let (ti, kdk, kdv) = (t as i32, kv_dim_k as i32, kv_dim_v as i32);
2452        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
2453        let __s_b = self.gpu.stream();
2454        let mut b = __s_b.launch_builder(&f);
2455        b.arg(k_row).arg(v_row).arg(kc).arg(vc).arg(&ti).arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
2456        unsafe { b.launch(cfg)?; }
2457        Ok(())
2458    }
2459
2460    /// Device-to-device copy of a CudaView `src` into `dst[off..off+len]` (f32). Like `copy_into`
2461    /// but the source is a sub-view (e.g. one column of a token-major activation buffer).
2462    pub fn copy_view_into(&self, dst: &mut CudaSlice<f32>, off: usize,
2463                          src: &cudarc::driver::CudaView<f32>, len: usize)
2464                          -> Result<(), Box<dyn std::error::Error>> {
2465        let mut view = dst.slice_mut(off..off + len);
2466        self.gpu.stream().memcpy_dtod(&src.slice(0..len), &mut view)?;
2467        Ok(())
2468    }
2469
2470    /// Real device-to-device COPY of `src` into a freshly allocated buffer (NOT an Arc clone).
2471    /// Used for cache snapshots (MTP-PLAN §D.4): `CudaSlice::clone()` only bumps a refcount and
2472    /// would alias the live buffer; this allocs new device memory and memcpy_dtod's the contents.
2473    pub fn clone_dtod(&self, src: &CudaSlice<f32>) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2474        let mut dst = self.gpu.stream().alloc_zeros::<f32>(src.len())?;
2475        self.gpu.stream().memcpy_dtod(src, &mut dst)?;
2476        Ok(dst)
2477    }
2478
2479    /// D2D row extraction: copy a view (e.g. one row of a [B, n] batch buffer) into `dst`.
2480    /// Stream-ordered, async — decode_batch's per-sequence row plumbing.
2481    pub fn dtod_copy_view(&self, src: &cudarc::driver::CudaView<f32>, dst: &mut CudaSlice<f32>)
2482                          -> Result<(), Box<dyn std::error::Error>> {
2483        self.gpu.stream().memcpy_dtod(src, dst)?;
2484        Ok(())
2485    }
2486
2487    /// D2D i8 twin of `dtod_copy_view` (q8_1 activation rows).
2488    pub fn dtod_copy_view_i8(&self, src: &cudarc::driver::CudaView<i8>, dst: &mut CudaSlice<i8>)
2489                             -> Result<(), Box<dyn std::error::Error>> {
2490        self.gpu.stream().memcpy_dtod(src, dst)?;
2491        Ok(())
2492    }
2493
2494    /// D2D row placement: copy `src` into `dst[offset .. offset+src.len()]`.
2495    pub fn dtod_copy_into(&self, src: &CudaSlice<f32>, dst: &mut CudaSlice<f32>, offset: usize)
2496                          -> Result<(), Box<dyn std::error::Error>> {
2497        let n = src.len();
2498        let mut dv = dst.slice_mut(offset..offset + n);
2499        self.gpu.stream().memcpy_dtod(src, &mut dv)?;
2500        Ok(())
2501    }
2502
2503    /// Uninitialized i8 device buffer (decode_batch q8_1 row scratch).
2504    pub fn uninit_i8(&self, n: usize) -> Result<CudaSlice<i8>, Box<dyn std::error::Error>> {
2505        self.alloc_uninit::<i8>(n)
2506    }
2507
2508    /// Resident-quantized linear (Stage-A: f32 dequant-in-kernel). y[m,out]=x[m,in]@W[out,in]^T.
2509    pub fn qmatvec(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize, out_f: usize,
2510                   qtype: i32, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2511        let f = self.func("qmatvec_f32");
2512        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite output: skip memset
2513        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2514        let (inf, outf, mi, qt, rb) = (in_f as i32, out_f as i32, m as i32, qtype, row_bytes as i64);
2515        let __s_b = self.gpu.stream();
2516        let mut b = __s_b.launch_builder(&f);
2517        b.arg(w).arg(x).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&qt).arg(&rb);
2518        unsafe { b.launch(cfg)?; }
2519        Ok(y)
2520    }
2521
2522    /// Allocate a reusable u8 GPU scratch buffer (for staged expert weights).
2523    pub fn alloc_u8(&self, n: usize) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
2524        let s = self.gpu.stream().alloc_zeros::<u8>(n)?;
2525        self.keep_if_capturing(&s);
2526        Ok(s)
2527    }
2528
2529    /// Uninitialized u8 scratch — skips alloc_zeros' memset. ONLY for staging buffers whose read
2530    /// range is fully overwritten by a stage_expert H2D before any kernel reads it (LAUNCH-STRUCTURE
2531    /// STAGE 2: the per-layer MoE scratch trio was 3 dead ~1MB memsets per layer per decode token).
2532    pub fn alloc_u8_uninit(&self, n: usize) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
2533        let s = unsafe { self.gpu.stream().alloc::<u8>(n)? };
2534        self.keep_if_capturing(&s);
2535        Ok(s)
2536    }
2537
2538    /// Zero a SUB-RANGE of an f32 buffer (CudaViewMut) — the row-sized memset the moe_out
2539    /// memset-elision uses for tokens that fall off the gdec fast path (LAUNCH-STRUCTURE STAGE 2).
2540    pub fn memset_zeros_view(&self, dst: &mut cudarc::driver::CudaViewMut<f32>)
2541                             -> Result<(), Box<dyn std::error::Error>> {
2542        self.gpu.stream().memset_zeros(dst)?;
2543        Ok(())
2544    }
2545
2546    /// EDGE-1 staging: copy `host_bytes` (a sub-slice of a HostExps buffer) into `scratch`
2547    /// at byte offset `off` (async H2D on the default stream). Length is host_bytes.len().
2548    /// The qmatvec_view that reads `scratch[off..]` is enqueued on the SAME stream after this,
2549    /// so ordering is guaranteed without an explicit sync (Stage-1; Stage-2 prefetch on a 2nd
2550    /// stream would require an event).
2551    pub fn stage_expert(&self, host_bytes: &[u8], scratch: &mut CudaSlice<u8>, off: usize)
2552                        -> Result<(), Box<dyn std::error::Error>> {
2553        let mut dst = scratch.slice_mut(off..off + host_bytes.len());  // CudaViewMut<u8>
2554        self.gpu.stream().memcpy_htod(host_bytes, &mut dst)?;            // accepts &[u8] HostSlice src
2555        Ok(())
2556    }
2557
2558    /// EDGE-1 §A: fused MoE router. `logits` is the router output [t, n_expert] (device, f32, the
2559    /// `gate_inp @ z` result). Returns (sel_idx [t, n_used] i32, sel_w [t, n_used] f32): the top-k
2560    /// expert ids (DESC by prob, ascending-index tiebreak) and renormalized weights. Replaces the
2561    /// host dtoh + softmax-256 + stable DESC top-8 sort + renorm (hybrid_forward.rs ~281-298).
2562    /// One CTA per token row, 256 threads (one per expert).
2563    pub fn moe_router_topk(&self, logits: &CudaSlice<f32>, t: usize, n_expert: usize, n_used: usize)
2564                           -> Result<(CudaSlice<i32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2565        let f = self.func("moe_router_topk_f32");
2566        let mut sel_idx = self.alloc_uninit::<i32>(t * n_used)?;  // kernel fully overwrites
2567        let mut sel_w = self.alloc_uninit::<f32>(t * n_used)?;    // kernel fully overwrites
2568        let cfg = LaunchConfig { grid_dim: (t as u32, 1, 1), block_dim: (n_expert as u32, 1, 1),
2569                                 shared_mem_bytes: 0 };
2570        let (ne, nu) = (n_expert as i32, n_used as i32);
2571        let __s_b = self.gpu.stream();
2572        let mut b = __s_b.launch_builder(&f);
2573        b.arg(logits).arg(&mut sel_idx).arg(&mut sel_w).arg(&ne).arg(&nu);
2574        unsafe { b.launch(cfg)?; }
2575        Ok((sel_idx, sel_w))
2576    }
2577
2578    /// gemma4 twin: per-expert output scale folded into the topk renorm write (replaces the
2579    /// separate moe_w_exscale launch; value chain identical: (w/ws) * s[sel]).
2580    pub fn moe_router_topk_scaled(&self, logits: &CudaSlice<f32>, t: usize, n_expert: usize,
2581                                  n_used: usize, ex_scale: &CudaSlice<f32>)
2582                                  -> Result<(CudaSlice<i32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2583        // barrier-lean v2 twin (per-warp top-k + one-warp merge) FALSIFIED 2026-07-14:
2584        // bit-identical streams but −1.4% (26B plain N=3 interleaved) — at t=1 the grid is
2585        // ONE block, so the 6.6us is launch/dependency overhead, not the barrier chain;
2586        // fewer barriers bought nothing and the merge structure cost. jsonl is the record.
2587        let f = self.func("moe_router_topk_scaled_f32");
2588        let mut sel_idx = self.alloc_uninit::<i32>(t * n_used)?;
2589        let mut sel_w = self.alloc_uninit::<f32>(t * n_used)?;
2590        let cfg = LaunchConfig { grid_dim: (t as u32, 1, 1), block_dim: (n_expert as u32, 1, 1),
2591                                 shared_mem_bytes: 0 };
2592        let (ne, nu) = (n_expert as i32, n_used as i32);
2593        let __s_b = self.gpu.stream();
2594        let mut b = __s_b.launch_builder(&f);
2595        b.arg(logits).arg(&mut sel_idx).arg(&mut sel_w).arg(&ne).arg(&nu).arg(ex_scale);
2596        unsafe { b.launch(cfg)?; }
2597        Ok((sel_idx, sel_w))
2598    }
2599
2600    /// LAUNCH-STRUCTURE STAGE 1 (2026-07-05): fused router + SINGLE-SYNC host readback. The old
2601    /// MEMRA_FUSED_ROUTER path lost 2% at t=1 because it paid TWO full stream syncs (dtoh_i32 then
2602    /// dtoh, each = clone_dtoh + synchronize) + two alloc_zeros memsets per MoE layer, where the
2603    /// host route pays ONE sync on the 1KB logits dtoh. This variant: uninit outputs (kernel fully
2604    /// overwrites), both DtoH copies issued ASYNC into a persistent PINNED host staging buffer
2605    /// (flags=0 — cacheable, NOT cudarc's WRITECOMBINED default, so the host-side reads of sel/w
2606    /// stay cached), then ONE synchronize. Numerics identical to `moe_router_topk` (same kernel).
2607    pub fn moe_router_topk_host(&self, logits: &CudaSlice<f32>, t: usize, n_expert: usize, n_used: usize)
2608                                -> Result<(Vec<u32>, Vec<f32>), Box<dyn std::error::Error>> {
2609        let f = self.func("moe_router_topk_f32");
2610        let n = t * n_used;
2611        let mut sel_idx = self.alloc_uninit::<i32>(n)?;
2612        let mut sel_w = self.alloc_uninit::<f32>(n)?;
2613        let cfg = LaunchConfig { grid_dim: (t as u32, 1, 1), block_dim: (n_expert as u32, 1, 1),
2614                                 shared_mem_bytes: 0 };
2615        let (ne, nu) = (n_expert as i32, n_used as i32);
2616        let __s_b = self.gpu.stream();
2617        let mut b = __s_b.launch_builder(&f);
2618        b.arg(logits).arg(&mut sel_idx).arg(&mut sel_w).arg(&ne).arg(&nu);
2619        unsafe { b.launch(cfg)?; }
2620        // single-sync readback: sel (i32) at offset 0, w (f32) at offset n*4 of the pinned stage.
2621        let bytes = n * 8;
2622        let mut guard = self.router_stage.lock().unwrap();
2623        if guard.as_ref().map(|p| p.cap < bytes).unwrap_or(true) {
2624            *guard = Some(PinnedStage::new(bytes.max(4096))?);
2625        }
2626        let stage = guard.as_mut().unwrap();
2627        let (si, sw) = unsafe {
2628            (std::slice::from_raw_parts_mut(stage.ptr as *mut i32, n),
2629             std::slice::from_raw_parts_mut(stage.ptr.add(n * 4) as *mut f32, n))
2630        };
2631        self.gpu.stream().memcpy_dtoh(&sel_idx, si)?;   // async (pinned dst)
2632        self.gpu.stream().memcpy_dtoh(&sel_w, sw)?;     // async (pinned dst)
2633        self.gpu.stream().synchronize()?;               // ONE sync for both
2634        Ok((si.iter().map(|&i| i as u32).collect(), sw.to_vec()))
2635    }
2636
2637    /// EDGE-1 §C.2: async H2D of `host_bytes` into `scratch[off..]` on the COPY stream, returning a
2638    /// recorded event the compute stream can `wait` on before the dependent GEMM. Used for in-token
2639    /// expert prefetch (pipeline by one). `host_bytes` should be pinned for a true DMA (§C.1).
2640    pub fn stage_expert_async(&self, host_bytes: &[u8], scratch: &mut CudaSlice<u8>, off: usize)
2641                              -> Result<cudarc::driver::CudaEvent, Box<dyn std::error::Error>> {
2642        let mut dst = scratch.slice_mut(off..off + host_bytes.len());
2643        self.copy_stream.memcpy_htod(host_bytes, &mut dst)?;
2644        Ok(self.copy_stream.record_event(None)?)
2645    }
2646
2647    /// Make the compute stream wait for an async copy event (the consumer side of `stage_expert_async`).
2648    pub fn compute_wait(&self, ev: &cudarc::driver::CudaEvent) -> Result<(), Box<dyn std::error::Error>> {
2649        self.gpu.stream().wait(ev)?;
2650        Ok(())
2651    }
2652
2653    /// qmatvec over a byte sub-range of a (resident/scratch) CudaSlice<u8> holding ONE expert
2654    /// matrix. x is a CudaView<f32> (a sliced row of z, or a sliced activation). Reuses the
2655    /// validated qmatvec_f32 dequant path (NOT a fast path — the correctness gate). The
2656    /// CudaView base+offset pointer is honored by the launch arg.
2657    pub fn qmatvec_view(&self, w: &CudaSlice<u8>, range: std::ops::Range<usize>,
2658                        x: &cudarc::driver::CudaView<f32>, m: usize, in_f: usize, out_f: usize,
2659                        qtype: i32, row_bytes: usize)
2660                        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2661        let f = self.func("qmatvec_f32");
2662        let wv = w.slice(range);  // CudaView<u8>, offset honored
2663        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite output: skip memset
2664        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2665        let (inf, outf, mi, qt, rb) = (in_f as i32, out_f as i32, m as i32, qtype, row_bytes as i64);
2666        let __s_b = self.gpu.stream();
2667        let mut b = __s_b.launch_builder(&f);
2668        b.arg(&wv).arg(x).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&qt).arg(&rb);
2669        unsafe { b.launch(cfg)?; }
2670        Ok(y)
2671    }
2672
2673    /// STAGE-2 GROUPED DECODE (2026-07-04): one MoE layer's gate+up+SiLU for all `n_used` routed
2674    /// experts of ONE token in ONE launch (replaces 8x qmatvec(gate) + 8x qmatvec(up) + 8x
2675    /// silu_mul = 24 launches). `gp`/`up` are the 8 expert weight-block device pointers (SLRU
2676    /// cache slots — fixed-address, stable for the launch). Returns act [n_used, n_ff].
2677    /// BIT-IDENTICAL to the sequential chain: each dot reproduces qmatvec_f32's exact 256-thread
2678    /// reduction; the SiLU epilogue is silu_mul_f32's exact expression (see kernel header).
2679    #[allow(clippy::too_many_arguments)]
2680    /// dp4a q8 twins (MoE expert dp4a arc, 2026-07-06): same contract as the _f32 versions but
2681    /// consume a PRE-QUANTIZED q8_1 activation. FP-order differs from _f32 (int dot + warp tree)
2682    /// — the argmax/stream-identity battery arbitrates; MEMRA_MOE_Q8=0 restores f32.
2683    pub fn moe_gate_up_silu8_q8(&self, gp: WPtr8, up: WPtr8,
2684                                aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
2685                                in_f: usize, n_ff: usize, n_used: usize, qt_g: i32, qt_u: i32,
2686                                rb_g: usize, rb_u: usize)
2687                                -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2688        let f = self.func("moe_gate_up_silu8_q8");
2689        let mut act = self.alloc_uninit::<f32>(n_used * n_ff)?;
2690        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
2691                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2692        let (inf, nff, rbg, rbu) = (in_f as i32, n_ff as i32, rb_g as i64, rb_u as i64);
2693        let __s_b = self.gpu.stream();
2694        let mut b = __s_b.launch_builder(&f);
2695        b.arg(&gp).arg(&up).arg(aq).arg(ad).arg(&mut act)
2696         .arg(&inf).arg(&nff).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu);
2697        unsafe { b.launch(cfg)?; }
2698        Ok(act)
2699    }
2700
2701    #[allow(clippy::too_many_arguments)]
2702    pub fn moe_down8_fma_q8(&self, dp: WPtr8, w: F32x8,
2703                            aq2: &CudaSlice<i8>, ad2: &CudaSlice<f32>,
2704                            dst: &mut cudarc::driver::CudaViewMut<f32>,
2705                            in_f: usize, out_f: usize, n_used: usize, qt: i32, rb: usize)
2706                            -> Result<(), Box<dyn std::error::Error>> {
2707        let f = self.func("moe_down8_fma_q8");
2708        let cfg = LaunchConfig { grid_dim: (out_f as u32, 1, 1),
2709                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2710        let (inf, outf, nu, rbi) = (in_f as i32, out_f as i32, n_used as i32, rb as i64);
2711        let __s_b = self.gpu.stream();
2712        let mut b = __s_b.launch_builder(&f);
2713        b.arg(&dp).arg(&w).arg(aq2).arg(ad2).arg(dst)
2714         .arg(&inf).arg(&outf).arg(&nu).arg(&qt).arg(&rbi);
2715        unsafe { b.launch(cfg)?; }
2716        Ok(())
2717    }
2718
2719    /// q8 sequential expert matvec (staged path twin of qmatvec_view for IQ3_S/IQ4_XS).
2720    pub fn qmatvec_expert_q8(&self, w: &CudaSlice<u8>, range: std::ops::Range<usize>,
2721                             aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize,
2722                             in_f: usize, out_f: usize, qtype: i32, row_bytes: usize)
2723                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2724        let f = self.func("qmatvec_expert_q8");
2725        let wv = w.slice(range);
2726        let mut y = self.alloc_uninit::<f32>(m * out_f)?;
2727        const ROWS: u32 = 4;   // MEMRA_MMVQ_ROWS
2728        let cfg = LaunchConfig { grid_dim: ((out_f as u32 + ROWS - 1) / ROWS, m as u32, 1),
2729                                 block_dim: (32, ROWS, 1), shared_mem_bytes: 0 };
2730        let (inf, outf, mi, rbi) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
2731        let __s_b = self.gpu.stream();
2732        let mut b = __s_b.launch_builder(&f);
2733        b.arg(&wv).arg(aq).arg(ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&qtype).arg(&rbi);
2734        unsafe { b.launch(cfg)?; }
2735        Ok(y)
2736    }
2737
2738    pub fn moe_gate_up_silu8(&self, gp: WPtr8, up: WPtr8, x: &cudarc::driver::CudaView<f32>,
2739                             in_f: usize, n_ff: usize, n_used: usize, qt_g: i32, qt_u: i32,
2740                             rb_g: usize, rb_u: usize)
2741                             -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2742        let f = self.func("moe_gate_up_silu8_f32");
2743        let mut act = self.alloc_uninit::<f32>(n_used * n_ff)?;  // fully overwritten
2744        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
2745                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2746        let (inf, nff, rbg, rbu) = (in_f as i32, n_ff as i32, rb_g as i64, rb_u as i64);
2747        let __s_b = self.gpu.stream();
2748        let mut b = __s_b.launch_builder(&f);
2749        b.arg(&gp).arg(&up).arg(x).arg(&mut act)
2750         .arg(&inf).arg(&nff).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu);
2751        unsafe { b.launch(cfg)?; }
2752        Ok(act)
2753    }
2754
2755    /// STAGE-2 GROUPED DECODE: one MoE layer's down-proj + weighted accumulation for all `n_used`
2756    /// routed experts in ONE launch (replaces 8x qmatvec(down) + 8x axpy = 16 launches), writing
2757    /// the token's moe_out row DIRECTLY (`dst` is the zeroed row; the in-kernel slot-ordered
2758    /// __fmaf_rn chain starting at 0.0f reproduces the sequential axpy_f32 accumulation into the
2759    /// zeroed row bit-for-bit — the A2 byte-identity scheme at m=1).
2760    #[allow(clippy::too_many_arguments)]
2761    pub fn moe_down8_fma_into(&self, dp: WPtr8, w: F32x8, act: &CudaSlice<f32>,
2762                              dst: &mut cudarc::driver::CudaViewMut<f32>,
2763                              in_f: usize, out_f: usize, n_used: usize, qt: i32, rb: usize)
2764                              -> Result<(), Box<dyn std::error::Error>> {
2765        let f = self.func("moe_down8_fma_f32");
2766        let cfg = LaunchConfig { grid_dim: (out_f as u32, 1, 1),
2767                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2768        let (inf, outf, nu, rbv) = (in_f as i32, out_f as i32, n_used as i32, rb as i64);
2769        let __s_b = self.gpu.stream();
2770        let mut b = __s_b.launch_builder(&f);
2771        b.arg(&dp).arg(&w).arg(act).arg(dst).arg(&inf).arg(&outf).arg(&nu).arg(&qt).arg(&rbv);
2772        unsafe { b.launch(cfg)?; }
2773        Ok(())
2774    }
2775
2776    /// LAUNCH-STRUCTURE STAGE 3: device-dispatch twin of `moe_gate_up_silu8` for FULLY-RESIDENT
2777    /// layers. The expert ids come from the router kernel's DEVICE `sel` output (no DtoH) and the
2778    /// weight pointers from the per-layer device table `[3, n_expert]` of slot base addresses.
2779    /// BIT-IDENTICAL math (same grid/block/reduction; only the pointer/id source differs).
2780    #[allow(clippy::too_many_arguments)]
2781    /// dp4a q8 twin of the _dev pair (resident-experts arc).
2782    ///
2783    /// GEOMETRY VARIANTS (multirow/occupancy arc 2026-07-05): all outputs are BIT-IDENTICAL to
2784    /// the base one-warp-per-(row,slot) kernel (same expert_dot_g g-order + warp tree per row;
2785    /// down's FMA chain stays slot-ordered serial). Seams:
2786    ///   MEMRA_MOE_DEVQ8_GU   = 0(base) | 1 | 2 | 4 -> _r{1,2,4} multirow twin (RPW rows/warp)
2787    ///                       | s2 (gate/up warp split) | s2z (s2 + WPB rows packed per block)
2788    ///                       | gs4 (gate/up x low/high-group 4-warp split, nsb==64 only)
2789    ///                       | u64 (nsb==64 unrolled ILP twin, geometry unchanged)
2790    ///   MEMRA_MOE_DEVQ8_WPB  = warps per block for _r twins / z-rows for s2z (default 4)
2791    ///   MEMRA_MOE_DEVQ8_DOWN = auto(default: w8h2 when in_f==512 & n_used<=8 — measured +3.8%
2792    ///                       decode on 35B/G7e) | 0 (base one-warp serial-slot) | 1 | 2 | 4 ->
2793    ///                       _w8r{1,2,4} slot-parallel twin | h2 (half-warp dual-row, nsb==16
2794    ///                       only) | w8h2 (h2 x slot-parallel)
2795    #[allow(clippy::too_many_arguments)]
2796    /// MoE PREFILL pair-batch matvec: one launch covers all (token,expert) pairs for one proj.
2797    #[allow(clippy::too_many_arguments)]
2798    pub fn moe_pairs_matvec_q8(&self, table: &CudaSlice<u64>, proj: i32,
2799                               pair_tok: &CudaSlice<i32>, pair_ex: &CudaSlice<i32>,
2800                               aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
2801                               in_f: usize, out_f: usize, n_expert: usize, n_pairs: usize,
2802                               qtype: i32, row_bytes: usize)
2803                               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2804        let f = self.func("moe_pairs_matvec_q8");
2805        let mut y = self.alloc_uninit::<f32>(n_pairs * out_f)?;
2806        const ROWS: u32 = 4;
2807        let cfg = LaunchConfig { grid_dim: ((out_f as u32 + ROWS - 1) / ROWS, n_pairs as u32, 1),
2808                                 block_dim: (32, ROWS, 1), shared_mem_bytes: 0 };
2809        let (inf, outf, ne, np, rbi) = (in_f as i32, out_f as i32, n_expert as i32,
2810                                        n_pairs as i32, row_bytes as i64);
2811        let __s_b = self.gpu.stream();
2812        let mut b = __s_b.launch_builder(&f);
2813        b.arg(table).arg(&proj).arg(pair_tok).arg(pair_ex).arg(aq).arg(ad).arg(&mut y)
2814         .arg(&inf).arg(&outf).arg(&ne).arg(&np).arg(&qtype).arg(&rbi);
2815        unsafe { b.launch(cfg)?; }
2816        Ok(y)
2817    }
2818
2819    /// Expert-major pair matvec (weight-reuse across each expert's token group).
2820    #[allow(clippy::too_many_arguments)]
2821    pub fn moe_pairs_matvec_q8_em(&self, table: &CudaSlice<u64>, proj: i32,
2822                                  ex_ids: &CudaSlice<i32>, ex_off: &CudaSlice<i32>,
2823                                  ex_pairs: &CudaSlice<i32>, pair_tok: &CudaSlice<i32>,
2824                                  aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
2825                                  in_f: usize, out_f: usize, n_expert: usize, n_active: usize,
2826                                  n_pairs: usize, qtype: i32, row_bytes: usize)
2827                                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2828        let f = self.func("moe_pairs_matvec_q8_em");
2829        let mut y = self.alloc_uninit::<f32>(n_pairs * out_f)?;
2830        const ROWS: u32 = 4;
2831        let cfg = LaunchConfig { grid_dim: ((out_f as u32 + ROWS - 1) / ROWS, n_active as u32, 1),
2832                                 block_dim: (32, ROWS, 1), shared_mem_bytes: 0 };
2833        let (inf, outf, ne, na, rbi) = (in_f as i32, out_f as i32, n_expert as i32,
2834                                        n_active as i32, row_bytes as i64);
2835        let __s_b = self.gpu.stream();
2836        let mut b = __s_b.launch_builder(&f);
2837        b.arg(table).arg(&proj).arg(ex_ids).arg(ex_off).arg(ex_pairs).arg(pair_tok)
2838         .arg(aq).arg(ad).arg(&mut y)
2839         .arg(&inf).arg(&outf).arg(&ne).arg(&na).arg(&qtype).arg(&rbi);
2840        unsafe { b.launch(cfg)?; }
2841        Ok(y)
2842    }
2843
2844    // Decode-once expert-major MMQ (rung 3). Same CSR inputs/geometry as _em; kernel dequants each
2845    // weight group once per (row,group) then dp4a's across the expert's token group.
2846    #[allow(clippy::too_many_arguments)]
2847    pub fn moe_pairs_matvec_q8_dec(&self, table: &CudaSlice<u64>, proj: i32,
2848                                   ex_ids: &CudaSlice<i32>, ex_off: &CudaSlice<i32>,
2849                                   ex_pairs: &CudaSlice<i32>, pair_tok: &CudaSlice<i32>,
2850                                   aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
2851                                   in_f: usize, out_f: usize, n_expert: usize, n_active: usize,
2852                                   n_pairs: usize, qtype: i32, row_bytes: usize)
2853                                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2854        let f = self.func("moe_pairs_matvec_q8_dec");
2855        let mut y = self.alloc_uninit::<f32>(n_pairs * out_f)?;
2856        const ROWS: u32 = 4;
2857        let cfg = LaunchConfig { grid_dim: ((out_f as u32 + ROWS - 1) / ROWS, n_active as u32, 1),
2858                                 block_dim: (32, ROWS, 1), shared_mem_bytes: 0 };
2859        let (inf, outf, ne, na, rbi) = (in_f as i32, out_f as i32, n_expert as i32,
2860                                        n_active as i32, row_bytes as i64);
2861        let __s_b = self.gpu.stream();
2862        let mut b = __s_b.launch_builder(&f);
2863        b.arg(table).arg(&proj).arg(ex_ids).arg(ex_off).arg(ex_pairs).arg(pair_tok)
2864         .arg(aq).arg(ad).arg(&mut y)
2865         .arg(&inf).arg(&outf).arg(&ne).arg(&na).arg(&qtype).arg(&rbi);
2866        unsafe { b.launch(cfg)?; }
2867        Ok(y)
2868    }
2869
2870    pub fn moe_pairs_gelu_mul(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>, n: usize)
2871                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2872        let f = self.func("moe_pairs_gelu_mul");
2873        let mut act = self.alloc_uninit::<f32>(n)?;
2874        let cfg = LaunchConfig::for_num_elems(n as u32);
2875        let nl = n as i64;
2876        let __s_b = self.gpu.stream();
2877        let mut b = __s_b.launch_builder(&f);
2878        b.arg(gate).arg(up).arg(&mut act).arg(&nl);
2879        unsafe { b.launch(cfg)?; }
2880        Ok(act)
2881    }
2882
2883    pub fn moe_pairs_silu_mul(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>, n: usize)
2884                              -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2885        let f = self.func("moe_pairs_silu_mul");
2886        let mut act = self.alloc_uninit::<f32>(n)?;
2887        let cfg = LaunchConfig::for_num_elems(n as u32);
2888        let nl = n as i64;
2889        let __s_b = self.gpu.stream();
2890        let mut b = __s_b.launch_builder(&f);
2891        b.arg(gate).arg(up).arg(&mut act).arg(&nl);
2892        unsafe { b.launch(cfg)?; }
2893        Ok(act)
2894    }
2895
2896    #[allow(clippy::too_many_arguments)]
2897    pub fn moe_pairs_scatter(&self, y_down: &CudaSlice<f32>, pair_w: &CudaSlice<f32>,
2898                             tok_pair_off: &CudaSlice<i32>, tok_pair_ids: &CudaSlice<i32>,
2899                             moe_out: &mut CudaSlice<f32>, t: usize, n_embd: usize)
2900                             -> Result<(), Box<dyn std::error::Error>> {
2901        let f = self.func("moe_pairs_scatter");
2902        let cfg = LaunchConfig { grid_dim: (((n_embd + 255) / 256) as u32, t as u32, 1),
2903                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
2904        let ne = n_embd as i32;
2905        let __s_b = self.gpu.stream();
2906        let mut b = __s_b.launch_builder(&f);
2907        b.arg(y_down).arg(pair_w).arg(tok_pair_off).arg(tok_pair_ids).arg(moe_out).arg(&ne);
2908        unsafe { b.launch(cfg)?; }
2909        Ok(())
2910    }
2911
2912    /// gemma4 GELU twin of moe_gate_up_silu8_dev_q8 (base geometry — slot-packed j8/j8r2
2913    /// twins probed 2026-08-01 g26 decode dig: bit-identical rows, -2.5%/-2.9% whole-model
2914    /// decode x3 interleaved -> refuted and killed; research/g26-decode-20260801/receipts.md).
2915    #[allow(clippy::too_many_arguments)]
2916    pub fn moe_gate_up_gelu8_dev_q8(&self, table: &CudaSlice<u64>, sel: &cudarc::driver::CudaView<i32>,
2917                                    aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
2918                                    in_f: usize, n_ff: usize, n_used: usize, n_expert: usize,
2919                                    qt_g: i32, qt_u: i32, rb_g: usize, rb_u: usize)
2920                                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2921        let mut act = self.alloc_uninit::<f32>(n_used * n_ff)?;
2922        let (inf, nff, ne, rbg, rbu) = (in_f as i32, n_ff as i32, n_expert as i32,
2923                                        rb_g as i64, rb_u as i64);
2924        let f = self.func("moe_gate_up_gelu8_dev_q8");
2925        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
2926                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2927        let __s_b = self.gpu.stream();
2928        let mut b = __s_b.launch_builder(&f);
2929        b.arg(table).arg(sel).arg(aq).arg(ad).arg(&mut act)
2930         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu);
2931        unsafe { b.launch(cfg)?; }
2932        Ok(act)
2933    }
2934
2935    /// gemma4 GELU rows twin (verify): one launch over (n_ff, n_used, t).
2936    #[allow(clippy::too_many_arguments)]
2937    pub fn moe_gate_up_gelu8_dev_q8_rows(&self, table: &CudaSlice<u64>, sel: &CudaSlice<i32>,
2938                                         aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, t: usize,
2939                                         in_f: usize, n_ff: usize, n_used: usize, n_expert: usize,
2940                                         qt_g: i32, qt_u: i32, rb_g: usize, rb_u: usize)
2941                                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2942        let mut act = self.alloc_uninit::<f32>(t * n_used * n_ff)?;
2943        let (inf, nff, ne, rbg, rbu, nu) = (in_f as i32, n_ff as i32, n_expert as i32,
2944                                            rb_g as i64, rb_u as i64, n_used as i32);
2945        let f = self.func("moe_gate_up_gelu8_dev_q8_rows");
2946        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, t as u32),
2947                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2948        let __s_b = self.gpu.stream();
2949        let mut b = __s_b.launch_builder(&f);
2950        b.arg(table).arg(sel).arg(aq).arg(ad).arg(&mut act)
2951         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu).arg(&nu);
2952        unsafe { b.launch(cfg)?; }
2953        Ok(act)
2954    }
2955
2956    /// gemma4 GELU CSR twin (verify dedup: owner block serves every pair of its expert).
2957    #[allow(clippy::too_many_arguments)]
2958    pub fn moe_gate_up_gelu8_dev_q8_csr(&self, table: &CudaSlice<u64>, sel: &CudaSlice<i32>,
2959                                        aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, n_pairs: usize,
2960                                        in_f: usize, n_ff: usize, n_used: usize, n_expert: usize,
2961                                        qt_g: i32, qt_u: i32, rb_g: usize, rb_u: usize)
2962                                        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2963        let mut act = self.alloc_uninit::<f32>(n_pairs * n_ff)?;
2964        let (inf, nff, ne, rbg, rbu, nu, npi) = (in_f as i32, n_ff as i32, n_expert as i32,
2965                                                 rb_g as i64, rb_u as i64, n_used as i32,
2966                                                 n_pairs as i32);
2967        let f = self.func("moe_gate_up_gelu8_dev_q8_csr");
2968        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_pairs as u32, 1),
2969                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2970        let __s_b = self.gpu.stream();
2971        let mut b = __s_b.launch_builder(&f);
2972        b.arg(table).arg(sel).arg(aq).arg(ad).arg(&mut act)
2973         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu).arg(&nu).arg(&npi);
2974        unsafe { b.launch(cfg)?; }
2975        Ok(act)
2976    }
2977
2978    /// gemma4 generic down rows twin (verify): one launch over (out_f, 1, t).
2979    #[allow(clippy::too_many_arguments)]
2980    pub fn moe_down8_fma_dev_q8_rows_g(&self, table: &CudaSlice<u64>, sel: &CudaSlice<i32>,
2981                                       w: &CudaSlice<f32>, aq2: &CudaSlice<i8>, ad2: &CudaSlice<f32>,
2982                                       dst: &mut CudaSlice<f32>, t: usize,
2983                                       in_f: usize, out_f: usize, n_used: usize, n_expert: usize,
2984                                       qt: i32, rb: usize)
2985                                       -> Result<(), Box<dyn std::error::Error>> {
2986        let (inf, outf, nu, ne, rbi) = (in_f as i32, out_f as i32, n_used as i32,
2987                                        n_expert as i32, rb as i64);
2988        let f = self.func("moe_down8_fma_dev_q8_rows_g");
2989        let cfg = LaunchConfig { grid_dim: (out_f as u32, 1, t as u32),
2990                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
2991        let __s_b = self.gpu.stream();
2992        let mut b = __s_b.launch_builder(&f);
2993        b.arg(table).arg(sel).arg(w).arg(aq2).arg(ad2).arg(dst)
2994         .arg(&inf).arg(&outf).arg(&nu).arg(&ne).arg(&qt).arg(&rbi);
2995        unsafe { b.launch(cfg)?; }
2996        Ok(())
2997    }
2998
2999    /// rp_q4 microprobe (2026-07-10 verify-trunk lever): b4 GGUF-block layout vs the Q4_0
3000    /// split-plane twin on the wq-class shape. Returns (blk_us, rp_us) after asserting bitwise
3001    /// identity. Bench-only surface (rp_q4_probe bin); no production dispatch reads this.
3002    pub fn rp_probe_q4(&self, m: usize) -> Result<(f64, f64), Box<dyn std::error::Error>> {
3003        let (out_f, in_f) = (2048usize, 2816usize);
3004        let nblk = in_f / 32;
3005        let mut seed = 0x9E3779B97F4A7C15u64;
3006        let mut rng = move || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) as u8 };
3007        let mut w = vec![0u8; out_f * nblk * 18];
3008        for b in w.iter_mut() { *b = rng(); }
3009        for r in 0..out_f {
3010            for g in 0..nblk {
3011                let off = (r * nblk + g) * 18;
3012                w[off] = 0x00; w[off + 1] = 0x2C;   // sane half d
3013            }
3014        }
3015        let qplane = out_f * nblk * 16;
3016        let mut wrp = vec![0u8; w.len()];
3017        for r in 0..out_f {
3018            for g in 0..nblk {
3019                let src = &w[(r * nblk + g) * 18..(r * nblk + g) * 18 + 18];
3020                wrp[qplane + (r * nblk + g) * 2..qplane + (r * nblk + g) * 2 + 2]
3021                    .copy_from_slice(&src[0..2]);
3022                wrp[(r * nblk + g) * 16..(r * nblk + g) * 16 + 16].copy_from_slice(&src[2..18]);
3023            }
3024        }
3025        let w_d = self.htod_bytes(&w)?;
3026        let wrp_d = self.htod_bytes(&wrp)?;
3027        let mut aq = vec![0i8; m * in_f];
3028        for v in aq.iter_mut() { *v = rng() as i8; }
3029        let aq_d = self.htod_i8(&aq)?;
3030        let ad_d = self.htod(&vec![0.03125f32; m * nblk])?;
3031        let mut y0 = self.alloc_uninit::<f32>(m * out_f)?;
3032        let mut y1 = self.alloc_uninit::<f32>(m * out_f)?;
3033        const RPB: u32 = 4;
3034        let cfg = LaunchConfig { grid_dim: ((out_f as u32).div_ceil(RPB), 1, 1),
3035                                 block_dim: (32, RPB, 1), shared_mem_bytes: 0 };
3036        let (inf, outf, mi) = (in_f as i32, out_f as i32, m as i32);
3037        let (rb, qp) = ((nblk * 18) as i64, qplane as i64);
3038        let fb = self.func("qmatvec_q4_0_mmvq_b4");
3039        let fr = self.func("qmatvec_q4_0_mmvq_b4_rp");
3040        {
3041            let __s_b = self.gpu.stream();
3042            let mut b = __s_b.launch_builder(&fb);
3043            b.arg(&w_d).arg(&aq_d).arg(&ad_d).arg(&mut y0).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
3044            unsafe { b.launch(cfg)?; }
3045            let __s_b = self.gpu.stream();
3046            let mut b = __s_b.launch_builder(&fr);
3047            b.arg(&wrp_d).arg(&aq_d).arg(&ad_d).arg(&mut y1).arg(&inf).arg(&outf).arg(&mi).arg(&qp);
3048            unsafe { b.launch(cfg)?; }
3049        }
3050        self.gpu.stream().synchronize()?;
3051        let (h0, h1) = (self.dtoh(&y0)?, self.dtoh(&y1)?);
3052        let nd = h0.iter().zip(&h1).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
3053        if nd != 0 { return Err(format!("rp twin not bitwise: {nd}/{} diffs", h0.len()).into()); }
3054        let mut time = |rp: bool| -> Result<f64, Box<dyn std::error::Error>> {
3055            self.gpu.stream().synchronize()?;
3056            let t0 = std::time::Instant::now();
3057            for _ in 0..500 {
3058                if rp {
3059                    let __s_b = self.gpu.stream();
3060                    let mut b = __s_b.launch_builder(&fr);
3061                    b.arg(&wrp_d).arg(&aq_d).arg(&ad_d).arg(&mut y1)
3062                     .arg(&inf).arg(&outf).arg(&mi).arg(&qp);
3063                    unsafe { b.launch(cfg)?; }
3064                } else {
3065                    let __s_b = self.gpu.stream();
3066                    let mut b = __s_b.launch_builder(&fb);
3067                    b.arg(&w_d).arg(&aq_d).arg(&ad_d).arg(&mut y0)
3068                     .arg(&inf).arg(&outf).arg(&mi).arg(&rb);
3069                    unsafe { b.launch(cfg)?; }
3070                }
3071            }
3072            self.gpu.stream().synchronize()?;
3073            Ok(t0.elapsed().as_secs_f64() * 1e6 / 500.0)
3074        };
3075        let _ = time(false)?; let _ = time(true)?;   // warm
3076        Ok((time(false)?, time(true)?))
3077    }
3078
3079    /// Build the Q4_0 split-plane decode mirror for a 2D Quant tensor (device-side permutation,
3080    /// q4_0_split_rp_build). Raw bytes stay resident (prefill/gemm/Stage-A); the m<=8 decode
3081    /// dispatch prefers the mirror (_rp twins). No-op unless (Q4_0, 2D, mirror absent).
3082    /// VRAM cost == the tensor's weight size. MEMRA_Q4RP=0 disables at the call sites.
3083    pub fn build_q4_rp4(&self, t: &mut crate::model::GpuTensor)
3084                        -> Result<(), Box<dyn std::error::Error>> {
3085        use crate::model::GpuTensor;
3086        let GpuTensor::Quant { bytes, qtype, row_bytes, ne, rp4, .. } = t else { return Ok(()) };
3087        if *qtype != QT_Q4_0 || rp4.is_some() || ne.len() != 2 { return Ok(()); }
3088        let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
3089        if in_f % 32 != 0 || *row_bytes != (in_f / 32) * 18 { return Ok(()); }
3090        let nblk = in_f / 32;
3091        let mut dst = self.alloc_uninit::<u8>(out_f * nblk * 18)?;
3092        let f = self.func("q4_0_split_rp_build");
3093        let n = (out_f * nblk) as i32;
3094        let cfg = LaunchConfig { grid_dim: (((out_f * nblk) as u32).div_ceil(256), 1, 1),
3095                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
3096        let (of, nb) = (out_f as i32, nblk as i32);
3097        let _ = n;
3098        let __s_b = self.gpu.stream();
3099        let mut b = __s_b.launch_builder(&f);
3100        b.arg(&*bytes).arg(&mut dst).arg(&of).arg(&nb);
3101        unsafe { b.launch(cfg)?; }
3102        *rp4 = Some(dst);
3103        Ok(())
3104    }
3105
3106    /// Q8_0 twin of `build_q4_rp4` (H100 coalescing fix, 2026-07-26 ncu: GGUF 34B-stride
3107    /// weight loads hold Max Bandwidth at 41-46%; the split mirror makes them aligned 16B
3108    /// ldcs). Raw bytes stay resident (prefill GEMM/MMQ/fused m=1 launches read GGUF layout);
3109    /// the mmvq/batched decode arms prefer the mirror via `rp4`. Bit-identical outputs.
3110    pub fn build_q8_rp4(&self, t: &mut crate::model::GpuTensor)
3111                        -> Result<(), Box<dyn std::error::Error>> {
3112        use crate::model::GpuTensor;
3113        let GpuTensor::Quant { bytes, qtype, row_bytes, ne, rp4, .. } = t else { return Ok(()) };
3114        if *qtype != QT_Q8_0 || rp4.is_some() || ne.len() != 2 { return Ok(()); }
3115        let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
3116        if in_f % 32 != 0 || *row_bytes != (in_f / 32) * 34 { return Ok(()); }
3117        *rp4 = Some(self.build_q8_rp4_raw(bytes, in_f, out_f)?);
3118        Ok(())
3119    }
3120
3121    /// Raw rp-mirror build for gates/benches: split GGUF Q8_0 bytes into the qplane+dplane
3122    /// mirror without a GpuTensor (same kernel the loader path above uses).
3123    pub fn build_q8_rp4_raw(&self, bytes: &CudaSlice<u8>, in_f: usize, out_f: usize)
3124                            -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
3125        assert!(in_f % 32 == 0);
3126        let nblk = in_f / 32;
3127        let mut dst = self.alloc_uninit::<u8>(out_f * nblk * 34)?;
3128        let f = self.func("q8_0_split_rp_build");
3129        let cfg = LaunchConfig { grid_dim: (((out_f * nblk) as u32).div_ceil(256), 1, 1),
3130                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
3131        let (of, nb) = (out_f as i32, nblk as i32);
3132        let __s_b = self.gpu.stream();
3133        let mut b = __s_b.launch_builder(&f);
3134        b.arg(&*bytes).arg(&mut dst).arg(&of).arg(&nb);
3135        unsafe { b.launch(cfg)?; }
3136        Ok(dst)
3137    }
3138
3139    /// K-quant twins of `build_q8_rp4` (H100 K-quant coalescing fix, 2026-08-01 ncu on the
3140    /// q27 Q4_K_M decode: q4_K mmvq DRAM 41-54% with 65% excessive sectors, q6_K 40% with
3141    /// 78% — the 144B/210B superblock strides land every 4B weight load off-sector). The
3142    /// mirror re-packs each tensor into planes (q4_K: qs ++ 16B meta; q6_K: ql ++ qh ++
3143    /// scales ++ d — same total bytes) so every quant fetch is an aligned 16B ldcs. Raw
3144    /// bytes stay resident (prefill GEMM/dequant/Stage-A read GGUF layout); the mmvq/batched
3145    /// decode arms prefer the mirror via `rp4`. Bit-identical outputs.
3146    pub fn build_q4k_rp4(&self, t: &mut crate::model::GpuTensor)
3147                         -> Result<(), Box<dyn std::error::Error>> {
3148        use crate::model::GpuTensor;
3149        let GpuTensor::Quant { bytes, qtype, row_bytes, ne, rp4, .. } = t else { return Ok(()) };
3150        if *qtype != QT_Q4_K || rp4.is_some() || ne.len() != 2 { return Ok(()); }
3151        let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
3152        if in_f % 256 != 0 || *row_bytes != (in_f / 256) * 144 { return Ok(()); }
3153        *rp4 = Some(self.build_kq_rp4_raw(bytes, in_f, out_f, QT_Q4_K)?);
3154        Ok(())
3155    }
3156
3157    pub fn build_q6k_rp4(&self, t: &mut crate::model::GpuTensor)
3158                         -> Result<(), Box<dyn std::error::Error>> {
3159        use crate::model::GpuTensor;
3160        let GpuTensor::Quant { bytes, qtype, row_bytes, ne, rp4, .. } = t else { return Ok(()) };
3161        if *qtype != QT_Q6_K || rp4.is_some() || ne.len() != 2 { return Ok(()); }
3162        let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
3163        if in_f % 256 != 0 || *row_bytes != (in_f / 256) * 210 { return Ok(()); }
3164        *rp4 = Some(self.build_kq_rp4_raw(bytes, in_f, out_f, QT_Q6_K)?);
3165        Ok(())
3166    }
3167
3168    /// Raw K-quant rp-mirror build for gates/benches (same kernels the loader path uses).
3169    pub fn build_kq_rp4_raw(&self, bytes: &CudaSlice<u8>, in_f: usize, out_f: usize, qtype: i32)
3170                            -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
3171        assert!(in_f % 256 == 0);
3172        let nsbk = in_f / 256;
3173        let (sb_bytes, kname) = match qtype {
3174            QT_Q4_K => (144usize, "q4_K_split_rp_build"),
3175            QT_Q6_K => (210usize, "q6_K_split_rp_build"),
3176            _ => return Err(format!("build_kq_rp4_raw: qtype {qtype} has no rp mirror").into()),
3177        };
3178        let mut dst = self.alloc_uninit::<u8>(out_f * nsbk * sb_bytes)?;
3179        let f = self.func(kname);
3180        let cfg = LaunchConfig { grid_dim: (((out_f * nsbk) as u32).div_ceil(256), 1, 1),
3181                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
3182        let (of, nb) = (out_f as i32, nsbk as i32);
3183        let __s_b = self.gpu.stream();
3184        let mut b = __s_b.launch_builder(&f);
3185        b.arg(&*bytes).arg(&mut dst).arg(&of).arg(&nb);
3186        unsafe { b.launch(cfg)?; }
3187        Ok(dst)
3188    }
3189
3190    /// MEMRA_KQRP seam: the K-quant (q4_K/q6_K) split-plane decode mirrors at model load.
3191    /// Default follows the Q8RP convention — ON on the Hopper lane (80GB pays the mirror
3192    /// VRAM), OFF elsewhere (a 24GB card cannot hold model + mirror + KV for the big trunks).
3193    pub fn kqrp_enabled() -> bool {
3194        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3195        *ON.get_or_init(|| match std::env::var("MEMRA_KQRP").as_deref() {
3196            Ok("0") => false,
3197            Ok(_) => true,
3198            Err(_) => cfg!(memra_hopper_mma),
3199        })
3200    }
3201
3202    /// IN-PLACE split-plane swap (the 31B dense arc): build the split layout and REPLACE the
3203    /// GGUF bytes (zero extra steady-state VRAM — the transient peak is one tensor's size).
3204    /// The tensor's `rp` flag then routes every consumer (mmvq/batched `_rp` twins, the
3205    /// `qmatvec_gemm_q4_0_rp` prefill kernel). Callers gate on the fast path being active —
3206    /// the Stage-A f32 oracle (`MEMRA_FAST=0`) reads GGUF layout and must never see a swap.
3207    pub fn build_q4_rp_swap(&self, t: &mut crate::model::GpuTensor)
3208                            -> Result<bool, Box<dyn std::error::Error>> {
3209        self.build_q4_rp4(t)?;
3210        self.gpu.stream().synchronize()?;   // build kernel reads the GGUF bytes — drain BEFORE dropping them
3211        use crate::model::GpuTensor;
3212        let GpuTensor::Quant { bytes, rp4, rp, .. } = t else { return Ok(false) };
3213        match rp4.take() {
3214            Some(split) => {
3215                *bytes = split;   // the GGUF-layout buffer drops here
3216                *rp = true;
3217                Ok(true)
3218            }
3219            None => Ok(false),
3220        }
3221    }
3222
3223    /// MEMRA_Q4RP seam (default ON): the Q4_0 split-plane decode mirror at model load.
3224    pub fn q4rp_enabled() -> bool {
3225        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3226        *ON.get_or_init(|| std::env::var("MEMRA_Q4RP").map(|v| v != "0").unwrap_or(true))
3227    }
3228
3229    /// gemma4-E4B: dense [t][row_elems] gather of layer il's rows from the strided prologue
3230    /// buffer ([t][n_layer][n_epl]; off = il*n_epl, stride = n_layer*n_epl).
3231    pub fn copy_rows_strided(&self, src: &CudaSlice<f32>, dst: &mut CudaSlice<f32>,
3232                             row_elems: usize, n_rows: usize, src_stride: usize, src_off: usize)
3233                             -> Result<(), Box<dyn std::error::Error>> {
3234        let f = self.func("copy_rows_strided_f32");
3235        let cfg = LaunchConfig { grid_dim: (((row_elems as u32 + 255) / 256).max(1), n_rows as u32, 1),
3236                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
3237        let (re, nr) = (row_elems as i32, n_rows as i32);
3238        let (st, off) = (src_stride as i64, src_off as i64);
3239        let __s_b = self.gpu.stream();
3240        let mut b = __s_b.launch_builder(&f);
3241        b.arg(src).arg(&mut *dst).arg(&re).arg(&nr).arg(&st).arg(&off);
3242        unsafe { b.launch(cfg)?; }
3243        Ok(())
3244    }
3245
3246    /// Async device u32 store (value rides the kernel ARG — no host-memory transfer/sync).
3247    pub fn u32_set_k(&self, dst: &mut CudaSlice<u32>, v: u32, idx: usize)
3248                     -> Result<(), Box<dyn std::error::Error>> {
3249        let f = self.func("u32_set_k");
3250        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (1, 1, 1), shared_mem_bytes: 0 };
3251        let ii = idx as i32;
3252        let __s_b = self.gpu.stream();
3253        let mut b = __s_b.launch_builder(&f);
3254        b.arg(dst).arg(&v).arg(&ii);
3255        unsafe { b.launch(cfg)?; }
3256        Ok(())
3257    }
3258
3259    /// counter += v (device-slot append advance; the +1 twin is `inc_seqlen`).
3260    pub fn i32_add_k(&self, d: &mut CudaSlice<i32>, v: i32) -> Result<(), Box<dyn std::error::Error>> {
3261        let f = self.func("i32_add_k");
3262        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
3263        let __s_b = self.gpu.stream();
3264        let mut b = __s_b.launch_builder(&f);
3265        b.arg(d).arg(&v);
3266        unsafe { b.launch(cfg)?; }
3267        Ok(())
3268    }
3269
3270    /// pos rows from a device counter: dst[i] = ctr[0] + i (verify-stream rope positions).
3271    pub fn i32_iota_from(&self, ctr: &CudaSlice<i32>, dst: &mut CudaSlice<i32>, n: usize)
3272                         -> Result<(), Box<dyn std::error::Error>> {
3273        let f = self.func("i32_iota_from");
3274        let cfg = LaunchConfig::for_num_elems(n as u32);
3275        let ni = n as i32;
3276        let __s_b = self.gpu.stream();
3277        let mut b = __s_b.launch_builder(&f);
3278        b.arg(ctr).arg(dst).arg(&ni);
3279        unsafe { b.launch(cfg)?; }
3280        Ok(())
3281    }
3282
3283    /// In-place trim-id translate: buf[idx] = map[buf[idx]] (FR-Spec d2t, async single-slot).
3284    pub fn u32_map_k(&self, buf: &mut CudaSlice<u32>, map: &CudaSlice<u32>, idx: usize)
3285                     -> Result<(), Box<dyn std::error::Error>> {
3286        let f = self.func("u32_map_k");
3287        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (1, 1, 1), shared_mem_bytes: 0 };
3288        let ii = idx as i32;
3289        let __s_b = self.gpu.stream();
3290        let mut b = __s_b.launch_builder(&f);
3291        b.arg(buf).arg(map).arg(&ii);
3292        unsafe { b.launch(cfg)?; }
3293        Ok(())
3294    }
3295
3296    /// Pack a[off..off+n1] ++ b[0..n2] into one buffer (single dtoh follows).
3297    #[allow(clippy::too_many_arguments)]
3298    pub fn u32_pack2(&self, a: &CudaSlice<u32>, off_a: usize, n1: usize,
3299                     b_in: &CudaSlice<u32>, n2: usize, out: &mut CudaSlice<u32>)
3300                     -> Result<(), Box<dyn std::error::Error>> {
3301        let f = self.func("u32_pack2");
3302        let cfg = LaunchConfig::for_num_elems((n1 + n2) as u32);
3303        let (oa, i1, i2) = (off_a as i32, n1 as i32, n2 as i32);
3304        let __s_b = self.gpu.stream();
3305        let mut b = __s_b.launch_builder(&f);
3306        b.arg(a).arg(&oa).arg(&i1).arg(b_in).arg(&i2).arg(out);
3307        unsafe { b.launch(cfg)?; }
3308        Ok(())
3309    }
3310
3311    /// gemma4 R3 device fold: w[i] *= s[sel[i]] over the router's [n] (sel, w) pair.
3312    pub fn moe_w_exscale(&self, w: &mut CudaSlice<f32>, sel: &CudaSlice<i32>,
3313                         s: &CudaSlice<f32>, n: usize) -> Result<(), Box<dyn std::error::Error>> {
3314        let f = self.func("moe_w_exscale");
3315        let cfg = LaunchConfig::for_num_elems(n as u32);
3316        let ni = n as i32;
3317        let __s_b = self.gpu.stream();
3318        let mut b = __s_b.launch_builder(&f);
3319        b.arg(w).arg(sel).arg(s).arg(&ni);
3320        unsafe { b.launch(cfg)?; }
3321        Ok(())
3322    }
3323
3324    /// Down-projection macro fold: w[i] *= macros[2*n_expert + sel[i]] on the device router
3325    /// weights (one launch per MoE layer, only for macro-carrying artifacts — see MoeWeights).
3326    pub fn moe_w_scale_by_expert(&self, w: &mut CudaSlice<f32>, sel: &CudaSlice<i32>,
3327                                 macros: &CudaSlice<f32>, n_expert: usize, n: usize)
3328                                 -> Result<(), Box<dyn std::error::Error>> {
3329        let f = self.func("moe_w_scale_by_expert");
3330        let cfg = LaunchConfig { grid_dim: (n.div_ceil(64) as u32, 1, 1),
3331                                 block_dim: (64, 1, 1), shared_mem_bytes: 0 };
3332        let (ne, nn) = (n_expert as i32, n as i32);
3333        let __s_b = self.gpu.stream();
3334        let mut b = __s_b.launch_builder(&f);
3335        b.arg(w).arg(sel).arg(macros).arg(&ne).arg(&nn);
3336        unsafe { b.launch(cfg)?; }
3337        Ok(())
3338    }
3339
3340    pub fn moe_gate_up_silu8_dev_q8(&self, table: &CudaSlice<u64>, sel: &cudarc::driver::CudaView<i32>,
3341                                    aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
3342                                    in_f: usize, n_ff: usize, n_used: usize, n_expert: usize,
3343                                    qt_g: i32, qt_u: i32, rb_g: usize, rb_u: usize,
3344                                    macros: &CudaSlice<f32>)
3345                                    -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3346        static GU: std::sync::OnceLock<(String, u32)> = std::sync::OnceLock::new();
3347        let (mode, wpb) = GU.get_or_init(|| {
3348            let mode = std::env::var("MEMRA_MOE_DEVQ8_GU").unwrap_or_default();
3349            let wpb = std::env::var("MEMRA_MOE_DEVQ8_WPB").ok()
3350                .and_then(|v| v.parse().ok()).unwrap_or(4u32).clamp(1, 16);
3351            (mode, wpb)
3352        });
3353        let (mode, wpb) = (mode.as_str(), *wpb);
3354        let mut act = self.alloc_uninit::<f32>(n_used * n_ff)?;
3355        let (inf, nff, ne, rbg, rbu) = (in_f as i32, n_ff as i32, n_expert as i32,
3356                                        rb_g as i64, rb_u as i64);
3357        let (f, cfg) = match mode {
3358            "1" | "2" | "4" => {
3359                let rpw: u32 = mode.parse().unwrap();
3360                let f = self.func(match rpw { 1 => "moe_gate_up_silu8_dev_q8_r1",
3361                                              2 => "moe_gate_up_silu8_dev_q8_r2",
3362                                              _ => "moe_gate_up_silu8_dev_q8_r4" });
3363                let rows_per_block = (rpw * wpb) as usize;
3364                let gx = n_ff.div_ceil(rows_per_block) as u32;
3365                (f, LaunchConfig { grid_dim: (gx, n_used as u32, 1),
3366                                   block_dim: (32, wpb, 1), shared_mem_bytes: 0 })
3367            }
3368            "j8" if n_used <= 32 => (self.func("moe_gate_up_silu8_dev_q8_j8"),
3369                     LaunchConfig { grid_dim: (n_ff as u32, 1, 1),
3370                                    block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 }),
3371            // SMEM-GRID twins (IQ3_S 2KB grid copied to shared, static smem — bit-identical dots)
3372            "vsm2" => {
3373                let f = self.func("moe_gate_up_silu8_dev_q8_vsm2");
3374                let sh = (rb_g + rb_u) as u32;
3375                use cudarc::driver::sys::CUfunction_attribute_enum as A;
3376                f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
3377                (f, LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3378                                   block_dim: (32, 1, 1), shared_mem_bytes: sh })
3379            }
3380            "vsm" => {
3381                let f = self.func("moe_gate_up_silu8_dev_q8_vsm");
3382                let sh = (rb_g + rb_u) as u32;
3383                use cudarc::driver::sys::CUfunction_attribute_enum as A;
3384                f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
3385                (f, LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3386                                   block_dim: (32, 1, 1), shared_mem_bytes: sh })
3387            }
3388            "sg" => (self.func("moe_gate_up_silu8_dev_q8_sg"),
3389                     LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3390                                    block_dim: (32, 1, 1), shared_mem_bytes: 0 }),
3391            "j8sg" if n_used <= 32 => (self.func("moe_gate_up_silu8_dev_q8_j8sg"),
3392                     LaunchConfig { grid_dim: (n_ff as u32, 1, 1),
3393                                    block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 }),
3394            "u64" if in_f == 2048 => (self.func("moe_gate_up_silu8_dev_q8_u64"),
3395                     LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3396                                    block_dim: (32, 1, 1), shared_mem_bytes: 0 }),
3397            "gs4" if in_f == 2048 => (self.func("moe_gate_up_silu8_dev_q8_gs4"),
3398                     LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3399                                    block_dim: (32, 4, 1), shared_mem_bytes: 0 }),
3400            // _v twin (down8 lane 2026-07-08): wide-load IQ4_XS dot, base geometry, bit-identical.
3401            "v" | "" => (self.func("moe_gate_up_silu8_dev_q8_v"),
3402                    LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3403                                   block_dim: (32, 1, 1), shared_mem_bytes: 0 }),
3404            "s2" => (self.func("moe_gate_up_silu8_dev_q8_s2"),
3405                     LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3406                                    block_dim: (32, 2, 1), shared_mem_bytes: 0 }),
3407            "s2z" => {
3408                let rz = wpb.min(16);        // s2z smem tile is [16][2]
3409                (self.func("moe_gate_up_silu8_dev_q8_s2z"),
3410                 LaunchConfig { grid_dim: (n_ff.div_ceil(rz as usize) as u32, n_used as u32, 1),
3411                                block_dim: (32, 2, rz), shared_mem_bytes: 0 })
3412            }
3413            _ => (self.func("moe_gate_up_silu8_dev_q8"),
3414                  LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3415                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 }),
3416        };
3417        let __s_b = self.gpu.stream();
3418        let mut b = __s_b.launch_builder(&f);
3419        b.arg(table).arg(sel).arg(aq).arg(ad).arg(&mut act)
3420         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu).arg(macros);
3421        unsafe { b.launch(cfg)?; }
3422        Ok(act)
3423    }
3424
3425    #[allow(clippy::too_many_arguments)]
3426    pub fn moe_down8_fma_dev_q8(&self, table: &CudaSlice<u64>, sel: &cudarc::driver::CudaView<i32>,
3427                                w: &cudarc::driver::CudaView<f32>,
3428                                aq2: &CudaSlice<i8>, ad2: &CudaSlice<f32>,
3429                                dst: &mut cudarc::driver::CudaViewMut<f32>,
3430                                in_f: usize, out_f: usize, n_used: usize, n_expert: usize,
3431                                qt: i32, rb: usize)
3432                                -> Result<(), Box<dyn std::error::Error>> {
3433        static DOWN: std::sync::OnceLock<String> = std::sync::OnceLock::new();
3434        let mode = DOWN.get_or_init(|| std::env::var("MEMRA_MOE_DEVQ8_DOWN").unwrap_or_default());
3435        let (inf, outf, nu, ne, rbi) = (in_f as i32, out_f as i32, n_used as i32,
3436                                        n_expert as i32, rb as i64);
3437        // the w8 twins' smem tile is [RPW][8] — n_used must fit the 8-slot tile;
3438        // the h2 twins are nsb==16 (in_f==512) shape-gated.
3439        let (f, cfg) = match mode.as_str() {
3440            m @ ("1" | "2" | "4") if n_used <= 8 => {
3441                let rpw: usize = m.parse().unwrap();
3442                let f = self.func(match rpw { 1 => "moe_down8_fma_dev_q8_w8r1",
3443                                              2 => "moe_down8_fma_dev_q8_w8r2",
3444                                              _ => "moe_down8_fma_dev_q8_w8r4" });
3445                (f, LaunchConfig { grid_dim: (out_f.div_ceil(rpw) as u32, 1, 1),
3446                                   block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 })
3447            }
3448            "h2" if in_f == 512 => (self.func("moe_down8_fma_dev_q8_h2"),
3449                LaunchConfig { grid_dim: (out_f.div_ceil(2) as u32, 1, 1),
3450                               block_dim: (32, 1, 1), shared_mem_bytes: 0 }),
3451            // "" = AUTO gemma shape (in_f==704): w8r2 measured +1 tok/s vs base (sweep
3452            // 1/2/4 -> 133.6/134.2/133.6, 2026-07-10); slot-ordered chain preserved.
3453            "" if in_f == 704 && n_used <= 8 =>
3454                (self.func("moe_down8_fma_dev_q8_w8r2"),
3455                 LaunchConfig { grid_dim: (out_f.div_ceil(2) as u32, 1, 1),
3456                                block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 }),
3457            // "" = AUTO: the measured winner for the 35B expert shape (arc 2026-07-05, +3.8%);
3458            // any shape the h2 kernels can't take (nsb!=16 / n_used>8) falls to base via `_`.
3459            // _v twins (down8 lane 2026-07-08): wide-load IQ4_XS dot, bit-identical outputs.
3460            "w8h2v" | "" if in_f == 512 && n_used <= 8 =>
3461                (self.func("moe_down8_fma_dev_q8_w8h2v"),
3462                 LaunchConfig { grid_dim: (out_f.div_ceil(2) as u32, 1, 1),
3463                                block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 }),
3464            "w8h2r2v" if in_f == 512 && n_used <= 8 =>
3465                (self.func("moe_down8_fma_dev_q8_w8h2r2v"),
3466                 LaunchConfig { grid_dim: (out_f.div_ceil(4) as u32, 1, 1),
3467                                block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 }),
3468            "w8h2r2" if in_f == 512 && n_used <= 8 =>
3469                (self.func("moe_down8_fma_dev_q8_w8h2r2"),
3470                 LaunchConfig { grid_dim: (out_f.div_ceil(4) as u32, 1, 1),
3471                                block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 }),
3472            "w8h2" if in_f == 512 && n_used <= 8 =>
3473                (self.func("moe_down8_fma_dev_q8_w8h2"),
3474                 LaunchConfig { grid_dim: (out_f.div_ceil(2) as u32, 1, 1),
3475                                block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 }),
3476            _ => (self.func("moe_down8_fma_dev_q8"),
3477                  LaunchConfig { grid_dim: (out_f as u32, 1, 1),
3478                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 }),
3479        };
3480        let __s_b = self.gpu.stream();
3481        let mut b = __s_b.launch_builder(&f);
3482        b.arg(table).arg(sel).arg(w).arg(aq2).arg(ad2).arg(dst)
3483         .arg(&inf).arg(&outf).arg(&nu).arg(&ne).arg(&qt).arg(&rbi);
3484        unsafe { b.launch(cfg)?; }
3485        Ok(())
3486    }
3487
3488    /// SMALL-M VERIFY rows twin (MEMRA_SPEC_M2, lane/spec-m2): ONE launch covers all `t` tokens
3489    /// of the spec verify's MoE dev gate/up (grid.z = token) — the _v geometry per token, with
3490    /// tok-offset sel/aq/ad/act pointers matching the serial loop's slices. BIT-IDENTICAL per
3491    /// token (see the kernel header). aq/ad are the BATCHED z-quantize ([t, in_f] rows —
3492    /// quantize_q8_1's per-32-block program is row-independent, so batched rows == the serial
3493    /// loop's per-token quantize_q8_1_view bytes). Returns act [t, n_used, n_ff].
3494    #[allow(clippy::too_many_arguments)]
3495    pub fn moe_gate_up_silu8_dev_q8_rows(&self, table: &CudaSlice<u64>, sel: &CudaSlice<i32>,
3496                                         aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, t: usize,
3497                                         in_f: usize, n_ff: usize, n_used: usize, n_expert: usize,
3498                                         qt_g: i32, qt_u: i32, rb_g: usize, rb_u: usize,
3499                                         macros: &CudaSlice<f32>)
3500                                         -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3501        let f = self.func("moe_gate_up_silu8_dev_q8_v_rows");
3502        let mut act = self.alloc_uninit::<f32>(t * n_used * n_ff)?;
3503        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, t as u32),
3504                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
3505        let (inf, nff, ne, nu, rbg, rbu) = (in_f as i32, n_ff as i32, n_expert as i32,
3506                                            n_used as i32, rb_g as i64, rb_u as i64);
3507        let __s_b = self.gpu.stream();
3508        let mut b = __s_b.launch_builder(&f);
3509        b.arg(table).arg(sel).arg(aq).arg(ad).arg(&mut act)
3510         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu).arg(&nu).arg(macros);
3511        unsafe { b.launch(cfg)?; }
3512        Ok(act)
3513    }
3514
3515    /// SMALL-M VERIFY rows twin of the down proj: w8h2v geometry per token on a grid.z token
3516    /// axis. Caller gates the w8h2v shape contract (in_f == 512, n_used <= 8) — same gate as
3517    /// the AUTO dispatch in `moe_down8_fma_dev_q8`. aq2/ad2 = batched act quantize
3518    /// ([t*n_used, in_f] rows). dst rows are FULLY overwritten per token.
3519    #[allow(clippy::too_many_arguments)]
3520    pub fn moe_down8_fma_dev_q8_rows(&self, table: &CudaSlice<u64>, sel: &CudaSlice<i32>,
3521                                     w: &CudaSlice<f32>, aq2: &CudaSlice<i8>, ad2: &CudaSlice<f32>,
3522                                     dst: &mut CudaSlice<f32>, t: usize,
3523                                     in_f: usize, out_f: usize, n_used: usize, n_expert: usize,
3524                                     qt: i32, rb: usize)
3525                                     -> Result<(), Box<dyn std::error::Error>> {
3526        assert!(in_f == 512 && n_used <= 8, "down rows twin is w8h2v shape-gated");
3527        let f = self.func("moe_down8_fma_dev_q8_w8h2v_rows");
3528        let cfg = LaunchConfig { grid_dim: (out_f.div_ceil(2) as u32, 1, t as u32),
3529                                 block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 };
3530        let (inf, outf, nu, ne, rbi) = (in_f as i32, out_f as i32, n_used as i32,
3531                                        n_expert as i32, rb as i64);
3532        let __s_b = self.gpu.stream();
3533        let mut b = __s_b.launch_builder(&f);
3534        b.arg(table).arg(sel).arg(w).arg(aq2).arg(ad2).arg(dst)
3535         .arg(&inf).arg(&outf).arg(&nu).arg(&ne).arg(&qt).arg(&rbi);
3536        unsafe { b.launch(cfg)?; }
3537        Ok(())
3538    }
3539
3540    /// CSR gate/up v3 (owner-scan dedup, no build kernel): qtypes {IQ4_XS, IQ3_S} (caller
3541    /// gates), grid.y = pair index; the first pair of each expert serves all its pairs.
3542    /// Bit-identical to moe_gate_up_silu8_dev_q8_v_rows (explicit-intrinsic accumulate).
3543    #[allow(clippy::too_many_arguments)]
3544    pub fn moe_gate_up_silu8_dev_q8_csr(&self, table: &CudaSlice<u64>, sel: &CudaSlice<i32>,
3545                                        aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
3546                                        n_pairs: usize, in_f: usize, n_ff: usize, n_used: usize,
3547                                        n_expert: usize, qt_g: i32, qt_u: i32, rb_g: usize, rb_u: usize)
3548                                        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3549        let f = self.func("moe_gate_up_silu8_dev_q8_csr_iq4");
3550        let mut act = self.alloc_uninit::<f32>(n_pairs * n_ff)?;
3551        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_pairs as u32, 1),
3552                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
3553        let (inf, nff, ne, nu, npi, rbg, rbu) = (in_f as i32, n_ff as i32, n_expert as i32,
3554                                                 n_used as i32, n_pairs as i32, rb_g as i64, rb_u as i64);
3555        let __s_b = self.gpu.stream();
3556        let mut b = __s_b.launch_builder(&f);
3557        b.arg(table).arg(sel).arg(aq).arg(ad).arg(&mut act)
3558         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu).arg(&nu).arg(&npi);
3559        unsafe { b.launch(cfg)?; }
3560        Ok(act)
3561    }
3562
3563
3564    /// TEST SEAM (down8 lane 2026-07-08): launch a down dev_q8 variant BY NAME with its
3565    /// canonical geometry, bypassing the env-cached dispatch so moe-devq8-check can byte-
3566    /// compare variants in one process. Variants: "base", "w8h2", "w8h2r2", "w8h2v", "w8h2r2v".
3567    #[allow(clippy::too_many_arguments)]
3568    pub fn moe_down8_fma_dev_q8_variant(&self, variant: &str, table: &CudaSlice<u64>,
3569                                        sel: &cudarc::driver::CudaView<i32>,
3570                                        w: &cudarc::driver::CudaView<f32>,
3571                                        aq2: &CudaSlice<i8>, ad2: &CudaSlice<f32>,
3572                                        dst: &mut cudarc::driver::CudaViewMut<f32>,
3573                                        in_f: usize, out_f: usize, n_used: usize, n_expert: usize,
3574                                        qt: i32, rb: usize)
3575                                        -> Result<(), Box<dyn std::error::Error>> {
3576        let (inf, outf, nu, ne, rbi) = (in_f as i32, out_f as i32, n_used as i32,
3577                                        n_expert as i32, rb as i64);
3578        let (f, cfg) = match variant {
3579            "w8h2" | "w8h2v" => {
3580                (self.func(if variant == "w8h2" { "moe_down8_fma_dev_q8_w8h2" }
3581                           else { "moe_down8_fma_dev_q8_w8h2v" }),
3582                 LaunchConfig { grid_dim: (out_f.div_ceil(2) as u32, 1, 1),
3583                                block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 })
3584            }
3585            "w8h2r2" | "w8h2r2v" => {
3586                (self.func(if variant == "w8h2r2" { "moe_down8_fma_dev_q8_w8h2r2" }
3587                           else { "moe_down8_fma_dev_q8_w8h2r2v" }),
3588                 LaunchConfig { grid_dim: (out_f.div_ceil(4) as u32, 1, 1),
3589                                block_dim: (32, n_used as u32, 1), shared_mem_bytes: 0 })
3590            }
3591            _ => (self.func("moe_down8_fma_dev_q8"),
3592                  LaunchConfig { grid_dim: (out_f as u32, 1, 1),
3593                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 }),
3594        };
3595        let __s_b = self.gpu.stream();
3596        let mut b = __s_b.launch_builder(&f);
3597        b.arg(table).arg(sel).arg(w).arg(aq2).arg(ad2).arg(dst)
3598         .arg(&inf).arg(&outf).arg(&nu).arg(&ne).arg(&qt).arg(&rbi);
3599        unsafe { b.launch(cfg)?; }
3600        Ok(())
3601    }
3602
3603    /// TEST SEAM (down8 lane): gate_up twin of the above. Variants: "base", "v".
3604    #[allow(clippy::too_many_arguments)]
3605    pub fn moe_gate_up_silu8_dev_q8_variant(&self, variant: &str, table: &CudaSlice<u64>,
3606                                            sel: &cudarc::driver::CudaView<i32>,
3607                                            aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
3608                                            in_f: usize, n_ff: usize, n_used: usize,
3609                                            n_expert: usize, qt_g: i32, qt_u: i32,
3610                                            rb_g: usize, rb_u: usize)
3611                                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3612        let mut act = self.alloc_uninit::<f32>(n_used * n_ff)?;
3613        let (inf, nff, ne, rbg, rbu) = (in_f as i32, n_ff as i32, n_expert as i32,
3614                                        rb_g as i64, rb_u as i64);
3615        let f = self.func(if variant == "v" { "moe_gate_up_silu8_dev_q8_v" }
3616                          else { "moe_gate_up_silu8_dev_q8" });
3617        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3618                                 block_dim: (32, 1, 1), shared_mem_bytes: 0 };
3619        let __s_b = self.gpu.stream();
3620        let mut b = __s_b.launch_builder(&f);
3621        b.arg(table).arg(sel).arg(aq).arg(ad).arg(&mut act)
3622         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu);
3623        unsafe { b.launch(cfg)?; }
3624        Ok(act)
3625    }
3626
3627    pub fn moe_gate_up_silu8_dev(&self, table: &CudaSlice<u64>, sel: &cudarc::driver::CudaView<i32>,
3628                                 x: &cudarc::driver::CudaView<f32>,
3629                                 in_f: usize, n_ff: usize, n_used: usize, n_expert: usize,
3630                                 qt_g: i32, qt_u: i32, rb_g: usize, rb_u: usize,
3631                                 macros: &CudaSlice<f32>)
3632                                 -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3633        let f = self.func("moe_gate_up_silu8_dev");
3634        let mut act = self.alloc_uninit::<f32>(n_used * n_ff)?;  // fully overwritten
3635        let cfg = LaunchConfig { grid_dim: (n_ff as u32, n_used as u32, 1),
3636                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
3637        let (inf, nff, ne, rbg, rbu) = (in_f as i32, n_ff as i32, n_expert as i32,
3638                                        rb_g as i64, rb_u as i64);
3639        let __s_b = self.gpu.stream();
3640        let mut b = __s_b.launch_builder(&f);
3641        b.arg(table).arg(sel).arg(x).arg(&mut act)
3642         .arg(&inf).arg(&nff).arg(&ne).arg(&qt_g).arg(&qt_u).arg(&rbg).arg(&rbu).arg(macros);
3643        unsafe { b.launch(cfg)?; }
3644        Ok(act)
3645    }
3646
3647    /// LAUNCH-STRUCTURE STAGE 3: device-dispatch twin of `moe_down8_fma_into` — expert ids AND
3648    /// renormalized weights read from the router kernel's device output. BIT-IDENTICAL chain.
3649    #[allow(clippy::too_many_arguments)]
3650    pub fn moe_down8_fma_dev(&self, table: &CudaSlice<u64>, sel: &cudarc::driver::CudaView<i32>,
3651                             w: &cudarc::driver::CudaView<f32>, act: &CudaSlice<f32>,
3652                             dst: &mut cudarc::driver::CudaViewMut<f32>,
3653                             in_f: usize, out_f: usize, n_used: usize, n_expert: usize,
3654                             qt: i32, rb: usize)
3655                             -> Result<(), Box<dyn std::error::Error>> {
3656        let f = self.func("moe_down8_fma_dev");
3657        let cfg = LaunchConfig { grid_dim: (out_f as u32, 1, 1),
3658                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
3659        let (inf, outf, nu, ne, rbv) = (in_f as i32, out_f as i32, n_used as i32,
3660                                        n_expert as i32, rb as i64);
3661        let __s_b = self.gpu.stream();
3662        let mut b = __s_b.launch_builder(&f);
3663        b.arg(table).arg(sel).arg(w).arg(act).arg(dst)
3664         .arg(&inf).arg(&outf).arg(&nu).arg(&ne).arg(&qt).arg(&rbv);
3665        unsafe { b.launch(cfg)?; }
3666        Ok(())
3667    }
3668
3669    /// dst[i] += alpha * src[i], i in 0..n. dst is a CudaViewMut (a row of moe_out).
3670    pub fn axpy_into(&self, src: &CudaSlice<f32>, alpha: f32,
3671                     dst: &mut cudarc::driver::CudaViewMut<f32>, n: usize)
3672                     -> Result<(), Box<dyn std::error::Error>> {
3673        let f = self.func("axpy_f32");
3674        let cfg = LaunchConfig::for_num_elems(n as u32);
3675        let (a, ni) = (alpha, n as i32);
3676        let __s_b = self.gpu.stream();
3677        let mut b = __s_b.launch_builder(&f);
3678        b.arg(src).arg(dst).arg(&a).arg(&ni);
3679        unsafe { b.launch(cfg)?; }
3680        Ok(())
3681    }
3682
3683    /// dst[r*ncols + c] += src[r*ncols + c] * scale[r]. Per-row scalar accumulate (shared expert).
3684    pub fn add_scaled_rows(&self, src: &CudaSlice<f32>, scale: &CudaSlice<f32>,
3685                           dst: &mut CudaSlice<f32>, ncols: usize, nrows: usize)
3686                           -> Result<(), Box<dyn std::error::Error>> {
3687        let f = self.func("add_scaled_rows_f32");
3688        let cfg = LaunchConfig::for_num_elems((ncols * nrows) as u32);
3689        let (nc, nr) = (ncols as i32, nrows as i32);
3690        let __s_b = self.gpu.stream();
3691        let mut b = __s_b.launch_builder(&f);
3692        b.arg(src).arg(scale).arg(dst).arg(&nc).arg(&nr);
3693        unsafe { b.launch(cfg)?; }
3694        Ok(())
3695    }
3696
3697    // ======== A2 GROUPED MoE PREFILL KERNELS ========
3698
3699    /// Gather m_e rows from src[T, ncols] into dst[m_e, ncols] using index array idx[m_e].
3700    pub fn gather_rows(&self, src: &CudaSlice<f32>, idx: &CudaSlice<i32>,
3701                       dst: &mut CudaSlice<f32>, ncols: usize, m_e: usize)
3702                       -> Result<(), Box<dyn std::error::Error>> {
3703        let f = self.func("gather_rows_f32");
3704        let cfg = LaunchConfig::for_num_elems((m_e * ncols) as u32);
3705        let (nc, me) = (ncols as i32, m_e as i32);
3706        let __s_b = self.gpu.stream();
3707        let mut b = __s_b.launch_builder(&f);
3708        b.arg(src).arg(idx).arg(dst).arg(&nc).arg(&me);
3709        unsafe { b.launch(cfg)?; }
3710        Ok(())
3711    }
3712
3713    /// Scatter expert outputs into per-token slots: dst[tok_idx[r], slot_idx[r], :] = src[r, :] * weight[r].
3714    /// dst is [T, n_used, ncols], zero-initialized. Each (expert, token) pair maps to a unique slot.
3715    /// Scatter expert outputs into per-token slots (raw copy, no weight multiply).
3716    /// Weight stored into wbuf[tok*n_used + slot] for FMA in reduce step.
3717    pub fn scatter_slot(&self, src: &CudaSlice<f32>, tok_idx: &CudaSlice<i32>,
3718                        slot_idx: &CudaSlice<i32>, weight: &CudaSlice<f32>,
3719                        dst: &mut CudaSlice<f32>, wbuf: &mut CudaSlice<f32>,
3720                        ncols: usize, n_used: usize, m_e: usize)
3721                        -> Result<(), Box<dyn std::error::Error>> {
3722        let f = self.func("scatter_add_slot_f32");
3723        let cfg = LaunchConfig::for_num_elems((m_e * ncols) as u32);
3724        let (nc, nu, me) = (ncols as i32, n_used as i32, m_e as i32);
3725        let __s_b = self.gpu.stream();
3726        let mut b = __s_b.launch_builder(&f);
3727        b.arg(src).arg(tok_idx).arg(slot_idx).arg(weight).arg(dst).arg(wbuf).arg(&nc).arg(&nu).arg(&me);
3728        unsafe { b.launch(cfg)?; }
3729        Ok(())
3730    }
3731
3732    /// Reduce n_used slots per token: dst[t, col] = sum_s slots[t, s, col].
3733    /// Reduce n_used slots per token: dst[t, col] = sum_s FMA(wbuf[t,s], slots[t,s,col], acc).
3734    /// Uses FMA for bit-identity with the sequential axpy path.
3735    pub fn reduce_slots(&self, slots: &CudaSlice<f32>, wbuf: &CudaSlice<f32>,
3736                        dst: &mut CudaSlice<f32>, ncols: usize, n_used: usize, t: usize)
3737                        -> Result<(), Box<dyn std::error::Error>> {
3738        let f = self.func("reduce_slots_f32");
3739        let cfg = LaunchConfig::for_num_elems((t * ncols) as u32);
3740        let (nc, nu, ti) = (ncols as i32, n_used as i32, t as i32);
3741        let __s_b = self.gpu.stream();
3742        let mut b = __s_b.launch_builder(&f);
3743        b.arg(slots).arg(wbuf).arg(dst).arg(&nc).arg(&nu).arg(&ti);
3744        unsafe { b.launch(cfg)?; }
3745        Ok(())
3746    }
3747
3748    /// Stage-B: quantize activation [m,in] f32 -> q8_1 (int8 qs + per-block f32 scale).
3749    /// Quantize an activation [m, in_f] to q8_1 (int8 qs + per-32 f32 scale). Public so the
3750    /// forward can quantize a SHARED activation ONCE and feed it to several matmuls (gate+up
3751    /// share `z`; q/k/v and wqkv/gate/beta/alpha share `h`) — quantize_q8_1 was 13.5% of decode
3752    /// GPU time, ~half of it redundant re-quantization of the same row.
3753    /// quantize_q8_1 over a CudaView (a sliced z-row) — same kernel, offset-honoring arg.
3754    pub fn quantize_q8_1_view(&self, x: &cudarc::driver::CudaView<f32>, m: usize, in_f: usize)
3755                     -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3756        let f = self.func("quantize_q8_1");
3757        let nblk = in_f / 32;
3758        let mut q = self.alloc_uninit::<i8>(m * in_f)?;
3759        let mut d = self.alloc_uninit::<f32>(m * nblk)?;
3760        let cfg = LaunchConfig::for_num_elems((m * in_f) as u32);
3761        let (inf, mi) = (in_f as i32, m as i32);
3762        let __s_b = self.gpu.stream();
3763        let mut b = __s_b.launch_builder(&f);
3764        b.arg(x).arg(&mut q).arg(&mut d).arg(&inf).arg(&mi);
3765        unsafe { b.launch(cfg)?; }
3766        Ok((q, d))
3767    }
3768
3769    pub fn quantize_q8_1(&self, x: &CudaSlice<f32>, m: usize, in_f: usize)
3770                     -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3771        let nblk = in_f / 32;
3772        let mut q = self.alloc_uninit::<i8>(m * in_f)?;  // full-overwrite output: skip memset
3773        let mut d = self.alloc_uninit::<f32>(m * nblk)?;  // full-overwrite output: skip memset
3774        // WARP-PER-BLOCK kernel: one warp per 32-block -> m*in_f threads total.
3775        let cfg = LaunchConfig::for_num_elems((m * in_f) as u32);
3776        let (inf, mi) = (in_f as i32, m as i32);
3777        if Self::pdl_on() && Self::pdl_wb_on() {
3778            {
3779            use cudarc::driver::{DevicePtr, DevicePtrMut};
3780            let s = &self.gpu.stream();
3781            let (px, _g0) = x.device_ptr(s);
3782            let (pq, _g1) = q.device_ptr_mut(s); let (pd, _g2) = d.device_ptr_mut(s);
3783            let mut ps = [
3784                &px as *const _ as *mut std::ffi::c_void, &pq as *const _ as *mut _,
3785                &pd as *const _ as *mut _, &inf as *const _ as *mut _,
3786                &mi as *const _ as *mut _,
3787            ];
3788            unsafe { self.launch_pdl("quantize_q8_1", cfg.grid_dim, cfg.block_dim, &mut ps)?; }
3789            }
3790            return Ok((q, d));
3791        }
3792        let f = self.func("quantize_q8_1");
3793        let __s_b = self.gpu.stream();
3794        let mut b = __s_b.launch_builder(&f);
3795        b.arg(x).arg(&mut q).arg(&mut d).arg(&inf).arg(&mi);
3796        unsafe { b.launch(cfg)?; }
3797        Ok((q, d))
3798    }
3799
3800    /// Stage-C FP4: quantize activation [m,in] f32 -> e2m1 nibbles (aq4: u32 [m, in/8]) + per-16
3801    /// UE4M3 scale (ad4: u8 [m, in/16]), the layout the mxf4nvf4 block-scale GEMM B-operand wants.
3802    /// in_f must be a multiple of 64 (one NVFP4 K-block). One thread per (token, 16-block).
3803    pub fn quantize_fp4_act(&self, x: &CudaSlice<f32>, m: usize, in_f: usize)
3804                     -> Result<(CudaSlice<u32>, CudaSlice<u8>), Box<dyn std::error::Error>> {
3805        let f = self.func("quantize_fp4_act");
3806        let nb16 = in_f / 16;
3807        let mut aq4 = self.alloc_uninit::<u32>(m * (in_f / 8))?;  // full-overwrite output: skip memset
3808        let mut ad4 = self.alloc_uninit::<u8>(m * nb16)?;  // full-overwrite output: skip memset
3809        let cfg = LaunchConfig::for_num_elems((m * nb16) as u32);
3810        let (inf, mi) = (in_f as i32, m as i32);
3811        let __s_b = self.gpu.stream();
3812        let mut b = __s_b.launch_builder(&f);
3813        b.arg(x).arg(&mut aq4).arg(&mut ad4).arg(&inf).arg(&mi);
3814        unsafe { b.launch(cfg)?; }
3815        Ok((aq4, ad4))
3816    }
3817
3818    /// Stage-C FP4 GEMM (NVFP4 weights): native mxf4nvf4 block-scale tensor-core matmul. Feeds raw
3819    /// e2m1 weight nibbles + raw UE4M3 micro-scales directly to mma.sync.m16n8k64 (762 TFLOP/s peak,
3820    /// 3.5x int8). Activation `x` is quantized to FP4 e2m1 here. NVFP4 per-tensor macro-scale applied
3821    /// post (scale==1.0 -> no-op). `bytes` = raw NVFP4 weight rows. Used by the MEMRA_FP4 prefill path.
3822    pub fn qmatvec_gemm_nvfp4_fp4(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize,
3823                                  in_f: usize, out_f: usize, row_bytes: usize, scale: f32)
3824                                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3825        assert!(in_f % 64 == 0, "FP4 GEMM requires in_f % 64 == 0, got {in_f}");
3826        let (aq4, ad4) = self.quantize_fp4_act(x, m, in_f)?;
3827        let mut y = self.fp4_gemm_launch(bytes, &aq4, &ad4, m, in_f, out_f, row_bytes)?;
3828        if scale != 1.0 { self.scale_inplace(&mut y, scale, m * out_f)?; }
3829        Ok(y)
3830    }
3831
3832    /// Shared mxf4 GEMM launch (pre-quantized FP4 activation aq4/ad4). Same CTA tile as the int8 GEMM
3833    /// (BM=64 rows x BN=128 tokens, 4 warps). No macro-scale applied here.
3834    fn fp4_gemm_launch(&self, bytes: &CudaSlice<u8>, aq4: &CudaSlice<u32>, ad4: &CudaSlice<u8>,
3835                       m: usize, in_f: usize, out_f: usize, row_bytes: usize)
3836                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3837        let f = self.func("qmatvec_gemm_nvfp4_fp4");
3838        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite output: skip memset
3839        const BM: u32 = 64; const BN: u32 = 256;
3840        let cfg = LaunchConfig {
3841            grid_dim: ((out_f as u32 + BM - 1) / BM, (m as u32 + BN - 1) / BN, 1),
3842            block_dim: (32, 4, 1), shared_mem_bytes: 0,
3843        };
3844        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
3845        let __s_b = self.gpu.stream();
3846        let mut b = __s_b.launch_builder(&f);
3847        b.arg(bytes).arg(aq4).arg(ad4).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
3848        unsafe { b.launch(cfg)?; }
3849        Ok(y)
3850    }
3851
3852    /// Test entry (kernel_check): run the FP4 GEMM from raw bytes; NO macro-scale (caller compares bare).
3853    pub fn qmatvec_gemm_nvfp4_fp4_raw(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize,
3854                                      in_f: usize, out_f: usize, row_bytes: usize)
3855                                      -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3856        assert!(in_f % 64 == 0, "FP4 GEMM requires in_f % 64 == 0, got {in_f}");
3857        let (aq4, ad4) = self.quantize_fp4_act(x, m, in_f)?;
3858        self.fp4_gemm_launch(bytes, &aq4, &ad4, m, in_f, out_f, row_bytes)
3859    }
3860
3861    /// Stage-B: Q8_0 weight x q8_1 activation int8 dp4a matmul. y[m,out]=x@W^T.
3862    pub fn qmatvec_q8_0_fast(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3863                             out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3864        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
3865        let f = self.func("qmatvec_q8_0_dp4a");
3866        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite output: skip memset
3867        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
3868        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
3869        let __s_b = self.gpu.stream();
3870        let mut b = __s_b.launch_builder(&f);
3871        b.arg(w).arg(&aq).arg(&ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
3872        unsafe { b.launch(cfg)?; }
3873        Ok(y)
3874    }
3875
3876    /// Stage-B: Q4_K weight x q8_1 activation int8 dp4a (decode). Min-offset via q8_1 sum term.
3877    #[allow(non_snake_case)] // Keep GGUF qtype spelling visible at the public kernel boundary.
3878    pub fn qmatvec_q4_K_fast(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3879                             out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3880        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
3881        let f = self.func("qmatvec_q4_K_dp4a");
3882        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite output: skip memset
3883        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
3884        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
3885        let __s_b = self.gpu.stream();
3886        let mut b = __s_b.launch_builder(&f);
3887        b.arg(w).arg(&aq).arg(&ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
3888        unsafe { b.launch(cfg)?; }
3889        Ok(y)
3890    }
3891
3892    /// Stage-B: Q6_K weight x q8_1 activation int8 dp4a (decode, symmetric).
3893    #[allow(non_snake_case)] // Keep GGUF qtype spelling visible at the public kernel boundary.
3894    pub fn qmatvec_q6_K_fast(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3895                             out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3896        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
3897        let f = self.func("qmatvec_q6_K_dp4a");
3898        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite output: skip memset
3899        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
3900        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
3901        let __s_b = self.gpu.stream();
3902        let mut b = __s_b.launch_builder(&f);
3903        b.arg(w).arg(&aq).arg(&ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
3904        unsafe { b.launch(cfg)?; }
3905        Ok(y)
3906    }
3907
3908    /// Stage-B: Q5_K weight x q8_1 activation int8 dp4a (decode). Min-offset via q8_1 sum term.
3909    #[allow(non_snake_case)] // Keep GGUF qtype spelling visible at the public kernel boundary.
3910    pub fn qmatvec_q5_K_fast(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3911                             out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3912        self.qmatvec_dp4a_named("qmatvec_q5_K_dp4a", w, x, m, in_f, out_f, row_bytes)
3913    }
3914    /// Stage-B: Q3_K weight x q8_1 activation int8 dp4a (decode, symmetric).
3915    #[allow(non_snake_case)] // Keep GGUF qtype spelling visible at the public kernel boundary.
3916    pub fn qmatvec_q3_K_fast(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3917                             out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3918        self.qmatvec_dp4a_named("qmatvec_q3_K_dp4a", w, x, m, in_f, out_f, row_bytes)
3919    }
3920    /// A6 split-plane twin of `qmatvec_nvfp4_fast` (weights repacked; used by the rp gates).
3921    pub fn qmatvec_nvfp4_fast_rp(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3922                                 out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3923        assert!(in_f % 64 == 0, "NVFP4 dp4a requires in_f % 64 == 0, got {in_f}");
3924        self.qmatvec_dp4a_named("qmatvec_nvfp4_dp4a_rp", w, x, m, in_f, out_f, row_bytes)
3925    }
3926    /// Stage-B: NVFP4 weight x q8_1 activation int8 dp4a (decode, symmetric, codebook lookup).
3927    pub fn qmatvec_nvfp4_fast(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3928                              out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3929        // B1: the NVFP4 dp4a kernel maps two 32-elem q8_1 blocks onto one 64-elem block_nvfp4
3930        // (sblk = g >> 1). in_f must be a multiple of 64 or the last block reads a partial superblock.
3931        assert!(in_f % 64 == 0, "NVFP4 dp4a requires in_f % 64 == 0, got {in_f}");
3932        self.qmatvec_dp4a_named("qmatvec_nvfp4_dp4a", w, x, m, in_f, out_f, row_bytes)
3933    }
3934    /// Stage-B (optional perf): IQ4_XS codebook int8 dp4a.
3935    #[allow(non_snake_case)] // Keep GGUF qtype spelling visible at the public kernel boundary.
3936    pub fn qmatvec_iq4_XS_fast(&self, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
3937                               out_f: usize, row_bytes: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3938        self.qmatvec_dp4a_named("qmatvec_iq4_XS_dp4a", w, x, m, in_f, out_f, row_bytes)
3939    }
3940
3941    /// Shared dp4a launcher: quantize_q8_1 then call the named kernel (grid (out,m), block 64).
3942    fn qmatvec_dp4a_named(&self, name: &str, w: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize,
3943                          in_f: usize, out_f: usize, row_bytes: usize)
3944                          -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3945        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
3946        let f = self.func(name);
3947        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite output: skip memset
3948        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
3949        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
3950        let __s_b = self.gpu.stream();
3951        let mut b = __s_b.launch_builder(&f);
3952        b.arg(w).arg(&aq).arg(&ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
3953        unsafe { b.launch(cfg)?; }
3954        Ok(y)
3955    }
3956
3957    pub fn htod(&self, v: &[f32]) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3958        Ok(self.gpu.stream().clone_htod(v)?)
3959    }
3960    pub fn htod_i32(&self, v: &[i32]) -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3961        Ok(self.gpu.stream().clone_htod(v)?)
3962    }
3963    /// i8 upload (moe-devq8-check: synthetic q8_1 activation bytes).
3964    pub fn htod_i8(&self, v: &[i8]) -> Result<CudaSlice<i8>, Box<dyn std::error::Error>> {
3965        Ok(self.gpu.stream().clone_htod(v)?)
3966    }
3967    pub fn htod_u64(&self, v: &[u64]) -> Result<CudaSlice<u64>, Box<dyn std::error::Error>> {
3968        Ok(self.gpu.stream().clone_htod(v)?)
3969    }
3970    /// View twin of `dtoh` (lean-logits component 3: D2H one row of a [B, n_vocab] stack).
3971    pub fn dtoh_view(&self, d: &cudarc::driver::CudaView<f32>)
3972                     -> Result<Vec<f32>, Box<dyn std::error::Error>> {
3973        let v = self.gpu.stream().clone_dtoh(d)?;
3974        self.gpu.stream().synchronize()?;
3975        Ok(v)
3976    }
3977    pub fn dtoh(&self, d: &CudaSlice<f32>) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
3978        let v = self.gpu.stream().clone_dtoh(d)?;
3979                self.gpu.stream().synchronize()?;
3980        Ok(v)
3981    }
3982    /// Queue two f32 device-to-host copies on the compute stream, then establish one host
3983    /// boundary for both. Hy3's CPU/GPU expert split needs the router logits and the MoE input;
3984    /// issuing them together avoids a second stream synchronization in every trunk layer.
3985    pub fn dtoh_pair(
3986        &self,
3987        a: &CudaSlice<f32>,
3988        b: &CudaSlice<f32>,
3989    ) -> Result<(Vec<f32>, Vec<f32>), Box<dyn std::error::Error>> {
3990        let av = self.gpu.stream().clone_dtoh(a)?;
3991        let bv = self.gpu.stream().clone_dtoh(b)?;
3992        self.gpu.stream().synchronize()?;
3993        Ok((av, bv))
3994    }
3995    /// Device-to-host copy of an i32 buffer (fused-router sel_idx readback).
3996    pub fn dtoh_i32(&self, d: &CudaSlice<i32>) -> Result<Vec<i32>, Box<dyn std::error::Error>> {
3997        let v = self.gpu.stream().clone_dtoh(d)?;
3998        self.gpu.stream().synchronize()?;
3999        Ok(v)
4000    }
4001    /// Device-to-host copy of a u8 buffer (used to read back the quantized KV cache for validation).
4002    pub fn dtoh_u8(&self, d: &CudaSlice<u8>) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
4003        let v = self.gpu.stream().clone_dtoh(d)?;
4004        self.gpu.stream().synchronize()?;
4005        Ok(v)
4006    }
4007    pub fn zeros(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4008        let s = self.gpu.stream().alloc_zeros::<f32>(n)?;
4009        self.keep_if_capturing(&s);
4010        Ok(s)
4011    }
4012
4013    /// GPU-resident greedy argmax (CUDA-GRAPH-PLAN Phase 1): logits[n_vocab] -> token id in a
4014    /// resident device u32 [1]. PARALLEL 2-pass (RANK1 LEVER): the old single-CTA scan (one 256-thread
4015    /// block on one SM over 248K logits) was memory-starved at ~426us/token. Now pass 1 fans NB=256
4016    /// blocks across the SMs to saturate HBM, pass 2 reduces the NB partials. Bit-identical to host
4017    /// `argmax` (smallest index on tie). The whole point is NOT to dtoh logits — only a [1] u32 is read
4018    /// back (or kept resident for graph replay). Returns the device token buffer.
4019    /// Softmax probability of the (already-argmaxed) token `tok` under `logits` — the spec-decode
4020    /// p-min confidence signal. 2-pass like the parallel argmax; returns a device [1] f32.
4021    pub fn prob_of_token_device(&self, logits: &CudaSlice<f32>, tok: &CudaSlice<u32>, n_vocab: usize)
4022                                -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4023        let nb = ARGMAX_NB;
4024        let mut part = self.alloc_uninit::<f32>(nb)?;
4025        let mut p = self.alloc_uninit::<f32>(1)?;
4026        let f1 = self.func("prob_of_token_partial_f32");
4027        let cfg1 = LaunchConfig { grid_dim: (nb as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4028        let nv = n_vocab as i32;
4029        let __s_b1 = self.gpu.stream();
4030        let mut b1 = __s_b1.launch_builder(&f1);
4031        b1.arg(logits).arg(tok).arg(&mut part).arg(&nv);
4032        unsafe { b1.launch(cfg1)?; }
4033        let f2 = self.func("prob_of_token_final_f32");
4034        let cfg2 = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4035        let nbi = nb as i32;
4036        let __s_b2 = self.gpu.stream();
4037        let mut b2 = __s_b2.launch_builder(&f2);
4038        b2.arg(&part).arg(&mut p).arg(&nbi);
4039        unsafe { b2.launch(cfg2)?; }
4040        Ok(p)
4041    }
4042
4043    /// Like `prob_of_token_device` but writes into a PERSISTENT `p_out` buffer (stable pointer).
4044    /// Required for CUDA-graph capture of the draft chain: the captured prob kernels must write
4045    /// where the host reads the p-min confidence between replays. Same kernels, same math.
4046    /// Slot-addressed twin of `prob_of_token_device_into`: token read from `tok_all[tok_idx]`
4047    /// (a view at the slot), probability written to `p_out[p_idx]` — same two kernels, the
4048    /// pointers just land mid-buffer. Zero-sync (gemma confidence-adaptive draft depth).
4049    pub fn prob_of_token_device_col(&self, logits: &CudaSlice<f32>,
4050                                    tok_all: &CudaSlice<u32>, tok_idx: usize,
4051                                    p_out: &mut CudaSlice<f32>, p_idx: usize, n_vocab: usize)
4052                                    -> Result<(), Box<dyn std::error::Error>> {
4053        let tok_v = tok_all.slice(tok_idx..tok_idx + 1);
4054        let mut p_v = p_out.slice_mut(p_idx..p_idx + 1);
4055        let nb = ARGMAX_NB;
4056        let mut part = self.alloc_uninit::<f32>(nb)?;
4057        let f1 = self.func("prob_of_token_partial_f32");
4058        let cfg1 = LaunchConfig { grid_dim: (nb as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4059        let nv = n_vocab as i32;
4060        let __s_b1 = self.gpu.stream();
4061        let mut b1 = __s_b1.launch_builder(&f1);
4062        b1.arg(logits).arg(&tok_v).arg(&mut part).arg(&nv);
4063        unsafe { b1.launch(cfg1)?; }
4064        let f2 = self.func("prob_of_token_final_f32");
4065        let cfg2 = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4066        let nbi = nb as i32;
4067        let __s_b2 = self.gpu.stream();
4068        let mut b2 = __s_b2.launch_builder(&f2);
4069        b2.arg(&part).arg(&mut p_v).arg(&nbi);
4070        unsafe { b2.launch(cfg2)?; }
4071        Ok(())
4072    }
4073
4074    pub fn prob_of_token_device_into(&self, logits: &CudaSlice<f32>, tok: &CudaSlice<u32>,
4075                                     p_out: &mut CudaSlice<f32>, n_vocab: usize)
4076                                     -> Result<(), Box<dyn std::error::Error>> {
4077        let nb = ARGMAX_NB;
4078        let mut part = self.alloc_uninit::<f32>(nb)?;
4079        let f1 = self.func("prob_of_token_partial_f32");
4080        let cfg1 = LaunchConfig { grid_dim: (nb as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4081        let nv = n_vocab as i32;
4082        let __s_b1 = self.gpu.stream();
4083        let mut b1 = __s_b1.launch_builder(&f1);
4084        b1.arg(logits).arg(tok).arg(&mut part).arg(&nv);
4085        unsafe { b1.launch(cfg1)?; }
4086        let f2 = self.func("prob_of_token_final_f32");
4087        let cfg2 = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4088        let nbi = nb as i32;
4089        let __s_b2 = self.gpu.stream();
4090        let mut b2 = __s_b2.launch_builder(&f2);
4091        b2.arg(&part).arg(p_out).arg(&nbi);
4092        unsafe { b2.launch(cfg2)?; }
4093        Ok(())
4094    }
4095
4096    pub fn argmax_token_device(&self, logits: &CudaSlice<f32>, n_vocab: usize)
4097                               -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
4098        let mut tok = unsafe { self.gpu.stream().alloc::<u32>(1)? };
4099        self.argmax_token_device_into(logits, &mut tok, n_vocab)?;
4100        Ok(tok)
4101    }
4102    /// Like `argmax_token_device` but writes into a PERSISTENT `tok` buffer (stable pointer) instead
4103    /// of allocating a fresh one. Required for CUDA-graph capture: the captured argmax must write the
4104    /// next token into the SAME device buffer the next replay's embed_gather reads, so the buffer
4105    /// pointer is baked once and the token id never round-trips to host inside steady state. The
4106    /// pass-1 partials scratch (`argmax_partials`) is also a resident stable-pointer buffer so both
4107    /// captured passes bake fixed addresses.
4108    pub fn argmax_token_device_into(&self, logits: &CudaSlice<f32>, tok: &mut CudaSlice<u32>,
4109                                    n_vocab: usize) -> Result<(), Box<dyn std::error::Error>> {
4110        let nb = ARGMAX_NB;
4111        let f1 = self.func("argmax_partial_f32");
4112        let f2 = self.func("argmax_final_f32");
4113        let mut guard = self.argmax_partials.lock().unwrap();
4114        if guard.is_none() {
4115            // allocate ONCE; under generate_graph this runs in the tracking-off prime window so the
4116            // buffers carry no cudarc events (illegal inside capture).
4117            let pv = self.gpu.stream().alloc_zeros::<f32>(nb)?;
4118            let pi = self.gpu.stream().alloc_zeros::<i32>(nb)?;
4119            *guard = Some((pv, pi));
4120        }
4121        let (part_v, part_i) = guard.as_mut().unwrap();
4122        let nv = n_vocab as i32;
4123        let nbi = nb as i32;
4124        // pass 1: NB blocks x 256 threads grid-stride scan -> per-block (val, idx) partials.
4125        let cfg1 = LaunchConfig { grid_dim: (nb as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4126        let __s_b1 = self.gpu.stream();
4127        let mut b1 = __s_b1.launch_builder(&f1);
4128        b1.arg(logits).arg(&mut *part_v).arg(&mut *part_i).arg(&nv);
4129        unsafe { b1.launch(cfg1)?; }
4130        // pass 2: one block reduces NB partials -> token_out[0].
4131        let cfg2 = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4132        let __s_b2 = self.gpu.stream();
4133        let mut b2 = __s_b2.launch_builder(&f2);
4134        b2.arg(&*part_v).arg(&*part_i).arg(tok).arg(&nbi);
4135        unsafe { b2.launch(cfg2)?; }
4136        Ok(())
4137    }
4138    /// Column-`col` device argmax over a stacked verify-logits buffer [t, n_vocab] (spec accept
4139    /// walk): toks[out_idx] = argmax(logits[col*n_vocab .. (col+1)*n_vocab]). SAME 2-pass kernels
4140    /// and tie-break contract as `argmax_token_device_into` (bit-identical to host argmax,
4141    /// argmax_gate-validated) — only the input pointer (a column view) and the output slot differ.
4142    /// Lets the accept walk read ONE [t] u32 instead of dtoh'ing the full [t, n_vocab] logits.
4143    pub fn argmax_token_device_col(&self, logits: &CudaSlice<f32>, col: usize, n_vocab: usize,
4144                                   toks: &mut CudaSlice<u32>, out_idx: usize)
4145                                   -> Result<(), Box<dyn std::error::Error>> {
4146        let nb = ARGMAX_NB;
4147        let f1 = self.func("argmax_partial_f32");
4148        let f2 = self.func("argmax_final_f32");
4149        let mut guard = self.argmax_partials.lock().unwrap();
4150        if guard.is_none() {
4151            let pv = self.gpu.stream().alloc_zeros::<f32>(nb)?;
4152            let pi = self.gpu.stream().alloc_zeros::<i32>(nb)?;
4153            *guard = Some((pv, pi));
4154        }
4155        let (part_v, part_i) = guard.as_mut().unwrap();
4156        let col_view = logits.slice(col * n_vocab..(col + 1) * n_vocab);
4157        let nv = n_vocab as i32;
4158        let nbi = nb as i32;
4159        let cfg1 = LaunchConfig { grid_dim: (nb as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4160        let __s_b1 = self.gpu.stream();
4161        let mut b1 = __s_b1.launch_builder(&f1);
4162        b1.arg(&col_view).arg(&mut *part_v).arg(&mut *part_i).arg(&nv);
4163        unsafe { b1.launch(cfg1)?; }
4164        let mut tok_view = toks.slice_mut(out_idx..out_idx + 1);
4165        let cfg2 = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4166        let __s_b2 = self.gpu.stream();
4167        let mut b2 = __s_b2.launch_builder(&f2);
4168        b2.arg(&*part_v).arg(&*part_i).arg(&mut tok_view).arg(&nbi);
4169        unsafe { b2.launch(cfg2)?; }
4170        Ok(())
4171    }
4172    /// Read back a device u32 buffer (the spec accept walk's [t] per-column argmax tokens).
4173    pub fn htod_u32_v(&self, v: &[u32]) -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
4174        Ok(self.gpu.stream().clone_htod(v)?)
4175    }
4176    pub fn dtoh_u32(&self, d: &CudaSlice<u32>) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
4177        let v = self.gpu.stream().clone_dtoh(d)?;
4178        self.gpu.stream().synchronize()?;
4179        Ok(v)
4180    }
4181    /// Allocate a zeroed device u32 buffer (persistent spec-loop prediction slots).
4182    /// H2D into an EXISTING u32 buffer (stable pointer — the per-step grammar-mask upload:
4183    /// contents change every step, the address must not, so a captured graph can read it).
4184    pub fn htod_u32_into(&self, dst: &mut CudaSlice<u32>, src: &[u32])
4185                         -> Result<(), Box<dyn std::error::Error>> {
4186        let mut view = dst.slice_mut(0..src.len());
4187        self.gpu.stream().memcpy_htod(src, &mut view)?;
4188        Ok(())
4189    }
4190
4191    pub fn alloc_u32_zeroed(&self, n: usize) -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
4192        let s = self.gpu.stream().alloc_zeros::<u32>(n)?;
4193        self.keep_if_capturing(&s);
4194        Ok(s)
4195    }
4196    /// embed_gather into a PERSISTENT `x_out` buffer (stable pointer) for CUDA-graph capture (the
4197    /// embed output starts the per-step kernel chain and must be at a fixed address across replays).
4198    pub fn embed_gather_device_into(&self, embd: &CudaSlice<u8>, token_d: &CudaSlice<u32>,
4199                                    x_out: &mut CudaSlice<f32>, n_embd: usize, qtype: i32,
4200                                    row_bytes: usize) -> Result<(), Box<dyn std::error::Error>> {
4201        let f = self.func("embed_gather_u32");
4202        let cfg = LaunchConfig { grid_dim: (((n_embd as u32 + 255) / 256).max(1), 1, 1),
4203                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4204        let (ne, qt, rb) = (n_embd as i32, qtype, row_bytes as i64);
4205        let __s_b = self.gpu.stream();
4206        let mut b = __s_b.launch_builder(&f);
4207        b.arg(embd).arg(token_d).arg(x_out).arg(&ne).arg(&qt).arg(&rb);
4208        unsafe { b.launch(cfg)?; }
4209        Ok(())
4210    }
4211    /// Read a [1] i32 device counter (pos / seqlen) back to host. Tiny D2H + sync.
4212    pub fn dtoh_i32_one(&self, d: &CudaSlice<i32>) -> Result<i32, Box<dyn std::error::Error>> {
4213        let v = self.gpu.stream().clone_dtoh(d)?;
4214        self.gpu.stream().synchronize()?;
4215        Ok(v[0])
4216    }
4217    /// Set a [1] i32 device counter IN PLACE (keeps the buffer pointer stable — required for the
4218    /// graph-resident pos/seqlen counters whose addresses are baked into captured graphs). Restores
4219    /// the counter value after the throwaway capture warmups corrupt it.
4220    /// ASYNC i32 single-slot store (value rides the kernel arg — no host-memory transfer/sync).
4221    /// The graph-arc device-len counters use this; set_i32_one below is the SYNCING pageable
4222    /// copy (fine at stream-idle boundaries, poison mid-round).
4223    pub fn i32_set_k(&self, dst: &mut CudaSlice<i32>, v: i32)
4224                     -> Result<(), Box<dyn std::error::Error>> {
4225        let f = self.func("i32_set_k");
4226        let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (1, 1, 1), shared_mem_bytes: 0 };
4227        let idx = 0i32;
4228        let __s_b = self.gpu.stream();
4229        let mut b = __s_b.launch_builder(&f);
4230        b.arg(dst).arg(&v).arg(&idx);
4231        unsafe { b.launch(cfg)?; }
4232        Ok(())
4233    }
4234
4235    pub fn set_i32_one(&self, d: &mut CudaSlice<i32>, v: i32) -> Result<(), Box<dyn std::error::Error>> {
4236        self.gpu.stream().memcpy_htod(&[v], d)?;
4237        Ok(())
4238    }
4239    /// Set a [1] u32 device buffer IN PLACE (stable pointer) — for the resident `token_d` counter
4240    /// during priming / capture-state restore.
4241    pub fn set_u32_one(&self, d: &mut CudaSlice<u32>, v: u32) -> Result<(), Box<dyn std::error::Error>> {
4242        self.gpu.stream().memcpy_htod(&[v], d)?;
4243        Ok(())
4244    }
4245    /// Read back a [1] u32 device buffer (the argmax token). One tiny D2H + sync.
4246    pub fn dtoh_u32_one(&self, d: &CudaSlice<u32>) -> Result<u32, Box<dyn std::error::Error>> {
4247        let v = self.gpu.stream().clone_dtoh(d)?;
4248        self.gpu.stream().synchronize()?;
4249        Ok(v[0])
4250    }
4251    /// Upload raw bytes to a resident device u8 buffer (e.g. the embed table for device gather).
4252    pub fn upload_u8(&self, bytes: &[u8]) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
4253        Ok(self.gpu.stream().clone_htod(bytes)?)
4254    }
4255    /// Embed-from-device (CUDA-GRAPH-PLAN Phase 1): gather+dequant the row for the token id in
4256    /// `token_d[0]` from the resident embed table `embd` -> x_out[n_embd]. Bit-identical to host
4257    /// EmbedHost::gather (same per-dtype `deq`). No host round-trip of the token id.
4258    pub fn embed_gather_device(&self, embd: &CudaSlice<u8>, token_d: &CudaSlice<u32>,
4259                               n_embd: usize, qtype: i32, row_bytes: usize)
4260                               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4261        let f = self.func("embed_gather_u32");
4262        let mut x = self.alloc_uninit::<f32>(n_embd)?;
4263        let cfg = LaunchConfig { grid_dim: (((n_embd as u32 + 255) / 256).max(1), 1, 1),
4264                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4265        let (ne, qt, rb) = (n_embd as i32, qtype, row_bytes as i64);
4266        let __s_b = self.gpu.stream();
4267        let mut b = __s_b.launch_builder(&f);
4268        b.arg(embd).arg(token_d).arg(&mut x).arg(&ne).arg(&qt).arg(&rb);
4269        unsafe { b.launch(cfg)?; }
4270        Ok(x)
4271    }
4272
4273
4274    /// T-token device embed gather (spec verify/replay): tokens uploaded as a tiny [T] u32 htod,
4275    /// rows dequanted on-device -> x[T, n_embd]. Replaces host per-row dequant + T*n_embd*4B htod
4276    /// (nsys: 84% of spec API time was HtoD). Bit-identical rows (same per-dtype deq).
4277    pub fn embed_gather_device_t(&self, embd: &CudaSlice<u8>, tokens: &[u32],
4278                                 n_embd: usize, qtype: i32, row_bytes: usize)
4279                                 -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4280        let t = tokens.len();
4281        let tok_d = self.gpu.stream().clone_htod(tokens)?;
4282        let f = self.func("embed_gather_u32_t");
4283        let mut x = self.alloc_uninit::<f32>(t * n_embd)?;
4284        let cfg = LaunchConfig { grid_dim: (((n_embd as u32 + 255) / 256).max(1), t as u32, 1),
4285                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4286        let (ne, qt, rb, ti) = (n_embd as i32, qtype, row_bytes as i64, t as i32);
4287        let __s_b = self.gpu.stream();
4288        let mut b = __s_b.launch_builder(&f);
4289        b.arg(embd).arg(&tok_d).arg(&mut x).arg(&ne).arg(&qt).arg(&rb).arg(&ti);
4290        unsafe { b.launch(cfg)?; }
4291        Ok(x)
4292    }
4293
4294    /// T-token embed gather from a DEVICE token buffer (round-stream stage c: the verify tokens
4295    /// are assembled on-device from the draft-chain pack slots; no host round trip). Same kernel
4296    /// as embed_gather_device_t — bit-identical rows.
4297    /// embed_gather over a token VIEW (spec round: tokens live in the round's batch buffer).
4298    pub fn embed_gather_device_tv(&self, embd: &CudaSlice<u8>, tok_v: &cudarc::driver::CudaView<u32>,
4299                                  t: usize, n_embd: usize, qtype: i32, row_bytes: usize)
4300                                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4301        let f = self.func("embed_gather_u32_t");
4302        let mut x = self.alloc_uninit::<f32>(t * n_embd)?;
4303        let cfg = LaunchConfig { grid_dim: (((n_embd as u32 + 255) / 256).max(1), t as u32, 1),
4304                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4305        let (ne, qt, rb, ti) = (n_embd as i32, qtype, row_bytes as i64, t as i32);
4306        let __s_b = self.gpu.stream();
4307        let mut b = __s_b.launch_builder(&f);
4308        b.arg(embd).arg(tok_v).arg(&mut x).arg(&ne).arg(&qt).arg(&rb).arg(&ti);
4309        unsafe { b.launch(cfg)?; }
4310        Ok(x)
4311    }
4312
4313    pub fn embed_gather_device_td(&self, embd: &CudaSlice<u8>, tok_d: &CudaSlice<u32>, t: usize,
4314                                  n_embd: usize, qtype: i32, row_bytes: usize)
4315                                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4316        let f = self.func("embed_gather_u32_t");
4317        let mut x = self.alloc_uninit::<f32>(t * n_embd)?;
4318        let cfg = LaunchConfig { grid_dim: (((n_embd as u32 + 255) / 256).max(1), t as u32, 1),
4319                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
4320        let (ne, qt, rb, ti) = (n_embd as i32, qtype, row_bytes as i64, t as i32);
4321        let __s_b = self.gpu.stream();
4322        let mut b = __s_b.launch_builder(&f);
4323        b.arg(embd).arg(tok_d).arg(&mut x).arg(&ne).arg(&qt).arg(&rb).arg(&ti);
4324        unsafe { b.launch(cfg)?; }
4325        Ok(x)
4326    }
4327
4328    /// Uninitialized device buffer — SKIPS the memset that `alloc_zeros` always issues. Decode
4329    /// profile (nsys): ~1050 memsets/token = 6.5% of decode GPU time + ~half the launch count, the
4330    /// dominant contributor to the 19% inter-kernel idle gap and a blocker for clean CUDA-graph
4331    /// capture. Use ONLY for buffers a kernel FULLY overwrites (every element written, no `+=`).
4332    /// SAFETY: caller guarantees the producing kernel writes every element before any read.
4333    #[inline]
4334    /// Keep an allocation alive for the current capture (no-op when retain mode is off).
4335    fn keep_if_capturing<T: cudarc::driver::DeviceRepr + Send + 'static>(&self, s: &CudaSlice<T>) {
4336        if self.capture_keep_on.load(std::sync::atomic::Ordering::Relaxed) {
4337            self.capture_keep.lock().unwrap().push(Box::new(s.clone()));
4338        }
4339    }
4340
4341    fn alloc_uninit<T: cudarc::driver::DeviceRepr + Send + 'static>(&self, n: usize)
4342            -> Result<CudaSlice<T>, Box<dyn std::error::Error>> {
4343        let mut s = unsafe { self.gpu.stream().alloc::<T>(n)? };
4344        // MEMRA_DEBUG_ZERO_ALLOCS=1 (task #14 defect hunt): memset EVERY engine allocation —
4345        // the global uninit-read discriminator (the prime-fn-scoped zeroing experiment could
4346        // not cover engine-internal buffers). Debug-only: massive launch overhead.
4347        {
4348            static Z: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4349            if *Z.get_or_init(|| std::env::var("MEMRA_DEBUG_ZERO_ALLOCS").as_deref() == Ok("1")) {
4350                // raw D8 memset (T lacks ValidAsZeroBits in the generic bound)
4351                use cudarc::driver::DevicePtrMut;
4352                let n_bytes = s.len() * std::mem::size_of::<T>();
4353                let stream = self.gpu.stream();
4354                let (p_, _g) = s.device_ptr_mut(&stream);
4355                unsafe {
4356                    cudarc::driver::sys::cuMemsetD8Async(p_, 0, n_bytes, stream.cu_stream())
4357                        .result()?;
4358                }
4359            }
4360        }
4361        self.keep_if_capturing(&s);
4362        Ok(s)
4363    }
4364
4365    /// Public f32 uninitialized scratch (see `alloc_uninit`). For decode/forward scratch a kernel
4366    /// fully overwrites. SAFETY: producing kernel must write every element before any read.
4367    /// Uninitialized q8_1 activation pair (int8 + per-32 scales) — the fa combine q8-emit
4368    /// consumers alloc through this (m=1 decode arms).
4369    pub fn uninit_q8_pair(&self, n: usize)
4370        -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4371        Ok((self.alloc_uninit::<i8>(n)?, self.alloc_uninit::<f32>(n / 32)?))
4372    }
4373
4374    pub fn uninit(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4375        self.alloc_uninit::<f32>(n)
4376    }
4377
4378    /// i8 uninitialized scratch (same contract as `uninit`).
4379    pub fn alloc_i8_uninit(&self, n: usize) -> Result<CudaSlice<i8>, Box<dyn std::error::Error>> {
4380        self.alloc_uninit::<i8>(n)
4381    }
4382
4383    /// RMSNorm: x[ncols,nrows] row-major, weight[ncols] -> dst. One block/row, 256 threads.
4384    /// gemma4: 3 rms_norms of the SAME input in one launch (one reduction, three weights).
4385    /// Per-output bit-identical to three rms_norm calls (verbatim reduction/scale chain).
4386    #[allow(clippy::too_many_arguments)]
4387    pub fn rms_norm3(&self, x: &CudaSlice<f32>, w0: &CudaSlice<f32>, w1: &CudaSlice<f32>,
4388                     w2: &CudaSlice<f32>, d0: &mut CudaSlice<f32>, d1: &mut CudaSlice<f32>,
4389                     d2: &mut CudaSlice<f32>, ncols: usize, nrows: usize, eps: f32)
4390                     -> Result<(), Box<dyn std::error::Error>> {
4391        let f = self.func("rms_norm3_f32");
4392        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4393        let (nc, e) = (ncols as i32, eps);
4394        let __s_b = self.gpu.stream();
4395        let mut b = __s_b.launch_builder(&f);
4396        b.arg(x).arg(w0).arg(w1).arg(w2).arg(d0).arg(d1).arg(d2).arg(&nc).arg(&e);
4397        unsafe { b.launch(cfg)?; }
4398        Ok(())
4399    }
4400
4401    /// gemma4 fused q/k/v head norms (one launch, per-row rms_norm_f32-verbatim).
4402    #[allow(clippy::too_many_arguments)]
4403    /// True when the warp-per-row qkv norm would engage for (rows, ncols) — the emit lane
4404    /// piggybacks on the same conditions.
4405    pub fn qkvnorm_w_on_prefill(rows: usize, ncols: usize) -> bool {
4406        static WARP_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4407        *WARP_ON.get_or_init(|| {
4408            std::env::var("MEMRA_QKVNORM_W").map(|v| v != "0").unwrap_or(true)
4409        }) && ncols % 4 == 0 && rows >= 64
4410    }
4411
4412    /// w4 norm with bf16 V EMIT (31B glue lane): the v segment also writes its normed rows as
4413    /// bf16 (the FA V operand — bit-identical to a post-hoc f32_to_bf16). Prefill-depth only.
4414    #[allow(clippy::too_many_arguments)]
4415    pub fn rms_norm_qkv_w4b(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
4416                        wq: &CudaSlice<f32>, wk: &CudaSlice<f32>, wv: &CudaSlice<f32>,
4417                        dq: &mut CudaSlice<f32>, dk: &mut CudaSlice<f32>, dv: &mut CudaSlice<f32>,
4418                        dvb: &mut CudaSlice<u8>,
4419                        ncols: usize, rq: usize, rk: usize, eps: f32, vf16: bool)
4420                        -> Result<(), Box<dyn std::error::Error>> {
4421        assert!(ncols % 4 == 0 && rq + 2 * rk >= 64);
4422        let f = self.func("rms_norm_qkv_w4b_f32");
4423        let rows = (rq + 2 * rk) as u32;
4424        let cfg = LaunchConfig {
4425            grid_dim: (rows.div_ceil(8), 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0,
4426        };
4427        let (nc, rqi, rki, rvi, e) = (ncols as i32, rq as i32, rk as i32, rk as i32, eps);
4428        let vf = vf16 as i32;
4429        let __s_b = self.gpu.stream();
4430        let mut b = __s_b.launch_builder(&f);
4431        b.arg(q).arg(k).arg(v).arg(wq).arg(wk).arg(wv).arg(dq).arg(dk).arg(dv).arg(&mut *dvb)
4432         .arg(&nc).arg(&rqi).arg(&rki).arg(&rvi).arg(&e).arg(&vf);
4433        unsafe { b.launch(cfg)?; }
4434        Ok(())
4435    }
4436
4437    pub fn rms_norm_qkv(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
4438                        wq: &CudaSlice<f32>, wk: &CudaSlice<f32>, wv: &CudaSlice<f32>,
4439                        dq: &mut CudaSlice<f32>, dk: &mut CudaSlice<f32>, dv: &mut CudaSlice<f32>,
4440                        ncols: usize, rq: usize, rk: usize, eps: f32)
4441                        -> Result<(), Box<dyn std::error::Error>> {
4442        // Warp-per-row float4 twin (default; MEMRA_QKVNORM_W=0 reverts): the block-per-row form
4443        // spends 767us/launch on 17k+ 2KB rows at prefill depth (launch/reduce latency-bound,
4444        // ~92GB/s). Own numeric config (reduce order differs) — battery-gated.
4445        static WARP_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4446        let warp_on = *WARP_ON.get_or_init(|| {
4447            std::env::var("MEMRA_QKVNORM_W").map(|v| v != "0").unwrap_or(true)
4448        });
4449        // rows >= 64 keeps decode (nh + 2*nkv rows) on the block-tree kernel — decode/verify/
4450        // replay numerics are untouched on every model; only prefill depth takes the new config.
4451        if warp_on && ncols % 4 == 0 && rq + 2 * rk >= 64 {
4452            let f = self.func("rms_norm_qkv_w4_f32");
4453            let rows = (rq + 2 * rk) as u32;
4454            let cfg = LaunchConfig {
4455                grid_dim: (rows.div_ceil(8), 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0,
4456            };
4457            let (nc, rqi, rki, rvi, e) = (ncols as i32, rq as i32, rk as i32, rk as i32, eps);
4458            let __s_b = self.gpu.stream();
4459            let mut b = __s_b.launch_builder(&f);
4460            b.arg(q).arg(k).arg(v).arg(wq).arg(wk).arg(wv).arg(dq).arg(dk).arg(dv)
4461             .arg(&nc).arg(&rqi).arg(&rki).arg(&rvi).arg(&e);
4462            unsafe { b.launch(cfg)?; }
4463            return Ok(());
4464        }
4465        let f = self.func("rms_norm_qkv_f32");
4466        let grid = (rq + 2 * rk) as u32;
4467        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4468        let (nc, rqi, rki, e) = (ncols as i32, rq as i32, rk as i32, eps);
4469        let __s_b = self.gpu.stream();
4470        let mut b = __s_b.launch_builder(&f);
4471        b.arg(q).arg(k).arg(v).arg(wq).arg(wk).arg(wv).arg(dq).arg(dk).arg(dv)
4472         .arg(&nc).arg(&rqi).arg(&rki).arg(&e);
4473        unsafe { b.launch(cfg)?; }
4474        Ok(())
4475    }
4476
4477    /// gemma4 fused pair of rms_norms over two different inputs (same width).
4478    #[allow(clippy::too_many_arguments)]
4479    pub fn rms_norm2x(&self, a: &CudaSlice<f32>, bb: &CudaSlice<f32>, wa: &CudaSlice<f32>,
4480                      wb: &CudaSlice<f32>, da: &mut CudaSlice<f32>, db: &mut CudaSlice<f32>,
4481                      ncols: usize, nrows: usize, eps: f32)
4482                      -> Result<(), Box<dyn std::error::Error>> {
4483        let f = self.func("rms_norm2x_f32");
4484        let cfg = LaunchConfig { grid_dim: (2 * nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4485        let (nc, nr, e) = (ncols as i32, nrows as i32, eps);
4486        let __s_b = self.gpu.stream();
4487        let mut b = __s_b.launch_builder(&f);
4488        b.arg(a).arg(bb).arg(wa).arg(wb).arg(da).arg(db).arg(&nc).arg(&nr).arg(&e);
4489        unsafe { b.launch(cfg)?; }
4490        Ok(())
4491    }
4492
4493    /// gemma4 R4: in-place final-logit softcap y = cap*tanh(y/cap).
4494    pub fn softcap(&self, y: &mut CudaSlice<f32>, cap: f32, n: usize)
4495                   -> Result<(), Box<dyn std::error::Error>> {
4496        let f = self.func("softcap_f32");
4497        let cfg = LaunchConfig::for_num_elems(n as u32);
4498        let ni = n as i32;
4499        let __s_b = self.gpu.stream();
4500        let mut b = __s_b.launch_builder(&f);
4501        b.arg(y).arg(&cap).arg(&ni);
4502        unsafe { b.launch(cfg)?; }
4503        Ok(())
4504    }
4505
4506    /// gemma4 suppress-token mask: y[row][ids[j]] = -inf over t logits rows (fixed-arg launch —
4507    /// graph-capture safe; NOT monotonic like softcap, so it must run before any argmax).
4508    pub fn mask_ids_rows(&self, y: &mut CudaSlice<f32>, ids: &CudaSlice<i32>, n_ids: usize,
4509                         n_vocab: usize, t: usize)
4510                         -> Result<(), Box<dyn std::error::Error>> {
4511        let f = self.func("mask_ids_rows_f32");
4512        let cfg = LaunchConfig::for_num_elems((n_ids * t) as u32);
4513        let (ni, nv, ti) = (n_ids as i32, n_vocab as i32, t as i32);
4514        let __s_b = self.gpu.stream();
4515        let mut b = __s_b.launch_builder(&f);
4516        b.arg(y).arg(ids).arg(&ni).arg(&nv).arg(&ti);
4517        unsafe { b.launch(cfg)?; }
4518        Ok(())
4519    }
4520
4521    /// gemma4: res = (a+b)*c AND dst = rms_norm(res, w) in one launch.
4522    #[allow(clippy::too_many_arguments)]
4523    pub fn add_scale_rms_norm(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, c: f32,
4524                              w: &CudaSlice<f32>, res: &mut CudaSlice<f32>, dst: &mut CudaSlice<f32>,
4525                              ncols: usize, nrows: usize, eps: f32)
4526                              -> Result<(), Box<dyn std::error::Error>> {
4527        let f = self.func("add_scale_rms_norm_f32");
4528        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4529        let (nc, e2) = (ncols as i32, eps);
4530        let __s_b = self.gpu.stream();
4531        let mut b = __s_b.launch_builder(&f);
4532        b.arg(a).arg(b_in).arg(&c).arg(w).arg(res).arg(dst).arg(&nc).arg(&e2);
4533        unsafe { b.launch(cfg)?; }
4534        Ok(())
4535    }
4536
4537    /// gemma4: res = (a+b)*c AND the next layer's attn_norm EMITTED q8_1 in one launch.
4538    /// Quantize epilogue bit-identical to quantize_q8_1 (the rms_norm_q8_1 form).
4539    #[allow(clippy::too_many_arguments)]
4540    pub fn add_scale_rms_norm_q8_1(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, c: f32,
4541                                   w: &CudaSlice<f32>, res: &mut CudaSlice<f32>,
4542                                   ncols: usize, nrows: usize, eps: f32)
4543                                   -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4544        let mut out_q = self.alloc_uninit::<i8>(nrows * ncols)?;
4545        let mut out_d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
4546        let (nc, e2) = (ncols as i32, eps);
4547        if Self::pdl_on() && Self::pdl_wb_on() {
4548            {
4549            use cudarc::driver::{DevicePtr, DevicePtrMut};
4550            let s = &self.gpu.stream();
4551            let (pa, _g0) = a.device_ptr(s); let (pb, _g1) = b_in.device_ptr(s);
4552            let (pw, _g2) = w.device_ptr(s); let (pr, _g3) = res.device_ptr_mut(s);
4553            let (pq, _g4) = out_q.device_ptr_mut(s); let (pd, _g5) = out_d.device_ptr_mut(s);
4554            let mut ps = [
4555                &pa as *const _ as *mut std::ffi::c_void, &pb as *const _ as *mut _,
4556                &c as *const _ as *mut _, &pw as *const _ as *mut _,
4557                &pr as *const _ as *mut _, &pq as *const _ as *mut _,
4558                &pd as *const _ as *mut _, &nc as *const _ as *mut _,
4559                &e2 as *const _ as *mut _,
4560            ];
4561            unsafe { self.launch_pdl("add_scale_rms_norm_q8_1", (nrows as u32, 1, 1),
4562                                     (rms_block(), 1, 1), &mut ps)?; }
4563            }
4564            return Ok((out_q, out_d));
4565        }
4566        let f = self.func("add_scale_rms_norm_q8_1");
4567        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4568        let __s_b = self.gpu.stream();
4569        let mut b = __s_b.launch_builder(&f);
4570        b.arg(a).arg(b_in).arg(&c).arg(w).arg(res).arg(&mut out_q).arg(&mut out_d).arg(&nc).arg(&e2);
4571        unsafe { b.launch(cfg)?; }
4572        Ok((out_q, out_d))
4573    }
4574
4575    /// Slot-fed add_scale_rms_norm_q8_1 twin (alloc-free capture lane).
4576    #[allow(clippy::too_many_arguments)]
4577    pub fn add_scale_rms_norm_q8_1_into(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, c: f32,
4578                                        w: &CudaSlice<f32>, res: &mut CudaSlice<f32>,
4579                                        ncols: usize, nrows: usize, eps: f32,
4580                                        out_q: &mut CudaSlice<i8>, out_d: &mut CudaSlice<f32>)
4581                                        -> Result<(), Box<dyn std::error::Error>> {
4582        debug_assert!(out_q.len() >= nrows * ncols && out_d.len() >= nrows * (ncols / 32));
4583        let (nc, e2) = (ncols as i32, eps);
4584        if Self::pdl_on() && Self::pdl_wb_on() {
4585            use cudarc::driver::{DevicePtr, DevicePtrMut};
4586            let s = &self.gpu.stream();
4587            let (pa, _g0) = a.device_ptr(s); let (pb, _g1) = b_in.device_ptr(s);
4588            let (pw, _g2) = w.device_ptr(s); let (pr, _g3) = res.device_ptr_mut(s);
4589            let (pq, _g4) = out_q.device_ptr_mut(s); let (pd, _g5) = out_d.device_ptr_mut(s);
4590            let mut ps = [
4591                &pa as *const _ as *mut std::ffi::c_void, &pb as *const _ as *mut _,
4592                &c as *const _ as *mut _, &pw as *const _ as *mut _,
4593                &pr as *const _ as *mut _, &pq as *const _ as *mut _,
4594                &pd as *const _ as *mut _, &nc as *const _ as *mut _,
4595                &e2 as *const _ as *mut _,
4596            ];
4597            unsafe { self.launch_pdl("add_scale_rms_norm_q8_1", (nrows as u32, 1, 1),
4598                                     (rms_block(), 1, 1), &mut ps)?; }
4599            return Ok(());
4600        }
4601        let f = self.func("add_scale_rms_norm_q8_1");
4602        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4603        let __s_b = self.gpu.stream();
4604        let mut b = __s_b.launch_builder(&f);
4605        b.arg(a).arg(b_in).arg(&c).arg(w).arg(res).arg(&mut *out_q).arg(&mut *out_d).arg(&nc).arg(&e2);
4606        unsafe { b.launch(cfg)?; }
4607        Ok(())
4608    }
4609
4610    /// E4B glue fusion: rms(a, wa) prologue + the add_scale_rms_norm_q8_1 program — one launch
4611    /// replaces the per-layer rms_norm_f32(y) + emit pair in the PLE tail.
4612    #[allow(clippy::too_many_arguments)]
4613    pub fn rms_pre_add_scale_rms_norm_q8_1(&self, a: &CudaSlice<f32>, wa: &CudaSlice<f32>,
4614                                           b_in: &CudaSlice<f32>, c: f32,
4615                                           w: &CudaSlice<f32>, res: &mut CudaSlice<f32>,
4616                                           ncols: usize, nrows: usize, eps: f32)
4617                                           -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4618        let mut out_q = self.alloc_uninit::<i8>(nrows * ncols)?;
4619        let mut out_d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
4620        let (nc, e2) = (ncols as i32, eps);
4621        if Self::pdl_on() {
4622            {
4623            use cudarc::driver::{DevicePtr, DevicePtrMut};
4624            let s = &self.gpu.stream();
4625            let (pa, _g0) = a.device_ptr(s); let (pwa, _g1) = wa.device_ptr(s);
4626            let (pb, _g2) = b_in.device_ptr(s); let (pw, _g3) = w.device_ptr(s);
4627            let (pr, _g4) = res.device_ptr_mut(s);
4628            let (pq, _g5) = out_q.device_ptr_mut(s); let (pd, _g6) = out_d.device_ptr_mut(s);
4629            let mut ps = [
4630                &pa as *const _ as *mut std::ffi::c_void, &pwa as *const _ as *mut _,
4631                &pb as *const _ as *mut _, &c as *const _ as *mut _,
4632                &pw as *const _ as *mut _, &pr as *const _ as *mut _,
4633                &pq as *const _ as *mut _, &pd as *const _ as *mut _,
4634                &nc as *const _ as *mut _, &e2 as *const _ as *mut _,
4635            ];
4636            unsafe { self.launch_pdl("rms_pre_add_scale_rms_norm_q8_1", (nrows as u32, 1, 1),
4637                                     (rms_block(), 1, 1), &mut ps)?; }
4638            }
4639            return Ok((out_q, out_d));
4640        }
4641        let f = self.func("rms_pre_add_scale_rms_norm_q8_1");
4642        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4643        let __s_b = self.gpu.stream();
4644        let mut b = __s_b.launch_builder(&f);
4645        b.arg(a).arg(wa).arg(b_in).arg(&c).arg(w).arg(res).arg(&mut out_q).arg(&mut out_d).arg(&nc).arg(&e2);
4646        unsafe { b.launch(cfg)?; }
4647        Ok((out_q, out_d))
4648    }
4649
4650    /// GELU(tanh)*up with the activation emitted q8_1 alongside f32 (glue-fusion lane): the
4651    /// consumer matmul rides matmul_pre, killing its standalone quantize_q8_1 launch.
4652    pub fn gelu_tanh_mul_q8_1(&self, gate: &CudaSlice<f32>, up: &cudarc::driver::CudaView<f32>,
4653                              act: &mut CudaSlice<f32>, ncols: usize, nrows: usize)
4654                              -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4655        debug_assert!(ncols % 128 == 0);
4656        let mut out_q = self.alloc_uninit::<i8>(nrows * ncols)?;
4657        let mut out_d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
4658        let nc = ncols as i32;
4659        if Self::pdl_on() {
4660            {
4661            use cudarc::driver::{DevicePtr, DevicePtrMut};
4662            let s = &self.gpu.stream();
4663            let (pg, _g0) = gate.device_ptr(s); let (pu, _g1) = up.device_ptr(s);
4664            let (pact, _g2) = act.device_ptr_mut(s);
4665            let (pq, _g3) = out_q.device_ptr_mut(s); let (pd, _g4) = out_d.device_ptr_mut(s);
4666            let mut ps = [
4667                &pg as *const _ as *mut std::ffi::c_void, &pu as *const _ as *mut _,
4668                &pact as *const _ as *mut _, &pq as *const _ as *mut _,
4669                &pd as *const _ as *mut _, &nc as *const _ as *mut _,
4670            ];
4671            unsafe { self.launch_pdl("gelu_tanh_mul_q8_1", (nrows as u32, 1, 1),
4672                                     (rms_block(), 1, 1), &mut ps)?; }
4673            }
4674            return Ok((out_q, out_d));
4675        }
4676        let f = self.func("gelu_tanh_mul_q8_1");
4677        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4678        let __s_b = self.gpu.stream();
4679        let mut b = __s_b.launch_builder(&f);
4680        b.arg(gate).arg(up).arg(act).arg(&mut out_q).arg(&mut out_d).arg(&nc);
4681        unsafe { b.launch(cfg)?; }
4682        Ok((out_q, out_d))
4683    }
4684
4685    /// Slot-fed gelu_tanh_mul_q8_1 twin (alloc-free capture lane; incl. the PDL arm).
4686    #[allow(clippy::too_many_arguments)]
4687    pub fn gelu_tanh_mul_q8_1_into(&self, gate: &CudaSlice<f32>, up: &cudarc::driver::CudaView<f32>,
4688                                   act: &mut CudaSlice<f32>, ncols: usize, nrows: usize,
4689                                   out_q: &mut CudaSlice<i8>, out_d: &mut CudaSlice<f32>)
4690                                   -> Result<(), Box<dyn std::error::Error>> {
4691        debug_assert!(ncols % 128 == 0);
4692        debug_assert!(out_q.len() >= nrows * ncols && out_d.len() >= nrows * (ncols / 32));
4693        let nc = ncols as i32;
4694        if Self::pdl_on() {
4695            use cudarc::driver::{DevicePtr, DevicePtrMut};
4696            let s = &self.gpu.stream();
4697            let (pg, _g0) = gate.device_ptr(s); let (pu, _g1) = up.device_ptr(s);
4698            let (pact, _g2) = act.device_ptr_mut(s);
4699            let (pq, _g3) = out_q.device_ptr_mut(s); let (pd, _g4) = out_d.device_ptr_mut(s);
4700            let mut ps = [
4701                &pg as *const _ as *mut std::ffi::c_void, &pu as *const _ as *mut _,
4702                &pact as *const _ as *mut _, &pq as *const _ as *mut _,
4703                &pd as *const _ as *mut _, &nc as *const _ as *mut _,
4704            ];
4705            unsafe { self.launch_pdl("gelu_tanh_mul_q8_1", (nrows as u32, 1, 1),
4706                                     (rms_block(), 1, 1), &mut ps)?; }
4707            return Ok(());
4708        }
4709        let f = self.func("gelu_tanh_mul_q8_1");
4710        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4711        let __s_b = self.gpu.stream();
4712        let mut b = __s_b.launch_builder(&f);
4713        b.arg(gate).arg(up).arg(&mut *act).arg(&mut *out_q).arg(&mut *out_d).arg(&nc);
4714        unsafe { b.launch(cfg)?; }
4715        Ok(())
4716    }
4717
4718    /// gemma4: add + rms_norm3 with outputs 0/2 emitted q8_1 (zsh + moe_in) and 1 f32 (router).
4719    #[allow(clippy::too_many_arguments)]
4720    pub fn add_rms_norm3_q8z(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>,
4721                             w0: &CudaSlice<f32>, w1: &CudaSlice<f32>, w2: &CudaSlice<f32>,
4722                             res: &mut CudaSlice<f32>, out1: &mut CudaSlice<f32>,
4723                             ncols: usize, nrows: usize, eps: f32)
4724                             -> Result<((CudaSlice<i8>, CudaSlice<f32>), (CudaSlice<i8>, CudaSlice<f32>)), Box<dyn std::error::Error>> {
4725        let mut q0 = self.alloc_uninit::<i8>(nrows * ncols)?;
4726        let mut d0 = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
4727        let mut q2 = self.alloc_uninit::<i8>(nrows * ncols)?;
4728        let mut d2 = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
4729        let f = self.func("add_rms_norm3_q8z_f32");
4730        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4731        let (nc, e2) = (ncols as i32, eps);
4732        let __s_b = self.gpu.stream();
4733        let mut b = __s_b.launch_builder(&f);
4734        b.arg(a).arg(b_in).arg(w0).arg(w1).arg(w2).arg(res)
4735         .arg(&mut q0).arg(&mut d0).arg(out1).arg(&mut q2).arg(&mut d2).arg(&nc).arg(&e2);
4736        unsafe { b.launch(cfg)?; }
4737        Ok(((q0, d0), (q2, d2)))
4738    }
4739
4740    /// gemma4: res = a+b AND the three rms_norms of res in one launch.
4741    #[allow(clippy::too_many_arguments)]
4742    pub fn add_rms_norm3(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>,
4743                         w0: &CudaSlice<f32>, w1: &CudaSlice<f32>, w2: &CudaSlice<f32>,
4744                         res: &mut CudaSlice<f32>, d0: &mut CudaSlice<f32>, d1: &mut CudaSlice<f32>,
4745                         d2: &mut CudaSlice<f32>, ncols: usize, nrows: usize, eps: f32)
4746                         -> Result<(), Box<dyn std::error::Error>> {
4747        let f = self.func("add_rms_norm3_f32");
4748        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4749        let (nc, e2) = (ncols as i32, eps);
4750        let __s_b = self.gpu.stream();
4751        let mut b = __s_b.launch_builder(&f);
4752        b.arg(a).arg(b_in).arg(w0).arg(w1).arg(w2).arg(res).arg(d0).arg(d1).arg(d2).arg(&nc).arg(&e2);
4753        unsafe { b.launch(cfg)?; }
4754        Ok(())
4755    }
4756
4757    /// dst = (a + b) * c (residual add + layer scale, one launch).
4758    pub fn add_scale(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, c: f32,
4759                     dst: &mut CudaSlice<f32>, n: usize) -> Result<(), Box<dyn std::error::Error>> {
4760        let f = self.func("add_scale_f32");
4761        let cfg = LaunchConfig::for_num_elems(n as u32);
4762        let ni = n as i32;
4763        let __s_b = self.gpu.stream();
4764        let mut b = __s_b.launch_builder(&f);
4765        b.arg(a).arg(b_in).arg(&c).arg(dst).arg(&ni);
4766        unsafe { b.launch(cfg)?; }
4767        Ok(())
4768    }
4769
4770    pub fn rms_norm(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, dst: &mut CudaSlice<f32>,
4771                    ncols: usize, nrows: usize, eps: f32) -> Result<(), Box<dyn std::error::Error>> {
4772        let (nc, e) = (ncols as i32, eps);
4773        if Self::pdl_on() && Self::pdl_wb_on() {
4774            use cudarc::driver::{DevicePtr, DevicePtrMut};
4775            let s = &self.gpu.stream();
4776            let (px, _g0) = x.device_ptr(s); let (pw, _g1) = w.device_ptr(s);
4777            let (pd, _g2) = dst.device_ptr_mut(s);
4778            let mut ps = [
4779                &px as *const _ as *mut std::ffi::c_void, &pw as *const _ as *mut _,
4780                &pd as *const _ as *mut _, &nc as *const _ as *mut _,
4781                &e as *const _ as *mut _,
4782            ];
4783            unsafe { self.launch_pdl("rms_norm_f32", (nrows as u32, 1, 1),
4784                                     (rms_block(), 1, 1), &mut ps)?; }
4785            return Ok(());
4786        }
4787        let f = self.func("rms_norm_f32");
4788        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4789        let __s_b = self.gpu.stream();
4790        let mut b = __s_b.launch_builder(&f);
4791        b.arg(x).arg(w).arg(dst).arg(&nc).arg(&e);
4792        unsafe { b.launch(cfg)?; }
4793        Ok(())
4794    }
4795
4796    /// RMS-norm with blockDim=1024 — BIT-IDENTICAL to the fused `rms_norm_q8_1` and
4797    /// `add_rms_norm_q8_1` kernels' sum-of-squares reduction. The spec verify path MUST use this
4798    /// to match decode's FP accumulation order: the standard `rms_norm` at blockDim=256 has a
4799    /// different per-thread stride (ncols/256 partials vs ncols/1024 partials) and therefore a
4800    /// different shfl-tree reduction that can shift `scale = rsqrt(sum/n + eps)` by ULPs, causing
4801    /// divergence through the GDN scan and argmax flips on the 9B text prompt. The underlying
4802    /// `rms_norm_f32` kernel supports any blockDim (generic reduce with shared[32]).
4803    pub fn rms_norm_decode(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, dst: &mut CudaSlice<f32>,
4804                           ncols: usize, nrows: usize, eps: f32) -> Result<(), Box<dyn std::error::Error>> {
4805        let f = self.func("rms_norm_f32");
4806        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (1024, 1, 1), shared_mem_bytes: 0 };
4807        let (nc, e) = (ncols as i32, eps);
4808        let __s_b = self.gpu.stream();
4809        let mut b = __s_b.launch_builder(&f);
4810        b.arg(x).arg(w).arg(dst).arg(&nc).arg(&e);
4811        unsafe { b.launch(cfg)?; }
4812        Ok(())
4813    }
4814
4815    /// DECODE GLUE-FUSION LEVER: `z = rms_norm(x)*w` emitted DIRECTLY as q8_1 (no f32 `z` materialized,
4816    /// no standalone quantize_q8_1 launch). Returns (out_q [nrows*ncols i8], out_d [nrows*nblk f32])
4817    /// ready to feed matmul_pre. BIT-IDENTICAL to rms_norm + quantize_q8_1. ncols % 32 == 0.
4818    pub fn rms_norm_q8_1(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, ncols: usize, nrows: usize,
4819                         eps: f32) -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4820        let nblk = ncols / 32;
4821        let mut q = self.alloc_uninit::<i8>(nrows * ncols)?;
4822        let mut d = self.alloc_uninit::<f32>(nrows * nblk)?;
4823        let (nc, e) = (ncols as i32, eps);
4824        if Self::pdl_on() {
4825            {
4826            use cudarc::driver::{DevicePtr, DevicePtrMut};
4827            let s = &self.gpu.stream();
4828            let (px, _g0) = x.device_ptr(s); let (pw, _g1) = w.device_ptr(s);
4829            let (pq, _g2) = q.device_ptr_mut(s); let (pd, _g3) = d.device_ptr_mut(s);
4830            let mut ps = [
4831                &px as *const _ as *mut std::ffi::c_void, &pw as *const _ as *mut _,
4832                &pq as *const _ as *mut _, &pd as *const _ as *mut _,
4833                &nc as *const _ as *mut _, &e as *const _ as *mut _,
4834            ];
4835            unsafe { self.launch_pdl("rms_norm_q8_1", (nrows as u32, 1, 1), (1024, 1, 1),
4836                                     &mut ps)?; }
4837            }
4838            return Ok((q, d));
4839        }
4840        let f = self.func("rms_norm_q8_1");
4841        // 1024 threads: decode is nrows=1 -> ONE CTA; 32 warps hide the pass1->pass2 latency
4842        // (s[32] reduce already sized for 32 warps). Same shape math at any blockDim.
4843        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (1024, 1, 1), shared_mem_bytes: 0 };
4844        let __s_b = self.gpu.stream();
4845        let mut b = __s_b.launch_builder(&f);
4846        b.arg(x).arg(w).arg(&mut q).arg(&mut d).arg(&nc).arg(&e);
4847        unsafe { b.launch(cfg)?; }
4848        Ok((q, d))
4849    }
4850
4851    /// Slot-fed rms_norm_q8_1 twin (alloc-free capture lane): identical launch (incl. the
4852    /// PDL arm), caller-owned outputs.
4853    pub fn rms_norm_q8_1_into(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, ncols: usize,
4854                              nrows: usize, eps: f32,
4855                              q: &mut CudaSlice<i8>, d: &mut CudaSlice<f32>)
4856                              -> Result<(), Box<dyn std::error::Error>> {
4857        let nblk = ncols / 32;
4858        debug_assert!(q.len() >= nrows * ncols && d.len() >= nrows * nblk);
4859        let (nc, e) = (ncols as i32, eps);
4860        if Self::pdl_on() {
4861            use cudarc::driver::{DevicePtr, DevicePtrMut};
4862            let s = &self.gpu.stream();
4863            let (px, _g0) = x.device_ptr(s); let (pw, _g1) = w.device_ptr(s);
4864            let (pq, _g2) = q.device_ptr_mut(s); let (pd, _g3) = d.device_ptr_mut(s);
4865            let mut ps = [
4866                &px as *const _ as *mut std::ffi::c_void, &pw as *const _ as *mut _,
4867                &pq as *const _ as *mut _, &pd as *const _ as *mut _,
4868                &nc as *const _ as *mut _, &e as *const _ as *mut _,
4869            ];
4870            unsafe { self.launch_pdl("rms_norm_q8_1", (nrows as u32, 1, 1), (1024, 1, 1),
4871                                     &mut ps)?; }
4872            return Ok(());
4873        }
4874        let f = self.func("rms_norm_q8_1");
4875        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (1024, 1, 1), shared_mem_bytes: 0 };
4876        let __s_b = self.gpu.stream();
4877        let mut b = __s_b.launch_builder(&f);
4878        b.arg(x).arg(w).arg(&mut *q).arg(&mut *d).arg(&nc).arg(&e);
4879        unsafe { b.launch(cfg)?; }
4880        Ok(())
4881    }
4882
4883    /// Slot-fed quantize_q8_1 twin (alloc-free capture lane).
4884    pub fn quantize_q8_1_into(&self, x: &CudaSlice<f32>, m: usize, in_f: usize,
4885                              q: &mut CudaSlice<i8>, d: &mut CudaSlice<f32>)
4886                              -> Result<(), Box<dyn std::error::Error>> {
4887        let nblk = in_f / 32;
4888        debug_assert!(q.len() >= m * in_f && d.len() >= m * nblk);
4889        let cfg = LaunchConfig::for_num_elems((m * in_f) as u32);
4890        let (inf, mi) = (in_f as i32, m as i32);
4891        if Self::pdl_on() && Self::pdl_wb_on() {
4892            use cudarc::driver::{DevicePtr, DevicePtrMut};
4893            let s = &self.gpu.stream();
4894            let (px, _g0) = x.device_ptr(s);
4895            let (pq, _g1) = q.device_ptr_mut(s); let (pd, _g2) = d.device_ptr_mut(s);
4896            let mut ps = [
4897                &px as *const _ as *mut std::ffi::c_void, &pq as *const _ as *mut _,
4898                &pd as *const _ as *mut _, &inf as *const _ as *mut _,
4899                &mi as *const _ as *mut _,
4900            ];
4901            unsafe { self.launch_pdl("quantize_q8_1", cfg.grid_dim, cfg.block_dim, &mut ps)?; }
4902            return Ok(());
4903        }
4904        let f = self.func("quantize_q8_1");
4905        let __s_b = self.gpu.stream();
4906        let mut b = __s_b.launch_builder(&f);
4907        b.arg(x).arg(&mut *q).arg(&mut *d).arg(&inf).arg(&mi);
4908        unsafe { b.launch(cfg)?; }
4909        Ok(())
4910    }
4911
4912    /// DECODE GLUE-FUSION LEVER: `res = a+b; z = rms_norm(res)*w` with z emitted as q8_1. `res` is
4913    /// still written (the post-ffn residual add reads it). Fuses add_rms_norm + quantize_q8_1.
4914    /// Returns (out_q, out_d) for matmul_pre. BIT-IDENTICAL. ncols % 32 == 0.
4915    pub fn add_rms_norm_q8_1(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, w: &CudaSlice<f32>,
4916                             res: &mut CudaSlice<f32>, ncols: usize, nrows: usize, eps: f32)
4917                             -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4918        let nblk = ncols / 32;
4919        let mut q = self.alloc_uninit::<i8>(nrows * ncols)?;
4920        let mut d = self.alloc_uninit::<f32>(nrows * nblk)?;
4921        let f = self.func("add_rms_norm_q8_1");
4922        // 1024 threads: same single-CTA-at-decode reasoning as rms_norm_q8_1.
4923        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (1024, 1, 1), shared_mem_bytes: 0 };
4924        let (nc, e) = (ncols as i32, eps);
4925        let __s_bld = self.gpu.stream();
4926        let mut bld = __s_bld.launch_builder(&f);
4927        bld.arg(a).arg(b_in).arg(w).arg(res).arg(&mut q).arg(&mut d).arg(&nc).arg(&e);
4928        unsafe { bld.launch(cfg)?; }
4929        Ok((q, d))
4930    }
4931
4932    /// RANK3 LEVER (add+rmsnorm fuse): `res = a + b; dst = rms_norm(res) * w` in ONE launch. Fuses
4933    /// e.add(a,b,res) + e.rms_norm(res,w,dst), removing one launch + one HBM read of the residual per
4934    /// residual+norm pair. BIT-IDENTICAL to the two-kernel sequence (same IEEE add, same reduction).
4935    pub fn add_rms_norm(&self, a: &CudaSlice<f32>, b: &CudaSlice<f32>, w: &CudaSlice<f32>,
4936                        res: &mut CudaSlice<f32>, dst: &mut CudaSlice<f32>, ncols: usize, nrows: usize,
4937                        eps: f32) -> Result<(), Box<dyn std::error::Error>> {
4938        let (nc, e) = (ncols as i32, eps);
4939        if Self::pdl_on() && Self::pdl_wb_on() {
4940            use cudarc::driver::{DevicePtr, DevicePtrMut};
4941            let s = &self.gpu.stream();
4942            let (pa, _g0) = a.device_ptr(s); let (pb, _g1) = b.device_ptr(s);
4943            let (pw, _g2) = w.device_ptr(s);
4944            let (pr, _g3) = res.device_ptr_mut(s); let (pd, _g4) = dst.device_ptr_mut(s);
4945            let mut ps = [
4946                &pa as *const _ as *mut std::ffi::c_void, &pb as *const _ as *mut _,
4947                &pw as *const _ as *mut _, &pr as *const _ as *mut _,
4948                &pd as *const _ as *mut _, &nc as *const _ as *mut _,
4949                &e as *const _ as *mut _,
4950            ];
4951            unsafe { self.launch_pdl("add_rms_norm_f32", (nrows as u32, 1, 1),
4952                                     (rms_block(), 1, 1), &mut ps)?; }
4953            return Ok(());
4954        }
4955        let f = self.func("add_rms_norm_f32");
4956        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4957        let __s_b2 = self.gpu.stream();
4958        let mut b2 = __s_b2.launch_builder(&f);
4959        b2.arg(a).arg(b).arg(w).arg(&mut *res).arg(&mut *dst).arg(&nc).arg(&e);
4960        unsafe { b2.launch(cfg)?; }
4961        Ok(())
4962    }
4963
4964    /// E4B glue fusion: rms(a, wa) prologue + add_rms_norm — folds the post-attn norm into
4965    /// the tail entry (res = rms(a)*wa + b; dst = rms(res)*w).
4966    #[allow(clippy::too_many_arguments)]
4967    pub fn rms_pre_add_rms_norm(&self, a: &CudaSlice<f32>, wa: &CudaSlice<f32>,
4968                                b: &CudaSlice<f32>, w: &CudaSlice<f32>,
4969                                res: &mut CudaSlice<f32>, dst: &mut CudaSlice<f32>,
4970                                ncols: usize, nrows: usize, eps: f32)
4971                                -> Result<(), Box<dyn std::error::Error>> {
4972        let f = self.func("rms_pre_add_rms_norm_f32");
4973        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
4974        let (nc, e) = (ncols as i32, eps);
4975        let __s_b2 = self.gpu.stream();
4976        let mut b2 = __s_b2.launch_builder(&f);
4977        b2.arg(a).arg(wa).arg(b).arg(w).arg(&mut *res).arg(&mut *dst).arg(&nc).arg(&e);
4978        unsafe { b2.launch(cfg)?; }
4979        Ok(())
4980    }
4981
4982    /// wave-2 fold: rms(a,wa) + add + ffn-norm with zsh EMITTED q8_1 (fused2 consumes it).
4983    #[allow(clippy::too_many_arguments)]
4984    pub fn rms_pre_add_rms_norm_q8z(&self, a: &CudaSlice<f32>, wa: &CudaSlice<f32>,
4985                                    b: &CudaSlice<f32>, w: &CudaSlice<f32>,
4986                                    res: &mut CudaSlice<f32>, dst: &mut CudaSlice<f32>,
4987                                    ncols: usize, nrows: usize, eps: f32)
4988                                    -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4989        debug_assert!(ncols % 128 == 0);
4990        let mut out_q = self.alloc_uninit::<i8>(nrows * ncols)?;
4991        let mut out_d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
4992        let (nc, e) = (ncols as i32, eps);
4993        if Self::pdl_on() {
4994            {
4995            use cudarc::driver::{DevicePtr, DevicePtrMut};
4996            let s = &self.gpu.stream();
4997            let (pa, _g0) = a.device_ptr(s); let (pwa, _g1) = wa.device_ptr(s);
4998            let (pb, _g2) = b.device_ptr(s); let (pw, _g3) = w.device_ptr(s);
4999            let (pr, _g4) = res.device_ptr_mut(s); let (pdst, _g5) = dst.device_ptr_mut(s);
5000            let (pq, _g6) = out_q.device_ptr_mut(s); let (pd, _g7) = out_d.device_ptr_mut(s);
5001            let mut ps = [
5002                &pa as *const _ as *mut std::ffi::c_void, &pwa as *const _ as *mut _,
5003                &pb as *const _ as *mut _, &pw as *const _ as *mut _,
5004                &pr as *const _ as *mut _, &pdst as *const _ as *mut _,
5005                &pq as *const _ as *mut _, &pd as *const _ as *mut _,
5006                &nc as *const _ as *mut _, &e as *const _ as *mut _,
5007            ];
5008            unsafe { self.launch_pdl("rms_pre_add_rms_norm_q8z_f32", (nrows as u32, 1, 1),
5009                                     (rms_block(), 1, 1), &mut ps)?; }
5010            }
5011            return Ok((out_q, out_d));
5012        }
5013        let f = self.func("rms_pre_add_rms_norm_q8z_f32");
5014        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
5015        let __s_b2 = self.gpu.stream();
5016        let mut b2 = __s_b2.launch_builder(&f);
5017        b2.arg(a).arg(wa).arg(b).arg(w).arg(&mut *res).arg(&mut *dst)
5018          .arg(&mut out_q).arg(&mut out_d).arg(&nc).arg(&e);
5019        unsafe { b2.launch(cfg)?; }
5020        Ok((out_q, out_d))
5021    }
5022
5023    /// wave-4b: OUT-dim concat of three Q4_0 tensors (same in_features; rows are independent
5024    /// blocks, so the concat is a D2D byte concat of the GGUF-layout planes). Returns None
5025    /// off-class (non-Q4_0, mismatched widths, or any tensor already rp-swapped in place).
5026    pub fn build_q4_out_concat3(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
5027                                w2: &crate::model::GpuTensor)
5028                                -> Result<Option<crate::model::GpuTensor>, Box<dyn std::error::Error>> {
5029        use crate::model::GpuTensor;
5030        let part = |w: &GpuTensor| -> Option<(usize, usize)> {
5031            match w {
5032                GpuTensor::Quant { qtype, row_bytes, rp, .. }
5033                    if *qtype == QT_Q4_0 && !*rp => Some((*row_bytes, w.out_features())),
5034                _ => None,
5035            }
5036        };
5037        let (Some((rb0, o0)), Some((rb1, o1)), Some((rb2, o2))) = (part(w0), part(w1), part(w2))
5038        else { return Ok(None) };
5039        if rb0 != rb1 || rb0 != rb2
5040            || w0.in_features() != w1.in_features() || w0.in_features() != w2.in_features() {
5041            return Ok(None);
5042        }
5043        fn bytes_of(w: &crate::model::GpuTensor) -> &CudaSlice<u8> {
5044            match w { crate::model::GpuTensor::Quant { bytes, .. } => bytes, _ => unreachable!() }
5045        }
5046        let (b0, b1, b2) = (bytes_of(w0), bytes_of(w1), bytes_of(w2));
5047        let total = rb0 * (o0 + o1 + o2);
5048        let mut cat = self.alloc_u8(total)?;
5049        self.copy_u8_into(&mut cat, 0, b0, rb0 * o0)?;
5050        self.copy_u8_into(&mut cat, rb0 * o0, b1, rb1 * o1)?;
5051        self.copy_u8_into(&mut cat, rb0 * (o0 + o1), b2, rb2 * o2)?;
5052        Ok(Some(GpuTensor::Quant {
5053            bytes: cat, qtype: QT_Q4_0, row_bytes: rb0,
5054            ne: vec![w0.in_features() as u64, (o0 + o1 + o2) as u64], scale: 1.0, rp: false,
5055            #[cfg(memra_cutlass)]
5056            cutlass: None,
5057            fp8: None, blk: None, rp4: None, f16: None,
5058        }))
5059    }
5060
5061    /// wave-4b: the qkv-cat twin — one contiguous [rq+2*rk, hd] input from the concat matvec.
5062    #[allow(clippy::too_many_arguments)]
5063    pub fn rms_norm_qkv_rope_cat(&self, qkv: &CudaSlice<f32>,
5064                                 wq: &CudaSlice<f32>, wk: &CudaSlice<f32>, wv: &CudaSlice<f32>,
5065                                 q: &mut CudaSlice<f32>, k: &mut CudaSlice<f32>, v: &mut CudaSlice<f32>,
5066                                 head_dim: usize, rq: usize, rk: usize,
5067                                 pos: &CudaSlice<i32>, nh_q: usize, nh_k: usize,
5068                                 base: f32, freq_scale: f32, ff: Option<&CudaSlice<f32>>, eps: f32)
5069                                 -> Result<(), Box<dyn std::error::Error>> {
5070        let rows = rq + rk + rk;
5071        let theta_scale = base.powf(-2.0 / head_dim as f32);
5072        let (nc, rqi, rki, nhq, nhk) = (head_dim as i32, rq as i32, rk as i32, nh_q as i32, nh_k as i32);
5073        if Self::pdl_on() {
5074            use cudarc::driver::{DevicePtr, DevicePtrMut};
5075            let s = &self.gpu.stream();
5076            let (pqkv, _g0) = qkv.device_ptr(s);
5077            let (pwq, _g1) = wq.device_ptr(s); let (pwk, _g2) = wk.device_ptr(s);
5078            let (pwv, _g3) = wv.device_ptr(s);
5079            let (pq, _g4) = q.device_ptr_mut(s); let (pk, _g5) = k.device_ptr_mut(s);
5080            let (pv, _g6) = v.device_ptr_mut(s);
5081            let (ppos, _g7) = pos.device_ptr(s);
5082            let (pff, _g8) = match ff {
5083                Some(t) => { let (p, g) = t.device_ptr(s); (p, Some(g)) }
5084                None => (0, None),
5085            };
5086            let mut ps = [
5087                &pqkv as *const _ as *mut std::ffi::c_void,
5088                &pwq as *const _ as *mut _, &pwk as *const _ as *mut _,
5089                &pwv as *const _ as *mut _,
5090                &pq as *const _ as *mut _, &pk as *const _ as *mut _,
5091                &pv as *const _ as *mut _,
5092                &nc as *const _ as *mut _, &rqi as *const _ as *mut _,
5093                &rki as *const _ as *mut _, &ppos as *const _ as *mut _,
5094                &nhq as *const _ as *mut _, &nhk as *const _ as *mut _,
5095                &theta_scale as *const _ as *mut _, &freq_scale as *const _ as *mut _,
5096                &pff as *const _ as *mut _, &eps as *const _ as *mut _,
5097            ];
5098            unsafe { self.launch_pdl("rms_norm_qkv_rope_cat_f32", (rows as u32, 1, 1),
5099                                     (rms_block(), 1, 1), &mut ps)?; }
5100            return Ok(());
5101        }
5102        let f = self.func("rms_norm_qkv_rope_cat_f32");
5103        let cfg = LaunchConfig { grid_dim: (rows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
5104        let __s_b = self.gpu.stream();
5105        let mut b = __s_b.launch_builder(&f);
5106        match ff {
5107            Some(t) => { b.arg(qkv).arg(wq).arg(wk).arg(wv)
5108                          .arg(&mut *q).arg(&mut *k).arg(&mut *v)
5109                          .arg(&nc).arg(&rqi).arg(&rki).arg(pos).arg(&nhq).arg(&nhk)
5110                          .arg(&theta_scale).arg(&freq_scale).arg(t).arg(&eps);
5111                         unsafe { b.launch(cfg)?; } }
5112            None => { let null: u64 = 0;
5113                      b.arg(qkv).arg(wq).arg(wk).arg(wv)
5114                       .arg(&mut *q).arg(&mut *k).arg(&mut *v)
5115                       .arg(&nc).arg(&rqi).arg(&rki).arg(pos).arg(&nhq).arg(&nhk)
5116                       .arg(&theta_scale).arg(&freq_scale).arg(&null).arg(&eps);
5117                      unsafe { b.launch(cfg)?; } }
5118        }
5119        Ok(())
5120    }
5121
5122    /// wave-3 fold: rms_norm_qkv + rope_neox2 in ONE launch (n_dims == head_dim; ff nullable).
5123    #[allow(clippy::too_many_arguments)]
5124    pub fn rms_norm_qkv_rope(&self, q0: &CudaSlice<f32>, k0: &CudaSlice<f32>, v0: &CudaSlice<f32>,
5125                             wq: &CudaSlice<f32>, wk: &CudaSlice<f32>, wv: &CudaSlice<f32>,
5126                             q: &mut CudaSlice<f32>, k: &mut CudaSlice<f32>, v: &mut CudaSlice<f32>,
5127                             head_dim: usize, rq: usize, rk: usize,
5128                             pos: &CudaSlice<i32>, nh_q: usize, nh_k: usize,
5129                             base: f32, freq_scale: f32, ff: Option<&CudaSlice<f32>>, eps: f32)
5130                             -> Result<(), Box<dyn std::error::Error>> {
5131        let f = self.func("rms_norm_qkv_rope_f32");
5132        let rows = rq + rk + rk;   // q rows + k rows + v rows (rk == rv)
5133        let cfg = LaunchConfig { grid_dim: (rows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
5134        let theta_scale = base.powf(-2.0 / head_dim as f32);
5135        let (nc, rqi, rki, nhq, nhk) = (head_dim as i32, rq as i32, rk as i32, nh_q as i32, nh_k as i32);
5136        let __s_b = self.gpu.stream();
5137        let mut b = __s_b.launch_builder(&f);
5138        match ff {
5139            Some(t) => { b.arg(q0).arg(k0).arg(v0).arg(wq).arg(wk).arg(wv)
5140                          .arg(&mut *q).arg(&mut *k).arg(&mut *v)
5141                          .arg(&nc).arg(&rqi).arg(&rki).arg(pos).arg(&nhq).arg(&nhk)
5142                          .arg(&theta_scale).arg(&freq_scale).arg(t).arg(&eps);
5143                         unsafe { b.launch(cfg)?; } }
5144            None => { let null: u64 = 0;
5145                      b.arg(q0).arg(k0).arg(v0).arg(wq).arg(wk).arg(wv)
5146                       .arg(&mut *q).arg(&mut *k).arg(&mut *v)
5147                       .arg(&nc).arg(&rqi).arg(&rki).arg(pos).arg(&nhq).arg(&nhk)
5148                       .arg(&theta_scale).arg(&freq_scale).arg(&null).arg(&eps);
5149                      unsafe { b.launch(cfg)?; } }
5150        }
5151        Ok(())
5152    }
5153
5154    /// FUSED norm+rope+APPEND (m=1 decode, 2026-07-23): one launch replaces the
5155    /// rms_norm_qkv_rope + append_kv_quantized_dc pair. Kernel lives in the flash fatbins
5156    /// (format-flavored quant tail) — `g` must mirror the append path's flavor exactly.
5157    #[allow(clippy::too_many_arguments)]
5158    pub fn rms_norm_qkv_rope_append_dc(&self, q0: &CudaSlice<f32>, k0: &CudaSlice<f32>,
5159                             v0: &CudaSlice<f32>,
5160                             wq: &CudaSlice<f32>, wk: &CudaSlice<f32>, wv: &CudaSlice<f32>,
5161                             q: &mut CudaSlice<f32>, k: &mut CudaSlice<f32>, v: &mut CudaSlice<f32>,
5162                             head_dim: usize, rq: usize, rk: usize,
5163                             pos: &CudaSlice<i32>, nh_q: usize, nh_k: usize,
5164                             base: f32, freq_scale: f32, ff: Option<&CudaSlice<f32>>, eps: f32,
5165                             kc: &mut CudaSlice<u8>, vc: &mut CudaSlice<u8>,
5166                             t_dev: &CudaSlice<i32>, k_tok_bytes: usize, v_tok_bytes: usize,
5167                             g: bool)
5168                             -> Result<(), Box<dyn std::error::Error>> {
5169        let rows = rq + rk + rk;
5170        let theta_scale = base.powf(-2.0 / head_dim as f32);
5171        let (nc, rqi, rki, nhq, nhk) = (head_dim as i32, rq as i32, rk as i32, nh_q as i32, nh_k as i32);
5172        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
5173        if Self::pdl_on() && Self::pdl_wb_on() {
5174            use cudarc::driver::{DevicePtr, DevicePtrMut};
5175            let s = &self.gpu.stream();
5176            let (p0, _a0) = q0.device_ptr(s); let (p1, _a1) = k0.device_ptr(s);
5177            let (p2, _a2) = v0.device_ptr(s);
5178            let (pwq, _a3) = wq.device_ptr(s); let (pwk, _a4) = wk.device_ptr(s);
5179            let (pwv, _a5) = wv.device_ptr(s);
5180            let (pq, _a6) = q.device_ptr_mut(s); let (pk, _a7) = k.device_ptr_mut(s);
5181            let (pv, _a8) = v.device_ptr_mut(s);
5182            let (pp, _a9) = pos.device_ptr(s);
5183            let pff: u64 = match ff { Some(t) => { let (p, _gg) = t.device_ptr(s); p as u64 }
5184                                      None => 0 };
5185            let (pkc, _a10) = kc.device_ptr_mut(s); let (pvc, _a11) = vc.device_ptr_mut(s);
5186            let (pt, _a12) = t_dev.device_ptr(s);
5187            let mut ps = [
5188                &p0 as *const _ as *mut std::ffi::c_void, &p1 as *const _ as *mut _,
5189                &p2 as *const _ as *mut _, &pwq as *const _ as *mut _,
5190                &pwk as *const _ as *mut _, &pwv as *const _ as *mut _,
5191                &pq as *const _ as *mut _, &pk as *const _ as *mut _,
5192                &pv as *const _ as *mut _, &nc as *const _ as *mut _,
5193                &rqi as *const _ as *mut _, &rki as *const _ as *mut _,
5194                &pp as *const _ as *mut _, &nhq as *const _ as *mut _,
5195                &nhk as *const _ as *mut _, &theta_scale as *const _ as *mut _,
5196                &freq_scale as *const _ as *mut _, &pff as *const _ as *mut _,
5197                &eps as *const _ as *mut _, &pkc as *const _ as *mut _,
5198                &pvc as *const _ as *mut _, &pt as *const _ as *mut _,
5199                &ktb as *const _ as *mut _, &vtb as *const _ as *mut _,
5200            ];
5201            unsafe { self.launch_pdl_flash(g, "rms_norm_qkv_rope_append_dc_f32",
5202                                           (rows as u32, 1, 1), (rms_block(), 1, 1), 0, &mut ps)?; }
5203            return Ok(());
5204        }
5205        let f = if g { self.func_g("rms_norm_qkv_rope_append_dc_f32") }
5206                else { self.func("rms_norm_qkv_rope_append_dc_f32") };
5207        let cfg = LaunchConfig { grid_dim: (rows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
5208        let __s_b = self.gpu.stream();
5209        let mut b = __s_b.launch_builder(&f);
5210        match ff {
5211            Some(t) => { b.arg(q0).arg(k0).arg(v0).arg(wq).arg(wk).arg(wv)
5212                          .arg(&mut *q).arg(&mut *k).arg(&mut *v)
5213                          .arg(&nc).arg(&rqi).arg(&rki).arg(pos).arg(&nhq).arg(&nhk)
5214                          .arg(&theta_scale).arg(&freq_scale).arg(t).arg(&eps)
5215                          .arg(&mut *kc).arg(&mut *vc).arg(t_dev).arg(&ktb).arg(&vtb);
5216                         unsafe { b.launch(cfg)?; } }
5217            None => { let null: u64 = 0;
5218                      b.arg(q0).arg(k0).arg(v0).arg(wq).arg(wk).arg(wv)
5219                       .arg(&mut *q).arg(&mut *k).arg(&mut *v)
5220                       .arg(&nc).arg(&rqi).arg(&rki).arg(pos).arg(&nhq).arg(&nhk)
5221                       .arg(&theta_scale).arg(&freq_scale).arg(&null).arg(&eps)
5222                       .arg(&mut *kc).arg(&mut *vc).arg(t_dev).arg(&ktb).arg(&vtb);
5223                      unsafe { b.launch(cfg)?; } }
5224        }
5225        Ok(())
5226    }
5227
5228    /// wave-2 fold: a + b with the sum emitted q8_1 alongside f32.
5229    pub fn add_q8_1(&self, a: &CudaSlice<f32>, b: &CudaSlice<f32>, res: &mut CudaSlice<f32>,
5230                    ncols: usize, nrows: usize)
5231                    -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5232        debug_assert!(ncols % 128 == 0);
5233        let mut out_q = self.alloc_uninit::<i8>(nrows * ncols)?;
5234        let mut out_d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
5235        let f = self.func("add_q8_1_f32");
5236        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
5237        let nc = ncols as i32;
5238        let __s_b2 = self.gpu.stream();
5239        let mut b2 = __s_b2.launch_builder(&f);
5240        b2.arg(a).arg(b).arg(&mut *res).arg(&mut out_q).arg(&mut out_d).arg(&nc);
5241        unsafe { b2.launch(cfg)?; }
5242        Ok((out_q, out_d))
5243    }
5244
5245    /// E4B FFN-tail exit fusion (glue wave 5): resid = b + rms(a, wa) emitted f32 + q8_1 pair
5246    /// in ONE launch — replaces rms_norm(a,wa->sn) + add_q8_1(sn,b). Same rms_block() config
5247    /// as both parents (bit-identity: identical reduction + quad-walk quantize).
5248    pub fn rms_pre_add_q8_1(&self, a: &CudaSlice<f32>, wa: &CudaSlice<f32>, b: &CudaSlice<f32>,
5249                            res: &mut CudaSlice<f32>, ncols: usize, nrows: usize, eps: f32)
5250                            -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5251        debug_assert!(ncols % 128 == 0);
5252        let mut out_q = self.alloc_uninit::<i8>(nrows * ncols)?;
5253        let mut out_d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
5254        let f = self.func("rms_pre_add_q8_1_f32");
5255        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1),
5256                                 shared_mem_bytes: 0 };
5257        let (nc, ep) = (ncols as i32, eps);
5258        let __s_b2 = self.gpu.stream();
5259        let mut b2 = __s_b2.launch_builder(&f);
5260        b2.arg(a).arg(wa).arg(b).arg(&mut *res).arg(&mut out_q).arg(&mut out_d).arg(&nc).arg(&ep);
5261        unsafe { b2.launch(cfg)?; }
5262        Ok((out_q, out_d))
5263    }
5264
5265    /// L2 norm per row (head_dim), no weight.
5266    /// PREFILL l2 dispatch (round 27): the warp-per-row float4 v2 when the numeric-config
5267    /// seam allows (MEMRA_L2_V2, default ON, d_state==128 only); else the strided kernel.
5268    pub fn l2_v2_on(ncols: usize) -> bool {
5269        ncols == 128 && std::env::var("MEMRA_L2_V2").as_deref() != Ok("0")
5270    }
5271
5272    pub fn l2_norm_pp(&self, x: &CudaSlice<f32>, dst: &mut CudaSlice<f32>,
5273                      dst16: Option<&mut CudaSlice<u8>>, ncols: usize, nrows: usize,
5274                      eps: f32) -> Result<(), Box<dyn std::error::Error>> {
5275        if Self::l2_v2_on(ncols) {
5276            let f = self.func("l2_norm_pp_v2_f32");
5277            let rows_per_block = 8u32;   // 256 threads = 8 warps = 8 rows
5278            let cfg = LaunchConfig { grid_dim: ((nrows as u32).div_ceil(rows_per_block), 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
5279            let (nc, nr, e) = (ncols as i32, nrows as i32, eps);
5280            // mirror-fold: bf16 twin address by value (0 = skip; matches the nullable param)
5281            let d16: u64 = match dst16 { Some(d) => self.addr_u8(d), None => 0 };
5282            let __s_b = self.gpu.stream();
5283            let mut b = __s_b.launch_builder(&f);
5284            b.arg(x).arg(dst).arg(&d16).arg(&nc).arg(&nr).arg(&e);
5285            unsafe { b.launch(cfg)?; }
5286            return Ok(());
5287        }
5288        self.l2_norm(x, dst, ncols, nrows, eps)
5289    }
5290
5291    pub fn l2_norm(&self, x: &CudaSlice<f32>, dst: &mut CudaSlice<f32>, ncols: usize, nrows: usize,
5292                   eps: f32) -> Result<(), Box<dyn std::error::Error>> {
5293        let f = self.func("l2_norm_f32");
5294        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
5295        let (nc, e) = (ncols as i32, eps);
5296        let __s_b = self.gpu.stream();
5297        let mut b = __s_b.launch_builder(&f);
5298        b.arg(x).arg(dst).arg(&nc).arg(&e);
5299        unsafe { b.launch(cfg)?; }
5300        Ok(())
5301    }
5302
5303    /// L2-norm with blockDim=32 (warp-tree reduction) — BIT-IDENTICAL to gdn_prep_decode_f32's
5304    /// per-warp L2 norm. The verify path MUST use this to match decode's FP accumulation order:
5305    /// l2_norm at blockDim=256 produces a different shfl-tree reduction of the 128-element
5306    /// squared-sum (pairwise tree vs serial-4-then-warp-tree), causing ULP differences that
5307    /// propagate through gdn_scan and flip argmax on marginal logits.
5308    pub fn l2_norm_decode(&self, x: &CudaSlice<f32>, dst: &mut CudaSlice<f32>, ncols: usize,
5309                          nrows: usize, eps: f32) -> Result<(), Box<dyn std::error::Error>> {
5310        let f = self.func("l2_norm_f32");
5311        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
5312        let (nc, e) = (ncols as i32, eps);
5313        let __s_b = self.gpu.stream();
5314        let mut b = __s_b.launch_builder(&f);
5315        b.arg(x).arg(dst).arg(&nc).arg(&e);
5316        unsafe { b.launch(cfg)?; }
5317        Ok(())
5318    }
5319
5320    /// RoPE NEOX in-place. x:[head_dim, n_heads, n_tokens], pos:[n_tokens].
5321    pub fn rope_neox(&self, x: &mut CudaSlice<f32>, pos: &CudaSlice<i32>, head_dim: usize,
5322                     n_dims: usize, n_heads: usize, n_tokens: usize, freq_base: f32, freq_scale: f32)
5323                     -> Result<(), Box<dyn std::error::Error>> {
5324        let f = self.func("rope_neox_f32");
5325        let theta_scale = (freq_base).powf(-2.0 / n_dims as f32);
5326        let grid = (n_heads * n_tokens) as u32;
5327        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: ((head_dim / 2) as u32, 1, 1), shared_mem_bytes: 0 };
5328        let (hd, nd, nh) = (head_dim as i32, n_dims as i32, n_heads as i32);
5329        let __s_b = self.gpu.stream();
5330        let mut b = __s_b.launch_builder(&f);
5331        b.arg(x).arg(pos).arg(&hd).arg(&nd).arg(&nh).arg(&theta_scale).arg(&freq_scale);
5332        unsafe { b.launch(cfg)?; }
5333        Ok(())
5334    }
5335
5336    /// RoPE NEOX with per-dim freq factors (gemma4 global layers, rope_freqs.weight [n_dims/2]).
5337    pub fn rope_neox_ff(&self, x: &mut CudaSlice<f32>, pos: &CudaSlice<i32>, head_dim: usize,
5338                        n_dims: usize, n_heads: usize, n_tokens: usize, freq_base: f32,
5339                        freq_scale: f32, ff: &CudaSlice<f32>)
5340                        -> Result<(), Box<dyn std::error::Error>> {
5341        let f = self.func("rope_neox_ff_f32");
5342        let theta_scale = (freq_base).powf(-2.0 / n_dims as f32);
5343        let grid = (n_heads * n_tokens) as u32;
5344        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: ((head_dim / 2) as u32, 1, 1), shared_mem_bytes: 0 };
5345        let (hd, nd, nh) = (head_dim as i32, n_dims as i32, n_heads as i32);
5346        let __s_b = self.gpu.stream();
5347        let mut b = __s_b.launch_builder(&f);
5348        b.arg(x).arg(pos).arg(&hd).arg(&nd).arg(&nh).arg(&theta_scale).arg(&freq_scale).arg(ff);
5349        unsafe { b.launch(cfg)?; }
5350        Ok(())
5351    }
5352
5353    /// gemma4: rope q and k in one launch (per-row chain = rope_neox / rope_neox_ff verbatim).
5354    #[allow(clippy::too_many_arguments)]
5355    pub fn rope_neox2(&self, q: &mut CudaSlice<f32>, k: &mut CudaSlice<f32>,
5356                      pos: &CudaSlice<i32>, head_dim: usize, n_dims: usize,
5357                      nh_q: usize, nh_k: usize, n_tokens: usize, freq_base: f32,
5358                      freq_scale: f32, ff: Option<&CudaSlice<f32>>)
5359                      -> Result<(), Box<dyn std::error::Error>> {
5360        let f = self.func("rope_neox2_f32");
5361        let theta_scale = (freq_base).powf(-2.0 / n_dims as f32);
5362        let grid = ((nh_q + nh_k) * n_tokens) as u32;
5363        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: ((head_dim / 2) as u32, 1, 1), shared_mem_bytes: 0 };
5364        let (hd, nd, nq, nk, nt) = (head_dim as i32, n_dims as i32, nh_q as i32, nh_k as i32, n_tokens as i32);
5365        let __s_b = self.gpu.stream();
5366        let mut b = __s_b.launch_builder(&f);
5367        b.arg(q).arg(k).arg(pos).arg(&hd).arg(&nd).arg(&nq).arg(&nk).arg(&nt)
5368         .arg(&theta_scale).arg(&freq_scale);
5369        match ff {
5370            Some(ffv) => { b.arg(ffv); unsafe { b.launch(cfg)?; } }
5371            None => {
5372                let null: u64 = 0;
5373                b.arg(&null);
5374                unsafe { b.launch(cfg)?; }
5375            }
5376        }
5377        Ok(())
5378    }
5379
5380    /// gemma4 R1: dst = GELU_tanh(gate) * up.
5381    pub fn gelu_tanh_mul(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>, dst: &mut CudaSlice<f32>, n: usize)
5382                         -> Result<(), Box<dyn std::error::Error>> {
5383        let f = self.func("gelu_tanh_mul_f32");
5384        let cfg = LaunchConfig::for_num_elems(n as u32);
5385        let ni = n as i32;
5386        let __s_b = self.gpu.stream();
5387        let mut b = __s_b.launch_builder(&f);
5388        b.arg(gate).arg(up).arg(dst).arg(&ni);
5389        unsafe { b.launch(cfg)?; }
5390        Ok(())
5391    }
5392
5393    pub fn silu_mul(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>, dst: &mut CudaSlice<f32>, n: usize)
5394                    -> Result<(), Box<dyn std::error::Error>> {
5395        let f = self.func("silu_mul_f32");
5396        // float4 kernel: one thread per 4 elements (tail handled in-kernel)
5397        let cfg = LaunchConfig::for_num_elems((n as u32).div_ceil(4));
5398        let ni = n as i32;
5399        let __s_b = self.gpu.stream();
5400        let mut b = __s_b.launch_builder(&f);
5401        b.arg(gate).arg(up).arg(dst).arg(&ni);
5402        unsafe { b.launch(cfg)?; }
5403        Ok(())
5404    }
5405
5406    /// f16out twin of `silu_mul` (task #17): the epilogue also emits the fp16 GEMM operand
5407    /// for the down projection — kills the standalone convert pass. Bit-identical class.
5408    pub fn silu_mul_f16out(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
5409                           dst: &mut CudaSlice<f32>, dst16: &mut CudaSlice<u8>, n: usize)
5410                           -> Result<(), Box<dyn std::error::Error>> {
5411        let f = self.func("silu_mul_f16out_f32");
5412        let cfg = LaunchConfig::for_num_elems((n as u32).div_ceil(4));
5413        let ni = n as i32;
5414        let __s_b = self.gpu.stream();
5415        let mut b = __s_b.launch_builder(&f);
5416        b.arg(gate).arg(up).arg(dst).arg(dst16).arg(&ni);
5417        unsafe { b.launch(cfg)?; }
5418        Ok(())
5419    }
5420
5421    /// FFN SwiGLU epilogue fusion (RANK3 LEVER 2): `dst = silu(gate*gs) * (up*us)` in ONE launch,
5422    /// folding the per-tensor NVFP4 macro-scale (`gs`,`us`) that would otherwise be two separate
5423    /// `scale_inplace` launches on the gate/up matmul outputs. BIT-IDENTICAL to
5424    /// scale_inplace(gate,gs); scale_inplace(up,us); silu_mul(gate,up,dst) — identical float ops in
5425    /// identical order. For non-NVFP4 weights gs==us==1.0 -> identical to `silu_mul`. Net: -2
5426    /// launches per dense FFN layer (the gate+up post-matmul scales).
5427    pub fn silu_mul_scaled(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>, gs: f32, us: f32,
5428                           dst: &mut CudaSlice<f32>, n: usize) -> Result<(), Box<dyn std::error::Error>> {
5429        let f = self.func("silu_mul_scaled_f32");
5430        let cfg = LaunchConfig::for_num_elems(n as u32);
5431        let ni = n as i32;
5432        let (gsf, usf) = (gs, us);
5433        let __s_b = self.gpu.stream();
5434        let mut b = __s_b.launch_builder(&f);
5435        b.arg(gate).arg(up).arg(&gsf).arg(&usf).arg(dst).arg(&ni);
5436        unsafe { b.launch(cfg)?; }
5437        Ok(())
5438    }
5439
5440    /// swigluoai (MiniMax-M3 / GPT-OSS): clamped SwiGLU epilogue, math 1:1 vs llama.cpp
5441    /// ggml_cuda_op_swiglu_oai_single. `dst = swish_alpha(clamp(gate*gs)) * (1 + clamp(up*us))`.
5442    /// gs/us fold the NVFP4 macro-scales exactly like `silu_mul_scaled`.
5443    #[allow(clippy::too_many_arguments)]
5444    pub fn swigluoai_mul_scaled(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>, gs: f32, us: f32,
5445                                alpha: f32, limit: f32, dst: &mut CudaSlice<f32>, n: usize)
5446                                -> Result<(), Box<dyn std::error::Error>> {
5447        let f = self.func("swigluoai_mul_scaled_f32");
5448        let cfg = LaunchConfig::for_num_elems(n as u32);
5449        let ni = n as i32;
5450        let __s_b = self.gpu.stream();
5451        let mut b = __s_b.launch_builder(&f);
5452        b.arg(gate).arg(up).arg(&gs).arg(&us).arg(&alpha).arg(&limit).arg(dst).arg(&ni);
5453        unsafe { b.launch(cfg)?; }
5454        Ok(())
5455    }
5456
5457    /// RANK2 LEVER (q8_1 quant-fold): SwiGLU epilogue that EMITS the q8_1 quantization of `act`
5458    /// directly (aq int8 [n] + ad f32 [n/32]), so ffn_down's standalone `quantize_q8_1` launch is
5459    /// removed — the down-proj activation has one consumer, so the quant folds into the producer for
5460    /// free (no extra HBM read; no f32 `act` write). gs/us fold the gate/up NVFP4 macro-scales like
5461    /// `silu_mul_scaled`. BIT-IDENTICAL q8_1 to silu_mul_scaled(...) then quantize_q8_1(...). Only
5462    /// valid when ffn_down uses the q8_1 dp4a/mmvq path; the caller checks `uses_q8_1_fast(ffn_down)`.
5463    /// n must be a multiple of 32 (n_ff always is).
5464    pub fn silu_mul_scaled_q8_1(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>, gs: f32, us: f32,
5465                                n: usize)
5466                                -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5467        let f = self.func("silu_mul_scaled_q8_1");
5468        let nblk = n / 32;
5469        let mut aq = self.alloc_uninit::<i8>(n)?;       // full-overwrite output
5470        let mut ad = self.alloc_uninit::<f32>(nblk)?;   // full-overwrite output
5471        // WARP-PER-BLOCK kernel: one warp (32 lanes) per 32-block -> n threads total.
5472        let cfg = LaunchConfig::for_num_elems(n as u32);
5473        let (gsf, usf, ni) = (gs, us, n as i32);
5474        let __s_b = self.gpu.stream();
5475        let mut b = __s_b.launch_builder(&f);
5476        b.arg(gate).arg(up).arg(&gsf).arg(&usf).arg(&mut aq).arg(&mut ad).arg(&ni);
5477        unsafe { b.launch(cfg)?; }
5478        Ok((aq, ad))
5479    }
5480
5481    pub fn add(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, dst: &mut CudaSlice<f32>, n: usize)
5482               -> Result<(), Box<dyn std::error::Error>> {
5483        let f = self.func("add_f32");
5484        // float4 kernel: one thread per 4 elements (tail handled in-kernel)
5485        let cfg = LaunchConfig::for_num_elems((n as u32).div_ceil(4));
5486        let ni = n as i32;
5487        let __s_bld = self.gpu.stream();
5488        let mut bld = __s_bld.launch_builder(&f);
5489        bld.arg(a).arg(b_in).arg(dst).arg(&ni);
5490        unsafe { bld.launch(cfg)?; }
5491        Ok(())
5492    }
5493
5494    pub fn mul(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, dst: &mut CudaSlice<f32>, n: usize)
5495               -> Result<(), Box<dyn std::error::Error>> {
5496        let f = self.func("mul_f32");
5497        let cfg = LaunchConfig::for_num_elems(n as u32);
5498        let ni = n as i32;
5499        let __s_bld = self.gpu.stream();
5500        let mut bld = __s_bld.launch_builder(&f);
5501        bld.arg(a).arg(b_in).arg(dst).arg(&ni);
5502        unsafe { bld.launch(cfg)?; }
5503        Ok(())
5504    }
5505
5506    /// Unified weight-tensor matmul: dispatches quant tensors to qmatvec (weights packed) and
5507    /// float tensors to cuBLASLt. y[m,out] = x[m,in] @ W[out,in]^T.
5508    pub fn matmul(&self, w: &crate::model::GpuTensor, x: &CudaSlice<f32>, m: usize)
5509                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5510        use crate::model::GpuTensor;
5511        let in_f = w.in_features();
5512        let out_f = w.out_features();
5513        // PREFILL (T>1) ROOT FIX: batched tensor-core int8 GEMM. Decodes each weight tile to int8
5514        // in smem ONCE and reuses across all tokens via mma — vs the dp4a matvec's per-token weight
5515        // re-read. Only the 4 daily-hot dtypes; m=1 decode keeps dp4a (it's bandwidth-bound, mma
5516        // gives nothing). Quantize the activation once here then call the GEMM.
5517        // m cutoff FIXED at 16: the m=4 MMA-verify A/B (2026-07-06, was MEMRA_GEMM_M) measured
5518        // NEGATIVE — the MMA tile grid starves at m=4 (BN=256 -> grid.y=1) and its FP order
5519        // shifted verify argmax at tight margins. Do not lower without re-running that battery.
5520        #[allow(non_snake_case)]
5521        // VERIFY-EXACT scope pushes the GEMM crossover out of reach (usize::MAX) — the
5522        // t>=16 dflash verify must ride the decode-exact batched class (parity law).
5523        let GEMM_M_THRESHOLD = if self.verify_exact_on() { usize::MAX } else { 16usize };
5524
5525        // PREFILL GEMM (m>=16). ACCURACY-FIRST dispatch (2026-06-28, prefill-gemm-beat-research wf
5526        // wllbyo6vc step 1): the int8 W4A8 GEMM (qmatvec_gemm, q8_1 activation, s32 accumulate) is
5527        // ACCURATE (prefill logit maxdiff 0.159, < dp4a 0.55) and the default. The FP4 W4A4 mxf4 path
5528        // (try_fp4_gemm) quantizes the ACTIVATION to e2m1 4-bit (8 magnitude levels) -> maxdiff 1.0
5529        // when combined — a real accuracy loss, NOT a math bug. So FP4-W4A4 is taken ONLY under the
5530        // explicit MEMRA_FP4 opt-in AND it must come SECOND (int8 W4A8 is the correct default for NVFP4).
5531        // The workflow plan rebuilds the FP4 path (kill per-K repack, widen K, deepen pipeline, TMA) to
5532        // be both fast AND accurate; until then NVFP4 prefill defaults to the accurate int8 GEMM.
5533        // TINY-OUT_F GUARD (2026-06-28, ncu trace): the tiling GEMM's grid is (ceil(out_f/BM=64),
5534        // ceil(m/BN=256)). For tiny out_f (ssm_beta/ssm_alpha out_f=num_v_heads~32), grid.x=1 -> only
5535        // ceil(m/256) CTAs (e.g. 2 for m=512) on 82 SMs = 0.39% SM throughput, 852us EACH (measured
5536        // worst offender). The dp4a path grids (out_f, m) = far more CTAs, filling the GPU. So route
5537        // out_f < 2*BM to dp4a (skip the tiling GEMM which structurally can't fill the SMs here).
5538        const GEMM_MIN_OUT_F: usize = 128;   // 2*BM; below this the GEMM grid.x starves the 82 SMs
5539        // VENDORED llama MMQ prefill GEMMs. NVFP4 W4A8 is DEFAULT-ON (2026-07-05 flip: same int8
5540        // accuracy class as the int8 GEMM below at ~1.9x pp512, rp-loader coexists with the A6
5541        // repack; MEMRA_MMQ_W4A8=0 = escape hatch). W4A4 mxf4nvf4 + Q4_K/Q5_K stay behind MEMRA_MMQ=1.
5542        // The env policy lives in mmq_supports/qmatvec_mmq. Feeds raw f32 activation `x` (the
5543        // launcher quantizes internally). out_f>=MMQ_Y/2 keeps the tile grid from starving the SMs.
5544        // FP8-ACT PREFILL (MEMRA_PP_FP8=1, probe verdict 2026-07-08): F8-E4M3-origin projections
5545        // carry their raw e4m3 device bytes (the `fp8` operand stashed at load next to the Q8_0
5546        // re-encode) — cuBLASLt FP8 TN at 620-795 TF vs 47-72 TF for this class's int8 GEMM.
5547        // Weight side EXACT (checkpoint bytes); activation rides ONE per-batch e4m3 scale
5548        // (amax/448) folded with weight_scale in-GEMM. Prefill only; decode keeps Q8_0 untouched.
5549        if m >= GEMM_M_THRESHOLD {
5550            if let Some(y) = self.try_fp8_gemm(w, x, m)? { return Ok(y); }
5551            // PER-BLOCK FP8 MMQ (lane/fp8-mmq): the block-128 class try_fp8_gemm skips (cuBLASLt
5552            // takes no block grid on sm_120). Exact per block — the checkpoint's e4m3 bytes and its
5553            // f32 grid go into the tile unchanged. TWO SOURCES, TWO DEFAULTS: the load-time stash is
5554            // opt-in (MEMRA_FP8_MMQ=1), the native-resident QT_F8_E4M3_BLK grid is DEFAULT ON
5555            // (MEMRA_FP8_MMQ=0 reverts it to dequant-per-call) — see fp8_ffi.rs for why the same
5556            // tile defaults differently by operand source.
5557            if let Some(y) = self.try_fp8_blk_mmq(w, x, m)? { return Ok(y); }
5558            // FP16-mirror prefill (MEMRA_PP_F16=1, probe 2026-07-26: 3.2-3.7x the MMQ class).
5559            // Mirror presence IS the gate (only built under the env). Decode never reaches here.
5560            if let Some(y) = self.try_f16_gemm(w, x, m)? { return Ok(y); }
5561        }
5562        // F8-E4M3 BLOCK-128 (QT_F8_E4M3_BLK, lane/fp8-blk128-decode). TWO arms, split at the SAME
5563        // m threshold the rest of this method uses:
5564        //   * m >= threshold (prefill): dequant-per-call to the ARM B' Q8_0 slab and recurse, so
5565        //     prefill keeps the floor's kernels AND the floor's bits (try_e4m3_blk_prefill).
5566        //   * m <  threshold: the native per-block GEMV — m=1 decode and the m=2..15 verify tiers.
5567        //     grid.y=m runs the exact m=1 program per (token,row), so the decode-parity law holds
5568        //     across every tier by construction with no batched twin needed.
5569        //
5570        // NOT gated on `fast`: this dtype has no dp4a twin and no Stage-A f32-dequant oracle (the
5571        // generic `deq()` switch has no block-scale input), exactly as QT_F8_E4M3 has none, so
5572        // MEMRA_FAST=0 cannot route it anywhere else. Placed before every GEMM/MMQ arm below
5573        // because gemm_supports/mmq_supports/mmvq_supports all deliberately REFUSE this qtype —
5574        // reaching the generic tail would panic rather than produce wrong numbers, and this pair of
5575        // arms is what makes sure it never gets there.
5576        if let GpuTensor::Quant { qtype, .. } = w {
5577            if *qtype == QT_F8_E4M3_BLK {
5578                if m >= GEMM_M_THRESHOLD {
5579                    if let Some(y) = self.try_e4m3_blk_prefill(w, x, m)? { return Ok(y); }
5580                }
5581                let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
5582                if let Some(y) = self.try_e4m3_blk_pre(w, &aq, &ad, m)? { return Ok(y); }
5583            }
5584        }
5585        if m >= GEMM_M_THRESHOLD && out_f >= GEMM_MIN_OUT_F && self.mmq_supports(w) {
5586            return self.qmatvec_mmq(w, x, m);
5587        }
5588        if m >= GEMM_M_THRESHOLD && out_f >= GEMM_MIN_OUT_F && self.gemm_supports(w) {
5589            let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
5590            return self.qmatvec_gemm(w, &aq, &ad, m);
5591        }
5592        // FP4 W4A4 only as an explicit speed/accuracy tradeoff opt-in, and only if the int8 GEMM
5593        // above didn't already handle this weight (e.g. NVFP4 with in_f%64!=0, or MEMRA_NO_GEMM set).
5594        if m >= GEMM_M_THRESHOLD {
5595            if let Some(y) = self.try_fp4_gemm(w, x, m, in_f, out_f)? { return Ok(y); }
5596        }
5597        // Stage-B fast int8 dp4a is the DEFAULT since 2026-07-08 (it has been the daily path
5598        // for weeks; the old opt-in flag was a silent-slow-path landmine). MEMRA_FAST=0 reverts
5599        // to Stage-A f32-dequant (the correctness oracle path).
5600        let fast = std::env::var("MEMRA_FAST").as_deref() != Ok("0");
5601        // PERF-3 decode-GEMV: m=1 warp-per-row MMVQ (MEMRA_MMVQ). The big decode matvecs reach
5602        // `matmul` directly (ffn_down, lm_head output, wo), so route them here too — not only the
5603        // matmul_pre siblings. qmatvec_mmvq_raw quantizes the activation internally (q8_1) like the
5604        // _fast paths; the NVFP4 macro-scale is applied by the `scale != 1.0` block below.
5605        if m == 1 && fast {
5606            if let GpuTensor::Quant { bytes, qtype, row_bytes, rp, rp4, scale, .. } = w {
5607                if self.mmvq_supports(*qtype) {
5608                    // NVFP4 macro-scale rides the kernel's fused epilogue arg (one launch total);
5609                    // non-NVFP4 has scale==1.0 so qmatvec_mmvq skips scale_inplace either way.
5610                    // Q4_0 split-plane mirror (rp4): the decode arm reads it via the _rp twins.
5611                    let (bytes, rp) = match rp4 { Some(m4) => (m4, true), None => (bytes, *rp) };
5612                    let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
5613                    return self.qmatvec_mmvq(bytes, &aq, &ad, m, in_f, out_f, *qtype, *row_bytes, *scale, rp);
5614                }
5615            }
5616        }
5617        // BATCHED weight-resident matvec for the m=2-4 band (the MTP/verify forward's ffn_down, wo, and
5618        // lm_head `output` reach `matmul` directly at m=T=2..4). Walks the weight ONCE, dp4a vs all m
5619        // activation columns -> 1 weight read for m tokens (vs grid.y=m re-reading m times below). Quant
5620        // the activation once here (q8_1) like the _fast paths; macro-scale applied via the scale!=1.0
5621        // block below. MEMRA_NO_BATCHED -> per-m path.
5622        //
5623        // DECODE-PARITY GATE (2026-07-07, the 9B synth K=3/4/6 spec FAIL root cause): the batched
5624        // kernels are bit-identical per (token,row) to MMVQ's 32-thread warp reduce, NOT to the
5625        // dp4a kernels' 128-thread two-level reduce. Without MEMRA_MMVQ the m=1 decode chain rides
5626        // dp4a, so a verify riding batched here has a DIFFERENT FP order than the decode it must
5627        // match bit-for-bit — greedy spec flips at tight-margin tokens (the old HANDOVER "ENV LAW:
5628        // FAST+MMVQ both required" footgun, closed here). Parity law: the m>1 kernel CLASS must be
5629        // a pure function of (dtype, env) equal to the m=1 class — batched iff MMVQ. Without MMVQ
5630        // the verify falls to the per-m grid.y=m dp4a path below (each column = the exact m=1
5631        // dp4a program). MEMRA_MMVQ=1 (the daily config) is dispatch-unchanged.
5632        if (2..=16).contains(&m) && fast && std::env::var("MEMRA_NO_BATCHED").is_err()
5633            && (m <= 4 || Self::b8_enabled()) {
5634            // b16 tier (2026-07-11, spec K>7): Q4_0/Q6_K have base+_rp b16 kernels; Q8_0's
5635            // b16 exists only as the split-plane _rp twin, so it joins iff the q8rp mirror
5636            // is present (rp4) — the mirror pick below then routes to the _rp family.
5637            // QT_F8_E4M3 joins unconditionally (lane/rp-on-st): its b16 IS the base kernel,
5638            // because the native e4m3 row layout is already aligned and needs no mirror.
5639            // NVFP4/Q4_K/Q8_0 all join unconditionally now (lane/rp-on-st): each has base + _rp
5640            // b16 twins, so either residency layout has its aligned form at this width. Q8_0's
5641            // old `rp4.is_some()` precondition is GONE — the mirror is a bandwidth lever, not the
5642            // exact tier's admission ticket (it was refusing FP8-ST over 23.9 MiB of ssm_beta).
5643            let m_ok = m <= 8 || matches!(w, GpuTensor::Quant { qtype, .. }
5644                if *qtype == QT_Q4_0 || *qtype == QT_Q6_K || *qtype == QT_F8_E4M3
5645                    || *qtype == QT_NVFP4 || *qtype == QT_Q4_K || *qtype == QT_Q5_K || *qtype == QT_Q8_0);
5646            if m_ok {
5647            if let GpuTensor::Quant { bytes, qtype, row_bytes, rp, rp4, .. } = w {
5648                if self.batched_supports(*qtype) && self.mmvq_supports(*qtype) {
5649                    let (bytes, rp) = match rp4 { Some(m4) => (m4, true), None => (bytes, *rp) };
5650                    let mcols = Self::batched_mcols(m);
5651                    let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
5652                    let mut y = self.qmatvec_mmvq_batched(bytes, &aq, &ad, m, in_f, out_f, *qtype, *row_bytes, mcols, 1.0, rp)?;
5653                    if let GpuTensor::Quant { scale, .. } = w {
5654                        if *scale != 1.0 { self.scale_inplace(&mut y, *scale, m * out_f)?; }
5655                    }
5656                    return Ok(y);
5657                }
5658            }
5659        }
5660        }
5661        // F8-E4M3 (MEMRA_ST_E4M3) catch-all for the m<16 band the arms above didn't take (m=9..15,
5662        // the K=8 verify tier; or m=2..8 under MEMRA_NO_BATCHED/MEMRA_B8=0): grid.y=m e4m3 mmvq —
5663        // the SAME per-(token,row) program as the m=1 decode launch (bit-identical by construction),
5664        // weight re-read m times (rare tier; exactness over bandwidth here). There is no _dp4a twin
5665        // for this dtype, so the generic match below must never see it under `fast`.
5666        if fast {
5667            if let GpuTensor::Quant { bytes, qtype, row_bytes, scale, .. } = w {
5668                if *qtype == QT_F8_E4M3 {
5669                    let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
5670                    return self.qmatvec_mmvq(bytes, &aq, &ad, m, in_f, out_f, *qtype, *row_bytes,
5671                                             *scale, false);
5672                }
5673            }
5674        }
5675        let mut y = match w {
5676            GpuTensor::Quant { bytes, qtype, row_bytes, .. } if fast && *qtype == QT_Q8_0 =>
5677                self.qmatvec_q8_0_fast(bytes, x, m, in_f, out_f, *row_bytes)?,
5678            GpuTensor::Quant { bytes, qtype, row_bytes, .. } if fast && *qtype == QT_Q4_K =>
5679                self.qmatvec_q4_K_fast(bytes, x, m, in_f, out_f, *row_bytes)?,
5680            GpuTensor::Quant { bytes, qtype, row_bytes, .. } if fast && *qtype == QT_Q6_K =>
5681                self.qmatvec_q6_K_fast(bytes, x, m, in_f, out_f, *row_bytes)?,
5682            GpuTensor::Quant { bytes, qtype, row_bytes, .. } if fast && *qtype == QT_Q5_K =>
5683                self.qmatvec_q5_K_fast(bytes, x, m, in_f, out_f, *row_bytes)?,
5684            GpuTensor::Quant { bytes, qtype, row_bytes, .. } if fast && *qtype == QT_Q3_K =>
5685                self.qmatvec_q3_K_fast(bytes, x, m, in_f, out_f, *row_bytes)?,
5686            GpuTensor::Quant { bytes, qtype, row_bytes, rp, .. } if fast && *qtype == QT_NVFP4 =>
5687                self.qmatvec_dp4a_named(
5688                    if *rp { "qmatvec_nvfp4_dp4a_rp" } else { "qmatvec_nvfp4_dp4a" },
5689                    bytes, x, m, in_f, out_f, *row_bytes)?,
5690            // IQ4_XS trunk fast path — DEFAULT ON since 2026-08-02 (MEMRA_IQ_FAST=0 reverts to
5691            // Stage-A; see iq_fast_enabled). The old opt-in default was the KAT-Coder decode
5692            // anomaly (research/kat-anomaly-20260802/).
5693            GpuTensor::Quant { bytes, qtype, row_bytes, .. }
5694                if fast && *qtype == QT_IQ4_XS && Self::iq_fast_enabled() =>
5695                self.qmatvec_iq4_XS_fast(bytes, x, m, in_f, out_f, *row_bytes)?,
5696            // B3: IQ3_S uses the Stage-A f32 dequant-in-kernel path. There is NO
5697            // qmatvec_iq3_s_dp4a kernel — do NOT add a `*qtype == QT_IQ3_S` fast guard here
5698            // without first writing the matching kernel, or func() will panic
5699            // "kernel ... not in any fatbin".
5700            GpuTensor::Quant { bytes, qtype, row_bytes, rp, .. } =>
5701                // Stage-A generic: repacked NVFP4 uses the device-side split-plane tag (the
5702                // deq(row,j) form cannot address the planes; same value/product order).
5703                self.qmatvec(bytes, x, m, in_f, out_f,
5704                             if *rp && *qtype == QT_NVFP4 { QT_NVFP4_RP } else { *qtype },
5705                             *row_bytes)?,
5706            GpuTensor::Float { data, .. } => self.linear(x, data, m, in_f, out_f)?,
5707            // MEMRA_FULL_PREC bf16-resident weight: dequant-on-use to f32 scratch, then the same
5708            // cuBLASLt f32 GEMV as the Float arm.
5709            GpuTensor::FloatBf16 { data, .. } =>
5710                self.linear_bf16_chunked(x, data, m, in_f, out_f, false)?,
5711        };
5712        // NVFP4 per-tensor macro-scale (post-matmul). scale==1.0 for all other quants/float -> no-op.
5713        if let GpuTensor::Quant { scale, .. } = w {
5714            if *scale != 1.0 { self.scale_inplace(&mut y, *scale, m * out_f)?; }
5715        }
5716        Ok(y)
5717    }
5718
5719    /// True if `w` would take the int8-dp4a fast path under MEMRA_FAST (so its activation can be
5720    /// pre-quantized once and shared across sibling matmuls via `matmul_pre`).
5721    pub fn uses_q8_1_fast(&self, w: &crate::model::GpuTensor) -> bool {
5722        use crate::model::GpuTensor;
5723        if std::env::var("MEMRA_FAST").as_deref() == Ok("0") { return false; }
5724        match w {
5725            // QT_F8_E4M3_BLK is admitted for the same reason QT_F8_E4M3 is: its ONLY kernel class
5726            // takes the shared q8_1 activation, so callers may pre-quantize once and share it
5727            // across siblings. It is NOT admitted to any of the fused/dual epilogue doors those
5728            // siblings can then open (`q8_fused_params`, `e4m3_fused_params` and
5729            // `matmul_pre_dual_noscale` all match on their own qtype and refuse this one) — the
5730            // block class has no fused twin yet, so each of its projections takes its own launch.
5731            GpuTensor::Quant { qtype, .. } => matches!(*qtype,
5732                QT_Q8_0 | QT_Q4_K | QT_Q6_K | QT_Q5_K | QT_Q3_K | QT_NVFP4 | QT_F8_E4M3
5733                | QT_F8_E4M3_BLK | QT_Q4_0)
5734                || (*qtype == QT_IQ4_XS && Self::iq_fast_enabled()),
5735            GpuTensor::Float { .. } | GpuTensor::FloatBf16 { .. } => false,
5736        }
5737    }
5738
5739    /// matmul with a PRE-QUANTIZED q8_1 activation (aq,ad from `quantize_q8_1`). Skips the
5740    /// per-matmul re-quantize so sibling matmuls that share an input (gate+up share `z`;
5741    /// q/k/v + wqkv/gate/beta/alpha share `h`) quantize ONCE. Caller MUST have checked
5742    /// `uses_q8_1_fast(w)`; falls back to plain `matmul` otherwise (Stage-A / Float / non-fast).
5743    pub fn matmul_pre(&self, w: &crate::model::GpuTensor, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
5744                      x_fallback: &CudaSlice<f32>, m: usize)
5745                      -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5746        use crate::model::GpuTensor;
5747        // Every raw-f32 arm below (fp8/f16/MMQ/fp4) reads m*in_f from x_fallback. Callers that
5748        // pre-quantized and dropped the f32 input pass an EMPTY x_fallback (E4B's fusion port:
5749        // h = zeros(0)) — the length guard keeps those on the aq/ad GEMM instead of feeding a
5750        // 0-byte buffer to a convert kernel (illegal address -> cublasLt status 13; the E4B
5751        // rc=30013 dig, 2026-07-31).
5752        let x_raw_ok = x_fallback.len() >= m * w.in_features();
5753        // FP8-ACT PREFILL (MEMRA_PP_FP8=1): same arm as `matmul` — the fp8 operand needs the RAW
5754        // f32 activation (per-batch e4m3 quant differs from q8_1), so x_fallback not aq/ad.
5755        if m >= 16 && x_raw_ok && !self.verify_exact_on() {
5756            if let Some(y) = self.try_fp8_gemm(w, x_fallback, m)? { return Ok(y); }
5757            // PER-BLOCK FP8 MMQ — same arm as `matmul` (stash opt-in, native-resident default ON);
5758            // its own quantizer wants the RAW f32 activation, so x_fallback not aq/ad.
5759            if let Some(y) = self.try_fp8_blk_mmq(w, x_fallback, m)? { return Ok(y); }
5760            // FP16-mirror prefill (same arm as `matmul` — fp16 wants the RAW f32 activation).
5761            if let Some(y) = self.try_f16_gemm(w, x_fallback, m)? { return Ok(y); }
5762        }
5763        // BLOCK-128 e4m3 (QT_F8_E4M3_BLK) — the same two arms as `matmul`, split at the same m, and
5764        // placed at the same point in the order (after the prefill GEMM hooks, before every arm
5765        // that refuses this qtype). The prefill arm needs the RAW f32 activation for the Q8_0
5766        // dispatch it recurses into, so it takes x_fallback and is skipped when that is empty
5767        // (a pre-quantized caller that dropped its f32 input never runs at prefill m anyway).
5768        if m >= 16 && x_raw_ok && !self.verify_exact_on() {
5769            if let Some(y) = self.try_e4m3_blk_prefill(w, x_fallback, m)? { return Ok(y); }
5770        }
5771        if let Some(y) = self.try_e4m3_blk_pre(w, aq, ad, m)? { return Ok(y); }
5772        // VENDORED llama MMQ prefill GEMMs (NVFP4 W4A8 default-on; W4A4/k-quant behind MEMRA_MMQ=1
5773        // — policy in mmq_supports) — use the RAW f32 activation (their own internal quant:
5774        // q8_1 D4 for NVFP4 W4A8, FP8/UE4M3 for W4A4, q8_1 DS4 for Q4_K/Q5_K), so x_fallback not
5775        // aq/ad.
5776        if m >= 16 && w.out_features() >= 128 && self.mmq_supports(w) && !self.verify_exact_on()
5777            && x_raw_ok {
5778            return self.qmatvec_mmq(w, x_fallback, m);
5779        }
5780        // Stage-C FP4 prefill (MEMRA_FP4): native mxf4 GEMM needs the f32 activation (FP4-quant differs
5781        // from q8_1), so re-quantize from x_fallback rather than reuse aq/ad. NVFP4 only, m>=16.
5782        if m >= 16 && x_raw_ok && !self.verify_exact_on() {
5783            if let Some(y) = self.try_fp4_gemm(w, x_fallback, m, w.in_features(), w.out_features())? {
5784                return Ok(y);
5785            }
5786        }
5787        // Prefill GEMM root fix: if T>1 and the dtype has a GEMM kernel, batch via tensor cores
5788        // (reuses the already-quantized aq/ad — no extra quantize). m=1 falls through to dp4a.
5789        if m >= 16 && self.gemm_supports(w) && !self.verify_exact_on() {
5790            return self.qmatvec_gemm(w, aq, ad, m);
5791        }
5792        if !self.uses_q8_1_fast(w) { return self.matmul(w, x_fallback, m); }
5793        let in_f = w.in_features();
5794        let out_f = w.out_features();
5795        let (bytes, qtype, row_bytes, scale, rp) = match w {
5796            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } => (bytes, *qtype, *row_bytes, *scale, *rp),
5797            _ => unreachable!("uses_q8_1_fast guaranteed Quant"),
5798        };
5799        // Q4_0 split-plane mirror: only the mmvq/batched decode arms read it (the _rp twins);
5800        // the dp4a/oracle tails below keep the raw GGUF bytes.
5801        let (mbytes, mrp) = match w {
5802            GpuTensor::Quant { rp4: Some(m4), .. } => (m4, true),
5803            _ => (bytes, rp),
5804        };
5805        // PERF-3 decode-GEMV: warp-per-row MMVQ for the m=1 decode arm, gated behind MEMRA_MMVQ.
5806        // Only the 4 daily-hot dtypes have an _mmvq kernel (Q8_0/Q4_K/Q6_K/NVFP4); Q5_K/Q3_K/IQ4_XS
5807        // keep _dp4a (the oracle/fallback). Bit-equivalent to _dp4a up to f32 reduction order.
5808        if m == 1 && self.mmvq_supports(qtype) {
5809            return self.qmatvec_mmvq(mbytes, aq, ad, m, in_f, out_f, qtype, row_bytes, scale, mrp);
5810        }
5811        // BATCHED weight-resident matvec for the m=2-4 band (the MTP/verify forward: full_attn_verify
5812        // and decode_step_t run their projections at m=T=k=2..4). The plain _dp4a path below launches
5813        // grid.y=m INDEPENDENT blocks per output row -> the weight row is re-read m times from HBM/L2.
5814        // The _b2/_b4 kernels walk the weight ONCE and dp4a vs all m activation columns, so m tokens
5815        // cost ~1 weight read instead of m (decode is weight-BW-bound). BIT-IDENTICAL per (token,row)
5816        // to the _mmvq path (32-thread warp reduce — NOT the dp4a 128-thread reduce below).
5817        // m=2 -> mcols=2; m∈{3,4} -> mcols=4; m∈{5..8} -> mcols=8 (kernel guards c>=m).
5818        // MEMRA_NO_BATCHED forces the per-m grid.y=m path (the A/B reference); MEMRA_B8=0 keeps
5819        // m=5..8 on the old per-m path (b8-tier-only seam).
5820        // DECODE-PARITY GATE (2026-07-07): batched iff mmvq_supports — see matmul's parity note.
5821        // Without MEMRA_MMVQ, m=1 decode rides dp4a (the arm below at m=1); the verify must ride
5822        // the SAME class per column (grid.y=m dp4a = the exact m=1 dp4a program per column).
5823        if (2..=16).contains(&m) && self.batched_supports(qtype) && self.mmvq_supports(qtype)
5824            && std::env::var("MEMRA_NO_BATCHED").is_err()
5825            && (m <= 4 || Self::b8_enabled())
5826            // b16 tier: every class routed here now has base + _rp b16 kernels (Q4_0/Q6_K
5827            // pre-existing; NVFP4/Q4_K/Q8_0-base/F8_E4M3 added lane/rp-on-st 2026-08-06), so
5828            // there is no mirror precondition left — `mrp` still selects the LAYOUT below.
5829            && (m <= 8 || qtype == QT_Q4_0 || qtype == QT_Q6_K || qtype == QT_NVFP4
5830                || qtype == QT_Q4_K || qtype == QT_Q5_K || qtype == QT_F8_E4M3 || qtype == QT_Q8_0) {
5831            let mcols = Self::batched_mcols(m);
5832            return self.qmatvec_mmvq_batched(mbytes, aq, ad, m, in_f, out_f, qtype, row_bytes, mcols, scale, mrp);
5833        }
5834        // F8-E4M3 catch-all (m=9..15 / batched-disabled seams): grid.y=m e4m3 mmvq — this dtype
5835        // has NO _dp4a twin, and per (token,row) the mmvq body is the exact m=1 decode program.
5836        // Q4_0 joins the catch-all (2026-07-11): adaptive-K cap 8 makes verify t=9 reachable
5837        // for the first time (past the b8 tier) and Q4_0 has no dp4a twin either. The mirror
5838        // (mbytes/mrp) keeps the rp layout consistent with the m=1 decode program.
5839        if qtype == QT_F8_E4M3 || qtype == QT_Q4_0 {
5840            let (b2, r2) = if qtype == QT_Q4_0 { (mbytes, mrp) } else { (bytes, rp) };
5841            return self.qmatvec_mmvq(b2, aq, ad, m, in_f, out_f, qtype, row_bytes, scale, r2);
5842        }
5843        let name = match qtype {
5844            QT_Q8_0 => "qmatvec_q8_0_dp4a", QT_Q4_K => "qmatvec_q4_K_dp4a",
5845            QT_Q6_K => "qmatvec_q6_K_dp4a", QT_Q5_K => "qmatvec_q5_K_dp4a",
5846            QT_Q3_K => "qmatvec_q3_K_dp4a",
5847            QT_NVFP4 => if rp { "qmatvec_nvfp4_dp4a_rp" } else { "qmatvec_nvfp4_dp4a" },
5848            QT_IQ4_XS => "qmatvec_iq4_XS_dp4a",
5849            _ => unreachable!(),
5850        };
5851        let f = self.func(name);
5852        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite GEMM output: skip memset
5853        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
5854        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
5855        let __s_b = self.gpu.stream();
5856        let mut b = __s_b.launch_builder(&f);
5857        b.arg(bytes).arg(aq).arg(ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
5858        unsafe { b.launch(cfg)?; }
5859        if scale != 1.0 { self.scale_inplace(&mut y, scale, m * out_f)?; }
5860        Ok(y)
5861    }
5862
5863    /// DECODE-EXACT matmul at any m: guarantees the SAME warp-per-row (MMVQ, 32-thread) FP
5864    /// accumulation order as the T=1 decode path for EVERY token row. The spec-decode verify MUST
5865    /// use this for linear-attn projections to be bit-identical to greedy decode. The dp4a kernel
5866    /// (128 threads, two-level reduction) used by `matmul`/`matmul_pre` at m>=5 has a different
5867    /// shfl-tree shape that produces ULP differences propagating through gdn_scan into argmax flips.
5868    /// The MMVQ kernel with grid.y=m already processes each row independently (same 32-thread warp
5869    /// reduce as m=1); this method just forces that path unconditionally.
5870    pub fn matmul_decode_exact(&self, w: &crate::model::GpuTensor, x: &CudaSlice<f32>, m: usize)
5871                               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5872        use crate::model::GpuTensor;
5873        // FLOAT tensors (35B ssm_beta/ssm_alpha on every linear layer, F32 ne=[2048,32]): the
5874        // generic path is cuBLASLt, whose reduction splits are n-DEPENDENT — m=1 vs m=2 col-0
5875        // outputs differ in every bit (probe 2026-07-06: 32/32 bit-diff, maxdiff 3.5e-3), which
5876        // shifted 35B verify logits 0.26-0.56 vs eager and flipped greedy at tight margins (the
5877        // p3 spec FAIL). Decode-exact contract: per-COLUMN m=1 cuBLASLt calls — each column's
5878        // reduction is the exact kernel the T=1 decode path runs, so verify==decode bit-for-bit.
5879        // m<=10 here (K+2 verify tier), so the extra launches are a handful of 4us gemvs.
5880        if let GpuTensor::Float { data, .. } = w {
5881            return self.linear_decode_exact(x, data, m, w.in_features(), w.out_features());
5882        }
5883        // MEMRA_FULL_PREC bf16-resident weight: dequant-on-use, then the per-column decode-exact
5884        // float linear (same n-independent reduction contract as the Float arm above).
5885        if let GpuTensor::FloatBf16 { data, .. } = w {
5886            let (in_f, out_f) = (w.in_features(), w.out_features());
5887            return self.linear_bf16_chunked(x, data, m, in_f, out_f, true);
5888        }
5889        if !self.uses_q8_1_fast(w) { return self.matmul(w, x, m); }
5890        let in_f = w.in_features();
5891        let out_f = w.out_features();
5892        let (bytes, qtype, row_bytes, scale, rp) = match w {
5893            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } => (bytes, *qtype, *row_bytes, *scale, *rp),
5894            _ => return self.matmul(w, x, m),
5895        };
5896        // Q4_0 split-plane mirror for the mmvq/batched arms below (dp4a tail = matmul_pre,
5897        // which does its own mirror pick).
5898        let (bytes, rp) = match w {
5899            GpuTensor::Quant { rp4: Some(m4), .. } => (m4, true),
5900            _ => (bytes, rp),
5901        };
5902        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
5903        // BLOCK-128 e4m3 (QT_F8_E4M3_BLK): the same single kernel every other entry dispatches, so
5904        // the decode-exact contract needs nothing special — grid.y=m runs the m=1 program per
5905        // (token,row) by construction, which is exactly what this method exists to guarantee.
5906        if let Some(y) = self.try_e4m3_blk_pre(w, &aq, &ad, m)? { return Ok(y); }
5907        // Batched weight-resident matvec for m=2-8: BIT-IDENTICAL per (token,row) to MMVQ (exact
5908        // integer dp4a, same warp reduce — kernel-check gate rel=0.00e0), one weight read for m
5909        // tokens. The dispatch the divergence fix must avoid is dp4a's 128-thread two-level
5910        // reduce, NOT this. m=5..8 is the K=4..7 spec-verify tier (b8): pre-b8 T=5 fell to the
5911        // grid.y=m per-row MMVQ below = 5 full weight reads/launch — the measured 27B K=4 cliff.
5912        // DECODE-PARITY GATE (2026-07-07): batched (MMVQ-class order) only when the m=1 decode
5913        // chain rides MMVQ too — without MEMRA_MMVQ decode is dp4a, so the exact-contract here
5914        // must be per-column dp4a (matmul_pre fallthrough), not the MMVQ order.
5915        if (2..=16).contains(&m) && self.batched_supports(qtype) && self.mmvq_supports(qtype)
5916            && std::env::var("MEMRA_NO_BATCHED").is_err()
5917            && (m <= 4 || Self::b8_enabled())
5918            // Every b16 class has base + _rp twins after lane/rp-on-st (see matmul_pre's note):
5919            // no mirror precondition, `rp` selects the layout only.
5920            && (m <= 8 || qtype == QT_Q4_0 || qtype == QT_Q6_K || qtype == QT_F8_E4M3
5921                || qtype == QT_NVFP4 || qtype == QT_Q4_K || qtype == QT_Q5_K || qtype == QT_Q8_0) {
5922            let mcols = Self::batched_mcols(m);
5923            return self.qmatvec_mmvq_batched(bytes, &aq, &ad, m, in_f, out_f, qtype, row_bytes, mcols, scale, rp);
5924        }
5925        if self.mmvq_supports(qtype) {
5926            // MMVQ at grid.y=m: each row is processed by its own warp independently — same 32-thread
5927            // accumulation + warp_reduce_sum as m=1 decode. Bit-identical per row.
5928            return self.qmatvec_mmvq(bytes, &aq, &ad, m, in_f, out_f, qtype, row_bytes, scale, rp);
5929        }
5930        // Fallback for non-MMVQ quant types (Q5_K, Q3_K): use dp4a (the only available kernel).
5931        // These types are not used in the 27B's linear-attn NVFP4+Q4_K layers.
5932        self.matmul_pre(w, &aq, &ad, x, m)
5933    }
5934
5935    /// DECODE-EXACT matmul from a PRE-QUANTIZED q8_1 activation (batched-verify epilogue
5936    /// re-fuse, lane/vt-fixes fix 2, 2026-08-03): the EXACT `matmul_decode_exact` dispatch for
5937    /// q8_1-fast Quant tensors, with the caller's (aq, ad) replacing the internal
5938    /// `quantize_q8_1`. quantize_q8_1 is deterministic (same input bytes -> same q8 bytes), so
5939    /// sharing one quantize across sibling matmuls of the same activation — or consuming the
5940    /// q8 emitted by a fused epilogue (rms_norm_q8_1 / add_rms_norm_q8_1 /
5941    /// silu_mul_scaled_q8_1 / gated_rmsnorm_q8_1, all kernel-check-pinned bit-identical to
5942    /// their unfused chains) — cannot change any dispatched kernel's input bytes.
5943    /// Caller MUST guarantee `uses_q8_1_fast(w)` (the fused epilogues only exist on that path).
5944    pub fn matmul_decode_exact_pre(&self, w: &crate::model::GpuTensor, aq: &CudaSlice<i8>,
5945                                   ad: &CudaSlice<f32>, m: usize)
5946                                   -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5947        use crate::model::GpuTensor;
5948        debug_assert!(self.uses_q8_1_fast(w),
5949                      "matmul_decode_exact_pre: caller must guarantee q8_1-fast");
5950        // BLOCK-128 e4m3: same single kernel, all m — see matmul_decode_exact's note.
5951        if let Some(y) = self.try_e4m3_blk_pre(w, aq, ad, m)? { return Ok(y); }
5952        let in_f = w.in_features();
5953        let out_f = w.out_features();
5954        let (bytes, qtype, row_bytes, scale, rp) = match w {
5955            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } =>
5956                (bytes, *qtype, *row_bytes, *scale, *rp),
5957            _ => return Err("matmul_decode_exact_pre: Quant tensor required (q8_1-fast contract)".into()),
5958        };
5959        // Q4_0 split-plane mirror — same pick as matmul_decode_exact.
5960        let (bytes, rp) = match w {
5961            GpuTensor::Quant { rp4: Some(m4), .. } => (m4, true),
5962            _ => (bytes, rp),
5963        };
5964        // Dispatch mirror of matmul_decode_exact's q8_1-fast tail, condition for condition.
5965        if (2..=16).contains(&m) && self.batched_supports(qtype) && self.mmvq_supports(qtype)
5966            && std::env::var("MEMRA_NO_BATCHED").is_err()
5967            && (m <= 4 || Self::b8_enabled())
5968            && (m <= 8 || qtype == QT_Q4_0 || qtype == QT_Q6_K || qtype == QT_F8_E4M3
5969                || qtype == QT_NVFP4 || qtype == QT_Q4_K || qtype == QT_Q5_K || qtype == QT_Q8_0) {
5970            let mcols = Self::batched_mcols(m);
5971            return self.qmatvec_mmvq_batched(bytes, aq, ad, m, in_f, out_f, qtype, row_bytes, mcols, scale, rp);
5972        }
5973        if self.mmvq_supports(qtype) {
5974            return self.qmatvec_mmvq(bytes, aq, ad, m, in_f, out_f, qtype, row_bytes, scale, rp);
5975        }
5976        // Non-MMVQ quant types (Q5_K/Q3_K under MEMRA_MMVQ=0): dp4a via matmul_pre — the same
5977        // fallback matmul_decode_exact takes. m <= 16 on the verify tier never reads x_fallback.
5978        let x0 = self.zeros(0)?;
5979        self.matmul_pre(w, aq, ad, &x0, m)
5980    }
5981
5982    /// DUAL gate+up batched matvec from a PRE-QUANTIZED activation, macro-scales DEFERRED
5983    /// (lane/vt-fixes fix 2): same eligibility as `matmul_decode_exact_dual`, but the caller's
5984    /// (aq, ad) replaces the internal quantize and the NVFP4 per-tensor scales are RETURNED
5985    /// instead of applied via two `scale_inplace` launches — the fused SwiGLU epilogue
5986    /// (`silu_mul_scaled_q8_1`) folds them, exactly like the m=1 decode chain does. Deferring
5987    /// is value-exact: `y[i]*s` inline in the epilogue is the same IEEE multiply scale_inplace
5988    /// would store (f32 store/load round-trips are exact). None -> caller falls back to the
5989    /// per-tensor path.
5990    pub fn matmul_decode_exact_dual_pre(&self, w0: &crate::model::GpuTensor,
5991                                        w1: &crate::model::GpuTensor,
5992                                        aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize)
5993        -> Result<Option<((CudaSlice<f32>, f32), (CudaSlice<f32>, f32))>, Box<dyn std::error::Error>> {
5994        use crate::model::GpuTensor;
5995        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5996        let on = *ON.get_or_init(|| {
5997            std::env::var("MEMRA_SPEC_DUAL_T").map(|v| v != "0").unwrap_or(true)
5998        });
5999        if !on || !(2..=7).contains(&m) || std::env::var("MEMRA_NO_BATCHED").is_ok()
6000            || !self.uses_q8_1_fast(w0) || !self.uses_q8_1_fast(w1) {
6001            return Ok(None);
6002        }
6003        // DECODE-PARITY GATE (lane/nvfp4-strict, 2026-08-05): batched iff MMVQ — the dual
6004        // kernels are the MMVQ warp-reduce family, and without MEMRA_MMVQ the m=1 decode
6005        // chain this verify must match bit-for-bit rides dp4a (see matmul_decode_exact's
6006        // note). The singles enforce this via `mmvq_supports`; the dual door skipped it.
6007        if !self.mmvq_supports(QT_NVFP4) { return Ok(None); }
6008        let (in_f, out_f) = (w0.in_features(), w0.out_features());
6009        if w1.in_features() != in_f || w1.out_features() != out_f {
6010            return Ok(None);
6011        }
6012        let (b0, b1, row_bytes, s0, s1, rp) = match (w0, w1) {
6013            (GpuTensor::Quant { bytes: b0, qtype: q0, row_bytes: rb0, scale: s0, rp: rp0, rp4: None, .. },
6014             GpuTensor::Quant { bytes: b1, qtype: q1, row_bytes: rb1, scale: s1, rp: rp1, rp4: None, .. })
6015                if *q0 == QT_NVFP4 && *q1 == QT_NVFP4 && rb0 == rb1 && rp0 == rp1 =>
6016                (b0, b1, *rb0, *s0, *s1, *rp0),
6017            _ => return Ok(None),
6018        };
6019        // m=5..7: only the exact-width rp duals exist (vt-fixes fix 1b); GGUF layout keeps
6020        // the singles. The b8 dual (MCOLS=8 at m=5..8) measured FLAT and stays dead.
6021        if m > 4 && !(rp && Self::b8_enabled()
6022            && std::env::var("MEMRA_B567").as_deref() != Ok("0")) {
6023            return Ok(None);
6024        }
6025        let (y0, y1) = self.qmatvec_batched_dual_raw(b0, b1, aq, ad, m, in_f, out_f, row_bytes, rp)?;
6026        Ok(Some(((y0, s0), (y1, s1))))
6027    }
6028
6029    /// DUAL gate+up BATCHED matvec at verify t=2..8 (lane/verify-economics, 2026-08-02): ONE
6030    /// launch computes both FFN projections of a verify batch — same activation, same shape,
6031    /// blockIdx.y selects the tensor. Per (tensor, token, row) the kernel body is the single
6032    /// batched program on the SAME layout (split-plane rp: b2 rp / b4 rpr2 / b8 rpr2; GGUF:
6033    /// b2 base / b4 r2 / b8 r2) -> BIT-IDENTICAL to the two single `matmul_decode_exact`
6034    /// launches (kernel-check gates bitwise on both layouts; run-spec K=1..8 arbitrates e2e).
6035    /// The one activation quantize replaces two IDENTICAL quantizes of the same `x` (same
6036    /// kernel, same input -> same q8_1 bytes), and the two independent weight streams in one
6037    /// grid restore the memory-level parallelism the two-launch form loses to tail drain +
6038    /// launch gap (m=1 dual_mr2 precedent: DRAM 40% -> 47-50% on the 27B pair).
6039    /// `Some((y0, y1))` only when both tensors are NVFP4, the SAME layout (both rp or both
6040    /// GGUF, no rp4 mirror), identical (in_f, out_f, row_bytes), q8_1-fast, and m in 2..=4
6041    /// (the b2/b4 tiers = verify T for K=1..3, the profitable-K window — the b8 dual measured
6042    /// FLAT vs the rpsc singles x3 interleaved, research/verify-economics-20260802, and was
6043    /// killed per doctrine). None -> caller runs the two singles. MEMRA_SPEC_DUAL_T=0 rollback.
6044    pub fn matmul_decode_exact_dual(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6045                                    x: &CudaSlice<f32>, m: usize)
6046        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6047        use crate::model::GpuTensor;
6048        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6049        let on = *ON.get_or_init(|| {
6050            std::env::var("MEMRA_SPEC_DUAL_T").map(|v| v != "0").unwrap_or(true)
6051        });
6052        if !on || !(2..=4).contains(&m) || std::env::var("MEMRA_NO_BATCHED").is_ok()
6053            || !self.uses_q8_1_fast(w0) || !self.uses_q8_1_fast(w1) {
6054            return Ok(None);
6055        }
6056        // DECODE-PARITY GATE (lane/nvfp4-strict, 2026-08-05): batched iff MMVQ — same law as
6057        // the singles' `batched_supports && mmvq_supports` check in matmul_decode_exact,
6058        // which this dual door bypassed. Without MEMRA_MMVQ the m=1 decode is dp4a; the
6059        // verify must ride the per-column dp4a class, not the MMVQ-family dual.
6060        if !self.mmvq_supports(QT_NVFP4) { return Ok(None); }
6061        let (in_f, out_f) = (w0.in_features(), w0.out_features());
6062        if w1.in_features() != in_f || w1.out_features() != out_f {
6063            return Ok(None);
6064        }
6065        let (b0, b1, row_bytes, s0, s1, rp) = match (w0, w1) {
6066            (GpuTensor::Quant { bytes: b0, qtype: q0, row_bytes: rb0, scale: s0, rp: rp0, rp4: None, .. },
6067             GpuTensor::Quant { bytes: b1, qtype: q1, row_bytes: rb1, scale: s1, rp: rp1, rp4: None, .. })
6068                if *q0 == QT_NVFP4 && *q1 == QT_NVFP4 && rb0 == rb1 && rp0 == rp1 =>
6069                (b0, b1, *rb0, *s0, *s1, *rp0),
6070            _ => return Ok(None),
6071        };
6072        // Engagement receipt (MEMRA_DEBUG=1): the first dead-arm A/B lesson — a `rp: false`
6073        // gate silently no-op'd the whole experiment; prove the arm is live in the log.
6074        if std::env::var("MEMRA_DEBUG").is_ok() {
6075            static ONCE: std::sync::Once = std::sync::Once::new();
6076            ONCE.call_once(|| eprintln!("[memra] dual gate+up batched ENGAGED (m={m} rp={rp})"));
6077        }
6078        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
6079        let (y0, y1) = self.qmatvec_batched_dual_raw(b0, b1, &aq, &ad, m, in_f, out_f, row_bytes, rp)?;
6080        let mut y0 = y0;
6081        let mut y1 = y1;
6082        if s0 != 1.0 { self.scale_inplace(&mut y0, s0, m * out_f)?; }
6083        if s1 != 1.0 { self.scale_inplace(&mut y1, s1, m * out_f)?; }
6084        Ok(Some((y0, y1)))
6085    }
6086
6087    /// Launch body of the dual batched twins from raw NVFP4 weight bytes + a pre-quantized q8_1
6088    /// activation (kernel-check's bit-equivalence entry; matmul_decode_exact_dual's core).
6089    /// mcols tier = batched_mcols(m); macro-scale NOT applied. `rp` selects the split-plane
6090    /// twins (both buffers must be the repacked layout).
6091    #[allow(clippy::too_many_arguments)]
6092    pub fn qmatvec_batched_dual_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
6093                                    aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
6094                                    m: usize, in_f: usize, out_f: usize, row_bytes: usize, rp: bool)
6095        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6096        const ROWS_PER_BLOCK: u32 = 4;
6097        let mcols = Self::batched_mcols(m);
6098        // EXACT-WIDTH duals at m=5..7 (vt-fixes fix 1b): rp-only; bit-identical to the two
6099        // b5/b6/b7 singles (blockIdx.y selects the tensor, same template body).
6100        let (name, rows_per_block) = match (mcols, rp, m) {
6101            (2, false, _) => ("qmatvec_nvfp4_mmvq_dual_b2", ROWS_PER_BLOCK),
6102            (4, false, _) => ("qmatvec_nvfp4_mmvq_dual_b4_r2", ROWS_PER_BLOCK * 2),
6103            (2, true, _) => ("qmatvec_nvfp4_mmvq_dual_b2_rp", ROWS_PER_BLOCK),
6104            (4, true, _) => ("qmatvec_nvfp4_mmvq_dual_b4_rpr2", ROWS_PER_BLOCK * 2),
6105            (8, true, 5) => ("qmatvec_nvfp4_mmvq_dual_b5_rpr2", ROWS_PER_BLOCK * 2),
6106            (8, true, 6) => ("qmatvec_nvfp4_mmvq_dual_b6_rpr2", ROWS_PER_BLOCK * 2),
6107            (8, true, 7) => ("qmatvec_nvfp4_mmvq_dual_b7_rpr2", ROWS_PER_BLOCK * 2),
6108            _ => return Err(format!("qmatvec_batched_dual_raw: no dual kernel for m {m}").into()),
6109        };
6110        let f = self.func(name);
6111        let mut y0 = self.alloc_uninit::<f32>(m * out_f)?;
6112        let mut y1 = self.alloc_uninit::<f32>(m * out_f)?;
6113        let cfg = LaunchConfig {
6114            grid_dim: ((out_f as u32 + rows_per_block - 1) / rows_per_block, 2, 1),
6115            block_dim: (32, ROWS_PER_BLOCK, 1),
6116            shared_mem_bytes: 0,
6117        };
6118        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
6119        let __s_b = self.gpu.stream();
6120        let mut b = __s_b.launch_builder(&f);
6121        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
6122            .arg(&inf).arg(&outf).arg(&mi).arg(&rb);
6123        unsafe { b.launch(cfg)?; }
6124        Ok((y0, y1))
6125    }
6126
6127    /// Like `matmul_pre` but RETURNS THE RAW (un-macro-scaled) matmul output together with the
6128    /// per-tensor NVFP4 scale, instead of applying `scale_inplace` internally. Used by the fused
6129    /// SwiGLU epilogue (RANK3 LEVER 2) so the gate/up scales fold into one `silu_mul_scaled` launch.
6130    /// `Some((y_raw, scale))` only on the m==1 decode fast path (mmvq / dp4a) where the scale is a
6131    /// separate post-launch op we can defer; returns `None` for every other path (prefill GEMM, FP4
6132    /// GEMM, Stage-A, Float) so the caller falls back to the scaled `matmul_pre` + `silu_mul`.
6133    /// DUAL gate+up NVFP4 matvec (mm-fusion): ONE launch computes both projections (same
6134    /// activation, same shape) — grid.y selects the tensor. Bit-identical per element to two
6135    /// mr2 launches at m=1. Returns (gate_raw, up_raw) un-scaled (caller folds the two macro
6136    /// scales into the SwiGLU epilogue, same as the matmul_pre_noscale contract). None unless
6137    /// both tensors are NVFP4 q8_1-fast with identical (in_f, out_f, row_bytes) and m==1.
6138    pub fn matmul_pre_dual_noscale(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6139                                   aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize)
6140        -> Result<Option<((CudaSlice<f32>, f32), (CudaSlice<f32>, f32))>, Box<dyn std::error::Error>> {
6141        use crate::model::GpuTensor;
6142        if m != 1 || !self.uses_q8_1_fast(w0) || !self.uses_q8_1_fast(w1) { return Ok(None); }
6143        // FP-ORDER LAW (lane/nvfp4-strict, 2026-08-05): every kernel this door can dispatch
6144        // (q8_0 fused2, nvfp4 dual_mr2) is the MMVQ family — 32-thread warp reduce. Without
6145        // MEMRA_MMVQ the m=1 singles ride dp4a (128-thread two-level reduce), so fusing here
6146        // would mix dispatch families across the pair — the exact class `q8_fused_params`
6147        // already refuses for Q8_0. The NVFP4 arm lacked this check, which is why
6148        // decode-batch-gate `--mode strict`'s equalizing env (MEMRA_MMVQ=0) never pinned
6149        // NVFP4 models: decode_step_h kept riding dual_mr2 while the batched body fell to
6150        // dp4a (gate1 maxdiff 1.639e-1 / gate2 step-8 divergence at the 2026-08-05 train
6151        // HEAD, research/nvfp4-strict-20260805/). Default env (MMVQ on) is dispatch-unchanged.
6152        if !self.mmvq_supports(QT_NVFP4) { return Ok(None); }
6153        let (in_f, out_f) = (w0.in_features(), w0.out_features());
6154        if w1.in_features() != in_f || w1.out_features() != out_f { return Ok(None); }
6155        // Q8_0 ARM (lane/q27-deepdive, 2026-08-05): the dense-FFN gate+up pair on a Q8_0 trunk fell
6156        // through this NVFP4-only gate to two `matmul_pre_noscale` launches — measured 128 of the
6157        // 1015 launches/token on q27-Q8_0 decode, the single largest un-fused class in the tick
6158        // (nsys `research/q27-deepdive-20260805/nsys/`). `q8_fused2_core` already serves the same
6159        // pair shape for the shared-expert gate/up, and its kernel body is `qmatvec_q8_0_mmvq`
6160        // VERBATIM per (tensor,row) -> BIT-IDENTICAL to the two separate launches. Q8_0 carries no
6161        // macro-scale (q8_fused_params requires scale==1.0), so the noscale contract is satisfied
6162        // by returning 1.0 for both: the SwiGLU epilogue's fold becomes the identity it already is
6163        // on this dtype today. Seam: MEMRA_Q8_FFN_FUSE2=0 rolls back to the two-launch pair.
6164        // rp4 guard: with MEMRA_Q8RP the singles route to the `_rp` split-plane twin over the
6165        // mirror buffer; the fused2 kernel has no `_rp` form, so fusing there would swap
6166        // dispatch families mid-model. Bail and let the two singles run (mirror lane unchanged).
6167        let no_mirror = |w: &crate::model::GpuTensor| {
6168            !matches!(w, GpuTensor::Quant { rp4: Some(_), .. })
6169        };
6170        if self.q8_ffn_fuse2_on()
6171            && no_mirror(w0) && no_mirror(w1)
6172            && let Some([p0, p1]) = self.q8_fused_params(&[w0, w1])
6173        {
6174            let (y0, y1) = self.q8_fused2_core(p0.0, p1.0, aq, ad, in_f, p0.1, p1.1, p0.2)?;
6175            return Ok(Some(((y0, 1.0), (y1, 1.0))));
6176        }
6177        // F8-E4M3 ARM (lane/fp8-decode-v1, 2026-08-05): with native e4m3 residency the FFN gate+up
6178        // pair (and the ssm beta+alpha dual, which routes through this same entry) fell through
6179        // both the NVFP4 gate below and the Q8_0 arm above to two `matmul_pre_noscale` launches —
6180        // native residency was UN-FUSING the trunk relative to the Q8_0 slab it replaces. The
6181        // fused2 kernel body is `qmatvec_e4m3_mmvq` VERBATIM per (tensor,row). Contract match:
6182        // `matmul_pre_noscale` on e4m3 launches with scale 1.0 and RETURNS the per-tensor
6183        // weight_scale for the caller to fold, so we pass ws=1.0 here and return (s0,s1) — same
6184        // bits, and the two macro-scale multiplies still fold into the SwiGLU epilogue.
6185        // MEMRA_E4M3_DUAL=0 rolls back to the two-launch pair.
6186        if let Some([p0, p1]) = self.e4m3_fused_params(&[w0, w1]) {
6187            let (y0, y1) = self.e4m3_fused2_core(p0.0, p1.0, aq, ad, in_f, p0.1, p1.1, p0.2,
6188                                                 1.0, 1.0)?;
6189            return Ok(Some(((y0, p0.3), (y1, p1.3))));
6190        }
6191        let (b0, q0, rb0, s0, rp0) = match w0 {
6192            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } => (bytes, *qtype, *row_bytes, *scale, *rp),
6193            _ => return Ok(None),
6194        };
6195        let (b1, q1, rb1, s1, rp1) = match w1 {
6196            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } => (bytes, *qtype, *row_bytes, *scale, *rp),
6197            _ => return Ok(None),
6198        };
6199        if q0 != QT_NVFP4 || q1 != QT_NVFP4 || rb0 != rb1 || rp0 != rp1 { return Ok(None); }
6200        const ROWS_PER_BLOCK: u32 = 4;   // matches MEMRA_MMVQ_ROWS in qmatvec.cu
6201        const RPW: u32 = 2;
6202        let rows_per_block = ROWS_PER_BLOCK * RPW;
6203        let f = self.func(if rp0 { "qmatvec_nvfp4_mmvq_dual_mr2_rp" } else { "qmatvec_nvfp4_mmvq_dual_mr2" });
6204        let mut y0 = self.alloc_uninit::<f32>(out_f)?;
6205        let mut y1 = self.alloc_uninit::<f32>(out_f)?;
6206        let cfg = LaunchConfig {
6207            grid_dim: ((out_f as u32 + rows_per_block - 1) / rows_per_block, 2, 1),
6208            block_dim: (32, ROWS_PER_BLOCK, 1), shared_mem_bytes: 0,
6209        };
6210        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, 1i32, rb0 as i64);
6211        // noscale contract: the caller folds s0/s1 into the SwiGLU epilogue — the kernel's fused
6212        // yscale args stay 1.0 here (they exist for the single-tensor callers).
6213        let one = 1.0f32;
6214        let __s_b = self.gpu.stream();
6215        let mut b = __s_b.launch_builder(&f);
6216        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
6217         .arg(&inf).arg(&outf).arg(&mi).arg(&rb).arg(&one).arg(&one);
6218        unsafe { b.launch(cfg)?; }
6219        Ok(Some(((y0, s0), (y1, s1))))
6220    }
6221
6222    /// FUSED Q8_0 m=1 matvec PAIR with UNEQUAL out_f (trunk launch-fusion, 2026-07-05). Folds two
6223    /// same-input q8_0 projections (35B trunk: wqkv+wqkv_gate 8192/4096, gate_shexp+up_shexp
6224    /// 512/512) into ONE launch via a block-offset split (blocks [0,nb0) -> w0, rest -> w1) — the
6225    /// dual-mr2 recipe with the same-out_f restriction lifted. Per (tensor,row) the kernel body is
6226    /// qmatvec_q8_0_mmvq VERBATIM -> BIT-IDENTICAL to two separate m=1 launches. Returns None when
6227    /// ineligible (not both Q8_0 / in_f mismatch / MEMRA_MMVQ off / MEMRA_Q8_DUAL=0) — caller falls
6228    /// back to the per-tensor path.
6229    pub fn matmul_q8_fused2(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6230                            aq: &CudaSlice<i8>, ad: &CudaSlice<f32>)
6231        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6232        // e4m3 twin (lane/fp8-decode-v1): this entry is the trunk's generic m=1 pair door
6233        // (wqkv+wqkv_gate, ssm_beta+alpha, gate_shexp+up_shexp), so admitting QT_F8_E4M3 here
6234        // fuses the NATIVE-RESIDENCY FP8 trunk at every existing call site with no call-site
6235        // change. Scale is folded in-kernel per range -> the returned buffers are already scaled,
6236        // exactly like the per-tensor `matmul_pre` e4m3 dispatch this replaces.
6237        if let Some([p0, p1]) = self.e4m3_fused_params(&[w0, w1]) {
6238            return Ok(Some(self.e4m3_fused2_core(p0.0, p1.0, aq, ad, w0.in_features(),
6239                                                 p0.1, p1.1, p0.2, p0.3, p1.3)?));
6240        }
6241        let Some([p0, p1]) = self.q8_fused_params(&[w0, w1]) else { return Ok(None) };
6242        Ok(Some(self.q8_fused2_core(p0.0, p1.0, aq, ad, w0.in_features(), p0.1, p1.1, p0.2)?))
6243    }
6244
6245    #[allow(clippy::too_many_arguments)]
6246    fn q8_fused2_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
6247                      aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
6248                      in_f: usize, out0: usize, out1: usize, row_bytes: usize)
6249        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6250        const ROWS_PER_BLOCK: u32 = 4;   // matches MEMRA_MMVQ_ROWS in qmatvec.cu
6251        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
6252        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
6253        let f = self.func("qmatvec_q8_0_mmvq_fused2");
6254        let mut y0 = self.alloc_uninit::<f32>(out0)?;
6255        let mut y1 = self.alloc_uninit::<f32>(out1)?;
6256        let cfg = LaunchConfig { grid_dim: (nb0 + nb1, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
6257                                 shared_mem_bytes: 0 };
6258        let (inf, o0, o1, rbl) = (in_f as i32, out0 as i32, out1 as i32, row_bytes as i64);
6259        let __s_b = self.gpu.stream();
6260        let mut b = __s_b.launch_builder(&f);
6261        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
6262         .arg(&inf).arg(&o0).arg(&o1).arg(&rbl);
6263        unsafe { b.launch(cfg)?; }
6264        Ok((y0, y1))
6265    }
6266
6267    /// f32-activation entry for the fused2 pair: quantizes x to q8_1 ONCE then runs the fused
6268    /// launch — replaces two `matmul(w, x, 1)` calls that would each re-quantize the same x
6269    /// (35B shared-expert gate+up per MoE layer per token). Same bits: quantize_q8_1 is
6270    /// deterministic, the fused body is the MMVQ kernel verbatim. None when ineligible (the
6271    /// callers' m==1-under-MEMRA_FAST dispatch would take MMVQ; anything else falls back).
6272    pub fn matmul_q8_fused2_x(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6273                              x: &CudaSlice<f32>)
6274        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6275        if !self.uses_q8_1_fast(w0) || !self.uses_q8_1_fast(w1) { return Ok(None); }
6276        if let Some([p0, p1]) = self.e4m3_fused_params(&[w0, w1]) {
6277            let (aq, ad) = self.quantize_q8_1(x, 1, w0.in_features())?;
6278            return Ok(Some(self.e4m3_fused2_core(p0.0, p1.0, &aq, &ad, w0.in_features(),
6279                                                 p0.1, p1.1, p0.2, p0.3, p1.3)?));
6280        }
6281        let Some([p0, p1]) = self.q8_fused_params(&[w0, w1]) else { return Ok(None) };
6282        let (aq, ad) = self.quantize_q8_1(x, 1, w0.in_features())?;
6283        Ok(Some(self.q8_fused2_core(p0.0, p1.0, &aq, &ad, w0.in_features(), p0.1, p1.1, p0.2)?))
6284    }
6285
6286    /// Test entry for the kernel_check gate: launch the fused2 kernel from raw weight bytes,
6287    /// quantizing the f32 activation internally (mirrors qmatvec_mmvq_raw; no env gating).
6288    #[allow(clippy::too_many_arguments)]
6289    pub fn qmatvec_q8_fused2_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, x: &CudaSlice<f32>,
6290                                 in_f: usize, out0: usize, out1: usize, row_bytes: usize)
6291        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6292        let (aq, ad) = self.quantize_q8_1(x, 1, in_f)?;
6293        self.q8_fused2_core(b0, b1, &aq, &ad, in_f, out0, out1, row_bytes)
6294    }
6295
6296    /// FUSED Q8_0 m=1 matvec TRIPLE (wq+wk+wv on the 35B full-attn layers: out_f 8192/512/512).
6297    /// Same block-offset recipe as `matmul_q8_fused2` with three ranges. BIT-IDENTICAL per
6298    /// (tensor,row) to three separate m=1 MMVQ launches.
6299    /// FUSED Q4_0 m=1 TRIPLE (gemma q/k/v — same quantized input; per (tensor,row) chain
6300    /// identical to the mr2 kernel). Returns None unless all three are Q4_0 with equal in_f.
6301    pub fn matmul_q4_fused3(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6302                            w2: &crate::model::GpuTensor,
6303                            aq: &CudaSlice<i8>, ad: &CudaSlice<f32>)
6304        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6305        use crate::model::GpuTensor;
6306        let q4 = |w: &GpuTensor| -> Option<(usize, usize)> {
6307            match w {
6308                GpuTensor::Quant { qtype, row_bytes, .. } if *qtype == QT_Q4_0 =>
6309                    Some((*row_bytes, w.out_features())),
6310                _ => None,
6311            }
6312        };
6313        let (Some((rb0, o0)), Some((rb1, o1)), Some((rb2, o2))) = (q4(w0), q4(w1), q4(w2))
6314        else { return Ok(None) };
6315        if w0.in_features() != w1.in_features() || w0.in_features() != w2.in_features() {
6316            return Ok(None);
6317        }
6318        // Effective (bytes, rp) per tensor: mirror (rp4) OR the in-place swap (rp flag,
6319        // bytes already split). Mixed layouts cannot share one fused launch -> fall back to
6320        // the separate matvecs (each routes its own rp).
6321        fn eff(w: &GpuTensor) -> (&CudaSlice<u8>, bool) {
6322            match w {
6323                GpuTensor::Quant { bytes, rp4, rp, .. } => match rp4 {
6324                    Some(m) => (m, true),
6325                    None => (bytes, *rp),
6326                },
6327                _ => unreachable!(),
6328            }
6329        }
6330        let ((b0, rp0), (b1, rp1), (b2, rp2)) = (eff(w0), eff(w1), eff(w2));
6331        if rp0 != rp1 || rp1 != rp2 { return Ok(None); }
6332        let rp = rp0;
6333        let rpb: u32 = 4;
6334        // mr1 (one row/warp, 2026-07-14): follows the singles' MEMRA_Q40_MR default — the
6335        // fused t=1 kernels were left on mr2 when the singles flipped (DRAM-duty map:
6336        // fused3 57% / fused2 86%; small qkv segments starve under mr2's half grid).
6337        let mr1 = rp && Self::q40_mr1_on();
6338        let nb = |o: usize| if mr1 { (o as u32).div_ceil(rpb) }
6339                            else { (o as u32).div_ceil(2).div_ceil(rpb) };
6340        let grid = nb(o0) + nb(o1) + nb(o2);
6341        let mut y0 = self.alloc_uninit::<f32>(o0)?;
6342        let mut y1 = self.alloc_uninit::<f32>(o1)?;
6343        let mut y2 = self.alloc_uninit::<f32>(o2)?;
6344        let f = self.func(if mr1 { "qmatvec_q4_0_mmvq_fused3_mr1_rp" }
6345                          else if rp { "qmatvec_q4_0_mmvq_fused3_rp" }
6346                          else { "qmatvec_q4_0_mmvq_fused3" });
6347        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: (32, rpb, 1), shared_mem_bytes: 0 };
6348        let inf = w0.in_features() as i32;
6349        let (oo0, oo1, oo2) = (o0 as i32, o1 as i32, o2 as i32);
6350        let (r0, r1, r2) = (rb0 as i64, rb1 as i64, rb2 as i64);
6351        // PDL wave-A (2026-07-23): the mr1 kernel carries MEMRA_PDL_ENTRY; only that
6352        // variant may take the programmatic-serialization launch.
6353        if mr1 && Self::pdl_on() && Self::pdl_mmvq_on() {
6354            {
6355            use cudarc::driver::{DevicePtr, DevicePtrMut};
6356            let s = &self.gpu.stream();
6357            let (p0, _g0) = b0.device_ptr(s); let (p1, _g1) = b1.device_ptr(s);
6358            let (p2, _g2) = b2.device_ptr(s); let (paq, _g3) = aq.device_ptr(s);
6359            let (pad, _g4) = ad.device_ptr(s);
6360            let (py0, _g5) = y0.device_ptr_mut(s); let (py1, _g6) = y1.device_ptr_mut(s);
6361            let (py2, _g7) = y2.device_ptr_mut(s);
6362            let mut ps = [
6363                &p0 as *const _ as *mut std::ffi::c_void, &p1 as *const _ as *mut _,
6364                &p2 as *const _ as *mut _, &paq as *const _ as *mut _,
6365                &pad as *const _ as *mut _, &py0 as *const _ as *mut _,
6366                &py1 as *const _ as *mut _, &py2 as *const _ as *mut _,
6367                &inf as *const _ as *mut _, &oo0 as *const _ as *mut _,
6368                &oo1 as *const _ as *mut _, &oo2 as *const _ as *mut _,
6369                &r0 as *const _ as *mut _, &r1 as *const _ as *mut _,
6370                &r2 as *const _ as *mut _,
6371            ];
6372            unsafe { self.launch_pdl("qmatvec_q4_0_mmvq_fused3_mr1_rp",
6373                                     (grid, 1, 1), (32, rpb, 1), &mut ps)?; }
6374            }
6375            return Ok(Some((y0, y1, y2)));
6376        }
6377        let __s_b = self.gpu.stream();
6378        let mut b = __s_b.launch_builder(&f);
6379        b.arg(b0).arg(b1).arg(b2).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1).arg(&mut y2)
6380         .arg(&inf).arg(&oo0).arg(&oo1).arg(&oo2).arg(&r0).arg(&r1).arg(&r2);
6381        unsafe { b.launch(cfg)?; }
6382        Ok(Some((y0, y1, y2)))
6383    }
6384
6385    /// Slot-fed fused3 twin (alloc-free capture lane): identical launch, caller-owned outputs.
6386    /// Returns Ok(false) when the fused path is unavailable (caller falls back).
6387    #[allow(clippy::too_many_arguments)]
6388    pub fn matmul_q4_fused3_into(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6389                                 w2: &crate::model::GpuTensor,
6390                                 aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
6391                                 y0: &mut CudaSlice<f32>, y1: &mut CudaSlice<f32>,
6392                                 y2: &mut CudaSlice<f32>)
6393        -> Result<bool, Box<dyn std::error::Error>> {
6394        use crate::model::GpuTensor;
6395        let q4 = |w: &GpuTensor| -> Option<(usize, usize)> {
6396            match w {
6397                GpuTensor::Quant { qtype, row_bytes, .. } if *qtype == QT_Q4_0 =>
6398                    Some((*row_bytes, w.out_features())),
6399                _ => None,
6400            }
6401        };
6402        let (Some((rb0, o0)), Some((rb1, o1)), Some((rb2, o2))) = (q4(w0), q4(w1), q4(w2))
6403        else { return Ok(false) };
6404        if w0.in_features() != w1.in_features() || w0.in_features() != w2.in_features() {
6405            return Ok(false);
6406        }
6407        fn eff(w: &GpuTensor) -> (&CudaSlice<u8>, bool) {
6408            match w {
6409                GpuTensor::Quant { bytes, rp4, rp, .. } => match rp4 {
6410                    Some(m) => (m, true),
6411                    None => (bytes, *rp),
6412                },
6413                _ => unreachable!(),
6414            }
6415        }
6416        let ((b0, rp0), (b1, rp1), (b2, rp2)) = (eff(w0), eff(w1), eff(w2));
6417        if rp0 != rp1 || rp1 != rp2 { return Ok(false); }
6418        let rp = rp0;
6419        let rpb: u32 = 4;
6420        let mr1 = rp && Self::q40_mr1_on();
6421        let nb = |o: usize| if mr1 { (o as u32).div_ceil(rpb) }
6422                            else { (o as u32).div_ceil(2).div_ceil(rpb) };
6423        let grid = nb(o0) + nb(o1) + nb(o2);
6424        debug_assert!(y0.len() >= o0 && y1.len() >= o1 && y2.len() >= o2);
6425        let f = self.func(if mr1 { "qmatvec_q4_0_mmvq_fused3_mr1_rp" }
6426                          else if rp { "qmatvec_q4_0_mmvq_fused3_rp" }
6427                          else { "qmatvec_q4_0_mmvq_fused3" });
6428        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: (32, rpb, 1), shared_mem_bytes: 0 };
6429        let inf = w0.in_features() as i32;
6430        let (oo0, oo1, oo2) = (o0 as i32, o1 as i32, o2 as i32);
6431        let (r0, r1, r2) = (rb0 as i64, rb1 as i64, rb2 as i64);
6432        // PDL wave-A: identical to the owned twin (capture-lane parity).
6433        if mr1 && Self::pdl_on() && Self::pdl_mmvq_on() {
6434            use cudarc::driver::{DevicePtr, DevicePtrMut};
6435            let s = &self.gpu.stream();
6436            let (p0, _g0) = b0.device_ptr(s); let (p1, _g1) = b1.device_ptr(s);
6437            let (p2, _g2) = b2.device_ptr(s); let (paq, _g3) = aq.device_ptr(s);
6438            let (pad, _g4) = ad.device_ptr(s);
6439            let (py0, _g5) = y0.device_ptr_mut(s); let (py1, _g6) = y1.device_ptr_mut(s);
6440            let (py2, _g7) = y2.device_ptr_mut(s);
6441            let mut ps = [
6442                &p0 as *const _ as *mut std::ffi::c_void, &p1 as *const _ as *mut _,
6443                &p2 as *const _ as *mut _, &paq as *const _ as *mut _,
6444                &pad as *const _ as *mut _, &py0 as *const _ as *mut _,
6445                &py1 as *const _ as *mut _, &py2 as *const _ as *mut _,
6446                &inf as *const _ as *mut _, &oo0 as *const _ as *mut _,
6447                &oo1 as *const _ as *mut _, &oo2 as *const _ as *mut _,
6448                &r0 as *const _ as *mut _, &r1 as *const _ as *mut _,
6449                &r2 as *const _ as *mut _,
6450            ];
6451            unsafe { self.launch_pdl("qmatvec_q4_0_mmvq_fused3_mr1_rp",
6452                                     (grid, 1, 1), (32, rpb, 1), &mut ps)?; }
6453            return Ok(true);
6454        }
6455        let __s_b = self.gpu.stream();
6456        let mut b = __s_b.launch_builder(&f);
6457        b.arg(b0).arg(b1).arg(b2).arg(aq).arg(ad).arg(&mut *y0).arg(&mut *y1).arg(&mut *y2)
6458         .arg(&inf).arg(&oo0).arg(&oo1).arg(&oo2).arg(&r0).arg(&r1).arg(&r2);
6459        unsafe { b.launch(cfg)?; }
6460        Ok(true)
6461    }
6462
6463    /// FUSED Q4_0 m=1 PAIR (gemma shared gate+up).
6464    pub fn matmul_q4_fused2(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6465                            aq: &CudaSlice<i8>, ad: &CudaSlice<f32>)
6466        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6467        use crate::model::GpuTensor;
6468        let q4 = |w: &GpuTensor| -> Option<(usize, usize)> {
6469            match w {
6470                GpuTensor::Quant { qtype, row_bytes, .. } if *qtype == QT_Q4_0 =>
6471                    Some((*row_bytes, w.out_features())),
6472                _ => None,
6473            }
6474        };
6475        let (Some((rb0, o0)), Some((rb1, o1))) = (q4(w0), q4(w1)) else { return Ok(None) };
6476        if w0.in_features() != w1.in_features() { return Ok(None); }
6477        // Effective (bytes, rp) per tensor (mirror or in-place swap); mixed -> separate matvecs.
6478        fn eff(w: &GpuTensor) -> (&CudaSlice<u8>, bool) {
6479            match w {
6480                GpuTensor::Quant { bytes, rp4, rp, .. } => match rp4 {
6481                    Some(m) => (m, true),
6482                    None => (bytes, *rp),
6483                },
6484                _ => unreachable!(),
6485            }
6486        }
6487        let ((b0, rp0), (b1, rp1)) = (eff(w0), eff(w1));
6488        if rp0 != rp1 { return Ok(None); }
6489        let rp = rp0;
6490        let rpb: u32 = 4;
6491        // mr1 twin — see matmul_q4_fused3.
6492        let mr1 = rp && Self::q40_mr1_on();
6493        let nb = |o: usize| if mr1 { (o as u32).div_ceil(rpb) }
6494                            else { (o as u32).div_ceil(2).div_ceil(rpb) };
6495        let grid = nb(o0) + nb(o1);
6496        let mut y0 = self.alloc_uninit::<f32>(o0)?;
6497        let mut y1 = self.alloc_uninit::<f32>(o1)?;
6498        let f = self.func(if mr1 { "qmatvec_q4_0_mmvq_fused2_mr1_rp" }
6499                          else if rp { "qmatvec_q4_0_mmvq_fused2_rp" }
6500                          else { "qmatvec_q4_0_mmvq_fused2" });
6501        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: (32, rpb, 1), shared_mem_bytes: 0 };
6502        let inf = w0.in_features() as i32;
6503        let (oo0, oo1) = (o0 as i32, o1 as i32);
6504        let (r0, r1) = (rb0 as i64, rb1 as i64);
6505        // PDL wave-A: mr1 kernel carries MEMRA_PDL_ENTRY.
6506        if mr1 && Self::pdl_on() && Self::pdl_mmvq_on() {
6507            {
6508            use cudarc::driver::{DevicePtr, DevicePtrMut};
6509            let s = &self.gpu.stream();
6510            let (p0, _g0) = b0.device_ptr(s); let (p1, _g1) = b1.device_ptr(s);
6511            let (paq, _g2) = aq.device_ptr(s); let (pad, _g3) = ad.device_ptr(s);
6512            let (py0, _g4) = y0.device_ptr_mut(s); let (py1, _g5) = y1.device_ptr_mut(s);
6513            let mut ps = [
6514                &p0 as *const _ as *mut std::ffi::c_void, &p1 as *const _ as *mut _,
6515                &paq as *const _ as *mut _, &pad as *const _ as *mut _,
6516                &py0 as *const _ as *mut _, &py1 as *const _ as *mut _,
6517                &inf as *const _ as *mut _, &oo0 as *const _ as *mut _,
6518                &oo1 as *const _ as *mut _, &r0 as *const _ as *mut _,
6519                &r1 as *const _ as *mut _,
6520            ];
6521            unsafe { self.launch_pdl("qmatvec_q4_0_mmvq_fused2_mr1_rp",
6522                                     (grid, 1, 1), (32, rpb, 1), &mut ps)?; }
6523            }
6524            return Ok(Some((y0, y1)));
6525        }
6526        let __s_b = self.gpu.stream();
6527        let mut b = __s_b.launch_builder(&f);
6528        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
6529         .arg(&inf).arg(&oo0).arg(&oo1).arg(&r0).arg(&r1);
6530        unsafe { b.launch(cfg)?; }
6531        Ok(Some((y0, y1)))
6532    }
6533
6534    /// Slot-fed fused2 twin (alloc-free capture lane): identical launch, caller-owned outputs.
6535    pub fn matmul_q4_fused2_into(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6536                                 aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
6537                                 y0: &mut CudaSlice<f32>, y1: &mut CudaSlice<f32>)
6538        -> Result<bool, Box<dyn std::error::Error>> {
6539        use crate::model::GpuTensor;
6540        let q4 = |w: &GpuTensor| -> Option<(usize, usize)> {
6541            match w {
6542                GpuTensor::Quant { qtype, row_bytes, .. } if *qtype == QT_Q4_0 =>
6543                    Some((*row_bytes, w.out_features())),
6544                _ => None,
6545            }
6546        };
6547        let (Some((rb0, o0)), Some((rb1, o1))) = (q4(w0), q4(w1)) else { return Ok(false) };
6548        if w0.in_features() != w1.in_features() { return Ok(false); }
6549        fn eff(w: &GpuTensor) -> (&CudaSlice<u8>, bool) {
6550            match w {
6551                GpuTensor::Quant { bytes, rp4, rp, .. } => match rp4 {
6552                    Some(m) => (m, true),
6553                    None => (bytes, *rp),
6554                },
6555                _ => unreachable!(),
6556            }
6557        }
6558        let ((b0, rp0), (b1, rp1)) = (eff(w0), eff(w1));
6559        if rp0 != rp1 { return Ok(false); }
6560        let rp = rp0;
6561        let rpb: u32 = 4;
6562        let mr1 = rp && Self::q40_mr1_on();
6563        let nb = |o: usize| if mr1 { (o as u32).div_ceil(rpb) }
6564                            else { (o as u32).div_ceil(2).div_ceil(rpb) };
6565        let grid = nb(o0) + nb(o1);
6566        debug_assert!(y0.len() >= o0 && y1.len() >= o1);
6567        let f = self.func(if mr1 { "qmatvec_q4_0_mmvq_fused2_mr1_rp" }
6568                          else if rp { "qmatvec_q4_0_mmvq_fused2_rp" }
6569                          else { "qmatvec_q4_0_mmvq_fused2" });
6570        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: (32, rpb, 1), shared_mem_bytes: 0 };
6571        let inf = w0.in_features() as i32;
6572        let (oo0, oo1) = (o0 as i32, o1 as i32);
6573        let (r0, r1) = (rb0 as i64, rb1 as i64);
6574        // PDL wave-A: identical to the owned twin (capture-lane parity).
6575        if mr1 && Self::pdl_on() && Self::pdl_mmvq_on() {
6576            use cudarc::driver::{DevicePtr, DevicePtrMut};
6577            let s = &self.gpu.stream();
6578            let (p0, _g0) = b0.device_ptr(s); let (p1, _g1) = b1.device_ptr(s);
6579            let (paq, _g2) = aq.device_ptr(s); let (pad, _g3) = ad.device_ptr(s);
6580            let (py0, _g4) = y0.device_ptr_mut(s); let (py1, _g5) = y1.device_ptr_mut(s);
6581            let mut ps = [
6582                &p0 as *const _ as *mut std::ffi::c_void, &p1 as *const _ as *mut _,
6583                &paq as *const _ as *mut _, &pad as *const _ as *mut _,
6584                &py0 as *const _ as *mut _, &py1 as *const _ as *mut _,
6585                &inf as *const _ as *mut _, &oo0 as *const _ as *mut _,
6586                &oo1 as *const _ as *mut _, &r0 as *const _ as *mut _,
6587                &r1 as *const _ as *mut _,
6588            ];
6589            unsafe { self.launch_pdl("qmatvec_q4_0_mmvq_fused2_mr1_rp",
6590                                     (grid, 1, 1), (32, rpb, 1), &mut ps)?; }
6591            return Ok(true);
6592        }
6593        let __s_b = self.gpu.stream();
6594        let mut b = __s_b.launch_builder(&f);
6595        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut *y0).arg(&mut *y1)
6596         .arg(&inf).arg(&oo0).arg(&oo1).arg(&r0).arg(&r1);
6597        unsafe { b.launch(cfg)?; }
6598        Ok(true)
6599    }
6600
6601    /// BATCHED fused2 (2026-07-13, megakernel-microcosm probe): gate+up b-tier matvecs in
6602    /// ONE segmented-grid launch — the up segment fills SMs as the gate segment drains
6603    /// (the per-launch tail waves behind the 6x-falsified b-tier plateau). Bit-identical
6604    /// per row to two mr2_rp launches. rp layout required; m in 2..=8 (b16 has no twin).
6605    pub fn matmul_q4_fused2_batched(&self, w0: &crate::model::GpuTensor,
6606                                    w1: &crate::model::GpuTensor,
6607                                    aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize)
6608        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6609        use crate::model::GpuTensor;
6610        if m < 2 || m > 8 { return Ok(None); }
6611        let q4 = |w: &GpuTensor| -> Option<(usize, usize)> {
6612            match w {
6613                GpuTensor::Quant { qtype, row_bytes, .. } if *qtype == QT_Q4_0 =>
6614                    Some((*row_bytes, w.out_features())),
6615                _ => None,
6616            }
6617        };
6618        let (Some((rb0, o0)), Some((_rb1, o1))) = (q4(w0), q4(w1)) else { return Ok(None) };
6619        if w0.in_features() != w1.in_features() { return Ok(None); }
6620        fn eff(w: &GpuTensor) -> (&CudaSlice<u8>, bool) {
6621            match w {
6622                GpuTensor::Quant { bytes, rp4, rp, .. } => match rp4 {
6623                    Some(mr) => (mr, true),
6624                    None => (bytes, *rp),
6625                },
6626                _ => unreachable!(),
6627            }
6628        }
6629        let ((b0, rp0), (b1, rp1)) = (eff(w0), eff(w1));
6630        if !rp0 || !rp1 { return Ok(None); }
6631        let mcols = Self::batched_mcols(m);
6632        let rpb: u32 = 4;
6633        let nb = |o: usize| (o as u32).div_ceil(2 * rpb);
6634        let grid = nb(o0) + nb(o1);
6635        let mut y0 = self.alloc_uninit::<f32>(m * o0)?;
6636        let mut y1 = self.alloc_uninit::<f32>(m * o1)?;
6637        let f = self.func(match mcols { 2 => "qmatvec_q4_0_mmvq_b2_f2_rp",
6638                                        4 => "qmatvec_q4_0_mmvq_b4_f2_rp",
6639                                        _ => "qmatvec_q4_0_mmvq_b8_f2_rp" });
6640        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: (32, rpb, 1),
6641                                 shared_mem_bytes: 0 };
6642        let inf = w0.in_features() as i32;
6643        let (oo0, oo1, mi) = (o0 as i32, o1 as i32, m as i32);
6644        let rb = rb0 as i64;
6645        let __s_b = self.gpu.stream();
6646        let mut b = __s_b.launch_builder(&f);
6647        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
6648         .arg(&inf).arg(&oo0).arg(&oo1).arg(&mi).arg(&rb);
6649        unsafe { b.launch(cfg)?; }
6650        Ok(Some((y0, y1)))
6651    }
6652
6653    /// BATCHED fused3 (see matmul_q4_fused2_batched): three-segment single launch for the
6654    /// verify qkv triple. Same-in_f q4_0 rp tensors, m in 2..=8. Bit-identical per row.
6655    #[allow(clippy::too_many_arguments)]
6656    pub fn matmul_q4_fused3_batched(&self, w0: &crate::model::GpuTensor,
6657                                    w1: &crate::model::GpuTensor, w2: &crate::model::GpuTensor,
6658                                    aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize)
6659        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6660        use crate::model::GpuTensor;
6661        if m < 2 || m > 8 { return Ok(None); }
6662        let q4 = |w: &GpuTensor| -> Option<usize> {
6663            match w {
6664                GpuTensor::Quant { qtype, .. } if *qtype == QT_Q4_0 => Some(w.out_features()),
6665                _ => None,
6666            }
6667        };
6668        let (Some(o0), Some(o1), Some(o2)) = (q4(w0), q4(w1), q4(w2)) else { return Ok(None) };
6669        if w0.in_features() != w1.in_features() || w0.in_features() != w2.in_features() {
6670            return Ok(None);
6671        }
6672        fn eff(w: &GpuTensor) -> (&CudaSlice<u8>, bool) {
6673            match w {
6674                GpuTensor::Quant { bytes, rp4, rp, .. } => match rp4 {
6675                    Some(mr) => (mr, true),
6676                    None => (bytes, *rp),
6677                },
6678                _ => unreachable!(),
6679            }
6680        }
6681        let ((b0, rp0), (b1, rp1), (b2, rp2)) = (eff(w0), eff(w1), eff(w2));
6682        if !rp0 || !rp1 || !rp2 { return Ok(None); }
6683        let mcols = Self::batched_mcols(m);
6684        let rpb: u32 = 4;
6685        let nb = |o: usize| (o as u32).div_ceil(2 * rpb);
6686        let grid = nb(o0) + nb(o1) + nb(o2);
6687        let mut y0 = self.alloc_uninit::<f32>(m * o0)?;
6688        let mut y1 = self.alloc_uninit::<f32>(m * o1)?;
6689        let mut y2 = self.alloc_uninit::<f32>(m * o2)?;
6690        let f = self.func(match mcols { 2 => "qmatvec_q4_0_mmvq_b2_f3_rp",
6691                                        4 => "qmatvec_q4_0_mmvq_b4_f3_rp",
6692                                        _ => "qmatvec_q4_0_mmvq_b8_f3_rp" });
6693        let cfg = LaunchConfig { grid_dim: (grid, 1, 1), block_dim: (32, rpb, 1),
6694                                 shared_mem_bytes: 0 };
6695        let inf = w0.in_features() as i32;
6696        let (oo0, oo1, oo2, mi) = (o0 as i32, o1 as i32, o2 as i32, m as i32);
6697        let rb = 0i64;
6698        let __s_b = self.gpu.stream();
6699        let mut b = __s_b.launch_builder(&f);
6700        b.arg(b0).arg(b1).arg(b2).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1).arg(&mut y2)
6701         .arg(&inf).arg(&oo0).arg(&oo1).arg(&oo2).arg(&mi).arg(&rb);
6702        unsafe { b.launch(cfg)?; }
6703        Ok(Some((y0, y1, y2)))
6704    }
6705
6706    pub fn matmul_q8_fused3(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6707                            w2: &crate::model::GpuTensor,
6708                            aq: &CudaSlice<i8>, ad: &CudaSlice<f32>)
6709        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6710        // e4m3 twin (lane/fp8-decode-v1): the full-attn wq/wk/wv triple — on the NV-27B those three
6711        // are per-tensor FP8, so native residency without this arm meant three separate launches.
6712        if let Some([p0, p1, p2]) = self.e4m3_fused_params(&[w0, w1, w2]) {
6713            return Ok(Some(self.e4m3_fused3_core(p0.0, p1.0, p2.0, aq, ad, w0.in_features(),
6714                                                 p0.1, p1.1, p2.1, p0.2,
6715                                                 p0.3, p1.3, p2.3)?));
6716        }
6717        let Some([p0, p1, p2]) = self.q8_fused_params(&[w0, w1, w2]) else { return Ok(None) };
6718        Ok(Some(self.q8_fused3_core(p0.0, p1.0, p2.0, aq, ad, w0.in_features(),
6719                                    p0.1, p1.1, p2.1, p0.2)?))
6720    }
6721
6722    #[allow(clippy::too_many_arguments)]
6723    fn q8_fused3_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, b2: &CudaSlice<u8>,
6724                      aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
6725                      in_f: usize, out0: usize, out1: usize, out2: usize, row_bytes: usize)
6726        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6727        const ROWS_PER_BLOCK: u32 = 4;
6728        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
6729        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
6730        let nb2 = (out2 as u32).div_ceil(ROWS_PER_BLOCK);
6731        let f = self.func("qmatvec_q8_0_mmvq_fused3");
6732        let mut y0 = self.alloc_uninit::<f32>(out0)?;
6733        let mut y1 = self.alloc_uninit::<f32>(out1)?;
6734        let mut y2 = self.alloc_uninit::<f32>(out2)?;
6735        let cfg = LaunchConfig { grid_dim: (nb0 + nb1 + nb2, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
6736                                 shared_mem_bytes: 0 };
6737        let (inf, o0, o1, o2, rbl) = (in_f as i32, out0 as i32, out1 as i32, out2 as i32, row_bytes as i64);
6738        let __s_b = self.gpu.stream();
6739        let mut b = __s_b.launch_builder(&f);
6740        b.arg(b0).arg(b1).arg(b2).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1).arg(&mut y2)
6741         .arg(&inf).arg(&o0).arg(&o1).arg(&o2).arg(&rbl);
6742        unsafe { b.launch(cfg)?; }
6743        Ok((y0, y1, y2))
6744    }
6745
6746    /// Test entry for the kernel_check gate: fused3 from raw weight bytes (internal q8_1 quant).
6747    #[allow(clippy::too_many_arguments)]
6748    pub fn qmatvec_q8_fused3_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, b2: &CudaSlice<u8>,
6749                                 x: &CudaSlice<f32>, in_f: usize, out0: usize, out1: usize,
6750                                 out2: usize, row_bytes: usize)
6751        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6752        let (aq, ad) = self.quantize_q8_1(x, 1, in_f)?;
6753        self.q8_fused3_core(b0, b1, b2, &aq, &ad, in_f, out0, out1, out2, row_bytes)
6754    }
6755
6756    /// BATCHED twin of `matmul_q8_fused2` for the verify t=2-4 tier (MEMRA_SPEC_FUSED_T call
6757    /// sites, lane/close35b): ONE launch computes both same-input Q8_0 projections for m tokens.
6758    /// Per (tensor,token,row) the kernel body is q8_0_mmvq_batched VERBATIM with the identical
6759    /// row mapping (Q8_0's batched_variant is always "base") -> BIT-IDENTICAL to the two
6760    /// per-tensor _b2/_b4 launches `matmul_decode_exact` dispatches at m=2-4, with the caller's
6761    /// single shared q8_1 activation replacing two per-call re-quantizes (quantize_q8_1 is
6762    /// deterministic -> same bytes). None when ineligible (m outside 2..=4 / not both Q8_0 /
6763    /// in_f mismatch / MEMRA_MMVQ=0 / MEMRA_Q8_DUAL=0 / MEMRA_NO_BATCHED set — the last keeps
6764    /// dispatch parity: without batched kernels decode-exact runs grid.y=m MMVQ, and the fused
6765    /// twin must not introduce a batched program the reference path would not run).
6766    pub fn matmul_q8_fused2_t(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6767                              aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize)
6768        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6769        // m<=8 (lane/q27-deepdive, 2026-08-05): was 2..=4 (the verify tier's mcols 2/4). The
6770        // serving tick's mcols-8 tier now has its fused2_b8 wrapper, so c=5..8 batched decode
6771        // fuses too — same template body, still bit-identical to the two _b8 launches.
6772        if !(2..=8).contains(&m) || std::env::var("MEMRA_NO_BATCHED").is_ok() { return Ok(None); }
6773        // e4m3 twin: MEMRA_B8 parity — without it m=5..8 e4m3 decode runs the per-m grid.y=m path,
6774        // so the fused b8 launch would introduce a batched program the reference path would not run.
6775        if let Some([p0, p1]) = self.e4m3_fused_params(&[w0, w1]) {
6776            if m > 4 && !Self::b8_enabled() { return Ok(None); }
6777            return Ok(Some(self.e4m3_fused2_t_core(p0.0, p1.0, aq, ad, m, w0.in_features(),
6778                                                   p0.1, p1.1, p0.2, p0.3, p1.3)?));
6779        }
6780        let Some([p0, p1]) = self.q8_fused_params(&[w0, w1]) else { return Ok(None) };
6781        Ok(Some(self.q8_fused2_t_core(p0.0, p1.0, aq, ad, m, w0.in_features(), p0.1, p1.1, p0.2)?))
6782    }
6783
6784    #[allow(clippy::too_many_arguments)]
6785    fn q8_fused2_t_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
6786                        aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize,
6787                        in_f: usize, out0: usize, out1: usize, row_bytes: usize)
6788        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6789        const ROWS_PER_BLOCK: u32 = 4;   // matches MEMRA_MMVQ_ROWS in qmatvec.cu
6790        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
6791        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
6792        let f = self.func(match Self::batched_mcols(m) {
6793            2 => "qmatvec_q8_0_mmvq_fused2_b2",
6794            4 => "qmatvec_q8_0_mmvq_fused2_b4",
6795            // b8 = the SERVING tier (lane/q27-deepdive): c=5..8 batched decode.
6796            _ => "qmatvec_q8_0_mmvq_fused2_b8",
6797        });
6798        let mut y0 = self.alloc_uninit::<f32>(m * out0)?;
6799        let mut y1 = self.alloc_uninit::<f32>(m * out1)?;
6800        let cfg = LaunchConfig { grid_dim: (nb0 + nb1, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
6801                                 shared_mem_bytes: 0 };
6802        let (inf, o0, o1, mi, rbl) = (in_f as i32, out0 as i32, out1 as i32, m as i32, row_bytes as i64);
6803        let __s_b = self.gpu.stream();
6804        let mut b = __s_b.launch_builder(&f);
6805        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
6806         .arg(&inf).arg(&o0).arg(&o1).arg(&mi).arg(&rbl);
6807        unsafe { b.launch(cfg)?; }
6808        Ok((y0, y1))
6809    }
6810
6811    /// Test entry for the kernel_check gate: fused2 batched from raw weight bytes (internal
6812    /// q8_1 quant of the [m, in_f] activation), no env gating.
6813    #[allow(clippy::too_many_arguments)]
6814    pub fn qmatvec_q8_fused2_t_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
6815                                   x: &CudaSlice<f32>, m: usize,
6816                                   in_f: usize, out0: usize, out1: usize, row_bytes: usize)
6817        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6818        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
6819        self.q8_fused2_t_core(b0, b1, &aq, &ad, m, in_f, out0, out1, row_bytes)
6820    }
6821
6822    /// BATCHED twin of `matmul_q8_fused3` (wq+wk+wv at verify t=2-4). Same contract as
6823    /// `matmul_q8_fused2_t` with three ranges.
6824    #[allow(clippy::too_many_arguments)]
6825    pub fn matmul_q8_fused3_t(&self, w0: &crate::model::GpuTensor, w1: &crate::model::GpuTensor,
6826                              w2: &crate::model::GpuTensor,
6827                              aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize)
6828        -> Result<Option<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>> {
6829        if !(2..=4).contains(&m) || std::env::var("MEMRA_NO_BATCHED").is_ok() { return Ok(None); }
6830        if let Some([p0, p1, p2]) = self.e4m3_fused_params(&[w0, w1, w2]) {
6831            return Ok(Some(self.e4m3_fused3_t_core(p0.0, p1.0, p2.0, aq, ad, m, w0.in_features(),
6832                                                   p0.1, p1.1, p2.1, p0.2,
6833                                                   p0.3, p1.3, p2.3)?));
6834        }
6835        let Some([p0, p1, p2]) = self.q8_fused_params(&[w0, w1, w2]) else { return Ok(None) };
6836        Ok(Some(self.q8_fused3_t_core(p0.0, p1.0, p2.0, aq, ad, m, w0.in_features(),
6837                                      p0.1, p1.1, p2.1, p0.2)?))
6838    }
6839
6840    #[allow(clippy::too_many_arguments)]
6841    fn q8_fused3_t_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, b2: &CudaSlice<u8>,
6842                        aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize,
6843                        in_f: usize, out0: usize, out1: usize, out2: usize, row_bytes: usize)
6844        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6845        const ROWS_PER_BLOCK: u32 = 4;
6846        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
6847        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
6848        let nb2 = (out2 as u32).div_ceil(ROWS_PER_BLOCK);
6849        let f = self.func(if Self::batched_mcols(m) == 2 { "qmatvec_q8_0_mmvq_fused3_b2" }
6850                          else { "qmatvec_q8_0_mmvq_fused3_b4" });
6851        let mut y0 = self.alloc_uninit::<f32>(m * out0)?;
6852        let mut y1 = self.alloc_uninit::<f32>(m * out1)?;
6853        let mut y2 = self.alloc_uninit::<f32>(m * out2)?;
6854        let cfg = LaunchConfig { grid_dim: (nb0 + nb1 + nb2, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
6855                                 shared_mem_bytes: 0 };
6856        let (inf, o0, o1, o2, mi, rbl) = (in_f as i32, out0 as i32, out1 as i32, out2 as i32,
6857                                          m as i32, row_bytes as i64);
6858        let __s_b = self.gpu.stream();
6859        let mut b = __s_b.launch_builder(&f);
6860        b.arg(b0).arg(b1).arg(b2).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1).arg(&mut y2)
6861         .arg(&inf).arg(&o0).arg(&o1).arg(&o2).arg(&mi).arg(&rbl);
6862        unsafe { b.launch(cfg)?; }
6863        Ok((y0, y1, y2))
6864    }
6865
6866    /// Test entry for the kernel_check gate: fused3 batched from raw weight bytes.
6867    #[allow(clippy::too_many_arguments)]
6868    pub fn qmatvec_q8_fused3_t_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, b2: &CudaSlice<u8>,
6869                                   x: &CudaSlice<f32>, m: usize, in_f: usize, out0: usize,
6870                                   out1: usize, out2: usize, row_bytes: usize)
6871        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6872        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
6873        self.q8_fused3_t_core(b0, b1, b2, &aq, &ad, m, in_f, out0, out1, out2, row_bytes)
6874    }
6875
6876    /// Rollback seam for the Q8_0 dense-FFN gate+up fusion arm in `matmul_pre_dual_noscale`
6877    /// (lane/q27-deepdive, 2026-08-05). Default ON; `MEMRA_Q8_FFN_FUSE2=0` restores the
6878    /// two-`matmul_pre_noscale` pair. Read once — the dispatch must not vary within a run.
6879    pub fn q8_ffn_fuse2_on(&self) -> bool {
6880        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6881        *ON.get_or_init(|| std::env::var("MEMRA_Q8_FFN_FUSE2").as_deref() != Ok("0"))
6882    }
6883
6884    /// Eligibility + param extraction for the fused q8_0 launches: every tensor must be Quant Q8_0
6885    /// with macro-scale 1.0 (always true for GGUF q8_0; only NVFP4 carries scale) and share w[0]'s
6886    /// in_f (q8_0 row_bytes is a pure function of in_f, so equal in_f => equal row_bytes). MEMRA_MMVQ
6887    /// must be on: the fused body is the MMVQ kernel; without it decode m=1 runs dp4a and fusing
6888    /// would mix dispatch families (FP-order law). MEMRA_Q8_DUAL=0 = rollback seam.
6889    #[allow(clippy::type_complexity)]
6890    fn q8_fused_params<'w, const N: usize>(&self, ws: &[&'w crate::model::GpuTensor; N])
6891        -> Option<[(&'w CudaSlice<u8>, usize, usize); N]> {
6892        use crate::model::GpuTensor;
6893        if std::env::var("MEMRA_MMVQ").as_deref() == Ok("0") { return None; }
6894        if std::env::var("MEMRA_Q8_DUAL").is_ok_and(|v| v == "0") { return None; }
6895        let in_f = ws[0].in_features();
6896        let mut out: [Option<(&CudaSlice<u8>, usize, usize)>; N] = [None; N];
6897        for (i, w) in ws.iter().enumerate() {
6898            match w {
6899                GpuTensor::Quant { bytes, qtype, row_bytes, scale, .. }
6900                    if *qtype == QT_Q8_0 && *scale == 1.0 && w.in_features() == in_f =>
6901                        out[i] = Some((bytes, w.out_features(), *row_bytes)),
6902                _ => return None,
6903            }
6904        }
6905        Some(out.map(|o| o.unwrap()))
6906    }
6907
6908    /// Rollback seam for the F8-E4M3 launch-fusion arm (lane/fp8-decode-v1, 2026-08-05).
6909    /// Default ON; `MEMRA_E4M3_DUAL=0` restores the per-tensor m=1/batched launches.
6910    pub fn e4m3_dual_on(&self) -> bool {
6911        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6912        *ON.get_or_init(|| std::env::var("MEMRA_E4M3_DUAL").as_deref() != Ok("0"))
6913    }
6914
6915    /// Eligibility + param extraction for the FUSED e4m3 launches — the QT_F8_E4M3 twin of
6916    /// `q8_fused_params`. Differences that are inherent to the dtype, not policy:
6917    ///   * each tensor carries its OWN per-tensor `weight_scale` (returned as the 4th field);
6918    ///     Q8_0 hard-requires scale==1.0 because it has no macro-scale at all.
6919    ///   * no MEMRA_MMVQ gate: `mmvq_supports` exempts QT_F8_E4M3 (the e4m3 mmvq family is that
6920    ///     dtype's ONLY int8-act kernel class), so the per-tensor fallback these fused kernels
6921    ///     replace is ALWAYS the same mmvq body under every env — the FP-order law holds.
6922    ///   * `row_bytes == in_f` is asserted rather than derived: the native-residency load arm keeps
6923    ///     the checkpoint's raw [out_f, in_f] rows, and a re-encoded slab must never reach here.
6924    /// Rejects any split-plane mirror (`rp`/`rp4`): there is no `_rp` e4m3 fused form, so fusing
6925    /// there would swap dispatch families mid-model. MEMRA_E4M3_DUAL=0 = rollback seam.
6926    #[allow(clippy::type_complexity)]
6927    fn e4m3_fused_params<'w, const N: usize>(&self, ws: &[&'w crate::model::GpuTensor; N])
6928        -> Option<[(&'w CudaSlice<u8>, usize, usize, f32); N]> {
6929        use crate::model::GpuTensor;
6930        if !self.e4m3_dual_on() { return None; }
6931        let in_f = ws[0].in_features();
6932        let mut out: [Option<(&CudaSlice<u8>, usize, usize, f32)>; N] = [None; N];
6933        for (i, w) in ws.iter().enumerate() {
6934            match w {
6935                GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, rp4, .. }
6936                    if *qtype == QT_F8_E4M3 && w.in_features() == in_f
6937                        && *row_bytes == in_f && !*rp && rp4.is_none() =>
6938                        out[i] = Some((bytes, w.out_features(), *row_bytes, *scale)),
6939                _ => return None,
6940            }
6941        }
6942        Some(out.map(|o| o.unwrap()))
6943    }
6944
6945    /// FUSED e4m3 m=1 PAIR. Block-offset split (`qmatvec_e4m3_mmvq_fused2`), per-tensor
6946    /// weight_scale folded at the write like the single-tensor `qmatvec_e4m3_mmvq` — so per
6947    /// (tensor,row) this is BIT-IDENTICAL to two separate m=1 launches, scale included.
6948    #[allow(clippy::too_many_arguments)]
6949    fn e4m3_fused2_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
6950                        aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
6951                        in_f: usize, out0: usize, out1: usize, row_bytes: usize,
6952                        ws0: f32, ws1: f32)
6953        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6954        const ROWS_PER_BLOCK: u32 = 4;   // matches MEMRA_MMVQ_ROWS in qmatvec.cu
6955        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
6956        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
6957        let f = self.func("qmatvec_e4m3_mmvq_fused2");
6958        let mut y0 = self.alloc_uninit::<f32>(out0)?;
6959        let mut y1 = self.alloc_uninit::<f32>(out1)?;
6960        let cfg = LaunchConfig { grid_dim: (nb0 + nb1, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
6961                                 shared_mem_bytes: 0 };
6962        let (inf, o0, o1, rbl) = (in_f as i32, out0 as i32, out1 as i32, row_bytes as i64);
6963        let __s_b = self.gpu.stream();
6964        let mut b = __s_b.launch_builder(&f);
6965        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
6966         .arg(&inf).arg(&o0).arg(&o1).arg(&rbl).arg(&ws0).arg(&ws1);
6967        unsafe { b.launch(cfg)?; }
6968        Ok((y0, y1))
6969    }
6970
6971    /// FUSED e4m3 m=1 TRIPLE (`qmatvec_e4m3_mmvq_fused3`). Same contract as the pair.
6972    #[allow(clippy::too_many_arguments)]
6973    fn e4m3_fused3_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, b2: &CudaSlice<u8>,
6974                        aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
6975                        in_f: usize, out0: usize, out1: usize, out2: usize, row_bytes: usize,
6976                        ws0: f32, ws1: f32, ws2: f32)
6977        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6978        const ROWS_PER_BLOCK: u32 = 4;
6979        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
6980        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
6981        let nb2 = (out2 as u32).div_ceil(ROWS_PER_BLOCK);
6982        let f = self.func("qmatvec_e4m3_mmvq_fused3");
6983        let mut y0 = self.alloc_uninit::<f32>(out0)?;
6984        let mut y1 = self.alloc_uninit::<f32>(out1)?;
6985        let mut y2 = self.alloc_uninit::<f32>(out2)?;
6986        let cfg = LaunchConfig { grid_dim: (nb0 + nb1 + nb2, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
6987                                 shared_mem_bytes: 0 };
6988        let (inf, o0, o1, o2, rbl) = (in_f as i32, out0 as i32, out1 as i32, out2 as i32,
6989                                      row_bytes as i64);
6990        let __s_b = self.gpu.stream();
6991        let mut b = __s_b.launch_builder(&f);
6992        b.arg(b0).arg(b1).arg(b2).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1).arg(&mut y2)
6993         .arg(&inf).arg(&o0).arg(&o1).arg(&o2).arg(&rbl).arg(&ws0).arg(&ws1).arg(&ws2);
6994        unsafe { b.launch(cfg)?; }
6995        Ok((y0, y1, y2))
6996    }
6997
6998    /// BATCHED FUSED e4m3 pair (m=2..8). The batched kernels carry no `ws` arg (every batched
6999    /// kernel in the tree is scale-free), so each output takes its own `scale_inplace` — the
7000    /// SAME post-op the per-tensor batched dispatch applies, hence still bit-identical.
7001    #[allow(clippy::too_many_arguments)]
7002    fn e4m3_fused2_t_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
7003                          aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize,
7004                          in_f: usize, out0: usize, out1: usize, row_bytes: usize,
7005                          ws0: f32, ws1: f32)
7006        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7007        const ROWS_PER_BLOCK: u32 = 4;
7008        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
7009        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
7010        let f = self.func(match Self::batched_mcols(m) {
7011            2 => "qmatvec_e4m3_mmvq_fused2_b2",
7012            4 => "qmatvec_e4m3_mmvq_fused2_b4",
7013            _ => "qmatvec_e4m3_mmvq_fused2_b8",
7014        });
7015        let mut y0 = self.alloc_uninit::<f32>(m * out0)?;
7016        let mut y1 = self.alloc_uninit::<f32>(m * out1)?;
7017        let cfg = LaunchConfig { grid_dim: (nb0 + nb1, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
7018                                 shared_mem_bytes: 0 };
7019        let (inf, o0, o1, mi, rbl) = (in_f as i32, out0 as i32, out1 as i32, m as i32,
7020                                      row_bytes as i64);
7021        let __s_b = self.gpu.stream();
7022        let mut b = __s_b.launch_builder(&f);
7023        b.arg(b0).arg(b1).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1)
7024         .arg(&inf).arg(&o0).arg(&o1).arg(&mi).arg(&rbl);
7025        unsafe { b.launch(cfg)?; }
7026        if ws0 != 1.0 { self.scale_inplace(&mut y0, ws0, m * out0)?; }
7027        if ws1 != 1.0 { self.scale_inplace(&mut y1, ws1, m * out1)?; }
7028        Ok((y0, y1))
7029    }
7030
7031    /// BATCHED FUSED e4m3 triple (m=2..4). Same contract as the batched pair.
7032    #[allow(clippy::too_many_arguments)]
7033    fn e4m3_fused3_t_core(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, b2: &CudaSlice<u8>,
7034                          aq: &CudaSlice<i8>, ad: &CudaSlice<f32>, m: usize,
7035                          in_f: usize, out0: usize, out1: usize, out2: usize, row_bytes: usize,
7036                          ws0: f32, ws1: f32, ws2: f32)
7037        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7038        const ROWS_PER_BLOCK: u32 = 4;
7039        let nb0 = (out0 as u32).div_ceil(ROWS_PER_BLOCK);
7040        let nb1 = (out1 as u32).div_ceil(ROWS_PER_BLOCK);
7041        let nb2 = (out2 as u32).div_ceil(ROWS_PER_BLOCK);
7042        let f = self.func(if Self::batched_mcols(m) == 2 { "qmatvec_e4m3_mmvq_fused3_b2" }
7043                          else { "qmatvec_e4m3_mmvq_fused3_b4" });
7044        let mut y0 = self.alloc_uninit::<f32>(m * out0)?;
7045        let mut y1 = self.alloc_uninit::<f32>(m * out1)?;
7046        let mut y2 = self.alloc_uninit::<f32>(m * out2)?;
7047        let cfg = LaunchConfig { grid_dim: (nb0 + nb1 + nb2, 1, 1), block_dim: (32, ROWS_PER_BLOCK, 1),
7048                                 shared_mem_bytes: 0 };
7049        let (inf, o0, o1, o2, mi, rbl) = (in_f as i32, out0 as i32, out1 as i32, out2 as i32,
7050                                          m as i32, row_bytes as i64);
7051        let __s_b = self.gpu.stream();
7052        let mut b = __s_b.launch_builder(&f);
7053        b.arg(b0).arg(b1).arg(b2).arg(aq).arg(ad).arg(&mut y0).arg(&mut y1).arg(&mut y2)
7054         .arg(&inf).arg(&o0).arg(&o1).arg(&o2).arg(&mi).arg(&rbl);
7055        unsafe { b.launch(cfg)?; }
7056        if ws0 != 1.0 { self.scale_inplace(&mut y0, ws0, m * out0)?; }
7057        if ws1 != 1.0 { self.scale_inplace(&mut y1, ws1, m * out1)?; }
7058        if ws2 != 1.0 { self.scale_inplace(&mut y2, ws2, m * out2)?; }
7059        Ok((y0, y1, y2))
7060    }
7061
7062    /// BLOCK-128 e4m3 MMVQ launcher (`qmatvec_e4m3_blk_mmvq`, lane/fp8-blk128-decode 2026-08-05).
7063    /// The per-block-dequant twin of `qmatvec_mmvq`'s QT_F8_E4M3 arm: same grid/block decomposition
7064    /// (warp per output row, ROWS_PER_BLOCK warps per block, grid.y = m), same q8_1 activation, but
7065    /// the weight scale is a resident [rows, cols] f32 grid read per k128 block inside the kernel
7066    /// instead of one scalar folded at the write. It cannot share `qmatvec_mmvq`'s body because
7067    /// that launcher's arg list is fixed at (bytes, aq, ad, y, in_f, out_f, m, row_bytes [, scale]).
7068    ///
7069    /// `mr` and `rp` have no analogue here (no split-plane e4m3 layout exists), so there is exactly
7070    /// one kernel and no name table — a shape this cannot serve must be refused at LOAD, not here.
7071    pub fn qmatvec_e4m3_blk_mmvq(&self, bytes: &CudaSlice<u8>, aq: &CudaSlice<i8>,
7072                                 ad: &CudaSlice<f32>, scales: &CudaSlice<f32>,
7073                                 m: usize, in_f: usize, out_f: usize, row_bytes: usize,
7074                                 scale_cols: usize)
7075        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7076        let mut y = self.alloc_uninit::<f32>(m * out_f)?;   // full-overwrite output: skip memset
7077        self.qmatvec_e4m3_blk_mmvq_into(bytes, aq, ad, scales, m, in_f, out_f, row_bytes,
7078                                        scale_cols, &mut y)?;
7079        Ok(y)
7080    }
7081
7082    /// Slot-fed twin of `qmatvec_e4m3_blk_mmvq` (caller-owned output; the alloc-free capture lane).
7083    #[allow(clippy::too_many_arguments)]
7084    pub fn qmatvec_e4m3_blk_mmvq_into(&self, bytes: &CudaSlice<u8>, aq: &CudaSlice<i8>,
7085                                      ad: &CudaSlice<f32>, scales: &CudaSlice<f32>,
7086                                      m: usize, in_f: usize, out_f: usize, row_bytes: usize,
7087                                      scale_cols: usize, y: &mut CudaSlice<f32>)
7088        -> Result<(), Box<dyn std::error::Error>> {
7089        const ROWS_PER_BLOCK: u32 = 4;   // matches MEMRA_MMVQ_ROWS in qmatvec.cu
7090        let f = self.func("qmatvec_e4m3_blk_mmvq");
7091        let cfg = LaunchConfig {
7092            grid_dim: ((out_f as u32).div_ceil(ROWS_PER_BLOCK), m as u32, 1),
7093            block_dim: (32, ROWS_PER_BLOCK, 1),   // warp-per-row
7094            shared_mem_bytes: 0,                  // warp-only reduce
7095        };
7096        let (inf, outf, mi, rb, sc) =
7097            (in_f as i32, out_f as i32, m as i32, row_bytes as i64, scale_cols as i32);
7098        let __s_b = self.gpu.stream();
7099        let mut b = __s_b.launch_builder(&f);
7100        b.arg(bytes).arg(aq).arg(ad).arg(scales).arg(&mut *y)
7101         .arg(&inf).arg(&outf).arg(&mi).arg(&rb).arg(&sc);
7102        unsafe { b.launch(cfg)?; }
7103        Ok(())
7104    }
7105
7106    /// BLOCK-128 e4m3 BATCHED matvec (lane/rp-on-st, 2026-08-06): the weight-read-once twin of
7107    /// `qmatvec_e4m3_blk_mmvq` for m=2..16. Per (token,row) BIT-IDENTICAL to the grid.y=m launch
7108    /// (same fmaf chain, same per-k32 `s * ad` fold, same warp reduce), so it inherits the
7109    /// decode-exactness contract while reading the weight ONCE for up to `mcols` columns instead
7110    /// of `m` times. `mcols` must be one of {2,4,8,16} and satisfy `mcols >= m`.
7111    #[allow(clippy::too_many_arguments)]
7112    pub fn qmatvec_e4m3_blk_mmvq_batched(&self, bytes: &CudaSlice<u8>, aq: &CudaSlice<i8>,
7113                                         ad: &CudaSlice<f32>, scales: &CudaSlice<f32>,
7114                                         m: usize, in_f: usize, out_f: usize, row_bytes: usize,
7115                                         scale_cols: usize, mcols: usize)
7116        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7117        const ROWS_PER_BLOCK: u32 = 4;   // matches MEMRA_MMVQ_ROWS in qmatvec.cu
7118        debug_assert!(mcols >= m, "blk batched: mcols {mcols} < m {m}");
7119        let name = match mcols {
7120            2 => "qmatvec_e4m3_blk_mmvq_b2",
7121            4 => "qmatvec_e4m3_blk_mmvq_b4",
7122            8 => "qmatvec_e4m3_blk_mmvq_b8",
7123            16 => "qmatvec_e4m3_blk_mmvq_b16",
7124            _ => return Err(format!("qmatvec_e4m3_blk_mmvq_batched: no kernel for mcols {mcols}").into()),
7125        };
7126        let mut y = self.alloc_uninit::<f32>(m * out_f)?;
7127        let f = self.func(name);
7128        let cfg = LaunchConfig {
7129            grid_dim: ((out_f as u32).div_ceil(ROWS_PER_BLOCK), 1, 1),
7130            block_dim: (32, ROWS_PER_BLOCK, 1),
7131            shared_mem_bytes: 0,
7132        };
7133        let (inf, outf, mi, rb, sc) =
7134            (in_f as i32, out_f as i32, m as i32, row_bytes as i64, scale_cols as i32);
7135        let __s_b = self.gpu.stream();
7136        let mut b = __s_b.launch_builder(&f);
7137        b.arg(bytes).arg(aq).arg(ad).arg(scales).arg(&mut y)
7138         .arg(&inf).arg(&outf).arg(&mi).arg(&rb).arg(&sc);
7139        unsafe { b.launch(cfg)?; }
7140        Ok(y)
7141    }
7142
7143    /// Test entry for the kernel_check exactness gate: the block-128 e4m3 batched MMVQ from raw
7144    /// bytes with an internal q8_1 quantize (mirrors `qmatvec_batched_raw`).
7145    #[allow(clippy::too_many_arguments)]
7146    pub fn qmatvec_e4m3_blk_batched_raw(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>,
7147                                        scales: &CudaSlice<f32>, m: usize, in_f: usize,
7148                                        out_f: usize, row_bytes: usize, scale_cols: usize,
7149                                        mcols: usize)
7150        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7151        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
7152        self.qmatvec_e4m3_blk_mmvq_batched(bytes, &aq, &ad, scales, m, in_f, out_f, row_bytes,
7153                                           scale_cols, mcols)
7154    }
7155
7156    /// Test entry for the kernel_check exactness gate: the block-128 e4m3 MMVQ from raw bytes with
7157    /// an internal q8_1 quantize (mirrors `qmatvec_mmvq_raw`).
7158    #[allow(clippy::too_many_arguments)]
7159    pub fn qmatvec_e4m3_blk_mmvq_raw(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>,
7160                                     scales: &CudaSlice<f32>, m: usize, in_f: usize, out_f: usize,
7161                                     row_bytes: usize, scale_cols: usize)
7162        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7163        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
7164        self.qmatvec_e4m3_blk_mmvq(bytes, &aq, &ad, scales, m, in_f, out_f, row_bytes, scale_cols)
7165    }
7166
7167    /// Test entries for the kernel_check bit-parity gate: fused e4m3 launches from raw weight
7168    /// bytes with internal q8_1 quantize, no env gating (mirrors `qmatvec_q8_fused*_raw`).
7169    #[allow(clippy::too_many_arguments)]
7170    pub fn qmatvec_e4m3_fused2_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, x: &CudaSlice<f32>,
7171                                   in_f: usize, out0: usize, out1: usize, row_bytes: usize,
7172                                   ws0: f32, ws1: f32)
7173        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7174        let (aq, ad) = self.quantize_q8_1(x, 1, in_f)?;
7175        self.e4m3_fused2_core(b0, b1, &aq, &ad, in_f, out0, out1, row_bytes, ws0, ws1)
7176    }
7177
7178    #[allow(clippy::too_many_arguments)]
7179    pub fn qmatvec_e4m3_fused3_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>, b2: &CudaSlice<u8>,
7180                                   x: &CudaSlice<f32>, in_f: usize, out0: usize, out1: usize,
7181                                   out2: usize, row_bytes: usize, ws0: f32, ws1: f32, ws2: f32)
7182        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7183        let (aq, ad) = self.quantize_q8_1(x, 1, in_f)?;
7184        self.e4m3_fused3_core(b0, b1, b2, &aq, &ad, in_f, out0, out1, out2, row_bytes,
7185                              ws0, ws1, ws2)
7186    }
7187
7188    #[allow(clippy::too_many_arguments)]
7189    pub fn qmatvec_e4m3_fused2_t_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
7190                                     x: &CudaSlice<f32>, m: usize, in_f: usize, out0: usize,
7191                                     out1: usize, row_bytes: usize, ws0: f32, ws1: f32)
7192        -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7193        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
7194        self.e4m3_fused2_t_core(b0, b1, &aq, &ad, m, in_f, out0, out1, row_bytes, ws0, ws1)
7195    }
7196
7197    #[allow(clippy::too_many_arguments)]
7198    pub fn qmatvec_e4m3_fused3_t_raw(&self, b0: &CudaSlice<u8>, b1: &CudaSlice<u8>,
7199                                     b2: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize,
7200                                     in_f: usize, out0: usize, out1: usize, out2: usize,
7201                                     row_bytes: usize, ws0: f32, ws1: f32, ws2: f32)
7202        -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7203        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
7204        self.e4m3_fused3_t_core(b0, b1, b2, &aq, &ad, m, in_f, out0, out1, out2, row_bytes,
7205                                ws0, ws1, ws2)
7206    }
7207
7208    /// THE single dispatch point for `QT_F8_E4M3_BLK` from a PRE-QUANTIZED q8_1 activation
7209    /// (lane/fp8-blk128-decode). Every `matmul_pre`-family entry calls this first, so the block-128
7210    /// class has exactly ONE code path across `matmul`, `matmul_pre`, `matmul_pre_noscale`,
7211    /// `matmul_decode_exact` and `matmul_decode_exact_pre` — the same kernel at the same grid for
7212    /// every m, which is what makes verify == decode bit-for-bit at every tier for free.
7213    ///
7214    /// Returns None for any other qtype (the caller continues its normal dispatch). The `blk: Some`
7215    /// pattern is part of the match, not an unwrap: qtype and grid presence are set together in the
7216    /// one residency arm that builds this tensor, and a qtype-without-grid would be a construction
7217    /// bug — better to fall through and hit a loud refusal than to unwrap a None here.
7218    fn try_e4m3_blk_pre(&self, w: &crate::model::GpuTensor, aq: &CudaSlice<i8>,
7219                        ad: &CudaSlice<f32>, m: usize)
7220        -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
7221        use crate::model::GpuTensor;
7222        if let GpuTensor::Quant { bytes, qtype, row_bytes, blk: Some(g), .. } = w {
7223            if *qtype == QT_F8_E4M3_BLK {
7224                // BATCHED tier m=2..16 (lane/rp-on-st): weight read ONCE for up to mcols columns
7225                // instead of m grid.y re-reads. Bit-identical per (token,row) to the grid.y=m form
7226                // below, so the decode-exactness contract is preserved at every width. Gated by
7227                // the same seams the other batched families honor (MEMRA_NO_BATCHED, MEMRA_B8) so
7228                // one rollback door covers every dtype's batched tier.
7229                if (2..=16).contains(&m) && std::env::var("MEMRA_NO_BATCHED").is_err()
7230                    && (m <= 4 || Self::b8_enabled()) {
7231                    let mcols = Self::batched_mcols(m);
7232                    return Ok(Some(self.qmatvec_e4m3_blk_mmvq_batched(
7233                        bytes, aq, ad, &g.scales, m, w.in_features(), w.out_features(),
7234                        *row_bytes, g.cols, mcols)?));
7235                }
7236                return Ok(Some(self.qmatvec_e4m3_blk_mmvq(
7237                    bytes, aq, ad, &g.scales, m, w.in_features(), w.out_features(),
7238                    *row_bytes, g.cols)?));
7239            }
7240        }
7241        Ok(None)
7242    }
7243
7244    /// PREFILL (m >= GEMM_M_THRESHOLD) for `QT_F8_E4M3_BLK` — DEQUANT-PER-CALL to the Q8_0 slab
7245    /// this class's residency replaced, then the ordinary Q8_0 prefill dispatch on the transient.
7246    ///
7247    /// WHY THIS EXISTS AT ALL, i.e. the regression it prevents: the decode kernel is a warp-per-row
7248    /// GEMV. At grid.y=m it re-reads the whole weight once PER TOKEN, so letting a 512-token prefill
7249    /// chunk reach it would be a ~500x weight-traffic blowup on the single most bandwidth-bound part
7250    /// of the forward. Native residency is a DECODE win and must not be paid for in prefill, so
7251    /// prefill keeps the floor's arithmetic and the floor's kernels.
7252    ///
7253    /// WHY DEQUANT-PER-CALL rather than a second resident slab: a resident slab is dual residency —
7254    /// it gives back the entire 1.0-vs-1.0625 B/weight win this lane exists to capture (and then
7255    /// some, since the e4m3 copy stays too). The transient costs one linear device pass per
7256    /// (projection, prefill call) and frees immediately.
7257    ///
7258    /// NUMERICALLY IT IS THE FLOOR, EXACTLY: `fp8_blk_dequant_q8_0` is the merged ARM B' kernel,
7259    /// gate-proven BYTE-IDENTICAL to the host dequant+re-encode (kernel-check `fp8-blk-gpu`). So the
7260    /// slab these bytes form is bit-for-bit the slab the `MEMRA_ST_E4M3_BLK=0` arm makes resident,
7261    /// and every prefill kernel downstream sees identical input — prefill logits under this lane are
7262    /// bit-identical to prefill logits under the floor, which is what makes the decode A/B a clean
7263    /// single-variable comparison instead of a two-variable one.
7264    ///
7265    /// WHAT IT COSTS, MEASURED, AND WHY THAT COST IS MOSTLY STRUCTURAL (27B block-128 ckpt, pp512,
7266    /// this rig = RTX 5090 Laptop, ~896 GB/s GDDR7). This arm makes prefill move the weight THREE
7267    /// times instead of once: read 6.88 GB of e4m3, write 7.31 GB of Q8_0, then the MMQ reads that
7268    /// 7.31 GB back. The two extra passes are 14.19 GB = 15.8 ms at this card's roofline against a
7269    /// ~332 ms pp512, i.e. **~-4.5% pp is a floor no kernel tuning can remove** — only deleting the
7270    /// dequant can. Measured: the dequant kernel costs 27.9 ms/pass (nsys, 208 projections) after
7271    /// the 2026-08-05 vector rewrite (was 66.5 ms at one byte per thread), and e2e pp512 is
7272    /// 1451.4 vs the slab arm's 1541.6 tok/s = -5.8% (N=3 interleaved pairs). So ~1.3pp of the
7273    /// -5.8% is residual kernel inefficiency and ~4.5pp is the extra traffic itself.
7274    ///
7275    /// SO THE DEQUANT IS NO LONGER THE DEFAULT ROUTE — it is the FALLBACK. The per-block FP8 MMQ
7276    /// tile (`try_fp8_blk_mmq`) consumes the resident e4m3 bytes + grid DIRECTLY, deleting both extra
7277    /// passes, and since 2026-08-05 it runs FIRST and by default for the native-resident source
7278    /// (`fp8_blk_mmq_native_enabled`; `MEMRA_FP8_MMQ=0` is the seam back to this dequant). On paper
7279    /// the trade was unassumable — lane/fp8-mmq-v2 measured that tile at 0.85-1.09x the Q8_0 MMQ
7280    /// floor GEMM-only, so it swapped a -4.5% traffic cost for a 0-to-15% GEMM cost of unknown sign.
7281    /// Measured on the 27B (3 arms interleaved, N=3, research/fp8blk-20260805/VERDICT.md): slab
7282    /// 1540.5 / this dequant 1449.1 / the tile 1553.3 tok/s, min(tile) > max(slab). The tile wins
7283    /// because v2's denominator had its slab already resident while this class's floor must build it
7284    /// every call; same tile, opposite sign, because the question changed.
7285    ///
7286    /// THIS ARM STILL RUNS, and is not dead code: every `try_fp8_blk_mmq` precondition (in_f % 16,
7287    /// grid dims vs shape, per-tensor scale == 1.0, the e4m3-NaN scan) refuses by falling through to
7288    /// here, so a checkpoint the tile cannot take keeps exact prefill on the floor's own bits rather
7289    /// than losing the class. It is also what `MEMRA_FP8_MMQ=0` reverts to.
7290    fn try_e4m3_blk_prefill(&self, w: &crate::model::GpuTensor, x: &CudaSlice<f32>, m: usize)
7291        -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
7292        use crate::model::GpuTensor;
7293        let GpuTensor::Quant { bytes, qtype, blk: Some(g), .. } = w else { return Ok(None) };
7294        if *qtype != QT_F8_E4M3_BLK { return Ok(None) }
7295        // NO-DEQUANT ROUTE, THE DEFAULT (MEMRA_FP8_MMQ=0 reverts): the per-block MMQ tile eats the
7296        // resident e4m3 bytes and grid as-is, so neither extra weight pass happens. Its own
7297        // preconditions (in_f % 16, grid dims, scale == 1.0, no e4m3 NaN code) can refuse — fall
7298        // through to the dequant below when they do, never silently produce nothing.
7299        if let Some(y) = self.try_fp8_blk_mmq(w, x, m)? { return Ok(Some(y)); }
7300        let (in_f, out_f) = (w.in_features(), w.out_features());
7301        let slab = self.fp8_blk_dequant_q8_0_dev(bytes, &g.scales, out_f, in_f)?;
7302        let tmp = GpuTensor::Quant {
7303            bytes: slab,
7304            qtype: QT_Q8_0,
7305            row_bytes: in_f / 32 * 34,
7306            ne: vec![in_f as u64, out_f as u64],
7307            scale: 1.0,
7308            rp: false,
7309            #[cfg(memra_cutlass)]
7310            cutlass: None,
7311            fp8: None, blk: None, f16: None, rp4: None,
7312        };
7313        // Recursion terminates: `tmp` is QT_Q8_0 with `blk: None`, so it cannot re-enter this arm.
7314        Ok(Some(self.matmul(&tmp, x, m)?))
7315    }
7316
7317    pub fn matmul_pre_noscale(&self, w: &crate::model::GpuTensor, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
7318                              m: usize) -> Result<Option<(CudaSlice<f32>, f32)>, Box<dyn std::error::Error>> {
7319        use crate::model::GpuTensor;
7320        // BLOCK-128 e4m3: every scale factor is folded inside the kernel per k128, so the
7321        // "separable post-op scale" this entry exists to defer is 1.0 — return it explicitly
7322        // rather than let the tail below refuse and cost the caller a re-dispatch.
7323        if m == 1 {
7324            if let Some(y) = self.try_e4m3_blk_pre(w, aq, ad, m)? { return Ok(Some((y, 1.0))); }
7325        }
7326        // Only the m==1 fast path applies the scale as a separable post-op; bail everywhere else.
7327        if m != 1 || !self.uses_q8_1_fast(w) { return Ok(None); }
7328        let in_f = w.in_features();
7329        let out_f = w.out_features();
7330        let (bytes, qtype, row_bytes, scale, rp) = match w {
7331            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } => (bytes, *qtype, *row_bytes, *scale, *rp),
7332            _ => return Ok(None),
7333        };
7334        // MMVQ warp-per-row (scale==1.0 passed -> kernel skips its internal scale; we return scale).
7335        if self.mmvq_supports(qtype) {
7336            // Q4_0 split-plane mirror (dp4a fallback below keeps the raw GGUF bytes).
7337            let (mbytes, mrp) = match w {
7338                GpuTensor::Quant { rp4: Some(m4), .. } => (m4, true),
7339                _ => (bytes, rp),
7340            };
7341            let y = self.qmatvec_mmvq(mbytes, aq, ad, m, in_f, out_f, qtype, row_bytes, /*scale*/ 1.0, mrp)?;
7342            return Ok(Some((y, scale)));
7343        }
7344        // dp4a fallback: same launch as matmul_pre but WITHOUT the post scale_inplace.
7345        let name = match qtype {
7346            QT_Q8_0 => "qmatvec_q8_0_dp4a", QT_Q4_K => "qmatvec_q4_K_dp4a",
7347            QT_Q6_K => "qmatvec_q6_K_dp4a", QT_Q5_K => "qmatvec_q5_K_dp4a",
7348            QT_Q3_K => "qmatvec_q3_K_dp4a",
7349            QT_NVFP4 => if rp { "qmatvec_nvfp4_dp4a_rp" } else { "qmatvec_nvfp4_dp4a" },
7350            QT_IQ4_XS => "qmatvec_iq4_XS_dp4a",
7351            _ => return Ok(None),
7352        };
7353        let f = self.func(name);
7354        let mut y = self.alloc_uninit::<f32>(m * out_f)?;
7355        let cfg = LaunchConfig { grid_dim: (out_f as u32, m as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
7356        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
7357        let __s_b = self.gpu.stream();
7358        let mut b = __s_b.launch_builder(&f);
7359        b.arg(bytes).arg(aq).arg(ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
7360        unsafe { b.launch(cfg)?; }
7361        Ok(Some((y, scale)))
7362    }
7363
7364    /// True if `qtype` has a warp-per-row MMVQ decode kernel AND MEMRA_MMVQ is set. Only the 4
7365    /// daily-hot dtypes (Q8_0, Q4_K, Q6_K, NVFP4) — others keep the _dp4a matvec (oracle/fallback).
7366    pub fn mmvq_supports(&self, qtype: i32) -> bool {
7367        // DEFAULT ON since 2026-07-08 (MEMRA_MMVQ=0 reverts to the _dp4a matvec class).
7368        // QT_F8_E4M3 is exempt from the MEMRA_MMVQ=0 escape: the e4m3 mmvq family is that dtype's
7369        // ONLY int8-act kernel class (there is no _dp4a twin), so its m=1/verify/batched dispatch
7370        // is a pure function of the dtype — the decode-parity law holds under every env.
7371        if qtype == QT_F8_E4M3 { return true; }
7372        if std::env::var("MEMRA_MMVQ").as_deref() == Ok("0") { return false; }
7373        matches!(qtype, QT_Q8_0 | QT_Q4_K | QT_Q5_K | QT_Q6_K | QT_NVFP4 | QT_Q4_0)
7374    }
7375
7376    /// PERF-3 warp-per-row MMVQ launcher (decode m=1 hot path). block=(32,ROWS_PER_BLOCK,1):
7377    /// one warp owns one output row, warp-only __shfl reduction (no smem barrier). Bit-equivalent
7378    /// to qmatvec_*_dp4a up to f32 reduction order. Pre-quantized q8_1 activation (aq,ad). NVFP4
7379    /// per-tensor macro-scale applied post (scale==1.0 for other dtypes -> no-op).
7380    pub fn qmatvec_mmvq(&self, bytes: &CudaSlice<u8>, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
7381                        m: usize, in_f: usize, out_f: usize, qtype: i32, row_bytes: usize, scale: f32,
7382                        rp: bool)
7383                        -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7384        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite GEMM output: skip memset
7385        self.qmatvec_mmvq_into(bytes, aq, ad, m, in_f, out_f, qtype, row_bytes, scale, rp, &mut y)?;
7386        Ok(y)
7387    }
7388
7389    /// Slot-fed MMVQ twin (alloc-free capture lane): full policy body, caller-owned output.
7390    #[allow(clippy::too_many_arguments)]
7391    pub fn qmatvec_mmvq_into(&self, bytes: &CudaSlice<u8>, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
7392                        m: usize, in_f: usize, out_f: usize, qtype: i32, row_bytes: usize, scale: f32,
7393                        rp: bool, y: &mut CudaSlice<f32>)
7394                        -> Result<(), Box<dyn std::error::Error>> {
7395        debug_assert!(y.len() >= m * out_f);
7396        const ROWS_PER_BLOCK: u32 = 4;   // matches MEMRA_MMVQ_ROWS in qmatvec.cu
7397        // SMALL-SHAPE GRID FILL (H100 lane, 2026-07-26 microbench: attn qkv out_f=2048 =
7398        // 0.97 waves at the 4-warp block -> 66% of peak). The g2 twin (2 warps/block)
7399        // doubles the grid when the 4-warp launch would be sub-wave; per-row program
7400        // identical -> bit-identical. MEMRA_Q80_G2=0 reverts.
7401        if qtype == QT_Q8_0 && rp && m == 1 && out_f >= 64
7402            && (out_f as u32).div_ceil(ROWS_PER_BLOCK) < 4 * self.sm_count() as u32
7403            && {
7404                static G2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7405                *G2.get_or_init(|| std::env::var("MEMRA_Q80_G2").as_deref() != Ok("0"))
7406            }
7407        {
7408            let f = self.func("qmatvec_q8_0_mmvq_rp_g2");
7409            let cfg = LaunchConfig {
7410                grid_dim: ((out_f as u32).div_ceil(2), 1, 1),
7411                block_dim: (32, 2, 1),
7412                shared_mem_bytes: 0,
7413            };
7414            let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, 1i32, row_bytes as i64);
7415            let __s_b = self.gpu.stream();
7416            let mut b = __s_b.launch_builder(&f);
7417            b.arg(bytes).arg(aq).arg(ad).arg(&mut *y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
7418            unsafe { b.launch(cfg)?; }
7419            if scale != 1.0 { self.scale_inplace(y, scale, out_f)?; }
7420            return Ok(());
7421        }
7422        // Multi-row-per-warp (mr2) policy, fixed since the 2026-07 sweeps (the MEMRA_MMVQ_MR
7423        // override + mr4 kernel were retired 2026-07-08 — mr4 regressed on register pressure and
7424        // crashed under rp; q4_K/q6_K mr2 measured flat, "no gain = no change"):
7425        //   NVFP4 m=1 -> mr2 (clean +1-2% on 9B: RPW acc chains hide the weight-load latency
7426        //     that pins the single-row kernel at 30-46% DRAM). Bit-identical per row.
7427        //   Q5_K m=1 -> mr2 (2026-07-05: the FR-Spec trimmed draft head is Q5_K 32768 rows = 8%
7428        //     of the 27B p3 spec wall; latency-bound like the other k-quants pre-fix).
7429        //   Q4_K/Q6_K m=1 -> single-row (mr2 measured +0.7% / flat — weight-bandwidth-bound).
7430        let mut mr: u32 = if m == 1 && (qtype == QT_NVFP4 || qtype == QT_Q5_K) { 2 } else { 1 };
7431        // Q4_0 mr (gemma trunk): DEFAULT 1 since 2026-07-13 (MEMRA_Q40_MR=2 reverts) — the
7432        // mr1 rp twin doubles the block count and wins the tail-quantization/latency battle
7433        // on every gemma model (E4B +3.75%: 198.9 vs 191.7; 26B +0.7%; 31B +0.9%; N=2-3
7434        // valid-window interleaved, bit-identical per row — same dot program).
7435        if m == 1 && qtype == QT_Q4_0 {
7436            static Q40MR: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
7437            // shape policy PROBED NEGATIVE (2026-07-13): tall-only mr1 197.2 vs
7438            // mr1-everywhere 198.7 — mr1 wins wide-output shapes too; arm removed.
7439            mr = *Q40MR.get_or_init(|| std::env::var("MEMRA_Q40_MR").ok()
7440                .and_then(|v| v.parse().ok()).unwrap_or(1));
7441        }
7442        // q5issue lane (2026-07-08): MEMRA_Q5K_ISSUE swaps the q5_K m=1 mmvq kernels for the
7443        // issue-reduced `_il` bodies (uint4 header/qh/qs loads + branchless scale decode —
7444        // cuts ~34 LDG.U16 + ~5 LDG.U8 + a warp-divergent scale branch per 32-elem group-row
7445        // to 5 LDG.128). Bit-identical per (token,row) to the reference kernels.
7446        // `1` = shape-aware policy (N=3 clock-locked micro-bench, mem P0, synthetic real shapes):
7447        //   out_f <= 65536 (trunk/frspec regime): il at the default mr — mr2_il -9.5%/-10.5%
7448        //     on 4096x4096/4096x8192, -3.1% on the 32768 frspec head vs the mr2-ref default;
7449        //   out_f > 65536 (the 248320-row 27B lm_head, already ~97% of the mem wall): mr2_il
7450        //     REGRESSES +22% there but mr1_il wins -2.1% vs the mr2-ref default -> force mr=1.
7451        // `2` = force il at the current mr for EVERY shape (A/B probe seam). Default OFF.
7452        let q5_mode = std::env::var("MEMRA_Q5K_ISSUE").ok();
7453        let q5_force = q5_mode.as_deref() == Some("2");
7454        // DEFAULT ON since 2026-07-08 (MEMRA_Q5K_ISSUE=0 reverts): +1.8% 9B plain e2e N=3
7455        // (128.2 -> 130.4), 27B flat (its big head is already at the mem wall), all gates green.
7456        let q5_il = qtype == QT_Q5_K && m == 1
7457            && (q5_force || q5_mode.as_deref().map(|v| v != "0").unwrap_or(true));
7458        if q5_il && !q5_force && out_f > 65536 { mr = 1; }
7459        // Q4_0 split-plane rp: mr2 default; MEMRA_Q40_MR=1 reaches the mr1 rp twin
7460        // (2026-07-13 — the tall-input/short-output tail-quantization probe).
7461        if qtype == QT_Q4_0 && rp && mr != 1 { mr = 2; }
7462        // Q8_0 rp (H100 lane): mr1 default — the q4_0 mr2 recipe MEASURED NEGATIVE on H100
7463        // (2026-07-26 N=3: mr1 186.2 vs mr2 171.5 tok/s; halving the grid on 132 SMs costs
7464        // more than 2-row ILP buys). mr2 kernel stays behind MEMRA_Q80_MR=2 for the corpus.
7465        if qtype == QT_Q8_0 && rp {
7466            static Q80MR: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
7467            mr = *Q80MR.get_or_init(|| std::env::var("MEMRA_Q80_MR").ok()
7468                .and_then(|v| v.parse().ok()).unwrap_or(1));
7469        }
7470        let name = match (qtype, mr, rp) {
7471            (QT_NVFP4, 2, false) => "qmatvec_nvfp4_mmvq_mr2",
7472            (QT_NVFP4, 2, true)  => "qmatvec_nvfp4_mmvq_mr2_rp",
7473            (QT_NVFP4, _, true)  => "qmatvec_nvfp4_mmvq_rp",
7474            (QT_Q4_0, 1, true)   => "qmatvec_q4_0_mmvq_rp",
7475            (QT_Q4_0, _, true)   => "qmatvec_q4_0_mmvq_mr2_rp",
7476            (QT_Q5_K, 2, _) => if q5_il { "qmatvec_q5_K_mmvq_mr2_il" } else { "qmatvec_q5_K_mmvq_mr2" },
7477            (QT_Q8_0, 2, true) => "qmatvec_q8_0_mmvq_mr2_rp",
7478            // rpca (cp.async-staged weight ring): MEASURED NEGATIVE on H100 for Q8_0
7479            // (2026-07-26 N=3: 181.8 vs plain rp 185.5 — the smem round-trip exceeds the
7480            // latency it hides for 8-bit direct-dp4a; the NVFP4 win case overlaps table
7481            // decode with half the bytes). OPT-IN via MEMRA_Q80_CA=1 for the corpus.
7482            (QT_Q8_0, _, true) if in_f % 1024 == 0 && {
7483                static CA: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7484                *CA.get_or_init(|| std::env::var("MEMRA_Q80_CA").as_deref() == Ok("1"))
7485            } => "qmatvec_q8_0_mmvq_rpca",
7486            (QT_Q8_0, _, true) => "qmatvec_q8_0_mmvq_rp",
7487            (QT_Q8_0, _, _) => "qmatvec_q8_0_mmvq",
7488            // K-quant split-plane twins (H100 K-quant coalescing fix, 2026-08-01): the rp4
7489            // mirror routes here; GGUF layout keeps the plain kernels. rp bytes MUST never
7490            // reach a GGUF-layout kernel or vice versa.
7491            (QT_Q4_K, _, true) => "qmatvec_q4_K_mmvq_rp",
7492            (QT_Q6_K, _, true) => "qmatvec_q6_K_mmvq_rp",
7493            (QT_Q4_K, _, _) => "qmatvec_q4_K_mmvq",
7494            (QT_Q4_0, 2, false) => "qmatvec_q4_0_mmvq_mr2",
7495            (QT_Q4_0, _, false) => "qmatvec_q4_0_mmvq",
7496            (QT_Q5_K, _, _) => if q5_il { "qmatvec_q5_K_mmvq_il" } else { "qmatvec_q5_K_mmvq" },
7497            (QT_Q6_K, _, _) => "qmatvec_q6_K_mmvq",
7498            (QT_NVFP4, _, false) => "qmatvec_nvfp4_mmvq",
7499            (QT_F8_E4M3, _, _) => "qmatvec_e4m3_mmvq",
7500            _ => panic!("qmatvec_mmvq: qtype {qtype} has no MMVQ kernel"),
7501        };
7502        let f = self.func(name);
7503        // each block still has ROWS_PER_BLOCK warps; with mr rows/warp it covers ROWS_PER_BLOCK*mr rows.
7504        let rows_per_block = ROWS_PER_BLOCK * mr;
7505        let cfg = LaunchConfig {
7506            grid_dim: ((out_f as u32 + rows_per_block - 1) / rows_per_block, m as u32, 1),
7507            block_dim: (32, ROWS_PER_BLOCK, 1),   // warp-per-row (x mr rows each)
7508            shared_mem_bytes: 0,                  // warp-only reduce at m=1
7509        };
7510        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
7511        let __s_b = self.gpu.stream();
7512        let mut b = __s_b.launch_builder(&f);
7513        // NVFP4 + e4m3 mmvq kernels take the macro-scale as a fused epilogue arg (applied at the
7514        // write — bit-identical to the old separate scale_inplace pass, minus one launch per matvec:
7515        // 53 scale launches/token on the 9B; for e4m3 the scale is the checkpoint's per-tensor f32
7516        // weight_scale). Other mmvq kernels keep the 8-arg signature.
7517        if qtype == QT_NVFP4 || qtype == QT_F8_E4M3 {
7518            b.arg(bytes).arg(aq).arg(ad).arg(&mut *y).arg(&inf).arg(&outf).arg(&mi).arg(&rb).arg(&scale);
7519            unsafe { b.launch(cfg)?; }
7520        } else if Self::pdl_on() && Self::pdl_mmvq_on()
7521            && matches!(name, "qmatvec_q4_0_mmvq_rp" | "qmatvec_q6_K_mmvq"
7522                              | "qmatvec_q6_K_mmvq_rp") {
7523            // PDL wave-A (2026-07-23): the two decode-hot single-matvec kernels carry
7524            // MEMRA_PDL_ENTRY — grid launches while the producer drains. ONLY the marked
7525            // names may take this launch (unmarked kernels would read unordered).
7526            {
7527            use cudarc::driver::{DevicePtr, DevicePtrMut};
7528            let s = &self.gpu.stream();
7529            let (pw, _g0) = bytes.device_ptr(s); let (paq, _g1) = aq.device_ptr(s);
7530            let (pad, _g2) = ad.device_ptr(s); let (py, _g3) = y.device_ptr_mut(s);
7531            let mut ps = [
7532                &pw as *const _ as *mut std::ffi::c_void, &paq as *const _ as *mut _,
7533                &pad as *const _ as *mut _, &py as *const _ as *mut _,
7534                &inf as *const _ as *mut _, &outf as *const _ as *mut _,
7535                &mi as *const _ as *mut _, &rb as *const _ as *mut _,
7536            ];
7537            unsafe { self.launch_pdl(name, cfg.grid_dim, cfg.block_dim, &mut ps)?; }
7538            }
7539            if scale != 1.0 { self.scale_inplace(y, scale, m * out_f)?; }
7540        } else {
7541            b.arg(bytes).arg(aq).arg(ad).arg(&mut *y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
7542            unsafe { b.launch(cfg)?; }
7543            if scale != 1.0 { self.scale_inplace(y, scale, m * out_f)?; }
7544        }
7545        Ok(())
7546    }
7547
7548    /// Test entry for the kernel_check bit-equivalence gate: run the warp-per-row MMVQ directly
7549    /// from raw weight bytes (quantize the f32 activation `x` to q8_1 internally). NVFP4 per-tensor
7550    /// macro-scale is NOT applied (caller compares bare, like qmatvec_*_fast). Mirrors qmatvec_gemm_raw.
7551    pub fn qmatvec_mmvq_raw(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
7552                            out_f: usize, qtype: i32, row_bytes: usize, rp: bool)
7553                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7554        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
7555        self.qmatvec_mmvq(bytes, &aq, &ad, m, in_f, out_f, qtype, row_bytes, 1.0, rp)
7556    }
7557
7558    /// True if `qtype` has a batched weight-resident (`_b2`/`_b4`) matvec kernel. These mirror the
7559    /// `_mmvq` kernels but iterate the m token columns INSIDE one warp/row, so the weight bytes leave
7560    /// HBM/L2 once for m tokens (vs grid.y=m re-reading m times). The 5 daily-hot dtypes have them.
7561    pub fn batched_supports(&self, qtype: i32) -> bool {
7562        matches!(qtype, QT_Q8_0 | QT_Q4_K | QT_Q5_K | QT_Q6_K | QT_NVFP4 | QT_F8_E4M3 | QT_Q4_0)
7563    }
7564
7565    /// IQ4_XS trunk fast seam: MEMRA_IQ_FAST=0 reverts non-expert IQ4_XS matmuls to the Stage-A
7566    /// f32 oracle path. Default ON since 2026-08-02 (research/kat-anomaly-20260802/): the old
7567    /// opt-in default left every IQ4_XS-trunk artifact (KAT-Coder IQ4_XS: attn_qkv/attn_gate/
7568    /// ssm_out/shexp, ~0.52GB re-read per decode tick) on the oracle kernel — decode 106.7 ->
7569    /// 193.4 tok/s (x5 interleaved), pp512 228 -> 697, same bytes, via qmatvec_iq4_XS_dp4a. The
7570    /// supported artifacts carry IQ4_XS only in EXPERT banks (their own dispatch, not this seam),
7571    /// so this admission is dispatch-unchanged for every non-IQ4_XS-trunk model.
7572    pub fn iq_fast_enabled() -> bool {
7573        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7574        *ON.get_or_init(|| std::env::var("MEMRA_IQ_FAST").map(|v| v != "0").unwrap_or(true))
7575    }
7576
7577    /// b8 tier seam: MEMRA_B8=0 keeps m=5..8 on the per-m grid.y=m path (m=2..4 batched dispatch
7578    /// unaffected). Default ON — the K=4..7 spec-verify weight-read-once fix.
7579    pub fn b8_enabled() -> bool {
7580        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7581        *ON.get_or_init(|| std::env::var("MEMRA_B8").map(|v| v != "0").unwrap_or(true))
7582    }
7583
7584    /// Compile-time column batch for a runtime m: 2 -> b2, 3..4 -> b4, 5..8 -> b8.
7585    pub fn batched_mcols(m: usize) -> usize {
7586        if m == 2 { 2 } else if m <= 4 { 4 } else if m <= 8 { 8 } else { 16 }
7587    }
7588
7589    /// Kernel name for the batched matvec of `(qtype, mcols)`. mcols ∈ {2,4,8}. The b8 tier is the
7590    /// K=4..7 spec-verify fix (T=5..8): pre-b8 those T fell to grid.y=m per-row MMVQ = m full
7591    /// weight reads/launch — the measured 27B K=4 cliff (101 -> 73 tok/s at p3 despite acceptance
7592    /// holding 54%). One b8 launch reads the weight ONCE for up to 8 columns (c >= m masked).
7593    fn batched_kernel_name(qtype: i32, mcols: usize) -> Option<&'static str> {
7594        Some(match (qtype, mcols) {
7595            (QT_Q8_0, 2) => "qmatvec_q8_0_mmvq_b2", (QT_Q8_0, 4) => "qmatvec_q8_0_mmvq_b4",
7596            (QT_Q8_0, 8) => "qmatvec_q8_0_mmvq_b8",
7597            // b16 now has BOTH forms (lane/rp-on-st, 2026-08-06). It used to be rp-ONLY, which
7598            // made the q8rp mirror the exact-16 tier's admission ticket for any model carrying a
7599            // single Q8_0 matmul — measured as the FP8-ST refusal (`L0.ssm_beta qtype=0
7600            // rp4=false`, 96 t / 23.9 MiB = 0.143% of resident weight). The mirror stays a
7601            // BANDWIDTH lever on Q8_0-dominant GGUFs; it is no longer a correctness prerequisite.
7602            (QT_Q8_0, 16) => "qmatvec_q8_0_mmvq_b16",
7603            (QT_Q4_K, 2) => "qmatvec_q4_K_mmvq_b2", (QT_Q4_K, 4) => "qmatvec_q4_K_mmvq_b4",
7604            (QT_Q4_K, 8) => "qmatvec_q4_K_mmvq_b8",
7605            // b16 base + _rp (lane/rp-on-st): the 9B NVFP4 GGUF's blocker — real NVFP4 GGUFs keep
7606            // Q4_K attention next to NVFP4 MLP, and the tier's predicate is an ALL.
7607            (QT_Q4_K, 16) => "qmatvec_q4_K_mmvq_b16",
7608            (QT_Q5_K, 2) => "qmatvec_q5_K_mmvq_b2", (QT_Q5_K, 4) => "qmatvec_q5_K_mmvq_b4",
7609            (QT_Q5_K, 8) => "qmatvec_q5_K_mmvq_b8",
7610            // b16 base only (lane/rp-on-st): Q5_K has no rp twins at any width, so there is
7611            // nothing to mirror. Named by the diagnostic as `L0.wqkv_gate qtype=3` on the 9B.
7612            (QT_Q5_K, 16) => "qmatvec_q5_K_mmvq_b16",
7613            (QT_Q6_K, 2) => "qmatvec_q6_K_mmvq_b2", (QT_Q6_K, 4) => "qmatvec_q6_K_mmvq_b4",
7614            (QT_Q6_K, 8) => "qmatvec_q6_K_mmvq_b8", (QT_Q6_K, 16) => "qmatvec_q6_K_mmvq_b16",
7615            (QT_NVFP4, 2) => "qmatvec_nvfp4_mmvq_b2", (QT_NVFP4, 4) => "qmatvec_nvfp4_mmvq_b4",
7616            (QT_NVFP4, 8) => "qmatvec_nvfp4_mmvq_b8",
7617            // b16 (lane/rp-on-st): no mirror needed — NVFP4's 36 B/k32 block is already the
7618            // aligned form its own kernel walks. Unlocks the exact-16 tier for every NVFP4 model
7619            // AND for the mixed FP8-ST artifact, whose 193 NVFP4 tensors were refusing it.
7620            (QT_NVFP4, 16) => "qmatvec_nvfp4_mmvq_b16",
7621            (QT_F8_E4M3, 2) => "qmatvec_e4m3_mmvq_b2", (QT_F8_E4M3, 4) => "qmatvec_e4m3_mmvq_b4",
7622            (QT_F8_E4M3, 8) => "qmatvec_e4m3_mmvq_b8",
7623            // b16 tier (lane/rp-on-st): e4m3 needs NO split-plane mirror to reach it — its native
7624            // row-major layout is already 32B-aligned per k32 block, so the base kernel IS the
7625            // aligned form. Contrast Q8_0, whose b16 exists only as the `_rp` twin (hence q8rp).
7626            (QT_F8_E4M3, 16) => "qmatvec_e4m3_mmvq_b16",
7627            (QT_Q4_0, 2) => "qmatvec_q4_0_mmvq_b2", (QT_Q4_0, 4) => "qmatvec_q4_0_mmvq_b4",
7628            (QT_Q4_0, 8) => "qmatvec_q4_0_mmvq_b8", (QT_Q4_0, 16) => "qmatvec_q4_0_mmvq_b16",
7629            _ => return None,
7630        })
7631    }
7632
7633    /// BATCHED weight-tile-resident matvec from a PRE-QUANTIZED q8_1 activation (the m=2-8 verify/MTP
7634    /// win). One warp walks the weight row ONCE, dp4a vs all m activation columns -> weight HBM/L2
7635    /// traffic 1x for m tokens (vs grid.y=m re-reading it m times). `mcols` ∈ {2,4,8} is the
7636    /// compile-time batch; m must be <= mcols (the c >= m columns are masked in-kernel). y is
7637    /// [m, out_f] token-major. NVFP4 per-tensor macro-scale applied post
7638    /// (scale==1.0 for other dtypes -> no-op). BIT-IDENTICAL per (token,row) to qmatvec_*_mmvq.
7639    ///
7640    /// NVFP4 VARIANT DISPATCH: the batched NVFP4 kernel measured memory-LATENCY bound on the real
7641    /// 27B verify (ncu --set full, 12 steady launches: long_scoreboard 18-30 stalls/issue vs <=1.7
7642    /// for every other reason, DRAM only 41-51% active, lg_throttle 0.7, L1 hit 94% — ONE 6-LDG
7643    /// weight wavefront in flight per warp is the binding constraint, NOT bandwidth and NOT the
7644    /// column-unroll break). Two exactness-free fixes, chosen PER SHAPE from the DRAM-cold 8-copy
7645    /// msweep on all six 27B shapes (2026-07-03):
7646    ///   `pf` = next-g weight-prefetch double-buffer (48 regs, occupancy intact) — wins everywhere
7647    ///          it applies for b4 (-3..-14%), never loses;
7648    ///   `r2` = two rows/warp (67 regs -> 7 resident blocks/SM) — the bigger win (-8.5..-30%) but
7649    ///          wave-quantization-sensitive: with the grid halved to ceil(out_f/8) blocks, a
7650    ///          fractional straggler wave (waves in ~1.05-1.5) costs a full extra latency round on
7651    ///          a latency-bound kernel (27B ffn_down 640 blocks / 574 resident = 1.11 waves: +17%),
7652    ///          while <=1 wave (9B ffn_down 0.89: -30%) or >=2 waves (tail amortized; qkv 2.2:
7653    ///          -8.5%, ffn_gate 3.8: -12.5%) win. For b2, r2 wins on DEEP k-loops (in_f>=6144:
7654    ///          -8..-19%) where the 2-col body starves weight MLP hardest; pf measured negative.
7655    /// b4: r2 when waves(out_f) <= 1 (and grid fills >=half the SMs) or >= 2, else pf.
7656    /// b2: in_f>=6144 -> r2, else base.
7657    /// MEMRA_MMVQ_BV=base|pf|r2|pfr2 forces one variant everywhere (A/B + rollback seam).
7658    /// All variants BIT-IDENTICAL per (token,row): same dp4a order, scales, adg factor, reduce —
7659    /// only load issue time and the row->warp mapping change (kernel-check gates all of them).
7660    /// `rp` = the weight buffer is the A6 SPLIT-PLANE repacked layout (NVFP4 only): the same
7661    /// wave-aware auto rule applies, mapped onto the `_rp` twins (rp/rpr2/rpr2w8 mirror
7662    /// pf/r2/r2w8 — regs 44/67/64 land in the same residency classes).
7663    /// The variant the batched dispatch will pick for this (shape, m, mcols, layout) — exposed so
7664    /// gates can distinguish bit-identical variants (bit-bad==0 required) from the k-split family
7665    /// (deterministic but k-reduce-order-shifted: rel<1e-3 + run-to-run bit-identity required).
7666    /// Device SM count (cached) — grid-fill policy input.
7667    pub fn sm_count(&self) -> i32 {
7668        static SMS: std::sync::OnceLock<i32> = std::sync::OnceLock::new();
7669        *SMS.get_or_init(|| {
7670            use cudarc::driver::sys::CUdevice_attribute_enum as A;
7671            self.gpu.ctx.attribute(A::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT).unwrap_or(82)
7672        })
7673    }
7674
7675    pub fn batched_variant(&self, _m: usize, in_f: usize, out_f: usize, qtype: i32,
7676                           row_bytes: usize, mcols: usize, rp: bool) -> &'static str {
7677        // Q8_0 never joined the auto variant machinery (on sm_120 its only batched shapes
7678        // were tiny aux tensors). On Q8_0-trunk models the layout is the whole game: the
7679        // split-plane mirror (rp) routes to the _rp twins (H100 coalescing fix, 2026-07-26);
7680        // GGUF layout stays "base". rp bytes MUST never reach the base kernel or vice versa.
7681        if qtype == QT_Q8_0 {
7682            return if rp { "rp" } else { "base" };
7683        }
7684        static BV: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
7685        let bv = *BV.get_or_init(|| match std::env::var("MEMRA_MMVQ_BV").as_deref() {
7686            Ok("base") => "base", Ok("pf") => "pf", Ok("r2") => "r2", Ok("r2w8") => "r2w8",
7687            Ok("pfr2") => "pfr2", Ok("ca") => "ca", Ok("car2") => "car2",
7688            // rp* = SPLIT-PLANE REPACKED layout kernels (A6 prototype): W must already be the
7689            // repacked buffer (msweep MSWEEP_RP harness) — never valid on GGUF-layout weights.
7690            Ok("rp") => "rp", Ok("rpr2") => "rpr2", Ok("rpr2w8") => "rpr2w8",
7691            // rpca* = cp.async software-pipelined split-plane (2026-07-05): hides the _rp
7692            // long_scoreboard load stall. rp-layout only; b4/b2 (no b8 twin).
7693            Ok("rpca") => "rpca", Ok("rpcar2") => "rpcar2",
7694            // 2026-07-06 m-small latency arc: rpsc = rpr2 + per-warp smem scale prestage (kills
7695            // the scale-plane global dependency, zero reg growth); rpms/rpmsc = m-split x2
7696            // across warp pairs (2x blocks of rpr2, column halves per warp, BIT-identical to
7697            // _rp); rpks/rpksc = k-split x2 (fastest microbench cells but k-reduce-order-shifted:
7698            // run-spec self-consistency FAILED on the 27B daily driver — verify logits must be
7699            // bit-identical to the decode path — measurement corpus ONLY, never auto).
7700            Ok("rpsc") => "rpsc", Ok("rpms") => "rpms", Ok("rpmsc") => "rpmsc",
7701            Ok("rpks") => "rpks", Ok("rpksc") => "rpksc",
7702            _ => "auto",
7703        });
7704        // cp.async ring variants need 16B-aligned rows (in_f%256==0 -> (in_f/64)*36 % 16 == 0)
7705        // and whole 32-group warp iterations (nsb%32==0 <=> in_f%1024==0). All 27B/9B trunk
7706        // shapes qualify; anything else falls back to the register variants.
7707        let ca_ok = qtype == QT_NVFP4 && (row_bytes % 16 == 0) && (in_f % 1024 == 0);
7708        // rpsc: smem scale plane fits (nsb64 <= 272) + int4-aligned staging (nsb64 % 4 == 0).
7709        // rpks/rpksc: half-plane staging alignment needs nsb64 % 8 == 0 (in_f % 512 == 0).
7710        // MEMRA_KS=0 removes the 2026-07-06 rpsc/rpks/rpksc entries from AUTO (rollback seam;
7711        // forced MEMRA_MMVQ_BV values still work).
7712        static KS_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7713        let ks_on = *KS_ON.get_or_init(|| std::env::var("MEMRA_KS").as_deref() != Ok("0"));
7714        let sc_ok = ks_on && qtype == QT_NVFP4 && (in_f % 256 == 0) && (in_f / 64 <= 272);
7715        let ks_ok = ks_on && qtype == QT_NVFP4 && (in_f % 512 == 0) && (in_f / 64 <= 272);
7716        static SMS: std::sync::OnceLock<i32> = std::sync::OnceLock::new();
7717        let sms = *SMS.get_or_init(|| {
7718            use cudarc::driver::sys::CUdevice_attribute_enum as A;
7719            self.gpu.ctx.attribute(A::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT).unwrap_or(82)
7720        });
7721        // k-quant r2 port (2026-07-04): q4_K/q5_K/q6_K have _r2/_r2w8 twins. ncu on the DRAM-cold
7722        // 9B msweep showed q4_K/q5_K b4 memory-latency bound like NVFP4 pre-fix (long_scoreboard
7723        // 19.6/16.4 per issue, DRAM 47.7/38.2%, L2 weight hit ~13%); q6_K lm_head is the exception
7724        // at DRAM 90-91% = wall-bound (yet r2 still wins -8%: deeper MLP raises achieved DRAM).
7725        // No _pf port (a k-quant group stages 10+ words vs NVFP4's 5 — register cost outweighs;
7726        // r2 covers the same MLP) and no rp (GGUF layout only). Q8_0 stays base: its only real
7727        // batched shapes are the tiny out_f=32 ssm_alpha/beta (8-block grids never fill one SM).
7728        // AUTO RULE = the measured winners table (differs from NVFP4's!):
7729        //   r2w8 NEVER in auto — the reg squeeze (72 -> 64 regs = stack spill) loses to unbounded
7730        //     r2 on every measured k-quant cell, incl. the wave-crossing lm_heads (q6_K 1316 vs
7731        //     r2 1258us) — kernels kept behind the force seam for the corpus;
7732        //   q4_K: r2 whenever the halved grid fills the SMs (blocks >= 4*SMs), INCLUDING the
7733        //     1.05-2.0 straggler window where NVFP4's r2 lost (qkv 1.78 waves: r2 -15% here; the
7734        //     k-quant base kernel leaves more latency on the table than a straggler wave costs);
7735        //   q5_K/q6_K: r2 only at waves >= 2 (the 248320-row lm_heads, 48+ waves: q6_K -8%, q5_K
7736        //     -2%); mid shapes measured base-or-flat (q5_K qkv 49.1 base vs 49.7 r2, attn_gate
7737        //     flat, attn_k base) — the 5/6-bit two-stream unpack makes r2's staging pricier.
7738        //   b2 same table with 8-row blocks: q4_K r2 when filled (-3..-22% all measured shapes),
7739        //     q5_K/q6_K r2 at waves >= 2 (27B lm_head -2.9%; 9B q6_K flat, harmless).
7740        let kq_r2 = matches!(qtype, QT_Q4_K | QT_Q5_K | QT_Q6_K);
7741        // MEMRA_KQ_BV=base|r2|r2w8 forces the k-quant variant WITHOUT touching the NVFP4 dispatch
7742        // (MEMRA_MMVQ_BV is global — an interleaved k-quant-only e2e A/B needs this narrower seam).
7743        static KQBV: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
7744        let kq_bv = *KQBV.get_or_init(|| match std::env::var("MEMRA_KQ_BV").as_deref() {
7745            Ok("base") => "base", Ok("r2") => "r2", Ok("r2w8") => "r2w8",
7746            _ => "auto",
7747        });
7748        let variant: &'static str = if qtype == QT_Q4_0 {
7749            // Q4_0 r2 (gemma verify trunk, 2026-07-10): shared activation loads + the
7750            // row-independent ones-sum computed once per (col,group) for 2 rows. Same
7751            // fill rule as q4_K: r2 when the halved grid still fills the SMs.
7752            static Q40BV: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
7753            let q40 = *Q40BV.get_or_init(|| match std::env::var("MEMRA_Q40_BV").as_deref() {
7754                // ms/sm/la = force-only measurement seams (ALL FLAT/NEGATIVE 2026-07-13,
7755                // never auto): m-split flat (nvcc keeps 72 regs); smem-slab −11% (staging
7756                // + syncs cost more than the stalls, bank-pad made no difference);
7757                // register load-ahead flat (nvcc already reorders). The b-tier limiter
7758                // is still unidentified — see the jsonl row.
7759                Ok("base") => "base", Ok("r2") => "r2", Ok("ms") => "ms", Ok("sm") => "sm",
7760                Ok("la") => "la", _ => "auto",
7761            });
7762            let v = if q40 != "auto" { q40 }
7763            else if (out_f as u32).div_ceil(8) >= 4 * sms as u32 { "r2" } else { "base" };
7764            // split-plane mirror twins (2026-07-10): same fill rule, _rp names.
7765            // (m-split r2 pair twin PROBED FLAT 2026-07-13 — nvcc kept 72 regs either way
7766            // and the limiter is the per-column activation load chain (long_scoreboard
7767            // 42.5%), not occupancy; arm killed per doctrine, jsonl row is the record.)
7768            if rp { match v { "ms" => "r2ms_rp", "sm" => "r2sm_rp", "la" => "r2la_rp",
7769                              "r2" => "r2_rp", _ => "rp" } }
7770            else if matches!(v, "ms" | "sm" | "la") { "r2" } else { v }
7771        } else if qtype != QT_NVFP4 && !kq_r2 {
7772            "base"
7773        } else if kq_r2 && rp {
7774            // K-quant split-plane mirror (2026-08-01): only the plain _rp batched twins are
7775            // compiled for q4_K/q6_K — rp is a LAYOUT, it must survive every heuristic
7776            // (split-plane bytes through a GGUF-layout kernel = NaN). q5_K never mirrors.
7777            "rp"
7778        } else if kq_r2 {
7779            // k-quant r2w8 only exists at b4 (b2_r2 already 8-resident; b8 has no w8 twin) ->
7780            // mcols != 4 forced r2w8 falls to unbounded r2.
7781            if kq_bv != "auto" {
7782                if kq_bv == "r2w8" && mcols != 4 { "r2" } else { kq_bv }
7783            } else if bv != "auto" {
7784                match bv {
7785                    "r2" | "pfr2" | "rpr2" | "car2" => "r2",
7786                    "r2w8" | "rpr2w8" => if mcols != 4 { "r2" } else { "r2w8" },
7787                    _ => "base",   // base/pf/ca/rp forced -> base (no such k-quant kernels)
7788                }
7789            } else {
7790                let blocks = (out_f + 7) / 8;
7791                let waves = blocks as f64 / (7 * sms as usize) as f64;
7792                let filled = blocks >= 4 * sms as usize;
7793                let use_r2 = if qtype == QT_Q4_K { filled } else { waves >= 2.0 };
7794                if use_r2 { "r2" } else { "base" }
7795            }
7796        } else if bv != "auto" {
7797            // r2w8 only exists for b4/b8 (the b2_r2 kernel is already 8-blocks-resident at 60 regs).
7798            // ca/car2 need the alignment gate AND have no b8 twins; pfr2 has no b8 twin either —
7799            // unsupported (shape, mcols) combos fall back to pf/r2.
7800            // On rp buffers, forced legacy names map to their rp twins (layout law).
7801            let v = if bv == "r2w8" && mcols == 2 { "r2" }
7802                else if bv == "ca" && (!ca_ok || mcols == 8) { "pf" }
7803                else if bv == "car2" && (!ca_ok || mcols == 8) { "r2" }
7804                else if bv == "pfr2" && mcols == 8 { "r2" }
7805                else if (bv == "rpr2w8" || bv == "rpr2") && mcols == 2 { "rpr2" }
7806                // rpca* has no b8 twin (falls to rpr2w8/rpr2); needs the ca alignment gate.
7807                else if (bv == "rpca" || bv == "rpcar2") && (!ca_ok || mcols == 8) {
7808                    if mcols == 8 { "rpr2w8" } else { "rpr2" }
7809                }
7810                else if bv == "rpcar2" && mcols == 2 { "rpca" }
7811                // rpsc/rpmsc/rpks* gate on smem-fit + alignment; fall to rpr2 outside it
7812                // (rpms has no smem and no alignment need — always valid on rp buffers).
7813                else if (bv == "rpsc" || bv == "rpmsc") && !sc_ok { "rpr2" }
7814                else if (bv == "rpks" || bv == "rpksc") && !ks_ok { "rpr2" }
7815                else { bv };
7816            if rp {
7817                match v {
7818                    "base" | "pf" | "ca" | "rp" => "rp",
7819                    "r2" | "pfr2" | "car2" | "rpr2" => "rpr2",
7820                    "r2w8" | "rpr2w8" => if mcols == 2 { "rpr2" } else { "rpr2w8" },
7821                    other => other,   // rpca/rpcar2/rpsc/rpks/rpksc pass through (already rp-layout)
7822                }
7823            } else { v }
7824        } else if mcols == 8 {
7825            // b8 AUTO (2026-07-06 m-small latency arc, g7e DRAM-cold rp msweep m=5/6/8 all five
7826            // 27B shapes): rpsc — the rpr2w8 schedule with the warp's scale rows prestaged to
7827            // smem, leaving ONE global dependency (the quant stream) in the k-loop at zero reg
7828            // growth. BIT-identical to rpr2w8 and wins or ties EVERY b8 cell: ffn_gate m5
7829            // 50.7->46.9 m8 64.1->57.1 (-11%), qkv m8 34.6->33.0, ssm_out m8 29.7->28.8,
7830            // attn_gate m8 26.9->26.1, ffn_down m5 58.2->56.9. The faster split-grid twins are
7831            // OUT: rpksc (k-split, ffn_down m5 -21%) broke run-spec self-consistency (k-reduce
7832            // order shifts verify argmax at tie margins — verify must stay bit-identical to the
7833            // m=1 decode chain); rpmsc (m-split, bit-identical) measured NEGATIVE everywhere
7834            // (twin warp's duplicated weight stream: ffn_down m5 85.7 vs 56.9).
7835            if rp { if sc_ok { "rpsc" } else { "rpr2w8" } } else { "r2w8" }
7836        } else if mcols >= 4 {
7837            // r2 runs 7 resident blocks/SM (67 regs); its __launch_bounds__(128,8) twin `r2w8`
7838            // (64 regs) runs 8. grid = ceil(out_f/8) for both. rp twins land in the same
7839            // residency classes (rp 44 regs ~ pf-class occupancy, rpr2 67, rpr2w8 64).
7840            let blocks = (out_f + 7) / 8;
7841            let r7 = 7 * sms as usize;
7842            let r8 = 8 * sms as usize;
7843            let waves = blocks as f64 / r7 as f64;
7844            let filled = blocks >= 4 * sms as usize;
7845            // 2026-07-06 m-small latency arc: b4 keeps the wave rule (rpms/rpmsc measured
7846            // flat-to-negative at m=3/4 on every shape — the m-split twin duplicates the weight
7847            // stream; rpsc b4 also negative on r2-class picks, ffn_down m4 51.1 vs 46.5).
7848            if filled && blocks.div_ceil(r8) < blocks.div_ceil(r7) {
7849                // the extra residency drops the INTEGER wave count -> the straggler wave a
7850                // latency-bound kernel pays in full disappears (ffn_down 1.11 -> 0.98 waves:
7851                // 112.5 -> 81.6us, beats pf 90.1; qkv 2.23 -> 1.95: 58.1 -> 51.1).
7852                if rp { "rpr2w8" } else { "r2w8" }
7853            } else if waves >= 2.0 || (waves <= 1.0 && filled) {
7854                // tail amortized (>=2 waves) or single wave: unbounded r2 (no reg-squeeze tax —
7855                // gate/up 81.1 vs 83.9 bounded, attn_q 61.0 vs 63.4).
7856                if rp { "rpr2" } else { "r2" }
7857            } else {
7858                // fractional straggler-wave window with no crossing, or grid too small to fill
7859                // the SMs (tiny out_f<=1024 shapes want max row-parallelism): prefetch variant
7860                // (rp = the r1 split-plane twin — measured the attn_gate winner, 35.4 vs pf 36.4).
7861                if rp { "rp" } else { "pf" }
7862            }
7863        } else if in_f >= 6144 {
7864            // b2 deep-k (2026-07-06): every new twin measured flat-to-negative here (rpms 44.1
7865            // vs rpr2 40.8 ffn_down; rpsc 43.6; the winning rpks is banned on k-order) — rpr2
7866            // stays.
7867            if rp { "rpr2" } else { "r2" }
7868        }
7869        else if rp {
7870            // b2 shallow-k: qkv (out_f=10240, 0.97 waves at 7-resident) is the one measured cell
7871            // where the r2-schedule scale-prestage twin beats the r1 rp pick (24.7 vs 28.9us
7872            // -15%); the wider (ffn_gate 1.65 waves) and smaller (attn_gate 0.58) shapes LOSE
7873            // (41.8 vs 38.2 / 16.6 vs 14.6) — gate on the single-wave window.
7874            let waves = ((out_f + 7) / 8) as f64 / (7 * sms as usize) as f64;
7875            if sc_ok && waves >= 0.9 && waves <= 1.1 { "rpsc" } else { "rp" }
7876        } else { "base" };
7877        variant
7878    }
7879
7880    pub fn qmatvec_mmvq_batched(&self, bytes: &CudaSlice<u8>, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
7881                                m: usize, in_f: usize, out_f: usize, qtype: i32, row_bytes: usize,
7882                                mcols: usize, scale: f32, rp: bool)
7883                                -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7884        const ROWS_PER_BLOCK: u32 = 4;
7885        // TUNE SEAM (H100 lane): MEMRA_BVAR forces the batched-variant pick for the whole
7886        // process — the auto heuristics were tuned on sm_120 (82 SMs / 858 GB/s) and the
7887        // sm_90a re-tune sweeps this seam empirically. Layout variants stay safe: an rp
7888        // weight keeps its rp-layout kernel family regardless of the override.
7889        let forced: Option<&'static str> = {
7890            static V: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
7891            V.get_or_init(|| std::env::var("MEMRA_BVAR").ok())
7892                .as_deref()
7893                .map(|s| Box::leak(s.to_string().into_boxed_str()) as &'static str)
7894        };
7895        let variant = match forced {
7896            Some(v) if !rp || v.contains("rp") => v,
7897            _ => self.batched_variant(m, in_f, out_f, qtype, row_bytes, mcols, rp),
7898        };
7899        let base_name = Self::batched_kernel_name(qtype, mcols)
7900            .ok_or_else(|| format!("qmatvec_mmvq_batched: no kernel for qtype {qtype} mcols {mcols}"))?;
7901        // b16 tier (t=9..16 verify): only base/_rp b16 kernels are compiled — the b2..b8
7902        // per-shape perf variants (r2/pf/...) do not apply at this width. rp is a LAYOUT,
7903        // not a perf variant: it must survive (base kernel on split-plane bytes = NaN).
7904        let variant = if mcols == 16 { if rp { "rp" } else { "base" } } else { variant };
7905        // EXACT-WIDTH b5/b6/b7 twins (lane/vt-fixes fix 1, 2026-08-03): the b8 kernels
7906        // allocate acc[WROWS][8] at ANY m, so T=5..7 verify paid the full 8-wide register
7907        // tax — the measured T=4->5 cliff. The same template at MCOLS=m runs the identical
7908        // per-(token,row) chain (columns c >= m never execute in either form) ->
7909        // BIT-IDENTICAL to the b8 launch. NVFP4 split-plane only (the sm_120 default trunk);
7910        // covers both b8 auto schedules (rpsc, rpr2w8). MEMRA_B567=0 rollback.
7911        static B567: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7912        let b567 = *B567.get_or_init(|| std::env::var("MEMRA_B567").as_deref() != Ok("0"));
7913        if b567 && qtype == QT_NVFP4 && rp && mcols == 8 && (5..=7).contains(&m)
7914            && matches!(variant, "rpsc" | "rpr2w8") {
7915            let f = self.func(&format!("qmatvec_nvfp4_mmvq_b{m}_{variant}"));
7916            let rows_per_block = ROWS_PER_BLOCK * 2; // r2-class schedules: 2 rows/warp
7917            let mut y = self.alloc_uninit::<f32>(m * out_f)?;
7918            let cfg = LaunchConfig {
7919                grid_dim: ((out_f as u32 + rows_per_block - 1) / rows_per_block, 1, 1),
7920                block_dim: (32, ROWS_PER_BLOCK, 1), shared_mem_bytes: 0 };
7921            let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
7922            let __s_b = self.gpu.stream();
7923            let mut b = __s_b.launch_builder(&f);
7924            b.arg(bytes).arg(aq).arg(ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
7925            unsafe { b.launch(cfg)?; }
7926            if scale != 1.0 { self.scale_inplace(&mut y, scale, m * out_f)?; }
7927            return Ok(y);
7928        }
7929        let (name, rows_per_block): (std::borrow::Cow<'static, str>, u32) = match variant {
7930            "base" => (base_name.into(), ROWS_PER_BLOCK),
7931            "pf" => (format!("{base_name}_pf").into(), ROWS_PER_BLOCK),
7932            "ca" => (format!("{base_name}_ca").into(), ROWS_PER_BLOCK),
7933            "rp" => (format!("{base_name}_rp").into(), ROWS_PER_BLOCK),
7934            "rpca" => (format!("{base_name}_rpca").into(), ROWS_PER_BLOCK), // 1 row/warp cp.async
7935            // split families: 2 warp-pairs x 2 rows = 4 rows/block (the k-range or column set
7936            // splits across the pair's two warps; grid.x doubles vs rpr2 at the same regs).
7937            "rpks" => (format!("{base_name}_rpks").into(), ROWS_PER_BLOCK),
7938            "rpksc" => (format!("{base_name}_rpksc").into(), ROWS_PER_BLOCK),
7939            "rpms" => (format!("{base_name}_rpms").into(), ROWS_PER_BLOCK),
7940            "rpmsc" => (format!("{base_name}_rpmsc").into(), ROWS_PER_BLOCK),
7941            "r2ms_rp" => (format!("{base_name}_r2ms_rp").into(), ROWS_PER_BLOCK),
7942            "r2sm_rp" => (format!("{base_name}_r2sm_rp").into(), ROWS_PER_BLOCK * 2),
7943            "r2la_rp" => (format!("{base_name}_r2la_rp").into(), ROWS_PER_BLOCK * 2),
7944            v => (format!("{base_name}_{v}").into(), ROWS_PER_BLOCK * 2), // r2-class: 2 rows/warp
7945        };
7946        debug_assert!(!rp || name.contains("_rp"), "rp weight dispatched to a GGUF-layout kernel");
7947        let f = self.func(&name);
7948        let mut y = self.alloc_uninit::<f32>(m * out_f)?;
7949        // r2sm_rp: [MCOLS][32 blk][8 int] activation slab + [MCOLS][32] f32 scales.
7950        let smem = if name.contains("_r2sm_rp") { (mcols * 32 * 9 * 4 + mcols * 32 * 4) as u32 }
7951                   else { 0 };
7952        let cfg = LaunchConfig {
7953            grid_dim: ((out_f as u32 + rows_per_block - 1) / rows_per_block, 1, 1),
7954            block_dim: (32, ROWS_PER_BLOCK, 1), shared_mem_bytes: smem };
7955        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
7956        let __s_b = self.gpu.stream();
7957        let mut b = __s_b.launch_builder(&f);
7958        b.arg(bytes).arg(aq).arg(ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
7959        unsafe { b.launch(cfg)?; }
7960        if scale != 1.0 { self.scale_inplace(&mut y, scale, m * out_f)?; }
7961        Ok(y)
7962    }
7963
7964    /// BATCHED weight-tile-resident matvec from raw weight bytes (quantizes the f32 activation `x` to
7965    /// q8_1 internally; macro-scale NOT applied — caller compares bare, like qmatvec_*_fast). For the
7966    /// kernel_check bit-equivalence gate. `mcols` ∈ {2,4,8}. Works for Q8_0/Q4_K/Q5_K/Q6_K/NVFP4.
7967    pub fn qmatvec_batched_raw(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize,
7968                               in_f: usize, out_f: usize, qtype: i32, row_bytes: usize, mcols: usize,
7969                               rp: bool)
7970                               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7971        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
7972        self.qmatvec_mmvq_batched(bytes, &aq, &ad, m, in_f, out_f, qtype, row_bytes, mcols, 1.0, rp)
7973    }
7974
7975    /// Back-compat NVFP4-only batched raw launcher (used by older gates). Delegates to the generic one.
7976    pub fn qmatvec_nvfp4_batched_raw(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize,
7977                                     in_f: usize, out_f: usize, row_bytes: usize, mcols: usize,
7978                                     rp: bool)
7979                                     -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7980        self.qmatvec_batched_raw(bytes, x, m, in_f, out_f, QT_NVFP4, row_bytes, mcols, rp)
7981    }
7982
7983    /// Stage-C FP4 gate (MEMRA_FP4): if `w` is an NVFP4 weight with in_f%64==0, run the native mxf4
7984    /// block-scale GEMM and apply the per-tensor macro-scale, returning Some(y). Else None (caller
7985    /// falls through to the int8 GEMM / dp4a). Strict opt-in over the proven int8 path; m>=16 only.
7986    fn try_fp4_gemm(&self, w: &crate::model::GpuTensor, x: &CudaSlice<f32>, m: usize,
7987                    in_f: usize, out_f: usize)
7988                    -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
7989        use crate::model::GpuTensor;
7990        if cfg!(memra_portable_cuda) { return Ok(None); }
7991        if std::env::var("MEMRA_FP4").is_err() { return Ok(None); }
7992        // CUTLASS prefill branch (m>=128 + MEMRA_FP4_CUTLASS + a repacked CutlassWeight present): route
7993        // to the CUTLASS sm120 NVFP4 GEMM, folding the per-tensor macro-scale into the epilogue alpha
7994        // (1/scale) — no post-matmul scale_inplace. Decode (m<128) and the m∈[16,128) middle band keep
7995        // the hand-roll below: CUTLASS's 128-row M-tile wastes work under 128.
7996        // The hand-roll applies the per-tensor macro-scale as a POST-matmul MULTIPLY (scale_inplace(y,
7997        // scale)); CUTLASS's epilogue does D = alpha * (A@B^T), so alpha == scale reproduces it exactly
7998        // (NOT 1/scale — the plan sketch had this inverted; the kernel_check arm gates it). scale==1.0
7999        // for the common no-macro-scale case.
8000        #[cfg(memra_cutlass)]
8001        if m >= 128 && std::env::var("MEMRA_FP4_CUTLASS").is_ok() {
8002            if let GpuTensor::Quant { bytes, qtype, scale, row_bytes, cutlass, .. } = w {
8003                if *qtype == QT_NVFP4 && in_f % 64 == 0 {
8004                    if let Some(cw) = cutlass {
8005                        // Resident fast path: load-time-repacked B + swizzled SFB (no per-call repack).
8006                        let y = self.cutlass_fp4_gemm(&cw.b_packed, &cw.sfb_swizzled, x, *scale,
8007                                                      m, out_f, in_f)?;
8008                        return Ok(Some(y));
8009                    } else if std::env::var("MEMRA_FP4_CUTLASS_OTF").is_ok() {
8010                        // On-the-fly repack (MEMRA_FP4_CUTLASS_OTF): de-interleave + swizzle the B operand
8011                        // from raw bytes per prefill call. No resident doubling of the NVFP4 weight VRAM
8012                        // (the load-time repack ~doubles it) — needed for models that don't fit the
8013                        // resident path (e.g. the 27B on 24GB). Slower (per-call repack) but argmax-exact.
8014                        let (b_packed, sfb_sw) = self.build_cutlass_weight(bytes, out_f, in_f, *row_bytes)?;
8015                        let y = self.cutlass_fp4_gemm(&b_packed, &sfb_sw, x, *scale, m, out_f, in_f)?;
8016                        return Ok(Some(y));
8017                    }
8018                }
8019            }
8020        }
8021        if let GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } = w {
8022            // A6: the hand-rolled W4A4 mxf4 GEMM reads 36B GGUF blocks — no rp port (MEMRA_FP4 is
8023            // an opt-in accuracy tradeoff); repacked tensors fall through to the int8 GEMM.
8024            if *qtype == QT_NVFP4 && in_f % 64 == 0 && !*rp {
8025                let y = self.qmatvec_gemm_nvfp4_fp4(bytes, x, m, in_f, out_f, *row_bytes, *scale)?;
8026                return Ok(Some(y));
8027            }
8028        }
8029        Ok(None)
8030    }
8031
8032    /// rms_norm + fused fp16 twin (task #14): f32 output verbatim `rms_norm` + the fp16
8033    /// copy the f16-mirror GEMM group would otherwise produce with a standalone convert
8034    /// launch. BIT-IDENTICAL end-to-end (same reduction, same __float2half values).
8035    pub fn rms_norm_f16out(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>,
8036                           dst: &mut CudaSlice<f32>, dst16: &mut CudaSlice<u8>,
8037                           ncols: usize, nrows: usize, eps: f32)
8038                           -> Result<(), Box<dyn std::error::Error>> {
8039        let f = self.func("rms_norm_f16out_f32");
8040        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
8041        let (nc, e) = (ncols as i32, eps);
8042        let __s_b = self.gpu.stream();
8043        let mut b = __s_b.launch_builder(&f);
8044        b.arg(x).arg(w).arg(dst).arg(dst16).arg(&nc).arg(&e);
8045        unsafe { b.launch(cfg)?; }
8046        Ok(())
8047    }
8048
8049    /// add+norm(+f16out) fusion for the prefill trunk (round 28; add_rms_norm precedent —
8050    /// bit-identical to add_f32 -> rms_norm_f16out). block_dim matches rms_norm_f16out's.
8051    #[allow(clippy::too_many_arguments)]
8052    pub fn add_rms_norm_f16out(&self, a: &CudaSlice<f32>, b: &CudaSlice<f32>, w: &CudaSlice<f32>,
8053                               res: &mut CudaSlice<f32>, dst: &mut CudaSlice<f32>,
8054                               dst16: &mut CudaSlice<u8>, ncols: usize, nrows: usize, eps: f32)
8055                               -> Result<(), Box<dyn std::error::Error>> {
8056        let f = self.func("add_rms_norm_f16out_f32");
8057        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
8058        let (nc, e) = (ncols as i32, eps);
8059        let __s_lb = self.gpu.stream();
8060        let mut lb = __s_lb.launch_builder(&f);
8061        lb.arg(a).arg(b).arg(w).arg(res).arg(dst).arg(dst16).arg(&nc).arg(&e);
8062        unsafe { lb.launch(cfg)?; }
8063        Ok(())
8064    }
8065
8066    /// matmul_group with a PRE-EMITTED fp16 activation (task #14: the producer norm fused
8067    /// the convert). Mirror-less members fall back to `matmul` on the f32 activation.
8068    pub fn matmul_group_xh(&self, ws: &[&crate::model::GpuTensor], x: &CudaSlice<f32>,
8069                           xh: &CudaSlice<u8>, m: usize)
8070                           -> Result<Vec<CudaSlice<f32>>, Box<dyn std::error::Error>> {
8071        let mut out = Vec::with_capacity(ws.len());
8072        let in_f = ws[0].in_features();
8073        for w in ws {
8074            if w.in_features() == in_f && m >= 16 && !self.verify_exact_on() {
8075                if let Some(y) = self.try_f16_gemm_pre(w, xh, m)? {
8076                    out.push(y);
8077                    continue;
8078                }
8079            }
8080            out.push(self.matmul(w, x, m)?);
8081        }
8082        Ok(out)
8083    }
8084
8085    /// task #14 pad-proofing: zero beta/g_log at rows >= len_d[0] (pads become identity
8086    /// GDN steps). Layouts [T, H].
8087    pub fn gdn_pad_mask(&self, beta: &mut CudaSlice<f32>, g_log: &mut CudaSlice<f32>,
8088                        len_d: &CudaSlice<i32>, h: usize, t: usize)
8089                        -> Result<(), Box<dyn std::error::Error>> {
8090        let f = self.func("gdn_pad_mask_f32");
8091        let cfg = LaunchConfig::for_num_elems((t * h) as u32);
8092        let (hi, ti) = (h as i32, t as i32);
8093        let __s_b = self.gpu.stream();
8094        let mut b = __s_b.launch_builder(&f);
8095        b.arg(beta).arg(g_log).arg(len_d).arg(&hi).arg(&ti);
8096        unsafe { b.launch(cfg)?; }
8097        Ok(())
8098    }
8099
8100    /// task #14 pad-proofing: dst[ncols] = src row (len_d[0]-1) — device-indexed last-row
8101    /// gather for the padded prime graph's h_seed/hlast.
8102    pub fn row_gather_dev(&self, src: &CudaSlice<f32>, dst: &mut CudaSlice<f32>,
8103                          len_d: &CudaSlice<i32>, ncols: usize)
8104                          -> Result<(), Box<dyn std::error::Error>> {
8105        let f = self.func("row_gather_dev_f32");
8106        let cfg = LaunchConfig::for_num_elems(ncols as u32);
8107        let nc = ncols as i32;
8108        let __s_b = self.gpu.stream();
8109        let mut b = __s_b.launch_builder(&f);
8110        b.arg(src).arg(dst).arg(len_d).arg(&nc);
8111        unsafe { b.launch(cfg)?; }
8112        Ok(())
8113    }
8114
8115    /// Grouped matmul: several weights consuming ONE activation (hybrid layers: the GDN
8116    /// 4-tuple wqkv/gate/beta/alpha, attention q/k/v, ffn gate/up). Semantics identical to
8117    /// calling `matmul` per weight; the f16-mirror arm converts the activation ONCE for the
8118    /// whole group instead of once per GEMM (the standalone converts were ~250 launches/prime
8119    /// of small-kernel gap fuel — nsys 2026-07-26). Any member without a mirror (or with a
8120    /// different in_f) falls back to its own `matmul` — behavior unchanged.
8121    pub fn matmul_group(&self, ws: &[&crate::model::GpuTensor], x: &CudaSlice<f32>, m: usize)
8122                        -> Result<Vec<CudaSlice<f32>>, Box<dyn std::error::Error>> {
8123        use crate::model::GpuTensor;
8124        let mut out = Vec::with_capacity(ws.len());
8125        let any_mirror = ws.iter().any(|w| matches!(w, GpuTensor::Quant { f16: Some(_), .. }));
8126        if m >= 16 && any_mirror && !self.verify_exact_on() {
8127            let in_f = ws[0].in_features();
8128            let xh = self.f16_act(x, m * in_f, in_f)?;
8129            for w in ws {
8130                if w.in_features() == in_f {
8131                    if let Some(y) = self.try_f16_gemm_pre(w, &xh, m)? {
8132                        out.push(y);
8133                        continue;
8134                    }
8135                }
8136                out.push(self.matmul(w, x, m)?);
8137            }
8138            return Ok(out);
8139        }
8140        for w in ws {
8141            out.push(self.matmul(w, x, m)?);
8142        }
8143        Ok(out)
8144    }
8145
8146    /// Cross-request grouped matmul (task #13): run ONE projection group over the
8147    /// CONCATENATION of several sequences' activations (m = sum of per-seq rows — the
8148    /// GEMM-batch win vLLM gets from continuous batching), then split each output back
8149    /// into per-seq buffers. Zero view plumbing: gather/scatter are stream-ordered D2D
8150    /// copies (~us at prime sizes). NUMERIC CONFIG NOTE: a GEMM at m=sum tiles K
8151    /// differently than per-seq GEMMs — argmax-gated like every prefill GEMM change.
8152    pub fn matmul_group_multi(&self, ws: &[&crate::model::GpuTensor],
8153                              xs: &[&CudaSlice<f32>], ms: &[usize])
8154                              -> Result<Vec<Vec<CudaSlice<f32>>>, Box<dyn std::error::Error>> {
8155        assert_eq!(xs.len(), ms.len());
8156        let in_f = ws[0].in_features();
8157        let total: usize = ms.iter().sum();
8158        let mut xcat = self.uninit(total * in_f)?;
8159        let mut off = 0usize;
8160        for (x, &m) in xs.iter().zip(ms) {
8161            self.copy_into(&mut xcat, off * in_f, x, m * in_f)?;
8162            off += m;
8163        }
8164        let ys = self.matmul_group(ws, &xcat, total)?;
8165        let mut out: Vec<Vec<CudaSlice<f32>>> = (0..xs.len()).map(|_| Vec::new()).collect();
8166        for (w, y) in ws.iter().zip(ys) {
8167            let out_f = w.out_features();
8168            let mut off = 0usize;
8169            for (s, &m) in ms.iter().enumerate() {
8170                let mut ys_s = self.uninit(m * out_f)?;
8171                let src = y.slice(off * out_f..(off + m) * out_f);
8172                self.gpu.stream().memcpy_dtod(&src, &mut ys_s)?;
8173                out[s].push(ys_s);
8174                off += m;
8175            }
8176        }
8177        Ok(out)
8178    }
8179
8180    /// True if `w`'s qtype has a batched tensor-core GEMM kernel (the prefill T>1 root fix).
8181    /// Only the 4 daily-hot dtypes: Q8_0, Q4_K, Q6_K, NVFP4. NVFP4 needs in_f % 64 == 0.
8182    /// DEFAULT-ON (2026-06-28): measured pp512 9B-NVFP4 = 1413 tok/s WITH this GEMM vs 298 with the
8183    /// dp4a fallback (4.7x) AND MORE accurate (prefill logit maxdiff 0.159 vs dp4a 0.55, both argmax
8184    /// MATCH). The int8 tensor-core GEMM is unconditional (its historical MEMRA_GEMM opt-in gate
8185    /// shipped with Phase 0 — mma + smem swizzle + cp.async — and was removed). Prefill-only
8186    /// (m>=GEMM_M_THRESHOLD); m=1 decode keeps dp4a/MMVQ (this returns true but matmul only calls it
8187    /// at m>=threshold). Portable CUDA targets always use the correctness fallback; on sm_120a,
8188    /// MEMRA_NO_GEMM forces that same dp4a fallback (the bit-reference).
8189    pub fn gemm_supports(&self, w: &crate::model::GpuTensor) -> bool {
8190        use crate::model::GpuTensor;
8191        if !legacy_quant_gemm_allowed(
8192            cfg!(memra_portable_cuda),
8193            cfg!(memra_hopper_mma),
8194            std::env::var_os("MEMRA_NO_GEMM").is_some(),
8195        ) {
8196            return false;
8197        }
8198        match w {
8199            GpuTensor::Quant { qtype, .. } =>
8200                matches!(*qtype, QT_Q8_0 | QT_Q4_K | QT_Q6_K | QT_Q5_K | QT_Q4_0)
8201                || (*qtype == QT_NVFP4 && w.in_features() % 64 == 0),
8202            GpuTensor::Float { .. } | GpuTensor::FloatBf16 { .. } => false,
8203        }
8204    }
8205
8206    /// Batched tensor-core int8 GEMM with a PRE-QUANTIZED q8_1 activation (aq,ad). The prefill
8207    /// (T>1) root fix: decode each weight 32-block to int8 in shared memory ONCE per (row-tile,
8208    /// K-step) and reuse it across all BN tokens via mma.sync.m16n8k32.s8 — amortizing the weight
8209    /// read/decode N-fold (vs the dp4a matvec's per-token re-read). s32 accumulate is exact vs
8210    /// dp4a; only the final f32 block-scale rounding differs. Caller MUST have checked
8211    /// `gemm_supports(w)`. y[m,out] token-major. NVFP4 per-tensor macro-scale applied post.
8212    pub fn qmatvec_gemm(&self, w: &crate::model::GpuTensor, aq: &CudaSlice<i8>, ad: &CudaSlice<f32>,
8213                        m: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8214        use crate::model::GpuTensor;
8215        let in_f = w.in_features();
8216        let out_f = w.out_features();
8217        let (bytes, qtype, row_bytes, scale, rp) = match w {
8218            GpuTensor::Quant { bytes, qtype, row_bytes, scale, rp, .. } => (bytes, *qtype, *row_bytes, *scale, *rp),
8219            _ => unreachable!("gemm_supports guaranteed Quant"),
8220        };
8221        // wgmma arm (sm_90a, task 8): the m64n64k32 warpgroup kernel reads the rp4 split-plane
8222        // mirror AS-IS (qplane rows = its A operand, the half dplane its scales) and the same
8223        // (aq, ad) activation planes. Same numeric class as the mma kernel below (exact s32 per
8224        // 32-block, one f32 scale fold per block, ascending K) — argmax/tolerance gated like
8225        // every prefill GEMM, not bit-gated. MEMRA_WGMMA=0 restores the portable kernel.
8226        if cfg!(memra_hopper_mma) && qtype == QT_Q8_0 && out_f % 64 == 0 && wgmma_gemm_enabled() {
8227            if let GpuTensor::Quant { rp4: Some(m4), .. } = w {
8228                let mut y = self.qmatvec_gemm_q8_0_wgmma_raw(m4, aq, ad, m, in_f, out_f)?;
8229                if scale != 1.0 { self.scale_inplace(&mut y, scale, m * out_f)?; }
8230                return Ok(y);
8231            }
8232        }
8233        let name = match qtype {
8234            QT_Q8_0 => "qmatvec_gemm_q8_0", QT_Q4_K => "qmatvec_gemm_q4_K",
8235            QT_Q4_0 => if rp { "qmatvec_gemm_q4_0_rp" } else { "qmatvec_gemm_q4_0" },
8236            QT_Q5_K => "qmatvec_gemm_q5_K",
8237            QT_Q6_K => "qmatvec_gemm_q6_K",
8238            QT_NVFP4 => if rp { "qmatvec_gemm_nvfp4_rp" } else { "qmatvec_gemm_nvfp4" },
8239            _ => unreachable!(),
8240        };
8241        let f = self.func(name);
8242        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite GEMM output: skip memset
8243        // CTA tile MUST match the .cu per-kernel tile. MMQ-PORT: kernel1 (Q8_0/Q4_K/Q5_K) runs llama's
8244        // 128x128 SQUARE tile (K1_BM=128 x K1_BN=128, 8 warps); kernel2 (Q6_K/NVFP4) keeps 64x256, 4 warps
8245        // (the macro BM/BN in the .cu). Grid dims are selected by qtype so each launches its own tile.
8246        let is_k1 = matches!(qtype, QT_Q8_0 | QT_Q4_K | QT_Q5_K | QT_Q4_0);
8247        // TUNE SEAM: MEMRA_GEMM_K1_LAUNCH overrides kernel1's launch tile to match a -D-swept fatbin.
8248        let k1_tile = if is_k1 { k1_launch_override().unwrap_or((128, 128, 8)) } else { (128, 128, 8) };
8249        let (bm, bn): (u32, u32) = if is_k1 { (k1_tile.0, k1_tile.1) } else { (64, 256) };
8250        let warps: u32 = if is_k1 { k1_tile.2 } else {
8251            match qtype { QT_NVFP4 => 8, _ => 4 }
8252        };
8253        let cfg = LaunchConfig {
8254            grid_dim: ((out_f as u32 + bm - 1) / bm, (m as u32 + bn - 1) / bn, 1),
8255            block_dim: (32, warps, 1),
8256            shared_mem_bytes: 0,
8257        };
8258        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
8259        let __s_b = self.gpu.stream();
8260        let mut b = __s_b.launch_builder(&f);
8261        b.arg(bytes).arg(aq).arg(ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
8262        unsafe { b.launch(cfg)?; }
8263        if scale != 1.0 { self.scale_inplace(&mut y, scale, m * out_f)?; }
8264        Ok(y)
8265    }
8266
8267    /// Test entry: run the GEMM directly from raw weight bytes + qtype (no GpuTensor). Quantizes
8268    /// the f32 activation `x` to q8_1 internally then launches the tensor-core GEMM. NVFP4 per-tensor
8269    /// macro-scale is NOT applied here (caller passes it separately, like the dp4a path). Used by
8270    /// kernel_check for the bit-equivalence gate vs qmatvec_*_dp4a.
8271    pub fn qmatvec_gemm_raw(&self, bytes: &CudaSlice<u8>, x: &CudaSlice<f32>, m: usize, in_f: usize,
8272                            out_f: usize, qtype: i32, row_bytes: usize)
8273                            -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8274        let (aq, ad) = self.quantize_q8_1(x, m, in_f)?;
8275        let name = match qtype {
8276            QT_Q8_0 => "qmatvec_gemm_q8_0", QT_Q4_K => "qmatvec_gemm_q4_K",
8277            QT_Q4_0 => "qmatvec_gemm_q4_0",
8278            QT_Q5_K => "qmatvec_gemm_q5_K",
8279            QT_Q6_K => "qmatvec_gemm_q6_K", QT_NVFP4 => "qmatvec_gemm_nvfp4",
8280            QT_NVFP4_RP => "qmatvec_gemm_nvfp4_rp",
8281            _ => panic!("qmatvec_gemm_raw: qtype {qtype} has no GEMM kernel"),
8282        };
8283        let f = self.func(name);
8284        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite GEMM output: skip memset
8285        // MMQ-PORT: kernel1 (Q8_0/Q4_K/Q5_K) = llama 128x128 tile, 8 warps; kernel2 (Q6_K/NVFP4) = 64x256,
8286        // 4/8 warps. Grid tile per qtype (must match the .cu K1_BM/K1_BN vs BM/BN). KEEP IN SYNC w/ qmatvec_gemm.
8287        let is_k1 = matches!(qtype, QT_Q8_0 | QT_Q4_K | QT_Q5_K | QT_Q4_0);
8288        // TUNE SEAM: MEMRA_GEMM_K1_LAUNCH overrides kernel1's launch tile to match a -D-swept fatbin.
8289        let k1_tile = if is_k1 { k1_launch_override().unwrap_or((128, 128, 8)) } else { (128, 128, 8) };
8290        let (bm, bn): (u32, u32) = if is_k1 { (k1_tile.0, k1_tile.1) } else { (64, 256) };
8291        let warps: u32 = if is_k1 { k1_tile.2 } else {
8292            match qtype { QT_NVFP4 | QT_NVFP4_RP => 8, _ => 4 }
8293        };
8294        let cfg = LaunchConfig {
8295            grid_dim: ((out_f as u32 + bm - 1) / bm, (m as u32 + bn - 1) / bn, 1),
8296            block_dim: (32, warps, 1), shared_mem_bytes: 0,
8297        };
8298        let (inf, outf, mi, rb) = (in_f as i32, out_f as i32, m as i32, row_bytes as i64);
8299        let __s_b = self.gpu.stream();
8300        let mut b = __s_b.launch_builder(&f);
8301        b.arg(bytes).arg(&aq).arg(&ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi).arg(&rb);
8302        unsafe { b.launch(cfg)?; }
8303        Ok(y)
8304    }
8305
8306    /// H100 warpgroup GEMM raw entry (task 8): launch `qmatvec_gemm_q8_0_wgmma` on an rp4
8307    /// split-plane mirror + pre-quantized (aq, ad) activation planes. One warpgroup (128 thr)
8308    /// owns a 64x64 C tile; grid (out_f/64, ceil(m/64)). out_f % 64 == 0 REQUIRED (row loads
8309    /// and dplane scale reads are unguarded); the token edge is guarded in-kernel.
8310    /// Standalone harness verdict (tools/bench_q8_gemm_wgmma.cu, 4096x4096x512): rel 1.6e-05
8311    /// vs CPU ref, 179us vs the portable mma kernel's 688us (3.84x, unpipelined).
8312    pub fn qmatvec_gemm_q8_0_wgmma_raw(&self, rp4: &CudaSlice<u8>, aq: &CudaSlice<i8>,
8313                                       ad: &CudaSlice<f32>, m: usize, in_f: usize, out_f: usize)
8314                                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8315        assert!(out_f % 64 == 0 && in_f % 32 == 0, "wgmma GEMM needs out_f%64==0, in_f%32==0");
8316        let f = self.func("qmatvec_gemm_q8_0_wgmma");
8317        let mut y = self.alloc_uninit::<f32>(m * out_f)?;  // full-overwrite GEMM output
8318        let cfg = LaunchConfig {
8319            grid_dim: ((out_f / 64) as u32, (m as u32).div_ceil(64), 1),
8320            block_dim: (128, 1, 1), shared_mem_bytes: 0,
8321        };
8322        let (inf, outf, mi) = (in_f as i32, out_f as i32, m as i32);
8323        let __s_b = self.gpu.stream();
8324        let mut b = __s_b.launch_builder(&f);
8325        b.arg(rp4).arg(aq).arg(ad).arg(&mut y).arg(&inf).arg(&outf).arg(&mi);
8326        unsafe { b.launch(cfg)?; }
8327        Ok(y)
8328    }
8329
8330    /// y[i] *= s. NVFP4 per-tensor macro-scale broadcast over the whole output.
8331    pub fn scale_inplace(&self, y: &mut CudaSlice<f32>, s: f32, n: usize)
8332                         -> Result<(), Box<dyn std::error::Error>> {
8333        let f = self.func("scale_f32");
8334        let cfg = LaunchConfig::for_num_elems(n as u32);
8335        let (sf, ni) = (s, n as i32);
8336        let __s_b = self.gpu.stream();
8337        let mut b = __s_b.launch_builder(&f);
8338        b.arg(y).arg(&sf).arg(&ni);
8339        unsafe { b.launch(cfg)?; }
8340        Ok(())
8341    }
8342
8343    /// MEMRA_FULL_PREC dequant-on-use: expand a bf16-resident weight (`GpuTensor::FloatBf16`, raw
8344    /// bf16 bytes) to a transient f32 scratch of `n` elements, which then feeds the existing f32
8345    /// cuBLASLt GEMV. The scratch is freed when the caller drops it, so peak VRAM = resident bf16
8346    /// weights + ONE (largest) weight's f32 expansion + activations. SLOW IS FINE (research mode).
8347    pub fn bf16_to_f32(&self, data: &cudarc::driver::CudaView<'_, u8>, n: usize)
8348                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8349        let mut out = self.alloc_uninit::<f32>(n)?;
8350        let f = self.func("bf16_to_f32");
8351        let cfg = LaunchConfig::for_num_elems(n as u32);
8352        let ni = n as i32;
8353        let __s_b = self.gpu.stream();
8354        let mut b = __s_b.launch_builder(&f);
8355        b.arg(data).arg(&mut out).arg(&ni);
8356        unsafe { b.launch(cfg)?; }
8357        Ok(out)
8358    }
8359
8360    /// Chunked bf16 linear (MEMRA_FULL_PREC): y[m,out] = x @ W_bf16^T with the f32 dequant scratch
8361    /// bounded to CHUNK_ROWS rows (256MB at in_f=4096) instead of the whole weight — the 4GB
8362    /// lm_head expansion OOM'd the 24GB budget. Row-chunking partitions OUTPUT rows; each row's
8363    /// dot is computed by the identical kernel on identical bytes, so per-(token,row) results are
8364    /// bit-identical to the unchunked form. `exact` selects linear_decode_exact (per-column m=1
8365    /// calls, the spec-verify contract) vs plain linear.
8366    fn linear_bf16_chunked(&self, x: &CudaSlice<f32>, data: &CudaSlice<u8>, m: usize,
8367                           in_f: usize, out_f: usize, exact: bool)
8368                           -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8369        const CHUNK_BYTES: usize = 256 << 20;
8370        let chunk_rows = (CHUNK_BYTES / (in_f * 4)).max(1).min(out_f);
8371        if chunk_rows >= out_f {
8372            let wf32 = self.bf16_to_f32(&data.slice(0..in_f * out_f * 2), in_f * out_f)?;
8373            return if exact { self.linear_decode_exact(x, &wf32, m, in_f, out_f) }
8374                   else { self.linear(x, &wf32, m, in_f, out_f) };
8375        }
8376        let mut y = self.alloc_uninit::<f32>(m * out_f)?;
8377        let mut r0 = 0usize;
8378        while r0 < out_f {
8379            let rows = chunk_rows.min(out_f - r0);
8380            let wslice = data.slice(r0 * in_f * 2..(r0 + rows) * in_f * 2);
8381            let wf32 = self.bf16_to_f32(&wslice, in_f * rows)?;
8382            let yc = if exact { self.linear_decode_exact(x, &wf32, m, in_f, rows)? }
8383                     else { self.linear(x, &wf32, m, in_f, rows)? };
8384            // scatter [m, rows] into y[m, out_f] at column offset r0 (m is tiny in decode/verify)
8385            for mi in 0..m {
8386                let src = yc.slice(mi * rows..(mi + 1) * rows);
8387                let mut dst = y.slice_mut(mi * out_f + r0..mi * out_f + r0 + rows);
8388                self.gpu.stream().memcpy_dtod(&src, &mut dst)?;
8389            }
8390            r0 += rows;
8391        }
8392        Ok(y)
8393    }
8394
8395    /// On-device linear: y[m,out] = x[m,in] @ W[out,in]^T, weights row-major [out,in] (ggml).
8396    /// cuBLASLt col-major mapping (see memra_runtime::Gpu::linear_f32 for the derivation).
8397    /// DECODE-EXACT float linear: per-column m=1 cuBLASLt calls. cuBLASLt's reduction split is
8398    /// n-dependent (lt_ndep probe: m=1 vs m=2 col0 differs every bit), so spec-verify batches
8399    /// must not batch float matmuls the T=1 decode chain runs at m=1. Used by the small-t MoE
8400    /// router/shexp sites and matmul_decode_exact's Float arm.
8401    pub fn linear_decode_exact(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, m_tokens: usize,
8402                               in_f: usize, out_f: usize)
8403                               -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8404        if m_tokens == 1 { return self.linear(x, w, 1, in_f, out_f); }
8405        let xv = self.view(x, m_tokens * in_f);
8406        let mut y = self.alloc_uninit::<f32>(m_tokens * out_f)?;
8407        for t in 0..m_tokens {
8408            let row = xv.slice(t * in_f..(t + 1) * in_f);
8409            let mut xr = self.alloc_uninit::<f32>(in_f)?;
8410            self.copy_view_into(&mut xr, 0, &row, in_f)?;
8411            let yr = self.linear(&xr, w, 1, in_f, out_f)?;
8412            self.copy_into(&mut y, t * out_f, &yr, out_f)?;
8413        }
8414        Ok(y)
8415    }
8416
8417    pub fn linear(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, m_tokens: usize, in_f: usize, out_f: usize)
8418                  -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8419        use cudarc::cublaslt::{Matmul, MatmulConfig};
8420        let mut c = self.alloc_uninit::<f32>(m_tokens * out_f)?;  // cuBLASLt beta=0: C fully written
8421        let cfg = MatmulConfig {
8422            transa: true, transb: false, transc: false,
8423            m: out_f as u64, n: m_tokens as u64, k: in_f as u64,
8424            alpha: 1.0, lda: in_f as i64, ldb: in_f as i64, beta: 0.0, ldc: out_f as i64,
8425            stride_a: None, stride_b: None, stride_c: None, stride_bias: None, batch_size: None,
8426        };
8427        unsafe { self.gpu.blas.matmul(cfg, w, x, &mut c, None, None)?; }
8428        Ok(c)
8429    }
8430
8431    /// Naive SDPA. Q:[head_dim,n_head,T], K/V:[head_dim,n_head_kv,T_kv] -> O:[head_dim,n_head,T].
8432    pub fn sdpa_naive(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
8433                      o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize, n_head_kv: usize,
8434                      t: usize, t_kv: usize, scale: f32, causal: bool)
8435                      -> Result<(), Box<dyn std::error::Error>> {
8436        let f = self.func("sdpa_naive_f32");
8437        let cfg = LaunchConfig {
8438            grid_dim: (n_head as u32, t as u32, 1),
8439            block_dim: (128, 1, 1),
8440            shared_mem_bytes: (t_kv * 4) as u32,
8441        };
8442        let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32, t as i32, t_kv as i32, causal as i32);
8443        let __s_b = self.gpu.stream();
8444        let mut b = __s_b.launch_builder(&f);
8445        b.arg(q).arg(k).arg(v).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi).arg(&scale).arg(&cz);
8446        unsafe { b.launch(cfg)?; }
8447        Ok(())
8448    }
8449
8450    /// Windowed sdpa_naive twin (gemma4 R6): masks keys older than q_pos-(window-1).
8451    #[allow(clippy::too_many_arguments)]
8452    pub fn sdpa_naive_w(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
8453                        o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize, n_head_kv: usize,
8454                        t: usize, t_kv: usize, scale: f32, causal: bool, window: usize)
8455                        -> Result<(), Box<dyn std::error::Error>> {
8456        let f = self.func("sdpa_naive_w_f32");
8457        let cfg = LaunchConfig {
8458            grid_dim: (n_head as u32, t as u32, 1),
8459            block_dim: (128, 1, 1),
8460            shared_mem_bytes: (t_kv * 4) as u32,
8461        };
8462        let (hd, nh, nhkv, ti, tkvi, cz, wi) = (head_dim as i32, n_head as i32, n_head_kv as i32,
8463                                                t as i32, t_kv as i32, causal as i32, window as i32);
8464        let __s_b = self.gpu.stream();
8465        let mut b = __s_b.launch_builder(&f);
8466        b.arg(q).arg(k).arg(v).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8467         .arg(&scale).arg(&cz).arg(&wi);
8468        unsafe { b.launch(cfg)?; }
8469        Ok(())
8470    }
8471
8472    /// SDPA where K/V are CudaViews into a resident KV cache (decode hot path, no host round-trip).
8473    pub fn sdpa_naive_view(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<f32>,
8474                           v: &cudarc::driver::CudaView<f32>, o: &mut CudaSlice<f32>,
8475                           head_dim: usize, n_head: usize, n_head_kv: usize, t: usize, t_kv: usize,
8476                           scale: f32, causal: bool) -> Result<(), Box<dyn std::error::Error>> {
8477        let f = self.func("sdpa_naive_f32");
8478        let cfg = LaunchConfig {
8479            grid_dim: (n_head as u32, t as u32, 1), block_dim: (128, 1, 1),
8480            shared_mem_bytes: (t_kv * 4) as u32,
8481        };
8482        let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32, t as i32, t_kv as i32, causal as i32);
8483        let __s_b = self.gpu.stream();
8484        let mut b = __s_b.launch_builder(&f);
8485        b.arg(q).arg(k).arg(v).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi).arg(&scale).arg(&cz);
8486        unsafe { b.launch(cfg)?; }
8487        Ok(())
8488    }
8489
8490    /// Correctness fallback for quantized resident K/V views. Dequantizes K and V once into f32
8491    /// workspaces, then calls `sdpa_naive`. This is an explicit API: the optimized prefill view
8492    /// dispatch remains unchanged, so callers can use it as a reference or compatibility path.
8493    /// Dequant a quantized KV view into caller-owned f32 buffers (one grid-stride launch).
8494    /// `g` picks the kf8vf8-module stamp for e4m3 caches (same flag contract as fa_decode/
8495    /// fa_prefill_view). Used by the E4B shared-KV prefill arms (2026-07-31) to feed the
8496    /// f32 fa_prefill_w / fa_prefill_hd512 twins from the target layer's quantized rows.
8497    #[allow(clippy::too_many_arguments)]
8498    pub fn fa_dequant_kv_view_f32(&self, k: &cudarc::driver::CudaView<u8>,
8499                                  v: &cudarc::driver::CudaView<u8>,
8500                                  kf: &mut CudaSlice<f32>, vf: &mut CudaSlice<f32>,
8501                                  kv_dim_k: usize, kv_dim_v: usize, t_kv: usize,
8502                                  k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
8503                                  -> Result<(), Box<dyn std::error::Error>> {
8504        let f = if g { self.func_g("fa_dequant_kv_ws_f32") } else { self.func("fa_dequant_kv_ws_f32") };
8505        let total = (t_kv * (kv_dim_k + kv_dim_v)) as u64;
8506        let nblk = ((total + 255) / 256).min(65535 * 16) as u32;
8507        let cfg = LaunchConfig { grid_dim: (nblk.max(1), 1, 1), block_dim: (256, 1, 1),
8508                                 shared_mem_bytes: 0 };
8509        let (kdk, kdv, tkvi) = (kv_dim_k as i32, kv_dim_v as i32, t_kv as i32);
8510        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
8511        let __s_b = self.gpu.stream();
8512        let mut b = __s_b.launch_builder(&f);
8513        b.arg(k).arg(v).arg(&mut *kf).arg(&mut *vf).arg(&kdk).arg(&kdv).arg(&tkvi).arg(&ktb).arg(&vtb);
8514        unsafe { b.launch(cfg)?; }
8515        Ok(())
8516    }
8517
8518    #[allow(clippy::too_many_arguments)]
8519    pub fn sdpa_naive_quantized_view(
8520        &self,
8521        q: &CudaSlice<f32>,
8522        k: &cudarc::driver::CudaView<u8>,
8523        v: &cudarc::driver::CudaView<u8>,
8524        o: &mut CudaSlice<f32>,
8525        head_dim: usize,
8526        n_head: usize,
8527        n_head_kv: usize,
8528        t: usize,
8529        t_kv: usize,
8530        scale: f32,
8531        causal: bool,
8532        k_tok_bytes: usize,
8533        v_tok_bytes: usize,
8534    ) -> Result<(), Box<dyn std::error::Error>> {
8535        let kv_dim = n_head_kv * head_dim;
8536        let mut kf = self.uninit(t_kv * kv_dim)?;
8537        let mut vf = self.uninit(t_kv * kv_dim)?;
8538        let f = self.func("fa_dequant_kv_ws_f32");
8539        let total = (2 * t_kv * kv_dim) as u64;
8540        let nblk = ((total + 255) / 256).min(65535 * 16) as u32;
8541        let cfg = LaunchConfig {
8542            grid_dim: (nblk.max(1), 1, 1),
8543            block_dim: (256, 1, 1),
8544            shared_mem_bytes: 0,
8545        };
8546        let (kv_dim_i, t_kv_i) = (kv_dim as i32, t_kv as i32);
8547        let (k_tok_bytes_i, v_tok_bytes_i) = (k_tok_bytes as i64, v_tok_bytes as i64);
8548        let __s_b = self.gpu.stream();
8549        let mut b = __s_b.launch_builder(&f);
8550        b.arg(k)
8551            .arg(v)
8552            .arg(&mut kf)
8553            .arg(&mut vf)
8554            .arg(&kv_dim_i)
8555            .arg(&kv_dim_i)
8556            .arg(&t_kv_i)
8557            .arg(&k_tok_bytes_i)
8558            .arg(&v_tok_bytes_i);
8559        unsafe { b.launch(cfg)? };
8560        self.sdpa_naive(
8561            q, &kf, &vf, o, head_dim, n_head, n_head_kv, t, t_kv, scale, causal,
8562        )
8563    }
8564
8565    /// WINDOWED twin of `sdpa_naive_quantized_view` (step35 SWA prefill): dequant the KV byte
8566    /// view into f32 workspaces with the SAME `fa_dequant_kv_ws_f32` launch, then run
8567    /// `sdpa_naive_w` instead of `sdpa_naive`. `window == 0` is the unwindowed form (the kernel
8568    /// treats a non-positive window as "no window mask"), so this is a strict superset of the
8569    /// unwindowed function above and produces bit-identical output at window == 0.
8570    ///
8571    /// Why this exists: EVERY windowed FlashAttention stamp in flash_attn.cu is head_dim-256
8572    /// only (`fa_prefill_w_f32` == `fa_prefill_f32_body<256>`, and the quantized-view windowed
8573    /// twins likewise), while step35 is head_dim 128. Its SWA layers therefore have no windowed
8574    /// FA path and take this f32 floor in v0 — same cache bytes, same numeric class as the
8575    /// unwindowed quantized-view fallback, so the chunk-invariance contract holds on both.
8576    #[allow(clippy::too_many_arguments)]
8577    pub fn sdpa_naive_w_quantized_view(
8578        &self,
8579        q: &CudaSlice<f32>,
8580        k: &cudarc::driver::CudaView<u8>,
8581        v: &cudarc::driver::CudaView<u8>,
8582        o: &mut CudaSlice<f32>,
8583        head_dim: usize,
8584        n_head: usize,
8585        n_head_kv: usize,
8586        t: usize,
8587        t_kv: usize,
8588        scale: f32,
8589        causal: bool,
8590        window: usize,
8591        k_tok_bytes: usize,
8592        v_tok_bytes: usize,
8593    ) -> Result<(), Box<dyn std::error::Error>> {
8594        let kv_dim = n_head_kv * head_dim;
8595        let mut kf = self.uninit(t_kv * kv_dim)?;
8596        let mut vf = self.uninit(t_kv * kv_dim)?;
8597        let f = self.func("fa_dequant_kv_ws_f32");
8598        let total = (2 * t_kv * kv_dim) as u64;
8599        let nblk = ((total + 255) / 256).min(65535 * 16) as u32;
8600        let cfg = LaunchConfig {
8601            grid_dim: (nblk.max(1), 1, 1),
8602            block_dim: (256, 1, 1),
8603            shared_mem_bytes: 0,
8604        };
8605        let (kv_dim_i, t_kv_i) = (kv_dim as i32, t_kv as i32);
8606        let (k_tok_bytes_i, v_tok_bytes_i) = (k_tok_bytes as i64, v_tok_bytes as i64);
8607        let __s_b = self.gpu.stream();
8608        let mut b = __s_b.launch_builder(&f);
8609        b.arg(k)
8610            .arg(v)
8611            .arg(&mut kf)
8612            .arg(&mut vf)
8613            .arg(&kv_dim_i)
8614            .arg(&kv_dim_i)
8615            .arg(&t_kv_i)
8616            .arg(&k_tok_bytes_i)
8617            .arg(&v_tok_bytes_i);
8618        unsafe { b.launch(cfg)? };
8619        self.sdpa_naive_w(
8620            q, &kf, &vf, o, head_dim, n_head, n_head_kv, t, t_kv, scale, causal, window,
8621        )
8622    }
8623
8624    /// Hand-written FlashAttention prefill (sm_120, FA-2 online softmax on validated mma.sync,
8625    /// head_dim 256 or 128 (template-stamped twins), GQA, causal). Replaces sdpa_naive for T>1.
8626    /// Q/K/V/O [head_dim, n_head(_kv), T].
8627    pub fn fa_prefill(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
8628                      o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize, n_head_kv: usize,
8629                      t: usize, t_kv: usize, scale: f32, causal: bool)
8630                      -> Result<(), Box<dyn std::error::Error>> {
8631        if portable_mma_gated() {
8632            return self.sdpa_naive(q, k, v, o, head_dim, n_head, n_head_kv,
8633                                   t, t_kv, scale, causal);
8634        }
8635        // FA3 v10 arm (task #20, OPT-IN MEMRA_FA3=1 — harness-proven 883us vs the shipped
8636        // kernel's 993us at T=2048): TMA-swizzled wgmma FA, fresh causal hd256 only.
8637        // NEW NUMERIC CONFIG (GDN-mma precedent): online softmax / bf16-P class — the
8638        // run-gen argmax + greedy-stream batteries arbitrate; not bit-paired.
8639        // PROMOTED default-ON hopper (2026-07-27): 3-seed 2048-prime -> 128-decode
8640        // streams MATCH vs mma, full battery green, lane interleaved 5/5 (+2.4%).
8641        // MEMRA_FA3=0 reverts; kernel-check pins the mma config regardless.
8642        let fa3_on = head_dim == 256 && causal && t == t_kv
8643            && match std::env::var("MEMRA_FA3").as_deref() {
8644                Ok("0") => false,
8645                Ok("1") => true,
8646                _ => cfg!(memra_hopper_mma),
8647            };
8648        if fa3_on {
8649            let n = t * n_head * head_dim;
8650            let nkv = t * n_head_kv * head_dim;
8651            let mut q16 = self.alloc_u8_uninit(n * 2)?;
8652            let mut k16 = self.alloc_u8_uninit(nkv * 2)?;
8653            let mut v16 = self.alloc_u8_uninit(nkv * 2)?;
8654            self.f32_to_bf16_into(q, &mut q16, n)?;
8655            self.f32_to_bf16_into(k, &mut k16, nkv)?;
8656            self.f32_to_bf16_into(v, &mut v16, nkv)?;
8657            let rc = {
8658                use cudarc::driver::{DevicePtr, DevicePtrMut};
8659                let stream = self.gpu.stream();
8660                let (qp, _g1) = q16.device_ptr(&stream);
8661                let (kp, _g2) = k16.device_ptr(&stream);
8662                let (vp, _g3) = v16.device_ptr(&stream);
8663                let (op, _g4) = o.device_ptr_mut(&stream);
8664                unsafe {
8665                    memra_fa3_prefill(qp as *const core::ffi::c_void,
8666                                     kp as *const core::ffi::c_void,
8667                                     vp as *const core::ffi::c_void,
8668                                     op as *mut f32,
8669                                     t as i32, n_head as i32, n_head_kv as i32,
8670                                     head_dim as i32, scale,
8671                                     stream.cu_stream() as *mut core::ffi::c_void)
8672                }
8673            };
8674            if rc != 0 {
8675                return Err(format!("memra_fa3_prefill rc={rc}").into());
8676            }
8677            return Ok(());
8678        }
8679        // FLOOR PORT (P2+P0a+P0b+P1): 4 warps/CTA, BLOCK_Q=64 query rows, BK=32 KV tile,
8680        // Q-in-reg + register-O, grid.y=n_head_kv (4 Q-heads share staged K/V).
8681        // P1 plain arm (MEMRA_FA_P1=1 opt-in until the qwen battery): the engine-study body
8682        // (FA2 schedule + boundary split + swizzle) on the non-windowed lane. bf16 pre-convert.
8683        static FA_P1: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8684        let fa_p1 = *FA_P1.get_or_init(|| std::env::var("MEMRA_FA_P1").as_deref() == Ok("1"));
8685        if fa_p1 && head_dim == 256 && !std::env::var("MEMRA_FA_FLOOR").is_ok() {
8686            const BLOCK_Q: usize = 64; const BKX: usize = 32;
8687            let f = self.func("fa_prefill_bf16_p1");
8688            let shmem = (2 * (2 * BKX * head_dim + BLOCK_Q * BKX)
8689                       + 4 * (BLOCK_Q * BKX + 2 * BLOCK_Q)) as u32;
8690            use cudarc::driver::sys::CUfunction_attribute_enum as A;
8691            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8692            let cfg = LaunchConfig {
8693                grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 1),
8694                block_dim: (32, 4, 1), shared_mem_bytes: shmem,
8695            };
8696            let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32,
8697                n_head_kv as i32, t as i32, t_kv as i32, causal as i32);
8698            let qb = self.f32_to_bf16(q, t * n_head * head_dim)?;
8699            let kb = self.f32_to_bf16(k, t_kv * n_head_kv * head_dim)?;
8700            let vb = self.f32_to_bf16(v, t_kv * n_head_kv * head_dim)?;
8701            let __s_b = self.gpu.stream();
8702            let mut b = __s_b.launch_builder(&f);
8703            b.arg(&qb).arg(&kb).arg(&vb).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti)
8704             .arg(&tkvi).arg(&scale).arg(&cz);
8705            unsafe { b.launch(cfg)?; }
8706            return Ok(());
8707        }
8708        // Edge 5a (DEFAULT): fa_prefill_f32_pp — register-resident softmax (no sSw smem
8709        // round-trip), the FA3 softmax-GEMM overlap variant. ncu (pp512): short_scoreboard
8710        // 4.32->3.47, wait 1.99->1.45, per-call ~577us->~440us (1.31x) at flat 12.1% warps /
8711        // 255 regs / 2 CTAs (occupancy preserved). Bit-safe: 9B+27B argmax MATCH, rel 2.55e-3
8712        // vs floor 3.03e-3. MEMRA_FA_FLOOR reverts to the serialized-softmax floor kernel.
8713        const BK: usize = 32;
8714        // W2 lane (MEMRA_FA_PP_W2=1, ncu 2026-07-26): 2-warp/32-row CTA tile doubles grid.x —
8715        // bit-identical per-row math, pure coverage trade for the 6.25%-occupancy starvation.
8716        let w2 = std::env::var("MEMRA_FA_PP_W2").as_deref() == Ok("1");
8717        let (block_q, warps, w2_sfx): (usize, u32, &str) =
8718            if w2 { (32, 2, "_w2") } else { (64, 4, "") };
8719        // hd128 twins (2026-07-07): the prefill kernels are template-stamped at 256 (original
8720        // names, dispatch unchanged) and 128 (`_hd128`, the MiniMax-M3 class). Callers gate
8721        // other head_dims to sdpa_naive before reaching here.
8722        let hd_sfx = fa_hd_suffix(head_dim)?;
8723        let floor = std::env::var("MEMRA_FA_FLOOR").is_ok();
8724        // BF16-KV staging lane (2026-07-26, default ON): the kernel converts K/V to bf16
8725        // during staging anyway — pre-converting to bf16 mirrors is BIT-IDENTICAL (same
8726        // __float2bfloat16 values into the same mma) and turns the 67%-of-stalls scalar
8727        // staging into int4 vector copies. MEMRA_FA_BF16KV=0 reverts.
8728        let bf16kv = !floor && !w2
8729            && std::env::var("MEMRA_FA_BF16KV").as_deref() != Ok("0");
8730        let (kb16, vb16) = if bf16kv {
8731            let n = t_kv * n_head_kv * head_dim;
8732            let mut kb = self.alloc_u8_uninit(n * 2)?;
8733            let mut vb = self.alloc_u8_uninit(n * 2)?;
8734            let fcv = self.func("f32_to_bf16_bulk");
8735            let ni = n as i64;
8736            let cfgc = LaunchConfig::for_num_elems((n as u32).div_ceil(4));
8737            let __s_b = self.gpu.stream();
8738            let mut b = __s_b.launch_builder(&fcv);
8739            b.arg(k).arg(&mut kb).arg(&ni);
8740            unsafe { b.launch(cfgc)?; }
8741            let __s_b = self.gpu.stream();
8742            let mut b = __s_b.launch_builder(&fcv);
8743            b.arg(v).arg(&mut vb).arg(&ni);
8744            unsafe { b.launch(cfgc)?; }
8745            (Some(kb), Some(vb))
8746        } else {
8747            (None, None)
8748        };
8749        let f = self.func(&if bf16kv {
8750            format!("fa_prefill_bf16kv_pp{hd_sfx}")
8751        } else {
8752            format!("fa_prefill_f32{}{}{hd_sfx}",
8753                    if floor { "" } else { "_pp" },
8754                    if floor { "" } else { w2_sfx })
8755        });
8756        // persistent smem: bf16*(KV_STAGES*(sK + sV) + sP) + f32*(sS + sM + sL);
8757        // the bf16kv ring doubles the K/V stages (KV_STAGES=2).
8758        let kv_stages = if bf16kv { 2 } else { 1 };
8759        let shmem = (2 * (kv_stages * 2 * BK * head_dim + block_q * BK)
8760                   + 4 * (block_q * BK + 2 * block_q)) as u32;
8761        use cudarc::driver::sys::CUfunction_attribute_enum as A;
8762        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8763        let cfg = LaunchConfig {
8764            grid_dim: ((t as u32 + block_q as u32 - 1) / block_q as u32, n_head as u32, 1),
8765            block_dim: (32, warps, 1), shared_mem_bytes: shmem,
8766        };
8767        let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32, t as i32, t_kv as i32, causal as i32);
8768        let __s_b = self.gpu.stream();
8769        let mut b = __s_b.launch_builder(&f);
8770        b.arg(q);
8771        match (&kb16, &vb16) {
8772            (Some(kb), Some(vb)) => { b.arg(kb).arg(vb); }
8773            _ => { b.arg(k).arg(v); }
8774        }
8775        b.arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi).arg(&scale).arg(&cz);
8776        unsafe { b.launch(cfg)?; }
8777        Ok(())
8778    }
8779
8780    /// Windowed FA prefill (gemma4 SWA layers past the sliding window, hd256): fa_prefill's
8781    /// exact dispatch (pp default, MEMRA_FA_FLOOR seam) with the sliding-window mask + tile
8782    /// skip in-kernel. Replaces the O(T*T_kv) scalar sdpa_naive_w on the prime path.
8783    #[allow(clippy::too_many_arguments)]
8784    pub fn fa_prefill_w(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
8785                        o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize, n_head_kv: usize,
8786                        t: usize, t_kv: usize, scale: f32, causal: bool, window: usize)
8787                        -> Result<(), Box<dyn std::error::Error>> {
8788        // sm_90a rides the mma twins (portable_mma_gated, 2026-07-31 — the raw
8789        // portable_cuda gate was stale-conservative on Hopper; fa_prefill already flipped).
8790        if portable_mma_gated() {
8791            return self.sdpa_naive_w(q, k, v, o, head_dim, n_head, n_head_kv,
8792                                     t, t_kv, scale, causal, window);
8793        }
8794        // Default: bf16-prestaged twin (same treatment as hd512 — Q/K/V pre-converted once,
8795        // int4 stage copies; bit-identical, kernel_check-gated). MEMRA_FAW_STAGE=f32 reverts;
8796        // MEMRA_FA_FLOOR keeps the f32 floor stamp untouched.
8797        static FAW_F32: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8798        let faw_f32 = *FAW_F32.get_or_init(|| {
8799            std::env::var("MEMRA_FAW_STAGE").as_deref() == Ok("f32")
8800        });
8801        let floor = std::env::var("MEMRA_FA_FLOOR").is_ok();
8802        self.fa_prefill_w_arm(q, k, v, o, head_dim, n_head, n_head_kv, t, t_kv, scale, causal,
8803                              window, floor || faw_f32, floor)
8804    }
8805
8806    /// Windowed FA prefill with PRE-CONVERTED bf16 operands (producer-emitted; 31B glue lane).
8807    /// Launches the P1 stamp directly — callers guarantee qb/kb/vb hold the exact bf16 of q/k/v.
8808    #[allow(clippy::too_many_arguments)]
8809    pub fn fa_prefill_w_pre(&self, qb: &CudaSlice<u8>, kb: &CudaSlice<u8>, vb: &CudaSlice<u8>,
8810                            o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize,
8811                            n_head_kv: usize, t: usize, t_kv: usize, scale: f32, causal: bool,
8812                            window: usize, v_f16: bool)
8813                            -> Result<(), Box<dyn std::error::Error>> {
8814        const BLOCK_Q: usize = 64; const BK: usize = 32;
8815        debug_assert_eq!(head_dim, 256);
8816        let hp = fa_f16pv_on() && faw_hp_on() && n_head % 2 == 0
8817            && (n_head / n_head_kv) % 2 == 0;
8818        debug_assert!(!v_f16 || hp, "f16 V emitted but the SWA hp arm is off");
8819        if hp {
8820            const BLOCK_QH: usize = 32;
8821            // V bytes must be f16 for the h2 stamp; producer normally emits f16 (v_f16),
8822            // else re-encode through the pooled scratch (stream-ordered reuse).
8823            let mut vguard = self.fa_vf16_scratch.lock().unwrap();
8824            let vh: &CudaSlice<u8> = if v_f16 { vb } else {
8825                let n = t_kv * n_head_kv * head_dim;
8826                if vguard.as_ref().map(|b| b.len() < n * 2).unwrap_or(true) {
8827                    *vguard = Some(self.alloc_uninit::<u8>(n * 2)?);
8828                }
8829                self.bf16_to_f16_into(vb, n, vguard.as_mut().unwrap())?;
8830                vguard.as_ref().unwrap()
8831            };
8832            let f = self.func("fa_prefill_w_bf16_p1h2");
8833            let shmem = (2 * (2 * BK * head_dim + 2 * BLOCK_QH * BK)
8834                       + 4 * (2 * BLOCK_QH)) as u32;
8835            use cudarc::driver::sys::CUfunction_attribute_enum as A;
8836            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8837            let cfg = LaunchConfig {
8838                grid_dim: ((t as u32).div_ceil(BLOCK_QH as u32), (n_head / 2) as u32, 1),
8839                block_dim: (32, 4, 1), shared_mem_bytes: shmem,
8840            };
8841            let (hd, nh, nhkv, ti, tkvi, cz, wi) = (head_dim as i32, n_head as i32,
8842                n_head_kv as i32, t as i32, t_kv as i32, causal as i32, window as i32);
8843            let __s_b = self.gpu.stream();
8844            let mut b = __s_b.launch_builder(&f);
8845            b.arg(qb).arg(kb).arg(vh).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8846             .arg(&scale).arg(&cz).arg(&wi);
8847            unsafe { b.launch(cfg)?; }
8848            return Ok(());
8849        }
8850        let f = self.func("fa_prefill_w_bf16_p1");
8851        let shmem = (2 * (2 * BK * head_dim + BLOCK_Q * BK)
8852                   + 4 * (BLOCK_Q * BK + 2 * BLOCK_Q)) as u32;
8853        use cudarc::driver::sys::CUfunction_attribute_enum as A;
8854        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8855        let cfg = LaunchConfig {
8856            grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 1),
8857            block_dim: (32, 4, 1), shared_mem_bytes: shmem,
8858        };
8859        let (hd, nh, nhkv, ti, tkvi, cz, wi) = (head_dim as i32, n_head as i32,
8860            n_head_kv as i32, t as i32, t_kv as i32, causal as i32, window as i32);
8861        let __s_b = self.gpu.stream();
8862        let mut b = __s_b.launch_builder(&f);
8863        b.arg(qb).arg(kb).arg(vb).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8864         .arg(&scale).arg(&cz).arg(&wi);
8865        unsafe { b.launch(cfg)?; }
8866        Ok(())
8867    }
8868
8869    /// Windowed FA prefill with the stage arm FORCED — the kernel_check bit-identity entry.
8870    #[allow(clippy::too_many_arguments)]
8871    pub fn fa_prefill_w_arm(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
8872                            o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize,
8873                            n_head_kv: usize, t: usize, t_kv: usize, scale: f32, causal: bool,
8874                            window: usize, f32_stage: bool, floor: bool)
8875                            -> Result<(), Box<dyn std::error::Error>> {
8876        const BLOCK_Q: usize = 64; const BK: usize = 32;
8877        debug_assert_eq!(head_dim, 256, "fa_prefill_w is stamped hd256 only");
8878        // P1 (2026-07-22 engine study): per-head Br=64 stamp with the FA2 schedule (V-copy
8879        // over GEMM0, next-K over softmax+GEMM1) + boundary/interior mask split. FP order
8880        // preserved -> bit-identical (gated). MEMRA_FAW_P1=0 reverts to the g4/o2 arms.
8881        static P1_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8882        let p1 = !floor && !f32_stage
8883            && *P1_ON.get_or_init(|| {
8884                std::env::var("MEMRA_FAW_P1").map(|v| v != "0").unwrap_or(true)
8885            });
8886        let hp = p1 && fa_f16pv_on() && faw_hp_on() && n_head % 2 == 0
8887            && (n_head / n_head_kv) % 2 == 0;
8888        if hp {
8889            const BLOCK_QH: usize = 32;
8890            let f = self.func("fa_prefill_w_bf16_p1h2");
8891            let shmem = (2 * (2 * BK * head_dim + 2 * BLOCK_QH * BK)
8892                       + 4 * (2 * BLOCK_QH)) as u32;
8893            use cudarc::driver::sys::CUfunction_attribute_enum as A;
8894            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8895            let cfg = LaunchConfig {
8896                grid_dim: ((t as u32).div_ceil(BLOCK_QH as u32), (n_head / 2) as u32, 1),
8897                block_dim: (32, 4, 1), shared_mem_bytes: shmem,
8898            };
8899            let (hd, nh, nhkv, ti, tkvi, cz, wi) = (head_dim as i32, n_head as i32,
8900                n_head_kv as i32, t as i32, t_kv as i32, causal as i32, window as i32);
8901            let qb = self.f32_to_bf16(q, t * n_head * head_dim)?;
8902            let kb = self.f32_to_bf16(k, t_kv * n_head_kv * head_dim)?;
8903            let vh = self.f32_to_f16(v, t_kv * n_head_kv * head_dim)?;
8904            let __s_b = self.gpu.stream();
8905            let mut b = __s_b.launch_builder(&f);
8906            b.arg(&qb).arg(&kb).arg(&vh).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8907             .arg(&scale).arg(&cz).arg(&wi);
8908            unsafe { b.launch(cfg)?; }
8909            return Ok(());
8910        }
8911        if p1 {
8912            let f = self.func("fa_prefill_w_bf16_p1");
8913            let shmem = (2 * (2 * BK * head_dim + BLOCK_Q * BK)
8914                       + 4 * (BLOCK_Q * BK + 2 * BLOCK_Q)) as u32;
8915            use cudarc::driver::sys::CUfunction_attribute_enum as A;
8916            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8917            let cfg = LaunchConfig {
8918                grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 1),
8919                block_dim: (32, 4, 1), shared_mem_bytes: shmem,
8920            };
8921            let (hd, nh, nhkv, ti, tkvi, cz, wi) = (head_dim as i32, n_head as i32,
8922                n_head_kv as i32, t as i32, t_kv as i32, causal as i32, window as i32);
8923            let qb = self.f32_to_bf16(q, t * n_head * head_dim)?;
8924            let kb = self.f32_to_bf16(k, t_kv * n_head_kv * head_dim)?;
8925            let vb = self.f32_to_bf16(v, t_kv * n_head_kv * head_dim)?;
8926            let __s_b = self.gpu.stream();
8927            let mut b = __s_b.launch_builder(&f);
8928            b.arg(&qb).arg(&kb).arg(&vb).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8929             .arg(&scale).arg(&cz).arg(&wi);
8930            unsafe { b.launch(cfg)?; }
8931            return Ok(());
8932        }
8933        // MQA head-grouping (MEMRA_FAW_G4=0 reverts): 4 heads/CTA share the staged K/V —
8934        // per-(head,row) FP chain identical to the per-head stamp -> bit-identical (gated).
8935        static G4_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8936        let g4 = !floor && !f32_stage && n_head_kv == 1 && n_head % 4 == 0
8937            && *G4_ON.get_or_init(|| {
8938                std::env::var("MEMRA_FAW_G4").map(|v| v != "0").unwrap_or(true)
8939            });
8940        if g4 {
8941            const SP_M: usize = 16;
8942            // Occupancy-2 twin (MEMRA_FAW_O2=0 reverts): one shared K/V buffer inside the dead
8943            // Q-stage region -> ~36.5KB smem, 2 CTA/SM (the llama hd256 mechanism). Bit-identical.
8944            static O2_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8945            let o2 = *O2_ON.get_or_init(|| {
8946                std::env::var("MEMRA_FAW_O2").map(|v| v != "0").unwrap_or(true)
8947            });
8948            let f = self.func(if o2 { "fa_prefill_w_bf16_g4o2" } else { "fa_prefill_w_bf16_g4" });
8949            let shmem = if o2 {
8950                (2 * (4 * SP_M * head_dim + 4 * SP_M * BK) + 4 * (4 * SP_M)) as u32
8951            } else {
8952                (2 * (2 * BK * head_dim + 4 * SP_M * head_dim + 4 * SP_M * BK)
8953                    + 4 * (4 * SP_M)) as u32
8954            };
8955            use cudarc::driver::sys::CUfunction_attribute_enum as A;
8956            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8957            let cfg = LaunchConfig {
8958                grid_dim: ((t as u32).div_ceil(SP_M as u32), (n_head / 4) as u32, 1),
8959                block_dim: (32, 4, 1), shared_mem_bytes: shmem,
8960            };
8961            let (hd, nh, nhkv, ti, tkvi, cz, wi) = (head_dim as i32, n_head as i32,
8962                n_head_kv as i32, t as i32, t_kv as i32, causal as i32, window as i32);
8963            let qb = self.f32_to_bf16(q, t * n_head * head_dim)?;
8964            let kb = self.f32_to_bf16(k, t_kv * n_head_kv * head_dim)?;
8965            let vb = self.f32_to_bf16(v, t_kv * n_head_kv * head_dim)?;
8966            let __s_b = self.gpu.stream();
8967            let mut b = __s_b.launch_builder(&f);
8968            b.arg(&qb).arg(&kb).arg(&vb).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8969             .arg(&scale).arg(&cz).arg(&wi);
8970            unsafe { b.launch(cfg)?; }
8971            return Ok(());
8972        }
8973        let f = self.func(if floor { "fa_prefill_w_f32" }
8974                          else if f32_stage { "fa_prefill_w_f32_pp" }
8975                          else { "fa_prefill_w_bf16_pp" });
8976        let shmem = (2 * (2 * BK * head_dim + BLOCK_Q * BK)
8977                   + 4 * (BLOCK_Q * BK + 2 * BLOCK_Q)) as u32;
8978        use cudarc::driver::sys::CUfunction_attribute_enum as A;
8979        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
8980        let cfg = LaunchConfig {
8981            grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 1),
8982            block_dim: (32, 4, 1), shared_mem_bytes: shmem,
8983        };
8984        let (hd, nh, nhkv, ti, tkvi, cz, wi) = (head_dim as i32, n_head as i32, n_head_kv as i32,
8985                                                t as i32, t_kv as i32, causal as i32, window as i32);
8986        if f32_stage {
8987            let __s_b = self.gpu.stream();
8988            let mut b = __s_b.launch_builder(&f);
8989            b.arg(q).arg(k).arg(v).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8990             .arg(&scale).arg(&cz).arg(&wi);
8991            unsafe { b.launch(cfg)?; }
8992        } else {
8993            let qb = self.f32_to_bf16(q, t * n_head * head_dim)?;
8994            let kb = self.f32_to_bf16(k, t_kv * n_head_kv * head_dim)?;
8995            let vb = self.f32_to_bf16(v, t_kv * n_head_kv * head_dim)?;
8996            let __s_b = self.gpu.stream();
8997            let mut b = __s_b.launch_builder(&f);
8998            b.arg(&qb).arg(&kb).arg(&vb).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
8999             .arg(&scale).arg(&cz).arg(&wi);
9000            unsafe { b.launch(cfg)?; }
9001        }
9002        Ok(())
9003    }
9004
9005    /// hd512 FA prefill (gemma4 GLOBAL layers): BLOCK_Q=32 x 2 warps, Q staged in smem,
9006    /// grid.z = 2 O-halves (each CTA computes the full 512-dim scores, accumulates half the
9007    /// V dims). Replaces the scalar sdpa_naive on the prime path's globals.
9008    #[allow(clippy::too_many_arguments)]
9009    pub fn fa_prefill_hd512(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
9010                            o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize,
9011                            n_head_kv: usize, t: usize, t_kv: usize, scale: f32, causal: bool)
9012                            -> Result<(), Box<dyn std::error::Error>> {
9013        // sm_90a rides the mma twins (portable_mma_gated, 2026-07-31 — same flip as _w).
9014        if portable_mma_gated() {
9015            return self.sdpa_naive(q, k, v, o, head_dim, n_head, n_head_kv,
9016                                   t, t_kv, scale, causal);
9017        }
9018        // Default: pre-convert Q/K/V to bf16 once and stage int4 (8 bf16/copy) — at 1 CTA/SM the
9019        // synchronous stage serializes with compute and MQA re-stages the same K/V per head CTA;
9020        // pre-converting halves staged bytes and cuts stage instructions 8x. BIT-IDENTICAL to the
9021        // f32-staged kernel (the converter applies the same __float2bfloat16 the stage applied;
9022        // kernel_check gates the identity). MEMRA_FA512_STAGE=f32 = rollback to the f32 kernel.
9023        static F32_STAGE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
9024        let f32_stage = *F32_STAGE.get_or_init(|| {
9025            std::env::var("MEMRA_FA512_STAGE").as_deref() == Ok("f32")
9026        });
9027        // Single-pass arm (MEMRA_FA512_SP=0 reverts to the z=2 bf16 kernel): GEMM0 split-K across
9028        // the 2 warps instead of recomputed per O-half CTA — the 2026-07-22 kernel-diff excess.
9029        // Own numeric config (partial-sum order) — battery-gated.
9030        static SP_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
9031        let sp = !f32_stage
9032            && *SP_ON.get_or_init(|| {
9033                std::env::var("MEMRA_FA512_SP").map(|v| v != "0").unwrap_or(true)
9034            });
9035        self.fa_prefill_hd512_arm(q, k, v, o, head_dim, n_head, n_head_kv, t, t_kv, scale,
9036                                  causal, f32_stage, sp, sp && fa_f16pv_on())
9037    }
9038
9039    /// hd512 single-pass FA with PRE-CONVERTED bf16 operands (producer-emitted).
9040    #[allow(clippy::too_many_arguments)]
9041    pub fn fa_prefill_hd512_pre(&self, qb: &CudaSlice<u8>, kb: &CudaSlice<u8>, vb: &CudaSlice<u8>,
9042                                o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize,
9043                                n_head_kv: usize, t: usize, t_kv: usize, scale: f32, causal: bool,
9044                                v_f16: bool)
9045                                -> Result<(), Box<dyn std::error::Error>> {
9046        debug_assert_eq!(head_dim, 512);
9047        const SP_M: usize = 16; const BKS: usize = 32;
9048        // f16-P/V door (MEMRA_FA_F16PV=1): P and the P@V accumulation in f16 (llama's fa=1 VKQ
9049        // class); KQ/softmax/rescale-band/final-normalize stay f32. Own numeric config —
9050        // battery-gated. V bytes must be f16 for the sp16 kernel (stage/ldmatrix are typeless).
9051        let f16pv = fa_f16pv_on();
9052        let nw = if f16pv { fa512_wide_warps() } else { 2 };
9053        let hp = f16pv && fa512_hp_on() && n_head % 2 == 0 && (n_head / n_head_kv) % 2 == 0;
9054        debug_assert!(!v_f16 || f16pv, "f16 V emitted without the door on");
9055        let mut vguard = self.fa_vf16_scratch.lock().unwrap();
9056        let vref: &CudaSlice<u8> = if f16pv && !v_f16 {
9057            // Fallback re-encode (producer emitted bf16); the emit lane normally hands f16.
9058            let n = t_kv * n_head_kv * head_dim;
9059            let need = n * 2;
9060            if vguard.as_ref().map(|b| b.len() < need).unwrap_or(true) {
9061                *vguard = Some(self.alloc_uninit::<u8>(need)?);
9062            }
9063            let dst = vguard.as_mut().unwrap();
9064            self.bf16_to_f16_into(vb, n, dst)?;
9065            vguard.as_ref().unwrap()
9066        } else { vb };
9067        let f = self.func(if hp { "fa_prefill_bf16_hd512_sp16h2" }
9068                          else { match (f16pv, nw) {
9069                              (true, 4) => "fa_prefill_bf16_hd512_sp16w4",
9070                              (true, _) => "fa_prefill_bf16_hd512_sp16",
9071                              _ => "fa_prefill_bf16_hd512_sp",
9072                          } });
9073        let (nwarp, npart) = if hp { (4usize, 4usize) } else if nw > 2 { (nw, nw) } else { (2, 1) };
9074        // h2 drops sQ (Q register-resident) and doubles sP/sS/sL for the head pair.
9075        let shmem = if hp {
9076            (2 * (2 * BKS * head_dim + 2 * SP_M * BKS)
9077               + 4 * (2 * npart * SP_M * BKS + 2 * SP_M)) as u32
9078        } else {
9079            (2 * (SP_M * head_dim + 2 * BKS * head_dim + SP_M * BKS)
9080               + 4 * (npart * SP_M * BKS + SP_M)) as u32
9081        };
9082        use cudarc::driver::sys::CUfunction_attribute_enum as A;
9083        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9084        let grid_y = if hp { (n_head / 2) as u32 } else { n_head as u32 };
9085        let cfg = LaunchConfig {
9086            grid_dim: ((t as u32).div_ceil(SP_M as u32), grid_y, 1),
9087            block_dim: (32, nwarp as u32, 1), shared_mem_bytes: shmem,
9088        };
9089        let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32,
9090                                            t as i32, t_kv as i32, causal as i32);
9091        let __s_b = self.gpu.stream();
9092        let mut b = __s_b.launch_builder(&f);
9093        b.arg(qb).arg(kb).arg(vref).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
9094         .arg(&scale).arg(&cz);
9095        unsafe { b.launch(cfg)?; }
9096        Ok(())
9097    }
9098
9099    /// hd512 FA prefill with the stage/sp arms FORCED — the kernel_check gate entry
9100    /// (`fa_prefill_hd512` picks the arms from MEMRA_FA512_STAGE / MEMRA_FA512_SP).
9101    #[allow(clippy::too_many_arguments)]
9102    pub fn fa_prefill_hd512_arm(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
9103                                o: &mut CudaSlice<f32>, head_dim: usize, n_head: usize,
9104                                n_head_kv: usize, t: usize, t_kv: usize, scale: f32, causal: bool,
9105                                f32_stage: bool, sp: bool, f16pv: bool)
9106                                -> Result<(), Box<dyn std::error::Error>> {
9107        debug_assert_eq!(head_dim, 512, "fa_prefill_hd512 is hd512 only");
9108        if sp && !f32_stage {
9109            // Single-pass: 16 q-rows/CTA, 2 warps, grid (ceil(T/16), n_head, 1).
9110            // smem: sQ[16][512] + sK[32][512] + sV[32][512] + sP[16][32] (bf16) + sS[16][32]+sL f32.
9111            // f16pv: sp16 kernel — f16 P + f16 P@V accum, V operand encoded f16.
9112            const SP_M: usize = 16; const BKS: usize = 32;
9113            let nw = if f16pv { fa512_wide_warps() } else { 2 };
9114            let hp = f16pv && fa512_hp_on() && n_head % 2 == 0 && (n_head / n_head_kv) % 2 == 0;
9115            let f = self.func(if hp { "fa_prefill_bf16_hd512_sp16h2" }
9116                              else { match (f16pv, nw) {
9117                                  (true, 4) => "fa_prefill_bf16_hd512_sp16w4",
9118                                  (true, _) => "fa_prefill_bf16_hd512_sp16",
9119                                  _ => "fa_prefill_bf16_hd512_sp",
9120                              } });
9121            let (nwarp, npart) = if hp { (4usize, 4usize) } else if nw > 2 { (nw, nw) } else { (2, 1) };
9122            let shmem = if hp {
9123                (2 * (2 * BKS * head_dim + 2 * SP_M * BKS)
9124                   + 4 * (2 * npart * SP_M * BKS + 2 * SP_M)) as u32
9125            } else {
9126                (2 * (SP_M * head_dim + 2 * BKS * head_dim + SP_M * BKS)
9127                   + 4 * (npart * SP_M * BKS + SP_M)) as u32
9128            };
9129            use cudarc::driver::sys::CUfunction_attribute_enum as A;
9130            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9131            let grid_y = if hp { (n_head / 2) as u32 } else { n_head as u32 };
9132            let cfg = LaunchConfig {
9133                grid_dim: ((t as u32).div_ceil(SP_M as u32), grid_y, 1),
9134                block_dim: (32, nwarp as u32, 1), shared_mem_bytes: shmem,
9135            };
9136            let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32,
9137                                                t as i32, t_kv as i32, causal as i32);
9138            let qb = self.f32_to_bf16(q, t * n_head * head_dim)?;
9139            let kb = self.f32_to_bf16(k, t_kv * n_head_kv * head_dim)?;
9140            let vb = if f16pv { self.f32_to_f16(v, t_kv * n_head_kv * head_dim)? }
9141                     else { self.f32_to_bf16(v, t_kv * n_head_kv * head_dim)? };
9142            let __s_b = self.gpu.stream();
9143            let mut b = __s_b.launch_builder(&f);
9144            b.arg(&qb).arg(&kb).arg(&vb).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
9145             .arg(&scale).arg(&cz);
9146            unsafe { b.launch(cfg)?; }
9147            return Ok(());
9148        }
9149        const BLOCK_Q: usize = 32; const BK: usize = 32; const HALF: usize = 256;
9150        let f = self.func(if f32_stage { "fa_prefill_f32_hd512" } else { "fa_prefill_bf16_hd512" });
9151        // sQ[32][512] + sK[BK][512] + sV[BK][256] + sP[32][BK] (bf16) + sL[32] f32
9152        let shmem = (2 * (BLOCK_Q * head_dim + BK * head_dim + BK * HALF + BLOCK_Q * BK)
9153                   + 4 * BLOCK_Q) as u32;
9154        use cudarc::driver::sys::CUfunction_attribute_enum as A;
9155        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9156        let cfg = LaunchConfig {
9157            grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 2),
9158            block_dim: (32, 2, 1), shared_mem_bytes: shmem,
9159        };
9160        let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32,
9161                                            t as i32, t_kv as i32, causal as i32);
9162        if f32_stage {
9163            let __s_b = self.gpu.stream();
9164            let mut b = __s_b.launch_builder(&f);
9165            b.arg(q).arg(k).arg(v).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
9166             .arg(&scale).arg(&cz);
9167            unsafe { b.launch(cfg)?; }
9168        } else {
9169            let qb = self.f32_to_bf16(q, t * n_head * head_dim)?;
9170            let kb = self.f32_to_bf16(k, t_kv * n_head_kv * head_dim)?;
9171            let vb = self.f32_to_bf16(v, t_kv * n_head_kv * head_dim)?;
9172            let __s_b = self.gpu.stream();
9173            let mut b = __s_b.launch_builder(&f);
9174            b.arg(&qb).arg(&kb).arg(&vb).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi)
9175             .arg(&scale).arg(&cz);
9176            unsafe { b.launch(cfg)?; }
9177        }
9178        Ok(())
9179    }
9180
9181    /// rope_neox2 with bf16 EMIT (31B glue lane): identical rope math/stores plus the post-rope
9182    /// values written as bf16 — the FA q/k operands come from this launch (bit-identical to the
9183    /// separate f32_to_bf16 the FA entries would run).
9184    #[allow(clippy::too_many_arguments)]
9185    pub fn rope_neox2_bf16e(&self, q: &mut CudaSlice<f32>, k: &mut CudaSlice<f32>,
9186                            qb: &mut CudaSlice<u8>, kb: &mut CudaSlice<u8>,
9187                            pos: &CudaSlice<i32>, head_dim: usize, n_dims: usize,
9188                            nh_q: usize, nh_k: usize, n_tokens: usize, base: f32,
9189                            freq_scale: f32, ff: Option<&CudaSlice<f32>>)
9190                            -> Result<(), Box<dyn std::error::Error>> {
9191        let f = self.func("rope_neox2_bf16e_f32");
9192        let rows = ((nh_q + nh_k) * n_tokens) as u32;
9193        let cfg = LaunchConfig { grid_dim: (rows, 1, 1),
9194                                 block_dim: ((head_dim / 2) as u32, 1, 1), shared_mem_bytes: 0 };
9195        let theta_scale = base.powf(-2.0 / n_dims as f32);
9196        let (hd, nd, nhq, nhk, nt) = (head_dim as i32, n_dims as i32, nh_q as i32,
9197                                      nh_k as i32, n_tokens as i32);
9198        let __s_b = self.gpu.stream();
9199        let mut b = __s_b.launch_builder(&f);
9200        match ff {
9201            Some(t) => { b.arg(&mut *q).arg(&mut *k).arg(&mut *qb).arg(&mut *kb).arg(pos)
9202                          .arg(&hd).arg(&nd).arg(&nhq).arg(&nhk).arg(&nt)
9203                          .arg(&theta_scale).arg(&freq_scale).arg(t);
9204                         unsafe { b.launch(cfg)?; } }
9205            None => { let null: u64 = 0;
9206                      b.arg(&mut *q).arg(&mut *k).arg(&mut *qb).arg(&mut *kb).arg(pos)
9207                       .arg(&hd).arg(&nd).arg(&nhq).arg(&nhk).arg(&nt)
9208                       .arg(&theta_scale).arg(&freq_scale).arg(&null);
9209                      unsafe { b.launch(cfg)?; } }
9210        }
9211        Ok(())
9212    }
9213
9214    /// Flat f32 -> bf16 conversion into a fresh scratch buffer (2 bytes/elem). `n % 4 == 0`
9215    /// (float4 in, 4x bf16 out). Feeds the bf16-staged hd512 FA prefill.
9216    pub fn f32_to_bf16(&self, x: &CudaSlice<f32>, n: usize)
9217                       -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
9218        assert!(n % 4 == 0, "f32_to_bf16 requires n % 4 == 0, got {n}");
9219        let mut y = self.alloc_uninit::<u8>(n * 2)?;
9220        let f = self.func("f32_to_bf16_flat");
9221        let n_i = n as i64;
9222        let cfg = LaunchConfig {
9223            grid_dim: (((n / 4) as u32).div_ceil(256), 1, 1),
9224            block_dim: (256, 1, 1), shared_mem_bytes: 0,
9225        };
9226        let __s_b = self.gpu.stream();
9227        let mut b = __s_b.launch_builder(&f);
9228        b.arg(x).arg(&mut y).arg(&n_i);
9229        unsafe { b.launch(cfg)?; }
9230        Ok(y)
9231    }
9232
9233    pub fn f32_to_f16(&self, x: &CudaSlice<f32>, n: usize)
9234                      -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
9235        assert!(n % 4 == 0, "f32_to_f16 requires n % 4 == 0, got {n}");
9236        let mut y = self.alloc_uninit::<u8>(n * 2)?;
9237        let f = self.func("f32_to_f16_flat");
9238        let n_i = n as i64;
9239        let cfg = LaunchConfig {
9240            grid_dim: (((n / 4) as u32).div_ceil(256), 1, 1),
9241            block_dim: (256, 1, 1), shared_mem_bytes: 0,
9242        };
9243        let __s_b = self.gpu.stream();
9244        let mut b = __s_b.launch_builder(&f);
9245        b.arg(x).arg(&mut y).arg(&n_i);
9246        unsafe { b.launch(cfg)?; }
9247        Ok(y)
9248    }
9249
9250    /// bf16 bytes -> f16 bytes, n elements (the f16-P/V door's V re-encode on the emit lane).
9251    pub fn bf16_to_f16(&self, xb: &CudaSlice<u8>, n: usize)
9252                       -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
9253        let mut y = self.alloc_uninit::<u8>(n * 2)?;
9254        self.bf16_to_f16_into(xb, n, &mut y)?;
9255        Ok(y)
9256    }
9257
9258    /// Same conversion into a caller-owned (pooled) buffer; `y.len() >= n*2`.
9259    pub fn bf16_to_f16_into(&self, xb: &CudaSlice<u8>, n: usize, y: &mut CudaSlice<u8>)
9260                            -> Result<(), Box<dyn std::error::Error>> {
9261        assert!(n % 2 == 0, "bf16_to_f16 requires n % 2 == 0, got {n}");
9262        assert!(y.len() >= n * 2);
9263        let f = self.func("bf16_to_f16_flat");
9264        let n2 = (n / 2) as i64;
9265        let cfg = LaunchConfig {
9266            grid_dim: (((n / 2) as u32).div_ceil(256), 1, 1),
9267            block_dim: (256, 1, 1), shared_mem_bytes: 0,
9268        };
9269        let __s_b = self.gpu.stream();
9270        let mut b = __s_b.launch_builder(&f);
9271        b.arg(xb).arg(y).arg(&n2);
9272        unsafe { b.launch(cfg)?; }
9273        Ok(())
9274    }
9275
9276    /// task #18 (attn side): varlen FA — bf16 K/V mirrors (2 launches) + ONE
9277    /// fa_prefill_bf16kv launch for every fresh sequence. Same per-block math as the
9278    /// per-seq path (bit-gateable). Caller guarantees: fresh causal (T_kv == T),
9279    /// head_dim in {256, 128}, bf16kv lane on.
9280    #[allow(clippy::too_many_arguments)]
9281    pub fn fa_prefill_vl8(&self, seqs: &[FaSeqVl], head_dim: usize, n_head: usize,
9282                          n_head_kv: usize, scale: f32)
9283                          -> Result<(), Box<dyn std::error::Error>> {
9284        const BK: usize = 32;
9285        let b = seqs.len();
9286        assert!(b >= 1 && b <= 8);
9287        let mut packed = [FaSeqVl::default(); 8];
9288        packed[..b].copy_from_slice(seqs);
9289        let v = FaVl8(packed);
9290        let max_t = seqs.iter().map(|s| s.t).max().unwrap() as u32;
9291        let ept = (n_head_kv * head_dim) as i32;
9292        {
9293            let f = self.func("fa_mirror_vl");
9294            let max_n = (max_t as i64) * ept as i64;
9295            let blocks = ((max_n as u32).div_ceil(4)).div_ceil(256);
9296            for which in 0..2i32 {
9297                let cfg = LaunchConfig { grid_dim: (blocks, 1, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
9298                let __s_lb = self.gpu.stream();
9299                let mut lb = __s_lb.launch_builder(&f);
9300                lb.arg(&v).arg(&ept).arg(&which);
9301                unsafe { lb.launch(cfg)?; }
9302            }
9303        }
9304        let hd_sfx = fa_hd_suffix(head_dim)?;
9305        let f = self.func(&format!("fa_prefill_bf16kv_vl{hd_sfx}"));
9306        let block_q = 64usize;
9307        let kv_stages = 2usize;
9308        let shmem = (2 * (kv_stages * 2 * BK * head_dim + block_q * BK)
9309                   + 4 * (block_q * BK + 2 * block_q)) as u32;
9310        use cudarc::driver::sys::CUfunction_attribute_enum as A;
9311        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9312        let cfg = LaunchConfig {
9313            grid_dim: (max_t.div_ceil(block_q as u32), n_head as u32, b as u32),
9314            block_dim: (32, 4, 1), shared_mem_bytes: shmem,
9315        };
9316        let (hd, nh, nhkv) = (head_dim as i32, n_head as i32, n_head_kv as i32);
9317        let __s_lb = self.gpu.stream();
9318        let mut lb = __s_lb.launch_builder(&f);
9319        lb.arg(&v).arg(&hd).arg(&nh).arg(&nhkv).arg(&scale);
9320        unsafe { lb.launch(cfg)?; }
9321        Ok(())
9322    }
9323
9324    /// task #18 (attn pre-FA): varlen split + QK-norm + RoPE + KV-append — FOUR launches
9325    /// for every fresh sequence (was 6 x B, plus the q/k/v split copies which the view
9326    /// inputs remove entirely). Fresh-only (append at t0=0, RoPE pos = token index).
9327    #[allow(clippy::too_many_arguments)]
9328    pub fn attn_pre_vl8(&self, seqs: &[AttnPreVl], wq: &CudaSlice<f32>, wk: &CudaSlice<f32>,
9329                        head_dim: usize, rope_dims: usize, n_head: usize, n_head_kv: usize,
9330                        eps: f32, freq_base: f32, freq_scale: f32,
9331                        kv_dim_k: usize, kv_dim_v: usize,
9332                        k_tok_bytes: usize, v_tok_bytes: usize)
9333                        -> Result<(), Box<dyn std::error::Error>> {
9334        let b = seqs.len();
9335        assert!(b >= 1 && b <= 8);
9336        let mut packed = [AttnPreVl::default(); 8];
9337        packed[..b].copy_from_slice(seqs);
9338        let v = AttnPreVl8(packed);
9339        let max_t = seqs.iter().map(|s| s.t).max().unwrap() as u32;
9340        let (hd, nh, nhkv) = (head_dim as i32, n_head as i32, n_head_kv as i32);
9341        {
9342            let f = self.func("q_gate_split_vl");
9343            let n = max_t * (n_head * head_dim) as u32;
9344            let cfg = LaunchConfig { grid_dim: (n.div_ceil(256), 1, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
9345            let __s_lb = self.gpu.stream();
9346            let mut lb = __s_lb.launch_builder(&f);
9347            lb.arg(&v).arg(&hd).arg(&nh);
9348            unsafe { lb.launch(cfg)?; }
9349        }
9350        {
9351            let f = self.func("attn_rms_vl");
9352            let cfg = LaunchConfig { grid_dim: (max_t * n_head as u32, 2, b as u32), block_dim: (rms_block(), 1, 1), shared_mem_bytes: 0 };
9353            let __s_lb = self.gpu.stream();
9354            let mut lb = __s_lb.launch_builder(&f);
9355            lb.arg(&v).arg(wq).arg(wk).arg(&hd).arg(&nh).arg(&nhkv).arg(&eps);
9356            unsafe { lb.launch(cfg)?; }
9357        }
9358        {
9359            let f = self.func("attn_rope_vl");
9360            let theta_scale = freq_base.powf(-2.0 / rope_dims as f32);
9361            let nd = rope_dims as i32;
9362            let cfg = LaunchConfig { grid_dim: (max_t * n_head as u32, 2, b as u32), block_dim: ((head_dim / 2) as u32, 1, 1), shared_mem_bytes: 0 };
9363            let __s_lb = self.gpu.stream();
9364            let mut lb = __s_lb.launch_builder(&f);
9365            lb.arg(&v).arg(&hd).arg(&nd).arg(&nh).arg(&nhkv).arg(&theta_scale).arg(&freq_scale);
9366            unsafe { lb.launch(cfg)?; }
9367        }
9368        {
9369            let f = self.func("append_kv_vl");
9370            let nblk = (kv_dim_k.max(kv_dim_v) / 32) as u32;
9371            let cfg = LaunchConfig { grid_dim: (nblk, max_t, b as u32), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
9372            let (kdk, kdv) = (kv_dim_k as i32, kv_dim_v as i32);
9373            let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
9374            let __s_lb = self.gpu.stream();
9375            let mut lb = __s_lb.launch_builder(&f);
9376            lb.arg(&v).arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
9377            unsafe { lb.launch(cfg)?; }
9378        }
9379        Ok(())
9380    }
9381
9382    /// FA prefill where K/V are QUANTIZED CudaViews into the resident byte KV cache (the T=K verify
9383    /// path, MTP-PLAN §D.3). Uses `fa_prefill_q` (inline-dequant during stage-to-smem). The view's
9384    /// base+offset pointer is honored; the kernel reads [0..t_kv*tok_bytes). Q is the T fresh query
9385    /// rows; t = T, t_kv = cache len. k_tok_bytes/v_tok_bytes are the per-token byte strides.
9386    pub fn fa_prefill_view(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
9387                           v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
9388                           head_dim: usize, n_head: usize, n_head_kv: usize,
9389                           t: usize, t_kv: usize, scale: f32, causal: bool,
9390                           k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
9391                           -> Result<(), Box<dyn std::error::Error>> {
9392        if portable_mma_gated() {
9393            return self.sdpa_naive_quantized_view(q, k, v, o, head_dim, n_head, n_head_kv,
9394                                                  t, t_kv, scale, causal,
9395                                                  k_tok_bytes, v_tok_bytes);
9396        }
9397        const BLOCK_Q: usize = 64; const BK: usize = 32;
9398        // g = e4m3 cache: the kernel parses via DQ_K_ELEM/DQ_V_ELEM (format macros) — the
9399        // kf8vf8-module stamp reads fp8 with the identical MMA/softmax/PV body.
9400        let name = format!("fa_prefill_q{}", fa_hd_suffix(head_dim)?);
9401        let f = if g { self.func_g(&name) } else { self.func(&name) };
9402        let shmem = (2 * (2 * BK * head_dim + BLOCK_Q * BK)
9403                   + 4 * (BLOCK_Q * BK + 2 * BLOCK_Q)) as u32;
9404        use cudarc::driver::sys::CUfunction_attribute_enum as A;
9405        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9406        let cfg = LaunchConfig {
9407            grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 1),
9408            block_dim: (32, 4, 1), shared_mem_bytes: shmem,
9409        };
9410        let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32, t as i32, t_kv as i32, causal as i32);
9411        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
9412        let __s_b = self.gpu.stream();
9413        let mut b = __s_b.launch_builder(&f);
9414        b.arg(q).arg(k).arg(v).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi).arg(&scale).arg(&cz)
9415         .arg(&ktb).arg(&vtb);
9416        unsafe { b.launch(cfg)?; }
9417        Ok(())
9418    }
9419
9420    /// ARC B (2026-07-05): dequant-once chunk-prime FA. Same contract as `fa_prefill_view`, but
9421    /// instead of every (q-block, head) CTA re-dequanting the whole quantized KV stream inline
9422    /// (T/64 x n_head redundant at chunk prime — 30.5% of the 32k prime wall), dequant the full
9423    /// [t_kv, kv_dim] K and V ONCE into a resident bf16 workspace (fa_dequant_kv_ws_bf16), then
9424    /// run `fa_prefill_qw` (the bf16-workspace twin) over it. EXACT: the workspace holds the same
9425    /// __float2bfloat16(dq_*_elem(...)) values fa_prefill_q stages to smem, and the twin's MMA/
9426    /// softmax/PV code is byte-identical -> bit-identical O (kernel_check pins bitdiff=0).
9427    /// The workspace allocation is REUSED across layers/chunks (grown to the largest shape);
9428    /// contents are rewritten per call. MEMRA_PRIME_DEQW=0 falls back to fa_prefill_view (callers gate).
9429    #[allow(clippy::too_many_arguments)]
9430    pub fn fa_prefill_view_ws(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
9431                              v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
9432                              head_dim: usize, n_head: usize, n_head_kv: usize,
9433                              t: usize, t_kv: usize, scale: f32, causal: bool,
9434                              k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
9435                              -> Result<(), Box<dyn std::error::Error>> {
9436        if portable_mma_gated() {
9437            return self.sdpa_naive_quantized_view(q, k, v, o, head_dim, n_head, n_head_kv,
9438                                                  t, t_kv, scale, causal,
9439                                                  k_tok_bytes, v_tok_bytes);
9440        }
9441        const BLOCK_Q: usize = 64; const BK: usize = 32;
9442        let kv_dim_k = n_head_kv * head_dim;
9443        let kv_dim_v = n_head_kv * head_dim;
9444        let k_ws_bytes = t_kv * kv_dim_k * 2;   // bf16
9445        let v_ws_bytes = t_kv * kv_dim_v * 2;
9446        // Lock held across BOTH launches: enqueue-only (µs), all compute serializes on gpu.stream.
9447        let mut guard = self.prime_deqw_ws.lock().unwrap();
9448        let need_grow = match guard.as_ref() {
9449            Some((kw, vw)) => kw.len() < k_ws_bytes || vw.len() < v_ws_bytes,
9450            None => true,
9451        };
9452        if need_grow {
9453            let grow = |cur: usize, need: usize| if cur >= need { cur } else { need };
9454            let (ck, cv) = guard.as_ref().map(|(a, b)| (a.len(), b.len())).unwrap_or((0, 0));
9455            *guard = Some((self.alloc_u8(grow(ck, k_ws_bytes))?, self.alloc_u8(grow(cv, v_ws_bytes))?));
9456        }
9457        let (kw, vw) = guard.as_mut().unwrap();
9458        // pass 1: dequant K+V once into the bf16 workspace (grid-stride, 1 thread/elem)
9459        {
9460            // only THIS pass parses KV bytes — pass 2 reads the bf16 workspace (format-free).
9461            let f = if g { self.func_g("fa_dequant_kv_ws_bf16") } else { self.func("fa_dequant_kv_ws_bf16") };
9462            let total = (t_kv * (kv_dim_k + kv_dim_v)) as u64;
9463            let nblk = ((total + 255) / 256).min(65535 * 16) as u32;
9464            let cfg = LaunchConfig { grid_dim: (nblk.max(1), 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
9465            let (kdk, kdv, tkvi) = (kv_dim_k as i32, kv_dim_v as i32, t_kv as i32);
9466            let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
9467            let __s_b = self.gpu.stream();
9468            let mut b = __s_b.launch_builder(&f);
9469            b.arg(k).arg(v).arg(&mut *kw).arg(&mut *vw).arg(&kdk).arg(&kdv).arg(&tkvi).arg(&ktb).arg(&vtb);
9470            unsafe { b.launch(cfg)?; }
9471        }
9472        // pass 2: the bf16-workspace prefill twin (same tile sizes/loop structure as fa_prefill_q).
9473        // DEFAULT: cp.async double-buffered staging twin (fa_prefill_qw_db, +32KB smem for the
9474        // second K/V tile pair, 1 CTA/SM): overlaps tile n+1's L2->smem copy with tile n's MMA.
9475        // Bit-identical output (staging is a pure byte copy; kernel_check pins bitdiff=0 under
9476        // both twins). A/B (27B g7e, N=3): 32k prime 17.10->16.51s, 16k 9.09->8.65s — the copy
9477        // latency hides behind the MMA pipe and beats the 2-CTA/SM occupancy of the sync twin.
9478        // MEMRA_PRIME_DEQW_DB=0 falls back to the single-buffer twin.
9479        let db = std::env::var("MEMRA_PRIME_DEQW_DB").map(|v| v != "0").unwrap_or(true);
9480        {
9481            let hd_sfx = fa_hd_suffix(head_dim)?;
9482            let f = self.func(&format!("fa_prefill_qw{}{hd_sfx}", if db { "_db" } else { "" }));
9483            let shmem = if db {
9484                // 4x KV tile buffers (bf16) + sP (bf16) + sL (f32)
9485                (2 * (4 * BK * head_dim + BLOCK_Q * BK) + 4 * BLOCK_Q) as u32
9486            } else {
9487                (2 * (2 * BK * head_dim + BLOCK_Q * BK)
9488                       + 4 * (BLOCK_Q * BK + 2 * BLOCK_Q)) as u32
9489            };
9490            use cudarc::driver::sys::CUfunction_attribute_enum as A;
9491            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9492            let cfg = LaunchConfig {
9493                grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 1),
9494                block_dim: (32, 4, 1), shared_mem_bytes: shmem,
9495            };
9496            let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32, t as i32, t_kv as i32, causal as i32);
9497            let (kdk, kdv) = (kv_dim_k as i32, kv_dim_v as i32);
9498            let __s_b = self.gpu.stream();
9499            let mut b = __s_b.launch_builder(&f);
9500            b.arg(q).arg(&*kw).arg(&*vw).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi).arg(&scale).arg(&cz)
9501             .arg(&kdk).arg(&kdv);
9502            unsafe { b.launch(cfg)?; }
9503        }
9504        Ok(())
9505    }
9506
9507    /// WINDOWED `fa_prefill_view_ws` twin at head_dim 128 (lane/pp-prefill 2026-08-07):
9508    /// step35's SWA prefill (win=512, 33 of 45 layers) previously had NO windowed FA prefill
9509    /// stamp — every windowed twin was hd256-only — and took `sdpa_naive_w_quantized_view`,
9510    /// the f32 floor, at 565 ms/layer on a pp4096 where the hd128 FA family does the harder
9511    /// causal-4096 in 3.3 ms (41% of the whole prime; research/pp-prefill-20260807 anatomy).
9512    /// Same two-pass shape as the unwindowed function: dequant K/V ONCE into the resident
9513    /// bf16 workspace, then the windowed qw kernel (`fa_prefill_qw_db_w_hd128`, cp.async
9514    /// double-buffered; MEMRA_PRIME_DEQW_DB=0 selects the single-buffer twin). The window
9515    /// mask is `fa_prefill_f32_body`'s exact predicate; `window == 0` is bit-identical to
9516    /// `fa_prefill_view_ws` by construction (default-arg body). NEW NUMERIC CLASS vs the
9517    /// f32 floor on SWA rows (bf16 MMA online-softmax vs f32 serial softmax) — adoption is
9518    /// gated by the full battery, and the class must change UNIFORMLY for a whole request
9519    /// (kernel selection keys on seq_end, never per chunk — the chunkfix law).
9520    /// hd128-only deliberately: the only windowed-prefill consumer at another head_dim is
9521    /// gemma4 (hd256), which already has `fa_prefill_w_f32`.
9522    #[allow(clippy::too_many_arguments)]
9523    pub fn fa_prefill_view_ws_w_hd128(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
9524                                      v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
9525                                      head_dim: usize, n_head: usize, n_head_kv: usize,
9526                                      t: usize, t_kv: usize, scale: f32, causal: bool,
9527                                      window: usize, k_tok_bytes: usize, v_tok_bytes: usize)
9528                                      -> Result<(), Box<dyn std::error::Error>> {
9529        assert_eq!(head_dim, 128, "fa_prefill_view_ws_w_hd128: only the hd128 twin is stamped");
9530        if portable_mma_gated() {
9531            return self.sdpa_naive_w_quantized_view(q, k, v, o, head_dim, n_head, n_head_kv,
9532                                                    t, t_kv, scale, causal, window,
9533                                                    k_tok_bytes, v_tok_bytes);
9534        }
9535        const BLOCK_Q: usize = 64; const BK: usize = 32;
9536        let kv_dim_k = n_head_kv * head_dim;
9537        let kv_dim_v = n_head_kv * head_dim;
9538        let k_ws_bytes = t_kv * kv_dim_k * 2;   // bf16
9539        let v_ws_bytes = t_kv * kv_dim_v * 2;
9540        let mut guard = self.prime_deqw_ws.lock().unwrap();
9541        let need_grow = match guard.as_ref() {
9542            Some((kw, vw)) => kw.len() < k_ws_bytes || vw.len() < v_ws_bytes,
9543            None => true,
9544        };
9545        if need_grow {
9546            let grow = |cur: usize, need: usize| if cur >= need { cur } else { need };
9547            let (ck, cv) = guard.as_ref().map(|(a, b)| (a.len(), b.len())).unwrap_or((0, 0));
9548            *guard = Some((self.alloc_u8(grow(ck, k_ws_bytes))?, self.alloc_u8(grow(cv, v_ws_bytes))?));
9549        }
9550        let (kw, vw) = guard.as_mut().unwrap();
9551        // pass 1: dequant K+V once into the bf16 workspace (identical to fa_prefill_view_ws —
9552        // the workspace bytes are the SAME __float2bfloat16(dq(...)) values either way).
9553        {
9554            let f = self.func("fa_dequant_kv_ws_bf16");
9555            let total = (t_kv * (kv_dim_k + kv_dim_v)) as u64;
9556            let nblk = ((total + 255) / 256).min(65535 * 16) as u32;
9557            let cfg = LaunchConfig { grid_dim: (nblk.max(1), 1, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
9558            let (kdk, kdv, tkvi) = (kv_dim_k as i32, kv_dim_v as i32, t_kv as i32);
9559            let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
9560            let __s_b = self.gpu.stream();
9561            let mut b = __s_b.launch_builder(&f);
9562            b.arg(k).arg(v).arg(&mut *kw).arg(&mut *vw).arg(&kdk).arg(&kdv).arg(&tkvi).arg(&ktb).arg(&vtb);
9563            unsafe { b.launch(cfg)?; }
9564        }
9565        // pass 2: the WINDOWED qw twin (db default, same as the unwindowed wrapper).
9566        let db = std::env::var("MEMRA_PRIME_DEQW_DB").map(|v| v != "0").unwrap_or(true);
9567        {
9568            let f = self.func(if db { "fa_prefill_qw_db_w_hd128" } else { "fa_prefill_qw_w_hd128" });
9569            let shmem = if db {
9570                (2 * (4 * BK * head_dim + BLOCK_Q * BK) + 4 * BLOCK_Q) as u32
9571            } else {
9572                (2 * (2 * BK * head_dim + BLOCK_Q * BK)
9573                       + 4 * (BLOCK_Q * BK + 2 * BLOCK_Q)) as u32
9574            };
9575            use cudarc::driver::sys::CUfunction_attribute_enum as A;
9576            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9577            let cfg = LaunchConfig {
9578                grid_dim: ((t as u32 + BLOCK_Q as u32 - 1) / BLOCK_Q as u32, n_head as u32, 1),
9579                block_dim: (32, 4, 1), shared_mem_bytes: shmem,
9580            };
9581            let (hd, nh, nhkv, ti, tkvi, cz) = (head_dim as i32, n_head as i32, n_head_kv as i32, t as i32, t_kv as i32, causal as i32);
9582            let (kdk, kdv, wnd) = (kv_dim_k as i32, kv_dim_v as i32, window as i32);
9583            let __s_b = self.gpu.stream();
9584            let mut b = __s_b.launch_builder(&f);
9585            b.arg(q).arg(&*kw).arg(&*vw).arg(o).arg(&hd).arg(&nh).arg(&nhkv).arg(&ti).arg(&tkvi).arg(&scale).arg(&cz)
9586             .arg(&kdk).arg(&kdv).arg(&wnd);
9587            unsafe { b.launch(cfg)?; }
9588        }
9589        Ok(())
9590    }
9591
9592    /// FA decode (T=1 split-K) over the resident QUANTIZED KV cache (q8_0 K / q5_1 V) as u8 views.
9593    /// Replaces sdpa_naive_view for decode; inline-dequants per element. k_tok_bytes/v_tok_bytes are
9594    /// the per-token byte strides (differ: q8_0=34*nblk, q5_1=24*nblk per token).
9595    pub fn fa_decode(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
9596                     v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
9597                     head_dim: usize, n_head: usize, n_head_kv: usize, t_kv: usize, scale: f32,
9598                     k_tok_bytes: usize, v_tok_bytes: usize)
9599                     -> Result<(), Box<dyn std::error::Error>> {
9600        self.fa_decode_kvmod(q, k, v, o, head_dim, n_head, n_head_kv, t_kv, scale,
9601                             k_tok_bytes, v_tok_bytes, false)
9602    }
9603
9604    /// `fa_decode` with an explicit fp8-module flag (`g`): gemma windowed layers under
9605    /// MEMRA_GEMMA_WKV read an e4m3 cache — every kernel must come from the kf8vf8 module
9606    /// and the v4 lane (q8_0-hardcoded staging) is excluded.
9607    #[allow(clippy::too_many_arguments)]
9608    /// UNIFIED scalar decode launch (fa_decode_f32, nullable-ctr): ONE symbol for host-len
9609    /// (kvmod eager) and device-len (graph/stream) callers — the textually-identical f32_dc
9610    /// twin compiled apart and its ULP drift flipped 31B verify argmaxes (2026-07-12).
9611    #[allow(clippy::too_many_arguments)]
9612    #[allow(clippy::too_many_arguments)]
9613    fn fa_decode_scalar_unified(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
9614                                v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
9615                                head_dim: usize, n_head: usize, n_head_kv: usize,
9616                                t_kv_host: usize, t_kv_dev: Option<&CudaSlice<i32>>,
9617                                scale: f32, n_splits: usize, split_keys: usize,
9618                                k_tok_bytes: usize, v_tok_bytes: usize, g: bool,
9619                                part_o: &mut CudaSlice<f32>, part_m: &mut CudaSlice<f32>,
9620                                part_l: &mut CudaSlice<f32>,
9621                                q8_out: Option<(&mut CudaSlice<i8>, &mut CudaSlice<f32>)>)
9622                                -> Result<(), Box<dyn std::error::Error>> {
9623        let f = if g { self.func_g("fa_decode_f32") } else { self.fa_func("fa_decode_f32", head_dim) };
9624        let cfg = LaunchConfig { grid_dim: (n_head as u32, n_splits as u32, 1),
9625            block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: (4 * (head_dim + 32)) as u32 };
9626        let (hd, nh, nhkv, nsp) = (head_dim as i32, n_head as i32, n_head_kv as i32, n_splits as i32);
9627        let (ktb, vtb, tkvi, ski) = (k_tok_bytes as i64, v_tok_bytes as i64, t_kv_host as i32,
9628                                     split_keys as i32);
9629        let __s_b = self.gpu.stream();
9630        let mut b = __s_b.launch_builder(&f);
9631        match t_kv_dev {
9632            Some(d) => { b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
9633                          .arg(&hd).arg(&nh).arg(&nhkv).arg(&tkvi).arg(d).arg(&scale).arg(&nsp)
9634                          .arg(&ski).arg(&ktb).arg(&vtb);
9635                         unsafe { b.launch(cfg)?; } }
9636            None => { let null: u64 = 0;
9637                      b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
9638                       .arg(&hd).arg(&nh).arg(&nhkv).arg(&tkvi).arg(&null).arg(&scale).arg(&nsp)
9639                       .arg(&ski).arg(&ktb).arg(&vtb);
9640                      unsafe { b.launch(cfg)?; } }
9641        }
9642        let cfg2 = LaunchConfig { grid_dim: (n_head as u32, 1, 1),
9643            block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 };
9644        if let Some((oq, od)) = q8_out {
9645            // wave-5b: q8-emitting combine — the wo matmul_pre consumes the pair directly.
9646            let fc = if g { self.func_g("fa_decode_combine_q8_1") }
9647                     else { self.fa_func("fa_decode_combine_q8_1", head_dim) };
9648            let __s_b2 = self.gpu.stream();
9649            let mut b2 = __s_b2.launch_builder(&fc);
9650            b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(oq).arg(od).arg(&hd).arg(&nh).arg(&nsp);
9651            unsafe { b2.launch(cfg2)?; }
9652            return Ok(());
9653        }
9654        let fc = if g { self.func_g("fa_decode_combine_f32") } else { self.fa_func("fa_decode_combine_f32", head_dim) };
9655        let __s_b2 = self.gpu.stream();
9656        let mut b2 = __s_b2.launch_builder(&fc);
9657        b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(o).arg(&hd).arg(&nh).arg(&nsp);
9658        unsafe { b2.launch(cfg2)?; }
9659        Ok(())
9660    }
9661
9662    pub fn fa_decode_kvmod(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
9663                     v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
9664                     head_dim: usize, n_head: usize, n_head_kv: usize, t_kv: usize, scale: f32,
9665                     k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
9666                     -> Result<(), Box<dyn std::error::Error>> {
9667        // PERF-4: the warp-per-token vec path replaces the scalar element-per-thread fa_decode_f32 —
9668        // warp-per-token fa_decode_vec_q (grid=(n_head_kv,n_splits), block=(32,gqa_ratio)).
9669        // The block dequants each KV tile ONCE into smem (bf16) and broadcasts to all gqa Q-head
9670        // warps -> each KV byte leaves HBM/L2 ~1x/group (vs 4x). ARGS identical; func/grid/block/
9671        // smem/n_splits differ. fa_decode_f32 stays the bit-reference fallback. Combine is shared.
9672        //
9673        // SPLIT-K: the scalar path has grid.x=n_head (32) blocks; the vec path only has
9674        // grid.x=n_head_kv (8). To avoid starving the GPU at mid ctx, the vec path splits MORE
9675        // aggressively (64 keys/split vs 256) so grid.y rises and 8*n_splits fills the SMs.
9676        // At VERY short ctx (t_kv<96) even 1 split can't fill the GPU from 8 KV heads, so the
9677        // broadcast can't beat the scalar path's 4x-more-blocks latency hiding — fall back to
9678        // scalar there (measured crossover: vec 0.68x at t_kv=64, 1.23x at t_kv=96, 2.2x at 256).
9679        // DEFAULT-ON (2026-06-28): clean clock-locked sweep proved vec beats scalar at every
9680        // t_kv>=96 and the gain WIDENS with ctx (graph decode: +9.5% @128, +11.6% @512, +11.8%
9681        // @2048) — the KV-byte-broadcast (4x fewer HBM reads/group) compounds as attention grows.
9682        // MEMRA_NO_FA_VEC forces the scalar bit-reference. Below FA_VEC_MIN_TKV the scalar path's
9683        // 4x-more-blocks (grid.x=n_head=32 vs n_head_kv=8) hides latency better, so keep scalar there.
9684        // g + no-v4: the g-module REGISTER twin mis-decodes the gemma windowed shape
9685        // (root-cause open, jsonl) — only reachable by forcing v4 off (MEMRA_FA_V4_MAX);
9686        // fall to the exact scalar there instead of the broken register arm.
9687        let mut fa_vec = std::env::var("MEMRA_NO_FA_VEC").is_err() && t_kv >= fa_vec_min_tkv();
9688        // hd256 under g: v4-or-scalar. hd128/other under g ride the REGISTER g-lane (the
9689        // dq_K_lane/dq_V_lane macros are format-aware; v3 is format-gated off, v2/smem
9690        // arms are excluded under g). Mirrored in kvmod / fa_decode_dc / fa_geom_eager.
9691        if g && head_dim == 256 && !fa_v4_at(t_kv) { fa_vec = false; }
9692        let sp = fa_split_keys(t_kv, n_head_kv);
9693        let n_splits = if fa_vec { ((t_kv + sp - 1) / sp).max(1) } else { ((t_kv + 255) / 256).max(1) };
9694        let o_len = n_head * n_splits * head_dim;
9695        let ml_len = n_head * n_splits;
9696        let mut part_guard = self.fa_part_pool.lock().unwrap();
9697        if part_guard.as_ref().map(|pp| pp.0.len() < o_len || pp.1.len() < ml_len).unwrap_or(true) {
9698            // RETIRE-ON-GROW, never free (#68 root cause, 2026-08-04): captured graphs (the
9699            // per-session persistent draft graph, the decode/prime graph doors) BAKE these pool
9700            // buffer addresses. Dropping the old buffers on grow returns them to the async pool,
9701            // later live allocations land at those addresses, and the next graph REPLAY writes
9702            // its fa partials over them — the ST serve-spec corruption (acceptance collapse +
9703            // output corruption began the burst after the trunk's t_kv growth first realloc'd
9704            // this pool past the draft-capture size; research/fp8ship-20260804). Retiring keeps
9705            // the baked addresses alive (single-stream: eager writes the new buffers, replays
9706            // touch only the old — never concurrently). Doubling growth bounds retired VRAM
9707            // (total retired < final size).
9708            let old = part_guard.take();
9709            let (co, cm) = old.as_ref().map(|pp| (pp.0.len(), pp.1.len())).unwrap_or((0, 0));
9710            if let Some(old) = old {
9711                self.fa_part_retired.lock().unwrap().push(old);
9712            }
9713            if std::env::var("MEMRA_DEBUG_FAPOOL").is_ok() {
9714                eprintln!("[fa-pool] REALLOC o {} -> {} ml {} -> {} (old retired)", co, o_len, cm, ml_len);
9715            }
9716            *part_guard = Some((self.alloc_uninit::<f32>(o_len.max(2 * co))?,
9717                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?,
9718                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?));
9719        }
9720        let pg = part_guard.as_mut().unwrap();
9721        self.gpu.stream().memset_zeros(&mut pg.0.slice_mut(0..o_len))?;
9722        self.gpu.stream().memset_zeros(&mut pg.1.slice_mut(0..ml_len))?;
9723        self.gpu.stream().memset_zeros(&mut pg.2.slice_mut(0..ml_len))?;
9724        let (part_o, part_m, part_l) = (&mut pg.0, &mut pg.1, &mut pg.2);
9725        let (part_o, part_m, part_l) = (&mut *part_o, &mut *part_m, &mut *part_l);
9726        let (hd, nh, nhkv, tkvi, nsp) = (head_dim as i32, n_head as i32, n_head_kv as i32, t_kv as i32, n_splits as i32);
9727        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
9728        // The vec kernel holds head_dim/32 register accumulators (FA_DEC_MAX_DPL=8 -> head_dim<=256).
9729        // All shipped models use head_dim=256; fall back to scalar for anything wider rather than
9730        // silently truncating the accumulator.
9731        let fa_vec = fa_vec && head_dim <= 512 && head_dim % 32 == 0;
9732        // hd-512 vec crossover (MEMRA_FA512_MIN, default 512): the DPL16 twin wins at depth
9733        // (82.5 -> vec at 1736) but the scalar's more-blocks latency hiding wins at tiny t_kv
9734        // (the same scalar-floor physics as hd256's old 96 floor; short-ctx plain regressed
9735        // 178.4 -> 173.7 when 512 rode vec unconditionally).
9736        let fa512_min = fa512_min_tkv();
9737        // FA-DEEP pick (bit-identical twins, see fa_deep_at): default module only — the
9738        // g-module keeps the v4 pick (its class is not the depth-decay class).
9739        let deep = fa_vec && head_dim == 256 && fa_v4_at(t_kv) && !g
9740            && fa_deep_at(t_kv) && !matches!(fa_v4_mode(), "noB3" | "stage");
9741        let (f, cfg) = if fa_vec && head_dim == 512 && t_kv >= fa512_min {
9742            // gemma4 globals (hd 512): the DPL16 register twin (fa_decode_vec_q body with a
9743            // 16-slot accumulator ceiling). Scalar fallback measured 82.5us/layer at 1736 ctx.
9744            let gqa = (n_head / n_head_kv).max(1) as u32;
9745            let fv = self.fa_func("fa_decode_vec_q_dpl16", head_dim);
9746            (fv, LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
9747                 block_dim: (32, gqa, 1), shared_mem_bytes: 0 })
9748        } else if fa_vec && head_dim <= 256 {
9749            let gqa = (n_head / n_head_kv).max(1) as u32;
9750            // DEEP-CTX smem twin (2026-07-05): the register-dequant path's GQA reuse rides L2,
9751            // which holds to ~8k ctx but dies at 40k (layer KV ~37MB) — the 4 GQA warps then
9752            // re-read every KV byte from DRAM (4x traffic). Above MEMRA_FA_SMEM_TKV (default
9753            // 1024 — the 2026-07-05 crossover re-sweep on real prompts: p3 spec 73.8->79.2 at
9754            // 2048, flat down to 512, p2 +5%, p1/9B unchanged; the ARC-A probe's synthetic
9755            // 2.1x smem-at-all-depths pointed here; 0=never) dispatch the smem-broadcast twin:
9756            // dequant each tile ONCE per block.
9757            // Bit-identical per (token,split): same bf16 round-trip, same accumulation order,
9758            // same partial layout -> same combine. Short/mid ctx keeps the register path (it won
9759            // there by 12x — latency, not bandwidth, rules small KV).
9760            static SMEM_TKV: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
9761            let smem_tkv = *SMEM_TKV.get_or_init(|| {
9762                std::env::var("MEMRA_FA_SMEM_TKV").ok().and_then(|v| v.parse().ok())
9763                    .unwrap_or_else(|| FA_SMEM_TKV_DEFAULT.load(std::sync::atomic::Ordering::Relaxed))
9764            });
9765            if fa_v4_at(t_kv) && head_dim == 256 {
9766                // FA v4 lane (2026-07-10): key-per-lane score phase, zero shuffles per key.
9767                // NEW NUMERIC CONFIG (chunk-serial per-key dot) — battery-arbitrated.
9768                // g (fp8-windowed): the v4 staging is format-aware (2026-07-12) — kf8vf8 module.
9769                let v4name = match fa_v4_mode() {
9770                    "noB3" => "fa_decode_vec_q_v4_noB3",     // phase probe (WRONG OUTPUT)
9771                    "stage" => "fa_decode_vec_q_v4_stage",   // phase probe (WRONG OUTPUT)
9772                    _ if deep => "fa_decode_vec_q_v4_deep",
9773                    _ => "fa_decode_vec_q_v4",
9774                };
9775                let fv = if g { self.func_g(v4name) } else { self.func(v4name) };
9776                // fa_v4_smem (deep: fa_v4_deep_smem, +640B row pads) + sV (g: raw e4m3 sV
9777                // tile = 1B/elem — half the smem, 3->5 blocks/SM)
9778                let shmem = (if deep { 12160 } else { 11520 }
9779                             + 32 * head_dim * if g { 1 } else { 2 }) as u32;
9780                use cudarc::driver::sys::CUfunction_attribute_enum as A;
9781                fv.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9782                (fv,
9783                 LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
9784                     block_dim: (32, gqa, 1), shared_mem_bytes: shmem })
9785            } else if fa_v3_active(head_dim) {
9786                // FA v3 lane: dp4a-K hybrid (register-quantized Q, raw q8_0 K, staged-V kept).
9787                // smem = sV only (half of v2's).
9788                let fv = if g { self.func_g("fa_decode_vec_q_v3") } else { self.func("fa_decode_vec_q_v3") };
9789                let shmem = (32 * head_dim * 2) as u32;      // sV bf16 [FA_DEC_TILE=32][hd]
9790                (fv,
9791                 LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
9792                     block_dim: (32, gqa, 1), shared_mem_bytes: shmem })
9793            } else if fa_v2_on() {
9794                // FAVENDOR lane: llama fattn-vec tile-batched softmax + wide-load staging on
9795                // OUR smem KV broadcast. Replaces BOTH per-key twins when on; same grid/block/
9796                // partials; same 32KB sK+sV tile as the smem twin.
9797                let fv = if g { self.func_g("fa_decode_vec_q_v2") } else { self.func("fa_decode_vec_q_v2") };
9798                let shmem = (2 * 32 * head_dim * 2) as u32;   // sK+sV bf16 [FA_DEC_TILE=32][hd]
9799                (fv,
9800                 LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
9801                     block_dim: (32, gqa, 1), shared_mem_bytes: shmem })
9802            } else if smem_tkv > 0 && t_kv >= smem_tkv && !g
9803                && !(head_dim == 512 && Self::gkv_on()) {
9804                // (fp8 exclusions: the smem twin's V-stage is q5_1-hardcoded — neither the wkv
9805                // windowed layers (g) nor the gkv globals (hd512) may be forced onto it via
9806                // MEMRA_FA_SMEM_TKV; they fall through to the format-clean register/scalar arms.)
9807                let fv = if g { self.func_g("fa_decode_vec_q_smem") } else { self.func("fa_decode_vec_q_smem") };
9808                let shmem = (2 * 32 * head_dim * 2) as u32;   // sK+sV bf16 [FA_DEC_TILE=32][hd]
9809                use cudarc::driver::sys::CUfunction_attribute_enum as A;
9810                fv.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9811                (fv,
9812                 LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
9813                     block_dim: (32, gqa, 1), shared_mem_bytes: shmem })
9814            } else {
9815                // REGISTER-DEQUANT kernel (2026-07-03): per-warp direct q8_0/q5_1 register
9816                // dequant, zero dynamic shared memory.
9817                let fv = if g { self.func_g("fa_decode_vec_q") } else { self.func("fa_decode_vec_q") };
9818                (fv,
9819                 LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
9820                     block_dim: (32, gqa, 1), shared_mem_bytes: 0 })
9821            }
9822        } else {
9823            // UNIFIED scalar (nullable-ctr symbol shared with graph/stream callers). The
9824            // split ladder value rides along so ns_eff reproduces THIS n_splits in-kernel.
9825            return self.fa_decode_scalar_unified(q, k, v, o, head_dim, n_head, n_head_kv,
9826                                                 t_kv, None, scale, n_splits,
9827                                                 if fa_vec { sp } else { 256 },
9828                                                 k_tok_bytes, v_tok_bytes, g,
9829                                                 part_o, part_m, part_l, None);
9830        };
9831        let __s_b = self.gpu.stream();
9832        let mut b = __s_b.launch_builder(&f);
9833        b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
9834         .arg(&hd).arg(&nh).arg(&nhkv).arg(&tkvi).arg(&scale).arg(&nsp).arg(&ktb).arg(&vtb);
9835        unsafe { b.launch(cfg)?; }
9836        // (combine re-tile refuted in the fa-deep lane — flat/worse both shapes; the v4
9837        // combine stays for all arms. Receipts research/fa-decode-deep-20260802/.)
9838        let (fc, cfg2) = (if g { self.func_g("fa_decode_combine_f32") } else { self.fa_func("fa_decode_combine_f32", head_dim) },
9839            LaunchConfig { grid_dim: (n_head as u32, 1, 1), block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 });
9840        let __s_b2 = self.gpu.stream();
9841        let mut b2 = __s_b2.launch_builder(&fc);
9842        b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(o).arg(&hd).arg(&nh).arg(&nsp);
9843        unsafe { b2.launch(cfg2)?; }
9844        Ok(())
9845    }
9846
9847    /// BATCHED-TICK increment 2: ONE fa_decode launch covering ALL B sequences of the
9848    /// batched decode step (blockIdx.z = sequence). Per-seq K/V cache bases ride a device
9849    /// pointer table (`kv_ptrs`, [2B] interleaved k0,v0,...); per-seq key bounds ride the
9850    /// tick's position table (`pos_seq`, T_kv = pos+1). v4-lane only: the CALLER
9851    /// (decode_batch) gates every row through `fa_seqs_eligible` AND one `fa_split_keys`
9852    /// rung (`split_keys`), so each sequence's split partition, key walk and combine order
9853    /// reproduce its per-seq eager v4 program exactly (kernel-check pins seqs-vs-loop bit
9854    /// identity; decode-batch-gate strict pins the whole tick vs decode_step_h).
9855    /// q is the stacked [B, n_head, head_dim] tick buffer read in place (no per-seq q
9856    /// copies); o is written [B, n_head, head_dim] in place (no per-seq a copies).
9857    #[allow(clippy::too_many_arguments)]
9858    pub fn fa_decode_batch_seqs_v4(&self, q: &CudaSlice<f32>,
9859                                   kv_ptrs: &cudarc::driver::CudaView<u64>,
9860                                   pos_seq: &CudaSlice<i32>, o: &mut CudaSlice<f32>,
9861                                   head_dim: usize, n_head: usize, n_head_kv: usize,
9862                                   b_n: usize, t_kv_max: usize, scale: f32,
9863                                   split_keys: usize, k_tok_bytes: usize, v_tok_bytes: usize)
9864                                   -> Result<(), Box<dyn std::error::Error>> {
9865        debug_assert!(head_dim == 256, "seqs twin is v4-stamped (hd256 only)");
9866        let n_splits_max = (t_kv_max + split_keys - 1) / split_keys;
9867        let o_len = b_n * n_head * n_splits_max * head_dim;
9868        let ml_len = b_n * n_head * n_splits_max;
9869        let mut part_guard = self.fa_part_pool.lock().unwrap();
9870        if part_guard.as_ref().map(|pp| pp.0.len() < o_len || pp.1.len() < ml_len).unwrap_or(true) {
9871            // RETIRE-ON-GROW, never free (#68 root cause, 2026-08-04): captured graphs (the
9872            // per-session persistent draft graph, the decode/prime graph doors) BAKE these pool
9873            // buffer addresses. Dropping the old buffers on grow returns them to the async pool,
9874            // later live allocations land at those addresses, and the next graph REPLAY writes
9875            // its fa partials over them — the ST serve-spec corruption (acceptance collapse +
9876            // output corruption began the burst after the trunk's t_kv growth first realloc'd
9877            // this pool past the draft-capture size; research/fp8ship-20260804). Retiring keeps
9878            // the baked addresses alive (single-stream: eager writes the new buffers, replays
9879            // touch only the old — never concurrently). Doubling growth bounds retired VRAM
9880            // (total retired < final size).
9881            let old = part_guard.take();
9882            let (co, cm) = old.as_ref().map(|pp| (pp.0.len(), pp.1.len())).unwrap_or((0, 0));
9883            if let Some(old) = old {
9884                self.fa_part_retired.lock().unwrap().push(old);
9885            }
9886            if std::env::var("MEMRA_DEBUG_FAPOOL").is_ok() {
9887                eprintln!("[fa-pool] REALLOC o {} -> {} ml {} -> {} (old retired)", co, o_len, cm, ml_len);
9888            }
9889            *part_guard = Some((self.alloc_uninit::<f32>(o_len.max(2 * co))?,
9890                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?,
9891                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?));
9892        }
9893        let pg = part_guard.as_mut().unwrap();
9894        self.gpu.stream().memset_zeros(&mut pg.0.slice_mut(0..o_len))?;
9895        self.gpu.stream().memset_zeros(&mut pg.1.slice_mut(0..ml_len))?;
9896        self.gpu.stream().memset_zeros(&mut pg.2.slice_mut(0..ml_len))?;
9897        let (part_o, part_m, part_l) = (&mut pg.0, &mut pg.1, &mut pg.2);
9898        let (hd, nh, nhkv) = (head_dim as i32, n_head as i32, n_head_kv as i32);
9899        let (nspm, spk) = (n_splits_max as i32, split_keys as i32);
9900        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
9901        let gqa = (n_head / n_head_kv).max(1) as u32;
9902        let f = self.func("fa_decode_vec_q_seqs_v4");
9903        // fa_v4_smem (11520B) + sV bf16 tile — the v4 eager arm's sizing on the default module.
9904        let shmem = (11520 + 32 * head_dim * 2) as u32;
9905        use cudarc::driver::sys::CUfunction_attribute_enum as A;
9906        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
9907        let cfg = LaunchConfig { grid_dim: (n_head_kv as u32, n_splits_max as u32, b_n as u32),
9908            block_dim: (32, gqa, 1), shared_mem_bytes: shmem };
9909        {
9910            let __s_b = self.gpu.stream();
9911            let mut b = __s_b.launch_builder(&f);
9912            b.arg(q).arg(kv_ptrs).arg(pos_seq).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
9913             .arg(&hd).arg(&nh).arg(&nhkv).arg(&scale).arg(&nspm).arg(&spk).arg(&ktb).arg(&vtb);
9914            unsafe { b.launch(cfg)?; }
9915        }
9916        let fc = self.func("fa_decode_combine_seqs");
9917        let cfg2 = LaunchConfig { grid_dim: (n_head as u32, b_n as u32, 1),
9918            block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 };
9919        let __s_b2 = self.gpu.stream();
9920        let mut b2 = __s_b2.launch_builder(&fc);
9921        b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(o).arg(&hd).arg(&nh)
9922          .arg(pos_seq).arg(&nspm).arg(&spk);
9923        unsafe { b2.launch(cfg2)?; }
9924        Ok(())
9925    }
9926
9927    /// BATCHED-TICK increment 2: z-batched decode KV append — one launch appends this
9928    /// step's B rows, each into ITS OWN sequence cache at slot pos_seq[z], through the same
9929    /// [2B] interleaved pointer table the seqs FA reads. Each (block, z) warp executes the
9930    /// per-token appender's exact warp program on row z of the stacked [B, kv_dim] k/v —
9931    /// written cache bytes are BIT-IDENTICAL to the B per-seq calls it replaces
9932    /// (kernel-check pins the bytes). Default flash module only (callers exclude fp8-KV).
9933    #[allow(clippy::too_many_arguments)]
9934    pub fn append_kv_quantized_seqs(&self, k_rows: &CudaSlice<f32>, v_rows: &CudaSlice<f32>,
9935                                    kv_ptrs: &cudarc::driver::CudaView<u64>,
9936                                    pos_seq: &CudaSlice<i32>, b_n: usize,
9937                                    kv_dim_k: usize, kv_dim_v: usize,
9938                                    k_tok_bytes: usize, v_tok_bytes: usize)
9939                                    -> Result<(), Box<dyn std::error::Error>> {
9940        let f = self.func("append_quantize_kv_q8_0_q5_1_seqs");
9941        let nblk = (kv_dim_k.max(kv_dim_v) / 32) as u32;
9942        let cfg = LaunchConfig { grid_dim: (nblk, b_n as u32, 1),
9943            block_dim: (32, 1, 1), shared_mem_bytes: 0 };
9944        let (kdk, kdv) = (kv_dim_k as i32, kv_dim_v as i32);
9945        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
9946        let __s_b = self.gpu.stream();
9947        let mut b = __s_b.launch_builder(&f);
9948        b.arg(k_rows).arg(v_rows).arg(kv_ptrs).arg(pos_seq)
9949         .arg(&kdk).arg(&kdv).arg(&ktb).arg(&vtb);
9950        unsafe { b.launch(cfg)?; }
9951        Ok(())
9952    }
9953
9954    /// True iff the MULTI-ROW verify FA (`fa_decode_rows`) is usable for a verify batch whose
9955    /// FIRST row attends `base_len + 1` keys: every row must take the SAME kernel eager decode
9956    /// would (the vec path) — mirrors fa_decode's gate exactly (MEMRA_NO_FA_VEC + FA_VEC_MIN_TKV +
9957    /// head_dim), evaluated at the MINIMUM row bound so no row could have picked scalar.
9958    /// MEMRA_FA_ROWS_OFF=1 is the A/B + fallback seam (per-row loop).
9959    pub fn fa_rows_eligible(&self, base_len: usize, head_dim: usize) -> bool {
9960        std::env::var("MEMRA_NO_FA_VEC").is_err()
9961            && std::env::var("MEMRA_FA_ROWS_OFF").is_err()
9962            && base_len + 1 >= fa_vec_min_tkv()
9963            && head_dim <= 256 && head_dim % 32 == 0
9964    }
9965
9966    /// MULTI-ROW verify FA: run fa_decode_vec_q's EXACT per-row program for T causal query rows
9967    /// (row r attends keys [0..base_len+r+1)) in ONE kernel launch with grid.z = row, plus ONE
9968    /// row-batched combine. Replaces the T separate (fa_decode + combine) launches of the spec
9969    /// verify — same per-row split partition (n_splits_r = ceil(t_kv_r/split_keys), the
9970    /// fa_split_keys formula), same key-walk order, same reduce shapes => bit-identical outputs
9971    /// per row (kernel-check pins rows-vs-loop byte identity; run-spec is the end gate).
9972    /// Caller must have checked `fa_rows_eligible(base_len, head_dim)`.
9973    /// q is the verify's token-major [T, n_head, head_dim] stack; o is written [T, n_head, head_dim].
9974    #[allow(clippy::too_many_arguments)]
9975    pub fn fa_decode_rows(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
9976                          v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
9977                          head_dim: usize, n_head: usize, n_head_kv: usize,
9978                          base_len: usize, t: usize, scale: f32,
9979                          k_tok_bytes: usize, v_tok_bytes: usize,
9980                          // hd512 dpl16 twin is DEVICE-LEN (graph arc): base_dev/plus feed the
9981                          // kernel; host base_len keeps sizing the splits/partials. hd256 twins
9982                          // keep the host arg. None is a bug for hd512 (asserted below).
9983                          base_dev: Option<(&CudaSlice<i32>, i32)>,
9984                          // K and V planes hold the same values (gemma globals, wv:=wk): pick
9985                          // the _kv twin — V plane never read, value rides the q8_0 key dq.
9986                          kv_shared: bool,
9987                          // this layer's cache is e4m3 (gemma windowed under wkv): resolve the
9988                          // hd256 rows kernel from the kf8vf8 module. PER-CALL — a global env
9989                          // check here hijacked qwen/kernel-check hd256 rows (8 FAILs, 230ebbe).
9990                          g: bool,
9991                          // t=1 decode arm only: emit (int8, per-32 scales) from the dc combine
9992                          // (hd512 path) — the standalone quantize launch folds away.
9993                          mut q8_out: Option<(&mut CudaSlice<i8>, &mut CudaSlice<f32>)>)
9994                          -> Result<(), Box<dyn std::error::Error>> {
9995        debug_assert!(base_len + 1 >= fa_vec_min_tkv() && head_dim <= 512 && head_dim % 32 == 0);
9996        let t_kv_max = base_len + t;                       // LAST row's key bound
9997        let mut sp = fa_split_keys(t_kv_max, n_head_kv);   // env/default — same value every row
9998        // hd512 split override (MEMRA_FA_SP512, 2026-07-11): gemma globals have n_head_kv=2 so
9999        // the grid is (2 x n_splits) — at depth ~29 splits = 58 blocks on 82 SMs (half idle,
10000        // rows_dpl16 8x off its byte floor). EVERY gemma hd512 caller shares THIS wrapper
10001        // (parity law), so the partition is freely tunable — verify and decode move together.
10002        if head_dim == 512 {
10003            static SP512: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
10004            // default 16 (2026-07-11 depth sweep, N=2: plain 155.4->156.5, depth spec
10005            // 236.9->250.4; 12/24/32 all worse). hd512 exists only on gemma globals.
10006            let v = *SP512.get_or_init(|| std::env::var("MEMRA_FA_SP512").ok()
10007                .and_then(|x| x.parse().ok()).unwrap_or(0));
10008            sp = if v >= 8 { v } else { FA_SP512_DEFAULT.load(std::sync::atomic::Ordering::Relaxed) };
10009        }
10010        let (hd, nh, nhkv) = (head_dim as i32, n_head as i32, n_head_kv as i32);
10011        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
10012        let gqa = (n_head / n_head_kv).max(1) as u32;
10013        // LADDER-RUNG STRADDLE FIX (issue #10, 2026-07-13, g7e-proven): one sp for every row
10014        // diverges from eager decode when a split-ladder rung falls INSIDE the batch — row r's
10015        // eager twin used fa_split_keys(t_kv_r), the batch used fa_split_keys(t_kv_max), and
10016        // the different partition changes the combine's FP order (greedy tie flips at depth;
10017        // MEMRA_FA_SPLIT=64 pin -> PASS on the exact g7e failing config). Fix: group
10018        // consecutive rows by their OWN ladder value and launch once per group — each row then
10019        // executes the exact per-row program eager ran. Rungs land once per doubling, so this
10020        // is 1 launch in the common case and 2 on a crossing round. hd512 keeps one group (its
10021        // sp override is t_kv-independent by construction).
10022        let mut groups: Vec<(usize, usize, usize)> = Vec::new();   // (row0, t_g, sp_g)
10023        if head_dim == 512 || fa_split_keys(base_len + 1, n_head_kv) == sp {
10024            groups.push((0, t, sp));
10025        } else {
10026            let mut r0 = 0usize;
10027            while r0 < t {
10028                let sp_g = fa_split_keys(base_len + r0 + 1, n_head_kv);
10029                let mut r1 = r0 + 1;
10030                while r1 < t && fa_split_keys(base_len + r1 + 1, n_head_kv) == sp_g { r1 += 1; }
10031                groups.push((r0, r1 - r0, sp_g));
10032                r0 = r1;
10033            }
10034        }
10035        // Deep-ctx smem twin for the VERIFY rows (2026-07-05): same threshold + rationale as
10036        // fa_decode's dispatch — at 40k the register path's GQA L2-reuse premise is dead and the
10037        // verify multiplies the 4x DRAM re-read by T rows. Bit-identical per (row,token,split).
10038        static SMEM_TKV_R: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
10039        let smem_tkv = *SMEM_TKV_R.get_or_init(|| {
10040            std::env::var("MEMRA_FA_SMEM_TKV").ok().and_then(|v| v.parse().ok())
10041                .unwrap_or_else(|| FA_SMEM_TKV_DEFAULT.load(std::sync::atomic::Ordering::Relaxed))
10042        });
10043        let v4 = fa_v4_at(base_len + t) && head_dim == 256;
10044        let v3 = fa_v3_active(head_dim);
10045        let smem_rows = head_dim <= 256 && !v3 && !fa_v2_on() && smem_tkv > 0 && t_kv_max >= smem_tkv;
10046        // kv_shared twin RETIRED (2026-07-11 depth run-gen gate): the wv:=wk premise fails
10047        // POST-cache — cached K is k-normed+roped, cached V is not; the twin fed roped keys
10048        // in as values. Verify/decode/stream gates were blind (both sides shared the wrong
10049        // symbol — the parity law's blind spot); only prefill-vs-decode at depth caught it.
10050        let _ = kv_shared;
10051        // i2 twin: 2-key interleaved walk (MEMRA_FA_I2=0 reverts). i4 probed NEGATIVE
10052        // (157.3 vs 161.2 depth plain — register pressure past i2's sweet spot; jsonl).
10053        let i2 = head_dim == 512 && std::env::var("MEMRA_FA_I2").as_deref() != Ok("0");
10054        // v4-hd512 (MEMRA_FA_V512=1 opt-in, 2026-07-14): the v4 key-per-lane recipe on the
10055        // globals lane (depth profile: i2 ~4.6x off its byte floor — the v3-class
10056        // reduce-per-key latency signature). NEW NUMERIC CONFIG shared by every hd512
10057        // caller (decode+verify flip together); run-gen argmax + acceptance arbitrate.
10058        // T-BATCHED hd512 (DEFAULT ON 2026-07-14, MEMRA_FA_TB512=0 seam): one block per
10059        // (kv_head, split) stages its tile once and loops the rows over it — kills the
10060        // x t DRAM re-read of the full-ctx globals (depth cell +1.4%, plain flat, N=3
10061        // interleaved). FIXED absolute partition = NEW NUMERIC for the combine order,
10062        // shared by every hd512 caller through this wrapper (decode+verify flip together;
10063        // depth stream identical, acceptance unshifted, spec 256/256 x3 models).
10064        // Requires sp <= 32 (single staged tile; acc reused per row). The z-form v4_512
10065        // sibling (in-kernel dp4a port alone) probed FLAT — hd512 was DRAM-re-read-bound,
10066        // not unpack-bound; jsonl 2026-07-14.
10067        static TB512: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
10068        // gqa <= 16 = fa_v4_smem_512's q-array capacity; past it fall to the register twins.
10069        let tb512 = head_dim == 512 && sp <= 32 && n_head / n_head_kv.max(1) <= 16
10070            && *TB512.get_or_init(|| std::env::var("MEMRA_FA_TB512").as_deref() != Ok("0"));
10071        let fname = if tb512 { "fa_decode_vec_q_rows_v4_512_tb" }
10072                    else if i2 { "fa_decode_vec_q_rows_dpl16_i2" }
10073                    else if head_dim == 512 { "fa_decode_vec_q_rows_dpl16" }   // gemma globals (parity law)
10074                    else if v4 { "fa_decode_vec_q_rows_v4" }
10075                    else if v3 { "fa_decode_vec_q_rows_v3" }
10076                    else if fa_v2_on() { "fa_decode_vec_q_rows_v2" }
10077                    else if smem_rows { "fa_decode_vec_q_rows_smem" }
10078                    else { "fa_decode_vec_q_rows" };
10079        let f = if head_dim == 512 { self.fa_func(fname, head_dim) }
10080                else if g {
10081                    // FP8-WINDOWED: hd256 rows over an e4m3 cache — kf8vf8 module, SAME symbol
10082                    // choice as decode's kvmod dispatch (parity law: excluding v4 here paired
10083                    // g-module rows against decode's g-module v4 — different programs, short-VG
10084                    // maxdiff 2.0 / spec stream 0/128, 2026-07-12). rows_v4 is format-aware
10085                    // since fda9790; only the smem twin stays excluded (V-stage q5_1-only).
10086                    // hd128 (qwen fp8-KV) lands on the base/register rows via fname — the
10087                    // dq macros are format-aware.
10088                    self.func_g(if smem_rows { "fa_decode_vec_q_rows" } else { fname })
10089                }
10090                else { self.func(fname) };
10091        let shmem = if tb512 {
10092            // fa_v4_smem_512 (q 9KB gqa<=16 + k tile 18KB) + sV 32*512 (e4m3 module halves it)
10093            let gk = Self::gkv_on();
10094            let sh = (8192 + 1024 + 32 * 512 + 32 * 64
10095                      + 32 * head_dim * if gk { 1 } else { 2 }) as u32;
10096            use cudarc::driver::sys::CUfunction_attribute_enum as A;
10097            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
10098            sh
10099        } else if v4 || v3 || smem_rows || fa_v2_on() {
10100            // v4: fa_v4_smem (11.5KB) + sV; v3 stages sV only; v2/smem twins stage sK+sV.
10101            let sh = (if v4 { 11520 + 32 * head_dim * if g { 1 } else { 2 } }
10102                      else if v3 { 32 * head_dim * 2 } else { 2 * 32 * head_dim * 2 }) as u32;
10103            use cudarc::driver::sys::CUfunction_attribute_enum as A;
10104            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
10105            sh
10106        } else { 0 };
10107        // Per-GROUP launches (single group in the common case — identical to the pre-fix
10108        // single launch there): each group gets its own partials (the rows kernel indexes
10109        // partials by its LOCAL grid.z row) and q/o row-offset views.
10110        for &(r0, t_g, sp_g) in &groups {
10111            let n_splits_g = (base_len + r0 + t_g).div_ceil(sp_g);
10112            let (nspm, spk) = (n_splits_g as i32, sp_g as i32);
10113            let base_i = (base_len + r0) as i32;
10114            let o_len = t_g * n_head * n_splits_g * head_dim;
10115            let ml_len = t_g * n_head * n_splits_g;
10116            let mut part_guard = self.fa_part_pool.lock().unwrap();
10117        if part_guard.as_ref().map(|pp| pp.0.len() < o_len || pp.1.len() < ml_len).unwrap_or(true) {
10118            // RETIRE-ON-GROW, never free (#68 root cause, 2026-08-04): captured graphs (the
10119            // per-session persistent draft graph, the decode/prime graph doors) BAKE these pool
10120            // buffer addresses. Dropping the old buffers on grow returns them to the async pool,
10121            // later live allocations land at those addresses, and the next graph REPLAY writes
10122            // its fa partials over them — the ST serve-spec corruption (acceptance collapse +
10123            // output corruption began the burst after the trunk's t_kv growth first realloc'd
10124            // this pool past the draft-capture size; research/fp8ship-20260804). Retiring keeps
10125            // the baked addresses alive (single-stream: eager writes the new buffers, replays
10126            // touch only the old — never concurrently). Doubling growth bounds retired VRAM
10127            // (total retired < final size).
10128            let old = part_guard.take();
10129            let (co, cm) = old.as_ref().map(|pp| (pp.0.len(), pp.1.len())).unwrap_or((0, 0));
10130            if let Some(old) = old {
10131                self.fa_part_retired.lock().unwrap().push(old);
10132            }
10133            if std::env::var("MEMRA_DEBUG_FAPOOL").is_ok() {
10134                eprintln!("[fa-pool] REALLOC o {} -> {} ml {} -> {} (old retired)", co, o_len, cm, ml_len);
10135            }
10136            *part_guard = Some((self.alloc_uninit::<f32>(o_len.max(2 * co))?,
10137                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?,
10138                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?));
10139        }
10140        let pg = part_guard.as_mut().unwrap();
10141        self.gpu.stream().memset_zeros(&mut pg.0.slice_mut(0..o_len))?;
10142        self.gpu.stream().memset_zeros(&mut pg.1.slice_mut(0..ml_len))?;
10143        self.gpu.stream().memset_zeros(&mut pg.2.slice_mut(0..ml_len))?;
10144        let (part_o, part_m, part_l) = (&mut pg.0, &mut pg.1, &mut pg.2);
10145            let (part_o, part_m, part_l) = (&mut *part_o, &mut *part_m, &mut *part_l);
10146            let qv = self.view(q, t * n_head * head_dim);
10147            let q_g = qv.slice(r0 * n_head * head_dim..(r0 + t_g) * n_head * head_dim);
10148            let cfg = LaunchConfig { grid_dim: (n_head_kv as u32, n_splits_g as u32, t_g as u32),
10149                block_dim: (32, gqa, 1), shared_mem_bytes: shmem };
10150            {
10151                let __s_b = self.gpu.stream();
10152                let mut b = __s_b.launch_builder(&f);
10153                if tb512 {
10154                    // rows-inner launch: grid.z dropped, the kernel loops n_rows itself.
10155                    let (bd, plus) = base_dev.expect("hd512 rows twin requires a device base counter");
10156                    let plus_g = plus + r0 as i32;
10157                    let nr = t_g as i32;
10158                    if Self::pdl_on() && Self::pdl_wb_on() {
10159                        // wave-B2b: flavor mirrors fa_func(fname, 512) = gkv.
10160                        use cudarc::driver::{DevicePtr, DevicePtrMut};
10161                        let s = &self.gpu.stream();
10162                        let (pq, _b0) = q_g.device_ptr(s); let (pk, _b1) = k.device_ptr(s);
10163                        let (pv, _b2) = v.device_ptr(s);
10164                        let (po, _b3) = part_o.device_ptr_mut(s);
10165                        let (pm, _b4) = part_m.device_ptr_mut(s);
10166                        let (pl, _b5) = part_l.device_ptr_mut(s);
10167                        let (pb, _b6) = bd.device_ptr(s);
10168                        let mut ps = [
10169                            &pq as *const _ as *mut std::ffi::c_void, &pk as *const _ as *mut _,
10170                            &pv as *const _ as *mut _, &po as *const _ as *mut _,
10171                            &pm as *const _ as *mut _, &pl as *const _ as *mut _,
10172                            &hd as *const _ as *mut _, &nh as *const _ as *mut _,
10173                            &nhkv as *const _ as *mut _, &pb as *const _ as *mut _,
10174                            &plus_g as *const _ as *mut _, &scale as *const _ as *mut _,
10175                            &nspm as *const _ as *mut _, &spk as *const _ as *mut _,
10176                            &ktb as *const _ as *mut _, &vtb as *const _ as *mut _,
10177                            &nr as *const _ as *mut _,
10178                        ];
10179                        unsafe { self.launch_pdl_flash(Self::gkv_on(),
10180                            "fa_decode_vec_q_rows_v4_512_tb",
10181                            (n_head_kv as u32, n_splits_g as u32, 1), (32, gqa, 1),
10182                            shmem, &mut ps)?; }
10183                    } else {
10184                    let cfg_tb = LaunchConfig {
10185                        grid_dim: (n_head_kv as u32, n_splits_g as u32, 1),
10186                        block_dim: (32, gqa, 1), shared_mem_bytes: shmem };
10187                    b.arg(&q_g).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10188                     .arg(&hd).arg(&nh).arg(&nhkv).arg(bd).arg(&plus_g).arg(&scale).arg(&nspm).arg(&spk)
10189                     .arg(&ktb).arg(&vtb).arg(&nr);
10190                    unsafe { b.launch(cfg_tb)?; }
10191                    }
10192                } else if head_dim == 512 {
10193                    let (bd, plus) = base_dev.expect("hd512 rows twin requires a device base counter");
10194                    let plus_g = plus + r0 as i32;
10195                    b.arg(&q_g).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10196                     .arg(&hd).arg(&nh).arg(&nhkv).arg(bd).arg(&plus_g).arg(&scale).arg(&nspm).arg(&spk)
10197                     .arg(&ktb).arg(&vtb);
10198                    unsafe { b.launch(cfg)?; }
10199                } else {
10200                    b.arg(&q_g).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10201                     .arg(&hd).arg(&nh).arg(&nhkv).arg(&base_i).arg(&scale).arg(&nspm).arg(&spk)
10202                     .arg(&ktb).arg(&vtb);
10203                    unsafe { b.launch(cfg)?; }
10204                }
10205            }
10206            let cfg2 = LaunchConfig { grid_dim: (n_head as u32, t_g as u32, 1),
10207                    block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 };
10208            let mut o_g = o.slice_mut(r0 * n_head * head_dim..(r0 + t_g) * n_head * head_dim);
10209            if head_dim == 512 {
10210                // device-len combine (shared by verify/eager/graph — parity by symbol): the
10211                // per-row n_splits derives from the SAME counter the rows kernel read.
10212                let (bd, plus) = base_dev.unwrap();
10213                let plus_g = plus + r0 as i32;
10214                if let Some((oq, od)) = q8_out.as_mut() {
10215                    // wave-5b port (2026-07-23, t=1 decode only): q8-emitting dc combine.
10216                    debug_assert!(t == 1, "rows q8 emit is a t=1 decode arm");
10217                    if Self::pdl_on() && Self::pdl_wb_on() {
10218                        // wave-B2: flavor mirrors fa_func (hd512 + gkv → kf8vf8).
10219                        use cudarc::driver::{DevicePtr, DevicePtrMut};
10220                        let s = &self.gpu.stream();
10221                        let (po, _g0) = part_o.device_ptr(s); let (pm, _g1) = part_m.device_ptr(s);
10222                        let (pl, _g2) = part_l.device_ptr(s);
10223                        let (pq, _g3) = oq.device_ptr_mut(s); let (pd, _g4) = od.device_ptr_mut(s);
10224                        let (pb, _g5) = bd.device_ptr(s);
10225                        let mut ps = [
10226                            &po as *const _ as *mut std::ffi::c_void, &pm as *const _ as *mut _,
10227                            &pl as *const _ as *mut _, &pq as *const _ as *mut _,
10228                            &pd as *const _ as *mut _, &hd as *const _ as *mut _,
10229                            &nh as *const _ as *mut _, &pb as *const _ as *mut _,
10230                            &plus_g as *const _ as *mut _, &nspm as *const _ as *mut _,
10231                            &spk as *const _ as *mut _,
10232                        ];
10233                        unsafe { self.launch_pdl_flash(Self::gkv_on(),
10234                            "fa_decode_combine_rows_dc_q8_1",
10235                            cfg2.grid_dim, cfg2.block_dim, 0, &mut ps)?; }
10236                        continue;
10237                    }
10238                    let fc = self.fa_func("fa_decode_combine_rows_dc_q8_1", head_dim);
10239                    let __s_b2 = self.gpu.stream();
10240                    let mut b2 = __s_b2.launch_builder(&fc);
10241                    b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(&mut **oq).arg(&mut **od)
10242                      .arg(&hd).arg(&nh).arg(bd).arg(&plus_g).arg(&nspm).arg(&spk);
10243                    unsafe { b2.launch(cfg2)?; }
10244                    continue;
10245                }
10246                let fc = self.fa_func("fa_decode_combine_rows_dc", head_dim);
10247                let __s_b2 = self.gpu.stream();
10248                let mut b2 = __s_b2.launch_builder(&fc);
10249                b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(&mut o_g).arg(&hd).arg(&nh)
10250                  .arg(bd).arg(&plus_g).arg(&nspm).arg(&spk);
10251                unsafe { b2.launch(cfg2)?; }
10252            } else {
10253                // q8 emit is wired for the hd512 dc-combine arm only — a Some here would
10254                // leave the caller's pair unwritten (consumer would read garbage).
10255                assert!(q8_out.is_none(), "rows q8 emit requires the hd512 dc combine");
10256                let fc = self.func("fa_decode_combine_rows");
10257                let __s_b2 = self.gpu.stream();
10258                let mut b2 = __s_b2.launch_builder(&fc);
10259                b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(&mut o_g).arg(&hd).arg(&nh)
10260                  .arg(&base_i).arg(&nspm).arg(&spk);
10261                unsafe { b2.launch(cfg2)?; }
10262            }
10263        }
10264        Ok(())
10265    }
10266
10267    /// WINDOWED verify rows (gemma R6 deep-ctx): every row attends exactly `window` keys —
10268    /// bit-identical per row to the T=1 decode's fa_decode over the window VIEW. Caller gates
10269    /// base_len + 1 >= window (no under-window rows) and head_dim == 256 (v4 stamp).
10270    #[allow(clippy::too_many_arguments)]
10271    pub fn fa_decode_rows_w(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
10272                            v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
10273                            head_dim: usize, n_head: usize, n_head_kv: usize,
10274                            base_dev: &CudaSlice<i32>, base_plus: i32, t: usize, scale: f32,
10275                            window: usize, k_tok_bytes: usize, v_tok_bytes: usize,
10276                            q8_out: Option<(&mut CudaSlice<i8>, &mut CudaSlice<f32>)>)
10277                            -> Result<(), Box<dyn std::error::Error>> {
10278        // DEVICE-LEN (graph arc step 1, 2026-07-11): the causal base rides an i32 counter
10279        // (kernel T_kv = dev[0] + base_plus + r + 1) so depth graphs can replay with len
10280        // advancing on-device. dc paths pass kvl.len_d with plus=-1; verify/eager sync the
10281        // counter with one async set_i32_one first. Partials/splits size from `window` (host).
10282        debug_assert!(head_dim == 256);
10283        // windowed split (MEMRA_FA_SPW, default 32 — re-swept 2026-07-12 under the raw-e4m3 sV
10284        // occupancy ceiling (4 blocks/SM): t=1 decode is GRID-limited (win/sp splits x nkv
10285        // blocks), so smaller splits fill the ceiling — 1.7k 174.4/174.0 vs 48's 170.7/170.3,
10286        // 4.9k 159.8 vs 157.4 (N=2 interleaved, stable window). Spec serving prefers 64
10287        // (verify t=K+1 fills the grid via grid.z=t; depth K=7 281.3 vs 249.3 at 32) — set
10288        // MEMRA_FA_SPW=64 there, same config law as MEMRA_GEMMA_GKV=0. MUST be one value for
10289        // ALL widths: a t-keyed probe broke decode-vs-verify combine order (stream 9/128).
10290        let sp = {
10291            static SPW: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
10292            let v = *SPW.get_or_init(|| std::env::var("MEMRA_FA_SPW").ok()
10293                .and_then(|x| x.parse().ok()).unwrap_or(0));
10294            if v >= 8 { v } else { FA_SPW_DEFAULT.load(std::sync::atomic::Ordering::Relaxed) }
10295        };
10296        let n_splits_max = (window + sp - 1) / sp;
10297        let (hd, nh, nhkv) = (head_dim as i32, n_head as i32, n_head_kv as i32);
10298        let (nspm, spk, wini) = (n_splits_max as i32, sp as i32, window as i32);
10299        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
10300        let gqa = (n_head / n_head_kv).max(1) as u32;
10301        let o_len = t * n_head * n_splits_max * head_dim;
10302        let ml_len = t * n_head * n_splits_max;
10303        let mut part_guard = self.fa_part_pool.lock().unwrap();
10304        if part_guard.as_ref().map(|pp| pp.0.len() < o_len || pp.1.len() < ml_len).unwrap_or(true) {
10305            // RETIRE-ON-GROW, never free (#68 root cause, 2026-08-04): captured graphs (the
10306            // per-session persistent draft graph, the decode/prime graph doors) BAKE these pool
10307            // buffer addresses. Dropping the old buffers on grow returns them to the async pool,
10308            // later live allocations land at those addresses, and the next graph REPLAY writes
10309            // its fa partials over them — the ST serve-spec corruption (acceptance collapse +
10310            // output corruption began the burst after the trunk's t_kv growth first realloc'd
10311            // this pool past the draft-capture size; research/fp8ship-20260804). Retiring keeps
10312            // the baked addresses alive (single-stream: eager writes the new buffers, replays
10313            // touch only the old — never concurrently). Doubling growth bounds retired VRAM
10314            // (total retired < final size).
10315            let old = part_guard.take();
10316            let (co, cm) = old.as_ref().map(|pp| (pp.0.len(), pp.1.len())).unwrap_or((0, 0));
10317            if let Some(old) = old {
10318                self.fa_part_retired.lock().unwrap().push(old);
10319            }
10320            if std::env::var("MEMRA_DEBUG_FAPOOL").is_ok() {
10321                eprintln!("[fa-pool] REALLOC o {} -> {} ml {} -> {} (old retired)", co, o_len, cm, ml_len);
10322            }
10323            *part_guard = Some((self.alloc_uninit::<f32>(o_len.max(2 * co))?,
10324                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?,
10325                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?));
10326        }
10327        let pg = part_guard.as_mut().unwrap();
10328        self.gpu.stream().memset_zeros(&mut pg.0.slice_mut(0..o_len))?;
10329        self.gpu.stream().memset_zeros(&mut pg.1.slice_mut(0..ml_len))?;
10330        self.gpu.stream().memset_zeros(&mut pg.2.slice_mut(0..ml_len))?;
10331        let (part_o, part_m, part_l) = (&mut pg.0, &mut pg.1, &mut pg.2);
10332        // Lane pick: decode AND verify both land here in the windowed regime (parity law —
10333        // hybrid_forward verify_attn), so the pick only needs internal consistency, not
10334        // clone-of-decode bit fidelity (SASS-proven impossible for textually identical
10335        // kernels, jsonl 2026-07-10). v4 under the threshold; smem twin at/above the smem
10336        // floor (deep-ctx broadcast win); register twin between.
10337        static SMEM_TKV_W: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
10338        let smem_tkv = *SMEM_TKV_W.get_or_init(|| {
10339            std::env::var("MEMRA_FA_SMEM_TKV").ok().and_then(|v| v.parse().ok())
10340                .unwrap_or_else(|| FA_SMEM_TKV_DEFAULT.load(std::sync::atomic::Ordering::Relaxed))
10341        });
10342        // MULTI-ROW v4: resurrected 2026-07-14 (the '33 tok/s collapse' was a paired-map
10343        // partial-write bug, not the mechanism) and falsified HONESTLY at gqa 2: bit-exact
10344        // but −1.7% on the 31B depth cell — the sp helper warp already hides staging
10345        // in-block, and mr trades L2-cheap redundant bytes for serialized per-warp gqa
10346        // score/B3 chains. Arm deleted; jsonl row 2026-07-14 is the record.
10347        use cudarc::driver::sys::CUfunction_attribute_enum as A;
10348        // FP8-WINDOWED (wkv): the v4 family is format-aware (2026-07-12 KFMT/VFMT staging
10349        // arms) — wkv rides the SAME lane logic, resolved from the kf8vf8 module. One symbol
10350        // per (lane, format-module) keeps parity structural; the old register-i2 detour
10351        // (-33%) is retired.
10352        let wg = Self::wkv_on();
10353        // STAGING-PARALLEL v4 (MEMRA_FA_SPW2, default ON at gqa==1): warp 1 = staging helper
10354        // (v4 is 61% staging); score phases identical to v4_w. Same symbol all t.
10355        let sp2 = gqa <= 4 && fa_v4_at(window)
10356            && std::env::var("MEMRA_FA_SPW2").as_deref() != Ok("0");
10357        if sp2 {
10358            let sh = (11520 + 32 * head_dim * if wg { 1 } else { 2 }) as u32;
10359            if Self::pdl_on() && Self::pdl_wb_on() {
10360                // wave-B2b: flavor mirrors wg.
10361                use cudarc::driver::{DevicePtr, DevicePtrMut};
10362                let s = &self.gpu.stream();
10363                let (pq, _b0) = q.device_ptr(s); let (pk, _b1) = k.device_ptr(s);
10364                let (pv, _b2) = v.device_ptr(s);
10365                let (po, _b3) = part_o.device_ptr_mut(s);
10366                let (pm, _b4) = part_m.device_ptr_mut(s);
10367                let (pl, _b5) = part_l.device_ptr_mut(s);
10368                let (pb, _b6) = base_dev.device_ptr(s);
10369                let mut ps = [
10370                    &pq as *const _ as *mut std::ffi::c_void, &pk as *const _ as *mut _,
10371                    &pv as *const _ as *mut _, &po as *const _ as *mut _,
10372                    &pm as *const _ as *mut _, &pl as *const _ as *mut _,
10373                    &hd as *const _ as *mut _, &nh as *const _ as *mut _,
10374                    &nhkv as *const _ as *mut _, &pb as *const _ as *mut _,
10375                    &base_plus as *const _ as *mut _, &scale as *const _ as *mut _,
10376                    &nspm as *const _ as *mut _, &spk as *const _ as *mut _,
10377                    &ktb as *const _ as *mut _, &vtb as *const _ as *mut _,
10378                    &wini as *const _ as *mut _,
10379                ];
10380                unsafe { self.launch_pdl_flash(wg, "fa_decode_vec_q_rows_v4_w_sp",
10381                    (n_head_kv as u32, n_splits_max as u32, t as u32), (32, gqa + 1, 1),
10382                    sh, &mut ps)?; }
10383            } else {
10384            let f = if wg { self.func_g("fa_decode_vec_q_rows_v4_w_sp") }
10385                    else { self.func("fa_decode_vec_q_rows_v4_w_sp") };
10386            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
10387            let cfg = LaunchConfig { grid_dim: (n_head_kv as u32, n_splits_max as u32, t as u32),
10388                block_dim: (32, gqa + 1, 1), shared_mem_bytes: sh };
10389            let __s_b = self.gpu.stream();
10390            let mut b = __s_b.launch_builder(&f);
10391            b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10392             .arg(&hd).arg(&nh).arg(&nhkv).arg(base_dev).arg(&base_plus).arg(&scale).arg(&nspm).arg(&spk)
10393             .arg(&ktb).arg(&vtb).arg(&wini);
10394            unsafe { b.launch(cfg)?; }
10395            }
10396        } else {
10397        if fa_v4_at(window) && Self::pdl_on() && Self::pdl_wb_on() {
10398            // wave-B2b: the v4_w pick only (smem/reg twins stay builder-launched).
10399            let sh = (11520 + 32 * head_dim * if wg { 1 } else { 2 }) as u32;
10400            use cudarc::driver::{DevicePtr, DevicePtrMut};
10401            let s = &self.gpu.stream();
10402            let (pq, _b0) = q.device_ptr(s); let (pk, _b1) = k.device_ptr(s);
10403            let (pv, _b2) = v.device_ptr(s);
10404            let (po, _b3) = part_o.device_ptr_mut(s);
10405            let (pm, _b4) = part_m.device_ptr_mut(s);
10406            let (pl, _b5) = part_l.device_ptr_mut(s);
10407            let (pb, _b6) = base_dev.device_ptr(s);
10408            let mut ps = [
10409                &pq as *const _ as *mut std::ffi::c_void, &pk as *const _ as *mut _,
10410                &pv as *const _ as *mut _, &po as *const _ as *mut _,
10411                &pm as *const _ as *mut _, &pl as *const _ as *mut _,
10412                &hd as *const _ as *mut _, &nh as *const _ as *mut _,
10413                &nhkv as *const _ as *mut _, &pb as *const _ as *mut _,
10414                &base_plus as *const _ as *mut _, &scale as *const _ as *mut _,
10415                &nspm as *const _ as *mut _, &spk as *const _ as *mut _,
10416                &ktb as *const _ as *mut _, &vtb as *const _ as *mut _,
10417                &wini as *const _ as *mut _,
10418            ];
10419            unsafe { self.launch_pdl_flash(wg, "fa_decode_vec_q_rows_v4_w",
10420                (n_head_kv as u32, n_splits_max as u32, t as u32), (32, gqa, 1),
10421                sh, &mut ps)?; }
10422        } else {
10423        let pick = |name: &str| if wg { self.func_g(name) } else { self.func(name) };
10424        let (f, sh) = if fa_v4_at(window) {
10425            let f = pick("fa_decode_vec_q_rows_v4_w");
10426            (f, (11520 + 32 * head_dim * if wg { 1 } else { 2 }) as u32)
10427        } else if smem_tkv > 0 && window >= smem_tkv {
10428            // NOTE: the smem twin's V-stage is still q5_1-hardcoded — unreachable under wkv
10429            // at the gemma window (v4 covers it); revisit if the smem floor ever drops.
10430            (pick("fa_decode_vec_q_rows_smem_w"), (2 * 32 * head_dim * 2) as u32)
10431        } else {
10432            (pick("fa_decode_vec_q_rows_reg_w"), 0u32)
10433        };
10434        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
10435        let cfg = LaunchConfig { grid_dim: (n_head_kv as u32, n_splits_max as u32, t as u32),
10436            block_dim: (32, gqa, 1), shared_mem_bytes: sh };
10437        let __s_b = self.gpu.stream();
10438        let mut b = __s_b.launch_builder(&f);
10439        b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10440         .arg(&hd).arg(&nh).arg(&nhkv).arg(base_dev).arg(&base_plus).arg(&scale).arg(&nspm).arg(&spk)
10441         .arg(&ktb).arg(&vtb).arg(&wini);
10442        unsafe { b.launch(cfg)?; }
10443        }
10444        }
10445        let cfg2 = LaunchConfig { grid_dim: (n_head as u32, t as u32, 1),
10446                block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 };
10447        if let Some((oq, od)) = q8_out {
10448            // wave-5b port (2026-07-23): q8-emitting combine — the t=1 decode's wo matvec
10449            // consumes the pair directly; the standalone quantize launch folds away.
10450            if Self::pdl_on() && Self::pdl_wb_on() {
10451                // wave-B2: flavor mirrors the builder's wg choice.
10452                use cudarc::driver::{DevicePtr, DevicePtrMut};
10453                let s = &self.gpu.stream();
10454                let (po, _g0) = part_o.device_ptr(s); let (pm, _g1) = part_m.device_ptr(s);
10455                let (pl, _g2) = part_l.device_ptr(s);
10456                let (pq, _g3) = oq.device_ptr_mut(s); let (pd, _g4) = od.device_ptr_mut(s);
10457                let mut ps = [
10458                    &po as *const _ as *mut std::ffi::c_void, &pm as *const _ as *mut _,
10459                    &pl as *const _ as *mut _, &pq as *const _ as *mut _,
10460                    &pd as *const _ as *mut _, &hd as *const _ as *mut _,
10461                    &nh as *const _ as *mut _, &nspm as *const _ as *mut _,
10462                    &spk as *const _ as *mut _, &wini as *const _ as *mut _,
10463                ];
10464                unsafe { self.launch_pdl_flash(wg, "fa_decode_combine_rows_w_q8_1",
10465                                               cfg2.grid_dim, cfg2.block_dim, 0, &mut ps)?; }
10466                return Ok(());
10467            }
10468            let fc = if wg { self.func_g("fa_decode_combine_rows_w_q8_1") }
10469                     else { self.func("fa_decode_combine_rows_w_q8_1") };
10470            let __s_b2 = self.gpu.stream();
10471            let mut b2 = __s_b2.launch_builder(&fc);
10472            b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(oq).arg(od).arg(&hd).arg(&nh)
10473              .arg(&nspm).arg(&spk).arg(&wini);
10474            unsafe { b2.launch(cfg2)?; }
10475            return Ok(());
10476        }
10477        let fc = if wg { self.func_g("fa_decode_combine_rows_w") }
10478                 else { self.func("fa_decode_combine_rows_w") };
10479        let __s_b2 = self.gpu.stream();
10480        let mut b2 = __s_b2.launch_builder(&fc);
10481        b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(o).arg(&hd).arg(&nh)
10482          .arg(&nspm).arg(&spk).arg(&wini);
10483        unsafe { b2.launch(cfg2)?; }
10484        Ok(())
10485    }
10486
10487    /// ROUND-STREAM stage (c): fa rows with the causal base from a device counter. Two lanes:
10488    /// v3 (qwen stream, fa_v3_active) and v4 (gemma hd256 burst — rows_v4_dc, g-module aware);
10489    /// `t_kv_upper` sizes splits/partials — the same one-sp-for-all-rows approximation class
10490    /// the host rows path already uses (battery-arbitrated); actual per-row bounds derive
10491    /// in-kernel from the counter (+ base_plus, v4 lane only — v3's kernel has no plus arg).
10492    #[allow(clippy::too_many_arguments)]
10493    pub fn fa_decode_rows_dc(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
10494                             v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
10495                             head_dim: usize, n_head: usize, n_head_kv: usize,
10496                             base_dev: &CudaSlice<i32>, t_kv_upper: usize, t: usize, scale: f32,
10497                             k_tok_bytes: usize, v_tok_bytes: usize, base_plus: i32, g: bool)
10498                             -> Result<(), Box<dyn std::error::Error>> {
10499        let v4 = head_dim == 256 && fa_v4_at(t_kv_upper);
10500        assert!(v4 || fa_v3_active(head_dim), "stream fa rows requires the v3 or v4 lane");
10501        assert!(v4 || base_plus == 0, "v3_dc kernel takes no plus arg");
10502        if v4 {
10503            let sp = fa_split_keys(t_kv_upper, n_head_kv);
10504            let n_splits_max = (t_kv_upper + sp - 1) / sp;
10505            let (hd, nh, nhkv) = (head_dim as i32, n_head as i32, n_head_kv as i32);
10506            let (nspm, spk) = (n_splits_max as i32, sp as i32);
10507            let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
10508            let gqa = (n_head / n_head_kv).max(1) as u32;
10509            let o_len = t * n_head * n_splits_max * head_dim;
10510            let ml_len = t * n_head * n_splits_max;
10511            let mut part_guard = self.fa_part_pool.lock().unwrap();
10512            if part_guard.as_ref().map(|pp| pp.0.len() < o_len || pp.1.len() < ml_len).unwrap_or(true) {
10513                // RETIRE-ON-GROW, never free (#68 root cause, 2026-08-04): captured graphs (the
10514            // per-session persistent draft graph, the decode/prime graph doors) BAKE these pool
10515            // buffer addresses. Dropping the old buffers on grow returns them to the async pool,
10516            // later live allocations land at those addresses, and the next graph REPLAY writes
10517            // its fa partials over them — the ST serve-spec corruption (acceptance collapse +
10518            // output corruption began the burst after the trunk's t_kv growth first realloc'd
10519            // this pool past the draft-capture size; research/fp8ship-20260804). Retiring keeps
10520            // the baked addresses alive (single-stream: eager writes the new buffers, replays
10521            // touch only the old — never concurrently). Doubling growth bounds retired VRAM
10522            // (total retired < final size).
10523                let old = part_guard.take();
10524                let (co, cm) = old.as_ref().map(|pp| (pp.0.len(), pp.1.len())).unwrap_or((0, 0));
10525                if let Some(old) = old {
10526                    self.fa_part_retired.lock().unwrap().push(old);
10527                }
10528                if std::env::var("MEMRA_DEBUG_FAPOOL").is_ok() {
10529                    eprintln!("[fa-pool] REALLOC o {} -> {} ml {} -> {} (old retired)", co, o_len, cm, ml_len);
10530                }
10531                *part_guard = Some((self.alloc_uninit::<f32>(o_len.max(2 * co))?,
10532                                    self.alloc_uninit::<f32>(ml_len.max(2 * cm))?,
10533                                    self.alloc_uninit::<f32>(ml_len.max(2 * cm))?));
10534            }
10535            let pg = part_guard.as_mut().unwrap();
10536            self.gpu.stream().memset_zeros(&mut pg.0.slice_mut(0..o_len))?;
10537            self.gpu.stream().memset_zeros(&mut pg.1.slice_mut(0..ml_len))?;
10538            self.gpu.stream().memset_zeros(&mut pg.2.slice_mut(0..ml_len))?;
10539            let (part_o, part_m, part_l) = (&mut pg.0, &mut pg.1, &mut pg.2);
10540            let f = if g { self.func_g("fa_decode_vec_q_rows_v4_dc") }
10541                    else { self.func("fa_decode_vec_q_rows_v4_dc") };
10542            let sh = (11520 + 32 * head_dim * if g { 1 } else { 2 }) as u32;
10543            use cudarc::driver::sys::CUfunction_attribute_enum as A;
10544            f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
10545            let cfg = LaunchConfig { grid_dim: (n_head_kv as u32, n_splits_max as u32, t as u32),
10546                block_dim: (32, gqa, 1), shared_mem_bytes: sh };
10547            let __s_b = self.gpu.stream();
10548            let mut b = __s_b.launch_builder(&f);
10549            b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10550             .arg(&hd).arg(&nh).arg(&nhkv).arg(base_dev).arg(&base_plus).arg(&scale)
10551             .arg(&nspm).arg(&spk).arg(&ktb).arg(&vtb);
10552            unsafe { b.launch(cfg)?; }
10553            let fc = self.func("fa_decode_combine_rows_dc");
10554            let cfg2 = LaunchConfig { grid_dim: (n_head as u32, t as u32, 1),
10555                block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 };
10556            let __s_b2 = self.gpu.stream();
10557            let mut b2 = __s_b2.launch_builder(&fc);
10558            b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(o).arg(&hd).arg(&nh)
10559              .arg(base_dev).arg(&base_plus).arg(&nspm).arg(&spk);
10560            unsafe { b2.launch(cfg2)?; }
10561            return Ok(());
10562        }
10563        let sp = fa_split_keys(t_kv_upper, n_head_kv);
10564        let n_splits_max = (t_kv_upper + sp - 1) / sp;
10565        let (hd, nh, nhkv) = (head_dim as i32, n_head as i32, n_head_kv as i32);
10566        let (nspm, spk) = (n_splits_max as i32, sp as i32);
10567        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
10568        let gqa = (n_head / n_head_kv).max(1) as u32;
10569        let o_len = t * n_head * n_splits_max * head_dim;
10570        let ml_len = t * n_head * n_splits_max;
10571        let mut part_guard = self.fa_part_pool.lock().unwrap();
10572        if part_guard.as_ref().map(|pp| pp.0.len() < o_len || pp.1.len() < ml_len).unwrap_or(true) {
10573            // RETIRE-ON-GROW, never free (#68 root cause, 2026-08-04): captured graphs (the
10574            // per-session persistent draft graph, the decode/prime graph doors) BAKE these pool
10575            // buffer addresses. Dropping the old buffers on grow returns them to the async pool,
10576            // later live allocations land at those addresses, and the next graph REPLAY writes
10577            // its fa partials over them — the ST serve-spec corruption (acceptance collapse +
10578            // output corruption began the burst after the trunk's t_kv growth first realloc'd
10579            // this pool past the draft-capture size; research/fp8ship-20260804). Retiring keeps
10580            // the baked addresses alive (single-stream: eager writes the new buffers, replays
10581            // touch only the old — never concurrently). Doubling growth bounds retired VRAM
10582            // (total retired < final size).
10583            let old = part_guard.take();
10584            let (co, cm) = old.as_ref().map(|pp| (pp.0.len(), pp.1.len())).unwrap_or((0, 0));
10585            if let Some(old) = old {
10586                self.fa_part_retired.lock().unwrap().push(old);
10587            }
10588            if std::env::var("MEMRA_DEBUG_FAPOOL").is_ok() {
10589                eprintln!("[fa-pool] REALLOC o {} -> {} ml {} -> {} (old retired)", co, o_len, cm, ml_len);
10590            }
10591            *part_guard = Some((self.alloc_uninit::<f32>(o_len.max(2 * co))?,
10592                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?,
10593                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?));
10594        }
10595        let pg = part_guard.as_mut().unwrap();
10596        self.gpu.stream().memset_zeros(&mut pg.0.slice_mut(0..o_len))?;
10597        self.gpu.stream().memset_zeros(&mut pg.1.slice_mut(0..ml_len))?;
10598        self.gpu.stream().memset_zeros(&mut pg.2.slice_mut(0..ml_len))?;
10599        let (part_o, part_m, part_l) = (&mut pg.0, &mut pg.1, &mut pg.2);
10600        let f = self.func("fa_decode_vec_q_rows_v3_dc");
10601        let sh = (32 * head_dim * 2) as u32;
10602        use cudarc::driver::sys::CUfunction_attribute_enum as A;
10603        f.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, sh as i32)?;
10604        let cfg = LaunchConfig { grid_dim: (n_head_kv as u32, n_splits_max as u32, t as u32),
10605            block_dim: (32, gqa, 1), shared_mem_bytes: sh };
10606        let __s_b = self.gpu.stream();
10607        let mut b = __s_b.launch_builder(&f);
10608        b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10609         .arg(&hd).arg(&nh).arg(&nhkv).arg(base_dev).arg(&scale).arg(&nspm).arg(&spk)
10610         .arg(&ktb).arg(&vtb);
10611        unsafe { b.launch(cfg)?; }
10612        let fc = self.func("fa_decode_combine_rows_dc");
10613        let cfg2 = LaunchConfig { grid_dim: (n_head as u32, t as u32, 1),
10614            block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 };
10615        let plus0 = 0i32;
10616        let __s_b2 = self.gpu.stream();
10617        let mut b2 = __s_b2.launch_builder(&fc);
10618        b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(o).arg(&hd).arg(&nh)
10619          .arg(base_dev).arg(&plus0).arg(&nspm).arg(&spk);
10620        unsafe { b2.launch(cfg2)?; }
10621        Ok(())
10622    }
10623
10624    /// Device-counter variant of `fa_decode` (CUDA-GRAPH-PLAN Phase 2). The sequence length is read
10625    /// from `t_kv_dev[0]` (resident device i32[1]) for the attention loop bound + per-split key range;
10626    /// the GRID `n_splits` is sized for `bucket_max` (the bucket's max t_kv — baked at capture time).
10627    /// Empty splits (key range beyond the actual t_kv) write an empty partial (m=NEG_INF) so the
10628    /// shared combine skips them -> bit-correct for ANY actual t_kv <= bucket_max.
10629    ///
10630    /// BIT-IDENTITY (the gate): pass `bucket_max == actual_t_kv` and this reproduces `fa_decode`
10631    /// EXACTLY (same n_splits, same per, same split boundaries, same combine) while reading t_kv from
10632    /// device. Bucketing (bucket_max > t_kv) is for the future captured path and changes split
10633    /// grouping (different but mathematically-equal log-sum-exp merge).
10634    pub fn fa_decode_dc(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
10635                        v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
10636                        head_dim: usize, n_head: usize, n_head_kv: usize,
10637                        t_kv_dev: &CudaSlice<i32>, bucket_max: usize, scale: f32,
10638                        k_tok_bytes: usize, v_tok_bytes: usize, g: bool)
10639                        -> Result<(), Box<dyn std::error::Error>> {
10640        self.fa_decode_dc_q8(q, k, v, o, head_dim, n_head, n_head_kv, t_kv_dev, bucket_max,
10641                             scale, k_tok_bytes, v_tok_bytes, g, None)
10642    }
10643
10644    /// `fa_decode_dc` with an optional q8_1 sink (wave 5b): when `q8_out` is given the
10645    /// combine emits (int8, per-32 scales) for the wo matmul_pre and skips the f32 O write.
10646    #[allow(clippy::too_many_arguments)]
10647    pub fn fa_decode_dc_q8(&self, q: &CudaSlice<f32>, k: &cudarc::driver::CudaView<u8>,
10648                        v: &cudarc::driver::CudaView<u8>, o: &mut CudaSlice<f32>,
10649                        head_dim: usize, n_head: usize, n_head_kv: usize,
10650                        t_kv_dev: &CudaSlice<i32>, bucket_max: usize, scale: f32,
10651                        k_tok_bytes: usize, v_tok_bytes: usize, g: bool,
10652                        q8_out: Option<(&mut CudaSlice<i8>, &mut CudaSlice<f32>)>)
10653                        -> Result<(), Box<dyn std::error::Error>> {
10654        // The fa_vec gate + n_splits are sized from bucket_max (host, fixed at capture). The kernel
10655        // reads the ACTUAL t_kv from t_kv_dev for the per-split bound. DEFAULT-ON to MATCH the eager
10656        // `fa_decode` gate above — graph capture must mirror eager's kernel choice or the graph-vs-eager
10657        // bit-identity gate breaks. MEMRA_NO_FA_VEC forces scalar on BOTH paths in lockstep.
10658        // `g` = this layer's cache is e4m3 (gemma windowed under wkv) — every pick below must
10659        // mirror fa_decode_kvmod's g-routing or the graph diverges from eager (short/mid 1/96,
10660        // 2026-07-12).
10661        let mut fa_vec = std::env::var("MEMRA_NO_FA_VEC").is_err() && bucket_max >= fa_vec_min_tkv();
10662        if g && head_dim == 256 && !fa_v4_at(bucket_max) { fa_vec = false; }   // mirror kvmod/geom
10663        let sp = fa_split_keys(bucket_max, n_head_kv);
10664        let n_splits = if fa_vec { ((bucket_max + sp - 1) / sp).max(1) } else { ((bucket_max + 255) / 256).max(1) };
10665        let o_len = n_head * n_splits * head_dim;
10666        let ml_len = n_head * n_splits;
10667        let mut part_guard = self.fa_part_pool.lock().unwrap();
10668        if part_guard.as_ref().map(|pp| pp.0.len() < o_len || pp.1.len() < ml_len).unwrap_or(true) {
10669            // RETIRE-ON-GROW, never free (#68 root cause, 2026-08-04): captured graphs (the
10670            // per-session persistent draft graph, the decode/prime graph doors) BAKE these pool
10671            // buffer addresses. Dropping the old buffers on grow returns them to the async pool,
10672            // later live allocations land at those addresses, and the next graph REPLAY writes
10673            // its fa partials over them — the ST serve-spec corruption (acceptance collapse +
10674            // output corruption began the burst after the trunk's t_kv growth first realloc'd
10675            // this pool past the draft-capture size; research/fp8ship-20260804). Retiring keeps
10676            // the baked addresses alive (single-stream: eager writes the new buffers, replays
10677            // touch only the old — never concurrently). Doubling growth bounds retired VRAM
10678            // (total retired < final size).
10679            let old = part_guard.take();
10680            let (co, cm) = old.as_ref().map(|pp| (pp.0.len(), pp.1.len())).unwrap_or((0, 0));
10681            if let Some(old) = old {
10682                self.fa_part_retired.lock().unwrap().push(old);
10683            }
10684            if std::env::var("MEMRA_DEBUG_FAPOOL").is_ok() {
10685                eprintln!("[fa-pool] REALLOC o {} -> {} ml {} -> {} (old retired)", co, o_len, cm, ml_len);
10686            }
10687            *part_guard = Some((self.alloc_uninit::<f32>(o_len.max(2 * co))?,
10688                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?,
10689                                self.alloc_uninit::<f32>(ml_len.max(2 * cm))?));
10690        }
10691        let pg = part_guard.as_mut().unwrap();
10692        self.gpu.stream().memset_zeros(&mut pg.0.slice_mut(0..o_len))?;
10693        self.gpu.stream().memset_zeros(&mut pg.1.slice_mut(0..ml_len))?;
10694        self.gpu.stream().memset_zeros(&mut pg.2.slice_mut(0..ml_len))?;
10695        let (part_o, part_m, part_l) = (&mut pg.0, &mut pg.1, &mut pg.2);
10696        let (hd, nh, nhkv, nsp) = (head_dim as i32, n_head as i32, n_head_kv as i32, n_splits as i32);
10697        let (ktb, vtb) = (k_tok_bytes as i64, v_tok_bytes as i64);
10698        let fa_vec = fa_vec && head_dim <= 512 && head_dim % 32 == 0;
10699        // FA-DEEP pick keyed on bucket_max (the fa_v4_at precedent) — bit-identical twins,
10700        // so a threshold falling between t_kv and bucket_max cannot diverge eager-vs-graph.
10701        let deep = fa_vec && head_dim == 256 && fa_v4_at(bucket_max) && !g
10702            && fa_deep_at(bucket_max) && !matches!(fa_v4_mode(), "noB3" | "stage");
10703        let (f, cfg) = if fa_vec && head_dim == 512 && bucket_max >= {
10704            static FA512_MIN_DC: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
10705            *FA512_MIN_DC.get_or_init(|| std::env::var("MEMRA_FA512_MIN").ok()
10706                .and_then(|v| v.parse().ok()).unwrap_or(512))
10707        } {
10708            // gemma globals dc twin (mirror the eager dpl16 pick incl the crossover floor).
10709            let gqa = (n_head / n_head_kv).max(1) as u32;
10710            (self.fa_func("fa_decode_vec_q_dpl16_dc", head_dim),
10711             LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
10712                 block_dim: (32, gqa, 1), shared_mem_bytes: 0 })
10713        } else if fa_vec && head_dim == 512 {
10714            // under the 512 floor eager runs scalar — the SAME unified symbol, ctr non-null;
10715            // ns_eff in-kernel reproduces eager's ceil(t_kv/sp) partition for the LIVE len.
10716            return self.fa_decode_scalar_unified(q, k, v, o, head_dim, n_head, n_head_kv,
10717                                                 0, Some(t_kv_dev), scale, n_splits, sp,
10718                                                 k_tok_bytes, v_tok_bytes, g,
10719                                                 &mut *part_o, &mut *part_m, &mut *part_l, q8_out);
10720        } else if fa_vec && head_dim == 256 && fa_v4_at(bucket_max) {
10721            // gemma/qwen v4 dc twin (eager default lane) — capture must mirror eager's pick,
10722            // incl the g-module route + raw-e4m3 sV sizing.
10723            let gqa = (n_head / n_head_kv).max(1) as u32;
10724            let fv = if g { self.func_g("fa_decode_vec_q_v4_dc") }
10725                     else if deep { self.func("fa_decode_vec_q_v4_deep_dc") }
10726                     else { self.func("fa_decode_vec_q_v4_dc") };
10727            let shmem = (if deep { 12160 } else { 11520 }
10728                         + 32 * head_dim * if g { 1 } else { 2 }) as u32;
10729            use cudarc::driver::sys::CUfunction_attribute_enum as A;
10730            fv.set_attribute(A::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shmem as i32)?;
10731            (fv, LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
10732                 block_dim: (32, gqa, 1), shared_mem_bytes: shmem })
10733        } else if fa_vec && fa_v3_active(head_dim) {
10734            // FA v3 lane _dc twin: the captured graph must run the SAME walk body as eager
10735            // under MEMRA_FA_V3=1 (eager, rows-verify and graph switch together).
10736            let gqa = (n_head / n_head_kv).max(1) as u32;
10737            let fv = if g { self.func_g("fa_decode_vec_q_v3_dc") } else { self.func("fa_decode_vec_q_v3_dc") };
10738            let shmem = (32 * head_dim * 2) as u32;       // sV bf16 [FA_DEC_TILE=32][hd]
10739            (fv,
10740             LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
10741                 block_dim: (32, gqa, 1), shared_mem_bytes: shmem })
10742        } else if fa_vec && fa_v2_on() {
10743            // FAVENDOR lane: v2 _dc twin — the captured graph must run the SAME walk body as
10744            // eager under MEMRA_FA_V2=1 or graph_decode_gate's bit-identity breaks (the flag is
10745            // a numeric config; eager, rows-verify and graph all switch together).
10746            let gqa = (n_head / n_head_kv).max(1) as u32;
10747            let fv = if g { self.func_g("fa_decode_vec_q_v2_dc") } else { self.func("fa_decode_vec_q_v2_dc") };
10748            let shmem = (2 * 32 * head_dim * 2) as u32;   // sK+sV bf16 [FA_DEC_TILE=32][hd]
10749            (fv,
10750             LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
10751                 block_dim: (32, gqa, 1), shared_mem_bytes: shmem })
10752        } else if fa_vec {
10753            let gqa = (n_head / n_head_kv).max(1) as u32;
10754            // REGISTER-DEQUANT twin: zero dynamic smem (see fa_decode above).
10755            let fv = if g { self.func_g("fa_decode_vec_q_dc") } else { self.func("fa_decode_vec_q_dc") };
10756            (fv,
10757             LaunchConfig { grid_dim: (n_head_kv as u32, n_splits as u32, 1),
10758                 block_dim: (32, gqa, 1), shared_mem_bytes: 0 })
10759        } else {
10760            return self.fa_decode_scalar_unified(q, k, v, o, head_dim, n_head, n_head_kv,
10761                                                 0, Some(t_kv_dev), scale, n_splits,
10762                                                 if fa_vec { sp } else { 256 },
10763                                                 k_tok_bytes, v_tok_bytes, g,
10764                                                 &mut *part_o, &mut *part_m, &mut *part_l, q8_out);
10765        };
10766        let ski = sp as i32;   // one-partition law: the twins derive ns_eff from (T_kv, ski)
10767        let __s_b = self.gpu.stream();
10768        let mut b = __s_b.launch_builder(&f);
10769        b.arg(q).arg(k).arg(v).arg(&mut *part_o).arg(&mut *part_m).arg(&mut *part_l)
10770         .arg(&hd).arg(&nh).arg(&nhkv).arg(t_kv_dev).arg(&scale).arg(&nsp).arg(&ski)
10771         .arg(&ktb).arg(&vtb);
10772        unsafe { b.launch(cfg)?; }
10773        let cfg2 = LaunchConfig { grid_dim: (n_head as u32, 1, 1), block_dim: (head_dim as u32, 1, 1), shared_mem_bytes: 0 };
10774        if let Some((oq, od)) = q8_out {
10775            let fc = if g { self.func_g("fa_decode_combine_q8_1") }
10776                     else { self.fa_func("fa_decode_combine_q8_1", head_dim) };
10777            let __s_b2 = self.gpu.stream();
10778            let mut b2 = __s_b2.launch_builder(&fc);
10779            b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(oq).arg(od).arg(&hd).arg(&nh).arg(&nsp);
10780            unsafe { b2.launch(cfg2)?; }
10781            return Ok(());
10782        }
10783        let fc = if g { self.func_g("fa_decode_combine_f32") } else { self.fa_func("fa_decode_combine_f32", head_dim) };
10784        let __s_b2 = self.gpu.stream();
10785        let mut b2 = __s_b2.launch_builder(&fc);
10786        b2.arg(&*part_o).arg(&*part_m).arg(&*part_l).arg(o).arg(&hd).arg(&nh).arg(&nsp);
10787        unsafe { b2.launch(cfg2)?; }
10788        Ok(())
10789    }
10790
10791    /// EAGER fa_decode geometry for a given actual `t_kv` (CUDA-GRAPH-PLAN §3.3 bucketing). Returns
10792    /// `(fa_vec, n_splits)` EXACTLY as `fa_decode` computes them so the graph-capture path can key its
10793    /// bucket on the same `(kernel, n_splits)` pair and pass a `bucket_max` that reproduces eager's
10794    /// n_splits bit-for-bit. (Per = ceil(t_kv/n_splits) is then recomputed from the DEVICE t_kv inside
10795    /// the kernel and matches eager when n_splits matches — the bit-identity contract.)
10796    pub fn fa_geom_eager(&self, t_kv: usize, head_dim: usize, n_head_kv: usize, g: bool) -> (bool, usize) {
10797        // MUST mirror `fa_decode` / `fa_decode_dc` (default-ON 2026-06-28). This is the bucket-key
10798        // source: if it disagrees with the actual kernel pick, the graph captures the wrong path and
10799        // replay diverges from eager. All three sites read MEMRA_NO_FA_VEC in lockstep.
10800        let fa_ok = std::env::var("MEMRA_NO_FA_VEC").is_err() && t_kv >= fa_vec_min_tkv();
10801        // hd512 dpl16 vec lane (gemma globals, 2026-07-11 graph-arc fix): the original key
10802        // hardcoded vec = hd<=256, so for hd512 it bucketed by the SCALAR 256-key splits while
10803        // the dpl16/rows_dpl16 kernels split by the ladder — n_splits changed WITHIN a bucket
10804        // (mid-ctx graph mismatch at pos 19 + partials OOB at longer runs). Mirror the real
10805        // fa_decode dispatch: vec512 above the fa512 floor, vec256 as before.
10806        let vec512 = fa_ok && head_dim == 512 && t_kv >= fa512_min_tkv();
10807        let mut fa_vec = vec512 || (fa_ok && head_dim <= 256 && head_dim % 32 == 0);
10808        // g (fp8-windowed): mirror kvmod's clamp — only the v4 lane parses e4m3 in the vec
10809        // family; everything else falls to the g-module scalar.
10810        // hd256 under g: v4-or-scalar. hd128/other under g ride the REGISTER g-lane (the
10811        // dq_K_lane/dq_V_lane macros are format-aware; v3 is format-gated off, v2/smem
10812        // arms are excluded under g). Mirrored in kvmod / fa_decode_dc / fa_geom_eager.
10813        if g && head_dim == 256 && !fa_v4_at(t_kv) { fa_vec = false; }
10814        let sp = fa_split_keys(t_kv, n_head_kv);
10815        let n_splits = if fa_vec { ((t_kv + sp - 1) / sp).max(1) } else { ((t_kv + 255) / 256).max(1) };
10816        (fa_vec, n_splits)
10817    }
10818
10819    /// `bucket_max` (host t_kv to feed `fa_decode_dc` / `full_attn_decode_dc`) that makes the _dc
10820    /// kernel pick the SAME (fa_vec, n_splits) as eager would for actual `t_kv`. Because the dc
10821    /// launcher derives both from `bucket_max` via the same formulas, we just hand it `t_kv` itself:
10822    /// the n_splits is then identical, and the per-split boundaries (computed from the DEVICE t_kv in
10823    /// the kernel) match eager exactly. The bucket KEY (for the graph HashMap) is `(fa_vec, n_splits)`.
10824    pub fn fa_bucket_key(&self, t_kv: usize, head_dim: usize, n_head_kv: usize, g: bool) -> (bool, usize) {
10825        self.fa_geom_eager(t_kv, head_dim, n_head_kv, g)
10826    }
10827
10828    /// CUDA-graph capture wrapper (CUDA-GRAPH-PLAN §3.2, llama.cpp warmup pattern). Runs `step`
10829    /// inline TWICE (warmup — lets the caching allocator settle to stable pointers and any one-time
10830    /// kernel attribute/JIT happen outside capture), then captures a THIRD invocation on the Engine's
10831    /// decode stream (RELAXED mode) and instantiates it into a replayable `CudaGraph`. The closure
10832    /// must enqueue ONLY device work on `e.stream()` (no dtoh / no synchronize / no host branch on
10833    /// device data) — every per-step varying scalar must come from a device counter. Returns the
10834    /// instantiated graph; `CudaGraph::launch()` replays the whole step in one dispatch.
10835    /// `capture_graph` with CAPTURE-RETAIN: every Engine allocation made during the warmups
10836    /// and the capture is kept alive in the returned keeper — hold it as long as the graph
10837    /// replays (transients returning to the pool get reused by unrelated work and corrupt
10838    /// replays; the draft-graph root cause). Model-generic, next capture reuses it.
10839    pub fn capture_graph_retained<F>(&self, step: F)
10840        -> Result<(cudarc::driver::CudaGraph, Vec<Box<dyn std::any::Any + Send>>), Box<dyn std::error::Error>>
10841        where F: FnMut(&Engine) -> Result<(), Box<dyn std::error::Error>>
10842    {
10843        use cudarc::driver::sys::CUgraphInstantiate_flags;
10844        self.capture_graph_retained_flags(
10845            CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, step)
10846    }
10847
10848    /// Retained capture with an explicit instantiate flag. ALLOC-FREE captured graphs
10849    /// (zero mem nodes — the gemma slotted door) should pass UPLOAD instead of
10850    /// AUTO_FREE_ON_LAUNCH: the auto-free flag's launch-time mem-pool scan was measured at
10851    /// ~0.25us/node (205us on the 826-node step) even with nothing to free.
10852    pub fn capture_graph_retained_flags<F>(&self,
10853        flags: cudarc::driver::sys::CUgraphInstantiate_flags, mut step: F)
10854        -> Result<(cudarc::driver::CudaGraph, Vec<Box<dyn std::any::Any + Send>>), Box<dyn std::error::Error>>
10855        where F: FnMut(&Engine) -> Result<(), Box<dyn std::error::Error>>
10856    {
10857        use cudarc::driver::sys::CUstreamCaptureMode;
10858        // KEEP scope = WARMUPS ONLY (2026-07-13): keep_if_capturing retains via
10859        // CudaSlice::clone, which is a device ALLOC + D2D COPY on the stream — clones made
10860        // while the capture region is open become dead copy NODES replayed every launch
10861        // (E4B: 1440 copies = 0.74ms/token, the whole graph-vs-eager regression). The
10862        // warmup runs allocate the same transient sequence at the same pool addresses, so
10863        // retaining the warmup clones preserves the draft-graph fix without polluting the
10864        // captured graph.
10865        self.capture_keep.lock().unwrap().clear();
10866        let was_tracking = self.gpu.ctx.is_event_tracking();
10867        if was_tracking { unsafe { self.gpu.ctx.disable_event_tracking(); } }
10868        let mut run = || -> Result<cudarc::driver::CudaGraph, Box<dyn std::error::Error>> {
10869            self.capture_keep_on.store(true, std::sync::atomic::Ordering::Relaxed);
10870            let w = (|| { step(self)?; step(self) })();
10871            self.capture_keep_on.store(false, std::sync::atomic::Ordering::Relaxed);
10872            w?;
10873            self.gpu.stream().synchronize()?;
10874            self.gpu.stream().begin_capture(CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_RELAXED)?;
10875            let r = step(self);
10876            let g = self.gpu.stream().end_capture(flags);
10877            r?;
10878            let graph = g?.ok_or("capture produced no graph (stream was not capturing)")?;
10879            graph.upload()?;
10880            Ok(graph)
10881        };
10882        let result = run();
10883        self.capture_keep_on.store(false, std::sync::atomic::Ordering::Relaxed);
10884        if was_tracking { unsafe { self.gpu.ctx.enable_event_tracking(); } }
10885        let keeper = std::mem::take(&mut *self.capture_keep.lock().unwrap());
10886        Ok((result?, keeper))
10887    }
10888
10889    pub fn capture_graph<F>(&self, mut step: F) -> Result<cudarc::driver::CudaGraph, Box<dyn std::error::Error>>
10890        where F: FnMut(&Engine) -> Result<(), Box<dyn std::error::Error>>
10891    {
10892        use cudarc::driver::sys::{CUstreamCaptureMode, CUgraphInstantiate_flags};
10893        // EVENT TRACKING OFF for capture. The Engine creates a 2nd stream (copy_stream) so cudarc is in
10894        // multi-stream mode and, by default, records a CudaEvent per CudaSlice alloc/use to serialize
10895        // cross-stream access. Those per-buffer event waits issue stream ops that are NOT permitted
10896        // inside a capture region (CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED). The captured decode step is
10897        // strictly SINGLE-STREAM (every kernel on gpu.stream), so this synchronization is unnecessary
10898        // here — disable it for the whole warmup+capture, re-enable after. SAFETY: the decode-dc path
10899        // touches only gpu.stream; no buffer crosses to copy_stream during capture.
10900        let was_tracking = self.gpu.ctx.is_event_tracking();
10901        if was_tracking { unsafe { self.gpu.ctx.disable_event_tracking(); } }
10902        // Q1 PROBE (MEMRA_GRAPH_IFLAG): the generic capture body's cuMemAllocAsync nodes are
10903        // EXACTLY BALANCED by in-graph free nodes (measured census q27: 1589 ALLOC / 1589
10904        // FREE), so AUTO_FREE_ON_LAUNCH has nothing to reclaim at launch — it only pays its
10905        // per-node launch-time mem-pool scan. `upload` / `none` select the alternatives to
10906        // measure that scan's real cost on the generic path. Diagnostic door only; the
10907        // default stays AUTO_FREE until a measured A/B justifies moving it.
10908        let iflag = {
10909            static F: std::sync::OnceLock<CUgraphInstantiate_flags> = std::sync::OnceLock::new();
10910            *F.get_or_init(|| match std::env::var("MEMRA_GRAPH_IFLAG").as_deref() {
10911                // UPLOAD = the gemma slotted door's zero-mem-node choice; PRIORITY = the flag
10912                // hybrid_forward.rs:5935 actually ships (both drop the auto-free launch scan).
10913                Ok("upload") => CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD,
10914                Ok("priority") =>
10915                    CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY,
10916                _ => CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH,
10917            })
10918        };
10919        // MEMRA_GRAPH_CAPTIME=1 (Q1 lane): phase-resolved capture cost. Recapture is paid at
10920        // every kernel-class crossing, so it — not steady-state decode — is the quantity a
10921        // mem-node reduction could plausibly shrink. Only `instantiate` (cuStreamEndCapture +
10922        // cuGraphInstantiateWithFlags) and `upload` scale with node count; the warmups are
10923        // eager step executions and are node-count-invariant. Printing the split bounds the
10924        // refactor's ceiling instead of assuming it.
10925        let ct = {
10926            static T: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
10927            *T.get_or_init(|| std::env::var("MEMRA_GRAPH_CAPTIME").as_deref() == Ok("1"))
10928        };
10929        // MEMRA_GRAPH_WARMUPS (Q1 lane; DEFAULT 1 since lane/graph-warmups 2026-08-05): the
10930        // phase split showed the eager warmups are 80% of recapture cost (q27 27.4 of 34.4 ms
10931        // pod / 42% of 52.6 ms 5090) — 3x larger than the ENTIRE mem-node ceiling the audit
10932        // chased, and node-count-invariant, so no capture-body refactor could touch it.
10933        // Warmup 2's theorized job was async-pool ADDRESS STABILITY: warmup 1's allocs may
10934        // grow/map the pool, warmup 2 re-walks the same sequence over the freed blocks so the
10935        // captured third run bakes settled addresses. That hazard is the #68 stale-baked-
10936        // address class — which the engine now guards STRUCTURALLY rather than by re-walking:
10937        // in-body transients are captured as BALANCED in-graph alloc/free node pairs (census
10938        // 1589/1589 — replays allocate for themselves; no baked transient pointers), every
10939        // externally-referenced buffer is stable-pointer by design (fa_part_pool retires-on-
10940        // grow and never frees, resident counters/scratch, cache set in place), and the
10941        // draft-graph path additionally rides capture_graph_retained (capture_keep holds all
10942        // warmup+capture allocs alive). One warmup therefore suffices for kernel-attr
10943        // settling and pool mapping. Arbitrated adversarially, not by taste:
10944        // graph-warmup-stress (pool-growth cycles large<->small x10, overlap arm, forced
10945        // recaptures over freed blocks — bit-identity vs eager + canary teeth) is GREEN at
10946        // warmups=1 on the deployment rig, plus graph-decode-gate 256-step bit-identity,
10947        // graph-session-gate, run-spec K=1..8 (receipts research/graph-warmups-5090-20260805/
10948        // + the pod's research/graph-allocfree-20260805/). Measured: recapture -38..-42% q27 /
10949        // -41% q9, decode +~1%, capture+prime -13ms. MEMRA_GRAPH_WARMUPS=2 = the rollback
10950        // seam; tools/graph-warmup-stress-gate.sh = the gate any regression re-runs.
10951        let warmups = {
10952            static W: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
10953            *W.get_or_init(|| std::env::var("MEMRA_GRAPH_WARMUPS").ok()
10954                .and_then(|v| v.parse().ok()).filter(|n| *n >= 1).unwrap_or(1))
10955        };
10956        let mut run = || -> Result<cudarc::driver::CudaGraph, Box<dyn std::error::Error>> {
10957            let t_w = std::time::Instant::now();
10958            // warmup: inline runs (no capture) so allocator pointers + kernel attrs are stable.
10959            for _ in 0..warmups { step(self)?; }
10960            self.gpu.stream().synchronize()?;
10961            let ms_warm = t_w.elapsed().as_secs_f64() * 1e3;
10962            // capture the third run.
10963            let t_c = std::time::Instant::now();
10964            self.gpu.stream().begin_capture(CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_RELAXED)?;
10965            // If the body errors mid-capture, end the capture before propagating so the stream isn't
10966            // left in a capturing state.
10967            let r = step(self);
10968            let ms_body = t_c.elapsed().as_secs_f64() * 1e3;
10969            let t_i = std::time::Instant::now();
10970            let g = self.gpu.stream().end_capture(iflag);
10971            let ms_inst = t_i.elapsed().as_secs_f64() * 1e3;
10972            r?;
10973            let graph = g?.ok_or("capture produced no graph (stream was not capturing)")?;
10974            let t_u = std::time::Instant::now();
10975            graph.upload()?;
10976            if ct {
10977                println!("[graph-captime] warmup2x {ms_warm:.2} ms  capture-body {ms_body:.2} ms  \
10978                          instantiate {ms_inst:.2} ms  upload {:.2} ms",
10979                         t_u.elapsed().as_secs_f64() * 1e3);
10980            }
10981            Ok(graph)
10982        };
10983        let result = run();
10984        if was_tracking { unsafe { self.gpu.ctx.enable_event_tracking(); } }
10985        result
10986    }
10987
10988    /// gdn_scan variant where state_in/out are CudaViews (resident SSM state, in-place per step).
10989    pub fn gdn_scan_s128_view(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
10990                              g: &CudaSlice<f32>, beta: &CudaSlice<f32>,
10991                              state_in: &cudarc::driver::CudaView<f32>,
10992                              state_out: &mut cudarc::driver::CudaViewMut<f32>,
10993                              o: &mut CudaSlice<f32>, n_head: usize, t: usize, scale: f32)
10994                              -> Result<(), Box<dyn std::error::Error>> {
10995        let f = self.func("gdn_scan_s128");
10996        const S_V: u32 = 128; const WARP: u32 = 32; const COLS: u32 = 4;
10997        let cfg = LaunchConfig { grid_dim: (n_head as u32, 1, S_V / COLS), block_dim: (WARP, COLS, 1), shared_mem_bytes: 0 };
10998        let (h, ti) = (n_head as i32, t as i32);
10999        let __s_b = self.gpu.stream();
11000        let mut b = __s_b.launch_builder(&f);
11001        b.arg(q).arg(k).arg(v).arg(g).arg(beta).arg(state_in).arg(state_out).arg(o).arg(&h).arg(&ti).arg(&scale);
11002        unsafe { b.launch(cfg)?; }
11003        Ok(())
11004    }
11005
11006    /// conv1d where the input is a CudaView (resident conv state assembled in place).
11007    pub fn ssm_conv1d_view(&self, x: &cudarc::driver::CudaView<f32>, w: &CudaSlice<f32>, y: &mut CudaSlice<f32>,
11008                           conv_dim: usize, t: usize, d_conv: usize, silu: bool)
11009                           -> Result<(), Box<dyn std::error::Error>> {
11010        let f = self.func("ssm_conv1d_silu_f32");
11011        // grid.x = channel, grid.y = T-tiles (block 256 strides over T) — parallel over both axes.
11012        let cfg = LaunchConfig { grid_dim: (conv_dim as u32, ((t as u32 + 255) / 256).max(1), 1),
11013                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11014        let (cd, ti, dc, s) = (conv_dim as i32, t as i32, d_conv as i32, silu as i32);
11015        let __s_b = self.gpu.stream();
11016        let mut b = __s_b.launch_builder(&f);
11017        b.arg(x).arg(w).arg(y).arg(&cd).arg(&ti).arg(&dc).arg(&s);
11018        unsafe { b.launch(cfg)?; }
11019        Ok(())
11020    }
11021
11022    /// Depthwise causal conv1d + optional SiLU.
11023    /// x:[conv_dim, T+d_conv-1] channel-major (first d_conv-1 cols = carried state),
11024    /// w:[d_conv, conv_dim] kernel-major, y:[conv_dim, T] channel-major.
11025    /// FUSED prefill conv (token-major input, zero left-state): replaces
11026    /// transpose + zeros + conv_left_pad + ssm_conv1d with ONE launch reading the matmul output
11027    /// directly. Output channel-major [conv_dim, T], SiLU applied. BIT-IDENTICAL accumulation.
11028    pub fn ssm_conv1d_tm(&self, qkv_tm: &CudaSlice<f32>, w: &CudaSlice<f32>, y: &mut CudaSlice<f32>,
11029                         conv_dim: usize, t: usize, d_conv: usize)
11030                         -> Result<(), Box<dyn std::error::Error>> {
11031        let f = self.func("ssm_conv1d_tm_f32");
11032        let cfg = LaunchConfig {
11033            grid_dim: (((conv_dim + 255) / 256) as u32, t as u32, 1),
11034            block_dim: (256, 1, 1), shared_mem_bytes: 0,
11035        };
11036        let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11037        let __s_b = self.gpu.stream();
11038        let mut b = __s_b.launch_builder(&f);
11039        b.arg(qkv_tm).arg(w).arg(y).arg(&cd).arg(&ti).arg(&dc);
11040        unsafe { b.launch(cfg)?; }
11041        Ok(())
11042    }
11043
11044    /// BATCHED verify conv (T>1, carried state): window reads the resident conv ring for
11045    /// negative rows; separate ring-update launch afterwards. BIT-IDENTICAL per value to the
11046    /// T=1 chain. T >= pad rides the pure input-column ring update (unchanged legacy path);
11047    /// T < pad (the MEMRA_SPEC_M2 t=2 verify arm) needs old-ring sources for the roll — the
11048    /// update kernel would race reading the ring it rewrites, so that arm clones the ring
11049    /// (dtod) and rolls via ssm_conv_ring_rebuild (PURE COPIES: the ring stores raw input
11050    /// columns; the final ring == what T sequential decode ring rolls leave).
11051    pub fn ssm_conv1d_tm_state(&self, qkv_tm: &CudaSlice<f32>, conv_state: &mut CudaSlice<f32>,
11052                               w: &CudaSlice<f32>, y: &mut CudaSlice<f32>,
11053                               conv_dim: usize, t: usize, d_conv: usize)
11054                               -> Result<(), Box<dyn std::error::Error>> {
11055        self.ssm_conv1d_tm_state_pad(qkv_tm, conv_state, w, y, conv_dim, t, d_conv, None)
11056    }
11057
11058    /// task #14: `pad_len` = device true length for PADDED prime graphs — the ring update
11059    /// reads rows [len-pad, len) instead of the pad tail. None = the classic host-T path.
11060    #[allow(clippy::too_many_arguments)]
11061    pub fn ssm_conv1d_tm_state_pad(&self, qkv_tm: &CudaSlice<f32>, conv_state: &mut CudaSlice<f32>,
11062                               w: &CudaSlice<f32>, y: &mut CudaSlice<f32>,
11063                               conv_dim: usize, t: usize, d_conv: usize,
11064                               pad_len: Option<&CudaSlice<i32>>)
11065                               -> Result<(), Box<dyn std::error::Error>> {
11066        assert!(t >= 1, "ssm_conv1d_tm_state requires T >= 1");
11067        // clone BEFORE the window kernel is issued is not required (stream-ordered: the dtod and
11068        // the window kernel both read the pre-roll ring; the roll launches after both) — but
11069        // cloning first keeps the ordering trivially correct under any future stream split.
11070        let ring_old = if t < d_conv - 1 { Some(self.clone_dtod(conv_state)?) } else { None };
11071        {
11072            let f = self.func("ssm_conv1d_tm_state_f32");
11073            let cfg = LaunchConfig {
11074                grid_dim: (((conv_dim + 255) / 256) as u32, t as u32, 1),
11075                block_dim: (256, 1, 1), shared_mem_bytes: 0,
11076            };
11077            let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11078            let __s_b = self.gpu.stream();
11079            let mut b = __s_b.launch_builder(&f);
11080            b.arg(qkv_tm).arg(&*conv_state).arg(w).arg(y).arg(&cd).arg(&ti).arg(&dc);
11081            unsafe { b.launch(cfg)?; }
11082        }
11083        match (ring_old, pad_len) {
11084            (None, Some(len_d)) => {
11085                let f = self.func("ssm_conv_ring_update_dev_f32");
11086                let n = conv_dim * (d_conv - 1);
11087                let cfg = LaunchConfig::for_num_elems(n as u32);
11088                let (cd, dc) = (conv_dim as i32, d_conv as i32);
11089                let __s_b = self.gpu.stream();
11090                let mut b = __s_b.launch_builder(&f);
11091                b.arg(qkv_tm).arg(conv_state).arg(len_d).arg(&cd).arg(&dc);
11092                unsafe { b.launch(cfg)?; }
11093            }
11094            (None, None) => {
11095                let f = self.func("ssm_conv_ring_update_f32");
11096                let n = conv_dim * (d_conv - 1);
11097                let cfg = LaunchConfig::for_num_elems(n as u32);
11098                let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11099                let __s_b = self.gpu.stream();
11100                let mut b = __s_b.launch_builder(&f);
11101                b.arg(qkv_tm).arg(conv_state).arg(&cd).arg(&ti).arg(&dc);
11102                unsafe { b.launch(cfg)?; }
11103            }
11104            (Some(old), _) => self.ssm_conv_ring_rebuild(qkv_tm, &old, conv_state, conv_dim, t, d_conv)?,
11105        }
11106        Ok(())
11107    }
11108
11109    /// qkv-view twin (task #16): batched prime reads the concat GEMM output directly.
11110    pub fn ssm_conv1d_tm_state_pad_v(&self, qkv_tm: &cudarc::driver::CudaView<f32>, conv_state: &mut CudaSlice<f32>,
11111                               w: &CudaSlice<f32>, y: &mut CudaSlice<f32>,
11112                               conv_dim: usize, t: usize, d_conv: usize,
11113                               pad_len: Option<&CudaSlice<i32>>)
11114                               -> Result<(), Box<dyn std::error::Error>> {
11115        assert!(t >= 1, "ssm_conv1d_tm_state requires T >= 1");
11116        // clone BEFORE the window kernel is issued is not required (stream-ordered: the dtod and
11117        // the window kernel both read the pre-roll ring; the roll launches after both) — but
11118        // cloning first keeps the ordering trivially correct under any future stream split.
11119        let ring_old = if t < d_conv - 1 { Some(self.clone_dtod(conv_state)?) } else { None };
11120        {
11121            let f = self.func("ssm_conv1d_tm_state_f32");
11122            let cfg = LaunchConfig {
11123                grid_dim: (((conv_dim + 255) / 256) as u32, t as u32, 1),
11124                block_dim: (256, 1, 1), shared_mem_bytes: 0,
11125            };
11126            let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11127            let __s_b = self.gpu.stream();
11128            let mut b = __s_b.launch_builder(&f);
11129            b.arg(qkv_tm).arg(&*conv_state).arg(w).arg(y).arg(&cd).arg(&ti).arg(&dc);
11130            unsafe { b.launch(cfg)?; }
11131        }
11132        match (ring_old, pad_len) {
11133            (None, Some(len_d)) => {
11134                let f = self.func("ssm_conv_ring_update_dev_f32");
11135                let n = conv_dim * (d_conv - 1);
11136                let cfg = LaunchConfig::for_num_elems(n as u32);
11137                let (cd, dc) = (conv_dim as i32, d_conv as i32);
11138                let __s_b = self.gpu.stream();
11139                let mut b = __s_b.launch_builder(&f);
11140                b.arg(qkv_tm).arg(conv_state).arg(len_d).arg(&cd).arg(&dc);
11141                unsafe { b.launch(cfg)?; }
11142            }
11143            (None, None) => {
11144                let f = self.func("ssm_conv_ring_update_f32");
11145                let n = conv_dim * (d_conv - 1);
11146                let cfg = LaunchConfig::for_num_elems(n as u32);
11147                let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11148                let __s_b = self.gpu.stream();
11149                let mut b = __s_b.launch_builder(&f);
11150                b.arg(qkv_tm).arg(conv_state).arg(&cd).arg(&ti).arg(&dc);
11151                unsafe { b.launch(cfg)?; }
11152            }
11153            (Some(_), _) => unreachable!(
11154                "ssm_conv1d_tm_state_pad_v: T < d_conv-1 has no view path (PRIME_MIN_T gates it)"),
11155        }
11156        Ok(())
11157    }
11158
11159    /// PREFIX conv-ring rebuild (spec REPLAY-FREE partial accept): overwrite the resident ring
11160    /// with the state a T=1 chain holds after only the FIRST `tc` columns of `qkv_tm` — the last
11161    /// `pad` entries of [ring_old | cols 0..tc-1]. PURE COPIES (the ring stores raw inputs; no
11162    /// arithmetic, cannot perturb FP order). `ring_old` = the pre-round snapshot ring.
11163    pub fn ssm_conv_ring_rebuild(&self, qkv_tm: &CudaSlice<f32>, ring_old: &CudaSlice<f32>,
11164                                 conv_state: &mut CudaSlice<f32>,
11165                                 conv_dim: usize, tc: usize, d_conv: usize)
11166                                 -> Result<(), Box<dyn std::error::Error>> {
11167        let f = self.func("ssm_conv_ring_rebuild_f32");
11168        let n = conv_dim * (d_conv - 1);
11169        let cfg = LaunchConfig::for_num_elems(n as u32);
11170        let (cd, ti, dc) = (conv_dim as i32, tc as i32, d_conv as i32);
11171        let __s_b = self.gpu.stream();
11172        let mut b = __s_b.launch_builder(&f);
11173        b.arg(qkv_tm).arg(ring_old).arg(conv_state).arg(&cd).arg(&ti).arg(&dc);
11174        unsafe { b.launch(cfg)?; }
11175        Ok(())
11176    }
11177
11178    /// FUSED decode GDN prep (T=1): repack + q/k L2-norm + beta sigmoid + g_log in one launch.
11179    /// Replaces 5 tiny serialized kernels on the decode critical path. L2 reduce runs as a 32-lane
11180    /// warp tree (vs l2_norm_f32's 256-thread two-level tree) — same math, different FP sum order;
11181    /// the argmax + run-spec gates are the authority.
11182    #[allow(clippy::too_many_arguments)]
11183    pub fn gdn_prep_decode(&self, conv_out: &CudaSlice<f32>, beta_raw: &CudaSlice<f32>,
11184                           alpha: &CudaSlice<f32>, dt_bias: &CudaSlice<f32>, a: &CudaSlice<f32>,
11185                           q_l2: &mut CudaSlice<f32>, k_l2: &mut CudaSlice<f32>, v_g: &mut CudaSlice<f32>,
11186                           beta: &mut CudaSlice<f32>, g_log: &mut CudaSlice<f32>,
11187                           d_state: usize, num_v: usize, num_k: usize, key_dim: usize, eps: f32)
11188                           -> Result<(), Box<dyn std::error::Error>> {
11189        let f = self.func("gdn_prep_decode_f32");
11190        let cfg = LaunchConfig { grid_dim: (num_v as u32, 1, 1), block_dim: (32, 4, 1), shared_mem_bytes: 0 };
11191        let (ds, nv, nk, kd) = (d_state as i32, num_v as i32, num_k as i32, key_dim as i32);
11192        let __s_b = self.gpu.stream();
11193        let mut b = __s_b.launch_builder(&f);
11194        b.arg(conv_out).arg(beta_raw).arg(alpha).arg(dt_bias).arg(a)
11195         .arg(q_l2).arg(k_l2).arg(v_g).arg(beta).arg(g_log)
11196         .arg(&ds).arg(&nv).arg(&nk).arg(&kd).arg(&eps);
11197        unsafe { b.launch(cfg)?; }
11198        Ok(())
11199    }
11200
11201    /// FUSED prefill conv + GDN repack: token-major qkv -> q_g/k_g/v_g in ONE launch (no conv_out
11202    /// materialization, no qkv_to_gdn_repack pass). BIT-IDENTICAL values; scatter matches
11203    /// qkv_to_gdn_repack's modulo head-repeat mapping exactly.
11204    #[allow(clippy::too_many_arguments)]
11205    pub fn ssm_conv1d_gdn(&self, qkv_tm: &CudaSlice<f32>, w: &CudaSlice<f32>,
11206                          q_g: &mut CudaSlice<f32>, k_g: &mut CudaSlice<f32>, v_g: &mut CudaSlice<f32>,
11207                          conv_dim: usize, t: usize, d_conv: usize,
11208                          d_state: usize, num_v: usize, num_k: usize, key_dim: usize)
11209                          -> Result<(), Box<dyn std::error::Error>> {
11210        let f = self.func("ssm_conv1d_gdn_f32");
11211        let cfg = LaunchConfig {
11212            grid_dim: (((conv_dim + 255) / 256) as u32, t as u32, 1),
11213            block_dim: (256, 1, 1), shared_mem_bytes: 0,
11214        };
11215        let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11216        let (ds, nv, nk, kd) = (d_state as i32, num_v as i32, num_k as i32, key_dim as i32);
11217        let __s_b = self.gpu.stream();
11218        let mut b = __s_b.launch_builder(&f);
11219        b.arg(qkv_tm).arg(w).arg(q_g).arg(k_g).arg(v_g)
11220         .arg(&cd).arg(&ti).arg(&dc).arg(&ds).arg(&nv).arg(&nk).arg(&kd);
11221        unsafe { b.launch(cfg)?; }
11222        Ok(())
11223    }
11224
11225    pub fn ssm_conv1d(&self, x: &CudaSlice<f32>, w: &CudaSlice<f32>, y: &mut CudaSlice<f32>,
11226                      conv_dim: usize, t: usize, d_conv: usize, silu: bool)
11227                      -> Result<(), Box<dyn std::error::Error>> {
11228        let f = self.func("ssm_conv1d_silu_f32");
11229        let cfg = LaunchConfig { grid_dim: (conv_dim as u32, ((t as u32 + 255) / 256).max(1), 1),
11230                                 block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11231        let (cd, ti, dc, s) = (conv_dim as i32, t as i32, d_conv as i32, silu as i32);
11232        let __s_b = self.gpu.stream();
11233        let mut b = __s_b.launch_builder(&f);
11234        b.arg(x).arg(w).arg(y).arg(&cd).arg(&ti).arg(&dc).arg(&s);
11235        unsafe { b.launch(cfg)?; }
11236        Ok(())
11237    }
11238
11239    /// Gated DeltaNet scan, S_v=128. q,k,v:[128,H,T]; g,beta:[H,T]; state:[128,128,H] transposed;
11240    /// o:[128,H,T]. Single sequence.
11241    pub fn gdn_scan_s128(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
11242                         g: &CudaSlice<f32>, beta: &CudaSlice<f32>, state_in: &CudaSlice<f32>,
11243                         state_out: &mut CudaSlice<f32>, o: &mut CudaSlice<f32>,
11244                         n_head: usize, t: usize, scale: f32)
11245                         -> Result<(), Box<dyn std::error::Error>> {
11246        let f = self.func("gdn_scan_s128");
11247        const S_V: u32 = 128; const WARP: u32 = 32; const COLS_PER_BLOCK: u32 = 4;
11248        let cfg = LaunchConfig {
11249            grid_dim: (n_head as u32, 1, S_V / COLS_PER_BLOCK),
11250            block_dim: (WARP, COLS_PER_BLOCK, 1),
11251            shared_mem_bytes: 0,
11252        };
11253        let (h, ti) = (n_head as i32, t as i32);
11254        let __s_b = self.gpu.stream();
11255        let mut b = __s_b.launch_builder(&f);
11256        b.arg(q).arg(k).arg(v).arg(g).arg(beta).arg(state_in).arg(state_out).arg(o).arg(&h).arg(&ti).arg(&scale);
11257        unsafe { b.launch(cfg)?; }
11258        Ok(())
11259    }
11260
11261    // ==== B2' batched decode state ops (decode_batch.rs) ====
11262    // Per-seq state pointers ride device u64 arrays (views into the per-step pointer table).
11263    // Bodies are the single-seq kernels per sequence — bit-identical per row.
11264
11265    #[allow(clippy::too_many_arguments)]
11266    pub fn ssm_conv1d_fused_decode_b(
11267        &self, qkv_cols: &CudaSlice<f32>, conv_state_ptrs: &cudarc::driver::CudaView<u64>,
11268        w: &CudaSlice<f32>, conv_outs: &mut CudaSlice<f32>, conv_dim: usize, d_conv: usize,
11269        b_n: usize) -> Result<(), Box<dyn std::error::Error>> {
11270        let f = self.func("ssm_conv1d_fused_decode_b_f32");
11271        let cfg = LaunchConfig {
11272            grid_dim: (((conv_dim + 255) / 256) as u32, 1, b_n as u32),
11273            block_dim: (256, 1, 1), shared_mem_bytes: 0,
11274        };
11275        let (cd, dc) = (conv_dim as i32, d_conv as i32);
11276        let __s_b = self.gpu.stream();
11277        let mut b = __s_b.launch_builder(&f);
11278        b.arg(qkv_cols).arg(conv_state_ptrs).arg(w).arg(conv_outs).arg(&cd).arg(&dc);
11279        unsafe { b.launch(cfg)?; }
11280        Ok(())
11281    }
11282
11283    #[allow(clippy::too_many_arguments)]
11284    pub fn gdn_prep_decode_b(
11285        &self, conv_outs: &CudaSlice<f32>, beta_raws: &CudaSlice<f32>, alphas: &CudaSlice<f32>,
11286        dt_bias: &CudaSlice<f32>, a: &CudaSlice<f32>,
11287        q_l2: &mut CudaSlice<f32>, k_l2: &mut CudaSlice<f32>, v_g: &mut CudaSlice<f32>,
11288        beta: &mut CudaSlice<f32>, g_log: &mut CudaSlice<f32>,
11289        d_state: usize, num_v: usize, num_k: usize, key_dim: usize, eps: f32,
11290        conv_dim: usize, b_n: usize) -> Result<(), Box<dyn std::error::Error>> {
11291        let f = self.func("gdn_prep_decode_b_f32");
11292        let cfg = LaunchConfig {
11293            grid_dim: (num_v as u32, 1, b_n as u32),
11294            block_dim: (32, 4, 1), shared_mem_bytes: 0,
11295        };
11296        let (ds, nv, nk, kd, cd) =
11297            (d_state as i32, num_v as i32, num_k as i32, key_dim as i32, conv_dim as i32);
11298        let __s_b = self.gpu.stream();
11299        let mut b = __s_b.launch_builder(&f);
11300        b.arg(conv_outs).arg(beta_raws).arg(alphas).arg(dt_bias).arg(a)
11301         .arg(q_l2).arg(k_l2).arg(v_g).arg(beta).arg(g_log)
11302         .arg(&ds).arg(&nv).arg(&nk).arg(&kd).arg(&eps).arg(&cd);
11303        unsafe { b.launch(cfg)?; }
11304        Ok(())
11305    }
11306
11307    #[allow(clippy::too_many_arguments)]
11308    pub fn gdn_scan_s128_batched(
11309        &self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
11310        g: &CudaSlice<f32>, beta: &CudaSlice<f32>,
11311        state_in_ptrs: &cudarc::driver::CudaView<u64>,
11312        state_out_ptrs: &cudarc::driver::CudaView<u64>,
11313        o: &mut CudaSlice<f32>, n_head: usize, b_n: usize, scale: f32)
11314        -> Result<(), Box<dyn std::error::Error>> {
11315        let f = self.func("gdn_scan_s128_b");
11316        const S_V: u32 = 128; const WARP: u32 = 32; const COLS_PER_BLOCK: u32 = 4;
11317        let cfg = LaunchConfig {
11318            grid_dim: (n_head as u32, b_n as u32, S_V / COLS_PER_BLOCK),
11319            block_dim: (WARP, COLS_PER_BLOCK, 1), shared_mem_bytes: 0,
11320        };
11321        let h = n_head as i32;
11322        let __s_b = self.gpu.stream();
11323        let mut b = __s_b.launch_builder(&f);
11324        b.arg(q).arg(k).arg(v).arg(g).arg(beta).arg(state_in_ptrs).arg(state_out_ptrs)
11325         .arg(o).arg(&h).arg(&scale);
11326        unsafe { b.launch(cfg)?; }
11327        Ok(())
11328    }
11329
11330    /// A4 seam: chunked WY GDN prefill. DEFAULT ON (`MEMRA_GDN_CHUNKED=0` = rollback to the
11331    /// sequential scan). Flipped 2026-07-04 with the full battery green: kernel-check ALL
11332    /// GREEN x {9B, 27B} incl the f64-truth chunk gates; run-gen argmax 82==82 both models
11333    /// on AND off (24/24 sweep runs); run-spec K={1,2,3,4,6,8} PASS x {9B synth, 9B text,
11334    /// 27B p2, 27B p3}; e2e first-16-token agreement 6/6 (full-256 drifts at index 47-125
11335    /// on 5/6 prompts — accepted cache-state-FP class, batched-prime precedent).
11336    /// PREFILL-ONLY: decode + spec verify never route here (decode==verify dispatch
11337    /// identity law); prime_cache/forward/forward_last are the only callers.
11338    pub fn gdn_chunked_enabled() -> bool {
11339        static E: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
11340        *E.get_or_init(|| std::env::var("MEMRA_GDN_CHUNKED").map(|v| v != "0").unwrap_or(true))
11341    }
11342
11343    /// A4 chunk size (MEMRA_GDN_CHUNK, default 32 — the sweep winner: the O(T*C) chunk
11344    /// matrices grow with C while the sequential state pass is C-flat, so smaller chunks
11345    /// win; C=32/64 also get the register-history solve template). Clamped to multiples
11346    /// of 32 in [32, 128] (kernel row mappings require it).
11347    pub fn gdn_chunk_size() -> usize {
11348        static C: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
11349        *C.get_or_init(|| {
11350            let c: usize = std::env::var("MEMRA_GDN_CHUNK").ok()
11351                .and_then(|v| v.parse().ok()).unwrap_or(32);
11352            c.clamp(32, 128) / 32 * 32
11353        })
11354    }
11355
11356    /// A4: chunked WY / blockwise-inverse GDN prefill (see cu/hybrid.cu K1-K5 header for the
11357    /// math). Same contract as `gdn_scan_s128` (layouts, state ping-pong) but chunk-parallel:
11358    /// NOT bit-identical to the sequential scan (chunked FP accumulation order); run-gen
11359    /// argmax + run-spec batteries are the accuracy authority. PREFILL callers only.
11360    #[allow(clippy::too_many_arguments)]
11361    /// task #18: K1-K3 of the chunked WY scan (shared by the per-seq path and the
11362    /// batched-prime varlen path). Returns (gcum, P, U, W); `A` is K3-internal.
11363    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
11364    #[allow(clippy::too_many_arguments)]
11365    pub fn gdn_chunk_k123(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
11366                          g: &CudaSlice<f32>, beta: &CudaSlice<f32>, wb16: Option<&mut CudaSlice<u8>>,
11367                          n_head: usize, t: usize, c: usize, hk: usize,
11368                          k2w: Option<(&CudaSlice<u8>, &CudaSlice<u8>, &mut CudaSlice<u8>)>)
11369                          -> Result<(CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
11370        const D: usize = 128;
11371        let h = n_head;
11372        let nc = (t + c - 1) / c;
11373        let (hi, ti, ci) = (h as i32, t as i32, c as i32);
11374        let mut gcum = self.uninit(t * h)?;
11375        let mut a = self.uninit(nc * h * c * c)?;
11376        let mut p = self.uninit(nc * h * c * c)?;
11377        let mut u = self.uninit(nc * h * c * D)?;
11378        let mut w = self.uninit(nc * h * c * D)?;
11379        {   // K1
11380            let f = self.func("gdn_chunk_cumgate_f32");
11381            let cfg = LaunchConfig { grid_dim: (nc as u32, h as u32, 1), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
11382            let __s_b = self.gpu.stream();
11383            let mut b = __s_b.launch_builder(&f);
11384            b.arg(g).arg(&mut gcum).arg(&hi).arg(&ti).arg(&ci);
11385            unsafe { b.launch(cfg)?; }
11386        }
11387        if let Some((qb, kb, pb)) = k2w {
11388            // K2-wgmma (MEMRA_GDN_WGMMA path, c==32): A + pre-masked Pb16 in one kernel;
11389            // the P f32 buffer stays UNWRITTEN (its only wgmma-path consumer is Pb16).
11390            assert!(c == 32, "gdn_k2_wgmma is a C==32 tile");
11391            let f = self.func("gdn_k2_wgmma");
11392            let cfg = LaunchConfig { grid_dim: (nc as u32, h as u32, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
11393            let hki = hk as i32;
11394            let __s_b = self.gpu.stream();
11395            let mut b = __s_b.launch_builder(&f);
11396            b.arg(qb).arg(kb).arg(&gcum).arg(beta).arg(&mut a).arg(&mut *pb).arg(&hi).arg(&ti).arg(&ci).arg(&hki);
11397            unsafe { b.launch(cfg)?; }
11398        } else if c <= 64 && !portable_mma_gated() {   // K2 register-tiled (2x2 outputs/thread, whole-chunk smem k tile)
11399            let f = self.func("gdn_chunk_attn_f32");
11400            let jt = ((c + 31) / 32) as u32;
11401            let cfg = LaunchConfig { grid_dim: (nc as u32, h as u32, jt), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11402            let hki = hk as i32;
11403            let __s_b = self.gpu.stream();
11404            let mut b = __s_b.launch_builder(&f);
11405            b.arg(q).arg(k).arg(&gcum).arg(beta).arg(&mut a).arg(&mut p).arg(&hi).arg(&ti).arg(&ci).arg(&hki);
11406            unsafe { b.launch(cfg)?; }
11407        } else {       // K2 generic (C = 128, or the portable target's low-smem fallback)
11408            assert!(hk == h, "generic K2 is broadcast-only (de-broadcast rides C==32)");
11409            let f = self.func("gdn_chunk_attn_g_f32");
11410            let cfg = LaunchConfig { grid_dim: (nc as u32, h as u32, 1), block_dim: (32, 8, 1), shared_mem_bytes: 0 };
11411            let __s_b = self.gpu.stream();
11412            let mut b = __s_b.launch_builder(&f);
11413            b.arg(q).arg(k).arg(&gcum).arg(beta).arg(&mut a).arg(&mut p).arg(&hi).arg(&ti).arg(&ci);
11414            unsafe { b.launch(cfg)?; }
11415        }
11416        {   // K3 (register-history templates for C=32/64; local-memory generic otherwise)
11417            let cfg = LaunchConfig { grid_dim: (nc as u32, h as u32, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11418            match c {
11419                32 | 64 => {
11420                    let f = self.func(if c == 32 { "gdn_chunk_solve32_f32" } else { "gdn_chunk_solve64_f32" });
11421                    // mirror-fold: W's bf16 twin emitted on store (0 = skip)
11422                    let wb: u64 = match wb16 { Some(d) => self.addr_u8(d), None => 0 };
11423                    let hki = hk as i32;
11424                    let __s_b = self.gpu.stream();
11425                    let mut b = __s_b.launch_builder(&f);
11426                    b.arg(v).arg(k).arg(&a).arg(&gcum).arg(&mut u).arg(&mut w).arg(&wb).arg(&hi).arg(&ti).arg(&hki);
11427                    unsafe { b.launch(cfg)?; }
11428                }
11429                _ => {
11430                    assert!(hk == h, "generic K3 is broadcast-only");
11431                    let f = self.func("gdn_chunk_solve_f32");
11432                    let __s_b = self.gpu.stream();
11433                    let mut b = __s_b.launch_builder(&f);
11434                    b.arg(v).arg(k).arg(&a).arg(&gcum).arg(&mut u).arg(&mut w).arg(&hi).arg(&ti).arg(&ci);
11435                    unsafe { b.launch(cfg)?; }
11436                }
11437            }
11438        }
11439        Ok((gcum, p, u, w))
11440    }
11441
11442    /// task #21 de-broadcast seam: q/k stored at num_k distinct GQA heads instead of
11443    /// the num_v broadcast. MEMRA_GDN_DB=0 reverts. Only the chunked prefill path
11444    /// consumes the compact layout (hk plumbed; hk == H reproduces broadcast exactly).
11445    pub fn gdn_db_on() -> bool {
11446        std::env::var("MEMRA_GDN_DB").as_deref() != Ok("0")
11447    }
11448
11449    /// Whether the K4/K5 mma pair serves at chunk size `c` (mirrors gdn_scan_chunked's
11450    /// seam read — env re-read per call ON PURPOSE, kernel-check pins both configs).
11451    pub fn gdn_mma_enabled(&self, c: usize) -> bool {
11452        !portable_mma_gated() && c == 32
11453            && match std::env::var("MEMRA_GDN_MMA").as_deref() {
11454                Ok("1") => true,
11455                Ok("0") => false,
11456                _ => cfg!(memra_hopper_mma),
11457            }
11458    }
11459
11460    /// task #22: whether the fused K4+K5 (+K2) wgmma path serves (nested inside the
11461    /// mma config; same per-call env read discipline).
11462    pub fn gdn_wgmma_on(&self, c: usize) -> bool {
11463        self.gdn_mma_enabled(c)
11464            && match std::env::var("MEMRA_GDN_WGMMA").as_deref() {
11465                Ok("0") => false,
11466                Ok("1") => true,
11467                _ => cfg!(memra_hopper_mma),
11468            }
11469    }
11470
11471    /// task #18 conv-fuse: carried-ring conv + SiLU + GDN repack in ONE pass (the
11472    /// conv_out intermediate and its transposed re-read disappear — 11.8ms of the
11473    /// T=2048 prime). Ring update stays the separate follow-up launch (pad-aware).
11474    /// BIT-IDENTICAL values to ssm_conv1d_tm_state_pad + qkv_to_gdn_repack.
11475    #[allow(clippy::too_many_arguments)]
11476    pub fn ssm_conv1d_gdn_state_pad(&self, qkv_tm: &cudarc::driver::CudaView<f32>,
11477                               conv_state: &mut CudaSlice<f32>, w: &CudaSlice<f32>,
11478                               q_g: &mut CudaSlice<f32>, k_g: &mut CudaSlice<f32>,
11479                               v_g: &mut CudaSlice<f32>,
11480                               conv_dim: usize, t: usize, d_conv: usize,
11481                               d_state: usize, num_v: usize, num_k: usize, key_dim: usize,
11482                               hk: usize,
11483                               pad_len: Option<&CudaSlice<i32>>)
11484                               -> Result<(), Box<dyn std::error::Error>> {
11485        assert!(t >= d_conv - 1, "fused state conv requires T >= pad (PRIME_MIN_T gates)");
11486        {
11487            let f = self.func("ssm_conv1d_gdn_state_f32");
11488            let cfg = LaunchConfig {
11489                grid_dim: (((conv_dim + 255) / 256) as u32, t as u32, 1),
11490                block_dim: (256, 1, 1), shared_mem_bytes: 0,
11491            };
11492            let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11493            let (ds, nv, nk, kd, hki) = (d_state as i32, num_v as i32, num_k as i32, key_dim as i32, hk as i32);
11494            let __s_b = self.gpu.stream();
11495            let mut b = __s_b.launch_builder(&f);
11496            b.arg(qkv_tm).arg(&*conv_state).arg(w).arg(q_g).arg(k_g).arg(v_g)
11497             .arg(&cd).arg(&ti).arg(&dc).arg(&ds).arg(&nv).arg(&nk).arg(&kd).arg(&hki);
11498            unsafe { b.launch(cfg)?; }
11499        }
11500        match pad_len {
11501            Some(len_d) => {
11502                let f = self.func("ssm_conv_ring_update_dev_f32");
11503                let n = conv_dim * (d_conv - 1);
11504                let cfg = LaunchConfig::for_num_elems(n as u32);
11505                let (cd, dc) = (conv_dim as i32, d_conv as i32);
11506                let __s_b = self.gpu.stream();
11507                let mut b = __s_b.launch_builder(&f);
11508                b.arg(qkv_tm).arg(conv_state).arg(len_d).arg(&cd).arg(&dc);
11509                unsafe { b.launch(cfg)?; }
11510            }
11511            None => {
11512                let f = self.func("ssm_conv_ring_update_f32");
11513                let n = conv_dim * (d_conv - 1);
11514                let cfg = LaunchConfig::for_num_elems(n as u32);
11515                let (cd, ti, dc) = (conv_dim as i32, t as i32, d_conv as i32);
11516                let __s_b = self.gpu.stream();
11517                let mut b = __s_b.launch_builder(&f);
11518                b.arg(qkv_tm).arg(conv_state).arg(&cd).arg(&ti).arg(&dc);
11519                unsafe { b.launch(cfg)?; }
11520            }
11521        }
11522        Ok(())
11523    }
11524
11525    /// task #18 increment 2: allocate ONE sequence's chunk buffers (no launches) —
11526    /// K1-K5 all run varlen afterwards. `a`/`w` become struct members so the varlen
11527    /// K2/K3 can write them.
11528    pub fn gdn_chunk_alloc(&self, n_head: usize, t: usize, c: usize, hk: usize)
11529                           -> Result<GdnChunkBufs, Box<dyn std::error::Error>> {
11530        const D: usize = 128;
11531        assert!(c == 32, "gdn_chunk_alloc: varlen chain is the C==32 mma pair");
11532        let h = n_head;
11533        let nc = (t + c - 1) / c;
11534        Ok(GdnChunkBufs {
11535            gcum: self.uninit(t * h)?,
11536            a: self.uninit(nc * h * c * c)?,
11537            p: self.uninit(nc * h * c * c)?,
11538            u: self.uninit(nc * h * c * D)?,
11539            w: self.uninit(nc * h * c * D)?,
11540            kb16: self.alloc_u8_uninit(t * hk * D * 2)?,
11541            wb16: self.alloc_u8_uninit(nc * h * c * D * 2)?,
11542            y16: self.alloc_u8_uninit(nc * h * c * D * 2)?,
11543            ssnap16: self.alloc_u8_uninit(nc * h * D * D * 2)?,
11544            qb16: self.alloc_u8_uninit(t * hk * D * 2)?,
11545            pb16: self.alloc_u8_uninit(nc * h * c * c * 2)?,
11546            o: self.uninit(D * h * t)?,
11547            t, nc,
11548        })
11549    }
11550
11551    /// view-source twin of f32_to_bf16 (the batched FA3 v mirror reads a concat view).
11552    pub fn f32_to_bf16_v(&self, x: &cudarc::driver::CudaView<f32>, dst: &mut CudaSlice<u8>, n: usize)
11553                         -> Result<(), Box<dyn std::error::Error>> {
11554        let f = self.func("f32_to_bf16_bulk");
11555        let ni = n as i64;
11556        let cfg = LaunchConfig::for_num_elems((n as u32).div_ceil(4));
11557        let __s_b = self.gpu.stream();
11558        let mut b = __s_b.launch_builder(&f);
11559        b.arg(x).arg(dst).arg(&ni);
11560        unsafe { b.launch(cfg)?; }
11561        Ok(())
11562    }
11563
11564    /// f32 -> bf16 bulk mirror into a caller buffer (the K4/K5 operand mirrors).
11565    pub fn f32_to_bf16_into(&self, x: &CudaSlice<f32>, dst: &mut CudaSlice<u8>, n: usize)
11566                       -> Result<(), Box<dyn std::error::Error>> {
11567        let f = self.func("f32_to_bf16_bulk");
11568        let ni = n as i64;
11569        let cfg = LaunchConfig::for_num_elems((n as u32).div_ceil(4));
11570        let __s_b = self.gpu.stream();
11571        let mut b = __s_b.launch_builder(&f);
11572        b.arg(x).arg(dst).arg(&ni);
11573        unsafe { b.launch(cfg)?; }
11574        Ok(())
11575    }
11576
11577    /// task #18 increment 2: varlen K1+K2+K3 — three launches run every sequence's
11578    /// cumgate/attn/solve (per-block math identical to the per-seq kernels).
11579    pub fn gdn_chunk_k123_vl8(&self, seqs: &[GdnSeqVl], n_head: usize, hk: usize,
11580                              wq: Option<&GdnWVl8>)
11581                              -> Result<(), Box<dyn std::error::Error>> {
11582        let b = seqs.len();
11583        assert!(b >= 1 && b <= 8, "gdn_chunk_k123_vl8: 1..=8 sequences");
11584        let mut packed = [GdnSeqVl::default(); 8];
11585        packed[..b].copy_from_slice(seqs);
11586        let v = GdnVl8(packed);
11587        let (hi, ci) = (n_head as i32, 32i32);
11588        let max_nc = seqs.iter().map(|a| a.nc).max().unwrap() as u32;
11589        {
11590            let f = self.func("gdn_chunk_cumgate_vl");
11591            let cfg = LaunchConfig { grid_dim: (max_nc, n_head as u32, b as u32), block_dim: (32, 1, 1), shared_mem_bytes: 0 };
11592            let __s_lb = self.gpu.stream();
11593            let mut lb = __s_lb.launch_builder(&f);
11594            lb.arg(&v).arg(&hi).arg(&ci);
11595            unsafe { lb.launch(cfg)?; }
11596        }
11597        let hki = hk as i32;
11598        if let Some(w) = wq {   // K2-wgmma vl twin (writes A + pre-masked Pb16)
11599            let f = self.func("gdn_k2_wgmma_vl");
11600            let cfg = LaunchConfig { grid_dim: (max_nc, n_head as u32, b as u32), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
11601            let __s_lb = self.gpu.stream();
11602            let mut lb = __s_lb.launch_builder(&f);
11603            lb.arg(&v).arg(w).arg(&hi).arg(&ci).arg(&hki);
11604            unsafe { lb.launch(cfg)?; }
11605        } else {
11606            let f = self.func("gdn_chunk_attn_vl");
11607            let cfg = LaunchConfig { grid_dim: (max_nc, n_head as u32, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11608            let __s_lb = self.gpu.stream();
11609            let mut lb = __s_lb.launch_builder(&f);
11610            lb.arg(&v).arg(&hi).arg(&ci).arg(&hki);
11611            unsafe { lb.launch(cfg)?; }
11612        }
11613        {
11614            let f = self.func("gdn_chunk_solve32_vl");
11615            let cfg = LaunchConfig { grid_dim: (max_nc, n_head as u32, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11616            let __s_lb = self.gpu.stream();
11617            let mut lb = __s_lb.launch_builder(&f);
11618            lb.arg(&v).arg(&hi).arg(&ci).arg(&hki);
11619            unsafe { lb.launch(cfg)?; }
11620        }
11621        Ok(())
11622    }
11623
11624    /// task #18 increment 3: varlen PREP chain — conv(+ring) / repack / fused-l2 /
11625    /// fused gate-prep, 5 launches for every sequence (per-element math identical
11626    /// to the per-seq kernels; l2/gate fusions write disjoint outputs).
11627    #[allow(clippy::too_many_arguments)]
11628    pub fn gdn_prep_vl8(&self, seqs: &[GdnPrepVl], conv_w: &CudaSlice<f32>,
11629                        dt_bias: &CudaSlice<f32>, a: &CudaSlice<f32>,
11630                        conv_dim: usize, d_conv: usize, d_state: usize,
11631                        num_v: usize, num_k: usize, key_dim: usize, hk: usize, eps: f32)
11632                        -> Result<(), Box<dyn std::error::Error>> {
11633        let b = seqs.len();
11634        assert!(b >= 1 && b <= 8);
11635        let mut packed = [GdnPrepVl::default(); 8];
11636        packed[..b].copy_from_slice(seqs);
11637        let v = GdnPrepVl8(packed);
11638        let max_t = seqs.iter().map(|s| s.t).max().unwrap() as u32;
11639        let (cdi, dci) = (conv_dim as i32, d_conv as i32);
11640        let conv_fuse = std::env::var("MEMRA_CONV_FUSE").as_deref() != Ok("0");
11641        assert!(conv_fuse || hk == num_v, "de-broadcast requires the fused conv");
11642        if conv_fuse {
11643            let f = self.func("ssm_conv1d_gdn_state_vl");
11644            let cfg = LaunchConfig { grid_dim: ((conv_dim as u32).div_ceil(256), max_t, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11645            let (dsi, nvi, nki, kdi, hki) = (d_state as i32, num_v as i32, num_k as i32, key_dim as i32, hk as i32);
11646            let __s_lb = self.gpu.stream();
11647            let mut lb = __s_lb.launch_builder(&f);
11648            lb.arg(&v).arg(conv_w).arg(&cdi).arg(&dci).arg(&dsi).arg(&nvi).arg(&nki).arg(&kdi).arg(&hki);
11649            unsafe { lb.launch(cfg)?; }
11650        } else {
11651            let f = self.func("ssm_conv1d_tm_state_vl");
11652            let cfg = LaunchConfig { grid_dim: ((conv_dim as u32).div_ceil(256), max_t, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11653            let __s_lb = self.gpu.stream();
11654            let mut lb = __s_lb.launch_builder(&f);
11655            lb.arg(&v).arg(conv_w).arg(&cdi).arg(&dci);
11656            unsafe { lb.launch(cfg)?; }
11657        }
11658        {
11659            let f = self.func("ssm_conv_ring_update_vl");
11660            let n = (conv_dim * (d_conv - 1)) as u32;
11661            let cfg = LaunchConfig { grid_dim: (n.div_ceil(256), 1, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11662            let __s_lb = self.gpu.stream();
11663            let mut lb = __s_lb.launch_builder(&f);
11664            lb.arg(&v).arg(&cdi).arg(&dci);
11665            unsafe { lb.launch(cfg)?; }
11666        }
11667        if !conv_fuse {
11668            let f = self.func("qkv_to_gdn_repack_vl");
11669            let n = max_t * (num_v * d_state) as u32;
11670            let cfg = LaunchConfig { grid_dim: (n.div_ceil(256), 1, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11671            let (dsi, nvi, nki, kdi) = (d_state as i32, num_v as i32, num_k as i32, key_dim as i32);
11672            let __s_lb = self.gpu.stream();
11673            let mut lb = __s_lb.launch_builder(&f);
11674            lb.arg(&v).arg(&dsi).arg(&nvi).arg(&nki).arg(&kdi);
11675            unsafe { lb.launch(cfg)?; }
11676        }
11677        if Self::l2_v2_on(d_state) {
11678            let f = self.func("gdn_l2_v2_vl");
11679            let cfg = LaunchConfig { grid_dim: ((max_t * hk as u32).div_ceil(8), 2, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11680            let (dsi, nvi) = (d_state as i32, hk as i32);
11681            let __s_lb = self.gpu.stream();
11682            let mut lb = __s_lb.launch_builder(&f);
11683            lb.arg(&v).arg(&dsi).arg(&nvi).arg(&eps);
11684            unsafe { lb.launch(cfg)?; }
11685        } else {
11686            let f = self.func("gdn_l2_vl");
11687            let cfg = LaunchConfig { grid_dim: (max_t * hk as u32, 2, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11688            let (dsi, nvi) = (d_state as i32, hk as i32);
11689            let __s_lb = self.gpu.stream();
11690            let mut lb = __s_lb.launch_builder(&f);
11691            lb.arg(&v).arg(&dsi).arg(&nvi).arg(&eps);
11692            unsafe { lb.launch(cfg)?; }
11693        }
11694        {
11695            let f = self.func("gdn_gate_prep_vl");
11696            let n = max_t * num_v as u32;
11697            let cfg = LaunchConfig { grid_dim: (n.div_ceil(256), 1, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11698            let nvi = num_v as i32;
11699            let __s_lb = self.gpu.stream();
11700            let mut lb = __s_lb.launch_builder(&f);
11701            lb.arg(&v).arg(dt_bias).arg(a).arg(&nvi);
11702            unsafe { lb.launch(cfg)?; }
11703        }
11704        Ok(())
11705    }
11706
11707    /// varlen bf16 mirrors over the gdnseq_t table (which: 0 = k_l2 -> kb16, 1 = w -> wb16).
11708    pub fn gdn_mirror_vl8(&self, seqs: &[GdnSeqVl], n_head: usize, which: i32, hk: usize)
11709                          -> Result<(), Box<dyn std::error::Error>> {
11710        let b = seqs.len();
11711        assert!(b >= 1 && b <= 8);
11712        let mut packed = [GdnSeqVl::default(); 8];
11713        packed[..b].copy_from_slice(seqs);
11714        let v = GdnVl8(packed);
11715        let ept = (if which == 0 { hk } else { n_head } * 128) as i32;
11716        let max_n = seqs.iter().map(|s| if which == 0 { s.t as i64 * ept as i64 }
11717                                        else { s.nc as i64 * ept as i64 * 32 }).max().unwrap();
11718        let f = self.func("gdn_mirror_vl");
11719        let blocks = ((max_n as u32).div_ceil(4)).div_ceil(256);
11720        let cfg = LaunchConfig { grid_dim: (blocks, 1, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11721        let __s_lb = self.gpu.stream();
11722        let mut lb = __s_lb.launch_builder(&f);
11723        lb.arg(&v).arg(&ept).arg(&which);
11724        unsafe { lb.launch(cfg)?; }
11725        Ok(())
11726    }
11727
11728    /// varlen gated-norm tail (+f16out) — one launch replaces B gated_rmsnorm calls.
11729    pub fn gdn_tail_vl8(&self, seqs: &[GdnPrepVl], norm_w: &CudaSlice<f32>,
11730                        d_state: usize, num_v: usize, eps: f32)
11731                        -> Result<(), Box<dyn std::error::Error>> {
11732        let b = seqs.len();
11733        assert!(b >= 1 && b <= 8);
11734        let mut packed = [GdnPrepVl::default(); 8];
11735        packed[..b].copy_from_slice(seqs);
11736        let v = GdnPrepVl8(packed);
11737        let max_t = seqs.iter().map(|s| s.t).max().unwrap() as u32;
11738        let f = self.func("gated_rmsnorm_f16out_vl");
11739        // block_dim MUST match gated_rmsnorm's (128): the reduction tree order pins the scale
11740        let cfg = LaunchConfig { grid_dim: (max_t * num_v as u32, 1, b as u32), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
11741        let (dsi, nvi) = (d_state as i32, num_v as i32);
11742        let __s_lb = self.gpu.stream();
11743        let mut lb = __s_lb.launch_builder(&f);
11744        lb.arg(&v).arg(norm_w).arg(&dsi).arg(&nvi).arg(&eps);
11745        unsafe { lb.launch(cfg)?; }
11746        Ok(())
11747    }
11748
11749    /// Raw device address helpers for the varlen by-value arg struct (single-stream
11750    /// launches; every buffer outlives the call — the f16 FFI discipline).
11751    pub fn addr_f32(&self, x: &CudaSlice<f32>) -> u64 {
11752        use cudarc::driver::DevicePtr;
11753        let s = self.gpu.stream();
11754        let (p, _g) = x.device_ptr(&s);
11755        p as u64
11756    }
11757    pub fn addr_f32_mut(&self, x: &mut CudaSlice<f32>) -> u64 {
11758        use cudarc::driver::DevicePtrMut;
11759        let s = self.gpu.stream();
11760        let (p, _g) = x.device_ptr_mut(&s);
11761        p as u64
11762    }
11763    pub fn addr_f32v(&self, x: &cudarc::driver::CudaView<f32>) -> u64 {
11764        use cudarc::driver::DevicePtr;
11765        let s = self.gpu.stream();
11766        let (p, _g) = x.device_ptr(&s);
11767        p as u64
11768    }
11769    pub fn addr_u8(&self, x: &CudaSlice<u8>) -> u64 {
11770        use cudarc::driver::DevicePtr;
11771        let s = self.gpu.stream();
11772        let (p, _g) = x.device_ptr(&s);
11773        p as u64
11774    }
11775
11776    /// task #18: the varlen K4+K5 pair — TWO launches run every sequence's state pass
11777    /// and output pass (grid gains a seq dim; per-block math identical to the per-seq
11778    /// launches, so this is strictly bit-gateable against them).
11779    pub fn gdn_chunk_vl8(&self, seqs: &[GdnSeqVl], n_head: usize, scale: f32, hk: usize,
11780                         wq: Option<&GdnWVl8>)
11781                         -> Result<(), Box<dyn std::error::Error>> {
11782        const NSPLIT: u32 = 4;
11783        let b = seqs.len();
11784        assert!(b >= 1 && b <= 8, "gdn_chunk_vl8: 1..=8 sequences");
11785        let mut packed = [GdnSeqVl::default(); 8];
11786        packed[..b].copy_from_slice(seqs);
11787        let v = GdnVl8(packed);
11788        let (hi, ci) = (n_head as i32, 32i32);
11789        let max_nc = seqs.iter().map(|a| a.nc).max().unwrap() as u32;
11790        let hki = hk as i32;
11791        if let Some(w) = wq {
11792            // K4+K5 fused wgmma vl twin: one launch, Y/Ssnap never materialized.
11793            let f = self.func("gdn_k45_wgmma_vl");
11794            let cfg = LaunchConfig { grid_dim: (n_head as u32, NSPLIT, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11795            let __s_lb = self.gpu.stream();
11796            let mut lb = __s_lb.launch_builder(&f);
11797            lb.arg(&v).arg(w).arg(&scale).arg(&hi).arg(&ci).arg(&hki);
11798            unsafe { lb.launch(cfg)?; }
11799            let _ = max_nc;
11800            return Ok(());
11801        }
11802        {
11803            let f = self.func("gdn_chunk_state_mma_vl");
11804            let cfg = LaunchConfig { grid_dim: (n_head as u32, NSPLIT, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11805            let __s_lb = self.gpu.stream();
11806            let mut lb = __s_lb.launch_builder(&f);
11807            lb.arg(&v).arg(&hi).arg(&ci).arg(&hki);
11808            unsafe { lb.launch(cfg)?; }
11809        }
11810        {
11811            let f = self.func("gdn_chunk_output_mma_vl");
11812            let cfg = LaunchConfig { grid_dim: (max_nc, n_head as u32, b as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11813            let __s_lb = self.gpu.stream();
11814            let mut lb = __s_lb.launch_builder(&f);
11815            lb.arg(&v).arg(&hi).arg(&ci).arg(&scale).arg(&hki);
11816            unsafe { lb.launch(cfg)?; }
11817        }
11818        Ok(())
11819    }
11820    pub fn gdn_scan_chunked(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
11821                            g: &CudaSlice<f32>, beta: &CudaSlice<f32>, kb16_pre: Option<&CudaSlice<u8>>,
11822                            qb16_pre: Option<&CudaSlice<u8>>,
11823                            state_in: &CudaSlice<f32>,
11824                            state_out: &mut CudaSlice<f32>, o: &mut CudaSlice<f32>,
11825                            n_head: usize, t: usize, scale: f32, c: usize, hk: usize)
11826                            -> Result<(), Box<dyn std::error::Error>> {
11827        const D: usize = 128;
11828        const NSPLIT: u32 = 4;
11829        assert!(c >= 1 && c <= 128, "gdn_scan_chunked: C must be in 1..=128");
11830        let h = n_head;
11831        let nc = (t + c - 1) / c;
11832        let (hi, ti, ci) = (h as i32, t as i32, c as i32);
11833        // mirror-fold (round 27): on the mma path W's bf16 twin is emitted by K3's store
11834        // (wb16 pre-allocated and threaded through k123) and k's by the producer l2 when
11835        // the caller hands `kb16_pre` — both standalone mirror passes disappear.
11836        let gdn_mma_pre = !portable_mma_gated() && c == 32
11837            && match std::env::var("MEMRA_GDN_MMA").as_deref() {
11838                Ok("1") => true,
11839                Ok("0") => false,
11840                _ => cfg!(memra_hopper_mma),
11841            };
11842        let mut wb16_pre: Option<CudaSlice<u8>> = if gdn_mma_pre {
11843            Some(self.alloc_u8_uninit(nc * h * c * D * 2)?)
11844        } else { None };
11845        // K2-wgmma pre-work (MEMRA_GDN_WGMMA): the kb16/qb16 mirrors hoist ABOVE K123 so
11846        // K2 rides them via cp.async; K2 writes the pre-masked Pb16 directly (the
11847        // gdn_p_bf16_masked pass and the in-branch mirror builds disappear).
11848        let gdn_wgmma_pre = gdn_mma_pre
11849            && match std::env::var("MEMRA_GDN_WGMMA").as_deref() {
11850                Ok("0") => false,
11851                Ok("1") => true,
11852                _ => cfg!(memra_hopper_mma),
11853            };
11854        let nk = t * hk * D;
11855        let mut kb16_local: Option<CudaSlice<u8>> = None;
11856        if gdn_mma_pre && kb16_pre.is_none() {
11857            let mut kb = self.alloc_u8_uninit(nk * 2)?;
11858            let f = self.func("f32_to_bf16_bulk");
11859            let n2 = nk as i64;
11860            let cfg2 = LaunchConfig::for_num_elems((nk as u32).div_ceil(4));
11861            let __s_b = self.gpu.stream();
11862            let mut b = __s_b.launch_builder(&f);
11863            b.arg(k).arg(&mut kb).arg(&n2);
11864            unsafe { b.launch(cfg2)?; }
11865            kb16_local = Some(kb);
11866        }
11867        let kb16_ref0: Option<&CudaSlice<u8>> = kb16_local.as_ref().or(kb16_pre);
11868        if let Some(kb) = kb16_pre { assert!(kb.len() >= nk * 2, "kb16_pre too small"); }
11869        let mut qb16: Option<CudaSlice<u8>> = None;
11870        let mut pb16: Option<CudaSlice<u8>> = None;
11871        if gdn_wgmma_pre {
11872            // mirror-fold (round 35): prep's l2 v2 emits qb16 in-epilogue (kb16 pattern);
11873            // the standalone bulk cvt only serves callers without the prep mirror.
11874            if qb16_pre.is_none() {
11875                let mut qb = self.alloc_u8_uninit(nk * 2)?;
11876                let f = self.func("f32_to_bf16_bulk");
11877                let n2 = nk as i64;
11878                let cfg2 = LaunchConfig::for_num_elems((nk as u32).div_ceil(4));
11879                let __s_b = self.gpu.stream();
11880                let mut b = __s_b.launch_builder(&f);
11881                b.arg(q).arg(&mut qb).arg(&n2);
11882                unsafe { b.launch(cfg2)?; }
11883                qb16 = Some(qb);
11884            } else if let Some(qb) = qb16_pre {
11885                assert!(qb.len() >= nk * 2, "qb16_pre too small");
11886            }
11887            pb16 = Some(self.alloc_u8_uninit(nc * h * c * c * 2)?);
11888        }
11889        let qb16_ref0: Option<&CudaSlice<u8>> = qb16.as_ref().or(qb16_pre);
11890        let k2w = if gdn_wgmma_pre {
11891            Some((*qb16_ref0.as_ref().unwrap(),
11892                  *kb16_ref0.as_ref().unwrap(),
11893                  pb16.as_mut().unwrap()))
11894        } else { None };
11895        let (gcum, p, u, w) = self.gdn_chunk_k123(q, k, v, g, beta, wb16_pre.as_mut(), n_head, t, c, hk, k2w)?;
11896        let _ = &w;
11897        let mut y = self.uninit(nc * h * c * D)?;
11898        let mut ssnap = self.uninit(nc * h * D * D)?;   // chunk-start state snapshots (K5 phase 1)
11899        // K4-MMA seam (MEMRA_GDN_MMA; harness verdict 1.75x — tools/bench_gdn_k4.cu, ledger
11900        // 2026-07-26): M in mma accumulator fragments, bf16 W/k mirrors through a cp.async
11901        // ring. C==32 only (the kernel's tile). PROMOTED default-ON on the Hopper lane
11902        // after the STATE-CARRY battery (2026-07-26): 2048-token prime (64 in-kernel state
11903        // carries) -> 256 greedy decode tokens IDENTICAL to f32 on 3 seeds, AND chunked-
11904        // continuation prime (MEMRA_PRIME_CHUNK=512, 4 cross-call carries via cache.recur)
11905        // IDENTICAL on 2 seeds; plus argmax MATCH, pp512 +3.5% (17286), oracle out
11906        // mean_rel ~1e-4. kernel-check pins BOTH configs (f32 tight band forced =0; mma
11907        // band 8e-2/8e-1 vs f64 truth). =0 reverts; portable stays f32. NOT read via
11908        // OnceLock ON PURPOSE: kernel-check toggles the env per call to pin both forms.
11909        let gdn_mma = !portable_mma_gated() && c == 32
11910            && match std::env::var("MEMRA_GDN_MMA").as_deref() {
11911                Ok("1") => true,
11912                Ok("0") => false,
11913                _ => cfg!(memra_hopper_mma),
11914            };
11915        if gdn_mma {
11916            let wb16 = wb16_pre.take().expect("mma path pre-allocates wb16 (K3 store fold)");
11917            let kb16_ref: &CudaSlice<u8> = kb16_ref0.expect("mma path pre-builds kb16 above K123");
11918            // K4+K5 FUSED wgmma seam (MEMRA_GDN_WGMMA, task #22; harness verdict
11919            // tools/bench_gdn_wgmma.cu v5, ledger 1f08b997: in-band Y 1.07e-2 / state
11920            // 1.03e-2 / O 1.08e-2, 91.3us vs 70.4 K4-only at H=32 T=512). K5's output
11921            // pass runs inside the persistent-M kernel; Y and Ssnap are never
11922            // materialized. New numeric class (gk folds into k^T instead of ys) —
11923            // explicit opt-in until the state-carry battery promotes it. Env read per
11924            // call (kernel-check pins configs by toggling env, GDN_MMA precedent).
11925            // PROMOTED default-ON hopper (2026-07-27): full battery green — harness
11926            // in-band, argmax gate PASS, 3-seed greedy IDENTICAL after ~2k prime,
11927            // chunked-continuation IDENTICAL, kernel-check + decode-batch gates green,
11928            // official prefill lane +0.74% interleaved x5 (5/5 rounds). =0 reverts.
11929            if gdn_wgmma_pre {
11930                // qb16/pb16 pre-built above K123 (K2-wgmma wrote the masked Pb16).
11931                let qb16 = qb16_ref0.unwrap();
11932                let pb16 = pb16.as_ref().unwrap();
11933                {
11934                    let f = self.func("gdn_k45_wgmma");
11935                    let cfg = LaunchConfig { grid_dim: (h as u32, 4, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11936                    let hki = hk as i32;
11937                    let __s_b = self.gpu.stream();
11938                    let mut b = __s_b.launch_builder(&f);
11939                    b.arg(kb16_ref).arg(&gcum).arg(beta).arg(&u).arg(&wb16).arg(qb16).arg(pb16)
11940                     .arg(o).arg(&scale).arg(state_in).arg(&mut *state_out).arg(&hi).arg(&ti).arg(&ci).arg(&hki);
11941                    unsafe { b.launch(cfg)?; }
11942                }
11943                return Ok(());
11944            }
11945            // COUPLED PAIR: K4-mma writes Y and Ssnap as bf16 (their only consumer is
11946            // K5-mma, which rounds to bf16 regardless — identical numerics, half the
11947            // traffic; harness K5 63.0 -> 35.3us). Fresh bf16 buffers replace the f32 ones.
11948            let mut y16 = self.alloc_u8_uninit(nc * h * c * D * 2)?;
11949            let mut ssnap16 = self.alloc_u8_uninit(nc * h * D * D * 2)?;
11950            {
11951                let f = self.func("gdn_chunk_state_mma");
11952                let cfg = LaunchConfig { grid_dim: (h as u32, NSPLIT, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11953                let hki = hk as i32;
11954                let __s_b = self.gpu.stream();
11955                let mut b = __s_b.launch_builder(&f);
11956                b.arg(kb16_ref).arg(&gcum).arg(beta).arg(&u).arg(&wb16).arg(&mut y16).arg(&mut ssnap16)
11957                 .arg(state_in).arg(&mut *state_out).arg(&hi).arg(&ti).arg(&ci).arg(&hki);
11958                unsafe { b.launch(cfg)?; }
11959            }
11960            {   // K5-mma (bf16 St/Y consumers)
11961                let f = self.func("gdn_chunk_output_mma");
11962                let jt = ((c + 31) / 32) as u32;
11963                let cfg = LaunchConfig { grid_dim: (nc as u32, h as u32, jt), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11964                let hki = hk as i32;
11965                let __s_b = self.gpu.stream();
11966                let mut b = __s_b.launch_builder(&f);
11967                b.arg(q).arg(&gcum).arg(&p).arg(&y16).arg(&ssnap16).arg(o).arg(&hi).arg(&ti).arg(&ci).arg(&scale).arg(&hki);
11968                unsafe { b.launch(cfg)?; }
11969            }
11970            return Ok(());
11971        }
11972        {   // K4 (sequential over chunks inside; blocks col-partition the state)
11973            let f = self.func("gdn_chunk_state_f32");
11974            let cfg = LaunchConfig { grid_dim: (h as u32, NSPLIT, 1), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11975            let __s_b = self.gpu.stream();
11976            let mut b = __s_b.launch_builder(&f);
11977            b.arg(k).arg(&gcum).arg(beta).arg(&u).arg(&w).arg(&mut y).arg(&mut ssnap)
11978             .arg(state_in).arg(&mut *state_out).arg(&hi).arg(&ti).arg(&ci);
11979            unsafe { b.launch(cfg)?; }
11980        }
11981        {   // K5 (j-blocked: grid.z = 32-row output blocks per chunk; writes o fully)
11982            let f = self.func("gdn_chunk_output_f32");
11983            let jt = ((c + 31) / 32) as u32;
11984            let cfg = LaunchConfig { grid_dim: (nc as u32, h as u32, jt), block_dim: (256, 1, 1), shared_mem_bytes: 0 };
11985            let __s_b = self.gpu.stream();
11986            let mut b = __s_b.launch_builder(&f);
11987            b.arg(q).arg(&gcum).arg(&p).arg(&y).arg(&ssnap).arg(o).arg(&hi).arg(&ti).arg(&ci).arg(&scale);
11988            unsafe { b.launch(cfg)?; }
11989        }
11990        Ok(())
11991    }
11992
11993    /// PREFILL GDN scan dispatch (the A4 seam): chunked WY form when enabled and T is in the
11994    /// batched-prefill regime, else the sequential scan. Callers: hybrid_forward::linear_attn
11995    /// (forward/forward_last) + linear_attn_prime (prime_cache). Decode (T=1) and the spec
11996    /// verify call `gdn_scan_s128` DIRECTLY — the decode==verify dispatch identity is untouched.
11997    ///
11998    /// MEMRA_GDN_DIFF=1: numerical-oracle mode — runs BOTH forms on the same inputs, prints the
11999    /// per-call (== per-layer, in call order) output/state error distribution, and keeps the
12000    /// SEQUENTIAL results so the run stays on the shipped path (stage-1 prototype evidence).
12001    #[allow(clippy::too_many_arguments)]
12002    #[allow(clippy::too_many_arguments)]
12003    pub fn gdn_scan_prefill(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
12004                            g: &CudaSlice<f32>, beta: &CudaSlice<f32>, kb16_pre: Option<&CudaSlice<u8>>,
12005                            qb16_pre: Option<&CudaSlice<u8>>,
12006                            state_in: &CudaSlice<f32>,
12007                            state_out: &mut CudaSlice<f32>, o: &mut CudaSlice<f32>,
12008                            n_head: usize, t: usize, scale: f32, hk: usize)
12009                            -> Result<(), Box<dyn std::error::Error>> {
12010        if std::env::var("MEMRA_GDN_DIFF").is_ok() && t >= 16 {
12011            assert!(hk == n_head, "GDN_DIFF oracle is broadcast-only");
12012            return self.gdn_scan_diff(q, k, v, g, beta, state_in, state_out, o, n_head, t, scale);
12013        }
12014        if Self::gdn_chunked_enabled() && t >= 16 {
12015            self.gdn_scan_chunked(q, k, v, g, beta, kb16_pre, qb16_pre, state_in, state_out, o, n_head, t, scale,
12016                                  Self::gdn_chunk_size(), hk)
12017        } else {
12018            assert!(hk == n_head, "s128 scan is broadcast-only (prep guarantees by predicate)");
12019            self.gdn_scan_s128(q, k, v, g, beta, state_in, state_out, o, n_head, t, scale)
12020        }
12021    }
12022
12023    /// Stage-1 oracle: run sequential AND chunked, report per-call error stats, keep sequential.
12024    #[allow(clippy::too_many_arguments)]
12025    fn gdn_scan_diff(&self, q: &CudaSlice<f32>, k: &CudaSlice<f32>, v: &CudaSlice<f32>,
12026                     g: &CudaSlice<f32>, beta: &CudaSlice<f32>, state_in: &CudaSlice<f32>,
12027                     state_out: &mut CudaSlice<f32>, o: &mut CudaSlice<f32>,
12028                     n_head: usize, t: usize, scale: f32)
12029                     -> Result<(), Box<dyn std::error::Error>> {
12030        static CALL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12031        let call = CALL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12032        let mut o_c = self.uninit(o.len())?;
12033        let mut st_c = self.uninit(state_out.len())?;
12034        self.gdn_scan_chunked(q, k, v, g, beta, None, None, state_in, &mut st_c, &mut o_c,
12035                              n_head, t, scale, Self::gdn_chunk_size(), n_head)?;
12036        self.gdn_scan_s128(q, k, v, g, beta, state_in, state_out, o, n_head, t, scale)?;
12037        let (oh_s, oh_c) = (self.dtoh(o)?, self.dtoh(&o_c)?);
12038        let (sh_s, sh_c) = (self.dtoh(state_out)?, self.dtoh(&st_c)?);
12039        let stats = |a: &[f32], b: &[f32]| -> (f32, f32, f64) {
12040            let mut max_abs = 0f32; let mut max_rel = 0f32; let mut sum_rel = 0f64;
12041            for (x, y) in a.iter().zip(b) {
12042                let ad = (x - y).abs();
12043                let rel = ad / x.abs().max(y.abs()).max(1e-3);
12044                if ad > max_abs { max_abs = ad; }
12045                if rel > max_rel { max_rel = rel; }
12046                sum_rel += rel as f64;
12047            }
12048            (max_abs, max_rel, sum_rel / a.len() as f64)
12049        };
12050        let (o_ma, o_mr, o_mean) = stats(&oh_s, &oh_c);
12051        let (s_ma, s_mr, s_mean) = stats(&sh_s, &sh_c);
12052        println!("[gdn-diff call {call:3} T={t} C={}] out: max_abs={o_ma:.3e} max_rel={o_mr:.3e} mean_rel={o_mean:.3e} | \
12053                  state: max_abs={s_ma:.3e} max_rel={s_mr:.3e} mean_rel={s_mean:.3e}",
12054                 Self::gdn_chunk_size());
12055        Ok(())
12056    }
12057
12058    /// softplus-based g_log: g_log[h,t] = a[h] * softplus(alpha[h,t] + dt_bias[h]). a pre-negated.
12059    pub fn gdn_glog(&self, alpha: &CudaSlice<f32>, dt_bias: &CudaSlice<f32>, a: &CudaSlice<f32>,
12060                    g_log: &mut CudaSlice<f32>, n_head: usize, t: usize)
12061                    -> Result<(), Box<dyn std::error::Error>> {
12062        let f = self.func("gdn_glog_f32");
12063        let cfg = LaunchConfig::for_num_elems((n_head * t) as u32);
12064        let (h, ti) = (n_head as i32, t as i32);
12065        let __s_b = self.gpu.stream();
12066        let mut b = __s_b.launch_builder(&f);
12067        b.arg(alpha).arg(dt_bias).arg(a).arg(g_log).arg(&h).arg(&ti);
12068        unsafe { b.launch(cfg)?; }
12069        Ok(())
12070    }
12071
12072    /// view twins (task #16): the batched prime's GDN core reads the CONCAT projection
12073    /// buffers at row offsets (CudaView) — same kernels, same values, no split copies.
12074    pub fn sigmoid_v(&self, x: &cudarc::driver::CudaView<f32>, y: &mut CudaSlice<f32>, n: usize)
12075                     -> Result<(), Box<dyn std::error::Error>> {
12076        let f = self.func("sigmoid_f32");
12077        let cfg = LaunchConfig::for_num_elems(n as u32);
12078        let ni = n as i32;
12079        let __s_b = self.gpu.stream();
12080        let mut b = __s_b.launch_builder(&f);
12081        b.arg(x).arg(y).arg(&ni);
12082        unsafe { b.launch(cfg)?; }
12083        Ok(())
12084    }
12085
12086    pub fn gdn_glog_v(&self, alpha: &cudarc::driver::CudaView<f32>, dt_bias: &CudaSlice<f32>,
12087                      a: &CudaSlice<f32>, g_log: &mut CudaSlice<f32>, n_head: usize, t: usize)
12088                      -> Result<(), Box<dyn std::error::Error>> {
12089        let f = self.func("gdn_glog_f32");
12090        let cfg = LaunchConfig::for_num_elems((n_head * t) as u32);
12091        let (h, ti) = (n_head as i32, t as i32);
12092        let __s_b = self.gpu.stream();
12093        let mut b = __s_b.launch_builder(&f);
12094        b.arg(alpha).arg(dt_bias).arg(a).arg(g_log).arg(&h).arg(&ti);
12095        unsafe { b.launch(cfg)?; }
12096        Ok(())
12097    }
12098
12099    pub fn sigmoid(&self, x: &CudaSlice<f32>, y: &mut CudaSlice<f32>, n: usize)
12100                   -> Result<(), Box<dyn std::error::Error>> {
12101        let f = self.func("sigmoid_f32");
12102        let cfg = LaunchConfig::for_num_elems(n as u32);
12103        let ni = n as i32;
12104        let __s_b = self.gpu.stream();
12105        let mut b = __s_b.launch_builder(&f);
12106        b.arg(x).arg(y).arg(&ni);
12107        unsafe { b.launch(cfg)?; }
12108        Ok(())
12109    }
12110
12111    /// attn out-gate fused epilogue (task #17): dst = a * sigmoid(g) + fp16 twin, one launch
12112    /// (replaces sigmoid + mul + convert). Bit-identical class.
12113    pub fn sig_mul_f16out(&self, a: &CudaSlice<f32>, g: &CudaSlice<f32>,
12114                          dst: &mut CudaSlice<f32>, dst16: &mut CudaSlice<u8>, n: usize)
12115                          -> Result<(), Box<dyn std::error::Error>> {
12116        let f = self.func("sig_mul_f16out_f32");
12117        let cfg = LaunchConfig::for_num_elems(n as u32);
12118        let ni = n as i32;
12119        let __s_b = self.gpu.stream();
12120        let mut b = __s_b.launch_builder(&f);
12121        b.arg(a).arg(g).arg(dst).arg(dst16).arg(&ni);
12122        unsafe { b.launch(cfg)?; }
12123        Ok(())
12124    }
12125
12126    /// step35 (Step-3.7-Flash) SEPARATE head-wise attention gate: one scalar per query head,
12127    /// broadcast over head_dim. `dst = a * sigmoid(g)` where `a`/`dst` are `[head_dim, n_head, T]`
12128    /// (the `q_gate_split` layout) and `g` is the PRE-sigmoid `attn_gate` projection output in
12129    /// token-major `[T, n_head]`. `dst16` is the optional fp16 operand for wo (None -> skipped).
12130    ///
12131    /// NOT interchangeable with `sig_mul_f16out`, which gates FULL WIDTH (qwen35 packs one gate
12132    /// value per (head, dim) element inside wq). Using this for that, or that for this, silently
12133    /// applies the wrong number of distinct gate values.
12134    #[allow(clippy::too_many_arguments)]
12135    pub fn attn_head_gate(&self, a: &CudaSlice<f32>, g: &CudaSlice<f32>,
12136                          dst: &mut CudaSlice<f32>, dst16: Option<&mut CudaSlice<u8>>,
12137                          head_dim: usize, n_head: usize, t: usize)
12138                          -> Result<(), Box<dyn std::error::Error>> {
12139        let f = self.func("attn_head_gate_f32");
12140        let cfg = LaunchConfig::for_num_elems((head_dim * n_head * t) as u32);
12141        let (hd, nh, ti) = (head_dim as i32, n_head as i32, t as i32);
12142        // nullable device pointer by value (0 = skip), same convention as `l2_norm_pp`.
12143        let d16: u64 = match dst16 { Some(d) => self.addr_u8(d), None => 0 };
12144        let __s_b = self.gpu.stream();
12145        let mut b = __s_b.launch_builder(&f);
12146        b.arg(a).arg(g).arg(dst).arg(&d16).arg(&hd).arg(&nh).arg(&ti);
12147        unsafe { b.launch(cfg)?; }
12148        Ok(())
12149    }
12150
12151    /// step35 CLAMPED SwiGLU: `dst = min(silu(gate*gs), limit) * clamp(up*us, +-limit)`.
12152    /// Verbatim from llama.cpp `llama-graph.cpp:2146-2165` (routed, `swiglu_clamp_exp`) and
12153    /// `:1751-1770` (shared, `swiglu_clamp_shexp`), non-DEEPSEEK4 branch.
12154    ///
12155    /// This is NOT `swigluoai_mul_scaled`: that one clamps the gate BEFORE swish and multiplies by
12156    /// `(1 + clamp(up))`. Caller MUST check `limit > 1e-6` (upstream's eps gate) and use the plain
12157    /// `silu_mul_scaled` path otherwise — at limit=0 this kernel would clamp every positive
12158    /// activation to zero. On Step-3.7-Flash only layers 43 (7.0) and 44 (16.0) have a live limit.
12159    #[allow(clippy::too_many_arguments)]
12160    pub fn swiglu_clamped_mul_scaled(&self, gate: &CudaSlice<f32>, up: &CudaSlice<f32>,
12161                                     gs: f32, us: f32, limit: f32,
12162                                     dst: &mut CudaSlice<f32>, n: usize)
12163                                     -> Result<(), Box<dyn std::error::Error>> {
12164        debug_assert!(limit > 1e-6, "swiglu_clamped needs a live limit; use silu_mul_scaled");
12165        let f = self.func("swiglu_clamped_mul_scaled_f32");
12166        let cfg = LaunchConfig::for_num_elems(n as u32);
12167        let ni = n as i32;
12168        let __s_b = self.gpu.stream();
12169        let mut b = __s_b.launch_builder(&f);
12170        b.arg(gate).arg(up).arg(&gs).arg(&us).arg(&limit).arg(dst).arg(&ni);
12171        unsafe { b.launch(cfg)?; }
12172        Ok(())
12173    }
12174
12175    /// gated RMSNorm: dst = RMSNorm(o, w[ncols]) * silu(z), per row of ncols. nrows blocks.
12176    pub fn gated_rmsnorm(&self, o: &CudaSlice<f32>, w: &CudaSlice<f32>, z: &CudaSlice<f32>,
12177                         dst: &mut CudaSlice<f32>, ncols: usize, nrows: usize, eps: f32)
12178                         -> Result<(), Box<dyn std::error::Error>> {
12179        let f = self.func("gated_rmsnorm_f32");
12180        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
12181        let (nc, e) = (ncols as i32, eps);
12182        let __s_b = self.gpu.stream();
12183        let mut b = __s_b.launch_builder(&f);
12184        b.arg(o).arg(w).arg(z).arg(dst).arg(&nc).arg(&e);
12185        unsafe { b.launch(cfg)?; }
12186        Ok(())
12187    }
12188
12189    /// f16out twin of `gated_rmsnorm` (task #17): epilogue also emits the fp16 operand for
12190    /// the ssm_out GEMM. Bit-identical class (same floats + the cvt kernel's __float2half).
12191    pub fn gated_rmsnorm_f16out(&self, o: &CudaSlice<f32>, w: &CudaSlice<f32>, z: &CudaSlice<f32>,
12192                                dst: &mut CudaSlice<f32>, dst16: &mut CudaSlice<u8>,
12193                                ncols: usize, nrows: usize, eps: f32)
12194                                -> Result<(), Box<dyn std::error::Error>> {
12195        let f = self.func("gated_rmsnorm_f16out_f32");
12196        // block_dim MUST match gated_rmsnorm's (128): the reduction tree order pins the scale
12197        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
12198        let (nc, e) = (ncols as i32, eps);
12199        let __s_b = self.gpu.stream();
12200        let mut b = __s_b.launch_builder(&f);
12201        b.arg(o).arg(w).arg(z).arg(dst).arg(dst16).arg(&nc).arg(&e);
12202        unsafe { b.launch(cfg)?; }
12203        Ok(())
12204    }
12205
12206    /// add+RMSNorm emitting the f32 normed row AND its q8_1 quantization in one launch (the MoE
12207    /// layer input: z feeds the router matmul as f32, the expert dp4a as q8_1). BIT-IDENTICAL to
12208    /// add_rms_norm + quantize_q8_1. Returns (q, d) alongside the caller-provided res/z buffers.
12209    #[allow(clippy::too_many_arguments)]
12210    pub fn add_rms_norm_zq8(&self, a: &CudaSlice<f32>, b_in: &CudaSlice<f32>, w: &CudaSlice<f32>,
12211                            res: &mut CudaSlice<f32>, z: &mut CudaSlice<f32>,
12212                            ncols: usize, nrows: usize, eps: f32)
12213                            -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
12214        assert!(ncols % 32 == 0);
12215        let mut q = self.alloc_uninit::<i8>(nrows * ncols)?;
12216        let mut d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
12217        let f = self.func("add_rms_norm_zq8");
12218        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (1024, 1, 1), shared_mem_bytes: 0 };
12219        let (nc, ep) = (ncols as i32, eps);
12220        let __s_b = self.gpu.stream();
12221        let mut b = __s_b.launch_builder(&f);
12222        b.arg(a).arg(b_in).arg(w).arg(res).arg(z).arg(&mut q).arg(&mut d).arg(&nc).arg(&ep);
12223        unsafe { b.launch(cfg)?; }
12224        Ok((q, d))
12225    }
12226
12227    /// gated RMSNorm emitting q8_1 directly (fused quantize epilogue) — the ssm_out matvec input.
12228    /// BIT-IDENTICAL bytes to gated_rmsnorm + quantize_q8_1 (ncols % 32 == 0; blocks never straddle
12229    /// rows). Saves one launch per linear-attn layer (36/token on the 9B).
12230    /// z-view twins of gated_rmsnorm(+f16out) — task #16 batched-prime split removal.
12231    pub fn gated_rmsnorm_zv(&self, o: &CudaSlice<f32>, w: &CudaSlice<f32>,
12232                            z: &cudarc::driver::CudaView<f32>,
12233                            dst: &mut CudaSlice<f32>, ncols: usize, nrows: usize, eps: f32)
12234                            -> Result<(), Box<dyn std::error::Error>> {
12235        let f = self.func("gated_rmsnorm_f32");
12236        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
12237        let (nc, e) = (ncols as i32, eps);
12238        let __s_b = self.gpu.stream();
12239        let mut b = __s_b.launch_builder(&f);
12240        b.arg(o).arg(w).arg(z).arg(dst).arg(&nc).arg(&e);
12241        unsafe { b.launch(cfg)?; }
12242        Ok(())
12243    }
12244
12245    pub fn gated_rmsnorm_f16out_zv(&self, o: &CudaSlice<f32>, w: &CudaSlice<f32>,
12246                                   z: &cudarc::driver::CudaView<f32>,
12247                                   dst: &mut CudaSlice<f32>, dst16: &mut CudaSlice<u8>,
12248                                   ncols: usize, nrows: usize, eps: f32)
12249                                   -> Result<(), Box<dyn std::error::Error>> {
12250        let f = self.func("gated_rmsnorm_f16out_f32");
12251        // block_dim MUST match gated_rmsnorm's (128): the reduction tree order pins the scale
12252        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
12253        let (nc, e) = (ncols as i32, eps);
12254        let __s_b = self.gpu.stream();
12255        let mut b = __s_b.launch_builder(&f);
12256        b.arg(o).arg(w).arg(z).arg(dst).arg(dst16).arg(&nc).arg(&e);
12257        unsafe { b.launch(cfg)?; }
12258        Ok(())
12259    }
12260
12261    pub fn gated_rmsnorm_q8_1(&self, o: &CudaSlice<f32>, w: &CudaSlice<f32>, z: &CudaSlice<f32>,
12262                              ncols: usize, nrows: usize, eps: f32)
12263                              -> Result<(CudaSlice<i8>, CudaSlice<f32>), Box<dyn std::error::Error>> {
12264        assert!(ncols % 32 == 0);
12265        let f = self.func("gated_rmsnorm_q8_1");
12266        let mut out_q = self.alloc_uninit::<i8>(nrows * ncols)?;
12267        let mut out_d = self.alloc_uninit::<f32>(nrows * (ncols / 32))?;
12268        let cfg = LaunchConfig { grid_dim: (nrows as u32, 1, 1), block_dim: (128, 1, 1), shared_mem_bytes: 0 };
12269        let (nc, ep) = (ncols as i32, eps);
12270        let __s_b = self.gpu.stream();
12271        let mut b = __s_b.launch_builder(&f);
12272        b.arg(o).arg(w).arg(z).arg(&mut out_q).arg(&mut out_d).arg(&nc).arg(&ep);
12273        unsafe { b.launch(cfg)?; }
12274        Ok((out_q, out_d))
12275    }
12276
12277    /// transpose [rows,cols] row-major -> [cols,rows] row-major.
12278    pub fn transpose(&self, inp: &CudaSlice<f32>, rows: usize, cols: usize)
12279                     -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
12280        let f = self.func("transpose_f32");
12281        let mut out = self.zeros(rows * cols)?;
12282        let cfg = LaunchConfig::for_num_elems((rows * cols) as u32);
12283        let (r, c) = (rows as i32, cols as i32);
12284        let __s_b = self.gpu.stream();
12285        let mut b = __s_b.launch_builder(&f);
12286        b.arg(inp).arg(&mut out).arg(&r).arg(&c);
12287        unsafe { b.launch(cfg)?; }
12288        Ok(out)
12289    }
12290
12291    /// repeat-interleave heads: in[head_dim,n_in,T] -> out[head_dim,n_out,T].
12292    pub fn repeat_heads(&self, inp: &CudaSlice<f32>, out: &mut CudaSlice<f32>,
12293                        head_dim: usize, n_in: usize, n_out: usize, t: usize)
12294                        -> Result<(), Box<dyn std::error::Error>> {
12295        let f = self.func("repeat_heads_f32");
12296        let cfg = LaunchConfig::for_num_elems((head_dim * n_out * t) as u32);
12297        let (hd, ni, no, ti) = (head_dim as i32, n_in as i32, n_out as i32, t as i32);
12298        let __s_b = self.gpu.stream();
12299        let mut b = __s_b.launch_builder(&f);
12300        b.arg(inp).arg(out).arg(&hd).arg(&ni).arg(&no).arg(&ti);
12301        unsafe { b.launch(cfg)?; }
12302        Ok(())
12303    }
12304
12305    /// q|gate split (on-device). qf:[T, n_head*2*head_dim] -> q_out,gate_out:[head_dim,n_head,T].
12306    /// Replaces the dtoh->host-double-loop->htod in full_attn / full_attn_decode.
12307    pub fn q_gate_split(&self, qf: &CudaSlice<f32>, q_out: &mut CudaSlice<f32>,
12308                        gate_out: &mut CudaSlice<f32>, head_dim: usize, n_head: usize, t: usize)
12309                        -> Result<(), Box<dyn std::error::Error>> {
12310        let f = self.func("q_gate_split_f32");
12311        let cfg = LaunchConfig::for_num_elems((head_dim * n_head * t) as u32);
12312        let (hd, nh, ti) = (head_dim as i32, n_head as i32, t as i32);
12313        let __s_b = self.gpu.stream();
12314        let mut b = __s_b.launch_builder(&f);
12315        b.arg(qf).arg(q_out).arg(gate_out).arg(&hd).arg(&nh).arg(&ti);
12316        unsafe { b.launch(cfg)?; }
12317        Ok(())
12318    }
12319
12320    /// qkv->GDN repack (on-device). conv_out:[conv_dim,T] channel-major ->
12321    /// q_g/k_g/v_g:[d_state,num_v,T] with q/k head-repeat kh = vh % num_k (validated modulo mapping).
12322    /// Replaces the dtoh->host-q/k/v-repack->3x-htod in linear_attn / linear_attn_decode.
12323    pub fn qkv_to_gdn_repack(&self, conv_out: &CudaSlice<f32>, q_g: &mut CudaSlice<f32>,
12324                             k_g: &mut CudaSlice<f32>, v_g: &mut CudaSlice<f32>,
12325                             d_state: usize, num_v: usize, num_k: usize, key_dim: usize, t: usize)
12326                             -> Result<(), Box<dyn std::error::Error>> {
12327        let f = self.func("qkv_to_gdn_repack_f32");
12328        let cfg = LaunchConfig::for_num_elems((d_state * num_v * t) as u32);
12329        let (ds, nv, nk, kd, ti) = (d_state as i32, num_v as i32, num_k as i32, key_dim as i32, t as i32);
12330        let __s_b = self.gpu.stream();
12331        let mut b = __s_b.launch_builder(&f);
12332        b.arg(conv_out).arg(q_g).arg(k_g).arg(v_g).arg(&ds).arg(&nv).arg(&nk).arg(&kd).arg(&ti);
12333        unsafe { b.launch(cfg)?; }
12334        Ok(())
12335    }
12336
12337    /// conv left zero-pad (prefill from zero state). src:[conv_dim,T] -> dst:[conv_dim,T+pad],
12338    /// cols 0..pad = 0, cols pad..pad+T = src. `dst` MUST be pre-zeroed. No dtoh/host-loop/htod.
12339    pub fn conv_left_pad(&self, src: &CudaSlice<f32>, dst: &mut CudaSlice<f32>,
12340                         conv_dim: usize, t: usize, pad: usize)
12341                         -> Result<(), Box<dyn std::error::Error>> {
12342        let f = self.func("conv_left_pad_f32");
12343        let cfg = LaunchConfig::for_num_elems((conv_dim * t) as u32);
12344        let (cd, ti, p) = (conv_dim as i32, t as i32, pad as i32);
12345        let __s_b = self.gpu.stream();
12346        let mut b = __s_b.launch_builder(&f);
12347        b.arg(src).arg(dst).arg(&cd).arg(&ti).arg(&p);
12348        unsafe { b.launch(cfg)?; }
12349        Ok(())
12350    }
12351
12352    /// conv-state assemble + ring roll (decode T=1). conv_state:[conv_dim,pad] (resident),
12353    /// qkv_col:[conv_dim] -> conv_in:[conv_dim,pad+1]; AND rolls conv_state (keep last pad cols).
12354    /// Replaces the dtoh->host-conv-ring-assemble->ring-update->htod in linear_attn_decode.
12355    pub fn conv_assemble_and_roll(&self, qkv_col: &CudaSlice<f32>, conv_state: &mut CudaSlice<f32>,
12356                                  conv_in: &mut CudaSlice<f32>, conv_dim: usize, pad: usize)
12357                                  -> Result<(), Box<dyn std::error::Error>> {
12358        let f = self.func("conv_assemble_and_roll_f32");
12359        let cfg = LaunchConfig::for_num_elems(conv_dim as u32);
12360        let (cd, p) = (conv_dim as i32, pad as i32);
12361        let __s_b = self.gpu.stream();
12362        let mut b = __s_b.launch_builder(&f);
12363        b.arg(qkv_col).arg(conv_state).arg(conv_in).arg(&cd).arg(&p);
12364        unsafe { b.launch(cfg)?; }
12365        Ok(())
12366    }
12367
12368    /// RANK3 LEVER (conv fuse, T=1 DECODE): fused conv_assemble_and_roll + ssm_conv1d_silu in ONE
12369    /// launch. Assembles the conv window [conv_state | qkv_col] in registers, computes the depthwise
12370    /// causal conv + SiLU into `conv_out`, and rolls the ring — never materializing conv_in to HBM.
12371    /// Replaces e.conv_assemble_and_roll(...) + e.ssm_conv1d(...). BIT-IDENTICAL to that two-kernel
12372    /// sequence (same 8-wide accumulation order, same SiLU). `conv_out` is [conv_dim] (T=1).
12373    pub fn ssm_conv1d_fused_decode(&self, qkv_col: &CudaSlice<f32>, conv_state: &mut CudaSlice<f32>,
12374                                   w: &CudaSlice<f32>, conv_out: &mut CudaSlice<f32>,
12375                                   conv_dim: usize, d_conv: usize)
12376                                   -> Result<(), Box<dyn std::error::Error>> {
12377        let f = self.func("ssm_conv1d_fused_decode_f32");
12378        let cfg = LaunchConfig::for_num_elems(conv_dim as u32);
12379        let (cd, dc) = (conv_dim as i32, d_conv as i32);
12380        let __s_b = self.gpu.stream();
12381        let mut b = __s_b.launch_builder(&f);
12382        b.arg(qkv_col).arg(conv_state).arg(w).arg(conv_out).arg(&cd).arg(&dc);
12383        unsafe { b.launch(cfg)?; }
12384        Ok(())
12385    }
12386
12387    /// Copy a contiguous range [start, start+len) out of src into a fresh slice (device→device via host).
12388    /// Used for qkv split views. Small/rare; not perf-critical in Stage 1.
12389    pub fn slice_range(&self, src: &CudaSlice<f32>, start: usize, len: usize)
12390                       -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
12391        let host = self.gpu.stream().clone_dtoh(src)?;
12392        self.gpu.stream().synchronize()?;
12393        Ok(self.htod(&host[start..start + len])?)
12394    }
12395}
12396
12397#[cfg(test)]
12398mod target_dispatch_tests {
12399    use super::legacy_quant_gemm_allowed;
12400
12401    #[test]
12402    fn legacy_quant_gemm_arch_policy_honors_the_escape_hatch() {
12403        // sm_120a native lane
12404        assert!(legacy_quant_gemm_allowed(false, false, false));
12405        assert!(!legacy_quant_gemm_allowed(false, false, true));
12406        // pure portable lane (sm_89): gated
12407        assert!(!legacy_quant_gemm_allowed(true, false, false));
12408        assert!(!legacy_quant_gemm_allowed(true, false, true));
12409        // Hopper-MMA lane (sm_90a): portable build, int8-MMA GEMM re-admitted
12410        assert!(legacy_quant_gemm_allowed(true, true, false));
12411        assert!(!legacy_quant_gemm_allowed(true, true, true));
12412    }
12413
12414    #[cfg(all(memra_portable_cuda, not(memra_hopper_mma)))]
12415    #[test]
12416    fn portable_build_disables_legacy_quant_gemm_without_an_env_override() {
12417        assert!(!legacy_quant_gemm_allowed(cfg!(memra_portable_cuda), cfg!(memra_hopper_mma), false));
12418    }
12419
12420    #[cfg(memra_hopper_mma)]
12421    #[test]
12422    fn hopper_mma_build_re_admits_legacy_quant_gemm() {
12423        assert!(legacy_quant_gemm_allowed(cfg!(memra_portable_cuda), cfg!(memra_hopper_mma), false));
12424        assert!(super::portable_mma_gated() == false);
12425    }
12426}
12427
12428/// The memra-kv device seam (Phase D): the cache's 7 ops delegate to the engine's
12429/// inherent methods (inherent methods win name resolution, so no recursion).
12430impl memra_kv::KvDev for Engine {
12431    fn zeros(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
12432        Engine::zeros(self, n)
12433    }
12434    fn uninit(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
12435        Engine::uninit(self, n)
12436    }
12437    fn alloc_u8(&self, n: usize) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
12438        Engine::alloc_u8(self, n)
12439    }
12440    fn htod_i32(&self, v: &[i32]) -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
12441        Engine::htod_i32(self, v)
12442    }
12443    fn clone_dtod(&self, src: &CudaSlice<f32>) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
12444        Engine::clone_dtod(self, src)
12445    }
12446    fn copy_into(&self, dst: &mut CudaSlice<f32>, off: usize, src: &CudaSlice<f32>, len: usize)
12447                 -> Result<(), Box<dyn std::error::Error>> {
12448        Engine::copy_into(self, dst, off, src, len)
12449    }
12450    fn set_i32_one(&self, d: &mut CudaSlice<i32>, v: i32) -> Result<(), Box<dyn std::error::Error>> {
12451        Engine::set_i32_one(self, d, v)
12452    }
12453}