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