memra_engine/decode.rs
1//! Incremental decode (T=1) with the dual cache + greedy generation loop. Serves end-to-end.
2//! Reuses the validated kernels; threads KV (full-attn) and conv/SSM state (linear-attn) across steps.
3
4use crate::cache::{Cache, RecurLayer};
5use crate::forward::argmax;
6use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer};
7use crate::Engine;
8use cudarc::driver::CudaSlice;
9use std::collections::HashMap;
10
11/// Persistent CUDA-graph decode state (CUDA-GRAPH-PLAN Phase 3). Holds the device-resident counters
12/// the captured graph reads/writes (`token_d` = current/next token id, `pos_d` = rope position) — both
13/// at FIXED addresses baked into every captured graph — plus the per-`t_kv`-bucket graph cache. The
14/// bucket key is the eager `(fa_vec, n_splits)` pair (see `Engine::fa_bucket_key`): every t_kv that
15/// maps to the same key reproduces eager's split geometry, so one captured graph replays bit-identically
16/// for the whole bucket. A new key triggers a re-capture (n_splits changes ~every 64 tokens).
17pub struct GraphDecodeState {
18 pub token_d: CudaSlice<u32>, // [1] resident next-token id (argmax writes, embed reads)
19 pub pos_d: CudaSlice<i32>, // [1] resident rope position counter
20 pub graphs: HashMap<(bool, usize), cudarc::driver::CudaGraph>,
21 pub bucket_max: HashMap<(bool, usize), usize>, // bucket key -> bucket_max fed to the capture
22 pub captures: usize, // count of (re)captures, for reporting
23}
24
25/// Long-lived step-wise CUDA-graph decode session (see HybridModel::graph_session_new).
26/// One replay per step(); the only steady-state D2H is the 4-byte next-token read.
27pub struct GraphSession {
28 pub gs: GraphDecodeState,
29 pub cache: Cache,
30 /// LOAD-BEARING hold: the captured graph's embed-gather node references this
31 /// allocation — dropping it would free memory the graph still reads.
32 #[allow(dead_code)]
33 embd_gpu: CudaSlice<u8>,
34 graph: cudarc::driver::CudaGraph,
35 plan: Vec<crate::graph_update::FaMain>,
36 /// session budget: last valid t_kv (pos + max_new + 1 at creation).
37 pub bucket_max: usize,
38 /// current capture's kernel-class segment end — step() recaptures past it
39 /// (round 45: exec-update retunes splits, it cannot swap kernels; see
40 /// graph_decode_loop's SEGMENTS note).
41 seg_end: usize,
42 qt: i32,
43 row_bytes: usize,
44 n_vocab: usize,
45 /// GRAMMAR MASK (constrained decoding, 2026-08-03): packed llguidance bitset the
46 /// captured graph reads (mask_logits_f32 between lm_head and the in-graph argmax).
47 /// STABLE POINTER — baked at capture, carried across recaptures; the caller uploads
48 /// fresh contents (upload_mask) before every step. None = no mask node captured.
49 mask_dev: Option<CudaSlice<u32>>,
50 mask_words: usize,
51}
52
53impl GraphSession {
54 /// One graph-replay decode step. Returns the next token (already fed back into the
55 /// resident token_d — the following step consumes it). Errors past bucket_max
56 /// (the caller sized max_new at capture). Transparently recaptures when the eager
57 /// kernel class changes (fa_vec floor / v4 max / fa512 floor crossings).
58 pub fn step(&mut self, e: &Engine, m: &crate::hybrid::HybridModel)
59 -> Result<u32, Box<dyn std::error::Error>> {
60 if self.cache.pos + 1 >= self.bucket_max {
61 return Err("GraphSession: past bucket_max (generation budget exceeded)".into());
62 }
63 if self.cache.pos + 1 > self.seg_end {
64 m.graph_session_recapture(e, self)?;
65 }
66 crate::graph_update::fa_apply(&self.graph, &mut self.plan, self.cache.pos + 1,
67 crate::fa_split_keys)?;
68 self.graph.launch()?;
69 self.cache.pos += 1;
70 for kvl in self.cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
71 kvl.len += 1;
72 }
73 e.dtoh_u32_one(&self.gs.token_d)
74 }
75
76 /// GRAMMAR MASK upload (constrained graph sessions): fresh packed-bitset contents into
77 /// the STABLE buffer the captured graph reads — call before every step(). The word
78 /// count is a capture-time kernel arg (constant per model: the tokenizer vocab is
79 /// fixed), so the length must match the capture exactly.
80 pub fn upload_mask(&mut self, e: &Engine, words: &[u32])
81 -> Result<(), Box<dyn std::error::Error>> {
82 let Some(d) = self.mask_dev.as_mut() else {
83 return Err("upload_mask: session captured without a mask node".into());
84 };
85 if words.len() != self.mask_words {
86 return Err(format!("upload_mask: {} words != captured {}",
87 words.len(), self.mask_words).into());
88 }
89 e.htod_u32_into(d, words)
90 }
91
92 /// Profiling decomposition of step() (graph-session-gate MEMRA_GS_PROF): the three
93 /// phases exposed separately. prof_launch is ASYNC (no sync) — prof_read carries the
94 /// sync+D2H. Advances the session exactly like step().
95 pub fn prof_apply(&mut self, _e: &Engine) -> Result<(), Box<dyn std::error::Error>> {
96 crate::graph_update::fa_apply(&self.graph, &mut self.plan, self.cache.pos + 1,
97 crate::fa_split_keys)
98 }
99 pub fn prof_launch(&mut self) -> Result<(), Box<dyn std::error::Error>> {
100 self.graph.launch()?;
101 self.cache.pos += 1;
102 for kvl in self.cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
103 kvl.len += 1;
104 }
105 Ok(())
106 }
107 pub fn prof_read(&mut self, e: &Engine) -> Result<u32, Box<dyn std::error::Error>> {
108 e.dtoh_u32_one(&self.gs.token_d)
109 }
110}
111
112impl GraphDecodeState {
113 pub fn new(e: &Engine) -> Result<Self, Box<dyn std::error::Error>> {
114 Ok(GraphDecodeState {
115 token_d: e.stream().clone_htod(&[0u32])?,
116 pos_d: e.htod_i32(&[0])?,
117 graphs: HashMap::new(),
118 bucket_max: HashMap::new(),
119 captures: 0,
120 })
121 }
122}
123
124/// Generation parameters for the reusable serving API (`generate_with`).
125#[derive(Clone, Debug)]
126pub struct GenParams {
127 pub max_new: usize, // hard cap on generated tokens
128 pub max_ctx: Option<usize>, // context-length guard; None => prompt+max_new+8
129 pub eos: Vec<u32>, // stop on any of these token ids (eos/eog + specials)
130}
131impl Default for GenParams {
132 fn default() -> Self {
133 GenParams {
134 max_new: 128,
135 max_ctx: None,
136 eos: Vec::new(),
137 }
138 }
139}
140
141/// Why generation stopped.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub enum StopReason {
144 Eos,
145 MaxNew,
146 ContextFull,
147 Callback,
148}
149
150/// Result of `generate_with`: the generated token ids + why it stopped.
151pub struct GenOutput {
152 pub tokens: Vec<u32>,
153 pub stop_reason: StopReason,
154}
155
156/// Diagnostic-only snapshots of Hy3 layer 0 in the eager T=1 serving path.
157/// Each buffer is one residual-width device row captured before the next stage can reuse it.
158pub struct Hy3Layer0Stages {
159 pub attention_output: CudaSlice<f32>,
160 pub after_attention: CudaSlice<f32>,
161 pub mlp_output: CudaSlice<f32>,
162 pub residual: CudaSlice<f32>,
163}
164
165impl HybridModel {
166 /// Device embed table for the dc fast loops (lazy ~0.5GB upload). On OOM — tight fits
167 /// where resident experts + KV leave no headroom (35B ct-NVFP4 artifact at default
168 /// budget, 2026-07-17) — returns None and the caller stays on the host-embd eager loop
169 /// instead of panicking. Double-init race is benign (identical bytes, loser dropped).
170 fn embd_gpu_try(&self, e: &Engine) -> Option<&cudarc::driver::CudaSlice<u8>> {
171 if let Some(v) = self.embd_gpu.get() {
172 return Some(v);
173 }
174 match e.upload_u8(&self.embd.raw) {
175 Ok(buf) => Some(self.embd_gpu.get_or_init(|| buf)),
176 Err(err) => {
177 eprintln!("[embd-gpu] upload failed ({err}); dc loop disabled, host-embd eager loop serves");
178 None
179 }
180 }
181 }
182}
183
184impl HybridModel {
185 /// One decode step for `token` at cache.pos; returns logits [n_vocab] (host f32). Advances cache.
186 pub fn decode_step(
187 &self,
188 e: &Engine,
189 token: u32,
190 cache: &mut Cache,
191 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
192 Ok(self.decode_step_h(e, token, cache)?.0)
193 }
194
195 /// Dense-FFN SwiGLU (T=1 decode): `down @ (silu(gate@z) * (up@z))`. Two fused levers stack here:
196 /// - RANK3 LEVER 2: gate+up NVFP4 macro-scales fold into ONE `silu_mul_scaled*` launch (via
197 /// `matmul_pre_noscale`), saving the two separate `scale_inplace` launches.
198 /// - RANK2 LEVER (q8_1 quant-fold): when ffn_down is ALSO on the q8_1 fast path, the SwiGLU
199 /// epilogue EMITS the q8_1 quantization of `act` directly (`silu_mul_scaled_q8_1`) and feeds
200 /// ffn_down via `matmul_pre`, removing ffn_down's standalone `quantize_q8_1` launch (the
201 /// down-proj activation has one consumer, so the quant folds into its producer for free).
202 /// BIT-IDENTICAL to matmul_pre(gate)+matmul_pre(up)+silu_mul+quantize_q8_1+matmul(down): same
203 /// float silu*mul, same amax/127 q8_1 rounding, same dp4a/mmvq dot. Falls back to the f32 `act`
204 /// + plain matmul(down) path whenever any of the three is off the fast path.
205 #[allow(clippy::too_many_arguments)]
206 fn ffn_swiglu_decode(
207 &self,
208 e: &Engine,
209 ffn_gate: &crate::model::GpuTensor,
210 ffn_up: &crate::model::GpuTensor,
211 ffn_down: &crate::model::GpuTensor,
212 z: &CudaSlice<f32>,
213 n_embd: usize,
214 n_ff: usize,
215 lim: Option<f32>,
216 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
217 // M3 dense layers use swigluoai (clamped) — the silu_mul fused fast paths below encode
218 // plain SiLU; route through ffn_act (macro-scales folded via matmul_pre) until clamped
219 // fused twins exist. step35's per-layer `lim` is the same problem, same escape hatch:
220 // silu_mul_scaled / silu_mul_scaled_q8_1 have no clamped twin.
221 if self.cfg.m3.is_some() || lim.is_some() {
222 let (zq, zd) = e.quantize_q8_1(z, 1, n_embd)?;
223 let gate = e.matmul_pre(ffn_gate, &zq, &zd, z, 1)?;
224 let up = e.matmul_pre(ffn_up, &zq, &zd, z, 1)?;
225 let mut act = e.uninit(n_ff)?;
226 Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0, lim, &mut act, n_ff)?;
227 return Ok(e.matmul(ffn_down, &act, 1)?);
228 }
229 if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
230 let (zq, zd) = e.quantize_q8_1(z, 1, n_embd)?;
231 // DUAL mm-fusion first (NVFP4 gate+up in ONE launch), else two noscale launches.
232 let pair = match e.matmul_pre_dual_noscale(ffn_gate, ffn_up, &zq, &zd, 1)? {
233 Some((g, u)) => (Some(g), Some(u)),
234 None => (
235 e.matmul_pre_noscale(ffn_gate, &zq, &zd, 1)?,
236 e.matmul_pre_noscale(ffn_up, &zq, &zd, 1)?,
237 ),
238 };
239 match pair {
240 (Some((gate, gs)), Some((up, us))) => {
241 // RANK2 fold: if ffn_down is q8_1-fast, emit act PRE-QUANTIZED and skip the
242 // standalone quantize_q8_1 before ffn_down.
243 if e.uses_q8_1_fast(ffn_down) {
244 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, n_ff)?;
245 return Ok(e.matmul_pre(
246 ffn_down, &aq, &ad, /*x_fallback unused on fast path*/ &gate, 1,
247 )?);
248 }
249 let mut act = e.uninit(n_ff)?;
250 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, n_ff)?;
251 return Ok(e.matmul(ffn_down, &act, 1)?);
252 }
253 _ => {
254 // one (or both) not on the separable-scale fast path: scaled matmul + plain silu_mul.
255 let gate = e.matmul_pre(ffn_gate, &zq, &zd, z, 1)?;
256 let up = e.matmul_pre(ffn_up, &zq, &zd, z, 1)?;
257 let mut act = e.uninit(n_ff)?;
258 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
259 return Ok(e.matmul(ffn_down, &act, 1)?);
260 }
261 }
262 }
263 let gate = e.matmul(ffn_gate, z, 1)?;
264 let up = e.matmul(ffn_up, z, 1)?;
265 let mut act = e.uninit(n_ff)?;
266 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
267 Ok(e.matmul(ffn_down, &act, 1)?)
268 }
269
270 /// Like `ffn_swiglu_decode` but the input is ALREADY q8_1-quantized `(zq, zd)` — used by the
271 /// DECODE NORM-FUSION lever where `add_rms_norm_q8_1` emits the post-attn-normed activation
272 /// pre-quantized (no f32 `z` materialized, no standalone quantize_q8_1 launch). Caller GUARANTEES
273 /// ffn_gate and ffn_up are q8_1-fast (so `matmul_pre_noscale` returns Some at m=1). BIT-IDENTICAL
274 /// to ffn_swiglu_decode(z) when (zq,zd) == quantize_q8_1(z): same matmul_pre_noscale, same
275 /// silu_mul_scaled_q8_1 / silu_mul_scaled, same ffn_down dot.
276 fn ffn_swiglu_decode_pre(
277 &self,
278 e: &Engine,
279 ffn_gate: &crate::model::GpuTensor,
280 ffn_up: &crate::model::GpuTensor,
281 ffn_down: &crate::model::GpuTensor,
282 zq: &CudaSlice<i8>,
283 zd: &CudaSlice<f32>,
284 n_ff: usize,
285 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
286 let pair = match e.matmul_pre_dual_noscale(ffn_gate, ffn_up, zq, zd, 1)? {
287 Some((g, u)) => (Some(g), Some(u)),
288 None => (
289 e.matmul_pre_noscale(ffn_gate, zq, zd, 1)?,
290 e.matmul_pre_noscale(ffn_up, zq, zd, 1)?,
291 ),
292 };
293 match pair {
294 (Some((gate, gs)), Some((up, us))) => {
295 if e.uses_q8_1_fast(ffn_down) {
296 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, n_ff)?;
297 Ok(e.matmul_pre(ffn_down, &aq, &ad, &gate, 1)?)
298 } else {
299 let mut act = e.uninit(n_ff)?;
300 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, n_ff)?;
301 Ok(e.matmul(ffn_down, &act, 1)?)
302 }
303 }
304 // Unreachable when the caller's q8_1-fast guarantee holds (m==1 + fast => Some). Guard
305 // anyway: re-quant from the dequantized pair would need f32; surface a clear error.
306 _ => Err("ffn_swiglu_decode_pre: gate/up not separable-scale at m=1 (caller must guarantee q8_1-fast)".into()),
307 }
308 }
309
310 /// Shared post-attention residual + post-attn-norm + FFN for ONE decode layer, routed by ALL
311 /// decode loops (eager + dc + dc_cap) so they stay bit-identical by construction. DECODE
312 /// NORM-FUSION LEVER: when the layer is Dense AND ffn_gate/ffn_up are q8_1-fast (the daily NVFP4
313 /// case), fuses residual-add + post_attn_norm + q8_1-quantize into ONE `add_rms_norm_q8_1` launch
314 /// and feeds the FFN the pre-quantized activation (skipping its internal quantize_q8_1) — removing
315 /// 1-2 launches + the f32 `z` HBM round-trip per layer. BIT-IDENTICAL to the unfused
316 /// add_rms_norm(or add+rms_norm) + quantize_q8_1 + ffn (all proven bit-identical in kernel_check).
317 /// MEMRA_NO_FUSE_NORMQ forces the unfused f32 path. Returns (x1 residual f32, ffn_out f32).
318 /// True when ALL of a mixer's input projections are on the q8_1 fast path (so the attn-input
319 /// rms_norm can emit q8_1 directly and the mixer skips its internal quantize_q8_1).
320 pub(crate) fn mixer_in_q8_1_fast(&self, e: &Engine, mixer: &Mixer) -> bool {
321 match mixer {
322 Mixer::Full(fa) => {
323 // step35 also projects its head-wise GATE from the same attn-normed input, so
324 // the fused (h-less) arm requires attn_gate on the q8_1 fast path too — without
325 // this the gate matmul would get a zero-length `h`.
326 let gate_ok = match &fa.attn_gate {
327 Some(g) => e.uses_q8_1_fast(g),
328 None => true,
329 };
330 gate_ok && e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk)
331 && e.uses_q8_1_fast(&fa.wv)
332 }
333 Mixer::Linear(la) => {
334 e.uses_q8_1_fast(&la.wqkv)
335 && e.uses_q8_1_fast(&la.wqkv_gate)
336 && e.uses_q8_1_fast(&la.ssm_beta)
337 && e.uses_q8_1_fast(&la.ssm_alpha)
338 }
339 // MLA (increment 2, loader-only): predicate only — never claim the fused
340 // norm+quantize chain for an arm that has no forward yet.
341 Mixer::Mla(_) => false,
342 }
343 }
344
345 /// attn_norm + mixer for the EAGER loop, with the attn-input NORM-FUSION. MEMRA_NO_FUSE_NORMQ
346 /// forces the unfused (separate rms_norm + mixer-internal quantize) path.
347 fn attn_in_norm_mixer(
348 &self,
349 e: &Engine,
350 layer: &crate::hybrid::HybridLayer,
351 x: &CudaSlice<f32>,
352 pos_d: &CudaSlice<i32>,
353 pos: usize,
354 cache: &mut Cache,
355 il: usize,
356 n_embd: usize,
357 eps: f32,
358 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
359 let anorm = layer.attn_norm.float_data();
360 let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
361 && self.mixer_in_q8_1_fast(e, &layer.mixer);
362 if fuse {
363 let (hq, hd) = e.rms_norm_q8_1(x, anorm, n_embd, 1, eps)?;
364 // h is unused on the fast path (matmul_pre x_fallback only used at m>=16); pass a zero-len.
365 let h0 = e.zeros(0)?;
366 match &layer.mixer {
367 Mixer::Full(fa) => {
368 self.full_attn_decode_pre(e, fa, &h0, Some((&hq, &hd)), pos_d, pos, cache, il)
369 }
370 Mixer::Linear(la) => {
371 self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)
372 }
373 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
374 }
375 } else {
376 let mut h = e.uninit(n_embd)?;
377 e.rms_norm(x, anorm, &mut h, n_embd, 1, eps)?;
378 match &layer.mixer {
379 Mixer::Full(fa) => self.full_attn_decode(e, fa, &h, pos_d, pos, cache, il),
380 Mixer::Linear(la) => self.linear_attn_decode(e, la, &h, cache, il),
381 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
382 }
383 }
384 }
385
386 /// attn_norm + mixer for the DEVICE-COUNTER loop (decode_step_dc). Full-attn uses the dc path;
387 /// linear uses the eager-state path (persistent=false), same as decode_step_dc. NORM-FUSED.
388 fn attn_in_norm_mixer_dc(
389 &self,
390 e: &Engine,
391 layer: &crate::hybrid::HybridLayer,
392 x: &CudaSlice<f32>,
393 pos_d: &CudaSlice<i32>,
394 cache: &mut Cache,
395 il: usize,
396 n_embd: usize,
397 eps: f32,
398 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
399 let anorm = layer.attn_norm.float_data();
400 let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
401 && self.mixer_in_q8_1_fast(e, &layer.mixer);
402 if fuse {
403 let (hq, hd) = e.rms_norm_q8_1(x, anorm, n_embd, 1, eps)?;
404 let h0 = e.zeros(0)?;
405 match &layer.mixer {
406 Mixer::Full(fa) => {
407 self.full_attn_decode_dc_pre(e, fa, &h0, &hq, &hd, pos_d, cache, il)
408 }
409 Mixer::Linear(la) => {
410 self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)
411 }
412 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
413 }
414 } else {
415 let mut h = e.uninit(n_embd)?;
416 e.rms_norm(x, anorm, &mut h, n_embd, 1, eps)?;
417 match &layer.mixer {
418 Mixer::Full(fa) => self.full_attn_decode_dc(e, fa, &h, pos_d, cache, il),
419 Mixer::Linear(la) => self.linear_attn_decode(e, la, &h, cache, il),
420 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
421 }
422 }
423 }
424
425 /// attn_norm + mixer for the CAPTURE loop (decode_step_dc_cap). Full-attn uses the dc_cap path
426 /// (fixed bucket_max); linear uses the persistent-state path. NORM-FUSED; capture-safe (rms_norm_q8_1
427 /// + the *_pre mixers enqueue the same kernels every replay, stable buffers).
428 fn attn_in_norm_mixer_dc_cap(
429 &self,
430 e: &Engine,
431 layer: &crate::hybrid::HybridLayer,
432 x: &CudaSlice<f32>,
433 pos_d: &CudaSlice<i32>,
434 cache: &mut Cache,
435 il: usize,
436 bucket_max: usize,
437 n_embd: usize,
438 eps: f32,
439 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
440 let anorm = layer.attn_norm.float_data();
441 let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
442 && self.mixer_in_q8_1_fast(e, &layer.mixer);
443 if fuse {
444 let (hq, hd) = e.rms_norm_q8_1(x, anorm, n_embd, 1, eps)?;
445 let h0 = e.zeros(0)?;
446 match &layer.mixer {
447 Mixer::Full(fa) => self.full_attn_decode_dc_cap_pre(
448 e, fa, &h0, &hq, &hd, pos_d, cache, il, bucket_max,
449 ),
450 Mixer::Linear(la) => {
451 self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, true)
452 }
453 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
454 }
455 } else {
456 let mut h = e.uninit(n_embd)?;
457 e.rms_norm(x, anorm, &mut h, n_embd, 1, eps)?;
458 match &layer.mixer {
459 Mixer::Full(fa) => {
460 self.full_attn_decode_dc_cap(e, fa, &h, pos_d, cache, il, bucket_max)
461 }
462 Mixer::Linear(la) => self.linear_attn_decode_cap(e, la, &h, cache, il),
463 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
464 }
465 }
466 }
467
468 fn residual_norm_ffn(
469 &self,
470 e: &Engine,
471 layer: &crate::hybrid::HybridLayer,
472 x: &CudaSlice<f32>,
473 mixed: &CudaSlice<f32>,
474 n_embd: usize,
475 il: usize,
476 eps: f32,
477 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
478 let pnorm = layer.post_attn_norm.float_data();
479 match &layer.ffn {
480 crate::hybrid::Ffn::Dense {
481 ffn_gate,
482 ffn_up,
483 ffn_down,
484 } => {
485 let n_ff = ffn_gate.out_features();
486 // cfg.m3: the fused-pre chain's silu_mul_scaled* epilogues are plain SiLU —
487 // M3's swigluoai must route through ffn_swiglu_decode's m3 arm (FAST-gate
488 // MISMATCH root cause #2, 2026-07-07: L0 dense FFN clamp skipped under FAST).
489 // step35: SAME failure shape, per LAYER. A dense FFN's limit is the SHEXP array
490 // (upstream's one build_ffn serves dense + shared expert, llama-graph.cpp:1751).
491 let lim = self.cfg.clamp_shexp_at(il as u32);
492 let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
493 && self.cfg.m3.is_none()
494 && lim.is_none()
495 && e.uses_q8_1_fast(ffn_gate)
496 && e.uses_q8_1_fast(ffn_up);
497 if fuse {
498 let mut x1 = e.uninit(n_embd)?;
499 let (zq, zd) = e.add_rms_norm_q8_1(x, mixed, pnorm, &mut x1, n_embd, 1, eps)?;
500 let ffn_out =
501 self.ffn_swiglu_decode_pre(e, ffn_gate, ffn_up, ffn_down, &zq, &zd, n_ff)?;
502 Ok((x1, ffn_out))
503 } else {
504 let mut x1 = e.uninit(n_embd)?;
505 let mut z = e.uninit(n_embd)?;
506 e.add_rms_norm(x, mixed, pnorm, &mut x1, &mut z, n_embd, 1, eps)?;
507 let ffn_out = self.ffn_swiglu_decode(
508 e, ffn_gate, ffn_up, ffn_down, &z, n_embd, n_ff, lim)?;
509 Ok((x1, ffn_out))
510 }
511 }
512 crate::hybrid::Ffn::Moe(m) => {
513 let mut x1 = e.uninit(n_embd)?;
514 let mut z = e.uninit(n_embd)?;
515 // z-quantize fuse (add_rms_norm_zq8) measured NEGATIVE here (158.8 vs 160.6:
516 // the fused warp-per-block quantize pass re-reads z slower than the dedicated
517 // coalesced quantize_q8_1). Kernel + threading kept for graph-capture use where
518 // launch count matters more; eager default = unfused (no gain = no change).
519 e.add_rms_norm(x, mixed, pnorm, &mut x1, &mut z, n_embd, 1, eps)?;
520 let ffn_out = self.moe_ffn_il_zq8(e, m, &z, None, 1, il as u16)?;
521 Ok((x1, ffn_out))
522 }
523 }
524 }
525
526 /// EAGLE3 aux-hidden capture (EAGLE-PLAN N1): one decode step that ALSO returns the trunk
527 /// residual-stream `x` taken AFTER each of the blocks in `aux_layers` (the EAGLE3 encoder feeds
528 /// these 3 layer hiddens through `fc`). Returns (logits[n_vocab] host, aux: Vec<[n_embd] dev>),
529 /// one device buffer per requested aux layer, in `aux_layers` order. The captured tensor is the
530 /// residual `x` produced by that block (`x2` at the loop tail), cloned before the next block
531 /// overwrites it — cheap (one clone_dtod of [n_embd] per aux layer). T=1 decode regime.
532 pub fn decode_step_aux(
533 &self,
534 e: &Engine,
535 token: u32,
536 cache: &mut Cache,
537 aux_layers: &[usize],
538 ) -> Result<(Vec<f32>, Vec<CudaSlice<f32>>), Box<dyn std::error::Error>> {
539 let (logits, aux, _) = self.decode_step_aux_inner(e, token, cache, aux_layers, false)?;
540 Ok((logits, aux))
541 }
542
543 /// Diagnostic-only Hy3 layer-0 trace through the real eager T=1 serving path. Besides the
544 /// final block residual, this captures the attention output before its residual add, the
545 /// after-attention residual, and the dense-MLP output before the final residual add.
546 pub fn decode_step_hy3_layer0_stages(
547 &self,
548 e: &Engine,
549 token: u32,
550 cache: &mut Cache,
551 ) -> Result<(Vec<f32>, Hy3Layer0Stages), Box<dyn std::error::Error>> {
552 if self.cfg.hy3.is_none() {
553 return Err("decode_step_hy3_layer0_stages requires a Hy3 model".into());
554 }
555 if !matches!(
556 self.layers.first().map(|layer| &layer.ffn),
557 Some(crate::hybrid::Ffn::Dense { .. })
558 ) {
559 return Err("Hy3 diagnostic expected layer 0 to use a dense MLP".into());
560 }
561 let (logits, _, stages) = self.decode_step_aux_inner(e, token, cache, &[], true)?;
562 Ok((
563 logits,
564 stages.ok_or("Hy3 layer-0 stages were not captured")?,
565 ))
566 }
567
568 fn decode_step_aux_inner(
569 &self,
570 e: &Engine,
571 token: u32,
572 cache: &mut Cache,
573 aux_layers: &[usize],
574 capture_hy3_layer0: bool,
575 ) -> Result<(Vec<f32>, Vec<CudaSlice<f32>>, Option<Hy3Layer0Stages>), Box<dyn std::error::Error>>
576 {
577 let cfg = &self.cfg;
578 let n_embd = cfg.n_embd as usize;
579 let eps = cfg.rms_eps;
580 let pos = cache.pos;
581 let pos_d = e.htod_i32(&[pos as i32])?;
582
583 let mut x = e.htod(&self.embd.gather(n_embd, &[token]))?;
584 let mut aux: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
585 let mut hy3_layer0 = None;
586
587 for (il, layer) in self.layers.iter().enumerate() {
588 // attn-input NORM-FUSION (eager); shared with decode_step_h.
589 let mixed =
590 self.attn_in_norm_mixer(e, layer, &x, &pos_d, pos, cache, il, n_embd, eps)?;
591 // DECODE NORM-FUSION LEVER (residual_norm_ffn): residual add + post_attn RMSNorm +
592 // q8_1-quantize fused into ONE add_rms_norm_q8_1 launch on the Dense q8_1-fast path, then
593 // the FFN consumes the pre-quantized activation. Bit-identical to the unfused path.
594 let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
595 let mut x2 = e.uninit(n_embd)?;
596 e.add(&x1, &ffn_out, &mut x2, n_embd)?;
597 if capture_hy3_layer0 && il == 0 {
598 hy3_layer0 = Some(Hy3Layer0Stages {
599 attention_output: e.clone_dtod(&mixed)?,
600 after_attention: e.clone_dtod(&x1)?,
601 mlp_output: e.clone_dtod(&ffn_out)?,
602 residual: e.clone_dtod(&x2)?,
603 });
604 }
605 // EAGLE3 N1: capture this block's residual output if it is an aux layer.
606 if aux_layers.contains(&il) {
607 aux.push(e.clone_dtod(&x2)?);
608 }
609 x = x2;
610 }
611 // re-order aux to match aux_layers order (contains() pushes in il order; aux_layers is the
612 // canonical order the encoder concats in — they coincide since aux_layers is ascending).
613 let mut hn = e.uninit(n_embd)?;
614 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
615 let logits = e.matmul(&self.output, &hn, 1)?;
616 let host = e.dtoh(&logits)?;
617 cache.pos += 1;
618 Ok((host, aux, hy3_layer0))
619 }
620
621 /// Like `decode_step`, but ALSO returns the trunk's hidden state `x` taken BEFORE the final
622 /// `output_norm` (MTP-PLAN §A: this is `h_seed` for the NextN head). Device buffer [n_embd].
623 pub fn decode_step_h(
624 &self,
625 e: &Engine,
626 token: u32,
627 cache: &mut Cache,
628 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
629 if self.is_gemma4_e4b() {
630 crate::pp::warn_unwired_once("gemma4-e4b eager decode");
631 return self.gemma4_e4b_decode_step_h(e, token, cache);
632 }
633 if self.cfg.gemma4.is_some() {
634 // pp2 door for the gemma4 arm lives inside gemma4_decode_step_h.
635 return self.gemma4_decode_step_h(e, token, cache);
636 }
637 // M2 ppN door (crate::pp): N-stage split of this walk with an explicit activation
638 // handoff at each boundary. Default OFF — unset env means this branch never taken.
639 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
640 return self.decode_step_h_ppn(e, token, cache, &fence);
641 }
642 let cfg = &self.cfg;
643 let n_embd = cfg.n_embd as usize;
644 let eps = cfg.rms_eps;
645 let pos = cache.pos;
646 let pos_d = e.htod_i32(&[pos as i32])?;
647
648 // embed the single token -> [1, n_embd]
649 let mut x = e.htod(&self.embd.gather(n_embd, &[token]))?;
650
651 // CROSS-LAYER ADD+NORM FUSION (launch-arc 2026-07-07): layer il's post-FFN residual add
652 // (x2 = x1 + ffn_out) and layer il+1's attn_norm+quantize are consecutive row-wise ops —
653 // add_rms_norm_q8_1 does all three in ONE launch (bit-identity proven in kernel_check:
654 // add_rms_norm == add then rms_norm; _q8_1 == then quantize_q8_1). Carry the un-added
655 // (x1, ffn_out) pair into the next iteration; the fused launch materializes x2 (the
656 // residual this layer needs) as its `res` output. Falls back to the separate add when
657 // the next mixer is off the q8_1 fast path.
658 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
659 for (il, layer) in self.layers.iter().enumerate() {
660 let anorm = layer.attn_norm.float_data();
661 let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
662 && self.mixer_in_q8_1_fast(e, &layer.mixer);
663 // NOTE: take() FIRST, branch on fuse after — a tuple pattern like
664 // `if let (Some(p), true) = (pending.take(), fuse)` DROPS the taken pair when
665 // fuse is false (pattern fails post-take) and silently loses the residual add.
666 let taken = pending.take();
667 let mixed = match (taken, fuse) {
668 (Some((x1, f1)), true) => {
669 // fused add + attn_norm + q8_1 (this layer's mixer input), res -> x2
670 let mut x2 = e.uninit(n_embd)?;
671 let (hq, hd) = e.add_rms_norm_q8_1(&x1, &f1, anorm, &mut x2, n_embd, 1, eps)?;
672 x = x2;
673 let h0 = e.zeros(0)?;
674 match &layer.mixer {
675 Mixer::Full(fa) => self.full_attn_decode_pre(
676 e,
677 fa,
678 &h0,
679 Some((&hq, &hd)),
680 &pos_d,
681 pos,
682 cache,
683 il,
684 )?,
685 Mixer::Linear(la) => {
686 self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)?
687 }
688 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
689 }
690 }
691 (taken, _) => {
692 if let Some((x1, f1)) = taken {
693 let mut x2 = e.uninit(n_embd)?;
694 e.add(&x1, &f1, &mut x2, n_embd)?;
695 x = x2;
696 }
697 self.attn_in_norm_mixer(e, layer, &x, &pos_d, pos, cache, il, n_embd, eps)?
698 }
699 };
700
701 // DECODE NORM-FUSION LEVER (residual_norm_ffn): add+post_attn_norm+q8_1 fused on the Dense
702 // fast path. Bit-identical to add + rms_norm + ffn (add_rms_norm == add then rms_norm,
703 // proven in kernel_check; add_rms_norm_q8_1 == add_rms_norm then quantize_q8_1).
704 let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
705 pending = Some((x1, ffn_out));
706 }
707 // final layer's add (no next norm to fuse with — output_norm is f32-out)
708 if let Some((x1, f1)) = pending.take() {
709 let mut x2 = e.uninit(n_embd)?;
710 e.add(&x1, &f1, &mut x2, n_embd)?;
711 x = x2;
712 }
713
714 let mut hn = e.uninit(n_embd)?;
715 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
716 // h_seed = trunk hidden BEFORE output_norm (default, §A) or AFTER it (MEMRA_SPEC_HPOST,
717 // the reference engines' convention — see spec::spec_hpost).
718 let h_seed = if crate::spec::spec_hpost() {
719 e.clone_dtod(&hn)?
720 } else {
721 e.clone_dtod(&x)?
722 };
723 // head-MIPS feasibility probe (MEMRA_DUMP_HN=<path>): append pre-head hiddens for
724 // offline bound analysis. Diagnostic only.
725 if let Ok(path) = std::env::var("MEMRA_DUMP_HN") {
726 let hh = e.dtoh(&hn)?;
727 use std::io::Write;
728 let mut fo = std::fs::OpenOptions::new()
729 .create(true)
730 .append(true)
731 .open(path)?;
732 for v in &hh {
733 fo.write_all(&v.to_le_bytes())?;
734 }
735 }
736 let logits = e.matmul(&self.output, &hn, 1)?;
737 let host = e.dtoh(&logits)?;
738 cache.pos += 1;
739 Ok((host, h_seed))
740 }
741
742 /// M1-PP2 stage subgraph: run layers [lo, hi) of the generic eager walk. Enters with a
743 /// MATERIALIZED residual `x` (no pending fusion pair from outside the range) and exits
744 /// with the range's final residual materialized (the trailing add executed, exactly like
745 /// the last layer of an unsplit walk). Body is the `decode_step_h` loop verbatim with the
746 /// cross-layer add+norm fusion carry LOCAL to the range — so the only state a stage
747 /// boundary has to move is the [n_embd] hidden state. Bit-identity of the cut relies on
748 /// the kernel-check-pinned `add_rms_norm_q8_1 == add then rms_norm_q8_1` identity
749 /// (`pp2-gate` verifies end-to-end on real weights).
750 /// `pub(crate)`: also the B=1 serve fast-path's trunk (decode_batch.rs
751 /// `decode_step_b1_fast`, H3) — shared verbatim so the serve path inherits every m=1
752 /// fusion instead of needing a batched twin per lever.
753 #[allow(clippy::too_many_arguments)]
754 pub(crate) fn decode_layers_eager(
755 &self,
756 e: &Engine,
757 mut x: CudaSlice<f32>,
758 lo: usize,
759 hi: usize,
760 pos_d: &CudaSlice<i32>,
761 pos: usize,
762 cache: &mut Cache,
763 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
764 let n_embd = self.cfg.n_embd as usize;
765 let eps = self.cfg.rms_eps;
766 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
767 for il in lo..hi {
768 let layer = &self.layers[il];
769 let anorm = layer.attn_norm.float_data();
770 let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
771 && self.mixer_in_q8_1_fast(e, &layer.mixer);
772 // take() FIRST, branch on fuse after (see decode_step_h: a tuple pattern drops
773 // the taken pair when fuse is false and silently loses the residual add).
774 let taken = pending.take();
775 let mixed = match (taken, fuse) {
776 (Some((x1, f1)), true) => {
777 let mut x2 = e.uninit(n_embd)?;
778 let (hq, hd) = e.add_rms_norm_q8_1(&x1, &f1, anorm, &mut x2, n_embd, 1, eps)?;
779 x = x2;
780 let h0 = e.zeros(0)?;
781 match &layer.mixer {
782 Mixer::Full(fa) => self.full_attn_decode_pre(
783 e,
784 fa,
785 &h0,
786 Some((&hq, &hd)),
787 pos_d,
788 pos,
789 cache,
790 il,
791 )?,
792 Mixer::Linear(la) => {
793 self.linear_attn_decode_pre(e, la, &h0, &hq, &hd, cache, il, false)?
794 }
795 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
796 }
797 }
798 (taken, _) => {
799 if let Some((x1, f1)) = taken {
800 let mut x2 = e.uninit(n_embd)?;
801 e.add(&x1, &f1, &mut x2, n_embd)?;
802 x = x2;
803 }
804 self.attn_in_norm_mixer(e, layer, &x, pos_d, pos, cache, il, n_embd, eps)?
805 }
806 };
807 let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
808 pending = Some((x1, ffn_out));
809 }
810 // range's final add (no next norm inside the range to fuse with)
811 if let Some((x1, f1)) = pending.take() {
812 let mut x2 = e.uninit(n_embd)?;
813 e.add(&x1, &f1, &mut x2, n_embd)?;
814 x = x2;
815 }
816 Ok(x)
817 }
818
819 /// M2: `decode_step_h` as N stage subgraphs, each on ITS OWN CUDA stream (and, under
820 /// MEMRA_PP_DEVICES, its own device/engine), with the transport-selected boundary
821 /// handoff at each fence cut. Stage 0 = embed + its layer range; each middle stage
822 /// RXes boundary s-1 (waits its ev_tx), runs its range, TXes boundary s; the last
823 /// stage adds output_norm + lm head. Per-layer KV/linear state stays owned by the
824 /// stage that runs the layer; `cache.pos` is snapshotted once and advanced once.
825 /// MEMRA_PP_STREAMS=0 = the increment-1 same-stream seam.
826 /// Gate: `ppn-gate` (bit-identical logits vs unsplit at every N/knob combination).
827 fn decode_step_h_ppn(
828 &self,
829 e: &Engine,
830 token: u32,
831 cache: &mut Cache,
832 fence: &[usize],
833 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
834 if crate::pp::pp2_streams_off() {
835 return self.decode_step_h_ppn_samestream(e, token, cache, fence);
836 }
837 let rt = crate::pp::PpNRt::get(e)?;
838 let n_st = fence.len() - 1;
839 assert_eq!(
840 rt.n_stages(), n_st,
841 "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
842 );
843 // #87 REVERSE PUBLICATION (lane/pp2spec-crash): this body's stage-stream
844 // allocations may reuse pool blocks freed from a PREVIOUS ppn call's outputs
845 // (h_seed, verify vx/ckpt) whose primary-stream consumers are still queued —
846 // the reuse-write races the queued read. Order every stage stream behind the
847 // caller's stream before the first stage allocation. Full anatomy:
848 // `PpNRt::fence_stages_behind`.
849 rt.fence_stages_behind(&e.stream())?;
850 let cfg = &self.cfg;
851 let n_embd = cfg.n_embd as usize;
852 let eps = cfg.rms_eps;
853 let pos = cache.pos;
854
855 // PER-STAGE pos_d (M2 pipelining law): every stage uploads its OWN copy of the
856 // step's pos scalar on ITS stream, so the buffer is allocated, consumed, and
857 // freed on one stream (a shared stage-0 pos_d freed at fn return breaks under
858 // deferred readback: the free enqueues on stream 0 while stages 1..N-1 still
859 // dereference it — the 2026-08-02 pipelined-gate all-logits divergence).
860
861 // ---- STAGE 0 (its own stream): embed + layers [0, fence[1]) + boundary-0 TX ----
862 let mut slot = {
863 let _st0 = rt.enter(0);
864 let e0 = rt.engine(0, e);
865 let pos_d = e0.htod_i32(&[pos as i32])?;
866 let x = e0.htod(&self.embd.gather(n_embd, &[token]))?;
867 let x = self.decode_layers_eager(e0, x, fence[0], fence[1], &pos_d, pos, cache)?;
868 rt.tx(0, &x, n_embd)?
869 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
870 };
871
872 // ---- MIDDLE STAGES s in [1, n_st-1): RX boundary s-1 -> range -> TX boundary s ----
873 for s in 1..n_st - 1 {
874 let _st = rt.enter(s);
875 let es = rt.engine(s, e);
876 let pos_d = es.htod_i32(&[pos as i32])?;
877 let x = rt.rx(s - 1, slot, n_embd)?;
878 let x = self.decode_layers_eager(es, x, fence[s], fence[s + 1], &pos_d, pos, cache)?;
879 slot = rt.tx(s, &x, n_embd)?;
880 }
881
882 // ---- LAST STAGE: RX + layers [fence[n_st-1], n) + output_norm + lm head ----
883 let _stl = rt.enter(n_st - 1);
884 let el = rt.engine(n_st - 1, e);
885 let pos_d = el.htod_i32(&[pos as i32])?;
886 let x = rt.rx(n_st - 2, slot, n_embd)?;
887 let x =
888 self.decode_layers_eager(el, x, fence[n_st - 1], fence[n_st], &pos_d, pos, cache)?;
889 let e = el; // head runs through the last stage's engine on its stream
890
891 let mut hn = e.uninit(n_embd)?;
892 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
893 let h_seed = if crate::spec::spec_hpost() {
894 e.clone_dtod(&hn)?
895 } else {
896 e.clone_dtod(&x)?
897 };
898 // same diagnostics door as decode_step_h (MEMRA_DUMP_HN) so the arms stay observably
899 // interchangeable.
900 if let Ok(path) = std::env::var("MEMRA_DUMP_HN") {
901 let hh = e.dtoh(&hn)?;
902 use std::io::Write;
903 let mut fo = std::fs::OpenOptions::new()
904 .create(true)
905 .append(true)
906 .open(path)?;
907 for v in &hh {
908 fo.write_all(&v.to_le_bytes())?;
909 }
910 }
911 let logits = e.matmul(&self.output, &hn, 1)?;
912 let host = e.dtoh(&logits)?;
913 cache.pos += 1;
914 Ok((host, h_seed))
915 }
916
917 /// MEMRA_PP_STREAMS=0 rollback seam: the increment-1 body generalized to N — every
918 /// stage subgraph on the ambient compute stream, each boundary = two plain dtod copies.
919 fn decode_step_h_ppn_samestream(
920 &self,
921 e: &Engine,
922 token: u32,
923 cache: &mut Cache,
924 fence: &[usize],
925 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
926 let cfg = &self.cfg;
927 let n_embd = cfg.n_embd as usize;
928 let eps = cfg.rms_eps;
929 let pos = cache.pos;
930 let pos_d = e.htod_i32(&[pos as i32])?;
931
932 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) ----
933 let x = e.htod(&self.embd.gather(n_embd, &[token]))?;
934 let mut x = self.decode_layers_eager(e, x, fence[0], fence[1], &pos_d, pos, cache)?;
935
936 // ---- each later stage: explicit [n_embd] handoff (TX copy, RX copy) + range ----
937 for s in 1..fence.len() - 1 {
938 let boundary_tx = e.clone_dtod(&x)?;
939 let boundary_rx = e.clone_dtod(&boundary_tx)?;
940 x = self.decode_layers_eager(e, boundary_rx, fence[s], fence[s + 1], &pos_d, pos, cache)?;
941 }
942
943 let mut hn = e.uninit(n_embd)?;
944 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
945 let h_seed = if crate::spec::spec_hpost() {
946 e.clone_dtod(&hn)?
947 } else {
948 e.clone_dtod(&x)?
949 };
950 if let Ok(path) = std::env::var("MEMRA_DUMP_HN") {
951 let hh = e.dtoh(&hn)?;
952 use std::io::Write;
953 let mut fo = std::fs::OpenOptions::new()
954 .create(true)
955 .append(true)
956 .open(path)?;
957 for v in &hh {
958 fo.write_all(&v.to_le_bytes())?;
959 }
960 }
961 let logits = e.matmul(&self.output, &hn, 1)?;
962 let host = e.dtoh(&logits)?;
963 cache.pos += 1;
964 Ok((host, h_seed))
965 }
966
967 /// M2 increment 3 (DEFERRED READBACK — the pipelining seed): the ppN step WITHOUT the
968 /// terminal logits D2H. Returns `PendingLogits` (device logits + completion event +
969 /// the runtime's dedicated readback stream); the caller keeps 2+ tokens in flight by
970 /// enqueueing step t+1 BEFORE waiting step t (with MEMRA_PP_OVERLAP=1 the
971 /// double-buffered boundary slots actually alternate, so stage 0 of t+1 runs under
972 /// stage 1..N-1 of t; the slot ev_tx/ev_rx chain keeps each token's math fully
973 /// event-ordered either way — enqueueing deeper than 2 is CORRECT, the slots simply
974 /// serialize device-side).
975 ///
976 /// EXACTNESS CONTRACT: per-token logits are BIT-IDENTICAL to the serial arm — same
977 /// kernels, same per-token event order; only the host-side wait moves (scheduling
978 /// change, never math). The pipelined replay arm of `ppn-gate` proves it per step.
979 ///
980 /// NOT produced here (both are trunk COPIES — no math feeding the logits changes):
981 /// h_seed and the MEMRA_DUMP_HN diagnostic tap. The serving loop decides their
982 /// deferred form when it adopts this API.
983 ///
984 /// The caller advances the token stream, so `cache.pos` advances at ENQUEUE (host
985 /// state; device work is event-ordered regardless).
986 pub fn decode_step_h_ppn_deferred(
987 &self,
988 e: &Engine,
989 token: u32,
990 cache: &mut Cache,
991 ) -> Result<crate::pp::PendingLogits, Box<dyn std::error::Error>> {
992 let fence = crate::pp::pp_cuts(self.layers.len())
993 .ok_or("ppn deferred: pp door closed (MEMRA_PP_STAGES unset)")?;
994 if crate::pp::pp2_streams_off() {
995 return Err("ppn deferred needs per-stage streams (MEMRA_PP_STREAMS=0 set)".into());
996 }
997 if self.cfg.gemma4.is_some() {
998 return Err("ppn deferred: generic eager arm only (gemma4 is 2-stage serial)".into());
999 }
1000 if crate::pp::pp_multi_stream_same_device()
1001 && std::env::var("MEMRA_PP_FORCE_SAME_DEV_PIPELINED").as_deref() != Ok("1")
1002 {
1003 return Err(
1004 "ppn deferred: refused with 2+ stage streams on one device — repro'd \
1005 nondeterministic logits (35% flake, 2026-08-02 x20 soak, root cause open: \
1006 shared-Engine kernels concurrent on co-located streams). Use one device \
1007 per stage (MEMRA_PP_DEVICES) or the serial arm. \
1008 MEMRA_PP_FORCE_SAME_DEV_PIPELINED=1 overrides for soak/bisect measurement."
1009 .into(),
1010 );
1011 }
1012 let rt = crate::pp::PpNRt::get(e)?;
1013 let n_st = fence.len() - 1;
1014 assert_eq!(
1015 rt.n_stages(), n_st,
1016 "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
1017 );
1018 let cfg = &self.cfg;
1019 let n_embd = cfg.n_embd as usize;
1020 let eps = cfg.rms_eps;
1021 let pos = cache.pos;
1022
1023 // Per-stage pos_d — see decode_step_h_ppn: under deferred readback a shared
1024 // pos_d's fn-end free races stages 1..N-1 (the free enqueues on stream 0 at
1025 // ENQUEUE time here, no terminal D2H to drain first). Each stage owns its copy.
1026 let mut slot = {
1027 let _st0 = rt.enter(0);
1028 let e0 = rt.engine(0, e);
1029 let pos_d = e0.htod_i32(&[pos as i32])?;
1030 let x = e0.htod(&self.embd.gather(n_embd, &[token]))?;
1031 let x = self.decode_layers_eager(e0, x, fence[0], fence[1], &pos_d, pos, cache)?;
1032 rt.tx(0, &x, n_embd)?
1033 };
1034 for s in 1..n_st - 1 {
1035 let _st = rt.enter(s);
1036 let es = rt.engine(s, e);
1037 let pos_d = es.htod_i32(&[pos as i32])?;
1038 let x = rt.rx(s - 1, slot, n_embd)?;
1039 let x = self.decode_layers_eager(es, x, fence[s], fence[s + 1], &pos_d, pos, cache)?;
1040 slot = rt.tx(s, &x, n_embd)?;
1041 }
1042 let _stl = rt.enter(n_st - 1);
1043 let el = rt.engine(n_st - 1, e);
1044 let pos_d = el.htod_i32(&[pos as i32])?;
1045 let x = rt.rx(n_st - 2, slot, n_embd)?;
1046 let x =
1047 self.decode_layers_eager(el, x, fence[n_st - 1], fence[n_st], &pos_d, pos, cache)?;
1048
1049 let mut hn = el.uninit(n_embd)?;
1050 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1051 let logits = el.matmul(&self.output, &hn, 1)?;
1052 let ev = rt.record_done()?;
1053 cache.pos += 1;
1054 Ok(crate::pp::PendingLogits::new(logits, ev, rt.readback_stream().clone()))
1055 }
1056
1057 /// LOCKSTEP MULTI-STREAM decode (lane-3 M1): m independent streams advance one token each
1058 /// through a single per-layer walk. Per-stream math is identical to `decode_step_h` (same
1059 /// fusion chain, same mixer and FFN calls against that stream's own `Cache`), so each
1060 /// stream's token sequence is bit-identical to its single-stream run. The lockstep order
1061 /// puts the m streams' layer-il MoE calls adjacent in time, so one stream's expert-cache
1062 /// fill serves its siblings within the step — the measured cross-stream io amortization
1063 /// (1.12x/1.32x/1.66x at m=2/4/8) lands without batching attention or the CPU ABI.
1064 pub fn decode_step_lockstep(
1065 &self,
1066 e: &Engine,
1067 tokens: &[u32],
1068 caches: &mut [Cache],
1069 ) -> Result<Vec<Vec<f32>>, Box<dyn std::error::Error>> {
1070 if tokens.len() != caches.len() || tokens.is_empty() {
1071 return Err("lockstep needs one token per stream cache".into());
1072 }
1073 if self.cfg.gemma4.is_some() {
1074 return Err("lockstep decode does not support the gemma4 paths".into());
1075 }
1076 let cfg = &self.cfg;
1077 let n_embd = cfg.n_embd as usize;
1078 let eps = cfg.rms_eps;
1079 let m = tokens.len();
1080
1081 let mut pos_d = Vec::with_capacity(m);
1082 let mut x: Vec<CudaSlice<f32>> = Vec::with_capacity(m);
1083 for (s, &token) in tokens.iter().enumerate() {
1084 pos_d.push(e.htod_i32(&[caches[s].pos as i32])?);
1085 x.push(e.htod(&self.embd.gather(n_embd, &[token]))?);
1086 }
1087 let mut pending: Vec<Option<(CudaSlice<f32>, CudaSlice<f32>)>> =
1088 (0..m).map(|_| None).collect();
1089
1090 // M2 (MEMRA_LOCKSTEP_GROUPED=1): MoE layers batch all m rows through
1091 // moe_ffn_lockstep — resident experts amortize weight reads across streams via the
1092 // grouped GEMM machinery; CPU-assigned experts keep per-row companion calls.
1093 let grouped = match std::env::var("MEMRA_LOCKSTEP_GROUPED").as_deref() {
1094 Ok("1") => true,
1095 Ok("0") => false,
1096 // Auto: grouped wins from m>=3 under the default q8 lanes (M2 gate 2026-07-23:
1097 // m=2 6.17 base vs 5.85 grouped; m=3 6.31 grouped; m=4 5.66 vs 5.34).
1098 _ => m >= 3,
1099 };
1100 // M4a (MEMRA_LOCKSTEP_BATCH_ATTN=1): EXPERIMENTAL DOOR, measured flat — default off.
1101 // Full-attention layers run their WEIGHT-BOUND work (q/k/v and output projections) once
1102 // at m instead of m times, KV-bound work stays per stream. Bit-identity PASS, but e2e
1103 // flat at m=2 (4.72/4.72) and -2% at m=3 (5.24 vs 5.35), 2026-07-25: full-attn is the
1104 // minority layer type here (GDN dominates), so the m-band weight-read saving covers few
1105 // layers and is cancelled by the norm->q8_1 fusion this path gives up on exactly those
1106 // layers, plus its gather/scatter copies. The primitive itself
1107 // (`full_attn_decode_batched`) stays as the m-band building block for a serve loop,
1108 // where batching happens across requests at higher m and no fused alternative exists.
1109 let batch_attn = matches!(
1110 std::env::var("MEMRA_LOCKSTEP_BATCH_ATTN").as_deref(), Ok("1")
1111 ) && m >= 2;
1112 let pos_cat = e.htod_i32(
1113 &caches.iter().take(m).map(|c| c.pos as i32).collect::<Vec<_>>(),
1114 )?;
1115 let n_embd_total = n_embd * m;
1116 let mut xcat = e.uninit(n_embd_total)?;
1117 for (il, layer) in self.layers.iter().enumerate() {
1118 let anorm = layer.attn_norm.float_data();
1119 let fuse = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
1120 && self.mixer_in_q8_1_fast(e, &layer.mixer);
1121 let mut mixed_rows: Vec<Option<CudaSlice<f32>>> = (0..m).map(|_| None).collect();
1122 if batch_attn && matches!(layer.mixer, Mixer::Full(_)) {
1123 // Unfused residual+norm into the contiguous m-band buffer. Bit-identical to the
1124 // fused arm by construction (add_rms_norm_q8_1 == add, rms_norm, quantize_q8_1);
1125 // the batched mixer quantizes all m rows in one call.
1126 for s in 0..m {
1127 if let Some((x1, f1)) = pending[s].take() {
1128 let mut x2 = e.uninit(n_embd)?;
1129 e.add(&x1, &f1, &mut x2, n_embd)?;
1130 x[s] = x2;
1131 }
1132 let mut hn = e.uninit(n_embd)?;
1133 e.rms_norm(&x[s], anorm, &mut hn, n_embd, 1, eps)?;
1134 e.copy_into(&mut xcat, s * n_embd, &hn, n_embd)?;
1135 }
1136 let Mixer::Full(fa) = &layer.mixer else { unreachable!() };
1137 let out_cat =
1138 self.full_attn_decode_batched(e, fa, &xcat, m, &pos_cat, caches, il)?;
1139 for s in 0..m {
1140 let mut mixed = e.uninit(n_embd)?;
1141 e.copy_view_into(
1142 &mut mixed, 0,
1143 &out_cat.slice(s * n_embd..(s + 1) * n_embd), n_embd)?;
1144 if grouped && matches!(&layer.ffn, crate::hybrid::Ffn::Moe(_)) {
1145 mixed_rows[s] = Some(mixed);
1146 } else {
1147 let (x1, ffn_out) =
1148 self.residual_norm_ffn(e, layer, &x[s], &mixed, n_embd, il, eps)?;
1149 pending[s] = Some((x1, ffn_out));
1150 }
1151 }
1152 } else {
1153 for s in 0..m {
1154 let pos = caches[s].pos;
1155 let taken = pending[s].take();
1156 let mixed = match (taken, fuse) {
1157 (Some((x1, f1)), true) => {
1158 let mut x2 = e.uninit(n_embd)?;
1159 let (hq, hd) =
1160 e.add_rms_norm_q8_1(&x1, &f1, anorm, &mut x2, n_embd, 1, eps)?;
1161 x[s] = x2;
1162 let h0 = e.zeros(0)?;
1163 match &layer.mixer {
1164 Mixer::Full(fa) => self.full_attn_decode_pre(
1165 e,
1166 fa,
1167 &h0,
1168 Some((&hq, &hd)),
1169 &pos_d[s],
1170 pos,
1171 &mut caches[s],
1172 il,
1173 )?,
1174 Mixer::Linear(la) => self.linear_attn_decode_pre(
1175 e,
1176 la,
1177 &h0,
1178 &hq,
1179 &hd,
1180 &mut caches[s],
1181 il,
1182 false,
1183 )?,
1184 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1185 }
1186 }
1187 (taken, _) => {
1188 if let Some((x1, f1)) = taken {
1189 let mut x2 = e.uninit(n_embd)?;
1190 e.add(&x1, &f1, &mut x2, n_embd)?;
1191 x[s] = x2;
1192 }
1193 self.attn_in_norm_mixer(
1194 e,
1195 layer,
1196 &x[s],
1197 &pos_d[s],
1198 pos,
1199 &mut caches[s],
1200 il,
1201 n_embd,
1202 eps,
1203 )?
1204 }
1205 };
1206 if grouped && matches!(&layer.ffn, crate::hybrid::Ffn::Moe(_)) {
1207 mixed_rows[s] = Some(mixed);
1208 } else {
1209 let (x1, ffn_out) =
1210 self.residual_norm_ffn(e, layer, &x[s], &mixed, n_embd, il, eps)?;
1211 pending[s] = Some((x1, ffn_out));
1212 }
1213 }
1214 }
1215 if grouped {
1216 if let crate::hybrid::Ffn::Moe(moe_weights) = &layer.ffn {
1217 // Per-stream add+norm (identical math to residual_norm_ffn's MoE arm),
1218 // rows batched for the cross-stream MoE stage, outputs split back.
1219 let pnorm = layer.post_attn_norm.float_data();
1220 let mut zbatch = e.uninit(n_embd_total)?;
1221 let mut x1s: Vec<CudaSlice<f32>> = Vec::with_capacity(m);
1222 for s in 0..m {
1223 let mixed = mixed_rows[s].take().expect("grouped MoE row missing");
1224 let mut x1 = e.uninit(n_embd)?;
1225 let mut z = e.uninit(n_embd)?;
1226 e.add_rms_norm(&x[s], &mixed, pnorm, &mut x1, &mut z, n_embd, 1, eps)?;
1227 e.copy_view_into(&mut zbatch, s * n_embd, &z.slice(0..n_embd), n_embd)?;
1228 x1s.push(x1);
1229 }
1230 let max_block = self.max_moe_block();
1231 let ffn_all =
1232 self.moe_ffn_lockstep(e, moe_weights, &zbatch, m, il as u16, max_block)?;
1233 for (s, x1) in x1s.into_iter().enumerate() {
1234 let mut out = e.uninit(n_embd)?;
1235 e.copy_view_into(
1236 &mut out, 0,
1237 &ffn_all.slice(s * n_embd..(s + 1) * n_embd), n_embd)?;
1238 pending[s] = Some((x1, out));
1239 }
1240 }
1241 }
1242 }
1243
1244 let mut logits_host = Vec::with_capacity(m);
1245 for s in 0..m {
1246 if let Some((x1, f1)) = pending[s].take() {
1247 let mut x2 = e.uninit(n_embd)?;
1248 e.add(&x1, &f1, &mut x2, n_embd)?;
1249 x[s] = x2;
1250 }
1251 let mut hn = e.uninit(n_embd)?;
1252 e.rms_norm(&x[s], self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1253 let logits = e.matmul(&self.output, &hn, 1)?;
1254 logits_host.push(e.dtoh(&logits)?);
1255 caches[s].pos += 1;
1256 }
1257 Ok(logits_host)
1258 }
1259
1260 /// DEVICE-COUNTER decode step (CUDA-GRAPH-PLAN Phase 2). A clone of `decode_step_h` that removes
1261 /// the two per-step VARYING host kernel-args by reading them from device counters:
1262 /// 1. the KV-append write slot -> per-layer `kvl.len_d` (device i32[1])
1263 /// 2. the fa_decode t_kv bound -> the same `kvl.len_d` after `inc_seqlen`
1264 /// plus it keeps the token id + rope pos DEVICE-RESIDENT (embed_gather_device, device rope pos,
1265 /// argmax_token_device). NO graph capture yet — runs the kernels eagerly through the counter
1266 /// path. Must be BIT-IDENTICAL to `decode_step_h`'s token stream (the gate).
1267 ///
1268 /// Args: `token_d` = resident device token id [1] (this step's input token); `pos_d` = resident
1269 /// device rope pos i32[1] (== cache.pos at entry; INCREMENTED in-path); `embd_gpu` = resident embed
1270 /// table; (qt,row_bytes) from EmbedHost::qt_and_row_bytes. Returns the NEXT token id device buffer.
1271 /// `cache.pos` and each `kvl.len`/`kvl.len_d` are advanced to match `decode_step_h`.
1272 pub fn decode_step_dc(
1273 &self,
1274 e: &Engine,
1275 token_d: &CudaSlice<u32>,
1276 pos_d: &mut CudaSlice<i32>,
1277 embd_gpu: &CudaSlice<u8>,
1278 embd_qt: i32,
1279 embd_row_bytes: usize,
1280 cache: &mut Cache,
1281 n_vocab: usize,
1282 ) -> Result<CudaSlice<u32>, Box<dyn std::error::Error>> {
1283 // Route gemma4 to ITS dc twin (mirrors decode_step_h): the generic walk below is the
1284 // qwen-class layer stack — running gemma weights through it produced the argmax-INIT
1285 // passthrough the round-45 g12 gate caught (first Hopper gating of this lane).
1286 if self.is_gemma4_e4b() {
1287 return Err("e4b has no device-counter decode step (dc/graph unwired)".into());
1288 }
1289 // PP DOOR: fail closed (pp2-hardening 2026-08-06). Same hole the batched path had —
1290 // the dc walk below is `for (il, layer) in self.layers.iter().enumerate()` on one
1291 // stream, with no stage split, so a sharded cross-device placement would peer-read
1292 // every remote layer's weights per step. Sits BEFORE the gemma4 delegate because
1293 // that twin has the same unsplit shape. The graph-capture path (`decode_step_dc_cap*`)
1294 // is covered transitively: it captures this same kernel chain, and its drivers reach
1295 // dc first — but a future capture path that does NOT is why the guard is a shared
1296 // helper (`pp::refuse_unsplit_if_remote`) rather than four copies.
1297 crate::pp::refuse_unsplit_if_remote(
1298 "decode_step_dc",
1299 "use the eager pp arm (decode_step_h), which IS stage-split",
1300 )?;
1301 if self.cfg.gemma4.is_some() {
1302 return self.gemma4_decode_step_dc(e, token_d, pos_d, embd_gpu, embd_qt,
1303 embd_row_bytes, cache, n_vocab, None);
1304 }
1305 let cfg = &self.cfg;
1306 let n_embd = cfg.n_embd as usize;
1307 let eps = cfg.rms_eps;
1308
1309 // embed the single (DEVICE-resident) token -> [1, n_embd], no host round-trip of the id.
1310 let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_row_bytes)?;
1311
1312 for (il, layer) in self.layers.iter().enumerate() {
1313 // attn-input NORM-FUSION (dc path); bit-identical to decode_step_h (Phase-2 gate).
1314 let mixed = self.attn_in_norm_mixer_dc(e, layer, &x, pos_d, cache, il, n_embd, eps)?;
1315
1316 // DECODE NORM-FUSION LEVER (residual_norm_ffn): see decode_step_h. Shared helper -> dc
1317 // path stays bit-identical to decode_step_h's token stream (the Phase-2 gate).
1318 let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
1319 let mut x2 = e.uninit(n_embd)?;
1320 e.add(&x1, &ffn_out, &mut x2, n_embd)?;
1321 x = x2;
1322 }
1323
1324 let mut hn = e.uninit(n_embd)?;
1325 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1326 let logits = e.matmul(&self.output, &hn, 1)?;
1327 // device argmax -> next token id stays resident (no logits dtoh).
1328 let next_tok = e.argmax_token_device(&logits, n_vocab)?;
1329 // advance rope pos counter on-device (replaces the per-step htod_i32(&[pos])).
1330 e.inc_seqlen(pos_d)?;
1331 cache.pos += 1;
1332 Ok(next_tok)
1333 }
1334
1335 /// CAPTURE body for CUDA-graph replay (CUDA-GRAPH-PLAN Phase 3). One full decode step enqueued
1336 /// entirely on `e.stream()` with ZERO host sync and ZERO per-step varying host kernel-args:
1337 /// - embed reads the PERSISTENT device `token_d` (last step's argmax), writes scratch `x`.
1338 /// - full-attn layers size n_splits from `bucket_max` (fixed for this capture); the kernel reads
1339 /// the ACTUAL t_kv from the device counter `kvl.len_d`. KV append + device-counter inc happen
1340 /// in-graph. The host `kvl.len`/`cache.pos` are NOT advanced here (the driver advances the host
1341 /// mirrors once per replay; only the DEVICE counters advance inside the graph).
1342 /// - linear-attn layers use the persistent-state variant (copy-back, stable pointers).
1343 /// - lm_head -> parallel 2-pass argmax (`argmax_partial_f32`+`argmax_final_f32`) writes the
1344 /// next id into the PERSISTENT `token_d`.
1345 /// - `inc_seqlen(pos_d)` advances the rope-pos device counter in-graph.
1346 /// Captured ONCE per `bucket_max`; replayed for every t_kv in that bucket. Bit-identical to eager
1347 /// when `bucket_max` reproduces eager's n_splits for the replayed t_kv (the bucket-key contract).
1348 pub fn decode_step_dc_cap(
1349 &self,
1350 e: &Engine,
1351 token_d: &mut CudaSlice<u32>,
1352 pos_d: &mut CudaSlice<i32>,
1353 embd_gpu: &CudaSlice<u8>,
1354 embd_qt: i32,
1355 embd_row_bytes: usize,
1356 cache: &mut Cache,
1357 n_vocab: usize,
1358 bucket_max: usize,
1359 ) -> Result<(), Box<dyn std::error::Error>> {
1360 self.decode_step_dc_cap_masked(e, token_d, pos_d, embd_gpu, embd_qt, embd_row_bytes,
1361 cache, n_vocab, bucket_max, None)
1362 }
1363
1364 /// `decode_step_dc_cap` + GRAMMAR MASK (constrained decoding): with `mask =
1365 /// Some((buf, words))`, mask_logits_f32 bans the packed bitset's unset ids IN the
1366 /// captured graph — a stable-pointer read between lm_head and the in-graph argmax
1367 /// (the KV-pointer pattern: contents change per step, address is baked). `None` is
1368 /// bit-for-bit the unmasked capture.
1369 #[allow(clippy::too_many_arguments)]
1370 pub fn decode_step_dc_cap_masked(
1371 &self,
1372 e: &Engine,
1373 token_d: &mut CudaSlice<u32>,
1374 pos_d: &mut CudaSlice<i32>,
1375 embd_gpu: &CudaSlice<u8>,
1376 embd_qt: i32,
1377 embd_row_bytes: usize,
1378 cache: &mut Cache,
1379 n_vocab: usize,
1380 bucket_max: usize,
1381 mask: Option<(&CudaSlice<u32>, usize)>,
1382 ) -> Result<(), Box<dyn std::error::Error>> {
1383 let cfg = &self.cfg;
1384 let n_embd = cfg.n_embd as usize;
1385 let eps = cfg.rms_eps;
1386
1387 let mut x = e.embed_gather_device(embd_gpu, token_d, n_embd, embd_qt, embd_row_bytes)?;
1388
1389 for (il, layer) in self.layers.iter().enumerate() {
1390 // attn-input NORM-FUSION (capture path); capture-safe + bit-identical to eager.
1391 let mixed = self.attn_in_norm_mixer_dc_cap(
1392 e, layer, &x, pos_d, cache, il, bucket_max, n_embd, eps,
1393 )?;
1394 // DECODE NORM-FUSION LEVER (residual_norm_ffn): see decode_step_aux. Shared helper keeps
1395 // the capture path bit-identical to eager by construction.
1396 let (x1, ffn_out) = self.residual_norm_ffn(e, layer, &x, &mixed, n_embd, il, eps)?;
1397 let mut x2 = e.uninit(n_embd)?;
1398 e.add(&x1, &ffn_out, &mut x2, n_embd)?;
1399 x = x2;
1400 }
1401
1402 let mut hn = e.uninit(n_embd)?;
1403 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, 1, eps)?;
1404 let mut logits = e.matmul(&self.output, &hn, 1)?;
1405 // GRAMMAR MASK: ban before the argmax reads the row (masked argmax == host
1406 // masked-argmax — -FLT_MAX is the argmax kernels' init sentinel).
1407 if let Some((m, words)) = mask {
1408 e.mask_logits_col(&mut logits, m, 0, n_vocab, words)?;
1409 }
1410 // argmax into the PERSISTENT token_d (next step's embed reads it) — same buffer pointer baked
1411 // at capture, written each replay, so the token id never round-trips to host in steady state.
1412 e.argmax_token_device_into(&logits, token_d, n_vocab)?;
1413 e.inc_seqlen(pos_d)?;
1414 Ok(())
1415 }
1416
1417 /// CUDA-GRAPH decode driver (CUDA-GRAPH-PLAN Phase 3). Primes the prompt EAGERLY (device-counter
1418 /// `decode_step_dc`, advancing host + device counters together), then generates `max_new` tokens by
1419 /// CUDA-graph REPLAY: per step it picks the t_kv bucket key, captures a graph on first sight of that
1420 /// key (re-using the SAME persistent counters/cache so replays continue the sequence), and replays.
1421 /// The argmax-written next token stays device-resident in `gs.token_d`; we read back only the [1]
1422 /// u32 after each launch (the gate compares it; a real server can defer this). Returns the generated
1423 /// token ids. Greedy. Bit-identical to eager `decode_step` (the gate).
1424 ///
1425 /// CAPTURE STATE HYGIENE: `capture_graph` runs the step body 3x (2 warmup + 1 capture), each of
1426 /// which mutates the device KV/conv/ssm/counter state. We SNAPSHOT the cache + device counters +
1427 /// token id before capturing and RESTORE them after, so the 3 throwaway runs leave zero residue and
1428 /// replay resumes from the true pre-capture state.
1429 pub fn generate_graph(
1430 &self,
1431 e: &Engine,
1432 gs: &mut GraphDecodeState,
1433 prompt: &[u32],
1434 max_new: usize,
1435 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
1436 let n_embd = self.cfg.n_embd as usize;
1437 let head_dim = self.cfg.head_dim_k as usize;
1438 let (qt, row_bytes) = self.embd.qt_and_row_bytes(n_embd);
1439
1440 // EVENT TRACKING OFF for the WHOLE graph-decode session. cudarc records a per-CudaSlice event
1441 // (the Engine is in multi-stream mode via copy_stream) and inserts `stream.wait(event)` on every
1442 // kernel arg whose buffer was touched — those waits are illegal inside a capture region. The
1443 // captured decode step is strictly single-stream, so this tracking is unnecessary. Disable it
1444 // BEFORE allocating ANY buffer the captured graph will reference (cache, embd, counters,
1445 // scratch) so none of them carry events. SAFETY: decode-dc touches only gpu.stream.
1446 let was_tracking = e.ctx().is_event_tracking();
1447 if was_tracking {
1448 unsafe {
1449 e.ctx().disable_event_tracking();
1450 }
1451 }
1452 let r = self.generate_graph_inner(e, gs, prompt, max_new, n_embd, head_dim, qt, row_bytes);
1453 if was_tracking {
1454 unsafe {
1455 e.ctx().enable_event_tracking();
1456 }
1457 }
1458 r
1459 }
1460
1461 fn generate_graph_inner(
1462 &self,
1463 e: &Engine,
1464 gs: &mut GraphDecodeState,
1465 prompt: &[u32],
1466 max_new: usize,
1467 n_embd: usize,
1468 head_dim: usize,
1469 qt: i32,
1470 row_bytes: usize,
1471 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
1472 let _ = n_embd;
1473 let embd_gpu = e.upload_u8(&self.embd.raw)?;
1474 let max_ctx = prompt.len() + max_new + 8;
1475 let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
1476
1477 // (Re)create the persistent counters tracking-OFF so they carry no events (the caller's
1478 // GraphDecodeState::new may have allocated them with tracking on).
1479 gs.pos_d = e.htod_i32(&[0])?;
1480 gs.token_d = e.stream().clone_htod(&[0u32])?;
1481 // PRIME eagerly: feed each prompt token; advance host + device counters together.
1482 let mut next_in = 0u32;
1483 for &tok in prompt {
1484 e.set_u32_one(&mut gs.token_d, tok)?;
1485 let nt = self.decode_step_dc(
1486 e,
1487 &gs.token_d,
1488 &mut gs.pos_d,
1489 &embd_gpu,
1490 qt,
1491 row_bytes,
1492 &mut cache,
1493 /*n_vocab*/ self.output.out_features(),
1494 )?;
1495 next_in = e.dtoh_u32_one(&nt)?;
1496 }
1497 // gs.token_d now must hold the first generated INPUT token (= argmax of the last prime step).
1498 e.set_u32_one(&mut gs.token_d, next_in)?;
1499
1500 // gemma4 rides ITS graph machinery (per-bucket captures + alloc-free slots; same token
1501 // stream convention: first generated token is out[0]) — graph_decode_loop below captures
1502 // the qwen-class dc step (the round-45 g12 illegal-address find).
1503 if self.cfg.gemma4.is_some() {
1504 let (toks, _reason) = self.gemma4_generate_graph(
1505 e, cache.pos, next_in, &mut cache, max_new, &[], |_| true)?;
1506 gs.captures += 1;
1507 return Ok(toks);
1508 }
1509
1510 let mut out = Vec::with_capacity(max_new);
1511 self.graph_decode_loop(e, gs, &mut cache, &embd_gpu, qt, row_bytes, head_dim, max_new,
1512 |tok| { out.push(tok); None })?;
1513 Ok(out)
1514 }
1515
1516 /// The CUDA-graph EXEC-UPDATE replay loop over an already-primed cache (2026-07-15,
1517 /// the E4B graph-exec pattern generalized): capture the dc step per KERNEL-CLASS
1518 /// SEGMENT, classify its fa nodes (`graph_update::fa_plan` — symbol list is
1519 /// model-generic), then per token retune the fa split geometry to the LIVE eager
1520 /// ladder (`fa_apply` keeps graph and eager in FP lockstep — bit-exact) and replay.
1521 /// The previous per-bucket-key capture map recaptured on every ladder rung
1522 /// (32 recaptures/256 tokens = 97 vs 128 tok/s eager; decode-bench 2026-07-15).
1523 ///
1524 /// SEGMENTS (round 45, the q35 graph-gate dig): exec-update can retune split counts
1525 /// but can NOT swap kernels — a session spanning an eager KERNEL-CLASS boundary
1526 /// (fa_vec floor, the v4 max, the fa512 floor) replayed the capture-time kernel
1527 /// against a different eager kernel below the boundary: valid softmax, different
1528 /// fold order, and the first near-tie flips the stream (q35: deterministic 144/256
1529 /// from step 110, exactly the scalar->vec crossing; regime pinned either way =
1530 /// BIT-IDENTICAL 256/256). One capture per crossed class boundary (2-3/session,
1531 /// not per rung) keeps graph and eager on the SAME kernel at every t_kv.
1532 ///
1533 /// Callers must have synced gs.token_d (= the FIRST generated token), gs.pos_d
1534 /// (= cache.pos) and every kvl.len_d (= kvl.len). Event tracking must be OFF.
1535 #[allow(clippy::too_many_arguments)]
1536 pub(crate) fn graph_decode_loop(&self, e: &Engine, gs: &mut GraphDecodeState,
1537 cache: &mut Cache, embd_gpu: &CudaSlice<u8>,
1538 qt: i32, row_bytes: usize, head_dim: usize, max_new: usize,
1539 mut emit: impl FnMut(u32) -> Option<StopReason>)
1540 -> Result<StopReason, Box<dyn std::error::Error>> {
1541 let _ = head_dim;
1542 let n_vocab = self.output.out_features();
1543 let final_max = cache.pos + max_new + 1;
1544
1545 // first generated token = argmax of the last prime step (emit before replay 1).
1546 let first = e.dtoh_u32_one(&gs.token_d)?;
1547 if let Some(r) = emit(first) { return Ok(r); }
1548 let mut done = 1usize;
1549 while done < max_new {
1550 let (graph, mut plan, seg_end) = self.graph_capture_segment(
1551 e, cache, gs, embd_gpu, qt, row_bytes, n_vocab, final_max)?;
1552
1553 while done < max_new && cache.pos + 1 <= seg_end {
1554 // retune fa geometry to the live t_kv AFTER this replay's in-graph append.
1555 crate::graph_update::fa_apply(&graph, &mut plan, cache.pos + 1,
1556 crate::fa_split_keys)?;
1557 graph.launch()?;
1558 cache.pos += 1;
1559 for kvl in cache.kv.iter_mut().filter_map(|k| k.as_mut()) {
1560 kvl.len += 1;
1561 }
1562 // read back the [1] u32 next token (the only D2H in steady state).
1563 let tok = e.dtoh_u32_one(&gs.token_d)?;
1564 done += 1;
1565 if let Some(r) = emit(tok) { return Ok(r); }
1566 }
1567 }
1568 Ok(StopReason::MaxNew)
1569 }
1570
1571 /// Step-wise CUDA-graph decode session (ARCHITECTURE-H100.md graph-serving lane,
1572 /// 2026-07-26): generate_graph's prime+capture lifted into a long-lived session so a
1573 /// SERVING scheduler can replay ONE step per tick instead of blocking a whole
1574 /// generation. Serving policy (measured): graphs win only at B=1 (214 solo vs 425
1575 /// aggregate batched-eager at B=4) — this is the single-interactive-session path.
1576 /// Capture discipline is generate_graph's verbatim: event tracking must be OFF for
1577 /// every buffer the graph references (new() toggles it), capture at bucket_max =
1578 /// pos + max_new + 1, fa geometry retuned per step (fa_apply, FP lockstep with eager).
1579 pub fn graph_session_new(
1580 &self,
1581 e: &Engine,
1582 prompt: &[u32],
1583 max_new: usize,
1584 ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
1585 let n_embd = self.cfg.n_embd as usize;
1586 let (qt, row_bytes) = self.embd.qt_and_row_bytes(n_embd);
1587 let was_tracking = e.ctx().is_event_tracking();
1588 if was_tracking {
1589 unsafe { e.ctx().disable_event_tracking(); }
1590 }
1591 let r = self.graph_session_new_inner(e, prompt, max_new, qt, row_bytes);
1592 if was_tracking {
1593 unsafe { e.ctx().enable_event_tracking(); }
1594 }
1595 r
1596 }
1597
1598 fn graph_session_new_inner(
1599 &self,
1600 e: &Engine,
1601 prompt: &[u32],
1602 max_new: usize,
1603 qt: i32,
1604 row_bytes: usize,
1605 ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
1606 let n_vocab = self.output.out_features();
1607 let embd_gpu = e.upload_u8(&self.embd.raw)?;
1608 let max_ctx = prompt.len() + max_new + 8;
1609 let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
1610 let mut gs = GraphDecodeState::new(e)?;
1611 gs.pos_d = e.htod_i32(&[0])?;
1612 gs.token_d = e.stream().clone_htod(&[0u32])?;
1613 // prime (dc path — device counters advance with the host)
1614 let mut next_in = 0u32;
1615 for &tok in prompt {
1616 e.set_u32_one(&mut gs.token_d, tok)?;
1617 let nt = self.decode_step_dc(e, &gs.token_d, &mut gs.pos_d, &embd_gpu,
1618 qt, row_bytes, &mut cache, n_vocab)?;
1619 next_in = e.dtoh_u32_one(&nt)?;
1620 }
1621 e.set_u32_one(&mut gs.token_d, next_in)?;
1622 self.graph_session_capture(e, cache, gs, embd_gpu, max_new, qt, row_bytes, n_vocab,
1623 None, 0)
1624 }
1625
1626 /// GraphSession over an ALREADY-PRIMED cache (round 35): keeps the chunked-prefill
1627 /// TTFT. graph_session_new's token-wise re-prime made solo long-prompt promotion a
1628 /// net ~3x END-TO-END LOSS (measured live: 871-tok prompt + 400 gen = 6.4s vs ~2.2s
1629 /// eager). Device counters sync from host state; capture recipe unchanged.
1630 /// Requires event tracking OFF (engine default; MEMRA_EVT=1 callers must not use this
1631 /// — the primed cache's buffers would carry events, illegal inside capture).
1632 pub fn graph_session_from_cache(
1633 &self,
1634 e: &Engine,
1635 cache: Cache,
1636 first_token: u32,
1637 max_new: usize,
1638 ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
1639 self.graph_session_from_cache_masked(e, cache, first_token, max_new, None)
1640 }
1641
1642 /// `graph_session_from_cache` + GRAMMAR MASK (constrained decoding, 2026-08-03):
1643 /// `mask_init = Some(packed bitset)` allocates the session's stable mask buffer
1644 /// (tracking is OFF here — capture-legal), seeds it with the FIRST step's mask, and
1645 /// captures mask_logits_f32 into the graphed step. The caller re-uploads contents
1646 /// per step via `GraphSession::upload_mask` — same stable-pointer discipline as the
1647 /// KV len_d counters. `None` = the unmasked session, byte-identical.
1648 pub fn graph_session_from_cache_masked(
1649 &self,
1650 e: &Engine,
1651 mut cache: Cache,
1652 first_token: u32,
1653 max_new: usize,
1654 mask_init: Option<&[u32]>,
1655 ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
1656 if e.ctx().is_event_tracking() {
1657 return Err("graph_session_from_cache requires event tracking OFF (MEMRA_EVT unset)".into());
1658 }
1659 let n_embd = self.cfg.n_embd as usize;
1660 let (qt, row_bytes) = self.embd.qt_and_row_bytes(n_embd);
1661 let n_vocab = self.output.out_features();
1662 let embd_gpu = e.upload_u8(&self.embd.raw)?;
1663 let mut gs = GraphDecodeState::new(e)?;
1664 gs.pos_d = e.htod_i32(&[cache.pos as i32])?;
1665 gs.token_d = e.stream().clone_htod(&[first_token])?;
1666 for kvl in cache.kv.iter_mut().flatten() {
1667 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
1668 }
1669 let mask_dev = match mask_init {
1670 Some(w) => Some(e.htod_u32_v(w)?),
1671 None => None,
1672 };
1673 let mask_words = mask_init.map(|w| w.len()).unwrap_or(0);
1674 self.graph_session_capture(e, cache, gs, embd_gpu, max_new, qt, row_bytes, n_vocab,
1675 mask_dev, mask_words)
1676 }
1677
1678 /// Eager fa kernel-class fingerprint at a given t_kv: the fa_vec pick plus the
1679 /// intra-vec variant switches (v4 max, fa512 floor) plus the split-ladder rung.
1680 /// fa_apply handles split-count changes WITHIN a rung; anything that changes this
1681 /// tuple needs a fresh capture (bucket_max drives the capture-time kernel pick).
1682 /// Round 45; LADDER RUNG ADDED 2026-08-02 (lane/ladder-3072): the dc kernels derive
1683 /// their in-kernel partition from the CAPTURED split_keys arg (ns_eff =
1684 /// ceil(T_kv/split_keys) — the ONE-PARTITION law), and fa_apply retunes only
1685 /// n_splits/grid. A capture whose segment straddled a ladder rung therefore replayed
1686 /// the far side's partition against eager's near side — same math, different FP fold
1687 /// order, and the first near-tie flips the stream (latent at the old 3072 rung: kat
1688 /// P=3000 passed on logit margins; exposed by the 512 rung: kat P=400 flipped 97/160).
1689 /// With the rung in the fingerprint a capture never straddles it, so the captured
1690 /// split_keys equals the live ladder on every replay — bit-exact at every t_kv.
1691 pub(crate) fn fa_class_of(&self, e: &Engine, t_kv: usize) -> (bool, bool, bool, usize) {
1692 let head_dim = self.cfg.head_dim_k as usize;
1693 let nkv = self.cfg.n_head_kv as usize;
1694 let g_fp8 = Engine::kv_fp8_on();
1695 (e.fa_geom_eager(t_kv, head_dim, nkv, g_fp8).0,
1696 crate::fa_v4_at_pub(t_kv),
1697 head_dim == 512 && t_kv >= crate::fa512_min_tkv(),
1698 crate::fa_split_keys_pub(t_kv, nkv))
1699 }
1700
1701 /// Last t_kv (clamped to `final_max`) sharing `start`'s eager kernel class.
1702 pub(crate) fn fa_segment_end(&self, e: &Engine, start: usize, final_max: usize) -> usize {
1703 let cls = self.fa_class_of(e, start);
1704 let mut end = start;
1705 while end < final_max && self.fa_class_of(e, end + 1) == cls { end += 1; }
1706 end
1707 }
1708
1709 /// Capture one kernel-class segment: snapshot/rollback the warmup runs, capture the
1710 /// dc step at bucket_max = the segment's last t_kv, fa_plan. Shared by the session
1711 /// creation, the session's recapture-on-cross, and graph_decode_loop.
1712 #[allow(clippy::too_many_arguments)]
1713 pub(crate) fn graph_capture_segment(
1714 &self,
1715 e: &Engine,
1716 cache: &mut Cache,
1717 gs: &mut GraphDecodeState,
1718 embd_gpu: &CudaSlice<u8>,
1719 qt: i32,
1720 row_bytes: usize,
1721 n_vocab: usize,
1722 final_max: usize,
1723 ) -> Result<(cudarc::driver::CudaGraph, Vec<crate::graph_update::FaMain>, usize),
1724 Box<dyn std::error::Error>> {
1725 self.graph_capture_segment_masked(e, cache, gs, embd_gpu, qt, row_bytes, n_vocab,
1726 final_max, None)
1727 }
1728
1729 /// `graph_capture_segment` + optional in-graph grammar mask (see decode_step_dc_cap_masked).
1730 #[allow(clippy::too_many_arguments)]
1731 pub(crate) fn graph_capture_segment_masked(
1732 &self,
1733 e: &Engine,
1734 cache: &mut Cache,
1735 gs: &mut GraphDecodeState,
1736 embd_gpu: &CudaSlice<u8>,
1737 qt: i32,
1738 row_bytes: usize,
1739 n_vocab: usize,
1740 final_max: usize,
1741 mask: Option<(&CudaSlice<u32>, usize)>,
1742 ) -> Result<(cudarc::driver::CudaGraph, Vec<crate::graph_update::FaMain>, usize),
1743 Box<dyn std::error::Error>> {
1744 let t0 = cache.pos + 1;
1745 let seg_end = self.fa_segment_end(e, t0, final_max);
1746 let bucket_max = seg_end;
1747 let snap = cache.snapshot(e)?;
1748 let pos_save = e.dtoh_i32_one(&gs.pos_d)?;
1749 let len_save: Vec<Option<i32>> = cache.kv.iter()
1750 .map(|k| k.as_ref().map(|kvl| e.dtoh_i32_one(&kvl.len_d).unwrap())).collect();
1751 let tok_save = e.dtoh_u32_one(&gs.token_d)?;
1752 let graph = {
1753 let GraphDecodeState { token_d, pos_d, .. } = gs;
1754 let token_d: &mut CudaSlice<u32> = token_d;
1755 let pos_d: &mut CudaSlice<i32> = pos_d;
1756 let cache_ref = &mut *cache;
1757 e.capture_graph(|e| {
1758 self.decode_step_dc_cap_masked(e, token_d, pos_d, embd_gpu, qt, row_bytes,
1759 cache_ref, n_vocab, bucket_max, mask)
1760 })?
1761 };
1762 gs.captures += 1;
1763 cache.rollback(e, &snap, 0)?;
1764 e.set_i32_one(&mut gs.pos_d, pos_save)?;
1765 for (il, ls) in len_save.iter().enumerate() {
1766 if let (Some(kvl), Some(v)) = (cache.kv[il].as_mut(), ls) {
1767 e.set_i32_one(&mut kvl.len_d, *v)?;
1768 }
1769 }
1770 e.set_u32_one(&mut gs.token_d, tok_save)?;
1771 let plan = crate::graph_update::fa_plan(&graph)?;
1772 if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
1773 eprintln!("[graph-census] segment t_kv {t0}..={seg_end} fa_plan mains: {}",
1774 plan.len());
1775 if let Ok(c) = crate::graph_update::node_census(&graph) {
1776 eprintln!("[graph-census] {c:?}");
1777 }
1778 }
1779 Ok((graph, plan, seg_end))
1780 }
1781
1782 /// Measurement door for `graph_session_recapture` (graph-allocfree-probe): the capture
1783 /// path timed WITHOUT the prompt prime. Same call the live step() makes at a
1784 /// kernel-class crossing.
1785 pub fn graph_session_recapture_pub(&self, e: &Engine, sess: &mut GraphSession)
1786 -> Result<(), Box<dyn std::error::Error>> {
1787 self.graph_session_recapture(e, sess)
1788 }
1789
1790 /// Session recapture at a kernel-class boundary (called by GraphSession::step).
1791 /// The mask node (when present) re-bakes the SAME stable buffer — contents carry over.
1792 pub(crate) fn graph_session_recapture(&self, e: &Engine, sess: &mut GraphSession)
1793 -> Result<(), Box<dyn std::error::Error>> {
1794 let mask = sess.mask_dev.take();
1795 let (graph, plan, seg_end) = self.graph_capture_segment_masked(
1796 e, &mut sess.cache, &mut sess.gs, &sess.embd_gpu,
1797 sess.qt, sess.row_bytes, sess.n_vocab, sess.bucket_max,
1798 mask.as_ref().map(|d| (d, sess.mask_words)))?;
1799 sess.mask_dev = mask;
1800 sess.graph = graph;
1801 sess.plan = plan;
1802 sess.seg_end = seg_end;
1803 Ok(())
1804 }
1805
1806 /// Shared capture tail: capture the FIRST kernel-class segment, build the session.
1807 #[allow(clippy::too_many_arguments)]
1808 fn graph_session_capture(
1809 &self,
1810 e: &Engine,
1811 mut cache: Cache,
1812 mut gs: GraphDecodeState,
1813 embd_gpu_owned: CudaSlice<u8>,
1814 max_new: usize,
1815 qt: i32,
1816 row_bytes: usize,
1817 n_vocab: usize,
1818 mask_dev: Option<CudaSlice<u32>>,
1819 mask_words: usize,
1820 ) -> Result<(GraphSession, u32), Box<dyn std::error::Error>> {
1821 let embd_gpu = embd_gpu_owned;
1822 let bucket_max = cache.pos + max_new + 1;
1823 let (graph, plan, seg_end) = self.graph_capture_segment_masked(
1824 e, &mut cache, &mut gs, &embd_gpu, qt, row_bytes, n_vocab, bucket_max,
1825 mask_dev.as_ref().map(|d| (d, mask_words)))?;
1826 let first = e.dtoh_u32_one(&gs.token_d)?;
1827 Ok((GraphSession {
1828 gs, cache, embd_gpu, graph, plan, bucket_max, seg_end, qt, row_bytes, n_vocab,
1829 mask_dev, mask_words,
1830 }, first))
1831 }
1832
1833 /// Device-counter full-attention decode (CUDA-GRAPH-PLAN Phase 2): clone of `full_attn_decode`
1834 /// using the `_dc` KV-append (write slot from `kvl.len_d`) + `_dc` fa_decode (t_kv from `kvl.len_d`
1835 /// after inc), and the resident device rope `pos_d`. Bit-identical to `full_attn_decode` (the
1836 /// `_dc` kernels reproduce the same math; fa_decode_dc with bucket_max==t_kv reproduces the same
1837 /// n_splits/per/combine). Advances `kvl.len`/`kvl.len_d`.
1838 pub(crate) fn full_attn_decode_dc(
1839 &self,
1840 e: &Engine,
1841 fa: &FullAttnLayer,
1842 h: &CudaSlice<f32>,
1843 pos_d: &CudaSlice<i32>,
1844 cache: &mut Cache,
1845 il: usize,
1846 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1847 // eager-mirror path: advance host counters and size n_splits from the live t_kv (bit-identical
1848 // to fa_decode). The capture path uses full_attn_decode_dc_cap (fixed bucket_max, no host
1849 // advance, full-buffer K/V view).
1850 self.full_attn_decode_dc_inner(e, fa, h, None, pos_d, cache, il, None)
1851 }
1852
1853 /// PRE-QUANTIZED-INPUT dc full-attn (device-counter path). See full_attn_decode_pre. BIT-IDENTICAL.
1854 pub(crate) fn full_attn_decode_dc_pre(
1855 &self,
1856 e: &Engine,
1857 fa: &FullAttnLayer,
1858 h: &CudaSlice<f32>,
1859 hq: &CudaSlice<i8>,
1860 hd: &CudaSlice<f32>,
1861 pos_d: &CudaSlice<i32>,
1862 cache: &mut Cache,
1863 il: usize,
1864 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1865 self.full_attn_decode_dc_inner(e, fa, h, Some((hq, hd)), pos_d, cache, il, None)
1866 }
1867
1868 /// PRE-QUANTIZED-INPUT CAPTURE dc full-attn (graph path, fixed bucket_max). BIT-IDENTICAL.
1869 pub(crate) fn full_attn_decode_dc_cap_pre(
1870 &self,
1871 e: &Engine,
1872 fa: &FullAttnLayer,
1873 h: &CudaSlice<f32>,
1874 hq: &CudaSlice<i8>,
1875 hd: &CudaSlice<f32>,
1876 pos_d: &CudaSlice<i32>,
1877 cache: &mut Cache,
1878 il: usize,
1879 bucket_max: usize,
1880 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1881 self.full_attn_decode_dc_inner(e, fa, h, Some((hq, hd)), pos_d, cache, il, Some(bucket_max))
1882 }
1883
1884 /// CAPTURE variant of `full_attn_decode_dc` (CUDA-GRAPH-PLAN Phase 3). `bucket_max` sizes the
1885 /// fa_decode_dc grid (n_splits) at capture time; the kernel reads the ACTUAL t_kv from the device
1886 /// counter `kvl.len_d`. Does NOT advance the host `kvl.len` (only the DEVICE counter via inc_seqlen,
1887 /// which is captured and replays each launch). Views the FULL K/V cache buffer so the kernel may
1888 /// safely read up to any t_kv within the bucket on replay. Bit-identical to eager when
1889 /// `bucket_max` yields the same n_splits as eager for the replayed t_kv (the bucket-key contract).
1890 pub(crate) fn full_attn_decode_dc_cap(
1891 &self,
1892 e: &Engine,
1893 fa: &FullAttnLayer,
1894 h: &CudaSlice<f32>,
1895 pos_d: &CudaSlice<i32>,
1896 cache: &mut Cache,
1897 il: usize,
1898 bucket_max: usize,
1899 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1900 self.full_attn_decode_dc_inner(e, fa, h, None, pos_d, cache, il, Some(bucket_max))
1901 }
1902
1903 fn full_attn_decode_dc_inner(
1904 &self,
1905 e: &Engine,
1906 fa: &FullAttnLayer,
1907 h: &CudaSlice<f32>,
1908 pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
1909 pos_d: &CudaSlice<i32>,
1910 cache: &mut Cache,
1911 il: usize,
1912 cap_bucket_max: Option<usize>,
1913 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1914 // step35 has no device-counter twin yet: the `_dc` family needs a windowed dc fa_decode
1915 // (SWA layers read a token-OFFSET view, which the dc kernels' len_d-derived t_kv cannot
1916 // express) plus a per-layer-n_head capture. Refuse loudly instead of silently running
1917 // the generic geometry. The eager arm (`step35_decode_attn`) is the supported decode.
1918 if self.cfg.step35.is_some() {
1919 return Err("step35 has no device-counter/graph decode arm (SWA needs an offset KV \
1920 view the dc kernels cannot express) — use the eager decode".into());
1921 }
1922 let cfg = &self.cfg;
1923 let n_head = cfg.n_head as usize;
1924 let n_head_kv = cfg.n_head_kv as usize;
1925 let head_dim = cfg.head_dim_k as usize;
1926 let eps = cfg.rms_eps;
1927 let scale = 1.0 / (head_dim as f32).sqrt();
1928
1929 let n_embd = cfg.n_embd as usize;
1930 // Q8 TRUNK-FUSION (2026-07-05): wq+wk+wv share input h — on the 35B every full-attn
1931 // projection is Q8_0, so ONE fused3 launch (block-offset split, out_f 8192/512/512)
1932 // replaces three launch-latency-class m=1 launches. BIT-IDENTICAL per (tensor,row) to
1933 // the three matmul_pre MMVQ dispatches (same kernel body). MEMRA_Q8_DUAL=0 rollback.
1934 let qkv_fused = |e: &Engine,
1935 hq: &CudaSlice<i8>,
1936 hd: &CudaSlice<f32>|
1937 -> Result<
1938 (CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>),
1939 Box<dyn std::error::Error>,
1940 > {
1941 if let Some((qf, k, v)) = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)? {
1942 return Ok((qf, k, v));
1943 }
1944 Ok((
1945 e.matmul_pre(&fa.wq, hq, hd, h, 1)?,
1946 e.matmul_pre(&fa.wk, hq, hd, h, 1)?,
1947 e.matmul_pre(&fa.wv, hq, hd, h, 1)?,
1948 ))
1949 };
1950 let (qf, mut k, v) =
1951 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
1952 match pre_q {
1953 Some((hq, hd)) => qkv_fused(e, hq, hd)?,
1954 None => {
1955 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
1956 qkv_fused(e, &hq, &hd)?
1957 }
1958 }
1959 } else {
1960 (
1961 e.matmul(&fa.wq, h, 1)?,
1962 e.matmul(&fa.wk, h, 1)?,
1963 e.matmul(&fa.wv, h, 1)?,
1964 )
1965 };
1966 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
1967 let gated = self.cfg.attn_out_gate();
1968 let (mut q, gate) = if gated {
1969 let mut q = e.uninit(n_head * head_dim)?;
1970 let mut gate = e.uninit(n_head * head_dim)?;
1971 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
1972 (q, Some(gate))
1973 } else {
1974 (qf, None)
1975 };
1976
1977 let mut qn = e.uninit(n_head * head_dim)?;
1978 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
1979 q = qn;
1980 let mut kn = e.uninit(n_head_kv * head_dim)?;
1981 e.rms_norm(
1982 &k,
1983 fa.k_norm.float_data(),
1984 &mut kn,
1985 head_dim,
1986 n_head_kv,
1987 eps,
1988 )?;
1989 k = kn;
1990 let rope_dims = cfg.rope_dim_count as usize;
1991 // rope pos from the resident device counter (no per-step host upload).
1992 e.rope_neox(
1993 &mut q,
1994 pos_d,
1995 head_dim,
1996 rope_dims,
1997 n_head,
1998 1,
1999 cfg.rope_freq_base,
2000 1.0,
2001 )?;
2002 e.rope_neox(
2003 &mut k,
2004 pos_d,
2005 head_dim,
2006 rope_dims,
2007 n_head_kv,
2008 1,
2009 cfg.rope_freq_base,
2010 1.0,
2011 )?;
2012
2013 let kvl = cache.kv[il].as_mut().unwrap();
2014 // (1) append at the device write slot kvl.len_d (== old len).
2015 e.append_kv_quantized_dc(
2016 &k,
2017 &v,
2018 &mut kvl.k,
2019 &mut kvl.v,
2020 &kvl.len_d,
2021 kvl.kv_dim_k,
2022 kvl.kv_dim_v,
2023 kvl.k_tok_bytes,
2024 kvl.v_tok_bytes,
2025 crate::Engine::kv_fp8_on(),
2026 )?;
2027 // (2) advance the device counter: kvl.len_d now holds new len == t_kv.
2028 e.inc_seqlen(&mut kvl.len_d)?;
2029 // n_splits sizing + K/V view extent:
2030 // - eager path (cap_bucket_max==None): advance host len; size from live t_kv == bit-identical
2031 // to fa_decode; view exactly t_kv*tok_bytes.
2032 // - capture path (Some(bucket_max)): DO NOT touch host len (replay advances only the device
2033 // counter); size n_splits from bucket_max; view the FULL cache buffer so any in-bucket t_kv
2034 // is in range on replay.
2035 let (bucket_max, k_view, v_view) = match cap_bucket_max {
2036 None => {
2037 kvl.len += 1;
2038 let t_kv = kvl.len;
2039 (
2040 t_kv,
2041 e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes),
2042 e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes),
2043 )
2044 }
2045 Some(bm) => (
2046 bm,
2047 e.view_u8(&kvl.k, kvl.k.len()),
2048 e.view_u8(&kvl.v, kvl.v.len()),
2049 ),
2050 };
2051 let (ktb, vtb) = (kvl.k_tok_bytes, kvl.v_tok_bytes);
2052 let mut attn = e.uninit(n_head * head_dim)?;
2053 if std::env::var("MEMRA_NOFA").is_ok() {
2054 return Err(
2055 "MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV cache; \
2056 unset MEMRA_NOFA to use fa_decode_dc"
2057 .into(),
2058 );
2059 }
2060 // (3) fa_decode reads t_kv from kvl.len_d; bucket_max yields the eager n_splits -> bit-identical.
2061 e.fa_decode_dc(
2062 &q,
2063 &k_view,
2064 &v_view,
2065 &mut attn,
2066 head_dim,
2067 n_head,
2068 n_head_kv,
2069 &kvl.len_d,
2070 bucket_max,
2071 scale,
2072 ktb,
2073 vtb,
2074 crate::Engine::kv_fp8_on(),
2075 )?;
2076
2077 let attn_g = match &gate {
2078 Some(gate) => {
2079 let mut gsig = e.uninit(n_head * head_dim)?;
2080 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2081 let mut ag = e.uninit(n_head * head_dim)?;
2082 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2083 ag
2084 }
2085 None => attn,
2086 };
2087 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2088 }
2089
2090 /// Greedy generation: prime with prompt tokens (decode them in sequence to build state),
2091 /// then generate `max_new` tokens. Returns the generated token ids. (Back-compat: greedy,
2092 /// no EOS/stop — used by the decode==prefill validation gate. New code uses `generate_with`.)
2093 pub fn generate(
2094 &self,
2095 e: &Engine,
2096 prompt: &[u32],
2097 max_new: usize,
2098 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
2099 let max_ctx = prompt.len() + max_new + 8;
2100 let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
2101 let mut last_logits = Vec::new();
2102 // prime: BATCHED cache prime (prime_cache — the prefill-throughput path, the measured #1
2103 // e2e gap: tokenwise primed at ~102/38 tok/s vs ~2000-5900 tok/s batched). Prompts below
2104 // PRIME_MIN_T, MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the
2105 // tokenwise loop. Frozen mixed residency would otherwise transiently stage the missing
2106 // expert bank through the GPU on every prompt replay.
2107 let t_prime = std::time::Instant::now();
2108 let batched_prime = prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
2109 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
2110 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
2111 if batched_prime {
2112 let (l, _h_seed, _hiddens) = self.prime_cache(e, prompt, &mut cache, 0)?;
2113 last_logits = l;
2114 } else {
2115 for &tok in prompt {
2116 last_logits = self.decode_step(e, tok, &mut cache)?;
2117 }
2118 }
2119 e.stream().synchronize()?;
2120 // Harness timing contract: prime wall time published for gen-only throughput math
2121 // (bench binaries read this right after the call; subtraction-from-total breaks down
2122 // when prime >> gen — measured ±80% error at 6k-token prompts).
2123 crate::PRIME_NANOS.store(
2124 t_prime.elapsed().as_nanos() as u64,
2125 std::sync::atomic::Ordering::Relaxed,
2126 );
2127 let mut out = Vec::with_capacity(max_new);
2128 if self.cfg.gemma4.is_some()
2129 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2130 // Graph serving probed FLAT vs this dc loop (2026-07-12, 1.7k N=2: 174.6/174.2 vs
2131 // 174.5/174.3) — the GRAPH-GATE's +2.5% is over the plain-eager loop, and the dc
2132 // arc already banked that; the gate (IDENTICAL at every ctx since the wkv
2133 // capture-arm fix) stays as the correctness harness.
2134 // DEVICE-COUNTER greedy loop (the dc arc): stream-identical to eager (DC-GATE).
2135 // E4B rides its own dc step (same trunk fns as its eager chain).
2136 let n_vocab = self.output.out_features();
2137 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2138 for kvl in cache.kv.iter_mut().flatten() {
2139 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2140 }
2141 let e4b = self.is_gemma4_e4b();
2142 // 26B/31B WHOLE-TOKEN GRAPH SERVING door (MEMRA_GEMMA_GRAPH=1): measured FLAT on
2143 // the 26B (jsonl 2026-07-12) but the 31B carries ~4% launch-gap share (HANDOVER
2144 // graph-arc note) and was never measured — the plain-short 1.00x cell probe.
2145 if !e4b && std::env::var("MEMRA_GEMMA_GRAPH").as_deref() == Ok("1") {
2146 let first = argmax(&last_logits) as u32;
2147 let (toks, _reason) = self.gemma4_generate_graph(
2148 e, cache.pos, first, &mut cache, max_new, &[], |_| true)?;
2149 out.extend(toks);
2150 return Ok(out);
2151 }
2152 let mut token_d = e.stream().clone_htod(&[argmax(&last_logits) as u32])?;
2153 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2154 // E4B GRAPH-EXEC-UPDATE SERVING: one capture at bucket=win, per-token fa
2155 // geometry retune, replay. The 2026-07-12 park ("flat 173.5, stream 64/64") did
2156 // NOT reproduce — the capture warmups are real self-feeding steps and the old
2157 // door dropped their 2 tokens (E4B-GRAPH-GATE 3/64). Snapshot/rollback (the 26B
2158 // graph-loop pattern) fixes the stream; the exec-update kills the bucket-split
2159 // tax (42 fa launches at 64 splits vs eager's ~ceil(t_kv/8)).
2160 // DEFAULT: budget-gated ON (2026-07-13 valid-window A/B: steady-state replay
2161 // beats eager but the one-time capture ~30ms crosses over near 200 tokens —
2162 // 128tok −1.3%, 400tok +0.9%). MEMRA_E4B_GRAPH=1 forces, =0 kills.
2163 let win = self.cfg.gemma4.as_ref().map(|g| g.sliding_window as usize).unwrap_or(0);
2164 let e4b_graph = match std::env::var("MEMRA_E4B_GRAPH").as_deref() {
2165 Ok("1") => true, Ok("0") => false, _ => max_new >= 256,
2166 };
2167 if e4b && cache.pos + max_new + 2 < win && e4b_graph {
2168 self.gemma4_e4b_graph_exec_loop(
2169 e, &mut cache, &mut token_d, &mut pos_d, embd_gpu, qt, rb, n_vocab, win,
2170 max_new, usize::MAX, |tok| { out.push(tok); None })?;
2171 return Ok(out);
2172 }
2173 for _ in 0..max_new {
2174 out.push(e.dtoh_u32(&token_d)?[0]);
2175 token_d = if e4b {
2176 self.gemma4_e4b_decode_step_dc(
2177 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
2178 )?
2179 } else {
2180 self.gemma4_decode_step_dc(
2181 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab, None,
2182 )?
2183 };
2184 }
2185 return Ok(out);
2186 }
2187 // QWEN DC-EAGER route (2026-07-15, MEMRA_QWEN_DC=0 seam — mirror of generate_with's
2188 // serving loop; see the note there. The graph route probed −11% first.)
2189 // step35 is EXCLUDED: this route calls `decode_step_dc`, whose full-attn arm refuses
2190 // step35 by design (SWA layers need a token-OFFSET KV view the dc kernels' len_d-derived
2191 // t_kv cannot express). Without this gate the door opens for any greedy model and the
2192 // refusal surfaces as a user-visible generate() error — the first PP-2 boot of
2193 // Step-3.7-Flash died exactly there, AFTER a clean load and an argmax MATCH.
2194 static QWEN_DC2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2195 let qwen_dc = *QWEN_DC2.get_or_init(||
2196 std::env::var("MEMRA_QWEN_DC").as_deref() != Ok("0"));
2197 if qwen_dc && max_new > 0 && self.cfg.step35.is_none()
2198 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2199 let n_vocab = self.output.out_features();
2200 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2201 for kvl in cache.kv.iter_mut().flatten() {
2202 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2203 }
2204 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2205 let mut token_d = e.stream().clone_htod(&[argmax(&last_logits) as u32])?;
2206 for _ in 0..max_new {
2207 out.push(e.dtoh_u32(&token_d)?[0]);
2208 token_d = self.decode_step_dc(e, &token_d, &mut pos_d, embd_gpu, qt, rb,
2209 &mut cache, n_vocab)?;
2210 }
2211 return Ok(out);
2212 }
2213 for _ in 0..max_new {
2214 let next = argmax(&last_logits) as u32;
2215 out.push(next);
2216 last_logits = self.decode_step(e, next, &mut cache)?;
2217 }
2218 Ok(out)
2219 }
2220
2221 /// E4B whole-token GRAPH-EXEC-UPDATE serving loop (shared by `generate` and
2222 /// `generate_with`): capture ONE self-feeding dcg step at bucket=`win`, then per token
2223 /// retune the fa nodes' split geometry to the live eager counts
2224 /// (`graph_update::fa_apply`) before replaying the instantiated exec.
2225 ///
2226 /// The capture's two warmup runs are REAL executions (self-feeding: they consume two
2227 /// tokens and advance KV/counters) — snapshot/rollback around the capture (the 26B
2228 /// graph-loop pattern) restores device+host state, or the stream drops those tokens
2229 /// (E4B-GRAPH-GATE 3/64 break, 2026-07-12). `emit` sees each token BEFORE its
2230 /// successor's replay; returning `Some(reason)` stops the loop. Caller owns the
2231 /// under-window gate (`cache.pos + budget + 2 < win`).
2232 #[allow(clippy::too_many_arguments)]
2233 fn gemma4_e4b_graph_exec_loop(
2234 &self, e: &Engine, cache: &mut Cache, token_d: &mut CudaSlice<u32>,
2235 pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>, qt: i32, rb: usize,
2236 n_vocab: usize, win: usize, budget: usize, ctx_cap: usize,
2237 mut emit: impl FnMut(u32) -> Option<StopReason>,
2238 ) -> Result<StopReason, Box<dyn std::error::Error>> {
2239 // BISECT ARM (MEMRA_E4B_DCG_EAGER=1): run the dcg step EAGERLY per token at the
2240 // exact live bucket — no capture/replay/exec-update. Separates "the dc-bucket path
2241 // diverges from dc-eager numerically" from "the replay/update mechanism is wrong".
2242 if let Ok(m) = std::env::var("MEMRA_E4B_DCG_EAGER") {
2243 // =1: exact live bucket per token; =2: the capture's fixed win bucket.
2244 let mut reason = StopReason::MaxNew;
2245 for _ in 0..budget {
2246 let tok = e.dtoh_u32_one(token_d)?;
2247 if let Some(r) = emit(tok) { reason = r; break; }
2248 if cache.pos >= ctx_cap { reason = StopReason::ContextFull; break; }
2249 let b = if m == "2" { win } else { cache.pos + 1 };
2250 self.gemma4_e4b_decode_step_dcg(e, token_d, pos_d, embd_gpu, qt, rb,
2251 cache, n_vocab, b)?;
2252 cache.pos += 1;
2253 for kvl in cache.kv.iter_mut().flatten() { kvl.len += 1; }
2254 }
2255 return Ok(reason);
2256 }
2257 // snapshot device+host state (the 2 capture-warmup runs must leave no residue).
2258 let snap = cache.snapshot(e)?;
2259 let pos_save = e.dtoh_i32_one(pos_d)?;
2260 let len_save: Vec<Option<i32>> = cache.kv.iter()
2261 .map(|k| k.as_ref().map(|kvl| e.dtoh_i32_one(&kvl.len_d).unwrap())).collect();
2262 let tok_save = e.dtoh_u32_one(token_d)?;
2263 let (graph, keeper) = e.capture_graph_retained(|e| {
2264 self.gemma4_e4b_decode_step_dcg(e, token_d, pos_d, embd_gpu, qt, rb,
2265 cache, n_vocab, win)
2266 })?;
2267 cache.rollback(e, &snap, 0)?;
2268 e.set_i32_one(pos_d, pos_save)?;
2269 for (il, ls) in len_save.iter().enumerate() {
2270 if let (Some(kvl), Some(v)) = (cache.kv[il].as_mut(), ls) {
2271 e.set_i32_one(&mut kvl.len_d, *v)?;
2272 }
2273 }
2274 e.set_u32_one(token_d, tok_save)?;
2275 let mut plan = crate::graph_update::fa_plan(&graph)?;
2276 if std::env::var("MEMRA_GRAPH_NODES_DUMP").as_deref() == Ok("1") {
2277 let nodes = crate::graph_update::kernel_nodes(&graph)?;
2278 let mut counts: std::collections::BTreeMap<String, (usize, (u32, u32, u32))> =
2279 std::collections::BTreeMap::new();
2280 for n in &nodes {
2281 counts.entry(n.name.clone())
2282 .or_insert((0, (n.params.gridDimX, n.params.gridDimY, n.params.gridDimZ)))
2283 .0 += 1;
2284 }
2285 eprintln!("[graph-nodes] {} kernel nodes, {} fa update units (bucket={win})",
2286 nodes.len(), plan.len());
2287 for (name, (c, grid)) in &counts {
2288 eprintln!("[graph-nodes] {c:4}x {name} grid={grid:?}");
2289 }
2290 }
2291 let mut reason = StopReason::MaxNew;
2292 let timing = std::env::var("MEMRA_E4B_GRAPH_TIMING").as_deref() == Ok("1");
2293 let (mut t_dtoh, mut t_apply, mut t_launch) =
2294 (std::time::Duration::ZERO, std::time::Duration::ZERO, std::time::Duration::ZERO);
2295 for _ in 0..budget {
2296 let t0 = std::time::Instant::now();
2297 let tok = e.dtoh_u32_one(token_d)?;
2298 let t1 = std::time::Instant::now();
2299 if let Some(r) = emit(tok) { reason = r; break; }
2300 if cache.pos >= ctx_cap { reason = StopReason::ContextFull; break; }
2301 // live t_kv AFTER this replay's in-graph append = pos + 1.
2302 crate::graph_update::fa_apply(&graph, &mut plan, cache.pos + 1,
2303 crate::fa_split_keys)?;
2304 let t2 = std::time::Instant::now();
2305 graph.launch()?;
2306 if timing {
2307 let t3 = std::time::Instant::now();
2308 t_dtoh += t1 - t0; t_apply += t2 - t1; t_launch += t3 - t2;
2309 }
2310 cache.pos += 1;
2311 for kvl in cache.kv.iter_mut().flatten() { kvl.len += 1; }
2312 }
2313 if timing {
2314 eprintln!("[e4b-graph timing] dtoh(sync-wait) {:?} apply {:?} launch {:?}",
2315 t_dtoh, t_apply, t_launch);
2316 }
2317 drop(keeper); // capture-retained transients must outlive every replay
2318 Ok(reason)
2319 }
2320
2321 /// The reusable serving generation API (BASE-3). Primes the prompt, then samples up to
2322 /// `params.max_new` tokens, stopping on EOS, any stop-token, or the context-length guard.
2323 /// Calls `on_token(id)` after each emitted token (for streaming; return `false` to stop early).
2324 /// Returns `GenOutput { tokens, stop_reason }`. Does NOT detokenize — the caller (which owns
2325 /// the tokenizer) handles text + stop-STRING matching on the detokenized tail.
2326 pub fn generate_with<F: FnMut(u32) -> bool>(
2327 &self,
2328 e: &Engine,
2329 prompt: &[u32],
2330 params: &GenParams,
2331 sampler: &mut crate::sampler::Sampler,
2332 mut on_token: F,
2333 ) -> Result<GenOutput, Box<dyn std::error::Error>> {
2334 // Context guard: prompt + generated must fit max_ctx (caller-supplied or model default).
2335 let ctx_cap = params.max_ctx.unwrap_or(prompt.len() + params.max_new + 8);
2336 if prompt.len() >= ctx_cap {
2337 return Ok(GenOutput {
2338 tokens: Vec::new(),
2339 stop_reason: StopReason::ContextFull,
2340 });
2341 }
2342 let room = ctx_cap - prompt.len();
2343 let budget = params.max_new.min(room);
2344
2345 let mut cache = Cache::new(e, &self.cfg, ctx_cap)?;
2346 let mut last_logits = Vec::new();
2347 // BATCHED PRIME (2026-07-06 fix — generate_with was still tokenwise! run-gen's "decode"
2348 // numbers folded a ~40-100 tok/s tokenwise prime into the rate) + PRIME_NANOS contract.
2349 // Frozen Hy3 CPU/GPU expert serving is the deliberate exception: its batched MoE path
2350 // bypasses the CPU tier and rereads the spilled expert bank.
2351 let t_prime = std::time::Instant::now();
2352 let batched = prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
2353 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
2354 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
2355 if batched {
2356 let (l, _h, _x) = self.prime_cache(e, prompt, &mut cache, 0)?;
2357 last_logits = l;
2358 for &tok in prompt {
2359 sampler.accept(tok);
2360 }
2361 } else {
2362 for &tok in prompt {
2363 last_logits = self.decode_step(e, tok, &mut cache)?;
2364 sampler.accept(tok);
2365 }
2366 }
2367 e.stream().synchronize()?;
2368 crate::PRIME_NANOS.store(
2369 t_prime.elapsed().as_nanos() as u64,
2370 std::sync::atomic::Ordering::Relaxed,
2371 );
2372 // MEMRA_PROFILE_GEN=2: profiler capture starts HERE — after the prime — so an
2373 // `nsys -c cudaProfilerApi` capture contains ONLY the decode loop (the run-spec
2374 // MEMRA_PROFILE_SPEC=2 pattern; =1 in run_gen brackets prime+decode).
2375 if std::env::var("MEMRA_PROFILE_GEN").as_deref() == Ok("2") {
2376 unsafe extern "C" {
2377 fn cudaProfilerStart() -> i32;
2378 }
2379 unsafe {
2380 cudaProfilerStart();
2381 }
2382 }
2383 let mut out = Vec::with_capacity(budget);
2384 let mut reason = StopReason::MaxNew;
2385 // gemma4 DEVICE-COUNTER greedy serving loop (the dc arc): token/pos/kv-lens live in
2386 // device counters, argmax on device — host sees 4B/token. Stream-identical to the
2387 // eager chain (DC-GATE). Penalties/temp fall through to the host-logits loop.
2388 if self.cfg.gemma4.is_some()
2389 && sampler.is_greedy() && sampler.penalty_last_n() == 0
2390 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2391 let n_vocab = self.output.out_features();
2392 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2393 for kvl in cache.kv.iter_mut().flatten() {
2394 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2395 }
2396 let first = crate::forward::argmax(&last_logits) as u32;
2397 let e4b = self.is_gemma4_e4b();
2398 let mut token_d = e.stream().clone_htod(&[first])?;
2399 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2400 // E4B GRAPH-EXEC-UPDATE serving door (under-window regime) — mirror of the
2401 // `generate` door incl the budget-gated default; run-gen/serving measure here.
2402 let win = self.cfg.gemma4.as_ref().map(|g| g.sliding_window as usize).unwrap_or(0);
2403 let e4b_graph = match std::env::var("MEMRA_E4B_GRAPH").as_deref() {
2404 Ok("1") => true, Ok("0") => false, _ => budget >= 256,
2405 };
2406 if e4b && cache.pos + budget + 2 < win && e4b_graph {
2407 let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
2408 let reason = self.gemma4_e4b_graph_exec_loop(
2409 e, &mut cache, &mut token_d, &mut pos_d, embd_gpu, qt, rb, n_vocab, win,
2410 budget, ctx_cap, |tok| {
2411 sampler_cell.accept(tok);
2412 out_cell.push(tok);
2413 if params.eos.contains(&tok) { return Some(StopReason::Eos); }
2414 if !on_token(tok) { return Some(StopReason::Callback); }
2415 None
2416 })?;
2417 return Ok(GenOutput { tokens: out, stop_reason: reason });
2418 }
2419 // 12B/31B WHOLE-TOKEN GRAPH door (MEMRA_GEMMA_GRAPH=1), mirrored from `generate`:
2420 // run-gen/serving measure THIS path, and the `generate` door never covered it —
2421 // the 2026-07-22 graph A/B read flat because the env engaged nothing here.
2422 if !e4b && std::env::var("MEMRA_GEMMA_GRAPH").as_deref() == Ok("1") {
2423 let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
2424 let eos = params.eos.clone();
2425 let (toks, greason) = self.gemma4_generate_graph(
2426 e, cache.pos, first, &mut cache, budget, &eos, |tok| {
2427 sampler_cell.accept(tok);
2428 out_cell.push(tok);
2429 on_token(tok)
2430 })?;
2431 let _ = toks;
2432 return Ok(GenOutput { tokens: out, stop_reason: greason });
2433 }
2434 let mut next = first;
2435 for _ in 0..budget {
2436 sampler.accept(next);
2437 out.push(next);
2438 if params.eos.contains(&next) {
2439 reason = StopReason::Eos;
2440 break;
2441 }
2442 if !on_token(next) {
2443 reason = StopReason::Callback;
2444 break;
2445 }
2446 if cache.pos >= ctx_cap {
2447 reason = StopReason::ContextFull;
2448 break;
2449 }
2450 token_d = if e4b {
2451 self.gemma4_e4b_decode_step_dc(
2452 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
2453 )?
2454 } else {
2455 self.gemma4_decode_step_dc(
2456 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab, None,
2457 )?
2458 };
2459 next = e.dtoh_u32(&token_d)?[0];
2460 }
2461 return Ok(GenOutput {
2462 tokens: out,
2463 stop_reason: reason,
2464 });
2465 }
2466 // QWEN DC-EAGER serving loop (2026-07-15, MEMRA_QWEN_DC=0 seam — the gemma dc-arc
2467 // pattern): the eager tail dtoh'd the FULL VOCAB logits + host-argmax'd every
2468 // token (the duty map's 10.3%-of-wall gap at 13% DRAM duty). decode_step_dc keeps
2469 // the token id + argmax device-resident — 4B/token host traffic, same tuned eager
2470 // kernels. Greedy + no-penalty only (sampling needs host logits).
2471 // (The CUDA-graph route was probed first and read −11%: the replay's dc-fa family
2472 // + capture rungs lag the tuned eager lanes; jsonl 2026-07-15.)
2473 // step35 is EXCLUDED here for the same reason as the `generate` mirror above: every route
2474 // inside this door (`decode_step_dc` and the `graph_decode_loop` capture) reaches
2475 // `full_attn_decode_dc_inner`, which refuses step35 because its SWA layers read a
2476 // token-OFFSET KV view the dc kernels cannot express. step35 takes the host-logits eager
2477 // loop at the bottom of this function (`decode_step` -> `step35_decode_attn`), which is
2478 // the supported decode for this arch. Removing this gate requires a windowed dc fa_decode
2479 // plus a per-layer-n_head capture, not a flag.
2480 static QWEN_DC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2481 let qwen_dc = *QWEN_DC.get_or_init(||
2482 std::env::var("MEMRA_QWEN_DC").as_deref() != Ok("0"));
2483 if qwen_dc && sampler.is_greedy() && sampler.penalty_last_n() == 0 && budget > 0
2484 && self.cfg.step35.is_none()
2485 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2486 let n_vocab = self.output.out_features();
2487 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2488 for kvl in cache.kv.iter_mut().flatten() {
2489 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2490 }
2491 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2492 let mut token_d = e.stream().clone_htod(
2493 &[crate::forward::argmax(&last_logits) as u32])?;
2494 // HYBRID GRAPH DOOR (round 35): graph_decode_loop over the batched-prime
2495 // cache — the E4B graph-exec door's hybrid mirror. Counters (pos_d/token_d/
2496 // len_d) synced above; event tracking is engine-default-OFF so capture over
2497 // these buffers is legal. PROMOTED default-ON at budget >= 256 (the E4B
2498 // door's amortization rule): official-shape A/B interleaved x5 = eager 190.3
2499 // -> graph 220.7 tok/s (+16.0%, 5/5, spread ±0.1); 128-tok stream IDENTICAL;
2500 // graph-decode-gate 256 steps x 16 buckets BIT-IDENTICAL. This REFUTES the
2501 // 2026-07-15 "-11%" qwen-graph verdict — it predated the exec-update rework
2502 // and the 07-26 FA family (stale-verdict law, round 35). =0 reverts.
2503 // Default ON at budget >= 256 on BOTH arches (unified-merge resolution,
2504 // 2026-07-30): main shipped this door budget-keyed on sm_120a (52222ddd,
2505 // E4B graph door) and every 5090 board row since measured with it; the H100
2506 // lane measured +16% x5. The branch-era arch-gate (79395a3e) cited the
2507 // stale 2026-07-15 "-11%" verdict, which predates main's promotion — the
2508 // rig-divergence law protects main's SHIPPED default, so the gate came off.
2509 // MEMRA_GEN_GRAPH=1 opts in anywhere; =0 reverts anywhere.
2510 //
2511 // KEY LOWERED 256 -> 48 (q27 deep dive, 2026-08-05, pro6000wk-runpod-community).
2512 // The 256 key was set by the E4B amortization rule, never by a measured crossover,
2513 // so every <=128-token generation — including the whole published board, which runs
2514 // --max-tokens 128 — was silently EAGER. Swept the actual crossover on TWO models
2515 // (the key is a cross-model default, so one artifact is not enough), interleaved
2516 // arms with the order alternated per rep, N=3, all runs argmax MATCH:
2517 // Qwen3.6-27B-Q8_0 : n=16 -7.47% | n=32 -1.35% | n=48 +0.90% | n=64 +1.93%
2518 // n=128 +3.80% | n=512 +5.50%
2519 // Qwen3.6-27B-NVFP4-MTP: n=16 -15.27% | n=32 +0.22% | n=48 +3.45%
2520 // n=64 +5.09% | n=128 +7.72%
2521 // Both models: clearly negative at 16, no reliable gain at 32, positive from 48 up,
2522 // monotone in budget from 48 on. 48 is the first budget where BOTH are positive, so
2523 // it is the key — the capture cost needs ~32 steps to amortize, not ~256. The n=32
2524 // nvfp4 cell is NOISY, not flat (graph arm 79.02/78.91/77.09, spread 1.93 vs an
2525 // eager spread of 0.04): it is not evidence of a win, and it is why the key sits at
2526 // 48 rather than 32. Exactness at the new key:
2527 // graph-decode-gate 256 steps BIT-IDENTICAL (buckets=16, captures=2),
2528 // graph-session-gate 96 tokens PASS, kernel-check ALL GREEN, run-spec K=1..8
2529 // self-consistency PASS. Board caveat: community board, RELATIVE deltas only.
2530 //
2531 // SM-GATED (5090-arbiter gate, 2026-08-05, research/q27-deepdive-20260805/local5090/):
2532 // the 48 key does NOT transfer to the 82-SM local rig. Same A/B protocol there
2533 // (tg128 d512, N=3 interleaved, order alternated, warmup discarded): q27-NVFP4-MTP
2534 // graph arm at n=128 = -1.61% (eager 45.86 / graph 45.12 median, 3/3 pairs lose),
2535 // and the crossover sweep stays negative through n=256 (-1.07%) and n=512 (-0.59%)
2536 // — on few-SM silicon the replay's fixed kernel forms lag the tuned eager lanes and
2537 // the launch-gap tax the graph amortizes is proportionally smaller. Key on SM count
2538 // (the fa_split_keys big_rig pattern, lib.rs fa_sm_count), threshold 180: the 48
2539 // crossover is MEASURED only at 188 SM (PRO 6000) and refuted at 82 SM; the 132-SM
2540 // H100 board and the 170-SM desktop 5090 are UNMEASURED at sub-256 budgets, so they
2541 // keep the shipped 256 key their board rows were measured with (rig-divergence +
2542 // stale-verdict laws). Widening the gate below 180 requires an on-box crossover
2543 // sweep on that silicon, not an inference from this comment.
2544 let big_rig = e.sm_count() >= 180;
2545 let gen_graph = match std::env::var("MEMRA_GEN_GRAPH").as_deref() {
2546 Ok("1") => true,
2547 Ok("0") => false,
2548 _ => budget >= if big_rig { 48 } else { 256 },
2549 };
2550 // SLRU expert cache is capture-ILLEGAL: a cache miss drains/H2Ds on the compute
2551 // stream mid-decode, which CUDA forbids while capturing (Ornith-35B Q4_K_M on the
2552 // 24GB rig died with CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED, 2026-08-01 — any MoE
2553 // model whose experts overflow the residency budget hit this at budget >= 256).
2554 // The door only opens with every MoE layer's experts device-resident; =1 cannot
2555 // legalize a capture, so this closes the forced door too.
2556 let moe_resident = self.layers.iter().all(|l| match &l.ffn {
2557 crate::hybrid::Ffn::Moe(m) => m.dev_exps.is_some(),
2558 _ => true,
2559 });
2560 if gen_graph && !moe_resident {
2561 static NOTICE: std::sync::Once = std::sync::Once::new();
2562 NOTICE.call_once(|| eprintln!(
2563 "[gen-graph] door CLOSED: MoE experts on the SLRU cache path \
2564 (capture-illegal) — eager decode"
2565 ));
2566 }
2567 if gen_graph && moe_resident && budget > 0 {
2568 let head_dim = self.cfg.head_dim_k as usize;
2569 let mut gs = GraphDecodeState::new(e)?;
2570 gs.pos_d = pos_d;
2571 gs.token_d = token_d;
2572 let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
2573 let reason = self.graph_decode_loop(
2574 e, &mut gs, &mut cache, embd_gpu, qt, rb, head_dim, budget, |tok| {
2575 sampler_cell.accept(tok);
2576 out_cell.push(tok);
2577 if params.eos.contains(&tok) { return Some(StopReason::Eos); }
2578 if !on_token(tok) { return Some(StopReason::Callback); }
2579 None
2580 })?;
2581 return Ok(GenOutput { tokens: out, stop_reason: reason });
2582 }
2583 let mut next = e.dtoh_u32(&token_d)?[0];
2584 for _ in 0..budget {
2585 sampler.accept(next);
2586 out.push(next);
2587 if params.eos.contains(&next) { reason = StopReason::Eos; break; }
2588 if !on_token(next) { reason = StopReason::Callback; break; }
2589 if cache.pos >= ctx_cap { reason = StopReason::ContextFull; break; }
2590 token_d = self.decode_step_dc(e, &token_d, &mut pos_d, embd_gpu, qt, rb,
2591 &mut cache, n_vocab)?;
2592 next = e.dtoh_u32(&token_d)?[0];
2593 }
2594 return Ok(GenOutput { tokens: out, stop_reason: reason });
2595 }
2596 for _ in 0..budget {
2597 let next = sampler.sample(&last_logits);
2598 sampler.accept(next);
2599 out.push(next);
2600 if params.eos.contains(&next) {
2601 reason = StopReason::Eos;
2602 break;
2603 }
2604 if !on_token(next) {
2605 reason = StopReason::Callback;
2606 break;
2607 }
2608 if cache.pos >= ctx_cap {
2609 reason = StopReason::ContextFull;
2610 break;
2611 }
2612 last_logits = self.decode_step(e, next, &mut cache)?;
2613 }
2614 Ok(GenOutput {
2615 tokens: out,
2616 stop_reason: reason,
2617 })
2618 }
2619
2620 /// Full-attention decode: project q/gate/k/v for the new token, QK-norm, RoPE at pos,
2621 /// append k,v to the layer KV cache, attend over the full [0..=pos] context.
2622 pub(crate) fn full_attn_decode(
2623 &self,
2624 e: &Engine,
2625 fa: &FullAttnLayer,
2626 h: &CudaSlice<f32>,
2627 pos_d: &CudaSlice<i32>,
2628 pos: usize,
2629 cache: &mut Cache,
2630 il: usize,
2631 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2632 self.full_attn_decode_pre(e, fa, h, None, pos_d, pos, cache, il)
2633 }
2634
2635 /// PRE-QUANTIZED-INPUT eager full-attn (attn-input NORM-FUSION lever): caller passes the
2636 /// attn-normed activation already q8_1 `(hq,hd)` (rms_norm_q8_1) -> skips internal quantize_q8_1.
2637 /// `None` = quantize h here (the spec / non-fused path). BIT-IDENTICAL.
2638 pub(crate) fn full_attn_decode_pre(
2639 &self,
2640 e: &Engine,
2641 fa: &FullAttnLayer,
2642 h: &CudaSlice<f32>,
2643 pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2644 pos_d: &CudaSlice<i32>,
2645 pos: usize,
2646 cache: &mut Cache,
2647 il: usize,
2648 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2649 if self.cfg.step35.is_some() {
2650 return self.step35_decode_attn(e, fa, il, h, pre_q, pos_d, cache);
2651 }
2652 let cfg = &self.cfg;
2653 let n_head = cfg.n_head as usize;
2654 let n_head_kv = cfg.n_head_kv as usize;
2655 let head_dim = cfg.head_dim_k as usize;
2656 let eps = cfg.rms_eps;
2657 let scale = 1.0 / (head_dim as f32).sqrt();
2658
2659 // LATENCY-HIDING (MEMRA_KV_PREFETCH=1): warm this layer's KV stream into L2 while the
2660 // q/k/v projections run ahead of the fa (fa is latency-bound; its lines land warm).
2661 // Value-free scheduling — no numeric config change.
2662 static KV_PF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2663 if *KV_PF.get_or_init(|| std::env::var("MEMRA_KV_PREFETCH").as_deref() == Ok("1")) {
2664 let kvl = cache.kv[il].as_ref().unwrap();
2665 let t_kv = kvl.len + 1;
2666 e.prefetch_l2(&kvl.k, t_kv * kvl.k_tok_bytes)?;
2667 e.prefetch_l2(&kvl.v, t_kv * kvl.v_tok_bytes)?;
2668 }
2669
2670 // wq|wk|wv all take the same input `h` (in_f = n_embd) — quantize q8_1 ONCE, feed all three.
2671 // Q8 TRUNK-FUSION: on Q8_0 trunks (35B) the three fold into ONE fused3 launch (same MMVQ
2672 // body per (tensor,row) — bit-identical; see full_attn_decode_dc_inner). MEMRA_Q8_DUAL=0 off.
2673 let n_embd = cfg.n_embd as usize;
2674 let qkv_fused = |e: &Engine,
2675 hq: &CudaSlice<i8>,
2676 hd: &CudaSlice<f32>|
2677 -> Result<
2678 (CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>),
2679 Box<dyn std::error::Error>,
2680 > {
2681 if let Some((qf, k, v)) = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)? {
2682 return Ok((qf, k, v));
2683 }
2684 Ok((
2685 e.matmul_pre(&fa.wq, hq, hd, h, 1)?,
2686 e.matmul_pre(&fa.wk, hq, hd, h, 1)?,
2687 e.matmul_pre(&fa.wv, hq, hd, h, 1)?,
2688 ))
2689 };
2690 let (qf, mut k, v) =
2691 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
2692 match pre_q {
2693 Some((hq, hd)) => qkv_fused(e, hq, hd)?,
2694 None => {
2695 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
2696 qkv_fused(e, &hq, &hd)?
2697 }
2698 }
2699 } else {
2700 (
2701 e.matmul(&fa.wq, h, 1)?,
2702 e.matmul(&fa.wk, h, 1)?,
2703 e.matmul(&fa.wv, h, 1)?,
2704 )
2705 };
2706 // q|gate fused: [2*head_dim per head]. Split on-device (no dtoh/host-loop/htod).
2707 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2708 let gated = self.cfg.attn_out_gate();
2709 let (mut q, gate) = if gated {
2710 let mut q = e.uninit(n_head * head_dim)?;
2711 let mut gate = e.uninit(n_head * head_dim)?;
2712 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
2713 (q, Some(gate))
2714 } else {
2715 (qf, None)
2716 };
2717
2718 // QK-norm + RoPE at position `pos`
2719 let mut qn = e.uninit(n_head * head_dim)?;
2720 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
2721 q = qn;
2722 let mut kn = e.uninit(n_head_kv * head_dim)?;
2723 e.rms_norm(
2724 &k,
2725 fa.k_norm.float_data(),
2726 &mut kn,
2727 head_dim,
2728 n_head_kv,
2729 eps,
2730 )?;
2731 k = kn;
2732 let rope_dims = cfg.rope_dim_count as usize;
2733 e.rope_neox(
2734 &mut q,
2735 pos_d,
2736 head_dim,
2737 rope_dims,
2738 n_head,
2739 1,
2740 cfg.rope_freq_base,
2741 1.0,
2742 )?;
2743 e.rope_neox(
2744 &mut k,
2745 pos_d,
2746 head_dim,
2747 rope_dims,
2748 n_head_kv,
2749 1,
2750 cfg.rope_freq_base,
2751 1.0,
2752 )?;
2753
2754 // append k,v into the RESIDENT GPU QUANTIZED KV cache at the current position (q8_0 K /
2755 // q5_1 V, on-device append-quantize kernel; no host round-trip). KVQUANT-PLAN §C/E2.
2756 let kvl = cache.kv[il].as_mut().unwrap();
2757 e.append_kv_quantized(
2758 &k,
2759 &v,
2760 &mut kvl.k,
2761 &mut kvl.v,
2762 kvl.len,
2763 kvl.kv_dim_k,
2764 kvl.kv_dim_v,
2765 kvl.k_tok_bytes,
2766 kvl.v_tok_bytes,
2767 crate::Engine::kv_fp8_on(),
2768 )?;
2769 kvl.len += 1;
2770 let t_kv = kvl.len;
2771
2772 // attend: q[hd,nh,1] over the resident byte K/V (view first t_kv*tok_bytes BYTES).
2773 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
2774 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
2775 let (ktb, vtb) = (kvl.k_tok_bytes, kvl.v_tok_bytes);
2776 let mut attn = e.uninit(n_head * head_dim)?;
2777 if std::env::var("MEMRA_NOFA").is_ok() {
2778 return Err(
2779 "MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV cache; \
2780 unset MEMRA_NOFA to use fa_decode"
2781 .into(),
2782 );
2783 }
2784 e.fa_decode_kvmod(
2785 &q,
2786 &k_view,
2787 &v_view,
2788 &mut attn,
2789 head_dim,
2790 n_head,
2791 n_head_kv,
2792 t_kv,
2793 scale,
2794 ktb,
2795 vtb,
2796 crate::Engine::kv_fp8_on(),
2797 )?;
2798 let _ = pos;
2799
2800 // output gate: attn * sigmoid(gate), then o-proj
2801 let attn_g = match &gate {
2802 Some(gate) => {
2803 let mut gsig = e.uninit(n_head * head_dim)?;
2804 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2805 let mut ag = e.uninit(n_head * head_dim)?;
2806 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2807 ag
2808 }
2809 None => attn,
2810 };
2811 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2812 }
2813
2814 /// BATCHED full-attention decode over `m` independent streams (one token each).
2815 ///
2816 /// Generic m-band primitive, not lockstep-specific: any caller holding `m` streams at the
2817 /// same layer (multi-stream decode, a continuous-batching serve loop) can use it. The split
2818 /// follows what the hardware cares about — WEIGHT-BOUND work runs once at `m` because all
2819 /// streams share the same projection weights (one weight read serves `m` tokens instead of
2820 /// `m` reads), while KV-BOUND work stays per stream because each stream owns its own cache.
2821 ///
2822 /// Bit-identity with the per-stream path holds by construction: `quantize_q8_1` and
2823 /// `rms_norm` are per-row, `rope_neox` takes a per-token position vector, the fused3/matmul
2824 /// m-band kernels are the same ones spec verify is gated on, and attention itself is
2825 /// untouched per stream.
2826 ///
2827 /// `xcat` is `[m, n_embd]` normed activations; `pos_cat` is the `m` rope positions;
2828 /// returns `[m, n_embd]` attention outputs.
2829 #[allow(clippy::too_many_arguments)]
2830 pub(crate) fn full_attn_decode_batched(
2831 &self,
2832 e: &Engine,
2833 fa: &FullAttnLayer,
2834 xcat: &CudaSlice<f32>,
2835 m: usize,
2836 pos_cat: &CudaSlice<i32>,
2837 caches: &mut [Cache],
2838 il: usize,
2839 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2840 if self.cfg.step35.is_some() {
2841 return Err("step35 has no batched (m-stream) decode mixer — per-layer n_head, \
2842 partial rope and the SWA offset view need a step35 twin".into());
2843 }
2844 let cfg = &self.cfg;
2845 let n_head = cfg.n_head as usize;
2846 let n_head_kv = cfg.n_head_kv as usize;
2847 let head_dim = cfg.head_dim_k as usize;
2848 let n_embd = cfg.n_embd as usize;
2849 let eps = cfg.rms_eps;
2850 let scale = 1.0 / (head_dim as f32).sqrt();
2851 let q_row = n_head * head_dim;
2852 let kv_row = n_head_kv * head_dim;
2853
2854 // --- weight-bound: one quantize + one q/k/v projection for all m streams ---
2855 let (hq, hd) = e.quantize_q8_1(xcat, m, n_embd)?;
2856 let use_q8 =
2857 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
2858 let (qf, mut k, v) = if use_q8 {
2859 match e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, &hq, &hd, m)? {
2860 Some(trio) => trio,
2861 None => (
2862 e.matmul_pre(&fa.wq, &hq, &hd, xcat, m)?,
2863 e.matmul_pre(&fa.wk, &hq, &hd, xcat, m)?,
2864 e.matmul_pre(&fa.wv, &hq, &hd, xcat, m)?,
2865 ),
2866 }
2867 } else {
2868 (
2869 e.matmul(&fa.wq, xcat, m)?,
2870 e.matmul(&fa.wk, xcat, m)?,
2871 e.matmul(&fa.wv, xcat, m)?,
2872 )
2873 };
2874
2875 // --- elementwise: batched by treating the m streams as extra rows/tokens ---
2876 let gated = cfg.attn_out_gate();
2877 let (mut q, gate) = if gated {
2878 let mut q = e.uninit(m * q_row)?;
2879 let mut gate = e.uninit(m * q_row)?;
2880 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, m)?;
2881 (q, Some(gate))
2882 } else {
2883 (qf, None)
2884 };
2885 let mut qn = e.uninit(m * q_row)?;
2886 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head * m, eps)?;
2887 q = qn;
2888 let mut kn = e.uninit(m * kv_row)?;
2889 e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, n_head_kv * m, eps)?;
2890 k = kn;
2891 let rope_dims = cfg.rope_dim_count as usize;
2892 e.rope_neox(&mut q, pos_cat, head_dim, rope_dims, n_head, m, cfg.rope_freq_base, 1.0)?;
2893 e.rope_neox(&mut k, pos_cat, head_dim, rope_dims, n_head_kv, m, cfg.rope_freq_base, 1.0)?;
2894
2895 // --- KV-bound: each stream appends to and attends over its own cache ---
2896 let mut attn_cat = e.uninit(m * q_row)?;
2897 let mut q_s = e.uninit(q_row)?;
2898 let mut k_s = e.uninit(kv_row)?;
2899 let mut v_s = e.uninit(kv_row)?;
2900 for (s, cache) in caches.iter_mut().enumerate().take(m) {
2901 e.copy_view_into(&mut k_s, 0, &k.slice(s * kv_row..(s + 1) * kv_row), kv_row)?;
2902 e.copy_view_into(&mut v_s, 0, &v.slice(s * kv_row..(s + 1) * kv_row), kv_row)?;
2903 e.copy_view_into(&mut q_s, 0, &q.slice(s * q_row..(s + 1) * q_row), q_row)?;
2904 let kvl = cache.kv[il].as_mut().unwrap();
2905 e.append_kv_quantized(
2906 &k_s,
2907 &v_s,
2908 &mut kvl.k,
2909 &mut kvl.v,
2910 kvl.len,
2911 kvl.kv_dim_k,
2912 kvl.kv_dim_v,
2913 kvl.k_tok_bytes,
2914 kvl.v_tok_bytes,
2915 crate::Engine::kv_fp8_on(),
2916 )?;
2917 kvl.len += 1;
2918 let t_kv = kvl.len;
2919 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
2920 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
2921 let mut attn = e.uninit(q_row)?;
2922 e.fa_decode_kvmod(
2923 &q_s,
2924 &k_view,
2925 &v_view,
2926 &mut attn,
2927 head_dim,
2928 n_head,
2929 n_head_kv,
2930 t_kv,
2931 scale,
2932 kvl.k_tok_bytes,
2933 kvl.v_tok_bytes,
2934 crate::Engine::kv_fp8_on(),
2935 )?;
2936 e.copy_into(&mut attn_cat, s * q_row, &attn, q_row)?;
2937 }
2938
2939 // --- weight-bound again: gate epilogue + one output projection for all m streams ---
2940 let attn_g = match &gate {
2941 Some(gate) => {
2942 let mut gsig = e.uninit(m * q_row)?;
2943 e.sigmoid(gate, &mut gsig, m * q_row)?;
2944 let mut ag = e.uninit(m * q_row)?;
2945 e.mul(&attn_cat, &gsig, &mut ag, m * q_row)?;
2946 ag
2947 }
2948 None => attn_cat,
2949 };
2950 e.matmul(&fa.wo, &attn_g, m)
2951 }
2952
2953 /// Linear-attention decode: conv with ring-buffer state, GDN scan carrying SSM state.
2954 pub fn linear_attn_decode(
2955 &self,
2956 e: &Engine,
2957 la: &LinearAttnLayer,
2958 h: &CudaSlice<f32>,
2959 cache: &mut Cache,
2960 il: usize,
2961 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2962 self.linear_attn_decode_inner(e, la, h, None, cache, il, false)
2963 }
2964
2965 /// PRE-QUANTIZED-INPUT variant (DECODE attn-input NORM-FUSION lever): the caller passes the
2966 /// post-attn-norm activation ALREADY q8_1-quantized `(hq,hd)` (produced by rms_norm_q8_1, fusing
2967 /// the attn_norm + the mixer's internal quantize_q8_1). Skips the internal quantize. Caller
2968 /// GUARANTEES the projections are q8_1-fast. `persistent` selects the capture-safe state plumbing.
2969 /// BIT-IDENTICAL to linear_attn_decode(h) when (hq,hd)==quantize_q8_1(rms_norm(x)*w).
2970 pub fn linear_attn_decode_pre(
2971 &self,
2972 e: &Engine,
2973 la: &LinearAttnLayer,
2974 h: &CudaSlice<f32>,
2975 hq: &CudaSlice<i8>,
2976 hd: &CudaSlice<f32>,
2977 cache: &mut Cache,
2978 il: usize,
2979 persistent: bool,
2980 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2981 self.linear_attn_decode_inner(e, la, h, Some((hq, hd)), cache, il, persistent)
2982 }
2983
2984 /// CAPTURE variant of `linear_attn_decode` (CUDA-GRAPH-PLAN Phase 3). The GDN scan needs distinct
2985 /// in/out SSM-state buffers; the eager path SWAPS a fresh scratch into `rl.ssm_state` (new pointer
2986 /// each step), which is a CAPTURE HAZARD — the graph bakes capture-time pointers and never re-runs
2987 /// the host swap, so replay would read a stale state buffer. Here we instead COPY the scratch back
2988 /// into the STABLE `rl.ssm_state` buffer (memcpy_dtod, captured, same pointers every replay). Math
2989 /// is identical; only the buffer plumbing differs. `conv_state` is already mutated in place (no
2990 /// pointer change) so it is capture-safe as-is.
2991 pub(crate) fn linear_attn_decode_cap(
2992 &self,
2993 e: &Engine,
2994 la: &LinearAttnLayer,
2995 h: &CudaSlice<f32>,
2996 cache: &mut Cache,
2997 il: usize,
2998 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2999 self.linear_attn_decode_inner(e, la, h, None, cache, il, true)
3000 }
3001
3002 fn linear_attn_decode_inner(
3003 &self,
3004 e: &Engine,
3005 la: &LinearAttnLayer,
3006 h: &CudaSlice<f32>,
3007 pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
3008 cache: &mut Cache,
3009 il: usize,
3010 persistent_state: bool,
3011 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3012 let cfg = &self.cfg;
3013 let ssm = cfg.ssm.as_ref().unwrap();
3014 let d_state = ssm.state_size as usize;
3015 let num_k = ssm.group_count as usize;
3016 let num_v = ssm.time_step_rank as usize;
3017 let d_conv = ssm.conv_kernel as usize;
3018 let head_k = d_state;
3019 let key_dim = head_k * num_k;
3020 let value_dim = d_state * num_v;
3021 let conv_dim = key_dim * 2 + value_dim;
3022 let eps = cfg.rms_eps;
3023 let scale = 1.0 / (d_state as f32).sqrt();
3024
3025 // projections (T=1): wqkv, wqkv_gate, ssm_beta, ssm_alpha ALL take input `h` (in_f = n_embd)
3026 // -> quantize q8_1 ONCE, feed all four (was 4x redundant quantize_q8_1 of the same row).
3027 let n_embd = cfg.n_embd as usize;
3028 let all_fast = e.uses_q8_1_fast(&la.wqkv)
3029 && e.uses_q8_1_fast(&la.wqkv_gate)
3030 && e.uses_q8_1_fast(&la.ssm_beta)
3031 && e.uses_q8_1_fast(&la.ssm_alpha);
3032 // beta+alpha DUAL fuse (2026-07-05): ssm_beta and ssm_alpha are the same tiny shape
3033 // ([n_embd -> num_v=32]) — out_f=32 launches are pure launch latency (15-16us each,
3034 // HANDOVER b4-headroom note). The existing dual mr2 kernel (FFN gate+up) folds them into
3035 // ONE launch. Bit-identical per row: same MMVQ warp-per-row body, blockIdx.y picks the
3036 // weight; the separable macro-scale multiply is the same single f32 mul as matmul_pre's
3037 // in-kernel scale. Falls back to two matmul_pre when ineligible (Float layers 1/2/4 etc).
3038 let beta_alpha =
3039 |e: &Engine,
3040 hq: &CudaSlice<i8>,
3041 hd: &CudaSlice<f32>|
3042 -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3043 if let Some(((mut b, bs), (mut a, as_))) =
3044 e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, hq, hd, 1)?
3045 {
3046 if bs != 1.0 {
3047 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
3048 }
3049 if as_ != 1.0 {
3050 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
3051 }
3052 return Ok((b, a));
3053 }
3054 // Q8_0 twin of the NVFP4 dual (9B GGUFs store ssm_beta/alpha as Q8_0 on most layers):
3055 // one fused2 launch, bit-identical per row, no macro-scale (q8_0 scale==1.0).
3056 if let Some((b, a)) = e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, hq, hd)? {
3057 return Ok((b, a));
3058 }
3059 Ok((
3060 e.matmul_pre(&la.ssm_beta, hq, hd, h, 1)?,
3061 e.matmul_pre(&la.ssm_alpha, hq, hd, h, 1)?,
3062 ))
3063 };
3064 // Q8 TRUNK-FUSION (2026-07-05): wqkv+wqkv_gate share (hq,hd) and in_f — on the 35B both
3065 // are Q8_0 (out_f 8192/4096), so ONE fused2 launch replaces the two biggest
3066 // launch-latency-class m=1 launches of every linear layer. BIT-IDENTICAL per (tensor,row)
3067 // (same MMVQ body, block-offset split). Falls back per-tensor when ineligible.
3068 let qkv_pair =
3069 |e: &Engine,
3070 hq: &CudaSlice<i8>,
3071 hd: &CudaSlice<f32>|
3072 -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3073 if let Some((qkv, z)) = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, hq, hd)? {
3074 return Ok((qkv, z));
3075 }
3076 Ok((
3077 e.matmul_pre(&la.wqkv, hq, hd, h, 1)?,
3078 e.matmul_pre(&la.wqkv_gate, hq, hd, h, 1)?,
3079 ))
3080 };
3081 let (qkv_mixed, z, beta_raw, alpha) = if all_fast {
3082 // attn-input NORM-FUSION: use the caller's pre-quantized (hq,hd) when provided (the
3083 // attn_norm already emitted q8_1 via rms_norm_q8_1), else quantize h here. Bit-identical.
3084 match pre_q {
3085 Some((hq, hd)) => {
3086 let (b, a) = beta_alpha(e, hq, hd)?;
3087 let (qkv, z) = qkv_pair(e, hq, hd)?;
3088 (qkv, z, b, a)
3089 }
3090 None => {
3091 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
3092 let (b, a) = beta_alpha(e, &hq, &hd)?;
3093 let (qkv, z) = qkv_pair(e, &hq, &hd)?;
3094 (qkv, z, b, a)
3095 }
3096 }
3097 } else {
3098 // 35B trunk lands HERE: wqkv/wqkv_gate are Q8_0 but ssm_beta/alpha are F32, so
3099 // all_fast is false. Still fuse the two Q8_0 projections (one quantize + ONE launch
3100 // instead of two matmuls each re-quantizing h) — matmul_q8_fused2_x is bit-identical
3101 // to the two m=1 MMVQ dispatches. beta/alpha keep the Float cuBLAS path.
3102 let (qm, zg) = match e.matmul_q8_fused2_x(&la.wqkv, &la.wqkv_gate, h)? {
3103 Some(pair) => pair,
3104 None => (e.matmul(&la.wqkv, h, 1)?, e.matmul(&la.wqkv_gate, h, 1)?),
3105 };
3106 (
3107 qm,
3108 zg,
3109 e.matmul(&la.ssm_beta, h, 1)?,
3110 e.matmul(&la.ssm_alpha, h, 1)?,
3111 )
3112 };
3113
3114 // RANK3 LEVER (conv fuse): assemble [conv_state | new col], depthwise causal conv + SiLU, and
3115 // roll the ring — ALL in ONE kernel (`ssm_conv1d_fused_decode`), never materializing conv_in
3116 // to HBM. Replaces conv_assemble_and_roll + ssm_conv1d. Bit-identical (same accumulation order).
3117 let rl = cache.recur[il].as_mut().unwrap();
3118 let mut conv_out = e.uninit(conv_dim)?; // [conv_dim, 1] channel-major, SiLU
3119 e.ssm_conv1d_fused_decode(
3120 &qkv_mixed,
3121 &mut rl.conv_state,
3122 la.ssm_conv1d.float_data(),
3123 &mut conv_out,
3124 conv_dim,
3125 d_conv,
3126 )?;
3127
3128 // GDN scan: SSM state stays RESIDENT on GPU. gdn needs DISTINCT in/out state buffers.
3129 // DECODE DETERMINISM FIX: write the new state into the PERSISTENT spare buffer
3130 // (`ssm_state_alt`) and PING-PONG the two owned buffers in place — instead of allocating a
3131 // fresh `state_scratch` via `e.uninit` each step and swapping its pointer in. The old
3132 // per-step alloc/free churned the stream-ordered async pool; the freed prior state block was
3133 // recycled by a later step's scratch while a kernel still referenced the swapped-in state,
3134 // a use-after-reuse that made decode RUN-TO-RUN nondeterministic (two identical primes
3135 // diverged). With two stable resident buffers there is no per-step alloc/free and no pool
3136 // churn; the math is byte-identical. `o` is a true per-step output (consumed immediately by
3137 // gated_rmsnorm below) so it stays a normal scratch.
3138 let mut o = e.uninit(d_state * num_v)?;
3139 let n_state = d_state * d_state * num_v;
3140 let _ = head_k; // head_k == d_state; the kernels use head_k = d_state internally.
3141 // GDN PREP, FUSED (2026-07-03): repack + q/k L2-norm + beta sigmoid + g_log in ONE
3142 // gdn_prep_decode launch (was 5 tiny serialized kernels: qkv_to_gdn_repack, 2x l2_norm,
3143 // sigmoid, gdn_glog). Same math; the L2 reduce runs a 32-lane warp tree instead of the
3144 // 256-thread two-level tree (different FP sum order) — gates: argmax + run-spec exactness.
3145 // (A prep+scan single-launch fusion — lane/gdnfuse, MEMRA_GDN_FUSE — measured NEUTRAL on
3146 // eager decode 2026-07-08 and was removed in the flag audit; rig5090.jsonl holds the record.)
3147 {
3148 let mut q_l2 = e.uninit(d_state * num_v)?;
3149 let mut k_l2 = e.uninit(d_state * num_v)?;
3150 let mut v_gd = e.uninit(d_state * num_v)?;
3151 let mut beta = e.uninit(num_v)?;
3152 let mut g_log = e.uninit(num_v)?;
3153 e.gdn_prep_decode(
3154 &conv_out,
3155 &beta_raw,
3156 &alpha,
3157 la.ssm_dt.float_data(),
3158 la.ssm_a.float_data(),
3159 &mut q_l2,
3160 &mut k_l2,
3161 &mut v_gd,
3162 &mut beta,
3163 &mut g_log,
3164 d_state,
3165 num_v,
3166 num_k,
3167 key_dim,
3168 eps,
3169 )?;
3170 // gdn reads ssm_state, writes the spare ssm_state_alt (disjoint resident fields).
3171 let RecurLayer {
3172 ssm_state,
3173 ssm_state_alt,
3174 ..
3175 } = rl;
3176 e.gdn_scan_s128(
3177 &q_l2,
3178 &k_l2,
3179 &v_gd,
3180 &g_log,
3181 &beta,
3182 ssm_state,
3183 ssm_state_alt,
3184 &mut o,
3185 num_v,
3186 1,
3187 scale,
3188 )?;
3189 }
3190 if persistent_state {
3191 // CAPTURE-safe (graph replay): the canonical state every replay reads must stay at a
3192 // FIXED pointer (baked into the captured graph). Copy the freshly-written spare BACK
3193 // into ssm_state (captured, replays each launch). No host pointer swap.
3194 let alt = std::mem::replace(&mut rl.ssm_state_alt, e.zeros(0)?);
3195 e.copy_into(&mut rl.ssm_state, 0, &alt, n_state)?;
3196 rl.ssm_state_alt = alt;
3197 } else {
3198 // EAGER: swap the two OWNED resident buffers in place (stable pointers, no alloc/free).
3199 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3200 }
3201
3202 // gated RMSNorm + ssm_out. FUSED-QUANTIZE ARM (launch-arc): when ssm_out rides the
3203 // q8_1 fast path, emit q8_1 straight from the gated norm (bit-identical bytes to
3204 // gated_rmsnorm + quantize_q8_1) and feed matmul_pre — one launch instead of three
3205 // (norm, quantize, scale all fold away). Fallback = the original f32 chain.
3206 if e.uses_q8_1_fast(&la.ssm_out) {
3207 // norm is PER d_state-ROW (num_v rows), exactly like the f32 twin's grid; the q8_1
3208 // block stream is row-major so the flat bytes feed the matvec unchanged.
3209 let (gq, gd) =
3210 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v, eps)?;
3211 let g0 = e.zeros(0)?;
3212 return Ok(e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, 1)?);
3213 }
3214 let mut gn = e.uninit(d_state * num_v)?;
3215 e.gated_rmsnorm(
3216 &o,
3217 la.ssm_norm.float_data(),
3218 &z,
3219 &mut gn,
3220 d_state,
3221 num_v,
3222 eps,
3223 )?;
3224 Ok(e.matmul(&la.ssm_out, &gn, 1)?)
3225 }
3226}