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::{CudaEvent, CudaSlice};
33use memra_gguf::config::Arch;
34
35type DualPpCudaSpan = Option<(CudaEvent, CudaEvent)>;
36
37fn dual_pp_timing_event(e: &Engine, context: &str) -> Option<CudaEvent> {
38 if !crate::pp::dual_pp_timing_on() {
39 return None;
40 }
41 match e.stream().record_event(Some(
42 cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT,
43 )) {
44 Ok(event) => Some(event),
45 Err(err) => {
46 crate::pp::record_dual_pp_timing_drop(context, &err);
47 None
48 }
49 }
50}
51
52/// Per-step, per-LAYER-RANGE invariants the batched trunk needs: the device state-pointer
53/// table for the range's layers, the arm picks, and the per-row `t_kv` snapshot. Built once
54/// per step per range by `HybridModel::batch_layer_ctx`, consumed by `decode_batch_layers`.
55///
56/// WHY IT IS RANGE-SCOPED AND NOT STEP-SCOPED (this is the whole point of the struct):
57/// `ptr_table` is a `CudaSlice<u64>` of DEVICE ADDRESSES, uploaded through `e` — so it lives
58/// on `e`'s device, and its entries are pointers into caches that live on the device that
59/// OWNS those layers. Under a pp stage split, stage s runs layers [fence[s], fence[s+1])
60/// whose cache state was allocated by stage s's engine (`pp::new_cache` -> `Cache::new_ppn`),
61/// so stage s must build its OWN table through its OWN engine. One step-wide table built on
62/// the primary would put every stage's kernel arguments in stage-0's HBM — a peer read per
63/// pointer fetch, which is the exact cliff `pp::refuse_unsplit_if_remote` exists to stop.
64/// `lo`/`hi` are recorded so the consumer can assert the ctx it was handed matches the range
65/// it was asked to run (the offsets in `lin_base`/`attn_base` are only valid for that range).
66pub(crate) struct BatchLayerCtx {
67 /// Offset into `ptr_table` of layer il's [conv x B][ssm_in x B][ssm_out x B] block
68 /// (linear-attn layers only). Indexed by ABSOLUTE layer id; `None` off-range.
69 lin_base: Vec<Option<usize>>,
70 /// Offset into `ptr_table` of layer il's [k0,v0,k1,v1,..] block (full-attn layers only).
71 /// Indexed by ABSOLUTE layer id; `None` off-range.
72 attn_base: Vec<Option<usize>>,
73 ptr_table: Option<CudaSlice<u64>>,
74 /// Per-row `pos + 1` — the t_kv each sequence attends at this step. Layer-invariant
75 /// within a step, so the arm picks below are decided once.
76 t_kvs: Vec<usize>,
77 t_kv_max: usize,
78 /// The single `fa_split_keys` rung every row shares (the rows-twins straddle law).
79 sp0: usize,
80 seqs_append: bool,
81 seqs_fa: bool,
82 lo: usize,
83 hi: usize,
84}
85
86// ---- MEMRA_BATCH_PHASE=1 (diagnostics): sync-bounded per-phase accumulators for the batched
87// tick. Each boundary syncs the stream, so the TOTAL inflates (launch pipelining is destroyed);
88// the value is the RANKING/shares, not absolute ms. Read via `batch_phase_report()`.
89pub(crate) static BATCH_PHASE: std::sync::Mutex<[f64; 12]> = std::sync::Mutex::new([0.0; 12]);
90pub const BATCH_PHASE_NAMES: [&str; 12] = [
91 "setup(ptrs+embed H2D)",
92 "attn batched pre (norm/qkv/rope)",
93 "attn per-seq: kv append",
94 "attn per-seq: q/a dtod copies",
95 "attn per-seq: fa_decode",
96 "attn post (gate+o-proj)",
97 "gdn batched projections",
98 "gdn state ops (conv/prep/scan)",
99 "gdn out (gated norm+proj)",
100 "ffn (add/norm/gate/up/act/down)",
101 "lm_head (norm+matmul)",
102 "logits D2H + host split",
103];
104pub fn batch_phase_on() -> bool {
105 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
106 *ON.get_or_init(|| std::env::var("MEMRA_BATCH_PHASE").as_deref() == Ok("1"))
107}
108/// Accumulate the elapsed time since `last` into phase slot `slot` and re-stamp `last`.
109/// No-op unless `MEMRA_BATCH_PHASE=1`. Syncs the ambient stream first, so under a pp stage
110/// scope this bounds the STAGE's stream, which is what the caller is timing.
111///
112/// A free fn rather than the closure it replaced: `decode_batch_layers` (the pp stage seam)
113/// runs the instrumented layer loop, so the marker has to be callable from both the seam
114/// and its caller's epilogue. `batch_phase_on()` is a `OnceLock` memo, so per-call cost is
115/// the same atomic load the hoisted `ph_on` local was.
116fn ph_mark(
117 e: &Engine,
118 slot: usize,
119 last: &mut std::time::Instant,
120) -> Result<(), Box<dyn std::error::Error>> {
121 if batch_phase_on() {
122 e.stream().synchronize()?;
123 let now = std::time::Instant::now();
124 BATCH_PHASE.lock().unwrap()[slot] += (now - *last).as_secs_f64();
125 *last = now;
126 }
127 Ok(())
128}
129
130pub fn batch_phase_report() -> String {
131 let ph = BATCH_PHASE.lock().unwrap();
132 let tot: f64 = ph.iter().sum();
133 let mut rows: Vec<(usize, f64)> = ph.iter().copied().enumerate().collect();
134 rows.sort_by(|a, b| b.1.total_cmp(&a.1));
135 let mut s = format!("[batch-phase] total {:.1} ms (sync-bounded; shares rank, not walltime)\n", tot * 1e3);
136 for (i, v) in rows {
137 s += &format!(" {:>6.1} ms {:>5.1}% {}\n", v * 1e3, v / tot * 100.0, BATCH_PHASE_NAMES[i]);
138 }
139 s
140}
141
142impl HybridModel {
143 /// Batched-decode width cap. 8 = the exactness-tier default (see the assert below);
144 /// MEMRA_DECODE_BATCH_CAP overrides for tier-probe measurement, clamped to 32.
145 pub fn decode_batch_cap() -> usize {
146 use std::sync::OnceLock;
147 static CAP: OnceLock<usize> = OnceLock::new();
148 *CAP.get_or_init(|| {
149 std::env::var("MEMRA_DECODE_BATCH_CAP").ok()
150 .and_then(|v| v.parse().ok())
151 .map(|c: usize| c.clamp(1, 32))
152 .unwrap_or(8)
153 })
154 }
155
156 /// EXACT-16 TIER admission (increment 3a, 2026-08-01, 5090 receipts
157 /// research/batched-tick-inc3-20260801): true iff EVERY matmul the batched decode step
158 /// runs has a per-(token,row) bit-exact kernel class at m=9..16 under the verify_exact
159 /// scope — i.e. the batched-mmvq b16 family (32-thread warp reduce, the exact m=1 mmvq
160 /// program per column) or the e4m3 grid.y=m mmvq catch-all. Q8_0 qualifies only with
161 /// the split-plane mirror (rp4, MEMRA_Q8RP): its b16 kernel exists only as the _rp twin.
162 /// Float matmuls (cuBLASLt, n-dependent reductions) and MoE FFNs disqualify the model.
163 /// Measured attribution for WHY the naked m=16 tier is not exact: the m>=16 arms
164 /// (MMQ int8-MMA `mul_mat_q` — MEMRA_PP_Q8MMQ default-on — and `qmatvec_gemm`, both
165 /// block-scale f32) and the m=9..15 dp4a tail (128-thread two-level reduce) all break
166 /// per-row bit-identity vs isolated decode (gate2 step-0 bit-diffs, maxdiff ~1.3-2.3e-1).
167 pub fn decode_batch_exact16_ok(&self) -> bool {
168 fn ok(w: &crate::model::GpuTensor) -> bool {
169 match w {
170 crate::model::GpuTensor::Quant { qtype, .. } =>
171 *qtype == crate::QT_Q4_0 || *qtype == crate::QT_Q6_K
172 || *qtype == crate::QT_F8_E4M3
173 // BLOCK-128 FP8-ST (lane/rp-on-st, 2026-08-06): admitted now that the class
174 // has a b16 batched kernel (`qmatvec_e4m3_blk_mmvq_b16`), bit-identical per
175 // (token,row) to its m=1 launch. Before that kernel existed this class fell to
176 // the grid.y=m form at every width — still EXACT, so the tier's correctness
177 // bar was met, but it re-read the weight m times, which is why admitting it
178 // without the kernel would have been a throughput trap rather than a win.
179 || *qtype == crate::QT_F8_E4M3_BLK
180 // NVFP4 (lane/rp-on-st, 2026-08-06) — THE blocker this lane measured. The
181 // mixed FP8-ST 27B is 193 NVFP4 dense-MLP tensors, and this predicate is an
182 // ALL over every matmul, so NVFP4's missing b16 refused the whole checkpoint
183 // (`B=16 > cap 8 with no exact tier ... refused`) even with both e4m3 classes
184 // admitted. It now has base + _rp b16 twins off its existing batched template
185 // (bit-identical per (token,row) to the m=1 mmvq: same nibble decode, dp4a
186 // order, ue4m3 scale, warp reduce). This also opens the tier for pure-NVFP4
187 // GGUF models, which is a behavior change on the primary format — hence the
188 // full decode-batch config+strict battery on both.
189 || *qtype == crate::QT_NVFP4
190 // Q4_K (lane/rp-on-st): named by MEMRA_EXACT16_WHY as the 9B NVFP4 GGUF's
191 // refusing class (`L0.wqkv qtype=1`) — mixed NVFP4 checkpoints keep Q4_K
192 // attention. Now has base + _rp b16.
193 || *qtype == crate::QT_Q4_K
194 // Q5_K (lane/rp-on-st): the FOURTH class the diagnostic named on the same 9B
195 // GGUF (`L0.wqkv_gate qtype=3`). A shipped mixed checkpoint spreads ~500
196 // matmuls over four/five classes, and this predicate is an ALL — so chunk 16
197 // was unreachable for every real artifact until every class had a b16.
198 || *qtype == crate::QT_Q5_K
199 // Q8_0 NO LONGER requires the mirror (rp4): it has a base b16 too, so the
200 // tier is reachable at zero VRAM. Named by the diagnostic as the FP8-ST
201 // refusal — `L0.ssm_beta qtype=0 rp4=false`, a 23.9 MiB residual class that
202 // was gating chunk 16 for a 16.4 GiB checkpoint.
203 || *qtype == crate::QT_Q8_0,
204 _ => false,
205 }
206 }
207 // WHY-NOT DIAGNOSTIC (lane/rp-on-st, 2026-08-06): this predicate is a bare bool over
208 // ~500 tensors, so a refusal produced only `B=16 > cap 8 with no exact tier ... refused`
209 // with no way to tell WHICH class refused. That cost this lane two wrong hypotheses (the
210 // rp mirror, then e4m3-only) before the NVFP4 gap was found. MEMRA_EXACT16_WHY=1 names
211 // the first refusing tensor + its qtype. Diagnostic-only per flags doctrine; default off,
212 // zero cost when unread.
213 let why = std::env::var("MEMRA_EXACT16_WHY").is_ok();
214 macro_rules! chk {
215 ($t:expr, $label:expr) => {{
216 let r = ok($t);
217 if !r && why {
218 // qtype = -1 means the tensor is NOT Quant at all (a float/BF16/F16
219 // container), which the tier can never admit — a distinct diagnosis from
220 // "quantized, but in a class with no b16 kernel".
221 let (qt, rp4) = match $t {
222 crate::model::GpuTensor::Quant { qtype, rp4, .. } => (*qtype, rp4.is_some()),
223 _ => (-1, false),
224 };
225 eprintln!("[exact16] REFUSED by {} qtype={qt} rp4={rp4}", $label);
226 }
227 r
228 }};
229 }
230 if self.cfg.m3.is_some() || self.is_gemma4_e4b() || self.cfg.gemma4.is_some() {
231 if why { eprintln!("[exact16] REFUSED by architecture (m3/gemma4)"); }
232 return false;
233 }
234 self.layers.iter().enumerate().all(|(li, l)| {
235 let mix_ok = match &l.mixer {
236 Mixer::Full(fa) => chk!(&fa.wq, format!("L{li}.wq")) && chk!(&fa.wk, format!("L{li}.wk"))
237 && chk!(&fa.wv, format!("L{li}.wv")) && chk!(&fa.wo, format!("L{li}.wo")),
238 Mixer::Linear(la) => chk!(&la.wqkv, format!("L{li}.wqkv"))
239 && chk!(&la.wqkv_gate, format!("L{li}.wqkv_gate"))
240 && chk!(&la.ssm_beta, format!("L{li}.ssm_beta"))
241 && chk!(&la.ssm_alpha, format!("L{li}.ssm_alpha"))
242 && chk!(&la.ssm_out, format!("L{li}.ssm_out")),
243 // MLA rides its own increment-4 arm; never admitted to the exact-16 tier here.
244 Mixer::Mla(_) => { if why { eprintln!("[exact16] REFUSED by L{li} MLA mixer"); } false }
245 };
246 let ffn_ok = match &l.ffn {
247 crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } =>
248 chk!(ffn_gate, format!("L{li}.ffn_gate")) && chk!(ffn_up, format!("L{li}.ffn_up"))
249 && chk!(ffn_down, format!("L{li}.ffn_down")),
250 crate::hybrid::Ffn::Moe(_) => { if why { eprintln!("[exact16] REFUSED by L{li} MoE ffn"); } false }
251 };
252 mix_ok && ffn_ok
253 }) && chk!(&self.output, "output".to_string())
254 }
255
256 /// H3 rollback/A-B seam (serve-path phase 2): `MEMRA_SERVE_B1FAST=0` sends B=1 back
257 /// through the batched body (the pre-change tick, bit-for-bit). Default ON.
258 ///
259 /// EXACTNESS, stated precisely (measured on-box 2026-08-05, sm_120 q9 NVFP4-MTP):
260 /// the fast path is BIT-IDENTICAL TO `decode_step_h` — decode-batch-gate's STRICT
261 /// gate1 (`--mode strict`) PASSes with it ON and FAILs with it OFF at maxdiff
262 /// 1.591e-1. It is deliberately NOT bit-identical to the batched body: the two
263 /// carry the long-accepted decode-config FP-composition gap (same class gate1's
264 /// config mode tolerates), and this lever moves solo sessions onto the NAKED side
265 /// of it. That is the desired direction — a c=1 serve request now computes exactly
266 /// what `run-gen` computes for the same prompt. Token-stream receipts:
267 /// research/servepath-p2-20260805 (greedy 150 ids + seeded-sampled identical to the
268 /// run-gen oracle AND cross-arm, so the gap is sub-token here as designed).
269 ///
270 /// Read fresh (an `AtomicU8` memo, not a `OnceLock`): decode-batch-gate flips this
271 /// seam BETWEEN gates in-process — gate1 needs the fast path ON to prove bit-identity,
272 /// gate2 needs it pinned OFF to keep testing the batched body. A latch-once read would
273 /// bake whichever gate ran first, so the gate could never test both sides. The memo
274 /// caches the parse but `set_b1_fast` invalidates it.
275 pub fn b1_fast_on() -> bool {
276 // 0 = unknown/invalidated, 1 = off, 2 = on
277 match Self::b1_fast_memo().load(std::sync::atomic::Ordering::Relaxed) {
278 1 => false,
279 2 => true,
280 _ => {
281 let on = std::env::var("MEMRA_SERVE_B1FAST").as_deref() != Ok("0");
282 Self::b1_fast_memo()
283 .store(if on { 2 } else { 1 }, std::sync::atomic::Ordering::Relaxed);
284 on
285 }
286 }
287 }
288
289 fn b1_fast_memo() -> &'static std::sync::atomic::AtomicU8 {
290 static MEMO: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
291 &MEMO
292 }
293
294 /// Test/gate seam: force the B=1 fast path on or off for the rest of the process,
295 /// overriding the env. Used by decode-batch-gate to pin gate2's reference arm.
296 pub fn set_b1_fast(on: bool) {
297 Self::b1_fast_memo()
298 .store(if on { 2 } else { 1 }, std::sync::atomic::Ordering::Relaxed);
299 }
300
301 /// Whether this architecture may switch a live serving row onto the eager B=1 fusion
302 /// class. Qwen35-MoE must stay on the batched trunk at every width: its eager and batched
303 /// hybrid/MoE walks are each deterministic, but crossing B=1 -> B>=2 changes greedy token
304 /// ids and can introduce an early EOS (Q35 sellgate, 2026-08-12).
305 pub fn b1_fast_arch_eligible(&self) -> bool {
306 b1_fast_arch_eligible(&self.cfg.arch)
307 }
308
309 /// H3 body: the m=1 FUSED trunk (`decode_layers_eager` — shared verbatim with
310 /// `decode_step_h`/the ppN stages) plus the batched path's own serving epilogue
311 /// (grammar mask, device sample, lean-logits park). See the call-site comment in
312 /// `decode_step_batch_sampled_lean_masked` for why this is bit-identical.
313 fn decode_step_b1_fast(
314 &self,
315 e: &Engine,
316 token: u32,
317 caches: &mut [&mut Cache],
318 samp: &[Option<(f32, u64, u32)>],
319 masks: &[Option<(&CudaSlice<u32>, usize)>],
320 lean: bool,
321 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
322 let n_embd = self.cfg.n_embd as usize;
323 let eps = self.cfg.rms_eps;
324 let pos = caches[0].pos;
325 let pos_d = e.htod_i32(&[pos as i32])?;
326 let x = e.htod(&self.embd.gather(n_embd, &[token]))?;
327 // the SHARED m=1 trunk: same function decode_step_h runs, so every m=1 fusion
328 // (cross-layer add+norm+q8_1, fused SwiGLU, lever 1's gate+up dual) fires here.
329 let x = self.decode_layers_eager(e, x, 0, self.layers.len(), &pos_d, pos, caches[0])?;
330 let mut hn = e.uninit(n_embd)?;
331 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
332 let logits = e.matmul(&self.output, &hn, 1)?;
333
334 // ---- epilogue: byte-for-byte the batched path's, at b_n=1 ----
335 let n_vocab = self.output.out_features();
336 let mut logits = logits;
337 let mut pristine: Option<CudaSlice<f32>> = None;
338 if let Some((mask, words)) = masks.first().copied().flatten() {
339 assert!(samp.first().copied().flatten().is_some(),
340 "grammar-masked row 0 must request a device sample");
341 if lean {
342 let cache = &mut caches[0];
343 if cache.last_logits_dev.as_ref().map(|d| d.len() < n_vocab).unwrap_or(true) {
344 cache.last_logits_dev = Some(e.uninit(n_vocab)?);
345 }
346 let dst = cache.last_logits_dev.as_mut().unwrap();
347 e.dtod_copy_view(&logits.slice(0..n_vocab), dst)?;
348 } else {
349 let mut p = e.uninit(n_vocab)?;
350 e.dtod_copy_view(&logits.slice(0..n_vocab), &mut p)?;
351 pristine = Some(p);
352 }
353 e.mask_logits_col(&mut logits, mask, 0, n_vocab, words)?;
354 }
355
356 let mut next: Vec<Option<u32>> = vec![None; 1];
357 if let Some((temp, seed, ctr)) = samp.first().copied().flatten() {
358 let mut toks = e.alloc_u32_zeroed(1)?;
359 if temp <= 0.0 {
360 e.argmax_token_device_col(&logits, 0, n_vocab, &mut toks, 0)?;
361 } else {
362 let mut pb = e.zeros(n_vocab)?;
363 e.gumbel_perturb_col(&logits, 0, &mut pb, n_vocab, seed, ctr, temp)?;
364 e.argmax_token_device_col(&pb, 0, n_vocab, &mut toks, 0)?;
365 }
366 next[0] = Some(e.dtoh_u32(&toks)?[0]);
367 }
368
369 let sampled = samp.first().copied().flatten().is_some();
370 let rows: Vec<Vec<f32>> = if lean && sampled {
371 if masks.first().copied().flatten().is_none() {
372 let cache = &mut caches[0];
373 if cache.last_logits_dev.as_ref().map(|d| d.len() < n_vocab).unwrap_or(true) {
374 cache.last_logits_dev = Some(e.uninit(n_vocab)?);
375 }
376 let dst = cache.last_logits_dev.as_mut().unwrap();
377 e.dtod_copy_view(&logits.slice(0..n_vocab), dst)?;
378 }
379 vec![Vec::new()]
380 } else if let Some(p) = pristine.as_ref() {
381 vec![e.dtoh(p)?]
382 } else {
383 vec![e.dtoh(&logits)?]
384 };
385 // decode_layers_eager does NOT advance cache.pos (decode_step_h advances it after
386 // the head); the batched path advances every cache at the tail — same here.
387 caches[0].pos += 1;
388 Ok((rows, next))
389 }
390
391 /// One batched greedy-decode step over B independent sequences.
392 /// `tokens[b]` is sequence b's input token; `caches[b]` its private cache (position,
393 /// quantized KV, GDN/conv state). Returns the B logits rows (host, [n_vocab] each).
394 /// Each cache's pos/len advance exactly as `decode_step_h` would.
395 pub fn decode_step_batch(
396 &self,
397 e: &Engine,
398 tokens: &[u32],
399 caches: &mut [&mut Cache],
400 ) -> Result<Vec<Vec<f32>>, Box<dyn std::error::Error>> {
401 let (rows, _) = self.decode_step_batch_sampled(e, tokens, caches, &[])?;
402 Ok(rows)
403 }
404
405 /// `decode_step_batch` + DEVICE-SIDE SAMPLING for eligible rows (the batched-tick lever,
406 /// 2026-08-01): the host sampler's temp-path is O(n_vocab) with a full-vocab exp per row
407 /// (measured 1.36 ms/row at the 9B's 248320 vocab = 10.9 ms/tick at B=8 — the single
408 /// largest component of the serving tick). Here each requested row samples ON DEVICE
409 /// between the lm_head matmul and the logits D2H:
410 /// temp <= 0 (greedy): the 2-pass device argmax — bit-identical to host argmax
411 /// (argmax-gate contract, same kernels as the dc serving path).
412 /// temp > 0: gumbel_perturb(seed, ctr, temp) + the same argmax = ONE categorical draw
413 /// from softmax(logits/temp) — the sampled-spec Philox machinery. Deterministic per
414 /// (seed, ctr) and INDEPENDENT of batch composition (the isolation contract;
415 /// decode-batch-gate gate3). NOTE: the draw stream differs from the host sampler's
416 /// SplitMix64 (distribution-equal, seed-deterministic, NOT byte-equal to the old
417 /// host draws) — greedy rows are unchanged bit-exact.
418 /// `samp[bi] = Some((temp, seed, ctr))` requests a device sample for row bi; the full
419 /// logits rows are still returned (worker keeps last_logits semantics + fallback rows).
420 pub fn decode_step_batch_sampled(
421 &self,
422 e: &Engine,
423 tokens: &[u32],
424 caches: &mut [&mut Cache],
425 samp: &[Option<(f32, u64, u32)>],
426 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
427 self.decode_step_batch_sampled_lean(e, tokens, caches, samp, false)
428 }
429
430 /// `decode_step_batch_sampled` + LEAN LOGITS (increment 2 component 3, 2026-08-01):
431 /// with `lean`, device-sampled rows SKIP the [n_vocab] logits D2H (9.4%/32.5% of the
432 /// pre-/post-inc2 tick profile) — their returned row is EMPTY. The audit-mapped
433 /// consumers: (a) the next tick's host sample — never fires, `device_next` carries the
434 /// token; (b) the graph-promotion argmax — reads only prefill logits (generated empty);
435 /// (c) the KV-reuse pool park at retire — the REAL consumer, served by a per-cache
436 /// device park: the row is dtod-copied into `cache.last_logits_dev` (device bandwidth)
437 /// and D2H'd ONCE at retire by the worker. Rows without a device sample keep a per-row
438 /// D2H. `lean=false` is bit-for-bit the previous method (gates + non-serving callers).
439 pub fn decode_step_batch_sampled_lean(
440 &self,
441 e: &Engine,
442 tokens: &[u32],
443 caches: &mut [&mut Cache],
444 samp: &[Option<(f32, u64, u32)>],
445 lean: bool,
446 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
447 self.decode_step_batch_sampled_lean_masked(e, tokens, caches, samp, &[], lean)
448 }
449
450 /// `decode_step_batch_sampled_lean` + GRAMMAR MASKS (constrained decoding, 2026-08-03):
451 /// `masks[bi] = Some((packed_bitset, words))` bans every unset-bit vocab id on row bi
452 /// (mask_logits_f32, -FLT_MAX) BETWEEN the lm_head matmul and the device sampler, so a
453 /// constrained row rides the SAME device-sample/lean-logits tick as everyone else — no
454 /// full-row D2H, no host O(n_vocab) sample. Contract: a masked row must also request a
455 /// device sample. The row's PRISTINE logits are preserved for their consumers before the
456 /// in-place ban: lean rows park the unmasked row into `cache.last_logits_dev` (the
457 /// retire-time reuse-pool park stays unmasked — continuations resume grammar-free, the
458 /// v1 host-path contract), non-lean rows D2H the unmasked row. `masks = &[]` is
459 /// bit-for-bit the unmasked method.
460 pub fn decode_step_batch_sampled_lean_masked(
461 &self,
462 e: &Engine,
463 tokens: &[u32],
464 caches: &mut [&mut Cache],
465 samp: &[Option<(f32, u64, u32)>],
466 masks: &[Option<(&CudaSlice<u32>, usize)>],
467 lean: bool,
468 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
469 self.decode_step_batch_sampled_lean_masked_schedule(
470 e, tokens, caches, samp, masks, lean, None,
471 )
472 }
473
474 /// Worker-scheduled twin of [`Self::decode_step_batch_sampled_lean_masked`]. The worker
475 /// supplies the balanced dual-wave boundary it used when forming this tick. Direct engine
476 /// callers keep the automatic midpoint above; the explicit seam makes scheduler chunking and
477 /// engine execution one checked contract instead of two coincident width calculations.
478 pub fn decode_step_batch_sampled_lean_masked_scheduled(
479 &self,
480 e: &Engine,
481 tokens: &[u32],
482 caches: &mut [&mut Cache],
483 samp: &[Option<(f32, u64, u32)>],
484 masks: &[Option<(&CudaSlice<u32>, usize)>],
485 lean: bool,
486 dual_wave_mid: usize,
487 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
488 self.decode_step_batch_sampled_lean_masked_schedule(
489 e, tokens, caches, samp, masks, lean, Some(dual_wave_mid),
490 )
491 }
492
493 #[allow(clippy::too_many_arguments)]
494 fn decode_step_batch_sampled_lean_masked_schedule(
495 &self,
496 e: &Engine,
497 tokens: &[u32],
498 caches: &mut [&mut Cache],
499 samp: &[Option<(f32, u64, u32)>],
500 masks: &[Option<(&CudaSlice<u32>, usize)>],
501 lean: bool,
502 scheduled_dual_mid: Option<usize>,
503 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
504 // NOTE (inc3 3c, 2026-08-01, KILLED ARM): a deferred-token-readback variant (all
505 // chunks of a tick writing device-sampled tokens into one shared buffer, ONE
506 // dtoh_u32 after the last chunk instead of one per chunk) measured FLAT at serve
507 // level on the 5090 (N=4 medians within +-0.7% at c=8/16/32 — 3 saved syncs
508 // against a ~100 ms weight-bound tick is ~0.1%, below resolution). Killed per the
509 // flags doctrine; receipts research/batched-tick-inc3-20260801 (serve-points.jsonl
510 // base vs defer arms) are the record. The per-chunk [B]-u32 readback below IS the
511 // tick's only steady-state D2H — one per chunk, none per seq.
512 let b_n = tokens.len();
513 assert!(b_n >= 1 && b_n == caches.len(), "tokens/caches length mismatch");
514 // ---- PP DOOR: THE BATCHED STAGE SPLIT (pp2-batch 2026-08-06) ----------------------
515 // Until this increment this body had NO pp arm: it walked lo=0..n_layers on the
516 // primary engine's stream, with no stage split, no boundary, and no `rt.enter()`. With
517 // the door open and a sharded cross-device placement, every projection for the remote
518 // stages' layers was read over PCIe, per step, silently — measured 7.4 vs 208.9 tok/s
519 // at B=1 (28x), 47.4 vs 657.0 at B=8 (13.9x) on a PRO 6000 pair over Gen5 x16 P2P.
520 // Nothing failed or warned, because peer reads return identical bytes and all three
521 // `decode-batch-gate` gates PASS on that config — the failure mode was performance,
522 // and a green exactness battery hid it. `pp2-hardening` made that regime FAIL CLOSED
523 // (research/pp2-hardening-20260806); this lane makes it legitimately split, so the
524 // refusal lifts for the batched path.
525 //
526 // `decode_step_batch_ppn` runs each stage's layer range through that stage's engine
527 // and stream with a [B, n_embd] boundary transfer between them, i.e. every stage
528 // touches only LOCAL weights and LOCAL cache state. The refusal below still guards
529 // the residue: the door open with `MEMRA_PP_STREAMS=0` (the same-stream rollback,
530 // which also disables the sharded loader, so nothing is remote — `pp_shard_off` and
531 // `pp2_streams_off` both make `pp_sharded_cross_device()` false) or a placement whose
532 // PpNRt fails to build. Keeping the call means a future path that reaches here in a
533 // remote regime still refuses instead of regressing 28x.
534 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
535 if !crate::pp::pp2_streams_off() && crate::pp::batch_pp_on() {
536 // Auto (flipped default) routes dual only in the re-gated regime and
537 // degrades serially elsewhere; Forced keeps every ineligible placement on
538 // the refusing dual body so the binding negative cells stay reachable.
539 let route_dual = crate::pp::dual_pp_route(
540 crate::pp::dual_pp_mode(),
541 b_n,
542 fence.len() - 1,
543 crate::pp::pp2_overlap(),
544 crate::pp::pp_host_bounce_active(),
545 );
546 if route_dual {
547 let mid = scheduled_dual_mid
548 .or_else(|| crate::pp::dual_pp_wave_mid(b_n))
549 .expect("dual PP B>=2 must have a wave midpoint");
550 return self.decode_step_batch_dual(
551 e, tokens, caches, samp, masks, lean, &fence, mid,
552 );
553 }
554 return self.decode_step_batch_ppn(
555 e, tokens, caches, samp, masks, lean, &fence,
556 );
557 }
558 }
559 if scheduled_dual_mid.is_some() {
560 return Err(
561 "decode_step_batch: worker supplied a dual-wave schedule but the PP-2 dual path is unavailable"
562 .into(),
563 );
564 }
565 crate::pp::refuse_unsplit_if_remote(
566 "decode_step_batch",
567 "drop MEMRA_PP_STREAMS=0 / MEMRA_BATCH_PP=0 so the batched path takes its OWN \
568 stage split (decode_step_batch_ppn), or serve single-stream over the eager pp \
569 arm (decode_step_h), which is also split",
570 )?;
571 // ---- H3: B=1 FAST-PATH (serve-path phase 2, 2026-08-05) ----------------------------
572 // At b_n==1 every projection below calls `matmul_pre(.., b_n)` with m=1, which is
573 // ALREADY the m=1 mmvq dispatch — so the m=1 *kernel family* was never the gap. What
574 // this body does NOT have is the m=1 *fusion chain* that `decode_step_h` carries:
575 // - the cross-layer add+norm+quantize fusion (`add_rms_norm_q8_1`: 3 launches -> 1),
576 // - the fused SwiGLU epilogue (`silu_mul_scaled_q8_1`: folds ffn_down's quantize
577 // into its producer) and, with it, `matmul_pre_dual_noscale`'s gate+up pair
578 // fusion — i.e. phase-1 LEVER 1.
579 // Routing b_n==1 through `decode_layers_eager` (the SHARED trunk `decode_step_h` and
580 // the ppN stages already use, lifted verbatim — not a copy) makes every present and
581 // future m=1 lever fire on the serve path automatically, which is the durable half of
582 // this change. The epilogue (grammar mask -> device sample -> lean logits park) is
583 // kept EXACTLY as the batched path runs it, so the serving contract is untouched.
584 // BIT-IDENTITY: the trunk is the same function `decode_step_h` calls, and every
585 // fusion it enables is kernel-check-pinned bit-identical to its unfused sequence
586 // (add_rms_norm == add;rms_norm | _q8_1 == +quantize_q8_1 | dual_noscale == two
587 // matmul_pre_noscale). Gate: decode-batch-gate B=1 vs decode_step_h + serve stream
588 // identity. MEMRA_SERVE_B1FAST=0 is the rollback/A-B seam.
589 if b_n == 1
590 && Self::b1_fast_on()
591 && self.b1_fast_arch_eligible()
592 && !self.is_gemma4_e4b()
593 && self.cfg.gemma4.is_none()
594 && self.cfg.m3.is_none()
595 && crate::pp::pp_cuts(self.layers.len()).is_none()
596 && !e.verify_exact_on()
597 {
598 return self.decode_step_b1_fast(e, tokens[0], caches, samp, masks, lean);
599 }
600 // MEMRA_DECODE_BATCH_CAP (experimental door, serving-lane tier probe 2026-08-01):
601 // default 8 keeps the v1 exactness policy — B=2..8 rides the verify-tier batched
602 // mmvq arms, per-row bit-identical to isolated m=1 decode. Values >8 are a
603 // MEASUREMENT DOOR ONLY: m=9..15 falls to the grid.y=m dp4a tail (m weight
604 // re-reads + a different reduce shape) and m>=16 crosses into the GEMM tier
605 // (block-scale f32 rounding) — BOTH break the "byte-identical to isolated"
606 // serving contract. Never default this above 8 without the batched-tier
607 // exactness policy landing.
608 let cap = Self::decode_batch_cap();
609 // EXACT-16 TIER (increment 3a): chunks of 9..=16 are admitted WITHOUT the env door
610 // when every matmul has a bit-exact b16-class kernel (see decode_batch_exact16_ok).
611 // The verify_exact scope below pins that dispatch for the whole step: it turns off
612 // the m>=16 GEMM arms (qmatvec_gemm + MMQ + fp8/f16/fp4 — all block-scale/foreign
613 // numeric configs) so every projection rides the batched-mmvq b16 tier, which is
614 // per-(token,row) bit-identical to isolated m=1 decode (gate2 bit-strength PASS at
615 // B=12/16, s32+s160, 5090 receipts research/batched-tick-inc3-20260801). Without
616 // the exact tier, B>cap stays refused; the env door (MEMRA_DECODE_BATCH_CAP) keeps
617 // its old meaning as the non-exact measurement probe.
618 let exact16 = b_n > 8 && b_n <= 16 && self.decode_batch_exact16_ok();
619 assert!(
620 b_n <= cap || exact16,
621 "decode_step_batch: B={b_n} > cap {cap} with no exact tier — refused. Either \
622 B>16 (there is NO exact kernel class above 16: m>16 crosses GEMM/dp4a numeric \
623 configs; the serve scheduler chunks wider concurrency into <=16 groups instead), \
624 or some matmul in this checkpoint has no bit-exact b16 kernel — run with \
625 MEMRA_EXACT16_WHY=1 to see which tensor and qtype refuses"
626 );
627 struct ExactScope<'a>(&'a Engine, bool);
628 impl Drop for ExactScope<'_> {
629 fn drop(&mut self) {
630 if self.1 {
631 self.0.set_verify_exact(false);
632 }
633 }
634 }
635 let _exact_scope = ExactScope(e, exact16);
636 if exact16 {
637 e.set_verify_exact(true);
638 }
639 // gemma4: NO batched arm at any B (per-layer SWA/global geometry, hd-512 MQA globals,
640 // weightless V-norm, softcapped head — none of it in the generic body below). This was
641 // an assert until 2026-08-07: one serve request panicked the worker, the respawn
642 // re-panicked on the queued request, and the process FATALed
643 // (research/gemma4-serve-20260807/raw/repro-panic-server-*.log). The worker now routes
644 // gemma4 sessions to the per-session eager loop and never calls here; this Err is the
645 // defense-in-depth backstop — a future path that reaches it refuses PER-REQUEST
646 // instead of killing the process. The eager arm (gemma4_decode_step_h) is the
647 // supported decode.
648 if self.is_gemma4_e4b() || self.cfg.gemma4.is_some() {
649 return Err("decode_step_batch has no gemma4 arm (per-layer swa/global geometry, \
650 softcapped head) — serve gemma4 on the eager per-session path".into());
651 }
652 // step35 (lane/step35-batched-decode, 2026-08-08): its OWN batched walk. The generic
653 // body below is the uniform Full arm — global n_head, 128-dim rope on every layer, no
654 // SWA window, no head-wise gate — which on step35 produced HTTP-200 GARBAGE at c>1
655 // (research/step-sku-20260807/raw/b2ab-pre-*.log), so step35 NEVER enters it at any B.
656 // `step35_decode_batch_layers` carries the real geometry: per-layer n_head (64/96),
657 // partial rope (64 full / 128 SWA, dual base, rope_freqs on FULL only), per-SESSION
658 // SWA view offsets from each session's own kvl.len, the separate head-wise gate at
659 // m=B, and the sigmoid-router MoE via the same moe_ffn_il_zq8 the eager path uses.
660 // MEMRA_STEP35_BATCH=0 = the fail-closed rollback seam. The server caps chunks at
661 // B=1; on PP-N the B=1 correctness default also refuses the eager numeric class, while
662 // an unsplit deployment can still use its existing eager B=1 route.
663 if self.cfg.step35.is_some() {
664 if !Self::step35_batch_on() {
665 return Err("step35 batched decode is disabled (MEMRA_STEP35_BATCH=0) — \
666 only a non-PP eager B=1 route remains available".into());
667 }
668 let n_embd = self.cfg.n_embd as usize;
669 let eps = self.cfg.rms_eps;
670 let mut ph_last = std::time::Instant::now();
671 let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
672 let pos_d = e.htod_i32(&pos_v)?;
673 let x = e.htod(&self.embd.gather(n_embd, tokens))?;
674 ph_mark(e, 0, &mut ph_last)?;
675 let x = self.step35_decode_batch_layers(
676 e, x, caches, &pos_d, 0, self.layers.len(), &mut ph_last)?;
677 let mut hn = e.uninit(b_n * n_embd)?;
678 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, b_n, eps)?;
679 let logits = e.matmul(&self.output, &hn, b_n)?;
680 ph_mark(e, 10, &mut ph_last)?;
681 return self.decode_batch_epilogue(
682 e, caches, samp, masks, lean, logits, b_n, &mut ph_last);
683 }
684 let n_embd = self.cfg.n_embd as usize;
685 let eps = self.cfg.rms_eps;
686
687 // MEMRA_BATCH_PHASE=1: sync-bounded phase accumulation (diagnostics — see header note).
688 // Initialized BEFORE the tick-input assembly below so slot 0 covers the HOST side of
689 // setup (pos_v/ptr-table builds, embed gather) as well as the H2D sync — the audit-fix
690 // lane's Q6 instrumentation gap (research/audit-fixes2-20260805): the old placement
691 // started the clock after the assembly, so slot 0 under-reported setup.
692 let mut ph_last = std::time::Instant::now();
693
694 // Per-row rope positions (each sequence at its own depth).
695 let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
696 let pos_d = e.htod_i32(&pos_v)?;
697
698 // Per-step, whole-trunk layer context: state pointer table + arm picks. Under a pp
699 // split this call is made once PER STAGE with that stage's engine and range instead
700 // (see `batch_layer_ctx`'s doc for why the table cannot be shared across devices).
701 let n_layers = self.layers.len();
702 let ctx = self.batch_layer_ctx(e, caches, 0, n_layers)?;
703
704 // Embed all B tokens -> x [B, n_embd] (host gather, one H2D).
705 let x = e.htod(&self.embd.gather(n_embd, tokens))?;
706 ph_mark(e, 0, &mut ph_last)?;
707
708 let x = self.decode_batch_layers(e, x, caches, &ctx, &pos_d, &mut ph_last)?;
709
710 // ---- output norm + lm_head at m=B, one D2H ----
711 let mut hn = e.uninit(b_n * n_embd)?;
712 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, b_n, eps)?;
713 let logits = e.matmul(&self.output, &hn, b_n)?;
714 ph_mark(e, 10, &mut ph_last)?;
715
716 self.decode_batch_epilogue(e, caches, samp, masks, lean, logits, b_n, &mut ph_last)
717 }
718
719 /// DUAL-ACTIVE PP-2 DECODE (increment 0): split one batch into wave A/B and drive
720 /// stage 0(B) from a scoped host walker while this thread drives stage 1(A). Step's
721 /// per-layer router readback synchronizes the host, so two CUDA streams issued by one
722 /// host thread would remain serial; this mirrors the proven prime PP-2 host schedule.
723 ///
724 /// This arm is the naked PP-2 default since the 2026-08-11 owner flip (`MEMRA_DUAL_PP`
725 /// unset = Auto; `0` is the serial rollback seam). It is fail-closed unless the
726 /// double-slot door is open, prewarms both slots, and uses `tx_pipelined` exclusively.
727 #[allow(clippy::too_many_arguments)]
728 fn decode_step_batch_dual(
729 &self,
730 e: &Engine,
731 tokens: &[u32],
732 caches: &mut [&mut Cache],
733 samp: &[Option<(f32, u64, u32)>],
734 masks: &[Option<(&CudaSlice<u32>, usize)>],
735 lean: bool,
736 fence: &[usize],
737 mid: usize,
738 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
739 let b_n = tokens.len();
740 assert!(b_n >= 1 && b_n == caches.len(), "tokens/caches length mismatch");
741 let Some(expected_mid) = crate::pp::dual_pp_wave_mid(b_n) else {
742 return self.decode_step_batch_ppn(e, tokens, caches, samp, masks, lean, fence);
743 };
744 if mid != expected_mid {
745 return Err(format!(
746 "decode_step_batch_dual: worker midpoint {mid} is not the balanced midpoint {expected_mid} for B={b_n}"
747 ).into());
748 }
749 if self.is_gemma4_e4b() || self.cfg.gemma4.is_some() {
750 return Err("decode_step_batch_dual has no gemma4 arm — serve gemma4 on the eager \
751 per-session path".into());
752 }
753 assert!(samp.is_empty() || samp.len() == b_n,
754 "decode_step_batch_dual: samp must be empty or have one entry per row");
755 assert!(masks.is_empty() || masks.len() == b_n,
756 "decode_step_batch_dual: masks must be empty or have one entry per row");
757
758 let cap = Self::decode_batch_cap();
759 let max_wave = mid.max(b_n - mid);
760 let exact16 = max_wave > 8 && max_wave <= 16 && self.decode_batch_exact16_ok();
761 if max_wave > cap && !exact16 {
762 return Err(format!(
763 "decode_step_batch_dual: B={b_n} waves {mid}+{} exceed per-wave cap {cap} with no exact tier — refused",
764 b_n - mid,
765 ).into());
766 }
767 let n_st = fence.len() - 1;
768 crate::pp::dual_pp_eligibility(
769 n_st,
770 crate::pp::pp2_overlap(),
771 crate::pp::pp_host_bounce_active(),
772 )
773 .map_err(|msg| -> Box<dyn std::error::Error> { msg.into() })?;
774 let rt = crate::pp::PpNRt::get(e)?;
775 assert_eq!(rt.n_stages(), n_st,
776 "PpNRt stage count {} != fence stages {n_st}", rt.n_stages());
777 let caller_stream = e.stream();
778 rt.fence_stages_behind(&caller_stream)?;
779
780 let n_embd = self.cfg.n_embd as usize;
781 let wave_cap = mid.max(b_n - mid) * n_embd;
782 rt.prepare_overlap_slots(0, wave_cap)?;
783
784 // EXACT-16 is a property of either scheduled wave, not the combined live width. Keep
785 // the scope live across both host walkers and set it on both stage-owned Engines.
786 struct ExactScopeN<'a>(Vec<&'a Engine>);
787 impl Drop for ExactScopeN<'_> {
788 fn drop(&mut self) {
789 for eng in &self.0 {
790 eng.set_verify_exact(false);
791 }
792 }
793 }
794 let _exact_scope = if exact16 {
795 let engines: Vec<&Engine> = (0..n_st).map(|s| rt.engine(s, e)).collect();
796 for eng in &engines {
797 eng.set_verify_exact(true);
798 }
799 Some(ExactScopeN(engines))
800 } else {
801 None
802 };
803
804 let step35_batched = self.cfg.step35.is_some();
805 if step35_batched && !Self::step35_batch_on() {
806 return Err("step35 batched decode is disabled (MEMRA_STEP35_BATCH=0) — \
807 dual-active PP-2 decode has no correct fallback trunk".into());
808 }
809
810 let (tokens_a, tokens_b) = tokens.split_at(mid);
811 let (caches_a, caches_b) = caches.split_at_mut(mid);
812 let (samp_a, samp_b) = if samp.is_empty() { (&[][..], &[][..]) }
813 else { samp.split_at(mid) };
814 let (masks_a, masks_b) = if masks.is_empty() { (&[][..], &[][..]) }
815 else { masks.split_at(mid) };
816
817 let (slot_a, ph_a, span_a0) = self.decode_step_batch_dual_stage0(
818 e, rt, tokens_a, caches_a, fence, step35_batched, false,
819 )?;
820
821 static LOGGED: std::sync::Once = std::sync::Once::new();
822 LOGGED.call_once(|| {
823 eprintln!("[dual-pp] dual-active PP-2 decode engaged (naked default since 2026-08-11; two waves)");
824 });
825
826 let (out_a, out_b, span_b0, span_b1) = std::thread::scope(
827 |scope| -> Result<_, Box<dyn std::error::Error>> {
828 let stage0_b = scope.spawn(move || {
829 let staged = self.decode_step_batch_dual_stage0(
830 e, rt, tokens_b, caches_b, fence, step35_batched, true,
831 ).map_err(|err| err.to_string())?;
832 Ok::<_, String>((staged, caches_b))
833 });
834
835 let out_a = self.decode_step_batch_dual_stage1(
836 e, rt, slot_a, caches_a, samp_a, masks_a, lean, fence,
837 step35_batched, ph_a, true,
838 )?;
839 let ((slot_b, ph_b, span_b0), caches_b) = stage0_b
840 .join()
841 .map_err(|_| "dual PP stage-0 wave-B host walker panicked")?
842 .map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
843 if !crate::pp::record_dual_pp_slot_pair(slot_a, slot_b) {
844 return Err(format!(
845 "decode_step_batch_dual: refused: wave A and B both selected boundary slot {slot_a}"
846 ).into());
847 }
848 let (out_b, span_b1) = self.decode_step_batch_dual_stage1(
849 e, rt, slot_b, caches_b, samp_b, masks_b, lean, fence,
850 step35_batched, ph_b, false,
851 )?;
852 Ok((out_a, out_b, span_b0, span_b1))
853 },
854 )?;
855
856 // Wave B is the final producer. One event publishes all last-stage work back to the
857 // caller after both epilogues, preserving the ordinary PP-N exit law.
858 rt.publish_to(1, &caller_stream)?;
859 let (out_a, span_a1) = out_a;
860 for (stage, span) in [span_a0, span_a1, span_b0, span_b1].into_iter().enumerate() {
861 if let Some((start, end)) = span {
862 crate::pp::record_dual_pp_stage_result(stage, start.elapsed_ms(&end));
863 }
864 }
865 let (mut rows, mut next) = out_a;
866 rows.extend(out_b.0);
867 next.extend(out_b.1);
868 Ok((rows, next))
869 }
870
871 #[allow(clippy::too_many_arguments)]
872 fn decode_step_batch_dual_stage0(
873 &self,
874 e: &Engine,
875 rt: &crate::pp::PpNRt,
876 tokens: &[u32],
877 caches: &mut [&mut Cache],
878 fence: &[usize],
879 step35_batched: bool,
880 track_overlap: bool,
881 ) -> Result<(usize, std::time::Instant, DualPpCudaSpan), Box<dyn std::error::Error>> {
882 let b_n = tokens.len();
883 let n_embd = self.cfg.n_embd as usize;
884 let mut ph_last = std::time::Instant::now();
885 rt.bind_stage(0)?;
886 let _st0 = rt.enter(0);
887 let e0 = rt.engine(0, e);
888 let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
889 let pos_d = e0.htod_i32(&pos_v)?;
890 let x = e0.htod(&self.embd.gather(n_embd, tokens))?;
891 ph_mark(e0, 0, &mut ph_last)?;
892 let timing_start = dual_pp_timing_event(e0, "stage0 start event");
893 let x = {
894 let _overlap = track_overlap.then(crate::pp::enter_dual_pp_stage);
895 if step35_batched {
896 self.step35_decode_batch_layers(
897 e0, x, caches, &pos_d, fence[0], fence[1], &mut ph_last)?
898 } else {
899 let ctx = self.batch_layer_ctx(e0, caches, fence[0], fence[1])?;
900 self.decode_batch_layers(e0, x, caches, &ctx, &pos_d, &mut ph_last)?
901 }
902 };
903 let timing = timing_start.and_then(|start| {
904 dual_pp_timing_event(e0, "stage0 end event").map(|end| (start, end))
905 });
906 let slot = rt.tx_pipelined(0, &x, b_n * n_embd)?;
907 Ok((slot, ph_last, timing))
908 }
909
910 #[allow(clippy::too_many_arguments)]
911 fn decode_step_batch_dual_stage1(
912 &self,
913 e: &Engine,
914 rt: &crate::pp::PpNRt,
915 slot: usize,
916 caches: &mut [&mut Cache],
917 samp: &[Option<(f32, u64, u32)>],
918 masks: &[Option<(&CudaSlice<u32>, usize)>],
919 lean: bool,
920 fence: &[usize],
921 step35_batched: bool,
922 mut ph_last: std::time::Instant,
923 track_overlap: bool,
924 ) -> Result<((Vec<Vec<f32>>, Vec<Option<u32>>), DualPpCudaSpan), Box<dyn std::error::Error>> {
925 let b_n = caches.len();
926 let n_embd = self.cfg.n_embd as usize;
927 let eps = self.cfg.rms_eps;
928 rt.bind_stage(1)?;
929 let _st1 = rt.enter(1);
930 let e1 = rt.engine(1, e);
931 let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
932 let pos_d = e1.htod_i32(&pos_v)?;
933 let x = rt.rx(0, slot, b_n * n_embd)?;
934 let timing_start = dual_pp_timing_event(e1, "stage1 start event");
935 let x = {
936 let _overlap = track_overlap.then(crate::pp::enter_dual_pp_stage);
937 if step35_batched {
938 self.step35_decode_batch_layers(
939 e1, x, caches, &pos_d, fence[1], fence[2], &mut ph_last)?
940 } else {
941 let ctx = self.batch_layer_ctx(e1, caches, fence[1], fence[2])?;
942 self.decode_batch_layers(e1, x, caches, &ctx, &pos_d, &mut ph_last)?
943 }
944 };
945 let timing = timing_start.and_then(|start| {
946 dual_pp_timing_event(e1, "stage1 end event").map(|end| (start, end))
947 });
948 let mut hn = e1.uninit(b_n * n_embd)?;
949 e1.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, b_n, eps)?;
950 let logits = e1.matmul(&self.output, &hn, b_n)?;
951 ph_mark(e1, 10, &mut ph_last)?;
952 Ok((self.decode_batch_epilogue(
953 e1, caches, samp, masks, lean, logits, b_n, &mut ph_last,
954 )?, timing))
955 }
956
957 /// THE BATCHED PP-N STEP (pp2-batch increment 2, 2026-08-06): the batched tick split
958 /// across `fence.len()-1` stages, each stage running ONLY its own layer range through
959 /// ITS OWN engine and stream, with a `[B, n_embd]` boundary activation between them.
960 /// The batched twin of `decode_step_h_ppn`, and the #1 item on the PP-2 serving bill —
961 /// without it a >VRAM SKU (Step-3.7-Flash: 105 GB, fits only across two cards) serves
962 /// SINGLE-STREAM only, because the batched path was the one loop with no stage split.
963 ///
964 /// STRUCTURE (mirrors the eager arm exactly, so the two stay comparable):
965 /// stage 0 `rt.enter(0)` -> per-stage pos_d + embed -> range -> `rt.tx`
966 /// middle stages `rt.rx` -> per-stage pos_d -> range -> `rt.tx`
967 /// last stage `rt.rx` -> per-stage pos_d -> range -> output_norm + lm_head ->
968 /// the batched serving epilogue (masks, device sample, lean park)
969 ///
970 /// FOUR THINGS ARE PER-STAGE, and each is per-stage for a measured reason:
971 ///
972 /// 1. THE ENGINE (`rt.engine(s, e)`). Not just for the remote device: `Engine` owns
973 /// lazily-grown stable-pointer scratch pools (`fa_part_pool`, `fa_vf16_scratch`,
974 /// `argmax_partials`) that are single-stream-safe BY DESIGN. Two stage streams
975 /// through one Engine is the shared-scratch race the pp2 lane hit (2026-08-02
976 /// nondeterministic all-logits divergence, 35% flake). `PpNRt::build` already gives
977 /// every stage s>0 its own Engine even on the primary device, so honouring
978 /// `rt.engine(s, e)` here is what scopes the pools per stage — the batched path
979 /// allocates MORE of that scratch than the eager one (fa at m=B), so this is the
980 /// load-bearing half of the trap's mitigation, not an inherited nicety.
981 ///
982 /// 2. THE POINTER TABLE (`batch_layer_ctx(es, caches, lo, hi)`). See [`BatchLayerCtx`]:
983 /// it holds DEVICE ADDRESSES of that range's cache state, uploaded through that
984 /// stage's engine. One step-wide table on the primary would put every stage's kernel
985 /// arguments in stage-0's HBM — a peer read per pointer fetch, the exact cliff this
986 /// whole lane exists to remove.
987 ///
988 /// 3. `pos_d` (the M2 pipelining law, learned on the eager arm): each stage uploads its
989 /// own copy of the step's per-row positions on ITS stream, so the buffer is
990 /// allocated, consumed and freed on one stream. A shared stage-0 `pos_d` freed at fn
991 /// return breaks under deferred readback — the free enqueues on stream 0 while later
992 /// stages still dereference it.
993 ///
994 /// 4. THE HEAD + EPILOGUE run on the LAST stage: `output_norm`/`output` were uploaded
995 /// through the last stage's engine by the sharded loader (`hybrid.rs`: `e_head =
996 /// layer_engine(e, n_trunk, n_trunk-1)`), and `cache.last_logits_dev` must be
997 /// allocated where the logits are.
998 ///
999 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME
1000 /// bytes in the same order — the split only moves where the residual is materialized,
1001 /// and the boundary is a straight f32 copy (dtod same-device / `cudaMemcpyPeerAsync`
1002 /// cross-device, no conversion). So batched PP-N must be BIT-IDENTICAL to single-device
1003 /// batched at the same B, in both placement orders. Gate: `decode-batch-gate --mode
1004 /// pp` (logit-dump, both orders) — the batched analogue of the eager arm's 48 steps x
1005 /// 248,320 f32 logits with zero differing bits.
1006 ///
1007 /// The B=1 fast path is NOT taken here (its condition already excludes an open door):
1008 /// it routes through `decode_layers_eager` whole-trunk on one engine, which is exactly
1009 /// the unsplit walk. B=1 under the door rides this function's B=1 case instead — the
1010 /// same trade the eager arm's own ppn step makes, and the reason the pp2 lane measured
1011 /// B=1 door-open at 0.854x (the lost fusion chain), not a cliff.
1012 #[allow(clippy::too_many_arguments)]
1013 fn decode_step_batch_ppn(
1014 &self,
1015 e: &Engine,
1016 tokens: &[u32],
1017 caches: &mut [&mut Cache],
1018 samp: &[Option<(f32, u64, u32)>],
1019 masks: &[Option<(&CudaSlice<u32>, usize)>],
1020 lean: bool,
1021 fence: &[usize],
1022 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
1023 let b_n = tokens.len();
1024 assert!(b_n >= 1 && b_n == caches.len(), "tokens/caches length mismatch");
1025 // gemma4: same no-arm refusal as the unsplit body (see decode_step_batch), Err not
1026 // assert — a request must never kill the worker process.
1027 if self.is_gemma4_e4b() || self.cfg.gemma4.is_some() {
1028 return Err("decode_step_batch_ppn has no gemma4 arm — serve gemma4 on the eager \
1029 per-session path".into());
1030 }
1031 // Same width policy as the unsplit body — the stage split changes WHERE kernels run,
1032 // never WHICH tier admits the width. Duplicated deliberately rather than hoisted:
1033 // the exact-16 scope must wrap the whole multi-stage walk (`set_verify_exact` is
1034 // per-Engine state read at dispatch on every stage), so it has to be established
1035 // here, and a shared helper returning a guard would have to own `e` plus the flag.
1036 let cap = Self::decode_batch_cap();
1037 let exact16 = b_n > 8 && b_n <= 16 && self.decode_batch_exact16_ok();
1038 assert!(
1039 b_n <= cap || exact16,
1040 "decode_step_batch_ppn: B={b_n} > cap {cap} with no exact tier — refused"
1041 );
1042 let rt = crate::pp::PpNRt::get(e)?;
1043 let n_st = fence.len() - 1;
1044 assert_eq!(
1045 rt.n_stages(), n_st,
1046 "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
1047 );
1048 // #87 REVERSE PUBLICATION (lane/pp2spec-crash): order every stage stream behind
1049 // the caller before this body's first stage allocation can reuse a pool block
1050 // whose queued primary-stream consumer has not read it yet. Anatomy:
1051 // `PpNRt::fence_stages_behind`. (This body dtoh+syncs its own logits, but its
1052 // PP-mode callers interleave with the spec verify's device-resident outputs in
1053 // the same worker, so the entry fence is the uniform law, not an optimization.)
1054 rt.fence_stages_behind(&e.stream())?;
1055 let n_embd = self.cfg.n_embd as usize;
1056 let eps = self.cfg.rms_eps;
1057 let payload = b_n * n_embd;
1058
1059 // EXACT-16 SCOPE, PER STAGE ENGINE: `verify_exact` is per-Engine state (an AtomicBool
1060 // on the Engine the dispatch reads), and each stage runs through a DIFFERENT Engine —
1061 // so setting it on the primary alone would leave stages 1..N-1 dispatching the m>=16
1062 // GEMM/MMQ arms while stage 0 used the exact b16 tier. That is a silent per-stage
1063 // numeric split (the failure this tier exists to prevent), so the flag is set on
1064 // every stage engine and cleared on all of them at scope exit.
1065 struct ExactScopeN<'a>(Vec<&'a Engine>);
1066 impl Drop for ExactScopeN<'_> {
1067 fn drop(&mut self) {
1068 for eng in &self.0 {
1069 eng.set_verify_exact(false);
1070 }
1071 }
1072 }
1073 let _exact_scope = if exact16 {
1074 let engines: Vec<&Engine> = (0..n_st).map(|s| rt.engine(s, e)).collect();
1075 for eng in &engines {
1076 eng.set_verify_exact(true);
1077 }
1078 Some(ExactScopeN(engines))
1079 } else {
1080 None
1081 };
1082
1083 let mut ph_last = std::time::Instant::now();
1084
1085 // B=1 PER-STAGE FAST PATH (measured 2026-08-06, PRO 6000 pair). The unsplit body's
1086 // b1_fast guard includes `pp_cuts().is_none()`, so opening the pp door dropped every
1087 // solo session off the m=1 FUSION chain (cross-layer add+norm+q8_1, fused SwiGLU,
1088 // lever 1's gate+up dual) and onto the batched m=1 walk. Cost, arm A vs arm C at B=1:
1089 // 208.5 vs 177.3 tok/s = -15.0% — and NOT a split cost, since arm B (stages=2 on ONE
1090 // card) pays the same 177, and the prior lane's `MEMRA_PP_SHARD=0` batched-body B=1
1091 // was 178.5. It was the fusion chain going missing, on the config the Step SKU serves
1092 // solo requests from.
1093 //
1094 // `decode_layers_eager(lo, hi)` is ALREADY range-scoped and is exactly what the eager
1095 // ppn arm (`decode_step_h_ppn`) calls per stage, so B=1 rides the same per-stage
1096 // structure: same engines, same streams, same [1, n_embd] boundary slots, same
1097 // stage-owned caches. Only the trunk kernels differ, and they differ identically to
1098 // how they differ off-door. Exactness is therefore the SAME accepted decode-config FP
1099 // class the unsplit b1_fast lever already carries (strict gate1 PASSes with it on,
1100 // FAILs with it off at maxdiff 1.591e-1) — which is why the pp gate pins
1101 // `set_b1_fast(false)`: with it on, the B=1 reference and the split arm would
1102 // legitimately sit on opposite sides of that gap and the bit-identity arm would
1103 // report a fake stage-split failure.
1104 //
1105 // Step3.5/Step3.7 are an exception (lane/cx-b1fix, 2026-08-10): their B>1 route is
1106 // `step35_decode_batch_layers`, and the live scheduler may move a session from B=1
1107 // to B>1. The eager/fused class and that batched class produce different greedy bytes,
1108 // so selecting the eager arm at B=1 made output depend on load history. Keep one
1109 // numeric class for this model family: Step35 always takes its stage-scoped batched
1110 // trunk at every width. The live transition gate in step35-b2-geometry-gate pins it.
1111 // Qwen35-MoE is the second exception (lane/cx-q35bug, 2026-08-12): on the Q35
1112 // sellgate workload the eager-B1 -> batched-B2 transition changed emitted token ids and
1113 // selected EOS at tokens 15/17/25. Keep that family on this generic batched trunk at B=1
1114 // too; dense Qwen35 retains the measured eager fast path.
1115 let b1_stage_fast = b_n == 1
1116 && Self::b1_fast_on()
1117 && self.b1_fast_arch_eligible()
1118 && !self.is_gemma4_e4b()
1119 && self.cfg.gemma4.is_none()
1120 && self.cfg.m3.is_none()
1121 && self.cfg.step35.is_none()
1122 && !e.verify_exact_on();
1123 // step35 (lane/step35-batched-decode, 2026-08-08): B>1 rides its OWN stage-scoped
1124 // batched walk (`step35_decode_batch_layers`) — the generic `decode_batch_layers`
1125 // remains OFF-LIMITS for this arch at every B (its uniform geometry produced the
1126 // b2ab HTTP-200 garbage: research/step-sku-20260807/raw/b2ab-pre-*.log). Since
1127 // lane/cx-b1fix, B=1 also takes this walk: a Step35 PP-N session must not change
1128 // numeric class when live decode width changes. The refusal below guards the
1129 // rollback residue; under PP-N, disabling the only correct trunk makes Step35
1130 // requests fail closed instead of falling back to the eager class.
1131 let step35_batched = self.cfg.step35.is_some();
1132 if step35_batched && !Self::step35_batch_on() {
1133 return Err("step35 batched decode is disabled (MEMRA_STEP35_BATCH=0) — \
1134 PP-N Step35 decode is unavailable because eager B=1 is a different \
1135 numeric class".into());
1136 }
1137 // Hoisted: `caches[0].pos` as a value argument alongside `caches[0]` as `&mut` in one
1138 // call is a borrow conflict; `pos` is Copy and the epilogue is what advances it.
1139 let pos0 = if b1_stage_fast { caches[0].pos } else { 0 };
1140
1141 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
1142 let mut slot = {
1143 let _st0 = rt.enter(0);
1144 let e0 = rt.engine(0, e);
1145 let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
1146 let pos_d = e0.htod_i32(&pos_v)?;
1147 let x = e0.htod(&self.embd.gather(n_embd, tokens))?;
1148 ph_mark(e0, 0, &mut ph_last)?;
1149 let x = if b1_stage_fast {
1150 self.decode_layers_eager(e0, x, fence[0], fence[1], &pos_d, pos0, caches[0])?
1151 } else if step35_batched {
1152 self.step35_decode_batch_layers(
1153 e0, x, caches, &pos_d, fence[0], fence[1], &mut ph_last)?
1154 } else {
1155 let ctx = self.batch_layer_ctx(e0, caches, fence[0], fence[1])?;
1156 self.decode_batch_layers(e0, x, caches, &ctx, &pos_d, &mut ph_last)?
1157 };
1158 rt.tx(0, &x, payload)?
1159 // x + pos_d + ctx.ptr_table drop here: freed stream-ordered on stage-0's stream.
1160 };
1161
1162 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
1163 for s in 1..n_st - 1 {
1164 let _st = rt.enter(s);
1165 let es = rt.engine(s, e);
1166 let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
1167 let pos_d = es.htod_i32(&pos_v)?;
1168 let x = rt.rx(s - 1, slot, payload)?;
1169 let x = if b1_stage_fast {
1170 self.decode_layers_eager(es, x, fence[s], fence[s + 1], &pos_d, pos0, caches[0])?
1171 } else if step35_batched {
1172 self.step35_decode_batch_layers(
1173 es, x, caches, &pos_d, fence[s], fence[s + 1], &mut ph_last)?
1174 } else {
1175 let ctx = self.batch_layer_ctx(es, caches, fence[s], fence[s + 1])?;
1176 self.decode_batch_layers(es, x, caches, &ctx, &pos_d, &mut ph_last)?
1177 };
1178 slot = rt.tx(s, &x, payload)?;
1179 }
1180
1181 // ---- LAST STAGE: RX + final range + head + the batched serving epilogue ----
1182 let _stl = rt.enter(n_st - 1);
1183 let el = rt.engine(n_st - 1, e);
1184 let pos_v: Vec<i32> = caches.iter().map(|c| c.pos as i32).collect();
1185 let pos_d = el.htod_i32(&pos_v)?;
1186 let x = rt.rx(n_st - 2, slot, payload)?;
1187 let x = if b1_stage_fast {
1188 self.decode_layers_eager(el, x, fence[n_st - 1], fence[n_st], &pos_d, pos0, caches[0])?
1189 } else if step35_batched {
1190 self.step35_decode_batch_layers(
1191 el, x, caches, &pos_d, fence[n_st - 1], fence[n_st], &mut ph_last)?
1192 } else {
1193 let ctx = self.batch_layer_ctx(el, caches, fence[n_st - 1], fence[n_st])?;
1194 self.decode_batch_layers(el, x, caches, &ctx, &pos_d, &mut ph_last)?
1195 };
1196
1197 let mut hn = el.uninit(payload)?;
1198 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, b_n, eps)?;
1199 let logits = el.matmul(&self.output, &hn, b_n)?;
1200 ph_mark(el, 10, &mut ph_last)?;
1201
1202 self.decode_batch_epilogue(el, caches, samp, masks, lean, logits, b_n, &mut ph_last)
1203 }
1204
1205 /// Build the per-step layer context for layers `[lo, hi)`: the device state-pointer
1206 /// table plus the step's arm picks. See [`BatchLayerCtx`] for why this is RANGE-scoped
1207 /// (the table holds device addresses and must be uploaded through the engine whose
1208 /// device runs those layers).
1209 ///
1210 /// Table layout is unchanged from the whole-trunk version — `lin_base`/`attn_base` are
1211 /// still indexed by ABSOLUTE layer id, so `decode_batch_layers`' body indexes them
1212 /// exactly as the old inline loop did. Only layers in `[lo, hi)` contribute entries; the
1213 /// rest stay `None`, which is a loud `expect` if a range ever reads outside its own.
1214 pub(crate) fn batch_layer_ctx(
1215 &self,
1216 e: &Engine,
1217 caches: &[&mut Cache],
1218 lo: usize,
1219 hi: usize,
1220 ) -> Result<BatchLayerCtx, Box<dyn std::error::Error>> {
1221 let cfg = &self.cfg;
1222 let head_dim = cfg.head_dim_k as usize;
1223 // Per-step STATE POINTER TABLE (one H2D): for every linear layer, [conv x B]
1224 // [ssm_in x B][ssm_out x B] device addresses. The batched state kernels read their
1225 // sequence's pointer from these arrays — states stay per-cache (no pooling refactor),
1226 // yet conv/prep/scan collapse from 3xB launches per layer to 3. Rebuilt every step
1227 // because the ssm ping-pong swaps pointers host-side after each scan.
1228 // INCREMENT 2 (2026-08-01): the SAME table now also carries, for every FULL-attn
1229 // layer, [k0,v0,k1,v1,...] cache base addresses — the z-batched seqs append and
1230 // seqs fa_decode kernels read their sequence's cache through it (the MoE
1231 // expert-table pattern), collapsing 2xB launches per attn layer to 2.
1232 let mut lin_base: Vec<Option<usize>> = vec![None; self.layers.len()];
1233 let mut attn_base: Vec<Option<usize>> = vec![None; self.layers.len()];
1234 let mut ptrs: Vec<u64> = Vec::new();
1235 {
1236 use cudarc::driver::DevicePtr;
1237 let s = &e.gpu.stream();
1238 for il in lo..hi {
1239 match &self.layers[il].mixer {
1240 Mixer::Linear(_) => {
1241 lin_base[il] = Some(ptrs.len());
1242 for c in caches.iter() {
1243 let rl = c.recur[il].as_ref().unwrap();
1244 let (p, _g) = rl.conv_state.device_ptr(s);
1245 ptrs.push(p as u64);
1246 }
1247 for c in caches.iter() {
1248 let rl = c.recur[il].as_ref().unwrap();
1249 let (p, _g) = rl.ssm_state.device_ptr(s);
1250 ptrs.push(p as u64);
1251 }
1252 for c in caches.iter() {
1253 let rl = c.recur[il].as_ref().unwrap();
1254 let (p, _g) = rl.ssm_state_alt.device_ptr(s);
1255 ptrs.push(p as u64);
1256 }
1257 }
1258 Mixer::Full(_) => {
1259 attn_base[il] = Some(ptrs.len());
1260 for c in caches.iter() {
1261 let kvl = c.kv[il].as_ref().unwrap();
1262 let (pk, _g) = kvl.k.device_ptr(s);
1263 let (pv, _g2) = kvl.v.device_ptr(s);
1264 ptrs.push(pk as u64);
1265 ptrs.push(pv as u64);
1266 }
1267 }
1268 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1269 }
1270 }
1271 }
1272 let ptr_table = if ptrs.is_empty() { None } else { Some(e.htod_u64(&ptrs)?) };
1273
1274 // INCREMENT 2 arm picks (per STEP — t_kv is layer-invariant within a tick):
1275 // - seqs APPEND: format-only condition (per-row program is t_kv-independent);
1276 // default flash module only (fp8-KV rides the per-seq g-module path).
1277 // - seqs FA: every row must take the v4 eager arm at ITS OWN t_kv AND all rows
1278 // must share ONE fa_split_keys rung (the rows-twins' straddle law) — a rung
1279 // crossing inside the batch keeps the per-seq loop for that step, so each
1280 // sequence always executes the exact program its isolated run would.
1281 // MEMRA_BATCH_APPEND=0 / MEMRA_BATCH_FA=0 are the rollback/A-B seams.
1282 //
1283 // The picks are t_kv-driven, and t_kv is layer-INVARIANT within a step, so every
1284 // stage of a pp split independently computes the SAME arms from the same `caches`
1285 // — a stage cannot silently take a different program than its unsplit self.
1286 let t_kvs: Vec<usize> = caches.iter().map(|c| c.pos + 1).collect();
1287 let t_kv_max = *t_kvs.iter().max().unwrap();
1288 let seqs_append = {
1289 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1290 *ON.get_or_init(|| std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0"))
1291 } && !Engine::kv_fp8_on();
1292 let sp0 = crate::fa_split_keys(t_kvs[0], cfg.n_head_kv as usize);
1293 let seqs_fa = {
1294 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1295 *ON.get_or_init(|| std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0"))
1296 } && t_kvs.iter().all(|&t| crate::fa_seqs_eligible(t, head_dim))
1297 && t_kvs.iter().all(|&t| crate::fa_split_keys(t, cfg.n_head_kv as usize) == sp0);
1298
1299 Ok(BatchLayerCtx {
1300 lin_base,
1301 attn_base,
1302 ptr_table,
1303 t_kvs,
1304 t_kv_max,
1305 sp0,
1306 seqs_append,
1307 seqs_fa,
1308 lo,
1309 hi,
1310 })
1311 }
1312
1313 /// THE PP SEAM (pp2-batch increment 1, 2026-08-06): run the batched trunk over layers
1314 /// `[ctx.lo, ctx.hi)`, entering with a materialized `[B, n_embd]` residual and exiting
1315 /// with the range's final residual materialized. The batched twin of
1316 /// `decode_layers_eager` — the eager arm has had this seam since M1-PP2 and every ppN
1317 /// stage calls it; the batched body had no equivalent, which is why every later PP-2
1318 /// increment (and spec-over-PP2, whose verify is a batched T=K+1 forward) waited on this
1319 /// extraction (`research/pp2-hardening-20260806/PROGRESS.md` bill item 1).
1320 ///
1321 /// SINGLE-DEVICE SEMANTICS ARE UNCHANGED BY CONSTRUCTION: the body is the old
1322 /// `for (il, layer) in self.layers.iter().enumerate()` loop moved verbatim, with `for il
1323 /// in ctx.lo..ctx.hi` as the header and the per-step invariants (`ptr_table`, arm picks,
1324 /// `t_kv`) read from `ctx` instead of enclosing locals. At `lo=0, hi=n_layers` — every
1325 /// call today — the launch sequence is identical, so the exactness contract in this
1326 /// module's header carries over untouched rather than needing a re-proof.
1327 ///
1328 /// UNLIKE the eager seam, this one is NOT yet stage-callable: `caches` is `&mut [&mut
1329 /// Cache]` mutated in place (KV `len` bumps, ssm ping-pong swaps), and `pos_d`/`x` come
1330 /// from the caller's device. Wiring a stage split means per-stage `pos_d` + a boundary
1331 /// `[B, n_embd]` transfer around this call, which is the NEXT increment. The seam exists
1332 /// so that increment is a call-site change, not a 250-line surgery.
1333 #[allow(clippy::too_many_arguments)]
1334 pub(crate) fn decode_batch_layers(
1335 &self,
1336 e: &Engine,
1337 mut x: CudaSlice<f32>,
1338 caches: &mut [&mut Cache],
1339 ctx: &BatchLayerCtx,
1340 pos_d: &CudaSlice<i32>,
1341 ph_last: &mut std::time::Instant,
1342 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1343 let b_n = caches.len();
1344 let cfg = &self.cfg;
1345 let n_embd = cfg.n_embd as usize;
1346 let eps = cfg.rms_eps;
1347 let (lin_base, attn_base) = (&ctx.lin_base, &ctx.attn_base);
1348 let ptr_table = &ctx.ptr_table;
1349 let (seqs_append, seqs_fa, sp0, t_kv_max) =
1350 (ctx.seqs_append, ctx.seqs_fa, ctx.sp0, ctx.t_kv_max);
1351 debug_assert_eq!(ctx.t_kvs.len(), b_n, "ctx built for a different batch width");
1352
1353 for il in ctx.lo..ctx.hi {
1354 let layer = &self.layers[il];
1355 // ---- attn_norm + q8_1 quantize, batched (B rows) ----
1356 let anorm = layer.attn_norm.float_data();
1357 let mut xn = e.uninit(b_n * n_embd)?;
1358 e.rms_norm(&x, anorm, &mut xn, n_embd, b_n, eps)?;
1359 let (hq, hd) = e.quantize_q8_1(&xn, b_n, n_embd)?;
1360
1361 // ---- mixer ----
1362 let mixed: CudaSlice<f32> = match &layer.mixer {
1363 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1364 Mixer::Full(fa) => {
1365 let geometry = cfg.full_attention_geometry_at(il as u32);
1366 let n_head = geometry.n_head as usize;
1367 let n_head_kv = geometry.n_head_kv as usize;
1368 let head_dim = geometry.head_dim_k as usize;
1369 let rope_dims = geometry.n_rot as usize;
1370 let rope_base = geometry.rope_base;
1371 let scale = geometry.attention_scale();
1372 // Batched projections: one weight read serves all B rows.
1373 let qf = e.matmul_pre(&fa.wq, &hq, &hd, &xn, b_n)?;
1374 let mut k = e.matmul_pre(&fa.wk, &hq, &hd, &xn, b_n)?;
1375 let v = e.matmul_pre(&fa.wv, &hq, &hd, &xn, b_n)?;
1376
1377 let gated = geometry.attention_gate
1378 == memra_gguf::config::AttentionGateKind::FusedQ;
1379 let (mut q, gate) = if gated {
1380 let mut qs = e.uninit(b_n * n_head * head_dim)?;
1381 let mut gs = e.uninit(b_n * n_head * head_dim)?;
1382 e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, b_n)?;
1383 (qs, Some(gs))
1384 } else {
1385 (qf, None)
1386 };
1387
1388 // QK-norm over B*n_head rows, rope with per-row positions.
1389 let mut qn = e.uninit(b_n * n_head * head_dim)?;
1390 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, b_n * n_head, eps)?;
1391 q = qn;
1392 let mut kn = e.uninit(b_n * n_head_kv * head_dim)?;
1393 e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, b_n * n_head_kv, eps)?;
1394 k = kn;
1395 e.rope_neox(&mut q, &pos_d, head_dim, rope_dims, n_head, b_n,
1396 rope_base, 1.0)?;
1397 e.rope_neox(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, b_n,
1398 rope_base, 1.0)?;
1399 ph_mark(e, 1, ph_last)?;
1400
1401 // INCREMENT 2 (2026-08-01): the per-seq (append, attend) launch train
1402 // becomes two phases. Phase A appends all B rows (one z-batched launch,
1403 // or the per-seq loop on the seam/fp8 path); phase B attends all B
1404 // sequences (one blockIdx.z launch + one combine on the batched arm —
1405 // which also reads q / writes attn at row offsets, killing the per-seq
1406 // q/a dtod copies — or the per-seq loop when any row is outside the v4
1407 // arm / a split rung crosses inside the batch). Caches are disjoint per
1408 // sequence, so the phase split leaves every row's math untouched.
1409 let q_dim = n_head * head_dim;
1410 let kv_dim = n_head_kv * head_dim;
1411 let mut attn = e.uninit(b_n * q_dim)?;
1412 // ---- phase A: KV append (all B rows) ----
1413 if seqs_append {
1414 let (kdk, kdv, ktb, vtb) = {
1415 let kvl = caches[0].kv[il].as_ref().unwrap();
1416 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes)
1417 };
1418 let base = attn_base[il].expect("full layer missing from pointer table");
1419 let table = ptr_table.as_ref().expect("pointer table missing");
1420 let kv_view = table.slice(base..base + 2 * b_n);
1421 e.append_kv_quantized_seqs(&k, &v, &kv_view, &pos_d, b_n,
1422 kdk, kdv, ktb, vtb)?;
1423 for cache in caches.iter_mut() {
1424 let kvl = cache.kv[il].as_mut().unwrap();
1425 debug_assert_eq!(kvl.len, cache.pos, "kv len / pos out of lockstep");
1426 kvl.len += 1;
1427 }
1428 } else {
1429 for (bi, cache) in caches.iter_mut().enumerate() {
1430 let kvl = cache.kv[il].as_mut().unwrap();
1431 let k_row = k.slice(bi * kv_dim..(bi + 1) * kv_dim);
1432 let v_row = v.slice(bi * kv_dim..(bi + 1) * kv_dim);
1433 e.append_kv_quantized_view(
1434 &k_row, &v_row, &mut kvl.k, &mut kvl.v, kvl.len,
1435 kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
1436 Engine::kv_fp8_on(),
1437 )?;
1438 kvl.len += 1;
1439 }
1440 }
1441 ph_mark(e, 2, ph_last)?;
1442 // ---- phase B: attention (all B sequences) ----
1443 if seqs_fa {
1444 let (ktb, vtb) = {
1445 let kvl = caches[0].kv[il].as_ref().unwrap();
1446 (kvl.k_tok_bytes, kvl.v_tok_bytes)
1447 };
1448 let base = attn_base[il].expect("full layer missing from pointer table");
1449 let table = ptr_table.as_ref().expect("pointer table missing");
1450 let kv_view = table.slice(base..base + 2 * b_n);
1451 e.fa_decode_batch_seqs_v4(&q, &kv_view, &pos_d, &mut attn,
1452 head_dim, n_head, n_head_kv, b_n,
1453 t_kv_max, scale, sp0, ktb, vtb)?;
1454 ph_mark(e, 4, ph_last)?;
1455 } else {
1456 for (bi, cache) in caches.iter_mut().enumerate() {
1457 let kvl = cache.kv[il].as_mut().unwrap();
1458 let t_kv = kvl.len;
1459 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
1460 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
1461 // The fallback keeps one FA launch per distinct KV view, but Q and
1462 // attention already live in packed row-major buffers. Pass those row
1463 // views directly; only the arithmetic-free materialization copies go.
1464 let q_row = q.slice(bi * q_dim..(bi + 1) * q_dim);
1465 let mut a_row = attn.slice_mut(bi * q_dim..(bi + 1) * q_dim);
1466 e.fa_decode_kvmod_view(
1467 &q_row, &k_view, &v_view, &mut a_row, head_dim, n_head, n_head_kv,
1468 t_kv, scale, kvl.k_tok_bytes, kvl.v_tok_bytes, Engine::kv_fp8_on(),
1469 )?;
1470 ph_mark(e, 4, ph_last)?;
1471 }
1472 }
1473
1474 // Output gate (element-wise — batches whole) + o-proj at m=B.
1475 let attn_g = match &gate {
1476 Some(g) => {
1477 let n = b_n * q_dim;
1478 let mut gsig = e.uninit(n)?;
1479 e.sigmoid(g, &mut gsig, n)?;
1480 let mut ag = e.uninit(n)?;
1481 e.mul(&attn, &gsig, &mut ag, n)?;
1482 ag
1483 }
1484 None => attn,
1485 };
1486 let o = e.matmul(&fa.wo, &attn_g, b_n)?;
1487 ph_mark(e, 5, ph_last)?;
1488 o
1489 }
1490 Mixer::Linear(la) => {
1491 // v2 (the B-scaling fix): the GDN mixer's PROJECTIONS carry the layer's
1492 // weight mass — batch them at m=B so wqkv/gate/beta/alpha/ssm_out stream
1493 // ONCE per step instead of once per sequence. Only the recurrent state ops
1494 // (fused conv ring, gdn prep, gdn scan) stay per-seq — they are state-bound
1495 // micro-kernels, not weight readers. Composition unchanged vs v1 (matmul_pre
1496 // == fused2 per (tensor,row); _bN mmvq per-row == m=1): same numeric config.
1497 let ssm = cfg.ssm.as_ref().expect("linear mixer requires ssm cfg");
1498 let d_state = ssm.state_size as usize;
1499 let num_k = ssm.group_count as usize;
1500 let num_v = ssm.time_step_rank as usize;
1501 let d_conv = ssm.conv_kernel as usize;
1502 let key_dim = d_state * num_k;
1503 let value_dim = d_state * num_v;
1504 let conv_dim = key_dim * 2 + value_dim;
1505 let gdn_scale = 1.0 / (d_state as f32).sqrt();
1506
1507 // ---- batched projections (the weight win) ----
1508 let qkv_mixed = e.matmul_pre(&la.wqkv, &hq, &hd, &xn, b_n)?;
1509 let z = e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, b_n)?;
1510 let beta_raw = e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, b_n)?;
1511 let alpha = e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, b_n)?;
1512 ph_mark(e, 6, ph_last)?;
1513
1514 // ---- batched recurrent state ops (3 launches for all B sequences) ----
1515 let base = lin_base[il].expect("linear layer missing from pointer table");
1516 let table = ptr_table.as_ref().expect("pointer table missing");
1517 let conv_view = table.slice(base..base + b_n);
1518 let in_view = table.slice(base + b_n..base + 2 * b_n);
1519 let out_view = table.slice(base + 2 * b_n..base + 3 * b_n);
1520 let mut conv_outs = e.uninit(b_n * conv_dim)?;
1521 e.ssm_conv1d_fused_decode_b(&qkv_mixed, &conv_view,
1522 la.ssm_conv1d.float_data(), &mut conv_outs,
1523 conv_dim, d_conv, b_n)?;
1524 let mut q_l2 = e.uninit(b_n * value_dim)?;
1525 let mut k_l2 = e.uninit(b_n * value_dim)?;
1526 let mut v_gd = e.uninit(b_n * value_dim)?;
1527 let mut beta_b = e.uninit(b_n * num_v)?;
1528 let mut g_log = e.uninit(b_n * num_v)?;
1529 e.gdn_prep_decode_b(&conv_outs, &beta_raw, &alpha,
1530 la.ssm_dt.float_data(), la.ssm_a.float_data(),
1531 &mut q_l2, &mut k_l2, &mut v_gd, &mut beta_b, &mut g_log,
1532 d_state, num_v, num_k, key_dim, eps, conv_dim, b_n)?;
1533 let mut o_all = e.uninit(b_n * value_dim)?;
1534 e.gdn_scan_s128_batched(&q_l2, &k_l2, &v_gd, &g_log, &beta_b,
1535 &in_view, &out_view, &mut o_all,
1536 num_v, b_n, gdn_scale)?;
1537 // ping-pong: scan wrote each seq's alt buffer; swap host handles (the
1538 // NEXT step's table rebuild picks up the new canonical pointers).
1539 for cache in caches.iter_mut() {
1540 let rl = cache.recur[il].as_mut().unwrap();
1541 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
1542 }
1543 ph_mark(e, 7, ph_last)?;
1544
1545 // ---- batched gated norm + out-projection ----
1546 let o = if e.uses_q8_1_fast(&la.ssm_out) {
1547 let (gq, gd) = e.gated_rmsnorm_q8_1(&o_all, la.ssm_norm.float_data(),
1548 &z, d_state, b_n * num_v, eps)?;
1549 let g0 = e.zeros(0)?;
1550 e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, b_n)?
1551 } else {
1552 let mut gn = e.uninit(b_n * value_dim)?;
1553 e.gated_rmsnorm(&o_all, la.ssm_norm.float_data(), &z, &mut gn,
1554 d_state, b_n * num_v, eps)?;
1555 e.matmul(&la.ssm_out, &gn, b_n)?
1556 };
1557 ph_mark(e, 8, ph_last)?;
1558 o
1559 }
1560 };
1561
1562 // ---- residual add + post_attn_norm + FFN, batched ----
1563 let pnorm = layer.post_attn_norm.float_data();
1564 let mut x1 = e.uninit(b_n * n_embd)?;
1565 let mut z = e.uninit(b_n * n_embd)?;
1566 e.add_rms_norm(&x, &mixed, pnorm, &mut x1, &mut z, n_embd, b_n, eps)?;
1567 let ffn_out = match &layer.ffn {
1568 crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1569 // v1 covers the SiLU family; M3's swigluoai clamp rides a scaled epilogue
1570 // (m=1 fused tier) — batched M3 lands with the batched-fusion pass.
1571 assert!(self.cfg.m3.is_none(),
1572 "decode_step_batch v1: M3 swigluoai FFN not yet batched");
1573 let n_ff = ffn_gate.out_features();
1574 let (zq, zd) = e.quantize_q8_1(&z, b_n, n_embd)?;
1575 // REFUTED ARM (lane/q27-deepdive, 2026-08-05): fusing this gate+up pair
1576 // into `matmul_q8_fused2_t` (the fused2_b8 tier) measured FLAT-TO-NEGATIVE
1577 // at the serving tick — bench c=8 213.1/213.8, 213.9/214.4, 214.4/213.5
1578 // (sign flips) and serve c=8 paired mean −0.20% over 3 passes. Mechanism:
1579 // unlike m=1 (where the pair is 128 of 1015 launches in a 7.67%-gap tick),
1580 // the c=8 tick is 73.2% one weight-bound kernel class with launch cost
1581 // already hidden — halving 128 launches of ~28k buys nothing. The m=1 arm
1582 // in `matmul_pre_dual_noscale` (+0.94%) stays; this call site keeps the two
1583 // launches. Kernel + fused2_b8 wrapper retained: kernel-check gates it at
1584 // m=5/8 and matmul_q8_fused2_t serves the verify tier. Receipts:
1585 // research/q27-deepdive-20260805/ (lever3-bench-*, serve-points.jsonl).
1586 let g = e.matmul_pre(ffn_gate, &zq, &zd, &z, b_n)?;
1587 let u = e.matmul_pre(ffn_up, &zq, &zd, &z, b_n)?;
1588 let mut act = e.uninit(b_n * n_ff)?;
1589 e.silu_mul(&g, &u, &mut act, b_n * n_ff)?;
1590 let (aq, ad) = e.quantize_q8_1(&act, b_n, n_ff)?;
1591 e.matmul_pre(ffn_down, &aq, &ad, &act, b_n)?
1592 }
1593 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &z, None, b_n, il as u16)?,
1594 };
1595 // next-layer input x = x1 + ffn_out (batched element-wise add)
1596 let mut x2 = e.uninit(b_n * n_embd)?;
1597 e.add(&x1, &ffn_out, &mut x2, b_n * n_embd)?;
1598 x = x2;
1599 ph_mark(e, 9, ph_last)?;
1600 }
1601 Ok(x)
1602 }
1603
1604 /// Rollback seam for the step35 batched decode arm (lane/step35-batched-decode,
1605 /// 2026-08-08). Default ON; `MEMRA_STEP35_BATCH=0` caps serving at B=1 and makes the
1606 /// batched bodies return Err. Since lane/cx-b1fix, PP-N also refuses the eager B=1
1607 /// numeric class, so the seam disables PP-N Step35 decode rather than serving unstable
1608 /// bytes. Also the b2geo35 gate's CANARY seam — the live assertions must fail under it.
1609 pub fn step35_batch_on() -> bool {
1610 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1611 *ON.get_or_init(|| std::env::var("MEMRA_STEP35_BATCH").as_deref() != Ok("0"))
1612 }
1613
1614 /// THE step35 BATCHED LAYER WALK (lane/step35-batched-decode, 2026-08-08): B sequences
1615 /// share one pass over layers `[lo, hi)` with the REAL step35 geometry — the arm that
1616 /// kills the B=1 pin (34 tok/s aggregate FLAT across c=1..8, round-robin serialized;
1617 /// research/step-sku-20260807 §4) without re-opening the b2ab garbage hole (the generic
1618 /// `decode_batch_layers` ran uniform n_head/full-width rope/no window/no gate over
1619 /// step35 weights and returned HTTP-200 garbage at c>1).
1620 ///
1621 /// SHAPE — batched where the weights are, per-session where the state is:
1622 /// * attn_norm + quantize + wq/wk/wv/attn_gate projections + q/k norms + rope + head
1623 /// gate + wo + residual/post-norm + FFN all run at m=B: ONE weight stream serves B
1624 /// rows (decode is weight-BW-bound; this is the entire win).
1625 /// * KV append + fa_decode stay a per-session loop — the SWA window makes each
1626 /// session's KV view a function of ITS OWN `kvl.len` (`off = len-win` when past the
1627 /// window), and the z-batched seqs kernels take one shared t_kv/rung, not per-row
1628 /// offsets. This is the same shape as `decode_batch_layers`' per-seq fallback arm,
1629 /// and it costs launches, not weight bandwidth (KV is per-session state either way).
1630 ///
1631 /// PER-LAYER GEOMETRY (the five mechanisms that make the generic body wrong here, all
1632 /// from `step35_geom`/cfg): n_head 64 full / 96 SWA (wq/wo/attn_gate widths per layer),
1633 /// partial rope (n_rot 64 full / 128 SWA), dual base (5e6/1e4) + `rope_freqs` factors
1634 /// on FULL layers only, SWA window 512 with per-SESSION view offsets, and the separate
1635 /// head-wise `attn_gate` (one pre-sigmoid scalar per (token, head), input = the
1636 /// post-attn_norm hidden, applied before wo).
1637 ///
1638 /// EXACTNESS (the isolation contract, decode-batch-gate gate2's bar): every kernel here
1639 /// is row-independent at m=B or per-session:
1640 /// * `rms_norm`/`add_rms_norm`/`quantize_q8_1`/`attn_head_gate`/activations: per-row
1641 /// programs, grid over rows — row bi's bytes are the 1-row call's bytes.
1642 /// * projections via `matmul_pre` at m=2..8: Q8_0/Q6_K-class rides the b2/b4/b8
1643 /// batched-mmvq tier (bit-identical per (token,row) to m=1 mmvq); IQ4_XS — this
1644 /// SKU's trunk class — has no mmvq/batched kernel, so BOTH m=1 decode and the m=B
1645 /// walk ride `qmatvec_iq4_XS_dp4a` (grid (out_f, m): each column IS the m=1 dp4a
1646 /// program). Same class at every width = the decode-parity law by construction.
1647 /// * `rope_neox2` takes per-row positions (tok = row / n_heads) — row bi rotates at
1648 /// ITS pos with the layer's (n_rot, base, ff), same bits as its solo call.
1649 /// * per-session append/fa_decode_kvmod: literally the eager arm's calls on that
1650 /// session's own cache and views.
1651 /// * MoE (`moe_ffn_il_zq8` at t=B): the router is per-column decode-exact at
1652 /// t < PRIME_MIN_T (m=1 program per column), sigmoid routing + expert dispatch are
1653 /// per-token — a session's experts are a function of its own row only.
1654 /// The known eager-vs-batched FP gap is why PP-N Step35 deliberately serves THIS walk at
1655 /// B=1 too: the scheduler can change width during a session, so one numeric class must
1656 /// cover every live width. `b2geo35` pins static widths and an explicit B=1 -> B>1
1657 /// transition under live defaults.
1658 ///
1659 /// STAGE-SCOPED FROM BIRTH: `[lo, hi)` + caller-supplied engine/pos_d, so
1660 /// `decode_step_batch_ppn` calls it per stage (per-stage engine, per-stage pos_d, the
1661 /// #87 entry fence and boundary slots unchanged) — the pp2-batch seam lesson.
1662 #[allow(clippy::too_many_arguments)]
1663 pub(crate) fn step35_decode_batch_layers(
1664 &self,
1665 e: &Engine,
1666 x: CudaSlice<f32>,
1667 caches: &mut [&mut Cache],
1668 pos_d: &CudaSlice<i32>,
1669 lo: usize,
1670 hi: usize,
1671 ph_last: &mut std::time::Instant,
1672 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1673 self.step35_decode_rows_layers(e, x, caches, pos_d, None, lo, hi, ph_last)
1674 }
1675
1676 /// Diagnostic generalization of the serving walk: `row_to_cache[r]` names the session
1677 /// whose KV row is consumed by hidden row `r`. Serving passes `None`, preserving the
1678 /// identity mapping and its launch sequence. The MoESD harness passes B groups of gamma
1679 /// consecutive rows so each session's verify columns append causally while projections and
1680 /// MoE dispatch see the full B*gamma target width.
1681 #[allow(clippy::too_many_arguments)]
1682 fn step35_decode_rows_layers(
1683 &self,
1684 e: &Engine,
1685 mut x: CudaSlice<f32>,
1686 caches: &mut [&mut Cache],
1687 pos_d: &CudaSlice<i32>,
1688 row_to_cache: Option<&[usize]>,
1689 lo: usize,
1690 hi: usize,
1691 ph_last: &mut std::time::Instant,
1692 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1693 let b_n = row_to_cache.map_or(caches.len(), |rows| rows.len());
1694 let cfg = &self.cfg;
1695 let n_embd = cfg.n_embd as usize;
1696 let eps = cfg.rms_eps;
1697 cfg.step35.as_ref().ok_or("step35_decode_batch_layers requires step35 cfg")?;
1698 if b_n == 0 || x.len() != b_n * n_embd || pos_d.len() != b_n {
1699 return Err(format!(
1700 "step35 row mapping shape mismatch: rows={b_n} x={} pos={} n_embd={n_embd}",
1701 x.len(), pos_d.len(),
1702 )
1703 .into());
1704 }
1705 if row_to_cache.is_some_and(|rows| rows.iter().any(|&ci| ci >= caches.len())) {
1706 return Err("step35 row mapping names a missing cache".into());
1707 }
1708 let cache_index = |row: usize| row_to_cache.map_or(row, |rows| rows[row]);
1709 // b2geo35 gate evidence: one line, first B>1 walk only (grep-stable prefix).
1710 if b_n > 1 {
1711 static ONCE: std::sync::Once = std::sync::Once::new();
1712 ONCE.call_once(|| {
1713 eprintln!("[step35-batch] first B>1 batched step35 walk: B={b_n} layers=[{lo},{hi})");
1714 });
1715 }
1716
1717 for il in lo..hi {
1718 let layer = &self.layers[il];
1719 let Mixer::Full(fa) = &layer.mixer else {
1720 return Err(format!("step35 layer {il} is not full-attn — corrupt config").into());
1721 };
1722 let geometry = self.step35_geom(il);
1723 let hd = geometry.head_dim_k as usize;
1724 let nkv = geometry.n_head_kv as usize;
1725 let nh = geometry.n_head as usize;
1726 let rbase = geometry.rope_base;
1727 let scale = geometry.attention_scale();
1728 let swa = geometry.window.is_some();
1729 let win = geometry.window.unwrap_or(0) as usize;
1730 let n_rot = geometry.n_rot as usize;
1731 let q_dim = nh * hd;
1732 let kv_dim = nkv * hd;
1733
1734 // ---- attn_norm + q8_1 quantize, batched (B rows) ----
1735 let anorm = layer.attn_norm.float_data();
1736 let mut xn = e.uninit(b_n * n_embd)?;
1737 e.rms_norm(&x, anorm, &mut xn, n_embd, b_n, eps)?;
1738 let (hq, hdq) = e.quantize_q8_1(&xn, b_n, n_embd)?;
1739
1740 // ---- batched projections: q/k/v + the separate head-wise gate (one weight
1741 // stream for B rows; xn is the live f32 fallback for non-q8_1-fast classes) ----
1742 let q0 = e.matmul_pre(&fa.wq, &hq, &hdq, &xn, b_n)?;
1743 let k0 = e.matmul_pre(&fa.wk, &hq, &hdq, &xn, b_n)?;
1744 let v0 = e.matmul_pre(&fa.wv, &hq, &hdq, &xn, b_n)?;
1745 let gw = fa.attn_gate.as_ref()
1746 .ok_or("step35 layer is missing attn_gate.weight (head-wise attention gate)")?;
1747 // gate input = the post-attn_norm hidden (upstream `cur`) — same xn/q8 pair.
1748 let gt = e.matmul_pre(gw, &hq, &hdq, &xn, b_n)?;
1749
1750 // ---- q/k RMSNorm over head_dim rows + the per-layer PARTIAL rope ----
1751 let mut q = e.uninit(b_n * q_dim)?;
1752 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, b_n * nh, eps)?;
1753 let mut k = e.uninit(b_n * kv_dim)?;
1754 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, b_n * nkv, eps)?;
1755 let ff = if geometry.rope_factors {
1756 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
1757 } else {
1758 None
1759 };
1760 e.rope_neox2(&mut q, &mut k, pos_d, hd, n_rot, nh, nkv, b_n, rbase, 1.0, ff)?;
1761 ph_mark(e, 1, ph_last)?;
1762
1763 // ---- per-session: KV append + windowed/global fa_decode (each session's OWN
1764 // len drives its view offset — the iso-gap law, no cross-session term) ----
1765 let mut attn = e.uninit(b_n * q_dim)?;
1766 if b_n == 1 {
1767 // B=1 SPECIALIZED ENTRY (lane/cx-eagerpar): the general row loop below
1768 // materializes q_row and a_row because a B>1 FA call consumes/produces one
1769 // contiguous row at a time. At B=1, q and attn already ARE those whole rows.
1770 // Pass them directly to the same fa_decode_kvmod call: this removes two
1771 // arithmetic-free D2D copies (90 launches/token on Step3.7's 45 layers)
1772 // without changing any arithmetic kernel, shape, argument value, or order.
1773 // Keep the B>1 body verbatim below; b1fix's one-class/transition gates are
1774 // the promotion bar, not an FP-similarity tolerance.
1775 let kvl = caches[cache_index(0)].kv[il].as_mut().unwrap();
1776 let k_row = k.slice(0..kv_dim);
1777 let v_row = v0.slice(0..kv_dim);
1778 let next_len = kvl.len + 1;
1779 let (off, t_kv) = if swa && next_len > win {
1780 (next_len - win, win)
1781 } else {
1782 (0, next_len)
1783 };
1784 let write_row = e.prepare_kv_append(kvl, off & !31usize, 1)?;
1785 e.append_kv_quantized_view(
1786 &k_row, &v_row, &mut kvl.k, &mut kvl.v, write_row,
1787 kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
1788 Engine::kv_fp8_on(),
1789 )?;
1790 kvl.len = next_len;
1791 ph_mark(e, 2, ph_last)?;
1792 let physical = kvl.physical_rows(off, off + t_kv)?;
1793 let k_view = e.view_u8_range(&kvl.k, physical.start * kvl.k_tok_bytes,
1794 physical.end * kvl.k_tok_bytes);
1795 let v_view = e.view_u8_range(&kvl.v, physical.start * kvl.v_tok_bytes,
1796 physical.end * kvl.v_tok_bytes);
1797 e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv,
1798 t_kv, scale, kvl.k_tok_bytes, kvl.v_tok_bytes,
1799 Engine::kv_fp8_on())?;
1800 ph_mark(e, 4, ph_last)?;
1801 } else {
1802 for bi in 0..b_n {
1803 let cache = &mut caches[cache_index(bi)];
1804 let kvl = cache.kv[il].as_mut().unwrap();
1805 let k_row = k.slice(bi * kv_dim..(bi + 1) * kv_dim);
1806 let v_row = v0.slice(bi * kv_dim..(bi + 1) * kv_dim);
1807 let next_len = kvl.len + 1;
1808 let (off, t_kv) = if swa && next_len > win {
1809 (next_len - win, win)
1810 } else {
1811 (0, next_len)
1812 };
1813 let write_row = e.prepare_kv_append(kvl, off & !31usize, 1)?;
1814 e.append_kv_quantized_view(
1815 &k_row, &v_row, &mut kvl.k, &mut kvl.v, write_row,
1816 kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes,
1817 Engine::kv_fp8_on(),
1818 )?;
1819 kvl.len = next_len;
1820 ph_mark(e, 2, ph_last)?;
1821 // the eager arm's SWA view arithmetic, verbatim (step35_decode_attn):
1822 // token-aligned offset, keys carry absolute rope, mask is positional.
1823 let physical = kvl.physical_rows(off, off + t_kv)?;
1824 let k_view = e.view_u8_range(&kvl.k, physical.start * kvl.k_tok_bytes,
1825 physical.end * kvl.k_tok_bytes);
1826 let v_view = e.view_u8_range(&kvl.v, physical.start * kvl.v_tok_bytes,
1827 physical.end * kvl.v_tok_bytes);
1828 // The per-session cache view remains authoritative (including SWA's
1829 // physical-row rebase), while Q/O use their existing packed row views.
1830 // This preserves the exact FA program and removes only the two D2D copies.
1831 let q_row = q.slice(bi * q_dim..(bi + 1) * q_dim);
1832 let mut a_row = attn.slice_mut(bi * q_dim..(bi + 1) * q_dim);
1833 e.fa_decode_kvmod_view(&q_row, &k_view, &v_view, &mut a_row,
1834 hd, nh, nkv, t_kv, scale,
1835 kvl.k_tok_bytes, kvl.v_tok_bytes,
1836 Engine::kv_fp8_on())?;
1837 ph_mark(e, 4, ph_last)?;
1838 }
1839 }
1840
1841 // ---- head-wise gate (one sigmoid per (token, head), pre-wo) + o-proj at m=B ----
1842 let mut ag = e.uninit(b_n * q_dim)?;
1843 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, b_n)?;
1844 let mixed = e.matmul(&fa.wo, &ag, b_n)?;
1845 ph_mark(e, 5, ph_last)?;
1846
1847 // ---- residual add + post_attn_norm + FFN, batched ----
1848 let pnorm = layer.post_attn_norm.float_data();
1849 let mut x1 = e.uninit(b_n * n_embd)?;
1850 let mut z = e.uninit(b_n * n_embd)?;
1851 e.add_rms_norm(&x, &mixed, pnorm, &mut x1, &mut z, n_embd, b_n, eps)?;
1852 let ffn_out = match &layer.ffn {
1853 crate::hybrid::Ffn::Dense { ffn_gate, ffn_up, ffn_down } => {
1854 // A dense step35 FFN's clamp is the SHEXP array (upstream's one
1855 // build_ffn serves dense + shared expert, llama-graph.cpp:1751);
1856 // ffn_act_lim dispatches clamped/plain per layer. Layers 0-2 (the
1857 // leading dense) have no live limit on this artifact, but the route
1858 // is correct by construction, not by artifact.
1859 let n_ff = ffn_gate.out_features();
1860 let (zq, zd) = e.quantize_q8_1(&z, b_n, n_embd)?;
1861 let g = e.matmul_pre(ffn_gate, &zq, &zd, &z, b_n)?;
1862 let u = e.matmul_pre(ffn_up, &zq, &zd, &z, b_n)?;
1863 let mut act = e.uninit(b_n * n_ff)?;
1864 Self::ffn_act_lim(e, cfg, &g, &u, 1.0, 1.0,
1865 cfg.clamp_shexp_at(il as u32), &mut act, b_n * n_ff)?;
1866 let (aq, ad) = e.quantize_q8_1(&act, b_n, n_ff)?;
1867 e.matmul_pre(ffn_down, &aq, &ad, &act, b_n)?
1868 }
1869 // t=B < PRIME_MIN_T: per-column decode-exact router + host sigmoid routing
1870 // + per-token expert dispatch — the same per-token program as eager t=1,
1871 // including the per-layer SwiGLU clamp (43/44) via the sequential path's
1872 // ffn_act_lim. The sigmoid-router deny on dev/pairs holds by predicate.
1873 crate::hybrid::Ffn::Moe(m) =>
1874 self.moe_ffn_il_zq8(e, m, &z, None, b_n, il as u16)?,
1875 };
1876 let mut x2 = e.uninit(b_n * n_embd)?;
1877 e.add(&x1, &ffn_out, &mut x2, b_n * n_embd)?;
1878 x = x2;
1879 ph_mark(e, 9, ph_last)?;
1880 }
1881 Ok(x)
1882 }
1883
1884 /// Standalone MoESD target forward. This entrypoint is not used by serving: it widens the
1885 /// existing Step-3.7 batched layer walk to B*gamma rows while preserving one causal KV chain
1886 /// per session. It returns device logits and performs no sampling or logits D2H, matching the
1887 /// target-model term T_T measured by the paper.
1888 pub fn moesd_target_forward(
1889 &self,
1890 e: &Engine,
1891 tokens: &[u32],
1892 batch: usize,
1893 gamma: usize,
1894 caches: &mut [&mut Cache],
1895 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1896 if self.cfg.step35.is_none() {
1897 return Err("MoESD target forward currently requires Step-3.7/Step35 geometry".into());
1898 }
1899 if batch == 0 || gamma == 0 || caches.len() != batch || tokens.len() != batch * gamma {
1900 return Err(format!(
1901 "MoESD shape mismatch: B={batch} gamma={gamma} caches={} tokens={}",
1902 caches.len(), tokens.len(),
1903 )
1904 .into());
1905 }
1906 let rows = batch * gamma;
1907 if rows > 256 {
1908 return Err(format!("MoESD target width {rows} exceeds the frozen 32*8 matrix").into());
1909 }
1910 let n_embd = self.cfg.n_embd as usize;
1911 let eps = self.cfg.rms_eps;
1912 let payload = rows * n_embd;
1913 let row_to_cache: Vec<usize> = (0..batch)
1914 .flat_map(|session| (0..gamma).map(move |_| session))
1915 .collect();
1916 let positions: Vec<i32> = row_to_cache
1917 .iter()
1918 .enumerate()
1919 .map(|(row, &session)| (caches[session].pos + row % gamma) as i32)
1920 .collect();
1921 let mut ph_last = std::time::Instant::now();
1922
1923 let logits = if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
1924 if fence.len() != 3 || crate::pp::pp2_streams_off() {
1925 return Err("MoESD PP target forward requires the live two-stage stream split".into());
1926 }
1927 let rt = crate::pp::PpNRt::get(e)?;
1928 if rt.n_stages() != 2 {
1929 return Err(format!("MoESD expected two PP stages, got {}", rt.n_stages()).into());
1930 }
1931 let caller_stream = e.stream();
1932 rt.fence_stages_behind(&caller_stream)?;
1933 let slot = {
1934 let _st0 = rt.enter(0);
1935 let e0 = rt.engine(0, e);
1936 let pos_d = e0.htod_i32(&positions)?;
1937 let x = e0.htod(&self.embd.gather(n_embd, tokens))?;
1938 ph_mark(e0, 0, &mut ph_last)?;
1939 let x = self.step35_decode_rows_layers(
1940 e0,
1941 x,
1942 caches,
1943 &pos_d,
1944 Some(&row_to_cache),
1945 fence[0],
1946 fence[1],
1947 &mut ph_last,
1948 )?;
1949 rt.tx(0, &x, payload)?
1950 };
1951 let logits = {
1952 let _st1 = rt.enter(1);
1953 let e1 = rt.engine(1, e);
1954 let pos_d = e1.htod_i32(&positions)?;
1955 let x = rt.rx(0, slot, payload)?;
1956 let x = self.step35_decode_rows_layers(
1957 e1,
1958 x,
1959 caches,
1960 &pos_d,
1961 Some(&row_to_cache),
1962 fence[1],
1963 fence[2],
1964 &mut ph_last,
1965 )?;
1966 let mut hn = e1.uninit(payload)?;
1967 e1.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, rows, eps)?;
1968 let logits = e1.matmul(&self.output, &hn, rows)?;
1969 rt.publish_to(1, &caller_stream)?;
1970 logits
1971 };
1972 logits
1973 } else {
1974 let pos_d = e.htod_i32(&positions)?;
1975 let x = e.htod(&self.embd.gather(n_embd, tokens))?;
1976 ph_mark(e, 0, &mut ph_last)?;
1977 let x = self.step35_decode_rows_layers(
1978 e,
1979 x,
1980 caches,
1981 &pos_d,
1982 Some(&row_to_cache),
1983 0,
1984 self.layers.len(),
1985 &mut ph_last,
1986 )?;
1987 let mut hn = e.uninit(payload)?;
1988 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, rows, eps)?;
1989 e.matmul(&self.output, &hn, rows)?
1990 };
1991 for cache in caches.iter_mut() {
1992 cache.pos += gamma;
1993 }
1994 Ok(logits)
1995 }
1996
1997 /// The batched tick's TAIL, after the trunk: grammar masks -> device sampling -> lean
1998 /// logits park -> `pos` bump. Split out with the pp seam (`decode_batch_layers`) because
1999 /// under a stage split this runs on the LAST stage's engine and device — the lm_head, the
2000 /// masks, the sampler, and `cache.last_logits_dev` all live where the final residual
2001 /// lands, and the caller must be able to place them there without duplicating 90 lines of
2002 /// serving contract. `logits` is `[b_n, n_vocab]` already computed by the caller (the
2003 /// output_norm + lm_head pair stays at the call site so a stage split can fence around
2004 /// it); everything after it is here, verbatim.
2005 #[allow(clippy::too_many_arguments)]
2006 fn decode_batch_epilogue(
2007 &self,
2008 e: &Engine,
2009 caches: &mut [&mut Cache],
2010 samp: &[Option<(f32, u64, u32)>],
2011 masks: &[Option<(&CudaSlice<u32>, usize)>],
2012 lean: bool,
2013 logits: CudaSlice<f32>,
2014 b_n: usize,
2015 ph_last: &mut std::time::Instant,
2016 ) -> Result<(Vec<Vec<f32>>, Vec<Option<u32>>), Box<dyn std::error::Error>> {
2017 // GRAMMAR MASKS (constrained decoding): preserve each masked row's PRISTINE logits
2018 // for its consumer (lean park into cache.last_logits_dev — the reuse-pool park stays
2019 // unmasked, the v1 contract — or the non-lean D2H), then ban in place BEFORE the
2020 // device sampler reads the row. All stream-ordered; masks=&[] takes no new branch.
2021 let n_vocab = self.output.out_features();
2022 let mut logits = logits;
2023 let mut pristine: Vec<Option<CudaSlice<f32>>> = Vec::new();
2024 if masks.iter().take(b_n).any(|m| m.is_some()) {
2025 pristine.resize_with(b_n, || None);
2026 for (bi, m) in masks.iter().take(b_n).enumerate() {
2027 let Some((mask, words)) = m else { continue };
2028 assert!(samp.get(bi).copied().flatten().is_some(),
2029 "grammar-masked row {bi} must request a device sample");
2030 if lean {
2031 let cache = &mut caches[bi];
2032 if cache.last_logits_dev.as_ref().map(|d| d.len() < n_vocab).unwrap_or(true) {
2033 cache.last_logits_dev = Some(e.uninit(n_vocab)?);
2034 }
2035 let dst = cache.last_logits_dev.as_mut().unwrap();
2036 e.dtod_copy_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab), dst)?;
2037 } else {
2038 let mut p = e.uninit(n_vocab)?;
2039 e.dtod_copy_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab), &mut p)?;
2040 pristine[bi] = Some(p);
2041 }
2042 e.mask_logits_col(&mut logits, mask, bi, n_vocab, *words)?;
2043 }
2044 }
2045
2046 // Device-side sampling for requested rows (see the method doc). Enqueued before the
2047 // big logits D2H so the tiny [B] token readback rides the same sync.
2048 let mut next: Vec<Option<u32>> = vec![None; b_n];
2049 if samp.iter().take(b_n).any(|s| s.is_some()) {
2050 let mut toks = e.alloc_u32_zeroed(b_n)?;
2051 let mut perturb: Option<CudaSlice<f32>> = None;
2052 for (bi, s) in samp.iter().take(b_n).enumerate() {
2053 let Some((temp, seed, ctr)) = s else { continue };
2054 if *temp <= 0.0 {
2055 e.argmax_token_device_col(&logits, bi, n_vocab, &mut toks, bi)?;
2056 } else {
2057 if perturb.is_none() {
2058 perturb = Some(e.zeros(n_vocab)?);
2059 }
2060 let pb = perturb.as_mut().unwrap();
2061 e.gumbel_perturb_col(&logits, bi, pb, n_vocab, *seed, *ctr, *temp)?;
2062 e.argmax_token_device_col(pb, 0, n_vocab, &mut toks, bi)?;
2063 }
2064 }
2065 let host_toks = e.dtoh_u32(&toks)?;
2066 for (bi, s) in samp.iter().take(b_n).enumerate() {
2067 if s.is_some() {
2068 next[bi] = Some(host_toks[bi]);
2069 }
2070 }
2071 }
2072
2073 let lean_any = lean && samp.iter().take(b_n).any(|s| s.is_some());
2074 let rows: Vec<Vec<f32>> = if lean_any {
2075 // LEAN: park device-sampled rows on-device (per-cache buffer, dtod); D2H only
2076 // the rows that still need host logits. No sampled rows + no fallback rows =
2077 // the big D2H disappears (the [B] token readback above already synced).
2078 for (bi, s) in samp.iter().take(b_n).enumerate() {
2079 if s.is_none() { continue; }
2080 // grammar-masked rows already parked their PRISTINE copy above — the
2081 // in-place ban has since poisoned this row for the reuse-pool consumer.
2082 if masks.get(bi).copied().flatten().is_some() { continue; }
2083 let cache = &mut caches[bi];
2084 if cache.last_logits_dev.as_ref().map(|d| d.len() < n_vocab).unwrap_or(true) {
2085 cache.last_logits_dev = Some(e.uninit(n_vocab)?);
2086 }
2087 let dst = cache.last_logits_dev.as_mut().unwrap();
2088 e.dtod_copy_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab), dst)?;
2089 }
2090 (0..b_n)
2091 .map(|bi| {
2092 if samp.get(bi).copied().flatten().is_some() {
2093 Ok(Vec::new())
2094 } else {
2095 e.dtoh_view(&logits.slice(bi * n_vocab..(bi + 1) * n_vocab))
2096 }
2097 })
2098 .collect::<Result<_, _>>()?
2099 } else {
2100 let host = e.dtoh(&logits)?;
2101 (0..b_n).map(|bi| {
2102 // grammar-masked non-lean rows return the PRISTINE copy (the in-place ban
2103 // must never leak into last_logits — reuse-pool/park semantics unchanged).
2104 if let Some(p) = pristine.get(bi).and_then(|p| p.as_ref()) {
2105 return e.dtoh(p);
2106 }
2107 Ok(host[bi * n_vocab..(bi + 1) * n_vocab].to_vec())
2108 }).collect::<Result<_, _>>()?
2109 };
2110 for c in caches.iter_mut() {
2111 c.pos += 1;
2112 }
2113 ph_mark(e, 11, ph_last)?;
2114 Ok((rows, next))
2115 }
2116}
2117
2118fn b1_fast_arch_eligible(arch: &Arch) -> bool {
2119 !matches!(arch, Arch::Qwen35Moe)
2120}
2121
2122#[cfg(test)]
2123mod tests {
2124 use super::b1_fast_arch_eligible;
2125 use memra_gguf::config::Arch;
2126
2127 #[test]
2128 fn qwen35_moe_stays_in_one_decode_numeric_class_across_widths() {
2129 assert!(!b1_fast_arch_eligible(&Arch::Qwen35Moe));
2130 assert!(b1_fast_arch_eligible(&Arch::Qwen35));
2131 assert!(b1_fast_arch_eligible(&Arch::Qwen3Moe));
2132 }
2133}