Skip to main content

memra_engine/
decode_batch.rs

1//! Batched decode step — B sequences share one fused pass (ARCHITECTURE-H100.md §3 B2').
2//!
3//! The bandwidth thesis: decode is weight-stream-bound, so every projection at m=B rows
4//! amortizes one weight read across B sequences. Row-parallel ops (norm/rope/quantize/
5//! activation) batch trivially — they are the SAME kernels prefill already runs at T rows.
6//! Only truly per-sequence state stays in a loop: KV append + fa_decode over each cache,
7//! and the GDN/conv recurrent step (v1: per-seq loop via the existing single-seq path;
8//! a blockIdx.z-batched GDN state kernel is the v2 fusion).
9//!
10//! EXACTNESS CONTRACT (the law this module lives under):
11//! - B == 1 must be BIT-IDENTICAL to `decode_step_h` (gate: decode-batch-gate).
12//! - 2 <= B <= 8: each row rides the m=2..9 verify-tier mmvq kernels, which are per-row
13//!   bit-identical to m=1 (the spec-exactness machinery decode_step_t relies on). Each
14//!   sequence's token stream must equal its isolated single-seq run (worker.rs contract:
15//!   "byte-identical to isolated").
16//! - 9 <= B <= 16 (the EXACT-16 tier, inc3 2026-08-01): admitted iff
17//!   `decode_batch_exact16_ok` — every matmul rides the b16 batched-mmvq class
18//!   (bit-identical per (token,row) to m=1; Q8_0 needs the q8rp mirror) under a
19//!   verify_exact scope that disables the m>=16 GEMM/MMQ arms. gate2 bit-strength
20//!   PASS at B=12/16 (research/batched-tick-inc3-20260801). Refused otherwise.
21//! - B > 16 crosses into GEMM/dp4a-tail numeric configs with NO exact kernel class —
22//!   refused (MEMRA_DECODE_BATCH_CAP stays a measurement door).
23//!
24//! v1 scope: the hybrid (Qwen3.5-class) non-gemma4 trunk. Fused m=1 micro-launches
25//! (fused3 QKV, cross-layer add+norm+q8 chain) are NOT used — the unfused sequence is
26//! bit-identical (kernel_check: add_rms_norm == add;rms_norm; _q8_1 == +quantize_q8_1)
27//! and keeps the batched path simple. Batched fusions are tuning work, not correctness.
28
29use crate::cache::Cache;
30use crate::hybrid::{HybridModel, Mixer};
31use crate::Engine;
32use cudarc::driver::CudaSlice;
33
34// ---- MEMRA_BATCH_PHASE=1 (diagnostics): sync-bounded per-phase accumulators for the batched
35// tick. Each boundary syncs the stream, so the TOTAL inflates (launch pipelining is destroyed);
36// the value is the RANKING/shares, not absolute ms. Read via `batch_phase_report()`.
37pub(crate) static BATCH_PHASE: std::sync::Mutex<[f64; 12]> = std::sync::Mutex::new([0.0; 12]);
38pub const BATCH_PHASE_NAMES: [&str; 12] = [
39    "setup(ptrs+embed H2D)",
40    "attn batched pre (norm/qkv/rope)",
41    "attn per-seq: kv append",
42    "attn per-seq: q/a dtod copies",
43    "attn per-seq: fa_decode",
44    "attn post (gate+o-proj)",
45    "gdn batched projections",
46    "gdn state ops (conv/prep/scan)",
47    "gdn out (gated norm+proj)",
48    "ffn (add/norm/gate/up/act/down)",
49    "lm_head (norm+matmul)",
50    "logits D2H + host split",
51];
52pub fn batch_phase_on() -> bool {
53    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
54    *ON.get_or_init(|| std::env::var("MEMRA_BATCH_PHASE").as_deref() == Ok("1"))
55}
56pub fn batch_phase_report() -> String {
57    let ph = BATCH_PHASE.lock().unwrap();
58    let tot: f64 = ph.iter().sum();
59    let mut rows: Vec<(usize, f64)> = ph.iter().copied().enumerate().collect();
60    rows.sort_by(|a, b| b.1.total_cmp(&a.1));
61    let mut s = format!("[batch-phase] total {:.1} ms (sync-bounded; shares rank, not walltime)\n", tot * 1e3);
62    for (i, v) in rows {
63        s += &format!("  {:>6.1} ms {:>5.1}%  {}\n", v * 1e3, v / tot * 100.0, BATCH_PHASE_NAMES[i]);
64    }
65    s
66}
67
68impl HybridModel {
69    /// Batched-decode width cap. 8 = the exactness-tier default (see the assert below);
70    /// MEMRA_DECODE_BATCH_CAP overrides for tier-probe measurement, clamped to 32.
71    pub fn decode_batch_cap() -> usize {
72        use std::sync::OnceLock;
73        static CAP: OnceLock<usize> = OnceLock::new();
74        *CAP.get_or_init(|| {
75            std::env::var("MEMRA_DECODE_BATCH_CAP").ok()
76                .and_then(|v| v.parse().ok())
77                .map(|c: usize| c.clamp(1, 32))
78                .unwrap_or(8)
79        })
80    }
81
82    /// EXACT-16 TIER admission (increment 3a, 2026-08-01, 5090 receipts
83    /// research/batched-tick-inc3-20260801): true iff EVERY matmul the batched decode step
84    /// runs has a per-(token,row) bit-exact kernel class at m=9..16 under the verify_exact
85    /// scope — i.e. the batched-mmvq b16 family (32-thread warp reduce, the exact m=1 mmvq
86    /// program per column) or the e4m3 grid.y=m mmvq catch-all. Q8_0 qualifies only with
87    /// the split-plane mirror (rp4, MEMRA_Q8RP): its b16 kernel exists only as the _rp twin.
88    /// Float matmuls (cuBLASLt, n-dependent reductions) and MoE FFNs disqualify the model.
89    /// Measured attribution for WHY the naked m=16 tier is not exact: the m>=16 arms
90    /// (MMQ int8-MMA `mul_mat_q` — MEMRA_PP_Q8MMQ default-on — and `qmatvec_gemm`, both
91    /// block-scale f32) and the m=9..15 dp4a tail (128-thread two-level reduce) all break
92    /// per-row bit-identity vs isolated decode (gate2 step-0 bit-diffs, maxdiff ~1.3-2.3e-1).
93    pub fn decode_batch_exact16_ok(&self) -> bool {
94        fn ok(w: &crate::model::GpuTensor) -> bool {
95            match w {
96                crate::model::GpuTensor::Quant { qtype, rp4, .. } =>
97                    *qtype == crate::QT_Q4_0 || *qtype == crate::QT_Q6_K
98                    || *qtype == crate::QT_F8_E4M3
99                    || (*qtype == crate::QT_Q8_0 && rp4.is_some()),
100                _ => false,
101            }
102        }
103        if self.cfg.m3.is_some() || self.is_gemma4_e4b() || self.cfg.gemma4.is_some() {
104            return false;
105        }
106        self.layers.iter().all(|l| {
107            let mix_ok = match &l.mixer {
108                Mixer::Full(fa) => [&fa.wq, &fa.wk, &fa.wv, &fa.wo].into_iter().all(ok),
109                Mixer::Linear(la) => [&la.wqkv, &la.wqkv_gate, &la.ssm_beta,
110                                      &la.ssm_alpha, &la.ssm_out].into_iter().all(ok),
111                // MLA rides its own increment-4 arm; never admitted to the exact-16 tier here.
112                Mixer::Mla(_) => false,
113            };
114            let ffn_ok = match &l.ffn {
115                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } =>
116                    [ffn_gate, ffn_up, ffn_down].into_iter().all(ok),
117                crate::hybrid::Ffn::Moe(_) => false,
118            };
119            mix_ok && ffn_ok
120        }) && ok(&self.output)
121    }
122
123    /// One batched greedy-decode step over B independent sequences.
124    /// `tokens[b]` is sequence b's input token; `caches[b]` its private cache (position,
125    /// quantized KV, GDN/conv state). Returns the B logits rows (host, [n_vocab] each).
126    /// Each cache's pos/len advance exactly as `decode_step_h` would.
127    pub fn decode_step_batch(
128        &self,
129        e: &Engine,
130        tokens: &[u32],
131        caches: &mut [&mut Cache],
132    ) -> Result<Vec<Vec<f32>>, Box<dyn std::error::Error>> {
133        let (rows, _) = self.decode_step_batch_sampled(e, tokens, caches, &[])?;
134        Ok(rows)
135    }
136
137    /// `decode_step_batch` + DEVICE-SIDE SAMPLING for eligible rows (the batched-tick lever,
138    /// 2026-08-01): the host sampler's temp-path is O(n_vocab) with a full-vocab exp per row
139    /// (measured 1.36 ms/row at the 9B's 248320 vocab = 10.9 ms/tick at B=8 — the single
140    /// largest component of the serving tick). Here each requested row samples ON DEVICE
141    /// between the lm_head matmul and the logits D2H:
142    ///   temp <= 0 (greedy): the 2-pass device argmax — bit-identical to host argmax
143    ///     (argmax-gate contract, same kernels as the dc serving path).
144    ///   temp > 0: gumbel_perturb(seed, ctr, temp) + the same argmax = ONE categorical draw
145    ///     from softmax(logits/temp) — the sampled-spec Philox machinery. Deterministic per
146    ///     (seed, ctr) and INDEPENDENT of batch composition (the isolation contract;
147    ///     decode-batch-gate gate3). NOTE: the draw stream differs from the host sampler's
148    ///     SplitMix64 (distribution-equal, seed-deterministic, NOT byte-equal to the old
149    ///     host draws) — greedy rows are unchanged bit-exact.
150    /// `samp[bi] = Some((temp, seed, ctr))` requests a device sample for row bi; the full
151    /// logits rows are still returned (worker keeps last_logits semantics + fallback rows).
152    pub fn decode_step_batch_sampled(
153        &self,
154        e: &Engine,
155        tokens: &[u32],
156        caches: &mut [&mut Cache],
157        samp: &[Option<(f32, u64, u32)>],
158    ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
159        self.decode_step_batch_sampled_lean(e, tokens, caches, samp, false)
160    }
161
162    /// `decode_step_batch_sampled` + LEAN LOGITS (increment 2 component 3, 2026-08-01):
163    /// with `lean`, device-sampled rows SKIP the [n_vocab] logits D2H (9.4%/32.5% of the
164    /// pre-/post-inc2 tick profile) — their returned row is EMPTY. The audit-mapped
165    /// consumers: (a) the next tick's host sample — never fires, `device_next` carries the
166    /// token; (b) the graph-promotion argmax — reads only prefill logits (generated empty);
167    /// (c) the KV-reuse pool park at retire — the REAL consumer, served by a per-cache
168    /// device park: the row is dtod-copied into `cache.last_logits_dev` (device bandwidth)
169    /// and D2H'd ONCE at retire by the worker. Rows without a device sample keep a per-row
170    /// D2H. `lean=false` is bit-for-bit the previous method (gates + non-serving callers).
171    pub fn decode_step_batch_sampled_lean(
172        &self,
173        e: &Engine,
174        tokens: &[u32],
175        caches: &mut [&mut Cache],
176        samp: &[Option<(f32, u64, u32)>],
177        lean: bool,
178    ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
179        self.decode_step_batch_sampled_lean_masked(e, tokens, caches, samp, &[], lean)
180    }
181
182    /// `decode_step_batch_sampled_lean` + GRAMMAR MASKS (constrained decoding, 2026-08-03):
183    /// `masks[bi] = Some((packed_bitset, words))` bans every unset-bit vocab id on row bi
184    /// (mask_logits_f32, -FLT_MAX) BETWEEN the lm_head matmul and the device sampler, so a
185    /// constrained row rides the SAME device-sample/lean-logits tick as everyone else — no
186    /// full-row D2H, no host O(n_vocab) sample. Contract: a masked row must also request a
187    /// device sample. The row's PRISTINE logits are preserved for their consumers before the
188    /// in-place ban: lean rows park the unmasked row into `cache.last_logits_dev` (the
189    /// retire-time reuse-pool park stays unmasked — continuations resume grammar-free, the
190    /// v1 host-path contract), non-lean rows D2H the unmasked row. `masks = &[]` is
191    /// bit-for-bit the unmasked method.
192    pub fn decode_step_batch_sampled_lean_masked(
193        &self,
194        e: &Engine,
195        tokens: &[u32],
196        caches: &mut [&mut Cache],
197        samp: &[Option<(f32, u64, u32)>],
198        masks: &[Option<(&CudaSlice<u32>, usize)>],
199        lean: bool,
200    ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
201        // NOTE (inc3 3c, 2026-08-01, KILLED ARM): a deferred-token-readback variant (all
202        // chunks of a tick writing device-sampled tokens into one shared buffer, ONE
203        // dtoh_u32 after the last chunk instead of one per chunk) measured FLAT at serve
204        // level on the 5090 (N=4 medians within +-0.7% at c=8/16/32 — 3 saved syncs
205        // against a ~100 ms weight-bound tick is ~0.1%, below resolution). Killed per the
206        // flags doctrine; receipts research/batched-tick-inc3-20260801 (serve-points.jsonl
207        // base vs defer arms) are the record. The per-chunk [B]-u32 readback below IS the
208        // tick's only steady-state D2H — one per chunk, none per seq.
209        let b_n = tokens.len();
210        assert!(b_n >= 1 && b_n == caches.len(), "tokens/caches length mismatch");
211        // MEMRA_DECODE_BATCH_CAP (experimental door, serving-lane tier probe 2026-08-01):
212        // default 8 keeps the v1 exactness policy — B=2..8 rides the verify-tier batched
213        // mmvq arms, per-row bit-identical to isolated m=1 decode. Values >8 are a
214        // MEASUREMENT DOOR ONLY: m=9..15 falls to the grid.y=m dp4a tail (m weight
215        // re-reads + a different reduce shape) and m>=16 crosses into the GEMM tier
216        // (block-scale f32 rounding) — BOTH break the "byte-identical to isolated"
217        // serving contract. Never default this above 8 without the batched-tier
218        // exactness policy landing.
219        let cap = Self::decode_batch_cap();
220        // EXACT-16 TIER (increment 3a): chunks of 9..=16 are admitted WITHOUT the env door
221        // when every matmul has a bit-exact b16-class kernel (see decode_batch_exact16_ok).
222        // The verify_exact scope below pins that dispatch for the whole step: it turns off
223        // the m>=16 GEMM arms (qmatvec_gemm + MMQ + fp8/f16/fp4 — all block-scale/foreign
224        // numeric configs) so every projection rides the batched-mmvq b16 tier, which is
225        // per-(token,row) bit-identical to isolated m=1 decode (gate2 bit-strength PASS at
226        // B=12/16, s32+s160, 5090 receipts research/batched-tick-inc3-20260801). Without
227        // the exact tier, B>cap stays refused; the env door (MEMRA_DECODE_BATCH_CAP) keeps
228        // its old meaning as the non-exact measurement probe.
229        let exact16 = b_n > 8 && b_n <= 16 && self.decode_batch_exact16_ok();
230        assert!(
231            b_n <= cap || exact16,
232            "decode_step_batch: B={b_n} > cap {cap} with no exact tier (Q8_0 m>8 needs the \
233             q8rp mirror's b16 class; m>16 crosses GEMM/dp4a numeric configs) — refused"
234        );
235        struct ExactScope<'a>(&'a Engine, bool);
236        impl Drop for ExactScope<'_> {
237            fn drop(&mut self) {
238                if self.1 {
239                    self.0.set_verify_exact(false);
240                }
241            }
242        }
243        let _exact_scope = ExactScope(e, exact16);
244        if exact16 {
245            e.set_verify_exact(true);
246        }
247        assert!(
248            !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
249            "decode_step_batch v1 covers the hybrid non-gemma4 trunk only"
250        );
251        let cfg = &self.cfg;
252        let n_embd = cfg.n_embd as usize;
253        let eps = cfg.rms_eps;
254        let n_head = cfg.n_head as usize;
255        let n_head_kv = cfg.n_head_kv as usize;
256        let head_dim = cfg.head_dim_k as usize;
257        let scale = 1.0 / (head_dim as f32).sqrt();
258        let rope_dims = cfg.rope_dim_count as usize;
259
260        // Per-row rope positions (each sequence at its own depth).
261        let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
262        let pos_d = e.htod_i32(&pos_v)?;
263
264        // Per-step STATE POINTER TABLE (one H2D): for every linear layer, [conv x B]
265        // [ssm_in x B][ssm_out x B] device addresses. The batched state kernels read their
266        // sequence's pointer from these arrays — states stay per-cache (no pooling refactor),
267        // yet conv/prep/scan collapse from 3xB launches per layer to 3. Rebuilt every step
268        // because the ssm ping-pong swaps pointers host-side after each scan.
269        // INCREMENT 2 (2026-08-01): the SAME table now also carries, for every FULL-attn
270        // layer, [k0,v0,k1,v1,...] cache base addresses — the z-batched seqs append and
271        // seqs fa_decode kernels read their sequence's cache through it (the MoE
272        // expert-table pattern), collapsing 2xB launches per attn layer to 2.
273        let mut lin_base: Vec<Option<usize>> = vec![None; self.layers.len()];
274        let mut attn_base: Vec<Option<usize>> = vec![None; self.layers.len()];
275        let mut ptrs: Vec<u64> = Vec::new();
276        {
277            use cudarc::driver::DevicePtr;
278            let s = &e.gpu.stream();
279            for (il, layer) in self.layers.iter().enumerate() {
280                match &layer.mixer {
281                    Mixer::Linear(_) => {
282                        lin_base[il] = Some(ptrs.len());
283                        for c in caches.iter() {
284                            let rl = c.recur[il].as_ref().unwrap();
285                            let (p, _g) = rl.conv_state.device_ptr(s);
286                            ptrs.push(p as u64);
287                        }
288                        for c in caches.iter() {
289                            let rl = c.recur[il].as_ref().unwrap();
290                            let (p, _g) = rl.ssm_state.device_ptr(s);
291                            ptrs.push(p as u64);
292                        }
293                        for c in caches.iter() {
294                            let rl = c.recur[il].as_ref().unwrap();
295                            let (p, _g) = rl.ssm_state_alt.device_ptr(s);
296                            ptrs.push(p as u64);
297                        }
298                    }
299                    Mixer::Full(_) => {
300                        attn_base[il] = Some(ptrs.len());
301                        for c in caches.iter() {
302                            let kvl = c.kv[il].as_ref().unwrap();
303                            let (pk, _g) = kvl.k.device_ptr(s);
304                            let (pv, _g2) = kvl.v.device_ptr(s);
305                            ptrs.push(pk as u64);
306                            ptrs.push(pv as u64);
307                        }
308                    }
309                    Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
310                }
311            }
312        }
313        let ptr_table = if ptrs.is_empty() { None } else { Some(e.htod_u64(&ptrs)?) };
314
315        // INCREMENT 2 arm picks (per STEP — t_kv is layer-invariant within a tick):
316        // - seqs APPEND: format-only condition (per-row program is t_kv-independent);
317        //   default flash module only (fp8-KV rides the per-seq g-module path).
318        // - seqs FA: every row must take the v4 eager arm at ITS OWN t_kv AND all rows
319        //   must share ONE fa_split_keys rung (the rows-twins' straddle law) — a rung
320        //   crossing inside the batch keeps the per-seq loop for that step, so each
321        //   sequence always executes the exact program its isolated run would.
322        // MEMRA_BATCH_APPEND=0 / MEMRA_BATCH_FA=0 are the rollback/A-B seams.
323        let t_kvs: Vec<usize> = caches.iter().map(|c| c.pos + 1).collect();
324        let t_kv_max = *t_kvs.iter().max().unwrap();
325        let seqs_append = {
326            static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
327            *ON.get_or_init(|| std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0"))
328        } && !Engine::kv_fp8_on();
329        let sp0 = crate::fa_split_keys(t_kvs[0], cfg.n_head_kv as usize);
330        let seqs_fa = {
331            static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
332            *ON.get_or_init(|| std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0"))
333        } && t_kvs.iter().all(|&t| crate::fa_seqs_eligible(t, head_dim))
334          && t_kvs.iter().all(|&t| crate::fa_split_keys(t, cfg.n_head_kv as usize) == sp0);
335
336        // Embed all B tokens -> x [B, n_embd] (host gather, one H2D).
337        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
338
339        // MEMRA_BATCH_PHASE=1: sync-bounded phase accumulation (diagnostics — see header note).
340        let ph_on = batch_phase_on();
341        let mut ph_last = std::time::Instant::now();
342        let ph_mark = |slot: usize,
343                       last: &mut std::time::Instant|
344         -> Result<(), Box<dyn std::error::Error>> {
345            if ph_on {
346                e.stream().synchronize()?;
347                let now = std::time::Instant::now();
348                BATCH_PHASE.lock().unwrap()[slot] += (now - *last).as_secs_f64();
349                *last = now;
350            }
351            Ok(())
352        };
353        ph_mark(0, &mut ph_last)?;
354
355        for (il, layer) in self.layers.iter().enumerate() {
356            // ---- attn_norm + q8_1 quantize, batched (B rows) ----
357            let anorm = layer.attn_norm.float_data();
358            let mut xn = e.uninit(b_n * n_embd)?;
359            e.rms_norm(&x, anorm, &mut xn, n_embd, b_n, eps)?;
360            let (hq, hd) = e.quantize_q8_1(&xn, b_n, n_embd)?;
361
362            // ---- mixer ----
363            let mixed: CudaSlice<f32> = match &layer.mixer {
364                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
365                Mixer::Full(fa) => {
366                    // Batched projections: one weight read serves all B rows.
367                    let qf = e.matmul_pre(&fa.wq, &hq, &hd, &xn, b_n)?;
368                    let mut k = e.matmul_pre(&fa.wk, &hq, &hd, &xn, b_n)?;
369                    let v = e.matmul_pre(&fa.wv, &hq, &hd, &xn, b_n)?;
370
371                    let gated = cfg.attn_out_gate();
372                    let (mut q, gate) = if gated {
373                        let mut qs = e.uninit(b_n * n_head * head_dim)?;
374                        let mut gs = e.uninit(b_n * n_head * head_dim)?;
375                        e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, b_n)?;
376                        (qs, Some(gs))
377                    } else {
378                        (qf, None)
379                    };
380
381                    // QK-norm over B*n_head rows, rope with per-row positions.
382                    let mut qn = e.uninit(b_n * n_head * head_dim)?;
383                    e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, b_n * n_head, eps)?;
384                    q = qn;
385                    let mut kn = e.uninit(b_n * n_head_kv * head_dim)?;
386                    e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, b_n * n_head_kv, eps)?;
387                    k = kn;
388                    e.rope_neox(&mut q, &pos_d, head_dim, rope_dims, n_head, b_n,
389                                cfg.rope_freq_base, 1.0)?;
390                    e.rope_neox(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, b_n,
391                                cfg.rope_freq_base, 1.0)?;
392                    ph_mark(1, &mut ph_last)?;
393
394                    // INCREMENT 2 (2026-08-01): the per-seq (append, attend) launch train
395                    // becomes two phases. Phase A appends all B rows (one z-batched launch,
396                    // or the per-seq loop on the seam/fp8 path); phase B attends all B
397                    // sequences (one blockIdx.z launch + one combine on the batched arm —
398                    // which also reads q / writes attn at row offsets, killing the per-seq
399                    // q/a dtod copies — or the per-seq loop when any row is outside the v4
400                    // arm / a split rung crosses inside the batch). Caches are disjoint per
401                    // sequence, so the phase split leaves every row's math untouched.
402                    let q_dim = n_head * head_dim;
403                    let kv_dim = n_head_kv * head_dim;
404                    let mut attn = e.uninit(b_n * q_dim)?;
405                    // ---- phase A: KV append (all B rows) ----
406                    if seqs_append {
407                        let (kdk, kdv, ktb, vtb) = {
408                            let kvl = caches[0].kv[il].as_ref().unwrap();
409                            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes)
410                        };
411                        let base = attn_base[il].expect("full layer missing from pointer table");
412                        let table = ptr_table.as_ref().expect("pointer table missing");
413                        let kv_view = table.slice(base..base + 2 * b_n);
414                        e.append_kv_quantized_seqs(&k, &v, &kv_view, &pos_d, b_n,
415                                                   kdk, kdv, ktb, vtb)?;
416                        for cache in caches.iter_mut() {
417                            let kvl = cache.kv[il].as_mut().unwrap();
418                            debug_assert_eq!(kvl.len, cache.pos, "kv len / pos out of lockstep");
419                            kvl.len += 1;
420                        }
421                    } else {
422                        for (bi, cache) in caches.iter_mut().enumerate() {
423                            let kvl = cache.kv[il].as_mut().unwrap();
424                            let k_row = k.slice(bi * kv_dim..(bi + 1) * kv_dim);
425                            let v_row = v.slice(bi * kv_dim..(bi + 1) * kv_dim);
426                            e.append_kv_quantized_view(
427                                &k_row, &v_row, &mut kvl.k, &mut kvl.v, kvl.len,
428                                kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
429                                Engine::kv_fp8_on(),
430                            )?;
431                            kvl.len += 1;
432                        }
433                    }
434                    ph_mark(2, &mut ph_last)?;
435                    // ---- phase B: attention (all B sequences) ----
436                    if seqs_fa {
437                        let (ktb, vtb) = {
438                            let kvl = caches[0].kv[il].as_ref().unwrap();
439                            (kvl.k_tok_bytes, kvl.v_tok_bytes)
440                        };
441                        let base = attn_base[il].expect("full layer missing from pointer table");
442                        let table = ptr_table.as_ref().expect("pointer table missing");
443                        let kv_view = table.slice(base..base + 2 * b_n);
444                        e.fa_decode_batch_seqs_v4(&q, &kv_view, &pos_d, &mut attn,
445                                                  head_dim, n_head, n_head_kv, b_n,
446                                                  t_kv_max, scale, sp0, ktb, vtb)?;
447                        ph_mark(4, &mut ph_last)?;
448                    } else {
449                        for (bi, cache) in caches.iter_mut().enumerate() {
450                            let kvl = cache.kv[il].as_mut().unwrap();
451                            let t_kv = kvl.len;
452                            let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
453                            let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
454                            // fa_decode wants a q slice starting at row bi: the fallback arm
455                            // scratch-copies the row (q8-class µs cost); the seqs arm above
456                            // reads/writes row offsets in place.
457                            let mut q_row = e.uninit(q_dim)?;
458                            e.dtod_copy_view(&q.slice(bi * q_dim..(bi + 1) * q_dim), &mut q_row)?;
459                            ph_mark(3, &mut ph_last)?;
460                            let mut a_row = e.uninit(q_dim)?;
461                            e.fa_decode_kvmod(
462                                &q_row, &k_view, &v_view, &mut a_row, head_dim, n_head, n_head_kv,
463                                t_kv, scale, kvl.k_tok_bytes, kvl.v_tok_bytes, Engine::kv_fp8_on(),
464                            )?;
465                            ph_mark(4, &mut ph_last)?;
466                            e.dtod_copy_into(&a_row, &mut attn, bi * q_dim)?;
467                            ph_mark(3, &mut ph_last)?;
468                        }
469                    }
470
471                    // Output gate (element-wise — batches whole) + o-proj at m=B.
472                    let attn_g = match &gate {
473                        Some(g) => {
474                            let n = b_n * q_dim;
475                            let mut gsig = e.uninit(n)?;
476                            e.sigmoid(g, &mut gsig, n)?;
477                            let mut ag = e.uninit(n)?;
478                            e.mul(&attn, &gsig, &mut ag, n)?;
479                            ag
480                        }
481                        None => attn,
482                    };
483                    let o = e.matmul(&fa.wo, &attn_g, b_n)?;
484                    ph_mark(5, &mut ph_last)?;
485                    o
486                }
487                Mixer::Linear(la) => {
488                    // v2 (the B-scaling fix): the GDN mixer's PROJECTIONS carry the layer's
489                    // weight mass — batch them at m=B so wqkv/gate/beta/alpha/ssm_out stream
490                    // ONCE per step instead of once per sequence. Only the recurrent state ops
491                    // (fused conv ring, gdn prep, gdn scan) stay per-seq — they are state-bound
492                    // micro-kernels, not weight readers. Composition unchanged vs v1 (matmul_pre
493                    // == fused2 per (tensor,row); _bN mmvq per-row == m=1): same numeric config.
494                    let ssm = cfg.ssm.as_ref().expect("linear mixer requires ssm cfg");
495                    let d_state = ssm.state_size as usize;
496                    let num_k = ssm.group_count as usize;
497                    let num_v = ssm.time_step_rank as usize;
498                    let d_conv = ssm.conv_kernel as usize;
499                    let key_dim = d_state * num_k;
500                    let value_dim = d_state * num_v;
501                    let conv_dim = key_dim * 2 + value_dim;
502                    let gdn_scale = 1.0 / (d_state as f32).sqrt();
503
504                    // ---- batched projections (the weight win) ----
505                    let qkv_mixed = e.matmul_pre(&la.wqkv, &hq, &hd, &xn, b_n)?;
506                    let z = e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, b_n)?;
507                    let beta_raw = e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, b_n)?;
508                    let alpha = e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, b_n)?;
509                    ph_mark(6, &mut ph_last)?;
510
511                    // ---- batched recurrent state ops (3 launches for all B sequences) ----
512                    let base = lin_base[il].expect("linear layer missing from pointer table");
513                    let table = ptr_table.as_ref().expect("pointer table missing");
514                    let conv_view = table.slice(base..base + b_n);
515                    let in_view = table.slice(base + b_n..base + 2 * b_n);
516                    let out_view = table.slice(base + 2 * b_n..base + 3 * b_n);
517                    let mut conv_outs = e.uninit(b_n * conv_dim)?;
518                    e.ssm_conv1d_fused_decode_b(&qkv_mixed, &conv_view,
519                                                la.ssm_conv1d.float_data(), &mut conv_outs,
520                                                conv_dim, d_conv, b_n)?;
521                    let mut q_l2 = e.uninit(b_n * value_dim)?;
522                    let mut k_l2 = e.uninit(b_n * value_dim)?;
523                    let mut v_gd = e.uninit(b_n * value_dim)?;
524                    let mut beta_b = e.uninit(b_n * num_v)?;
525                    let mut g_log = e.uninit(b_n * num_v)?;
526                    e.gdn_prep_decode_b(&conv_outs, &beta_raw, &alpha,
527                                        la.ssm_dt.float_data(), la.ssm_a.float_data(),
528                                        &mut q_l2, &mut k_l2, &mut v_gd, &mut beta_b, &mut g_log,
529                                        d_state, num_v, num_k, key_dim, eps, conv_dim, b_n)?;
530                    let mut o_all = e.uninit(b_n * value_dim)?;
531                    e.gdn_scan_s128_batched(&q_l2, &k_l2, &v_gd, &g_log, &beta_b,
532                                            &in_view, &out_view, &mut o_all,
533                                            num_v, b_n, gdn_scale)?;
534                    // ping-pong: scan wrote each seq's alt buffer; swap host handles (the
535                    // NEXT step's table rebuild picks up the new canonical pointers).
536                    for cache in caches.iter_mut() {
537                        let rl = cache.recur[il].as_mut().unwrap();
538                        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
539                    }
540                    ph_mark(7, &mut ph_last)?;
541
542                    // ---- batched gated norm + out-projection ----
543                    let o = if e.uses_q8_1_fast(&la.ssm_out) {
544                        let (gq, gd) = e.gated_rmsnorm_q8_1(&o_all, la.ssm_norm.float_data(),
545                                                            &z, d_state, b_n * num_v, eps)?;
546                        let g0 = e.zeros(0)?;
547                        e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, b_n)?
548                    } else {
549                        let mut gn = e.uninit(b_n * value_dim)?;
550                        e.gated_rmsnorm(&o_all, la.ssm_norm.float_data(), &z, &mut gn,
551                                        d_state, b_n * num_v, eps)?;
552                        e.matmul(&la.ssm_out, &gn, b_n)?
553                    };
554                    ph_mark(8, &mut ph_last)?;
555                    o
556                }
557            };
558
559            // ---- residual add + post_attn_norm + FFN, batched ----
560            let pnorm = layer.post_attn_norm.float_data();
561            let mut x1 = e.uninit(b_n * n_embd)?;
562            let mut z = e.uninit(b_n * n_embd)?;
563            e.add_rms_norm(&x, &mixed, pnorm, &mut x1, &mut z, n_embd, b_n, eps)?;
564            let ffn_out = match &layer.ffn {
565                crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
566                    // v1 covers the SiLU family; M3's swigluoai clamp rides a scaled epilogue
567                    // (m=1 fused tier) — batched M3 lands with the batched-fusion pass.
568                    assert!(self.cfg.m3.is_none(),
569                            "decode_step_batch v1: M3 swigluoai FFN not yet batched");
570                    let n_ff = ffn_gate.out_features();
571                    let (zq, zd) = e.quantize_q8_1(&z, b_n, n_embd)?;
572                    let g = e.matmul_pre(ffn_gate, &zq, &zd, &z, b_n)?;
573                    let u = e.matmul_pre(ffn_up, &zq, &zd, &z, b_n)?;
574                    let mut act = e.uninit(b_n * n_ff)?;
575                    e.silu_mul(&g, &u, &mut act, b_n * n_ff)?;
576                    let (aq, ad) = e.quantize_q8_1(&act, b_n, n_ff)?;
577                    e.matmul_pre(ffn_down, &aq, &ad, &act, b_n)?
578                }
579                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &z, None, b_n, il as u16)?,
580            };
581            // next-layer input x = x1 + ffn_out (batched element-wise add)
582            let mut x2 = e.uninit(b_n * n_embd)?;
583            e.add(&x1, &ffn_out, &mut x2, b_n * n_embd)?;
584            x = x2;
585            ph_mark(9, &mut ph_last)?;
586        }
587
588        // ---- output norm + lm_head at m=B, one D2H ----
589        let mut hn = e.uninit(b_n * n_embd)?;
590        e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, b_n, eps)?;
591        let logits = e.matmul(&self.output, &hn, b_n)?;
592        ph_mark(10, &mut ph_last)?;
593
594        // GRAMMAR MASKS (constrained decoding): preserve each masked row's PRISTINE logits
595        // for its consumer (lean park into cache.last_logits_dev — the reuse-pool park stays
596        // unmasked, the v1 contract — or the non-lean D2H), then ban in place BEFORE the
597        // device sampler reads the row. All stream-ordered; masks=&[] takes no new branch.
598        let n_vocab = self.output.out_features();
599        let mut logits = logits;
600        let mut pristine: Vec<Option<CudaSlice<f32>>> = Vec::new();
601        if masks.iter().take(b_n).any(|m| m.is_some()) {
602            pristine.resize_with(b_n, || None);
603            for (bi, m) in masks.iter().take(b_n).enumerate() {
604                let Some((mask, words)) = m else { continue };
605                assert!(samp.get(bi).copied().flatten().is_some(),
606                        "grammar-masked row {bi} must request a device sample");
607                if lean {
608                    let cache = &mut caches[bi];
609                    if cache.last_logits_dev.as_ref().map(|d| d.len() < n_vocab).unwrap_or(true) {
610                        cache.last_logits_dev = Some(e.uninit(n_vocab)?);
611                    }
612                    let dst = cache.last_logits_dev.as_mut().unwrap();
613                    e.dtod_copy_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab), dst)?;
614                } else {
615                    let mut p = e.uninit(n_vocab)?;
616                    e.dtod_copy_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab), &mut p)?;
617                    pristine[bi] = Some(p);
618                }
619                e.mask_logits_col(&mut logits, mask, bi, n_vocab, *words)?;
620            }
621        }
622
623        // Device-side sampling for requested rows (see the method doc). Enqueued before the
624        // big logits D2H so the tiny [B] token readback rides the same sync.
625        let mut next: Vec<Option<u32>> = vec![None; b_n];
626        if samp.iter().take(b_n).any(|s| s.is_some()) {
627            let mut toks = e.alloc_u32_zeroed(b_n)?;
628            let mut perturb: Option<CudaSlice<f32>> = None;
629            for (bi, s) in samp.iter().take(b_n).enumerate() {
630                let Some((temp, seed, ctr)) = s else { continue };
631                if *temp <= 0.0 {
632                    e.argmax_token_device_col(&logits, bi, n_vocab, &mut toks, bi)?;
633                } else {
634                    if perturb.is_none() {
635                        perturb = Some(e.zeros(n_vocab)?);
636                    }
637                    let pb = perturb.as_mut().unwrap();
638                    e.gumbel_perturb_col(&logits, bi, pb, n_vocab, *seed, *ctr, *temp)?;
639                    e.argmax_token_device_col(pb, 0, n_vocab, &mut toks, bi)?;
640                }
641            }
642            let host_toks = e.dtoh_u32(&toks)?;
643            for (bi, s) in samp.iter().take(b_n).enumerate() {
644                if s.is_some() {
645                    next[bi] = Some(host_toks[bi]);
646                }
647            }
648        }
649
650        let lean_any = lean && samp.iter().take(b_n).any(|s| s.is_some());
651        let rows: Vec<Vec<f32>> = if lean_any {
652            // LEAN: park device-sampled rows on-device (per-cache buffer, dtod); D2H only
653            // the rows that still need host logits. No sampled rows + no fallback rows =
654            // the big D2H disappears (the [B] token readback above already synced).
655            for (bi, s) in samp.iter().take(b_n).enumerate() {
656                if s.is_none() { continue; }
657                // grammar-masked rows already parked their PRISTINE copy above — the
658                // in-place ban has since poisoned this row for the reuse-pool consumer.
659                if masks.get(bi).copied().flatten().is_some() { continue; }
660                let cache = &mut caches[bi];
661                if cache.last_logits_dev.as_ref().map(|d| d.len() < n_vocab).unwrap_or(true) {
662                    cache.last_logits_dev = Some(e.uninit(n_vocab)?);
663                }
664                let dst = cache.last_logits_dev.as_mut().unwrap();
665                e.dtod_copy_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab), dst)?;
666            }
667            (0..b_n)
668                .map(|bi| {
669                    if samp.get(bi).copied().flatten().is_some() {
670                        Ok(Vec::new())
671                    } else {
672                        e.dtoh_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab))
673                    }
674                })
675                .collect::<Result<_, _>>()?
676        } else {
677            let host = e.dtoh(&logits)?;
678            (0..b_n).map(|bi| {
679                // grammar-masked non-lean rows return the PRISTINE copy (the in-place ban
680                // must never leak into last_logits — reuse-pool/park semantics unchanged).
681                if let Some(p) = pristine.get(bi).and_then(|p| p.as_ref()) {
682                    return e.dtoh(p);
683                }
684                Ok(host[bi * n_vocab..(bi + 1) * n_vocab].to_vec())
685            }).collect::<Result<_, _>>()?
686        };
687        for c in caches.iter_mut() {
688            c.pos += 1;
689        }
690        ph_mark(11, &mut ph_last)?;
691        Ok((rows, next))
692    }
693}