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