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 geometry = cfg.full_attention_geometry_at(il as u32);
1924 let n_head = geometry.n_head as usize;
1925 let n_head_kv = geometry.n_head_kv as usize;
1926 let head_dim = geometry.head_dim_k as usize;
1927 let eps = cfg.rms_eps;
1928 let scale = geometry.attention_scale();
1929
1930 let n_embd = cfg.n_embd as usize;
1931 // Q8 TRUNK-FUSION (2026-07-05): wq+wk+wv share input h — on the 35B every full-attn
1932 // projection is Q8_0, so ONE fused3 launch (block-offset split, out_f 8192/512/512)
1933 // replaces three launch-latency-class m=1 launches. BIT-IDENTICAL per (tensor,row) to
1934 // the three matmul_pre MMVQ dispatches (same kernel body). MEMRA_Q8_DUAL=0 rollback.
1935 let qkv_fused = |e: &Engine,
1936 hq: &CudaSlice<i8>,
1937 hd: &CudaSlice<f32>|
1938 -> Result<
1939 (CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>),
1940 Box<dyn std::error::Error>,
1941 > {
1942 if let Some((qf, k, v)) = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)? {
1943 return Ok((qf, k, v));
1944 }
1945 Ok((
1946 e.matmul_pre(&fa.wq, hq, hd, h, 1)?,
1947 e.matmul_pre(&fa.wk, hq, hd, h, 1)?,
1948 e.matmul_pre(&fa.wv, hq, hd, h, 1)?,
1949 ))
1950 };
1951 let (qf, mut k, v) =
1952 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
1953 match pre_q {
1954 Some((hq, hd)) => qkv_fused(e, hq, hd)?,
1955 None => {
1956 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
1957 qkv_fused(e, &hq, &hd)?
1958 }
1959 }
1960 } else {
1961 (
1962 e.matmul(&fa.wq, h, 1)?,
1963 e.matmul(&fa.wk, h, 1)?,
1964 e.matmul(&fa.wv, h, 1)?,
1965 )
1966 };
1967 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
1968 let gated = geometry.attention_gate
1969 == memra_gguf::config::AttentionGateKind::FusedQ;
1970 let (mut q, gate) = if gated {
1971 let mut q = e.uninit(n_head * head_dim)?;
1972 let mut gate = e.uninit(n_head * head_dim)?;
1973 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
1974 (q, Some(gate))
1975 } else {
1976 (qf, None)
1977 };
1978
1979 let mut qn = e.uninit(n_head * head_dim)?;
1980 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
1981 q = qn;
1982 let mut kn = e.uninit(n_head_kv * head_dim)?;
1983 e.rms_norm(
1984 &k,
1985 fa.k_norm.float_data(),
1986 &mut kn,
1987 head_dim,
1988 n_head_kv,
1989 eps,
1990 )?;
1991 k = kn;
1992 let rope_dims = geometry.n_rot as usize;
1993 // rope pos from the resident device counter (no per-step host upload).
1994 e.rope_neox(
1995 &mut q,
1996 pos_d,
1997 head_dim,
1998 rope_dims,
1999 n_head,
2000 1,
2001 geometry.rope_base,
2002 1.0,
2003 )?;
2004 e.rope_neox(
2005 &mut k,
2006 pos_d,
2007 head_dim,
2008 rope_dims,
2009 n_head_kv,
2010 1,
2011 geometry.rope_base,
2012 1.0,
2013 )?;
2014
2015 let kvl = cache.kv[il].as_mut().unwrap();
2016 // (1) append at the device write slot kvl.len_d (== old len).
2017 e.append_kv_quantized_dc(
2018 &k,
2019 &v,
2020 &mut kvl.k,
2021 &mut kvl.v,
2022 &kvl.len_d,
2023 kvl.kv_dim_k,
2024 kvl.kv_dim_v,
2025 kvl.k_tok_bytes,
2026 kvl.v_tok_bytes,
2027 crate::Engine::kv_fp8_on(),
2028 )?;
2029 // (2) advance the device counter: kvl.len_d now holds new len == t_kv.
2030 e.inc_seqlen(&mut kvl.len_d)?;
2031 // n_splits sizing + K/V view extent:
2032 // - eager path (cap_bucket_max==None): advance host len; size from live t_kv == bit-identical
2033 // to fa_decode; view exactly t_kv*tok_bytes.
2034 // - capture path (Some(bucket_max)): DO NOT touch host len (replay advances only the device
2035 // counter); size n_splits from bucket_max; view the FULL cache buffer so any in-bucket t_kv
2036 // is in range on replay.
2037 let (bucket_max, k_view, v_view) = match cap_bucket_max {
2038 None => {
2039 kvl.len += 1;
2040 let t_kv = kvl.len;
2041 (
2042 t_kv,
2043 e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes),
2044 e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes),
2045 )
2046 }
2047 Some(bm) => (
2048 bm,
2049 e.view_u8(&kvl.k, kvl.k.len()),
2050 e.view_u8(&kvl.v, kvl.v.len()),
2051 ),
2052 };
2053 let (ktb, vtb) = (kvl.k_tok_bytes, kvl.v_tok_bytes);
2054 let mut attn = e.uninit(n_head * head_dim)?;
2055 if std::env::var("MEMRA_NOFA").is_ok() {
2056 return Err(
2057 "MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV cache; \
2058 unset MEMRA_NOFA to use fa_decode_dc"
2059 .into(),
2060 );
2061 }
2062 // (3) fa_decode reads t_kv from kvl.len_d; bucket_max yields the eager n_splits -> bit-identical.
2063 e.fa_decode_dc(
2064 &q,
2065 &k_view,
2066 &v_view,
2067 &mut attn,
2068 head_dim,
2069 n_head,
2070 n_head_kv,
2071 &kvl.len_d,
2072 bucket_max,
2073 scale,
2074 ktb,
2075 vtb,
2076 crate::Engine::kv_fp8_on(),
2077 )?;
2078
2079 let attn_g = match &gate {
2080 Some(gate) => {
2081 let mut gsig = e.uninit(n_head * head_dim)?;
2082 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2083 let mut ag = e.uninit(n_head * head_dim)?;
2084 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2085 ag
2086 }
2087 None => attn,
2088 };
2089 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2090 }
2091
2092 /// Greedy generation: prime with prompt tokens (decode them in sequence to build state),
2093 /// then generate `max_new` tokens. Returns the generated token ids. (Back-compat: greedy,
2094 /// no EOS/stop — used by the decode==prefill validation gate. New code uses `generate_with`.)
2095 pub fn generate(
2096 &self,
2097 e: &Engine,
2098 prompt: &[u32],
2099 max_new: usize,
2100 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
2101 let max_ctx = prompt.len() + max_new + 8;
2102 let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
2103 let mut last_logits = Vec::new();
2104 // prime: BATCHED cache prime (prime_cache — the prefill-throughput path, the measured #1
2105 // e2e gap: tokenwise primed at ~102/38 tok/s vs ~2000-5900 tok/s batched). Prompts below
2106 // PRIME_MIN_T, MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the
2107 // tokenwise loop. Frozen mixed residency would otherwise transiently stage the missing
2108 // expert bank through the GPU on every prompt replay.
2109 let t_prime = std::time::Instant::now();
2110 let batched_prime = prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
2111 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
2112 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
2113 if batched_prime {
2114 let (l, _h_seed, _hiddens) = self.prime_cache(e, prompt, &mut cache, 0)?;
2115 last_logits = l;
2116 } else {
2117 for &tok in prompt {
2118 last_logits = self.decode_step(e, tok, &mut cache)?;
2119 }
2120 }
2121 e.stream().synchronize()?;
2122 // Harness timing contract: prime wall time published for gen-only throughput math
2123 // (bench binaries read this right after the call; subtraction-from-total breaks down
2124 // when prime >> gen — measured ±80% error at 6k-token prompts).
2125 crate::PRIME_NANOS.store(
2126 t_prime.elapsed().as_nanos() as u64,
2127 std::sync::atomic::Ordering::Relaxed,
2128 );
2129 let mut out = Vec::with_capacity(max_new);
2130 if self.cfg.gemma4.is_some()
2131 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2132 // Graph serving probed FLAT vs this dc loop (2026-07-12, 1.7k N=2: 174.6/174.2 vs
2133 // 174.5/174.3) — the GRAPH-GATE's +2.5% is over the plain-eager loop, and the dc
2134 // arc already banked that; the gate (IDENTICAL at every ctx since the wkv
2135 // capture-arm fix) stays as the correctness harness.
2136 // DEVICE-COUNTER greedy loop (the dc arc): stream-identical to eager (DC-GATE).
2137 // E4B rides its own dc step (same trunk fns as its eager chain).
2138 let n_vocab = self.output.out_features();
2139 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2140 for kvl in cache.kv.iter_mut().flatten() {
2141 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2142 }
2143 let e4b = self.is_gemma4_e4b();
2144 // 26B/31B WHOLE-TOKEN GRAPH SERVING door (MEMRA_GEMMA_GRAPH=1): measured FLAT on
2145 // the 26B (jsonl 2026-07-12) but the 31B carries ~4% launch-gap share (HANDOVER
2146 // graph-arc note) and was never measured — the plain-short 1.00x cell probe.
2147 if !e4b && std::env::var("MEMRA_GEMMA_GRAPH").as_deref() == Ok("1") {
2148 let first = argmax(&last_logits) as u32;
2149 let (toks, _reason) = self.gemma4_generate_graph(
2150 e, cache.pos, first, &mut cache, max_new, &[], |_| true)?;
2151 out.extend(toks);
2152 return Ok(out);
2153 }
2154 let mut token_d = e.stream().clone_htod(&[argmax(&last_logits) as u32])?;
2155 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2156 // E4B GRAPH-EXEC-UPDATE SERVING: one capture at bucket=win, per-token fa
2157 // geometry retune, replay. The 2026-07-12 park ("flat 173.5, stream 64/64") did
2158 // NOT reproduce — the capture warmups are real self-feeding steps and the old
2159 // door dropped their 2 tokens (E4B-GRAPH-GATE 3/64). Snapshot/rollback (the 26B
2160 // graph-loop pattern) fixes the stream; the exec-update kills the bucket-split
2161 // tax (42 fa launches at 64 splits vs eager's ~ceil(t_kv/8)).
2162 // DEFAULT: budget-gated ON (2026-07-13 valid-window A/B: steady-state replay
2163 // beats eager but the one-time capture ~30ms crosses over near 200 tokens —
2164 // 128tok −1.3%, 400tok +0.9%). MEMRA_E4B_GRAPH=1 forces, =0 kills.
2165 let win = self.cfg.gemma4.as_ref().map(|g| g.sliding_window as usize).unwrap_or(0);
2166 let e4b_graph = match std::env::var("MEMRA_E4B_GRAPH").as_deref() {
2167 Ok("1") => true, Ok("0") => false, _ => max_new >= 256,
2168 };
2169 if e4b && cache.pos + max_new + 2 < win && e4b_graph {
2170 self.gemma4_e4b_graph_exec_loop(
2171 e, &mut cache, &mut token_d, &mut pos_d, embd_gpu, qt, rb, n_vocab, win,
2172 max_new, usize::MAX, |tok| { out.push(tok); None })?;
2173 return Ok(out);
2174 }
2175 for _ in 0..max_new {
2176 out.push(e.dtoh_u32(&token_d)?[0]);
2177 token_d = if e4b {
2178 self.gemma4_e4b_decode_step_dc(
2179 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
2180 )?
2181 } else {
2182 self.gemma4_decode_step_dc(
2183 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab, None,
2184 )?
2185 };
2186 }
2187 return Ok(out);
2188 }
2189 // QWEN DC-EAGER route (2026-07-15, MEMRA_QWEN_DC=0 seam — mirror of generate_with's
2190 // serving loop; see the note there. The graph route probed −11% first.)
2191 // step35 is EXCLUDED: this route calls `decode_step_dc`, whose full-attn arm refuses
2192 // step35 by design (SWA layers need a token-OFFSET KV view the dc kernels' len_d-derived
2193 // t_kv cannot express). Without this gate the door opens for any greedy model and the
2194 // refusal surfaces as a user-visible generate() error — the first PP-2 boot of
2195 // Step-3.7-Flash died exactly there, AFTER a clean load and an argmax MATCH.
2196 static QWEN_DC2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2197 let qwen_dc = *QWEN_DC2.get_or_init(||
2198 std::env::var("MEMRA_QWEN_DC").as_deref() != Ok("0"));
2199 if qwen_dc && max_new > 0 && self.cfg.step35.is_none()
2200 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2201 let n_vocab = self.output.out_features();
2202 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2203 for kvl in cache.kv.iter_mut().flatten() {
2204 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2205 }
2206 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2207 let mut token_d = e.stream().clone_htod(&[argmax(&last_logits) as u32])?;
2208 for _ in 0..max_new {
2209 out.push(e.dtoh_u32(&token_d)?[0]);
2210 token_d = self.decode_step_dc(e, &token_d, &mut pos_d, embd_gpu, qt, rb,
2211 &mut cache, n_vocab)?;
2212 }
2213 return Ok(out);
2214 }
2215 for _ in 0..max_new {
2216 let next = argmax(&last_logits) as u32;
2217 out.push(next);
2218 last_logits = self.decode_step(e, next, &mut cache)?;
2219 }
2220 Ok(out)
2221 }
2222
2223 /// E4B whole-token GRAPH-EXEC-UPDATE serving loop (shared by `generate` and
2224 /// `generate_with`): capture ONE self-feeding dcg step at bucket=`win`, then per token
2225 /// retune the fa nodes' split geometry to the live eager counts
2226 /// (`graph_update::fa_apply`) before replaying the instantiated exec.
2227 ///
2228 /// The capture's two warmup runs are REAL executions (self-feeding: they consume two
2229 /// tokens and advance KV/counters) — snapshot/rollback around the capture (the 26B
2230 /// graph-loop pattern) restores device+host state, or the stream drops those tokens
2231 /// (E4B-GRAPH-GATE 3/64 break, 2026-07-12). `emit` sees each token BEFORE its
2232 /// successor's replay; returning `Some(reason)` stops the loop. Caller owns the
2233 /// under-window gate (`cache.pos + budget + 2 < win`).
2234 #[allow(clippy::too_many_arguments)]
2235 fn gemma4_e4b_graph_exec_loop(
2236 &self, e: &Engine, cache: &mut Cache, token_d: &mut CudaSlice<u32>,
2237 pos_d: &mut CudaSlice<i32>, embd_gpu: &CudaSlice<u8>, qt: i32, rb: usize,
2238 n_vocab: usize, win: usize, budget: usize, ctx_cap: usize,
2239 mut emit: impl FnMut(u32) -> Option<StopReason>,
2240 ) -> Result<StopReason, Box<dyn std::error::Error>> {
2241 // BISECT ARM (MEMRA_E4B_DCG_EAGER=1): run the dcg step EAGERLY per token at the
2242 // exact live bucket — no capture/replay/exec-update. Separates "the dc-bucket path
2243 // diverges from dc-eager numerically" from "the replay/update mechanism is wrong".
2244 if let Ok(m) = std::env::var("MEMRA_E4B_DCG_EAGER") {
2245 // =1: exact live bucket per token; =2: the capture's fixed win bucket.
2246 let mut reason = StopReason::MaxNew;
2247 for _ in 0..budget {
2248 let tok = e.dtoh_u32_one(token_d)?;
2249 if let Some(r) = emit(tok) { reason = r; break; }
2250 if cache.pos >= ctx_cap { reason = StopReason::ContextFull; break; }
2251 let b = if m == "2" { win } else { cache.pos + 1 };
2252 self.gemma4_e4b_decode_step_dcg(e, token_d, pos_d, embd_gpu, qt, rb,
2253 cache, n_vocab, b)?;
2254 cache.pos += 1;
2255 for kvl in cache.kv.iter_mut().flatten() { kvl.len += 1; }
2256 }
2257 return Ok(reason);
2258 }
2259 // snapshot device+host state (the 2 capture-warmup runs must leave no residue).
2260 let snap = cache.snapshot(e)?;
2261 let pos_save = e.dtoh_i32_one(pos_d)?;
2262 let len_save: Vec<Option<i32>> = cache.kv.iter()
2263 .map(|k| k.as_ref().map(|kvl| e.dtoh_i32_one(&kvl.len_d).unwrap())).collect();
2264 let tok_save = e.dtoh_u32_one(token_d)?;
2265 let (graph, keeper) = e.capture_graph_retained(|e| {
2266 self.gemma4_e4b_decode_step_dcg(e, token_d, pos_d, embd_gpu, qt, rb,
2267 cache, n_vocab, win)
2268 })?;
2269 cache.rollback(e, &snap, 0)?;
2270 e.set_i32_one(pos_d, pos_save)?;
2271 for (il, ls) in len_save.iter().enumerate() {
2272 if let (Some(kvl), Some(v)) = (cache.kv[il].as_mut(), ls) {
2273 e.set_i32_one(&mut kvl.len_d, *v)?;
2274 }
2275 }
2276 e.set_u32_one(token_d, tok_save)?;
2277 let mut plan = crate::graph_update::fa_plan(&graph)?;
2278 if std::env::var("MEMRA_GRAPH_NODES_DUMP").as_deref() == Ok("1") {
2279 let nodes = crate::graph_update::kernel_nodes(&graph)?;
2280 let mut counts: std::collections::BTreeMap<String, (usize, (u32, u32, u32))> =
2281 std::collections::BTreeMap::new();
2282 for n in &nodes {
2283 counts.entry(n.name.clone())
2284 .or_insert((0, (n.params.gridDimX, n.params.gridDimY, n.params.gridDimZ)))
2285 .0 += 1;
2286 }
2287 eprintln!("[graph-nodes] {} kernel nodes, {} fa update units (bucket={win})",
2288 nodes.len(), plan.len());
2289 for (name, (c, grid)) in &counts {
2290 eprintln!("[graph-nodes] {c:4}x {name} grid={grid:?}");
2291 }
2292 }
2293 let mut reason = StopReason::MaxNew;
2294 let timing = std::env::var("MEMRA_E4B_GRAPH_TIMING").as_deref() == Ok("1");
2295 let (mut t_dtoh, mut t_apply, mut t_launch) =
2296 (std::time::Duration::ZERO, std::time::Duration::ZERO, std::time::Duration::ZERO);
2297 for _ in 0..budget {
2298 let t0 = std::time::Instant::now();
2299 let tok = e.dtoh_u32_one(token_d)?;
2300 let t1 = std::time::Instant::now();
2301 if let Some(r) = emit(tok) { reason = r; break; }
2302 if cache.pos >= ctx_cap { reason = StopReason::ContextFull; break; }
2303 // live t_kv AFTER this replay's in-graph append = pos + 1.
2304 crate::graph_update::fa_apply(&graph, &mut plan, cache.pos + 1,
2305 crate::fa_split_keys)?;
2306 let t2 = std::time::Instant::now();
2307 graph.launch()?;
2308 if timing {
2309 let t3 = std::time::Instant::now();
2310 t_dtoh += t1 - t0; t_apply += t2 - t1; t_launch += t3 - t2;
2311 }
2312 cache.pos += 1;
2313 for kvl in cache.kv.iter_mut().flatten() { kvl.len += 1; }
2314 }
2315 if timing {
2316 eprintln!("[e4b-graph timing] dtoh(sync-wait) {:?} apply {:?} launch {:?}",
2317 t_dtoh, t_apply, t_launch);
2318 }
2319 drop(keeper); // capture-retained transients must outlive every replay
2320 Ok(reason)
2321 }
2322
2323 /// The reusable serving generation API (BASE-3). Primes the prompt, then samples up to
2324 /// `params.max_new` tokens, stopping on EOS, any stop-token, or the context-length guard.
2325 /// Calls `on_token(id)` after each emitted token (for streaming; return `false` to stop early).
2326 /// Returns `GenOutput { tokens, stop_reason }`. Does NOT detokenize — the caller (which owns
2327 /// the tokenizer) handles text + stop-STRING matching on the detokenized tail.
2328 pub fn generate_with<F: FnMut(u32) -> bool>(
2329 &self,
2330 e: &Engine,
2331 prompt: &[u32],
2332 params: &GenParams,
2333 sampler: &mut crate::sampler::Sampler,
2334 mut on_token: F,
2335 ) -> Result<GenOutput, Box<dyn std::error::Error>> {
2336 // Context guard: prompt + generated must fit max_ctx (caller-supplied or model default).
2337 let ctx_cap = params.max_ctx.unwrap_or(prompt.len() + params.max_new + 8);
2338 if prompt.len() >= ctx_cap {
2339 return Ok(GenOutput {
2340 tokens: Vec::new(),
2341 stop_reason: StopReason::ContextFull,
2342 });
2343 }
2344 let room = ctx_cap - prompt.len();
2345 let budget = params.max_new.min(room);
2346
2347 let mut cache = Cache::new(e, &self.cfg, ctx_cap)?;
2348 let mut last_logits = Vec::new();
2349 // BATCHED PRIME (2026-07-06 fix — generate_with was still tokenwise! run-gen's "decode"
2350 // numbers folded a ~40-100 tok/s tokenwise prime into the rate) + PRIME_NANOS contract.
2351 // Frozen Hy3 CPU/GPU expert serving is the deliberate exception: its batched MoE path
2352 // bypasses the CPU tier and rereads the spilled expert bank.
2353 let t_prime = std::time::Instant::now();
2354 let batched = prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
2355 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
2356 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
2357 if batched {
2358 let (l, _h, _x) = self.prime_cache(e, prompt, &mut cache, 0)?;
2359 last_logits = l;
2360 for &tok in prompt {
2361 sampler.accept(tok);
2362 }
2363 } else {
2364 for &tok in prompt {
2365 last_logits = self.decode_step(e, tok, &mut cache)?;
2366 sampler.accept(tok);
2367 }
2368 }
2369 e.stream().synchronize()?;
2370 crate::PRIME_NANOS.store(
2371 t_prime.elapsed().as_nanos() as u64,
2372 std::sync::atomic::Ordering::Relaxed,
2373 );
2374 // MEMRA_PROFILE_GEN=2: profiler capture starts HERE — after the prime — so an
2375 // `nsys -c cudaProfilerApi` capture contains ONLY the decode loop (the run-spec
2376 // MEMRA_PROFILE_SPEC=2 pattern; =1 in run_gen brackets prime+decode).
2377 if std::env::var("MEMRA_PROFILE_GEN").as_deref() == Ok("2") {
2378 unsafe extern "C" {
2379 fn cudaProfilerStart() -> i32;
2380 }
2381 unsafe {
2382 cudaProfilerStart();
2383 }
2384 }
2385 let mut out = Vec::with_capacity(budget);
2386 let mut reason = StopReason::MaxNew;
2387 // gemma4 DEVICE-COUNTER greedy serving loop (the dc arc): token/pos/kv-lens live in
2388 // device counters, argmax on device — host sees 4B/token. Stream-identical to the
2389 // eager chain (DC-GATE). Penalties/temp fall through to the host-logits loop.
2390 if self.cfg.gemma4.is_some()
2391 && sampler.is_greedy() && sampler.penalty_last_n() == 0
2392 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2393 let n_vocab = self.output.out_features();
2394 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2395 for kvl in cache.kv.iter_mut().flatten() {
2396 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2397 }
2398 let first = crate::forward::argmax(&last_logits) as u32;
2399 let e4b = self.is_gemma4_e4b();
2400 let mut token_d = e.stream().clone_htod(&[first])?;
2401 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2402 // E4B GRAPH-EXEC-UPDATE serving door (under-window regime) — mirror of the
2403 // `generate` door incl the budget-gated default; run-gen/serving measure here.
2404 let win = self.cfg.gemma4.as_ref().map(|g| g.sliding_window as usize).unwrap_or(0);
2405 let e4b_graph = match std::env::var("MEMRA_E4B_GRAPH").as_deref() {
2406 Ok("1") => true, Ok("0") => false, _ => budget >= 256,
2407 };
2408 if e4b && cache.pos + budget + 2 < win && e4b_graph {
2409 let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
2410 let reason = self.gemma4_e4b_graph_exec_loop(
2411 e, &mut cache, &mut token_d, &mut pos_d, embd_gpu, qt, rb, n_vocab, win,
2412 budget, ctx_cap, |tok| {
2413 sampler_cell.accept(tok);
2414 out_cell.push(tok);
2415 if params.eos.contains(&tok) { return Some(StopReason::Eos); }
2416 if !on_token(tok) { return Some(StopReason::Callback); }
2417 None
2418 })?;
2419 return Ok(GenOutput { tokens: out, stop_reason: reason });
2420 }
2421 // 12B/31B WHOLE-TOKEN GRAPH door (MEMRA_GEMMA_GRAPH=1), mirrored from `generate`:
2422 // run-gen/serving measure THIS path, and the `generate` door never covered it —
2423 // the 2026-07-22 graph A/B read flat because the env engaged nothing here.
2424 if !e4b && std::env::var("MEMRA_GEMMA_GRAPH").as_deref() == Ok("1") {
2425 let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
2426 let eos = params.eos.clone();
2427 let (toks, greason) = self.gemma4_generate_graph(
2428 e, cache.pos, first, &mut cache, budget, &eos, |tok| {
2429 sampler_cell.accept(tok);
2430 out_cell.push(tok);
2431 on_token(tok)
2432 })?;
2433 let _ = toks;
2434 return Ok(GenOutput { tokens: out, stop_reason: greason });
2435 }
2436 let mut next = first;
2437 for _ in 0..budget {
2438 sampler.accept(next);
2439 out.push(next);
2440 if params.eos.contains(&next) {
2441 reason = StopReason::Eos;
2442 break;
2443 }
2444 if !on_token(next) {
2445 reason = StopReason::Callback;
2446 break;
2447 }
2448 if cache.pos >= ctx_cap {
2449 reason = StopReason::ContextFull;
2450 break;
2451 }
2452 token_d = if e4b {
2453 self.gemma4_e4b_decode_step_dc(
2454 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab,
2455 )?
2456 } else {
2457 self.gemma4_decode_step_dc(
2458 e, &token_d, &mut pos_d, embd_gpu, qt, rb, &mut cache, n_vocab, None,
2459 )?
2460 };
2461 next = e.dtoh_u32(&token_d)?[0];
2462 }
2463 return Ok(GenOutput {
2464 tokens: out,
2465 stop_reason: reason,
2466 });
2467 }
2468 // QWEN DC-EAGER serving loop (2026-07-15, MEMRA_QWEN_DC=0 seam — the gemma dc-arc
2469 // pattern): the eager tail dtoh'd the FULL VOCAB logits + host-argmax'd every
2470 // token (the duty map's 10.3%-of-wall gap at 13% DRAM duty). decode_step_dc keeps
2471 // the token id + argmax device-resident — 4B/token host traffic, same tuned eager
2472 // kernels. Greedy + no-penalty only (sampling needs host logits).
2473 // (The CUDA-graph route was probed first and read −11%: the replay's dc-fa family
2474 // + capture rungs lag the tuned eager lanes; jsonl 2026-07-15.)
2475 // step35 is EXCLUDED here for the same reason as the `generate` mirror above: every route
2476 // inside this door (`decode_step_dc` and the `graph_decode_loop` capture) reaches
2477 // `full_attn_decode_dc_inner`, which refuses step35 because its SWA layers read a
2478 // token-OFFSET KV view the dc kernels cannot express. step35 takes the host-logits eager
2479 // loop at the bottom of this function (`decode_step` -> `step35_decode_attn`), which is
2480 // the supported decode for this arch. Removing this gate requires a windowed dc fa_decode
2481 // plus a per-layer-n_head capture, not a flag.
2482 static QWEN_DC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2483 let qwen_dc = *QWEN_DC.get_or_init(||
2484 std::env::var("MEMRA_QWEN_DC").as_deref() != Ok("0"));
2485 if qwen_dc && sampler.is_greedy() && sampler.penalty_last_n() == 0 && budget > 0
2486 && self.cfg.step35.is_none()
2487 && let Some(embd_gpu) = self.embd_gpu_try(e) {
2488 let n_vocab = self.output.out_features();
2489 let (qt, rb) = self.embd.qt_and_row_bytes(self.cfg.n_embd as usize);
2490 for kvl in cache.kv.iter_mut().flatten() {
2491 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2492 }
2493 let mut pos_d = e.htod_i32(&[cache.pos as i32])?;
2494 let mut token_d = e.stream().clone_htod(
2495 &[crate::forward::argmax(&last_logits) as u32])?;
2496 // HYBRID GRAPH DOOR (round 35): graph_decode_loop over the batched-prime
2497 // cache — the E4B graph-exec door's hybrid mirror. Counters (pos_d/token_d/
2498 // len_d) synced above; event tracking is engine-default-OFF so capture over
2499 // these buffers is legal. PROMOTED default-ON at budget >= 256 (the E4B
2500 // door's amortization rule): official-shape A/B interleaved x5 = eager 190.3
2501 // -> graph 220.7 tok/s (+16.0%, 5/5, spread ±0.1); 128-tok stream IDENTICAL;
2502 // graph-decode-gate 256 steps x 16 buckets BIT-IDENTICAL. This REFUTES the
2503 // 2026-07-15 "-11%" qwen-graph verdict — it predated the exec-update rework
2504 // and the 07-26 FA family (stale-verdict law, round 35). =0 reverts.
2505 // Default ON at budget >= 256 on BOTH arches (unified-merge resolution,
2506 // 2026-07-30): main shipped this door budget-keyed on sm_120a (52222ddd,
2507 // E4B graph door) and every 5090 board row since measured with it; the H100
2508 // lane measured +16% x5. The branch-era arch-gate (79395a3e) cited the
2509 // stale 2026-07-15 "-11%" verdict, which predates main's promotion — the
2510 // rig-divergence law protects main's SHIPPED default, so the gate came off.
2511 // MEMRA_GEN_GRAPH=1 opts in anywhere; =0 reverts anywhere.
2512 //
2513 // KEY LOWERED 256 -> 48 (q27 deep dive, 2026-08-05, pro6000wk-runpod-community).
2514 // The 256 key was set by the E4B amortization rule, never by a measured crossover,
2515 // so every <=128-token generation — including the whole published board, which runs
2516 // --max-tokens 128 — was silently EAGER. Swept the actual crossover on TWO models
2517 // (the key is a cross-model default, so one artifact is not enough), interleaved
2518 // arms with the order alternated per rep, N=3, all runs argmax MATCH:
2519 // Qwen3.6-27B-Q8_0 : n=16 -7.47% | n=32 -1.35% | n=48 +0.90% | n=64 +1.93%
2520 // n=128 +3.80% | n=512 +5.50%
2521 // Qwen3.6-27B-NVFP4-MTP: n=16 -15.27% | n=32 +0.22% | n=48 +3.45%
2522 // n=64 +5.09% | n=128 +7.72%
2523 // Both models: clearly negative at 16, no reliable gain at 32, positive from 48 up,
2524 // monotone in budget from 48 on. 48 is the first budget where BOTH are positive, so
2525 // it is the key — the capture cost needs ~32 steps to amortize, not ~256. The n=32
2526 // nvfp4 cell is NOISY, not flat (graph arm 79.02/78.91/77.09, spread 1.93 vs an
2527 // eager spread of 0.04): it is not evidence of a win, and it is why the key sits at
2528 // 48 rather than 32. Exactness at the new key:
2529 // graph-decode-gate 256 steps BIT-IDENTICAL (buckets=16, captures=2),
2530 // graph-session-gate 96 tokens PASS, kernel-check ALL GREEN, run-spec K=1..8
2531 // self-consistency PASS. Board caveat: community board, RELATIVE deltas only.
2532 //
2533 // SM-GATED (5090-arbiter gate, 2026-08-05, research/q27-deepdive-20260805/local5090/):
2534 // the 48 key does NOT transfer to the 82-SM local rig. Same A/B protocol there
2535 // (tg128 d512, N=3 interleaved, order alternated, warmup discarded): q27-NVFP4-MTP
2536 // graph arm at n=128 = -1.61% (eager 45.86 / graph 45.12 median, 3/3 pairs lose),
2537 // and the crossover sweep stays negative through n=256 (-1.07%) and n=512 (-0.59%)
2538 // — on few-SM silicon the replay's fixed kernel forms lag the tuned eager lanes and
2539 // the launch-gap tax the graph amortizes is proportionally smaller. Key on SM count
2540 // (the fa_split_keys big_rig pattern, lib.rs fa_sm_count), threshold 180: the 48
2541 // crossover is MEASURED only at 188 SM (PRO 6000) and refuted at 82 SM; the 132-SM
2542 // H100 board and the 170-SM desktop 5090 are UNMEASURED at sub-256 budgets, so they
2543 // keep the shipped 256 key their board rows were measured with (rig-divergence +
2544 // stale-verdict laws). Widening the gate below 180 requires an on-box crossover
2545 // sweep on that silicon, not an inference from this comment.
2546 let big_rig = e.sm_count() >= 180;
2547 let gen_graph = match std::env::var("MEMRA_GEN_GRAPH").as_deref() {
2548 Ok("1") => true,
2549 Ok("0") => false,
2550 _ => budget >= if big_rig { 48 } else { 256 },
2551 };
2552 // SLRU expert cache is capture-ILLEGAL: a cache miss drains/H2Ds on the compute
2553 // stream mid-decode, which CUDA forbids while capturing (Ornith-35B Q4_K_M on the
2554 // 24GB rig died with CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED, 2026-08-01 — any MoE
2555 // model whose experts overflow the residency budget hit this at budget >= 256).
2556 // The door only opens with every MoE layer's experts device-resident; =1 cannot
2557 // legalize a capture, so this closes the forced door too.
2558 let moe_resident = self.layers.iter().all(|l| match &l.ffn {
2559 crate::hybrid::Ffn::Moe(m) => m.dev_exps.is_some(),
2560 _ => true,
2561 });
2562 if gen_graph && !moe_resident {
2563 static NOTICE: std::sync::Once = std::sync::Once::new();
2564 NOTICE.call_once(|| eprintln!(
2565 "[gen-graph] door CLOSED: MoE experts on the SLRU cache path \
2566 (capture-illegal) — eager decode"
2567 ));
2568 }
2569 if gen_graph && moe_resident && budget > 0 {
2570 let head_dim = self.cfg.head_dim_k as usize;
2571 let mut gs = GraphDecodeState::new(e)?;
2572 gs.pos_d = pos_d;
2573 gs.token_d = token_d;
2574 let (out_cell, sampler_cell) = (&mut out, &mut *sampler);
2575 let reason = self.graph_decode_loop(
2576 e, &mut gs, &mut cache, embd_gpu, qt, rb, head_dim, budget, |tok| {
2577 sampler_cell.accept(tok);
2578 out_cell.push(tok);
2579 if params.eos.contains(&tok) { return Some(StopReason::Eos); }
2580 if !on_token(tok) { return Some(StopReason::Callback); }
2581 None
2582 })?;
2583 return Ok(GenOutput { tokens: out, stop_reason: reason });
2584 }
2585 let mut next = e.dtoh_u32(&token_d)?[0];
2586 for _ in 0..budget {
2587 sampler.accept(next);
2588 out.push(next);
2589 if params.eos.contains(&next) { reason = StopReason::Eos; break; }
2590 if !on_token(next) { reason = StopReason::Callback; break; }
2591 if cache.pos >= ctx_cap { reason = StopReason::ContextFull; break; }
2592 token_d = self.decode_step_dc(e, &token_d, &mut pos_d, embd_gpu, qt, rb,
2593 &mut cache, n_vocab)?;
2594 next = e.dtoh_u32(&token_d)?[0];
2595 }
2596 return Ok(GenOutput { tokens: out, stop_reason: reason });
2597 }
2598 for _ in 0..budget {
2599 let next = sampler.sample(&last_logits);
2600 sampler.accept(next);
2601 out.push(next);
2602 if params.eos.contains(&next) {
2603 reason = StopReason::Eos;
2604 break;
2605 }
2606 if !on_token(next) {
2607 reason = StopReason::Callback;
2608 break;
2609 }
2610 if cache.pos >= ctx_cap {
2611 reason = StopReason::ContextFull;
2612 break;
2613 }
2614 last_logits = self.decode_step(e, next, &mut cache)?;
2615 }
2616 Ok(GenOutput {
2617 tokens: out,
2618 stop_reason: reason,
2619 })
2620 }
2621
2622 /// Full-attention decode: project q/gate/k/v for the new token, QK-norm, RoPE at pos,
2623 /// append k,v to the layer KV cache, attend over the full [0..=pos] context.
2624 pub(crate) fn full_attn_decode(
2625 &self,
2626 e: &Engine,
2627 fa: &FullAttnLayer,
2628 h: &CudaSlice<f32>,
2629 pos_d: &CudaSlice<i32>,
2630 pos: usize,
2631 cache: &mut Cache,
2632 il: usize,
2633 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2634 self.full_attn_decode_pre(e, fa, h, None, pos_d, pos, cache, il)
2635 }
2636
2637 /// PRE-QUANTIZED-INPUT eager full-attn (attn-input NORM-FUSION lever): caller passes the
2638 /// attn-normed activation already q8_1 `(hq,hd)` (rms_norm_q8_1) -> skips internal quantize_q8_1.
2639 /// `None` = quantize h here (the spec / non-fused path). BIT-IDENTICAL.
2640 pub(crate) fn full_attn_decode_pre(
2641 &self,
2642 e: &Engine,
2643 fa: &FullAttnLayer,
2644 h: &CudaSlice<f32>,
2645 pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2646 pos_d: &CudaSlice<i32>,
2647 pos: usize,
2648 cache: &mut Cache,
2649 il: usize,
2650 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2651 if self.cfg.step35.is_some() {
2652 return self.step35_decode_attn(e, fa, il, h, pre_q, pos_d, cache);
2653 }
2654 let cfg = &self.cfg;
2655 let geometry = cfg.full_attention_geometry_at(il as u32);
2656 let n_head = geometry.n_head as usize;
2657 let n_head_kv = geometry.n_head_kv as usize;
2658 let head_dim = geometry.head_dim_k as usize;
2659 let eps = cfg.rms_eps;
2660 let scale = geometry.attention_scale();
2661
2662 // LATENCY-HIDING (MEMRA_KV_PREFETCH=1): warm this layer's KV stream into L2 while the
2663 // q/k/v projections run ahead of the fa (fa is latency-bound; its lines land warm).
2664 // Value-free scheduling — no numeric config change.
2665 static KV_PF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2666 if *KV_PF.get_or_init(|| std::env::var("MEMRA_KV_PREFETCH").as_deref() == Ok("1")) {
2667 let kvl = cache.kv[il].as_ref().unwrap();
2668 let t_kv = kvl.len + 1;
2669 e.prefetch_l2(&kvl.k, t_kv * kvl.k_tok_bytes)?;
2670 e.prefetch_l2(&kvl.v, t_kv * kvl.v_tok_bytes)?;
2671 }
2672
2673 // wq|wk|wv all take the same input `h` (in_f = n_embd) — quantize q8_1 ONCE, feed all three.
2674 // Q8 TRUNK-FUSION: on Q8_0 trunks (35B) the three fold into ONE fused3 launch (same MMVQ
2675 // body per (tensor,row) — bit-identical; see full_attn_decode_dc_inner). MEMRA_Q8_DUAL=0 off.
2676 let n_embd = cfg.n_embd as usize;
2677 let qkv_fused = |e: &Engine,
2678 hq: &CudaSlice<i8>,
2679 hd: &CudaSlice<f32>|
2680 -> Result<
2681 (CudaSlice<f32>, CudaSlice<f32>, CudaSlice<f32>),
2682 Box<dyn std::error::Error>,
2683 > {
2684 if let Some((qf, k, v)) = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)? {
2685 return Ok((qf, k, v));
2686 }
2687 Ok((
2688 e.matmul_pre(&fa.wq, hq, hd, h, 1)?,
2689 e.matmul_pre(&fa.wk, hq, hd, h, 1)?,
2690 e.matmul_pre(&fa.wv, hq, hd, h, 1)?,
2691 ))
2692 };
2693 let (qf, mut k, v) =
2694 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
2695 match pre_q {
2696 Some((hq, hd)) => qkv_fused(e, hq, hd)?,
2697 None => {
2698 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
2699 qkv_fused(e, &hq, &hd)?
2700 }
2701 }
2702 } else {
2703 (
2704 e.matmul(&fa.wq, h, 1)?,
2705 e.matmul(&fa.wk, h, 1)?,
2706 e.matmul(&fa.wv, h, 1)?,
2707 )
2708 };
2709 // q|gate fused: [2*head_dim per head]. Split on-device (no dtoh/host-loop/htod).
2710 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2711 let gated = geometry.attention_gate
2712 == memra_gguf::config::AttentionGateKind::FusedQ;
2713 let (mut q, gate) = if gated {
2714 let mut q = e.uninit(n_head * head_dim)?;
2715 let mut gate = e.uninit(n_head * head_dim)?;
2716 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
2717 (q, Some(gate))
2718 } else {
2719 (qf, None)
2720 };
2721
2722 // QK-norm + RoPE at position `pos`
2723 let mut qn = e.uninit(n_head * head_dim)?;
2724 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
2725 q = qn;
2726 let mut kn = e.uninit(n_head_kv * head_dim)?;
2727 e.rms_norm(
2728 &k,
2729 fa.k_norm.float_data(),
2730 &mut kn,
2731 head_dim,
2732 n_head_kv,
2733 eps,
2734 )?;
2735 k = kn;
2736 let rope_dims = geometry.n_rot as usize;
2737 e.rope_neox(
2738 &mut q,
2739 pos_d,
2740 head_dim,
2741 rope_dims,
2742 n_head,
2743 1,
2744 geometry.rope_base,
2745 1.0,
2746 )?;
2747 e.rope_neox(
2748 &mut k,
2749 pos_d,
2750 head_dim,
2751 rope_dims,
2752 n_head_kv,
2753 1,
2754 geometry.rope_base,
2755 1.0,
2756 )?;
2757
2758 // append k,v into the RESIDENT GPU QUANTIZED KV cache at the current position (q8_0 K /
2759 // q5_1 V, on-device append-quantize kernel; no host round-trip). KVQUANT-PLAN §C/E2.
2760 let kvl = cache.kv[il].as_mut().unwrap();
2761 e.append_kv_quantized(
2762 &k,
2763 &v,
2764 &mut kvl.k,
2765 &mut kvl.v,
2766 kvl.len,
2767 kvl.kv_dim_k,
2768 kvl.kv_dim_v,
2769 kvl.k_tok_bytes,
2770 kvl.v_tok_bytes,
2771 crate::Engine::kv_fp8_on(),
2772 )?;
2773 kvl.len += 1;
2774 let t_kv = kvl.len;
2775
2776 // attend: q[hd,nh,1] over the resident byte K/V (view first t_kv*tok_bytes BYTES).
2777 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
2778 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
2779 let (ktb, vtb) = (kvl.k_tok_bytes, kvl.v_tok_bytes);
2780 let mut attn = e.uninit(n_head * head_dim)?;
2781 if std::env::var("MEMRA_NOFA").is_ok() {
2782 return Err(
2783 "MEMRA_NOFA (naive f32 SDPA) is incompatible with the quantized KV cache; \
2784 unset MEMRA_NOFA to use fa_decode"
2785 .into(),
2786 );
2787 }
2788 e.fa_decode_kvmod(
2789 &q,
2790 &k_view,
2791 &v_view,
2792 &mut attn,
2793 head_dim,
2794 n_head,
2795 n_head_kv,
2796 t_kv,
2797 scale,
2798 ktb,
2799 vtb,
2800 crate::Engine::kv_fp8_on(),
2801 )?;
2802 let _ = pos;
2803
2804 // output gate: attn * sigmoid(gate), then o-proj
2805 let attn_g = match &gate {
2806 Some(gate) => {
2807 let mut gsig = e.uninit(n_head * head_dim)?;
2808 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2809 let mut ag = e.uninit(n_head * head_dim)?;
2810 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2811 ag
2812 }
2813 None => attn,
2814 };
2815 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2816 }
2817
2818 /// BATCHED full-attention decode over `m` independent streams (one token each).
2819 ///
2820 /// Generic m-band primitive, not lockstep-specific: any caller holding `m` streams at the
2821 /// same layer (multi-stream decode, a continuous-batching serve loop) can use it. The split
2822 /// follows what the hardware cares about — WEIGHT-BOUND work runs once at `m` because all
2823 /// streams share the same projection weights (one weight read serves `m` tokens instead of
2824 /// `m` reads), while KV-BOUND work stays per stream because each stream owns its own cache.
2825 ///
2826 /// Bit-identity with the per-stream path holds by construction: `quantize_q8_1` and
2827 /// `rms_norm` are per-row, `rope_neox` takes a per-token position vector, the fused3/matmul
2828 /// m-band kernels are the same ones spec verify is gated on, and attention itself is
2829 /// untouched per stream.
2830 ///
2831 /// `xcat` is `[m, n_embd]` normed activations; `pos_cat` is the `m` rope positions;
2832 /// returns `[m, n_embd]` attention outputs.
2833 #[allow(clippy::too_many_arguments)]
2834 pub(crate) fn full_attn_decode_batched(
2835 &self,
2836 e: &Engine,
2837 fa: &FullAttnLayer,
2838 xcat: &CudaSlice<f32>,
2839 m: usize,
2840 pos_cat: &CudaSlice<i32>,
2841 caches: &mut [Cache],
2842 il: usize,
2843 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2844 if self.cfg.step35.is_some() {
2845 return Err("step35 has no batched (m-stream) decode mixer — per-layer n_head, \
2846 partial rope and the SWA offset view need a step35 twin".into());
2847 }
2848 let cfg = &self.cfg;
2849 let geometry = cfg.full_attention_geometry_at(il as u32);
2850 let n_head = geometry.n_head as usize;
2851 let n_head_kv = geometry.n_head_kv as usize;
2852 let head_dim = geometry.head_dim_k as usize;
2853 let n_embd = cfg.n_embd as usize;
2854 let eps = cfg.rms_eps;
2855 let scale = geometry.attention_scale();
2856 let q_row = n_head * head_dim;
2857 let kv_row = n_head_kv * head_dim;
2858
2859 // --- weight-bound: one quantize + one q/k/v projection for all m streams ---
2860 let (hq, hd) = e.quantize_q8_1(xcat, m, n_embd)?;
2861 let use_q8 =
2862 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
2863 let (qf, mut k, v) = if use_q8 {
2864 match e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, &hq, &hd, m)? {
2865 Some(trio) => trio,
2866 None => (
2867 e.matmul_pre(&fa.wq, &hq, &hd, xcat, m)?,
2868 e.matmul_pre(&fa.wk, &hq, &hd, xcat, m)?,
2869 e.matmul_pre(&fa.wv, &hq, &hd, xcat, m)?,
2870 ),
2871 }
2872 } else {
2873 (
2874 e.matmul(&fa.wq, xcat, m)?,
2875 e.matmul(&fa.wk, xcat, m)?,
2876 e.matmul(&fa.wv, xcat, m)?,
2877 )
2878 };
2879
2880 // --- elementwise: batched by treating the m streams as extra rows/tokens ---
2881 let gated = geometry.attention_gate
2882 == memra_gguf::config::AttentionGateKind::FusedQ;
2883 let (mut q, gate) = if gated {
2884 let mut q = e.uninit(m * q_row)?;
2885 let mut gate = e.uninit(m * q_row)?;
2886 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, m)?;
2887 (q, Some(gate))
2888 } else {
2889 (qf, None)
2890 };
2891 let mut qn = e.uninit(m * q_row)?;
2892 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head * m, eps)?;
2893 q = qn;
2894 let mut kn = e.uninit(m * kv_row)?;
2895 e.rms_norm(&k, fa.k_norm.float_data(), &mut kn, head_dim, n_head_kv * m, eps)?;
2896 k = kn;
2897 let rope_dims = geometry.n_rot as usize;
2898 e.rope_neox(&mut q, pos_cat, head_dim, rope_dims, n_head, m, geometry.rope_base, 1.0)?;
2899 e.rope_neox(
2900 &mut k,
2901 pos_cat,
2902 head_dim,
2903 rope_dims,
2904 n_head_kv,
2905 m,
2906 geometry.rope_base,
2907 1.0,
2908 )?;
2909
2910 // --- KV-bound: each stream appends to and attends over its own cache ---
2911 let mut attn_cat = e.uninit(m * q_row)?;
2912 let mut q_s = e.uninit(q_row)?;
2913 let mut k_s = e.uninit(kv_row)?;
2914 let mut v_s = e.uninit(kv_row)?;
2915 for (s, cache) in caches.iter_mut().enumerate().take(m) {
2916 e.copy_view_into(&mut k_s, 0, &k.slice(s * kv_row..(s + 1) * kv_row), kv_row)?;
2917 e.copy_view_into(&mut v_s, 0, &v.slice(s * kv_row..(s + 1) * kv_row), kv_row)?;
2918 e.copy_view_into(&mut q_s, 0, &q.slice(s * q_row..(s + 1) * q_row), q_row)?;
2919 let kvl = cache.kv[il].as_mut().unwrap();
2920 e.append_kv_quantized(
2921 &k_s,
2922 &v_s,
2923 &mut kvl.k,
2924 &mut kvl.v,
2925 kvl.len,
2926 kvl.kv_dim_k,
2927 kvl.kv_dim_v,
2928 kvl.k_tok_bytes,
2929 kvl.v_tok_bytes,
2930 crate::Engine::kv_fp8_on(),
2931 )?;
2932 kvl.len += 1;
2933 let t_kv = kvl.len;
2934 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
2935 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
2936 let mut attn = e.uninit(q_row)?;
2937 e.fa_decode_kvmod(
2938 &q_s,
2939 &k_view,
2940 &v_view,
2941 &mut attn,
2942 head_dim,
2943 n_head,
2944 n_head_kv,
2945 t_kv,
2946 scale,
2947 kvl.k_tok_bytes,
2948 kvl.v_tok_bytes,
2949 crate::Engine::kv_fp8_on(),
2950 )?;
2951 e.copy_into(&mut attn_cat, s * q_row, &attn, q_row)?;
2952 }
2953
2954 // --- weight-bound again: gate epilogue + one output projection for all m streams ---
2955 let attn_g = match &gate {
2956 Some(gate) => {
2957 let mut gsig = e.uninit(m * q_row)?;
2958 e.sigmoid(gate, &mut gsig, m * q_row)?;
2959 let mut ag = e.uninit(m * q_row)?;
2960 e.mul(&attn_cat, &gsig, &mut ag, m * q_row)?;
2961 ag
2962 }
2963 None => attn_cat,
2964 };
2965 e.matmul(&fa.wo, &attn_g, m)
2966 }
2967
2968 /// Linear-attention decode: conv with ring-buffer state, GDN scan carrying SSM state.
2969 pub fn linear_attn_decode(
2970 &self,
2971 e: &Engine,
2972 la: &LinearAttnLayer,
2973 h: &CudaSlice<f32>,
2974 cache: &mut Cache,
2975 il: usize,
2976 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2977 self.linear_attn_decode_inner(e, la, h, None, cache, il, false)
2978 }
2979
2980 /// PRE-QUANTIZED-INPUT variant (DECODE attn-input NORM-FUSION lever): the caller passes the
2981 /// post-attn-norm activation ALREADY q8_1-quantized `(hq,hd)` (produced by rms_norm_q8_1, fusing
2982 /// the attn_norm + the mixer's internal quantize_q8_1). Skips the internal quantize. Caller
2983 /// GUARANTEES the projections are q8_1-fast. `persistent` selects the capture-safe state plumbing.
2984 /// BIT-IDENTICAL to linear_attn_decode(h) when (hq,hd)==quantize_q8_1(rms_norm(x)*w).
2985 pub fn linear_attn_decode_pre(
2986 &self,
2987 e: &Engine,
2988 la: &LinearAttnLayer,
2989 h: &CudaSlice<f32>,
2990 hq: &CudaSlice<i8>,
2991 hd: &CudaSlice<f32>,
2992 cache: &mut Cache,
2993 il: usize,
2994 persistent: bool,
2995 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2996 self.linear_attn_decode_inner(e, la, h, Some((hq, hd)), cache, il, persistent)
2997 }
2998
2999 /// CAPTURE variant of `linear_attn_decode` (CUDA-GRAPH-PLAN Phase 3). The GDN scan needs distinct
3000 /// in/out SSM-state buffers; the eager path SWAPS a fresh scratch into `rl.ssm_state` (new pointer
3001 /// each step), which is a CAPTURE HAZARD — the graph bakes capture-time pointers and never re-runs
3002 /// the host swap, so replay would read a stale state buffer. Here we instead COPY the scratch back
3003 /// into the STABLE `rl.ssm_state` buffer (memcpy_dtod, captured, same pointers every replay). Math
3004 /// is identical; only the buffer plumbing differs. `conv_state` is already mutated in place (no
3005 /// pointer change) so it is capture-safe as-is.
3006 pub(crate) fn linear_attn_decode_cap(
3007 &self,
3008 e: &Engine,
3009 la: &LinearAttnLayer,
3010 h: &CudaSlice<f32>,
3011 cache: &mut Cache,
3012 il: usize,
3013 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3014 self.linear_attn_decode_inner(e, la, h, None, cache, il, true)
3015 }
3016
3017 fn linear_attn_decode_inner(
3018 &self,
3019 e: &Engine,
3020 la: &LinearAttnLayer,
3021 h: &CudaSlice<f32>,
3022 pre_q: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
3023 cache: &mut Cache,
3024 il: usize,
3025 persistent_state: bool,
3026 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3027 let cfg = &self.cfg;
3028 let ssm = cfg.ssm.as_ref().unwrap();
3029 let d_state = ssm.state_size as usize;
3030 let num_k = ssm.group_count as usize;
3031 let num_v = ssm.time_step_rank as usize;
3032 let d_conv = ssm.conv_kernel as usize;
3033 let head_k = d_state;
3034 let key_dim = head_k * num_k;
3035 let value_dim = d_state * num_v;
3036 let conv_dim = key_dim * 2 + value_dim;
3037 let eps = cfg.rms_eps;
3038 let scale = 1.0 / (d_state as f32).sqrt();
3039
3040 // projections (T=1): wqkv, wqkv_gate, ssm_beta, ssm_alpha ALL take input `h` (in_f = n_embd)
3041 // -> quantize q8_1 ONCE, feed all four (was 4x redundant quantize_q8_1 of the same row).
3042 let n_embd = cfg.n_embd as usize;
3043 let all_fast = e.uses_q8_1_fast(&la.wqkv)
3044 && e.uses_q8_1_fast(&la.wqkv_gate)
3045 && e.uses_q8_1_fast(&la.ssm_beta)
3046 && e.uses_q8_1_fast(&la.ssm_alpha);
3047 // beta+alpha DUAL fuse (2026-07-05): ssm_beta and ssm_alpha are the same tiny shape
3048 // ([n_embd -> num_v=32]) — out_f=32 launches are pure launch latency (15-16us each,
3049 // HANDOVER b4-headroom note). The existing dual mr2 kernel (FFN gate+up) folds them into
3050 // ONE launch. Bit-identical per row: same MMVQ warp-per-row body, blockIdx.y picks the
3051 // weight; the separable macro-scale multiply is the same single f32 mul as matmul_pre's
3052 // in-kernel scale. Falls back to two matmul_pre when ineligible (Float layers 1/2/4 etc).
3053 let beta_alpha =
3054 |e: &Engine,
3055 hq: &CudaSlice<i8>,
3056 hd: &CudaSlice<f32>|
3057 -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3058 if let Some(((mut b, bs), (mut a, as_))) =
3059 e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, hq, hd, 1)?
3060 {
3061 if bs != 1.0 {
3062 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
3063 }
3064 if as_ != 1.0 {
3065 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
3066 }
3067 return Ok((b, a));
3068 }
3069 // Q8_0 twin of the NVFP4 dual (9B GGUFs store ssm_beta/alpha as Q8_0 on most layers):
3070 // one fused2 launch, bit-identical per row, no macro-scale (q8_0 scale==1.0).
3071 if let Some((b, a)) = e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, hq, hd)? {
3072 return Ok((b, a));
3073 }
3074 Ok((
3075 e.matmul_pre(&la.ssm_beta, hq, hd, h, 1)?,
3076 e.matmul_pre(&la.ssm_alpha, hq, hd, h, 1)?,
3077 ))
3078 };
3079 // Q8 TRUNK-FUSION (2026-07-05): wqkv+wqkv_gate share (hq,hd) and in_f — on the 35B both
3080 // are Q8_0 (out_f 8192/4096), so ONE fused2 launch replaces the two biggest
3081 // launch-latency-class m=1 launches of every linear layer. BIT-IDENTICAL per (tensor,row)
3082 // (same MMVQ body, block-offset split). Falls back per-tensor when ineligible.
3083 let qkv_pair =
3084 |e: &Engine,
3085 hq: &CudaSlice<i8>,
3086 hd: &CudaSlice<f32>|
3087 -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3088 if let Some((qkv, z)) = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, hq, hd)? {
3089 return Ok((qkv, z));
3090 }
3091 Ok((
3092 e.matmul_pre(&la.wqkv, hq, hd, h, 1)?,
3093 e.matmul_pre(&la.wqkv_gate, hq, hd, h, 1)?,
3094 ))
3095 };
3096 let (qkv_mixed, z, beta_raw, alpha) = if all_fast {
3097 // attn-input NORM-FUSION: use the caller's pre-quantized (hq,hd) when provided (the
3098 // attn_norm already emitted q8_1 via rms_norm_q8_1), else quantize h here. Bit-identical.
3099 match pre_q {
3100 Some((hq, hd)) => {
3101 let (b, a) = beta_alpha(e, hq, hd)?;
3102 let (qkv, z) = qkv_pair(e, hq, hd)?;
3103 (qkv, z, b, a)
3104 }
3105 None => {
3106 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
3107 let (b, a) = beta_alpha(e, &hq, &hd)?;
3108 let (qkv, z) = qkv_pair(e, &hq, &hd)?;
3109 (qkv, z, b, a)
3110 }
3111 }
3112 } else {
3113 // 35B trunk lands HERE: wqkv/wqkv_gate are Q8_0 but ssm_beta/alpha are F32, so
3114 // all_fast is false. Still fuse the two Q8_0 projections (one quantize + ONE launch
3115 // instead of two matmuls each re-quantizing h) — matmul_q8_fused2_x is bit-identical
3116 // to the two m=1 MMVQ dispatches. beta/alpha keep the Float cuBLAS path.
3117 let (qm, zg) = match e.matmul_q8_fused2_x(&la.wqkv, &la.wqkv_gate, h)? {
3118 Some(pair) => pair,
3119 None => (e.matmul(&la.wqkv, h, 1)?, e.matmul(&la.wqkv_gate, h, 1)?),
3120 };
3121 (
3122 qm,
3123 zg,
3124 e.matmul(&la.ssm_beta, h, 1)?,
3125 e.matmul(&la.ssm_alpha, h, 1)?,
3126 )
3127 };
3128
3129 // RANK3 LEVER (conv fuse): assemble [conv_state | new col], depthwise causal conv + SiLU, and
3130 // roll the ring — ALL in ONE kernel (`ssm_conv1d_fused_decode`), never materializing conv_in
3131 // to HBM. Replaces conv_assemble_and_roll + ssm_conv1d. Bit-identical (same accumulation order).
3132 let rl = cache.recur[il].as_mut().unwrap();
3133 let mut conv_out = e.uninit(conv_dim)?; // [conv_dim, 1] channel-major, SiLU
3134 e.ssm_conv1d_fused_decode(
3135 &qkv_mixed,
3136 &mut rl.conv_state,
3137 la.ssm_conv1d.float_data(),
3138 &mut conv_out,
3139 conv_dim,
3140 d_conv,
3141 )?;
3142
3143 // GDN scan: SSM state stays RESIDENT on GPU. gdn needs DISTINCT in/out state buffers.
3144 // DECODE DETERMINISM FIX: write the new state into the PERSISTENT spare buffer
3145 // (`ssm_state_alt`) and PING-PONG the two owned buffers in place — instead of allocating a
3146 // fresh `state_scratch` via `e.uninit` each step and swapping its pointer in. The old
3147 // per-step alloc/free churned the stream-ordered async pool; the freed prior state block was
3148 // recycled by a later step's scratch while a kernel still referenced the swapped-in state,
3149 // a use-after-reuse that made decode RUN-TO-RUN nondeterministic (two identical primes
3150 // diverged). With two stable resident buffers there is no per-step alloc/free and no pool
3151 // churn; the math is byte-identical. `o` is a true per-step output (consumed immediately by
3152 // gated_rmsnorm below) so it stays a normal scratch.
3153 let mut o = e.uninit(d_state * num_v)?;
3154 let n_state = d_state * d_state * num_v;
3155 let _ = head_k; // head_k == d_state; the kernels use head_k = d_state internally.
3156 // GDN PREP, FUSED (2026-07-03): repack + q/k L2-norm + beta sigmoid + g_log in ONE
3157 // gdn_prep_decode launch (was 5 tiny serialized kernels: qkv_to_gdn_repack, 2x l2_norm,
3158 // sigmoid, gdn_glog). Same math; the L2 reduce runs a 32-lane warp tree instead of the
3159 // 256-thread two-level tree (different FP sum order) — gates: argmax + run-spec exactness.
3160 // (A prep+scan single-launch fusion — lane/gdnfuse, MEMRA_GDN_FUSE — measured NEUTRAL on
3161 // eager decode 2026-07-08 and was removed in the flag audit; rig5090.jsonl holds the record.)
3162 {
3163 let mut q_l2 = e.uninit(d_state * num_v)?;
3164 let mut k_l2 = e.uninit(d_state * num_v)?;
3165 let mut v_gd = e.uninit(d_state * num_v)?;
3166 let mut beta = e.uninit(num_v)?;
3167 let mut g_log = e.uninit(num_v)?;
3168 e.gdn_prep_decode(
3169 &conv_out,
3170 &beta_raw,
3171 &alpha,
3172 la.ssm_dt.float_data(),
3173 la.ssm_a.float_data(),
3174 &mut q_l2,
3175 &mut k_l2,
3176 &mut v_gd,
3177 &mut beta,
3178 &mut g_log,
3179 d_state,
3180 num_v,
3181 num_k,
3182 key_dim,
3183 eps,
3184 )?;
3185 // gdn reads ssm_state, writes the spare ssm_state_alt (disjoint resident fields).
3186 let RecurLayer {
3187 ssm_state,
3188 ssm_state_alt,
3189 ..
3190 } = rl;
3191 e.gdn_scan_s128(
3192 &q_l2,
3193 &k_l2,
3194 &v_gd,
3195 &g_log,
3196 &beta,
3197 ssm_state,
3198 ssm_state_alt,
3199 &mut o,
3200 num_v,
3201 1,
3202 scale,
3203 )?;
3204 }
3205 if persistent_state {
3206 // CAPTURE-safe (graph replay): the canonical state every replay reads must stay at a
3207 // FIXED pointer (baked into the captured graph). Copy the freshly-written spare BACK
3208 // into ssm_state (captured, replays each launch). No host pointer swap.
3209 let alt = std::mem::replace(&mut rl.ssm_state_alt, e.zeros(0)?);
3210 e.copy_into(&mut rl.ssm_state, 0, &alt, n_state)?;
3211 rl.ssm_state_alt = alt;
3212 } else {
3213 // EAGER: swap the two OWNED resident buffers in place (stable pointers, no alloc/free).
3214 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3215 }
3216
3217 // gated RMSNorm + ssm_out. FUSED-QUANTIZE ARM (launch-arc): when ssm_out rides the
3218 // q8_1 fast path, emit q8_1 straight from the gated norm (bit-identical bytes to
3219 // gated_rmsnorm + quantize_q8_1) and feed matmul_pre — one launch instead of three
3220 // (norm, quantize, scale all fold away). Fallback = the original f32 chain.
3221 if e.uses_q8_1_fast(&la.ssm_out) {
3222 // norm is PER d_state-ROW (num_v rows), exactly like the f32 twin's grid; the q8_1
3223 // block stream is row-major so the flat bytes feed the matvec unchanged.
3224 let (gq, gd) =
3225 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v, eps)?;
3226 let g0 = e.zeros(0)?;
3227 return Ok(e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, 1)?);
3228 }
3229 let mut gn = e.uninit(d_state * num_v)?;
3230 e.gated_rmsnorm(
3231 &o,
3232 la.ssm_norm.float_data(),
3233 &z,
3234 &mut gn,
3235 d_state,
3236 num_v,
3237 eps,
3238 )?;
3239 Ok(e.matmul(&la.ssm_out, &gn, 1)?)
3240 }
3241}