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