Skip to main content

memra_engine/
spec.rs

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