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::Engine;
12use crate::cache::{Cache, KvLayer};
13use crate::forward::argmax;
14use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer, MtpHead};
15use cudarc::driver::CudaSlice;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18/// Parse the documented `MEMRA_SPEC_REPLAY=1` rollback seam.
19///
20/// Keep this shared with serving admission so `=0` cannot select replay in one
21/// layer while another layer treats it as disabled.
22pub fn spec_replay_env_on(value: Option<&str>) -> bool {
23    value == Some("1")
24}
25
26pub fn spec_replay_env_enabled() -> bool {
27    let value = std::env::var("MEMRA_SPEC_REPLAY").ok();
28    spec_replay_env_on(value.as_deref())
29}
30
31/// One compact, anchor-bounded DSpark supervision record. `tokens[0]` is the anchor at p and
32/// `hidden` is its predecessor carrier h[p-1], matching the live NextN/DSpark pairing. Target
33/// rows p..p+gamma-1 score tokens p+1..p+gamma. They are the full-target softmax's top-k
34/// entries; `target_tail_probs[j]` is the probability mass outside those rows. All flattened
35/// target arrays are `[gamma, top_k]` in row-major order.
36pub struct DsparkAnchorRecord {
37    pub position: usize,
38    pub hidden: Vec<f32>,
39    pub tokens: Vec<u32>,
40    pub target_top_ids: Vec<u32>,
41    pub target_top_logits: Vec<f32>,
42    pub target_top_probs: Vec<f32>,
43    pub target_tail_probs: Vec<f32>,
44}
45
46fn dspark_sparse_softmax_topk(
47    logits: &[f32],
48    top_k: usize,
49    temperature: f32,
50) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>, f32), Box<dyn std::error::Error>> {
51    if logits.is_empty() || top_k == 0 || top_k > logits.len() || temperature <= 0.0 {
52        return Err("invalid DSpark sparse-softmax shape or temperature".into());
53    }
54    if logits.iter().any(|value| !value.is_finite()) {
55        return Err("DSpark target logits contain a non-finite value".into());
56    }
57    let mut ranked: Vec<(u32, f32)> = logits
58        .iter()
59        .copied()
60        .enumerate()
61        .map(|(index, value)| (index as u32, value))
62        .collect();
63    let compare = |left: &(u32, f32), right: &(u32, f32)| {
64        right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
65    };
66    ranked.select_nth_unstable_by(top_k - 1, compare);
67    ranked[..top_k].sort_unstable_by(compare);
68
69    let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
70    let inv_temperature = 1.0f64 / temperature as f64;
71    let denominator: f64 = logits
72        .iter()
73        .map(|value| (((*value - max_logit) as f64) * inv_temperature).exp())
74        .sum();
75    let ids: Vec<u32> = ranked[..top_k].iter().map(|(index, _)| *index).collect();
76    let top_logits: Vec<f32> = ranked[..top_k].iter().map(|(_, value)| *value).collect();
77    let top_probs: Vec<f32> = top_logits
78        .iter()
79        .map(|value| ((((value - max_logit) as f64) * inv_temperature).exp() / denominator) as f32)
80        .collect();
81    let top_mass: f64 = top_probs.iter().map(|value| *value as f64).sum();
82    let tail = (1.0f64 - top_mass).clamp(0.0, 1.0) as f32;
83    Ok((ids, top_logits, top_probs, tail))
84}
85
86fn flatten_dspark_rows<T>(
87    rows: Vec<Option<Vec<T>>>,
88    position: usize,
89    label: &str,
90) -> Result<Vec<T>, Box<dyn std::error::Error>> {
91    let mut flattened = Vec::new();
92    for (slot, row) in rows.into_iter().enumerate() {
93        flattened.extend(
94            row.ok_or_else(|| format!("missing DSpark {label} at {position} slot {slot}"))?,
95        );
96    }
97    Ok(flattened)
98}
99
100/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
101/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
102/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
103/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
104/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
105/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
106/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
107pub(crate) fn spec_hpost() -> bool {
108    static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
109    *H.get_or_init(|| {
110        std::env::var("MEMRA_SPEC_HPOST")
111            .map(|v| v != "0")
112            .unwrap_or(false)
113    })
114}
115
116/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
117/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
118/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
119/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
120/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
121/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
122/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
123/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
124/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
125pub(crate) fn spec_lean() -> bool {
126    static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
127    // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
128    // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
129    // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
130    *L.get_or_init(|| {
131        std::env::var("MEMRA_SPEC_LEAN")
132            .map(|v| v != "0")
133            .unwrap_or(true)
134    })
135}
136
137/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
138/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
139/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
140/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
141/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
142/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
143///     ring — the ring stores raw input columns); every arithmetic kernel is the same one the
144///     t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
145///     t-loop == chained T=1 steps);
146/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
147///     pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
148/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
149pub(crate) fn spec_m2() -> bool {
150    static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
151    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
152    // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
153    // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
154    // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
155    *M.get_or_init(|| {
156        std::env::var("MEMRA_SPEC_M2")
157            .map(|v| v != "0")
158            .unwrap_or(true)
159    })
160}
161pub(crate) fn spec_stream() -> bool {
162    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
163    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
164}
165pub(crate) fn spec_stream_m() -> usize {
166    static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
167    *M.get_or_init(|| {
168        std::env::var("MEMRA_SPEC_STREAM_M")
169            .ok()
170            .and_then(|v| v.parse().ok())
171            .unwrap_or(4)
172    })
173}
174pub(crate) fn spec_devacc() -> bool {
175    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
176    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
177}
178/// Engine-bundle slice 2 (DSF-ROUNDCOST-20260820 §1.1 host/device round trips + §2 rows 2-3),
179/// DEFAULT ON (`MEMRA_DSPARK_DEFER_READBACK=0` reverts): the dspark round's draft-chain DtoH
180/// is DEFERRED past verify dispatch and merged with the verify-argmax readback into ONE host
181/// sync (2 blocking DtoH/round -> 1). Verify embeds DEVICE tokens (`chain_d`) through the
182/// resident embed table — `embed_gather_u32_t`, bit-identical rows to the host gather by its
183/// own pinned contract. The host therefore dispatches snap + the whole verify while the DRAFT
184/// is still executing, instead of blocking ~1.7 ms on the chain and letting the device drain.
185/// Ladder arm only: the confidence policies size vt from a pre-verify head readback (their
186/// chain readback merges into that same sync instead). Exactness unchanged BY CONSTRUCTION —
187/// same tokens, same kernels, same order; E2E + accept-bank gates arbitrate.
188pub(crate) fn dspark_defer_readback_on() -> bool {
189    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
190    *ON.get_or_init(|| {
191        std::env::var("MEMRA_DSPARK_DEFER_READBACK")
192            .map(|v| v != "0")
193            .unwrap_or(true)
194    })
195}
196/// Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1, lane/dspark-engine-bundle-20260820),
197/// DEFAULT ON (`MEMRA_STATE_COPY_BATCH=0` reverts): batch the dspark round's GDN state
198/// snapshot and partial-accept restore into single `copy_batch_uniform_f32` launches
199/// instead of ~2 memcpy dispatches (+2 alloc_zeros on the snap side) per linear layer per
200/// round — measured 0.67 ms/round snap + 0.25 ms/round commit of pure dispatch on the q38
201/// route. Launch-structure only: bytes, buffers and stream order are unchanged, so
202/// acceptance and streams stay bit-identical (E2E-gated on the B1 packs).
203pub(crate) fn state_copy_batch_on() -> bool {
204    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
205    *ON.get_or_init(|| {
206        std::env::var("MEMRA_STATE_COPY_BATCH")
207            .map(|v| v != "0")
208            .unwrap_or(true)
209    })
210}
211/// Engine-bundle slice 3 (DSF-ROUNDCOST-20260820 §5 rank 1, bucketed verify graphs),
212/// DEFAULT OFF — `MEMRA_DSPARK_VERIFY_GRAPH=1` opts in: the dspark verify's LINEAR-layer
213/// runs replay per-(segment, vt) CUDA graphs — see [`DsparkVerifyGraphs`]. Requires the
214/// slice-2 deferred path (device tokens); the eager walk is the byte-identical fallback.
215///
216/// MEASURED disposition (box6 card0, agentic pack, 2026-08-20): exactness holds (ALL
217/// EXACT, accept lines byte-match the bank) and steady-state prompts gain +0.4..+1.5
218/// tok/s, but the gate-scale MEAN is flat (109.2 vs 109.4): the AUTO_FREE launch scan
219/// costs 25.6 us x 16 graph launches/round (~0.41 ms — most of the eager-launch
220/// savings) and the first generation pays ~80 lazy captures. The residual verify gap
221/// lives in the FULL-ATTENTION per-row section (fa partial memsets + appends), i.e.
222/// the fa exec-update extension, not here. Off until one of: node-count reduction
223/// (ctx-scratch transients), WithParams UPLOAD instantiation, or the full-verify
224/// single-graph — each re-gated by the same battery.
225pub(crate) fn dspark_verify_graph_on() -> bool {
226    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
227    *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() == Ok("1"))
228}
229
230/// `t_pred0` for the `MEMRA_DEBUG_SPEC` per-round print, sampled-safe.
231///
232/// `generate_spec_inner2` fills its `preds` vector ONLY on the greedy path (`if !sampled`), and
233/// the per-round debug print was the sole consumer in the sampled arm: `t_pred(0)` survives round
234/// 0 (`base == 0` returns `last_pred`) and from round 1 (`base == 1`, a pending bonus) indexes an
235/// EMPTY vector — `index out of bounds: the len is 0 but the index is 0`, in the GPU worker
236/// thread, which then respawns and reloads weights while the request dies. So any sampled spec
237/// request longer than one round used to kill the worker whenever `MEMRA_DEBUG_SPEC` was set:
238/// the flag crashed precisely the regime it exists to investigate.
239///
240/// Fixed at the print site, not inside the closure, so the greedy accept walk keeps its strict
241/// indexing (an out-of-range pred there is a real bug and must still be loud).
242fn debug_t_pred0(sampled: bool, base: usize, last_pred: u32, preds: &[u32]) -> String {
243    if base == 0 {
244        return last_pred.to_string();
245    }
246    match preds.get(base - 1) {
247        Some(p) => p.to_string(),
248        // sampled: the greedy per-column argmax was never run for this round.
249        None => {
250            debug_assert!(
251                sampled,
252                "greedy spec: preds[{}] missing at base {base}",
253                base - 1
254            );
255            "n/a".to_string()
256        }
257    }
258}
259
260/// `MEMRA_SKEY_PROBE=1` — sampled-draft-graph key probe (lane/graph-s-key-exactness-20260819).
261///
262/// Reports, per burst and per round, which draft chain the sampled arm chose and under which
263/// filter regime, plus the ONE observable that separates a legal filtered draft from a stale
264/// pure-temp graph replayed under filters: an accept test whose gathered `q` is exactly 0.
265/// A draft token sampled from the FILTERED softmax can never gather q=0 (it was drawn from the
266/// kept set), so `q=0` in the verify means the draft came from a distribution the verify does
267/// not believe in — and `u * 0 < p` then accepts it unconditionally.
268///
269/// Its own env var, deliberately NOT `MEMRA_DEBUG_SPEC`: that flag panicked the GPU worker on
270/// any sampled spec request past round 0 until this lane fixed it (§2 of the bank note).
271pub(crate) fn skey_probe() -> bool {
272    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
273    *ON.get_or_init(|| std::env::var("MEMRA_SKEY_PROBE").as_deref() == Ok("1"))
274}
275
276/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
277/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
278/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
279/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
280/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
281/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
282/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
283/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
284/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
285pub trait SpecConstraint {
286    /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
287    /// masked argmax).
288    fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
289    /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
290    fn mask_words(&mut self) -> Result<Vec<u32>, String>;
291    /// Is `tok` consumable in the CURRENT state?
292    fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
293    /// Advance the state with an emitted token.
294    fn consume(&mut self, tok: u32) -> Result<(), String>;
295
296    // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
297    // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
298    // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
299    // loose, research/constrained-full-20260803). These three methods let the engine mask the
300    // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
301    // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
302    // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
303    // stays the correctness backstop and the emitted stream is unchanged by construction
304    // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
305    // argmax; a cut slot is recomputed as the masked argmax either way).
306    // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
307
308    /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
309    /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
310    fn draft_mask_enabled(&self) -> bool {
311        false
312    }
313    /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
314    /// slot. Called once per spec round, before the first draft position.
315    fn draft_begin(&mut self) -> Result<(), String> {
316        Ok(())
317    }
318    /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
319    /// for the draft position about to be sampled. `None` = draft masking off (no-op).
320    fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
321        Ok(None)
322    }
323    /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
324    /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
325    /// engine stops drafting; the token already pushed still goes through verify.
326    fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
327        Ok(false)
328    }
329}
330
331/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
332/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
333/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
334/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
335/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
336/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
337/// verify emits the masked argmax as usual).
338fn upload_draft_mask(
339    e: &Engine,
340    c: &mut dyn SpecConstraint,
341    dst: &mut CudaSlice<u32>,
342    d2t: Option<&Vec<u32>>,
343    d_vocab: usize,
344    words: usize,
345) -> Result<bool, Box<dyn std::error::Error>> {
346    let Some(tw) = c
347        .draft_mask_words()
348        .map_err(|e2| format!("constraint: {e2}"))?
349    else {
350        return Ok(false);
351    };
352    let bit = |t: usize| -> bool {
353        let w = t >> 5;
354        w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
355    };
356    let mut buf = vec![0u32; words];
357    match d2t {
358        // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
359        Some(map) => {
360            for (i, &t) in map.iter().enumerate().take(d_vocab) {
361                if bit(t as usize) {
362                    buf[i >> 5] |= 1u32 << (i & 31);
363                }
364            }
365        }
366        // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
367        // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
368        None => {
369            let n = tw.len().min(words);
370            buf[..n].copy_from_slice(&tw[..n]);
371        }
372    }
373    if buf.iter().all(|w| *w == 0) {
374        return Ok(false);
375    }
376    e.htod_u32_into(dst, &buf)?;
377    Ok(true)
378}
379
380/// Keep the full token-embedding table in host memory and upload only the rows needed by each
381/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
382/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
383/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
384pub(crate) fn spec_host_embd() -> bool {
385    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
386    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
387}
388
389/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
390/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
391/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
392/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
393/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
394/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
395/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
396/// run-spec K=1..8 + acceptance identity arbitrate e2e).
397pub(crate) fn spec_fused_t() -> bool {
398    static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
399    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
400    // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
401    // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
402    *F.get_or_init(|| {
403        std::env::var("MEMRA_SPEC_FUSED_T")
404            .map(|v| v != "0")
405            .unwrap_or(true)
406    })
407}
408
409/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
410/// Only call this on such buffers — the lean contract is "identical bytes by construction".
411fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
412    if spec_lean() { e.uninit(n) } else { e.zeros(n) }
413}
414
415/// Scratch KV for the MTP block (one full-attn layer).
416///
417/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
418/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
419/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
420/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
421/// engine's "mtp_update" design). Entries come from two sources:
422///   - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
423///     hidden chain-approximate — the reference engine accepts the same);
424///   - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
425///     from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
426/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
427/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
428/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
429/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
430/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
431/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
432/// committed row across turns (the predecessor-pairing seed + fill anchor).
433/// Per-request sampling config for the sampled-spec serve path.
434#[derive(Clone, Copy, Debug)]
435pub struct SpecSampling {
436    pub temp: f32,
437    pub seed: u64,
438    pub top_k: i32,            // 0 = off
439    pub top_p: f32,            // 1.0 = off
440    pub min_p: f32,            // 0.0 = off
441    pub penalty_last_n: usize, // 0 = penalties off
442    pub penalty_repeat: f32,
443    pub penalty_freq: f32,
444    pub penalty_present: f32,
445}
446
447/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
448/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
449pub const SPEC_TELEM_POS: usize = 8;
450
451/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
452/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
453/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
454/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
455/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
456/// in NEITHER drafted nor accepted.
457#[derive(Clone, Copy, Default, Debug)]
458pub struct SpecTelemetry {
459    /// verify rounds completed (a round-stream burst counts each of its M rounds).
460    pub rounds: u64,
461    /// tokens drafted / accepted across all rounds.
462    pub drafted: u64,
463    pub accepted: u64,
464    /// how often draft position j (0-based within a round's chain) was offered / accepted.
465    /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
466    /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
467    /// arrays cover the standard-path rounds only and their sums may undercount the totals.
468    pub pos_drafted: [u64; SPEC_TELEM_POS],
469    pub pos_accepted: [u64; SPEC_TELEM_POS],
470}
471
472impl SpecTelemetry {
473    /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
474    /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
475    /// a wrapped counter.
476    pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
477        let mut d = SpecTelemetry {
478            rounds: self.rounds.saturating_sub(prev.rounds),
479            drafted: self.drafted.saturating_sub(prev.drafted),
480            accepted: self.accepted.saturating_sub(prev.accepted),
481            ..Default::default()
482        };
483        for j in 0..SPEC_TELEM_POS {
484            d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
485            d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
486        }
487        d
488    }
489    /// Fieldwise `self += d` — the worker's per-model aggregation.
490    pub fn merge(&mut self, d: &SpecTelemetry) {
491        self.rounds += d.rounds;
492        self.drafted += d.drafted;
493        self.accepted += d.accepted;
494        for j in 0..SPEC_TELEM_POS {
495            self.pos_drafted[j] += d.pos_drafted[j];
496            self.pos_accepted[j] += d.pos_accepted[j];
497        }
498    }
499
500    /// Mean accepted draft-prefix length per verify round (tau).
501    pub fn tau(&self) -> f64 {
502        if self.rounds > 0 {
503            self.accepted as f64 / self.rounds as f64
504        } else {
505            0.0
506        }
507    }
508}
509
510/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
511/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
512/// launch, synchronization, allocation, or ordering dependency to the numeric path.
513struct SpecTelemetryCounters {
514    rounds: AtomicU64,
515    drafted: AtomicU64,
516    accepted: AtomicU64,
517    pos_drafted: [AtomicU64; SPEC_TELEM_POS],
518    pos_accepted: [AtomicU64; SPEC_TELEM_POS],
519}
520
521impl Default for SpecTelemetryCounters {
522    fn default() -> Self {
523        Self {
524            rounds: AtomicU64::new(0),
525            drafted: AtomicU64::new(0),
526            accepted: AtomicU64::new(0),
527            pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
528            pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
529        }
530    }
531}
532
533impl SpecTelemetryCounters {
534    fn record_round(&self, drafted: usize, accepted: usize) {
535        debug_assert!(accepted <= drafted);
536        self.rounds.fetch_add(1, Ordering::Relaxed);
537        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
538        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
539        for counter in self.pos_drafted.iter().take(drafted) {
540            counter.fetch_add(1, Ordering::Relaxed);
541        }
542        for counter in self.pos_accepted.iter().take(accepted) {
543            counter.fetch_add(1, Ordering::Relaxed);
544        }
545    }
546
547    /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
548    /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
549    fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
550        self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
551        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
552        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
553    }
554
555    fn snapshot(&self) -> SpecTelemetry {
556        SpecTelemetry {
557            rounds: self.rounds.load(Ordering::Relaxed),
558            drafted: self.drafted.load(Ordering::Relaxed),
559            accepted: self.accepted.load(Ordering::Relaxed),
560            pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
561            pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
562        }
563    }
564}
565
566pub struct SpecSession {
567    pub(crate) cache: Cache,
568    pub(crate) scratch: MtpScratch,
569    /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
570    /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
571    /// session must count them. Callers render output from this, not from their own echo.
572    pub committed: Vec<u32>,
573    /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
574    pub(crate) last_h: Option<CudaSlice<f32>>,
575    /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
576    /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
577    /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
578    pub next_pred: Option<u32>,
579    /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
580    /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
581    pub sctr: u32,
582    pub uctr: u32,
583    /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
584    /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
585    /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
586    /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
587    /// research/spec-serving-20260801). None before the first turn; error paths drop it
588    /// (next burst recaptures — serve retires errored sessions anyway).
589    pub(crate) draft_ctx: Option<DraftGraphCtx>,
590    /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
591    /// emitted by the last round but NOT committed to the caches. The old tail committed it with
592    /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
593    /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
594    /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
595    /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
596    /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
597    /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
598    /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
599    /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
600    /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
601    pub pending_tok: Option<u32>,
602    /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
603    /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
604    /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
605    /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
606    pub(crate) turn_ckpt: Option<SpecCheckpoint>,
607    /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
608    /// accounting the loop already does — no syncs, no allocation. NOTE a
609    /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
610    /// diff with [`SpecTelemetry::delta_since`] around each burst.
611    telem: SpecTelemetryCounters,
612    /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
613    /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
614    /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
615    /// prime, result lands in `boundary_captures`.
616    pub capture_at: Option<usize>,
617    /// The captures the last prime produced (see [`SpecBoundaryCapture`]). Worker drains them
618    /// post-burst to assemble prefix entries. A failed capture is silent, like `turn_ckpt` —
619    /// publication just isn't available for that request. Plural since
620    /// lane/frspec-multiturn-cache (2026-08-21): a cold burst can capture BOTH the miss-LCP
621    /// split (the shared-prefix class) and the stable pre-generation boundary (the
622    /// next-turn re-render class) — one entry per stop, exactly the boundary set the plain
623    /// prefill tick publishes/checkpoints.
624    pub boundary_captures: Vec<SpecBoundaryCapture>,
625    /// STABLE-BOUNDARY TURN CHECKPOINT REQUEST (lane/frspec-multiturn-cache, 2026-08-21): the
626    /// ABSOLUTE committed-length position the next non-empty prime should capture `turn_ckpt`
627    /// at, instead of prompt-end. The worker sets it to the STABLE PRE-GENERATION boundary
628    /// (`plain_checkpoint_boundary` — before the live generation header the client rewrites),
629    /// porting the 2026-08-09 plain-tier fix: a prompt-end spec checkpoint includes the
630    /// template's live assistant-generation header (`<|im_start|>assistant\n<think>\n`), which
631    /// the NEXT turn's re-render replaces, so `affinity_match` diverged a couple tokens below
632    /// the checkpoint and the spec pool declined 100% of multi-turn agent traffic (measured:
633    /// `spec-affinity: declined (history diverged at 6811 of checkpoint 6813)`,
634    /// research/multiturn-cache-20260821 B4). One-shot, `capture_at` convention; None = legacy
635    /// prompt-end capture.
636    pub ckpt_at: Option<usize>,
637}
638impl SpecSession {
639    /// Context capacity of the session's caches (the server's ContextFull guard).
640    pub fn cache_max_ctx(&self) -> usize {
641        self.cache.max_ctx
642    }
643    /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
644    /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
645    /// those rows are append-only for the session's lifetime (rollbacks never truncate below
646    /// the prime boundary), so no copy was taken at prime time.
647    pub fn cache_ref(&self) -> &Cache {
648        &self.cache
649    }
650    /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
651    /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
652    /// like the trunk KV — draft rows below the prompt end are append-only for the
653    /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
654    /// committed length, never below the prime boundary, and the true-hidden refresh
655    /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
656    /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
657    /// prefix-addressable; the prefix cache already refuses that class end to end).
658    pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
659        if self.scratch.kv.ring.is_some() {
660            return None;
661        }
662        Some((
663            &self.scratch.kv.k,
664            &self.scratch.kv.v,
665            self.scratch.kv.k_tok_bytes,
666            self.scratch.kv.v_tok_bytes,
667        ))
668    }
669    /// Snapshot the session's process-local acceptance counters for per-burst diffing.
670    pub fn telemetry(&self) -> SpecTelemetry {
671        self.telem.snapshot()
672    }
673    /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
674    /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
675    /// `spec_rewind_to_checkpoint`.
676    pub fn rewind_pos(&self) -> Option<usize> {
677        self.turn_ckpt.as_ref().map(|c| c.pos)
678    }
679    /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
680    pub fn rewind_is_resident(&self) -> bool {
681        self.turn_ckpt.as_ref().is_some_and(|ckpt| {
682            self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
683        })
684    }
685    /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
686    /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
687    /// session has never run a turn and has no prediction to hand over.
688    pub fn demote_ready(&self) -> bool {
689        self.pending_tok.is_none() && self.next_pred.is_some()
690    }
691    /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
692    pub fn has_pending(&self) -> bool {
693        self.pending_tok.is_some()
694    }
695    /// Committed row count == cache rows (the session invariant), for the caller's own
696    /// `fed`-length cross-check at a handoff boundary.
697    pub fn committed_len(&self) -> usize {
698        self.committed.len()
699    }
700    /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
701    /// cache + next-token prediction to the plain batched-decode path.
702    ///
703    /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
704    /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
705    /// tokenwise prime of the same `committed` sequence would have left it (that is the
706    /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
707    /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
708    /// committed row — and verify-column logits are bit-identical to plain decode's logits at
709    /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
710    /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
711    /// a state indistinguishable from one the batched path produced itself: the batched tick
712    /// emits `next_pred`, feeds it into this same cache, and decodes on.
713    ///
714    /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
715    /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
716    /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
717    /// path would silently skip a token.
718    ///
719    /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
720    /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
721    /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
722    /// would mean an `mtp_kv_fill` over the whole committed history).
723    pub fn into_demoted(self) -> Option<(Cache, u32)> {
724        if self.pending_tok.is_some() {
725            return None;
726        }
727        let np = self.next_pred?;
728        debug_assert_eq!(
729            self.cache.pos,
730            self.committed.len(),
731            "demotion handoff: cache rows != committed tokens"
732        );
733        Some((self.cache, np))
734    }
735    /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
736    /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
737    /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
738    /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
739    pub fn reset_graph_fallback_on_resume(&mut self) {
740        if let Some(line) = self
741            .draft_ctx
742            .as_mut()
743            .and_then(|c| c.failed.reset_on_resume())
744        {
745            eprintln!("{line}");
746        }
747    }
748}
749
750/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
751///
752/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
753/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
754/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
755/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
756/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
757/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
758///
759/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
760/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
761/// position index, so it must be a real device COPY — that copy is the entire reason a spec
762/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
763/// below the boundary were written by this turn's fill and are never revisited (the per-round
764/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
765/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
766/// predecessor-pairing anchor the next prime's fill reads for its first row.
767///
768/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
769pub(crate) struct SpecCheckpoint {
770    snap: crate::cache::CacheSnapshot,
771    /// Committed length at the boundary (== cache.pos there, the session invariant).
772    pos: usize,
773    /// Pre-output_norm hidden of row `pos - 1`.
774    last_h: CudaSlice<f32>,
775}
776
777/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
778/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
779/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
780/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
781/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
782/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
783/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
784/// so the worker slices those from the live caches post-burst instead of copying at prime time.
785pub struct SpecBoundaryCapture {
786    pub snap: crate::cache::CacheSnapshot,
787    /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
788    pub pos: usize,
789    /// Full-vocab logits after the prefix prime — the entry's boundary logits.
790    pub logits: Vec<f32>,
791    /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
792    /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
793    /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
794    /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
795    pub last_h: Vec<f32>,
796}
797
798/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
799/// spec boundary capture carries for later restored-session fills. Failure is silent
800/// (`turn_ckpt` convention): the capture publishes without an anchor.
801fn capture_boundary_hidden(
802    e: &Engine,
803    h_rows: &CudaSlice<f32>,
804    pos: usize,
805    n_embd: usize,
806) -> Vec<f32> {
807    if pos == 0 || h_rows.len() < pos * n_embd {
808        return Vec::new();
809    }
810    let Ok(mut row) = e.uninit(n_embd) else {
811        return Vec::new();
812    };
813    if e.copy_view_into(
814        &mut row,
815        0,
816        &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
817        n_embd,
818    )
819    .is_err()
820    {
821        return Vec::new();
822    }
823    e.dtoh(&row).unwrap_or_default()
824}
825
826/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
827/// Default ON: the token a burst emits at its own boundary is drawn from the request's
828/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
829/// every boundary) without touching greedy, which is byte-unaffected either way.
830pub fn spec_sampled_boundary_on() -> bool {
831    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
832    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
833}
834
835/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
836/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
837/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
838/// restores the pre-lane posture (each burst restarts the window from its own prompt
839/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
840/// must keep refusing penalized sampled prefix-cache restores, because the restored
841/// session's continuation burst is handed no prompt slice at all.
842pub fn spec_pen_session_on() -> bool {
843    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
844    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
845}
846
847/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
848/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
849/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
850/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
851/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
852/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
853pub fn spec_restore_republish_on() -> bool {
854    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
855    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
856}
857
858/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
859/// the argmax the pre-lane code would have emitted from the same row. This is how the
860/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
861fn spec_boundary_trace() -> bool {
862    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
863    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
864}
865
866/// llama-parity floor for the penalty window when the request does not ask for a bigger
867/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = usize::MAX` for any
868/// non-identity penalty, so this floor only matters to explicit small windows and to the
869/// CLI env path.
870const PEN_WINDOW_FLOOR: usize = 64;
871
872/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
873/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
874/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
875/// p column, the bonus column). The serve API arms `penalty_last_n = usize::MAX` for ANY
876/// non-identity penalty — "the whole context", llama's `repeat_last_n = -1` — so an
877/// uncapped session window would put a 128k-token history through that kernel: ~1.7e10
878/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
879/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
880/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
881/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
882/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
883/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
884const PEN_WINDOW_MAX: usize = 8192;
885
886/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
887/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
888/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
889/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
890/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
891/// client actually asked us to penalize, where the pre-lane code had NOTHING.
892fn pen_window_seed(
893    session_committed: &[u32],
894    burst_prompt: &[u32],
895    penalty_last_n: usize,
896) -> Vec<u32> {
897    let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
898    let take_prompt = burst_prompt.len().min(win);
899    let take_sess = (win - take_prompt).min(session_committed.len());
900    let mut hist = Vec::with_capacity(take_sess + take_prompt);
901    hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
902    hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
903    hist
904}
905
906/// Draw a BOUNDARY token from the target distribution the request asked for
907/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
908/// every burst boundary".
909///
910/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
911/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
912/// row after the last committed token on a continuation burst; the prefix-cache entry's
913/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
914/// regimes, so a sampled stream took a greedy token once per burst — measured, not
915/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
916/// customer asked for a sampled token, so this draws one.
917///
918/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
919/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
920/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
921/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
922/// composition means `sample_check`'s distributional oracle covers this draw too, and the
923/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
924///
925/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
926/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
927/// stream the accept walk uses — never a second, independently seeded stream (which would be
928/// a new distributional bug: two streams from one seed correlate wherever their counters
929/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
930/// to the cold session's own first draw from the same logits row, which is what preserves the
931/// sampled-hit lane's per-seed hit==cold byte identity.
932#[allow(clippy::too_many_arguments)]
933pub fn sample_boundary_token_dev(
934    e: &Engine,
935    logits: &CudaSlice<f32>,
936    n_vocab: usize,
937    sp: &SpecSampling,
938    pen_hist: &[u32],
939    sctr: &mut u32,
940    site: &str,
941) -> Result<u32, Box<dyn std::error::Error>> {
942    debug_assert!(
943        sp.temp > 0.0,
944        "boundary sampling is the sampled regime only"
945    );
946    // Own copy: penalize_logits mutates in place and the caller's row is live state
947    // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
948    let mut col = e.zeros(n_vocab)?;
949    e.copy_into(&mut col, 0, logits, n_vocab)?;
950    let pen_on = sp.penalty_last_n > 0
951        && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
952    if pen_on && !pen_hist.is_empty() {
953        // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
954        let w0 = pen_hist
955            .len()
956            .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
957        let hist = &pen_hist[w0..];
958        let hd = e.htod_u32_v(hist)?;
959        e.penalize_logits(
960            &mut col,
961            &hd,
962            hist.len(),
963            sp.penalty_repeat,
964            sp.penalty_freq,
965            sp.penalty_present,
966            n_vocab,
967        )?;
968    }
969    let rows0 = e.htod_i32(&[0])?;
970    let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
971    e.filter_stats(
972        &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
973        sp.top_p, sp.min_p,
974    )?;
975    let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
976    let mut perturb = e.zeros(n_vocab)?;
977    e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
978    *sctr = sctr.wrapping_add(1);
979    let td = e.argmax_token_device(&perturb, n_vocab)?;
980    let tok = e.dtoh_u32_one(&td)?;
981    if spec_boundary_trace() {
982        // the pre-lane token, from the SAME row, so the deviation rate is measurable.
983        let raw = e.argmax_token_device(logits, n_vocab)?;
984        let greedy = e.dtoh_u32_one(&raw)?;
985        eprintln!(
986            "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
987             deviates={} temp={} sctr={}",
988            (tok != greedy) as u8,
989            sp.temp,
990            sctr.wrapping_sub(1),
991        );
992    }
993    Ok(tok)
994}
995
996/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
997/// host `Vec<f32>`).
998#[allow(clippy::too_many_arguments)]
999pub fn sample_boundary_token(
1000    e: &Engine,
1001    logits: &[f32],
1002    sp: &SpecSampling,
1003    pen_hist: &[u32],
1004    sctr: &mut u32,
1005    site: &str,
1006) -> Result<u32, Box<dyn std::error::Error>> {
1007    let n_vocab = logits.len();
1008    let d = e.htod(logits)?;
1009    sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
1010}
1011
1012struct SpecPipeTraceClock {
1013    pair: usize,
1014    started: std::time::Instant,
1015}
1016
1017#[derive(Clone)]
1018struct SpecPipeTraceCtx {
1019    clock: std::sync::Arc<SpecPipeTraceClock>,
1020    round: usize,
1021    lane: usize,
1022}
1023
1024struct SpecPipeTraceMarker {
1025    trace: SpecPipeTraceCtx,
1026    phase: &'static str,
1027    edge: &'static str,
1028    slot: Option<usize>,
1029}
1030
1031unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
1032    let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
1033    let lane = if marker.trace.lane == 0 { "A" } else { "B" };
1034    let slot = marker
1035        .slot
1036        .map(|v| v.to_string())
1037        .unwrap_or_else(|| "-".into());
1038    let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
1039    use std::io::Write as _;
1040    let stderr = std::io::stderr();
1041    let mut stderr = stderr.lock();
1042    let _ = writeln!(
1043        stderr,
1044        "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
1045         slot={slot} t_ms={t_ms:.3}",
1046        marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
1047    );
1048}
1049
1050fn enqueue_spec_pipe_trace_marker(
1051    stream: &cudarc::driver::CudaStream,
1052    trace: Option<&SpecPipeTraceCtx>,
1053    phase: &'static str,
1054    edge: &'static str,
1055    slot: Option<usize>,
1056) -> Result<(), Box<dyn std::error::Error>> {
1057    let Some(trace) = trace else {
1058        return Ok(());
1059    };
1060    let marker = Box::new(SpecPipeTraceMarker {
1061        trace: trace.clone(),
1062        phase,
1063        edge,
1064        slot,
1065    });
1066    let raw = Box::into_raw(marker);
1067    let result = unsafe {
1068        cudarc::driver::result::stream::launch_host_function(
1069            stream.cu_stream(),
1070            spec_pipe_trace_marker,
1071            raw.cast(),
1072        )
1073    };
1074    if let Err(err) = result {
1075        unsafe {
1076            drop(Box::from_raw(raw));
1077        }
1078        return Err(err.into());
1079    }
1080    Ok(())
1081}
1082
1083#[derive(Default)]
1084struct SpecPipeProgress {
1085    setup_done: [bool; 2],
1086    draft_done: [usize; 2],
1087    stage0_done: [usize; 2],
1088    verify_done: [usize; 2],
1089    accept_done: [usize; 2],
1090    finished: [bool; 2],
1091    aborted: bool,
1092}
1093
1094/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
1095/// keeps its existing call stack and round locals; this object only orders phase entry. The
1096/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
1097/// cannot be interleaved by the two host threads.
1098struct SpecPipeSync {
1099    progress: std::sync::Mutex<SpecPipeProgress>,
1100    changed: std::sync::Condvar,
1101    primary: std::sync::Mutex<()>,
1102    trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
1103}
1104
1105impl SpecPipeSync {
1106    fn new() -> Self {
1107        static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1108        let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
1109            std::sync::Arc::new(SpecPipeTraceClock {
1110                pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1111                started: std::time::Instant::now(),
1112            })
1113        });
1114        Self {
1115            progress: std::sync::Mutex::new(SpecPipeProgress::default()),
1116            changed: std::sync::Condvar::new(),
1117            primary: std::sync::Mutex::new(()),
1118            trace,
1119        }
1120    }
1121}
1122
1123#[derive(Clone)]
1124struct SpecPipeLane {
1125    sync: std::sync::Arc<SpecPipeSync>,
1126    lane: usize,
1127}
1128
1129impl SpecPipeLane {
1130    fn peer(&self) -> usize {
1131        1 - self.lane
1132    }
1133
1134    fn aborted() -> Box<dyn std::error::Error> {
1135        "paired speculative peer aborted".into()
1136    }
1137
1138    fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
1139        self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
1140            clock: clock.clone(),
1141            round,
1142            lane: self.lane,
1143        })
1144    }
1145
1146    fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
1147        let mut p = self.sync.progress.lock().unwrap();
1148        while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
1149            p = self.sync.changed.wait(p).unwrap();
1150        }
1151        if p.aborted {
1152            Err(Self::aborted())
1153        } else {
1154            Ok(())
1155        }
1156    }
1157
1158    fn setup_end(&self) {
1159        let mut p = self.sync.progress.lock().unwrap();
1160        p.setup_done[self.lane] = true;
1161        self.sync.changed.notify_all();
1162    }
1163
1164    fn draft_begin(
1165        &self,
1166        round: usize,
1167    ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1168        let peer = self.peer();
1169        let mut p = self.sync.progress.lock().unwrap();
1170        loop {
1171            if p.aborted {
1172                return Err(Self::aborted());
1173            }
1174            let setup_ready =
1175                (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
1176            let prior_ready = p.accept_done[self.lane] >= round
1177                && (p.accept_done[peer] >= round || p.finished[peer]);
1178            let turn_ready = if self.lane == 0 {
1179                true
1180            } else {
1181                p.draft_done[0] > round || p.finished[0]
1182            };
1183            if setup_ready && prior_ready && turn_ready {
1184                break;
1185            }
1186            p = self.sync.changed.wait(p).unwrap();
1187        }
1188        drop(p);
1189        Ok(self.sync.primary.lock().unwrap())
1190    }
1191
1192    fn draft_end(&self, round: usize) {
1193        let mut p = self.sync.progress.lock().unwrap();
1194        p.draft_done[self.lane] = round + 1;
1195        self.sync.changed.notify_all();
1196    }
1197
1198    /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
1199    /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
1200    fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
1201        let peer = self.peer();
1202        let mut p = self.sync.progress.lock().unwrap();
1203        loop {
1204            if p.aborted {
1205                return Err(Self::aborted());
1206            }
1207            let ready = if self.lane == 0 {
1208                p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
1209            } else {
1210                p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
1211            };
1212            if ready {
1213                return Ok(self.lane == 0 || p.finished[peer]);
1214            }
1215            p = self.sync.changed.wait(p).unwrap();
1216        }
1217    }
1218
1219    fn stage0_end(&self, round: usize) {
1220        let mut p = self.sync.progress.lock().unwrap();
1221        p.stage0_done[self.lane] = round + 1;
1222        self.sync.changed.notify_all();
1223    }
1224
1225    /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
1226    /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
1227    fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
1228        let mut p = self.sync.progress.lock().unwrap();
1229        while !p.aborted
1230            && !(p.stage0_done[self.lane] > round
1231                && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
1232        {
1233            p = self.sync.changed.wait(p).unwrap();
1234        }
1235        if p.aborted {
1236            Err(Self::aborted())
1237        } else {
1238            Ok(())
1239        }
1240    }
1241
1242    fn verify_end(&self, round: usize) {
1243        let mut p = self.sync.progress.lock().unwrap();
1244        p.verify_done[self.lane] = round + 1;
1245        self.sync.changed.notify_all();
1246    }
1247
1248    fn accept_begin(
1249        &self,
1250        round: usize,
1251    ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1252        let mut p = self.sync.progress.lock().unwrap();
1253        loop {
1254            if p.aborted {
1255                return Err(Self::aborted());
1256            }
1257            let ready = if self.lane == 0 {
1258                p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
1259            } else {
1260                p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
1261            };
1262            if ready {
1263                break;
1264            }
1265            p = self.sync.changed.wait(p).unwrap();
1266        }
1267        drop(p);
1268        Ok(self.sync.primary.lock().unwrap())
1269    }
1270
1271    fn accept_end(&self, round: usize) {
1272        let mut p = self.sync.progress.lock().unwrap();
1273        p.accept_done[self.lane] = round + 1;
1274        self.sync.changed.notify_all();
1275    }
1276
1277    fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
1278        self.sync.primary.lock().unwrap()
1279    }
1280
1281    fn finish(&self, failed: bool) {
1282        let mut p = self.sync.progress.lock().unwrap();
1283        p.finished[self.lane] = true;
1284        p.aborted |= failed;
1285        self.sync.changed.notify_all();
1286    }
1287}
1288
1289struct SpecPipeFinish<'a> {
1290    lane: &'a SpecPipeLane,
1291    closed: bool,
1292}
1293
1294impl<'a> SpecPipeFinish<'a> {
1295    fn new(lane: &'a SpecPipeLane) -> Self {
1296        Self {
1297            lane,
1298            closed: false,
1299        }
1300    }
1301
1302    fn close(&mut self, failed: bool) {
1303        self.lane.finish(failed);
1304        self.closed = true;
1305    }
1306}
1307
1308impl Drop for SpecPipeFinish<'_> {
1309    fn drop(&mut self) {
1310        if !self.closed {
1311            self.lane.finish(true);
1312        }
1313    }
1314}
1315
1316/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
1317/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
1318/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
1319/// binds that context before touching the session, joins before returning, and never aliases the
1320/// pointer. Keep this exception local to the experimental pair call instead of marking the public
1321/// session type Send.
1322struct SpecPipeSessionPtr(*mut SpecSession);
1323
1324unsafe impl Send for SpecPipeSessionPtr {}
1325
1326impl SpecPipeSessionPtr {
1327    unsafe fn get_mut(&mut self) -> &mut SpecSession {
1328        unsafe { &mut *self.0 }
1329    }
1330}
1331
1332/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
1333/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
1334/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
1335/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
1336/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
1337/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
1338/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
1339/// so the eager fallback doesn't pay a doomed capture attempt every burst.
1340/// Capture identity of the parked SAMPLED draft graph (`DraftGraphCtx::graph_s`).
1341///
1342/// EXACTNESS, not perf (lane/graph-s-key-exactness-20260819; receipts
1343/// `research/spec-cache-20260818/GRAPH-S-KEY.md`). Two classes of field live here, both
1344/// load-bearing:
1345///
1346/// - **Baked constants.** `seed` and `temp` are capture-time constants INSIDE the graph and `k`
1347///   sizes the q slots its replays write. A resumed request changing any of them must recapture.
1348///   This is all the key used to carry.
1349/// - **Regime fields.** `top_k`/`top_p`/`min_p`/`pen_on` are not baked, but they decide whether
1350///   the captured graph is a legal draft chain AT ALL. The in-graph draw is one gumbel-max over
1351///   the RAW softmax (`gumbel_perturb_ctr`, unfiltered by construction), while the verify builds
1352///   the accept test's `q` from `filter_stats(q_slots, top_k, top_p, min_p)`. If those disagree
1353///   the accept test evaluates a distribution the draft was never sampled from: a draft token
1354///   below the filter threshold gathers `q = 0` (`softmax_gather_filtered_f32`,
1355///   `cu/spec_sample.cu`) and `u * 0 < p` accepts it UNCONDITIONALLY.
1356///
1357/// Omitting the regime fields was reachable — not through the prefix-cache spec restore (that
1358/// path is greedy-only, `memra-server` `spec_restore_convertible`), but through WHOLE-SESSION
1359/// spec reuse: a parked `SpecSession` carries this `DraftGraphCtx`, and the pool-resume probe
1360/// applies no sampler predicate at all. Turn 1 pure-temp parks a graph; turn 2 of the same
1361/// conversation, same explicit seed and temperature, adds `top_p`/`top_k` and inherits it.
1362#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1363pub(crate) struct SampledGraphKey {
1364    seed: u64,
1365    temp_bits: u32,
1366    k: usize,
1367    top_k: i32,
1368    top_p_bits: u32,
1369    min_p_bits: u32,
1370    pen_on: bool,
1371}
1372
1373impl SampledGraphKey {
1374    pub(crate) fn new(
1375        seed: u64,
1376        temp: f32,
1377        k: usize,
1378        top_k: i32,
1379        top_p: f32,
1380        min_p: f32,
1381        pen_on: bool,
1382    ) -> Self {
1383        SampledGraphKey {
1384            seed,
1385            temp_bits: temp.to_bits(),
1386            k,
1387            top_k,
1388            top_p_bits: top_p.to_bits(),
1389            min_p_bits: min_p.to_bits(),
1390            pen_on,
1391        }
1392    }
1393
1394    /// The one regime the in-graph sampled chain may stand in for the eager one: nothing but
1395    /// temperature shapes `q`. Computed FROM THE KEY so the capture guard, the launch guard and
1396    /// the key can never drift apart (they were three separate expressions before this lane, and
1397    /// the launch site simply forgot to ask).
1398    pub(crate) fn pure_temp(&self) -> bool {
1399        self.top_k == 0
1400            && f32::from_bits(self.top_p_bits) >= 1.0
1401            && f32::from_bits(self.min_p_bits) <= 0.0
1402            && !self.pen_on
1403    }
1404}
1405
1406pub(crate) struct DraftGraphCtx {
1407    g_tok: CudaSlice<u32>,
1408    g_pos: CudaSlice<i32>,
1409    g_seed: CudaSlice<f32>,
1410    g_p: CudaSlice<f32>,
1411    g_ctr: CudaSlice<u32>,
1412    g_q: CudaSlice<f32>,
1413    g_perturb: CudaSlice<f32>,
1414    q_slots: Vec<CudaSlice<f32>>,
1415    /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
1416    /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
1417    /// per-position contents the host re-uploads before each replay (the graph-promote
1418    /// pattern from decode.rs). Empty unless the session drafts under a grammar.
1419    g_dmask: CudaSlice<u32>,
1420    /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
1421    graph_masked: bool,
1422    graph: Option<cudarc::driver::CudaGraph>,
1423    graph_s: Option<cudarc::driver::CudaGraph>,
1424    /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
1425    /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
1426    failed: DraftGraphFallback,
1427    /// Capture identity of `graph_s` — see [`SampledGraphKey`]. `None` iff no sampled graph is
1428    /// parked; a request whose key differs drops the parked graph (and its q slots/keeper).
1429    s_key: Option<SampledGraphKey>,
1430    /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
1431    /// pool addresses the captured graph(s) bake. Without these, the transients return to the
1432    /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
1433    /// co-served session in the worker) reuses those addresses — the persisted graph's replay
1434    /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
1435    /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
1436    /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
1437    /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
1438    keeper: Vec<Box<dyn std::any::Any + Send>>,
1439    keeper_s: Vec<Box<dyn std::any::Any + Send>>,
1440}
1441
1442/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
1443/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
1444///
1445/// Three contracts:
1446/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
1447///   (returned, not printed, so the once-per-flip contract is unit-testable); the caller
1448///   `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
1449///   an already-failed graph returns None (the per-burst memoization that keeps the eager
1450///   fallback from paying a doomed capture attempt every burst).
1451/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
1452///   NEW request gets one fresh capture chance instead of carrying a transient-pressure
1453///   failure for the pool's whole lifetime. Returns the note line only when a flag was
1454///   actually set (quiet on the common clean-resume path).
1455/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1456///   capture attempt whose own failure would re-flip loudly.
1457#[derive(Default)]
1458pub(crate) struct DraftGraphFallback {
1459    greedy: bool,
1460    sampled: bool,
1461}
1462impl DraftGraphFallback {
1463    fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1464        if self.greedy {
1465            return None;
1466        }
1467        self.greedy = true;
1468        Some(format!(
1469            "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1470        ))
1471    }
1472    fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1473        if self.sampled {
1474            return None;
1475        }
1476        self.sampled = true;
1477        Some(format!(
1478            "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1479        ))
1480    }
1481    fn greedy_failed(&self) -> bool {
1482        self.greedy
1483    }
1484    fn sampled_failed(&self) -> bool {
1485        self.sampled
1486    }
1487    fn clear_greedy(&mut self) {
1488        self.greedy = false;
1489    }
1490    fn clear_sampled(&mut self) {
1491        self.sampled = false;
1492    }
1493    /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1494    /// was set (so clean resumes stay quiet).
1495    pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1496        if !self.greedy && !self.sampled {
1497            return None;
1498        }
1499        let which = match (self.greedy, self.sampled) {
1500            (true, true) => "greedy+sampled",
1501            (true, false) => "greedy",
1502            _ => "sampled",
1503        };
1504        self.greedy = false;
1505        self.sampled = false;
1506        Some(format!(
1507            "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1508        ))
1509    }
1510}
1511
1512impl DraftGraphCtx {
1513    fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1514        Ok(DraftGraphCtx {
1515            g_tok: e.alloc_u32_zeroed(1)?,
1516            g_pos: e.htod_i32(&[0])?,
1517            g_seed: e.zeros(n_embd)?,
1518            g_p: e.zeros(1)?,
1519            g_ctr: e.alloc_u32_zeroed(1)?,
1520            g_q: e.zeros(qlen)?,
1521            g_perturb: e.zeros(qlen)?,
1522            q_slots: Vec::new(),
1523            g_dmask: e.alloc_u32_zeroed(1)?,
1524            graph_masked: false,
1525            graph: None,
1526            graph_s: None,
1527            failed: DraftGraphFallback::default(),
1528            s_key: None,
1529            keeper: Vec::new(),
1530            keeper_s: Vec::new(),
1531        })
1532    }
1533}
1534
1535pub(crate) struct MtpScratch {
1536    kv: KvLayer,
1537    /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1538    /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1539    /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1540    /// smaller host-indexed SWA ring instead.
1541    cap: usize,
1542}
1543
1544fn mtp_scratch_layout(
1545    cfg: &memra_gguf::config::ModelConfig,
1546    geom: Option<&crate::hybrid::DraftGeom>,
1547) -> (usize, usize, usize, usize) {
1548    // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1549    let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1550    let head_dim_k = cfg.head_dim_k as usize;
1551    let head_dim_v = cfg.head_dim_v as usize;
1552    assert!(
1553        head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1554        "KVQUANT requires head_dim%32==0 (MTP scratch)"
1555    );
1556    let kv_dim_k = head_dim_k * n_head_kv;
1557    let kv_dim_v = head_dim_v * n_head_kv;
1558    // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1559    // policy shared with `MtpScratch::new` so admission scales the same allocation.
1560    let (kbb, vbb) = crate::kv_blk_bytes();
1561    let k_tok_bytes = (kv_dim_k / 32) * kbb;
1562    let v_tok_bytes = (kv_dim_v / 32) * vbb;
1563    (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1564}
1565
1566impl MtpScratch {
1567    fn new(
1568        e: &Engine,
1569        cfg: &memra_gguf::config::ModelConfig,
1570        cap: usize,
1571        geom: Option<&crate::hybrid::DraftGeom>,
1572    ) -> Result<Self, Box<dyn std::error::Error>> {
1573        // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1574        // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1575        // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1576        // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1577        let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
1578        let ring = if crate::cache::swa_ring_on() && cfg.arch.is_step35() {
1579            let window = cfg.step35.as_ref().unwrap().sliding_window as usize;
1580            Some(crate::cache::KvRing::new(
1581                crate::cache::swa_ring_rows(window, cap),
1582                window,
1583            ))
1584        } else {
1585            None
1586        };
1587        let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1588        Ok(MtpScratch {
1589            kv: KvLayer {
1590                k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1591                v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1592                kv_dim_k,
1593                kv_dim_v,
1594                k_tok_bytes,
1595                v_tok_bytes,
1596                len: 0,
1597                ring,
1598                len_d: e.htod_i32(&[0])?,
1599            },
1600            cap,
1601        })
1602    }
1603    /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1604    /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1605    /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1606    fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1607        if self
1608            .kv
1609            .ring
1610            .as_ref()
1611            .is_some_and(|ring| !ring.can_rewind_to(n))
1612        {
1613            return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1614        }
1615        self.kv.len = n;
1616        e.set_i32_one(&mut self.kv.len_d, n as i32)
1617    }
1618
1619    fn can_rewind_to(&self, n: usize) -> bool {
1620        self.kv
1621            .ring
1622            .as_ref()
1623            .is_none_or(|ring| ring.can_rewind_to(n))
1624    }
1625}
1626
1627/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1628/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1629/// full weight reads per round — recomputing columns the verify had already produced
1630/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1631/// to "after the first j verify columns" WITHOUT re-running the trunk:
1632/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1633///   consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1634///   to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1635///   registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1636///   pure-copy ring rebuild.
1637/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1638///   column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1639///   target: j <= t-1).
1640/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1641/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1642struct GdnStash {
1643    qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1644    q_l2: CudaSlice<f32>,
1645    k_l2: CudaSlice<f32>,
1646    v_g: CudaSlice<f32>, // [t, num_v, d_state]
1647    g_log: CudaSlice<f32>,
1648    beta: CudaSlice<f32>, // [t, num_v]
1649}
1650struct VerifyCkpt {
1651    gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1652    cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1653}
1654/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
1655pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
1656
1657/// Engine-bundle slice 3 (DSF-ROUNDCOST-20260820 §2 row 4 / §5 rank 1): bucketed CUDA
1658/// graphs for the dspark verify's LINEAR-layer segments. The measured verify is ~2,800
1659/// eager launches whose residual cost is DEVICE-side per-launch overhead (slice 2 proved
1660/// host dispatch is not the binder: fully-deferred dispatch bought ~0 wall). The 48 GDN
1661/// layers between full-attention layers are shape-static given vt — no positions, no
1662/// t_kv, state addressed through pointer tables — so runs of them capture per
1663/// (segment, vt) and replay as ONE graph launch each. Full-attention layers stay eager
1664/// (their per-row append/fa arm picks are t_kv-driven — the exec-update extension).
1665///
1666/// Per round out-of-graph: one pointer-table refresh (gdn ping-pong moves the canonical
1667/// handles), one input-staging copy per segment, host parity bookkeeping. Captured via
1668/// `capture_graph_retained` (2 warmups + capture, keeper retains warmup transients so
1669/// pool addresses stay stable); the warmups EXECUTE, so segment conv/ssm state is saved
1670/// before and restored after — the graph's first real launch starts from the exact
1671/// pre-round state. The ckpt column stash rides persistent slabs (written inside the
1672/// graph as memcpy nodes); commit reads them via `dspark_commit_prefix_slab`.
1673/// `MEMRA_DSPARK_VERIFY_GRAPH=0` reverts to the eager walk (byte-identical body).
1674pub(crate) struct DsparkVerifyGraphs {
1675    /// Linear-attention layer indices ascending; `lin_pos[il]` = index into the vecs.
1676    lin: Vec<usize>,
1677    lin_pos: std::collections::HashMap<usize, usize>,
1678    /// [n_lin x 6] pointer table (conv, s0, s1, conv, s1, s0 per layer), refreshed per
1679    /// verify from the live handles; layer il's slice starts at lin_pos[il]*6.
1680    table_all: CudaSlice<u64>,
1681    host_table: Vec<u64>,
1682    /// Persistent per-layer ckpt stash slabs: row r of the verify at slab offset
1683    /// r*words. Shared by every (segment, vt) bucket — one verify runs at a time.
1684    stash_conv: Vec<CudaSlice<f32>>,
1685    stash_ssm: Vec<CudaSlice<f32>>,
1686    conv_words: usize,
1687    ssm_words: usize,
1688    /// Per-vt input/output staging (stable addresses the graphs bake).
1689    stage: std::collections::HashMap<usize, (CudaSlice<f32>, CudaSlice<f32>)>,
1690    /// Per-vt dflash tap-sink buffers — the captured segments bake the tap dst address,
1691    /// so the sink buffer must live (and persist) with the graphs, not with the round.
1692    pub(crate) tap_bufs: std::collections::HashMap<usize, CudaSlice<f32>>,
1693    graphs: std::collections::HashMap<(usize, usize), DsparkSegGraph>,
1694    /// Warmup-corruption guard scratch: pre-capture conv/ssm of one segment.
1695    save_conv: CudaSlice<f32>,
1696    save_ssm: CudaSlice<f32>,
1697    max_run: usize,
1698    n_embd: usize,
1699    /// Set by the verify walk: this round's linear ckpt lives in the slabs (the caller
1700    /// commits through `dspark_commit_prefix_slab` instead of the cols arm).
1701    pub(crate) round_slab: bool,
1702}
1703
1704struct DsparkSegGraph {
1705    graph: cudarc::driver::CudaGraph,
1706    _keeper: Vec<Box<dyn std::any::Any + Send>>,
1707}
1708
1709// SAFETY: `CudaGraph` is not marked Send by cudarc because its raw driver handles carry
1710// no automatic trait; CUDA driver graph handles are context-scoped rather than
1711// OS-thread-affine (the SpecPipeSessionPtr precedent above). The ctx lives in
1712// `HybridModel::dspark_vgraphs` behind a Mutex and every touch happens on the engine's
1713// single decode-stream thread.
1714unsafe impl Send for DsparkVerifyGraphs {}
1715
1716impl DsparkVerifyGraphs {
1717    /// Build for this cache's shape. None when there are no linear layers, sizes are
1718    /// non-uniform, or the trunk keeps a gemma4 config (never on the qwen35 family).
1719    pub(crate) fn new(
1720        e: &Engine,
1721        cache: &Cache,
1722        t_max: usize,
1723        n_embd: usize,
1724    ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
1725        let lin: Vec<usize> = (0..cache.recur.len())
1726            .filter(|&il| cache.recur[il].is_some())
1727            .collect();
1728        if lin.is_empty() || t_max < 2 {
1729            return Ok(None);
1730        }
1731        let first = cache.recur[lin[0]].as_ref().unwrap();
1732        let (conv_words, ssm_words) = (first.conv_state.len(), first.ssm_state.len());
1733        for &il in &lin {
1734            let rl = cache.recur[il].as_ref().unwrap();
1735            if rl.conv_state.len() != conv_words || rl.ssm_state.len() != ssm_words {
1736                return Ok(None);
1737            }
1738        }
1739        let n = lin.len();
1740        let mut lin_pos = std::collections::HashMap::with_capacity(n);
1741        for (k, &il) in lin.iter().enumerate() {
1742            lin_pos.insert(il, k);
1743        }
1744        // longest run of consecutive linear layers (save-scratch sizing)
1745        let mut max_run = 1usize;
1746        let mut run = 1usize;
1747        for w in lin.windows(2) {
1748            if w[1] == w[0] + 1 {
1749                run += 1;
1750                max_run = max_run.max(run);
1751            } else {
1752                run = 1;
1753            }
1754        }
1755        let rows = t_max - 1;
1756        let mut stash_conv = Vec::with_capacity(n);
1757        let mut stash_ssm = Vec::with_capacity(n);
1758        for _ in 0..n {
1759            stash_conv.push(e.uninit(rows * conv_words)?);
1760            stash_ssm.push(e.uninit(rows * ssm_words)?);
1761        }
1762        let host_table = vec![0u64; n * 6];
1763        let table_all = e.htod_u64(&host_table)?;
1764        Ok(Some(Self {
1765            lin,
1766            lin_pos,
1767            table_all,
1768            host_table,
1769            stash_conv,
1770            stash_ssm,
1771            conv_words,
1772            ssm_words,
1773            stage: std::collections::HashMap::new(),
1774            tap_bufs: std::collections::HashMap::new(),
1775            graphs: std::collections::HashMap::new(),
1776            save_conv: e.uninit(max_run * conv_words)?,
1777            save_ssm: e.uninit(max_run * ssm_words)?,
1778            max_run,
1779            n_embd,
1780            round_slab: false,
1781        }))
1782    }
1783
1784    /// Rebuild the pointer table from the live handles (once per verify — the gdn
1785    /// ping-pong swaps the canonical/alt handles between rounds; a stale table would
1786    /// read the wrong parity's state).
1787    pub(crate) fn refresh_tables(
1788        &mut self,
1789        e: &Engine,
1790        cache: &Cache,
1791    ) -> Result<(), Box<dyn std::error::Error>> {
1792        use cudarc::driver::DevicePtr;
1793        {
1794            let s = &e.gpu.stream();
1795            for (k, &il) in self.lin.iter().enumerate() {
1796                let rl = cache.recur[il].as_ref().unwrap();
1797                let (pc, _g0) = rl.conv_state.device_ptr(s);
1798                let (p0, _g1) = rl.ssm_state.device_ptr(s);
1799                let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
1800                let o = k * 6;
1801                self.host_table[o] = pc as u64;
1802                self.host_table[o + 1] = p0 as u64;
1803                self.host_table[o + 2] = p1 as u64;
1804                self.host_table[o + 3] = pc as u64;
1805                self.host_table[o + 4] = p1 as u64;
1806                self.host_table[o + 5] = p0 as u64;
1807            }
1808        }
1809        e.htod_u64_into(&self.host_table, &mut self.table_all)?;
1810        Ok(())
1811    }
1812
1813    /// Run layers [start, end) (all linear) as one captured graph at this vt: stage the
1814    /// residual into the bucket's x_in, capture on first encounter (2 executing warmups
1815    /// bracketed by a segment state save/restore), launch, then apply the host parity
1816    /// bookkeeping the captured body would have done. Returns the fresh residual.
1817    #[allow(clippy::too_many_arguments)]
1818    fn run_segment(
1819        &mut self,
1820        model: &crate::hybrid::HybridModel,
1821        e: &Engine,
1822        start: usize,
1823        end: usize,
1824        x: &CudaSlice<f32>,
1825        t: usize,
1826        cache: &mut Cache,
1827    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1828        let n_embd = self.n_embd;
1829        debug_assert!(end - start <= self.max_run);
1830        if !self.stage.contains_key(&t) {
1831            let xin = e.uninit(t * n_embd)?;
1832            let xout = e.uninit(t * n_embd)?;
1833            self.stage.insert(t, (xin, xout));
1834        }
1835        // Stage the residual at the bucket's baked input address.
1836        {
1837            let (xin, _) = self.stage.get_mut(&t).unwrap();
1838            e.copy_into(xin, 0, x, t * n_embd)?;
1839        }
1840        let key = (start, t);
1841        if !self.graphs.contains_key(&key) {
1842            // The 2 warmups EXECUTE the segment on live state — save conv + the canonical
1843            // ssm of every segment layer first, restore after, so the graph's first real
1844            // launch starts from the exact pre-round state (bytes gated e2e).
1845            for (k, il) in (start..end).enumerate() {
1846                let rl = cache.recur[il].as_ref().unwrap();
1847                e.copy_into(
1848                    &mut self.save_conv,
1849                    k * self.conv_words,
1850                    &rl.conv_state,
1851                    self.conv_words,
1852                )?;
1853                e.copy_into(
1854                    &mut self.save_ssm,
1855                    k * self.ssm_words,
1856                    &rl.ssm_state,
1857                    self.ssm_words,
1858                )?;
1859            }
1860            let (graph, keeper) = {
1861                let table_all = &self.table_all;
1862                let lin_pos = &self.lin_pos;
1863                let stash_conv = &mut self.stash_conv;
1864                let stash_ssm = &mut self.stash_ssm;
1865                let (xin, xout) = self
1866                    .stage
1867                    .get_mut(&t)
1868                    .map(|(a, b)| (&*a, b))
1869                    .expect("stage bucket created above");
1870                let cache_ref: &mut Cache = cache;
1871                // AUTO_FREE_ON_LAUNCH (the retained default): UPLOAD via
1872                // cuGraphInstantiateWithFlags is CUDA_ERROR_INVALID_VALUE (the flag is
1873                // WithParams-only), and the alloc nodes need the auto-free semantics.
1874                // Its launch-time mem-pool scan is the measured limiter — 25.6 us per
1875                // cuGraphLaunch x 16 segments = ~0.41 ms/round, most of the
1876                // eager-launch savings — which is why this door is OPT-IN until the
1877                // node count drops (ctx-scratch transients / fused state chain) or the
1878                // full-verify single-graph (fa exec-update) lands.
1879                e.capture_graph_retained_flags(
1880                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH,
1881                    move |e| {
1882                    let mut xc: Option<CudaSlice<f32>> = None;
1883                    for il in start..end {
1884                        let k = lin_pos[&il];
1885                        let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
1886                        let nx = model.qwen35_tparallel_linear_layer(
1887                            e,
1888                            il,
1889                            xr,
1890                            t,
1891                            cache_ref,
1892                            None,
1893                            Some((&mut stash_conv[k], &mut stash_ssm[k])),
1894                            Some((table_all, k * 6)),
1895                        )?;
1896                        xc = Some(nx);
1897                    }
1898                        e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
1899                        Ok(())
1900                    },
1901                )?
1902            };
1903            // Undo the net host parity motion of the 3 body runs (each run swaps iff t
1904            // is odd -> 3 runs = net one swap), then restore the device state the
1905            // warmups consumed. The launch below then behaves exactly like one run.
1906            if t % 2 == 1 {
1907                for il in start..end {
1908                    let rl = cache.recur[il].as_mut().unwrap();
1909                    std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
1910                }
1911            }
1912            for (k, il) in (start..end).enumerate() {
1913                let rl = cache.recur[il].as_mut().unwrap();
1914                let (cw, sw) = (self.conv_words, self.ssm_words);
1915                {
1916                    let sv = e.view(&self.save_conv, self.max_run * cw);
1917                    let win = sv.slice(k * cw..(k + 1) * cw);
1918                    e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
1919                }
1920                {
1921                    let sv = e.view(&self.save_ssm, self.max_run * sw);
1922                    let win = sv.slice(k * sw..(k + 1) * sw);
1923                    e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
1924                }
1925            }
1926            self.graphs.insert(
1927                key,
1928                DsparkSegGraph {
1929                    graph,
1930                    _keeper: keeper,
1931                },
1932            );
1933        }
1934        self.graphs[&key].graph.launch()?;
1935        // Host parity bookkeeping for the replayed body (the captured host swaps do not
1936        // re-run at replay).
1937        if t % 2 == 1 {
1938            for il in start..end {
1939                let rl = cache.recur[il].as_mut().unwrap();
1940                std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
1941            }
1942        }
1943        let (_, xout) = self.stage.get(&t).unwrap();
1944        let mut out = e.uninit(t * n_embd)?;
1945        e.copy_into(&mut out, 0, xout, t * n_embd)?;
1946        Ok(out)
1947    }
1948
1949    /// Slab row (conv, ssm) device pointers + lengths for the commit restore of column
1950    /// `row` (0-based) of layer `il`. None for non-linear layers.
1951    pub(crate) fn slab_row(
1952        &self,
1953        e: &Engine,
1954        il: usize,
1955        row: usize,
1956    ) -> Option<(u64, u64, usize, usize)> {
1957        use cudarc::driver::DevicePtr;
1958        let k = *self.lin_pos.get(&il)?;
1959        let s = &e.gpu.stream();
1960        let (pc, _g0) = self.stash_conv[k].device_ptr(s);
1961        let (ps, _g1) = self.stash_ssm[k].device_ptr(s);
1962        Some((
1963            pc as u64 + (row * self.conv_words * 4) as u64,
1964            ps as u64 + (row * self.ssm_words * 4) as u64,
1965            self.conv_words,
1966            self.ssm_words,
1967        ))
1968    }
1969}
1970
1971impl VerifyCkpt {
1972    fn new(n_layer: usize) -> Self {
1973        VerifyCkpt {
1974            gdn: (0..n_layer).map(|_| None).collect(),
1975            cols: (0..n_layer).map(|_| None).collect(),
1976        }
1977    }
1978}
1979
1980/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
1981/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
1982/// a logical round number.
1983struct VerifyBoundaryTicket {
1984    rt: &'static crate::pp::PpNRt,
1985    caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1986    slot: usize,
1987    pos0: usize,
1988    t: usize,
1989    payload: usize,
1990    n_st: usize,
1991    pipelined: bool,
1992    pp_anatomy: bool,
1993    pp_started: std::time::Instant,
1994    reverse_ms: f64,
1995    stage0_ms: f64,
1996    tx_ms: f64,
1997    trace: Option<SpecPipeTraceCtx>,
1998}
1999
2000/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
2001/// increment-2 controller can also be armed by the server's fresh-process research door.
2002#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2003pub enum OptiForkGateMode {
2004    Disabled,
2005    Hit,
2006    Miss,
2007    Alternate,
2008    Abort,
2009    Controller,
2010}
2011
2012static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2013static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
2014    std::sync::atomic::AtomicU32::new(0);
2015static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2016static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2017static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2018static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2019static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2020static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2021static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2022static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2023static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2024static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2025    std::sync::atomic::AtomicU64::new(0);
2026static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2027    std::sync::atomic::AtomicU64::new(0);
2028static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2029
2030impl OptiForkGateMode {
2031    fn code(self) -> u8 {
2032        match self {
2033            Self::Disabled => 0,
2034            Self::Hit => 1,
2035            Self::Miss => 2,
2036            Self::Alternate => 3,
2037            Self::Abort => 4,
2038            Self::Controller => 5,
2039        }
2040    }
2041
2042    fn configured() -> Self {
2043        match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
2044            1 => Self::Hit,
2045            2 => Self::Miss,
2046            3 => Self::Alternate,
2047            4 => Self::Abort,
2048            5 => Self::Controller,
2049            _ => Self::Disabled,
2050        }
2051    }
2052
2053    fn action(self, generation: u64) -> OptiForkAction {
2054        match self {
2055            Self::Hit => OptiForkAction::Hit,
2056            Self::Miss => OptiForkAction::Miss,
2057            Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
2058            Self::Alternate => OptiForkAction::Miss,
2059            Self::Abort => OptiForkAction::Abort,
2060            Self::Disabled | Self::Controller => {
2061                unreachable!("non-forced mode cannot choose a forced fork action")
2062            }
2063        }
2064    }
2065
2066    fn is_forced(self) -> bool {
2067        matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
2068    }
2069}
2070
2071/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
2072pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
2073    OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
2074}
2075
2076/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
2077/// two-token draft-probability product. Serving can call this only through its explicit
2078/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
2079pub fn set_optipipe_controller_threshold(threshold: f32) {
2080    assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
2081    OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
2082    set_optipipe_gate_mode(OptiForkGateMode::Controller);
2083}
2084
2085#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2086pub struct OptiForkGateStats {
2087    pub attempts: u64,
2088    pub hits: u64,
2089    pub misses: u64,
2090    pub abort_drains: u64,
2091    pub refusals: u64,
2092    pub gate_checks: u64,
2093    pub gate_admits: u64,
2094    pub gate_rejects: u64,
2095    pub reconciles: u64,
2096    pub wasted_draft_tokens: u64,
2097    pub shadow_draft_tokens: u64,
2098    pub breaker_trips: u64,
2099}
2100
2101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2102pub struct OptiForkStateIdentity {
2103    pub trunk_kv_bytes: usize,
2104    pub recurrent_bytes: usize,
2105    pub scratch_kv_bytes: usize,
2106    pub hidden_bytes: usize,
2107}
2108
2109pub fn reset_optipipe_gate_stats() {
2110    for counter in [
2111        &OPTI_FORK_ATTEMPTS,
2112        &OPTI_FORK_HITS,
2113        &OPTI_FORK_MISSES,
2114        &OPTI_FORK_ABORT_DRAINS,
2115        &OPTI_FORK_REFUSALS,
2116        &OPTI_GATE_CHECKS,
2117        &OPTI_GATE_ADMITS,
2118        &OPTI_GATE_REJECTS,
2119        &OPTI_RECONCILES,
2120        &OPTI_WASTED_DRAFT_TOKENS,
2121        &OPTI_SHADOW_DRAFT_TOKENS,
2122        &OPTI_BREAKER_TRIPS,
2123    ] {
2124        counter.store(0, std::sync::atomic::Ordering::Relaxed);
2125    }
2126}
2127
2128pub fn optipipe_gate_stats() -> OptiForkGateStats {
2129    let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
2130    OptiForkGateStats {
2131        attempts: load(&OPTI_FORK_ATTEMPTS),
2132        hits: load(&OPTI_FORK_HITS),
2133        misses: load(&OPTI_FORK_MISSES),
2134        abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
2135        refusals: load(&OPTI_FORK_REFUSALS),
2136        gate_checks: load(&OPTI_GATE_CHECKS),
2137        gate_admits: load(&OPTI_GATE_ADMITS),
2138        gate_rejects: load(&OPTI_GATE_REJECTS),
2139        reconciles: load(&OPTI_RECONCILES),
2140        wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
2141        shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
2142        breaker_trips: load(&OPTI_BREAKER_TRIPS),
2143    }
2144}
2145
2146#[derive(Clone, Copy, Debug)]
2147struct OptiControllerPolicy {
2148    threshold: f32,
2149    consecutive_misses: u8,
2150    breaker_tripped: bool,
2151}
2152
2153impl OptiControllerPolicy {
2154    fn configured() -> Self {
2155        Self {
2156            threshold: f32::from_bits(
2157                OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
2158            ),
2159            consecutive_misses: 0,
2160            breaker_tripped: false,
2161        }
2162    }
2163
2164    fn admit(&self, q_proxy: f32) -> bool {
2165        q_proxy.is_finite()
2166            && (0.0..=1.0).contains(&q_proxy)
2167            && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
2168    }
2169
2170    /// Returns true exactly when this resolution newly trips the three-miss breaker.
2171    fn resolve(&mut self, hit: bool) -> bool {
2172        // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
2173        // every optimistic opportunity, so the safety breaker is measured separately and must
2174        // not silently turn this arm into "three attempts then serial".
2175        if self.threshold == 0.0 {
2176            self.consecutive_misses = 0;
2177            return false;
2178        }
2179        if hit {
2180            self.consecutive_misses = 0;
2181            return false;
2182        }
2183        self.consecutive_misses = self.consecutive_misses.saturating_add(1);
2184        if !self.breaker_tripped && self.consecutive_misses >= 3 {
2185            self.breaker_tripped = true;
2186            return true;
2187        }
2188        false
2189    }
2190}
2191
2192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2193enum OptiForkAction {
2194    Hit,
2195    Miss,
2196    Abort,
2197}
2198
2199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2200struct OptiForkGeneration {
2201    id: u64,
2202    slot: usize,
2203}
2204
2205#[derive(Default)]
2206struct OptiForkGenerationTracker {
2207    next: u64,
2208    live: [Option<u64>; 2],
2209}
2210
2211impl OptiForkGenerationTracker {
2212    fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2213        let generation = OptiForkGeneration {
2214            id: self.next,
2215            slot: (self.next & 1) as usize,
2216        };
2217        if let Some(live) = self.live[generation.slot] {
2218            return Err(format!(
2219                "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
2220                generation.slot,
2221            )
2222            .into());
2223        }
2224        self.next += 1;
2225        self.live[generation.slot] = Some(generation.id);
2226        Ok(generation)
2227    }
2228
2229    fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2230        match self.live[generation.slot] {
2231            Some(id) if id == generation.id => {
2232                self.live[generation.slot] = None;
2233                Ok(())
2234            }
2235            other => Err(format!(
2236                "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
2237                generation.id, generation.slot,
2238            )
2239            .into()),
2240        }
2241    }
2242}
2243
2244struct OptiForkSeedGeneration {
2245    h_seed: CudaSlice<f32>,
2246    fill_prev: CudaSlice<f32>,
2247    scratch_len: usize,
2248}
2249
2250/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
2251/// generic cache helper accepts one device and therefore cannot copy GDN state split across
2252/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
2253/// device ownership.
2254fn opti_snapshot_stage_owned(
2255    e: &Engine,
2256    cache: &Cache,
2257    rt: &'static crate::pp::PpNRt,
2258    fence: &[usize],
2259) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
2260    let n = cache.kv.len();
2261    let mut snapshot = crate::cache::CacheSnapshot {
2262        kv_len: vec![None; n],
2263        conv: (0..n).map(|_| None).collect(),
2264        ssm: (0..n).map(|_| None).collect(),
2265        pos: cache.pos,
2266    };
2267    opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
2268    Ok(snapshot)
2269}
2270
2271fn opti_snapshot_stage_owned_into(
2272    e: &Engine,
2273    cache: &Cache,
2274    rt: &'static crate::pp::PpNRt,
2275    fence: &[usize],
2276    snapshot: &mut crate::cache::CacheSnapshot,
2277) -> Result<(), Box<dyn std::error::Error>> {
2278    if fence.len() != rt.n_stages() + 1 || snapshot.kv_len.len() != cache.kv.len() {
2279        return Err("optipipe stage-owned snapshot shape mismatch".into());
2280    }
2281    for stage in 0..rt.n_stages() {
2282        opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
2283    }
2284    snapshot.pos = cache.pos;
2285    Ok(())
2286}
2287
2288/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
2289/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
2290/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
2291/// either point would capture one side of the fork at the wrong generation.
2292fn opti_snapshot_one_stage_owned_into(
2293    e: &Engine,
2294    cache: &Cache,
2295    rt: &'static crate::pp::PpNRt,
2296    fence: &[usize],
2297    stage: usize,
2298    snapshot: &mut crate::cache::CacheSnapshot,
2299) -> Result<(), Box<dyn std::error::Error>> {
2300    if fence.len() != rt.n_stages() + 1
2301        || snapshot.kv_len.len() != cache.kv.len()
2302        || stage >= rt.n_stages()
2303    {
2304        return Err("optipipe single-stage snapshot shape mismatch".into());
2305    }
2306    let _scope = rt.enter(stage);
2307    let owner = rt.engine(stage, e);
2308    for il in fence[stage]..fence[stage + 1] {
2309        snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
2310        match &cache.recur[il] {
2311            Some(recur) => {
2312                match snapshot.conv[il].as_mut() {
2313                    Some(dst) => {
2314                        owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
2315                    }
2316                    None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
2317                }
2318                match snapshot.ssm[il].as_mut() {
2319                    Some(dst) => {
2320                        owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
2321                    }
2322                    None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
2323                }
2324            }
2325            None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
2326                return Err(
2327                    format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
2328                );
2329            }
2330            None => {}
2331        }
2332    }
2333    snapshot.pos = cache.pos;
2334    Ok(())
2335}
2336
2337/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
2338/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
2339/// resolve, so the reconcile tables and conditional restores are stage-local.
2340struct OptiForkState {
2341    mode: OptiForkGateMode,
2342    controller: Option<OptiControllerPolicy>,
2343    generations: OptiForkGenerationTracker,
2344    active_snapshot_slot: usize,
2345    alternate_snapshot: crate::cache::CacheSnapshot,
2346    seeds: [OptiForkSeedGeneration; 2],
2347    rt: &'static crate::pp::PpNRt,
2348    fence: [usize; 3],
2349    split: usize,
2350    len_ptrs: CudaSlice<u64>,
2351    saved_lens: CudaSlice<i32>,
2352    forced_acc: CudaSlice<u32>,
2353    valid: CudaSlice<u32>,
2354    stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
2355    logical_payload_bytes: [usize; 2],
2356}
2357
2358struct OptiForkTicket {
2359    generation: OptiForkGeneration,
2360    boundary: Option<VerifyBoundaryTicket>,
2361    drain: std::sync::Arc<cudarc::driver::CudaStream>,
2362    settled: bool,
2363}
2364
2365struct OptiControllerTicket {
2366    generation: OptiForkGeneration,
2367    boundary: Option<VerifyBoundaryTicket>,
2368    ckpt: Option<VerifyCkpt>,
2369    verify_tokens: [u32; 2],
2370    draft_prob: f32,
2371    eager_seed: Option<CudaSlice<f32>>,
2372    q_proxy: f32,
2373    scratch_len: usize,
2374    issued_at: std::time::Instant,
2375    drain: std::sync::Arc<cudarc::driver::CudaStream>,
2376    settled: bool,
2377}
2378
2379struct OptiControllerPrepared {
2380    verify_tokens: [u32; 2],
2381    draft_prob: f32,
2382    eager_seed: Option<CudaSlice<f32>>,
2383    q_proxy: f32,
2384    scratch_len: usize,
2385}
2386
2387impl OptiControllerTicket {
2388    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
2389        self.boundary
2390            .take()
2391            .expect("controller boundary ticket already consumed")
2392    }
2393
2394    fn take_ckpt(&mut self) -> VerifyCkpt {
2395        self.ckpt
2396            .take()
2397            .expect("controller verify checkpoint already consumed")
2398    }
2399
2400    fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
2401        self.eager_seed.take()
2402    }
2403
2404    fn settle(&mut self) {
2405        self.settled = true;
2406    }
2407}
2408
2409impl Drop for OptiControllerTicket {
2410    fn drop(&mut self) {
2411        if !self.settled {
2412            let _ = self.drain.synchronize();
2413            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2414        }
2415    }
2416}
2417
2418impl OptiForkTicket {
2419    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
2420        self.boundary
2421            .take()
2422            .expect("fork ticket boundary already consumed")
2423    }
2424
2425    fn settle(&mut self) {
2426        self.settled = true;
2427    }
2428}
2429
2430impl Drop for OptiForkTicket {
2431    fn drop(&mut self) {
2432        if !self.settled {
2433            let _ = self.drain.synchronize();
2434            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2435        }
2436    }
2437}
2438
2439impl OptiForkState {
2440    #[allow(clippy::too_many_arguments)]
2441    fn new(
2442        e: &Engine,
2443        cache: &Cache,
2444        mode: OptiForkGateMode,
2445        alternate_snapshot: crate::cache::CacheSnapshot,
2446        h_seed: &CudaSlice<f32>,
2447        fill_prev: &CudaSlice<f32>,
2448        rt: &'static crate::pp::PpNRt,
2449        split: usize,
2450        n_layer: usize,
2451    ) -> Result<Self, Box<dyn std::error::Error>> {
2452        let fence = [0, split, n_layer];
2453        let mut logical_payload_bytes = [0usize; 2];
2454        for stage in 0..2 {
2455            for il in fence[stage]..fence[stage + 1] {
2456                logical_payload_bytes[stage] += alternate_snapshot.conv[il]
2457                    .as_ref()
2458                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
2459                logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
2460                    .as_ref()
2461                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
2462            }
2463        }
2464        let seeds = [
2465            OptiForkSeedGeneration {
2466                h_seed: e.clone_dtod(h_seed)?,
2467                fill_prev: e.clone_dtod(fill_prev)?,
2468                scratch_len: 0,
2469            },
2470            OptiForkSeedGeneration {
2471                h_seed: e.clone_dtod(h_seed)?,
2472                fill_prev: e.clone_dtod(fill_prev)?,
2473                scratch_len: 0,
2474            },
2475        ];
2476        let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
2477            let _stage = rt.enter(0);
2478            let e0 = rt.engine(0, e);
2479            (
2480                crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
2481                e0.htod_i32(&vec![0; split])?,
2482                e0.alloc_u32_zeroed(2)?,
2483                e0.alloc_u32_zeroed(1)?,
2484                e0.stream(),
2485            )
2486        };
2487        logical_payload_bytes[0] += seeds
2488            .iter()
2489            .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
2490            .sum::<usize>();
2491        logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
2492            + saved_lens.len() * std::mem::size_of::<i32>()
2493            + forced_acc.len() * std::mem::size_of::<u32>()
2494            + valid.len() * std::mem::size_of::<u32>();
2495        Ok(Self {
2496            mode,
2497            controller: (mode == OptiForkGateMode::Controller)
2498                .then(OptiControllerPolicy::configured),
2499            generations: OptiForkGenerationTracker::default(),
2500            active_snapshot_slot: 0,
2501            alternate_snapshot,
2502            seeds,
2503            rt,
2504            fence,
2505            split,
2506            len_ptrs,
2507            saved_lens,
2508            forced_acc,
2509            valid,
2510            stage0_stream,
2511            logical_payload_bytes,
2512        })
2513    }
2514
2515    fn reserve(
2516        &mut self,
2517        current_snapshot: &mut crate::cache::CacheSnapshot,
2518    ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2519        let generation = self.generations.reserve()?;
2520        if generation.slot != self.active_snapshot_slot {
2521            std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
2522            self.active_snapshot_slot = generation.slot;
2523        }
2524        Ok(generation)
2525    }
2526
2527    fn capture_seed(
2528        &mut self,
2529        e: &Engine,
2530        generation: OptiForkGeneration,
2531        h_seed: &CudaSlice<f32>,
2532        fill_prev: &CudaSlice<f32>,
2533        scratch_len: usize,
2534    ) -> Result<(), Box<dyn std::error::Error>> {
2535        let seed = &mut self.seeds[generation.slot];
2536        e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
2537        e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
2538        seed.scratch_len = scratch_len;
2539        Ok(())
2540    }
2541
2542    fn ticket(
2543        &self,
2544        generation: OptiForkGeneration,
2545        boundary: VerifyBoundaryTicket,
2546    ) -> OptiForkTicket {
2547        OptiForkTicket {
2548            generation,
2549            boundary: Some(boundary),
2550            drain: self.stage0_stream.clone(),
2551            settled: false,
2552        }
2553    }
2554
2555    #[allow(clippy::too_many_arguments)]
2556    fn controller_ticket(
2557        &self,
2558        generation: OptiForkGeneration,
2559        boundary: VerifyBoundaryTicket,
2560        ckpt: VerifyCkpt,
2561        verify_tokens: [u32; 2],
2562        draft_prob: f32,
2563        eager_seed: Option<CudaSlice<f32>>,
2564        q_proxy: f32,
2565        scratch_len: usize,
2566    ) -> OptiControllerTicket {
2567        OptiControllerTicket {
2568            generation,
2569            boundary: Some(boundary),
2570            ckpt: Some(ckpt),
2571            verify_tokens,
2572            draft_prob,
2573            eager_seed,
2574            q_proxy,
2575            scratch_len,
2576            issued_at: std::time::Instant::now(),
2577            drain: self.stage0_stream.clone(),
2578            settled: false,
2579        }
2580    }
2581
2582    fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2583        self.generations.reserve()
2584    }
2585
2586    fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
2587        &mut self.alternate_snapshot
2588    }
2589
2590    fn promote_successor_snapshot(
2591        &mut self,
2592        current_snapshot: &mut crate::cache::CacheSnapshot,
2593        generation: OptiForkGeneration,
2594    ) {
2595        std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
2596        self.active_snapshot_slot = generation.slot;
2597    }
2598
2599    fn queue_actual_reconcile(
2600        &mut self,
2601        e: &Engine,
2602        snapshot: &crate::cache::CacheSnapshot,
2603        acc: &CudaSlice<u32>,
2604        optimistic_pending: u32,
2605        base: usize,
2606    ) -> Result<(), Box<dyn std::error::Error>> {
2607        let saved: Vec<i32> = (0..self.split)
2608            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
2609            .collect();
2610        // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
2611        // decision point there and append a wait to stage 0 after its optimistic successor/TX;
2612        // the validity/reconcile kernels must never peer-read acc before it is written. The
2613        // increment-1 harness uses primary stage 0, where stream order already provides this.
2614        if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
2615            self.rt.fence_stages_behind(&e.stream())?;
2616        }
2617        let _stage = self.rt.enter(0);
2618        let e0 = self.rt.engine(0, e);
2619        e0.htod_i32_into(&mut self.saved_lens, &saved)?;
2620        e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
2621        e0.spec_fork_reconcile_kv(
2622            &self.len_ptrs,
2623            &self.saved_lens,
2624            acc,
2625            &self.valid,
2626            base,
2627            self.split,
2628        )
2629    }
2630
2631    fn finish_actual_reconcile(
2632        &mut self,
2633        e: &Engine,
2634        cache: &mut Cache,
2635        snapshot: &crate::cache::CacheSnapshot,
2636        n_acc: usize,
2637        base: usize,
2638        hit: bool,
2639    ) -> Result<(), Box<dyn std::error::Error>> {
2640        if hit {
2641            return Ok(());
2642        }
2643        let len_delta = base + n_acc;
2644        for il in 0..self.split {
2645            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2646                kv.len = saved + len_delta;
2647            }
2648        }
2649        {
2650            let _stage = self.rt.enter(1);
2651            let e1 = self.rt.engine(1, e);
2652            for il in self.split..self.fence[2] {
2653                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2654                    kv.len = saved + len_delta;
2655                    e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2656                }
2657            }
2658        }
2659        self.rt.publish_to(0, &e.stream())?;
2660        Ok(())
2661    }
2662
2663    fn cancel_controller_ticket(
2664        &mut self,
2665        e: &Engine,
2666        cache: &mut Cache,
2667        scratch: &mut MtpScratch,
2668        snapshot: &crate::cache::CacheSnapshot,
2669        ticket: &mut OptiControllerTicket,
2670    ) -> Result<(), Box<dyn std::error::Error>> {
2671        {
2672            let _stage = self.rt.enter(0);
2673            let e0 = self.rt.engine(0, e);
2674            for il in 0..self.split {
2675                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2676                    kv.len = saved;
2677                    e0.set_i32_one(&mut kv.len_d, saved as i32)?;
2678                }
2679            }
2680        }
2681        scratch.set_len(e, snapshot.pos)?;
2682        ticket.settle();
2683        self.generations.retire(ticket.generation)?;
2684        OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2685        OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
2686        eprintln!(
2687            "[opti-controller] tail-drain generation={} slot={}",
2688            ticket.generation.id, ticket.generation.slot,
2689        );
2690        Ok(())
2691    }
2692
2693    #[allow(clippy::too_many_arguments)]
2694    fn reconcile(
2695        &mut self,
2696        e: &Engine,
2697        cache: &mut Cache,
2698        scratch: &mut MtpScratch,
2699        snapshot: &crate::cache::CacheSnapshot,
2700        h_seed: &mut CudaSlice<f32>,
2701        fill_prev: &mut CudaSlice<f32>,
2702        generation: OptiForkGeneration,
2703        action: OptiForkAction,
2704        optimistic_pending: u32,
2705    ) -> Result<(), Box<dyn std::error::Error>> {
2706        debug_assert!(action != OptiForkAction::Abort);
2707        let miss_started = std::time::Instant::now();
2708        let keep = action == OptiForkAction::Hit;
2709        let saved: Vec<i32> = (0..self.split)
2710            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
2711            .collect();
2712        let seed = &self.seeds[generation.slot];
2713        {
2714            let _stage = self.rt.enter(0);
2715            let e0 = self.rt.engine(0, e);
2716            e0.htod_i32_into(&mut self.saved_lens, &saved)?;
2717            let forced = if keep {
2718                [1u32, optimistic_pending]
2719            } else {
2720                [0u32, optimistic_pending]
2721            };
2722            e0.htod_u32_into(&mut self.forced_acc, &forced)?;
2723            e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
2724            e0.spec_fork_reconcile_kv(
2725                &self.len_ptrs,
2726                &self.saved_lens,
2727                &self.forced_acc,
2728                &self.valid,
2729                0,
2730                self.split,
2731            )?;
2732            for il in 0..self.split {
2733                if let Some(recur) = cache.recur[il].as_mut() {
2734                    let conv = snapshot.conv[il]
2735                        .as_ref()
2736                        .ok_or("optipipe stage0 snapshot missing conv state")?;
2737                    let ssm = snapshot.ssm[il]
2738                        .as_ref()
2739                        .ok_or("optipipe stage0 snapshot missing ssm state")?;
2740                    e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
2741                    e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
2742                }
2743            }
2744            e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
2745            e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
2746        }
2747
2748        if keep {
2749            OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2750            return Ok(());
2751        }
2752
2753        for il in 0..self.split {
2754            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2755                kv.len = saved;
2756            }
2757        }
2758        scratch.set_len(e, seed.scratch_len)?;
2759        // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
2760        // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
2761        let caller = e.stream();
2762        self.rt.publish_to(0, &caller)?;
2763        caller.synchronize()?;
2764        let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
2765        eprintln!(
2766            "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
2767            generation.id, generation.slot,
2768        );
2769        OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2770        Ok(())
2771    }
2772
2773    fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2774        self.generations.retire(generation)
2775    }
2776}
2777
2778impl HybridModel {
2779    fn opti_graph_draft_step(
2780        &self,
2781        e: &Engine,
2782        mtp: &MtpHead,
2783        dctx: &mut DraftGraphCtx,
2784        scratch: &mut MtpScratch,
2785        d_vocab: usize,
2786    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2787        dctx.graph
2788            .as_ref()
2789            .ok_or("optipipe controller requires the greedy draft graph")?
2790            .launch()?;
2791        scratch.kv.len += 1;
2792        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
2793        if (idx as usize) >= d_vocab {
2794            return Err(
2795                format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
2796            );
2797        }
2798        let probability = e.dtoh(&dctx.g_p)?[0];
2799        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2800            return Err(format!("optipipe draft probability is invalid: {probability}").into());
2801        }
2802        let token = match &mtp.d2t {
2803            Some(map) => map[idx as usize],
2804            None => idx,
2805        };
2806        if token != idx {
2807            e.set_u32_one(&mut dctx.g_tok, token)?;
2808        }
2809        Ok((token, probability))
2810    }
2811
2812    #[allow(clippy::too_many_arguments)]
2813    fn opti_controller_draft_step(
2814        &self,
2815        e: &Engine,
2816        mtp: &MtpHead,
2817        dctx: &mut DraftGraphCtx,
2818        scratch: &mut MtpScratch,
2819        d_vocab: usize,
2820        eager_state: &mut Option<(u32, CudaSlice<f32>)>,
2821        eager_pos: usize,
2822        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2823    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2824        if dctx.graph.is_some() {
2825            return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
2826        }
2827        let (input_token, input_seed) = eager_state
2828            .take()
2829            .ok_or("optipipe eager continuation seed is unavailable")?;
2830        let (logits, next_seed) = self.mtp_head_forward_dev(
2831            e,
2832            mtp,
2833            input_token,
2834            &input_seed,
2835            scratch,
2836            eager_pos,
2837            embd_dev,
2838            None,
2839        )?;
2840        let token_d = e.argmax_token_device(&logits, d_vocab)?;
2841        let idx = e.dtoh_u32_one(&token_d)?;
2842        if (idx as usize) >= d_vocab {
2843            return Err(format!(
2844                "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
2845            )
2846            .into());
2847        }
2848        let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
2849        let probability = e.dtoh(&probability_d)?[0];
2850        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2851            return Err(
2852                format!("optipipe eager draft probability is invalid: {probability}").into(),
2853            );
2854        }
2855        let token = match &mtp.d2t {
2856            Some(map) => map[idx as usize],
2857            None => idx,
2858        };
2859        *eager_state = Some((token, next_seed));
2860        Ok((token, probability))
2861    }
2862
2863    /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
2864    /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
2865    /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
2866    /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
2867    /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
2868    /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
2869    /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
2870    /// transfer + host argmax per draft token from the K-token draft chain.
2871    #[allow(clippy::too_many_arguments)]
2872    fn mtp_head_forward_dev(
2873        &self,
2874        e: &Engine,
2875        mtp: &MtpHead,
2876        e_tok: u32,
2877        h_seed: &CudaSlice<f32>,
2878        scratch: &mut MtpScratch,
2879        mtp_pos: usize,
2880        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2881        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
2882        // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
2883        // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
2884        mask: Option<(&CudaSlice<u32>, usize)>,
2885    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2886        // MEMRA_SPEC_ANATOMY=1 — eager-step phase timers (diagnostic only). Phase boundaries
2887        // sync the stream, so absolute time inflates; the BREAKDOWN is the signal. Cumulative
2888        // summary on stderr every 128 steps: glue (embed..attn_norm), attn, ffn, head.
2889        use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
2890        static ANAT_NS: [AtomicU64; 5] = [
2891            AtomicU64::new(0),
2892            AtomicU64::new(0),
2893            AtomicU64::new(0),
2894            AtomicU64::new(0),
2895            AtomicU64::new(0),
2896        ];
2897        static ANAT_STEPS: AtomicU64 = AtomicU64::new(0);
2898        let anat = {
2899            static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2900            *ON.get_or_init(|| std::env::var("MEMRA_SPEC_ANATOMY").as_deref() == Ok("1"))
2901        };
2902        if anat {
2903            e.stream().synchronize()?; // drain prior queue so phase 0 starts clean
2904        }
2905        let t_all = std::time::Instant::now();
2906        let mut t_ph = std::time::Instant::now();
2907        let mut anat_mark = |i: usize,
2908                             e: &Engine,
2909                             t: &mut std::time::Instant|
2910         -> Result<(), Box<dyn std::error::Error>> {
2911            if anat {
2912                e.stream().synchronize()?;
2913                ANAT_NS[i].fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
2914                *t = std::time::Instant::now();
2915            }
2916            Ok(())
2917        };
2918        let cfg = &self.cfg;
2919        let n_embd = cfg.n_embd as usize;
2920        // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
2921        // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
2922        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2923        let eps = cfg.rms_eps;
2924        let pos_d = e.htod_i32(&[mtp_pos as i32])?;
2925
2926        // op A: a resident table transfers one 4B token id. The exact host-row capacity path
2927        // expands this one row on CPU and transfers n_embd f32 values instead.
2928        let e_emb = match embd_dev {
2929            Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
2930            None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
2931        };
2932
2933        // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
2934        let mut e_norm = e.zeros(n_embd)?;
2935        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
2936        let mut h_norm = e.zeros(n_embd)?;
2937        e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
2938
2939        // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
2940        let mut concat = e.zeros(2 * n_embd)?;
2941        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
2942        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
2943
2944        // op 4: inpSA = eh_proj @ concat  (eh_proj [2*n_embd, n_embd]) -> [n_embd]
2945        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
2946
2947        // op 5: a_norm = RMSNorm(inpSA, attn_norm)
2948        let mut a_norm = e.zeros(di)?;
2949        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
2950        anat_mark(0, e, &mut t_ph)?;
2951
2952        // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
2953        // scratch.cap, length from the device len_d) so eager drafts match graph drafts
2954        // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
2955        // advances only the device counter).
2956        let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
2957            // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
2958            // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
2959            // Advances BOTH the host len and the device counter itself (unlike the dc arm,
2960            // whose host-side mirror the caller does).
2961            (Mixer::Full(fa), Some(g)) => {
2962                self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?
2963            }
2964            (Mixer::Full(fa), None) => {
2965                let out =
2966                    self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
2967                scratch.kv.len += 1;
2968                out
2969            }
2970            (Mixer::Linear(_), _) => {
2971                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2972            }
2973            (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
2974        };
2975        anat_mark(1, e, &mut t_ph)?;
2976
2977        // op 7: x1 = inpSA + attn_out
2978        let mut x1 = e.zeros(di)?;
2979        e.add(&inp_sa, &attn_out, &mut x1, di)?;
2980
2981        // op 8: z = RMSNorm(x1, post_attn_norm)  (pre-FFN norm)
2982        let mut z = e.zeros(di)?;
2983        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
2984
2985        // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
2986        let ffn_out = match &mtp.ffn {
2987            crate::hybrid::Ffn::Dense {
2988                ffn_gate,
2989                ffn_up,
2990                ffn_down,
2991            } => {
2992                let n_ff = ffn_gate.out_features();
2993                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
2994                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
2995                    (
2996                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
2997                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
2998                    )
2999                } else {
3000                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
3001                };
3002                let mut act = e.zeros(n_ff)?;
3003                // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
3004                // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
3005                // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
3006                // passes None, which is `ffn_act`'s dispatch verbatim.
3007                Self::ffn_act_lim(
3008                    e,
3009                    &self.cfg,
3010                    &gate,
3011                    &up,
3012                    1.0,
3013                    1.0,
3014                    mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
3015                    &mut act,
3016                    n_ff,
3017                )?;
3018                e.matmul(ffn_down, &act, 1)?
3019            }
3020            // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
3021            // so they never alias trunk layer 0's cache keys.
3022            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
3023        };
3024        anat_mark(2, e, &mut t_ph)?;
3025
3026        // op 10: h_nextn = x1 + ffn_out (at di)
3027        let mut h_inner = e.zeros(di)?;
3028        e.add(&x1, &ffn_out, &mut h_inner, di)?;
3029
3030        // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
3031        // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
3032        let h_nextn = match mtp.geom.as_ref() {
3033            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
3034            None => h_inner,
3035        };
3036
3037        // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
3038        let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
3039        let mut final_h = e.zeros(n_embd)?;
3040        e.rms_norm(
3041            &h_nextn,
3042            final_norm.float_data(),
3043            &mut final_h,
3044            n_embd,
3045            1,
3046            eps,
3047        )?;
3048
3049        // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
3050        let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
3051        let mut logits = e.matmul(head, &final_h, 1)?;
3052        // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
3053        // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
3054        if let Some((mask_d, mw)) = mask {
3055            let d_vocab = head.out_features();
3056            e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
3057        }
3058        anat_mark(3, e, &mut t_ph)?;
3059        if anat {
3060            ANAT_NS[4].fetch_add(t_all.elapsed().as_nanos() as u64, Relaxed);
3061            let n = ANAT_STEPS.fetch_add(1, Relaxed) + 1;
3062            if n % 128 == 0 {
3063                let us = |i: usize| ANAT_NS[i].load(Relaxed) / n / 1000;
3064                eprintln!(
3065                    "[spec-anatomy] steps={n} avg us/step: glue={} attn={} ffn={} head={} total={}",
3066                    us(0),
3067                    us(1),
3068                    us(2),
3069                    us(3),
3070                    us(4)
3071                );
3072            }
3073        }
3074        // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
3075        // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
3076        Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
3077    }
3078
3079    /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
3080    /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
3081    /// the dc path, and all three are properties of this arch's MTP block:
3082    ///
3083    /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
3084    ///    window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
3085    ///    cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
3086    ///    mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
3087    ///    windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
3088    ///    starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
3089    ///    new kernel. That is deliberately not built here: see the CUDA-graph note below.
3090    /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
3091    ///    on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
3092    ///    trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
3093    ///    resolved `Step35MtpGeom`, never from `cfg`.
3094    /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
3095    ///    sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
3096    ///    fused-into-wq `q_gate_split` form the dc arm handles.
3097    ///
3098    /// WHY EAGER-ONLY IS NOT A GAP TODAY: `mtp_head_forward_cap` refuses step35 heads
3099    /// explicitly (the SWA-window refusal below), so the graph draft never engages for step35
3100    /// models regardless of eligibility — the eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
3101    /// than silently capturing a window-less (wrong past `win` draft rows) graph.
3102    ///
3103    /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
3104    /// caller must not mirror.
3105    fn mtp_step35_attn(
3106        &self,
3107        e: &Engine,
3108        fa: &FullAttnLayer,
3109        g: &crate::hybrid::Step35MtpGeom,
3110        h: &CudaSlice<f32>,
3111        pos_d: &CudaSlice<i32>,
3112        scratch: &mut MtpScratch,
3113    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3114        let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
3115        let eps = self.cfg.rms_eps;
3116        let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
3117        let n_embd = self.cfg.n_embd as usize;
3118        let gw = fa
3119            .attn_gate
3120            .as_ref()
3121            .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
3122
3123        let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
3124            && e.uses_q8_1_fast(&fa.wk)
3125            && e.uses_q8_1_fast(&fa.wv)
3126            && e.uses_q8_1_fast(gw)
3127        {
3128            let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
3129            let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
3130                Some(t3) => t3,
3131                None => (
3132                    e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
3133                    e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
3134                    e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
3135                ),
3136            };
3137            (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
3138        } else {
3139            (
3140                e.matmul(&fa.wq, h, 1)?,
3141                e.matmul(&fa.wk, h, 1)?,
3142                e.matmul(&fa.wv, h, 1)?,
3143                e.matmul(gw, h, 1)?,
3144            )
3145        };
3146
3147        let mut q = e.uninit(nh * hd)?;
3148        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
3149        let mut k = e.uninit(nkv * hd)?;
3150        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
3151        // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
3152        // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
3153        // the resolved flag, not the constant, so an all-full sibling stays correct.
3154        let ff = if g.swa {
3155            None
3156        } else {
3157            self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
3158        };
3159        #[cfg(debug_assertions)]
3160        if let Some(ff) = ff {
3161            crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
3162        }
3163        e.rope_neox2(
3164            &mut q,
3165            &mut k,
3166            pos_d,
3167            hd,
3168            g.n_rot,
3169            nh,
3170            nkv,
3171            1,
3172            g.rope_base,
3173            1.0,
3174            ff,
3175        )?;
3176
3177        // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
3178        // length on the host anyway, and the windowed view below needs it there to compute the
3179        // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
3180        // dc-family consumer of this scratch still agree.
3181        let kv = &mut scratch.kv;
3182        assert!(
3183            kv.len < scratch.cap,
3184            "step35 MTP scratch overflow ({} >= {})",
3185            kv.len,
3186            scratch.cap
3187        );
3188        let next_len = kv.len + 1;
3189        let (off, t_kv) = if g.swa && next_len > g.window {
3190            (next_len - g.window, g.window)
3191        } else {
3192            (0, next_len)
3193        };
3194        let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
3195        e.append_kv_quantized(
3196            &k,
3197            &v0,
3198            &mut kv.k,
3199            &mut kv.v,
3200            write_row,
3201            kv.kv_dim_k,
3202            kv.kv_dim_v,
3203            kv.k_tok_bytes,
3204            kv.v_tok_bytes,
3205            false,
3206        )?;
3207        kv.len = next_len;
3208        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3209        // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
3210        // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
3211        // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
3212        // therefore live, not theoretical.
3213        let physical = kv.physical_rows(off, off + t_kv)?;
3214        let k_view = e.view_u8_range(
3215            &kv.k,
3216            physical.start * kv.k_tok_bytes,
3217            physical.end * kv.k_tok_bytes,
3218        );
3219        let v_view = e.view_u8_range(
3220            &kv.v,
3221            physical.start * kv.v_tok_bytes,
3222            physical.end * kv.v_tok_bytes,
3223        );
3224        let mut attn = e.uninit(nh * hd)?;
3225        e.fa_decode_kvmod(
3226            &q,
3227            &k_view,
3228            &v_view,
3229            &mut attn,
3230            hd,
3231            nh,
3232            nkv,
3233            t_kv,
3234            scale,
3235            kv.k_tok_bytes,
3236            kv.v_tok_bytes,
3237            false,
3238        )?;
3239
3240        let mut ag = e.uninit(nh * hd)?;
3241        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
3242        Ok(e.matmul(&fa.wo, &ag, 1)?)
3243    }
3244
3245    /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
3246    /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
3247    /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
3248    /// chain, and replays keep seeing KV growth through the device counter (no recapture).
3249    /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
3250    /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
3251    /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
3252    /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
3253    /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
3254    fn mtp_full_attn_dc(
3255        &self,
3256        e: &Engine,
3257        fa: &FullAttnLayer,
3258        h: &CudaSlice<f32>,
3259        pos_d: &CudaSlice<i32>,
3260        scratch: &mut MtpScratch,
3261        geom: Option<&crate::hybrid::DraftGeom>,
3262    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3263        let cfg = &self.cfg;
3264        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3265        let geometry = cfg.full_attention_geometry_at(mtp_il);
3266        let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
3267        let n_head_kv = geom
3268            .map(|g| g.n_head_kv)
3269            .unwrap_or(geometry.n_head_kv as usize);
3270        let head_dim = geometry.head_dim_k as usize;
3271        let eps = cfg.rms_eps;
3272        let scale = geometry.attention_scale();
3273        let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
3274        let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
3275
3276        let (qf, mut k, v) =
3277            if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
3278                let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
3279                (
3280                    e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
3281                    e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
3282                    e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
3283                )
3284            } else {
3285                (
3286                    e.matmul(&fa.wq, h, 1)?,
3287                    e.matmul(&fa.wk, h, 1)?,
3288                    e.matmul(&fa.wv, h, 1)?,
3289                )
3290            };
3291        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
3292        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
3293        let (mut q, gate) = if gated {
3294            let mut q = e.zeros(n_head * head_dim)?;
3295            let mut gate = e.zeros(n_head * head_dim)?;
3296            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
3297            (q, Some(gate))
3298        } else {
3299            (qf, None)
3300        };
3301
3302        let mut qn = e.zeros(n_head * head_dim)?;
3303        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
3304        q = qn;
3305        let mut kn = e.zeros(n_head_kv * head_dim)?;
3306        e.rms_norm(
3307            &k,
3308            fa.k_norm.float_data(),
3309            &mut kn,
3310            head_dim,
3311            n_head_kv,
3312            eps,
3313        )?;
3314        k = kn;
3315        let rope_dims = geometry.n_rot as usize;
3316        e.rope_neox(
3317            &mut q,
3318            pos_d,
3319            head_dim,
3320            rope_dims,
3321            n_head,
3322            1,
3323            geometry.rope_base,
3324            1.0,
3325        )?;
3326        e.rope_neox(
3327            &mut k,
3328            pos_d,
3329            head_dim,
3330            rope_dims,
3331            n_head_kv,
3332            1,
3333            geometry.rope_base,
3334            1.0,
3335        )?;
3336
3337        let kv = &mut scratch.kv;
3338        // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
3339        e.append_kv_quantized_dc(
3340            &k,
3341            &v,
3342            &mut kv.k,
3343            &mut kv.v,
3344            &kv.len_d,
3345            kv.kv_dim_k,
3346            kv.kv_dim_v,
3347            kv.k_tok_bytes,
3348            kv.v_tok_bytes,
3349            false,
3350        )?;
3351        e.inc_seqlen(&mut kv.len_d)?;
3352        // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
3353        // key range from the device counter.
3354        let k_view = e.view_u8(&kv.k, kv.k.len());
3355        let v_view = e.view_u8(&kv.v, kv.v.len());
3356        let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
3357        let mut attn = e.zeros(n_head * head_dim)?;
3358        e.fa_decode_dc(
3359            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
3360            scale, ktb, vtb, false,
3361        )?;
3362
3363        let attn_g = match &gate {
3364            Some(gate) => {
3365                let mut gsig = e.zeros(n_head * head_dim)?;
3366                e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
3367                let mut ag = e.zeros(n_head * head_dim)?;
3368                e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
3369                ag
3370            }
3371            None => attn,
3372        };
3373        Ok(e.matmul(&fa.wo, &attn_g, 1)?)
3374    }
3375
3376    /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
3377    /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
3378    /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
3379    /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
3380    /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
3381    /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
3382    /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
3383    /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
3384    #[allow(clippy::too_many_arguments)]
3385    fn mtp_kv_fill(
3386        &self,
3387        e: &Engine,
3388        mtp: &MtpHead,
3389        tokens: &[u32],
3390        h: &CudaSlice<f32>,
3391        pos0: usize,
3392        scratch: &mut MtpScratch,
3393        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3394    ) -> Result<(), Box<dyn std::error::Error>> {
3395        let cfg = &self.cfg;
3396        let n_embd = cfg.n_embd as usize;
3397        let eps = cfg.rms_eps;
3398        let t = tokens.len();
3399        assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
3400        assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
3401        let Mixer::Full(fa) = &mtp.mixer else {
3402            panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3403        };
3404        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
3405        let pos_d = e.htod_i32(&pos_vec)?;
3406
3407        // ops A/1/2: embed + the two input norms, T-wide.
3408        let e_emb = match embd_dev {
3409            Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3410            None => e.htod(&self.embd.gather(n_embd, tokens))?,
3411        };
3412        let mut e_norm = e.zeros(t * n_embd)?;
3413        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
3414        let mut h_norm = e.zeros(t * n_embd)?;
3415        e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
3416
3417        // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
3418        let mut concat = e.zeros(t * 2 * n_embd)?;
3419        for i in 0..t {
3420            e.copy_view_into(
3421                &mut concat,
3422                i * 2 * n_embd,
3423                &e_norm.slice(i * n_embd..(i + 1) * n_embd),
3424                n_embd,
3425            )?;
3426            e.copy_view_into(
3427                &mut concat,
3428                i * 2 * n_embd + n_embd,
3429                &h_norm.slice(i * n_embd..(i + 1) * n_embd),
3430                n_embd,
3431            )?;
3432        }
3433
3434        // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
3435        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3436        let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
3437        let mut a_norm = e.zeros(t * di)?;
3438        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
3439
3440        // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
3441        // the fill only has to leave correct K/V rows behind for later chains to attend over.
3442        let n_head_kv = mtp
3443            .geom
3444            .as_ref()
3445            .map(|g| g.n_head_kv)
3446            .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
3447            .unwrap_or_else(|| {
3448                let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3449                cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
3450            });
3451        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3452        let geometry = cfg.full_attention_geometry_at(mtp_il);
3453        let head_dim = geometry.head_dim_k as usize;
3454        let mut k = e.matmul(&fa.wk, &a_norm, t)?;
3455        let v = e.matmul(&fa.wv, &a_norm, t)?;
3456        let mut kn = e.zeros(t * n_head_kv * head_dim)?;
3457        e.rms_norm(
3458            &k,
3459            fa.k_norm.float_data(),
3460            &mut kn,
3461            head_dim,
3462            n_head_kv * t,
3463            eps,
3464        )?;
3465        k = kn;
3466        // step35: rotary width AND base are per-layer, and the MTP block's values come from the
3467        // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
3468        // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
3469        // writes K rows the attention arm then re-derives at a different theta: correct-looking
3470        // output with dead acceptance, invisible to the exactness gates.
3471        let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
3472            Some(s) => (
3473                s.n_rot,
3474                s.rope_base,
3475                if s.swa {
3476                    None
3477                } else {
3478                    self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
3479                },
3480            ),
3481            None => (geometry.n_rot as usize, geometry.rope_base, None),
3482        };
3483        #[cfg(debug_assertions)]
3484        if let Some(ff) = ff {
3485            crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
3486        }
3487        match ff {
3488            Some(f) => e.rope_neox_ff(
3489                &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
3490            )?,
3491            None => e.rope_neox(
3492                &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
3493            )?,
3494        }
3495
3496        let kv = &mut scratch.kv;
3497        // Match the trunk prime contract: a chunk may need the aligned window immediately before
3498        // its first row, so preserve that prefix when the physical tail rebases at wrap.
3499        let retain_from = kv
3500            .ring
3501            .as_ref()
3502            .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
3503            .unwrap_or(0);
3504        let write_row = e.prepare_kv_append(kv, retain_from, t)?;
3505        for i in 0..t {
3506            let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
3507            let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
3508            e.append_kv_quantized_view(
3509                &k_row,
3510                &v_row,
3511                &mut kv.k,
3512                &mut kv.v,
3513                write_row + i,
3514                kv.kv_dim_k,
3515                kv.kv_dim_v,
3516                kv.k_tok_bytes,
3517                kv.v_tok_bytes,
3518                false,
3519            )?;
3520        }
3521        kv.len = pos0 + t;
3522        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3523        Ok(())
3524    }
3525
3526    /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
3527    /// every varying input device-resident —
3528    ///   - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
3529    ///     so the chain feeds itself; the host reads the same 4 bytes for the draft list),
3530    ///   - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
3531    ///   - rope pos from the persistent `pos_d` counter (inc'd in-graph),
3532    ///   - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
3533    /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
3534    /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
3535    /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
3536    /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
3537    /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
3538    /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
3539    /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
3540    /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
3541    /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
3542    /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
3543    /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
3544    /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
3545    /// seed/temp are capture-time constants (fixed per generate call, like p_min).
3546    #[allow(clippy::too_many_arguments)]
3547    fn mtp_head_forward_cap(
3548        &self,
3549        e: &Engine,
3550        mtp: &MtpHead,
3551        tok_d: &mut CudaSlice<u32>,
3552        pos_d: &mut CudaSlice<i32>,
3553        h_seed_d: &mut CudaSlice<f32>,
3554        p_d: &mut CudaSlice<f32>,
3555        scratch: &mut MtpScratch,
3556        with_prob: bool,
3557        with_head: bool,
3558        embd_gpu: &CudaSlice<u8>,
3559        embd_qt: i32,
3560        embd_rb: usize,
3561        d_vocab: usize,
3562        sampled_cap: Option<(
3563            &mut CudaSlice<u32>,
3564            &mut CudaSlice<f32>,
3565            &mut CudaSlice<f32>,
3566            u64,
3567            f32,
3568        )>,
3569        stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
3570        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
3571        // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
3572        // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
3573        // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
3574        // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
3575        mask_cap: Option<(&CudaSlice<u32>, usize)>,
3576    ) -> Result<(), Box<dyn std::error::Error>> {
3577        let cfg = &self.cfg;
3578        let n_embd = cfg.n_embd as usize;
3579        // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
3580        // whose device-counter key bound always starts at row 0 — it cannot express this block's
3581        // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
3582        // persistent scratch passes 512 rows. Nothing is lost today: `mtp_head_forward_cap`
3583        // refuses step35 heads explicitly (SWA refusal), so the eager chain
3584        // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
3585        // panic) is what the two capture sites and the round-stream capture already handle by
3586        // degrading to eager / stream-off.
3587        if mtp.step35.is_some() {
3588            return Err(
3589                "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
3590                        block's SWA view offset; same root cause as the dc decode refusal) — the \
3591                        eager draft chain serves this arch"
3592                    .into(),
3593            );
3594        }
3595        // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
3596        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3597        let eps = cfg.rms_eps;
3598        let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
3599        let mut e_norm = e.zeros(n_embd)?;
3600        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
3601        let mut h_norm = e.zeros(n_embd)?;
3602        e.rms_norm(
3603            &*h_seed_d,
3604            mtp.hnorm.float_data(),
3605            &mut h_norm,
3606            n_embd,
3607            1,
3608            eps,
3609        )?;
3610        let mut concat = e.zeros(2 * n_embd)?;
3611        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
3612        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
3613        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
3614        let mut a_norm = e.zeros(di)?;
3615        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
3616        let attn_out = match &mtp.mixer {
3617            Mixer::Full(fa) => {
3618                self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
3619            }
3620            Mixer::Linear(_) => {
3621                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3622            }
3623            Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
3624        };
3625        let mut x1 = e.zeros(di)?;
3626        e.add(&inp_sa, &attn_out, &mut x1, di)?;
3627        let mut z = e.zeros(di)?;
3628        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
3629        let ffn_out = match &mtp.ffn {
3630            crate::hybrid::Ffn::Dense {
3631                ffn_gate,
3632                ffn_up,
3633                ffn_down,
3634            } => {
3635                let n_ff = ffn_gate.out_features();
3636                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
3637                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
3638                    (
3639                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
3640                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
3641                    )
3642                } else {
3643                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
3644                };
3645                let mut act = e.zeros(n_ff)?;
3646                Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
3647                e.matmul(ffn_down, &act, 1)?
3648            }
3649            // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
3650            // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
3651            // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
3652            // error arm degrades the caller to eager/stream-off.
3653            crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
3654                self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
3655            }
3656            crate::hybrid::Ffn::Moe(_) => {
3657                return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into());
3658            }
3659        };
3660        let mut h_inner = e.zeros(di)?;
3661        e.add(&x1, &ffn_out, &mut h_inner, di)?;
3662        // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
3663        let h_nextn = match mtp.geom.as_ref() {
3664            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
3665            None => h_inner,
3666        };
3667        // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
3668        let final_h = if with_head || spec_hpost() {
3669            let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
3670            let mut fh = e.zeros(n_embd)?;
3671            e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
3672            Some(fh)
3673        } else {
3674            None
3675        };
3676        if with_head {
3677            let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
3678            let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
3679            // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
3680            // before the argmax — proposals become legal by construction. Contents-only
3681            // per-replay upload keeps the capture valid.
3682            if let Some((mask_d, mw)) = mask_cap {
3683                e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
3684            }
3685            if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
3686                // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
3687                // own buffer is pool-recycled after the capture body returns, so it can't be the
3688                // retention target), bump the device event counter, gumbel-perturb reading it,
3689                // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
3690                e.copy_into(q_out_d, 0, &logits, d_vocab)?;
3691                e.sctr_inc(ctr_d)?;
3692                e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
3693                e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
3694                // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
3695                // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
3696                if with_prob {
3697                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
3698                }
3699            } else {
3700                // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
3701                e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
3702                // p-min under a draft mask reads the MASKED row: confidence relative to the
3703                // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
3704                // is the right semantics for "does the drafter know what comes next here" and
3705                // the same row the pick came from. Draft-quality only — verify arbitrates.
3706                if with_prob {
3707                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
3708                }
3709            }
3710        }
3711        // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
3712        // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
3713        if let Some((out, slot, d2t)) = stream_pack {
3714            e.pack_tok_p(tok_d, p_d, out, slot)?;
3715            if let Some(map) = d2t {
3716                e.tok_map_u32(tok_d, map)?;
3717            }
3718        }
3719        // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
3720        if spec_hpost() {
3721            e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
3722        } else {
3723            e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
3724        }
3725        // advance the draft rope position in-graph.
3726        e.inc_seqlen(pos_d)?;
3727        Ok(())
3728    }
3729
3730    /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
3731    /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
3732    /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
3733    /// Advances `cache.pos` by T.
3734    pub fn decode_step_t(
3735        &self,
3736        e: &Engine,
3737        tokens: &[u32],
3738        pos0: usize,
3739        cache: &mut Cache,
3740    ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
3741        if self.is_gemma4_e4b() {
3742            return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
3743        }
3744        if self.cfg.gemma4.is_some() {
3745            return self.gemma4_decode_step_t(e, tokens, pos0, cache);
3746        }
3747        Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
3748    }
3749
3750    /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
3751    /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
3752    /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
3753    /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
3754    pub fn decode_step_t_h(
3755        &self,
3756        e: &Engine,
3757        tokens: &[u32],
3758        pos0: usize,
3759        cache: &mut Cache,
3760    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3761        self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
3762    }
3763
3764    /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
3765    /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
3766    pub fn decode_step_t_h_emb(
3767        &self,
3768        e: &Engine,
3769        tokens: &[u32],
3770        pos0: usize,
3771        cache: &mut Cache,
3772        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3773    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3774        let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
3775        Ok((e.dtoh(&logits_d)?, h_seed))
3776    }
3777
3778    /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
3779    /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
3780    /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
3781    /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
3782    /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
3783    pub fn decode_step_t_h_emb_dev(
3784        &self,
3785        e: &Engine,
3786        tokens: &[u32],
3787        pos0: usize,
3788        cache: &mut Cache,
3789        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3790    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3791        let n_embd = self.cfg.n_embd as usize;
3792        let t = tokens.len();
3793        let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
3794        // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
3795        let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
3796        e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
3797        Ok((logits, hs))
3798    }
3799
3800    /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
3801    /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
3802    /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
3803    /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
3804    /// retains/copies — they never change what any kernel computes).
3805    fn decode_step_t_core(
3806        &self,
3807        e: &Engine,
3808        tokens: &[u32],
3809        pos0: usize,
3810        cache: &mut Cache,
3811        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3812        mut ckpt: Option<&mut VerifyCkpt>,
3813    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3814        self.decode_step_t_core_stream(
3815            e,
3816            tokens,
3817            pos0,
3818            cache,
3819            embd_dev,
3820            ckpt.take(),
3821            None,
3822            None,
3823            None,
3824            None,
3825        )
3826    }
3827
3828    /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
3829    /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
3830    fn decode_step_t_core_pipelined(
3831        &self,
3832        e: &Engine,
3833        tokens: &[u32],
3834        pos0: usize,
3835        cache: &mut Cache,
3836        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3837        mut ckpt: Option<&mut VerifyCkpt>,
3838        pipe: &SpecPipeLane,
3839        round: usize,
3840    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3841        let fence = crate::pp::pp_cuts(self.layers.len())
3842            .ok_or("two-session speculative pipeline requires a PP stage cut")?;
3843        if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
3844            return Err("two-session speculative pipeline requires the PP verify split".into());
3845        }
3846        let interval_fence = pipe.stage0_begin(round)?;
3847        let ticket = self.verify_stage0_issue(
3848            e,
3849            tokens,
3850            pos0,
3851            cache,
3852            embd_dev,
3853            ckpt.as_deref_mut(),
3854            None,
3855            &fence,
3856            Some(interval_fence),
3857            pipe.trace(round),
3858        )?;
3859        pipe.stage0_end(round);
3860        pipe.stage1_begin(round)?;
3861        let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
3862        pipe.verify_end(round);
3863        Ok(result)
3864    }
3865
3866    /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
3867    /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
3868    /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
3869    /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
3870    /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
3871    /// `vtok_dev` (engine-bundle slice 2): device verify tokens for the EMBED only —
3872    /// unlike `stream` mode it changes nothing else (host pos iota, host-len KV appends).
3873    /// `tokens` then only sizes buffers (the dummy-slice pattern the round-stream arm uses).
3874    #[allow(clippy::too_many_arguments)]
3875    fn decode_step_t_core_stream(
3876        &self,
3877        e: &Engine,
3878        tokens: &[u32],
3879        pos0: usize,
3880        cache: &mut Cache,
3881        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3882        mut ckpt: Option<&mut VerifyCkpt>,
3883        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3884        pp_pipe: Option<bool>,
3885        vtok_dev: Option<&CudaSlice<u32>>,
3886        graphs: Option<&mut DsparkVerifyGraphs>,
3887    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3888        // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
3889        // exactly as the eager and batched steps do. This is the single funnel every verify
3890        // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
3891        // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
3892        // is untouched.
3893        //
3894        // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
3895        // walk was unsplit on one stream and a sharded cross-device placement peer-read every
3896        // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
3897        // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
3898        // or a placement whose PpNRt fails to build — so a config that would still walk the
3899        // whole trunk on one stream refuses instead of regressing 28x.
3900        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
3901            if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
3902                if vtok_dev.is_some() {
3903                    return Err(
3904                        "device-token dspark verify (slice-2 deferred readback) has no PP \
3905                         stage-split arm; set MEMRA_DSPARK_DEFER_READBACK=0 or run the dspark \
3906                         route on one device"
3907                            .into(),
3908                    );
3909                }
3910                return self.decode_step_t_core_ppn(
3911                    e,
3912                    tokens,
3913                    pos0,
3914                    cache,
3915                    embd_dev,
3916                    ckpt.take(),
3917                    stream,
3918                    &fence,
3919                    pp_pipe,
3920                );
3921            }
3922        }
3923        crate::pp::refuse_unsplit_if_remote(
3924            "decode_step_t (spec verify)",
3925            "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
3926             split (decode_step_t_core_ppn); or run spec on one device",
3927        )?;
3928        let cfg = &self.cfg;
3929        let n_embd = cfg.n_embd as usize;
3930        let eps = cfg.rms_eps;
3931        let t = tokens.len();
3932        let pos_d = match stream {
3933            Some((_, ctr)) => {
3934                let mut p = e.alloc_uninit::<i32>(t)?;
3935                e.pos_iota(ctr, &mut p, t)?;
3936                p
3937            }
3938            None => {
3939                let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3940                e.htod_i32(&pos_vec)?
3941            }
3942        };
3943
3944        // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
3945        let x = match (stream, embd_dev) {
3946            (Some((vtok, _)), Some((g, qt, rb))) => {
3947                e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3948            }
3949            (None, Some((g, qt, rb))) => match vtok_dev {
3950                // slice 2: device verify tokens, same embed_gather_u32_t kernel —
3951                // bit-identical rows to the host-token arm (same per-dtype deq).
3952                Some(vt_d) => e.embed_gather_device_td(g, vt_d, t, n_embd, qt, rb)?,
3953                None => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3954            },
3955            _ => {
3956                assert!(
3957                    vtok_dev.is_none(),
3958                    "device-token verify requires the resident embed table (embd_dev)"
3959                );
3960                e.htod(&self.embd.gather(n_embd, tokens))?
3961            }
3962        };
3963
3964        // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
3965        // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
3966        // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
3967        let x = self.verify_layers(
3968            e,
3969            x,
3970            0,
3971            self.layers.len(),
3972            &pos_d,
3973            pos0,
3974            t,
3975            cache,
3976            ckpt.take(),
3977            stream,
3978            graphs,
3979        )?;
3980
3981        let mut hn = vbuf(e, t * n_embd)?;
3982        let serving_head = self.cfg.step35.is_some() || self.qwen35_serving_class();
3983        let logits = if serving_head {
3984            // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
3985            // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
3986            // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
3987            // serve one batched numeric class at every live width, including B=1. Keep the
3988            // verify head in that same class; other generic families retain the decode-exact
3989            // head that their run-spec contract pins.
3990            e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3991            e.matmul(&self.output, &hn, t)?
3992        } else {
3993            e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3994            e.matmul_decode_exact(&self.output, &hn, t)?
3995        };
3996        // stream: the device pos counter owns position; host mirror reconciles at drain.
3997        if stream.is_none() {
3998            cache.pos += t;
3999        }
4000        // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
4001        Ok((logits, if spec_hpost() { hn } else { x }))
4002    }
4003
4004    /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
4005    /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
4006    /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
4007    /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
4008    /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
4009    /// the payload).
4010    ///
4011    /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
4012    /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
4013    /// receipts):
4014    ///
4015    /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
4016    ///    (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
4017    ///    DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
4018    ///    (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
4019    ///    s>0 its own Engine even on the primary device; honouring it here is what scopes the
4020    ///    pools. The verify path allocates MORE of that scratch than eager decode does (FA at
4021    ///    m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
4022    ///
4023    /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
4024    ///    buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
4025    ///    stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
4026    ///    read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
4027    ///    stage derives the identical iota, and each stage's own output buffer is stream-local.
4028    ///
4029    /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
4030    ///    sharded loader leaves the table with stage 0 by construction).
4031    ///
4032    /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
4033    ///    both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
4034    ///    n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
4035    ///    model, every round.
4036    ///
4037    /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
4038    /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
4039    /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
4040    /// through the primary context by UVA — the same read the batched serving epilogue's
4041    /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
4042    /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
4043    ///
4044    /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
4045    /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
4046    /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
4047    ///
4048    /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
4049    /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
4050    /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
4051    /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
4052    /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
4053    /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
4054    /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
4055    /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
4056    #[allow(clippy::too_many_arguments)]
4057    fn decode_step_t_core_ppn(
4058        &self,
4059        e: &Engine,
4060        tokens: &[u32],
4061        pos0: usize,
4062        cache: &mut Cache,
4063        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4064        mut ckpt: Option<&mut VerifyCkpt>,
4065        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4066        fence: &[usize],
4067        pp_pipe: Option<bool>,
4068    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4069        let ticket = self.verify_stage0_issue(
4070            e,
4071            tokens,
4072            pos0,
4073            cache,
4074            embd_dev,
4075            ckpt.as_deref_mut(),
4076            stream,
4077            fence,
4078            pp_pipe,
4079            None,
4080        )?;
4081        self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
4082    }
4083
4084    /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
4085    /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
4086    #[allow(clippy::too_many_arguments)]
4087    fn verify_stage0_issue(
4088        &self,
4089        e: &Engine,
4090        tokens: &[u32],
4091        pos0: usize,
4092        cache: &mut Cache,
4093        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4094        mut ckpt: Option<&mut VerifyCkpt>,
4095        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4096        fence: &[usize],
4097        pp_pipe: Option<bool>,
4098        trace: Option<SpecPipeTraceCtx>,
4099    ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
4100        assert!(
4101            !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
4102            "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
4103             (the gemma4 arms have their own decode_step_t twins)"
4104        );
4105        if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
4106            return Err(
4107                "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
4108                 boundary itself is host-staged, but device-resident verify still peer-reads \
4109                 primary-device token/position/embedding buffers from stage 0. Run plain PP \
4110                 serving on this host class; spec requires local per-stage inputs first."
4111                    .into(),
4112            );
4113        }
4114        let rt = crate::pp::PpNRt::get(e)?;
4115        let n_st = fence.len() - 1;
4116        assert_eq!(
4117            rt.n_stages(),
4118            n_st,
4119            "PpNRt stage count {} != fence stages {n_st}",
4120            rt.n_stages()
4121        );
4122        let n_embd = self.cfg.n_embd as usize;
4123        let t = tokens.len();
4124        let payload = t * n_embd;
4125        if pp_pipe.is_some() {
4126            assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
4127        }
4128        // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
4129        // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
4130        // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
4131        // the report below names exactly two stages and must never imply it measured middle ones.
4132        let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
4133        let pp_started = std::time::Instant::now();
4134        let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
4135        // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
4136        // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
4137        // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
4138        // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
4139        // stage stream and the wait would self-order into a no-op.
4140        let caller_stream = e.stream();
4141        // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
4142        // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
4143        // the primary stream still holds queued reads of them — with event tracking elided,
4144        // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
4145        // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
4146        // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
4147        // stage stream behind the caller before enqueueing new stage work.
4148        let reverse_started = std::time::Instant::now();
4149        if pp_pipe != Some(false) {
4150            rt.fence_stages_behind(&caller_stream)?;
4151        }
4152        if pp_pipe == Some(true) {
4153            // Both session verifies must alternate boundary slots even when the ordinary
4154            // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
4155            // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
4156            rt.prepare_overlap_slots(0, payload)?;
4157        }
4158        if pp_anatomy {
4159            // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
4160            // prices any primary-stream rollback/refresh tail inherited from the prior round.
4161            for s in 0..n_st {
4162                let _st = rt.enter(s);
4163                rt.engine(s, e).stream().synchronize()?;
4164            }
4165            reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
4166        }
4167
4168        // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
4169        // stream mode each stage's own `pos_iota` over the shared read-only device counter.
4170        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
4171            match stream {
4172                Some((_, ctr)) => {
4173                    let mut p = es.alloc_uninit::<i32>(t)?;
4174                    es.pos_iota(ctr, &mut p, t)?;
4175                    Ok(p)
4176                }
4177                None => {
4178                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4179                    es.htod_i32(&pos_vec)
4180                }
4181            }
4182        };
4183
4184        // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
4185        let slot = {
4186            let _st0 = rt.enter(0);
4187            let e0 = rt.engine(0, e);
4188            enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
4189            let stage0_started = std::time::Instant::now();
4190            let pos_d = stage_pos(e0)?;
4191            let x = match (stream, embd_dev) {
4192                (Some((vtok, _)), Some((g, qt, rb))) => {
4193                    e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
4194                }
4195                (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
4196                _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
4197            };
4198            let x = self.verify_layers(
4199                e0,
4200                x,
4201                fence[0],
4202                fence[1],
4203                &pos_d,
4204                pos0,
4205                t,
4206                cache,
4207                ckpt.as_deref_mut(),
4208                stream,
4209                None,
4210            )?;
4211            if pp_anatomy {
4212                e0.stream().synchronize()?;
4213                stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
4214            }
4215            let tx_started = std::time::Instant::now();
4216            let slot = if pp_pipe.is_some() {
4217                rt.tx_pipelined(0, &x, payload)?
4218            } else {
4219                rt.tx(0, &x, payload)?
4220            };
4221            enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
4222            if pp_anatomy {
4223                e0.stream().synchronize()?;
4224                tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
4225            }
4226            slot
4227            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
4228        };
4229
4230        Ok(VerifyBoundaryTicket {
4231            rt,
4232            caller_stream,
4233            slot,
4234            pos0,
4235            t,
4236            payload,
4237            n_st,
4238            pipelined: pp_pipe.is_some(),
4239            pp_anatomy,
4240            pp_started,
4241            reverse_ms,
4242            stage0_ms,
4243            tx_ms,
4244            trace,
4245        })
4246    }
4247
4248    /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
4249    /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
4250    #[allow(clippy::too_many_arguments)]
4251    fn verify_stage1_finish(
4252        &self,
4253        e: &Engine,
4254        ticket: VerifyBoundaryTicket,
4255        cache: &mut Cache,
4256        mut ckpt: Option<&mut VerifyCkpt>,
4257        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4258        fence: &[usize],
4259        publish_to_caller: bool,
4260    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4261        let VerifyBoundaryTicket {
4262            rt,
4263            caller_stream,
4264            slot,
4265            pos0,
4266            t,
4267            payload,
4268            n_st,
4269            pipelined,
4270            pp_anatomy,
4271            pp_started,
4272            reverse_ms,
4273            stage0_ms,
4274            tx_ms,
4275            trace,
4276        } = ticket;
4277        let n_embd = self.cfg.n_embd as usize;
4278        let eps = self.cfg.rms_eps;
4279        let mut slot = slot;
4280        let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
4281        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
4282            match stream {
4283                Some((_, ctr)) => {
4284                    let mut p = es.alloc_uninit::<i32>(t)?;
4285                    es.pos_iota(ctr, &mut p, t)?;
4286                    Ok(p)
4287                }
4288                None => {
4289                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4290                    es.htod_i32(&pos_vec)
4291                }
4292            }
4293        };
4294
4295        // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
4296        for s in 1..n_st - 1 {
4297            let _st = rt.enter(s);
4298            let es = rt.engine(s, e);
4299            let pos_d = stage_pos(es)?;
4300            let x = rt.rx(s - 1, slot, payload)?;
4301            let x = self.verify_layers(
4302                es,
4303                x,
4304                fence[s],
4305                fence[s + 1],
4306                &pos_d,
4307                pos0,
4308                t,
4309                cache,
4310                ckpt.as_deref_mut(),
4311                stream,
4312                None,
4313            )?;
4314            slot = if pipelined {
4315                rt.tx_pipelined(s, &x, payload)?
4316            } else {
4317                rt.tx(s, &x, payload)?
4318            };
4319        }
4320
4321        // ---- LAST STAGE: RX + final range + output_norm + lm head ----
4322        let _stl = rt.enter(n_st - 1);
4323        let el = rt.engine(n_st - 1, e);
4324        let pos_d = stage_pos(el)?;
4325        let rx_started = std::time::Instant::now();
4326        let x = rt.rx(n_st - 2, slot, payload)?;
4327        if pp_anatomy {
4328            el.stream().synchronize()?;
4329            rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
4330        }
4331        enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
4332        let stage1_started = std::time::Instant::now();
4333        let x = self.verify_layers(
4334            el,
4335            x,
4336            fence[n_st - 1],
4337            fence[n_st],
4338            &pos_d,
4339            pos0,
4340            t,
4341            cache,
4342            ckpt.as_deref_mut(),
4343            stream,
4344            None,
4345        )?;
4346
4347        let mut hn = vbuf(el, payload)?;
4348        let logits = if self.cfg.step35.is_some() {
4349            // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
4350            // Verify must not switch numeric class merely because the same session speculates.
4351            el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4352            el.matmul(&self.output, &hn, t)?
4353        } else {
4354            el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4355            el.matmul_decode_exact(&self.output, &hn, t)?
4356        };
4357        enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
4358        if pp_anatomy {
4359            el.stream().synchronize()?;
4360            stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
4361        }
4362        // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
4363        // stream. Order the caller's stream behind that work before the buffers escape this
4364        // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
4365        // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
4366        // the following arm's KV in the same process).
4367        if publish_to_caller {
4368            rt.publish_to(n_st - 1, &caller_stream)?;
4369        }
4370        if pp_anatomy {
4371            if publish_to_caller {
4372                caller_stream.synchronize()?;
4373            }
4374            eprintln!(
4375                "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
4376                 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
4377                pp_started.elapsed().as_secs_f64() * 1e3,
4378            );
4379        }
4380        // stream: the device pos counter owns position; host mirror reconciles at drain.
4381        if stream.is_none() {
4382            cache.pos += t;
4383        }
4384        Ok((logits, if spec_hpost() { hn } else { x }))
4385    }
4386
4387    /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
4388    ///
4389    /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
4390    /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
4391    /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
4392    /// Those classes are individually stable, but a near-tie prompt can choose different greedy
4393    /// bytes when a request moves from batched plain serving into speculative verify. Run the
4394    /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
4395    /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
4396    /// every norm/projection/FFN uses exactly the live serving dispatch.
4397    #[allow(clippy::too_many_arguments)]
4398    fn step35_verify_batch_layers(
4399        &self,
4400        e: &Engine,
4401        mut x: CudaSlice<f32>,
4402        lo: usize,
4403        hi: usize,
4404        pos0: usize,
4405        t: usize,
4406        cache: &mut Cache,
4407    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4408        let n_embd = self.cfg.n_embd as usize;
4409        self.cfg
4410            .step35
4411            .as_ref()
4412            .ok_or("step35 verify batch requires step35 cfg")?;
4413        let mut ph_last = std::time::Instant::now();
4414        for il in lo..hi {
4415            let mut next = e.uninit(t * n_embd)?;
4416            for r in 0..t {
4417                let mut row = e.uninit(n_embd)?;
4418                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
4419                // The caller owns this verify's position. During controller overlap, cache.pos
4420                // still describes generation N while this stage-0 walk belongs to N+1.
4421                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
4422                let mut one = [&mut *cache];
4423                let out = self.step35_decode_batch_layers(
4424                    e,
4425                    row,
4426                    &mut one,
4427                    &row_pos,
4428                    il,
4429                    il + 1,
4430                    &mut ph_last,
4431                )?;
4432                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
4433            }
4434            self.dflash_tap(e, cache, il, &next, t)?;
4435            x = next;
4436        }
4437        Ok(x)
4438    }
4439
4440    /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
4441    /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
4442    /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
4443    /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
4444    /// prefix-keep, not all-or-nothing).
4445    pub(crate) fn dspark_verify_t_am(
4446        &self,
4447        e: &Engine,
4448        tokens: &[u32],
4449        pos0: usize,
4450        cache: &mut Cache,
4451    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
4452        let (logits, _hn) = self.decode_step_t_core_stream(
4453            e, tokens, pos0, cache, None, None, None, None, None, None,
4454        )?;
4455        let t = tokens.len();
4456        let v = self.output.out_features();
4457        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
4458        for r in 0..t {
4459            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
4460        }
4461        Ok(e.dtoh_u32(&am_d)?)
4462    }
4463
4464    /// DSpark verify with the MTP column-stash armed: identical forward to
4465    /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
4466    /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
4467    /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
4468    pub(crate) fn dspark_verify_t_am_ckpt(
4469        &self,
4470        e: &Engine,
4471        tokens: &[u32],
4472        pos0: usize,
4473        cache: &mut Cache,
4474    ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
4475        let mut ck = VerifyCkpt::new(self.layers.len());
4476        let (logits, _hn) = self.decode_step_t_core_stream(
4477            e,
4478            tokens,
4479            pos0,
4480            cache,
4481            None,
4482            Some(&mut ck),
4483            None,
4484            None,
4485            None,
4486            None,
4487        )?;
4488        let t = tokens.len();
4489        let v = self.output.out_features();
4490        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
4491        for r in 0..t {
4492            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
4493        }
4494        Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
4495    }
4496
4497    /// Engine-bundle slice 2: `dspark_verify_t_am_ckpt` with DEVICE tokens and NO readback.
4498    /// The verify tokens are the round's `chain_d` (cand layout: [anchor, drafts...]); the
4499    /// embed gathers its first `t` entries on-device (`embed_gather_u32_t` — bit-identical
4500    /// rows to the host arm), so the host never blocks on the draft chain before dispatching
4501    /// verify. Returns the device per-row argmax buffer; the caller merges its readback with
4502    /// the chain's into ONE sync. Forward, ckpt fill and argmax walk are `_ckpt` verbatim.
4503    pub(crate) fn dspark_verify_t_am_ckpt_dev(
4504        &self,
4505        e: &Engine,
4506        vtok: &CudaSlice<u32>,
4507        t: usize,
4508        pos0: usize,
4509        cache: &mut Cache,
4510        embd_dev: (&CudaSlice<u8>, i32, usize),
4511        graphs: Option<&mut DsparkVerifyGraphs>,
4512    ) -> Result<(CudaSlice<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
4513        debug_assert!(
4514            vtok.len() >= t,
4515            "verify window exceeds the device token buffer"
4516        );
4517        // The slab flag is a per-round statement: clear it here so a verify that never
4518        // reaches the graphs door (rowwise env, a non-tparallel arm) cannot leave a
4519        // stale `true` steering the commit at slabs the round never wrote.
4520        let mut graphs = graphs;
4521        if let Some(g) = graphs.as_deref_mut() {
4522            g.round_slab = false;
4523        }
4524        let mut ck = VerifyCkpt::new(self.layers.len());
4525        // Dummy host tokens size the funnel; the embed reads `vtok` (the round-stream
4526        // arm's established pattern — spec.rs stream-mode verify does the same).
4527        let dummy = vec![0u32; t];
4528        let (logits, _hn) = self.decode_step_t_core_stream(
4529            e,
4530            &dummy,
4531            pos0,
4532            cache,
4533            Some(embd_dev),
4534            Some(&mut ck),
4535            None,
4536            None,
4537            Some(vtok),
4538            graphs,
4539        )?;
4540        let v = self.output.out_features();
4541        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
4542        for r in 0..t {
4543            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
4544        }
4545        Ok((am_d, DsparkVerifyCkpt(ck)))
4546    }
4547
4548    /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
4549    /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
4550    /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
4551    pub(crate) fn dspark_commit_prefix(
4552        &self,
4553        e: &Engine,
4554        cache: &mut Cache,
4555        snap: &crate::cache::CacheSnapshot,
4556        ckpt: &DsparkVerifyCkpt,
4557        keep: usize,
4558    ) -> Result<(), Box<dyn std::error::Error>> {
4559        self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
4560    }
4561
4562    /// Slice-3 commit twin: restore to `keep` accepted columns when the round's linear
4563    /// column stash lives in the graphs ctx's persistent slabs (`DsparkVerifyGraphs`) —
4564    /// the cols arm's exact semantics (KV lens + pos from the snapshot, GDN conv/ssm
4565    /// from the stash of column keep-1), slab-addressed and batched into two copy
4566    /// launches. `MEMRA_STATE_COPY_BATCH=0` falls back to per-layer view copies.
4567    pub(crate) fn dspark_commit_prefix_slab(
4568        &self,
4569        e: &Engine,
4570        cache: &mut Cache,
4571        snap: &crate::cache::CacheSnapshot,
4572        ctx: &DsparkVerifyGraphs,
4573        keep: usize,
4574    ) -> Result<(), Box<dyn std::error::Error>> {
4575        use cudarc::driver::DevicePtr;
4576        debug_assert!(keep >= 1, "keep==0 rounds take the legacy rollback");
4577        let mut conv_src: Vec<u64> = Vec::new();
4578        let mut ssm_src: Vec<u64> = Vec::new();
4579        let mut conv_dst: Vec<u64> = Vec::new();
4580        let mut ssm_dst: Vec<u64> = Vec::new();
4581        for il in 0..self.layers.len() {
4582            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
4583                kvl.len = saved + keep;
4584                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
4585            }
4586            if let Some(rl) = cache.recur[il].as_ref() {
4587                let (pc, ps, _cw, _sw) = ctx
4588                    .slab_row(e, il, keep - 1)
4589                    .ok_or("slab commit: linear layer missing from the graphs ctx")?;
4590                conv_src.push(pc);
4591                ssm_src.push(ps);
4592                let st = &e.gpu.stream();
4593                let (dc, _g0) = rl.conv_state.device_ptr(st);
4594                let (ds, _g1) = rl.ssm_state.device_ptr(st);
4595                conv_dst.push(dc as u64);
4596                ssm_dst.push(ds as u64);
4597            }
4598        }
4599        let n = conv_src.len();
4600        if n > 0 {
4601            if state_copy_batch_on() {
4602                let mut tt = vec![0u64; 2 * n];
4603                tt[..n].copy_from_slice(&conv_src);
4604                tt[n..].copy_from_slice(&conv_dst);
4605                let ct = e.htod_u64(&tt)?;
4606                tt[..n].copy_from_slice(&ssm_src);
4607                tt[n..].copy_from_slice(&ssm_dst);
4608                let st = e.htod_u64(&tt)?;
4609                e.copy_batch_uniform_f32(&ct, n, ctx.conv_words)?;
4610                e.copy_batch_uniform_f32(&st, n, ctx.ssm_words)?;
4611            } else {
4612                let (cw, sw) = (ctx.conv_words, ctx.ssm_words);
4613                let row = keep - 1;
4614                for il in 0..self.layers.len() {
4615                    let Some(rl) = cache.recur[il].as_mut() else {
4616                        continue;
4617                    };
4618                    let k = ctx.lin_pos[&il];
4619                    {
4620                        let sv = e.view(&ctx.stash_conv[k], (row + 1) * cw);
4621                        let win = sv.slice(row * cw..(row + 1) * cw);
4622                        e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
4623                    }
4624                    {
4625                        let sv = e.view(&ctx.stash_ssm[k], (row + 1) * sw);
4626                        let win = sv.slice(row * sw..(row + 1) * sw);
4627                        e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
4628                    }
4629                }
4630            }
4631        }
4632        cache.pos = snap.pos + keep;
4633        Ok(())
4634    }
4635
4636    /// Qwen35-family verify trunk in the live serving numeric class.
4637    ///
4638    /// Serving intentionally keeps this architecture in the generic batched program even at
4639    /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
4640    ///
4641    /// Two arms, one numeric class:
4642    /// - DENSE (`Arch::Qwen35`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
4643    ///   projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
4644    ///   program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
4645    ///   == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
4646    ///   append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
4647    ///   row's own t_kv-driven arm pick (the straddle law: every row executes the exact
4648    ///   program its isolated serving step would). One weight read per layer per round
4649    ///   instead of T — this is what makes MTP profitable in the exact class (the per-row
4650    ///   walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
4651    /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
4652    ///   serving layer body, preserving single-session autoregressive cache order (the
4653    ///   correctness reference; also the rollback seam for the t-parallel arm).
4654    ///
4655    /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
4656    /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
4657    #[allow(clippy::too_many_arguments)]
4658    fn qwen35_verify_batch_layers(
4659        &self,
4660        e: &Engine,
4661        x: CudaSlice<f32>,
4662        lo: usize,
4663        hi: usize,
4664        pos0: usize,
4665        t: usize,
4666        cache: &mut Cache,
4667        ckpt: Option<&mut VerifyCkpt>,
4668        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4669        graphs: Option<&mut DsparkVerifyGraphs>,
4670    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4671        // Qwen35Moe admitted 2026-08-20 (lane/draftcost-moe): the t-parallel arm already
4672        // carries the MoE FFN (`moe_ffn_il_zq8` at m=T) and the GDN per-row state loop; the
4673        // arch fence was a qualification gate, not a mechanism gap. Measured disease on the
4674        // 35B-A3B class: rowwise verify ~= 5.6 ms per drafted token (one full trunk step
4675        // each) — the same (K+1)-plain-steps wall the dense admission fixed on 2026-08-15.
4676        // Rollback seam unchanged: MEMRA_SPEC_VERIFY_ROWWISE=1.
4677        let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
4678            || !matches!(
4679                self.cfg.arch,
4680                memra_gguf::config::Arch::Qwen35 | memra_gguf::config::Arch::Qwen35Moe
4681            )
4682            || t > 16;
4683        if rowwise {
4684            if stream.is_some() {
4685                // rowwise replays per row with host cache.pos — irreconcilable with a
4686                // device position counter. Burst callers must keep t <= 16 and the
4687                // ROWWISE env unset; refusing beats silently mispositioned rows.
4688                return Err("qwen35 rowwise verify has no ROUND-STREAM arm \
4689                            (t > 16 or MEMRA_SPEC_VERIFY_ROWWISE=1)"
4690                    .into());
4691            }
4692            self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
4693        } else {
4694            self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt, stream, graphs)
4695        }
4696    }
4697
4698    /// The per-row correctness reference: replay each verify row through the authoritative
4699    /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
4700    #[allow(clippy::too_many_arguments)]
4701    fn qwen35_verify_rowwise(
4702        &self,
4703        e: &Engine,
4704        mut x: CudaSlice<f32>,
4705        lo: usize,
4706        hi: usize,
4707        pos0: usize,
4708        t: usize,
4709        cache: &mut Cache,
4710        mut ckpt: Option<&mut VerifyCkpt>,
4711    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4712        let n_embd = self.cfg.n_embd as usize;
4713        let saved_pos = cache.pos;
4714        let mut ph_last = std::time::Instant::now();
4715        for il in lo..hi {
4716            let mut next = e.uninit(t * n_embd)?;
4717            let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4718                if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
4719                    Some(Vec::with_capacity(t - 1))
4720                } else {
4721                    None
4722                };
4723            for r in 0..t {
4724                cache.pos = pos0 + r;
4725                let mut row = e.uninit(n_embd)?;
4726                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
4727                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
4728                let mut one = [&mut *cache];
4729                let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
4730                let out = match self.decode_batch_layers(
4731                    e,
4732                    row,
4733                    &mut one,
4734                    &ctx,
4735                    &row_pos,
4736                    &mut ph_last,
4737                ) {
4738                    Ok(out) => out,
4739                    Err(error) => {
4740                        cache.pos = saved_pos;
4741                        return Err(error);
4742                    }
4743                };
4744                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
4745                if r + 1 < t {
4746                    if let Some(states) = col_states.as_mut() {
4747                        let recur = cache.recur[il]
4748                            .as_ref()
4749                            .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
4750                        states.push((
4751                            e.clone_dtod(&recur.conv_state)?,
4752                            e.clone_dtod(&recur.ssm_state)?,
4753                        ));
4754                    }
4755                }
4756            }
4757            if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
4758                checkpoint.cols[il] = Some(states);
4759            }
4760            x = next;
4761        }
4762        cache.pos = saved_pos;
4763        Ok(x)
4764    }
4765
4766    /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
4767    ///
4768    /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
4769    /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
4770    /// pins the serving batch tier already carries:
4771    ///   * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
4772    ///     kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
4773    ///     alone;
4774    ///   * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
4775    ///     `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
4776    ///     launch is the per-row program (same pin the generic verify's fused norms rely on).
4777    /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
4778    /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
4779    /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
4780    /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
4781    /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
4782    /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
4783    /// program its isolated B=1 serving step would.
4784    ///
4785    /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
4786    /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
4787    #[allow(clippy::too_many_arguments)]
4788    fn qwen35_verify_tparallel(
4789        &self,
4790        e: &Engine,
4791        mut x: CudaSlice<f32>,
4792        lo: usize,
4793        hi: usize,
4794        pos0: usize,
4795        t: usize,
4796        cache: &mut Cache,
4797        mut ckpt: Option<&mut VerifyCkpt>,
4798        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4799        mut graphs: Option<&mut DsparkVerifyGraphs>,
4800    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4801        use cudarc::driver::DevicePtr;
4802        let cfg = &self.cfg;
4803        let n_embd = cfg.n_embd as usize;
4804        let eps = cfg.rms_eps;
4805        let head_dim_global = cfg.head_dim_k as usize;
4806        // STREAM (2b, lane/draftcost-moe): positions come from the device round counter
4807        // (pos_iota / i32_copy_add) so a burst round needs no host position knowledge.
4808        let pos_d = match stream {
4809            Some((_, ctr)) => {
4810                let mut p = e.alloc_uninit::<i32>(t)?;
4811                e.pos_iota(ctr, &mut p, t)?;
4812                p
4813            }
4814            None => {
4815                let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
4816                e.htod_i32(&pos_host)?
4817            }
4818        };
4819        // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
4820        // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
4821        let pos_rows: Vec<CudaSlice<i32>> = match stream {
4822            Some((_, ctr)) => (0..t)
4823                .map(|r| {
4824                    let mut b = e.alloc_uninit::<i32>(1)?;
4825                    e.i32_copy_add(ctr, &mut b, r as i32)?;
4826                    Ok(b)
4827                })
4828                .collect::<Result<_, Box<dyn std::error::Error>>>()?,
4829            None => (0..t)
4830                .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
4831                .collect::<Result<_, _>>()?,
4832        };
4833        let seqs_append =
4834            std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
4835        let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
4836
4837        // Engine-bundle slice 3: with a graphs ctx armed, runs of consecutive LINEAR layers
4838        // replay per-(segment, vt) CUDA graphs (captured from the SAME
4839        // `qwen35_tparallel_linear_layer` body the eager arm runs — no second copy of the
4840        // math). The full-attention layers stay eager: their per-row append/fa arm picks are
4841        // t_kv-driven (the straddle law) and belong to the exec-update extension, not this
4842        // slice. Pointer tables are refreshed once per verify (gdn ping-pong moves handles).
4843        // Merge guard (v0.98 train): the ROUND-STREAM arm (lane/draftcost-moe, device
4844        // position counter) and the dspark verify graphs (engine-bundle slice 3) have no
4845        // common caller — stream rides the qwen35moe burst, graphs ride the dspark route.
4846        // If a future caller arms both, refuse loudly instead of silently dropping the
4847        // graphs ctx (the stream linear arm takes linear_attn_verify_t, not the graphed
4848        // segment body).
4849        if stream.is_some() && graphs.is_some() {
4850            return Err(
4851                "qwen35 tparallel verify: ROUND-STREAM and dspark verify graphs \
4852                        cannot arm together"
4853                    .into(),
4854            );
4855        }
4856        if let Some(g) = graphs.as_deref_mut() {
4857            g.refresh_tables(e, cache)?;
4858            g.round_slab = false;
4859        }
4860        let mut il = lo;
4861        while il < hi {
4862            if graphs.is_some() && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
4863                let mut end = il;
4864                while end < hi && matches!(self.layers[end].mixer, Mixer::Linear(_)) {
4865                    end += 1;
4866                }
4867                let g = graphs.as_deref_mut().expect("checked above");
4868                x = g.run_segment(self, e, il, end, &x, t, cache)?;
4869                g.round_slab = true;
4870                il = end;
4871                continue;
4872            }
4873            let layer = &self.layers[il];
4874            if stream.is_none() && matches!(layer.mixer, Mixer::Linear(_)) {
4875                // Eager linear layer (no graphs ctx): the shared body, legacy cols-ckpt arm.
4876                // Under ROUND-STREAM the linear layers ride the match's stream arm below
4877                // (linear_attn_verify_t — the stream COMMIT needs its GdnStash).
4878                x = self.qwen35_tparallel_linear_layer(
4879                    e,
4880                    il,
4881                    &x,
4882                    t,
4883                    cache,
4884                    ckpt.as_deref_mut(),
4885                    None,
4886                    None,
4887                )?;
4888                il += 1;
4889                continue;
4890            }
4891            // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
4892            let anorm = layer.attn_norm.float_data();
4893            let mut xn = e.uninit(t * n_embd)?;
4894            e.rms_norm(&x, anorm, &mut xn, n_embd, t, eps)?;
4895            let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
4896
4897            let mixed: CudaSlice<f32> = match &layer.mixer {
4898                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4899                Mixer::Full(fa) => {
4900                    let geometry = cfg.full_attention_geometry_at(il as u32);
4901                    let n_head = geometry.n_head as usize;
4902                    let n_head_kv = geometry.n_head_kv as usize;
4903                    let head_dim = geometry.head_dim_k as usize;
4904                    let rope_dims = geometry.n_rot as usize;
4905                    let rope_base = geometry.rope_base;
4906                    let scale = geometry.attention_scale();
4907                    // Batched projections: one weight read serves all T rows.
4908                    let qf = e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?;
4909                    let mut k = e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?;
4910                    let v = e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?;
4911                    let gated =
4912                        geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
4913                    let (mut q, gate) = if gated {
4914                        let mut qs = e.uninit(t * n_head * head_dim)?;
4915                        let mut gs = e.uninit(t * n_head * head_dim)?;
4916                        e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
4917                        (qs, Some(gs))
4918                    } else {
4919                        (qf, None)
4920                    };
4921                    let mut qn = e.uninit(t * n_head * head_dim)?;
4922                    e.rms_norm(
4923                        &q,
4924                        fa.q_norm.float_data(),
4925                        &mut qn,
4926                        head_dim,
4927                        t * n_head,
4928                        eps,
4929                    )?;
4930                    q = qn;
4931                    let mut kn = e.uninit(t * n_head_kv * head_dim)?;
4932                    e.rms_norm(
4933                        &k,
4934                        fa.k_norm.float_data(),
4935                        &mut kn,
4936                        head_dim,
4937                        t * n_head_kv,
4938                        eps,
4939                    )?;
4940                    k = kn;
4941                    e.rope_neox(
4942                        &mut q, &pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
4943                    )?;
4944                    e.rope_neox(
4945                        &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
4946                    )?;
4947
4948                    // Per-row append + attend: row r sees rows 0..r in KV (causal within the
4949                    // draft), each through the b_n=1 serving kernels at its own t_kv.
4950                    let q_dim = n_head * head_dim;
4951                    let kv_dim = n_head_kv * head_dim;
4952                    let mut attn = e.uninit(t * q_dim)?;
4953                    let (kdk, kdv, ktb, vtb, kv_view) = {
4954                        let kvl = cache.kv[il].as_ref().unwrap();
4955                        let s = &e.gpu.stream();
4956                        let (pk, _g) = kvl.k.device_ptr(s);
4957                        let (pv, _g2) = kvl.v.device_ptr(s);
4958                        (
4959                            kvl.kv_dim_k,
4960                            kvl.kv_dim_v,
4961                            kvl.k_tok_bytes,
4962                            kvl.v_tok_bytes,
4963                            e.htod_u64(&[pk as u64, pv as u64])?,
4964                        )
4965                    };
4966                    if let Some((_, ctr)) = stream {
4967                        // STREAM ARM (2b): one batched dc append + the multi-row dc attention
4968                        // — the generic stream arm's exact shape (rows kernels are pinned
4969                        // byte-identical to the per-row programs by kernel-check). Host len
4970                        // stays a stale lower bound; the burst drain reconciles it.
4971                        let kvl = cache.kv[il].as_mut().unwrap();
4972                        e.append_kv_quantized_rows_dc(
4973                            &k,
4974                            &v,
4975                            &mut kvl.k,
4976                            &mut kvl.v,
4977                            ctr,
4978                            t,
4979                            kdk,
4980                            kdv,
4981                            ktb,
4982                            vtb,
4983                            Engine::kv_fp8_on(),
4984                        )?;
4985                        let upper = (kvl.len + t + 64).min(cache.max_ctx);
4986                        let k_view = e.view_u8(&kvl.k, upper * ktb);
4987                        let v_view = e.view_u8(&kvl.v, upper * vtb);
4988                        e.fa_decode_rows_dc(
4989                            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, ctr,
4990                            upper, t, scale, ktb, vtb, 0, false,
4991                        )?;
4992                    } else {
4993                        for r in 0..t {
4994                            // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
4995                            // whose row 0 is this row (arithmetic-free materialization copies,
4996                            // same as decode's per-seq fallback arm).
4997                            let mut k_row = e.uninit(kv_dim)?;
4998                            e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
4999                            let mut v_row = e.uninit(kv_dim)?;
5000                            e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
5001                            let pos_row = &pos_rows[r];
5002                            let kvl = cache.kv[il].as_mut().unwrap();
5003                            if seqs_append {
5004                                e.append_kv_quantized_seqs(
5005                                    &k_row,
5006                                    &v_row,
5007                                    &kv_view.slice(0..2),
5008                                    pos_row,
5009                                    1,
5010                                    kdk,
5011                                    kdv,
5012                                    ktb,
5013                                    vtb,
5014                                )?;
5015                                kvl.len += 1;
5016                            } else {
5017                                e.append_kv_quantized_view(
5018                                    &k_row.slice(0..kv_dim),
5019                                    &v_row.slice(0..kv_dim),
5020                                    &mut kvl.k,
5021                                    &mut kvl.v,
5022                                    kvl.len,
5023                                    kvl.kv_dim_k,
5024                                    kvl.kv_dim_v,
5025                                    kvl.k_tok_bytes,
5026                                    kvl.v_tok_bytes,
5027                                    Engine::kv_fp8_on(),
5028                                )?;
5029                                kvl.len += 1;
5030                            }
5031                            let t_kv = kvl.len;
5032                            let mut q_row = e.uninit(q_dim)?;
5033                            e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
5034                            let mut a_row = e.uninit(q_dim)?;
5035                            if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
5036                                let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
5037                                e.fa_decode_batch_seqs_v4(
5038                                    &q_row,
5039                                    &kv_view.slice(0..2),
5040                                    pos_row,
5041                                    &mut a_row,
5042                                    head_dim,
5043                                    n_head,
5044                                    n_head_kv,
5045                                    1,
5046                                    t_kv,
5047                                    scale,
5048                                    sp0_r,
5049                                    ktb,
5050                                    vtb,
5051                                )?;
5052                            } else {
5053                                let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
5054                                let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
5055                                let mut a_view = a_row.slice_mut(0..q_dim);
5056                                e.fa_decode_kvmod_view(
5057                                    &q_row.slice(0..q_dim),
5058                                    &k_view,
5059                                    &v_view,
5060                                    &mut a_view,
5061                                    head_dim,
5062                                    n_head,
5063                                    n_head_kv,
5064                                    t_kv,
5065                                    scale,
5066                                    kvl.k_tok_bytes,
5067                                    kvl.v_tok_bytes,
5068                                    Engine::kv_fp8_on(),
5069                                )?;
5070                            }
5071                            e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
5072                        }
5073                    }
5074
5075                    // Output gate (element-wise) + o-proj at m=T.
5076                    let attn_g = match &gate {
5077                        Some(g) => {
5078                            let n = t * q_dim;
5079                            let mut gsig = e.uninit(n)?;
5080                            e.sigmoid(g, &mut gsig, n)?;
5081                            let mut ag = e.uninit(n)?;
5082                            e.mul(&attn, &gsig, &mut ag, n)?;
5083                            ag
5084                        }
5085                        None => attn,
5086                    };
5087                    e.matmul(&fa.wo, &attn_g, t)?
5088                }
5089                // STREAM ARM (2b, lane/draftcost-moe): under a device position counter the
5090                // per-row serving-kernel chain cannot run (host state swaps keyed on host
5091                // row index are fine, but the stream COMMIT needs the GdnStash for its _dc
5092                // rebuild — the per-row chain only produces per-column clones). GDN rides
5093                // `linear_attn_verify_t`: batched q8_1-class projections, stash-producing,
5094                // and its one-scan recurrence is pinned bit-identical to T chained T=1
5095                // steps (its header + kernel-check). Position-independent, so no counter
5096                // plumbing is needed. Guards mirror the generic call site exactly.
5097                Mixer::Linear(la) if stream.is_some() => {
5098                    if !(t >= 3 || (t == 2 && spec_m2()))
5099                        || !self.mixer_in_q8_1_fast(e, &layer.mixer)
5100                        || !e.uses_q8_1_fast(&la.ssm_out)
5101                    {
5102                        return Err("qwen35 stream verify: GDN batched arm requires t>=3 \
5103                                    (or MEMRA_SPEC_M2 at t=2) and q8_1-fast projections"
5104                            .into());
5105                    }
5106                    let want = ckpt.is_some();
5107                    let (out, stash) = self.linear_attn_verify_t(
5108                        e,
5109                        la,
5110                        &xn,
5111                        Some((&hq, &hd)),
5112                        t,
5113                        cache,
5114                        il,
5115                        want,
5116                    )?;
5117                    if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
5118                        ck.gdn[il] = Some(st);
5119                    }
5120                    out
5121                }
5122                Mixer::Linear(_) => {
5123                    unreachable!("linear layers ride qwen35_tparallel_linear_layer")
5124                }
5125            };
5126
5127            // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
5128            let pnorm = layer.post_attn_norm.float_data();
5129            let mut x1 = e.uninit(t * n_embd)?;
5130            let mut zn = e.uninit(t * n_embd)?;
5131            e.add_rms_norm(&x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
5132            let ffn_out = match &layer.ffn {
5133                crate::hybrid::Ffn::Dense {
5134                    ffn_gate,
5135                    ffn_up,
5136                    ffn_down,
5137                } => {
5138                    assert!(
5139                        self.cfg.m3.is_none(),
5140                        "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
5141                    );
5142                    let n_ff = ffn_gate.out_features();
5143                    let (zq, zd) = e.quantize_q8_1(&zn, t, n_embd)?;
5144                    let g = e.matmul_pre(ffn_gate, &zq, &zd, &zn, t)?;
5145                    let u = e.matmul_pre(ffn_up, &zq, &zd, &zn, t)?;
5146                    let mut act = e.uninit(t * n_ff)?;
5147                    e.silu_mul(&g, &u, &mut act, t * n_ff)?;
5148                    let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
5149                    e.matmul_pre(ffn_down, &aq, &ad, &act, t)?
5150                }
5151                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
5152            };
5153            let mut x2 = e.uninit(t * n_embd)?;
5154            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
5155            // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
5156            self.dflash_tap(e, cache, il, &x2, t)?;
5157            x = x2;
5158            il += 1;
5159        }
5160        Ok(x)
5161    }
5162
5163    /// ONE t-parallel LINEAR layer (attn_norm + gdn mixer + post_attn_norm + FFN + tap) —
5164    /// the exact body the old in-loop Linear arm ran, extracted so the eager walk and the
5165    /// slice-3 captured segments execute the SAME code (a second copy is how dispatch
5166    /// mirrors drift — the verify_layers extraction lesson). Two deliberate changes, both
5167    /// bit-identical by construction:
5168    /// - the gdn ping-pong host swap moves from per-row to ONE end-of-body swap (t odd):
5169    ///   the device sequence is driven entirely by the 6-entry pointer table, which
5170    ///   already encodes both parities; the ckpt stash reads name row r's out buffer
5171    ///   directly (r even -> alt handle, odd -> canonical) — the same physical bytes the
5172    ///   legacy post-swap clone read.
5173    /// - `stash` (slice-3 ctx): persistent per-layer slabs written by copy_into instead of
5174    ///   per-row clone_dtod allocs — same bytes, capture-legal (no per-round host objects).
5175    /// `table_src` = (persistent pointer table, offset) when the ctx owns the tables;
5176    /// None builds the per-verify table exactly as before.
5177    #[allow(clippy::too_many_arguments)]
5178    fn qwen35_tparallel_linear_layer(
5179        &self,
5180        e: &Engine,
5181        il: usize,
5182        x: &CudaSlice<f32>,
5183        t: usize,
5184        cache: &mut Cache,
5185        mut ckpt: Option<&mut VerifyCkpt>,
5186        stash: Option<(&mut CudaSlice<f32>, &mut CudaSlice<f32>)>,
5187        table_src: Option<(&CudaSlice<u64>, usize)>,
5188    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5189        use cudarc::driver::DevicePtr;
5190        let cfg = &self.cfg;
5191        let n_embd = cfg.n_embd as usize;
5192        let eps = cfg.rms_eps;
5193        let layer = &self.layers[il];
5194        let Mixer::Linear(la) = &layer.mixer else {
5195            return Err("qwen35_tparallel_linear_layer on a non-linear layer".into());
5196        };
5197        // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
5198        let anorm = layer.attn_norm.float_data();
5199        let mut xn = e.uninit(t * n_embd)?;
5200        e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
5201        let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
5202
5203        let ssm = cfg.ssm.as_ref().expect("linear mixer requires ssm cfg");
5204        let d_state = ssm.state_size as usize;
5205        let num_k = ssm.group_count as usize;
5206        let num_v = ssm.time_step_rank as usize;
5207        let d_conv = ssm.conv_kernel as usize;
5208        let key_dim = d_state * num_k;
5209        let value_dim = d_state * num_v;
5210        let conv_dim = key_dim * 2 + value_dim;
5211        let gdn_scale = 1.0 / (d_state as f32).sqrt();
5212
5213        // ---- batched projections: one weight read for all T rows ----
5214        let qkv_mixed = e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?;
5215        let z = e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?;
5216        let beta_raw = e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?;
5217        let alpha = e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?;
5218        let beta_w = la.ssm_beta.out_features();
5219        let alpha_w = la.ssm_alpha.out_features();
5220        let qkv_w = la.wqkv.out_features();
5221
5222        // ---- per-row state chain through the b_n=1 serving kernels ----
5223        // 6-entry alternating pointer table expresses the ping-pong without a rebuild per
5224        // row: even rows scan s0 -> s1, odd rows s1 -> s0.
5225        let table_local: Option<CudaSlice<u64>> = match table_src {
5226            Some(_) => None,
5227            None => {
5228                let rl = cache.recur[il].as_ref().unwrap();
5229                let s = &e.gpu.stream();
5230                let (pc, _g0) = rl.conv_state.device_ptr(s);
5231                let (p0, _g1) = rl.ssm_state.device_ptr(s);
5232                let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
5233                Some(e.htod_u64(&[
5234                    pc as u64, p0 as u64, p1 as u64, pc as u64, p1 as u64, p0 as u64,
5235                ])?)
5236            }
5237        };
5238        let (table, toff): (&CudaSlice<u64>, usize) = match table_src {
5239            Some((tb, off)) => (tb, off),
5240            None => (table_local.as_ref().unwrap(), 0),
5241        };
5242        let mut o_all = e.uninit(t * value_dim)?;
5243        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
5244            if ckpt.is_some() && stash.is_none() && t >= 2 {
5245                Some(Vec::with_capacity(t - 1))
5246            } else {
5247                None
5248            };
5249        let mut stash = stash;
5250        // Per-row scratch reused across rows (uninit is cheap but not free at
5251        // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
5252        // [T, ...] buffers — zero arithmetic-free copies in this loop.
5253        let mut conv_out = e.uninit(conv_dim)?;
5254        let mut q_l2 = e.uninit(value_dim)?;
5255        let mut k_l2 = e.uninit(value_dim)?;
5256        let mut v_gd = e.uninit(value_dim)?;
5257        let mut beta_b = e.uninit(num_v)?;
5258        let mut g_log = e.uninit(num_v)?;
5259        for r in 0..t {
5260            let base = toff + if r % 2 == 0 { 0 } else { 3 };
5261            let conv_view = table.slice(base..base + 1);
5262            let in_view = table.slice(base + 1..base + 2);
5263            let out_view = table.slice(base + 2..base + 3);
5264            e.ssm_conv1d_fused_decode_b_view(
5265                &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
5266                &conv_view,
5267                la.ssm_conv1d.float_data(),
5268                &mut conv_out,
5269                conv_dim,
5270                d_conv,
5271                1,
5272            )?;
5273            e.gdn_prep_decode_b_view(
5274                &conv_out,
5275                &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
5276                &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
5277                la.ssm_dt.float_data(),
5278                la.ssm_a.float_data(),
5279                &mut q_l2,
5280                &mut k_l2,
5281                &mut v_gd,
5282                &mut beta_b,
5283                &mut g_log,
5284                d_state,
5285                num_v,
5286                num_k,
5287                key_dim,
5288                eps,
5289                conv_dim,
5290                1,
5291            )?;
5292            let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
5293            e.gdn_scan_s128_batched_view(
5294                &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row, num_v, 1,
5295                gdn_scale,
5296            )?;
5297            if r + 1 < t {
5298                // Row r's out buffer: even rows write s1 (the alt handle — no swaps ran),
5299                // odd rows write s0 — the same physical state the legacy post-swap
5300                // canonical clone read.
5301                let rl = cache.recur[il]
5302                    .as_ref()
5303                    .ok_or("qwen35 linear verify layer has no recurrent state")?;
5304                let ssm_src = if r % 2 == 0 {
5305                    &rl.ssm_state_alt
5306                } else {
5307                    &rl.ssm_state
5308                };
5309                match stash.as_mut() {
5310                    Some((conv_slab, ssm_slab)) => {
5311                        // BOTH stash reads go through the pointer table at run time: the
5312                        // ssm handles ping-pong between rounds, and the ctx (with its
5313                        // captured graphs) outlives the Cache — a fresh generation's
5314                        // conv/ssm buffers land at new addresses that only the per-round
5315                        // table refresh knows. A baked direct copy would read freed
5316                        // memory (parity was the slice-3 smoke divergence; cache
5317                        // lifetime is the cross-generation twin).
5318                        e.copy_indirect_src_f32(
5319                            &conv_view,
5320                            conv_slab,
5321                            r * conv_dim * (d_conv - 1),
5322                            conv_dim * (d_conv - 1),
5323                        )?;
5324                        // The ssm handles PING-PONG between rounds: a captured direct
5325                        // copy would bake the capture-time physical buffer and read the
5326                        // wrong parity after any odd-vt round (the slice-3 smoke
5327                        // divergence). Read the src address from row r's OUT table
5328                        // entry at run time — the same entry the scan just wrote.
5329                        e.copy_indirect_src_f32(
5330                            &out_view,
5331                            ssm_slab,
5332                            r * d_state * d_state * num_v,
5333                            d_state * d_state * num_v,
5334                        )?;
5335                    }
5336                    None => {
5337                        if let Some(states) = col_states.as_mut() {
5338                            states.push((e.clone_dtod(&rl.conv_state)?, e.clone_dtod(ssm_src)?));
5339                        }
5340                    }
5341                }
5342            }
5343        }
5344        // ONE end-of-body parity swap (t odd) — the legacy loop swapped per row; the net
5345        // handle motion is identical and the device sequence never read the handles.
5346        if t % 2 == 1 {
5347            let rl = cache.recur[il].as_mut().unwrap();
5348            std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
5349        }
5350        if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
5351            checkpoint.cols[il] = Some(states);
5352        }
5353
5354        // ---- batched gated norm + out-projection at m=T ----
5355        let mixed = if e.uses_q8_1_fast(&la.ssm_out) {
5356            let (gq, gd) = e.gated_rmsnorm_q8_1(
5357                &o_all,
5358                la.ssm_norm.float_data(),
5359                &z,
5360                d_state,
5361                t * num_v,
5362                eps,
5363            )?;
5364            let g0 = e.zeros(0)?;
5365            e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
5366        } else {
5367            let mut gn = e.uninit(t * value_dim)?;
5368            e.gated_rmsnorm(
5369                &o_all,
5370                la.ssm_norm.float_data(),
5371                &z,
5372                &mut gn,
5373                d_state,
5374                t * num_v,
5375                eps,
5376            )?;
5377            e.matmul(&la.ssm_out, &gn, t)?
5378        };
5379
5380        // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
5381        let pnorm = layer.post_attn_norm.float_data();
5382        let mut x1 = e.uninit(t * n_embd)?;
5383        let mut zn = e.uninit(t * n_embd)?;
5384        e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
5385        let ffn_out = match &layer.ffn {
5386            crate::hybrid::Ffn::Dense {
5387                ffn_gate,
5388                ffn_up,
5389                ffn_down,
5390            } => {
5391                assert!(
5392                    self.cfg.m3.is_none(),
5393                    "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
5394                );
5395                let n_ff = ffn_gate.out_features();
5396                let (zq, zd) = e.quantize_q8_1(&zn, t, n_embd)?;
5397                let g = e.matmul_pre(ffn_gate, &zq, &zd, &zn, t)?;
5398                let u = e.matmul_pre(ffn_up, &zq, &zd, &zn, t)?;
5399                let mut act = e.uninit(t * n_ff)?;
5400                e.silu_mul(&g, &u, &mut act, t * n_ff)?;
5401                let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
5402                e.matmul_pre(ffn_down, &aq, &ad, &act, t)?
5403            }
5404            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
5405        };
5406        let mut x2 = e.uninit(t * n_embd)?;
5407        e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
5408        // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
5409        self.dflash_tap(e, cache, il, &x2, t)?;
5410        Ok(x2)
5411    }
5412
5413    /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
5414    /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
5415    /// carried in from outside the range) and exits with the range's final residual materialized
5416    /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
5417    /// instead of one.
5418    ///
5419    /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
5420    /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
5421    /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
5422    /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
5423    /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
5424    /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
5425    /// code — there is no "split version" of the verify math.
5426    ///
5427    /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
5428    /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
5429    /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
5430    /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
5431    #[allow(clippy::too_many_arguments)]
5432    fn verify_layers(
5433        &self,
5434        e: &Engine,
5435        mut x: CudaSlice<f32>,
5436        lo: usize,
5437        hi: usize,
5438        pos_d: &CudaSlice<i32>,
5439        pos0: usize,
5440        t: usize,
5441        cache: &mut Cache,
5442        mut ckpt: Option<&mut VerifyCkpt>,
5443        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5444        graphs: Option<&mut DsparkVerifyGraphs>,
5445    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5446        if self.cfg.step35.is_some() {
5447            if stream.is_some() {
5448                return Err(
5449                    "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
5450                            cannot express the SWA offset KV view)"
5451                        .into(),
5452                );
5453            }
5454            return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
5455        }
5456        if self.qwen35_serving_class() {
5457            return self.qwen35_verify_batch_layers(
5458                e,
5459                x,
5460                lo,
5461                hi,
5462                pos0,
5463                t,
5464                cache,
5465                ckpt.take(),
5466                stream,
5467                graphs,
5468            );
5469        }
5470        let n_embd = self.cfg.n_embd as usize;
5471        let eps = self.cfg.rms_eps;
5472        // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
5473        // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
5474        // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
5475        // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
5476        // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
5477        // residual the next layer needs) as its `res` output. Falls back to the separate add
5478        // when the next layer is off the fused-q8 path.
5479        let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
5480        for il in lo..hi {
5481            let layer = &self.layers[il];
5482            // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
5483            // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
5484            // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
5485            // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
5486            // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
5487            // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
5488            // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
5489            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
5490            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
5491            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
5492            // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
5493            // projections only; Linear mixer: the batched arm — the per-column fallback needs
5494            // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
5495            // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
5496            // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
5497            // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
5498            // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
5499            // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
5500            // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
5501            // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
5502            let lin_q8_only = match &layer.mixer {
5503                Mixer::Linear(la) => {
5504                    (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
5505                }
5506                Mixer::Full(_) if self.cfg.step35.is_some() => false,
5507                _ => true,
5508            };
5509            // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
5510            // a non-fused layer still performs the residual add.
5511            let taken = pending.take();
5512            let (h, h_q8) = if norm_fused && lin_q8_only {
5513                let pair = match taken {
5514                    // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
5515                    // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
5516                    Some((x1p, f1p)) => {
5517                        let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
5518                        let p = e.add_rms_norm_q8_1(
5519                            &x1p,
5520                            &f1p,
5521                            layer.attn_norm.float_data(),
5522                            &mut x2,
5523                            n_embd,
5524                            t,
5525                            eps,
5526                        )?;
5527                        x = x2;
5528                        p
5529                    }
5530                    None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
5531                };
5532                (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
5533            } else {
5534                if let Some((x1p, f1p)) = taken {
5535                    let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
5536                    e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
5537                    x = x2;
5538                }
5539                let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
5540                if norm_fused {
5541                    e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5542                } else {
5543                    e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5544                }
5545                (h, None)
5546            };
5547            let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
5548
5549            let mixed = match &layer.mixer {
5550                Mixer::Full(fa) => self.full_attn_verify(
5551                    e,
5552                    fa,
5553                    &h,
5554                    h_q8_ref,
5555                    pos_d,
5556                    t,
5557                    cache,
5558                    il,
5559                    stream.map(|(_, c)| c),
5560                )?,
5561                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
5562                Mixer::Linear(la) => {
5563                    // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
5564                    // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
5565                    // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
5566                    // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
5567                    // chained T=1 steps (bit-identical). Falls back to the sequential per-column
5568                    // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
5569                    // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
5570                    // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
5571                    // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
5572                    // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
5573                    // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
5574                    if (t >= 3 || (t == 2 && spec_m2()))
5575                        && mixer_fast
5576                        && e.uses_q8_1_fast(&la.ssm_out)
5577                    {
5578                        let want = ckpt.is_some();
5579                        let (out, stash) =
5580                            self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
5581                        if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
5582                            ck.gdn[il] = Some(st);
5583                        }
5584                        out
5585                    } else {
5586                        let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
5587                        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
5588                            if ckpt.is_some() && t >= 2 {
5589                                Some(Vec::with_capacity(t - 1))
5590                            } else {
5591                                None
5592                            };
5593                        for col in 0..t {
5594                            let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
5595                            let src = h.slice(col * n_embd..(col + 1) * n_embd);
5596                            e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
5597                            let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
5598                            e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
5599                            // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
5600                            // (pure dtod — cannot change any computed value). Last column skipped:
5601                            // rebuild targets are j <= t-1 columns.
5602                            if let Some(cs) = col_states.as_mut() {
5603                                if col + 1 < t {
5604                                    let rl = cache.recur[il].as_ref().unwrap();
5605                                    cs.push((
5606                                        e.clone_dtod(&rl.conv_state)?,
5607                                        e.clone_dtod(&rl.ssm_state)?,
5608                                    ));
5609                                }
5610                            }
5611                        }
5612                        if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
5613                            // ReplaySSM-assessment instrumentation (2026-07-30): the
5614                            // per-column clones are the only true state snapshots left in
5615                            // the verify (the batched path stashes INPUTS and replays).
5616                            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
5617                                static ONCE: std::sync::Once = std::sync::Once::new();
5618                                let bytes: usize =
5619                                    cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
5620                                ONCE.call_once(|| eprintln!(
5621                                    "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
5622                                    cs.len(), bytes as f64 / 1e6));
5623                            }
5624                            ck.cols[il] = Some(cs);
5625                        }
5626                        out
5627                    }
5628                }
5629            };
5630
5631            // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
5632            // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
5633            // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
5634            let ffn_fuse = match &layer.ffn {
5635                crate::hybrid::Ffn::Dense {
5636                    ffn_gate, ffn_up, ..
5637                } => {
5638                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
5639                        && e.uses_q8_1_fast(ffn_gate)
5640                        && e.uses_q8_1_fast(ffn_up)
5641                }
5642                crate::hybrid::Ffn::Moe(_) => false,
5643            };
5644            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
5645            // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
5646            // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
5647            // per-row m=1 program; kernel-check pins bit-identity vs the unfused
5648            // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
5649            // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
5650            // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
5651            // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
5652            // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
5653            // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
5654            // mirror decode's dispatch or spec self-consistency fails.
5655            let dense_lim = self.cfg.clamp_shexp_at(il as u32);
5656            let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
5657            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
5658            let mut z = e.zeros(0)?; // replaced below on the unfused arms
5659            let z_q8 = if fuse_q8 {
5660                Some(e.add_rms_norm_q8_1(
5661                    &x,
5662                    &mixed,
5663                    layer.post_attn_norm.float_data(),
5664                    &mut x1,
5665                    n_embd,
5666                    t,
5667                    eps,
5668                )?)
5669            } else {
5670                let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
5671                if ffn_fuse {
5672                    e.add(&x, &mixed, &mut x1, t * n_embd)?;
5673                    e.rms_norm_decode(
5674                        &x1,
5675                        layer.post_attn_norm.float_data(),
5676                        &mut zf,
5677                        n_embd,
5678                        t,
5679                        eps,
5680                    )?;
5681                } else {
5682                    e.add_rms_norm(
5683                        &x,
5684                        &mixed,
5685                        layer.post_attn_norm.float_data(),
5686                        &mut x1,
5687                        &mut zf,
5688                        n_embd,
5689                        t,
5690                        eps,
5691                    )?;
5692                }
5693                z = zf;
5694                None
5695            };
5696            // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
5697            // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
5698            // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
5699            let ffn_out = match &layer.ffn {
5700                crate::hybrid::Ffn::Dense {
5701                    ffn_gate,
5702                    ffn_up,
5703                    ffn_down,
5704                } => {
5705                    let n_ff = ffn_gate.out_features();
5706                    if let Some((zq, zd)) = z_q8.as_ref() {
5707                        // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
5708                        // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
5709                        // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
5710                        // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
5711                        // scale_inplace store, value-exact) — the exact m=1 decode epilogue
5712                        // structure at nrows=t.
5713                        let pair =
5714                            match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
5715                                Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
5716                                None => None,
5717                            };
5718                        let (gate, gs, up, us) = match pair {
5719                            Some(x4) => x4,
5720                            None => (
5721                                e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
5722                                1.0, // scale already applied inside _pre
5723                                e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
5724                                1.0,
5725                            ),
5726                        };
5727                        if e.uses_q8_1_fast(ffn_down) {
5728                            let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
5729                            e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
5730                        } else {
5731                            let mut act = vbuf(e, t * n_ff)?;
5732                            e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
5733                            e.matmul_decode_exact(ffn_down, &act, t)?
5734                        }
5735                    } else {
5736                        // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
5737                        // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
5738                        // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
5739                        // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
5740                        // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
5741                        let (gate, up) =
5742                            match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
5743                                Some(pair) => pair,
5744                                None => (
5745                                    e.matmul_decode_exact(ffn_gate, &z, t)?,
5746                                    e.matmul_decode_exact(ffn_up, &z, t)?,
5747                                ),
5748                            };
5749                        let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
5750                        Self::ffn_act_lim(
5751                            e,
5752                            &self.cfg,
5753                            &gate,
5754                            &up,
5755                            1.0,
5756                            1.0,
5757                            dense_lim,
5758                            &mut act,
5759                            t * n_ff,
5760                        )?;
5761                        e.matmul_decode_exact(ffn_down, &act, t)?
5762                    }
5763                }
5764                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
5765            };
5766            // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
5767            // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
5768            // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
5769            pending = Some((x1, ffn_out));
5770        }
5771        // RANGE's final add (no next norm INSIDE the range to fuse with; for the
5772        // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
5773        if let Some((x1p, f1p)) = pending.take() {
5774            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
5775            e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
5776            x = x2;
5777        }
5778        Ok(x)
5779    }
5780    /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
5781    /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
5782    /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
5783    /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
5784    /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
5785    /// ssm state exactly like T sequential decode steps.
5786    /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
5787    /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
5788    #[allow(clippy::too_many_arguments)]
5789    fn linear_attn_verify_t(
5790        &self,
5791        e: &Engine,
5792        la: &LinearAttnLayer,
5793        h: &CudaSlice<f32>,
5794        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
5795        t: usize,
5796        cache: &mut Cache,
5797        il: usize,
5798        want_stash: bool,
5799    ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
5800        let cfg = &self.cfg;
5801        let ssm = cfg.ssm.as_ref().unwrap();
5802        let d_state = ssm.state_size as usize;
5803        let num_k = ssm.group_count as usize;
5804        let num_v = ssm.time_step_rank as usize;
5805        let d_conv = ssm.conv_kernel as usize;
5806        let key_dim = d_state * num_k;
5807        let conv_dim = key_dim * 2 + d_state * num_v;
5808        let eps = cfg.rms_eps;
5809        let scale = 1.0 / (d_state as f32).sqrt();
5810
5811        // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
5812        // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
5813        // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
5814        // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
5815        // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
5816        // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
5817        // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
5818        // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
5819        // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
5820        // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
5821        // Bit-identical per (tensor,token,row) — see spec_fused_t().
5822        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
5823        // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
5824        // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
5825        // and feeds every projection; the caller guaranteed all four input projections are
5826        // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
5827        let h_q8_t = if h_q8.is_none()
5828            && spec_fused_t()
5829            && (2..=4).contains(&t)
5830            && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
5831                || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
5832        {
5833            Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
5834        } else {
5835            None
5836        };
5837        // one view: the caller's fused-norm q8 or this fn's own shared quantize.
5838        let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
5839            h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
5840        let (qkv_mixed, z) = {
5841            let mut fused = None;
5842            if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
5843                let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
5844                fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
5845            } else if let Some((hq, hd)) = hq8_any {
5846                if spec_fused_t() && (2..=4).contains(&t) {
5847                    fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
5848                }
5849            }
5850            match (fused, hq8_any) {
5851                (Some(pair), _) => pair,
5852                (None, Some((hq, hd))) if h_q8.is_some() => (
5853                    e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
5854                    e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
5855                ),
5856                (None, _) => (
5857                    e.matmul_decode_exact(&la.wqkv, h, t)?,
5858                    e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
5859                ),
5860            }
5861        };
5862        // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
5863        // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
5864        // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
5865        // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
5866        let (beta_raw, alpha) = if t == 1 {
5867            let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
5868            match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
5869                Some(((mut b, bs), (mut a, as_))) => {
5870                    if bs != 1.0 {
5871                        e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
5872                    }
5873                    if as_ != 1.0 {
5874                        e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
5875                    }
5876                    (b, a)
5877                }
5878                // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
5879                // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
5880                // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
5881                None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
5882                    Some((b, a)) => (b, a),
5883                    None => (
5884                        e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
5885                        e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
5886                    ),
5887                },
5888            }
5889        } else {
5890            // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
5891            // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
5892            let mut nvfp4_fused = None;
5893            let mut q8_fused = None;
5894            if let Some((hq, hd)) = hq8_any {
5895                if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
5896                    nvfp4_fused =
5897                        e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
5898                    if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
5899                        static ONCE: std::sync::Once = std::sync::Once::new();
5900                        ONCE.call_once(|| {
5901                            eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
5902                        });
5903                    }
5904                }
5905                if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
5906                    q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
5907                }
5908            }
5909            if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
5910                if bs != 1.0 {
5911                    e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
5912                }
5913                if as_ != 1.0 {
5914                    e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
5915                }
5916                (b, a)
5917            } else if let Some(pair) = q8_fused {
5918                pair
5919            } else {
5920                match hq8_any {
5921                    Some((hq, hd)) if h_q8.is_some() => (
5922                        e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
5923                        e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
5924                    ),
5925                    _ => (
5926                        e.matmul_decode_exact(&la.ssm_beta, h, t)?,
5927                        e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
5928                    ),
5929                }
5930            }
5931        };
5932
5933        // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
5934        // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
5935        let rl = cache.recur[il].as_mut().unwrap();
5936        let mut conv_out = e.uninit(conv_dim * t)?;
5937        e.ssm_conv1d_tm_state(
5938            &qkv_mixed,
5939            &mut rl.conv_state,
5940            la.ssm_conv1d.float_data(),
5941            &mut conv_out,
5942            conv_dim,
5943            t,
5944            d_conv,
5945        )?;
5946
5947        // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
5948        let mut q_g = e.uninit(d_state * num_v * t)?;
5949        let mut k_g = e.uninit(d_state * num_v * t)?;
5950        let mut v_g = e.uninit(d_state * num_v * t)?;
5951        e.qkv_to_gdn_repack(
5952            &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
5953        )?;
5954        let mut q_l2 = e.uninit(d_state * num_v * t)?;
5955        e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
5956        let mut k_l2 = e.uninit(d_state * num_v * t)?;
5957        e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
5958        let mut beta = e.uninit(t * num_v)?;
5959        e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
5960        let mut g_log = e.uninit(t * num_v)?;
5961        e.gdn_glog(
5962            &alpha,
5963            la.ssm_dt.float_data(),
5964            la.ssm_a.float_data(),
5965            &mut g_log,
5966            num_v,
5967            t,
5968        )?;
5969
5970        // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
5971        // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
5972        let mut o = e.uninit(d_state * num_v * t)?;
5973        {
5974            let crate::cache::RecurLayer {
5975                ssm_state,
5976                ssm_state_alt,
5977                ..
5978            } = rl;
5979            e.gdn_scan_s128(
5980                &q_l2,
5981                &k_l2,
5982                &v_g,
5983                &g_log,
5984                &beta,
5985                ssm_state,
5986                ssm_state_alt,
5987                &mut o,
5988                num_v,
5989                t,
5990                scale,
5991            )?;
5992        }
5993        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
5994
5995        // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
5996        // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
5997        // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
5998        // T-wide launch is the per-row program; kernel-check pins bit-identity vs
5999        // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
6000        // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
6001        let out = if e.uses_q8_1_fast(&la.ssm_out) {
6002            let (gq, gd) =
6003                e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
6004            e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
6005        } else {
6006            let mut gn = e.uninit(d_state * num_v * t)?;
6007            e.gated_rmsnorm(
6008                &o,
6009                la.ssm_norm.float_data(),
6010                &z,
6011                &mut gn,
6012                d_state,
6013                num_v * t,
6014                eps,
6015            )?;
6016            // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
6017            // would fall to dp4a with a different FP reduction order — same class of bug as
6018            // the input projs).
6019            e.matmul_decode_exact(&la.ssm_out, &gn, t)?
6020        };
6021        let stash = if want_stash {
6022            Some(GdnStash {
6023                qkv_mixed,
6024                q_l2,
6025                k_l2,
6026                v_g,
6027                g_log,
6028                beta,
6029            })
6030        } else {
6031            None
6032        };
6033        Ok((out, stash))
6034    }
6035
6036    /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
6037    /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
6038    /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
6039    ///   are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
6040    ///   verify-probe gates), so keeping them == replaying them.
6041    /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
6042    ///   columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
6043    ///   snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
6044    ///   registers and writes it once at the end, so iterations 0..j-1 are independent of T:
6045    ///   bit-identical to the verify's own state after j tokens == the eager chain state.
6046    /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
6047    /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
6048    fn commit_verified_prefix(
6049        &self,
6050        e: &Engine,
6051        cache: &mut Cache,
6052        snap: &crate::cache::CacheSnapshot,
6053        ckpt: &VerifyCkpt,
6054        j: usize,
6055        kv_lens_done: bool,
6056        dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
6057    ) -> Result<(), Box<dyn std::error::Error>> {
6058        let cfg = &self.cfg;
6059        let ssm = cfg.ssm.as_ref().unwrap();
6060        let d_state = ssm.state_size as usize;
6061        let num_k = ssm.group_count as usize;
6062        let num_v = ssm.time_step_rank as usize;
6063        let d_conv = ssm.conv_kernel as usize;
6064        let conv_dim = d_state * num_k * 2 + d_state * num_v;
6065        let scale = 1.0 / (d_state as f32).sqrt();
6066        // Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1): the per-column-arm restores
6067        // are 2 tiny D2D copies per linear layer (~96 dispatches/partial round on the q38
6068        // route). When every cols-arm layer shares uniform state sizes (single ssm cfg —
6069        // always true today), batch them into two `copy_batch_uniform_f32` launches. Bytes,
6070        // buffers and stream order are identical to the per-layer memcpy sequence; the
6071        // kernel-rebuild (gdn-stash) arm below is untouched. MEMRA_STATE_COPY_BATCH=0 reverts.
6072        let mut batched_cols = false;
6073        if state_copy_batch_on() && dev_j.is_none() {
6074            use cudarc::driver::DevicePtr;
6075            let s = &e.gpu.stream();
6076            let mut conv_pairs: Vec<(u64, u64)> = Vec::new();
6077            let mut ssm_pairs: Vec<(u64, u64)> = Vec::new();
6078            let (mut conv_words, mut ssm_words) = (0usize, 0usize);
6079            let mut uniform = true;
6080            for il in 0..self.layers.len() {
6081                let Some(rl) = cache.recur[il].as_ref() else {
6082                    continue;
6083                };
6084                if ckpt.gdn[il].is_some() {
6085                    continue; // kernel-rebuild arm restores below, per layer
6086                }
6087                let Some(cols) = &ckpt.cols[il] else {
6088                    continue; // missing-ckpt error surfaces in the main loop
6089                };
6090                let (c, st) = &cols[j - 1];
6091                if conv_pairs.is_empty() {
6092                    conv_words = c.len();
6093                    ssm_words = st.len();
6094                } else if c.len() != conv_words || st.len() != ssm_words {
6095                    uniform = false;
6096                    break;
6097                }
6098                let (pc, _g0) = c.device_ptr(s);
6099                let (dc, _g1) = rl.conv_state.device_ptr(s);
6100                let (ps, _g2) = st.device_ptr(s);
6101                let (ds, _g3) = rl.ssm_state.device_ptr(s);
6102                conv_pairs.push((pc as u64, dc as u64));
6103                ssm_pairs.push((ps as u64, ds as u64));
6104            }
6105            if uniform && !conv_pairs.is_empty() {
6106                let n = conv_pairs.len();
6107                let mut t = vec![0u64; 2 * n];
6108                for (k, &(src, dst)) in conv_pairs.iter().enumerate() {
6109                    t[k] = src;
6110                    t[n + k] = dst;
6111                }
6112                let conv_t = e.htod_u64(&t)?;
6113                for (k, &(src, dst)) in ssm_pairs.iter().enumerate() {
6114                    t[k] = src;
6115                    t[n + k] = dst;
6116                }
6117                let ssm_t = e.htod_u64(&t)?;
6118                e.copy_batch_uniform_f32(&conv_t, n, conv_words)?;
6119                e.copy_batch_uniform_f32(&ssm_t, n, ssm_words)?;
6120                batched_cols = true;
6121            }
6122        }
6123        for il in 0..self.layers.len() {
6124            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
6125                kvl.len = saved + j;
6126                // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
6127                if !kv_lens_done {
6128                    e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
6129                }
6130            }
6131            if let Some(rl) = cache.recur[il].as_mut() {
6132                if let Some(st) = &ckpt.gdn[il] {
6133                    let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
6134                    let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
6135                    if let Some((acc, base, t_v)) = dev_j {
6136                        // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
6137                        e.ssm_conv_ring_rebuild_dc(
6138                            &st.qkv_mixed,
6139                            ring_old,
6140                            &mut rl.conv_state,
6141                            conv_dim,
6142                            acc,
6143                            base,
6144                            t_v,
6145                            d_conv,
6146                        )?;
6147                        let mut o = e.uninit(d_state * num_v * j.max(1))?;
6148                        e.gdn_scan_s128_dc(
6149                            &st.q_l2,
6150                            &st.k_l2,
6151                            &st.v_g,
6152                            &st.g_log,
6153                            &st.beta,
6154                            state_in,
6155                            &mut rl.ssm_state,
6156                            &mut o,
6157                            num_v,
6158                            acc,
6159                            base,
6160                            t_v,
6161                            scale,
6162                        )?;
6163                    } else {
6164                        e.ssm_conv_ring_rebuild(
6165                            &st.qkv_mixed,
6166                            ring_old,
6167                            &mut rl.conv_state,
6168                            conv_dim,
6169                            j,
6170                            d_conv,
6171                        )?;
6172                        let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
6173                        e.gdn_scan_s128(
6174                            &st.q_l2,
6175                            &st.k_l2,
6176                            &st.v_g,
6177                            &st.g_log,
6178                            &st.beta,
6179                            state_in,
6180                            &mut rl.ssm_state,
6181                            &mut o,
6182                            num_v,
6183                            j,
6184                            scale,
6185                        )?;
6186                    }
6187                } else if let Some(cols) = &ckpt.cols[il] {
6188                    if !batched_cols {
6189                        let (c, s) = &cols[j - 1];
6190                        e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
6191                        e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
6192                    }
6193                } else {
6194                    return Err(
6195                        "commit_verified_prefix: verify ckpt missing for linear layer".into(),
6196                    );
6197                }
6198            }
6199        }
6200        cache.pos = snap.pos + j;
6201        Ok(())
6202    }
6203
6204    /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
6205    /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
6206    fn commit_verified_prefix_stream(
6207        &self,
6208        e: &Engine,
6209        cache: &mut Cache,
6210        snap: &crate::cache::CacheSnapshot,
6211        ckpt: &VerifyCkpt,
6212        acc: &CudaSlice<u32>,
6213        base: usize,
6214        t_v: usize,
6215    ) -> Result<(), Box<dyn std::error::Error>> {
6216        let cfg = &self.cfg;
6217        let ssm = cfg.ssm.as_ref().unwrap();
6218        let d_state = ssm.state_size as usize;
6219        let num_k = ssm.group_count as usize;
6220        let num_v = ssm.time_step_rank as usize;
6221        let d_conv = ssm.conv_kernel as usize;
6222        let conv_dim = d_state * num_k * 2 + d_state * num_v;
6223        let scale = 1.0 / (d_state as f32).sqrt();
6224        for il in 0..self.layers.len() {
6225            if let Some(rl) = cache.recur[il].as_mut() {
6226                let st = ckpt.gdn[il]
6227                    .as_ref()
6228                    .ok_or("stream restore: batched-linear stash missing")?;
6229                let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
6230                let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
6231                e.ssm_conv_ring_rebuild_dc(
6232                    &st.qkv_mixed,
6233                    ring_old,
6234                    &mut rl.conv_state,
6235                    conv_dim,
6236                    acc,
6237                    base,
6238                    t_v,
6239                    d_conv,
6240                )?;
6241                let mut o = e.uninit(d_state * num_v * t_v)?;
6242                e.gdn_scan_s128_dc(
6243                    &st.q_l2,
6244                    &st.k_l2,
6245                    &st.v_g,
6246                    &st.g_log,
6247                    &st.beta,
6248                    state_in,
6249                    &mut rl.ssm_state,
6250                    &mut o,
6251                    num_v,
6252                    acc,
6253                    base,
6254                    t_v,
6255                    scale,
6256                )?;
6257            }
6258        }
6259        Ok(())
6260    }
6261
6262    /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
6263    /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
6264    /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
6265    /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
6266    /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
6267    pub fn decode_step_t_aux2(
6268        &self,
6269        e: &Engine,
6270        tokens: &[u32],
6271        pos0: usize,
6272        cache: &mut Cache,
6273        aux_layers: &[usize],
6274        pred_col: Option<usize>,
6275    ) -> Result<
6276        (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
6277        Box<dyn std::error::Error>,
6278    > {
6279        let cfg = &self.cfg;
6280        let n_embd = cfg.n_embd as usize;
6281        let eps = cfg.rms_eps;
6282        let t = tokens.len();
6283        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6284        let pos_d = e.htod_i32(&pos_vec)?;
6285        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
6286        let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
6287        let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
6288        let want_pred = pred_col.is_some();
6289
6290        for (il, layer) in self.layers.iter().enumerate() {
6291            // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
6292            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
6293            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
6294            let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
6295            if norm_fused {
6296                e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
6297            } else {
6298                e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
6299            }
6300            let mixed = match &layer.mixer {
6301                Mixer::Full(fa) => {
6302                    self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
6303                }
6304                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
6305                Mixer::Linear(la) => {
6306                    let mut out = e.zeros(t * n_embd)?;
6307                    for col in 0..t {
6308                        let mut h_col = e.zeros(n_embd)?;
6309                        let src = h.slice(col * n_embd..(col + 1) * n_embd);
6310                        e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
6311                        let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
6312                        e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
6313                    }
6314                    out
6315                }
6316            };
6317            let ffn_fuse = match &layer.ffn {
6318                crate::hybrid::Ffn::Dense {
6319                    ffn_gate, ffn_up, ..
6320                } => {
6321                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
6322                        && e.uses_q8_1_fast(ffn_gate)
6323                        && e.uses_q8_1_fast(ffn_up)
6324                }
6325                crate::hybrid::Ffn::Moe(_) => false,
6326            };
6327            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
6328            let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
6329            if ffn_fuse {
6330                e.add(&x, &mixed, &mut x1, t * n_embd)?;
6331                e.rms_norm_decode(
6332                    &x1,
6333                    layer.post_attn_norm.float_data(),
6334                    &mut z,
6335                    n_embd,
6336                    t,
6337                    eps,
6338                )?;
6339            } else {
6340                e.add_rms_norm(
6341                    &x,
6342                    &mixed,
6343                    layer.post_attn_norm.float_data(),
6344                    &mut x1,
6345                    &mut z,
6346                    n_embd,
6347                    t,
6348                    eps,
6349                )?;
6350            }
6351            let ffn_out = match &layer.ffn {
6352                crate::hybrid::Ffn::Dense {
6353                    ffn_gate,
6354                    ffn_up,
6355                    ffn_down,
6356                } => {
6357                    let n_ff = ffn_gate.out_features();
6358                    let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
6359                    let up = e.matmul_decode_exact(ffn_up, &z, t)?;
6360                    let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
6361                    // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
6362                    Self::ffn_act_lim(
6363                        e,
6364                        &self.cfg,
6365                        &gate,
6366                        &up,
6367                        1.0,
6368                        1.0,
6369                        self.cfg.clamp_shexp_at(il as u32),
6370                        &mut act,
6371                        t * n_ff,
6372                    )?;
6373                    e.matmul_decode_exact(ffn_down, &act, t)?
6374                }
6375                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
6376            };
6377            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
6378            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
6379            if aux_layers.contains(&il) {
6380                let mut a = e.zeros(n_embd)?;
6381                e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
6382                aux_last.push(a);
6383                if let Some(pc) = pred_col {
6384                    let mut ap = e.zeros(n_embd)?;
6385                    e.copy_view_into(
6386                        &mut ap,
6387                        0,
6388                        &x2.slice(pc * n_embd..(pc + 1) * n_embd),
6389                        n_embd,
6390                    )?;
6391                    aux_pred.push(ap);
6392                }
6393            }
6394            x = x2;
6395        }
6396        let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
6397        e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6398        let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
6399        let host = e.dtoh(&logits)?;
6400        cache.pos += t;
6401        Ok((
6402            host,
6403            aux_last,
6404            if want_pred { Some(aux_pred) } else { None },
6405        ))
6406    }
6407
6408    /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
6409    /// `step35_decode_attn`.
6410    ///
6411    /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
6412    /// the eager decode would have computed for the same tokens; that is what makes greedy spec
6413    /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
6414    /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
6415    /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
6416    /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
6417    /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
6418    /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
6419    /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
6420    /// position of each query row. A batched twin would have to reproduce all of that AND the
6421    /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
6422    /// take one `base_len`, not a per-row offset).
6423    ///
6424    /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
6425    /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
6426    /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
6427    /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
6428    /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
6429    /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
6430    /// step35 twin is a perf lane's job and must be gated against this arm.
6431    ///
6432    /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
6433    /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
6434    /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
6435    /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
6436    /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
6437    #[allow(clippy::too_many_arguments)]
6438    fn step35_verify(
6439        &self,
6440        e: &Engine,
6441        fa: &FullAttnLayer,
6442        h: &CudaSlice<f32>,
6443        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
6444        t: usize,
6445        cache: &mut Cache,
6446        il: usize,
6447    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6448        let n_embd = self.cfg.n_embd as usize;
6449        // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
6450        // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
6451        // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
6452        // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
6453        // cannot regress it into silently reading an empty buffer.
6454        assert_eq!(
6455            h.len(),
6456            t * n_embd,
6457            "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
6458             fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
6459            h_q8.is_some()
6460        );
6461        // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
6462        // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
6463        // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
6464        // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
6465        // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
6466        // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
6467        let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
6468        for r in 0..t {
6469            // Absolute position of this query row. `cache.pos` is the committed length at round
6470            // start and every row before r has already been appended by this loop, so the r-th
6471            // verify token sits at cache.pos + r — the same position eager decode would give it.
6472            let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
6473            let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
6474            e.copy_view_into(
6475                &mut h_row,
6476                0,
6477                &h.slice(r * n_embd..(r + 1) * n_embd),
6478                n_embd,
6479            )?;
6480            // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
6481            // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
6482            let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
6483            debug_assert_eq!(
6484                o.len(),
6485                n_embd,
6486                "step35_decode_attn returns post-wo [n_embd]"
6487            );
6488            e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
6489        }
6490        Ok(out)
6491    }
6492
6493    /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
6494    /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
6495    /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
6496    #[allow(clippy::too_many_arguments)]
6497    fn full_attn_verify(
6498        &self,
6499        e: &Engine,
6500        fa: &FullAttnLayer,
6501        h: &CudaSlice<f32>,
6502        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
6503        pos_d: &CudaSlice<i32>,
6504        t: usize,
6505        cache: &mut Cache,
6506        il: usize,
6507        stream_ctr: Option<&CudaSlice<i32>>,
6508    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6509        // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
6510        // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
6511        // its own arm. A verify that silently computes different attention than decode defeats the
6512        // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
6513        // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
6514        // shape and not laziness.
6515        if self.cfg.step35.is_some() {
6516            if stream_ctr.is_some() {
6517                return Err(
6518                    "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
6519                            cannot express the SWA offset KV view; same root cause as the dc \
6520                            decode refusal) — run spec without the stream arm"
6521                        .into(),
6522                );
6523            }
6524            return self.step35_verify(e, fa, h, h_q8, t, cache, il);
6525        }
6526        let cfg = &self.cfg;
6527        let geometry = cfg.full_attention_geometry_at(il as u32);
6528        let n_head = geometry.n_head as usize;
6529        let n_head_kv = geometry.n_head_kv as usize;
6530        let head_dim = geometry.head_dim_k as usize;
6531        let eps = cfg.rms_eps;
6532        let scale = geometry.attention_scale();
6533        let n_embd = cfg.n_embd as usize;
6534
6535        // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
6536        // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
6537        // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
6538        // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
6539        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
6540        // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
6541        // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
6542        // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
6543        let (qf, mut k, v) = {
6544            let mut fused = None;
6545            let qkv_fast =
6546                e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
6547            if t == 1 && qkv_fast {
6548                let (hq_o, hd_o);
6549                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
6550                    Some(p) => p,
6551                    None => {
6552                        (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
6553                        (&hq_o, &hd_o)
6554                    }
6555                };
6556                fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
6557            } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
6558                // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
6559                // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
6560                // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
6561                let (hq_o, hd_o);
6562                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
6563                    Some(p) => p,
6564                    None => {
6565                        (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
6566                        (&hq_o, &hd_o)
6567                    }
6568                };
6569                fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
6570            }
6571            match (fused, h_q8) {
6572                (Some(triple), _) => triple,
6573                // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
6574                // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
6575                (None, Some((hq, hd))) if qkv_fast => (
6576                    e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
6577                    e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
6578                    e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
6579                ),
6580                (None, _) => (
6581                    e.matmul_decode_exact(&fa.wq, h, t)?,
6582                    e.matmul_decode_exact(&fa.wk, h, t)?,
6583                    e.matmul_decode_exact(&fa.wv, h, t)?,
6584                ),
6585            }
6586        };
6587        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
6588        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
6589        let (mut q, gate) = if gated {
6590            let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
6591            let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
6592            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
6593            (q, Some(gate))
6594        } else {
6595            (qf, None)
6596        };
6597
6598        let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
6599        e.rms_norm(
6600            &q,
6601            fa.q_norm.float_data(),
6602            &mut qn,
6603            head_dim,
6604            n_head * t,
6605            eps,
6606        )?;
6607        q = qn;
6608        let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
6609        e.rms_norm(
6610            &k,
6611            fa.k_norm.float_data(),
6612            &mut kn,
6613            head_dim,
6614            n_head_kv * t,
6615            eps,
6616        )?;
6617        k = kn;
6618        let rope_dims = geometry.n_rot as usize;
6619        e.rope_neox(
6620            &mut q,
6621            pos_d,
6622            head_dim,
6623            rope_dims,
6624            n_head,
6625            t,
6626            geometry.rope_base,
6627            1.0,
6628        )?;
6629        e.rope_neox(
6630            &mut k,
6631            pos_d,
6632            head_dim,
6633            rope_dims,
6634            n_head_kv,
6635            t,
6636            geometry.rope_base,
6637            1.0,
6638        )?;
6639
6640        // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
6641        // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
6642        let kvl = cache.kv[il].as_mut().unwrap();
6643        let (kv_dim_k, kv_dim_v, ktb, vtb) =
6644            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
6645        if let Some(ctr) = stream_ctr {
6646            // stream: ONE batched append at the device counter (rows kernel = the per-view warp
6647            // math on a (block, token) grid, documented byte-identical); host len is a stale
6648            // LOWER BOUND under pre-issue (drain reconciles it).
6649            e.append_kv_quantized_rows_dc(
6650                &k,
6651                &v,
6652                &mut kvl.k,
6653                &mut kvl.v,
6654                ctr,
6655                t,
6656                kv_dim_k,
6657                kv_dim_v,
6658                ktb,
6659                vtb,
6660                crate::Engine::kv_fp8_on(),
6661            )?;
6662        } else {
6663            for i in 0..t {
6664                let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
6665                let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
6666                e.append_kv_quantized_view(
6667                    &k_row,
6668                    &v_row,
6669                    &mut kvl.k,
6670                    &mut kvl.v,
6671                    kvl.len + i,
6672                    kv_dim_k,
6673                    kv_dim_v,
6674                    ktb,
6675                    vtb,
6676                    crate::Engine::kv_fp8_on(),
6677                )?;
6678            }
6679            kvl.len += t;
6680        }
6681
6682        // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
6683        // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
6684        // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
6685        // which changes FP summation order and can flip argmax at tight logit margins. Query row r
6686        // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
6687        // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
6688        // keys. The verify appends all T tokens first but bounds the key range per row.
6689        //
6690        // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
6691        // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
6692        // per-row program for all T rows (grid.z = row, per-row n_splits from the same
6693        // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
6694        // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
6695        // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
6696        // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
6697        // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
6698        let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
6699        let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
6700        // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
6701        // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
6702        // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
6703        // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
6704        // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
6705        // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
6706        // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
6707        // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
6708        if let Some(ctr) = stream_ctr {
6709            // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
6710            // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
6711            // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
6712            let upper = kvl.len + t + 64;
6713            let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
6714            let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
6715            e.fa_decode_rows_dc(
6716                &q,
6717                &k_view,
6718                &v_view,
6719                &mut attn,
6720                head_dim,
6721                n_head,
6722                n_head_kv,
6723                ctr,
6724                upper.min(cache.max_ctx),
6725                t,
6726                scale,
6727                ktb,
6728                vtb,
6729                0,
6730                false,
6731            )?;
6732        } else if spec_lean() && t == 1 {
6733            let t_kv = base_len + 1;
6734            let k_view = e.view_u8(&kvl.k, t_kv * ktb);
6735            let v_view = e.view_u8(&kvl.v, t_kv * vtb);
6736            e.fa_decode_kvmod(
6737                &q,
6738                &k_view,
6739                &v_view,
6740                &mut attn,
6741                head_dim,
6742                n_head,
6743                n_head_kv,
6744                t_kv,
6745                scale,
6746                ktb,
6747                vtb,
6748                crate::Engine::kv_fp8_on(),
6749            )?;
6750        } else if e.fa_rows_eligible(base_len, head_dim) {
6751            let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
6752            let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
6753            e.fa_decode_rows(
6754                &q,
6755                &k_view,
6756                &v_view,
6757                &mut attn,
6758                head_dim,
6759                n_head,
6760                n_head_kv,
6761                base_len,
6762                t,
6763                scale,
6764                ktb,
6765                vtb,
6766                None,
6767                false,
6768                crate::Engine::kv_fp8_on(),
6769                None,
6770            )?;
6771        } else {
6772            for r in 0..t {
6773                let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
6774                let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
6775                let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
6776                // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
6777                let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
6778                let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
6779                e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
6780                let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
6781                e.fa_decode_kvmod(
6782                    &q_row,
6783                    &k_view_r,
6784                    &v_view_r,
6785                    &mut attn_row,
6786                    head_dim,
6787                    n_head,
6788                    n_head_kv,
6789                    t_kv_r,
6790                    scale,
6791                    ktb,
6792                    vtb,
6793                    crate::Engine::kv_fp8_on(),
6794                )?;
6795                e.copy_into(
6796                    &mut attn,
6797                    r * n_head * head_dim,
6798                    &attn_row,
6799                    n_head * head_dim,
6800                )?;
6801            }
6802        }
6803
6804        let attn_g = match &gate {
6805            Some(gate) => {
6806                let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
6807                e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
6808                let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
6809                e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
6810                ag
6811            }
6812            None => attn,
6813        };
6814        // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
6815        // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
6816        Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
6817    }
6818
6819    /// Context-linear bytes for a plain serving session's trunk cache.
6820    pub fn plain_session_kv_bytes_per_token(&self) -> usize {
6821        crate::cache::cache_bytes_per_token(&self.cfg)
6822    }
6823
6824    /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
6825    pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
6826        (
6827            self.plain_session_kv_bytes_per_token(),
6828            crate::cache::cache_ring_bytes_per_token(&self.cfg),
6829            crate::cache::cache_ring_row_cap(&self.cfg),
6830        )
6831    }
6832
6833    /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
6834    /// scratch. With no MTP head this equals the plain coefficient.
6835    pub fn spec_session_kv_bytes_per_token(&self) -> usize {
6836        let scratch = self
6837            .mtp
6838            .as_ref()
6839            .map(|mtp| {
6840                let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
6841                k + v
6842            })
6843            .unwrap_or(0);
6844        self.plain_session_kv_bytes_per_token()
6845            .saturating_add(scratch)
6846    }
6847
6848    /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
6849    /// capped by the same SWA ring rows as the trunk.
6850    pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
6851        let total = self.spec_session_kv_bytes_per_token();
6852        let (_, mut ring, rows) = self.plain_session_kv_shape();
6853        if rows > 0 {
6854            ring = ring.saturating_add(
6855                self.mtp
6856                    .as_ref()
6857                    .map(|mtp| {
6858                        let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
6859                        k + v
6860                    })
6861                    .unwrap_or(0),
6862            );
6863        }
6864        (total, ring, rows)
6865    }
6866
6867    /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
6868    /// the NextN head to draft K tokens then verifies them in one batched target forward.
6869    /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
6870    /// acceptance rate. `k` = draft length per round.
6871    ///
6872    /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
6873    /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
6874    /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
6875    /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
6876    /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
6877    /// captured graph references is event-free; the spec loop is strictly single-stream.
6878    /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
6879    /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
6880    /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
6881    /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
6882    /// generate_spec_inner2.
6883    /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
6884    /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
6885    /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
6886    /// hybrid linear-attn states are in-place (no position index), so a session can extend but
6887    /// never rewind — `committed` is the exact token list whose state the caches hold (includes
6888    /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
6889    pub fn new_session(
6890        &self,
6891        e: &Engine,
6892        max_ctx: usize,
6893    ) -> Result<SpecSession, Box<dyn std::error::Error>> {
6894        Ok(SpecSession {
6895            // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
6896            // is the SERVING spec-session path, and with the ppN door open across two cards a
6897            // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
6898            // round — the wrong-card class already fixed on the two batched serving paths
6899            // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
6900            // branch, same allocations), so single-device behavior is byte-unchanged.
6901            cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
6902            scratch: MtpScratch::new(
6903                e,
6904                &self.cfg,
6905                max_ctx,
6906                self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
6907            )?,
6908            committed: Vec::new(),
6909            last_h: None,
6910            next_pred: None,
6911            sctr: 0,
6912            uctr: 0,
6913            draft_ctx: None,
6914            pending_tok: None,
6915            turn_ckpt: None,
6916            telem: SpecTelemetryCounters::default(),
6917            capture_at: None,
6918            boundary_captures: Vec::new(),
6919            ckpt_at: None,
6920        })
6921    }
6922
6923    /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
6924    /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
6925    /// SpecSession around a trunk cache the worker already restored from a prefix-cache
6926    /// entry, re-installing the entry's published draft plane as the MTP scratch rows
6927    /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
6928    /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
6929    /// worker always receives a fully-warm continuation session (committed = whole
6930    /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
6931    /// boundary logits on the empty-suffix shape).
6932    ///
6933    /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
6934    /// gate): the identity target for a converted hit is the PLAIN hit serving the same
6935    /// request, and plain feeds a carried suffix via eager `decode_step` below
6936    /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
6937    /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
6938    /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
6939    /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
6940    /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
6941    /// burst prime.
6942    ///
6943    /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
6944    /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
6945    /// EXACTLY the rule the cold burst entry applies to its own first token from the same
6946    /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
6947    /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
6948    /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
6949    /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
6950    /// cold session draws from the identical row at counter 0 and then runs its rounds from
6951    /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
6952    /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
6953    /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
6954    /// span the session: `committed` here is the WHOLE prompt, so the restored session's
6955    /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
6956    ///
6957    /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
6958    /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
6959    /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
6960    /// and are never routed here.
6961    ///
6962    /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
6963    /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
6964    /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
6965    /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
6966    /// entry stays published for the next request.
6967    #[allow(clippy::too_many_arguments)]
6968    pub fn spec_session_from_restored(
6969        &self,
6970        e: &Engine,
6971        mut cache: Cache,
6972        prefix: Vec<u32>,
6973        suffix: &[u32],
6974        draft_k: &CudaSlice<u8>,
6975        draft_v: &CudaSlice<u8>,
6976        draft_k_tok_bytes: usize,
6977        draft_v_tok_bytes: usize,
6978        draft_len: usize,
6979        last_h: &[f32],
6980        // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
6981        // when a suffix follows — the feed's own logits are the boundary then.
6982        boundary_logits: &[f32],
6983        // The request's sampler, or None for greedy. Owned here so the seed rule lives in
6984        // ONE place instead of being half-applied by the worker.
6985        sampling: Option<SpecSampling>,
6986        require_anchor: bool,
6987        max_ctx: usize,
6988        // STABLE-BOUNDARY REPUBLICATION (lane/frspec-multiturn-cache, 2026-08-21): ABSOLUTE
6989        // prompt position to split the suffix feed at and capture the extended-entry
6990        // publication + this session's `turn_ckpt` — the worker's stable pre-generation
6991        // boundary (`plain_checkpoint_boundary`). None = legacy prompt-end republication.
6992        // WHY: the prompt-end capture below includes the template's live generation header
6993        // (`<|im_start|>assistant\n<think>\n`), which the next turn's re-render replaces, so
6994        // for a hybrid (whole-entry restores only) every extended entry's last ~2 tokens
6995        // diverged from every future prompt and the hit boundary FROZE at the first
6996        // lcp-split entry forever (measured: cached 6811 of 38228 by turn 8, B4).
6997        republish_at: Option<usize>,
6998    ) -> Result<SpecSession, (Option<Cache>, String)> {
6999        let pos = prefix.len();
7000        let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
7001            Err((Some(cache), msg))
7002        };
7003        if self.mtp.is_none() {
7004            return fail(cache, "no MTP head attached (nothing to draft with)".into());
7005        }
7006        if pos == 0 {
7007            return fail(cache, "empty committed prefix".into());
7008        }
7009        if cache.pos != pos {
7010            let msg = format!(
7011                "restored cache pos {} != restored prefix len {pos}",
7012                cache.pos
7013            );
7014            return fail(cache, msg);
7015        }
7016        if draft_len != pos {
7017            return fail(
7018                cache,
7019                format!("draft plane len {draft_len} != restored prefix len {pos}"),
7020            );
7021        }
7022        if pos + suffix.len() >= max_ctx {
7023            return fail(
7024                cache,
7025                format!(
7026                    "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
7027                    pos + suffix.len(),
7028                ),
7029            );
7030        }
7031        let mut scratch = match MtpScratch::new(
7032            e,
7033            &self.cfg,
7034            max_ctx,
7035            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
7036        ) {
7037            Ok(s) => s,
7038            Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
7039        };
7040        if scratch.kv.ring.is_some() {
7041            return fail(
7042                cache,
7043                "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
7044            );
7045        }
7046        if scratch.kv.k_tok_bytes != draft_k_tok_bytes
7047            || scratch.kv.v_tok_bytes != draft_v_tok_bytes
7048        {
7049            return fail(
7050                cache,
7051                format!(
7052                    "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
7053                     {}/{} bytes/token (stale entry across a format change)",
7054                    scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
7055                ),
7056            );
7057        }
7058        if pos > scratch.cap {
7059            return fail(
7060                cache,
7061                format!(
7062                    "draft plane rows {pos} exceed scratch capacity {}",
7063                    scratch.cap
7064                ),
7065            );
7066        }
7067        let kb = pos * draft_k_tok_bytes;
7068        let vb = pos * draft_v_tok_bytes;
7069        if draft_k.len() < kb || draft_v.len() < vb {
7070            return fail(
7071                cache,
7072                format!(
7073                    "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
7074                    draft_k.len(),
7075                    draft_v.len(),
7076                ),
7077            );
7078        }
7079        if kb > 0 {
7080            if let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb) {
7081                return fail(cache, format!("draft K restore copy failed: {err}"));
7082            }
7083        }
7084        if vb > 0 {
7085            if let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb) {
7086                return fail(cache, format!("draft V restore copy failed: {err}"));
7087            }
7088        }
7089        if let Err(err) = scratch.set_len(e, pos) {
7090            return fail(cache, format!("draft scratch len set failed: {err}"));
7091        }
7092        let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
7093            // anchor upload failure is acceptance-only when a suffix feed follows (fill
7094            // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
7095            // burst entry asserts committed + last_h + next_pred) — the caller says which.
7096            e.htod(last_h).ok()
7097        } else {
7098            None
7099        };
7100        if require_anchor && last_h_dev.is_none() {
7101            return fail(
7102                cache,
7103                "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
7104            );
7105        }
7106        let mut committed = prefix;
7107        // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
7108        // what the empty-suffix continuation assert in the burst entry requires.
7109        let next_pred;
7110        // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
7111        // consumes counter 0 and leaves 1, which is the state a cold session reaches after
7112        // drawing its own first token from the same row.
7113        let mut sctr = 0u32;
7114        let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
7115        // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
7116        // prompt, which is what the cold session's own burst sees (Item 2's window). Built
7117        // after the suffix joins `committed` below.
7118        let mut boundary_captures: Vec<SpecBoundaryCapture> = Vec::new();
7119        let mut restored_turn_ckpt: Option<SpecCheckpoint> = None;
7120        if !suffix.is_empty() {
7121            // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
7122            // From here on the trunk cache mutates: failures return Err((None, _)) and
7123            // the worker serves the request cold-plain instead of reusing the carrier.
7124            let dirty =
7125                |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
7126            let n_embd = self.cfg.n_embd as usize;
7127            let t = suffix.len();
7128            let mut h_rows = match e.uninit(t * n_embd) {
7129                Ok(b) => b,
7130                Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
7131            };
7132            // STABLE-BOUNDARY split (see `republish_at`): feed stops at the boundary so the
7133            // in-place GDN conv/ssm state can be snapshotted there — the only moment it
7134            // exists (the cold prime-split law). suffix-relative; None = one-segment legacy.
7135            let b_rel = republish_at
7136                .and_then(|abs| abs.checked_sub(pos))
7137                .filter(|&r| r > 0 && r < t);
7138            let mut feed_logits = Vec::new();
7139            let tokenwise_env = std::env::var("MEMRA_PRIME_TOKENWISE").is_ok()
7140                || e.frozen_cpu_experts_prefer_tokenwise_prime();
7141            let mut fed = 0usize;
7142            for seg_end in [b_rel, Some(t)].into_iter().flatten() {
7143                if seg_end <= fed {
7144                    continue;
7145                }
7146                let seg = &suffix[fed..seg_end];
7147                let batched = seg.len() >= crate::hybrid_forward::PRIME_MIN_T && !tokenwise_env;
7148                if batched {
7149                    // prefill_tick's prime arm: request-level prime_cache call; tokens still
7150                    // queued after this segment ride `queued_after` so Step35 arm selection
7151                    // stays keyed to the request's end (tick-seg law).
7152                    match self.prime_cache(e, seg, &mut cache, t - seg_end) {
7153                        Ok((l, _h_seed, hiddens)) => {
7154                            if let Err(err) =
7155                                e.copy_into(&mut h_rows, fed * n_embd, &hiddens, seg.len() * n_embd)
7156                            {
7157                                return dirty(format!("suffix hidden copy: {err}"));
7158                            }
7159                            feed_logits = l;
7160                        }
7161                        Err(err) => return dirty(format!("suffix prime failed: {err}")),
7162                    }
7163                } else {
7164                    // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
7165                    for (i, &tok) in seg.iter().enumerate() {
7166                        match self.decode_step_h(e, tok, &mut cache) {
7167                            Ok((l, h)) => {
7168                                if let Err(err) =
7169                                    e.copy_into(&mut h_rows, (fed + i) * n_embd, &h, n_embd)
7170                                {
7171                                    return dirty(format!("suffix hidden copy: {err}"));
7172                                }
7173                                feed_logits = l;
7174                            }
7175                            Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
7176                        }
7177                    }
7178                }
7179                fed = seg_end;
7180                if Some(seg_end) == b_rel {
7181                    // The stable pre-generation boundary: capture the extended-entry
7182                    // publication AND this session's own turn checkpoint here instead of at
7183                    // prompt-end (both would otherwise carry the volatile live-header tail
7184                    // the next re-render replaces). Failure silent, turn_ckpt convention.
7185                    debug_assert_eq!(
7186                        cache.pos,
7187                        pos + seg_end,
7188                        "stable-boundary capture off the feed split"
7189                    );
7190                    if spec_restore_republish_on() {
7191                        if let Ok(snap) = cache.snapshot(e) {
7192                            boundary_captures.push(SpecBoundaryCapture {
7193                                snap,
7194                                pos: pos + seg_end,
7195                                logits: feed_logits.clone(),
7196                                last_h: capture_boundary_hidden(e, &h_rows, seg_end, n_embd),
7197                            });
7198                        }
7199                    }
7200                    let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
7201                        e.uninit(n_embd).and_then(|mut a| {
7202                            e.copy_view_into(
7203                                &mut a,
7204                                0,
7205                                &h_rows.slice((seg_end - 1) * n_embd..seg_end * n_embd),
7206                                n_embd,
7207                            )?;
7208                            Ok(a)
7209                        });
7210                    if let (Ok(snap), Ok(last_h)) = (cache.snapshot(e), anchor) {
7211                        restored_turn_ckpt = Some(SpecCheckpoint {
7212                            snap,
7213                            pos: pos + seg_end,
7214                            last_h,
7215                        });
7216                    }
7217                }
7218            }
7219            // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
7220            // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
7221            // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
7222            // with T). Fill failures are acceptance-only — truncate to the restored rows
7223            // and continue; the burst's own set_len keeps the invariant.
7224            let mtp = self.mtp.as_ref().expect("mtp checked above");
7225            let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
7226            let embd_gpu = if spec_host_embd() {
7227                None
7228            } else {
7229                Some(
7230                    self.embd_gpu
7231                        .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
7232                )
7233            };
7234            let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
7235            let fill_chunk = 4096usize;
7236            let mut filled = true;
7237            let mut start = 0usize;
7238            'fill: while start < t {
7239                let end = (start + fill_chunk).min(t);
7240                let tc = end - start;
7241                let Ok(mut phs) = e.zeros(tc * n_embd) else {
7242                    filled = false;
7243                    break 'fill;
7244                };
7245                let (src_lo, dst_off, n_copy) = if start == 0 {
7246                    (0, n_embd, (tc - 1) * n_embd)
7247                } else {
7248                    ((start - 1) * n_embd, 0, tc * n_embd)
7249                };
7250                if start == 0 {
7251                    if let Some(lh) = last_h_dev.as_ref() {
7252                        if e.copy_into(&mut phs, 0, lh, n_embd).is_err() {
7253                            filled = false;
7254                            break 'fill;
7255                        }
7256                    }
7257                }
7258                if n_copy > 0
7259                    && e.copy_view_into(
7260                        &mut phs,
7261                        dst_off,
7262                        &h_rows.slice(src_lo..src_lo + n_copy),
7263                        n_copy,
7264                    )
7265                    .is_err()
7266                {
7267                    filled = false;
7268                    break 'fill;
7269                }
7270                if self
7271                    .mtp_kv_fill(
7272                        e,
7273                        mtp,
7274                        &suffix[start..end],
7275                        &phs,
7276                        pos + start,
7277                        &mut scratch,
7278                        embd_dev,
7279                    )
7280                    .is_err()
7281                {
7282                    filled = false;
7283                    break 'fill;
7284                }
7285                start = end;
7286            }
7287            if !filled {
7288                // acceptance-only: drafts over missing suffix rows are cheap and wrong,
7289                // so keep only the restored rows resident and let verify arbitrate.
7290                if let Err(err) = scratch.set_len(e, pos) {
7291                    return dirty(format!("scratch truncation after failed fill: {err}"));
7292                }
7293            }
7294            // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
7295            // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
7296            // finding (d)). Pre-lane, publication was armed only for COLD sessions
7297            // (`spec_resumed == 0` in the worker) and both engine capture sites require a
7298            // non-continuation burst — but a converted hit's first burst IS a continuation,
7299            // so a growing conversation learned exactly ONE boundary and turn 3 could never
7300            // hit a longer prefix than turn 2 did.
7301            //
7302            // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
7303            // line — the trunk is primed over the whole prompt, nothing is generated, and the
7304            // draft plane rows [0..prompt) are filled just above. That is a complete
7305            // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
7306            // publishes; the worker's existing publication sweep picks it up because it is
7307            // keyed on non-empty `boundary_captures` and is sampler- and resume-independent.
7308            // NOT the partial-restore hazard: the boundary is this session's own prompt END,
7309            // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
7310            // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
7311            // publication is an optimization, never a correctness dependency.
7312            //
7313            // SUPERSEDED WHEN `republish_at` FIRED (lane/frspec-multiturn-cache): a prompt-end
7314            // entry's tail is the live generation header the next re-render replaces, so on a
7315            // hybrid (whole-entry restores) it can never serve the conversation's next turn —
7316            // the stable-boundary capture above IS this publication, minus the poisoned tail.
7317            if spec_restore_republish_on() && boundary_captures.is_empty() {
7318                debug_assert_eq!(
7319                    cache.pos,
7320                    pos + t,
7321                    "extended-entry capture must sit at the restored session's prompt end",
7322                );
7323                if let Ok(snap) = cache.snapshot(e) {
7324                    boundary_captures.push(SpecBoundaryCapture {
7325                        snap,
7326                        pos: pos + t,
7327                        logits: feed_logits.clone(),
7328                        last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
7329                    });
7330                }
7331            }
7332            // continuation seed: the feed's boundary logits ARE the plain path's boundary
7333            // logits (same program), so greedy's argmax here is plain's first emitted token,
7334            // and the sampled draw is the cold sampled session's own first token.
7335            next_pred = Some(if sampled {
7336                let sp = sampling.expect("sampled implies a sampler");
7337                // `committed` is still the restored prefix here; the suffix joins it below —
7338                // so this is the last-N window over the WHOLE prompt, exactly the cold
7339                // session's own window at its first token.
7340                let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
7341                match sample_boundary_token(
7342                    e,
7343                    &feed_logits,
7344                    &sp,
7345                    &hist,
7346                    &mut sctr,
7347                    "restore-suffix-feed",
7348                ) {
7349                    Ok(t) => t,
7350                    // the trunk is already fed: hand nothing back, the worker serves the
7351                    // request cold-plain. Never fall back to an argmax — that would put a
7352                    // greedy token in a sampled stream to save a slow path.
7353                    Err(err) => {
7354                        return dirty(format!("boundary token draw failed: {err}"));
7355                    }
7356                }
7357            } else {
7358                argmax(&feed_logits) as u32
7359            });
7360            let mut lh = match e.uninit(n_embd) {
7361                Ok(b) => b,
7362                Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
7363            };
7364            if let Err(err) = e.copy_view_into(
7365                &mut lh,
7366                0,
7367                &h_rows.slice((t - 1) * n_embd..t * n_embd),
7368                n_embd,
7369            ) {
7370                return dirty(format!("boundary hidden copy: {err}"));
7371            }
7372            last_h_dev = Some(lh);
7373            committed.extend_from_slice(suffix);
7374        } else {
7375            // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
7376            // ENTRY's boundary logits are the boundary row, and this is the token the cold
7377            // session emits from that same row. Owned here rather than in the worker so the
7378            // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
7379            if boundary_logits.is_empty() {
7380                return fail(
7381                    cache,
7382                    "full-cover restore without the entry's boundary logits".into(),
7383                );
7384            }
7385            next_pred = Some(if sampled {
7386                let sp = sampling.expect("sampled implies a sampler");
7387                let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
7388                match sample_boundary_token(
7389                    e,
7390                    boundary_logits,
7391                    &sp,
7392                    &hist,
7393                    &mut sctr,
7394                    "restore-full-cover",
7395                ) {
7396                    Ok(t) => t,
7397                    // nothing has been mutated on this shape — hand the carrier back and let
7398                    // the hit serve PLAIN (the banked pre-lane path).
7399                    Err(err) => {
7400                        return fail(cache, format!("boundary token draw failed: {err}"));
7401                    }
7402                }
7403            } else {
7404                argmax(boundary_logits) as u32
7405            });
7406        }
7407        Ok(SpecSession {
7408            cache,
7409            scratch,
7410            committed,
7411            last_h: last_h_dev,
7412            next_pred,
7413            sctr,
7414            uctr: 0,
7415            draft_ctx: None,
7416            pending_tok: None,
7417            // Stable-boundary capture from the split feed above (None on the legacy shape):
7418            // a restored session previously parked WITHOUT a checkpoint, so the next turn's
7419            // affinity probe declined ("no turn checkpoint retained") and the conversation
7420            // fell back to the frozen prefix entry forever.
7421            turn_ckpt: restored_turn_ckpt,
7422            telem: SpecTelemetryCounters::default(),
7423            capture_at: None,
7424            boundary_captures,
7425            ckpt_at: None,
7426        })
7427    }
7428
7429    /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
7430    /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
7431    /// snapshot, or draft-KV row that only corrupts the following round.
7432    pub fn optipipe_compare_session_state(
7433        &self,
7434        e: &Engine,
7435        reference: &SpecSession,
7436        candidate: &SpecSession,
7437    ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
7438        fn fail(what: &str) -> Box<dyn std::error::Error> {
7439            format!("optipipe state mismatch: {what}").into()
7440        }
7441        fn same_f32(a: &[f32], b: &[f32]) -> bool {
7442            a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
7443        }
7444        fn compare_layers(
7445            es: &Engine,
7446            range: std::ops::Range<usize>,
7447            reference: &SpecSession,
7448            candidate: &SpecSession,
7449            report: &mut OptiForkStateIdentity,
7450        ) -> Result<(), Box<dyn std::error::Error>> {
7451            for il in range {
7452                match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
7453                    (Some(a), Some(b)) => {
7454                        if a.len != b.len {
7455                            return Err(fail(&format!(
7456                                "layer {il} host KV len {} != {}",
7457                                a.len, b.len
7458                            )));
7459                        }
7460                        let ad = es.dtoh_i32(&a.len_d)?;
7461                        let bd = es.dtoh_i32(&b.len_d)?;
7462                        if ad != bd || ad.first().copied() != Some(a.len as i32) {
7463                            return Err(fail(&format!(
7464                                "layer {il} device KV len {ad:?} != {bd:?} (host={})",
7465                                a.len,
7466                            )));
7467                        }
7468                        let kb = a.len * a.k_tok_bytes;
7469                        let vb = a.len * a.v_tok_bytes;
7470                        if kb > 0 {
7471                            let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
7472                            let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
7473                            if ak != bk {
7474                                let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
7475                                return Err(fail(&format!(
7476                                    "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
7477                                    at / a.k_tok_bytes,
7478                                    at % a.k_tok_bytes,
7479                                    ak[at],
7480                                    bk[at],
7481                                )));
7482                            }
7483                        }
7484                        if vb > 0 {
7485                            let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
7486                            let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
7487                            if av != bv {
7488                                let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
7489                                return Err(fail(&format!(
7490                                    "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
7491                                    at / a.v_tok_bytes,
7492                                    at % a.v_tok_bytes,
7493                                    av[at],
7494                                    bv[at],
7495                                )));
7496                            }
7497                        }
7498                        report.trunk_kv_bytes += kb + vb;
7499                    }
7500                    (None, None) => {}
7501                    _ => return Err(fail(&format!("layer {il} KV presence"))),
7502                }
7503                match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
7504                    (Some(a), Some(b)) => {
7505                        let ac = es.dtoh(&a.conv_state)?;
7506                        let bc = es.dtoh(&b.conv_state)?;
7507                        if !same_f32(&ac, &bc) {
7508                            return Err(fail(&format!("layer {il} conv state")));
7509                        }
7510                        let as_ = es.dtoh(&a.ssm_state)?;
7511                        let bs = es.dtoh(&b.ssm_state)?;
7512                        if !same_f32(&as_, &bs) {
7513                            return Err(fail(&format!("layer {il} SSM state")));
7514                        }
7515                        report.recurrent_bytes += (ac.len() + as_.len()) * 4;
7516                    }
7517                    (None, None) => {}
7518                    _ => return Err(fail(&format!("layer {il} recurrent presence"))),
7519                }
7520            }
7521            Ok(())
7522        }
7523
7524        if reference.committed != candidate.committed {
7525            return Err(fail("committed token ids"));
7526        }
7527        if reference.cache.pos != candidate.cache.pos
7528            || reference.cache.max_ctx != candidate.cache.max_ctx
7529        {
7530            return Err(fail("cache pos/capacity"));
7531        }
7532        if reference.pending_tok != candidate.pending_tok
7533            || reference.next_pred != candidate.next_pred
7534            || reference.sctr != candidate.sctr
7535            || reference.uctr != candidate.uctr
7536        {
7537            return Err(fail("pending/prediction/counter tail"));
7538        }
7539
7540        let mut report = OptiForkStateIdentity::default();
7541        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
7542            let rt = crate::pp::PpNRt::get(e)?;
7543            for stage in 0..rt.n_stages() {
7544                let _scope = rt.enter(stage);
7545                compare_layers(
7546                    rt.engine(stage, e),
7547                    fence[stage]..fence[stage + 1],
7548                    reference,
7549                    candidate,
7550                    &mut report,
7551                )?;
7552            }
7553        } else {
7554            compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
7555        }
7556
7557        let (a, b) = (&reference.scratch.kv, &candidate.scratch.kv);
7558        if a.len != b.len || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)? {
7559            return Err(fail("draft scratch length"));
7560        }
7561        let kb = a.len * a.k_tok_bytes;
7562        let vb = a.len * a.v_tok_bytes;
7563        if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
7564            return Err(fail("draft scratch K bytes"));
7565        }
7566        if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
7567            return Err(fail("draft scratch V bytes"));
7568        }
7569        report.scratch_kv_bytes = kb + vb;
7570
7571        match (&reference.last_h, &candidate.last_h) {
7572            (Some(a), Some(b)) => {
7573                let ah = e.dtoh(a)?;
7574                let bh = e.dtoh(b)?;
7575                if !same_f32(&ah, &bh) {
7576                    return Err(fail("last hidden/seed bytes"));
7577                }
7578                report.hidden_bytes = ah.len() * 4;
7579            }
7580            (None, None) => {}
7581            _ => return Err(fail("last hidden/seed presence")),
7582        }
7583        Ok(report)
7584    }
7585
7586    /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
7587    /// retained prompt-end checkpoint, so a request whose prompt matches
7588    /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
7589    ///
7590    /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
7591    /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
7592    /// restored from the device copy taken there, draft scratch length reset, `committed`
7593    /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
7594    /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
7595    /// every burst after it are identical to a cold run of the same token stream — the
7596    /// committed-tokens-authoritative contract.
7597    ///
7598    /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
7599    /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
7600    /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
7601    /// continue). The persistent draft graph survives: it bakes only session-stable pointers
7602    /// (the scratch KV, the resident embedding), none of which the rewind moves.
7603    ///
7604    /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
7605    /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
7606    /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
7607    pub fn spec_rewind_to_checkpoint(
7608        &self,
7609        e: &Engine,
7610        sess: &mut SpecSession,
7611    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
7612        if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
7613            !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
7614        }) {
7615            return Err(
7616                "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
7617            );
7618        }
7619        let Some(ckpt) = sess.turn_ckpt.take() else {
7620            return Ok(None);
7621        };
7622        assert!(
7623            ckpt.pos <= sess.committed.len(),
7624            "checkpoint past committed ({} > {})",
7625            ckpt.pos,
7626            sess.committed.len()
7627        );
7628        // Restore through each layer's owning engine. A single primary-engine rollback is not
7629        // sufficient when the serving cache is stage-owned under cross-device PP.
7630        crate::pp::restore_cache_checkpoint(e, &self.cfg, None, &mut sess.cache, &ckpt.snap)?;
7631        debug_assert_eq!(
7632            sess.cache.pos, ckpt.pos,
7633            "rollback landed off the checkpoint"
7634        );
7635        sess.scratch.set_len(e, ckpt.pos)?;
7636        sess.committed.truncate(ckpt.pos);
7637        sess.last_h = Some(ckpt.last_h);
7638        sess.next_pred = None;
7639        sess.pending_tok = None;
7640        Ok(Some(ckpt.pos))
7641    }
7642
7643    /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
7644    /// checkpoint without re-priming the checkpoint prefix.
7645    ///
7646    /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
7647    /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
7648    /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
7649    /// remain authoritative, so they are copied into a fresh larger scratch before its length is
7650    /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
7651    ///
7652    /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
7653    /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
7654    pub fn spec_grow_and_rewind_to_checkpoint(
7655        &self,
7656        e: &Engine,
7657        sess: &mut SpecSession,
7658        target_cap: usize,
7659    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
7660        if target_cap <= sess.cache.max_ctx {
7661            return self.spec_rewind_to_checkpoint(e, sess);
7662        }
7663        let Some(ckpt) = sess.turn_ckpt.as_ref() else {
7664            return Ok(None);
7665        };
7666        if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
7667            return Err(format!(
7668                "checkpoint pos {} outside committed length {}",
7669                ckpt.pos,
7670                sess.committed.len(),
7671            )
7672            .into());
7673        }
7674        if ckpt.pos > target_cap {
7675            return Err(format!(
7676                "checkpoint pos {} exceeds grown capacity {target_cap}",
7677                ckpt.pos,
7678            )
7679            .into());
7680        }
7681
7682        let mut grown_cache = crate::pp::new_cache(e, &self.cfg, target_cap)?;
7683        let mut grown_scratch = MtpScratch::new(
7684            e,
7685            &self.cfg,
7686            target_cap,
7687            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
7688        )?;
7689        crate::pp::restore_cache_checkpoint(
7690            e,
7691            &self.cfg,
7692            Some(&sess.cache),
7693            &mut grown_cache,
7694            &ckpt.snap,
7695        )?;
7696
7697        let src = &sess.scratch.kv;
7698        let dst = &mut grown_scratch.kv;
7699        if ckpt.pos > src.len
7700            || src.kv_dim_k != dst.kv_dim_k
7701            || src.kv_dim_v != dst.kv_dim_v
7702            || src.k_tok_bytes != dst.k_tok_bytes
7703            || src.v_tok_bytes != dst.v_tok_bytes
7704        {
7705            return Err(format!(
7706                "checkpoint draft layout mismatch (pos {}, source len {})",
7707                ckpt.pos, src.len,
7708            )
7709            .into());
7710        }
7711        let kb = ckpt.pos * src.k_tok_bytes;
7712        let vb = ckpt.pos * src.v_tok_bytes;
7713        if kb > 0 {
7714            e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
7715        }
7716        if vb > 0 {
7717            e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
7718        }
7719        grown_scratch.set_len(e, ckpt.pos)?;
7720        // The old scratch is dropped immediately after publication below. Bound its D2D reads
7721        // first; growth happens once per rewritten turn, outside the decode hot loop.
7722        e.stream().synchronize()?;
7723
7724        let ckpt = sess
7725            .turn_ckpt
7726            .take()
7727            .expect("checkpoint remained present through transactional grow");
7728        let pos = ckpt.pos;
7729        sess.cache = grown_cache;
7730        sess.scratch = grown_scratch;
7731        sess.committed.truncate(pos);
7732        sess.last_h = Some(ckpt.last_h);
7733        sess.next_pred = None;
7734        sess.pending_tok = None;
7735        sess.draft_ctx = None;
7736        debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
7737        debug_assert_eq!(
7738            sess.scratch.kv.len, pos,
7739            "grown draft rewind landed off checkpoint"
7740        );
7741        Ok(Some(pos))
7742    }
7743
7744    /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
7745    /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
7746    /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
7747    /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
7748    /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
7749    /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
7750    /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
7751    /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
7752    /// park-time flush is a future request whose sampler is not knowable here (residual
7753    /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
7754    pub fn spec_flush_pending(
7755        &self,
7756        e: &Engine,
7757        sess: &mut SpecSession,
7758        sampling: Option<SpecSampling>,
7759    ) -> Result<(), Box<dyn std::error::Error>> {
7760        let Some(b) = sess.pending_tok.take() else {
7761            return Ok(());
7762        };
7763        let mtp = self
7764            .mtp
7765            .as_ref()
7766            .expect("pending carry requires an MTP head");
7767        let n_embd = self.cfg.n_embd as usize;
7768        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
7769        let embd_gpu = if spec_host_embd() {
7770            None
7771        } else {
7772            Some(
7773                self.embd_gpu
7774                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
7775            )
7776        };
7777        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
7778        let pos_b = sess.cache.pos;
7779        sess.scratch.set_len(e, pos_b)?;
7780        let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
7781        sess.next_pred = Some(match sampling {
7782            Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
7783                // window includes `b` itself: it is committed by this pass, and the pre-lane
7784                // code never counted a boundary token in the penalty history at all.
7785                let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
7786                sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
7787            }
7788            _ => argmax(&lg_b) as u32,
7789        });
7790        let anchor = sess
7791            .last_h
7792            .as_ref()
7793            .expect("pending carry requires last_h (the predecessor-row anchor)");
7794        self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
7795        sess.last_h = Some(hb);
7796        sess.committed.push(b);
7797        Ok(())
7798    }
7799
7800    /// Solo target feed used only at speculative round boundaries. Step35 serving made its
7801    /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
7802    /// rounds through that same graph. Other model families keep their eager T=1 contract.
7803    fn spec_target_step_h(
7804        &self,
7805        e: &Engine,
7806        token: u32,
7807        cache: &mut Cache,
7808    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
7809        if self.cfg.step35.is_none() && !self.qwen35_serving_class() {
7810            return self.decode_step_h(e, token, cache);
7811        }
7812        let pos0 = cache.pos;
7813        let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
7814        Ok((e.dtoh(&logits)?, hidden))
7815    }
7816
7817    /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
7818    /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
7819    /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
7820    /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
7821    /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
7822    /// carries the drift until a near-tie flips deep in generation. One predicate so the five
7823    /// dispatch sites cannot drift apart again.
7824    /// Draft-graph head admissibility (lane/draftcost-moe, 2026-08-20): the capture body
7825    /// (`mtp_head_forward_cap`) supports Dense heads AND resident-MoE heads
7826    /// (`Ffn::Moe(m) if m.dev_exps.is_some()`); non-resident MoE still refuses inside the
7827    /// capture and the caller falls back to the eager chain by design. Trunk FFN class is
7828    /// irrelevant — the graph body is the HEAD forward only. One predicate for all three
7829    /// eligibility sites so they cannot drift (the qwen35_serving_class lesson).
7830    fn mtp_graph_capturable(&self) -> bool {
7831        self.mtp
7832            .as_ref()
7833            .map(|m| match &m.ffn {
7834                crate::hybrid::Ffn::Dense { .. } => true,
7835                crate::hybrid::Ffn::Moe(mo) => mo.dev_exps.is_some(),
7836            })
7837            .unwrap_or(false)
7838    }
7839
7840    fn qwen35_serving_class(&self) -> bool {
7841        matches!(
7842            self.cfg.arch,
7843            memra_gguf::config::Arch::Qwen35 | memra_gguf::config::Arch::Qwen35Moe
7844        )
7845    }
7846
7847    /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
7848    /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
7849    /// session already exist.
7850    pub fn spec_pipe_available(&self, e: &Engine) -> bool {
7851        if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
7852            || !spec_devacc()
7853            || spec_replay_env_enabled()
7854            || spec_stream()
7855            || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
7856            || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
7857            || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
7858            || std::env::var("MEMRA_SPEC_PMIN")
7859                .ok()
7860                .and_then(|v| v.parse::<f32>().ok())
7861                .unwrap_or(0.0)
7862                > 0.0
7863            || self.is_gemma4_e4b()
7864            || self.cfg.gemma4.is_some()
7865            || self.mtp.is_none()
7866        {
7867            return false;
7868        }
7869        let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
7870            return false;
7871        };
7872        if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
7873            return false;
7874        }
7875        crate::pp::PpNRt::get(e)
7876            .map(|rt| rt.n_stages() == 2 && rt.cross_device())
7877            .unwrap_or(false)
7878    }
7879
7880    /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
7881    /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
7882    /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
7883    #[allow(clippy::too_many_arguments)]
7884    pub fn generate_spec_session_pair(
7885        &self,
7886        e: &Engine,
7887        sess_a: &mut SpecSession,
7888        max_new_a: usize,
7889        k_a: usize,
7890        sess_b: &mut SpecSession,
7891        max_new_b: usize,
7892        k_b: usize,
7893    ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
7894    {
7895        if !self.spec_pipe_available(e) {
7896            return Err("two-session speculative pipeline is outside its reduced matrix".into());
7897        }
7898        if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
7899            return Err(
7900                "two-session speculative pipeline requires non-empty positive-K bursts".into(),
7901            );
7902        }
7903        for sess in [&*sess_a, &*sess_b] {
7904            if sess.committed.is_empty()
7905                || sess.last_h.is_none()
7906                || (sess.next_pred.is_none() && sess.pending_tok.is_none())
7907            {
7908                return Err("two-session speculative pipeline requires warm continuations".into());
7909            }
7910        }
7911
7912        let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
7913            && !spec_host_embd()
7914            && self.mtp_graph_capturable()
7915            && !crate::model::full_prec_enabled();
7916        let graph_a = graph_ok && k_a + 2 < 96;
7917        let graph_b = graph_ok && k_b + 2 < 96;
7918        let was_tracking = e.ctx().is_event_tracking();
7919        if (graph_a || graph_b) && was_tracking {
7920            unsafe {
7921                e.ctx().disable_event_tracking();
7922            }
7923        }
7924
7925        static LOGGED: std::sync::Once = std::sync::Once::new();
7926        LOGGED.call_once(|| {
7927            eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
7928        });
7929        let sync = std::sync::Arc::new(SpecPipeSync::new());
7930        let lane_a = SpecPipeLane {
7931            sync: sync.clone(),
7932            lane: 0,
7933        };
7934        let lane_b = SpecPipeLane { sync, lane: 1 };
7935        let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
7936        let (result_a, result_b) = std::thread::scope(|scope| {
7937            let b = scope.spawn(move || {
7938                let mut finish = SpecPipeFinish::new(&lane_b);
7939                let sess_b = unsafe { sess_b_ptr.get_mut() };
7940                let result = e
7941                    .ctx()
7942                    .bind_to_thread()
7943                    .map_err(|err| err.to_string())
7944                    .and_then(|_| {
7945                        self.generate_spec_inner2(
7946                            e,
7947                            &[],
7948                            max_new_b,
7949                            k_b,
7950                            graph_b,
7951                            Some(sess_b),
7952                            None,
7953                            None,
7954                            None,
7955                            None,
7956                            Some(&lane_b),
7957                        )
7958                        .map_err(|err| err.to_string())
7959                    });
7960                finish.close(result.is_err());
7961                result
7962            });
7963            let mut finish = SpecPipeFinish::new(&lane_a);
7964            let result_a = self.generate_spec_inner2(
7965                e,
7966                &[],
7967                max_new_a,
7968                k_a,
7969                graph_a,
7970                Some(sess_a),
7971                None,
7972                None,
7973                None,
7974                None,
7975                Some(&lane_a),
7976            );
7977            finish.close(result_a.is_err());
7978            let result_b = b
7979                .join()
7980                .map_err(|_| "paired speculative session B panicked".to_string())
7981                .and_then(|r| r);
7982            (result_a, result_b)
7983        });
7984
7985        if (graph_a || graph_b) && was_tracking {
7986            unsafe {
7987                e.ctx().enable_event_tracking();
7988            }
7989        }
7990        let result_a = result_a?;
7991        let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
7992        Ok((result_a, result_b))
7993    }
7994
7995    /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
7996    /// message rendered through the chat template continuation). Returns (new tokens emitted,
7997    /// drafted, accepted); session.committed grows by suffix + emitted.
7998    pub fn generate_spec_session(
7999        &self,
8000        e: &Engine,
8001        sess: &mut SpecSession,
8002        suffix: &[u32],
8003        max_new: usize,
8004        k: usize,
8005    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8006        self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
8007    }
8008
8009    /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
8010    /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
8011    /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
8012    /// for the filtered target (feat/filtered-spec).
8013    ///
8014    /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
8015    /// output — once right after the prime's first token, then once per round commit — so a
8016    /// streaming caller can flush text at round cadence instead of once per burst. The slices
8017    /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
8018    /// timing only: token bytes, session state, and exactness are untouched.
8019    ///
8020    /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
8021    /// the burst at the current round boundary, exactly as if `max_new` had been reached —
8022    /// the caller's scheduler regains control without waiting the burst out. Burst size is
8023    /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
8024    /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
8025    /// drains and the defensive tail flush can land with nothing new committed).
8026    #[allow(clippy::too_many_arguments)]
8027    pub fn generate_spec_session_sampled(
8028        &self,
8029        e: &Engine,
8030        sess: &mut SpecSession,
8031        suffix: &[u32],
8032        max_new: usize,
8033        k: usize,
8034        sampling: Option<SpecSampling>,
8035        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8036    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8037        self.generate_spec_session_sampled_prime_split(
8038            e, sess, suffix, max_new, k, sampling, None, on_commit,
8039        )
8040    }
8041
8042    /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
8043    /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
8044    /// pass `None` and stay on the existing zero-prime path.
8045    #[allow(clippy::too_many_arguments)]
8046    pub fn generate_spec_session_sampled_prime_split(
8047        &self,
8048        e: &Engine,
8049        sess: &mut SpecSession,
8050        suffix: &[u32],
8051        max_new: usize,
8052        k: usize,
8053        sampling: Option<SpecSampling>,
8054        prime_split: Option<usize>,
8055        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8056    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8057        self.generate_spec_session_constrained_prime_split(
8058            e,
8059            sess,
8060            suffix,
8061            max_new,
8062            k,
8063            sampling,
8064            None,
8065            prime_split,
8066            on_commit,
8067        )
8068    }
8069
8070    /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
8071    /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
8072    /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
8073    /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
8074    /// column — token-identical to constrained plain greedy decode. GREEDY only (the
8075    /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
8076    /// may drop (drafter is unconstrained); that is measured, not hidden.
8077    #[allow(clippy::too_many_arguments)]
8078    pub fn generate_spec_session_constrained(
8079        &self,
8080        e: &Engine,
8081        sess: &mut SpecSession,
8082        suffix: &[u32],
8083        max_new: usize,
8084        k: usize,
8085        sampling: Option<SpecSampling>,
8086        constraint: Option<&mut dyn SpecConstraint>,
8087        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8088    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8089        self.generate_spec_session_constrained_prime_split(
8090            e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
8091        )
8092    }
8093
8094    #[allow(clippy::too_many_arguments)]
8095    pub fn generate_spec_session_constrained_prime_split(
8096        &self,
8097        e: &Engine,
8098        sess: &mut SpecSession,
8099        suffix: &[u32],
8100        max_new: usize,
8101        k: usize,
8102        sampling: Option<SpecSampling>,
8103        constraint: Option<&mut dyn SpecConstraint>,
8104        prime_split: Option<usize>,
8105        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8106    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8107        if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
8108            return Err(
8109                "constrained spec decode is greedy-only (worker routes sampled \
8110                        constrained to plain decode)"
8111                    .into(),
8112            );
8113        }
8114        // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
8115        // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
8116        // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
8117        // serve continuation case — consume the carry in-loop with zero solo passes.
8118        if sess.pending_tok.is_some()
8119            && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
8120        {
8121            self.spec_flush_pending(e, sess, sampling)?;
8122        }
8123
8124        // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
8125        // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
8126        // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
8127        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
8128            && !spec_host_embd()
8129            && self.mtp_graph_capturable()
8130            && k + 2 < 96
8131            && !crate::model::full_prec_enabled();
8132        let was_tracking = e.ctx().is_event_tracking();
8133        if graph_draft && was_tracking {
8134            unsafe {
8135                e.ctx().disable_event_tracking();
8136            }
8137        }
8138        let r = self.generate_spec_inner2(
8139            e,
8140            suffix,
8141            max_new,
8142            k,
8143            graph_draft,
8144            Some(sess),
8145            sampling,
8146            constraint,
8147            on_commit,
8148            prime_split,
8149            None,
8150        );
8151        if graph_draft && was_tracking {
8152            unsafe {
8153                e.ctx().enable_event_tracking();
8154            }
8155        }
8156        let (out, d, a) = r?;
8157        Ok((out, d, a))
8158    }
8159
8160    pub fn generate_spec(
8161        &self,
8162        e: &Engine,
8163        prompt: &[u32],
8164        max_new: usize,
8165        k: usize,
8166    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8167        // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
8168        // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
8169        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
8170            && !spec_host_embd()
8171            && self.mtp_graph_capturable()
8172            && k + 2 < 96
8173            && !crate::model::full_prec_enabled();
8174        if !graph_draft {
8175            return self.generate_spec_inner2(
8176                e, prompt, max_new, k, false, None, None, None, None, None, None,
8177            );
8178        }
8179        let was_tracking = e.ctx().is_event_tracking();
8180        if was_tracking {
8181            unsafe {
8182                e.ctx().disable_event_tracking();
8183            }
8184        }
8185        let r = self.generate_spec_inner2(
8186            e, prompt, max_new, k, true, None, None, None, None, None, None,
8187        );
8188        if was_tracking {
8189            unsafe {
8190                e.ctx().enable_event_tracking();
8191            }
8192        }
8193        r
8194    }
8195
8196    fn generate_spec_inner2(
8197        &self,
8198        e: &Engine,
8199        prompt: &[u32],
8200        max_new: usize,
8201        k: usize,
8202        graph_draft: bool,
8203        mut sess: Option<&mut SpecSession>,
8204        sampling: Option<SpecSampling>,
8205        mut constraint: Option<&mut dyn SpecConstraint>,
8206        mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8207        prime_split: Option<usize>,
8208        pipe: Option<&SpecPipeLane>,
8209    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8210        assert!(k >= 1, "k must be >= 1");
8211        if let Some(p) = pipe {
8212            p.setup_begin()?;
8213        }
8214        // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
8215        let mut flushed = 0usize;
8216        // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
8217        // at the next round boundary (same exit as max_new reached — the session tail runs).
8218        // Initialized by the unconditional post-prime flush below.
8219        let mut keep_going;
8220        let mtp = self
8221            .mtp
8222            .as_ref()
8223            .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
8224        let n_vocab = self.output.out_features();
8225        // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
8226        // over the draft vocab and the winning index maps through d2t to a TARGET token id.
8227        // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
8228        let d_vocab = mtp
8229            .shared_head_head
8230            .as_ref()
8231            .unwrap_or(&self.output)
8232            .out_features();
8233        let n_embd = self.cfg.n_embd as usize;
8234        // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
8235        // already committed (their state is in the caches); 0 = fresh single-shot call.
8236        let session_mode = sess.is_some();
8237        let max_ctx = match sess.as_ref() {
8238            Some(s) => s.cache.max_ctx,
8239            None => prompt.len() + max_new + k + 8,
8240        };
8241        let mut own_cache;
8242        let mut own_scratch;
8243        // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
8244        // (requested split, destination list). Single-shot per burst; fresh calls have none.
8245        let mut sess_capture: Option<(Option<usize>, &mut Vec<SpecBoundaryCapture>)> = None;
8246        // STABLE-BOUNDARY turn-checkpoint request (lane/frspec-multiturn-cache): ABSOLUTE
8247        // committed-length position; consumed one-shot like `capture_at`. None = legacy
8248        // prompt-end capture below.
8249        let mut ckpt_req: Option<usize> = None;
8250        let (
8251            cache,
8252            scratch,
8253            mut sess_tail,
8254            mut sess_draft_slot,
8255            mut sess_pending_slot,
8256            sess_ckpt_slot,
8257            sess_telem,
8258        ): (
8259            &mut Cache,
8260            &mut MtpScratch,
8261            Option<(
8262                &mut Vec<u32>,
8263                &mut Option<CudaSlice<f32>>,
8264                &mut Option<u32>,
8265                &mut u32,
8266                &mut u32,
8267            )>,
8268            Option<&mut Option<DraftGraphCtx>>,
8269            Option<&mut Option<u32>>,
8270            Option<&mut Option<SpecCheckpoint>>,
8271            Option<&SpecTelemetryCounters>,
8272        ) = match sess.take() {
8273            Some(sr) => {
8274                let SpecSession {
8275                    cache,
8276                    scratch,
8277                    committed,
8278                    last_h,
8279                    next_pred,
8280                    sctr: s_sctr,
8281                    uctr: s_uctr,
8282                    draft_ctx,
8283                    pending_tok,
8284                    turn_ckpt,
8285                    telem,
8286                    capture_at,
8287                    boundary_captures,
8288                    ckpt_at,
8289                } = sr;
8290                sess_capture = Some((capture_at.take(), boundary_captures));
8291                ckpt_req = ckpt_at.take();
8292                (
8293                    cache,
8294                    scratch,
8295                    Some((committed, last_h, next_pred, s_sctr, s_uctr)),
8296                    Some(draft_ctx),
8297                    Some(pending_tok),
8298                    Some(turn_ckpt),
8299                    Some(telem),
8300                )
8301            }
8302            None => {
8303                // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
8304                // `Cache::new` verbatim.
8305                own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
8306                // Persistent scratch = max_ctx rows (~2KB/token quantized).
8307                own_scratch = MtpScratch::new(
8308                    e,
8309                    &self.cfg,
8310                    max_ctx,
8311                    self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
8312                )?;
8313                (
8314                    &mut own_cache,
8315                    &mut own_scratch,
8316                    None,
8317                    None,
8318                    None,
8319                    None,
8320                    None,
8321                )
8322            }
8323        };
8324        let base = cache.pos;
8325        // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
8326        // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
8327        // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
8328        // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
8329        let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
8330        // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
8331        // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
8332        // acceptance-only — exactness is verify's job either way).
8333        // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
8334        // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
8335        // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
8336        // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
8337        // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
8338        // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
8339        // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
8340        // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
8341        // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
8342        // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
8343        // per round on top of the acceptance win). Draft-quality-only: exactness stays the
8344        // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
8345        // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
8346        // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
8347        // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
8348        // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
8349        // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
8350        // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
8351        // + fallback seam).
8352        // Qwen35-MoE replay pin LIFTED (lane/draftcost-moe, 2026-08-20). The pin's stated
8353        // bar — the retained verify-state commit proven equivalent to sequential serving —
8354        // was waiting on this arch running the serving batched verify class, which the
8355        // t-parallel admission (this lane, increment 1) provided: the VerifyCkpt the
8356        // replay-free commit consumes is now produced by the SAME serving-class verify that
8357        // qualified dense qwen35 on 2026-08-15 (where the per-round duplicate replay
8358        // measured 69 -> 30 tok/s). Qualification receipts (run-spec K=1..8 both arms,
8359        // 8-prompt replay-vs-replay-free canary, long-prompt cell):
8360        // research/draftcost-moe-20260820/RECEIPTS.md. MEMRA_SPEC_REPLAY=1 stays the
8361        // rollback + A/B seam.
8362        let spec_replay = spec_replay_env_enabled();
8363        if constraint.is_some() && spec_replay {
8364            return Err(
8365                "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
8366                        (legacy replay commits an unmasked bonus)"
8367                    .into(),
8368            );
8369        }
8370        // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
8371        // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
8372        // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
8373        let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
8374
8375        // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
8376        // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
8377        // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
8378        // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
8379        // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
8380        // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
8381        // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
8382        // generation exactly where the last turn stopped — no prime at all. The stashed
8383        // `next_pred` plays prime_logits' role: it is the token produced from the logits after
8384        // committed.last() by the same rule this entry applies to a cold prime's last row —
8385        // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
8386        // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
8387        // where the sampler and the session's Philox counters were live). `last_h` seeds the
8388        // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
8389        let continuation = prompt.is_empty();
8390        if continuation {
8391            assert!(session_mode, "empty prompt requires a session");
8392            assert!(
8393                sess_tail
8394                    .as_ref()
8395                    .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
8396                        && lh.is_some()
8397                        && (np.is_some() || carried_pending.is_some())),
8398                "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
8399            );
8400        }
8401        let mut prime_logits;
8402        let mut prompt_h: Option<CudaSlice<f32>> = None;
8403        let t_prime = std::time::Instant::now();
8404        let batched_prime = !continuation
8405            && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
8406            && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
8407            && !e.frozen_cpu_experts_prefer_tokenwise_prime();
8408        let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
8409        if prime_split.is_some() && continuation {
8410            return Err("spec prime split requires a non-empty prime".into());
8411        }
8412        // STABLE-BOUNDARY TURN CHECKPOINT stop (lane/frspec-multiturn-cache, 2026-08-21):
8413        // the worker's `ckpt_at` request, ABSOLUTE -> prompt-relative. On WARM bursts
8414        // (base != 0, an affinity-rewound or pool-resumed session priming its own delta)
8415        // this is the only stop; on COLD bursts it usually coincides with `prime_split`
8416        // (both are the plain tier's stable pre-generation boundary). A boundary the prime
8417        // cannot honor (outside this prime's range) silently drops the capture — the
8418        // turn_ckpt convention: the next turn re-primes in full, never a wrong resume.
8419        let ckpt_rel = if continuation {
8420            None
8421        } else {
8422            ckpt_req
8423                .and_then(|abs| abs.checked_sub(base))
8424                .filter(|&r| r > 0 && r < prompt.len())
8425        };
8426        // Prime stops, ordered: each is a boundary the prime halts at so the in-place GDN
8427        // conv/ssm state can be snapshotted there (the only moment it exists). One stop =
8428        // the legacy single-split program, byte-for-byte.
8429        let mut stops: Vec<usize> = Vec::new();
8430        for b in [prime_split, ckpt_rel].into_iter().flatten() {
8431            if !stops.contains(&b) {
8432                stops.push(b);
8433            }
8434        }
8435        stops.sort_unstable();
8436        // Captured at the ckpt stop, installed into the session slot post-prime (replacing
8437        // the legacy prompt-end capture). Some(None) = capture attempted and failed -> the
8438        // slot is cleared (a stale checkpoint would rewind to the WRONG boundary).
8439        let mut ckpt_early: Option<Option<SpecCheckpoint>> = None;
8440        if continuation {
8441            prime_logits = Vec::new();
8442        } else if !stops.is_empty() {
8443            if let Some(&first) = stops.first() {
8444                if prime_split == Some(first) && first < crate::hybrid_forward::PRIME_MIN_T {
8445                    return Err(format!(
8446                        "spec prime split {first} is below PRIME_MIN_T {}",
8447                        crate::hybrid_forward::PRIME_MIN_T,
8448                    )
8449                    .into());
8450                }
8451            }
8452            // Mirror the plain worker's boundary stops exactly. Each segment is a
8453            // request-level prime (`queued_after` keeps Step35 arm selection independent of
8454            // the stops — tick-seg law); a segment below PRIME_MIN_T (and the final tail
8455            // under MEMRA_PRIME_TOKENWISE) takes the same eager tokenwise continuation as
8456            // prefill_tick. Retain every hidden row so the draft scratch fill remains one
8457            // coherent prompt.
8458            let mut h_all = e.uninit(prompt.len() * n_embd)?;
8459            prime_logits = Vec::new();
8460            let mut prev = 0usize;
8461            for seg_end in stops.iter().copied().chain(std::iter::once(prompt.len())) {
8462                if seg_end <= prev {
8463                    continue;
8464                }
8465                let seg = &prompt[prev..seg_end];
8466                let is_final = seg_end == prompt.len();
8467                let batched_seg = seg.len() >= crate::hybrid_forward::PRIME_MIN_T
8468                    && (!is_final
8469                        || (std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
8470                            && !e.frozen_cpu_experts_prefer_tokenwise_prime()));
8471                if batched_seg {
8472                    let (l, _, h_seg) =
8473                        self.prime_cache(e, seg, &mut *cache, prompt.len() - seg_end)?;
8474                    e.copy_into(&mut h_all, prev * n_embd, &h_seg, seg.len() * n_embd)?;
8475                    prime_logits = l;
8476                } else {
8477                    for (i, &tok) in seg.iter().enumerate() {
8478                        let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
8479                        e.copy_into(&mut h_all, (prev + i) * n_embd, &h, n_embd)?;
8480                        prime_logits = l;
8481                    }
8482                }
8483                prev = seg_end;
8484                if is_final {
8485                    break;
8486                }
8487                debug_assert_eq!(cache.pos, base + seg_end, "prime stop landed off boundary");
8488                // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm
8489                // states are about to be advanced in place by the next segment, so this is
8490                // the ONLY moment the boundary's recurrent state exists. Capture iff the
8491                // worker requested exactly this stop (cold sessions only — `capture_at` is
8492                // never armed warm). A failed snapshot is silent (turn_ckpt convention) —
8493                // publication is an optimization, never a correctness dependency.
8494                if base == 0 {
8495                    if let Some((requested, slot)) = sess_capture.as_mut() {
8496                        // Publish at the requested miss-LCP stop (the shared-prefix class)
8497                        // AND at the stable-boundary stop (the next-turn re-render class,
8498                        // lane/frspec-multiturn-cache) — the same boundary set the plain
8499                        // prefill tick learns. Without the second entry, the turn after a
8500                        // cold re-park could only hit the OLDER lcp entry (the measured
8501                        // one-turn transient: t3 restored 607 of 24122 while the plain arm
8502                        // rewound to 15222). Dedupe is the worker sweep's has_key.
8503                        if *requested == Some(seg_end) || ckpt_rel == Some(seg_end) {
8504                            if let Ok(snap) = cache.snapshot(e) {
8505                                slot.push(SpecBoundaryCapture {
8506                                    snap,
8507                                    pos: seg_end,
8508                                    logits: prime_logits.clone(),
8509                                    // rows [0..seg_end) of h_all are primed — the following
8510                                    // segments append, never overwrite.
8511                                    last_h: capture_boundary_hidden(e, &h_all, seg_end, n_embd),
8512                                });
8513                            }
8514                        }
8515                    }
8516                }
8517                // SESSION-AFFINITY TURN CHECKPOINT at the STABLE boundary (see `ckpt_at`):
8518                // same snapshot mechanics, installed post-prime in place of the prompt-end
8519                // capture the re-render class always diverged below.
8520                if ckpt_rel == Some(seg_end) {
8521                    let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
8522                        e.uninit(n_embd).and_then(|mut a| {
8523                            e.copy_view_into(
8524                                &mut a,
8525                                0,
8526                                &h_all.slice((seg_end - 1) * n_embd..seg_end * n_embd),
8527                                n_embd,
8528                            )?;
8529                            Ok(a)
8530                        });
8531                    ckpt_early = Some(match (cache.snapshot(e), anchor) {
8532                        (Ok(snap), Ok(last_h)) => Some(SpecCheckpoint {
8533                            snap,
8534                            pos: base + seg_end,
8535                            last_h,
8536                        }),
8537                        _ => None,
8538                    });
8539                }
8540            }
8541            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
8542                eprintln!(
8543                    "[spec-prime] stops={stops:?} tail={}",
8544                    prompt.len() - stops.last().copied().unwrap_or(0)
8545                );
8546            }
8547            prompt_h = Some(h_all);
8548        } else if batched_prime {
8549            let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
8550            prime_logits = l;
8551            prompt_h = Some(hiddens);
8552        } else {
8553            prime_logits = Vec::new();
8554            prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
8555            for (i, &tok) in prompt.iter().enumerate() {
8556                let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
8557                if let Some(ph) = prompt_h.as_mut() {
8558                    e.copy_into(ph, i * n_embd, &h, n_embd)?;
8559                }
8560                prime_logits = l;
8561            }
8562        }
8563        e.stream().synchronize()?;
8564        // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
8565        // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
8566        // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
8567        // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
8568        // prime_split. The mid-prompt capture above already consumed the request if it matched.
8569        if !continuation && base == 0 {
8570            if let Some((requested, slot)) = sess_capture.as_mut() {
8571                if *requested == Some(prompt.len()) && slot.is_empty() {
8572                    debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
8573                    if let Ok(snap) = cache.snapshot(e) {
8574                        slot.push(SpecBoundaryCapture {
8575                            snap,
8576                            pos: prompt.len(),
8577                            logits: prime_logits.clone(),
8578                            last_h: prompt_h
8579                                .as_ref()
8580                                .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
8581                                .unwrap_or_default(),
8582                        });
8583                    }
8584                }
8585            }
8586        }
8587        // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
8588        // prime-subtraction hack.
8589        crate::PRIME_NANOS.store(
8590            t_prime.elapsed().as_nanos() as u64,
8591            std::sync::atomic::Ordering::Relaxed,
8592        );
8593
8594        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
8595        // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
8596        // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
8597        let host_embd = spec_host_embd();
8598        let embd_gpu = if host_embd {
8599            None
8600        } else {
8601            Some(
8602                self.embd_gpu
8603                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
8604            )
8605        };
8606        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
8607        if host_embd {
8608            eprintln!(
8609                "[spec] host-row embedding: {} bytes kept off HBM",
8610                self.embd.raw.len()
8611            );
8612        }
8613        let mut out: Vec<u32> = Vec::with_capacity(max_new);
8614        let mut total_drafted = 0usize;
8615        let mut total_accepted = 0usize;
8616
8617        // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
8618        // The sampler config, the session's Philox counters and the penalty window are parsed
8619        // HERE, above the boundary-token selection, because the boundary token must be drawn
8620        // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
8621        // selection, which is the whole mechanical reason the boundary token was an argmax:
8622        // the sampler state was not in scope yet. Nothing here depends on the round loop, so
8623        // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
8624        // below takes the argmax path it always took).
8625        // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
8626        // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
8627        // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
8628        // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
8629        let sp = sampling.unwrap_or_else(|| SpecSampling {
8630            temp: std::env::var("MEMRA_SPEC_TEMP")
8631                .ok()
8632                .and_then(|v| v.parse().ok())
8633                .unwrap_or(0.0),
8634            seed: std::env::var("MEMRA_SEED")
8635                .ok()
8636                .and_then(|v| v.parse().ok())
8637                .unwrap_or(42),
8638            top_k: std::env::var("MEMRA_TOP_K")
8639                .ok()
8640                .and_then(|v| v.parse().ok())
8641                .unwrap_or(0),
8642            top_p: std::env::var("MEMRA_TOP_P")
8643                .ok()
8644                .and_then(|v| v.parse().ok())
8645                .unwrap_or(1.0),
8646            min_p: std::env::var("MEMRA_MIN_P")
8647                .ok()
8648                .and_then(|v| v.parse().ok())
8649                .unwrap_or(0.0),
8650            penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
8651                .ok()
8652                .and_then(|v| v.parse().ok())
8653                .unwrap_or(0),
8654            penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
8655                .ok()
8656                .and_then(|v| v.parse().ok())
8657                .unwrap_or(1.0),
8658            penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
8659                .ok()
8660                .and_then(|v| v.parse().ok())
8661                .unwrap_or(0.0),
8662            penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
8663                .ok()
8664                .and_then(|v| v.parse().ok())
8665                .unwrap_or(0.0),
8666        });
8667        let (sp_temp, sp_seed) = (sp.temp, sp.seed);
8668        let sampled = sp_temp > 0.0;
8669        // Counters resume from the session (burst continuity: randomness must never repeat
8670        // across generate_spec_session calls); one-shot callers start at (0,0). Read through
8671        // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
8672        let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
8673        let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
8674        // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
8675        // for the penalized+filtered target). History = generated tokens, host-tracked window.
8676        let pen_on = sampled
8677            && sp.penalty_last_n > 0
8678            && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
8679        // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
8680        // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
8681        // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
8682        // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
8683        // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
8684        // which is what the API contract says and what the plain sampler's own `history` does.
8685        // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
8686        let mut pen_hist: Vec<u32> = if pen_on {
8687            let sess_hist: &[u32] = if spec_pen_session_on() {
8688                sess_tail
8689                    .as_ref()
8690                    .map(|(c, ..)| c.as_slice())
8691                    .unwrap_or(&[])
8692            } else {
8693                &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
8694            };
8695            pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
8696        } else {
8697            Vec::new()
8698        };
8699        // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
8700        // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
8701        // request's own filtered/penalized target through the session's Philox stream
8702        // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
8703        // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
8704        // Emit it, then FEED it to establish the loop invariant below.
8705        // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
8706        // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
8707        // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
8708        // prompt's last logits (plain constrained-greedy identity); a continuation without
8709        // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
8710        // worker never resumes constrained sessions from the pool, so this cannot fire).
8711        if let Some(c) = constraint.as_deref_mut() {
8712            if continuation && carried_pending.is_none() {
8713                return Err("constrained spec continuation requires a carried pending \
8714                            (pool resume is unconstrained-only)"
8715                    .into());
8716            }
8717            if !continuation {
8718                c.mask_logits(&mut prime_logits)
8719                    .map_err(|e2| format!("constraint: {e2}"))?;
8720            }
8721        }
8722        let mut last_token = if let Some(b) = carried_pending {
8723            b
8724        } else if continuation {
8725            // A continuation's boundary token was DRAWN by the burst that stashed it (the
8726            // session tail below), or by `spec_session_from_restored` for a converted
8727            // prefix-cache hit — in both cases from the correct logits row with this same
8728            // session's Philox stream, which is why it can be consumed here as-is.
8729            sess_tail.as_ref().unwrap().2.unwrap()
8730        } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
8731            sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
8732        } else {
8733            // greedy (byte contract), the rollback door, or constrained (masked-argmax
8734            // identity — the worker routes sampled+constrained to the plain path, and this
8735            // function refuses the combination outright above).
8736            argmax(&prime_logits) as u32
8737        };
8738        if pen_on {
8739            // The boundary token is a GENERATED token: the plain sampler `accept()`s every
8740            // emitted token into its penalty history, and pre-lane the burst's first token
8741            // was invisible to penalties forever (never pushed, and never in `committed`
8742            // until this burst's tail). Covers the carry/continuation seeds too — neither is
8743            // in `committed` yet.
8744            pen_hist.push(last_token);
8745        }
8746        if carried_pending.is_none() {
8747            out.push(last_token);
8748            // grammar advances with every emitted token (carried pendings were consumed
8749            // by the burst that emitted them).
8750            if let Some(c) = constraint.as_deref_mut() {
8751                c.consume(last_token)
8752                    .map_err(|e2| format!("constraint: {e2}"))?;
8753            }
8754        }
8755        if continuation {
8756            // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
8757            // overhang so the chain's first append lands at slot base (== committed.len()).
8758            scratch.set_len(e, base)?;
8759        }
8760        // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
8761        // concatenating to the full `out`). Called after the prime's first token and after each
8762        // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
8763        // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
8764        // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
8765        fn flush_commit(
8766            cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
8767            out: &[u32],
8768            flushed: &mut usize,
8769        ) -> bool {
8770            if let Some(f) = cb.as_mut() {
8771                let keep = f(&out[*flushed..]);
8772                *flushed = out.len();
8773                keep
8774            } else {
8775                true
8776            }
8777        }
8778        keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
8779        // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
8780        // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
8781        // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
8782        // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
8783        // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
8784        // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
8785        // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
8786        // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
8787        // those, so their residual mass is p(x), correct by construction).
8788        let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
8789            match &mtp.d2t {
8790                Some(map) => Some(e.htod_u32_v(map)?),
8791                None => None,
8792            }
8793        } else {
8794            None
8795        };
8796        let mut q_full_buf: Option<CudaSlice<f32>> = None;
8797        // host Philox4x32-10 (mirrors spec_sample.cu; independent stream via ctr_lo tag)
8798        let host_u01 = |seed: u64, ctr: u32| -> f32 {
8799            let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
8800            let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
8801            let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
8802            for _ in 0..10 {
8803                let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
8804                let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
8805                let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
8806                c0 = n0;
8807                c1 = n1;
8808                c2 = n2;
8809                c3 = n3;
8810                k0 = k0.wrapping_add(0x9E3779B9);
8811                k1 = k1.wrapping_add(0xBB67AE85);
8812            }
8813            (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
8814        };
8815        let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
8816        let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
8817        let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
8818        let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
8819        let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
8820        let mut pen_hist_d: Option<CudaSlice<u32>> = None;
8821        let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
8822        // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
8823        // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
8824        // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
8825        let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
8826        let t_ent = std::time::Instant::now();
8827
8828        // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
8829        // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
8830        // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
8831        // the one that matters (a history-rewriting client mutates what the session GENERATED,
8832        // so the next turn's prompt agrees with this one up to exactly here).
8833        //
8834        // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
8835        // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
8836        // hold exactly `base + prompt.len()` rows and nothing generated.
8837        //
8838        // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
8839        // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
8840        // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
8841        // `<think>` block the client strips, so every later turn's diff diverged exactly one
8842        // token below the checkpoint and affinity declined 100% of the time. Measured on the
8843        // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
8844        // whole mechanism inert while looking, from the outside, like a working
8845        // correctness-declines-safely path — hence the decline log carries the offsets.
8846        //
8847        // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
8848        // state (the reason a spec session could not rewind before). The draft scratch needs no
8849        // copy: rows below the boundary are rewritten by the next turn's own fill.
8850        //
8851        // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
8852        // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
8853        // checkpoint rather than replacing it with a strictly worse one.
8854        //
8855        // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
8856        // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
8857        // fail the burst that is already running — so the error is swallowed, loud only under
8858        // MEMRA_DEBUG_SPEC.
8859        //
8860        // STABLE-BOUNDARY OVERRIDE (lane/frspec-multiturn-cache, 2026-08-21): the prompt-end
8861        // posture above was DISPROVED for the think-posture template class — the prompt's own
8862        // tail is the live generation header (`<|im_start|>assistant\n<think>\n`) that the
8863        // next turn's re-render replaces, so the diff diverged a couple tokens BELOW the
8864        // checkpoint and affinity declined 100% of multi-turn agent traffic (the same class
8865        // the plain tier fixed on 2026-08-09 via `plain_checkpoint_boundary`; the port to the
8866        // spec tier is this lane). When the worker armed `ckpt_at`, the capture happened at
8867        // that stop inside the prime above (`ckpt_early`) and is installed here instead;
8868        // capture-attempted-but-failed clears the slot exactly like the legacy arm.
8869        if let Some(slot) = sess_ckpt_slot {
8870            if let Some(early) = ckpt_early {
8871                if early.is_none() && std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
8872                    eprintln!(
8873                        "[spec] stable-boundary turn checkpoint skipped; \
8874                               next turn re-primes in full"
8875                    );
8876                }
8877                *slot = early;
8878            } else if !continuation {
8879                let pos = cache.pos;
8880                debug_assert_eq!(
8881                    pos,
8882                    base + prompt.len(),
8883                    "turn checkpoint must sit at the prompt end, before the init feed"
8884                );
8885                let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
8886                    if let Some(ph) = &prompt_h {
8887                        // hidden of the LAST primed row = the predecessor anchor at this
8888                        // boundary (exactly what a fresh prime of committed[..pos] leaves in
8889                        // last_h, and what the next prime's fill reads for its first row).
8890                        let np = prompt.len();
8891                        e.uninit(n_embd).and_then(|mut a| {
8892                            e.copy_view_into(
8893                                &mut a,
8894                                0,
8895                                &ph.slice((np - 1) * n_embd..np * n_embd),
8896                                n_embd,
8897                            )?;
8898                            Ok(a)
8899                        })
8900                    } else {
8901                        Err("no prompt hiddens".into())
8902                    };
8903                match (cache.snapshot(e), anchor) {
8904                    (Ok(snap), Ok(last_h)) => {
8905                        *slot = Some(SpecCheckpoint { snap, pos, last_h });
8906                    }
8907                    (s, a) => {
8908                        *slot = None; // a stale checkpoint would rewind to the WRONG boundary
8909                        if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
8910                            let err = s
8911                                .err()
8912                                .map(|e| e.to_string())
8913                                .or_else(|| a.err().map(|e| e.to_string()))
8914                                .unwrap_or_default();
8915                            eprintln!(
8916                                "[spec] turn checkpoint skipped ({err}); \
8917                                       next turn re-primes in full"
8918                            );
8919                        }
8920                    }
8921                }
8922            }
8923        }
8924        // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
8925        // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
8926        // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
8927        // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
8928        let mut last_pred = 0u32;
8929        let mut last_col_logits: Option<CudaSlice<f32>> = None;
8930        // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
8931        // recompute in the grammar-truncation walk — retained host-side, round 0 only.
8932        let mut init_logits_host: Option<Vec<f32>> = None;
8933        let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
8934            let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
8935            last_pred = argmax(&init_logits) as u32;
8936            if constraint.is_some() {
8937                init_logits_host = Some(init_logits.clone());
8938            }
8939            // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
8940            if sampled {
8941                last_col_logits = Some(e.htod(&init_logits)?);
8942            }
8943            h
8944        } else {
8945            // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
8946            let lh = sess_tail
8947                .as_ref()
8948                .unwrap()
8949                .1
8950                .as_ref()
8951                .expect("pending carry requires last_h");
8952            e.clone_dtod(lh)?
8953        };
8954        let t_init = t_ent.elapsed();
8955        let mut last_col_stats: Option<(f32, f32, f32)> = None;
8956        // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
8957        // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
8958        // stable pointer for the graph-draft round-start copy.
8959        let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
8960        // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
8961        // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
8962        // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
8963        // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
8964        // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
8965        // overwritten below).
8966        let mut fill_prev = e.clone_dtod(&h_seed0)?;
8967        {
8968            if let Some(ph) = &prompt_h {
8969                let np = prompt.len();
8970                e.copy_view_into(
8971                    &mut h_seed_buf,
8972                    0,
8973                    &ph.slice((np - 1) * n_embd..np * n_embd),
8974                    n_embd,
8975                )?;
8976            } else if continuation {
8977                if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
8978                    if let Some(lh) = lh.as_ref() {
8979                        e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
8980                    }
8981                }
8982            }
8983        }
8984        // Persistent device prediction slots for the accept walk (max k+1 verify columns).
8985        let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
8986
8987        let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
8988        let fork_mode = OptiForkGateMode::configured();
8989        // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
8990        // the end. Metric normalization vs the reference engine: BOTH engines count
8991        // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
8992        // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
8993        let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
8994        let mut st_drafted = vec![0usize; k];
8995        let mut st_accepted = vec![0usize; k];
8996        let mut st_len_hist = vec![0usize; k + 1];
8997        let mut st_full = 0usize;
8998        // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
8999        // stop the draft chain early when the head's softmax confidence in its own pick drops
9000        // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
9001        static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
9002        let p_min = *PMIN.get_or_init(|| {
9003            std::env::var("MEMRA_SPEC_PMIN")
9004                .ok()
9005                .and_then(|v| v.parse().ok())
9006                .unwrap_or(0.0)
9007        });
9008        // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
9009        // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
9010        // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
9011        // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
9012        // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
9013        // verify batch is not); the j==0 exemption stays for pending-less rounds.
9014        let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
9015            .map(|v| v == "1")
9016            .unwrap_or(false);
9017
9018        // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
9019        // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
9020        // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
9021        // cuBLAS path in an exotic head) falls back to the eager draft chain.
9022        // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
9023        // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
9024        // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
9025        // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
9026        // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
9027        // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
9028        // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
9029        // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
9030        let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
9031            Some(c) => c,
9032            None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
9033        };
9034        // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
9035        // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
9036        if sampled && dctx.g_q.len() < d_vocab {
9037            dctx.g_q = e.zeros(d_vocab)?;
9038            dctx.g_perturb = e.zeros(d_vocab)?;
9039        }
9040        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
9041        // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
9042        // truncation (the correctness backstop) stops cutting every tight-schema round.
9043        // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
9044        // shape, so a parked graph of the other shape is dropped and recaptured.
9045        let dmask_on = constraint
9046            .as_deref()
9047            .is_some_and(|c| c.draft_mask_enabled());
9048        let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
9049        if dmask_on && dctx.g_dmask.len() < dmask_words {
9050            dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
9051            dctx.graph = None; // the old capture baked the old (or no) mask pointer
9052            dctx.failed.clear_greedy();
9053            dctx.keeper.clear();
9054        }
9055        if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
9056            dctx.graph = None;
9057            dctx.failed.clear_greedy();
9058            dctx.keeper.clear();
9059        }
9060        if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
9061            let DraftGraphCtx {
9062                g_tok,
9063                g_pos,
9064                g_seed,
9065                g_p,
9066                g_dmask,
9067                ..
9068            } = &mut dctx;
9069            // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
9070            // host uploads the position's real words, so the warmups stay grammar-free.
9071            if dmask_on {
9072                e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
9073            }
9074            let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
9075            // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
9076            // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
9077            // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
9078            // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
9079            // passes (and, in serve, other sessions) recycle those addresses and the replay then
9080            // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
9081            let cap_res = e.capture_graph_retained(|e| {
9082                self.mtp_head_forward_cap(
9083                    e,
9084                    mtp,
9085                    g_tok,
9086                    g_pos,
9087                    g_seed,
9088                    g_p,
9089                    &mut *scratch,
9090                    p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
9091                    true,
9092                    embd_gpu.expect("graph draft requires resident embedding"),
9093                    embd_qt,
9094                    embd_rb,
9095                    d_vocab,
9096                    None,
9097                    None,
9098                    if dmask_on {
9099                        Some((g_dmask_ro, dmask_words))
9100                    } else {
9101                        None
9102                    },
9103                )
9104            });
9105            match cap_res {
9106                Ok((g, keep)) => {
9107                    scratch.set_len(e, base)?;
9108                    dctx.graph = Some(g);
9109                    dctx.graph_masked = dmask_on;
9110                    dctx.keeper = keep;
9111                }
9112                Err(err) => {
9113                    scratch.set_len(e, base)?;
9114                    // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
9115                    // silent. Once per flip — mark returns None on an already-failed ctx.
9116                    if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
9117                        eprintln!("{line}");
9118                    }
9119                }
9120            }
9121        }
9122        // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
9123        // graph object, built only when sampled && graph-eligible — the greedy capture above is
9124        // untouched (and skipped when sampled: its graph would never be launched). Same head
9125        // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
9126        // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
9127        // once per round); the raw head logits land in the persistent g_q for the host's
9128        // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
9129        // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
9130        // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
9131        // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
9132        // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
9133        // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
9134        // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
9135        // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
9136        // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
9137        // this compare misses at most ONCE per resumed request — the first burst recaptures
9138        // and every later burst in that request replays. A client that wants the parked graph
9139        // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
9140        // stable across its whole conversation.
9141        // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
9142        // softmax — it can hold neither per-row filter stats nor the varying penalty history.
9143        // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
9144        // force the eager draft (which computes stats/penalties per row).
9145        // KEY THE WHOLE REGIME, not just the baked constants (lane/graph-s-key-exactness-
9146        // 20260819). `s_key` used to be `(seed, temp, k)`; the filters and penalties were left
9147        // out, so a filtered request resuming a session that parked a PURE-TEMP graph kept it —
9148        // and the launch site never re-asked `pure_temp`. See [`SampledGraphKey`] for what that
9149        // costs (an unconditional accept of out-of-head draft tokens, i.e. an exactness bug on
9150        // the request shape the vendor-default flip makes the majority).
9151        let s_key = SampledGraphKey::new(sp_seed, sp_temp, k, sp.top_k, sp.top_p, sp.min_p, pen_on);
9152        let pure_temp = s_key.pure_temp();
9153        if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
9154            dctx.graph_s = None;
9155            dctx.failed.clear_sampled();
9156            dctx.s_key = None;
9157            dctx.q_slots.clear();
9158            dctx.keeper_s.clear();
9159        }
9160        if graph_draft
9161            && sampled
9162            && pure_temp
9163            && dctx.graph_s.is_none()
9164            && !dctx.failed.sampled_failed()
9165        {
9166            let DraftGraphCtx {
9167                g_tok,
9168                g_pos,
9169                g_seed,
9170                g_p,
9171                g_ctr,
9172                g_perturb,
9173                g_q,
9174                ..
9175            } = &mut dctx;
9176            // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
9177            let cap_res = e.capture_graph_retained(|e| {
9178                self.mtp_head_forward_cap(
9179                    e,
9180                    mtp,
9181                    g_tok,
9182                    g_pos,
9183                    g_seed,
9184                    g_p,
9185                    &mut *scratch,
9186                    p_min > 0.0,
9187                    true,
9188                    embd_gpu.expect("graph draft requires resident embedding"),
9189                    embd_qt,
9190                    embd_rb,
9191                    d_vocab,
9192                    Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
9193                    None,
9194                    None, // constrained spec is greedy-only — sampled never carries a hook
9195                )
9196            });
9197            match cap_res {
9198                Ok((g, keep)) => {
9199                    scratch.set_len(e, base)?;
9200                    for _ in 0..k {
9201                        dctx.q_slots.push(e.zeros(d_vocab)?);
9202                    }
9203                    dctx.graph_s = Some(g);
9204                    dctx.s_key = Some(s_key);
9205                    dctx.keeper_s = keep;
9206                }
9207                Err(err) => {
9208                    scratch.set_len(e, base)?;
9209                    // LOUD flip (audit Q2): same contract as the greedy capture above.
9210                    if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
9211                        eprintln!("{line}");
9212                    }
9213                }
9214            }
9215        }
9216        // ---- EXACTNESS GUARD, the enforceable half (lane/graph-s-key-exactness-20260819) ----
9217        // With the filters and penalties in `s_key`, a graph that SURVIVED the drop above was
9218        // captured under this request's exact regime, and capture requires `pure_temp` — so a
9219        // parked graph implies `pure_temp`. That implication is the whole exactness argument for
9220        // the graph arm, so it is asserted here rather than assumed: a future change that widens
9221        // the capture condition, narrows the key, or copies a `DraftGraphCtx` across regimes
9222        // fails LOUDLY at this line instead of silently drafting from the raw softmax while the
9223        // verify applies filter stats. Release builds refuse the graph (drop it, draft eager)
9224        // rather than launching it; the launch site re-tests `pure_temp` independently.
9225        if sampled && !pure_temp && dctx.graph_s.is_some() {
9226            debug_assert!(
9227                false,
9228                "sampled draft graph parked under {:?} survived into a FILTERED request \
9229                 (top_k={} top_p={} min_p={} pen_on={}): the in-graph chain draws from the RAW \
9230                 softmax, so the verify's filtered q would test a distribution the draft was \
9231                 never sampled from",
9232                dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
9233            );
9234            eprintln!(
9235                "[spec] BUG: dropping a parked sampled draft graph that outlived its capture \
9236                 regime (s_key={:?}, request top_k={} top_p={} min_p={} pen_on={}); drafting \
9237                 EAGER — the key must carry every field that shapes q",
9238                dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
9239            );
9240            dctx.graph_s = None;
9241            dctx.s_key = None;
9242            dctx.q_slots.clear();
9243            dctx.keeper_s.clear();
9244        }
9245        // SKEY PROBE (MEMRA_SKEY_PROBE=1): the burst-entry facts the reachability question turns
9246        // on — is this request sampled, is it in the pure-temp regime the sampled graph is only
9247        // legal in, and is a graph PARKED from an earlier request of the same session? The launch
9248        // arms below print which chain actually ran, so the probe never restates the condition.
9249        if skey_probe() {
9250            eprintln!(
9251                "[skey] burst sampled={} pure_temp={} temp={} top_k={} top_p={} min_p={} \
9252                 pen_on={} k={} graph_draft={} graph_s_parked={} s_key_parked={:?}",
9253                sampled as u8,
9254                pure_temp as u8,
9255                sp_temp,
9256                sp.top_k,
9257                sp.top_p,
9258                sp.min_p,
9259                pen_on as u8,
9260                k,
9261                graph_draft as u8,
9262                dctx.graph_s.is_some() as u8,
9263                dctx.s_key,
9264            );
9265        }
9266        let t_cap = t_ent.elapsed();
9267        // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
9268        // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
9269        // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
9270        // fill: the first chain step processes it and appends its entry at slot prompt.len().
9271        if let Some(ph) = &prompt_h {
9272            // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
9273            // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
9274            // global positions [base..base+tp). Fresh call: base==0, identical to before.
9275            scratch.set_len(e, base)?;
9276            // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
9277            // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
9278            // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
9279            // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
9280            let tp = prompt.len();
9281            let fill_chunk: usize = if crate::cache::swa_ring_on() {
9282                crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
9283            } else {
9284                // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
9285                // meaning one monolithic fill.
9286                std::env::var("MEMRA_PRIME_CHUNK")
9287                    .ok()
9288                    .and_then(|v| v.parse().ok())
9289                    .unwrap_or(4096)
9290            };
9291            let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
9292            let mut start = 0usize;
9293            while start < tp {
9294                let end = (start + fill_chunk).min(tp);
9295                let tc = end - start;
9296                {
9297                    // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
9298                    // reference engine's initial pending-h is zeroed too); a session turn's row 0
9299                    // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
9300                    // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
9301                    let mut phs = e.zeros(tc * n_embd)?;
9302                    let (src_lo, dst_off) = if start == 0 {
9303                        (0, n_embd)
9304                    } else {
9305                        ((start - 1) * n_embd, 0)
9306                    };
9307                    let n_copy = if start == 0 {
9308                        (tc - 1) * n_embd
9309                    } else {
9310                        tc * n_embd
9311                    };
9312                    if start == 0 {
9313                        if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
9314                            if let Some(lh) = lh.as_ref() {
9315                                e.copy_into(&mut phs, 0, lh, n_embd)?;
9316                            }
9317                        }
9318                    }
9319                    if n_copy > 0 {
9320                        e.copy_view_into(
9321                            &mut phs,
9322                            dst_off,
9323                            &ph.slice(src_lo..src_lo + n_copy),
9324                            n_copy,
9325                        )?;
9326                    }
9327                    self.mtp_kv_fill(
9328                        e,
9329                        mtp,
9330                        &prompt[start..end],
9331                        &phs,
9332                        base + start,
9333                        &mut *scratch,
9334                        embd_dev,
9335                    )?;
9336                }
9337                start = end;
9338            }
9339        }
9340        // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
9341        // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
9342        // (=1 brackets the whole call in run_spec.rs, prime included.)
9343        if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
9344            unsafe extern "C" {
9345                fn cudaProfilerStart() -> i32;
9346            }
9347            unsafe {
9348                cudaProfilerStart();
9349            }
9350        }
9351        // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
9352        // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
9353        // consume each other's device outputs; the host drains the ring every M rounds. v1
9354        // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
9355        // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
9356        // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
9357        // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
9358        // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
9359        let stream_on = crate::spec::spec_stream()
9360            && !sampled
9361            && !spec_replay
9362            && constraint.is_none()
9363            && !session_mode
9364            && embd_gpu.is_some()
9365            && !crate::model::full_prec_enabled()
9366            && k + 2 < 96;
9367        let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
9368        let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
9369        if stream_on {
9370            let cap = e.capture_graph(|e| {
9371                for j in 0..k.max(1) {
9372                    self.mtp_head_forward_cap(
9373                        e,
9374                        mtp,
9375                        &mut dctx.g_tok,
9376                        &mut dctx.g_pos,
9377                        &mut dctx.g_seed,
9378                        &mut dctx.g_p,
9379                        &mut *scratch,
9380                        true,
9381                        true,
9382                        embd_gpu.expect("round stream requires resident embedding"),
9383                        embd_qt,
9384                        embd_rb,
9385                        d_vocab,
9386                        None,
9387                        Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
9388                        None, // round-stream requires constraint.is_none() (see stream_on)
9389                    )?;
9390                }
9391                Ok(())
9392            });
9393            match cap {
9394                Ok(g) => {
9395                    scratch.set_len(e, 0)?;
9396                    stream_graph = Some(g);
9397                }
9398                Err(err) => {
9399                    scratch.set_len(e, 0)?;
9400                    if debug_spec {
9401                        eprintln!("[spec] stream-graph capture failed ({err}); stream off");
9402                    }
9403                }
9404            }
9405        }
9406        let stream_active = stream_on && stream_graph.is_some();
9407        if debug_spec {
9408            eprintln!(
9409                "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
9410                crate::spec::spec_stream(),
9411                dctx.graph.is_some(),
9412                stream_graph.is_some()
9413            );
9414        }
9415        let t_v_s = k + 1;
9416        // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
9417        // module (extracted 2026-07-12; the gemma burst reuses them).
9418        let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
9419        let crate::round_stream::StreamBufs {
9420            mut vtok_d,
9421            mut brk_d,
9422            mut pend_d,
9423            last_pred_d,
9424            mut pos_ctr,
9425            mut pos_start_d,
9426            mut ring_d,
9427            acc_d: mut stream_acc,
9428            m_rounds,
9429            k: _,
9430        } = sb;
9431        let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
9432            Some(crate::round_stream::kv_len_ptr_table(
9433                e,
9434                cache,
9435                Some(&pos_ctr),
9436            )?)
9437        } else {
9438            None
9439        };
9440
9441        let t_fill = t_ent.elapsed();
9442        let mut round = 0usize;
9443        // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
9444        // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
9445        // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
9446        // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
9447        // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
9448        // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
9449        // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
9450        // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
9451        // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
9452        // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
9453        // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
9454        // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
9455        // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
9456        // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
9457        // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
9458        // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
9459        // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
9460        // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
9461        // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
9462        // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
9463        // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
9464        // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
9465        // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
9466        // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
9467        // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
9468        // K=1..8 self-consistency PASS both models with the law ON (exactness held).
9469        let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
9470        // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
9471        // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
9472        let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
9473            .ok()
9474            .and_then(|v| v.parse().ok());
9475        let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
9476            4
9477        } else if self.cfg.n_embd as usize >= 2500 {
9478            2
9479        } else {
9480            1
9481        };
9482        let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
9483        // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
9484        // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
9485        // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
9486        let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
9487            .ok()
9488            .and_then(|v| v.parse().ok())
9489            .unwrap_or(1024);
9490        let floor_at = |pos: usize| -> usize {
9491            if adapt_floor_env.is_some() || pos < floor_ctx {
9492                adapt_floor
9493            } else if adapt_floor >= 4 {
9494                1
9495            } else {
9496                adapt_floor
9497            }
9498        };
9499        // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
9500        // fixed-K default path is untouched by this whole block.
9501        let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
9502            .ok()
9503            .and_then(|v| v.parse().ok())
9504            .unwrap_or(7);
9505        let k_cap = k.min(cap_max).max(1);
9506        let mut kc = k_cap;
9507        let mut opti_fork: Option<OptiForkState> = None;
9508        let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
9509        if fork_mode != OptiForkGateMode::Disabled {
9510            let fence = crate::pp::pp_cuts(self.layers.len());
9511            let refusal = if !session_mode {
9512                Some("not-session")
9513            } else if k != 1 || adapt {
9514                Some("requires-fixed-k1")
9515            } else if sampled || constraint.is_some() || spec_replay {
9516                Some("sampled-constrained-or-replay")
9517            } else if pipe.is_some() {
9518                Some("two-session-pipeline")
9519            } else if !spec_devacc() {
9520                Some("requires-device-accept")
9521            } else if stream_active || crate::spec::spec_stream() {
9522                Some("round-stream")
9523            } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
9524                Some("swa-ring")
9525            } else if crate::pp::pp_host_bounce_active() {
9526                Some("host-bounce")
9527            } else if fork_mode == OptiForkGateMode::Controller
9528                && cache.recur.iter().any(Option::is_some)
9529            {
9530                Some("controller-requires-zero-recurrent-state")
9531            } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
9532                Some("requires-pp2")
9533            } else {
9534                None
9535            };
9536            if let Some(reason) = refusal {
9537                OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9538                eprintln!("[opti-fork] refused reason={reason}");
9539            } else {
9540                let fence = fence.expect("validated PP-2 fence");
9541                let rt = crate::pp::PpNRt::get(e)?;
9542                let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
9543                let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
9544                let primary_supported =
9545                    primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
9546                if !rt.cross_device() || !primary_supported {
9547                    OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9548                    eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
9549                } else {
9550                    // Both recurrent snapshots and both seed generations are allocated before
9551                    // the first fork, each through its owning PP stage. Allocation failure
9552                    // therefore happens before any optimistic state mutation can occur.
9553                    let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
9554                    let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
9555                    let fork = OptiForkState::new(
9556                        e,
9557                        cache,
9558                        fork_mode,
9559                        alternate_snapshot,
9560                        &h_seed_buf,
9561                        &fill_prev,
9562                        rt,
9563                        fence[1],
9564                        self.layers.len(),
9565                    )?;
9566                    eprintln!(
9567                        "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
9568                         payload_dev0={} payload_dev1={} q_threshold={:.3}",
9569                        fence[1],
9570                        fork.logical_payload_bytes[0],
9571                        fork.logical_payload_bytes[1],
9572                        fork.controller.map_or(0.0, |policy| policy.threshold),
9573                    );
9574                    fork_snapshot = Some(current_snapshot);
9575                    opti_fork = Some(fork);
9576                }
9577            }
9578        }
9579        // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
9580        // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
9581        let mut snap = match fork_snapshot {
9582            Some(snapshot) => snapshot,
9583            None => cache.snapshot(e)?,
9584        };
9585        let mut carried_opti: Option<OptiControllerTicket> = None;
9586        // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
9587        // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
9588        let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
9589            Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
9590        } else {
9591            None
9592        };
9593        // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
9594        // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
9595        // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
9596        // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
9597        // pass of any kind). Verify still
9598        // checks every emitted token against the target -> exactness holds by construction; only
9599        // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
9600        // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
9601        // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
9602        let mut pending: Option<u32> = carried_pending;
9603        // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
9604        // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
9605        // the verify accept readback). Printed once at loop end via spec-stats.
9606        let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
9607        let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
9608        // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
9609        // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
9610        let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
9611        // grammar-truncation counters: how many rounds the verify-side cut fired and how many
9612        // already-verified tokens it threw away. THIS is the quantity draft masking targets.
9613        let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
9614        let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
9615        let mut ph_wait = 0f64;
9616        let mut ph_commit = 0f64;
9617        let mut ph_t = std::time::Instant::now();
9618        let mut ph_mark = |acc: &mut f64, on: bool| {
9619            if on {
9620                let now = std::time::Instant::now();
9621                *acc += (now - ph_t).as_secs_f64();
9622                ph_t = now;
9623            }
9624        };
9625        if let Some(p) = pipe {
9626            p.setup_end();
9627        }
9628        while keep_going && out.len() < max_new {
9629            // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
9630            // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
9631            if let (true, Some(sg), Some(ptrs)) = (
9632                stream_active && round >= 1 && pending.is_some(),
9633                &stream_graph,
9634                &stream_ptrs,
9635            ) {
9636                if debug_spec {
9637                    static ONCE: std::sync::Once = std::sync::Once::new();
9638                    ONCE.call_once(|| {
9639                        eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
9640                    });
9641                }
9642                e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
9643                e.set_u32_one(&mut pend_d, pending.unwrap())?;
9644                e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
9645                for _mi in 0..m_rounds {
9646                    e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
9647                    cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
9648                    e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
9649                    e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
9650                    e.u32_copy(&pend_d, &mut dctx.g_tok)?;
9651                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
9652                    sg.launch()?;
9653                    e.spec_assemble_verify(
9654                        &g_tokp2k,
9655                        &pend_d,
9656                        d2t_dev.as_ref(),
9657                        &mut vtok_d,
9658                        &mut brk_d,
9659                        p_min,
9660                        k,
9661                        pmin0,
9662                    )?;
9663                    let mut ck = VerifyCkpt::new(self.layers.len());
9664                    let dummy = vec![0u32; t_v_s];
9665                    let (tl_d, vx) = self.decode_step_t_core_stream(
9666                        e,
9667                        &dummy,
9668                        0,
9669                        &mut *cache,
9670                        embd_dev,
9671                        Some(&mut ck),
9672                        Some((&vtok_d, &pos_ctr)),
9673                        None,
9674                        None,
9675                        None,
9676                    )?;
9677                    for j in 0..t_v_s {
9678                        e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
9679                    }
9680                    e.spec_accept_greedy_dc(
9681                        &preds_d,
9682                        &vtok_d,
9683                        &last_pred_d,
9684                        &brk_d,
9685                        &mut stream_acc,
9686                    )?;
9687                    e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
9688                    e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
9689                    self.commit_verified_prefix_stream(
9690                        e,
9691                        &mut *cache,
9692                        &snap,
9693                        &ck,
9694                        &stream_acc,
9695                        1,
9696                        t_v_s,
9697                    )?;
9698                    e.spec_rollback_stream(
9699                        ptrs,
9700                        &pos_start_d,
9701                        &stream_acc,
9702                        1,
9703                        self.layers.len() + 1,
9704                    )?;
9705                    e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
9706                }
9707                e.stream().synchronize()?;
9708                let ring_h = e.dtoh_u32(&ring_d)?;
9709                let cnt = ring_h[0] as usize;
9710                for i in 0..cnt {
9711                    if out.len() < max_new {
9712                        out.push(ring_h[1 + i]);
9713                    }
9714                }
9715                let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
9716                for il in 0..self.layers.len() {
9717                    if let Some(kvl) = cache.kv[il].as_mut() {
9718                        kvl.len = pos_h;
9719                    }
9720                }
9721                cache.pos = pos_h;
9722                scratch.kv.len = pos_h;
9723                pending = Some(ring_h[cnt]); // last drained token = the live bonus
9724                last_token = ring_h[cnt];
9725                total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
9726                total_accepted += cnt.saturating_sub(m_rounds);
9727                if let Some(t) = sess_telem {
9728                    // totals only — the burst's per-round accept counts stayed on device
9729                    // (that is the point of the round-stream arm). pos_* untouched.
9730                    t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
9731                }
9732                round += m_rounds;
9733                // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
9734                keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
9735                continue;
9736            }
9737            let pipe_draft = match pipe {
9738                Some(p) => Some(p.draft_begin(round)?),
9739                None => None,
9740            };
9741            let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
9742            let mut current_opti = carried_opti.take();
9743            let mut fork_generation = if current_opti.is_none() && pending.is_some() {
9744                match opti_fork.as_mut() {
9745                    Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
9746                    None => None,
9747                    Some(_) => None,
9748                }
9749            } else {
9750                None
9751            };
9752            if current_opti.is_none() {
9753                if let Some(fork) = opti_fork.as_ref() {
9754                    opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
9755                } else {
9756                    cache.snapshot_into(e, &mut snap)?;
9757                }
9758            } else if snap.pos != pos {
9759                return Err(format!(
9760                    "optipipe carried snapshot pos {} != current pos {pos}",
9761                    snap.pos
9762                )
9763                .into());
9764            } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
9765            ph_mark(&mut ph_rest, phase_on);
9766
9767            // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
9768            // p-min semantics (both paths): stop the chain early when the head's confidence in
9769            // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
9770            // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
9771            let base0 = if pending.is_some() { 1usize } else { 0usize };
9772            // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
9773            // accepted run + 1 (the gemma law — see the setup block above the loop).
9774            let k_this = if adapt { kc } else { k };
9775            let mut draft: Vec<u32> = Vec::with_capacity(k);
9776            let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
9777            let mut controller_draft_prob: Option<f32> = None;
9778            let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
9779            if let Some(ticket) = current_opti.as_mut() {
9780                let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
9781                if ticket.verify_tokens[0] != carried_pending {
9782                    return Err(format!(
9783                        "optipipe carried pending mismatch: ticket={} live={carried_pending}",
9784                        ticket.verify_tokens[0],
9785                    )
9786                    .into());
9787                }
9788                draft.push(ticket.verify_tokens[1]);
9789                controller_draft_prob = Some(ticket.draft_prob);
9790                controller_eager_state = ticket
9791                    .take_eager_seed()
9792                    .map(|seed| (ticket.verify_tokens[1], seed));
9793            } else {
9794                // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
9795                // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
9796                // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
9797                // rejected drafts and p-min extras via the len mechanism).
9798                scratch.set_len(e, pos + base0 - 1)?;
9799                if pen_on {
9800                    // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
9801                    // device dedup: `penalty_last_n` is usize::MAX for any serve request with
9802                    // a penalty, so without the cap this grew with the whole session.
9803                    let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
9804                    let w0 = pen_hist.len().saturating_sub(win);
9805                    pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
9806                }
9807                if sampled {
9808                    draft_logits.clear();
9809                    draft_stats.clear();
9810                }
9811                // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
9812                // position's mask is computed on that clone and advanced by the PROPOSED token. The
9813                // real state moves only on emission (verify's job), so the emitted stream is
9814                // unchanged — the mask only removes tokens the verify would have truncated anyway.
9815                let mut dmask_live = dmask_on;
9816                if dmask_live {
9817                    let t_c = std::time::Instant::now();
9818                    constraint
9819                        .as_deref_mut()
9820                        .unwrap()
9821                        .draft_begin()
9822                        .map_err(|e2| format!("constraint: {e2}"))?;
9823                    dm_clone_ns += t_c.elapsed().as_nanos();
9824                    dm_rounds += 1;
9825                }
9826                if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
9827                    // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
9828                    // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
9829                    // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
9830                    e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
9831                    e.set_u32_one(&mut dctx.g_tok, last_token)?;
9832                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
9833                    for j in 0..k_this {
9834                        // per-position mask upload (contents only — the graph's baked pointer is
9835                        // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
9836                        // mask node degrades to a no-op ban instead of needing a second graph.
9837                        if dmask_live
9838                            && !upload_draft_mask(
9839                                e,
9840                                constraint.as_deref_mut().unwrap(),
9841                                &mut dctx.g_dmask,
9842                                mtp.d2t.as_ref(),
9843                                d_vocab,
9844                                dmask_words,
9845                            )?
9846                        {
9847                            // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
9848                            // genuinely miss the legal set): neutralize the captured mask node and
9849                            // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
9850                            e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
9851                            dmask_live = false;
9852                        }
9853                        gr.launch()?;
9854                        scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
9855                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
9856                        // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
9857                        // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
9858                        // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
9859                        // replay's embed node, and the MMU fault kills the CUDA context for the
9860                        // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
9861                        // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
9862                        // buffer (g_seed = the verify-side handoff vs head-side compute).
9863                        if (idx as usize) >= d_vocab {
9864                            // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
9865                            // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
9866                            // seed, untouched since the round-start copy — the pair discriminates
9867                            // "seed arrived poisoned" from "head forward produced NaN".
9868                            let seed_h = e.dtoh(&dctx.g_seed)?;
9869                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
9870                            let in_h = e.dtoh(&h_seed_buf)?;
9871                            let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
9872                            return Err(format!(
9873                                "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
9874                             round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
9875                             round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
9876                             the embed row (#87 trap)"
9877                            )
9878                            .into());
9879                        }
9880                        // trimmed draft vocab -> target token id (identity when no d2t map)
9881                        let d = match &mtp.d2t {
9882                            Some(map) => map[idx as usize],
9883                            None => idx,
9884                        };
9885                        let draft_p = if p_min > 0.0
9886                            || opti_fork
9887                                .as_ref()
9888                                .is_some_and(|fork| fork.controller.is_some())
9889                        {
9890                            Some(e.dtoh(&dctx.g_p)?[0])
9891                        } else {
9892                            None
9893                        };
9894                        if j == 0 {
9895                            controller_draft_prob = draft_p;
9896                        }
9897                        if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
9898                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
9899                                break;
9900                            }
9901                        }
9902                        draft.push(d);
9903                        // with a trimmed head the NEXT embed must read the TARGET id, not the draft
9904                        // index the argmax wrote — patch the persistent token buffer (4B htod).
9905                        if d != idx {
9906                            e.set_u32_one(&mut dctx.g_tok, d)?;
9907                        }
9908                        // advance the SPECULATIVE state with the proposal; a dead chain drops to
9909                        // unmasked drafting for the remaining positions (verify still arbitrates).
9910                        // speculative advance; a chain the grammar can no longer follow (EOS
9911                        // proposed) ends here. The captured mask node always runs, so a dead chain
9912                        // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
9913                        if dmask_live
9914                            && !constraint
9915                                .as_deref_mut()
9916                                .unwrap()
9917                                .draft_advance(d)
9918                                .map_err(|e2| format!("constraint: {e2}"))?
9919                        {
9920                            e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
9921                            break;
9922                        }
9923                    }
9924                // PURE-TEMP RE-TEST (lane/graph-s-key-exactness-20260819): the sampled graph is
9925                // legal ONLY in the regime it was captured in. The condition used to read
9926                // `(sampled, &dctx.graph_s)` and trusted `s_key` to have dropped anything else —
9927                // which it could not, because the key omitted the filters. Both halves are now
9928                // enforced: the key drops a stale graph, and this site refuses to launch one.
9929                } else if let (true, Some(gr)) = (sampled && pure_temp, &dctx.graph_s) {
9930                    if skey_probe() {
9931                        eprintln!(
9932                            "[skey] chain=graph_s round={round} pure_temp={} top_k={} \
9933                             top_p={} min_p={} s_key_parked={:?}",
9934                            pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
9935                        );
9936                    }
9937                    // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
9938                    // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
9939                    // and decides the break. Event-counter continuity: g_ctr is host-seeded to
9940                    // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
9941                    // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
9942                    // stream. Host sctr advances in lockstep (computed, no readback needed).
9943                    e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
9944                    e.set_u32_one(&mut dctx.g_tok, last_token)?;
9945                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
9946                    e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
9947                    for j in 0..k_this {
9948                        gr.launch()?;
9949                        scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
9950                        sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
9951                        // counts the p-min-discarded token too)
9952                        // q retention: ONE async D2D of the persistent head-logits buffer into this
9953                        // round's slot j (stream-ordered after the replay, before the next one).
9954                        e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
9955                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
9956                        // #87 SENTINEL TRAP (see the greedy graph arm above).
9957                        if (idx as usize) >= d_vocab {
9958                            let seed_h = e.dtoh(&dctx.g_seed)?;
9959                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
9960                            return Err(format!(
9961                                "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
9962                             {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
9963                             {seed_nan}/{n_embd} — refusing to dereference the embed row \
9964                             (#87 trap)"
9965                            )
9966                            .into());
9967                        }
9968                        let d = match &mtp.d2t {
9969                            Some(map) => map[idx as usize],
9970                            None => idx,
9971                        };
9972                        draft_idx.push(idx);
9973                        if p_min > 0.0 {
9974                            let p = e.dtoh(&dctx.g_p)?[0];
9975                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
9976                                break;
9977                            }
9978                        }
9979                        draft.push(d);
9980                        // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
9981                        if d != idx {
9982                            e.set_u32_one(&mut dctx.g_tok, d)?;
9983                        }
9984                    }
9985                    // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
9986                    // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
9987                    for j in 0..draft.len().max(draft_idx.len()) {
9988                        let rows0 = e.htod_i32(&[0])?;
9989                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
9990                        e.filter_stats(
9991                            &dctx.q_slots[j],
9992                            d_vocab,
9993                            &rows0,
9994                            &mut th_d,
9995                            &mut z_d,
9996                            &mut mx_d,
9997                            d_vocab,
9998                            1,
9999                            sp_temp,
10000                            sp.top_k,
10001                            sp.top_p,
10002                            sp.min_p,
10003                        )?;
10004                        draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
10005                    }
10006                } else {
10007                    if skey_probe() && sampled {
10008                        eprintln!(
10009                            "[skey] chain=eager round={round} pure_temp={} top_k={} \
10010                             top_p={} min_p={} s_key_parked={:?}",
10011                            pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
10012                        );
10013                    }
10014                    // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
10015                    let mut e_tok = last_token;
10016                    let mut d_seed = e.clone_dtod(&h_seed_buf)?;
10017                    for j in 0..k_this {
10018                        // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
10019                        // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
10020                        let mtp_pos = pos + base0 + j;
10021                        // draft-side grammar mask (eager twin of the graph arm's in-graph node).
10022                        // A position with no legal draft-vocab row drops to unmasked drafting for
10023                        // the rest of the chain (pre-lane behaviour; verify still arbitrates).
10024                        if dmask_live {
10025                            dmask_live = upload_draft_mask(
10026                                e,
10027                                constraint.as_deref_mut().unwrap(),
10028                                &mut dctx.g_dmask,
10029                                mtp.d2t.as_ref(),
10030                                d_vocab,
10031                                dmask_words,
10032                            )?;
10033                        }
10034                        let (dl_d, h_nextn) = self.mtp_head_forward_dev(
10035                            e,
10036                            mtp,
10037                            e_tok,
10038                            &d_seed,
10039                            &mut *scratch,
10040                            mtp_pos,
10041                            embd_dev,
10042                            if dmask_live {
10043                                Some((&dctx.g_dmask, dmask_words))
10044                            } else {
10045                                None
10046                            },
10047                        )?;
10048                        let tok_d = if sampled {
10049                            // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
10050                            // the filtered softmax (filters off => th=0, exact v1 semantics).
10051                            if perturb_buf.is_none() {
10052                                perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
10053                            }
10054                            let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
10055                            if pen_on {
10056                                let h = pen_hist_d.as_ref().unwrap();
10057                                let nh = h.len();
10058                                e.penalize_logits(
10059                                    &mut q_row,
10060                                    h,
10061                                    nh,
10062                                    sp.penalty_repeat,
10063                                    sp.penalty_freq,
10064                                    sp.penalty_present,
10065                                    d_vocab,
10066                                )?;
10067                            }
10068                            let rows0 = e.htod_i32(&[0])?;
10069                            let (mut th_d, mut z_d, mut mx_d) =
10070                                (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
10071                            e.filter_stats(
10072                                &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
10073                                1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
10074                            )?;
10075                            let (th, z, mx) =
10076                                (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
10077                            let pb = perturb_buf.as_mut().unwrap();
10078                            e.gumbel_perturb_filtered(
10079                                &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
10080                            )?;
10081                            sctr += 1;
10082                            draft_logits.push(q_row);
10083                            draft_stats.push((mx, th, z));
10084                            e.argmax_token_device(pb, d_vocab)?
10085                        } else {
10086                            e.argmax_token_device(&dl_d, d_vocab)?
10087                        };
10088                        let idx = e.dtoh_u32_one(&tok_d)?;
10089                        // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
10090                        // here because the eager chain's operands are all readable: dl_d (the head
10091                        // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
10092                        if (idx as usize) >= d_vocab {
10093                            let dl_h = e.dtoh(&dl_d)?;
10094                            let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
10095                            let seed_h = e.dtoh(&d_seed)?;
10096                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
10097                            return Err(format!(
10098                                "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
10099                             round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
10100                             step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
10101                             embed row (#87 trap)"
10102                            )
10103                            .into());
10104                        }
10105                        let d = match &mtp.d2t {
10106                            Some(map) => map[idx as usize],
10107                            None => idx,
10108                        };
10109                        if sampled {
10110                            draft_idx.push(idx);
10111                        }
10112                        let draft_p = if p_min > 0.0
10113                            || opti_fork
10114                                .as_ref()
10115                                .is_some_and(|fork| fork.controller.is_some())
10116                        {
10117                            let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
10118                            Some(e.dtoh(&p_d)?[0])
10119                        } else {
10120                            None
10121                        };
10122                        if j == 0 {
10123                            controller_draft_prob = draft_p;
10124                        }
10125                        if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
10126                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
10127                                break;
10128                            }
10129                        }
10130                        draft.push(d);
10131                        e_tok = d;
10132                        d_seed = h_nextn;
10133                        // speculative advance; a chain the grammar can no longer follow (EOS
10134                        // proposed) ends here — the prefix already proposed still rides verify.
10135                        if dmask_live
10136                            && !constraint
10137                                .as_deref_mut()
10138                                .unwrap()
10139                                .draft_advance(d)
10140                                .map_err(|e2| format!("constraint: {e2}"))?
10141                        {
10142                            break;
10143                        }
10144                    }
10145                    if opti_fork
10146                        .as_ref()
10147                        .is_some_and(|fork| fork.controller.is_some())
10148                    {
10149                        controller_eager_state = Some((e_tok, d_seed));
10150                    }
10151                }
10152            }
10153            let k_round = draft.len();
10154            if let Some(p) = pipe {
10155                p.draft_end(round);
10156            }
10157            drop(pipe_draft);
10158
10159            ph_mark(&mut ph_draft, phase_on);
10160            // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
10161            //         (committing its KV/recur inside the SAME weight read); drafts follow. ---
10162            let verify_tokens: Vec<u32> = match pending {
10163                Some(b) => {
10164                    let mut v = Vec::with_capacity(k_round + 1);
10165                    v.push(b);
10166                    v.extend_from_slice(&draft);
10167                    v
10168                }
10169                None => draft.clone(),
10170            };
10171            let base = if pending.is_some() { 1 } else { 0 };
10172            // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
10173            // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
10174            let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
10175                Some(ticket.take_ckpt())
10176            } else if spec_replay {
10177                None
10178            } else {
10179                Some(VerifyCkpt::new(self.layers.len()))
10180            };
10181            let controller_can_probe = base == 1
10182                && k_round == 1
10183                && out.len().saturating_add(2) < max_new
10184                && controller_draft_prob.is_some()
10185                && opti_fork
10186                    .as_ref()
10187                    .and_then(|fork| fork.controller.as_ref())
10188                    .is_some_and(|policy| !policy.breaker_tripped);
10189            let mut successor_attempt: Option<OptiControllerTicket> = None;
10190            let mut rejected_probe: Option<(f32, u32)> = None;
10191            let mut controller_prepared: Option<OptiControllerPrepared> = None;
10192            if controller_can_probe {
10193                // Prepare d2/q and, on admission, d3 before either current verify half is
10194                // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
10195                // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
10196                // the primary stream after N stage 1 would serialize the supposed pipeline.
10197                let eager_pos = scratch.kv.len + 1;
10198                let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
10199                    e,
10200                    mtp,
10201                    &mut dctx,
10202                    &mut *scratch,
10203                    d_vocab,
10204                    &mut controller_eager_state,
10205                    eager_pos,
10206                    embd_dev,
10207                )?;
10208                let first_probability = controller_draft_prob
10209                    .ok_or("optipipe controller probe lost first-token probability")?;
10210                let q_proxy = first_probability * pending_probability;
10211                OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10212                OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10213                let admitted = opti_fork
10214                    .as_ref()
10215                    .and_then(|fork| fork.controller.as_ref())
10216                    .ok_or("optipipe controller policy disappeared")?
10217                    .admit(q_proxy);
10218                if admitted {
10219                    OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10220                    let eager_pos = scratch.kv.len + 1;
10221                    let (optimistic_draft, optimistic_draft_probability) = self
10222                        .opti_controller_draft_step(
10223                            e,
10224                            mtp,
10225                            &mut dctx,
10226                            &mut *scratch,
10227                            d_vocab,
10228                            &mut controller_eager_state,
10229                            eager_pos,
10230                            embd_dev,
10231                        )?;
10232                    OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10233                    let eager_seed = controller_eager_state.take().map(|(token, seed)| {
10234                        debug_assert_eq!(token, optimistic_draft);
10235                        seed
10236                    });
10237                    controller_prepared = Some(OptiControllerPrepared {
10238                        verify_tokens: [optimistic_pending, optimistic_draft],
10239                        draft_prob: optimistic_draft_probability,
10240                        eager_seed,
10241                        q_proxy,
10242                        scratch_len: scratch.kv.len,
10243                    });
10244                } else {
10245                    OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10246                    OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10247                    rejected_probe = Some((q_proxy, optimistic_pending));
10248                    eprintln!(
10249                        "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
10250                        opti_fork
10251                            .as_ref()
10252                            .and_then(|fork| fork.controller.as_ref())
10253                            .expect("controller policy")
10254                            .threshold,
10255                    );
10256                }
10257            }
10258            let fork_attempt = match fork_generation.take() {
10259                Some(generation) if base == 1 && k_round == 1 => Some(generation),
10260                Some(generation) => {
10261                    opti_fork
10262                        .as_mut()
10263                        .expect("fork generation without fork state")
10264                        .retire(generation)?;
10265                    None
10266                }
10267                None => None,
10268            };
10269            let (tlogits_d, vx) = if let Some(p) = pipe {
10270                self.decode_step_t_core_pipelined(
10271                    e,
10272                    &verify_tokens,
10273                    pos,
10274                    &mut *cache,
10275                    embd_dev,
10276                    ckpt.as_mut(),
10277                    p,
10278                    round,
10279                )?
10280            } else if controller_can_probe {
10281                let fence = opti_fork
10282                    .as_ref()
10283                    .ok_or("optipipe controller probe lost fork state")?
10284                    .fence;
10285                let boundary = match current_opti.as_mut() {
10286                    Some(ticket) => ticket.take_boundary(),
10287                    None => self.verify_stage0_issue(
10288                        e,
10289                        &verify_tokens,
10290                        pos,
10291                        &mut *cache,
10292                        embd_dev,
10293                        ckpt.as_mut(),
10294                        None,
10295                        &fence,
10296                        Some(true),
10297                        None,
10298                    )?,
10299                };
10300                if let Some(prepared) = controller_prepared.take() {
10301                    let generation = {
10302                        let fork = opti_fork
10303                            .as_mut()
10304                            .ok_or("optipipe controller admission lost fork state")?;
10305                        let generation = fork.reserve_successor()?;
10306                        let rt = fork.rt;
10307                        let snapshot_fence = fork.fence;
10308                        opti_snapshot_one_stage_owned_into(
10309                            e,
10310                            cache,
10311                            rt,
10312                            &snapshot_fence,
10313                            0,
10314                            fork.successor_snapshot_mut(),
10315                        )?;
10316                        generation
10317                    };
10318                    let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
10319                    let successor_boundary = self.verify_stage0_issue(
10320                        e,
10321                        &prepared.verify_tokens,
10322                        pos + verify_tokens.len(),
10323                        &mut *cache,
10324                        embd_dev,
10325                        Some(&mut successor_ckpt),
10326                        None,
10327                        &fence,
10328                        Some(false),
10329                        None,
10330                    )?;
10331                    OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10332                    let fork = opti_fork
10333                        .as_ref()
10334                        .ok_or("optipipe controller ticket lost fork state")?;
10335                    successor_attempt = Some(fork.controller_ticket(
10336                        generation,
10337                        successor_boundary,
10338                        successor_ckpt,
10339                        prepared.verify_tokens,
10340                        prepared.draft_prob,
10341                        prepared.eager_seed,
10342                        prepared.q_proxy,
10343                        prepared.scratch_len,
10344                    ));
10345                    eprintln!(
10346                        "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
10347                         verify={:?}",
10348                        generation.id,
10349                        prepared.q_proxy,
10350                        fork.controller.expect("controller policy").threshold,
10351                        prepared.verify_tokens,
10352                    );
10353                }
10354                let result = self.verify_stage1_finish(
10355                    e,
10356                    boundary,
10357                    &mut *cache,
10358                    ckpt.as_mut(),
10359                    None,
10360                    &fence,
10361                    successor_attempt.is_none(),
10362                )?;
10363                if let Some(ticket) = current_opti.as_mut() {
10364                    ticket.settle();
10365                }
10366                if successor_attempt.is_some() {
10367                    let fork = opti_fork
10368                        .as_mut()
10369                        .ok_or("optipipe successor snapshot lost fork state")?;
10370                    let rt = fork.rt;
10371                    let snapshot_fence = fork.fence;
10372                    opti_snapshot_one_stage_owned_into(
10373                        e,
10374                        cache,
10375                        rt,
10376                        &snapshot_fence,
10377                        1,
10378                        fork.successor_snapshot_mut(),
10379                    )?;
10380                    // Publish N only after both independent successor-state queues are complete.
10381                    fork.rt.publish_to(1, &e.stream())?;
10382                }
10383                result
10384            } else if let Some(ticket) = current_opti.as_mut() {
10385                let fork = opti_fork
10386                    .as_mut()
10387                    .ok_or("optipipe carried controller ticket lost fork state")?;
10388                let boundary = ticket.take_boundary();
10389                let result = self.verify_stage1_finish(
10390                    e,
10391                    boundary,
10392                    &mut *cache,
10393                    ckpt.as_mut(),
10394                    None,
10395                    &fork.fence,
10396                    true,
10397                )?;
10398                ticket.settle();
10399                result
10400            } else if let Some(generation) = fork_attempt {
10401                let fork = opti_fork
10402                    .as_mut()
10403                    .expect("fork generation without fork state");
10404                fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
10405                let action = fork.mode.action(generation.id);
10406                let boundary = self.verify_stage0_issue(
10407                    e,
10408                    &verify_tokens,
10409                    pos,
10410                    &mut *cache,
10411                    embd_dev,
10412                    ckpt.as_mut(),
10413                    None,
10414                    &fork.fence,
10415                    Some(true),
10416                    None,
10417                )?;
10418                OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10419                let mut ticket = fork.ticket(generation, boundary);
10420                if action == OptiForkAction::Abort {
10421                    return Err(format!(
10422                        "optipipe forced abort with generation {} stage0 in flight",
10423                        generation.id,
10424                    )
10425                    .into());
10426                }
10427                fork.reconcile(
10428                    e,
10429                    &mut *cache,
10430                    &mut *scratch,
10431                    &snap,
10432                    &mut h_seed_buf,
10433                    &mut fill_prev,
10434                    generation,
10435                    action,
10436                    verify_tokens[0],
10437                )?;
10438                let result = if action == OptiForkAction::Hit {
10439                    let boundary = ticket.take_boundary();
10440                    self.verify_stage1_finish(
10441                        e,
10442                        boundary,
10443                        &mut *cache,
10444                        ckpt.as_mut(),
10445                        None,
10446                        &fork.fence,
10447                        true,
10448                    )?
10449                } else {
10450                    // The optimistic boundary slot has no reader. Re-run the unchanged serial
10451                    // verify only after E_restart published the restored stage-0 state.
10452                    self.decode_step_t_core(
10453                        e,
10454                        &verify_tokens,
10455                        pos,
10456                        &mut *cache,
10457                        embd_dev,
10458                        ckpt.as_mut(),
10459                    )?
10460                };
10461                ticket.settle();
10462                debug_assert_eq!(ticket.generation, generation);
10463                fork.retire(generation)?;
10464                result
10465            } else {
10466                self.decode_step_t_core(
10467                    e,
10468                    &verify_tokens,
10469                    pos,
10470                    &mut *cache,
10471                    embd_dev,
10472                    ckpt.as_mut(),
10473                )?
10474            };
10475            let pipe_accept = match pipe {
10476                Some(p) => Some(p.accept_begin(round)?),
10477                None => None,
10478            };
10479
10480            ph_mark(&mut ph_verify, phase_on);
10481            // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
10482            // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
10483            // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
10484            // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
10485            // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
10486            // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
10487            // (== the bonus), so every index shifts by `base` and last_pred is unused.
10488            let t_v = verify_tokens.len();
10489            let mut preds: Vec<u32> = Vec::new();
10490            if !sampled {
10491                for j in 0..t_v {
10492                    e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
10493                }
10494                preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
10495                // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
10496                // next round's last_token = the next chain's embed lookup. Catch it at the
10497                // source with the column named — an all-NaN VERIFY column implicates the
10498                // stage-split trunk (decode_step_t_core_ppn), not the draft head.
10499                if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
10500                    let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
10501                    let mut probe = e.zeros(n_vocab)?;
10502                    e.copy_view_into(&mut probe, 0, col, n_vocab)?;
10503                    let col_h = e.dtoh(&probe)?;
10504                    let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
10505                    return Err(format!(
10506                        "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
10507                         col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
10508                         — the stage-split verify produced a poisoned column (#87 trap)",
10509                        preds[bad]
10510                    )
10511                    .into());
10512                }
10513            }
10514            ph_mark(&mut ph_wait, phase_on);
10515            let t_pred = |j: usize| -> u32 {
10516                if j == 0 && base == 0 {
10517                    last_pred
10518                } else {
10519                    // GREEDY-ONLY: `preds` is filled under `if !sampled` above. The debug print
10520                    // used to call this from the sampled arm and panicked the worker; it now goes
10521                    // through `debug_t_pred0`. Keep the strict index here — in the greedy walk an
10522                    // out-of-range pred is a real bug, not something to paper over.
10523                    debug_assert!(
10524                        !sampled,
10525                        "t_pred is greedy-only: `preds` is empty in the sampled arm"
10526                    );
10527                    preds[base + j - 1]
10528                }
10529            };
10530            let mut devacc_seeded = false;
10531            let mut devacc_acc: Option<CudaSlice<u32>> = None;
10532            let (n_acc, bonus) = if !sampled {
10533                // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
10534                // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
10535                // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
10536                // gated on token identity vs the host walk (the arms below are bit-equal rules).
10537                if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
10538                {
10539                    let draft_d = e.htod_u32_v(&draft)?;
10540                    let mut acc_out = e.alloc_u32_zeroed(2)?;
10541                    e.spec_accept_greedy(
10542                        &preds_d,
10543                        &draft_d,
10544                        last_pred,
10545                        base,
10546                        k_round,
10547                        &mut acc_out,
10548                    )?;
10549                    devacc_acc = Some(acc_out.clone());
10550                    // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
10551                    // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
10552                    // non-replay commit arms skip their host-offset seed copies (guarded below);
10553                    // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
10554                    // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
10555                    // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
10556                    // the update lands after the arms (devacc_seeded guard below).
10557                    e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
10558                    // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
10559                    // unified rule; full accept rewrites the verify-left value). Host mirrors
10560                    // update after the readback; commit_verified_prefix skips its len_d writes.
10561                    if let Some(successor) = successor_attempt.as_ref() {
10562                        opti_fork
10563                            .as_mut()
10564                            .ok_or("optipipe successor reconcile lost fork state")?
10565                            .queue_actual_reconcile(
10566                                e,
10567                                &snap,
10568                                &acc_out,
10569                                successor.verify_tokens[0],
10570                                base,
10571                            )?;
10572                    } else if let Some(ptrs) = &kv_len_ptrs {
10573                        let saved: Vec<i32> = (0..self.layers.len())
10574                            .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
10575                            .collect();
10576                        let saved_d = e.htod_i32(&saved)?;
10577                        e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
10578                    }
10579                    devacc_seeded = true;
10580                    let ab = e.dtoh_u32(&acc_out)?;
10581                    (ab[0] as usize, ab[1])
10582                } else {
10583                    let mut n_acc = 0usize;
10584                    for j in 0..k_round {
10585                        if t_pred(j) == draft[j] {
10586                            n_acc += 1;
10587                        } else {
10588                            break;
10589                        }
10590                    }
10591                    // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
10592                    // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
10593                    (n_acc, t_pred(n_acc))
10594                }
10595            } else {
10596                // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
10597                if col_buf.is_none() {
10598                    col_buf = Some(e.zeros(n_vocab)?);
10599                }
10600                // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
10601                // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
10602                let mut pj = vec![0f32; k_round.max(1)];
10603                let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
10604                if k_round > 0 {
10605                    let mut ids: Vec<u32> = Vec::new();
10606                    let mut rows: Vec<i32> = Vec::new();
10607                    for j in 0..k_round {
10608                        if j > 0 || base == 1 {
10609                            ids.push(draft[j]);
10610                            rows.push((base + j) as i32 - 1);
10611                        }
10612                    }
10613                    if !ids.is_empty() {
10614                        let nr = rows.len();
10615                        // penalties: materialize the used columns into one contiguous penalized
10616                        // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
10617                        // penalties: materialize used columns contiguously, penalize all rows in
10618                        // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
10619                        let p_rows: Vec<i32> = if pen_on {
10620                            (0..nr as i32).collect()
10621                        } else {
10622                            rows.clone()
10623                        };
10624                        if pen_on {
10625                            if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
10626                                pcol_buf = Some(e.zeros(nr * n_vocab)?);
10627                            }
10628                            let pc = pcol_buf.as_mut().unwrap();
10629                            for (i2, &r) in rows.iter().enumerate() {
10630                                let c = r as usize;
10631                                e.copy_view_into(
10632                                    pc,
10633                                    i2 * n_vocab,
10634                                    &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
10635                                    n_vocab,
10636                                )?;
10637                            }
10638                            let h = pen_hist_d.as_ref().unwrap();
10639                            let nh = h.len();
10640                            e.penalize_logits_rows(
10641                                pc,
10642                                h,
10643                                nh,
10644                                sp.penalty_repeat,
10645                                sp.penalty_freq,
10646                                sp.penalty_present,
10647                                n_vocab,
10648                                nr,
10649                            )?;
10650                        }
10651                        let p_src: &CudaSlice<f32> = if pen_on {
10652                            pcol_buf.as_ref().unwrap()
10653                        } else {
10654                            &tlogits_d
10655                        };
10656                        let rowsd = e.htod_i32(&p_rows)?;
10657                        let (mut th_d, mut z_d, mut mx_d) =
10658                            (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
10659                        e.filter_stats(
10660                            p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
10661                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
10662                        )?;
10663                        let idsd = e.htod_u32_v(&ids)?;
10664                        let mut outd = e.zeros(nr)?;
10665                        e.softmax_gather_filtered(
10666                            p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
10667                            sp_temp,
10668                        )?;
10669                        let outv = e.dtoh(&outd)?;
10670                        let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
10671                        let mut oi = 0usize;
10672                        for j in 0..k_round {
10673                            if j > 0 || base == 1 {
10674                                pj[j] = outv[oi];
10675                                oi += 1;
10676                            }
10677                        }
10678                        col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
10679                    }
10680                    if base == 0 {
10681                        let lc: &CudaSlice<f32> = if pen_on {
10682                            if col_buf.is_none() {
10683                                col_buf = Some(e.zeros(n_vocab)?);
10684                            }
10685                            let cb = col_buf.as_mut().unwrap();
10686                            e.copy_into(
10687                                cb,
10688                                0,
10689                                last_col_logits
10690                                    .as_ref()
10691                                    .expect("sampled: last_col_logits unset"),
10692                                n_vocab,
10693                            )?;
10694                            let h = pen_hist_d.as_ref().unwrap();
10695                            let nh = h.len();
10696                            e.penalize_logits(
10697                                cb,
10698                                h,
10699                                nh,
10700                                sp.penalty_repeat,
10701                                sp.penalty_freq,
10702                                sp.penalty_present,
10703                                n_vocab,
10704                            )?;
10705                            col_buf.as_ref().unwrap()
10706                        } else {
10707                            last_col_logits
10708                                .as_ref()
10709                                .expect("sampled: last_col_logits unset")
10710                        };
10711                        let rows0 = e.htod_i32(&[0])?;
10712                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
10713                        e.filter_stats(
10714                            lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
10715                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
10716                        )?;
10717                        let idsd = e.htod_u32_v(&[draft[0]])?;
10718                        let mut outd = e.zeros(1)?;
10719                        e.softmax_gather_filtered(
10720                            lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
10721                        )?;
10722                        pj[0] = e.dtoh(&outd)?[0];
10723                        last_col_stats =
10724                            Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
10725                    }
10726                }
10727                // q source: the graph arm retained the head logits in the persistent q_slots;
10728                // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
10729                // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
10730                // computes them post-replay — graph engages only filter/penalty-free, so the
10731                // stats degenerate to th=0/full-Z there, keeping ONE accept path).
10732                let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
10733                    &dctx.q_slots
10734                } else {
10735                    &draft_logits
10736                };
10737                let mut n_acc = 0usize;
10738                for j in 0..k_round {
10739                    let (qmx, qth, qz) = draft_stats[j];
10740                    let idsd = e.htod_u32_v(&[draft_idx[j]])?;
10741                    let rowsd = e.htod_i32(&[0])?;
10742                    let thd = e.htod(&[qth])?;
10743                    let zd = e.htod(&[qz])?;
10744                    let _ = qmx;
10745                    let mut outd = e.zeros(1)?;
10746                    e.softmax_gather_filtered(
10747                        &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
10748                        sp_temp,
10749                    )?;
10750                    let qj = e.dtoh(&outd)?[0];
10751                    let u = host_u01(sp_seed, uctr);
10752                    uctr += 1;
10753                    let accept = (u as f64) * (qj as f64) < pj[j] as f64;
10754                    // SKEY PROBE: q == 0 for the token the draft actually proposed is the
10755                    // exactness signature (see `skey_probe`). Impossible when the draft was
10756                    // drawn from the same filtered distribution the verify reconstructs here;
10757                    // `u * 0 < p` makes it an UNCONDITIONAL accept whenever p > 0.
10758                    if skey_probe() && qj == 0.0 {
10759                        eprintln!(
10760                            "[skey] EXACTNESS q=0 round={round} j={j} draft_tok={} \
10761                             draft_idx={} p={:e} u={u} accepted={} th_z={:?}",
10762                            draft[j], draft_idx[j], pj[j], accept as u8, draft_stats[j],
10763                        );
10764                    }
10765                    if accept {
10766                        n_acc += 1;
10767                    } else {
10768                        break;
10769                    }
10770                }
10771                let bonus = if n_acc == k_round {
10772                    // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
10773                    let col = base + k_round - 1;
10774                    let cb = col_buf.as_mut().unwrap();
10775                    e.copy_view_into(
10776                        cb,
10777                        0,
10778                        &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
10779                        n_vocab,
10780                    )?;
10781                    if pen_on {
10782                        let h = pen_hist_d.as_ref().unwrap();
10783                        let nh = h.len();
10784                        e.penalize_logits(
10785                            cb,
10786                            h,
10787                            nh,
10788                            sp.penalty_repeat,
10789                            sp.penalty_freq,
10790                            sp.penalty_present,
10791                            n_vocab,
10792                        )?;
10793                    }
10794                    if perturb_buf.is_none() {
10795                        perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
10796                    }
10797                    // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
10798                    // truncation-fix; receipts research/sampfix-20260805/). The old code reused
10799                    // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
10800                    // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
10801                    // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
10802                    // last gathered column, in both base arms. `th` is a threshold in e-units of
10803                    // its OWN row's max, so feeding a neighbour's (row_max, th) into
10804                    // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
10805                    // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
10806                    // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
10807                    // falls through to its smallest-index tie-break => token id 0 ("!") spliced
10808                    // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
10809                    // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
10810                    // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
10811                    // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
10812                    // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
10813                    // and row_max is unused once nothing is masked), so this fix is a byte-level
10814                    // no-op for the untruncated serve default. One extra one-block filter_stats
10815                    // per full-accept round is the whole cost.
10816                    let (mx, th) = {
10817                        let rows0 = e.htod_i32(&[0])?;
10818                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
10819                        let cb0 = col_buf.as_ref().unwrap();
10820                        e.filter_stats(
10821                            cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
10822                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
10823                        )?;
10824                        (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
10825                    };
10826                    let pb = perturb_buf.as_mut().unwrap();
10827                    let cb2 = col_buf.as_ref().unwrap();
10828                    e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
10829                    sctr += 1;
10830                    let td = e.argmax_token_device(pb, n_vocab)?;
10831                    e.dtoh_u32_one(&td)?
10832                } else {
10833                    // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
10834                    let cb = col_buf.as_mut().unwrap();
10835                    if n_acc > 0 || base == 1 {
10836                        let col = base + n_acc - 1;
10837                        e.copy_view_into(
10838                            cb,
10839                            0,
10840                            &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
10841                            n_vocab,
10842                        )?;
10843                    } else {
10844                        let lc = last_col_logits.as_ref().unwrap();
10845                        e.copy_into(cb, 0, lc, n_vocab)?;
10846                    }
10847                    if pen_on {
10848                        let h = pen_hist_d.as_ref().unwrap();
10849                        let nh = h.len();
10850                        e.penalize_logits(
10851                            cb,
10852                            h,
10853                            nh,
10854                            sp.penalty_repeat,
10855                            sp.penalty_freq,
10856                            sp.penalty_present,
10857                            n_vocab,
10858                        )?;
10859                    }
10860                    let cb2 = col_buf.as_ref().unwrap();
10861                    let sc = sctr;
10862                    sctr += 1;
10863                    // p-stats for the reject column: from col_stats when the col was gathered,
10864                    // else (j==0&&base==0) from last_col_stats.
10865                    let p_stats = if n_acc > 0 || base == 1 {
10866                        // col index within the gathered set == number of gathered cols before n_acc
10867                        let gi = if base == 1 { n_acc } else { n_acc - 1 };
10868                        col_stats.get(gi).copied().unwrap_or_else(|| {
10869                            (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
10870                        })
10871                    } else {
10872                        last_col_stats.expect("sampled: last_col_stats unset at reject")
10873                    };
10874                    let q_stats = draft_stats[n_acc];
10875                    if let Some(map) = &d2t_dev {
10876                        if q_full_buf.is_none() {
10877                            q_full_buf = Some(e.zeros(n_vocab)?);
10878                        }
10879                        let qf = q_full_buf.as_mut().unwrap();
10880                        e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
10881                        let qf2 = q_full_buf.as_ref().unwrap();
10882                        e.residual_sample_filtered(
10883                            cb2,
10884                            Some(qf2),
10885                            n_vocab,
10886                            sp_temp,
10887                            sp_seed,
10888                            sc,
10889                            p_stats,
10890                            q_stats,
10891                            &mut sample_tok,
10892                        )?;
10893                    } else {
10894                        e.residual_sample_filtered(
10895                            cb2,
10896                            Some(&q_bufs[n_acc]),
10897                            n_vocab,
10898                            sp_temp,
10899                            sp_seed,
10900                            sc,
10901                            p_stats,
10902                            q_stats,
10903                            &mut sample_tok,
10904                        )?;
10905                    }
10906                    e.dtoh_u32(&sample_tok)?[0]
10907                };
10908                (n_acc, bonus)
10909            };
10910            // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
10911            // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
10912            // ordering). Walk the accepted drafts through the grammar in commit order; the
10913            // first illegal token truncates acceptance at its slot, and that slot's emission
10914            // is recomputed as the MASKED argmax of the target's own verify column — token-
10915            // identical to constrained plain greedy decode (an unmasked argmax that is
10916            // grammar-legal IS the masked argmax: masking only removes competitors). The
10917            // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
10918            // measured in acceptance numbers, never hidden.
10919            let (n_acc, bonus) = match constraint.as_deref_mut() {
10920                None => (n_acc, bonus),
10921                Some(c) => {
10922                    fn ce(e2: String) -> Box<dyn std::error::Error> {
10923                        format!("constraint: {e2}").into()
10924                    }
10925                    let mut na = n_acc;
10926                    let mut cut = false;
10927                    for (j, &d) in draft.iter().enumerate().take(n_acc) {
10928                        if c.is_allowed(d).map_err(ce)? {
10929                            c.consume(d).map_err(ce)?;
10930                        } else {
10931                            na = j;
10932                            cut = true;
10933                            dm_cut_tokens += n_acc - j;
10934                            break;
10935                        }
10936                    }
10937                    if cut {
10938                        dm_cuts += 1;
10939                    }
10940                    let mut bo = bonus;
10941                    if cut || !c.is_allowed(bo).map_err(ce)? {
10942                        let mut row = if na == 0 && base == 0 {
10943                            init_logits_host
10944                                .clone()
10945                                .ok_or("constraint: init logits missing (round-0 cut)")?
10946                        } else {
10947                            e.dtoh_view(
10948                                &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
10949                            )?
10950                        };
10951                        c.mask_logits(&mut row).map_err(ce)?;
10952                        bo = argmax(&row) as u32;
10953                    }
10954                    c.consume(bo).map_err(ce)?;
10955                    (na, bo)
10956                }
10957            };
10958            let mut successor_valid = false;
10959            if let Some((q_proxy, expected_d2)) = rejected_probe {
10960                let v_n = n_acc == 1 && bonus == expected_d2;
10961                eprintln!(
10962                    "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
10963                     expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
10964                );
10965            }
10966            if let Some(successor) = successor_attempt.as_ref() {
10967                successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
10968                let generation = successor.generation;
10969                let q_proxy = successor.q_proxy;
10970                let expected_pending = successor.verify_tokens[0];
10971                let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
10972                let fork = opti_fork
10973                    .as_mut()
10974                    .ok_or("optipipe successor resolution lost fork state")?;
10975                fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
10976                if successor_valid {
10977                    OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10978                } else {
10979                    OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10980                    OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10981                    OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
10982                }
10983                let breaker_tripped = fork
10984                    .controller
10985                    .as_mut()
10986                    .expect("controller policy")
10987                    .resolve(successor_valid);
10988                if breaker_tripped {
10989                    OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10990                }
10991                eprintln!(
10992                    "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
10993                     expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
10994                     resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
10995                    generation.id, successor_valid, !successor_valid, breaker_tripped,
10996                );
10997                if !successor_valid {
10998                    let mut successor = successor_attempt
10999                        .take()
11000                        .expect("controller successor disappeared on miss");
11001                    successor.settle();
11002                    fork.retire(generation)?;
11003                }
11004            }
11005            total_drafted += k_round;
11006            total_accepted += n_acc;
11007            if let Some(t) = sess_telem {
11008                // Greedy, rejection-sampling, and grammar truncation all converge here after
11009                // the accept decision is already on host. Fixed-size relaxed atomics only.
11010                t.record_round(k_round, n_acc);
11011            }
11012            if spec_stats {
11013                st_len_hist[k_round] += 1;
11014                for j in 0..k_round {
11015                    st_drafted[j] += 1;
11016                }
11017                for j in 0..n_acc {
11018                    st_accepted[j] += 1;
11019                }
11020                if n_acc == k_round {
11021                    st_full += 1;
11022                }
11023            }
11024
11025            if debug_spec {
11026                eprintln!(
11027                    "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
11028                    out.len(),
11029                    // NOT `t_pred(0)`: `preds` is filled only under `if !sampled` above, so on a
11030                    // sampled request round >= 1 (base == 1) indexed an EMPTY vector and PANICKED
11031                    // the GPU worker thread — a debug flag that killed the exact regime you would
11032                    // set it to investigate. See `debug_t_pred0`.
11033                    debug_t_pred0(sampled, base, last_pred, &preds)
11034                );
11035            }
11036
11037            // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
11038            let commit_started = std::time::Instant::now();
11039            // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
11040            // of them (overshoot past max_new included) or `committed` under-counts the cache rows
11041            // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
11042            // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
11043            for j in 0..n_acc {
11044                if !session_mode && out.len() >= max_new {
11045                    break;
11046                }
11047                out.push(draft[j]);
11048            }
11049            if pen_on {
11050                pen_hist.extend_from_slice(&draft[0..n_acc]);
11051                pen_hist.push(bonus);
11052            }
11053            let bonus_emitted = session_mode || out.len() < max_new;
11054            if bonus_emitted {
11055                out.push(bonus);
11056            }
11057            last_token = bonus;
11058
11059            // --- 5. ROLLBACK + advance (§C) ---
11060            if n_acc == k_round && !spec_replay {
11061                // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
11062                // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
11063                // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
11064                // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
11065                // last_pred is dead in the pending path (t_pred reads verify col 0).
11066                //
11067                // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
11068                // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
11069                // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
11070                // trunk hidden (the last verify column). set_len first: a p-min break may have
11071                // left one extra chain append at that slot. Partial accepts need NO fill (the
11072                // chain already covered every accepted position; round-start set_len truncates).
11073                let mut vh_seed = e.zeros(n_embd)?;
11074                e.copy_view_into(
11075                    &mut vh_seed,
11076                    0,
11077                    &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
11078                    n_embd,
11079                )?;
11080                if refresh {
11081                    // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
11082                    // overwrite ALL committed positions' scratch entries with K/V from their EXACT
11083                    // verify hiddens — the reference engine's mtp_update fills from true hiddens;
11084                    // the full stack (vx) is already resident from the verify. Replaces both the
11085                    // chain-approximate entries AND the old last-token-only fill. Acceptance-only
11086                    // (draft attention quality); exactness stays the verify's job.
11087                    scratch.set_len(e, pos)?;
11088                    // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
11089                    // (hidden of the last committed row before this verify batch).
11090                    let mut vxs = e.zeros(t_v * n_embd)?;
11091                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
11092                    if t_v > 1 {
11093                        e.copy_view_into(
11094                            &mut vxs,
11095                            n_embd,
11096                            &vx.slice(0..(t_v - 1) * n_embd),
11097                            (t_v - 1) * n_embd,
11098                        )?;
11099                    }
11100                    self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
11101                } else {
11102                    scratch.set_len(e, pos + base + k_round - 1)?;
11103                    // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
11104                    let mut hp = e.zeros(n_embd)?;
11105                    if t_v >= 2 {
11106                        e.copy_view_into(
11107                            &mut hp,
11108                            0,
11109                            &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
11110                            n_embd,
11111                        )?;
11112                    } else {
11113                        e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
11114                    }
11115                    self.mtp_kv_fill(
11116                        e,
11117                        mtp,
11118                        &[draft[k_round - 1]],
11119                        &hp,
11120                        pos + base + k_round - 1,
11121                        &mut *scratch,
11122                        embd_dev,
11123                    )?;
11124                }
11125                // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
11126                // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
11127                // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
11128                // col). Saves one MTP-block pass per round on top of the pairing fix.
11129                if !devacc_seeded {
11130                    e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
11131                    e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
11132                }
11133                pending = Some(bonus);
11134                if debug_spec {
11135                    eprintln!("  -> FULL ACCEPT (bonus pending, prev-h seed)");
11136                }
11137            } else if !spec_replay && base + n_acc >= 1 {
11138                // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
11139                // the verify's first j = base+n_acc columns ARE the committed sequence, computed
11140                // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
11141                // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
11142                // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
11143                // full-accept path — the legacy duplicate trunk replay is gone. The next chain
11144                // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
11145                // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
11146                // accept (never compounds: the next verify recomputes true hiddens for all
11147                // committed columns).
11148                let j = base + n_acc;
11149                self.commit_verified_prefix(
11150                    e,
11151                    &mut *cache,
11152                    &snap,
11153                    ckpt.as_ref().unwrap(),
11154                    j,
11155                    devacc_seeded,
11156                    if devacc_seeded {
11157                        devacc_acc.as_ref().map(|a| (a, base, t_v))
11158                    } else {
11159                        None
11160                    },
11161                )?;
11162                let mut seed = e.zeros(n_embd)?;
11163                e.copy_view_into(
11164                    &mut seed,
11165                    0,
11166                    &vx.slice((j - 1) * n_embd..j * n_embd),
11167                    n_embd,
11168                )?;
11169                // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
11170                // branch); without it the chain entries stand and only the tail truncates. Either
11171                // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
11172                // (persistent mode), rope pos+j+1 (chain convention).
11173                if refresh {
11174                    scratch.set_len(e, pos)?;
11175                    let mut vxs = e.zeros(j * n_embd)?;
11176                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
11177                    if j > 1 {
11178                        e.copy_view_into(
11179                            &mut vxs,
11180                            n_embd,
11181                            &vx.slice(0..(j - 1) * n_embd),
11182                            (j - 1) * n_embd,
11183                        )?;
11184                    }
11185                    self.mtp_kv_fill(
11186                        e,
11187                        mtp,
11188                        &verify_tokens[0..j],
11189                        &vxs,
11190                        pos,
11191                        &mut *scratch,
11192                        embd_dev,
11193                    )?;
11194                } else {
11195                    scratch.set_len(e, pos + j)?;
11196                }
11197                // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
11198                // bonus's predecessor (verify col j-1); no pseudo pass.
11199                if !devacc_seeded {
11200                    e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
11201                    e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
11202                }
11203                pending = Some(bonus);
11204                if debug_spec {
11205                    eprintln!("  -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
11206                }
11207            } else if !spec_replay {
11208                // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
11209                // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
11210                // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
11211                // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
11212                // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
11213                // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
11214                // base=1 pending machinery, bit-identical by the decode-exact verify contract.
11215                // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
11216                // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
11217                cache.rollback(e, &snap, 0)?;
11218                scratch.set_len(e, pos)?;
11219                e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
11220                pending = Some(bonus);
11221                if debug_spec {
11222                    eprintln!("  -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
11223                }
11224            } else {
11225                // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
11226                // this round survives, only possible before the first pending exists, ~round 0):
11227                // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
11228                // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
11229                // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
11230                // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
11231                // trunk hidden.
11232                cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
11233                let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
11234                if let Some(b) = pending.take() {
11235                    replay.push(b);
11236                }
11237                replay.extend_from_slice(&draft[0..n_acc]);
11238                replay.push(bonus);
11239                // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
11240                // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
11241                // last col exactly as before (byte-identical to the old _h_emb_dev call).
11242                let (rl_d, rx) = if self.qwen35_serving_class() {
11243                    let mut logits = Vec::with_capacity(replay.len() * n_vocab);
11244                    let mut hidden = e.uninit(replay.len() * n_embd)?;
11245                    for (row, &token) in replay.iter().enumerate() {
11246                        let (row_logits, row_hidden) =
11247                            self.spec_target_step_h(e, token, &mut *cache)?;
11248                        logits.extend_from_slice(&row_logits);
11249                        e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
11250                    }
11251                    (e.htod(&logits)?, hidden)
11252                } else {
11253                    self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
11254                };
11255                // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
11256                // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
11257                e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
11258                last_pred = e.dtoh_u32(&preds_d)?[0];
11259                if sampled {
11260                    let lr0 = replay.len();
11261                    let lc = last_col_logits
11262                        .as_mut()
11263                        .expect("sampled: last_col_logits unset");
11264                    e.copy_view_into(
11265                        lc,
11266                        0,
11267                        &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
11268                        n_vocab,
11269                    )?;
11270                }
11271                let lr = replay.len();
11272                if lr >= 2 {
11273                    e.copy_view_into(
11274                        &mut h_seed_buf,
11275                        0,
11276                        &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
11277                        n_embd,
11278                    )?;
11279                } else {
11280                    // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
11281                    // last_token, whose own-row hidden fill_prev still holds.
11282                    e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
11283                }
11284                // the bonus is COMMITTED here — it becomes the last committed row.
11285                let mut rh_last = e.zeros(n_embd)?;
11286                e.copy_view_into(
11287                    &mut rh_last,
11288                    0,
11289                    &rx.slice((lr - 1) * n_embd..lr * n_embd),
11290                    n_embd,
11291                )?;
11292                e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
11293                if debug_spec {
11294                    eprintln!("  -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
11295                }
11296            }
11297            if devacc_seeded {
11298                // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
11299                // consumed the old value (both slots carry the same value in every non-replay arm).
11300                e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
11301            }
11302            if successor_valid {
11303                let optimistic_scratch_len = successor_attempt
11304                    .as_ref()
11305                    .expect("valid controller successor disappeared")
11306                    .scratch_len;
11307                // The normal current-round commit refreshed/truncated the logical scratch tail.
11308                // Its optimistic successor row was already written physically, so restoring only
11309                // the retained logical length makes that row live for the carried round.
11310                scratch.set_len(e, optimistic_scratch_len)?;
11311            }
11312            if let Some(current) = current_opti.take() {
11313                opti_fork
11314                    .as_mut()
11315                    .ok_or("optipipe current retirement lost fork state")?
11316                    .retire(current.generation)?;
11317            }
11318            if successor_valid {
11319                let successor = successor_attempt
11320                    .take()
11321                    .expect("valid controller successor disappeared before promotion");
11322                let generation = successor.generation;
11323                opti_fork
11324                    .as_mut()
11325                    .ok_or("optipipe successor promotion lost fork state")?
11326                    .promote_successor_snapshot(&mut snap, generation);
11327                carried_opti = Some(successor);
11328            }
11329            if anatomy_on {
11330                // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
11331                // only for this diagnostic so it does not disappear into the following draft's
11332                // first token readback.
11333                e.stream().synchronize()?;
11334                ph_commit += commit_started.elapsed().as_secs_f64();
11335            }
11336            // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
11337            // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
11338            // final position — the floor's position key reads the committed depth). Burst
11339            // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
11340            // like gemma's burst arm.
11341            if adapt {
11342                let fl_now = floor_at(cache.pos);
11343                kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
11344            }
11345            ph_mark(&mut ph_rest, phase_on);
11346            if let Some(p) = pipe {
11347                p.accept_end(round);
11348            }
11349            drop(pipe_accept);
11350            round += 1;
11351            // sse-cadence: this round's accepted drafts + bonus are committed (out is
11352            // append-only past step 4) — flush at round cadence.
11353            keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
11354        }
11355        if let Some(mut ticket) = carried_opti.take() {
11356            opti_fork
11357                .as_mut()
11358                .ok_or("optipipe tail drain lost fork state")?
11359                .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
11360        }
11361        // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
11362        // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
11363        let _ = flush_commit(&mut on_commit, &out, &mut flushed);
11364
11365        if spec_stats {
11366            let per_slot: Vec<String> = (0..k)
11367                .map(|j| {
11368                    if st_drafted[j] > 0 {
11369                        format!(
11370                            "{}/{}={:.3}",
11371                            st_accepted[j],
11372                            st_drafted[j],
11373                            st_accepted[j] as f64 / st_drafted[j] as f64
11374                        )
11375                    } else {
11376                        "0/0".into()
11377                    }
11378                })
11379                .collect();
11380            let acc = if total_drafted > 0 {
11381                total_accepted as f64 / total_drafted as f64
11382            } else {
11383                0.0
11384            };
11385            eprintln!(
11386                "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
11387                       per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
11388                       tok_per_round={:.3}",
11389                per_slot.join(" "),
11390                (total_accepted + round) as f64 / round.max(1) as f64
11391            );
11392        }
11393        if constraint.is_some() {
11394            eprintln!(
11395                "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
11396                 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
11397                dm_clone_ns as f64 / 1e6,
11398                dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
11399            );
11400        }
11401        if phase_on {
11402            let tot = ph_draft + ph_verify + ph_wait + ph_rest;
11403            eprintln!(
11404                "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
11405                ph_draft * 1e3,
11406                ph_draft / tot * 100.0,
11407                ph_verify * 1e3,
11408                ph_verify / tot * 100.0,
11409                ph_wait * 1e3,
11410                ph_wait / tot * 100.0,
11411                ph_rest * 1e3,
11412                ph_rest / tot * 100.0
11413            );
11414        }
11415        if anatomy_on {
11416            let rounds_f = round.max(1) as f64;
11417            let other = (ph_rest - ph_commit).max(0.0);
11418            eprintln!(
11419                "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
11420                 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
11421                ph_draft * 1e3 / rounds_f,
11422                ph_verify * 1e3 / rounds_f,
11423                ph_wait * 1e3 / rounds_f,
11424                ph_commit * 1e3 / rounds_f,
11425                other * 1e3 / rounds_f,
11426            );
11427        }
11428        let _pipe_tail = pipe.map(|p| p.primary());
11429        // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
11430        // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
11431        // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
11432        // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
11433        if let Some(slot) = sess_draft_slot.take() {
11434            *slot = Some(dctx);
11435        }
11436        let t_rounds = t_ent.elapsed();
11437        if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
11438            // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
11439            // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
11440            // HERE, where the sampler, the session Philox counters and the penalty window are
11441            // all live and the boundary logits row still exists — that is the "make the state
11442            // available" half of the fix; the consuming burst then just emits it. `sctr` is
11443            // written to the session BELOW the draws so the advance is never lost.
11444            *next_pred_slot = Some(last_pred);
11445            let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
11446            let mut stashed_pending = false;
11447            if let Some(b) = pending.take() {
11448                if !sampled {
11449                    // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
11450                    // committing it with a solo T=1 pass — the next empty-suffix greedy burst
11451                    // consumes it as round-0 verify col 0 (a plain round edge; the old tail
11452                    // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
11453                    // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
11454                    // OUT of `committed` (cache rows == committed); the consuming call
11455                    // prepends it once its verify commits the row. next_pred is unknowable
11456                    // without the commit pass — None; callers gate on pending_tok too.
11457                    debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
11458                    if let Some(slot) = sess_pending_slot.take() {
11459                        *slot = Some(b);
11460                    }
11461                    *next_pred_slot = None;
11462                    // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
11463                    // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
11464                    *last_h = Some(e.clone_dtod(&fill_prev)?);
11465                    stashed_pending = true;
11466                } else {
11467                    // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
11468                    // the sampled round-0 accept needs this pass's logits (last_col_logits).
11469                    let pos_b = cache.pos;
11470                    scratch.set_len(e, pos_b)?;
11471                    let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
11472                    // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
11473                    // itself — the prediction AFTER the bonus never materialized; it would have
11474                    // been the next round's verify col 0). The commit's logits ARE that
11475                    // prediction — so they are also the row the next burst's boundary token
11476                    // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
11477                    *next_pred_slot = Some(if sample_boundary {
11478                        sample_boundary_token(
11479                            e,
11480                            &lg_b,
11481                            &sp,
11482                            &pen_hist,
11483                            &mut sctr,
11484                            "burst-tail-commit",
11485                        )?
11486                    } else {
11487                        argmax(&lg_b) as u32
11488                    });
11489                    self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
11490                    *last_h = Some(hb);
11491                }
11492            } else {
11493                // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
11494                *last_h = Some(e.clone_dtod(&fill_prev)?);
11495                if sample_boundary {
11496                    // No pending to commit, so the boundary row is the one `last_pred` was
11497                    // argmaxed from and the sampled path keeps it on device: the init feed's
11498                    // logits when the burst ran zero rounds, else the legacy-replay path's
11499                    // last verify column (both predict the token AFTER the last committed
11500                    // row). It is retained precisely because round 0's accept test needs it,
11501                    // so the draw costs no extra D2H of the [n_vocab] row.
11502                    match last_col_logits.as_ref() {
11503                        Some(lc) => {
11504                            *next_pred_slot = Some(sample_boundary_token_dev(
11505                                e,
11506                                lc,
11507                                n_vocab,
11508                                &sp,
11509                                &pen_hist,
11510                                &mut sctr,
11511                                "burst-tail-nopending",
11512                            )?);
11513                        }
11514                        // NAME THE FALLBACK (house standard): unreachable today — a sampled
11515                        // burst always feeds or replays, so the row exists — but if it ever
11516                        // is, the stream takes a greedy token and SAYS so rather than
11517                        // silently regressing to the pre-lane behaviour.
11518                        None => eprintln!(
11519                            "[spec-boundary] sampled tail kept the ARGMAX boundary token \
11520                             (reason: no retained boundary logits row)"
11521                        ),
11522                    }
11523                }
11524            }
11525            *sctr_slot = sctr;
11526            *uctr_slot = uctr;
11527            committed.extend_from_slice(prompt);
11528            if let Some(cb) = carried_pending {
11529                // the consumed carry's cache row landed in round 0's verify (every pending
11530                // round commits col 0) — it joins `committed` here, in sequence order.
11531                committed.push(cb);
11532            }
11533            if stashed_pending {
11534                // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
11535                // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
11536                // 18446744073709551615 out of range for slice of length 0", killing the
11537                // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
11538                // stream". Reachable because `pending` starts as `carried_pending` (a bonus
11539                // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
11540                // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
11541                // did). So a burst that stashes a pending without emitting anything of its own —
11542                // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
11543                // guard skipping every token under a tight budget — arrives here with
11544                // out.len() == 0 and stashed_pending == true.
11545                //
11546                // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
11547                // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
11548                // just above is already accounted. Saturating, not a min/assert: an empty `out`
11549                // here is a legitimate burst shape, not a corrupt state.
11550                let emitted = out.len().saturating_sub(1);
11551                committed.extend_from_slice(&out[..emitted]);
11552            } else {
11553                committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
11554            }
11555            debug_assert_eq!(
11556                cache.pos,
11557                committed.len(),
11558                "session invariant: cache rows == committed tokens"
11559            );
11560            if setup_trace {
11561                e.stream().synchronize()?; // bound the async tail fill in the trace
11562                let t_tail = t_ent.elapsed();
11563                eprintln!(
11564                    "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
11565                    t_init.as_secs_f64() * 1e3,
11566                    (t_cap - t_init).as_secs_f64() * 1e3,
11567                    (t_fill - t_cap).as_secs_f64() * 1e3,
11568                    (t_rounds - t_fill).as_secs_f64() * 1e3,
11569                    (t_tail - t_rounds).as_secs_f64() * 1e3,
11570                    t_tail.as_secs_f64() * 1e3,
11571                    out.len(),
11572                    continuation
11573                );
11574            }
11575            return Ok((out, total_drafted, total_accepted));
11576        }
11577        out.truncate(max_new);
11578        Ok((out, total_drafted, total_accepted))
11579    }
11580
11581    /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
11582    /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
11583    /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
11584    pub fn extract_dspark_anchors(
11585        &self,
11586        e: &Engine,
11587        tokens: &[u32],
11588        anchor_positions: &[usize],
11589        gamma: usize,
11590        top_k: usize,
11591        chunk: usize,
11592        temperature: f32,
11593    ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
11594        if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
11595            return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
11596        }
11597        if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
11598            return Err("DSpark anchor positions must be sorted and unique".into());
11599        }
11600        for &position in anchor_positions {
11601            if position == 0 || position + gamma >= tokens.len() {
11602                return Err(format!(
11603                    "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
11604                    tokens.len()
11605                )
11606                .into());
11607            }
11608        }
11609
11610        let n_vocab = self.output.out_features();
11611        let n_embd = self.cfg.n_embd as usize;
11612        let mut cache = crate::pp::new_cache(e, &self.cfg, tokens.len() + gamma + 8)?;
11613        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
11614        let embd_gpu = if spec_host_embd() {
11615            None
11616        } else {
11617            Some(
11618                self.embd_gpu
11619                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
11620            )
11621        };
11622        let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
11623
11624        struct PendingRecord {
11625            position: usize,
11626            hidden: Option<Vec<f32>>,
11627            tokens: Vec<u32>,
11628            target_top_ids: Vec<Option<Vec<u32>>>,
11629            target_top_logits: Vec<Option<Vec<f32>>>,
11630            target_top_probs: Vec<Option<Vec<f32>>>,
11631            target_tail_probs: Vec<Option<f32>>,
11632        }
11633
11634        let mut pending: Vec<PendingRecord> = anchor_positions
11635            .iter()
11636            .map(|&position| PendingRecord {
11637                position,
11638                hidden: None,
11639                tokens: tokens[position..=position + gamma].to_vec(),
11640                target_top_ids: vec![None; gamma],
11641                target_top_logits: vec![None; gamma],
11642                target_top_probs: vec![None; gamma],
11643                target_tail_probs: vec![None; gamma],
11644            })
11645            .collect();
11646
11647        let mut start = 0usize;
11648        while start < tokens.len() {
11649            let end = (start + chunk).min(tokens.len());
11650            let chunk_tokens = &tokens[start..end];
11651            let (target_logits, hidden_rows) =
11652                self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
11653            for record in &mut pending {
11654                let hidden_position = record.position - 1;
11655                if hidden_position >= start && hidden_position < end {
11656                    let local = hidden_position - start;
11657                    record.hidden = Some(
11658                        e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
11659                    );
11660                }
11661                for slot in 0..gamma {
11662                    let target_row = record.position + slot;
11663                    if target_row < start || target_row >= end {
11664                        continue;
11665                    }
11666                    let local = target_row - start;
11667                    let logits =
11668                        e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
11669                    let (ids, top_logits, probs, tail) =
11670                        dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
11671                    record.target_top_ids[slot] = Some(ids);
11672                    record.target_top_logits[slot] = Some(top_logits);
11673                    record.target_top_probs[slot] = Some(probs);
11674                    record.target_tail_probs[slot] = Some(tail);
11675                }
11676            }
11677            start = end;
11678        }
11679
11680        pending
11681            .into_iter()
11682            .map(|record| {
11683                let hidden = record
11684                    .hidden
11685                    .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
11686                let target_top_ids =
11687                    flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
11688                let target_top_logits = flatten_dspark_rows(
11689                    record.target_top_logits,
11690                    record.position,
11691                    "target logits",
11692                )?;
11693                let target_top_probs =
11694                    flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
11695                let target_tail_probs = record
11696                    .target_tail_probs
11697                    .into_iter()
11698                    .enumerate()
11699                    .map(|(slot, value)| {
11700                        value.ok_or_else(|| {
11701                            format!("missing DSpark tail at {} slot {slot}", record.position)
11702                        })
11703                    })
11704                    .collect::<Result<Vec<_>, _>>()?;
11705                Ok(DsparkAnchorRecord {
11706                    position: record.position,
11707                    hidden,
11708                    tokens: record.tokens,
11709                    target_top_ids,
11710                    target_top_logits,
11711                    target_top_probs,
11712                    target_tail_probs,
11713                })
11714            })
11715            .collect()
11716    }
11717
11718    /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
11719    /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
11720    /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
11721    /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
11722    /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
11723    /// quant-induced head/hidden-state mismatch from text drift.
11724    ///
11725    /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
11726    ///   draft_j  = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
11727    ///              eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
11728    ///   target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
11729    ///              at forced context tokens[0..p+j]). For j==0 this equals live spec
11730    ///              acceptance; for j>=1 live verify would condition on the drafts, here it
11731    ///              conditions on the corpus — deterministic and arm-comparable by design.
11732    ///
11733    /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
11734    /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
11735    /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
11736    ///
11737    /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
11738    /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
11739    /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
11740    /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
11741    /// agreement vs this path — not usable as a training-data source).
11742    pub fn replay_acceptance(
11743        &self,
11744        e: &Engine,
11745        tokens: &[u32],
11746        k: usize,
11747        stride: usize,
11748        chunk: usize,
11749        mut hdump: Option<&mut std::fs::File>,
11750    ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
11751        assert!(k >= 1 && stride >= 1 && chunk >= 2);
11752        let mtp = self
11753            .mtp
11754            .as_ref()
11755            .expect("replay_acceptance requires an MTP head");
11756        let n_vocab = self.output.out_features();
11757        let d_vocab = mtp
11758            .shared_head_head
11759            .as_ref()
11760            .unwrap_or(&self.output)
11761            .out_features();
11762        let n_embd = self.cfg.n_embd as usize;
11763        let t_total = tokens.len();
11764        assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
11765        // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
11766        let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
11767        let mut scratch = MtpScratch::new(
11768            e,
11769            &self.cfg,
11770            t_total + k + 8,
11771            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
11772        )?;
11773        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
11774        let embd_gpu = if spec_host_embd() {
11775            None
11776        } else {
11777            Some(
11778                self.embd_gpu
11779                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
11780            )
11781        };
11782        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
11783
11784        // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
11785        let mut bg: Vec<u32> = vec![0; t_total + 1];
11786        let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
11787        let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
11788        let mut seed_buf = e.zeros(n_embd)?;
11789        let mut preds_d = e.alloc_u32_zeroed(chunk)?;
11790        let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
11791        let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
11792        let mut s = 0usize;
11793        while s < t_total {
11794            let cend = (s + chunk).min(t_total);
11795            let tc = cend - s;
11796            let ch = &tokens[s..cend];
11797            // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
11798            //    the chunk's true hiddens.
11799            let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
11800            for j in 0..tc {
11801                e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
11802            }
11803            let preds = e.dtoh_u32(&preds_d)?;
11804            for j in 0..tc {
11805                bg[s + j + 1] = preds[j];
11806            }
11807            // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
11808            // checkpoint-quality metric (position j's logits score the GOLD next token).
11809            if nll_on {
11810                let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
11811                if jmax > 0 {
11812                    let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
11813                    let rows: Vec<i32> = (0..jmax as i32).collect();
11814                    let idsd = e.htod_u32_v(&ids)?;
11815                    let rowsd = e.htod_i32(&rows)?;
11816                    let mut outd = e.zeros(jmax)?;
11817                    e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
11818                    for pr in e.dtoh(&outd)? {
11819                        nll_sum += -((pr.max(1e-30)) as f64).ln();
11820                        nll_cnt += 1;
11821                    }
11822                }
11823            }
11824            if let Some(f) = hdump.as_deref_mut() {
11825                use std::io::Write;
11826                let host: Vec<f32> = e.dtoh(&vx)?;
11827                // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
11828                // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
11829                let mut bytes = Vec::with_capacity(tc * n_embd * 2);
11830                for v in &host[..tc * n_embd] {
11831                    let b = v.to_bits();
11832                    let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
11833                    bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
11834                }
11835                f.write_all(&bytes)?;
11836            }
11837            // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
11838            // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
11839            // per token saved; the forced trunk pass + hdump is all the mode needs).
11840            let chainless = stride > t_total;
11841            if chainless {
11842                e.copy_view_into(
11843                    &mut prev_last_h,
11844                    0,
11845                    &vx.slice((tc - 1) * n_embd..tc * n_embd),
11846                    n_embd,
11847                )?;
11848                s = cend;
11849                continue;
11850            }
11851            // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
11852            //    row s reads the previous chunk's last true hidden, zeros at corpus start).
11853            let mut vxs = e.zeros(tc * n_embd)?;
11854            e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
11855            if tc > 1 {
11856                e.copy_view_into(
11857                    &mut vxs,
11858                    n_embd,
11859                    &vx.slice(0..(tc - 1) * n_embd),
11860                    (tc - 1) * n_embd,
11861                )?;
11862            }
11863            scratch.set_len(e, s)?;
11864            self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
11865            // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
11866            //    [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
11867            //    truncates those approximate appends before they can ever be read.
11868            let ps: Vec<usize> = (s..cend)
11869                .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
11870                .collect();
11871            for &p in ps.iter().rev() {
11872                scratch.set_len(e, p)?;
11873                if p == s {
11874                    e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
11875                } else {
11876                    e.copy_view_into(
11877                        &mut seed_buf,
11878                        0,
11879                        &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
11880                        n_embd,
11881                    )?;
11882                }
11883                let mut e_tok = tokens[p];
11884                let mut d_seed = e.clone_dtod(&seed_buf)?;
11885                let mut drafts: Vec<u32> = Vec::with_capacity(k);
11886                for j in 0..k {
11887                    let (dl_d, h_nextn) = self.mtp_head_forward_dev(
11888                        e,
11889                        mtp,
11890                        e_tok,
11891                        &d_seed,
11892                        &mut scratch,
11893                        p + 1 + j,
11894                        embd_dev,
11895                        None, // acceptance-oracle walk: no grammar
11896                    )?;
11897                    let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
11898                    let idx = e.dtoh_u32_one(&tok_d)?;
11899                    let d = match &mtp.d2t {
11900                        Some(map) => map[idx as usize],
11901                        None => idx,
11902                    };
11903                    drafts.push(d);
11904                    e_tok = d;
11905                    d_seed = h_nextn;
11906                }
11907                // targets may live in a LATER chunk's bg — resolved after the walk.
11908                rows.push((p, drafts, Vec::new()));
11909            }
11910            // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
11911            //    expect scratch.len == cend with exact rows).
11912            scratch.set_len(e, s)?;
11913            self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
11914            e.copy_view_into(
11915                &mut prev_last_h,
11916                0,
11917                &vx.slice((tc - 1) * n_embd..tc * n_embd),
11918                n_embd,
11919            )?;
11920            s = cend;
11921        }
11922        for (p, drafts, targets) in rows.iter_mut() {
11923            for j in 0..drafts.len() {
11924                targets.push(bg[*p + 1 + j]);
11925            }
11926        }
11927        rows.sort_by_key(|r| r.0);
11928        if nll_cnt > 0 {
11929            let mean = nll_sum / nll_cnt as f64;
11930            println!(
11931                "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
11932                mean.exp()
11933            );
11934        }
11935        Ok((rows, bg))
11936    }
11937}
11938
11939#[cfg(test)]
11940mod dspark_sparse_tests {
11941    use super::dspark_sparse_softmax_topk;
11942
11943    #[test]
11944    fn topk_keeps_full_softmax_mass_and_stable_ties() {
11945        let logits = [1.0f32, 3.0, 3.0, -2.0];
11946        let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
11947        assert_eq!(ids, vec![1, 2]);
11948        assert_eq!(top_logits, vec![3.0, 3.0]);
11949        let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
11950        let expected = 1.0 / denominator;
11951        assert!((probs[0] - expected).abs() < 1.0e-6);
11952        assert!((probs[1] - expected).abs() < 1.0e-6);
11953        assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
11954        assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
11955    }
11956}
11957
11958#[cfg(test)]
11959mod spec_replay_env_tests {
11960    use super::spec_replay_env_on;
11961
11962    #[test]
11963    fn replay_requires_literal_one() {
11964        assert!(!spec_replay_env_on(None));
11965        assert!(!spec_replay_env_on(Some("")));
11966        assert!(!spec_replay_env_on(Some("0")));
11967        assert!(!spec_replay_env_on(Some("true")));
11968        assert!(!spec_replay_env_on(Some("2")));
11969        assert!(spec_replay_env_on(Some("1")));
11970    }
11971}
11972
11973#[cfg(test)]
11974mod telem_tests {
11975    use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
11976
11977    #[test]
11978    fn synthetic_accept_masks_produce_tau_and_position_histogram() {
11979        let counters = SpecTelemetryCounters::default();
11980        for mask in [
11981            [true, true, true],
11982            [true, true, false],
11983            [true, false, false],
11984            [false, false, false],
11985        ] {
11986            let accepted = mask.iter().take_while(|&&value| value).count();
11987            counters.record_round(mask.len(), accepted);
11988        }
11989
11990        let snapshot = counters.snapshot();
11991        assert_eq!(
11992            (snapshot.rounds, snapshot.drafted, snapshot.accepted),
11993            (4, 12, 6)
11994        );
11995        assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
11996        assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
11997        assert_eq!(snapshot.tau(), 1.5);
11998        assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
11999        assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
12000    }
12001
12002    /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
12003    /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
12004    #[test]
12005    fn delta_isolates_burst_contribution() {
12006        let mut t = SpecTelemetry::default();
12007        // "previous request": 2 rounds of k=3, accepts 3 then 1.
12008        for (kr, na) in [(3usize, 3usize), (3, 1)] {
12009            t.rounds += 1;
12010            t.drafted += kr as u64;
12011            t.accepted += na as u64;
12012            for j in 0..kr {
12013                t.pos_drafted[j] += 1;
12014            }
12015            for j in 0..na {
12016                t.pos_accepted[j] += 1;
12017            }
12018        }
12019        let before = t;
12020        // "this burst": 1 round k=3, accepts 2.
12021        t.rounds += 1;
12022        t.drafted += 3;
12023        t.accepted += 2;
12024        for j in 0..3 {
12025            t.pos_drafted[j] += 1;
12026        }
12027        for j in 0..2 {
12028            t.pos_accepted[j] += 1;
12029        }
12030        let d = t.delta_since(&before);
12031        assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
12032        assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
12033        assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
12034        assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
12035    }
12036
12037    /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
12038    /// aggregation invariant.
12039    #[test]
12040    fn merge_accumulates_fieldwise() {
12041        let mut agg = SpecTelemetry::default();
12042        let mut d1 = SpecTelemetry {
12043            rounds: 2,
12044            drafted: 6,
12045            accepted: 4,
12046            ..Default::default()
12047        };
12048        d1.pos_drafted[0] = 2;
12049        d1.pos_accepted[0] = 2;
12050        let mut d2 = SpecTelemetry {
12051            rounds: 1,
12052            drafted: 3,
12053            accepted: 1,
12054            ..Default::default()
12055        };
12056        d2.pos_drafted[0] = 1;
12057        d2.pos_accepted[0] = 1;
12058        d2.pos_drafted[1] = 1;
12059        agg.merge(&d1);
12060        agg.merge(&d2);
12061        assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
12062        assert_eq!(agg.pos_drafted[0], 3);
12063        assert_eq!(agg.pos_accepted[0], 3);
12064        assert_eq!(agg.pos_drafted[1], 1);
12065        assert_eq!(agg.pos_accepted[1], 0);
12066    }
12067
12068    /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
12069    /// public metrics surface and must never publish a u64-wrapped garbage value.
12070    #[test]
12071    fn delta_saturates_never_wraps() {
12072        let small = SpecTelemetry {
12073            rounds: 1,
12074            drafted: 2,
12075            accepted: 1,
12076            ..Default::default()
12077        };
12078        let big = SpecTelemetry {
12079            rounds: 5,
12080            drafted: 15,
12081            accepted: 9,
12082            ..Default::default()
12083        };
12084        let d = small.delta_since(&big);
12085        assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
12086    }
12087}
12088
12089#[cfg(test)]
12090mod opti_fork_tests {
12091    use super::{
12092        OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
12093    };
12094
12095    #[test]
12096    fn controller_threshold_and_three_miss_breaker_are_exact() {
12097        let mut policy = OptiControllerPolicy {
12098            threshold: 0.7,
12099            consecutive_misses: 0,
12100            breaker_tripped: false,
12101        };
12102        assert!(!policy.admit(0.699_999));
12103        assert!(policy.admit(0.7));
12104        assert!(!policy.resolve(false));
12105        assert!(!policy.resolve(false));
12106        assert!(policy.resolve(false));
12107        assert!(policy.breaker_tripped);
12108        assert!(!policy.admit(1.0));
12109        assert!(
12110            !policy.resolve(true),
12111            "a resolved hit cannot re-arm a tripped request"
12112        );
12113        assert!(policy.breaker_tripped);
12114    }
12115
12116    #[test]
12117    fn zero_threshold_is_the_true_unconditional_measurement_arm() {
12118        let mut policy = OptiControllerPolicy {
12119            threshold: 0.0,
12120            consecutive_misses: 0,
12121            breaker_tripped: false,
12122        };
12123        for _ in 0..16 {
12124            assert!(policy.admit(0.0));
12125            assert!(!policy.resolve(false));
12126        }
12127        for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
12128            assert!(
12129                !policy.admit(invalid),
12130                "invalid q proxy must fail closed: {invalid}"
12131            );
12132        }
12133        assert!(!policy.breaker_tripped);
12134        assert_eq!(policy.consecutive_misses, 0);
12135    }
12136
12137    #[test]
12138    fn alternating_mode_flips_by_generation_not_round_parity() {
12139        assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
12140        assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
12141        assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
12142        assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
12143    }
12144
12145    #[test]
12146    fn live_generation_cannot_be_overwritten() {
12147        let mut tracker = OptiForkGenerationTracker::default();
12148        let g0 = tracker.reserve().unwrap();
12149        let g1 = tracker.reserve().unwrap();
12150        let err = tracker.reserve().unwrap_err().to_string();
12151        assert!(
12152            err.contains("still owns generation 0"),
12153            "unexpected error: {err}"
12154        );
12155        tracker.retire(g0).unwrap();
12156        let g2 = tracker.reserve().unwrap();
12157        assert_eq!((g2.id, g2.slot), (2, 0));
12158        tracker.retire(g1).unwrap();
12159        tracker.retire(g2).unwrap();
12160    }
12161
12162    #[test]
12163    fn teardown_rejects_a_stale_generation_tag() {
12164        let mut tracker = OptiForkGenerationTracker::default();
12165        let g0 = tracker.reserve().unwrap();
12166        tracker.retire(g0).unwrap();
12167        let err = tracker.retire(g0).unwrap_err().to_string();
12168        assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
12169    }
12170}
12171
12172#[cfg(test)]
12173mod draft_graph_fallback_tests {
12174    use super::DraftGraphFallback;
12175
12176    /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
12177    #[test]
12178    fn flip_is_loud_once_and_memoized_after() {
12179        let mut f = DraftGraphFallback::default();
12180        let line = f
12181            .mark_greedy("out of memory")
12182            .expect("first flip must return the warn line");
12183        assert!(
12184            line.contains("WARN"),
12185            "flip line must be warn-level: {line}"
12186        );
12187        assert!(
12188            line.contains("out of memory"),
12189            "flip line must carry the reason: {line}"
12190        );
12191        assert!(f.greedy_failed());
12192        // re-marking an already-failed graph is the memoization: quiet, still failed.
12193        assert!(f.mark_greedy("out of memory").is_none());
12194        assert!(f.greedy_failed());
12195        // the two graphs' flags are independent (greedy flip leaves sampled capturable).
12196        assert!(!f.sampled_failed());
12197        let line_s = f
12198            .mark_sampled("capture unsupported")
12199            .expect("sampled flip is its own flip");
12200        assert!(
12201            line_s.contains("sampled"),
12202            "sampled flip names itself: {line_s}"
12203        );
12204        assert!(f.mark_sampled("capture unsupported").is_none());
12205    }
12206
12207    /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
12208    /// and says so exactly when there was something to reset.
12209    #[test]
12210    fn reset_on_resume_clears_flags_and_logs_once() {
12211        let mut f = DraftGraphFallback::default();
12212        // clean session: resume is silent, nothing to reset.
12213        assert!(f.reset_on_resume().is_none());
12214        f.mark_greedy("oom").unwrap();
12215        f.mark_sampled("oom").unwrap();
12216        let note = f
12217            .reset_on_resume()
12218            .expect("a set flag must produce the reset note");
12219        assert!(
12220            note.contains("greedy+sampled"),
12221            "note names what was reset: {note}"
12222        );
12223        assert!(
12224            !f.greedy_failed() && !f.sampled_failed(),
12225            "both flags cleared"
12226        );
12227        // and the NEXT failure after a reset is a fresh flip — loud again.
12228        assert!(f.mark_greedy("oom again").is_some());
12229        let note2 = f.reset_on_resume().expect("greedy-only reset");
12230        assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
12231    }
12232
12233    /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
12234    /// they precede a fresh capture attempt whose own failure re-flips loudly.
12235    #[test]
12236    fn shape_change_clears_are_silent() {
12237        let mut f = DraftGraphFallback::default();
12238        f.mark_greedy("oom").unwrap();
12239        f.clear_greedy();
12240        assert!(!f.greedy_failed());
12241        f.mark_sampled("oom").unwrap();
12242        f.clear_sampled();
12243        assert!(!f.sampled_failed());
12244        // after a silent clear there is nothing left for resume to report.
12245        assert!(f.reset_on_resume().is_none());
12246    }
12247}
12248
12249/// SAMPLED DRAFT-GRAPH KEY (lane/graph-s-key-exactness-20260819).
12250///
12251/// These are the CPU teeth for an exactness bug whose live reproduction needs a GPU, a trunk, a
12252/// drafter and a two-turn session: the key itself. Every test below fails against the pre-fix key
12253/// `(seed, temp.to_bits(), k)` — `legacy_key` restates it so the collision is explicit rather
12254/// than remembered.
12255#[cfg(test)]
12256mod sampled_graph_key_tests {
12257    use super::{SampledGraphKey, debug_t_pred0};
12258
12259    /// The pre-fix key, verbatim: `let s_key = (sp_seed, sp_temp.to_bits(), k);`
12260    fn legacy_key(k: &SampledGraphKey) -> (u64, u32, usize) {
12261        (k.seed, k.temp_bits, k.k)
12262    }
12263
12264    fn pure_temp_key() -> SampledGraphKey {
12265        // temperature 1.0, filters off — today's serve default, the shape that parks a graph.
12266        SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, false)
12267    }
12268
12269    /// THE COLLISION. Two requests that differ ONLY in the truncation filters shared one key, so
12270    /// a parked pure-temp graph survived into a filtered request and the launch site launched it.
12271    #[test]
12272    fn vendor_filters_change_the_key() {
12273        let parked = pure_temp_key();
12274        // qwen3.8 generation_config.json — what the vendor-default flip makes the default shape.
12275        let vendor = SampledGraphKey::new(12345, 1.0, 3, 20, 0.95, 0.0, false);
12276        assert_eq!(
12277            legacy_key(&parked),
12278            legacy_key(&vendor),
12279            "pre-fix key collided: this is the bug, and the reason a test asserts on it",
12280        );
12281        assert_ne!(parked, vendor, "post-fix key must separate the two regimes");
12282        assert!(parked.pure_temp());
12283        assert!(!vendor.pure_temp());
12284    }
12285
12286    /// Each distribution-shaping field alone is enough to drop the parked graph.
12287    #[test]
12288    fn every_filter_field_is_keyed() {
12289        let base = pure_temp_key();
12290        for (what, other) in [
12291            (
12292                "top_k",
12293                SampledGraphKey::new(12345, 1.0, 3, 20, 1.0, 0.0, false),
12294            ),
12295            (
12296                "top_p",
12297                SampledGraphKey::new(12345, 1.0, 3, 0, 0.95, 0.0, false),
12298            ),
12299            (
12300                "min_p",
12301                SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.05, false),
12302            ),
12303            (
12304                "penalties",
12305                SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, true),
12306            ),
12307        ] {
12308            assert_ne!(base, other, "{what} must be part of the key");
12309            assert!(!other.pure_temp(), "{what} leaves the pure-temp regime");
12310            assert_eq!(
12311                legacy_key(&base),
12312                legacy_key(&other),
12313                "{what} was invisible to the pre-fix key",
12314            );
12315        }
12316    }
12317
12318    /// The baked constants stay keyed (this half was always right — regression cover for it).
12319    #[test]
12320    fn baked_constants_stay_keyed() {
12321        let base = pure_temp_key();
12322        assert_ne!(
12323            base,
12324            SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false),
12325            "seed"
12326        );
12327        assert_ne!(
12328            base,
12329            SampledGraphKey::new(12345, 0.7, 3, 0, 1.0, 0.0, false),
12330            "temp"
12331        );
12332        assert_ne!(
12333            base,
12334            SampledGraphKey::new(12345, 1.0, 4, 0, 1.0, 0.0, false),
12335            "k"
12336        );
12337        // bitwise on temperature: 0.7f32 vs the same value re-derived must NOT differ.
12338        assert_eq!(
12339            SampledGraphKey::new(1, 0.7, 3, 0, 1.0, 0.0, false),
12340            SampledGraphKey::new(1, 7.0 / 10.0, 3, 0, 1.0, 0.0, false),
12341        );
12342    }
12343
12344    /// THE LOAD-BEARING HALF OF THE SEED DECISION (lane/session-resume-sampler-predicate-
12345    /// 20260820). The whole-session resume predicate deliberately does NOT compare `seed`: an
12346    /// omitted serve `seed` draws fresh per-request entropy, so comparing it would refuse every
12347    /// seed-omitting sampled conversation. That is only sound because the one piece of parked state
12348    /// that BAKES the seed — this graph — is re-keyed on it, so a seed change drops and recaptures.
12349    ///
12350    /// This test is the other end of that argument, asserted here rather than remembered in a
12351    /// comment: if a future change dropped `seed` from the key, the resume predicate's exclusion
12352    /// would silently become the unsound thing it is documented not to be.
12353    /// (Paired with `seed_alone_does_not_refuse` in `memra-sampling`.)
12354    #[test]
12355    fn seed_alone_still_rekeys_the_draft_graph() {
12356        let parked = pure_temp_key();
12357        let reseeded = SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false);
12358        assert_ne!(
12359            parked, reseeded,
12360            "a seed-only change MUST drop the parked sampled graph — the resume predicate's \
12361             decision not to compare seed rests on exactly this",
12362        );
12363        // Same regime on both sides: the drop is a recapture, not a fall to the eager chain
12364        // because of a filter difference.
12365        assert!(parked.pure_temp() && reseeded.pure_temp());
12366    }
12367
12368    /// `pure_temp()` is the capture guard's predicate, computed from the key so the two cannot
12369    /// drift. The equality below is the invariant the launch-site guard asserts: identical keys
12370    /// agree on the regime, so a graph that survives the drop is legal to launch.
12371    #[test]
12372    fn equal_keys_agree_on_the_regime() {
12373        let a = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
12374        let b = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
12375        assert_eq!(a, b);
12376        assert_eq!(a.pure_temp(), b.pure_temp());
12377        // top_p slightly above 1.0 (a client sending 1.0 exactly, or an operator default) is
12378        // still the unfiltered regime, matching the original `sp.top_p >= 1.0` test.
12379        assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.0, 0.0, false).pure_temp());
12380        assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.5, -1.0, false).pure_temp());
12381    }
12382
12383    /// MEMRA_DEBUG_SPEC on a SAMPLED spec request past round 0: the print must render without
12384    /// indexing the empty greedy `preds` vector (it panicked the GPU worker before this lane).
12385    #[test]
12386    fn debug_print_survives_the_sampled_arm() {
12387        // round >= 1 with a pending bonus == base 1, sampled == `preds` empty.
12388        assert_eq!(debug_t_pred0(true, 1, 4242, &[]), "n/a");
12389        assert_eq!(debug_t_pred0(true, 2, 4242, &[]), "n/a");
12390        // round 0 without a pending bonus still reports last_pred, in both arms.
12391        assert_eq!(debug_t_pred0(true, 0, 4242, &[]), "4242");
12392        assert_eq!(debug_t_pred0(false, 0, 4242, &[7, 8]), "4242");
12393        // greedy keeps the real prediction it always printed.
12394        assert_eq!(debug_t_pred0(false, 1, 4242, &[7, 8]), "7");
12395        assert_eq!(debug_t_pred0(false, 2, 4242, &[7, 8]), "8");
12396    }
12397}