Skip to main content

memra_engine/
spec.rs

1//! Qwen3.5 MTP (NextN) greedy speculative decode (research/mtp/MTP-PLAN.md §A/§B/§C/§D).
2//!
3//! Greedy spec decode is MATHEMATICALLY EXACT: the accepted+bonus token stream is token-for-token
4//! identical to plain greedy `generate`. This module provides:
5//!   - `mtp_head_forward`  (§A, T=1): one NextN draft-token forward.
6//!   - `decode_step_t`     (§D.3, T=K+1): batched target verify forward, all-column logits.
7//!   - `generate_spec`     (§B): the draft/verify/accept/rollback orchestrator.
8//! Cache snapshot/rollback lives in cache.rs (§D.4). The MTP head uses its OWN scratch KV (§D.6),
9//! PERSISTENT over the committed sequence (see `MtpScratch`).
10
11use crate::cache::{Cache, KvLayer};
12use crate::forward::argmax;
13use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer, MtpHead};
14use crate::Engine;
15use cudarc::driver::CudaSlice;
16
17/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
18/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
19/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
20/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
21/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
22/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
23/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
24pub(crate) fn spec_hpost() -> bool {
25    static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
26    *H.get_or_init(|| {
27        std::env::var("MEMRA_SPEC_HPOST")
28            .map(|v| v != "0")
29            .unwrap_or(false)
30    })
31}
32
33/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
34/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
35/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
36/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
37/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
38/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
39/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
40/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
41/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
42pub(crate) fn spec_lean() -> bool {
43    static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
44    // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
45    // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
46    // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
47    *L.get_or_init(|| {
48        std::env::var("MEMRA_SPEC_LEAN")
49            .map(|v| v != "0")
50            .unwrap_or(true)
51    })
52}
53
54/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
55/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
56/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
57/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
58/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
59/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
60///     ring — the ring stores raw input columns); every arithmetic kernel is the same one the
61///     t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
62///     t-loop == chained T=1 steps);
63/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
64///     pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
65/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
66pub(crate) fn spec_m2() -> bool {
67    static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
68    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
69    // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
70    // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
71    // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
72    *M.get_or_init(|| {
73        std::env::var("MEMRA_SPEC_M2")
74            .map(|v| v != "0")
75            .unwrap_or(true)
76    })
77}
78pub(crate) fn spec_stream() -> bool {
79    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
80    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
81}
82pub(crate) fn spec_stream_m() -> usize {
83    static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
84    *M.get_or_init(|| {
85        std::env::var("MEMRA_SPEC_STREAM_M")
86            .ok()
87            .and_then(|v| v.parse().ok())
88            .unwrap_or(4)
89    })
90}
91pub(crate) fn spec_devacc() -> bool {
92    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
93    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
94}
95
96/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
97/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
98/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
99/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
100/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
101/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
102/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
103/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
104/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
105pub trait SpecConstraint {
106    /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
107    /// masked argmax).
108    fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
109    /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
110    fn mask_words(&mut self) -> Result<Vec<u32>, String>;
111    /// Is `tok` consumable in the CURRENT state?
112    fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
113    /// Advance the state with an emitted token.
114    fn consume(&mut self, tok: u32) -> Result<(), String>;
115
116    // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
117    // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
118    // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
119    // loose, research/constrained-full-20260803). These three methods let the engine mask the
120    // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
121    // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
122    // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
123    // stays the correctness backstop and the emitted stream is unchanged by construction
124    // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
125    // argmax; a cut slot is recomputed as the masked argmax either way).
126    // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
127
128    /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
129    /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
130    fn draft_mask_enabled(&self) -> bool {
131        false
132    }
133    /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
134    /// slot. Called once per spec round, before the first draft position.
135    fn draft_begin(&mut self) -> Result<(), String> {
136        Ok(())
137    }
138    /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
139    /// for the draft position about to be sampled. `None` = draft masking off (no-op).
140    fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
141        Ok(None)
142    }
143    /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
144    /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
145    /// engine stops drafting; the token already pushed still goes through verify.
146    fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
147        Ok(false)
148    }
149}
150
151/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
152/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
153/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
154/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
155/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
156/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
157/// verify emits the masked argmax as usual).
158fn upload_draft_mask(
159    e: &Engine,
160    c: &mut dyn SpecConstraint,
161    dst: &mut CudaSlice<u32>,
162    d2t: Option<&Vec<u32>>,
163    d_vocab: usize,
164    words: usize,
165) -> Result<bool, Box<dyn std::error::Error>> {
166    let Some(tw) = c.draft_mask_words().map_err(|e2| format!("constraint: {e2}"))? else {
167        return Ok(false);
168    };
169    let bit = |t: usize| -> bool {
170        let w = t >> 5;
171        w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
172    };
173    let mut buf = vec![0u32; words];
174    match d2t {
175        // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
176        Some(map) => {
177            for (i, &t) in map.iter().enumerate().take(d_vocab) {
178                if bit(t as usize) {
179                    buf[i >> 5] |= 1u32 << (i & 31);
180                }
181            }
182        }
183        // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
184        // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
185        None => {
186            let n = tw.len().min(words);
187            buf[..n].copy_from_slice(&tw[..n]);
188        }
189    }
190    if buf.iter().all(|w| *w == 0) {
191        return Ok(false);
192    }
193    e.htod_u32_into(dst, &buf)?;
194    Ok(true)
195}
196
197/// Keep the full token-embedding table in host memory and upload only the rows needed by each
198/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
199/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
200/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
201pub(crate) fn spec_host_embd() -> bool {
202    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
203    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
204}
205
206/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
207/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
208/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
209/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
210/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
211/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
212/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
213/// run-spec K=1..8 + acceptance identity arbitrate e2e).
214pub(crate) fn spec_fused_t() -> bool {
215    static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
216    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
217    // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
218    // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
219    *F.get_or_init(|| {
220        std::env::var("MEMRA_SPEC_FUSED_T")
221            .map(|v| v != "0")
222            .unwrap_or(true)
223    })
224}
225
226/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
227/// Only call this on such buffers — the lean contract is "identical bytes by construction".
228fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
229    if spec_lean() {
230        e.uninit(n)
231    } else {
232        e.zeros(n)
233    }
234}
235
236/// Scratch KV for the MTP block (one full-attn layer).
237///
238/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
239/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
240/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
241/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
242/// engine's "mtp_update" design). Entries come from two sources:
243///   - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
244///     hidden chain-approximate — the reference engine accepts the same);
245///   - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
246///     from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
247/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
248/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
249/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
250/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
251/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
252/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
253/// committed row across turns (the predecessor-pairing seed + fill anchor).
254/// Per-request sampling config for the sampled-spec serve path.
255#[derive(Clone, Copy, Debug)]
256pub struct SpecSampling {
257    pub temp: f32,
258    pub seed: u64,
259    pub top_k: i32,            // 0 = off
260    pub top_p: f32,            // 1.0 = off
261    pub min_p: f32,            // 0.0 = off
262    pub penalty_last_n: usize, // 0 = penalties off
263    pub penalty_repeat: f32,
264    pub penalty_freq: f32,
265    pub penalty_present: f32,
266}
267
268/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
269/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
270pub const SPEC_TELEM_POS: usize = 8;
271
272/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
273/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
274/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
275/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
276/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
277/// in NEITHER drafted nor accepted.
278#[derive(Clone, Copy, Default, Debug)]
279pub struct SpecTelemetry {
280    /// verify rounds completed (a round-stream burst counts each of its M rounds).
281    pub rounds: u64,
282    /// tokens drafted / accepted across all rounds.
283    pub drafted: u64,
284    pub accepted: u64,
285    /// how often draft position j (0-based within a round's chain) was offered / accepted.
286    /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
287    /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
288    /// arrays cover the standard-path rounds only and their sums may undercount the totals.
289    pub pos_drafted: [u64; SPEC_TELEM_POS],
290    pub pos_accepted: [u64; SPEC_TELEM_POS],
291}
292
293impl SpecTelemetry {
294    /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
295    /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
296    /// a wrapped counter.
297    pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
298        let mut d = SpecTelemetry {
299            rounds: self.rounds.saturating_sub(prev.rounds),
300            drafted: self.drafted.saturating_sub(prev.drafted),
301            accepted: self.accepted.saturating_sub(prev.accepted),
302            ..Default::default()
303        };
304        for j in 0..SPEC_TELEM_POS {
305            d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
306            d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
307        }
308        d
309    }
310    /// Fieldwise `self += d` — the worker's per-model aggregation.
311    pub fn merge(&mut self, d: &SpecTelemetry) {
312        self.rounds += d.rounds;
313        self.drafted += d.drafted;
314        self.accepted += d.accepted;
315        for j in 0..SPEC_TELEM_POS {
316            self.pos_drafted[j] += d.pos_drafted[j];
317            self.pos_accepted[j] += d.pos_accepted[j];
318        }
319    }
320}
321
322pub struct SpecSession {
323    pub(crate) cache: Cache,
324    pub(crate) scratch: MtpScratch,
325    /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
326    /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
327    /// session must count them. Callers render output from this, not from their own echo.
328    pub committed: Vec<u32>,
329    /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
330    pub(crate) last_h: Option<CudaSlice<f32>>,
331    /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
332    /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
333    /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
334    pub next_pred: Option<u32>,
335    /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
336    /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
337    pub sctr: u32,
338    pub uctr: u32,
339    /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
340    /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
341    /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
342    /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
343    /// research/spec-serving-20260801). None before the first turn; error paths drop it
344    /// (next burst recaptures — serve retires errored sessions anyway).
345    pub(crate) draft_ctx: Option<DraftGraphCtx>,
346    /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
347    /// emitted by the last round but NOT committed to the caches. The old tail committed it with
348    /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
349    /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
350    /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
351    /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
352    /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
353    /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
354    /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
355    /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
356    /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
357    pub pending_tok: Option<u32>,
358    /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
359    /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
360    /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
361    /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
362    pub(crate) turn_ckpt: Option<SpecCheckpoint>,
363    /// Session-lifetime acceptance telemetry (lane/accept-telemetry). Host-side u64 adds at
364    /// the round accounting the loop already does — no syncs, no allocation. NOTE a
365    /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
366    /// diff with [`SpecTelemetry::delta_since`] around each burst.
367    pub telem: SpecTelemetry,
368}
369impl SpecSession {
370    /// Context capacity of the session's caches (the server's ContextFull guard).
371    pub fn cache_max_ctx(&self) -> usize {
372        self.cache.max_ctx
373    }
374    /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
375    /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
376    /// `spec_rewind_to_checkpoint`.
377    pub fn rewind_pos(&self) -> Option<usize> {
378        self.turn_ckpt.as_ref().map(|c| c.pos)
379    }
380    /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
381    pub fn rewind_is_resident(&self) -> bool {
382        self.turn_ckpt.as_ref().is_some_and(|ckpt| {
383            self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
384        })
385    }
386    /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
387    /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
388    /// session has never run a turn and has no prediction to hand over.
389    pub fn demote_ready(&self) -> bool {
390        self.pending_tok.is_none() && self.next_pred.is_some()
391    }
392    /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
393    pub fn has_pending(&self) -> bool {
394        self.pending_tok.is_some()
395    }
396    /// Committed row count == cache rows (the session invariant), for the caller's own
397    /// `fed`-length cross-check at a handoff boundary.
398    pub fn committed_len(&self) -> usize {
399        self.committed.len()
400    }
401    /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
402    /// cache + next-token prediction to the plain batched-decode path.
403    ///
404    /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
405    /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
406    /// tokenwise prime of the same `committed` sequence would have left it (that is the
407    /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
408    /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
409    /// committed row — and verify-column logits are bit-identical to plain decode's logits at
410    /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
411    /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
412    /// a state indistinguishable from one the batched path produced itself: the batched tick
413    /// emits `next_pred`, feeds it into this same cache, and decodes on.
414    ///
415    /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
416    /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
417    /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
418    /// path would silently skip a token.
419    ///
420    /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
421    /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
422    /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
423    /// would mean an `mtp_kv_fill` over the whole committed history).
424    pub fn into_demoted(self) -> Option<(Cache, u32)> {
425        if self.pending_tok.is_some() {
426            return None;
427        }
428        let np = self.next_pred?;
429        debug_assert_eq!(
430            self.cache.pos,
431            self.committed.len(),
432            "demotion handoff: cache rows != committed tokens"
433        );
434        Some((self.cache, np))
435    }
436    /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
437    /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
438    /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
439    /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
440    pub fn reset_graph_fallback_on_resume(&mut self) {
441        if let Some(line) = self
442            .draft_ctx
443            .as_mut()
444            .and_then(|c| c.failed.reset_on_resume())
445        {
446            eprintln!("{line}");
447        }
448    }
449}
450
451/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
452///
453/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
454/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
455/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
456/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
457/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
458/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
459///
460/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
461/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
462/// position index, so it must be a real device COPY — that copy is the entire reason a spec
463/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
464/// below the boundary were written by this turn's fill and are never revisited (the per-round
465/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
466/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
467/// predecessor-pairing anchor the next prime's fill reads for its first row.
468///
469/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
470pub(crate) struct SpecCheckpoint {
471    snap: crate::cache::CacheSnapshot,
472    /// Committed length at the boundary (== cache.pos there, the session invariant).
473    pos: usize,
474    /// Pre-output_norm hidden of row `pos - 1`.
475    last_h: CudaSlice<f32>,
476}
477
478/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
479/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
480/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
481/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
482/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
483/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
484/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
485/// so the eager fallback doesn't pay a doomed capture attempt every burst.
486pub(crate) struct DraftGraphCtx {
487    g_tok: CudaSlice<u32>,
488    g_pos: CudaSlice<i32>,
489    g_seed: CudaSlice<f32>,
490    g_p: CudaSlice<f32>,
491    g_ctr: CudaSlice<u32>,
492    g_q: CudaSlice<f32>,
493    g_perturb: CudaSlice<f32>,
494    q_slots: Vec<CudaSlice<f32>>,
495    /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
496    /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
497    /// per-position contents the host re-uploads before each replay (the graph-promote
498    /// pattern from decode.rs). Empty unless the session drafts under a grammar.
499    g_dmask: CudaSlice<u32>,
500    /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
501    graph_masked: bool,
502    graph: Option<cudarc::driver::CudaGraph>,
503    graph_s: Option<cudarc::driver::CudaGraph>,
504    /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
505    /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
506    failed: DraftGraphFallback,
507    /// (seed, temp.to_bits(), k) baked into graph_s at its capture.
508    s_key: Option<(u64, u32, usize)>,
509    /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
510    /// pool addresses the captured graph(s) bake. Without these, the transients return to the
511    /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
512    /// co-served session in the worker) reuses those addresses — the persisted graph's replay
513    /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
514    /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
515    /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
516    /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
517    keeper: Vec<Box<dyn std::any::Any + Send>>,
518    keeper_s: Vec<Box<dyn std::any::Any + Send>>,
519}
520
521/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
522/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
523///
524/// Three contracts:
525/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
526///   (returned, not printed, so the once-per-flip contract is unit-testable); the caller
527///   `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
528///   an already-failed graph returns None (the per-burst memoization that keeps the eager
529///   fallback from paying a doomed capture attempt every burst).
530/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
531///   NEW request gets one fresh capture chance instead of carrying a transient-pressure
532///   failure for the pool's whole lifetime. Returns the note line only when a flag was
533///   actually set (quiet on the common clean-resume path).
534/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
535///   capture attempt whose own failure would re-flip loudly.
536#[derive(Default)]
537pub(crate) struct DraftGraphFallback {
538    greedy: bool,
539    sampled: bool,
540}
541impl DraftGraphFallback {
542    fn mark_greedy(&mut self, reason: &str) -> Option<String> {
543        if self.greedy {
544            return None;
545        }
546        self.greedy = true;
547        Some(format!(
548            "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
549        ))
550    }
551    fn mark_sampled(&mut self, reason: &str) -> Option<String> {
552        if self.sampled {
553            return None;
554        }
555        self.sampled = true;
556        Some(format!(
557            "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
558        ))
559    }
560    fn greedy_failed(&self) -> bool {
561        self.greedy
562    }
563    fn sampled_failed(&self) -> bool {
564        self.sampled
565    }
566    fn clear_greedy(&mut self) {
567        self.greedy = false;
568    }
569    fn clear_sampled(&mut self) {
570        self.sampled = false;
571    }
572    /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
573    /// was set (so clean resumes stay quiet).
574    pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
575        if !self.greedy && !self.sampled {
576            return None;
577        }
578        let which = match (self.greedy, self.sampled) {
579            (true, true) => "greedy+sampled",
580            (true, false) => "greedy",
581            _ => "sampled",
582        };
583        self.greedy = false;
584        self.sampled = false;
585        Some(format!(
586            "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
587        ))
588    }
589}
590
591impl DraftGraphCtx {
592    fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
593        Ok(DraftGraphCtx {
594            g_tok: e.alloc_u32_zeroed(1)?,
595            g_pos: e.htod_i32(&[0])?,
596            g_seed: e.zeros(n_embd)?,
597            g_p: e.zeros(1)?,
598            g_ctr: e.alloc_u32_zeroed(1)?,
599            g_q: e.zeros(qlen)?,
600            g_perturb: e.zeros(qlen)?,
601            q_slots: Vec::new(),
602            g_dmask: e.alloc_u32_zeroed(1)?,
603            graph_masked: false,
604            graph: None,
605            graph_s: None,
606            failed: DraftGraphFallback::default(),
607            s_key: None,
608            keeper: Vec::new(),
609            keeper_s: Vec::new(),
610        })
611    }
612}
613
614pub(crate) struct MtpScratch {
615    kv: KvLayer,
616    /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
617    /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
618    /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
619    /// smaller host-indexed SWA ring instead.
620    cap: usize,
621}
622
623fn mtp_scratch_layout(
624    cfg: &memra_gguf::config::ModelConfig,
625    geom: Option<&crate::hybrid::DraftGeom>,
626) -> (usize, usize, usize, usize) {
627    // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
628    let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
629    let head_dim_k = cfg.head_dim_k as usize;
630    let head_dim_v = cfg.head_dim_v as usize;
631    assert!(
632        head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
633        "KVQUANT requires head_dim%32==0 (MTP scratch)"
634    );
635    let kv_dim_k = head_dim_k * n_head_kv;
636    let kv_dim_v = head_dim_v * n_head_kv;
637    // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
638    // policy shared with `MtpScratch::new` so admission scales the same allocation.
639    let (kbb, vbb) = crate::kv_blk_bytes();
640    let k_tok_bytes = (kv_dim_k / 32) * kbb;
641    let v_tok_bytes = (kv_dim_v / 32) * vbb;
642    (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
643}
644
645impl MtpScratch {
646    fn new(
647        e: &Engine,
648        cfg: &memra_gguf::config::ModelConfig,
649        cap: usize,
650        geom: Option<&crate::hybrid::DraftGeom>,
651    ) -> Result<Self, Box<dyn std::error::Error>> {
652        // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
653        // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
654        // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
655        // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
656        let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) =
657            mtp_scratch_layout(cfg, geom);
658        let ring = if crate::cache::swa_ring_on() && cfg.arch.is_step35() {
659            let window = cfg.step35.as_ref().unwrap().sliding_window as usize;
660            Some(crate::cache::KvRing::new(
661                crate::cache::swa_ring_rows(window, cap),
662                window,
663            ))
664        } else {
665            None
666        };
667        let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
668        Ok(MtpScratch {
669            kv: KvLayer {
670                k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
671                v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
672                kv_dim_k,
673                kv_dim_v,
674                k_tok_bytes,
675                v_tok_bytes,
676                len: 0,
677                ring,
678                len_d: e.htod_i32(&[0])?,
679            },
680            cap,
681        })
682    }
683    /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
684    /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
685    /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
686    fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
687        if self.kv.ring.as_ref().is_some_and(|ring| !ring.can_rewind_to(n)) {
688            return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
689        }
690        self.kv.len = n;
691        e.set_i32_one(&mut self.kv.len_d, n as i32)
692    }
693
694    fn can_rewind_to(&self, n: usize) -> bool {
695        self.kv.ring.as_ref().is_none_or(|ring| ring.can_rewind_to(n))
696    }
697}
698
699/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
700/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
701/// full weight reads per round — recomputing columns the verify had already produced
702/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
703/// to "after the first j verify columns" WITHOUT re-running the trunk:
704/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
705///   consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
706///   to the first j iterations of the verify's scan — the kernel's t-loop carries state in
707///   registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
708///   pure-copy ring rebuild.
709/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
710///   column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
711///   target: j <= t-1).
712/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
713/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
714struct GdnStash {
715    qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
716    q_l2: CudaSlice<f32>,
717    k_l2: CudaSlice<f32>,
718    v_g: CudaSlice<f32>, // [t, num_v, d_state]
719    g_log: CudaSlice<f32>,
720    beta: CudaSlice<f32>, // [t, num_v]
721}
722struct VerifyCkpt {
723    gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
724    cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
725}
726impl VerifyCkpt {
727    fn new(n_layer: usize) -> Self {
728        VerifyCkpt {
729            gdn: (0..n_layer).map(|_| None).collect(),
730            cols: (0..n_layer).map(|_| None).collect(),
731        }
732    }
733}
734
735impl HybridModel {
736    /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
737    /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
738    /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
739    /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
740    /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
741    /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
742    /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
743    /// transfer + host argmax per draft token from the K-token draft chain.
744    #[allow(clippy::too_many_arguments)]
745    fn mtp_head_forward_dev(
746        &self,
747        e: &Engine,
748        mtp: &MtpHead,
749        e_tok: u32,
750        h_seed: &CudaSlice<f32>,
751        scratch: &mut MtpScratch,
752        mtp_pos: usize,
753        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
754        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
755        // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
756        // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
757        mask: Option<(&CudaSlice<u32>, usize)>,
758    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
759        let cfg = &self.cfg;
760        let n_embd = cfg.n_embd as usize;
761        // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
762        // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
763        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
764        let eps = cfg.rms_eps;
765        let pos_d = e.htod_i32(&[mtp_pos as i32])?;
766
767        // op A: a resident table transfers one 4B token id. The exact host-row capacity path
768        // expands this one row on CPU and transfers n_embd f32 values instead.
769        let e_emb = match embd_dev {
770            Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
771            None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
772        };
773
774        // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
775        let mut e_norm = e.zeros(n_embd)?;
776        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
777        let mut h_norm = e.zeros(n_embd)?;
778        e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
779
780        // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
781        let mut concat = e.zeros(2 * n_embd)?;
782        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
783        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
784
785        // op 4: inpSA = eh_proj @ concat  (eh_proj [2*n_embd, n_embd]) -> [n_embd]
786        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
787
788        // op 5: a_norm = RMSNorm(inpSA, attn_norm)
789        let mut a_norm = e.zeros(di)?;
790        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
791
792        // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
793        // scratch.cap, length from the device len_d) so eager drafts match graph drafts
794        // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
795        // advances only the device counter).
796        let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
797            // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
798            // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
799            // Advances BOTH the host len and the device counter itself (unlike the dc arm,
800            // whose host-side mirror the caller does).
801            (Mixer::Full(fa), Some(g)) => self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?,
802            (Mixer::Full(fa), None) => {
803                let out =
804                    self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
805                scratch.kv.len += 1;
806                out
807            }
808            (Mixer::Linear(_), _) => {
809                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
810            }
811            (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
812        };
813
814        // op 7: x1 = inpSA + attn_out
815        let mut x1 = e.zeros(di)?;
816        e.add(&inp_sa, &attn_out, &mut x1, di)?;
817
818        // op 8: z = RMSNorm(x1, post_attn_norm)  (pre-FFN norm)
819        let mut z = e.zeros(di)?;
820        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
821
822        // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
823        let ffn_out = match &mtp.ffn {
824            crate::hybrid::Ffn::Dense {
825                ffn_gate,
826                ffn_up,
827                ffn_down,
828            } => {
829                let n_ff = ffn_gate.out_features();
830                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
831                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
832                    (
833                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
834                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
835                    )
836                } else {
837                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
838                };
839                let mut act = e.zeros(n_ff)?;
840                // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
841                // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
842                // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
843                // passes None, which is `ffn_act`'s dispatch verbatim.
844                Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
845                                  mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
846                                  &mut act, n_ff)?;
847                e.matmul(ffn_down, &act, 1)?
848            }
849            // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
850            // so they never alias trunk layer 0's cache keys.
851            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
852        };
853
854        // op 10: h_nextn = x1 + ffn_out (at di)
855        let mut h_inner = e.zeros(di)?;
856        e.add(&x1, &ffn_out, &mut h_inner, di)?;
857
858        // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
859        // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
860        let h_nextn = match mtp.geom.as_ref() {
861            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
862            None => h_inner,
863        };
864
865        // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
866        let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
867        let mut final_h = e.zeros(n_embd)?;
868        e.rms_norm(
869            &h_nextn,
870            final_norm.float_data(),
871            &mut final_h,
872            n_embd,
873            1,
874            eps,
875        )?;
876
877        // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
878        let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
879        let mut logits = e.matmul(head, &final_h, 1)?;
880        // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
881        // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
882        if let Some((mask_d, mw)) = mask {
883            let d_vocab = head.out_features();
884            e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
885        }
886        // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
887        // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
888        Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
889    }
890
891    /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
892    /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
893    /// the dc path, and all three are properties of this arch's MTP block:
894    ///
895    /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
896    ///    window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
897    ///    cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
898    ///    mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
899    ///    windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
900    ///    starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
901    ///    new kernel. That is deliberately not built here: see the CUDA-graph note below.
902    /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
903    ///    on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
904    ///    trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
905    ///    resolved `Step35MtpGeom`, never from `cfg`.
906    /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
907    ///    sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
908    ///    fused-into-wq `q_gate_split` form the dc arm handles.
909    ///
910    /// WHY EAGER-ONLY IS NOT A GAP TODAY: `graph_draft` requires `trunk_dense`, and this SKU's
911    /// trunk is a 288-expert MoE, so the graph draft is already off for every step35 model — the
912    /// eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
913    /// than silently capturing a window-less (wrong past `win` draft rows) graph.
914    ///
915    /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
916    /// caller must not mirror.
917    fn mtp_step35_attn(
918        &self,
919        e: &Engine,
920        fa: &FullAttnLayer,
921        g: &crate::hybrid::Step35MtpGeom,
922        h: &CudaSlice<f32>,
923        pos_d: &CudaSlice<i32>,
924        scratch: &mut MtpScratch,
925    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
926        let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
927        let eps = self.cfg.rms_eps;
928        let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
929        let n_embd = self.cfg.n_embd as usize;
930        let gw = fa.attn_gate.as_ref()
931            .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
932
933        let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk)
934            && e.uses_q8_1_fast(&fa.wv) && e.uses_q8_1_fast(gw)
935        {
936            let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
937            let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
938                Some(t3) => t3,
939                None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
940                         e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
941                         e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?),
942            };
943            (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
944        } else {
945            (e.matmul(&fa.wq, h, 1)?, e.matmul(&fa.wk, h, 1)?,
946             e.matmul(&fa.wv, h, 1)?, e.matmul(gw, h, 1)?)
947        };
948
949        let mut q = e.uninit(nh * hd)?;
950        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
951        let mut k = e.uninit(nkv * hd)?;
952        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
953        // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
954        // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
955        // the resolved flag, not the constant, so an all-full sibling stays correct.
956        let ff = if g.swa { None } else {
957            self.step35_aux.as_ref().and_then(|a| a.rope_freqs.as_ref())
958        };
959        e.rope_neox2(&mut q, &mut k, pos_d, hd, g.n_rot, nh, nkv, 1, g.rope_base, 1.0, ff)?;
960
961        // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
962        // length on the host anyway, and the windowed view below needs it there to compute the
963        // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
964        // dc-family consumer of this scratch still agree.
965        let kv = &mut scratch.kv;
966        assert!(kv.len < scratch.cap, "step35 MTP scratch overflow ({} >= {})", kv.len, scratch.cap);
967        let next_len = kv.len + 1;
968        let (off, t_kv) = if g.swa && next_len > g.window {
969            (next_len - g.window, g.window)
970        } else {
971            (0, next_len)
972        };
973        let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
974        e.append_kv_quantized(&k, &v0, &mut kv.k, &mut kv.v, write_row,
975                              kv.kv_dim_k, kv.kv_dim_v, kv.k_tok_bytes, kv.v_tok_bytes, false)?;
976        kv.len = next_len;
977        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
978        // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
979        // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
980        // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
981        // therefore live, not theoretical.
982        let physical = kv.physical_rows(off, off + t_kv)?;
983        let k_view = e.view_u8_range(&kv.k, physical.start * kv.k_tok_bytes,
984                                     physical.end * kv.k_tok_bytes);
985        let v_view = e.view_u8_range(&kv.v, physical.start * kv.v_tok_bytes,
986                                     physical.end * kv.v_tok_bytes);
987        let mut attn = e.uninit(nh * hd)?;
988        e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
989                          kv.k_tok_bytes, kv.v_tok_bytes, false)?;
990
991        let mut ag = e.uninit(nh * hd)?;
992        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
993        Ok(e.matmul(&fa.wo, &ag, 1)?)
994    }
995
996    /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
997    /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
998    /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
999    /// chain, and replays keep seeing KV growth through the device counter (no recapture).
1000    /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
1001    /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
1002    /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
1003    /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
1004    /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
1005    fn mtp_full_attn_dc(
1006        &self,
1007        e: &Engine,
1008        fa: &FullAttnLayer,
1009        h: &CudaSlice<f32>,
1010        pos_d: &CudaSlice<i32>,
1011        scratch: &mut MtpScratch,
1012        geom: Option<&crate::hybrid::DraftGeom>,
1013    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1014        let cfg = &self.cfg;
1015        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
1016        let geometry = cfg.full_attention_geometry_at(mtp_il);
1017        let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
1018        let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(geometry.n_head_kv as usize);
1019        let head_dim = geometry.head_dim_k as usize;
1020        let eps = cfg.rms_eps;
1021        let scale = geometry.attention_scale();
1022        let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
1023        let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
1024
1025        let (qf, mut k, v) =
1026            if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
1027                let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
1028                (
1029                    e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
1030                    e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
1031                    e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
1032                )
1033            } else {
1034                (
1035                    e.matmul(&fa.wq, h, 1)?,
1036                    e.matmul(&fa.wk, h, 1)?,
1037                    e.matmul(&fa.wv, h, 1)?,
1038                )
1039            };
1040        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
1041        let gated = geometry.attention_gate
1042            == memra_gguf::config::AttentionGateKind::FusedQ;
1043        let (mut q, gate) = if gated {
1044            let mut q = e.zeros(n_head * head_dim)?;
1045            let mut gate = e.zeros(n_head * head_dim)?;
1046            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
1047            (q, Some(gate))
1048        } else {
1049            (qf, None)
1050        };
1051
1052        let mut qn = e.zeros(n_head * head_dim)?;
1053        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
1054        q = qn;
1055        let mut kn = e.zeros(n_head_kv * head_dim)?;
1056        e.rms_norm(
1057            &k,
1058            fa.k_norm.float_data(),
1059            &mut kn,
1060            head_dim,
1061            n_head_kv,
1062            eps,
1063        )?;
1064        k = kn;
1065        let rope_dims = geometry.n_rot as usize;
1066        e.rope_neox(
1067            &mut q,
1068            pos_d,
1069            head_dim,
1070            rope_dims,
1071            n_head,
1072            1,
1073            geometry.rope_base,
1074            1.0,
1075        )?;
1076        e.rope_neox(
1077            &mut k,
1078            pos_d,
1079            head_dim,
1080            rope_dims,
1081            n_head_kv,
1082            1,
1083            geometry.rope_base,
1084            1.0,
1085        )?;
1086
1087        let kv = &mut scratch.kv;
1088        // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
1089        e.append_kv_quantized_dc(
1090            &k,
1091            &v,
1092            &mut kv.k,
1093            &mut kv.v,
1094            &kv.len_d,
1095            kv.kv_dim_k,
1096            kv.kv_dim_v,
1097            kv.k_tok_bytes,
1098            kv.v_tok_bytes,
1099            false,
1100        )?;
1101        e.inc_seqlen(&mut kv.len_d)?;
1102        // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
1103        // key range from the device counter.
1104        let k_view = e.view_u8(&kv.k, kv.k.len());
1105        let v_view = e.view_u8(&kv.v, kv.v.len());
1106        let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
1107        let mut attn = e.zeros(n_head * head_dim)?;
1108        e.fa_decode_dc(
1109            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
1110            scale, ktb, vtb, false,
1111        )?;
1112
1113        let attn_g = match &gate {
1114            Some(gate) => {
1115                let mut gsig = e.zeros(n_head * head_dim)?;
1116                e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
1117                let mut ag = e.zeros(n_head * head_dim)?;
1118                e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
1119                ag
1120            }
1121            None => attn,
1122        };
1123        Ok(e.matmul(&fa.wo, &attn_g, 1)?)
1124    }
1125
1126    /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
1127    /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
1128    /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
1129    /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
1130    /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
1131    /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
1132    /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
1133    /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
1134    #[allow(clippy::too_many_arguments)]
1135    fn mtp_kv_fill(
1136        &self,
1137        e: &Engine,
1138        mtp: &MtpHead,
1139        tokens: &[u32],
1140        h: &CudaSlice<f32>,
1141        pos0: usize,
1142        scratch: &mut MtpScratch,
1143        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1144    ) -> Result<(), Box<dyn std::error::Error>> {
1145        let cfg = &self.cfg;
1146        let n_embd = cfg.n_embd as usize;
1147        let eps = cfg.rms_eps;
1148        let t = tokens.len();
1149        assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
1150        assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
1151        let Mixer::Full(fa) = &mtp.mixer else {
1152            panic!("MTP block is full-attn in qwen35; linear MTP not supported")
1153        };
1154        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
1155        let pos_d = e.htod_i32(&pos_vec)?;
1156
1157        // ops A/1/2: embed + the two input norms, T-wide.
1158        let e_emb = match embd_dev {
1159            Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
1160            None => e.htod(&self.embd.gather(n_embd, tokens))?,
1161        };
1162        let mut e_norm = e.zeros(t * n_embd)?;
1163        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
1164        let mut h_norm = e.zeros(t * n_embd)?;
1165        e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
1166
1167        // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
1168        let mut concat = e.zeros(t * 2 * n_embd)?;
1169        for i in 0..t {
1170            e.copy_view_into(
1171                &mut concat,
1172                i * 2 * n_embd,
1173                &e_norm.slice(i * n_embd..(i + 1) * n_embd),
1174                n_embd,
1175            )?;
1176            e.copy_view_into(
1177                &mut concat,
1178                i * 2 * n_embd + n_embd,
1179                &h_norm.slice(i * n_embd..(i + 1) * n_embd),
1180                n_embd,
1181            )?;
1182        }
1183
1184        // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
1185        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
1186        let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
1187        let mut a_norm = e.zeros(t * di)?;
1188        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
1189
1190        // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
1191        // the fill only has to leave correct K/V rows behind for later chains to attend over.
1192        let n_head_kv = mtp
1193            .geom
1194            .as_ref()
1195            .map(|g| g.n_head_kv)
1196            .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
1197            .unwrap_or_else(|| {
1198                let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
1199                cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
1200            });
1201        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
1202        let geometry = cfg.full_attention_geometry_at(mtp_il);
1203        let head_dim = geometry.head_dim_k as usize;
1204        let mut k = e.matmul(&fa.wk, &a_norm, t)?;
1205        let v = e.matmul(&fa.wv, &a_norm, t)?;
1206        let mut kn = e.zeros(t * n_head_kv * head_dim)?;
1207        e.rms_norm(
1208            &k,
1209            fa.k_norm.float_data(),
1210            &mut kn,
1211            head_dim,
1212            n_head_kv * t,
1213            eps,
1214        )?;
1215        k = kn;
1216        // step35: rotary width AND base are per-layer, and the MTP block's values come from the
1217        // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
1218        // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
1219        // writes K rows the attention arm then re-derives at a different theta: correct-looking
1220        // output with dead acceptance, invisible to the exactness gates.
1221        let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
1222            Some(s) => (
1223                s.n_rot,
1224                s.rope_base,
1225                if s.swa { None } else {
1226                    self.step35_aux.as_ref().and_then(|a| a.rope_freqs.as_ref())
1227                },
1228            ),
1229            None => (geometry.n_rot as usize, geometry.rope_base, None),
1230        };
1231        match ff {
1232            Some(f) => e.rope_neox_ff(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, t,
1233                                      rope_base, 1.0, f)?,
1234            None => e.rope_neox(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, t,
1235                                rope_base, 1.0)?,
1236        }
1237
1238        let kv = &mut scratch.kv;
1239        // Match the trunk prime contract: a chunk may need the aligned window immediately before
1240        // its first row, so preserve that prefix when the physical tail rebases at wrap.
1241        let retain_from = kv
1242            .ring
1243            .as_ref()
1244            .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
1245            .unwrap_or(0);
1246        let write_row = e.prepare_kv_append(kv, retain_from, t)?;
1247        for i in 0..t {
1248            let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
1249            let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
1250            e.append_kv_quantized_view(
1251                &k_row,
1252                &v_row,
1253                &mut kv.k,
1254                &mut kv.v,
1255                write_row + i,
1256                kv.kv_dim_k,
1257                kv.kv_dim_v,
1258                kv.k_tok_bytes,
1259                kv.v_tok_bytes,
1260                false,
1261            )?;
1262        }
1263        kv.len = pos0 + t;
1264        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
1265        Ok(())
1266    }
1267
1268    /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
1269    /// every varying input device-resident —
1270    ///   - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
1271    ///     so the chain feeds itself; the host reads the same 4 bytes for the draft list),
1272    ///   - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
1273    ///   - rope pos from the persistent `pos_d` counter (inc'd in-graph),
1274    ///   - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
1275    /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
1276    /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
1277    /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
1278    /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
1279    /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
1280    /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
1281    /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
1282    /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
1283    /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
1284    /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
1285    /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
1286    /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
1287    /// seed/temp are capture-time constants (fixed per generate call, like p_min).
1288    #[allow(clippy::too_many_arguments)]
1289    fn mtp_head_forward_cap(
1290        &self,
1291        e: &Engine,
1292        mtp: &MtpHead,
1293        tok_d: &mut CudaSlice<u32>,
1294        pos_d: &mut CudaSlice<i32>,
1295        h_seed_d: &mut CudaSlice<f32>,
1296        p_d: &mut CudaSlice<f32>,
1297        scratch: &mut MtpScratch,
1298        with_prob: bool,
1299        with_head: bool,
1300        embd_gpu: &CudaSlice<u8>,
1301        embd_qt: i32,
1302        embd_rb: usize,
1303        d_vocab: usize,
1304        sampled_cap: Option<(
1305            &mut CudaSlice<u32>,
1306            &mut CudaSlice<f32>,
1307            &mut CudaSlice<f32>,
1308            u64,
1309            f32,
1310        )>,
1311        stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
1312        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
1313        // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
1314        // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
1315        // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
1316        // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
1317        mask_cap: Option<(&CudaSlice<u32>, usize)>,
1318    ) -> Result<(), Box<dyn std::error::Error>> {
1319        let cfg = &self.cfg;
1320        let n_embd = cfg.n_embd as usize;
1321        // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
1322        // whose device-counter key bound always starts at row 0 — it cannot express this block's
1323        // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
1324        // persistent scratch passes 512 rows. Nothing is lost today: `graph_draft` also requires
1325        // `trunk_dense`, and step35's trunk is a 288-expert MoE, so the eager chain
1326        // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
1327        // panic) is what the two capture sites and the round-stream capture already handle by
1328        // degrading to eager / stream-off.
1329        if mtp.step35.is_some() {
1330            return Err("step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
1331                        block's SWA view offset; same root cause as the dc decode refusal) — the \
1332                        eager draft chain serves this arch".into());
1333        }
1334        // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
1335        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
1336        let eps = cfg.rms_eps;
1337        let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
1338        let mut e_norm = e.zeros(n_embd)?;
1339        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
1340        let mut h_norm = e.zeros(n_embd)?;
1341        e.rms_norm(
1342            &*h_seed_d,
1343            mtp.hnorm.float_data(),
1344            &mut h_norm,
1345            n_embd,
1346            1,
1347            eps,
1348        )?;
1349        let mut concat = e.zeros(2 * n_embd)?;
1350        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
1351        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
1352        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
1353        let mut a_norm = e.zeros(di)?;
1354        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
1355        let attn_out = match &mtp.mixer {
1356            Mixer::Full(fa) => {
1357                self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
1358            }
1359            Mixer::Linear(_) => {
1360                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
1361            }
1362            Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1363        };
1364        let mut x1 = e.zeros(di)?;
1365        e.add(&inp_sa, &attn_out, &mut x1, di)?;
1366        let mut z = e.zeros(di)?;
1367        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
1368        let ffn_out = match &mtp.ffn {
1369            crate::hybrid::Ffn::Dense {
1370                ffn_gate,
1371                ffn_up,
1372                ffn_down,
1373            } => {
1374                let n_ff = ffn_gate.out_features();
1375                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
1376                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
1377                    (
1378                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
1379                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
1380                    )
1381                } else {
1382                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
1383                };
1384                let mut act = e.zeros(n_ff)?;
1385                Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
1386                e.matmul(ffn_down, &act, 1)?
1387            }
1388            // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
1389            // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
1390            // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
1391            // error arm degrades the caller to eager/stream-off.
1392            crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
1393                self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
1394            }
1395            crate::hybrid::Ffn::Moe(_) => {
1396                return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into())
1397            }
1398        };
1399        let mut h_inner = e.zeros(di)?;
1400        e.add(&x1, &ffn_out, &mut h_inner, di)?;
1401        // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
1402        let h_nextn = match mtp.geom.as_ref() {
1403            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
1404            None => h_inner,
1405        };
1406        // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
1407        let final_h = if with_head || spec_hpost() {
1408            let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
1409            let mut fh = e.zeros(n_embd)?;
1410            e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
1411            Some(fh)
1412        } else {
1413            None
1414        };
1415        if with_head {
1416            let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
1417            let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
1418            // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
1419            // before the argmax — proposals become legal by construction. Contents-only
1420            // per-replay upload keeps the capture valid.
1421            if let Some((mask_d, mw)) = mask_cap {
1422                e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
1423            }
1424            if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
1425                // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
1426                // own buffer is pool-recycled after the capture body returns, so it can't be the
1427                // retention target), bump the device event counter, gumbel-perturb reading it,
1428                // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
1429                e.copy_into(q_out_d, 0, &logits, d_vocab)?;
1430                e.sctr_inc(ctr_d)?;
1431                e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
1432                e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
1433                // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
1434                // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
1435                if with_prob {
1436                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
1437                }
1438            } else {
1439                // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
1440                e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
1441                // p-min under a draft mask reads the MASKED row: confidence relative to the
1442                // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
1443                // is the right semantics for "does the drafter know what comes next here" and
1444                // the same row the pick came from. Draft-quality only — verify arbitrates.
1445                if with_prob {
1446                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
1447                }
1448            }
1449        }
1450        // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
1451        // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
1452        if let Some((out, slot, d2t)) = stream_pack {
1453            e.pack_tok_p(tok_d, p_d, out, slot)?;
1454            if let Some(map) = d2t {
1455                e.tok_map_u32(tok_d, map)?;
1456            }
1457        }
1458        // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
1459        if spec_hpost() {
1460            e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
1461        } else {
1462            e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
1463        }
1464        // advance the draft rope position in-graph.
1465        e.inc_seqlen(pos_d)?;
1466        Ok(())
1467    }
1468
1469    /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
1470    /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
1471    /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
1472    /// Advances `cache.pos` by T.
1473    pub fn decode_step_t(&self, e: &Engine, tokens: &[u32], pos0: usize, cache: &mut Cache)
1474                         -> Result<Vec<f32>, Box<dyn std::error::Error>> {
1475        if self.is_gemma4_e4b() {
1476            return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
1477        }
1478        if self.cfg.gemma4.is_some() {
1479            return self.gemma4_decode_step_t(e, tokens, pos0, cache);
1480        }
1481        Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
1482    }
1483
1484    /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
1485    /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
1486    /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
1487    /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
1488    pub fn decode_step_t_h(
1489        &self,
1490        e: &Engine,
1491        tokens: &[u32],
1492        pos0: usize,
1493        cache: &mut Cache,
1494    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1495        self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
1496    }
1497
1498    /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
1499    /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
1500    pub fn decode_step_t_h_emb(
1501        &self,
1502        e: &Engine,
1503        tokens: &[u32],
1504        pos0: usize,
1505        cache: &mut Cache,
1506        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1507    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1508        let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
1509        Ok((e.dtoh(&logits_d)?, h_seed))
1510    }
1511
1512    /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
1513    /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
1514    /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
1515    /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
1516    /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
1517    pub fn decode_step_t_h_emb_dev(
1518        &self,
1519        e: &Engine,
1520        tokens: &[u32],
1521        pos0: usize,
1522        cache: &mut Cache,
1523        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1524    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1525        let n_embd = self.cfg.n_embd as usize;
1526        let t = tokens.len();
1527        let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
1528        // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
1529        let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
1530        e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
1531        Ok((logits, hs))
1532    }
1533
1534    /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
1535    /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
1536    /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
1537    /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
1538    /// retains/copies — they never change what any kernel computes).
1539    fn decode_step_t_core(
1540        &self,
1541        e: &Engine,
1542        tokens: &[u32],
1543        pos0: usize,
1544        cache: &mut Cache,
1545        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1546        mut ckpt: Option<&mut VerifyCkpt>,
1547    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1548        self.decode_step_t_core_stream(e, tokens, pos0, cache, embd_dev, ckpt.take(), None)
1549    }
1550
1551    /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
1552    /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
1553    /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
1554    /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
1555    /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
1556    #[allow(clippy::too_many_arguments)]
1557    fn decode_step_t_core_stream(
1558        &self,
1559        e: &Engine,
1560        tokens: &[u32],
1561        pos0: usize,
1562        cache: &mut Cache,
1563        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1564        mut ckpt: Option<&mut VerifyCkpt>,
1565        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
1566    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1567        // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
1568        // exactly as the eager and batched steps do. This is the single funnel every verify
1569        // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
1570        // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
1571        // is untouched.
1572        //
1573        // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
1574        // walk was unsplit on one stream and a sharded cross-device placement peer-read every
1575        // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
1576        // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
1577        // or a placement whose PpNRt fails to build — so a config that would still walk the
1578        // whole trunk on one stream refuses instead of regressing 28x.
1579        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
1580            if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
1581                return self.decode_step_t_core_ppn(
1582                    e, tokens, pos0, cache, embd_dev, ckpt.take(), stream, &fence,
1583                );
1584            }
1585        }
1586        crate::pp::refuse_unsplit_if_remote(
1587            "decode_step_t (spec verify)",
1588            "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
1589             split (decode_step_t_core_ppn); or run spec on one device",
1590        )?;
1591        let cfg = &self.cfg;
1592        let n_embd = cfg.n_embd as usize;
1593        let eps = cfg.rms_eps;
1594        let t = tokens.len();
1595        let pos_d = match stream {
1596            Some((_, ctr)) => {
1597                let mut p = e.alloc_uninit::<i32>(t)?;
1598                e.pos_iota(ctr, &mut p, t)?;
1599                p
1600            }
1601            None => {
1602                let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
1603                e.htod_i32(&pos_vec)?
1604            }
1605        };
1606
1607        // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
1608        let x = match (stream, embd_dev) {
1609            (Some((vtok, _)), Some((g, qt, rb))) => {
1610                e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
1611            }
1612            (None, Some((g, qt, rb))) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
1613            _ => e.htod(&self.embd.gather(n_embd, tokens))?,
1614        };
1615
1616        // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
1617        // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
1618        // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
1619        let x = self.verify_layers(
1620            e, x, 0, self.layers.len(), &pos_d, t, cache, ckpt.take(), stream,
1621        )?;
1622
1623        let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
1624        e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1625        let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
1626        // stream: the device pos counter owns position; host mirror reconciles at drain.
1627        if stream.is_none() {
1628            cache.pos += t;
1629        }
1630        // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
1631        Ok((logits, if spec_hpost() { hn } else { x }))
1632    }
1633
1634    /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
1635    /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
1636    /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
1637    /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
1638    /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
1639    /// the payload).
1640    ///
1641    /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
1642    /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
1643    /// receipts):
1644    ///
1645    /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
1646    ///    (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
1647    ///    DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
1648    ///    (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
1649    ///    s>0 its own Engine even on the primary device; honouring it here is what scopes the
1650    ///    pools. The verify path allocates MORE of that scratch than eager decode does (FA at
1651    ///    m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
1652    ///
1653    /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
1654    ///    buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
1655    ///    stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
1656    ///    read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
1657    ///    stage derives the identical iota, and each stage's own output buffer is stream-local.
1658    ///
1659    /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
1660    ///    sharded loader leaves the table with stage 0 by construction).
1661    ///
1662    /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
1663    ///    both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
1664    ///    n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
1665    ///    model, every round.
1666    ///
1667    /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
1668    /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
1669    /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
1670    /// through the primary context by UVA — the same read the batched serving epilogue's
1671    /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
1672    /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
1673    ///
1674    /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
1675    /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
1676    /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
1677    ///
1678    /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
1679    /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
1680    /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
1681    /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
1682    /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
1683    /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
1684    /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
1685    /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
1686    #[allow(clippy::too_many_arguments)]
1687    fn decode_step_t_core_ppn(
1688        &self,
1689        e: &Engine,
1690        tokens: &[u32],
1691        pos0: usize,
1692        cache: &mut Cache,
1693        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1694        mut ckpt: Option<&mut VerifyCkpt>,
1695        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
1696        fence: &[usize],
1697    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1698        assert!(
1699            !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
1700            "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
1701             (the gemma4 arms have their own decode_step_t twins)"
1702        );
1703        let rt = crate::pp::PpNRt::get(e)?;
1704        let n_st = fence.len() - 1;
1705        assert_eq!(
1706            rt.n_stages(), n_st,
1707            "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
1708        );
1709        let n_embd = self.cfg.n_embd as usize;
1710        let eps = self.cfg.rms_eps;
1711        let t = tokens.len();
1712        let payload = t * n_embd;
1713        // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
1714        // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
1715        // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
1716        // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
1717        // stage stream and the wait would self-order into a no-op.
1718        let caller_stream = e.stream();
1719        // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
1720        // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
1721        // the primary stream still holds queued reads of them — with event tracking elided,
1722        // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
1723        // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
1724        // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
1725        // stage stream behind the caller before enqueueing new stage work.
1726        rt.fence_stages_behind(&caller_stream)?;
1727
1728        // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
1729        // stream mode each stage's own `pos_iota` over the shared read-only device counter.
1730        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
1731            match stream {
1732                Some((_, ctr)) => {
1733                    let mut p = es.alloc_uninit::<i32>(t)?;
1734                    es.pos_iota(ctr, &mut p, t)?;
1735                    Ok(p)
1736                }
1737                None => {
1738                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
1739                    es.htod_i32(&pos_vec)
1740                }
1741            }
1742        };
1743
1744        // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
1745        let mut slot = {
1746            let _st0 = rt.enter(0);
1747            let e0 = rt.engine(0, e);
1748            let pos_d = stage_pos(e0)?;
1749            let x = match (stream, embd_dev) {
1750                (Some((vtok, _)), Some((g, qt, rb))) => {
1751                    e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
1752                }
1753                (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
1754                _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
1755            };
1756            let x = self.verify_layers(
1757                e0, x, fence[0], fence[1], &pos_d, t, cache, ckpt.as_deref_mut(), stream,
1758            )?;
1759            rt.tx(0, &x, payload)?
1760            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
1761        };
1762
1763        // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
1764        for s in 1..n_st - 1 {
1765            let _st = rt.enter(s);
1766            let es = rt.engine(s, e);
1767            let pos_d = stage_pos(es)?;
1768            let x = rt.rx(s - 1, slot, payload)?;
1769            let x = self.verify_layers(
1770                es, x, fence[s], fence[s + 1], &pos_d, t, cache, ckpt.as_deref_mut(), stream,
1771            )?;
1772            slot = rt.tx(s, &x, payload)?;
1773        }
1774
1775        // ---- LAST STAGE: RX + final range + output_norm + lm head ----
1776        let _stl = rt.enter(n_st - 1);
1777        let el = rt.engine(n_st - 1, e);
1778        let pos_d = stage_pos(el)?;
1779        let x = rt.rx(n_st - 2, slot, payload)?;
1780        let x = self.verify_layers(
1781            el, x, fence[n_st - 1], fence[n_st], &pos_d, t, cache, ckpt.as_deref_mut(), stream,
1782        )?;
1783
1784        let mut hn = vbuf(el, payload)?; // fully written by rms_norm_decode
1785        el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1786        let logits = el.matmul_decode_exact(&self.output, &hn, t)?;
1787        // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
1788        // stream. Order the caller's stream behind that work before the buffers escape this
1789        // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
1790        // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
1791        // the following arm's KV in the same process).
1792        rt.publish_to(n_st - 1, &caller_stream)?;
1793        // stream: the device pos counter owns position; host mirror reconciles at drain.
1794        if stream.is_none() {
1795            cache.pos += t;
1796        }
1797        Ok((logits, if spec_hpost() { hn } else { x }))
1798    }
1799
1800    /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
1801    /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
1802    /// carried in from outside the range) and exits with the range's final residual materialized
1803    /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
1804    /// instead of one.
1805    ///
1806    /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
1807    /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
1808    /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
1809    /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
1810    /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
1811    /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
1812    /// code — there is no "split version" of the verify math.
1813    ///
1814    /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
1815    /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
1816    /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
1817    /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
1818    #[allow(clippy::too_many_arguments)]
1819    fn verify_layers(
1820        &self,
1821        e: &Engine,
1822        mut x: CudaSlice<f32>,
1823        lo: usize,
1824        hi: usize,
1825        pos_d: &CudaSlice<i32>,
1826        t: usize,
1827        cache: &mut Cache,
1828        mut ckpt: Option<&mut VerifyCkpt>,
1829        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
1830    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1831        let n_embd = self.cfg.n_embd as usize;
1832        let eps = self.cfg.rms_eps;
1833        // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
1834        // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
1835        // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
1836        // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
1837        // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
1838        // residual the next layer needs) as its `res` output. Falls back to the separate add
1839        // when the next layer is off the fused-q8 path.
1840        let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
1841        for il in lo..hi {
1842            let layer = &self.layers[il];
1843            // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
1844            // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
1845            // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
1846            // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
1847            // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
1848            // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
1849            // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
1850            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
1851            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
1852            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
1853            // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
1854            // projections only; Linear mixer: the batched arm — the per-column fallback needs
1855            // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
1856            // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
1857            // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
1858            // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
1859            // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
1860            // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
1861            // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
1862            // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
1863            let lin_q8_only = match &layer.mixer {
1864                Mixer::Linear(la) => {
1865                    (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
1866                }
1867                Mixer::Full(_) if self.cfg.step35.is_some() => false,
1868                _ => true,
1869            };
1870            // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
1871            // a non-fused layer still performs the residual add.
1872            let taken = pending.take();
1873            let (h, h_q8) = if norm_fused && lin_q8_only {
1874                let pair = match taken {
1875                    // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
1876                    // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
1877                    Some((x1p, f1p)) => {
1878                        let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
1879                        let p = e.add_rms_norm_q8_1(
1880                            &x1p, &f1p, layer.attn_norm.float_data(), &mut x2, n_embd, t, eps,
1881                        )?;
1882                        x = x2;
1883                        p
1884                    }
1885                    None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
1886                };
1887                (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
1888            } else {
1889                if let Some((x1p, f1p)) = taken {
1890                    let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
1891                    e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
1892                    x = x2;
1893                }
1894                let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
1895                if norm_fused {
1896                    e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
1897                } else {
1898                    e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
1899                }
1900                (h, None)
1901            };
1902            let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
1903
1904            let mixed = match &layer.mixer {
1905                Mixer::Full(fa) => {
1906                    self.full_attn_verify(e, fa, &h, h_q8_ref, pos_d, t, cache, il,
1907                                          stream.map(|(_, c)| c))?
1908                }
1909                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1910                Mixer::Linear(la) => {
1911                    // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
1912                    // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
1913                    // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
1914                    // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
1915                    // chained T=1 steps (bit-identical). Falls back to the sequential per-column
1916                    // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
1917                    // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
1918                    // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
1919                    // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
1920                    // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
1921                    // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
1922                    if (t >= 3 || (t == 2 && spec_m2()))
1923                        && mixer_fast
1924                        && e.uses_q8_1_fast(&la.ssm_out)
1925                    {
1926                        let want = ckpt.is_some();
1927                        let (out, stash) =
1928                            self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
1929                        if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
1930                            ck.gdn[il] = Some(st);
1931                        }
1932                        out
1933                    } else {
1934                        let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
1935                        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
1936                            if ckpt.is_some() && t >= 2 {
1937                                Some(Vec::with_capacity(t - 1))
1938                            } else {
1939                                None
1940                            };
1941                        for col in 0..t {
1942                            let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
1943                            let src = h.slice(col * n_embd..(col + 1) * n_embd);
1944                            e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
1945                            let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
1946                            e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
1947                            // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
1948                            // (pure dtod — cannot change any computed value). Last column skipped:
1949                            // rebuild targets are j <= t-1 columns.
1950                            if let Some(cs) = col_states.as_mut() {
1951                                if col + 1 < t {
1952                                    let rl = cache.recur[il].as_ref().unwrap();
1953                                    cs.push((
1954                                        e.clone_dtod(&rl.conv_state)?,
1955                                        e.clone_dtod(&rl.ssm_state)?,
1956                                    ));
1957                                }
1958                            }
1959                        }
1960                        if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
1961                            // ReplaySSM-assessment instrumentation (2026-07-30): the
1962                            // per-column clones are the only true state snapshots left in
1963                            // the verify (the batched path stashes INPUTS and replays).
1964                            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
1965                                static ONCE: std::sync::Once = std::sync::Once::new();
1966                                let bytes: usize = cs.iter()
1967                                    .map(|(c, s)| (c.len() + s.len()) * 4).sum();
1968                                ONCE.call_once(|| eprintln!(
1969                                    "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
1970                                    cs.len(), bytes as f64 / 1e6));
1971                            }
1972                            ck.cols[il] = Some(cs);
1973                        }
1974                        out
1975                    }
1976                }
1977            };
1978
1979            // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
1980            // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
1981            // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
1982            let ffn_fuse = match &layer.ffn {
1983                crate::hybrid::Ffn::Dense {
1984                    ffn_gate, ffn_up, ..
1985                } => {
1986                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
1987                        && e.uses_q8_1_fast(ffn_gate)
1988                        && e.uses_q8_1_fast(ffn_up)
1989                }
1990                crate::hybrid::Ffn::Moe(_) => false,
1991            };
1992            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
1993            // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
1994            // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
1995            // per-row m=1 program; kernel-check pins bit-identity vs the unfused
1996            // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
1997            // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
1998            // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
1999            // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
2000            // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
2001            // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
2002            // mirror decode's dispatch or spec self-consistency fails.
2003            let dense_lim = self.cfg.clamp_shexp_at(il as u32);
2004            let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
2005            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
2006            let mut z = e.zeros(0)?; // replaced below on the unfused arms
2007            let z_q8 = if fuse_q8 {
2008                Some(e.add_rms_norm_q8_1(
2009                    &x,
2010                    &mixed,
2011                    layer.post_attn_norm.float_data(),
2012                    &mut x1,
2013                    n_embd,
2014                    t,
2015                    eps,
2016                )?)
2017            } else {
2018                let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
2019                if ffn_fuse {
2020                    e.add(&x, &mixed, &mut x1, t * n_embd)?;
2021                    e.rms_norm_decode(
2022                        &x1,
2023                        layer.post_attn_norm.float_data(),
2024                        &mut zf,
2025                        n_embd,
2026                        t,
2027                        eps,
2028                    )?;
2029                } else {
2030                    e.add_rms_norm(
2031                        &x,
2032                        &mixed,
2033                        layer.post_attn_norm.float_data(),
2034                        &mut x1,
2035                        &mut zf,
2036                        n_embd,
2037                        t,
2038                        eps,
2039                    )?;
2040                }
2041                z = zf;
2042                None
2043            };
2044            // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
2045            // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
2046            // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
2047            let ffn_out = match &layer.ffn {
2048                crate::hybrid::Ffn::Dense {
2049                    ffn_gate,
2050                    ffn_up,
2051                    ffn_down,
2052                } => {
2053                    let n_ff = ffn_gate.out_features();
2054                    if let Some((zq, zd)) = z_q8.as_ref() {
2055                        // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
2056                        // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
2057                        // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
2058                        // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
2059                        // scale_inplace store, value-exact) — the exact m=1 decode epilogue
2060                        // structure at nrows=t.
2061                        let pair = match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
2062                            Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
2063                            None => None,
2064                        };
2065                        let (gate, gs, up, us) = match pair {
2066                            Some(x4) => x4,
2067                            None => (
2068                                e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
2069                                1.0, // scale already applied inside _pre
2070                                e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
2071                                1.0,
2072                            ),
2073                        };
2074                        if e.uses_q8_1_fast(ffn_down) {
2075                            let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
2076                            e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
2077                        } else {
2078                            let mut act = vbuf(e, t * n_ff)?;
2079                            e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
2080                            e.matmul_decode_exact(ffn_down, &act, t)?
2081                        }
2082                    } else {
2083                        // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
2084                        // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
2085                        // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
2086                        // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
2087                        // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
2088                        let (gate, up) = match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
2089                            Some(pair) => pair,
2090                            None => (
2091                                e.matmul_decode_exact(ffn_gate, &z, t)?,
2092                                e.matmul_decode_exact(ffn_up, &z, t)?,
2093                            ),
2094                        };
2095                        let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
2096                        Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0, dense_lim,
2097                                          &mut act, t * n_ff)?;
2098                        e.matmul_decode_exact(ffn_down, &act, t)?
2099                    }
2100                }
2101                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
2102            };
2103            // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
2104            // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
2105            // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
2106            pending = Some((x1, ffn_out));
2107        }
2108        // RANGE's final add (no next norm INSIDE the range to fuse with; for the
2109        // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
2110        if let Some((x1p, f1p)) = pending.take() {
2111            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
2112            e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
2113            x = x2;
2114        }
2115        Ok(x)
2116    }
2117    /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
2118    /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
2119    /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
2120    /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
2121    /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
2122    /// ssm state exactly like T sequential decode steps.
2123    /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
2124    /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
2125    #[allow(clippy::too_many_arguments)]
2126    fn linear_attn_verify_t(
2127        &self,
2128        e: &Engine,
2129        la: &LinearAttnLayer,
2130        h: &CudaSlice<f32>,
2131        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2132        t: usize,
2133        cache: &mut Cache,
2134        il: usize,
2135        want_stash: bool,
2136    ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
2137        let cfg = &self.cfg;
2138        let ssm = cfg.ssm.as_ref().unwrap();
2139        let d_state = ssm.state_size as usize;
2140        let num_k = ssm.group_count as usize;
2141        let num_v = ssm.time_step_rank as usize;
2142        let d_conv = ssm.conv_kernel as usize;
2143        let key_dim = d_state * num_k;
2144        let conv_dim = key_dim * 2 + d_state * num_v;
2145        let eps = cfg.rms_eps;
2146        let scale = 1.0 / (d_state as f32).sqrt();
2147
2148        // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
2149        // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
2150        // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
2151        // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
2152        // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
2153        // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
2154        // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
2155        // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
2156        // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
2157        // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
2158        // Bit-identical per (tensor,token,row) — see spec_fused_t().
2159        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
2160        // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
2161        // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
2162        // and feeds every projection; the caller guaranteed all four input projections are
2163        // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
2164        let h_q8_t = if h_q8.is_none()
2165            && spec_fused_t()
2166            && (2..=4).contains(&t)
2167            && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
2168                || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
2169        {
2170            Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
2171        } else {
2172            None
2173        };
2174        // one view: the caller's fused-norm q8 or this fn's own shared quantize.
2175        let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
2176            h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
2177        let (qkv_mixed, z) = {
2178            let mut fused = None;
2179            if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
2180                let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
2181                fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
2182            } else if let Some((hq, hd)) = hq8_any {
2183                if spec_fused_t() && (2..=4).contains(&t) {
2184                    fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
2185                }
2186            }
2187            match (fused, hq8_any) {
2188                (Some(pair), _) => pair,
2189                (None, Some((hq, hd))) if h_q8.is_some() => (
2190                    e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
2191                    e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
2192                ),
2193                (None, _) => (
2194                    e.matmul_decode_exact(&la.wqkv, h, t)?,
2195                    e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
2196                ),
2197            }
2198        };
2199        // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
2200        // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
2201        // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
2202        // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
2203        let (beta_raw, alpha) = if t == 1 {
2204            let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
2205            match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
2206                Some(((mut b, bs), (mut a, as_))) => {
2207                    if bs != 1.0 {
2208                        e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
2209                    }
2210                    if as_ != 1.0 {
2211                        e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
2212                    }
2213                    (b, a)
2214                }
2215                // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
2216                // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
2217                // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
2218                None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
2219                    Some((b, a)) => (b, a),
2220                    None => (
2221                        e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
2222                        e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
2223                    ),
2224                },
2225            }
2226        } else {
2227            // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
2228            // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
2229            let mut fused = None;
2230            if let Some((hq, hd)) = hq8_any {
2231                if spec_fused_t() && (2..=4).contains(&t) {
2232                    fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
2233                }
2234            }
2235            match (fused, hq8_any) {
2236                (Some(pair), _) => pair,
2237                (None, Some((hq, hd))) if h_q8.is_some() => (
2238                    e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
2239                    e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
2240                ),
2241                (None, _) => (
2242                    e.matmul_decode_exact(&la.ssm_beta, h, t)?,
2243                    e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
2244                ),
2245            }
2246        };
2247
2248        // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
2249        // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
2250        let rl = cache.recur[il].as_mut().unwrap();
2251        let mut conv_out = e.uninit(conv_dim * t)?;
2252        e.ssm_conv1d_tm_state(
2253            &qkv_mixed,
2254            &mut rl.conv_state,
2255            la.ssm_conv1d.float_data(),
2256            &mut conv_out,
2257            conv_dim,
2258            t,
2259            d_conv,
2260        )?;
2261
2262        // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
2263        let mut q_g = e.uninit(d_state * num_v * t)?;
2264        let mut k_g = e.uninit(d_state * num_v * t)?;
2265        let mut v_g = e.uninit(d_state * num_v * t)?;
2266        e.qkv_to_gdn_repack(
2267            &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
2268        )?;
2269        let mut q_l2 = e.uninit(d_state * num_v * t)?;
2270        e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
2271        let mut k_l2 = e.uninit(d_state * num_v * t)?;
2272        e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
2273        let mut beta = e.uninit(t * num_v)?;
2274        e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
2275        let mut g_log = e.uninit(t * num_v)?;
2276        e.gdn_glog(
2277            &alpha,
2278            la.ssm_dt.float_data(),
2279            la.ssm_a.float_data(),
2280            &mut g_log,
2281            num_v,
2282            t,
2283        )?;
2284
2285        // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
2286        // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
2287        let mut o = e.uninit(d_state * num_v * t)?;
2288        {
2289            let crate::cache::RecurLayer {
2290                ssm_state,
2291                ssm_state_alt,
2292                ..
2293            } = rl;
2294            e.gdn_scan_s128(
2295                &q_l2,
2296                &k_l2,
2297                &v_g,
2298                &g_log,
2299                &beta,
2300                ssm_state,
2301                ssm_state_alt,
2302                &mut o,
2303                num_v,
2304                t,
2305                scale,
2306            )?;
2307        }
2308        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2309
2310        // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
2311        // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
2312        // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
2313        // T-wide launch is the per-row program; kernel-check pins bit-identity vs
2314        // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
2315        // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
2316        let out = if e.uses_q8_1_fast(&la.ssm_out) {
2317            let (gq, gd) =
2318                e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
2319            e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
2320        } else {
2321            let mut gn = e.uninit(d_state * num_v * t)?;
2322            e.gated_rmsnorm(
2323                &o,
2324                la.ssm_norm.float_data(),
2325                &z,
2326                &mut gn,
2327                d_state,
2328                num_v * t,
2329                eps,
2330            )?;
2331            // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
2332            // would fall to dp4a with a different FP reduction order — same class of bug as
2333            // the input projs).
2334            e.matmul_decode_exact(&la.ssm_out, &gn, t)?
2335        };
2336        let stash = if want_stash {
2337            Some(GdnStash {
2338                qkv_mixed,
2339                q_l2,
2340                k_l2,
2341                v_g,
2342                g_log,
2343                beta,
2344            })
2345        } else {
2346            None
2347        };
2348        Ok((out, stash))
2349    }
2350
2351    /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
2352    /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
2353    /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
2354    ///   are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
2355    ///   verify-probe gates), so keeping them == replaying them.
2356    /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
2357    ///   columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
2358    ///   snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
2359    ///   registers and writes it once at the end, so iterations 0..j-1 are independent of T:
2360    ///   bit-identical to the verify's own state after j tokens == the eager chain state.
2361    /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
2362    /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
2363    fn commit_verified_prefix(
2364        &self,
2365        e: &Engine,
2366        cache: &mut Cache,
2367        snap: &crate::cache::CacheSnapshot,
2368        ckpt: &VerifyCkpt,
2369        j: usize,
2370        kv_lens_done: bool,
2371        dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
2372    ) -> Result<(), Box<dyn std::error::Error>> {
2373        let cfg = &self.cfg;
2374        let ssm = cfg.ssm.as_ref().unwrap();
2375        let d_state = ssm.state_size as usize;
2376        let num_k = ssm.group_count as usize;
2377        let num_v = ssm.time_step_rank as usize;
2378        let d_conv = ssm.conv_kernel as usize;
2379        let conv_dim = d_state * num_k * 2 + d_state * num_v;
2380        let scale = 1.0 / (d_state as f32).sqrt();
2381        for il in 0..self.layers.len() {
2382            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
2383                kvl.len = saved + j;
2384                // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
2385                if !kv_lens_done {
2386                    e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2387                }
2388            }
2389            if let Some(rl) = cache.recur[il].as_mut() {
2390                if let Some(st) = &ckpt.gdn[il] {
2391                    let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
2392                    let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
2393                    if let Some((acc, base, t_v)) = dev_j {
2394                        // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
2395                        e.ssm_conv_ring_rebuild_dc(
2396                            &st.qkv_mixed,
2397                            ring_old,
2398                            &mut rl.conv_state,
2399                            conv_dim,
2400                            acc,
2401                            base,
2402                            t_v,
2403                            d_conv,
2404                        )?;
2405                        let mut o = e.uninit(d_state * num_v * j.max(1))?;
2406                        e.gdn_scan_s128_dc(
2407                            &st.q_l2,
2408                            &st.k_l2,
2409                            &st.v_g,
2410                            &st.g_log,
2411                            &st.beta,
2412                            state_in,
2413                            &mut rl.ssm_state,
2414                            &mut o,
2415                            num_v,
2416                            acc,
2417                            base,
2418                            t_v,
2419                            scale,
2420                        )?;
2421                    } else {
2422                        e.ssm_conv_ring_rebuild(
2423                            &st.qkv_mixed,
2424                            ring_old,
2425                            &mut rl.conv_state,
2426                            conv_dim,
2427                            j,
2428                            d_conv,
2429                        )?;
2430                        let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
2431                        e.gdn_scan_s128(
2432                            &st.q_l2,
2433                            &st.k_l2,
2434                            &st.v_g,
2435                            &st.g_log,
2436                            &st.beta,
2437                            state_in,
2438                            &mut rl.ssm_state,
2439                            &mut o,
2440                            num_v,
2441                            j,
2442                            scale,
2443                        )?;
2444                    }
2445                } else if let Some(cols) = &ckpt.cols[il] {
2446                    let (c, s) = &cols[j - 1];
2447                    e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
2448                    e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
2449                } else {
2450                    return Err(
2451                        "commit_verified_prefix: verify ckpt missing for linear layer".into(),
2452                    );
2453                }
2454            }
2455        }
2456        cache.pos = snap.pos + j;
2457        Ok(())
2458    }
2459
2460    /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
2461    /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
2462    fn commit_verified_prefix_stream(
2463        &self,
2464        e: &Engine,
2465        cache: &mut Cache,
2466        snap: &crate::cache::CacheSnapshot,
2467        ckpt: &VerifyCkpt,
2468        acc: &CudaSlice<u32>,
2469        base: usize,
2470        t_v: usize,
2471    ) -> Result<(), Box<dyn std::error::Error>> {
2472        let cfg = &self.cfg;
2473        let ssm = cfg.ssm.as_ref().unwrap();
2474        let d_state = ssm.state_size as usize;
2475        let num_k = ssm.group_count as usize;
2476        let num_v = ssm.time_step_rank as usize;
2477        let d_conv = ssm.conv_kernel as usize;
2478        let conv_dim = d_state * num_k * 2 + d_state * num_v;
2479        let scale = 1.0 / (d_state as f32).sqrt();
2480        for il in 0..self.layers.len() {
2481            if let Some(rl) = cache.recur[il].as_mut() {
2482                let st = ckpt.gdn[il]
2483                    .as_ref()
2484                    .ok_or("stream restore: batched-linear stash missing")?;
2485                let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
2486                let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
2487                e.ssm_conv_ring_rebuild_dc(
2488                    &st.qkv_mixed,
2489                    ring_old,
2490                    &mut rl.conv_state,
2491                    conv_dim,
2492                    acc,
2493                    base,
2494                    t_v,
2495                    d_conv,
2496                )?;
2497                let mut o = e.uninit(d_state * num_v * t_v)?;
2498                e.gdn_scan_s128_dc(
2499                    &st.q_l2,
2500                    &st.k_l2,
2501                    &st.v_g,
2502                    &st.g_log,
2503                    &st.beta,
2504                    state_in,
2505                    &mut rl.ssm_state,
2506                    &mut o,
2507                    num_v,
2508                    acc,
2509                    base,
2510                    t_v,
2511                    scale,
2512                )?;
2513            }
2514        }
2515        Ok(())
2516    }
2517
2518    /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
2519    /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
2520    /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
2521    /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
2522    /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
2523    pub fn decode_step_t_aux2(
2524        &self,
2525        e: &Engine,
2526        tokens: &[u32],
2527        pos0: usize,
2528        cache: &mut Cache,
2529        aux_layers: &[usize],
2530        pred_col: Option<usize>,
2531    ) -> Result<
2532        (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
2533        Box<dyn std::error::Error>,
2534    > {
2535        let cfg = &self.cfg;
2536        let n_embd = cfg.n_embd as usize;
2537        let eps = cfg.rms_eps;
2538        let t = tokens.len();
2539        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
2540        let pos_d = e.htod_i32(&pos_vec)?;
2541        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
2542        let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
2543        let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
2544        let want_pred = pred_col.is_some();
2545
2546        for (il, layer) in self.layers.iter().enumerate() {
2547            // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
2548            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
2549            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
2550            let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
2551            if norm_fused {
2552                e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
2553            } else {
2554                e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
2555            }
2556            let mixed = match &layer.mixer {
2557                Mixer::Full(fa) => {
2558                    self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
2559                }
2560                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
2561                Mixer::Linear(la) => {
2562                    let mut out = e.zeros(t * n_embd)?;
2563                    for col in 0..t {
2564                        let mut h_col = e.zeros(n_embd)?;
2565                        let src = h.slice(col * n_embd..(col + 1) * n_embd);
2566                        e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
2567                        let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
2568                        e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
2569                    }
2570                    out
2571                }
2572            };
2573            let ffn_fuse = match &layer.ffn {
2574                crate::hybrid::Ffn::Dense {
2575                    ffn_gate, ffn_up, ..
2576                } => {
2577                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
2578                        && e.uses_q8_1_fast(ffn_gate)
2579                        && e.uses_q8_1_fast(ffn_up)
2580                }
2581                crate::hybrid::Ffn::Moe(_) => false,
2582            };
2583            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
2584            let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
2585            if ffn_fuse {
2586                e.add(&x, &mixed, &mut x1, t * n_embd)?;
2587                e.rms_norm_decode(
2588                    &x1,
2589                    layer.post_attn_norm.float_data(),
2590                    &mut z,
2591                    n_embd,
2592                    t,
2593                    eps,
2594                )?;
2595            } else {
2596                e.add_rms_norm(
2597                    &x,
2598                    &mixed,
2599                    layer.post_attn_norm.float_data(),
2600                    &mut x1,
2601                    &mut z,
2602                    n_embd,
2603                    t,
2604                    eps,
2605                )?;
2606            }
2607            let ffn_out = match &layer.ffn {
2608                crate::hybrid::Ffn::Dense {
2609                    ffn_gate,
2610                    ffn_up,
2611                    ffn_down,
2612                } => {
2613                    let n_ff = ffn_gate.out_features();
2614                    let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
2615                    let up = e.matmul_decode_exact(ffn_up, &z, t)?;
2616                    let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
2617                    // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
2618                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
2619                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
2620                    e.matmul_decode_exact(ffn_down, &act, t)?
2621                }
2622                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
2623            };
2624            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
2625            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
2626            if aux_layers.contains(&il) {
2627                let mut a = e.zeros(n_embd)?;
2628                e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
2629                aux_last.push(a);
2630                if let Some(pc) = pred_col {
2631                    let mut ap = e.zeros(n_embd)?;
2632                    e.copy_view_into(
2633                        &mut ap,
2634                        0,
2635                        &x2.slice(pc * n_embd..(pc + 1) * n_embd),
2636                        n_embd,
2637                    )?;
2638                    aux_pred.push(ap);
2639                }
2640            }
2641            x = x2;
2642        }
2643        let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
2644        e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
2645        let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
2646        let host = e.dtoh(&logits)?;
2647        cache.pos += t;
2648        Ok((
2649            host,
2650            aux_last,
2651            if want_pred { Some(aux_pred) } else { None },
2652        ))
2653    }
2654
2655    /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
2656    /// `step35_decode_attn`.
2657    ///
2658    /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
2659    /// the eager decode would have computed for the same tokens; that is what makes greedy spec
2660    /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
2661    /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
2662    /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
2663    /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
2664    /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
2665    /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
2666    /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
2667    /// position of each query row. A batched twin would have to reproduce all of that AND the
2668    /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
2669    /// take one `base_len`, not a per-row offset).
2670    ///
2671    /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
2672    /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
2673    /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
2674    /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
2675    /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
2676    /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
2677    /// step35 twin is a perf lane's job and must be gated against this arm.
2678    ///
2679    /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
2680    /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
2681    /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
2682    /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
2683    /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
2684    #[allow(clippy::too_many_arguments)]
2685    fn step35_verify(
2686        &self,
2687        e: &Engine,
2688        fa: &FullAttnLayer,
2689        h: &CudaSlice<f32>,
2690        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2691        t: usize,
2692        cache: &mut Cache,
2693        il: usize,
2694    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2695        let n_embd = self.cfg.n_embd as usize;
2696        // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
2697        // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
2698        // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
2699        // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
2700        // cannot regress it into silently reading an empty buffer.
2701        assert_eq!(
2702            h.len(),
2703            t * n_embd,
2704            "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
2705             fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
2706            h_q8.is_some()
2707        );
2708        // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
2709        // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
2710        // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
2711        // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
2712        // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
2713        // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
2714        let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
2715        for r in 0..t {
2716            // Absolute position of this query row. `cache.pos` is the committed length at round
2717            // start and every row before r has already been appended by this loop, so the r-th
2718            // verify token sits at cache.pos + r — the same position eager decode would give it.
2719            let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
2720            let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
2721            e.copy_view_into(&mut h_row, 0, &h.slice(r * n_embd..(r + 1) * n_embd), n_embd)?;
2722            // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
2723            // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
2724            let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
2725            debug_assert_eq!(o.len(), n_embd, "step35_decode_attn returns post-wo [n_embd]");
2726            e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
2727        }
2728        Ok(out)
2729    }
2730
2731    /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
2732    /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
2733    /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
2734    #[allow(clippy::too_many_arguments)]
2735    fn full_attn_verify(
2736        &self,
2737        e: &Engine,
2738        fa: &FullAttnLayer,
2739        h: &CudaSlice<f32>,
2740        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2741        pos_d: &CudaSlice<i32>,
2742        t: usize,
2743        cache: &mut Cache,
2744        il: usize,
2745        stream_ctr: Option<&CudaSlice<i32>>,
2746    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2747        // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
2748        // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
2749        // its own arm. A verify that silently computes different attention than decode defeats the
2750        // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
2751        // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
2752        // shape and not laziness.
2753        if self.cfg.step35.is_some() {
2754            if stream_ctr.is_some() {
2755                return Err("step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
2756                            cannot express the SWA offset KV view; same root cause as the dc \
2757                            decode refusal) — run spec without the stream arm".into());
2758            }
2759            return self.step35_verify(e, fa, h, h_q8, t, cache, il);
2760        }
2761        let cfg = &self.cfg;
2762        let geometry = cfg.full_attention_geometry_at(il as u32);
2763        let n_head = geometry.n_head as usize;
2764        let n_head_kv = geometry.n_head_kv as usize;
2765        let head_dim = geometry.head_dim_k as usize;
2766        let eps = cfg.rms_eps;
2767        let scale = geometry.attention_scale();
2768        let n_embd = cfg.n_embd as usize;
2769
2770        // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
2771        // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
2772        // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
2773        // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
2774        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
2775        // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
2776        // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
2777        // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
2778        let (qf, mut k, v) = {
2779            let mut fused = None;
2780            let qkv_fast = e.uses_q8_1_fast(&fa.wq)
2781                && e.uses_q8_1_fast(&fa.wk)
2782                && e.uses_q8_1_fast(&fa.wv);
2783            if t == 1 && qkv_fast {
2784                let (hq_o, hd_o);
2785                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
2786                    Some(p) => p,
2787                    None => {
2788                        (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
2789                        (&hq_o, &hd_o)
2790                    }
2791                };
2792                fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
2793            } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
2794                // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
2795                // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
2796                // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
2797                let (hq_o, hd_o);
2798                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
2799                    Some(p) => p,
2800                    None => {
2801                        (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
2802                        (&hq_o, &hd_o)
2803                    }
2804                };
2805                fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
2806            }
2807            match (fused, h_q8) {
2808                (Some(triple), _) => triple,
2809                // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
2810                // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
2811                (None, Some((hq, hd))) if qkv_fast => (
2812                    e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
2813                    e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
2814                    e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
2815                ),
2816                (None, _) => (
2817                    e.matmul_decode_exact(&fa.wq, h, t)?,
2818                    e.matmul_decode_exact(&fa.wk, h, t)?,
2819                    e.matmul_decode_exact(&fa.wv, h, t)?,
2820                ),
2821            }
2822        };
2823        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2824        let gated = geometry.attention_gate
2825            == memra_gguf::config::AttentionGateKind::FusedQ;
2826        let (mut q, gate) = if gated {
2827            let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
2828            let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
2829            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
2830            (q, Some(gate))
2831        } else {
2832            (qf, None)
2833        };
2834
2835        let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
2836        e.rms_norm(
2837            &q,
2838            fa.q_norm.float_data(),
2839            &mut qn,
2840            head_dim,
2841            n_head * t,
2842            eps,
2843        )?;
2844        q = qn;
2845        let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
2846        e.rms_norm(
2847            &k,
2848            fa.k_norm.float_data(),
2849            &mut kn,
2850            head_dim,
2851            n_head_kv * t,
2852            eps,
2853        )?;
2854        k = kn;
2855        let rope_dims = geometry.n_rot as usize;
2856        e.rope_neox(
2857            &mut q,
2858            pos_d,
2859            head_dim,
2860            rope_dims,
2861            n_head,
2862            t,
2863            geometry.rope_base,
2864            1.0,
2865        )?;
2866        e.rope_neox(
2867            &mut k,
2868            pos_d,
2869            head_dim,
2870            rope_dims,
2871            n_head_kv,
2872            t,
2873            geometry.rope_base,
2874            1.0,
2875        )?;
2876
2877        // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
2878        // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
2879        let kvl = cache.kv[il].as_mut().unwrap();
2880        let (kv_dim_k, kv_dim_v, ktb, vtb) =
2881            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
2882        if let Some(ctr) = stream_ctr {
2883            // stream: ONE batched append at the device counter (rows kernel = the per-view warp
2884            // math on a (block, token) grid, documented byte-identical); host len is a stale
2885            // LOWER BOUND under pre-issue (drain reconciles it).
2886            e.append_kv_quantized_rows_dc(
2887                &k,
2888                &v,
2889                &mut kvl.k,
2890                &mut kvl.v,
2891                ctr,
2892                t,
2893                kv_dim_k,
2894                kv_dim_v,
2895                ktb,
2896                vtb,
2897                crate::Engine::kv_fp8_on(),
2898            )?;
2899        } else {
2900            for i in 0..t {
2901                let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
2902                let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
2903                e.append_kv_quantized_view(
2904                    &k_row,
2905                    &v_row,
2906                    &mut kvl.k,
2907                    &mut kvl.v,
2908                    kvl.len + i,
2909                    kv_dim_k,
2910                    kv_dim_v,
2911                    ktb,
2912                    vtb,
2913                    crate::Engine::kv_fp8_on(),
2914                )?;
2915            }
2916            kvl.len += t;
2917        }
2918
2919        // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
2920        // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
2921        // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
2922        // which changes FP summation order and can flip argmax at tight logit margins. Query row r
2923        // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
2924        // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
2925        // keys. The verify appends all T tokens first but bounds the key range per row.
2926        //
2927        // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
2928        // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
2929        // per-row program for all T rows (grid.z = row, per-row n_splits from the same
2930        // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
2931        // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
2932        // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
2933        // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
2934        // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
2935        let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
2936        let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
2937                                    // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
2938                                    // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
2939                                    // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
2940                                    // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
2941                                    // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
2942                                    // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
2943                                    // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
2944                                    // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
2945        if let Some(ctr) = stream_ctr {
2946            // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
2947            // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
2948            // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
2949            let upper = kvl.len + t + 64;
2950            let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
2951            let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
2952            e.fa_decode_rows_dc(
2953                &q,
2954                &k_view,
2955                &v_view,
2956                &mut attn,
2957                head_dim,
2958                n_head,
2959                n_head_kv,
2960                ctr,
2961                upper.min(cache.max_ctx),
2962                t,
2963                scale,
2964                ktb,
2965                vtb,
2966                0,
2967                false,
2968            )?;
2969        } else if spec_lean() && t == 1 {
2970            let t_kv = base_len + 1;
2971            let k_view = e.view_u8(&kvl.k, t_kv * ktb);
2972            let v_view = e.view_u8(&kvl.v, t_kv * vtb);
2973            e.fa_decode_kvmod(
2974                &q,
2975                &k_view,
2976                &v_view,
2977                &mut attn,
2978                head_dim,
2979                n_head,
2980                n_head_kv,
2981                t_kv,
2982                scale,
2983                ktb,
2984                vtb,
2985                crate::Engine::kv_fp8_on(),
2986            )?;
2987        } else if e.fa_rows_eligible(base_len, head_dim) {
2988            let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
2989            let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
2990            e.fa_decode_rows(
2991                &q,
2992                &k_view,
2993                &v_view,
2994                &mut attn,
2995                head_dim,
2996                n_head,
2997                n_head_kv,
2998                base_len,
2999                t,
3000                scale,
3001                ktb,
3002                vtb,
3003                None,
3004                false,
3005                crate::Engine::kv_fp8_on(),
3006                None,
3007            )?;
3008        } else {
3009            for r in 0..t {
3010                let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
3011                let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
3012                let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
3013                // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
3014                let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
3015                let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
3016                e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
3017                let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
3018                e.fa_decode_kvmod(
3019                    &q_row,
3020                    &k_view_r,
3021                    &v_view_r,
3022                    &mut attn_row,
3023                    head_dim,
3024                    n_head,
3025                    n_head_kv,
3026                    t_kv_r,
3027                    scale,
3028                    ktb,
3029                    vtb,
3030                    crate::Engine::kv_fp8_on(),
3031                )?;
3032                e.copy_into(
3033                    &mut attn,
3034                    r * n_head * head_dim,
3035                    &attn_row,
3036                    n_head * head_dim,
3037                )?;
3038            }
3039        }
3040
3041        let attn_g = match &gate {
3042            Some(gate) => {
3043                let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
3044                e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
3045                let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
3046                e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
3047                ag
3048            }
3049            None => attn,
3050        };
3051        // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
3052        // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
3053        Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
3054    }
3055
3056    /// Context-linear bytes for a plain serving session's trunk cache.
3057    pub fn plain_session_kv_bytes_per_token(&self) -> usize {
3058        crate::cache::cache_bytes_per_token(&self.cfg)
3059    }
3060
3061    /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
3062    pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
3063        (
3064            self.plain_session_kv_bytes_per_token(),
3065            crate::cache::cache_ring_bytes_per_token(&self.cfg),
3066            crate::cache::cache_ring_row_cap(&self.cfg),
3067        )
3068    }
3069
3070    /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
3071    /// scratch. With no MTP head this equals the plain coefficient.
3072    pub fn spec_session_kv_bytes_per_token(&self) -> usize {
3073        let scratch = self
3074            .mtp
3075            .as_ref()
3076            .map(|mtp| {
3077                let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
3078                k + v
3079            })
3080            .unwrap_or(0);
3081        self.plain_session_kv_bytes_per_token()
3082            .saturating_add(scratch)
3083    }
3084
3085    /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
3086    /// capped by the same SWA ring rows as the trunk.
3087    pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
3088        let total = self.spec_session_kv_bytes_per_token();
3089        let (_, mut ring, rows) = self.plain_session_kv_shape();
3090        if rows > 0 {
3091            ring = ring.saturating_add(
3092                self.mtp
3093                    .as_ref()
3094                    .map(|mtp| {
3095                        let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
3096                        k + v
3097                    })
3098                    .unwrap_or(0),
3099            );
3100        }
3101        (total, ring, rows)
3102    }
3103
3104    /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
3105    /// the NextN head to draft K tokens then verifies them in one batched target forward.
3106    /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
3107    /// acceptance rate. `k` = draft length per round.
3108    ///
3109    /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
3110    /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
3111    /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
3112    /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
3113    /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
3114    /// captured graph references is event-free; the spec loop is strictly single-stream.
3115    /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
3116    /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
3117    /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
3118    /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
3119    /// generate_spec_inner2.
3120    /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
3121    /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
3122    /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
3123    /// hybrid linear-attn states are in-place (no position index), so a session can extend but
3124    /// never rewind — `committed` is the exact token list whose state the caches hold (includes
3125    /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
3126    pub fn new_session(
3127        &self,
3128        e: &Engine,
3129        max_ctx: usize,
3130    ) -> Result<SpecSession, Box<dyn std::error::Error>> {
3131        Ok(SpecSession {
3132            // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
3133            // is the SERVING spec-session path, and with the ppN door open across two cards a
3134            // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
3135            // round — the wrong-card class already fixed on the two batched serving paths
3136            // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
3137            // branch, same allocations), so single-device behavior is byte-unchanged.
3138            cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
3139            scratch: MtpScratch::new(
3140                e,
3141                &self.cfg,
3142                max_ctx,
3143                self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
3144            )?,
3145            committed: Vec::new(),
3146            last_h: None,
3147            next_pred: None,
3148            sctr: 0,
3149            uctr: 0,
3150            draft_ctx: None,
3151            pending_tok: None,
3152            turn_ckpt: None,
3153            telem: SpecTelemetry::default(),
3154        })
3155    }
3156
3157    /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
3158    /// retained prompt-end checkpoint, so a request whose prompt matches
3159    /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
3160    ///
3161    /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
3162    /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
3163    /// restored from the device copy taken there, draft scratch length reset, `committed`
3164    /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
3165    /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
3166    /// every burst after it are identical to a cold run of the same token stream — the
3167    /// committed-tokens-authoritative contract.
3168    ///
3169    /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
3170    /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
3171    /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
3172    /// continue). The persistent draft graph survives: it bakes only session-stable pointers
3173    /// (the scratch KV, the resident embedding), none of which the rewind moves.
3174    ///
3175    /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
3176    /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
3177    /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
3178    pub fn spec_rewind_to_checkpoint(
3179        &self,
3180        e: &Engine,
3181        sess: &mut SpecSession,
3182    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
3183        if sess
3184            .turn_ckpt
3185            .as_ref()
3186            .is_some_and(|ckpt| {
3187                !sess.cache.can_rollback(&ckpt.snap, 0)
3188                    || !sess.scratch.can_rewind_to(ckpt.pos)
3189            })
3190        {
3191            return Err("SWA ring rewind checkpoint has been lapped; full re-prime required".into());
3192        }
3193        let Some(ckpt) = sess.turn_ckpt.take() else {
3194            return Ok(None);
3195        };
3196        assert!(
3197            ckpt.pos <= sess.committed.len(),
3198            "checkpoint past committed ({} > {})",
3199            ckpt.pos,
3200            sess.committed.len()
3201        );
3202        // Restore through each layer's owning engine. A single primary-engine rollback is not
3203        // sufficient when the serving cache is stage-owned under cross-device PP.
3204        crate::pp::restore_cache_checkpoint(e, &self.cfg, None, &mut sess.cache, &ckpt.snap)?;
3205        debug_assert_eq!(sess.cache.pos, ckpt.pos, "rollback landed off the checkpoint");
3206        sess.scratch.set_len(e, ckpt.pos)?;
3207        sess.committed.truncate(ckpt.pos);
3208        sess.last_h = Some(ckpt.last_h);
3209        sess.next_pred = None;
3210        sess.pending_tok = None;
3211        Ok(Some(ckpt.pos))
3212    }
3213
3214    /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
3215    /// checkpoint without re-priming the checkpoint prefix.
3216    ///
3217    /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
3218    /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
3219    /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
3220    /// remain authoritative, so they are copied into a fresh larger scratch before its length is
3221    /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
3222    ///
3223    /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
3224    /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
3225    pub fn spec_grow_and_rewind_to_checkpoint(
3226        &self,
3227        e: &Engine,
3228        sess: &mut SpecSession,
3229        target_cap: usize,
3230    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
3231        if target_cap <= sess.cache.max_ctx {
3232            return self.spec_rewind_to_checkpoint(e, sess);
3233        }
3234        let Some(ckpt) = sess.turn_ckpt.as_ref() else {
3235            return Ok(None);
3236        };
3237        if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
3238            return Err(format!(
3239                "checkpoint pos {} outside committed length {}",
3240                ckpt.pos,
3241                sess.committed.len(),
3242            )
3243            .into());
3244        }
3245        if ckpt.pos > target_cap {
3246            return Err(format!(
3247                "checkpoint pos {} exceeds grown capacity {target_cap}",
3248                ckpt.pos,
3249            )
3250            .into());
3251        }
3252
3253        let mut grown_cache = crate::pp::new_cache(e, &self.cfg, target_cap)?;
3254        let mut grown_scratch = MtpScratch::new(
3255            e,
3256            &self.cfg,
3257            target_cap,
3258            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
3259        )?;
3260        crate::pp::restore_cache_checkpoint(
3261            e,
3262            &self.cfg,
3263            Some(&sess.cache),
3264            &mut grown_cache,
3265            &ckpt.snap,
3266        )?;
3267
3268        let src = &sess.scratch.kv;
3269        let dst = &mut grown_scratch.kv;
3270        if ckpt.pos > src.len
3271            || src.kv_dim_k != dst.kv_dim_k
3272            || src.kv_dim_v != dst.kv_dim_v
3273            || src.k_tok_bytes != dst.k_tok_bytes
3274            || src.v_tok_bytes != dst.v_tok_bytes
3275        {
3276            return Err(format!(
3277                "checkpoint draft layout mismatch (pos {}, source len {})",
3278                ckpt.pos, src.len,
3279            )
3280            .into());
3281        }
3282        let kb = ckpt.pos * src.k_tok_bytes;
3283        let vb = ckpt.pos * src.v_tok_bytes;
3284        if kb > 0 {
3285            e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
3286        }
3287        if vb > 0 {
3288            e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
3289        }
3290        grown_scratch.set_len(e, ckpt.pos)?;
3291        // The old scratch is dropped immediately after publication below. Bound its D2D reads
3292        // first; growth happens once per rewritten turn, outside the decode hot loop.
3293        e.stream().synchronize()?;
3294
3295        let ckpt = sess
3296            .turn_ckpt
3297            .take()
3298            .expect("checkpoint remained present through transactional grow");
3299        let pos = ckpt.pos;
3300        sess.cache = grown_cache;
3301        sess.scratch = grown_scratch;
3302        sess.committed.truncate(pos);
3303        sess.last_h = Some(ckpt.last_h);
3304        sess.next_pred = None;
3305        sess.pending_tok = None;
3306        sess.draft_ctx = None;
3307        debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
3308        debug_assert_eq!(sess.scratch.kv.len, pos, "grown draft rewind landed off checkpoint");
3309        Ok(Some(pos))
3310    }
3311
3312    /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
3313    /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
3314    /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
3315    /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
3316    pub fn spec_flush_pending(
3317        &self,
3318        e: &Engine,
3319        sess: &mut SpecSession,
3320    ) -> Result<(), Box<dyn std::error::Error>> {
3321        let Some(b) = sess.pending_tok.take() else {
3322            return Ok(());
3323        };
3324        let mtp = self.mtp.as_ref().expect("pending carry requires an MTP head");
3325        let n_embd = self.cfg.n_embd as usize;
3326        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
3327        let embd_gpu = if spec_host_embd() {
3328            None
3329        } else {
3330            Some(
3331                self.embd_gpu
3332                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
3333            )
3334        };
3335        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
3336        let pos_b = sess.cache.pos;
3337        sess.scratch.set_len(e, pos_b)?;
3338        let (lg_b, hb) = self.decode_step_h(e, b, &mut sess.cache)?;
3339        sess.next_pred = Some(argmax(&lg_b) as u32);
3340        let anchor = sess
3341            .last_h
3342            .as_ref()
3343            .expect("pending carry requires last_h (the predecessor-row anchor)");
3344        self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
3345        sess.last_h = Some(hb);
3346        sess.committed.push(b);
3347        Ok(())
3348    }
3349
3350    /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
3351    /// message rendered through the chat template continuation). Returns (new tokens emitted,
3352    /// drafted, accepted); session.committed grows by suffix + emitted.
3353    pub fn generate_spec_session(
3354        &self,
3355        e: &Engine,
3356        sess: &mut SpecSession,
3357        suffix: &[u32],
3358        max_new: usize,
3359        k: usize,
3360    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3361        self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
3362    }
3363
3364    /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
3365    /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
3366    /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
3367    /// for the filtered target (feat/filtered-spec).
3368    ///
3369    /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
3370    /// output — once right after the prime's first token, then once per round commit — so a
3371    /// streaming caller can flush text at round cadence instead of once per burst. The slices
3372    /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
3373    /// timing only: token bytes, session state, and exactness are untouched.
3374    ///
3375    /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
3376    /// the burst at the current round boundary, exactly as if `max_new` had been reached —
3377    /// the caller's scheduler regains control without waiting the burst out. Burst size is
3378    /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
3379    /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
3380    /// drains and the defensive tail flush can land with nothing new committed).
3381    #[allow(clippy::too_many_arguments)]
3382    pub fn generate_spec_session_sampled(
3383        &self,
3384        e: &Engine,
3385        sess: &mut SpecSession,
3386        suffix: &[u32],
3387        max_new: usize,
3388        k: usize,
3389        sampling: Option<SpecSampling>,
3390        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
3391    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3392        self.generate_spec_session_constrained(e, sess, suffix, max_new, k, sampling, None, on_commit)
3393    }
3394
3395    /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
3396    /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
3397    /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
3398    /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
3399    /// column — token-identical to constrained plain greedy decode. GREEDY only (the
3400    /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
3401    /// may drop (drafter is unconstrained); that is measured, not hidden.
3402    #[allow(clippy::too_many_arguments)]
3403    pub fn generate_spec_session_constrained(
3404        &self,
3405        e: &Engine,
3406        sess: &mut SpecSession,
3407        suffix: &[u32],
3408        max_new: usize,
3409        k: usize,
3410        sampling: Option<SpecSampling>,
3411        constraint: Option<&mut dyn SpecConstraint>,
3412        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
3413    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3414        if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
3415            return Err("constrained spec decode is greedy-only (worker routes sampled \
3416                        constrained to plain decode)".into());
3417        }
3418        // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
3419        // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
3420        // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
3421        // serve continuation case — consume the carry in-loop with zero solo passes.
3422        if sess.pending_tok.is_some()
3423            && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
3424        {
3425            self.spec_flush_pending(e, sess)?;
3426        }
3427        let mtp_dense = self
3428            .mtp
3429            .as_ref()
3430            .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
3431            .unwrap_or(false);
3432        let trunk_dense = self
3433            .layers
3434            .iter()
3435            .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
3436        // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
3437        // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
3438        // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
3439        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
3440            && !spec_host_embd()
3441            && mtp_dense
3442            && trunk_dense
3443            && k + 2 < 96
3444            && !crate::model::full_prec_enabled();
3445        let was_tracking = e.ctx().is_event_tracking();
3446        if graph_draft && was_tracking {
3447            unsafe {
3448                e.ctx().disable_event_tracking();
3449            }
3450        }
3451        let r = self.generate_spec_inner2(e, suffix, max_new, k, graph_draft, Some(sess), sampling, constraint, on_commit);
3452        if graph_draft && was_tracking {
3453            unsafe {
3454                e.ctx().enable_event_tracking();
3455            }
3456        }
3457        let (out, d, a) = r?;
3458        Ok((out, d, a))
3459    }
3460
3461    pub fn generate_spec(
3462        &self,
3463        e: &Engine,
3464        prompt: &[u32],
3465        max_new: usize,
3466        k: usize,
3467    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3468        let mtp_dense = self
3469            .mtp
3470            .as_ref()
3471            .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
3472            .unwrap_or(false);
3473        let trunk_dense = self
3474            .layers
3475            .iter()
3476            .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
3477        // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
3478        // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
3479        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
3480            && !spec_host_embd()
3481            && mtp_dense
3482            && trunk_dense
3483            && k + 2 < 96
3484            && !crate::model::full_prec_enabled();
3485        if !graph_draft {
3486            return self.generate_spec_inner2(e, prompt, max_new, k, false, None, None, None, None);
3487        }
3488        let was_tracking = e.ctx().is_event_tracking();
3489        if was_tracking {
3490            unsafe {
3491                e.ctx().disable_event_tracking();
3492            }
3493        }
3494        let r = self.generate_spec_inner2(e, prompt, max_new, k, true, None, None, None, None);
3495        if was_tracking {
3496            unsafe {
3497                e.ctx().enable_event_tracking();
3498            }
3499        }
3500        r
3501    }
3502
3503    fn generate_spec_inner2(
3504        &self,
3505        e: &Engine,
3506        prompt: &[u32],
3507        max_new: usize,
3508        k: usize,
3509        graph_draft: bool,
3510        mut sess: Option<&mut SpecSession>,
3511        sampling: Option<SpecSampling>,
3512        mut constraint: Option<&mut dyn SpecConstraint>,
3513        mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
3514    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3515        assert!(k >= 1, "k must be >= 1");
3516        // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
3517        let mut flushed = 0usize;
3518        // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
3519        // at the next round boundary (same exit as max_new reached — the session tail runs).
3520        // Initialized by the unconditional post-prime flush below.
3521        let mut keep_going;
3522        let mtp = self
3523            .mtp
3524            .as_ref()
3525            .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
3526        let n_vocab = self.output.out_features();
3527        // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
3528        // over the draft vocab and the winning index maps through d2t to a TARGET token id.
3529        // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
3530        let d_vocab = mtp
3531            .shared_head_head
3532            .as_ref()
3533            .unwrap_or(&self.output)
3534            .out_features();
3535        let n_embd = self.cfg.n_embd as usize;
3536        // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
3537        // already committed (their state is in the caches); 0 = fresh single-shot call.
3538        let session_mode = sess.is_some();
3539        let max_ctx = match sess.as_ref() {
3540            Some(s) => s.cache.max_ctx,
3541            None => prompt.len() + max_new + k + 8,
3542        };
3543        let mut own_cache;
3544        let mut own_scratch;
3545        let (
3546            cache,
3547            scratch,
3548            mut sess_tail,
3549            mut sess_draft_slot,
3550            mut sess_pending_slot,
3551            sess_ckpt_slot,
3552            mut sess_telem,
3553        ): (
3554            &mut Cache,
3555            &mut MtpScratch,
3556            Option<(
3557                &mut Vec<u32>,
3558                &mut Option<CudaSlice<f32>>,
3559                &mut Option<u32>,
3560                &mut u32,
3561                &mut u32,
3562            )>,
3563            Option<&mut Option<DraftGraphCtx>>,
3564            Option<&mut Option<u32>>,
3565            Option<&mut Option<SpecCheckpoint>>,
3566            Option<&mut SpecTelemetry>,
3567        ) = match sess.take() {
3568            Some(sr) => {
3569                let SpecSession {
3570                    cache,
3571                    scratch,
3572                    committed,
3573                    last_h,
3574                    next_pred,
3575                    sctr: s_sctr,
3576                    uctr: s_uctr,
3577                    draft_ctx,
3578                    pending_tok,
3579                    turn_ckpt,
3580                    telem,
3581                } = sr;
3582                (
3583                    cache,
3584                    scratch,
3585                    Some((committed, last_h, next_pred, s_sctr, s_uctr)),
3586                    Some(draft_ctx),
3587                    Some(pending_tok),
3588                    Some(turn_ckpt),
3589                    Some(telem),
3590                )
3591            }
3592            None => {
3593                // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
3594                // `Cache::new` verbatim.
3595                own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
3596                // Persistent scratch = max_ctx rows (~2KB/token quantized).
3597                own_scratch = MtpScratch::new(
3598                    e,
3599                    &self.cfg,
3600                    max_ctx,
3601                    self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
3602                )?;
3603                (&mut own_cache, &mut own_scratch, None, None, None, None, None)
3604            }
3605        };
3606        let base = cache.pos;
3607        // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
3608        // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
3609        // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
3610        // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
3611        let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
3612        // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
3613        // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
3614        // acceptance-only — exactness is verify's job either way).
3615        // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
3616        // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
3617        // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
3618        // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
3619        // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
3620        // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
3621        // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
3622        // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
3623        // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
3624        // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
3625        // per round on top of the acceptance win). Draft-quality-only: exactness stays the
3626        // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
3627        // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
3628        // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
3629        // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
3630        // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
3631        // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
3632        // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
3633        // + fallback seam).
3634        let spec_replay = std::env::var("MEMRA_SPEC_REPLAY").is_ok();
3635        if constraint.is_some() && spec_replay {
3636            return Err("constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
3637                        (legacy replay commits an unmasked bonus)".into());
3638        }
3639        // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
3640        // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
3641        // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
3642        let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
3643
3644        // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
3645        // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
3646        // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
3647        // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
3648        // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
3649        // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
3650        // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
3651        // generation exactly where the last turn stopped — no prime at all. The stashed
3652        // `next_pred` plays prime_logits' argmax role (it IS the argmax of the logits after
3653        // committed.last()); `last_h` seeds the predecessor pairing below. Fresh calls and
3654        // non-empty suffixes take the normal path.
3655        let continuation = prompt.is_empty();
3656        if continuation {
3657            assert!(session_mode, "empty prompt requires a session");
3658            assert!(
3659                sess_tail
3660                    .as_ref()
3661                    .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
3662                        && lh.is_some()
3663                        && (np.is_some() || carried_pending.is_some())),
3664                "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
3665            );
3666        }
3667        let mut prime_logits;
3668        let mut prompt_h: Option<CudaSlice<f32>> = None;
3669        let t_prime = std::time::Instant::now();
3670        let batched_prime = !continuation
3671            && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
3672            && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
3673            && !e.frozen_cpu_experts_prefer_tokenwise_prime();
3674        if continuation {
3675            prime_logits = Vec::new();
3676        } else if batched_prime {
3677            let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
3678            prime_logits = l;
3679            prompt_h = Some(hiddens);
3680        } else {
3681            prime_logits = Vec::new();
3682            prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
3683            for (i, &tok) in prompt.iter().enumerate() {
3684                let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
3685                if let Some(ph) = prompt_h.as_mut() {
3686                    e.copy_into(ph, i * n_embd, &h, n_embd)?;
3687                }
3688                prime_logits = l;
3689            }
3690        }
3691        e.stream().synchronize()?;
3692        // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
3693        // prime-subtraction hack.
3694        crate::PRIME_NANOS.store(
3695            t_prime.elapsed().as_nanos() as u64,
3696            std::sync::atomic::Ordering::Relaxed,
3697        );
3698
3699        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
3700        // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
3701        // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
3702        let host_embd = spec_host_embd();
3703        let embd_gpu = if host_embd {
3704            None
3705        } else {
3706            Some(
3707                self.embd_gpu
3708                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
3709            )
3710        };
3711        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
3712        if host_embd {
3713            eprintln!(
3714                "[spec] host-row embedding: {} bytes kept off HBM",
3715                self.embd.raw.len()
3716            );
3717        }
3718        let mut out: Vec<u32> = Vec::with_capacity(max_new);
3719        let mut total_drafted = 0usize;
3720        let mut total_accepted = 0usize;
3721
3722        // First generated token = argmax of the prompt's last logits (== greedy's first token).
3723        // Emit it, then FEED it to establish the loop invariant below.
3724        // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
3725        // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
3726        // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
3727        // prompt's last logits (plain constrained-greedy identity); a continuation without
3728        // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
3729        // worker never resumes constrained sessions from the pool, so this cannot fire).
3730        if let Some(c) = constraint.as_deref_mut() {
3731            if continuation && carried_pending.is_none() {
3732                return Err("constrained spec continuation requires a carried pending \
3733                            (pool resume is unconstrained-only)".into());
3734            }
3735            if !continuation {
3736                c.mask_logits(&mut prime_logits)
3737                    .map_err(|e2| format!("constraint: {e2}"))?;
3738            }
3739        }
3740        let mut last_token = if let Some(b) = carried_pending {
3741            b
3742        } else if continuation {
3743            sess_tail.as_ref().unwrap().2.unwrap()
3744        } else {
3745            argmax(&prime_logits) as u32
3746        };
3747        if carried_pending.is_none() {
3748            out.push(last_token);
3749            // grammar advances with every emitted token (carried pendings were consumed
3750            // by the burst that emitted them).
3751            if let Some(c) = constraint.as_deref_mut() {
3752                c.consume(last_token).map_err(|e2| format!("constraint: {e2}"))?;
3753            }
3754        }
3755        if continuation {
3756            // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
3757            // overhang so the chain's first append lands at slot base (== committed.len()).
3758            scratch.set_len(e, base)?;
3759        }
3760        // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
3761        // concatenating to the full `out`). Called after the prime's first token and after each
3762        // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
3763        // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
3764        // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
3765        fn flush_commit(
3766            cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
3767            out: &[u32],
3768            flushed: &mut usize,
3769        ) -> bool {
3770            if let Some(f) = cb.as_mut() {
3771                let keep = f(&out[*flushed..]);
3772                *flushed = out.len();
3773                keep
3774            } else {
3775                true
3776            }
3777        }
3778        keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
3779        // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
3780        // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
3781        // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
3782        // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
3783        // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
3784        // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
3785        // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
3786        // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
3787        // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
3788        // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
3789        let sp = sampling.unwrap_or_else(|| SpecSampling {
3790            temp: std::env::var("MEMRA_SPEC_TEMP")
3791                .ok()
3792                .and_then(|v| v.parse().ok())
3793                .unwrap_or(0.0),
3794            seed: std::env::var("MEMRA_SEED")
3795                .ok()
3796                .and_then(|v| v.parse().ok())
3797                .unwrap_or(42),
3798            top_k: std::env::var("MEMRA_TOP_K")
3799                .ok()
3800                .and_then(|v| v.parse().ok())
3801                .unwrap_or(0),
3802            top_p: std::env::var("MEMRA_TOP_P")
3803                .ok()
3804                .and_then(|v| v.parse().ok())
3805                .unwrap_or(1.0),
3806            min_p: std::env::var("MEMRA_MIN_P")
3807                .ok()
3808                .and_then(|v| v.parse().ok())
3809                .unwrap_or(0.0),
3810            penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
3811                .ok()
3812                .and_then(|v| v.parse().ok())
3813                .unwrap_or(0),
3814            penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
3815                .ok()
3816                .and_then(|v| v.parse().ok())
3817                .unwrap_or(1.0),
3818            penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
3819                .ok()
3820                .and_then(|v| v.parse().ok())
3821                .unwrap_or(0.0),
3822            penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
3823                .ok()
3824                .and_then(|v| v.parse().ok())
3825                .unwrap_or(0.0),
3826        });
3827        let (sp_temp, sp_seed) = (sp.temp, sp.seed);
3828        let sampled = sp_temp > 0.0;
3829        // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
3830        // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
3831        // those, so their residual mass is p(x), correct by construction).
3832        let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
3833            match &mtp.d2t {
3834                Some(map) => Some(e.htod_u32_v(map)?),
3835                None => None,
3836            }
3837        } else {
3838            None
3839        };
3840        let mut q_full_buf: Option<CudaSlice<f32>> = None;
3841        // Counters resume from the session (burst continuity: randomness must never repeat
3842        // across generate_spec_session calls); one-shot callers start at (0,0). Read through
3843        // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
3844        let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
3845        let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
3846        // host Philox4x32-10 (mirrors spec_sample.cu; independent stream via ctr_lo tag)
3847        let host_u01 = |seed: u64, ctr: u32| -> f32 {
3848            let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
3849            let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
3850            let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
3851            for _ in 0..10 {
3852                let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
3853                let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
3854                let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
3855                c0 = n0;
3856                c1 = n1;
3857                c2 = n2;
3858                c3 = n3;
3859                k0 = k0.wrapping_add(0x9E3779B9);
3860                k1 = k1.wrapping_add(0xBB67AE85);
3861            }
3862            (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
3863        };
3864        let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
3865        let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
3866        let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
3867        let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
3868        let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
3869                                                        // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
3870                                                        // for the penalized+filtered target). History = generated tokens, host-tracked window.
3871        let pen_on = sampled
3872            && sp.penalty_last_n > 0
3873            && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
3874        let mut pen_hist: Vec<u32> = if pen_on {
3875            prompt.iter().rev().take(64).rev().cloned().collect() // llama-parity: history spans prompt tail too
3876        } else {
3877            Vec::new()
3878        };
3879        let mut pen_hist_d: Option<CudaSlice<u32>> = None;
3880        let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
3881        // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
3882        // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
3883        // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
3884        let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
3885        let t_ent = std::time::Instant::now();
3886
3887        // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
3888        // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
3889        // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
3890        // the one that matters (a history-rewriting client mutates what the session GENERATED,
3891        // so the next turn's prompt agrees with this one up to exactly here).
3892        //
3893        // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
3894        // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
3895        // hold exactly `base + prompt.len()` rows and nothing generated.
3896        //
3897        // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
3898        // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
3899        // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
3900        // `<think>` block the client strips, so every later turn's diff diverged exactly one
3901        // token below the checkpoint and affinity declined 100% of the time. Measured on the
3902        // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
3903        // whole mechanism inert while looking, from the outside, like a working
3904        // correctness-declines-safely path — hence the decline log carries the offsets.
3905        //
3906        // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
3907        // state (the reason a spec session could not rewind before). The draft scratch needs no
3908        // copy: rows below the boundary are rewritten by the next turn's own fill.
3909        //
3910        // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
3911        // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
3912        // checkpoint rather than replacing it with a strictly worse one.
3913        //
3914        // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
3915        // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
3916        // fail the burst that is already running — so the error is swallowed, loud only under
3917        // MEMRA_DEBUG_SPEC.
3918        if let Some(slot) = sess_ckpt_slot {
3919            if !continuation {
3920                let pos = cache.pos;
3921                debug_assert_eq!(
3922                    pos,
3923                    base + prompt.len(),
3924                    "turn checkpoint must sit at the prompt end, before the init feed"
3925                );
3926                let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
3927                    if let Some(ph) = &prompt_h {
3928                        // hidden of the LAST primed row = the predecessor anchor at this
3929                        // boundary (exactly what a fresh prime of committed[..pos] leaves in
3930                        // last_h, and what the next prime's fill reads for its first row).
3931                        let np = prompt.len();
3932                        e.uninit(n_embd).and_then(|mut a| {
3933                            e.copy_view_into(
3934                                &mut a,
3935                                0,
3936                                &ph.slice((np - 1) * n_embd..np * n_embd),
3937                                n_embd,
3938                            )?;
3939                            Ok(a)
3940                        })
3941                    } else {
3942                        Err("no prompt hiddens".into())
3943                    };
3944                match (cache.snapshot(e), anchor) {
3945                    (Ok(snap), Ok(last_h)) => {
3946                        *slot = Some(SpecCheckpoint { snap, pos, last_h });
3947                    }
3948                    (s, a) => {
3949                        *slot = None; // a stale checkpoint would rewind to the WRONG boundary
3950                        if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
3951                            let err = s.err().map(|e| e.to_string())
3952                                .or_else(|| a.err().map(|e| e.to_string()))
3953                                .unwrap_or_default();
3954                            eprintln!("[spec] turn checkpoint skipped ({err}); \
3955                                       next turn re-primes in full");
3956                        }
3957                    }
3958                }
3959            }
3960        }
3961        // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
3962        // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
3963        // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
3964        // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
3965        let mut last_pred = 0u32;
3966        let mut last_col_logits: Option<CudaSlice<f32>> = None;
3967        // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
3968        // recompute in the grammar-truncation walk — retained host-side, round 0 only.
3969        let mut init_logits_host: Option<Vec<f32>> = None;
3970        let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
3971            let (init_logits, h) = self.decode_step_h(e, last_token, &mut *cache)?;
3972            last_pred = argmax(&init_logits) as u32;
3973            if constraint.is_some() {
3974                init_logits_host = Some(init_logits.clone());
3975            }
3976            // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
3977            if sampled {
3978                last_col_logits = Some(e.htod(&init_logits)?);
3979            }
3980            h
3981        } else {
3982            // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
3983            let lh = sess_tail
3984                .as_ref()
3985                .unwrap()
3986                .1
3987                .as_ref()
3988                .expect("pending carry requires last_h");
3989            e.clone_dtod(lh)?
3990        };
3991        let t_init = t_ent.elapsed();
3992        let mut last_col_stats: Option<(f32, f32, f32)> = None;
3993        // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
3994        // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
3995        // stable pointer for the graph-draft round-start copy.
3996        let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
3997        // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
3998        // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
3999        // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
4000        // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
4001        // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
4002        // overwritten below).
4003        let mut fill_prev = e.clone_dtod(&h_seed0)?;
4004        {
4005            if let Some(ph) = &prompt_h {
4006                let np = prompt.len();
4007                e.copy_view_into(
4008                    &mut h_seed_buf,
4009                    0,
4010                    &ph.slice((np - 1) * n_embd..np * n_embd),
4011                    n_embd,
4012                )?;
4013            } else if continuation {
4014                if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
4015                    if let Some(lh) = lh.as_ref() {
4016                        e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
4017                    }
4018                }
4019            }
4020        }
4021        // Persistent device prediction slots for the accept walk (max k+1 verify columns).
4022        let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
4023
4024        let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
4025        // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
4026        // the end. Metric normalization vs the reference engine: BOTH engines count
4027        // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
4028        // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
4029        let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
4030        let mut st_drafted = vec![0usize; k];
4031        let mut st_accepted = vec![0usize; k];
4032        let mut st_len_hist = vec![0usize; k + 1];
4033        let mut st_full = 0usize;
4034        // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
4035        // stop the draft chain early when the head's softmax confidence in its own pick drops
4036        // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
4037        static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
4038        let p_min = *PMIN.get_or_init(|| {
4039            std::env::var("MEMRA_SPEC_PMIN")
4040                .ok()
4041                .and_then(|v| v.parse().ok())
4042                .unwrap_or(0.0)
4043        });
4044        // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
4045        // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
4046        // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
4047        // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
4048        // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
4049        // verify batch is not); the j==0 exemption stays for pending-less rounds.
4050        let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
4051            .map(|v| v == "1")
4052            .unwrap_or(false);
4053
4054        // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
4055        // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
4056        // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
4057        // cuBLAS path in an exotic head) falls back to the eager draft chain.
4058        // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
4059        // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
4060        // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
4061        // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
4062        // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
4063        // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
4064        // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
4065        // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
4066        let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
4067            Some(c) => c,
4068            None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
4069        };
4070        // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
4071        // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
4072        if sampled && dctx.g_q.len() < d_vocab {
4073            dctx.g_q = e.zeros(d_vocab)?;
4074            dctx.g_perturb = e.zeros(d_vocab)?;
4075        }
4076        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
4077        // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
4078        // truncation (the correctness backstop) stops cutting every tight-schema round.
4079        // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
4080        // shape, so a parked graph of the other shape is dropped and recaptured.
4081        let dmask_on = constraint.as_deref().is_some_and(|c| c.draft_mask_enabled());
4082        let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
4083        if dmask_on && dctx.g_dmask.len() < dmask_words {
4084            dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
4085            dctx.graph = None; // the old capture baked the old (or no) mask pointer
4086            dctx.failed.clear_greedy();
4087            dctx.keeper.clear();
4088        }
4089        if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
4090            dctx.graph = None;
4091            dctx.failed.clear_greedy();
4092            dctx.keeper.clear();
4093        }
4094        if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
4095            let DraftGraphCtx { g_tok, g_pos, g_seed, g_p, g_dmask, .. } = &mut dctx;
4096            // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
4097            // host uploads the position's real words, so the warmups stay grammar-free.
4098            if dmask_on {
4099                e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
4100            }
4101            let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
4102            // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
4103            // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
4104            // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
4105            // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
4106            // passes (and, in serve, other sessions) recycle those addresses and the replay then
4107            // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
4108            let cap_res = e.capture_graph_retained(|e| {
4109                self.mtp_head_forward_cap(
4110                    e,
4111                    mtp,
4112                    g_tok,
4113                    g_pos,
4114                    g_seed,
4115                    g_p,
4116                    &mut *scratch,
4117                    p_min > 0.0,
4118                    true,
4119                    embd_gpu.expect("graph draft requires resident embedding"),
4120                    embd_qt,
4121                    embd_rb,
4122                    d_vocab,
4123                    None,
4124                    None,
4125                    if dmask_on { Some((g_dmask_ro, dmask_words)) } else { None },
4126                )
4127            });
4128            match cap_res {
4129                Ok((g, keep)) => {
4130                    scratch.set_len(e, base)?;
4131                    dctx.graph = Some(g);
4132                    dctx.graph_masked = dmask_on;
4133                    dctx.keeper = keep;
4134                }
4135                Err(err) => {
4136                    scratch.set_len(e, base)?;
4137                    // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
4138                    // silent. Once per flip — mark returns None on an already-failed ctx.
4139                    if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
4140                        eprintln!("{line}");
4141                    }
4142                }
4143            }
4144        }
4145        // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
4146        // graph object, built only when sampled && graph-eligible — the greedy capture above is
4147        // untouched (and skipped when sampled: its graph would never be launched). Same head
4148        // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
4149        // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
4150        // once per round); the raw head logits land in the persistent g_q for the host's
4151        // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
4152        // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
4153        // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
4154        // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
4155        // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
4156        // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
4157        // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
4158        // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
4159        // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
4160        // this compare misses at most ONCE per resumed request — the first burst recaptures
4161        // and every later burst in that request replays. A client that wants the parked graph
4162        // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
4163        // stable across its whole conversation.
4164        // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
4165        // softmax — it can hold neither per-row filter stats nor the varying penalty history.
4166        // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
4167        // force the eager draft (which computes stats/penalties per row).
4168        let pure_temp = sp.top_k == 0 && sp.top_p >= 1.0 && sp.min_p <= 0.0 && !pen_on;
4169        let s_key = (sp_seed, sp_temp.to_bits(), k);
4170        if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
4171            dctx.graph_s = None;
4172            dctx.failed.clear_sampled();
4173            dctx.s_key = None;
4174            dctx.q_slots.clear();
4175            dctx.keeper_s.clear();
4176        }
4177        if graph_draft && sampled && pure_temp && dctx.graph_s.is_none()
4178            && !dctx.failed.sampled_failed()
4179        {
4180            let DraftGraphCtx { g_tok, g_pos, g_seed, g_p, g_ctr, g_perturb, g_q, .. } = &mut dctx;
4181            // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
4182            let cap_res = e.capture_graph_retained(|e| {
4183                self.mtp_head_forward_cap(
4184                    e,
4185                    mtp,
4186                    g_tok,
4187                    g_pos,
4188                    g_seed,
4189                    g_p,
4190                    &mut *scratch,
4191                    p_min > 0.0,
4192                    true,
4193                    embd_gpu.expect("graph draft requires resident embedding"),
4194                    embd_qt,
4195                    embd_rb,
4196                    d_vocab,
4197                    Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
4198                    None,
4199                    None, // constrained spec is greedy-only — sampled never carries a hook
4200                )
4201            });
4202            match cap_res {
4203                Ok((g, keep)) => {
4204                    scratch.set_len(e, base)?;
4205                    for _ in 0..k {
4206                        dctx.q_slots.push(e.zeros(d_vocab)?);
4207                    }
4208                    dctx.graph_s = Some(g);
4209                    dctx.s_key = Some(s_key);
4210                    dctx.keeper_s = keep;
4211                }
4212                Err(err) => {
4213                    scratch.set_len(e, base)?;
4214                    // LOUD flip (audit Q2): same contract as the greedy capture above.
4215                    if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
4216                        eprintln!("{line}");
4217                    }
4218                }
4219            }
4220        }
4221        let t_cap = t_ent.elapsed();
4222        // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
4223        // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
4224        // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
4225        // fill: the first chain step processes it and appends its entry at slot prompt.len().
4226        if let Some(ph) = &prompt_h {
4227            // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
4228            // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
4229            // global positions [base..base+tp). Fresh call: base==0, identical to before.
4230            scratch.set_len(e, base)?;
4231            // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
4232            // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
4233            // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
4234            // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
4235            let tp = prompt.len();
4236            let fill_chunk: usize = if crate::cache::swa_ring_on() {
4237                crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
4238            } else {
4239                // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
4240                // meaning one monolithic fill.
4241                std::env::var("MEMRA_PRIME_CHUNK")
4242                    .ok()
4243                    .and_then(|v| v.parse().ok())
4244                    .unwrap_or(4096)
4245            };
4246            let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
4247            let mut start = 0usize;
4248            while start < tp {
4249                let end = (start + fill_chunk).min(tp);
4250                let tc = end - start;
4251                {
4252                    // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
4253                    // reference engine's initial pending-h is zeroed too); a session turn's row 0
4254                    // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
4255                    // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
4256                    let mut phs = e.zeros(tc * n_embd)?;
4257                    let (src_lo, dst_off) = if start == 0 {
4258                        (0, n_embd)
4259                    } else {
4260                        ((start - 1) * n_embd, 0)
4261                    };
4262                    let n_copy = if start == 0 {
4263                        (tc - 1) * n_embd
4264                    } else {
4265                        tc * n_embd
4266                    };
4267                    if start == 0 {
4268                        if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
4269                            if let Some(lh) = lh.as_ref() {
4270                                e.copy_into(&mut phs, 0, lh, n_embd)?;
4271                            }
4272                        }
4273                    }
4274                    if n_copy > 0 {
4275                        e.copy_view_into(
4276                            &mut phs,
4277                            dst_off,
4278                            &ph.slice(src_lo..src_lo + n_copy),
4279                            n_copy,
4280                        )?;
4281                    }
4282                    self.mtp_kv_fill(
4283                        e,
4284                        mtp,
4285                        &prompt[start..end],
4286                        &phs,
4287                        base + start,
4288                        &mut *scratch,
4289                        embd_dev,
4290                    )?;
4291                }
4292                start = end;
4293            }
4294        }
4295        // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
4296        // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
4297        // (=1 brackets the whole call in run_spec.rs, prime included.)
4298        if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
4299            unsafe extern "C" {
4300                fn cudaProfilerStart() -> i32;
4301            }
4302            unsafe {
4303                cudaProfilerStart();
4304            }
4305        }
4306        // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
4307        // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
4308        // consume each other's device outputs; the host drains the ring every M rounds. v1
4309        // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
4310        // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
4311        // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
4312        // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
4313        // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
4314        let stream_on = crate::spec::spec_stream()
4315            && !sampled
4316            && !spec_replay
4317            && constraint.is_none()
4318            && !session_mode
4319            && embd_gpu.is_some()
4320            && !crate::model::full_prec_enabled()
4321            && k + 2 < 96;
4322        let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
4323        let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
4324        if stream_on {
4325            let cap = e.capture_graph(|e| {
4326                for j in 0..k.max(1) {
4327                    self.mtp_head_forward_cap(
4328                        e,
4329                        mtp,
4330                        &mut dctx.g_tok,
4331                        &mut dctx.g_pos,
4332                        &mut dctx.g_seed,
4333                        &mut dctx.g_p,
4334                        &mut *scratch,
4335                        true,
4336                        true,
4337                        embd_gpu.expect("round stream requires resident embedding"),
4338                        embd_qt,
4339                        embd_rb,
4340                        d_vocab,
4341                        None,
4342                        Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
4343                        None, // round-stream requires constraint.is_none() (see stream_on)
4344                    )?;
4345                }
4346                Ok(())
4347            });
4348            match cap {
4349                Ok(g) => {
4350                    scratch.set_len(e, 0)?;
4351                    stream_graph = Some(g);
4352                }
4353                Err(err) => {
4354                    scratch.set_len(e, 0)?;
4355                    if debug_spec {
4356                        eprintln!("[spec] stream-graph capture failed ({err}); stream off");
4357                    }
4358                }
4359            }
4360        }
4361        let stream_active = stream_on && stream_graph.is_some();
4362        if debug_spec {
4363            eprintln!("[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
4364                      crate::spec::spec_stream(), dctx.graph.is_some(), stream_graph.is_some());
4365        }
4366        let t_v_s = k + 1;
4367        // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
4368        // module (extracted 2026-07-12; the gemma burst reuses them).
4369        let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
4370        let crate::round_stream::StreamBufs {
4371            mut vtok_d,
4372            mut brk_d,
4373            mut pend_d,
4374            last_pred_d,
4375            mut pos_ctr,
4376            mut pos_start_d,
4377            mut ring_d,
4378            acc_d: mut stream_acc,
4379            m_rounds,
4380            k: _,
4381        } = sb;
4382        let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
4383            Some(crate::round_stream::kv_len_ptr_table(
4384                e,
4385                cache,
4386                Some(&pos_ctr),
4387            )?)
4388        } else {
4389            None
4390        };
4391
4392        let t_fill = t_ent.elapsed();
4393        let mut round = 0usize;
4394        // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
4395        // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
4396        // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
4397        // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
4398        // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
4399        // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
4400        // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
4401        // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
4402        // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
4403        // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
4404        // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
4405        // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
4406        // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
4407        // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
4408        // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
4409        // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
4410        // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
4411        // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
4412        // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
4413        // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
4414        // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
4415        // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
4416        // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
4417        // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
4418        // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
4419        // K=1..8 self-consistency PASS both models with the law ON (exactness held).
4420        let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
4421        // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
4422        // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
4423        let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
4424            .ok()
4425            .and_then(|v| v.parse().ok());
4426        let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
4427            4
4428        } else if self.cfg.n_embd as usize >= 2500 {
4429            2
4430        } else {
4431            1
4432        };
4433        let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
4434        // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
4435        // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
4436        // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
4437        let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
4438            .ok()
4439            .and_then(|v| v.parse().ok())
4440            .unwrap_or(1024);
4441        let floor_at = |pos: usize| -> usize {
4442            if adapt_floor_env.is_some() || pos < floor_ctx {
4443                adapt_floor
4444            } else if adapt_floor >= 4 {
4445                1
4446            } else {
4447                adapt_floor
4448            }
4449        };
4450        // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
4451        // fixed-K default path is untouched by this whole block.
4452        let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
4453            .ok()
4454            .and_then(|v| v.parse().ok())
4455            .unwrap_or(7);
4456        let k_cap = k.min(cap_max).max(1);
4457        let mut kc = k_cap;
4458        // PERSISTENT snapshot buffers: allocate ONCE, refresh in place each round (was 2 fresh
4459        // D2D clones per linear layer per round = 48 allocs + ~50MB of pool churn per round).
4460        let mut snap = cache.snapshot(e)?;
4461        // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
4462        // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
4463        let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
4464            Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
4465        } else {
4466            None
4467        };
4468        // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
4469        // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
4470        // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
4471        // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
4472        // pass of any kind). Verify still
4473        // checks every emitted token against the target -> exactness holds by construction; only
4474        // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
4475        // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
4476        // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
4477        let mut pending: Option<u32> = carried_pending;
4478                                             // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
4479                                             // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
4480                                             // the verify accept readback). Printed once at loop end via spec-stats.
4481        let phase_on = std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
4482        // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
4483        // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
4484        let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
4485        // grammar-truncation counters: how many rounds the verify-side cut fired and how many
4486        // already-verified tokens it threw away. THIS is the quantity draft masking targets.
4487        let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
4488        let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
4489        let mut ph_wait = 0f64;
4490        let mut ph_t = std::time::Instant::now();
4491        let mut ph_mark = |acc: &mut f64, on: bool| {
4492            if on {
4493                let now = std::time::Instant::now();
4494                *acc += (now - ph_t).as_secs_f64();
4495                ph_t = now;
4496            }
4497        };
4498        while keep_going && out.len() < max_new {
4499            // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
4500            // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
4501            if let (true, Some(sg), Some(ptrs)) = (
4502                stream_active && round >= 1 && pending.is_some(),
4503                &stream_graph,
4504                &stream_ptrs,
4505            ) {
4506                if debug_spec {
4507                    static ONCE: std::sync::Once = std::sync::Once::new();
4508                    ONCE.call_once(|| {
4509                        eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
4510                    });
4511                }
4512                e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
4513                e.set_u32_one(&mut pend_d, pending.unwrap())?;
4514                e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
4515                for _mi in 0..m_rounds {
4516                    e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
4517                    cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
4518                    e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
4519                    e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
4520                    e.u32_copy(&pend_d, &mut dctx.g_tok)?;
4521                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
4522                    sg.launch()?;
4523                    e.spec_assemble_verify(
4524                        &g_tokp2k,
4525                        &pend_d,
4526                        d2t_dev.as_ref(),
4527                        &mut vtok_d,
4528                        &mut brk_d,
4529                        p_min,
4530                        k,
4531                        pmin0,
4532                    )?;
4533                    let mut ck = VerifyCkpt::new(self.layers.len());
4534                    let dummy = vec![0u32; t_v_s];
4535                    let (tl_d, vx) = self.decode_step_t_core_stream(
4536                        e,
4537                        &dummy,
4538                        0,
4539                        &mut *cache,
4540                        embd_dev,
4541                        Some(&mut ck),
4542                        Some((&vtok_d, &pos_ctr)),
4543                    )?;
4544                    for j in 0..t_v_s {
4545                        e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
4546                    }
4547                    e.spec_accept_greedy_dc(
4548                        &preds_d,
4549                        &vtok_d,
4550                        &last_pred_d,
4551                        &brk_d,
4552                        &mut stream_acc,
4553                    )?;
4554                    e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
4555                    e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
4556                    self.commit_verified_prefix_stream(
4557                        e,
4558                        &mut *cache,
4559                        &snap,
4560                        &ck,
4561                        &stream_acc,
4562                        1,
4563                        t_v_s,
4564                    )?;
4565                    e.spec_rollback_stream(
4566                        ptrs,
4567                        &pos_start_d,
4568                        &stream_acc,
4569                        1,
4570                        self.layers.len() + 1,
4571                    )?;
4572                    e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
4573                }
4574                e.stream().synchronize()?;
4575                let ring_h = e.dtoh_u32(&ring_d)?;
4576                let cnt = ring_h[0] as usize;
4577                for i in 0..cnt {
4578                    if out.len() < max_new {
4579                        out.push(ring_h[1 + i]);
4580                    }
4581                }
4582                let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
4583                for il in 0..self.layers.len() {
4584                    if let Some(kvl) = cache.kv[il].as_mut() {
4585                        kvl.len = pos_h;
4586                    }
4587                }
4588                cache.pos = pos_h;
4589                scratch.kv.len = pos_h;
4590                pending = Some(ring_h[cnt]); // last drained token = the live bonus
4591                last_token = ring_h[cnt];
4592                total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
4593                total_accepted += cnt.saturating_sub(m_rounds);
4594                if let Some(t) = sess_telem.as_deref_mut() {
4595                    // totals only — the burst's per-round accept counts stayed on device
4596                    // (that is the point of the round-stream arm). pos_* untouched.
4597                    t.rounds += m_rounds as u64;
4598                    t.drafted += (k * m_rounds) as u64;
4599                    t.accepted += cnt.saturating_sub(m_rounds) as u64;
4600                }
4601                round += m_rounds;
4602                // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
4603                keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
4604                continue;
4605            }
4606            let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
4607            cache.snapshot_into(e, &mut snap)?; // §C: snapshot BEFORE draft+verify
4608            ph_mark(&mut ph_rest, phase_on);
4609
4610            // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
4611            // p-min semantics (both paths): stop the chain early when the head's confidence in
4612            // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
4613            // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
4614            let base0 = if pending.is_some() { 1usize } else { 0usize };
4615            // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
4616            // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
4617            // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
4618            // rejected drafts and p-min extras via the len mechanism).
4619            scratch.set_len(e, pos + base0 - 1)?;
4620            if pen_on {
4621                let w0 = pen_hist.len().saturating_sub(sp.penalty_last_n);
4622                pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
4623            }
4624            // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
4625            // accepted run + 1 (the gemma law — see the setup block above the loop).
4626            let k_this = if adapt { kc } else { k };
4627            let mut draft: Vec<u32> = Vec::with_capacity(k);
4628            let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
4629            if sampled {
4630                draft_logits.clear();
4631                draft_stats.clear();
4632            }
4633            // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
4634            // position's mask is computed on that clone and advanced by the PROPOSED token. The
4635            // real state moves only on emission (verify's job), so the emitted stream is
4636            // unchanged — the mask only removes tokens the verify would have truncated anyway.
4637            let mut dmask_live = dmask_on;
4638            if dmask_live {
4639                let t_c = std::time::Instant::now();
4640                constraint
4641                    .as_deref_mut()
4642                    .unwrap()
4643                    .draft_begin()
4644                    .map_err(|e2| format!("constraint: {e2}"))?;
4645                dm_clone_ns += t_c.elapsed().as_nanos();
4646                dm_rounds += 1;
4647            }
4648            if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
4649                // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
4650                // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
4651                // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
4652                e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
4653                e.set_u32_one(&mut dctx.g_tok, last_token)?;
4654                e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
4655                for j in 0..k_this {
4656                    // per-position mask upload (contents only — the graph's baked pointer is
4657                    // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
4658                    // mask node degrades to a no-op ban instead of needing a second graph.
4659                    if dmask_live
4660                        && !upload_draft_mask(
4661                            e,
4662                            constraint.as_deref_mut().unwrap(),
4663                            &mut dctx.g_dmask,
4664                            mtp.d2t.as_ref(),
4665                            d_vocab,
4666                            dmask_words,
4667                        )?
4668                    {
4669                        // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
4670                        // genuinely miss the legal set): neutralize the captured mask node and
4671                        // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
4672                        e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
4673                        dmask_live = false;
4674                    }
4675                    gr.launch()?;
4676                    scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
4677                    let idx = e.dtoh_u32_one(&dctx.g_tok)?;
4678                    // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
4679                    // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
4680                    // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
4681                    // replay's embed node, and the MMU fault kills the CUDA context for the
4682                    // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
4683                    // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
4684                    // buffer (g_seed = the verify-side handoff vs head-side compute).
4685                    if (idx as usize) >= d_vocab {
4686                        // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
4687                        // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
4688                        // seed, untouched since the round-start copy — the pair discriminates
4689                        // "seed arrived poisoned" from "head forward produced NaN".
4690                        let seed_h = e.dtoh(&dctx.g_seed)?;
4691                        let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
4692                        let in_h = e.dtoh(&h_seed_buf)?;
4693                        let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
4694                        return Err(format!(
4695                            "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
4696                             round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
4697                             round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
4698                             the embed row (#87 trap)"
4699                        )
4700                        .into());
4701                    }
4702                    // trimmed draft vocab -> target token id (identity when no d2t map)
4703                    let d = match &mtp.d2t {
4704                        Some(map) => map[idx as usize],
4705                        None => idx,
4706                    };
4707                    if p_min > 0.0 {
4708                        let p = e.dtoh(&dctx.g_p)?[0];
4709                        if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
4710                            break;
4711                        }
4712                    }
4713                    draft.push(d);
4714                    // with a trimmed head the NEXT embed must read the TARGET id, not the draft
4715                    // index the argmax wrote — patch the persistent token buffer (4B htod).
4716                    if d != idx {
4717                        e.set_u32_one(&mut dctx.g_tok, d)?;
4718                    }
4719                    // advance the SPECULATIVE state with the proposal; a dead chain drops to
4720                    // unmasked drafting for the remaining positions (verify still arbitrates).
4721                    // speculative advance; a chain the grammar can no longer follow (EOS
4722                    // proposed) ends here. The captured mask node always runs, so a dead chain
4723                    // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
4724                    if dmask_live
4725                        && !constraint
4726                            .as_deref_mut()
4727                            .unwrap()
4728                            .draft_advance(d)
4729                            .map_err(|e2| format!("constraint: {e2}"))?
4730                    {
4731                        e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
4732                        break;
4733                    }
4734                }
4735            } else if let (true, Some(gr)) = (sampled, &dctx.graph_s) {
4736                // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
4737                // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
4738                // and decides the break. Event-counter continuity: g_ctr is host-seeded to
4739                // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
4740                // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
4741                // stream. Host sctr advances in lockstep (computed, no readback needed).
4742                e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
4743                e.set_u32_one(&mut dctx.g_tok, last_token)?;
4744                e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
4745                e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
4746                for j in 0..k_this {
4747                    gr.launch()?;
4748                    scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
4749                    sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
4750                               // counts the p-min-discarded token too)
4751                               // q retention: ONE async D2D of the persistent head-logits buffer into this
4752                               // round's slot j (stream-ordered after the replay, before the next one).
4753                    e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
4754                    let idx = e.dtoh_u32_one(&dctx.g_tok)?;
4755                    // #87 SENTINEL TRAP (see the greedy graph arm above).
4756                    if (idx as usize) >= d_vocab {
4757                        let seed_h = e.dtoh(&dctx.g_seed)?;
4758                        let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
4759                        return Err(format!(
4760                            "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
4761                             {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
4762                             {seed_nan}/{n_embd} — refusing to dereference the embed row \
4763                             (#87 trap)"
4764                        )
4765                        .into());
4766                    }
4767                    let d = match &mtp.d2t {
4768                        Some(map) => map[idx as usize],
4769                        None => idx,
4770                    };
4771                    draft_idx.push(idx);
4772                    if p_min > 0.0 {
4773                        let p = e.dtoh(&dctx.g_p)?[0];
4774                        if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
4775                            break;
4776                        }
4777                    }
4778                    draft.push(d);
4779                    // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
4780                    if d != idx {
4781                        e.set_u32_one(&mut dctx.g_tok, d)?;
4782                    }
4783                }
4784                // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
4785                // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
4786                for j in 0..draft.len().max(draft_idx.len()) {
4787                    let rows0 = e.htod_i32(&[0])?;
4788                    let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
4789                    e.filter_stats(
4790                        &dctx.q_slots[j],
4791                        d_vocab,
4792                        &rows0,
4793                        &mut th_d,
4794                        &mut z_d,
4795                        &mut mx_d,
4796                        d_vocab,
4797                        1,
4798                        sp_temp,
4799                        sp.top_k,
4800                        sp.top_p,
4801                        sp.min_p,
4802                    )?;
4803                    draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
4804                }
4805            } else {
4806                // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
4807                let mut e_tok = last_token;
4808                let mut d_seed = e.clone_dtod(&h_seed_buf)?;
4809                for j in 0..k_this {
4810                    // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
4811                    // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
4812                    let mtp_pos = pos + base0 + j;
4813                    // draft-side grammar mask (eager twin of the graph arm's in-graph node).
4814                    // A position with no legal draft-vocab row drops to unmasked drafting for
4815                    // the rest of the chain (pre-lane behaviour; verify still arbitrates).
4816                    if dmask_live {
4817                        dmask_live = upload_draft_mask(
4818                            e,
4819                            constraint.as_deref_mut().unwrap(),
4820                            &mut dctx.g_dmask,
4821                            mtp.d2t.as_ref(),
4822                            d_vocab,
4823                            dmask_words,
4824                        )?;
4825                    }
4826                    let (dl_d, h_nextn) = self.mtp_head_forward_dev(
4827                        e,
4828                        mtp,
4829                        e_tok,
4830                        &d_seed,
4831                        &mut *scratch,
4832                        mtp_pos,
4833                        embd_dev,
4834                        if dmask_live { Some((&dctx.g_dmask, dmask_words)) } else { None },
4835                    )?;
4836                    let tok_d = if sampled {
4837                        // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
4838                        // the filtered softmax (filters off => th=0, exact v1 semantics).
4839                        if perturb_buf.is_none() {
4840                            perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
4841                        }
4842                        let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
4843                        if pen_on {
4844                            let h = pen_hist_d.as_ref().unwrap();
4845                            let nh = h.len();
4846                            e.penalize_logits(
4847                                &mut q_row,
4848                                h,
4849                                nh,
4850                                sp.penalty_repeat,
4851                                sp.penalty_freq,
4852                                sp.penalty_present,
4853                                d_vocab,
4854                            )?;
4855                        }
4856                        let rows0 = e.htod_i32(&[0])?;
4857                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
4858                        e.filter_stats(
4859                            &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab, 1,
4860                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
4861                        )?;
4862                        let (th, z, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
4863                        let pb = perturb_buf.as_mut().unwrap();
4864                        e.gumbel_perturb_filtered(
4865                            &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
4866                        )?;
4867                        sctr += 1;
4868                        draft_logits.push(q_row);
4869                        draft_stats.push((mx, th, z));
4870                        e.argmax_token_device(pb, d_vocab)?
4871                    } else {
4872                        e.argmax_token_device(&dl_d, d_vocab)?
4873                    };
4874                    let idx = e.dtoh_u32_one(&tok_d)?;
4875                    // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
4876                    // here because the eager chain's operands are all readable: dl_d (the head
4877                    // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
4878                    if (idx as usize) >= d_vocab {
4879                        let dl_h = e.dtoh(&dl_d)?;
4880                        let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
4881                        let seed_h = e.dtoh(&d_seed)?;
4882                        let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
4883                        return Err(format!(
4884                            "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
4885                             round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
4886                             step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
4887                             embed row (#87 trap)"
4888                        )
4889                        .into());
4890                    }
4891                    let d = match &mtp.d2t {
4892                        Some(map) => map[idx as usize],
4893                        None => idx,
4894                    };
4895                    if sampled {
4896                        draft_idx.push(idx);
4897                    }
4898                    if p_min > 0.0 {
4899                        let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
4900                        let p = e.dtoh(&p_d)?[0];
4901                        if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
4902                            break;
4903                        }
4904                    }
4905                    draft.push(d);
4906                    e_tok = d;
4907                    d_seed = h_nextn;
4908                    // speculative advance; a chain the grammar can no longer follow (EOS
4909                    // proposed) ends here — the prefix already proposed still rides verify.
4910                    if dmask_live
4911                        && !constraint
4912                            .as_deref_mut()
4913                            .unwrap()
4914                            .draft_advance(d)
4915                            .map_err(|e2| format!("constraint: {e2}"))?
4916                    {
4917                        break;
4918                    }
4919                }
4920            }
4921            let k_round = draft.len();
4922
4923            ph_mark(&mut ph_draft, phase_on);
4924            // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
4925            //         (committing its KV/recur inside the SAME weight read); drafts follow. ---
4926            let verify_tokens: Vec<u32> = match pending {
4927                Some(b) => {
4928                    let mut v = Vec::with_capacity(k_round + 1);
4929                    v.push(b);
4930                    v.extend_from_slice(&draft);
4931                    v
4932                }
4933                None => draft.clone(),
4934            };
4935            let base = if pending.is_some() { 1 } else { 0 };
4936            // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
4937            // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
4938            let mut ckpt = if spec_replay {
4939                None
4940            } else {
4941                Some(VerifyCkpt::new(self.layers.len()))
4942            };
4943            let (tlogits_d, vx) = self.decode_step_t_core(
4944                e,
4945                &verify_tokens,
4946                pos,
4947                &mut *cache,
4948                embd_dev,
4949                ckpt.as_mut(),
4950            )?;
4951
4952            ph_mark(&mut ph_verify, phase_on);
4953            // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
4954            // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
4955            // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
4956            // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
4957            // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
4958            // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
4959            // (== the bonus), so every index shifts by `base` and last_pred is unused.
4960            let t_v = verify_tokens.len();
4961            let mut preds: Vec<u32> = Vec::new();
4962            if !sampled {
4963                for j in 0..t_v {
4964                    e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
4965                }
4966                preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
4967                // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
4968                // next round's last_token = the next chain's embed lookup. Catch it at the
4969                // source with the column named — an all-NaN VERIFY column implicates the
4970                // stage-split trunk (decode_step_t_core_ppn), not the draft head.
4971                if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
4972                    let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
4973                    let mut probe = e.zeros(n_vocab)?;
4974                    e.copy_view_into(&mut probe, 0, col, n_vocab)?;
4975                    let col_h = e.dtoh(&probe)?;
4976                    let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
4977                    return Err(format!(
4978                        "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
4979                         col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
4980                         — the stage-split verify produced a poisoned column (#87 trap)",
4981                        preds[bad]
4982                    )
4983                    .into());
4984                }
4985            }
4986            ph_mark(&mut ph_wait, phase_on);
4987            let t_pred = |j: usize| -> u32 {
4988                if j == 0 && base == 0 {
4989                    last_pred
4990                } else {
4991                    preds[base + j - 1]
4992                }
4993            };
4994            let mut devacc_seeded = false;
4995            let mut devacc_acc: Option<CudaSlice<u32>> = None;
4996            let (n_acc, bonus) = if !sampled {
4997                // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
4998                // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
4999                // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
5000                // gated on token identity vs the host walk (the arms below are bit-equal rules).
5001                if crate::spec::spec_devacc() && k_round > 0 && !spec_replay
5002                    && constraint.is_none() {
5003                    let draft_d = e.htod_u32_v(&draft)?;
5004                    let mut acc_out = e.alloc_u32_zeroed(2)?;
5005                    e.spec_accept_greedy(
5006                        &preds_d,
5007                        &draft_d,
5008                        last_pred,
5009                        base,
5010                        k_round,
5011                        &mut acc_out,
5012                    )?;
5013                    devacc_acc = Some(acc_out.clone());
5014                    // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
5015                    // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
5016                    // non-replay commit arms skip their host-offset seed copies (guarded below);
5017                    // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
5018                    // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
5019                    // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
5020                    // the update lands after the arms (devacc_seeded guard below).
5021                    e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
5022                    // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
5023                    // unified rule; full accept rewrites the verify-left value). Host mirrors
5024                    // update after the readback; commit_verified_prefix skips its len_d writes.
5025                    if let Some(ptrs) = &kv_len_ptrs {
5026                        let saved: Vec<i32> = (0..self.layers.len())
5027                            .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
5028                            .collect();
5029                        let saved_d = e.htod_i32(&saved)?;
5030                        e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
5031                    }
5032                    devacc_seeded = true;
5033                    let ab = e.dtoh_u32(&acc_out)?;
5034                    (ab[0] as usize, ab[1])
5035                } else {
5036                    let mut n_acc = 0usize;
5037                    for j in 0..k_round {
5038                        if t_pred(j) == draft[j] {
5039                            n_acc += 1;
5040                        } else {
5041                            break;
5042                        }
5043                    }
5044                    // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
5045                    // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
5046                    (n_acc, t_pred(n_acc))
5047                }
5048            } else {
5049                // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
5050                if col_buf.is_none() {
5051                    col_buf = Some(e.zeros(n_vocab)?);
5052                }
5053                // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
5054                // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
5055                let mut pj = vec![0f32; k_round.max(1)];
5056                let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
5057                if k_round > 0 {
5058                    let mut ids: Vec<u32> = Vec::new();
5059                    let mut rows: Vec<i32> = Vec::new();
5060                    for j in 0..k_round {
5061                        if j > 0 || base == 1 {
5062                            ids.push(draft[j]);
5063                            rows.push((base + j) as i32 - 1);
5064                        }
5065                    }
5066                    if !ids.is_empty() {
5067                        let nr = rows.len();
5068                        // penalties: materialize the used columns into one contiguous penalized
5069                        // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
5070                        // penalties: materialize used columns contiguously, penalize all rows in
5071                        // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
5072                        let p_rows: Vec<i32> = if pen_on {
5073                            (0..nr as i32).collect()
5074                        } else {
5075                            rows.clone()
5076                        };
5077                        if pen_on {
5078                            if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
5079                                pcol_buf = Some(e.zeros(nr * n_vocab)?);
5080                            }
5081                            let pc = pcol_buf.as_mut().unwrap();
5082                            for (i2, &r) in rows.iter().enumerate() {
5083                                let c = r as usize;
5084                                e.copy_view_into(
5085                                    pc,
5086                                    i2 * n_vocab,
5087                                    &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
5088                                    n_vocab,
5089                                )?;
5090                            }
5091                            let h = pen_hist_d.as_ref().unwrap();
5092                            let nh = h.len();
5093                            e.penalize_logits_rows(
5094                                pc,
5095                                h,
5096                                nh,
5097                                sp.penalty_repeat,
5098                                sp.penalty_freq,
5099                                sp.penalty_present,
5100                                n_vocab,
5101                                nr,
5102                            )?;
5103                        }
5104                        let p_src: &CudaSlice<f32> = if pen_on {
5105                            pcol_buf.as_ref().unwrap()
5106                        } else {
5107                            &tlogits_d
5108                        };
5109                        let rowsd = e.htod_i32(&p_rows)?;
5110                        let (mut th_d, mut z_d, mut mx_d) =
5111                            (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
5112                        e.filter_stats(
5113                            p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
5114                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
5115                        )?;
5116                        let idsd = e.htod_u32_v(&ids)?;
5117                        let mut outd = e.zeros(nr)?;
5118                        e.softmax_gather_filtered(
5119                            p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
5120                            sp_temp,
5121                        )?;
5122                        let outv = e.dtoh(&outd)?;
5123                        let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
5124                        let mut oi = 0usize;
5125                        for j in 0..k_round {
5126                            if j > 0 || base == 1 {
5127                                pj[j] = outv[oi];
5128                                oi += 1;
5129                            }
5130                        }
5131                        col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
5132                    }
5133                    if base == 0 {
5134                        let lc: &CudaSlice<f32> = if pen_on {
5135                            if col_buf.is_none() {
5136                                col_buf = Some(e.zeros(n_vocab)?);
5137                            }
5138                            let cb = col_buf.as_mut().unwrap();
5139                            e.copy_into(
5140                                cb,
5141                                0,
5142                                last_col_logits
5143                                    .as_ref()
5144                                    .expect("sampled: last_col_logits unset"),
5145                                n_vocab,
5146                            )?;
5147                            let h = pen_hist_d.as_ref().unwrap();
5148                            let nh = h.len();
5149                            e.penalize_logits(
5150                                cb,
5151                                h,
5152                                nh,
5153                                sp.penalty_repeat,
5154                                sp.penalty_freq,
5155                                sp.penalty_present,
5156                                n_vocab,
5157                            )?;
5158                            col_buf.as_ref().unwrap()
5159                        } else {
5160                            last_col_logits
5161                                .as_ref()
5162                                .expect("sampled: last_col_logits unset")
5163                        };
5164                        let rows0 = e.htod_i32(&[0])?;
5165                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
5166                        e.filter_stats(
5167                            lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
5168                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
5169                        )?;
5170                        let idsd = e.htod_u32_v(&[draft[0]])?;
5171                        let mut outd = e.zeros(1)?;
5172                        e.softmax_gather_filtered(
5173                            lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
5174                        )?;
5175                        pj[0] = e.dtoh(&outd)?[0];
5176                        last_col_stats =
5177                            Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
5178                    }
5179                }
5180                // q source: the graph arm retained the head logits in the persistent q_slots;
5181                // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
5182                // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
5183                // computes them post-replay — graph engages only filter/penalty-free, so the
5184                // stats degenerate to th=0/full-Z there, keeping ONE accept path).
5185                let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
5186                    &dctx.q_slots
5187                } else {
5188                    &draft_logits
5189                };
5190                let mut n_acc = 0usize;
5191                for j in 0..k_round {
5192                    let (qmx, qth, qz) = draft_stats[j];
5193                    let idsd = e.htod_u32_v(&[draft_idx[j]])?;
5194                    let rowsd = e.htod_i32(&[0])?;
5195                    let thd = e.htod(&[qth])?;
5196                    let zd = e.htod(&[qz])?;
5197                    let _ = qmx;
5198                    let mut outd = e.zeros(1)?;
5199                    e.softmax_gather_filtered(
5200                        &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
5201                        sp_temp,
5202                    )?;
5203                    let qj = e.dtoh(&outd)?[0];
5204                    let u = host_u01(sp_seed, uctr);
5205                    uctr += 1;
5206                    if (u as f64) * (qj as f64) < pj[j] as f64 {
5207                        n_acc += 1;
5208                    } else {
5209                        break;
5210                    }
5211                }
5212                let bonus = if n_acc == k_round {
5213                    // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
5214                    let col = base + k_round - 1;
5215                    let cb = col_buf.as_mut().unwrap();
5216                    e.copy_view_into(
5217                        cb,
5218                        0,
5219                        &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
5220                        n_vocab,
5221                    )?;
5222                    if pen_on {
5223                        let h = pen_hist_d.as_ref().unwrap();
5224                        let nh = h.len();
5225                        e.penalize_logits(
5226                            cb,
5227                            h,
5228                            nh,
5229                            sp.penalty_repeat,
5230                            sp.penalty_freq,
5231                            sp.penalty_present,
5232                            n_vocab,
5233                        )?;
5234                    }
5235                    if perturb_buf.is_none() {
5236                        perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
5237                    }
5238                    // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
5239                    // truncation-fix; receipts research/sampfix-20260805/). The old code reused
5240                    // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
5241                    // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
5242                    // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
5243                    // last gathered column, in both base arms. `th` is a threshold in e-units of
5244                    // its OWN row's max, so feeding a neighbour's (row_max, th) into
5245                    // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
5246                    // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
5247                    // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
5248                    // falls through to its smallest-index tie-break => token id 0 ("!") spliced
5249                    // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
5250                    // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
5251                    // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
5252                    // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
5253                    // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
5254                    // and row_max is unused once nothing is masked), so this fix is a byte-level
5255                    // no-op for the untruncated serve default. One extra one-block filter_stats
5256                    // per full-accept round is the whole cost.
5257                    let (mx, th) = {
5258                        let rows0 = e.htod_i32(&[0])?;
5259                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
5260                        let cb0 = col_buf.as_ref().unwrap();
5261                        e.filter_stats(
5262                            cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
5263                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
5264                        )?;
5265                        (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
5266                    };
5267                    let pb = perturb_buf.as_mut().unwrap();
5268                    let cb2 = col_buf.as_ref().unwrap();
5269                    e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
5270                    sctr += 1;
5271                    let td = e.argmax_token_device(pb, n_vocab)?;
5272                    e.dtoh_u32_one(&td)?
5273                } else {
5274                    // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
5275                    let cb = col_buf.as_mut().unwrap();
5276                    if n_acc > 0 || base == 1 {
5277                        let col = base + n_acc - 1;
5278                        e.copy_view_into(
5279                            cb,
5280                            0,
5281                            &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
5282                            n_vocab,
5283                        )?;
5284                    } else {
5285                        let lc = last_col_logits.as_ref().unwrap();
5286                        e.copy_into(cb, 0, lc, n_vocab)?;
5287                    }
5288                    if pen_on {
5289                        let h = pen_hist_d.as_ref().unwrap();
5290                        let nh = h.len();
5291                        e.penalize_logits(
5292                            cb,
5293                            h,
5294                            nh,
5295                            sp.penalty_repeat,
5296                            sp.penalty_freq,
5297                            sp.penalty_present,
5298                            n_vocab,
5299                        )?;
5300                    }
5301                    let cb2 = col_buf.as_ref().unwrap();
5302                    let sc = sctr;
5303                    sctr += 1;
5304                    // p-stats for the reject column: from col_stats when the col was gathered,
5305                    // else (j==0&&base==0) from last_col_stats.
5306                    let p_stats = if n_acc > 0 || base == 1 {
5307                        // col index within the gathered set == number of gathered cols before n_acc
5308                        let gi = if base == 1 { n_acc } else { n_acc - 1 };
5309                        col_stats.get(gi).copied().unwrap_or_else(|| {
5310                            (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
5311                        })
5312                    } else {
5313                        last_col_stats.expect("sampled: last_col_stats unset at reject")
5314                    };
5315                    let q_stats = draft_stats[n_acc];
5316                    if let Some(map) = &d2t_dev {
5317                        if q_full_buf.is_none() {
5318                            q_full_buf = Some(e.zeros(n_vocab)?);
5319                        }
5320                        let qf = q_full_buf.as_mut().unwrap();
5321                        e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
5322                        let qf2 = q_full_buf.as_ref().unwrap();
5323                        e.residual_sample_filtered(
5324                            cb2,
5325                            Some(qf2),
5326                            n_vocab,
5327                            sp_temp,
5328                            sp_seed,
5329                            sc,
5330                            p_stats,
5331                            q_stats,
5332                            &mut sample_tok,
5333                        )?;
5334                    } else {
5335                        e.residual_sample_filtered(
5336                            cb2,
5337                            Some(&q_bufs[n_acc]),
5338                            n_vocab,
5339                            sp_temp,
5340                            sp_seed,
5341                            sc,
5342                            p_stats,
5343                            q_stats,
5344                            &mut sample_tok,
5345                        )?;
5346                    }
5347                    e.dtoh_u32(&sample_tok)?[0]
5348                };
5349                (n_acc, bonus)
5350            };
5351            // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
5352            // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
5353            // ordering). Walk the accepted drafts through the grammar in commit order; the
5354            // first illegal token truncates acceptance at its slot, and that slot's emission
5355            // is recomputed as the MASKED argmax of the target's own verify column — token-
5356            // identical to constrained plain greedy decode (an unmasked argmax that is
5357            // grammar-legal IS the masked argmax: masking only removes competitors). The
5358            // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
5359            // measured in acceptance numbers, never hidden.
5360            let (n_acc, bonus) = match constraint.as_deref_mut() {
5361                None => (n_acc, bonus),
5362                Some(c) => {
5363                    fn ce(e2: String) -> Box<dyn std::error::Error> {
5364                        format!("constraint: {e2}").into()
5365                    }
5366                    let mut na = n_acc;
5367                    let mut cut = false;
5368                    for (j, &d) in draft.iter().enumerate().take(n_acc) {
5369                        if c.is_allowed(d).map_err(ce)? {
5370                            c.consume(d).map_err(ce)?;
5371                        } else {
5372                            na = j;
5373                            cut = true;
5374                            dm_cut_tokens += n_acc - j;
5375                            break;
5376                        }
5377                    }
5378                    if cut {
5379                        dm_cuts += 1;
5380                    }
5381                    let mut bo = bonus;
5382                    if cut || !c.is_allowed(bo).map_err(ce)? {
5383                        let mut row = if na == 0 && base == 0 {
5384                            init_logits_host.clone()
5385                                .ok_or("constraint: init logits missing (round-0 cut)")?
5386                        } else {
5387                            e.dtoh_view(&tlogits_d.slice(
5388                                (base + na - 1) * n_vocab..(base + na) * n_vocab))?
5389                        };
5390                        c.mask_logits(&mut row).map_err(ce)?;
5391                        bo = argmax(&row) as u32;
5392                    }
5393                    c.consume(bo).map_err(ce)?;
5394                    (na, bo)
5395                }
5396            };
5397            total_drafted += k_round;
5398            total_accepted += n_acc;
5399            if let Some(t) = sess_telem.as_deref_mut() {
5400                // per-position accept walk (lane/accept-telemetry): host u64 adds on counts
5401                // the round already read back — zero syncs, zero allocation.
5402                t.rounds += 1;
5403                t.drafted += k_round as u64;
5404                t.accepted += n_acc as u64;
5405                for j in 0..k_round.min(SPEC_TELEM_POS) {
5406                    t.pos_drafted[j] += 1;
5407                }
5408                for j in 0..n_acc.min(SPEC_TELEM_POS) {
5409                    t.pos_accepted[j] += 1;
5410                }
5411            }
5412            if spec_stats {
5413                st_len_hist[k_round] += 1;
5414                for j in 0..k_round {
5415                    st_drafted[j] += 1;
5416                }
5417                for j in 0..n_acc {
5418                    st_accepted[j] += 1;
5419                }
5420                if n_acc == k_round {
5421                    st_full += 1;
5422                }
5423            }
5424
5425            if debug_spec {
5426                eprintln!("[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}", out.len(), t_pred(0));
5427            }
5428
5429            // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
5430            // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
5431            // of them (overshoot past max_new included) or `committed` under-counts the cache rows
5432            // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
5433            // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
5434            for j in 0..n_acc {
5435                if !session_mode && out.len() >= max_new {
5436                    break;
5437                }
5438                out.push(draft[j]);
5439            }
5440            if pen_on {
5441                pen_hist.extend_from_slice(&draft[0..n_acc]);
5442                pen_hist.push(bonus);
5443            }
5444            let bonus_emitted = session_mode || out.len() < max_new;
5445            if bonus_emitted {
5446                out.push(bonus);
5447            }
5448            last_token = bonus;
5449
5450            // --- 5. ROLLBACK + advance (§C) ---
5451            if n_acc == k_round {
5452                // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
5453                // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
5454                // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
5455                // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
5456                // last_pred is dead in the pending path (t_pred reads verify col 0).
5457                //
5458                // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
5459                // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
5460                // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
5461                // trunk hidden (the last verify column). set_len first: a p-min break may have
5462                // left one extra chain append at that slot. Partial accepts need NO fill (the
5463                // chain already covered every accepted position; round-start set_len truncates).
5464                let mut vh_seed = e.zeros(n_embd)?;
5465                e.copy_view_into(
5466                    &mut vh_seed,
5467                    0,
5468                    &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
5469                    n_embd,
5470                )?;
5471                if refresh {
5472                    // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
5473                    // overwrite ALL committed positions' scratch entries with K/V from their EXACT
5474                    // verify hiddens — the reference engine's mtp_update fills from true hiddens;
5475                    // the full stack (vx) is already resident from the verify. Replaces both the
5476                    // chain-approximate entries AND the old last-token-only fill. Acceptance-only
5477                    // (draft attention quality); exactness stays the verify's job.
5478                    scratch.set_len(e, pos)?;
5479                    // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
5480                    // (hidden of the last committed row before this verify batch).
5481                    let mut vxs = e.zeros(t_v * n_embd)?;
5482                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
5483                    if t_v > 1 {
5484                        e.copy_view_into(
5485                            &mut vxs,
5486                            n_embd,
5487                            &vx.slice(0..(t_v - 1) * n_embd),
5488                            (t_v - 1) * n_embd,
5489                        )?;
5490                    }
5491                    self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
5492                } else {
5493                    scratch.set_len(e, pos + base + k_round - 1)?;
5494                    // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
5495                    let mut hp = e.zeros(n_embd)?;
5496                    if t_v >= 2 {
5497                        e.copy_view_into(
5498                            &mut hp,
5499                            0,
5500                            &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
5501                            n_embd,
5502                        )?;
5503                    } else {
5504                        e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
5505                    }
5506                    self.mtp_kv_fill(
5507                        e,
5508                        mtp,
5509                        &[draft[k_round - 1]],
5510                        &hp,
5511                        pos + base + k_round - 1,
5512                        &mut *scratch,
5513                        embd_dev,
5514                    )?;
5515                }
5516                // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
5517                // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
5518                // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
5519                // col). Saves one MTP-block pass per round on top of the pairing fix.
5520                if !devacc_seeded {
5521                    e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
5522                    e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
5523                }
5524                pending = Some(bonus);
5525                if debug_spec {
5526                    eprintln!("  -> FULL ACCEPT (bonus pending, prev-h seed)");
5527                }
5528            } else if !spec_replay && base + n_acc >= 1 {
5529                // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
5530                // the verify's first j = base+n_acc columns ARE the committed sequence, computed
5531                // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
5532                // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
5533                // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
5534                // full-accept path — the legacy duplicate trunk replay is gone. The next chain
5535                // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
5536                // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
5537                // accept (never compounds: the next verify recomputes true hiddens for all
5538                // committed columns).
5539                let j = base + n_acc;
5540                self.commit_verified_prefix(
5541                    e,
5542                    &mut *cache,
5543                    &snap,
5544                    ckpt.as_ref().unwrap(),
5545                    j,
5546                    devacc_seeded,
5547                    if devacc_seeded {
5548                        devacc_acc.as_ref().map(|a| (a, base, t_v))
5549                    } else {
5550                        None
5551                    },
5552                )?;
5553                let mut seed = e.zeros(n_embd)?;
5554                e.copy_view_into(
5555                    &mut seed,
5556                    0,
5557                    &vx.slice((j - 1) * n_embd..j * n_embd),
5558                    n_embd,
5559                )?;
5560                // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
5561                // branch); without it the chain entries stand and only the tail truncates. Either
5562                // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
5563                // (persistent mode), rope pos+j+1 (chain convention).
5564                if refresh {
5565                    scratch.set_len(e, pos)?;
5566                    let mut vxs = e.zeros(j * n_embd)?;
5567                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
5568                    if j > 1 {
5569                        e.copy_view_into(
5570                            &mut vxs,
5571                            n_embd,
5572                            &vx.slice(0..(j - 1) * n_embd),
5573                            (j - 1) * n_embd,
5574                        )?;
5575                    }
5576                    self.mtp_kv_fill(
5577                        e,
5578                        mtp,
5579                        &verify_tokens[0..j],
5580                        &vxs,
5581                        pos,
5582                        &mut *scratch,
5583                        embd_dev,
5584                    )?;
5585                } else {
5586                    scratch.set_len(e, pos + j)?;
5587                }
5588                // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
5589                // bonus's predecessor (verify col j-1); no pseudo pass.
5590                if !devacc_seeded {
5591                    e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
5592                    e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
5593                }
5594                pending = Some(bonus);
5595                if debug_spec {
5596                    eprintln!("  -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
5597                }
5598            } else if !spec_replay {
5599                // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
5600                // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
5601                // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
5602                // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
5603                // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
5604                // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
5605                // base=1 pending machinery, bit-identical by the decode-exact verify contract.
5606                // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
5607                // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
5608                cache.rollback(e, &snap, 0)?;
5609                scratch.set_len(e, pos)?;
5610                e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
5611                pending = Some(bonus);
5612                if debug_spec {
5613                    eprintln!("  -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
5614                }
5615            } else {
5616                // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
5617                // this round survives, only possible before the first pending exists, ~round 0):
5618                // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
5619                // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
5620                // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
5621                // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
5622                // trunk hidden.
5623                cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
5624                let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
5625                if let Some(b) = pending.take() {
5626                    replay.push(b);
5627                }
5628                replay.extend_from_slice(&draft[0..n_acc]);
5629                replay.push(bonus);
5630                // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
5631                // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
5632                // last col exactly as before (byte-identical to the old _h_emb_dev call).
5633                let (rl_d, rx) =
5634                    self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?;
5635                // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
5636                // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
5637                e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
5638                last_pred = e.dtoh_u32(&preds_d)?[0];
5639                if sampled {
5640                    let lr0 = replay.len();
5641                    let lc = last_col_logits
5642                        .as_mut()
5643                        .expect("sampled: last_col_logits unset");
5644                    e.copy_view_into(
5645                        lc,
5646                        0,
5647                        &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
5648                        n_vocab,
5649                    )?;
5650                }
5651                let lr = replay.len();
5652                if lr >= 2 {
5653                    e.copy_view_into(
5654                        &mut h_seed_buf,
5655                        0,
5656                        &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
5657                        n_embd,
5658                    )?;
5659                } else {
5660                    // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
5661                    // last_token, whose own-row hidden fill_prev still holds.
5662                    e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
5663                }
5664                // the bonus is COMMITTED here — it becomes the last committed row.
5665                let mut rh_last = e.zeros(n_embd)?;
5666                e.copy_view_into(
5667                    &mut rh_last,
5668                    0,
5669                    &rx.slice((lr - 1) * n_embd..lr * n_embd),
5670                    n_embd,
5671                )?;
5672                e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
5673                if debug_spec {
5674                    eprintln!("  -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
5675                }
5676            }
5677            if devacc_seeded {
5678                // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
5679                // consumed the old value (both slots carry the same value in every non-replay arm).
5680                e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
5681            }
5682            // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
5683            // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
5684            // final position — the floor's position key reads the committed depth). Burst
5685            // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
5686            // like gemma's burst arm.
5687            if adapt {
5688                let fl_now = floor_at(cache.pos);
5689                kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
5690            }
5691            ph_mark(&mut ph_rest, phase_on);
5692            round += 1;
5693            // sse-cadence: this round's accepted drafts + bonus are committed (out is
5694            // append-only past step 4) — flush at round cadence.
5695            keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
5696        }
5697        // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
5698        // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
5699        let _ = flush_commit(&mut on_commit, &out, &mut flushed);
5700
5701        if spec_stats {
5702            let per_slot: Vec<String> = (0..k)
5703                .map(|j| {
5704                    if st_drafted[j] > 0 {
5705                        format!(
5706                            "{}/{}={:.3}",
5707                            st_accepted[j],
5708                            st_drafted[j],
5709                            st_accepted[j] as f64 / st_drafted[j] as f64
5710                        )
5711                    } else {
5712                        "0/0".into()
5713                    }
5714                })
5715                .collect();
5716            let acc = if total_drafted > 0 {
5717                total_accepted as f64 / total_drafted as f64
5718            } else {
5719                0.0
5720            };
5721            eprintln!(
5722                "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
5723                       per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
5724                       tok_per_round={:.3}",
5725                per_slot.join(" "),
5726                (total_accepted + round) as f64 / round.max(1) as f64
5727            );
5728        }
5729        if constraint.is_some() {
5730            eprintln!(
5731                "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
5732                 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
5733                dm_clone_ns as f64 / 1e6,
5734                dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
5735            );
5736        }
5737        if phase_on {
5738            let tot = ph_draft + ph_verify + ph_wait + ph_rest;
5739            eprintln!("[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
5740                      ph_draft * 1e3, ph_draft / tot * 100.0,
5741                      ph_verify * 1e3, ph_verify / tot * 100.0,
5742                      ph_wait * 1e3, ph_wait / tot * 100.0,
5743                      ph_rest * 1e3, ph_rest / tot * 100.0);
5744        }
5745        // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
5746        // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
5747        // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
5748        // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
5749        if let Some(slot) = sess_draft_slot.take() {
5750            *slot = Some(dctx);
5751        }
5752        let t_rounds = t_ent.elapsed();
5753        if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
5754            *sctr_slot = sctr;
5755            *uctr_slot = uctr;
5756            *next_pred_slot = Some(last_pred);
5757            let mut stashed_pending = false;
5758            if let Some(b) = pending.take() {
5759                if !sampled {
5760                    // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
5761                    // committing it with a solo T=1 pass — the next empty-suffix greedy burst
5762                    // consumes it as round-0 verify col 0 (a plain round edge; the old tail
5763                    // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
5764                    // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
5765                    // OUT of `committed` (cache rows == committed); the consuming call
5766                    // prepends it once its verify commits the row. next_pred is unknowable
5767                    // without the commit pass — None; callers gate on pending_tok too.
5768                    debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
5769                    if let Some(slot) = sess_pending_slot.take() {
5770                        *slot = Some(b);
5771                    }
5772                    *next_pred_slot = None;
5773                    // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
5774                    // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
5775                    *last_h = Some(e.clone_dtod(&fill_prev)?);
5776                    stashed_pending = true;
5777                } else {
5778                    // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
5779                    // the sampled round-0 accept needs this pass's logits (last_col_logits).
5780                    let pos_b = cache.pos;
5781                    scratch.set_len(e, pos_b)?;
5782                    let (lg_b, hb) = self.decode_step_h(e, b, &mut *cache)?;
5783                    // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
5784                    // itself — the prediction AFTER the bonus never materialized; it would have
5785                    // been the next round's verify col 0). The commit's logits ARE that
5786                    // prediction.
5787                    *next_pred_slot = Some(argmax(&lg_b) as u32);
5788                    self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
5789                    *last_h = Some(hb);
5790                }
5791            } else {
5792                // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
5793                *last_h = Some(e.clone_dtod(&fill_prev)?);
5794            }
5795            committed.extend_from_slice(prompt);
5796            if let Some(cb) = carried_pending {
5797                // the consumed carry's cache row landed in round 0's verify (every pending
5798                // round commits col 0) — it joins `committed` here, in sequence order.
5799                committed.push(cb);
5800            }
5801            if stashed_pending {
5802                // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
5803                // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
5804                // 18446744073709551615 out of range for slice of length 0", killing the
5805                // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
5806                // stream". Reachable because `pending` starts as `carried_pending` (a bonus
5807                // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
5808                // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
5809                // did). So a burst that stashes a pending without emitting anything of its own —
5810                // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
5811                // guard skipping every token under a tight budget — arrives here with
5812                // out.len() == 0 and stashed_pending == true.
5813                //
5814                // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
5815                // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
5816                // just above is already accounted. Saturating, not a min/assert: an empty `out`
5817                // here is a legitimate burst shape, not a corrupt state.
5818                let emitted = out.len().saturating_sub(1);
5819                committed.extend_from_slice(&out[..emitted]);
5820            } else {
5821                committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
5822            }
5823            debug_assert_eq!(
5824                cache.pos,
5825                committed.len(),
5826                "session invariant: cache rows == committed tokens"
5827            );
5828            if setup_trace {
5829                e.stream().synchronize()?; // bound the async tail fill in the trace
5830                let t_tail = t_ent.elapsed();
5831                eprintln!(
5832                    "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
5833                    t_init.as_secs_f64() * 1e3,
5834                    (t_cap - t_init).as_secs_f64() * 1e3,
5835                    (t_fill - t_cap).as_secs_f64() * 1e3,
5836                    (t_rounds - t_fill).as_secs_f64() * 1e3,
5837                    (t_tail - t_rounds).as_secs_f64() * 1e3,
5838                    t_tail.as_secs_f64() * 1e3,
5839                    out.len(),
5840                    continuation
5841                );
5842            }
5843            return Ok((out, total_drafted, total_accepted));
5844        }
5845        out.truncate(max_new);
5846        Ok((out, total_drafted, total_accepted))
5847    }
5848
5849    /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
5850    /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
5851    /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
5852    /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
5853    /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
5854    /// quant-induced head/hidden-state mismatch from text drift.
5855    ///
5856    /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
5857    ///   draft_j  = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
5858    ///              eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
5859    ///   target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
5860    ///              at forced context tokens[0..p+j]). For j==0 this equals live spec
5861    ///              acceptance; for j>=1 live verify would condition on the drafts, here it
5862    ///              conditions on the corpus — deterministic and arm-comparable by design.
5863    ///
5864    /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
5865    /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
5866    /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
5867    ///
5868    /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
5869    /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
5870    /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
5871    /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
5872    /// agreement vs this path — not usable as a training-data source).
5873    pub fn replay_acceptance(
5874        &self,
5875        e: &Engine,
5876        tokens: &[u32],
5877        k: usize,
5878        stride: usize,
5879        chunk: usize,
5880        mut hdump: Option<&mut std::fs::File>,
5881    ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
5882        assert!(k >= 1 && stride >= 1 && chunk >= 2);
5883        let mtp = self
5884            .mtp
5885            .as_ref()
5886            .expect("replay_acceptance requires an MTP head");
5887        let n_vocab = self.output.out_features();
5888        let d_vocab = mtp
5889            .shared_head_head
5890            .as_ref()
5891            .unwrap_or(&self.output)
5892            .out_features();
5893        let n_embd = self.cfg.n_embd as usize;
5894        let t_total = tokens.len();
5895        assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
5896        // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
5897        let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
5898        let mut scratch = MtpScratch::new(
5899            e,
5900            &self.cfg,
5901            t_total + k + 8,
5902            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5903        )?;
5904        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
5905        let embd_gpu = if spec_host_embd() {
5906            None
5907        } else {
5908            Some(
5909                self.embd_gpu
5910                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
5911            )
5912        };
5913        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
5914
5915        // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
5916        let mut bg: Vec<u32> = vec![0; t_total + 1];
5917        let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
5918        let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
5919        let mut seed_buf = e.zeros(n_embd)?;
5920        let mut preds_d = e.alloc_u32_zeroed(chunk)?;
5921        let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
5922        let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
5923        let mut s = 0usize;
5924        while s < t_total {
5925            let cend = (s + chunk).min(t_total);
5926            let tc = cend - s;
5927            let ch = &tokens[s..cend];
5928            // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
5929            //    the chunk's true hiddens.
5930            let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
5931            for j in 0..tc {
5932                e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
5933            }
5934            let preds = e.dtoh_u32(&preds_d)?;
5935            for j in 0..tc {
5936                bg[s + j + 1] = preds[j];
5937            }
5938            // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
5939            // checkpoint-quality metric (position j's logits score the GOLD next token).
5940            if nll_on {
5941                let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
5942                if jmax > 0 {
5943                    let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
5944                    let rows: Vec<i32> = (0..jmax as i32).collect();
5945                    let idsd = e.htod_u32_v(&ids)?;
5946                    let rowsd = e.htod_i32(&rows)?;
5947                    let mut outd = e.zeros(jmax)?;
5948                    e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
5949                    for pr in e.dtoh(&outd)? {
5950                        nll_sum += -((pr.max(1e-30)) as f64).ln();
5951                        nll_cnt += 1;
5952                    }
5953                }
5954            }
5955            if let Some(f) = hdump.as_deref_mut() {
5956                use std::io::Write;
5957                let host: Vec<f32> = e.dtoh(&vx)?;
5958                // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
5959                // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
5960                let mut bytes = Vec::with_capacity(tc * n_embd * 2);
5961                for v in &host[..tc * n_embd] {
5962                    let b = v.to_bits();
5963                    let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
5964                    bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
5965                }
5966                f.write_all(&bytes)?;
5967            }
5968            // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
5969            // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
5970            // per token saved; the forced trunk pass + hdump is all the mode needs).
5971            let chainless = stride > t_total;
5972            if chainless {
5973                e.copy_view_into(
5974                    &mut prev_last_h,
5975                    0,
5976                    &vx.slice((tc - 1) * n_embd..tc * n_embd),
5977                    n_embd,
5978                )?;
5979                s = cend;
5980                continue;
5981            }
5982            // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
5983            //    row s reads the previous chunk's last true hidden, zeros at corpus start).
5984            let mut vxs = e.zeros(tc * n_embd)?;
5985            e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
5986            if tc > 1 {
5987                e.copy_view_into(
5988                    &mut vxs,
5989                    n_embd,
5990                    &vx.slice(0..(tc - 1) * n_embd),
5991                    (tc - 1) * n_embd,
5992                )?;
5993            }
5994            scratch.set_len(e, s)?;
5995            self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
5996            // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
5997            //    [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
5998            //    truncates those approximate appends before they can ever be read.
5999            let ps: Vec<usize> = (s..cend)
6000                .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
6001                .collect();
6002            for &p in ps.iter().rev() {
6003                scratch.set_len(e, p)?;
6004                if p == s {
6005                    e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
6006                } else {
6007                    e.copy_view_into(
6008                        &mut seed_buf,
6009                        0,
6010                        &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
6011                        n_embd,
6012                    )?;
6013                }
6014                let mut e_tok = tokens[p];
6015                let mut d_seed = e.clone_dtod(&seed_buf)?;
6016                let mut drafts: Vec<u32> = Vec::with_capacity(k);
6017                for j in 0..k {
6018                    let (dl_d, h_nextn) = self.mtp_head_forward_dev(
6019                        e,
6020                        mtp,
6021                        e_tok,
6022                        &d_seed,
6023                        &mut scratch,
6024                        p + 1 + j,
6025                        embd_dev,
6026                        None, // acceptance-oracle walk: no grammar
6027                    )?;
6028                    let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
6029                    let idx = e.dtoh_u32_one(&tok_d)?;
6030                    let d = match &mtp.d2t {
6031                        Some(map) => map[idx as usize],
6032                        None => idx,
6033                    };
6034                    drafts.push(d);
6035                    e_tok = d;
6036                    d_seed = h_nextn;
6037                }
6038                // targets may live in a LATER chunk's bg — resolved after the walk.
6039                rows.push((p, drafts, Vec::new()));
6040            }
6041            // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
6042            //    expect scratch.len == cend with exact rows).
6043            scratch.set_len(e, s)?;
6044            self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
6045            e.copy_view_into(
6046                &mut prev_last_h,
6047                0,
6048                &vx.slice((tc - 1) * n_embd..tc * n_embd),
6049                n_embd,
6050            )?;
6051            s = cend;
6052        }
6053        for (p, drafts, targets) in rows.iter_mut() {
6054            for j in 0..drafts.len() {
6055                targets.push(bg[*p + 1 + j]);
6056            }
6057        }
6058        rows.sort_by_key(|r| r.0);
6059        if nll_cnt > 0 {
6060            let mean = nll_sum / nll_cnt as f64;
6061            println!(
6062                "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
6063                mean.exp()
6064            );
6065        }
6066        Ok((rows, bg))
6067    }
6068}
6069
6070#[cfg(test)]
6071mod telem_tests {
6072    use super::{SpecTelemetry, SPEC_TELEM_POS};
6073
6074    /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
6075    /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
6076    #[test]
6077    fn delta_isolates_burst_contribution() {
6078        let mut t = SpecTelemetry::default();
6079        // "previous request": 2 rounds of k=3, accepts 3 then 1.
6080        for (kr, na) in [(3usize, 3usize), (3, 1)] {
6081            t.rounds += 1;
6082            t.drafted += kr as u64;
6083            t.accepted += na as u64;
6084            for j in 0..kr { t.pos_drafted[j] += 1; }
6085            for j in 0..na { t.pos_accepted[j] += 1; }
6086        }
6087        let before = t;
6088        // "this burst": 1 round k=3, accepts 2.
6089        t.rounds += 1;
6090        t.drafted += 3;
6091        t.accepted += 2;
6092        for j in 0..3 { t.pos_drafted[j] += 1; }
6093        for j in 0..2 { t.pos_accepted[j] += 1; }
6094        let d = t.delta_since(&before);
6095        assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
6096        assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
6097        assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
6098        assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
6099    }
6100
6101    /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
6102    /// aggregation invariant.
6103    #[test]
6104    fn merge_accumulates_fieldwise() {
6105        let mut agg = SpecTelemetry::default();
6106        let mut d1 = SpecTelemetry { rounds: 2, drafted: 6, accepted: 4, ..Default::default() };
6107        d1.pos_drafted[0] = 2;
6108        d1.pos_accepted[0] = 2;
6109        let mut d2 = SpecTelemetry { rounds: 1, drafted: 3, accepted: 1, ..Default::default() };
6110        d2.pos_drafted[0] = 1;
6111        d2.pos_accepted[0] = 1;
6112        d2.pos_drafted[1] = 1;
6113        agg.merge(&d1);
6114        agg.merge(&d2);
6115        assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
6116        assert_eq!(agg.pos_drafted[0], 3);
6117        assert_eq!(agg.pos_accepted[0], 3);
6118        assert_eq!(agg.pos_drafted[1], 1);
6119        assert_eq!(agg.pos_accepted[1], 0);
6120    }
6121
6122    /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
6123    /// public metrics surface and must never publish a u64-wrapped garbage value.
6124    #[test]
6125    fn delta_saturates_never_wraps() {
6126        let small = SpecTelemetry { rounds: 1, drafted: 2, accepted: 1, ..Default::default() };
6127        let big = SpecTelemetry { rounds: 5, drafted: 15, accepted: 9, ..Default::default() };
6128        let d = small.delta_since(&big);
6129        assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
6130    }
6131}
6132
6133#[cfg(test)]
6134mod draft_graph_fallback_tests {
6135    use super::DraftGraphFallback;
6136
6137    /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
6138    #[test]
6139    fn flip_is_loud_once_and_memoized_after() {
6140        let mut f = DraftGraphFallback::default();
6141        let line = f.mark_greedy("out of memory").expect("first flip must return the warn line");
6142        assert!(line.contains("WARN"), "flip line must be warn-level: {line}");
6143        assert!(line.contains("out of memory"), "flip line must carry the reason: {line}");
6144        assert!(f.greedy_failed());
6145        // re-marking an already-failed graph is the memoization: quiet, still failed.
6146        assert!(f.mark_greedy("out of memory").is_none());
6147        assert!(f.greedy_failed());
6148        // the two graphs' flags are independent (greedy flip leaves sampled capturable).
6149        assert!(!f.sampled_failed());
6150        let line_s = f.mark_sampled("capture unsupported").expect("sampled flip is its own flip");
6151        assert!(line_s.contains("sampled"), "sampled flip names itself: {line_s}");
6152        assert!(f.mark_sampled("capture unsupported").is_none());
6153    }
6154
6155    /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
6156    /// and says so exactly when there was something to reset.
6157    #[test]
6158    fn reset_on_resume_clears_flags_and_logs_once() {
6159        let mut f = DraftGraphFallback::default();
6160        // clean session: resume is silent, nothing to reset.
6161        assert!(f.reset_on_resume().is_none());
6162        f.mark_greedy("oom").unwrap();
6163        f.mark_sampled("oom").unwrap();
6164        let note = f.reset_on_resume().expect("a set flag must produce the reset note");
6165        assert!(note.contains("greedy+sampled"), "note names what was reset: {note}");
6166        assert!(!f.greedy_failed() && !f.sampled_failed(), "both flags cleared");
6167        // and the NEXT failure after a reset is a fresh flip — loud again.
6168        assert!(f.mark_greedy("oom again").is_some());
6169        let note2 = f.reset_on_resume().expect("greedy-only reset");
6170        assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
6171    }
6172
6173    /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
6174    /// they precede a fresh capture attempt whose own failure re-flips loudly.
6175    #[test]
6176    fn shape_change_clears_are_silent() {
6177        let mut f = DraftGraphFallback::default();
6178        f.mark_greedy("oom").unwrap();
6179        f.clear_greedy();
6180        assert!(!f.greedy_failed());
6181        f.mark_sampled("oom").unwrap();
6182        f.clear_sampled();
6183        assert!(!f.sampled_failed());
6184        // after a silent clear there is nothing left for resume to report.
6185        assert!(f.reset_on_resume().is_none());
6186    }
6187}