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 + fa-execupdate slice 4c (DSF-ROUNDCOST-20260820 §5 rank 1),
212/// DEFAULT OFF — `MEMRA_DSPARK_VERIFY_GRAPH=1` opts in: per-(segment, vt) CUDA graphs
213/// for the LINEAR-layer runs, plus the full-verify single graph per (vt, rung) when a
214/// round's rows all ride one seqs rung — see [`DsparkVerifyGraphs`]. Requires the
215/// slice-2 deferred path (device tokens); the eager walk is the byte-identical fallback.
216///
217/// MEASURED disposition (box6 card0, agentic pack, 2026-08-20, both slices): exactness
218/// holds everywhere (ALL EXACT, accept lines byte-match the banks, ckpt-gate oracle
219/// green over the graph + slab-commit paths). Slice-3's AUTO_FREE launch-scan limiter
220/// (25.6 us x 16 launches ≈ 0.41 ms/round) is FIXED — the captured bodies' alloc nodes
221/// are balanced by in-graph frees (census 84/84 per segment, 1776/1776 full) so graphs
222/// instantiate USE_NODE_PRIORITY and the scan is gone. What remains at gate scale:
223/// segment graphs +0.1 tok/s over the batched-rows default (114.4 vs 114.3 x5
224/// interleaved — the linear launch overhead was only ~0.1 ms); the FULL-verify graph is
225/// NET NEGATIVE at gate scale (110.6 vs 114.2: ~14-21 (vt, rung) captures/process at
226/// 2 full-walk executions + ~2.9k-node instantiate each eat far more than the ~0.2-0.3
227/// ms/round of remaining launch overhead). The orchestration ceiling of §1.3 is spent —
228/// the fa/append recovery landed DEFAULT-ON as the batched rows arm
229/// (`dspark_fa_rows_on`), not as a graph. The serve-lifetime cell (DSF-ROUNDCOST §9,
230/// nj-ws-solo) measured the amortization: crossover K≈33 requests, steady −0.246
231/// ms/round, −1.25% session wall over 240 requests — and the graphs-serve lane wired
232/// the door into the session arm (`dspark_spec_session_burst`) as a model-owned
233/// capture pool shared across sessions. Stays opt-in pending the owner's default-ON
234/// ratification on the serve-surface battery.
235pub(crate) fn dspark_verify_graph_on() -> bool {
236    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
237    *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() == Ok("1"))
238}
239/// MTP-ROUTE verify graphs, DEFAULT ON for the GDN+MoE family since 2026-08-23
240/// (`MEMRA_SPEC_VERIFY_GRAPH=0` is the kill switch, `=1` opts other families in).
241///
242/// The slice-4c capture already lived inside `qwen35_verify_tparallel` and said so in its own
243/// comment — "stream rides the qwen35moe burst, graphs ride the dspark route" — with no caller
244/// on this route. The MTP spec round is that caller.
245///
246/// WHY it is worth a default (receipts: `research/orndecode-20260822/VGRAPH.md`). With
247/// `MEMRA_SPEC_PHASE=1` this route's round reads verify-ISSUE 44-58% and verify-WAIT **0.0%**:
248/// the host is never waiting for the device, it is spending its own time launching the trunk.
249/// Replay collapses that into one graph launch and the phase all but disappears (55-62 ms ->
250/// 8-10 ms per burst).
251///
252/// MEASURED, two host generations, forced ON/OFF, balanced 4+4 boots in both orders:
253///   * current-generation host (9950X, the serving class): OFF 266.0-266.5, ON 318.8-319.5
254///     tok/s — **+19.7%**, no overlap, sub-1% spread per arm; per-round 6.9 -> 5.7 ms.
255///   * Zen 3 host: +3-9% (that rig's own clock drift is wider than the effect, so the ratio
256///     comes from per-round phase totals, which are internal to each boot).
257/// The ON arm lands at ~320 tok/s on BOTH hosts while OFF tracks host speed — the arm moves
258/// the round off the host and onto the device, which is the whole point.
259///
260/// EXACTNESS is structural (same kernels, same order) and gated anyway: a fixed-seed SAMPLED
261/// completion hashes identically ON vs OFF **and across both hosts** (`08941d5bb9762b21`),
262/// greedy seed-pinned likewise, `run-spec` K=1..8 PASS on both arms with identical acceptance
263/// at every K, kernel-check ALL GREEN.
264///
265/// SCOPE, deliberately narrow: default ON only where it was measured — the GatedDeltaNet +
266/// MoE family (`vgraph_family_default`). Qwen3.8-27B is GDN + DENSE mlp and would otherwise
267/// inherit this default unmeasured, which is the family-by-family law this repo keeps; it can
268/// opt in with `=1` once it has its own interleave. Also never armed together with
269/// ROUND-STREAM, and a round wider than the pool declines it for the eager walk.
270pub(crate) fn spec_verify_graph_env() -> Option<bool> {
271    static ON: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
272    *ON.get_or_init(
273        || match std::env::var("MEMRA_SPEC_VERIFY_GRAPH").as_deref() {
274            Ok("1") => Some(true),
275            Ok("0") => Some(false),
276            _ => None,
277        },
278    )
279}
280/// SERVE-ROUTE twin of [`dspark_verify_graph_on`], DEFAULT ON — owner-ratified
281/// 2026-08-22 on the §10 serve-lifetime battery (DSF-ROUNDCOST-20260820 §10.3:
282/// crossover K=36–43, steady −0.357 ms/round, session wall −1.55..−1.65%, byte-exact
283/// 240/240 ×3 pairs, pool bounded at 8,852 MiB under `MEMRA_DSPARK_VG_MAX`). The env
284/// stays as the kill-switch: `MEMRA_DSPARK_VERIFY_GRAPH=0` restores the eager walk
285/// (byte-identical body); `MEMRA_DSPARK_VG_MAX=0` is the finer freeze valve. The BIN
286/// arm keeps its own opt-in default (`dspark_verify_graph_on`): at gate scale the
287/// capture toll is never repaid (§8 measured disposition — 14–21 captures over a
288/// 256-token run vs the serve session's thousands of rounds), and the two
289/// instruments must keep their own measured dispositions rather than share one flag.
290pub(crate) fn dspark_verify_graph_serve_on() -> bool {
291    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
292    *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() != Ok("0"))
293}
294/// Capture-count ceiling for the dspark verify-graph pool (graphs-serve lane) — the
295/// pool's memory policy STATED instead of silently unbounded. The keyspace is
296/// intrinsically finite — segment keys (run_start, vt) ≤ 16 runs x 7 windows, full
297/// keys (vt, rung, hi) ≤ 7 windows x the split-rung ladder (8 rungs at 32k ctx), ~168
298/// on the q38 export — so the default (256) never engages there; the knob is the
299/// safety valve for a future export with a wider ladder. At the ceiling the pool
300/// FREEZES: existing keys keep replaying, rounds needing a new capture run the eager
301/// walk byte-identically (round-atomic — a partial refusal would mix slab- and
302/// cols-stashed layers inside one commit). No eviction by design: destroying a live
303/// exec graph re-opens the stale-address class the indirect tables exist to close,
304/// and the bounded keyspace makes reclaim worthless.
305pub(crate) fn dspark_vg_cap() -> usize {
306    static CAP: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
307    *CAP.get_or_init(|| {
308        std::env::var("MEMRA_DSPARK_VG_MAX")
309            .ok()
310            .and_then(|v| v.parse().ok())
311            .unwrap_or(256)
312    })
313}
314/// Engine-bundle slice 4 (fa-execupdate lane, DSF-ROUNDCOST-20260820 §6 close: "the
315/// residual gap lives in the FULL-ATTENTION per-row section"), DEFAULT ON —
316/// `MEMRA_DSPARK_FA_ROWS=0` reverts to the per-row loop: when every row of a verify
317/// round takes the v4-seqs arm on ONE `fa_split_keys` rung (the straddle law, evaluated
318/// at the round's first and last t_kv — both eligibility gates are intervals in t_kv),
319/// the qwen35 t-parallel verify's per-row KV-append + fa-decode loop collapses into the
320/// z-batched serving twins: ONE `append_quantize_kv_q8_0_q5_1_seqs` + ONE
321/// `fa_decode_vec_q_seqs_v4` + ONE combine per full-attention layer, replacing
322/// T x (4 dtod row copies + append + 3 memsets + main + combine) launches. Bytes are
323/// pinned by the batched-tick increment-2 kernel-check (seqs-vs-per-seq-loop bit
324/// identity: per-row T_kv derives in-kernel from pos_seq[z]; splits >= ns_eff write the
325/// empty partial the combine never reads, so the shared n_splits_max stride changes no
326/// bytes) and re-gated e2e by this lane's battery.
327pub(crate) fn dspark_fa_rows_on() -> bool {
328    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
329    *ON.get_or_init(|| {
330        std::env::var("MEMRA_DSPARK_FA_ROWS")
331            .map(|v| v != "0")
332            .unwrap_or(true)
333    })
334}
335
336/// `t_pred0` for the `MEMRA_DEBUG_SPEC` per-round print, sampled-safe.
337///
338/// `generate_spec_inner2` fills its `preds` vector ONLY on the greedy path (`if !sampled`), and
339/// the per-round debug print was the sole consumer in the sampled arm: `t_pred(0)` survives round
340/// 0 (`base == 0` returns `last_pred`) and from round 1 (`base == 1`, a pending bonus) indexes an
341/// EMPTY vector — `index out of bounds: the len is 0 but the index is 0`, in the GPU worker
342/// thread, which then respawns and reloads weights while the request dies. So any sampled spec
343/// request longer than one round used to kill the worker whenever `MEMRA_DEBUG_SPEC` was set:
344/// the flag crashed precisely the regime it exists to investigate.
345///
346/// Fixed at the print site, not inside the closure, so the greedy accept walk keeps its strict
347/// indexing (an out-of-range pred there is a real bug and must still be loud).
348fn debug_t_pred0(sampled: bool, base: usize, last_pred: u32, preds: &[u32]) -> String {
349    if base == 0 {
350        return last_pred.to_string();
351    }
352    match preds.get(base - 1) {
353        Some(p) => p.to_string(),
354        // sampled: the greedy per-column argmax was never run for this round.
355        None => {
356            debug_assert!(
357                sampled,
358                "greedy spec: preds[{}] missing at base {base}",
359                base - 1
360            );
361            "n/a".to_string()
362        }
363    }
364}
365
366/// `MEMRA_SKEY_PROBE=1` — sampled-draft-graph key probe (lane/graph-s-key-exactness-20260819).
367///
368/// Reports, per burst and per round, which draft chain the sampled arm chose and under which
369/// filter regime, plus the ONE observable that separates a legal filtered draft from a stale
370/// pure-temp graph replayed under filters: an accept test whose gathered `q` is exactly 0.
371/// A draft token sampled from the FILTERED softmax can never gather q=0 (it was drawn from the
372/// kept set), so `q=0` in the verify means the draft came from a distribution the verify does
373/// not believe in — and `u * 0 < p` then accepts it unconditionally.
374///
375/// Its own env var, deliberately NOT `MEMRA_DEBUG_SPEC`: that flag panicked the GPU worker on
376/// any sampled spec request past round 0 until this lane fixed it (§2 of the bank note).
377pub(crate) fn skey_probe() -> bool {
378    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
379    *ON.get_or_init(|| std::env::var("MEMRA_SKEY_PROBE").as_deref() == Ok("1"))
380}
381
382/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
383/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
384/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
385/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
386/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
387/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
388/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
389/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
390/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
391pub trait SpecConstraint {
392    /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
393    /// masked argmax).
394    fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
395    /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
396    fn mask_words(&mut self) -> Result<Vec<u32>, String>;
397    /// Is `tok` consumable in the CURRENT state?
398    fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
399    /// Advance the state with an emitted token.
400    fn consume(&mut self, tok: u32) -> Result<(), String>;
401
402    // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
403    // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
404    // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
405    // loose, research/constrained-full-20260803). These three methods let the engine mask the
406    // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
407    // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
408    // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
409    // stays the correctness backstop and the emitted stream is unchanged by construction
410    // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
411    // argmax; a cut slot is recomputed as the masked argmax either way).
412    // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
413
414    /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
415    /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
416    fn draft_mask_enabled(&self) -> bool {
417        false
418    }
419    /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
420    /// slot. Called once per spec round, before the first draft position.
421    fn draft_begin(&mut self) -> Result<(), String> {
422        Ok(())
423    }
424    /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
425    /// for the draft position about to be sampled. `None` = draft masking off (no-op).
426    fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
427        Ok(None)
428    }
429    /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
430    /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
431    /// engine stops drafting; the token already pushed still goes through verify.
432    fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
433        Ok(false)
434    }
435}
436
437/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
438/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
439/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
440/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
441/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
442/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
443/// verify emits the masked argmax as usual).
444fn upload_draft_mask(
445    e: &Engine,
446    c: &mut dyn SpecConstraint,
447    dst: &mut CudaSlice<u32>,
448    d2t: Option<&Vec<u32>>,
449    d_vocab: usize,
450    words: usize,
451) -> Result<bool, Box<dyn std::error::Error>> {
452    let Some(tw) = c
453        .draft_mask_words()
454        .map_err(|e2| format!("constraint: {e2}"))?
455    else {
456        return Ok(false);
457    };
458    let bit = |t: usize| -> bool {
459        let w = t >> 5;
460        w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
461    };
462    let mut buf = vec![0u32; words];
463    match d2t {
464        // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
465        Some(map) => {
466            for (i, &t) in map.iter().enumerate().take(d_vocab) {
467                if bit(t as usize) {
468                    buf[i >> 5] |= 1u32 << (i & 31);
469                }
470            }
471        }
472        // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
473        // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
474        None => {
475            let n = tw.len().min(words);
476            buf[..n].copy_from_slice(&tw[..n]);
477        }
478    }
479    if buf.iter().all(|w| *w == 0) {
480        return Ok(false);
481    }
482    e.htod_u32_into(dst, &buf)?;
483    Ok(true)
484}
485
486/// Keep the full token-embedding table in host memory and upload only the rows needed by each
487/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
488/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
489/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
490pub(crate) fn spec_host_embd() -> bool {
491    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
492    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
493}
494
495/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
496/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
497/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
498/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
499/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
500/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
501/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
502/// run-spec K=1..8 + acceptance identity arbitrate e2e).
503pub(crate) fn spec_fused_t() -> bool {
504    static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
505    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
506    // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
507    // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
508    *F.get_or_init(|| {
509        std::env::var("MEMRA_SPEC_FUSED_T")
510            .map(|v| v != "0")
511            .unwrap_or(true)
512    })
513}
514
515/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
516/// Only call this on such buffers — the lean contract is "identical bytes by construction".
517fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
518    if spec_lean() { e.uninit(n) } else { e.zeros(n) }
519}
520
521/// Scratch KV for the MTP block (one full-attn layer).
522///
523/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
524/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
525/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
526/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
527/// engine's "mtp_update" design). Entries come from two sources:
528///   - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
529///     hidden chain-approximate — the reference engine accepts the same);
530///   - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
531///     from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
532/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
533/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
534/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
535/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
536/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
537/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
538/// committed row across turns (the predecessor-pairing seed + fill anchor).
539/// Per-request sampling config for the sampled-spec serve path.
540#[derive(Clone, Copy, Debug)]
541pub struct SpecSampling {
542    pub temp: f32,
543    pub seed: u64,
544    pub top_k: i32,            // 0 = off
545    pub top_p: f32,            // 1.0 = off
546    pub min_p: f32,            // 0.0 = off
547    pub penalty_last_n: usize, // 0 = penalties off
548    pub penalty_repeat: f32,
549    pub penalty_freq: f32,
550    pub penalty_present: f32,
551}
552
553impl SpecSampling {
554    /// Non-identity penalties requested — THE `pen_on` predicate (one definition; the
555    /// same group-off rule `SamplerIdentity::of` canonicalizes: a window with neutral
556    /// coefficients is penalties-absent). Both spec routes and the dspark accept walk
557    /// key their penalty arms off this.
558    pub fn pen_on(&self) -> bool {
559        self.penalty_last_n > 0
560            && (self.penalty_repeat != 1.0
561                || self.penalty_freq != 0.0
562                || self.penalty_present != 0.0)
563    }
564}
565
566/// Host Philox4x32-10 uniform in (0,1) — mirrors spec_sample.cu's `philox4`/`u01` with the
567/// ctr_lo tag 0xFFFF_FFFE, so the host accept-test stream never collides with any device
568/// sampling event (device Gumbel uses (i>>2, stream_pos); device residual uses 0xFFFF_FFFD).
569/// One value per (seed, ctr) EVENT; callers own the counter discipline. Extracted verbatim
570/// from generate_spec_inner2's closure for the dspark sampled-admission walk (the two paths
571/// MUST consume the identical stream construction — two ad-hoc Philox copies drifting apart
572/// is a distributional bug, not a style problem).
573pub(crate) fn host_u01(seed: u64, ctr: u32) -> f32 {
574    let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
575    let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
576    let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
577    for _ in 0..10 {
578        let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
579        let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
580        let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
581        c0 = n0;
582        c1 = n1;
583        c2 = n2;
584        c3 = n3;
585        k0 = k0.wrapping_add(0x9E3779B9);
586        k1 = k1.wrapping_add(0xBB67AE85);
587    }
588    (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
589}
590
591/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
592/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
593pub const SPEC_TELEM_POS: usize = 8;
594
595/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
596/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
597/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
598/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
599/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
600/// in NEITHER drafted nor accepted.
601#[derive(Clone, Copy, Default, Debug)]
602pub struct SpecTelemetry {
603    /// verify rounds completed (a round-stream burst counts each of its M rounds).
604    pub rounds: u64,
605    /// tokens drafted / accepted across all rounds.
606    pub drafted: u64,
607    pub accepted: u64,
608    /// how often draft position j (0-based within a round's chain) was offered / accepted.
609    /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
610    /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
611    /// arrays cover the standard-path rounds only and their sums may undercount the totals.
612    pub pos_drafted: [u64; SPEC_TELEM_POS],
613    pub pos_accepted: [u64; SPEC_TELEM_POS],
614}
615
616impl SpecTelemetry {
617    /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
618    /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
619    /// a wrapped counter.
620    pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
621        let mut d = SpecTelemetry {
622            rounds: self.rounds.saturating_sub(prev.rounds),
623            drafted: self.drafted.saturating_sub(prev.drafted),
624            accepted: self.accepted.saturating_sub(prev.accepted),
625            ..Default::default()
626        };
627        for j in 0..SPEC_TELEM_POS {
628            d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
629            d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
630        }
631        d
632    }
633    /// Fieldwise `self += d` — the worker's per-model aggregation.
634    pub fn merge(&mut self, d: &SpecTelemetry) {
635        self.rounds += d.rounds;
636        self.drafted += d.drafted;
637        self.accepted += d.accepted;
638        for j in 0..SPEC_TELEM_POS {
639            self.pos_drafted[j] += d.pos_drafted[j];
640            self.pos_accepted[j] += d.pos_accepted[j];
641        }
642    }
643
644    /// Mean accepted draft-prefix length per verify round (tau).
645    pub fn tau(&self) -> f64 {
646        if self.rounds > 0 {
647            self.accepted as f64 / self.rounds as f64
648        } else {
649            0.0
650        }
651    }
652}
653
654/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
655/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
656/// launch, synchronization, allocation, or ordering dependency to the numeric path.
657struct SpecTelemetryCounters {
658    rounds: AtomicU64,
659    drafted: AtomicU64,
660    accepted: AtomicU64,
661    pos_drafted: [AtomicU64; SPEC_TELEM_POS],
662    pos_accepted: [AtomicU64; SPEC_TELEM_POS],
663}
664
665impl Default for SpecTelemetryCounters {
666    fn default() -> Self {
667        Self {
668            rounds: AtomicU64::new(0),
669            drafted: AtomicU64::new(0),
670            accepted: AtomicU64::new(0),
671            pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
672            pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
673        }
674    }
675}
676
677impl SpecTelemetryCounters {
678    fn record_round(&self, drafted: usize, accepted: usize) {
679        debug_assert!(accepted <= drafted);
680        self.rounds.fetch_add(1, Ordering::Relaxed);
681        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
682        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
683        for counter in self.pos_drafted.iter().take(drafted) {
684            counter.fetch_add(1, Ordering::Relaxed);
685        }
686        for counter in self.pos_accepted.iter().take(accepted) {
687            counter.fetch_add(1, Ordering::Relaxed);
688        }
689    }
690
691    /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
692    /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
693    fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
694        self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
695        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
696        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
697    }
698
699    fn snapshot(&self) -> SpecTelemetry {
700        SpecTelemetry {
701            rounds: self.rounds.load(Ordering::Relaxed),
702            drafted: self.drafted.load(Ordering::Relaxed),
703            accepted: self.accepted.load(Ordering::Relaxed),
704            pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
705            pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
706        }
707    }
708}
709
710pub struct SpecSession {
711    pub(crate) cache: Cache,
712    pub(crate) scratch: MtpScratch,
713    /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
714    /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
715    /// session must count them. Callers render output from this, not from their own echo.
716    pub committed: Vec<u32>,
717    /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
718    pub(crate) last_h: Option<CudaSlice<f32>>,
719    /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
720    /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
721    /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
722    pub next_pred: Option<u32>,
723    /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
724    /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
725    pub sctr: u32,
726    pub uctr: u32,
727    /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
728    /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
729    /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
730    /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
731    /// research/spec-serving-20260801). None before the first turn; error paths drop it
732    /// (next burst recaptures — serve retires errored sessions anyway).
733    pub(crate) draft_ctx: Option<DraftGraphCtx>,
734    /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
735    /// emitted by the last round but NOT committed to the caches. The old tail committed it with
736    /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
737    /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
738    /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
739    /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
740    /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
741    /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
742    /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
743    /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
744    /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
745    pub pending_tok: Option<u32>,
746    /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
747    /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
748    /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
749    /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
750    pub(crate) turn_ckpt: Option<SpecCheckpoint>,
751    /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
752    /// accounting the loop already does — no syncs, no allocation. NOTE a
753    /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
754    /// diff with [`SpecTelemetry::delta_since`] around each burst.
755    telem: SpecTelemetryCounters,
756    /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
757    /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
758    /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
759    /// prime, result lands in `boundary_captures`.
760    pub capture_at: Option<usize>,
761    /// The captures the last prime produced (see [`SpecBoundaryCapture`]). Worker drains them
762    /// post-burst to assemble prefix entries. A failed capture is silent, like `turn_ckpt` —
763    /// publication just isn't available for that request. Plural since
764    /// lane/frspec-multiturn-cache (2026-08-21): a cold burst can capture BOTH the miss-LCP
765    /// split (the shared-prefix class) and the stable pre-generation boundary (the
766    /// next-turn re-render class) — one entry per stop, exactly the boundary set the plain
767    /// prefill tick publishes/checkpoints.
768    pub boundary_captures: Vec<SpecBoundaryCapture>,
769    /// STABLE-BOUNDARY TURN CHECKPOINT REQUEST (lane/frspec-multiturn-cache, 2026-08-21): the
770    /// ABSOLUTE committed-length position the next non-empty prime should capture `turn_ckpt`
771    /// at, instead of prompt-end. The worker sets it to the STABLE PRE-GENERATION boundary
772    /// (`plain_checkpoint_boundary` — before the live generation header the client rewrites),
773    /// porting the 2026-08-09 plain-tier fix: a prompt-end spec checkpoint includes the
774    /// template's live assistant-generation header (`<|im_start|>assistant\n<think>\n`), which
775    /// the NEXT turn's re-render replaces, so `affinity_match` diverged a couple tokens below
776    /// the checkpoint and the spec pool declined 100% of multi-turn agent traffic (measured:
777    /// `spec-affinity: declined (history diverged at 6811 of checkpoint 6813)`,
778    /// research/multiturn-cache-20260821 B4). One-shot, `capture_at` convention; None = legacy
779    /// prompt-end capture.
780    pub ckpt_at: Option<usize>,
781}
782impl SpecSession {
783    /// Context capacity of the session's caches (the server's ContextFull guard).
784    pub fn cache_max_ctx(&self) -> usize {
785        self.cache.max_ctx
786    }
787    /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
788    /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
789    /// those rows are append-only for the session's lifetime (rollbacks never truncate below
790    /// the prime boundary), so no copy was taken at prime time.
791    pub fn cache_ref(&self) -> &Cache {
792        &self.cache
793    }
794    /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
795    /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
796    /// like the trunk KV — draft rows below the prompt end are append-only for the
797    /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
798    /// committed length, never below the prime boundary, and the true-hidden refresh
799    /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
800    /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
801    /// prefix-addressable; the prefix cache already refuses that class end to end).
802    pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
803        if self.scratch.kv.ring.is_some() {
804            return None;
805        }
806        Some((
807            &self.scratch.kv.k,
808            &self.scratch.kv.v,
809            self.scratch.kv.k_tok_bytes,
810            self.scratch.kv.v_tok_bytes,
811        ))
812    }
813    /// Snapshot the session's process-local acceptance counters for per-burst diffing.
814    pub fn telemetry(&self) -> SpecTelemetry {
815        self.telem.snapshot()
816    }
817    /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
818    /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
819    /// `spec_rewind_to_checkpoint`.
820    pub fn rewind_pos(&self) -> Option<usize> {
821        self.turn_ckpt.as_ref().map(|c| c.pos)
822    }
823    /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
824    pub fn rewind_is_resident(&self) -> bool {
825        self.turn_ckpt.as_ref().is_some_and(|ckpt| {
826            self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
827        })
828    }
829    /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
830    /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
831    /// session has never run a turn and has no prediction to hand over.
832    pub fn demote_ready(&self) -> bool {
833        self.pending_tok.is_none() && self.next_pred.is_some()
834    }
835    /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
836    pub fn has_pending(&self) -> bool {
837        self.pending_tok.is_some()
838    }
839    /// Committed row count == cache rows (the session invariant), for the caller's own
840    /// `fed`-length cross-check at a handoff boundary.
841    pub fn committed_len(&self) -> usize {
842        self.committed.len()
843    }
844    /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
845    /// cache + next-token prediction to the plain batched-decode path.
846    ///
847    /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
848    /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
849    /// tokenwise prime of the same `committed` sequence would have left it (that is the
850    /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
851    /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
852    /// committed row — and verify-column logits are bit-identical to plain decode's logits at
853    /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
854    /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
855    /// a state indistinguishable from one the batched path produced itself: the batched tick
856    /// emits `next_pred`, feeds it into this same cache, and decodes on.
857    ///
858    /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
859    /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
860    /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
861    /// path would silently skip a token.
862    ///
863    /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
864    /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
865    /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
866    /// would mean an `mtp_kv_fill` over the whole committed history).
867    pub fn into_demoted(self) -> Option<(Cache, u32)> {
868        if self.pending_tok.is_some() {
869            return None;
870        }
871        let np = self.next_pred?;
872        debug_assert_eq!(
873            self.cache.pos,
874            self.committed.len(),
875            "demotion handoff: cache rows != committed tokens"
876        );
877        Some((self.cache, np))
878    }
879    /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
880    /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
881    /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
882    /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
883    pub fn reset_graph_fallback_on_resume(&mut self) {
884        if let Some(line) = self
885            .draft_ctx
886            .as_mut()
887            .and_then(|c| c.failed.reset_on_resume())
888        {
889            eprintln!("{line}");
890        }
891    }
892}
893
894/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
895///
896/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
897/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
898/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
899/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
900/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
901/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
902///
903/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
904/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
905/// position index, so it must be a real device COPY — that copy is the entire reason a spec
906/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
907/// below the boundary were written by this turn's fill and are never revisited (the per-round
908/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
909/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
910/// predecessor-pairing anchor the next prime's fill reads for its first row.
911///
912/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
913pub(crate) struct SpecCheckpoint {
914    snap: crate::cache::CacheSnapshot,
915    /// Committed length at the boundary (== cache.pos there, the session invariant).
916    pos: usize,
917    /// Pre-output_norm hidden of row `pos - 1`.
918    last_h: CudaSlice<f32>,
919}
920
921/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
922/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
923/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
924/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
925/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
926/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
927/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
928/// so the worker slices those from the live caches post-burst instead of copying at prime time.
929pub struct SpecBoundaryCapture {
930    pub snap: crate::cache::CacheSnapshot,
931    /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
932    pub pos: usize,
933    /// Full-vocab logits after the prefix prime — the entry's boundary logits.
934    pub logits: Vec<f32>,
935    /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
936    /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
937    /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
938    /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
939    pub last_h: Vec<f32>,
940}
941
942/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
943/// spec boundary capture carries for later restored-session fills. Failure is silent
944/// (`turn_ckpt` convention): the capture publishes without an anchor.
945fn capture_boundary_hidden(
946    e: &Engine,
947    h_rows: &CudaSlice<f32>,
948    pos: usize,
949    n_embd: usize,
950) -> Vec<f32> {
951    if pos == 0 || h_rows.len() < pos * n_embd {
952        return Vec::new();
953    }
954    let Ok(mut row) = e.uninit(n_embd) else {
955        return Vec::new();
956    };
957    if e.copy_view_into(
958        &mut row,
959        0,
960        &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
961        n_embd,
962    )
963    .is_err()
964    {
965        return Vec::new();
966    }
967    e.dtoh(&row).unwrap_or_default()
968}
969
970/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
971/// Default ON: the token a burst emits at its own boundary is drawn from the request's
972/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
973/// every boundary) without touching greedy, which is byte-unaffected either way.
974pub fn spec_sampled_boundary_on() -> bool {
975    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
976    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
977}
978
979/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
980/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
981/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
982/// restores the pre-lane posture (each burst restarts the window from its own prompt
983/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
984/// must keep refusing penalized sampled prefix-cache restores, because the restored
985/// session's continuation burst is handed no prompt slice at all.
986pub fn spec_pen_session_on() -> bool {
987    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
988    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
989}
990
991/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
992/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
993/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
994/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
995/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
996/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
997pub fn spec_restore_republish_on() -> bool {
998    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
999    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
1000}
1001
1002/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
1003/// the argmax the pre-lane code would have emitted from the same row. This is how the
1004/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
1005fn spec_boundary_trace() -> bool {
1006    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1007    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
1008}
1009
1010/// llama-parity floor for the penalty window when the request does not ask for a bigger
1011/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = usize::MAX` for any
1012/// non-identity penalty, so this floor only matters to explicit small windows and to the
1013/// CLI env path.
1014const PEN_WINDOW_FLOOR: usize = 64;
1015
1016/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
1017/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
1018/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
1019/// p column, the bonus column). The serve API arms `penalty_last_n = usize::MAX` for ANY
1020/// non-identity penalty — "the whole context", llama's `repeat_last_n = -1` — so an
1021/// uncapped session window would put a 128k-token history through that kernel: ~1.7e10
1022/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
1023/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
1024/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
1025/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
1026/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
1027/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
1028/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route's accept walk and
1029/// the dspark_sample_gate binary trim their uploads with the SAME cap — a second constant
1030/// is a second thing to drift.
1031pub const PEN_WINDOW_MAX: usize = 8192;
1032
1033/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
1034/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
1035/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
1036/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
1037/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
1038/// client actually asked us to penalize, where the pre-lane code had NOTHING.
1039/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route seeds its session
1040/// window through the SAME function (one definition of "the window" across both spec
1041/// routes and the gate binary's trunk-only reference arm).
1042pub fn pen_window_seed(
1043    session_committed: &[u32],
1044    burst_prompt: &[u32],
1045    penalty_last_n: usize,
1046) -> Vec<u32> {
1047    let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
1048    let take_prompt = burst_prompt.len().min(win);
1049    let take_sess = (win - take_prompt).min(session_committed.len());
1050    let mut hist = Vec::with_capacity(take_sess + take_prompt);
1051    hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
1052    hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
1053    hist
1054}
1055
1056/// Draw a BOUNDARY token from the target distribution the request asked for
1057/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
1058/// every burst boundary".
1059///
1060/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
1061/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
1062/// row after the last committed token on a continuation burst; the prefix-cache entry's
1063/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
1064/// regimes, so a sampled stream took a greedy token once per burst — measured, not
1065/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
1066/// customer asked for a sampled token, so this draws one.
1067///
1068/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
1069/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
1070/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
1071/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
1072/// composition means `sample_check`'s distributional oracle covers this draw too, and the
1073/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
1074///
1075/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
1076/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
1077/// stream the accept walk uses — never a second, independently seeded stream (which would be
1078/// a new distributional bug: two streams from one seed correlate wherever their counters
1079/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
1080/// to the cold session's own first draw from the same logits row, which is what preserves the
1081/// sampled-hit lane's per-seed hit==cold byte identity.
1082#[allow(clippy::too_many_arguments)]
1083pub fn sample_boundary_token_dev(
1084    e: &Engine,
1085    logits: &CudaSlice<f32>,
1086    n_vocab: usize,
1087    sp: &SpecSampling,
1088    pen_hist: &[u32],
1089    sctr: &mut u32,
1090    site: &str,
1091) -> Result<u32, Box<dyn std::error::Error>> {
1092    debug_assert!(
1093        sp.temp > 0.0,
1094        "boundary sampling is the sampled regime only"
1095    );
1096    // Own copy: penalize_logits mutates in place and the caller's row is live state
1097    // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
1098    let mut col = e.zeros(n_vocab)?;
1099    e.copy_into(&mut col, 0, logits, n_vocab)?;
1100    let pen_on = sp.penalty_last_n > 0
1101        && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
1102    if pen_on && !pen_hist.is_empty() {
1103        // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
1104        let w0 = pen_hist
1105            .len()
1106            .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
1107        let hist = &pen_hist[w0..];
1108        let hd = e.htod_u32_v(hist)?;
1109        e.penalize_logits(
1110            &mut col,
1111            &hd,
1112            hist.len(),
1113            sp.penalty_repeat,
1114            sp.penalty_freq,
1115            sp.penalty_present,
1116            n_vocab,
1117        )?;
1118    }
1119    let rows0 = e.htod_i32(&[0])?;
1120    let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
1121    e.filter_stats(
1122        &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
1123        sp.top_p, sp.min_p,
1124    )?;
1125    let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
1126    let mut perturb = e.zeros(n_vocab)?;
1127    e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
1128    *sctr = sctr.wrapping_add(1);
1129    let td = e.argmax_token_device(&perturb, n_vocab)?;
1130    let tok = e.dtoh_u32_one(&td)?;
1131    if spec_boundary_trace() {
1132        // the pre-lane token, from the SAME row, so the deviation rate is measurable.
1133        let raw = e.argmax_token_device(logits, n_vocab)?;
1134        let greedy = e.dtoh_u32_one(&raw)?;
1135        eprintln!(
1136            "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
1137             deviates={} temp={} sctr={}",
1138            (tok != greedy) as u8,
1139            sp.temp,
1140            sctr.wrapping_sub(1),
1141        );
1142    }
1143    Ok(tok)
1144}
1145
1146/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
1147/// host `Vec<f32>`).
1148#[allow(clippy::too_many_arguments)]
1149pub fn sample_boundary_token(
1150    e: &Engine,
1151    logits: &[f32],
1152    sp: &SpecSampling,
1153    pen_hist: &[u32],
1154    sctr: &mut u32,
1155    site: &str,
1156) -> Result<u32, Box<dyn std::error::Error>> {
1157    let n_vocab = logits.len();
1158    let d = e.htod(logits)?;
1159    sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
1160}
1161
1162struct SpecPipeTraceClock {
1163    pair: usize,
1164    started: std::time::Instant,
1165}
1166
1167#[derive(Clone)]
1168struct SpecPipeTraceCtx {
1169    clock: std::sync::Arc<SpecPipeTraceClock>,
1170    round: usize,
1171    lane: usize,
1172}
1173
1174struct SpecPipeTraceMarker {
1175    trace: SpecPipeTraceCtx,
1176    phase: &'static str,
1177    edge: &'static str,
1178    slot: Option<usize>,
1179}
1180
1181unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
1182    let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
1183    let lane = if marker.trace.lane == 0 { "A" } else { "B" };
1184    let slot = marker
1185        .slot
1186        .map(|v| v.to_string())
1187        .unwrap_or_else(|| "-".into());
1188    let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
1189    use std::io::Write as _;
1190    let stderr = std::io::stderr();
1191    let mut stderr = stderr.lock();
1192    let _ = writeln!(
1193        stderr,
1194        "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
1195         slot={slot} t_ms={t_ms:.3}",
1196        marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
1197    );
1198}
1199
1200fn enqueue_spec_pipe_trace_marker(
1201    stream: &cudarc::driver::CudaStream,
1202    trace: Option<&SpecPipeTraceCtx>,
1203    phase: &'static str,
1204    edge: &'static str,
1205    slot: Option<usize>,
1206) -> Result<(), Box<dyn std::error::Error>> {
1207    let Some(trace) = trace else {
1208        return Ok(());
1209    };
1210    let marker = Box::new(SpecPipeTraceMarker {
1211        trace: trace.clone(),
1212        phase,
1213        edge,
1214        slot,
1215    });
1216    let raw = Box::into_raw(marker);
1217    let result = unsafe {
1218        cudarc::driver::result::stream::launch_host_function(
1219            stream.cu_stream(),
1220            spec_pipe_trace_marker,
1221            raw.cast(),
1222        )
1223    };
1224    if let Err(err) = result {
1225        unsafe {
1226            drop(Box::from_raw(raw));
1227        }
1228        return Err(err.into());
1229    }
1230    Ok(())
1231}
1232
1233#[derive(Default)]
1234struct SpecPipeProgress {
1235    setup_done: [bool; 2],
1236    draft_done: [usize; 2],
1237    stage0_done: [usize; 2],
1238    verify_done: [usize; 2],
1239    accept_done: [usize; 2],
1240    finished: [bool; 2],
1241    aborted: bool,
1242}
1243
1244/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
1245/// keeps its existing call stack and round locals; this object only orders phase entry. The
1246/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
1247/// cannot be interleaved by the two host threads.
1248struct SpecPipeSync {
1249    progress: std::sync::Mutex<SpecPipeProgress>,
1250    changed: std::sync::Condvar,
1251    primary: std::sync::Mutex<()>,
1252    trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
1253}
1254
1255impl SpecPipeSync {
1256    fn new() -> Self {
1257        static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1258        let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
1259            std::sync::Arc::new(SpecPipeTraceClock {
1260                pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1261                started: std::time::Instant::now(),
1262            })
1263        });
1264        Self {
1265            progress: std::sync::Mutex::new(SpecPipeProgress::default()),
1266            changed: std::sync::Condvar::new(),
1267            primary: std::sync::Mutex::new(()),
1268            trace,
1269        }
1270    }
1271}
1272
1273#[derive(Clone)]
1274struct SpecPipeLane {
1275    sync: std::sync::Arc<SpecPipeSync>,
1276    lane: usize,
1277}
1278
1279impl SpecPipeLane {
1280    fn peer(&self) -> usize {
1281        1 - self.lane
1282    }
1283
1284    fn aborted() -> Box<dyn std::error::Error> {
1285        "paired speculative peer aborted".into()
1286    }
1287
1288    fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
1289        self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
1290            clock: clock.clone(),
1291            round,
1292            lane: self.lane,
1293        })
1294    }
1295
1296    fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
1297        let mut p = self.sync.progress.lock().unwrap();
1298        while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
1299            p = self.sync.changed.wait(p).unwrap();
1300        }
1301        if p.aborted {
1302            Err(Self::aborted())
1303        } else {
1304            Ok(())
1305        }
1306    }
1307
1308    fn setup_end(&self) {
1309        let mut p = self.sync.progress.lock().unwrap();
1310        p.setup_done[self.lane] = true;
1311        self.sync.changed.notify_all();
1312    }
1313
1314    fn draft_begin(
1315        &self,
1316        round: usize,
1317    ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1318        let peer = self.peer();
1319        let mut p = self.sync.progress.lock().unwrap();
1320        loop {
1321            if p.aborted {
1322                return Err(Self::aborted());
1323            }
1324            let setup_ready =
1325                (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
1326            let prior_ready = p.accept_done[self.lane] >= round
1327                && (p.accept_done[peer] >= round || p.finished[peer]);
1328            let turn_ready = if self.lane == 0 {
1329                true
1330            } else {
1331                p.draft_done[0] > round || p.finished[0]
1332            };
1333            if setup_ready && prior_ready && turn_ready {
1334                break;
1335            }
1336            p = self.sync.changed.wait(p).unwrap();
1337        }
1338        drop(p);
1339        Ok(self.sync.primary.lock().unwrap())
1340    }
1341
1342    fn draft_end(&self, round: usize) {
1343        let mut p = self.sync.progress.lock().unwrap();
1344        p.draft_done[self.lane] = round + 1;
1345        self.sync.changed.notify_all();
1346    }
1347
1348    /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
1349    /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
1350    fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
1351        let peer = self.peer();
1352        let mut p = self.sync.progress.lock().unwrap();
1353        loop {
1354            if p.aborted {
1355                return Err(Self::aborted());
1356            }
1357            let ready = if self.lane == 0 {
1358                p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
1359            } else {
1360                p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
1361            };
1362            if ready {
1363                return Ok(self.lane == 0 || p.finished[peer]);
1364            }
1365            p = self.sync.changed.wait(p).unwrap();
1366        }
1367    }
1368
1369    fn stage0_end(&self, round: usize) {
1370        let mut p = self.sync.progress.lock().unwrap();
1371        p.stage0_done[self.lane] = round + 1;
1372        self.sync.changed.notify_all();
1373    }
1374
1375    /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
1376    /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
1377    fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
1378        let mut p = self.sync.progress.lock().unwrap();
1379        while !p.aborted
1380            && !(p.stage0_done[self.lane] > round
1381                && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
1382        {
1383            p = self.sync.changed.wait(p).unwrap();
1384        }
1385        if p.aborted {
1386            Err(Self::aborted())
1387        } else {
1388            Ok(())
1389        }
1390    }
1391
1392    fn verify_end(&self, round: usize) {
1393        let mut p = self.sync.progress.lock().unwrap();
1394        p.verify_done[self.lane] = round + 1;
1395        self.sync.changed.notify_all();
1396    }
1397
1398    fn accept_begin(
1399        &self,
1400        round: usize,
1401    ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1402        let mut p = self.sync.progress.lock().unwrap();
1403        loop {
1404            if p.aborted {
1405                return Err(Self::aborted());
1406            }
1407            let ready = if self.lane == 0 {
1408                p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
1409            } else {
1410                p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
1411            };
1412            if ready {
1413                break;
1414            }
1415            p = self.sync.changed.wait(p).unwrap();
1416        }
1417        drop(p);
1418        Ok(self.sync.primary.lock().unwrap())
1419    }
1420
1421    fn accept_end(&self, round: usize) {
1422        let mut p = self.sync.progress.lock().unwrap();
1423        p.accept_done[self.lane] = round + 1;
1424        self.sync.changed.notify_all();
1425    }
1426
1427    fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
1428        self.sync.primary.lock().unwrap()
1429    }
1430
1431    fn finish(&self, failed: bool) {
1432        let mut p = self.sync.progress.lock().unwrap();
1433        p.finished[self.lane] = true;
1434        p.aborted |= failed;
1435        self.sync.changed.notify_all();
1436    }
1437}
1438
1439struct SpecPipeFinish<'a> {
1440    lane: &'a SpecPipeLane,
1441    closed: bool,
1442}
1443
1444impl<'a> SpecPipeFinish<'a> {
1445    fn new(lane: &'a SpecPipeLane) -> Self {
1446        Self {
1447            lane,
1448            closed: false,
1449        }
1450    }
1451
1452    fn close(&mut self, failed: bool) {
1453        self.lane.finish(failed);
1454        self.closed = true;
1455    }
1456}
1457
1458impl Drop for SpecPipeFinish<'_> {
1459    fn drop(&mut self) {
1460        if !self.closed {
1461            self.lane.finish(true);
1462        }
1463    }
1464}
1465
1466/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
1467/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
1468/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
1469/// binds that context before touching the session, joins before returning, and never aliases the
1470/// pointer. Keep this exception local to the experimental pair call instead of marking the public
1471/// session type Send.
1472struct SpecPipeSessionPtr(*mut SpecSession);
1473
1474unsafe impl Send for SpecPipeSessionPtr {}
1475
1476impl SpecPipeSessionPtr {
1477    unsafe fn get_mut(&mut self) -> &mut SpecSession {
1478        unsafe { &mut *self.0 }
1479    }
1480}
1481
1482/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
1483/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
1484/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
1485/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
1486/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
1487/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
1488/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
1489/// so the eager fallback doesn't pay a doomed capture attempt every burst.
1490/// Capture identity of the parked SAMPLED draft graph (`DraftGraphCtx::graph_s`).
1491///
1492/// EXACTNESS, not perf (lane/graph-s-key-exactness-20260819; receipts
1493/// `research/spec-cache-20260818/GRAPH-S-KEY.md`). Two classes of field live here, both
1494/// load-bearing:
1495///
1496/// - **Baked constants.** `seed` and `temp` are capture-time constants INSIDE the graph and `k`
1497///   sizes the q slots its replays write. A resumed request changing any of them must recapture.
1498///   This is all the key used to carry.
1499/// - **Regime fields.** `top_k`/`top_p`/`min_p`/`pen_on` are not baked, but they decide whether
1500///   the captured graph is a legal draft chain AT ALL. The in-graph draw is one gumbel-max over
1501///   the RAW softmax (`gumbel_perturb_ctr`, unfiltered by construction), while the verify builds
1502///   the accept test's `q` from `filter_stats(q_slots, top_k, top_p, min_p)`. If those disagree
1503///   the accept test evaluates a distribution the draft was never sampled from: a draft token
1504///   below the filter threshold gathers `q = 0` (`softmax_gather_filtered_f32`,
1505///   `cu/spec_sample.cu`) and `u * 0 < p` accepts it UNCONDITIONALLY.
1506///
1507/// Omitting the regime fields was reachable — not through the prefix-cache spec restore (that
1508/// path is greedy-only, `memra-server` `spec_restore_convertible`), but through WHOLE-SESSION
1509/// spec reuse: a parked `SpecSession` carries this `DraftGraphCtx`, and the pool-resume probe
1510/// applies no sampler predicate at all. Turn 1 pure-temp parks a graph; turn 2 of the same
1511/// conversation, same explicit seed and temperature, adds `top_p`/`top_k` and inherits it.
1512#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1513pub(crate) struct SampledGraphKey {
1514    seed: u64,
1515    temp_bits: u32,
1516    k: usize,
1517    top_k: i32,
1518    top_p_bits: u32,
1519    min_p_bits: u32,
1520    pen_on: bool,
1521}
1522
1523impl SampledGraphKey {
1524    pub(crate) fn new(
1525        seed: u64,
1526        temp: f32,
1527        k: usize,
1528        top_k: i32,
1529        top_p: f32,
1530        min_p: f32,
1531        pen_on: bool,
1532    ) -> Self {
1533        SampledGraphKey {
1534            seed,
1535            temp_bits: temp.to_bits(),
1536            k,
1537            top_k,
1538            top_p_bits: top_p.to_bits(),
1539            min_p_bits: min_p.to_bits(),
1540            pen_on,
1541        }
1542    }
1543
1544    /// The one regime the in-graph sampled chain may stand in for the eager one: nothing but
1545    /// temperature shapes `q`. Computed FROM THE KEY so the capture guard, the launch guard and
1546    /// the key can never drift apart (they were three separate expressions before this lane, and
1547    /// the launch site simply forgot to ask).
1548    pub(crate) fn pure_temp(&self) -> bool {
1549        self.top_k == 0
1550            && f32::from_bits(self.top_p_bits) >= 1.0
1551            && f32::from_bits(self.min_p_bits) <= 0.0
1552            && !self.pen_on
1553    }
1554}
1555
1556pub(crate) struct DraftGraphCtx {
1557    g_tok: CudaSlice<u32>,
1558    g_pos: CudaSlice<i32>,
1559    g_seed: CudaSlice<f32>,
1560    g_p: CudaSlice<f32>,
1561    g_ctr: CudaSlice<u32>,
1562    g_q: CudaSlice<f32>,
1563    g_perturb: CudaSlice<f32>,
1564    q_slots: Vec<CudaSlice<f32>>,
1565    /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
1566    /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
1567    /// per-position contents the host re-uploads before each replay (the graph-promote
1568    /// pattern from decode.rs). Empty unless the session drafts under a grammar.
1569    g_dmask: CudaSlice<u32>,
1570    /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
1571    graph_masked: bool,
1572    graph: Option<cudarc::driver::CudaGraph>,
1573    graph_s: Option<cudarc::driver::CudaGraph>,
1574    /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
1575    /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
1576    failed: DraftGraphFallback,
1577    /// Capture identity of `graph_s` — see [`SampledGraphKey`]. `None` iff no sampled graph is
1578    /// parked; a request whose key differs drops the parked graph (and its q slots/keeper).
1579    s_key: Option<SampledGraphKey>,
1580    /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
1581    /// pool addresses the captured graph(s) bake. Without these, the transients return to the
1582    /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
1583    /// co-served session in the worker) reuses those addresses — the persisted graph's replay
1584    /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
1585    /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
1586    /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
1587    /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
1588    keeper: Vec<Box<dyn std::any::Any + Send>>,
1589    keeper_s: Vec<Box<dyn std::any::Any + Send>>,
1590}
1591
1592/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
1593/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
1594///
1595/// Three contracts:
1596/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
1597///   (returned, not printed, so the once-per-flip contract is unit-testable); the caller
1598///   `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
1599///   an already-failed graph returns None (the per-burst memoization that keeps the eager
1600///   fallback from paying a doomed capture attempt every burst).
1601/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
1602///   NEW request gets one fresh capture chance instead of carrying a transient-pressure
1603///   failure for the pool's whole lifetime. Returns the note line only when a flag was
1604///   actually set (quiet on the common clean-resume path).
1605/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1606///   capture attempt whose own failure would re-flip loudly.
1607#[derive(Default)]
1608pub(crate) struct DraftGraphFallback {
1609    greedy: bool,
1610    sampled: bool,
1611}
1612impl DraftGraphFallback {
1613    fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1614        if self.greedy {
1615            return None;
1616        }
1617        self.greedy = true;
1618        Some(format!(
1619            "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1620        ))
1621    }
1622    fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1623        if self.sampled {
1624            return None;
1625        }
1626        self.sampled = true;
1627        Some(format!(
1628            "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1629        ))
1630    }
1631    fn greedy_failed(&self) -> bool {
1632        self.greedy
1633    }
1634    fn sampled_failed(&self) -> bool {
1635        self.sampled
1636    }
1637    fn clear_greedy(&mut self) {
1638        self.greedy = false;
1639    }
1640    fn clear_sampled(&mut self) {
1641        self.sampled = false;
1642    }
1643    /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1644    /// was set (so clean resumes stay quiet).
1645    pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1646        if !self.greedy && !self.sampled {
1647            return None;
1648        }
1649        let which = match (self.greedy, self.sampled) {
1650            (true, true) => "greedy+sampled",
1651            (true, false) => "greedy",
1652            _ => "sampled",
1653        };
1654        self.greedy = false;
1655        self.sampled = false;
1656        Some(format!(
1657            "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1658        ))
1659    }
1660}
1661
1662impl DraftGraphCtx {
1663    fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1664        Ok(DraftGraphCtx {
1665            g_tok: e.alloc_u32_zeroed(1)?,
1666            g_pos: e.htod_i32(&[0])?,
1667            g_seed: e.zeros(n_embd)?,
1668            g_p: e.zeros(1)?,
1669            g_ctr: e.alloc_u32_zeroed(1)?,
1670            g_q: e.zeros(qlen)?,
1671            g_perturb: e.zeros(qlen)?,
1672            q_slots: Vec::new(),
1673            g_dmask: e.alloc_u32_zeroed(1)?,
1674            graph_masked: false,
1675            graph: None,
1676            graph_s: None,
1677            failed: DraftGraphFallback::default(),
1678            s_key: None,
1679            keeper: Vec::new(),
1680            keeper_s: Vec::new(),
1681        })
1682    }
1683}
1684
1685pub(crate) struct MtpScratch {
1686    kv: KvLayer,
1687    /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1688    /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1689    /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1690    /// smaller host-indexed SWA ring instead.
1691    cap: usize,
1692    extra: Vec<MtpScratchPlane>,
1693}
1694
1695struct MtpScratchPlane {
1696    kv: KvLayer,
1697    cap: usize,
1698}
1699
1700fn mtp_scratch_layout(
1701    cfg: &memra_gguf::config::ModelConfig,
1702    geom: Option<&crate::hybrid::DraftGeom>,
1703) -> (usize, usize, usize, usize) {
1704    // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1705    let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1706    let head_dim_k = cfg.head_dim_k as usize;
1707    let head_dim_v = cfg.head_dim_v as usize;
1708    assert!(
1709        head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1710        "KVQUANT requires head_dim%32==0 (MTP scratch)"
1711    );
1712    let kv_dim_k = head_dim_k * n_head_kv;
1713    let kv_dim_v = head_dim_v * n_head_kv;
1714    // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1715    // policy shared with `MtpScratch::new` so admission scales the same allocation.
1716    let (kbb, vbb) = crate::kv_blk_bytes();
1717    let k_tok_bytes = (kv_dim_k / 32) * kbb;
1718    let v_tok_bytes = (kv_dim_v / 32) * vbb;
1719    (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1720}
1721
1722fn mtp_chain_head_index(step: usize, head_count: usize) -> usize {
1723    assert!(head_count > 0, "MTP chain requires at least one head");
1724    step % head_count
1725}
1726
1727impl MtpScratch {
1728    fn alloc_plane(
1729        e: &Engine,
1730        cfg: &memra_gguf::config::ModelConfig,
1731        plan: &memra_gguf::model_plan::ModelPlan,
1732        cap: usize,
1733        geom: Option<&crate::hybrid::DraftGeom>,
1734    ) -> Result<MtpScratchPlane, Box<dyn std::error::Error>> {
1735        let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
1736        let ring = if crate::cache::swa_ring_on()
1737            && crate::plan_backend::decode_batch_program(plan)
1738                == crate::plan_backend::DecodeBatchProgram::SlidingGatedMoe
1739        {
1740            let window = plan
1741                .layers
1742                .iter()
1743                .find_map(|layer| match layer.attention {
1744                    memra_gguf::model_plan::AttentionPlan::SlidingWindow { window, .. } => {
1745                        Some(window as usize)
1746                    }
1747                    _ => None,
1748                })
1749                .ok_or("sliding-gated-MoE draft scratch has no sliding-window layer")?;
1750            Some(crate::cache::KvRing::new(
1751                crate::cache::swa_ring_rows(window, cap),
1752                window,
1753            ))
1754        } else {
1755            None
1756        };
1757        let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1758        Ok(MtpScratchPlane {
1759            kv: KvLayer {
1760                k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1761                v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1762                kv_dim_k,
1763                kv_dim_v,
1764                k_tok_bytes,
1765                v_tok_bytes,
1766                len: 0,
1767                ring,
1768                len_d: e.htod_i32(&[0])?,
1769            },
1770            cap,
1771        })
1772    }
1773
1774    fn new(
1775        e: &Engine,
1776        cfg: &memra_gguf::config::ModelConfig,
1777        plan: &memra_gguf::model_plan::ModelPlan,
1778        cap: usize,
1779        geom: Option<&crate::hybrid::DraftGeom>,
1780    ) -> Result<Self, Box<dyn std::error::Error>> {
1781        // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1782        // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1783        // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1784        // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1785        let primary = Self::alloc_plane(e, cfg, plan, cap, geom)?;
1786        Ok(MtpScratch {
1787            kv: primary.kv,
1788            cap: primary.cap,
1789            extra: Vec::new(),
1790        })
1791    }
1792
1793    fn push_plane(
1794        &mut self,
1795        e: &Engine,
1796        cfg: &memra_gguf::config::ModelConfig,
1797        plan: &memra_gguf::model_plan::ModelPlan,
1798        geom: Option<&crate::hybrid::DraftGeom>,
1799    ) -> Result<(), Box<dyn std::error::Error>> {
1800        self.extra
1801            .push(Self::alloc_plane(e, cfg, plan, self.cap, geom)?);
1802        Ok(())
1803    }
1804
1805    fn plane_count(&self) -> usize {
1806        1 + self.extra.len()
1807    }
1808
1809    fn plane(&self, index: usize) -> (&KvLayer, usize) {
1810        if index == 0 {
1811            (&self.kv, self.cap)
1812        } else {
1813            let plane = &self.extra[index - 1];
1814            (&plane.kv, plane.cap)
1815        }
1816    }
1817
1818    fn plane_mut(&mut self, index: usize) -> (&mut KvLayer, usize) {
1819        if index == 0 {
1820            (&mut self.kv, self.cap)
1821        } else {
1822            let plane = &mut self.extra[index - 1];
1823            (&mut plane.kv, plane.cap)
1824        }
1825    }
1826
1827    fn set_plane_len(
1828        &mut self,
1829        e: &Engine,
1830        index: usize,
1831        n: usize,
1832    ) -> Result<(), Box<dyn std::error::Error>> {
1833        let (kv, _) = self.plane_mut(index);
1834        if kv.ring.as_ref().is_some_and(|ring| !ring.can_rewind_to(n)) {
1835            return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1836        }
1837        kv.len = n;
1838        e.set_i32_one(&mut kv.len_d, n as i32)
1839    }
1840
1841    /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1842    /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1843    /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1844    fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1845        if !self.can_rewind_to(n) {
1846            return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1847        }
1848        for index in 0..self.plane_count() {
1849            self.set_plane_len(e, index, n)?;
1850        }
1851        Ok(())
1852    }
1853
1854    fn can_rewind_to(&self, n: usize) -> bool {
1855        (0..self.plane_count()).all(|index| {
1856            self.plane(index)
1857                .0
1858                .ring
1859                .as_ref()
1860                .is_none_or(|ring| ring.can_rewind_to(n))
1861        })
1862    }
1863}
1864
1865/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1866/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1867/// full weight reads per round — recomputing columns the verify had already produced
1868/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1869/// to "after the first j verify columns" WITHOUT re-running the trunk:
1870/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1871///   consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1872///   to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1873///   registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1874///   pure-copy ring rebuild.
1875/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1876///   column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1877///   target: j <= t-1).
1878/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1879/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1880struct GdnStash {
1881    qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1882    q_l2: CudaSlice<f32>,
1883    k_l2: CudaSlice<f32>,
1884    v_g: CudaSlice<f32>, // [t, num_v, d_state]
1885    g_log: CudaSlice<f32>,
1886    beta: CudaSlice<f32>, // [t, num_v]
1887}
1888pub(crate) struct VerifyCkpt {
1889    gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1890    cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1891}
1892/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
1893pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
1894
1895/// Engine-bundle slice 3 (DSF-ROUNDCOST-20260820 §2 row 4 / §5 rank 1): bucketed CUDA
1896/// graphs for the dspark verify's LINEAR-layer segments. The measured verify is ~2,800
1897/// eager launches whose residual cost is DEVICE-side per-launch overhead (slice 2 proved
1898/// host dispatch is not the binder: fully-deferred dispatch bought ~0 wall). The 48 GDN
1899/// layers between full-attention layers are shape-static given vt — no positions, no
1900/// t_kv, state addressed through pointer tables — so runs of them capture per
1901/// (segment, vt) and replay as ONE graph launch each. Full-attention layers stay eager
1902/// (their per-row append/fa arm picks are t_kv-driven — the exec-update extension).
1903///
1904/// Per round out-of-graph: one pointer-table refresh (gdn ping-pong moves the canonical
1905/// handles), one input-staging copy per segment, host parity bookkeeping. Captured via
1906/// `capture_graph_retained` (2 warmups + capture, keeper retains warmup transients so
1907/// pool addresses stay stable); the warmups EXECUTE, so segment conv/ssm state is saved
1908/// before and restored after — the graph's first real launch starts from the exact
1909/// pre-round state. The ckpt column stash rides persistent slabs (written inside the
1910/// graph as memcpy nodes); commit reads them via `dspark_commit_prefix_slab`.
1911/// `MEMRA_DSPARK_VERIFY_GRAPH=0` reverts to the eager walk (byte-identical body).
1912pub(crate) struct DsparkVerifyGraphs {
1913    /// Linear-attention layer indices ascending; `lin_pos[il]` = index into the vecs.
1914    lin: Vec<usize>,
1915    lin_pos: std::collections::HashMap<usize, usize>,
1916    /// [n_lin x 6] pointer table (conv, s0, s1, conv, s1, s0 per layer), refreshed per
1917    /// verify from the live handles; layer il's slice starts at lin_pos[il]*6.
1918    table_all: CudaSlice<u64>,
1919    host_table: Vec<u64>,
1920    /// Persistent per-layer ckpt stash slabs: row r of the verify at slab offset
1921    /// r*words. Shared by every (segment, vt) bucket — one verify runs at a time.
1922    stash_conv: Vec<CudaSlice<f32>>,
1923    stash_ssm: Vec<CudaSlice<f32>>,
1924    conv_words: usize,
1925    ssm_words: usize,
1926    /// Per-vt input/output staging (stable addresses the graphs bake).
1927    stage: std::collections::HashMap<usize, (CudaSlice<f32>, CudaSlice<f32>)>,
1928    /// Per-vt dflash tap-sink buffers — the captured segments bake the tap dst address,
1929    /// so the sink buffer must live (and persist) with the graphs, not with the round.
1930    pub(crate) tap_bufs: std::collections::HashMap<usize, CudaSlice<f32>>,
1931    graphs: std::collections::HashMap<(usize, usize), DsparkSegGraph>,
1932    /// Warmup-corruption guard scratch: pre-capture conv/ssm of every linear layer
1933    /// (sized n_lin — the slice-4c full-verify warmups execute the whole walk).
1934    save_conv: CudaSlice<f32>,
1935    save_ssm: CudaSlice<f32>,
1936    max_run: usize,
1937    n_embd: usize,
1938    /// Set by the verify walk: this round's linear ckpt lives in the slabs (the caller
1939    /// commits through `dspark_commit_prefix_slab` instead of the cols arm).
1940    pub(crate) round_slab: bool,
1941    // ---- slice 4c: full-verify single graph per (vt, rung) ----
1942    /// Full-attention layer indices ascending; `fa_pos[il]` = index into the vec.
1943    fa: Vec<usize>,
1944    fa_pos: std::collections::HashMap<usize, usize>,
1945    /// [n_fa x 2 x t_cap] interleaved (k,v) base-pointer pairs, refreshed per verify;
1946    /// layer il's slice starts at `fa_pos[il] * 2 * t_cap` (the seqs twins read pairs
1947    /// [2z], z < t <= t_cap, so one t_cap-sized table serves every vt).
1948    fa_table: CudaSlice<u64>,
1949    fa_host_table: Vec<u64>,
1950    t_cap: usize,
1951    /// Per-vt position staging for the captured bodies — contents refreshed per round
1952    /// (rope reads row r; the seqs twins derive append slot and T_kv per z from it).
1953    pos_stage: std::collections::HashMap<usize, CudaSlice<i32>>,
1954    /// Full-verify graphs keyed (vt, rung_end, hi).
1955    full: std::collections::HashMap<(usize, usize, usize), DsparkSegGraph>,
1956    /// Largest n with every layer in [0, n) linear or full-attention (walk coverage).
1957    covered: usize,
1958    /// Every layer in [0, n) is linear or full-attention (no MLA/unknown mixers) — the
1959    /// full-verify capture walks all of them.
1960    walk_uniform: bool,
1961}
1962
1963struct DsparkSegGraph {
1964    graph: cudarc::driver::CudaGraph,
1965    _keeper: Vec<Box<dyn std::any::Any + Send>>,
1966}
1967
1968/// Per-call arguments of [`HybridModel::qwen35_tparallel_fa_layer`] — one struct so the
1969/// eager walk and the slice-4c captured full-verify graphs hand the SAME body its two
1970/// modes without a second copy of the math.
1971pub(crate) struct FaLayerArgs<'a> {
1972    /// [T] per-row positions (device): rope reads them row-indexed; the seqs twins read
1973    /// them per-z (append slot = pos, T_kv = pos + 1).
1974    pub pos_d: &'a CudaSlice<i32>,
1975    /// Verify-level lazy per-row 1-element position buffers — only the per-row fallback
1976    /// arm builds/uses them (graph mode refuses that arm).
1977    pub pos_rows: &'a mut Option<Vec<CudaSlice<i32>>>,
1978    pub pos0: usize,
1979    pub seqs_append: bool,
1980    pub batch_fa_on: bool,
1981    /// Some((kv pointer table, offset-in-u64s, rung_end)) = captured-graph mode.
1982    pub graph_cap: Option<(&'a CudaSlice<u64>, usize, usize)>,
1983    /// ROUND-STREAM (lane/draftcost-moe, v0.100 train merge): Some((token stream, device
1984    /// round counter)) routes the FA attend through the dc rows kernels and the Linear
1985    /// mixer through `linear_attn_verify_t` (the stream arms the old inline body carried).
1986    /// Never armed together with `graph_cap` (the verify-level merge guard refuses).
1987    pub stream: Option<(&'a CudaSlice<u32>, &'a CudaSlice<i32>)>,
1988    /// VerifyCkpt for the stream-Linear arm's GdnStash install; None in graph mode and
1989    /// for FA layers that never touch it.
1990    pub ckpt: Option<&'a mut VerifyCkpt>,
1991}
1992
1993// SAFETY: `CudaGraph` is not marked Send by cudarc because its raw driver handles carry
1994// no automatic trait; CUDA driver graph handles are context-scoped rather than
1995// OS-thread-affine (the SpecPipeSessionPtr precedent above). The ctx lives in
1996// `HybridModel::dspark_vgraphs` behind a Mutex and every touch happens on the engine's
1997// single decode-stream thread.
1998unsafe impl Send for DsparkVerifyGraphs {}
1999
2000impl DsparkVerifyGraphs {
2001    /// Build for this cache's shape. None when there are no linear layers, sizes are
2002    /// non-uniform, or the trunk keeps a gemma4 config (never on the qwen35 family).
2003    pub(crate) fn new(
2004        e: &Engine,
2005        cache: &Cache,
2006        t_max: usize,
2007        n_embd: usize,
2008    ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
2009        let lin: Vec<usize> = (0..cache.recur.len())
2010            .filter(|&il| cache.recur[il].is_some())
2011            .collect();
2012        if lin.is_empty() || t_max < 2 {
2013            return Ok(None);
2014        }
2015        let first = cache.recur[lin[0]].as_ref().unwrap();
2016        let (conv_words, ssm_words) = (first.conv_state.len(), first.ssm_state.len());
2017        for &il in &lin {
2018            let rl = cache.recur[il].as_ref().unwrap();
2019            if rl.conv_state.len() != conv_words || rl.ssm_state.len() != ssm_words {
2020                return Ok(None);
2021            }
2022        }
2023        let n = lin.len();
2024        let mut lin_pos = std::collections::HashMap::with_capacity(n);
2025        for (k, &il) in lin.iter().enumerate() {
2026            lin_pos.insert(il, k);
2027        }
2028        // longest run of consecutive linear layers (save-scratch sizing)
2029        let mut max_run = 1usize;
2030        let mut run = 1usize;
2031        for w in lin.windows(2) {
2032            if w[1] == w[0] + 1 {
2033                run += 1;
2034                max_run = max_run.max(run);
2035            } else {
2036                run = 1;
2037            }
2038        }
2039        let rows = t_max - 1;
2040        let mut stash_conv = Vec::with_capacity(n);
2041        let mut stash_ssm = Vec::with_capacity(n);
2042        for _ in 0..n {
2043            stash_conv.push(e.uninit(rows * conv_words)?);
2044            stash_ssm.push(e.uninit(rows * ssm_words)?);
2045        }
2046        let host_table = vec![0u64; n * 6];
2047        let table_all = e.htod_u64(&host_table)?;
2048        // slice 4c: full-attention census for the full-verify graphs.
2049        let fa: Vec<usize> = (0..cache.kv.len())
2050            .filter(|&il| cache.kv[il].is_some())
2051            .collect();
2052        let mut fa_pos = std::collections::HashMap::with_capacity(fa.len());
2053        for (k, &il) in fa.iter().enumerate() {
2054            fa_pos.insert(il, k);
2055        }
2056        let n_layers = cache.kv.len().max(cache.recur.len());
2057        // exactly one of (linear state, kv cache) per layer — no MLA/unknown mixers.
2058        let walk_uniform = (0..n_layers).all(|il| {
2059            cache.recur.get(il).is_some_and(|r| r.is_some())
2060                != cache.kv.get(il).is_some_and(|k| k.is_some())
2061        });
2062        // Contiguous covered prefix: the largest n such that every layer in [0, n) is
2063        // linear or full-attention. The TRUNK walk is [0, layers.len()) and the cache
2064        // vecs can carry EXTRA state slots past it (the q38 export keeps the MTP head
2065        // layer's kv at the tail — hi == lin+fa never held, the s4c battery's zero
2066        // 'full' captures). The full-graph guard is walk coverage, not slot arithmetic.
2067        let covered = (0..n_layers)
2068            .take_while(|il| lin_pos.contains_key(il) || fa_pos.contains_key(il))
2069            .count();
2070        let t_cap = t_max;
2071        let fa_host_table = vec![0u64; fa.len() * 2 * t_cap];
2072        let fa_table = e.htod_u64(&fa_host_table)?;
2073        Ok(Some(Self {
2074            lin,
2075            lin_pos,
2076            table_all,
2077            host_table,
2078            stash_conv,
2079            stash_ssm,
2080            conv_words,
2081            ssm_words,
2082            stage: std::collections::HashMap::new(),
2083            tap_bufs: std::collections::HashMap::new(),
2084            graphs: std::collections::HashMap::new(),
2085            save_conv: e.uninit(n * conv_words)?,
2086            save_ssm: e.uninit(n * ssm_words)?,
2087            max_run,
2088            n_embd,
2089            round_slab: false,
2090            fa,
2091            fa_pos,
2092            fa_table,
2093            fa_host_table,
2094            t_cap,
2095            pos_stage: std::collections::HashMap::new(),
2096            full: std::collections::HashMap::new(),
2097            covered,
2098            walk_uniform,
2099        }))
2100    }
2101
2102    /// Rebuild the pointer tables from the live handles (once per verify — the gdn
2103    /// ping-pong swaps the canonical/alt handles between rounds; a fresh generation's
2104    /// cache buffers land at new addresses; a stale table would read the wrong state).
2105    pub(crate) fn refresh_tables(
2106        &mut self,
2107        e: &Engine,
2108        cache: &Cache,
2109    ) -> Result<(), Box<dyn std::error::Error>> {
2110        use cudarc::driver::DevicePtr;
2111        {
2112            let s = &e.gpu.stream();
2113            for (k, &il) in self.lin.iter().enumerate() {
2114                let rl = cache.recur[il].as_ref().unwrap();
2115                let (pc, _g0) = rl.conv_state.device_ptr(s);
2116                let (p0, _g1) = rl.ssm_state.device_ptr(s);
2117                let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
2118                let o = k * 6;
2119                self.host_table[o] = pc as u64;
2120                self.host_table[o + 1] = p0 as u64;
2121                self.host_table[o + 2] = p1 as u64;
2122                self.host_table[o + 3] = pc as u64;
2123                self.host_table[o + 4] = p1 as u64;
2124                self.host_table[o + 5] = p0 as u64;
2125            }
2126            for (k, &il) in self.fa.iter().enumerate() {
2127                let kvl = cache.kv[il].as_ref().unwrap();
2128                let (pk, _g0) = kvl.k.device_ptr(s);
2129                let (pv, _g1) = kvl.v.device_ptr(s);
2130                let o = k * 2 * self.t_cap;
2131                for z in 0..self.t_cap {
2132                    self.fa_host_table[o + 2 * z] = pk as u64;
2133                    self.fa_host_table[o + 2 * z + 1] = pv as u64;
2134                }
2135            }
2136        }
2137        e.htod_u64_into(&self.host_table, &mut self.table_all)?;
2138        if !self.fa_host_table.is_empty() {
2139            e.htod_u64_into(&self.fa_host_table, &mut self.fa_table)?;
2140        }
2141        Ok(())
2142    }
2143
2144    /// Slice 4c eligibility: Some(rung_end) when this round can replay (or capture) a
2145    /// full-verify graph — the whole walk [lo, hi) is covered, every layer is linear or
2146    /// full-attention, and ALL of the round's per-row t_kv values take the v4-seqs arm
2147    /// on ONE `fa_split_keys` ladder step that the rung also sits on (the straddle law;
2148    /// both gates are t_kv intervals, so ends-inside means all-inside). The rung is the
2149    /// round's next power of two — grid/partial sizing only (`n_splits_max` is pure
2150    /// stride; splits >= ns_eff write the empty partial the combine never reads), so one
2151    /// captured graph is bit-identical for every round the rung covers.
2152    #[allow(clippy::too_many_arguments)]
2153    pub(crate) fn full_rung(
2154        &self,
2155        model: &crate::hybrid::HybridModel,
2156        cache: &Cache,
2157        lo: usize,
2158        hi: usize,
2159        t: usize,
2160        seqs_arms_on: bool,
2161    ) -> Option<usize> {
2162        if std::env::var("MEMRA_DSPARK_FULLG_DEBUG").as_deref() == Ok("1") {
2163            static ONCE: std::sync::Once = std::sync::Once::new();
2164            let len0 = self
2165                .fa
2166                .first()
2167                .and_then(|&il| cache.kv[il].as_ref())
2168                .map(|k| k.len);
2169            ONCE.call_once(|| {
2170                eprintln!(
2171                    "[fullg-debug] walk_uniform={} covered={} seqs_arms_on={} fa_rows_on={} t={} lo={} hi={} lin={} fa={} t_cap={} len0={:?}",
2172                    self.walk_uniform, self.covered, seqs_arms_on, dspark_fa_rows_on(), t, lo, hi,
2173                    self.lin.len(), self.fa.len(), self.t_cap, len0
2174                );
2175            });
2176        }
2177        if !self.walk_uniform
2178            || !seqs_arms_on
2179            || !dspark_fa_rows_on()
2180            || t < 2
2181            || lo != 0
2182            || hi > self.covered
2183            || t > self.t_cap
2184            || self.fa.is_empty()
2185        {
2186            return None;
2187        }
2188        let cfg = &model.cfg;
2189        let head_dim_global = cfg.head_dim_k as usize;
2190        let nkv = cfg.n_head_kv as usize;
2191        let kvl0 = cache.kv[self.fa[0]].as_ref().unwrap();
2192        // the z-batched twins read stacked rows at the cache's kv dims — must equal the
2193        // projection stride (the body's guard, hoisted so ineligible models fall back
2194        // instead of refusing mid-capture).
2195        let geom = cfg.full_attention_geometry_at(self.fa[0] as u32);
2196        let kv_dim = geom.n_head_kv as usize * geom.head_dim_k as usize;
2197        if kvl0.kv_dim_k != kv_dim || kvl0.kv_dim_v != kv_dim {
2198            return None;
2199        }
2200        let len0 = kvl0.len;
2201        let (t_kv_first, t_kv_last) = (len0 + 1, len0 + t);
2202        if !crate::fa_seqs_eligible(t_kv_first, head_dim_global)
2203            || !crate::fa_seqs_eligible(t_kv_last, head_dim_global)
2204            || crate::fa_split_keys(t_kv_first, nkv) != crate::fa_split_keys(t_kv_last, nkv)
2205        {
2206            return None;
2207        }
2208        let rung = t_kv_last.next_power_of_two().max(256);
2209        if crate::fa_split_keys(rung, nkv) != crate::fa_split_keys(t_kv_last, nkv) {
2210            return None;
2211        }
2212        Some(rung)
2213    }
2214
2215    /// Run the WHOLE verify walk [lo, hi) as one captured graph at (vt=t, rung): stage
2216    /// the residual + refresh the per-vt position staging, capture on first encounter
2217    /// (2 executing warmups bracketed by a full linear-state save/restore; KV warmup
2218    /// appends write the exact slots the replay writes — idempotent), launch, then apply
2219    /// the host bookkeeping the captured body skipped (per-linear-layer parity swap for
2220    /// odd t, per-fa-layer len bump). Returns the fresh residual.
2221    #[allow(clippy::too_many_arguments)]
2222    pub(crate) fn run_full(
2223        &mut self,
2224        model: &crate::hybrid::HybridModel,
2225        e: &Engine,
2226        lo: usize,
2227        hi: usize,
2228        x: &CudaSlice<f32>,
2229        t: usize,
2230        pos0: usize,
2231        rung: usize,
2232        cache: &mut Cache,
2233    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2234        let n_embd = self.n_embd;
2235        if !self.stage.contains_key(&t) {
2236            let xin = e.uninit(t * n_embd)?;
2237            let xout = e.uninit(t * n_embd)?;
2238            self.stage.insert(t, (xin, xout));
2239        }
2240        if !self.pos_stage.contains_key(&t) {
2241            self.pos_stage.insert(t, e.htod_i32(&vec![0i32; t])?);
2242        }
2243        // Per-round refresh: position contents + input staging (both addresses are baked
2244        // by the captured bodies; only their CONTENTS change round to round).
2245        {
2246            let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
2247            let pb = self.pos_stage.get_mut(&t).unwrap();
2248            e.htod_i32_into(pb, &pos_host)?;
2249            let (xin, _) = self.stage.get_mut(&t).unwrap();
2250            e.copy_into(xin, 0, x, t * n_embd)?;
2251        }
2252        let key = (t, rung, hi);
2253        if !self.full.contains_key(&key) {
2254            // The warmups EXECUTE the whole walk on live state — save every linear
2255            // layer's conv + canonical ssm first, restore after (KV needs no restore:
2256            // graph mode never bumps host lens and the appends write this round's own
2257            // slots).
2258            for (k, &il) in self.lin.iter().enumerate() {
2259                let rl = cache.recur[il].as_ref().unwrap();
2260                e.copy_into(
2261                    &mut self.save_conv,
2262                    k * self.conv_words,
2263                    &rl.conv_state,
2264                    self.conv_words,
2265                )?;
2266                e.copy_into(
2267                    &mut self.save_ssm,
2268                    k * self.ssm_words,
2269                    &rl.ssm_state,
2270                    self.ssm_words,
2271                )?;
2272            }
2273            let (graph, keeper) = {
2274                let table_all = &self.table_all;
2275                let lin_pos = &self.lin_pos;
2276                let fa_pos = &self.fa_pos;
2277                let fa_table = &self.fa_table;
2278                let t_cap = self.t_cap;
2279                let stash_conv = &mut self.stash_conv;
2280                let stash_ssm = &mut self.stash_ssm;
2281                let pos_d: &CudaSlice<i32> = &self.pos_stage[&t];
2282                let (xin, xout) = self
2283                    .stage
2284                    .get_mut(&t)
2285                    .map(|(a, b)| (&*a, b))
2286                    .expect("stage bucket created above");
2287                let cache_ref: &mut Cache = cache;
2288                let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
2289                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
2290                } else {
2291                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
2292                };
2293                e.capture_graph_retained_flags(iflag, move |e| {
2294                    let mut xc: Option<CudaSlice<f32>> = None;
2295                    for il in lo..hi {
2296                        let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
2297                        let nx = if let Some(&k) = lin_pos.get(&il) {
2298                            model.qwen35_tparallel_linear_layer(
2299                                e,
2300                                il,
2301                                xr,
2302                                t,
2303                                cache_ref,
2304                                None,
2305                                Some((&mut stash_conv[k], &mut stash_ssm[k])),
2306                                Some((table_all, k * 6)),
2307                            )?
2308                        } else if let Some(&kf) = fa_pos.get(&il) {
2309                            let mut no_rows: Option<Vec<CudaSlice<i32>>> = None;
2310                            model.qwen35_tparallel_fa_layer(
2311                                e,
2312                                il,
2313                                xr,
2314                                t,
2315                                cache_ref,
2316                                FaLayerArgs {
2317                                    pos_d,
2318                                    pos_rows: &mut no_rows,
2319                                    pos0,
2320                                    seqs_append: true,
2321                                    batch_fa_on: true,
2322                                    graph_cap: Some((fa_table, kf * 2 * t_cap, rung)),
2323                                    stream: None,
2324                                    ckpt: None,
2325                                },
2326                            )?
2327                        } else {
2328                            return Err(format!(
2329                                "run_full: layer {il} is neither linear nor full-attention"
2330                            )
2331                            .into());
2332                        };
2333                        xc = Some(nx);
2334                    }
2335                    e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
2336                    Ok(())
2337                })?
2338            };
2339            // Undo the net host parity motion of the 3 body runs (each run swaps iff t
2340            // is odd -> 3 runs = net one swap), then restore the device state the
2341            // warmups consumed (walk scope only — layers past hi never executed). The
2342            // launch below then behaves exactly like one run.
2343            if t % 2 == 1 {
2344                for &il in &self.lin {
2345                    if il < lo || il >= hi {
2346                        continue;
2347                    }
2348                    let rl = cache.recur[il].as_mut().unwrap();
2349                    std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2350                }
2351            }
2352            for (k, &il) in self.lin.iter().enumerate() {
2353                if il < lo || il >= hi {
2354                    continue;
2355                }
2356                let rl = cache.recur[il].as_mut().unwrap();
2357                let (cw, sw) = (self.conv_words, self.ssm_words);
2358                {
2359                    let sv = e.view(&self.save_conv, self.lin.len() * cw);
2360                    let win = sv.slice(k * cw..(k + 1) * cw);
2361                    e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
2362                }
2363                {
2364                    let sv = e.view(&self.save_ssm, self.lin.len() * sw);
2365                    let win = sv.slice(k * sw..(k + 1) * sw);
2366                    e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
2367                }
2368            }
2369            if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
2370                if let Ok(c) = crate::graph_update::node_census(&graph) {
2371                    eprintln!("[dspark-vg-census] full vt={t} rung={rung} {c:?}");
2372                }
2373            }
2374            self.full.insert(
2375                key,
2376                DsparkSegGraph {
2377                    graph,
2378                    _keeper: keeper,
2379                },
2380            );
2381        }
2382        self.full[&key].graph.launch()?;
2383        // Host bookkeeping for the replayed body (captured host code does not re-run):
2384        // gdn parity swap per linear layer (t odd), kv len bump per fa layer — scoped
2385        // to the WALK [lo, hi): the cache can carry extra state slots past it (the MTP
2386        // head layer's kv) that the walk never touches.
2387        if t % 2 == 1 {
2388            for &il in &self.lin {
2389                if il < lo || il >= hi {
2390                    continue;
2391                }
2392                let rl = cache.recur[il].as_mut().unwrap();
2393                std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2394            }
2395        }
2396        for &il in &self.fa {
2397            if il < lo || il >= hi {
2398                continue;
2399            }
2400            cache.kv[il].as_mut().unwrap().len += t;
2401        }
2402        let (_, xout) = self.stage.get(&t).unwrap();
2403        let mut out = e.uninit(t * n_embd)?;
2404        e.copy_into(&mut out, 0, xout, t * n_embd)?;
2405        Ok(out)
2406    }
2407
2408    /// Run layers [start, end) (all linear) as one captured graph at this vt: stage the
2409    /// residual into the bucket's x_in, capture on first encounter (2 executing warmups
2410    /// bracketed by a segment state save/restore), launch, then apply the host parity
2411    /// bookkeeping the captured body would have done. Returns the fresh residual.
2412    #[allow(clippy::too_many_arguments)]
2413    fn run_segment(
2414        &mut self,
2415        model: &crate::hybrid::HybridModel,
2416        e: &Engine,
2417        start: usize,
2418        end: usize,
2419        x: &CudaSlice<f32>,
2420        t: usize,
2421        cache: &mut Cache,
2422    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2423        let n_embd = self.n_embd;
2424        debug_assert!(end - start <= self.max_run);
2425        if !self.stage.contains_key(&t) {
2426            let xin = e.uninit(t * n_embd)?;
2427            let xout = e.uninit(t * n_embd)?;
2428            self.stage.insert(t, (xin, xout));
2429        }
2430        // Stage the residual at the bucket's baked input address.
2431        {
2432            let (xin, _) = self.stage.get_mut(&t).unwrap();
2433            e.copy_into(xin, 0, x, t * n_embd)?;
2434        }
2435        let key = (start, t);
2436        if !self.graphs.contains_key(&key) {
2437            // The 2 warmups EXECUTE the segment on live state — save conv + the canonical
2438            // ssm of every segment layer first, restore after, so the graph's first real
2439            // launch starts from the exact pre-round state (bytes gated e2e).
2440            for (k, il) in (start..end).enumerate() {
2441                let rl = cache.recur[il].as_ref().unwrap();
2442                e.copy_into(
2443                    &mut self.save_conv,
2444                    k * self.conv_words,
2445                    &rl.conv_state,
2446                    self.conv_words,
2447                )?;
2448                e.copy_into(
2449                    &mut self.save_ssm,
2450                    k * self.ssm_words,
2451                    &rl.ssm_state,
2452                    self.ssm_words,
2453                )?;
2454            }
2455            let (graph, keeper) = {
2456                let table_all = &self.table_all;
2457                let lin_pos = &self.lin_pos;
2458                let stash_conv = &mut self.stash_conv;
2459                let stash_ssm = &mut self.stash_ssm;
2460                let (xin, xout) = self
2461                    .stage
2462                    .get_mut(&t)
2463                    .map(|(a, b)| (&*a, b))
2464                    .expect("stage bucket created above");
2465                let cache_ref: &mut Cache = cache;
2466                // Slice 4 (fa-execupdate lane): USE_NODE_PRIORITY instead of
2467                // AUTO_FREE_ON_LAUNCH. The slice-3 measured limiter was AUTO_FREE's
2468                // launch-time mem-pool scan — 25.6 us per cuGraphLaunch x 16 segments
2469                // = ~0.41 ms/round, most of the eager-launch savings. The captured
2470                // body's cuMemAllocAsync transients are BALANCED by in-graph frees
2471                // (every transient drops inside the capture region — the generic
2472                // capture path's census precedent, 1589/1589), so AUTO_FREE has
2473                // nothing to reclaim and the graph is legal to instantiate without
2474                // it; PRIORITY is the flag the gemma slotted door ships for exactly
2475                // this reason (both alternatives drop the scan; UPLOAD via
2476                // cuGraphInstantiateWithFlags is WithParams-only and refused).
2477                // MEMRA_DSPARK_VG_AUTOFREE=1 reverts; MEMRA_GRAPH_CENSUS=1 prints
2478                // the node census at capture (the ALLOC==FREE receipt).
2479                let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
2480                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
2481                } else {
2482                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
2483                };
2484                e.capture_graph_retained_flags(iflag, move |e| {
2485                    let mut xc: Option<CudaSlice<f32>> = None;
2486                    for il in start..end {
2487                        let k = lin_pos[&il];
2488                        let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
2489                        let nx = model.qwen35_tparallel_linear_layer(
2490                            e,
2491                            il,
2492                            xr,
2493                            t,
2494                            cache_ref,
2495                            None,
2496                            Some((&mut stash_conv[k], &mut stash_ssm[k])),
2497                            Some((table_all, k * 6)),
2498                        )?;
2499                        xc = Some(nx);
2500                    }
2501                    e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
2502                    Ok(())
2503                })?
2504            };
2505            // Undo the net host parity motion of the 3 body runs (each run swaps iff t
2506            // is odd -> 3 runs = net one swap), then restore the device state the
2507            // warmups consumed. The launch below then behaves exactly like one run.
2508            if t % 2 == 1 {
2509                for il in start..end {
2510                    let rl = cache.recur[il].as_mut().unwrap();
2511                    std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2512                }
2513            }
2514            for (k, il) in (start..end).enumerate() {
2515                let rl = cache.recur[il].as_mut().unwrap();
2516                let (cw, sw) = (self.conv_words, self.ssm_words);
2517                {
2518                    let sv = e.view(&self.save_conv, self.lin.len() * cw);
2519                    let win = sv.slice(k * cw..(k + 1) * cw);
2520                    e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
2521                }
2522                {
2523                    let sv = e.view(&self.save_ssm, self.lin.len() * sw);
2524                    let win = sv.slice(k * sw..(k + 1) * sw);
2525                    e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
2526                }
2527            }
2528            if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
2529                if let Ok(c) = crate::graph_update::node_census(&graph) {
2530                    eprintln!("[dspark-vg-census] seg={start}..{end} vt={t} {c:?}");
2531                }
2532            }
2533            self.graphs.insert(
2534                key,
2535                DsparkSegGraph {
2536                    graph,
2537                    _keeper: keeper,
2538                },
2539            );
2540        }
2541        self.graphs[&key].graph.launch()?;
2542        // Host parity bookkeeping for the replayed body (the captured host swaps do not
2543        // re-run at replay).
2544        if t % 2 == 1 {
2545            for il in start..end {
2546                let rl = cache.recur[il].as_mut().unwrap();
2547                std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2548            }
2549        }
2550        let (_, xout) = self.stage.get(&t).unwrap();
2551        let mut out = e.uninit(t * n_embd)?;
2552        e.copy_into(&mut out, 0, xout, t * n_embd)?;
2553        Ok(out)
2554    }
2555
2556    /// Pool freeze check (`dspark_vg_cap`): below the ceiling new keys may capture.
2557    fn can_capture(&self) -> bool {
2558        self.graphs.len() + self.full.len() < dspark_vg_cap()
2559    }
2560
2561    /// Round-atomic segment-door readiness: TRUE when this round's walk can ride the
2562    /// per-(segment, vt) graphs without a NEW capture past the pool ceiling — every
2563    /// linear run in [lo, hi) already has its (run_start, t) key, or capture is still
2564    /// allowed. FALSE sends the WHOLE round down the eager cols-ckpt walk: a partial
2565    /// refusal would stash some layers in the ctx slabs and others in the round's cols
2566    /// while one commit reads only one of them.
2567    pub(crate) fn segments_ready(
2568        &self,
2569        model: &crate::hybrid::HybridModel,
2570        lo: usize,
2571        hi: usize,
2572        t: usize,
2573    ) -> bool {
2574        if self.can_capture() {
2575            return true;
2576        }
2577        let mut il = lo;
2578        while il < hi {
2579            if matches!(model.layers[il].mixer, Mixer::Linear(_)) {
2580                let start = il;
2581                while il < hi && matches!(model.layers[il].mixer, Mixer::Linear(_)) {
2582                    il += 1;
2583                }
2584                if !self.graphs.contains_key(&(start, t)) {
2585                    return false;
2586                }
2587            } else {
2588                il += 1;
2589            }
2590        }
2591        true
2592    }
2593
2594    /// Widest verify window this pool was built for. A caller whose round exceeds it must
2595    /// take the eager walk: the stash slabs hold `t_capacity() - 1` column rows, and slicing
2596    /// past them is a panic rather than a refusal.
2597    pub(crate) fn t_capacity(&self) -> usize {
2598        self.t_cap
2599    }
2600
2601    /// Slab row (conv, ssm) device pointers + lengths for the commit restore of column
2602    /// `row` (0-based) of layer `il`. None for non-linear layers.
2603    pub(crate) fn slab_row(
2604        &self,
2605        e: &Engine,
2606        il: usize,
2607        row: usize,
2608    ) -> Option<(u64, u64, usize, usize)> {
2609        use cudarc::driver::DevicePtr;
2610        let k = *self.lin_pos.get(&il)?;
2611        let s = &e.gpu.stream();
2612        let (pc, _g0) = self.stash_conv[k].device_ptr(s);
2613        let (ps, _g1) = self.stash_ssm[k].device_ptr(s);
2614        Some((
2615            pc as u64 + (row * self.conv_words * 4) as u64,
2616            ps as u64 + (row * self.ssm_words * 4) as u64,
2617            self.conv_words,
2618            self.ssm_words,
2619        ))
2620    }
2621}
2622
2623impl VerifyCkpt {
2624    fn new(n_layer: usize) -> Self {
2625        VerifyCkpt {
2626            gdn: (0..n_layer).map(|_| None).collect(),
2627            cols: (0..n_layer).map(|_| None).collect(),
2628        }
2629    }
2630}
2631
2632/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
2633/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
2634/// a logical round number.
2635struct VerifyBoundaryTicket {
2636    rt: &'static crate::pp::PpNRt,
2637    caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
2638    slot: usize,
2639    pos0: usize,
2640    t: usize,
2641    payload: usize,
2642    n_st: usize,
2643    pipelined: bool,
2644    pp_anatomy: bool,
2645    pp_started: std::time::Instant,
2646    reverse_ms: f64,
2647    stage0_ms: f64,
2648    tx_ms: f64,
2649    trace: Option<SpecPipeTraceCtx>,
2650}
2651
2652/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
2653/// increment-2 controller can also be armed by the server's fresh-process research door.
2654#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2655pub enum OptiForkGateMode {
2656    Disabled,
2657    Hit,
2658    Miss,
2659    Alternate,
2660    Abort,
2661    Controller,
2662}
2663
2664static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2665static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
2666    std::sync::atomic::AtomicU32::new(0);
2667static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2668static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2669static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2670static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2671static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2672static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2673static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2674static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2675static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2676static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2677    std::sync::atomic::AtomicU64::new(0);
2678static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2679    std::sync::atomic::AtomicU64::new(0);
2680static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2681
2682impl OptiForkGateMode {
2683    fn code(self) -> u8 {
2684        match self {
2685            Self::Disabled => 0,
2686            Self::Hit => 1,
2687            Self::Miss => 2,
2688            Self::Alternate => 3,
2689            Self::Abort => 4,
2690            Self::Controller => 5,
2691        }
2692    }
2693
2694    fn configured() -> Self {
2695        match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
2696            1 => Self::Hit,
2697            2 => Self::Miss,
2698            3 => Self::Alternate,
2699            4 => Self::Abort,
2700            5 => Self::Controller,
2701            _ => Self::Disabled,
2702        }
2703    }
2704
2705    fn action(self, generation: u64) -> OptiForkAction {
2706        match self {
2707            Self::Hit => OptiForkAction::Hit,
2708            Self::Miss => OptiForkAction::Miss,
2709            Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
2710            Self::Alternate => OptiForkAction::Miss,
2711            Self::Abort => OptiForkAction::Abort,
2712            Self::Disabled | Self::Controller => {
2713                unreachable!("non-forced mode cannot choose a forced fork action")
2714            }
2715        }
2716    }
2717
2718    fn is_forced(self) -> bool {
2719        matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
2720    }
2721}
2722
2723/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
2724pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
2725    OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
2726}
2727
2728/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
2729/// two-token draft-probability product. Serving can call this only through its explicit
2730/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
2731pub fn set_optipipe_controller_threshold(threshold: f32) {
2732    assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
2733    OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
2734    set_optipipe_gate_mode(OptiForkGateMode::Controller);
2735}
2736
2737#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2738pub struct OptiForkGateStats {
2739    pub attempts: u64,
2740    pub hits: u64,
2741    pub misses: u64,
2742    pub abort_drains: u64,
2743    pub refusals: u64,
2744    pub gate_checks: u64,
2745    pub gate_admits: u64,
2746    pub gate_rejects: u64,
2747    pub reconciles: u64,
2748    pub wasted_draft_tokens: u64,
2749    pub shadow_draft_tokens: u64,
2750    pub breaker_trips: u64,
2751}
2752
2753#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2754pub struct OptiForkStateIdentity {
2755    pub trunk_kv_bytes: usize,
2756    pub recurrent_bytes: usize,
2757    pub scratch_kv_bytes: usize,
2758    pub hidden_bytes: usize,
2759}
2760
2761pub fn reset_optipipe_gate_stats() {
2762    for counter in [
2763        &OPTI_FORK_ATTEMPTS,
2764        &OPTI_FORK_HITS,
2765        &OPTI_FORK_MISSES,
2766        &OPTI_FORK_ABORT_DRAINS,
2767        &OPTI_FORK_REFUSALS,
2768        &OPTI_GATE_CHECKS,
2769        &OPTI_GATE_ADMITS,
2770        &OPTI_GATE_REJECTS,
2771        &OPTI_RECONCILES,
2772        &OPTI_WASTED_DRAFT_TOKENS,
2773        &OPTI_SHADOW_DRAFT_TOKENS,
2774        &OPTI_BREAKER_TRIPS,
2775    ] {
2776        counter.store(0, std::sync::atomic::Ordering::Relaxed);
2777    }
2778}
2779
2780pub fn optipipe_gate_stats() -> OptiForkGateStats {
2781    let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
2782    OptiForkGateStats {
2783        attempts: load(&OPTI_FORK_ATTEMPTS),
2784        hits: load(&OPTI_FORK_HITS),
2785        misses: load(&OPTI_FORK_MISSES),
2786        abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
2787        refusals: load(&OPTI_FORK_REFUSALS),
2788        gate_checks: load(&OPTI_GATE_CHECKS),
2789        gate_admits: load(&OPTI_GATE_ADMITS),
2790        gate_rejects: load(&OPTI_GATE_REJECTS),
2791        reconciles: load(&OPTI_RECONCILES),
2792        wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
2793        shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
2794        breaker_trips: load(&OPTI_BREAKER_TRIPS),
2795    }
2796}
2797
2798#[derive(Clone, Copy, Debug)]
2799struct OptiControllerPolicy {
2800    threshold: f32,
2801    consecutive_misses: u8,
2802    breaker_tripped: bool,
2803}
2804
2805impl OptiControllerPolicy {
2806    fn configured() -> Self {
2807        Self {
2808            threshold: f32::from_bits(
2809                OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
2810            ),
2811            consecutive_misses: 0,
2812            breaker_tripped: false,
2813        }
2814    }
2815
2816    fn admit(&self, q_proxy: f32) -> bool {
2817        q_proxy.is_finite()
2818            && (0.0..=1.0).contains(&q_proxy)
2819            && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
2820    }
2821
2822    /// Returns true exactly when this resolution newly trips the three-miss breaker.
2823    fn resolve(&mut self, hit: bool) -> bool {
2824        // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
2825        // every optimistic opportunity, so the safety breaker is measured separately and must
2826        // not silently turn this arm into "three attempts then serial".
2827        if self.threshold == 0.0 {
2828            self.consecutive_misses = 0;
2829            return false;
2830        }
2831        if hit {
2832            self.consecutive_misses = 0;
2833            return false;
2834        }
2835        self.consecutive_misses = self.consecutive_misses.saturating_add(1);
2836        if !self.breaker_tripped && self.consecutive_misses >= 3 {
2837            self.breaker_tripped = true;
2838            return true;
2839        }
2840        false
2841    }
2842}
2843
2844#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2845enum OptiForkAction {
2846    Hit,
2847    Miss,
2848    Abort,
2849}
2850
2851#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2852struct OptiForkGeneration {
2853    id: u64,
2854    slot: usize,
2855}
2856
2857#[derive(Default)]
2858struct OptiForkGenerationTracker {
2859    next: u64,
2860    live: [Option<u64>; 2],
2861}
2862
2863impl OptiForkGenerationTracker {
2864    fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2865        let generation = OptiForkGeneration {
2866            id: self.next,
2867            slot: (self.next & 1) as usize,
2868        };
2869        if let Some(live) = self.live[generation.slot] {
2870            return Err(format!(
2871                "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
2872                generation.slot,
2873            )
2874            .into());
2875        }
2876        self.next += 1;
2877        self.live[generation.slot] = Some(generation.id);
2878        Ok(generation)
2879    }
2880
2881    fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2882        match self.live[generation.slot] {
2883            Some(id) if id == generation.id => {
2884                self.live[generation.slot] = None;
2885                Ok(())
2886            }
2887            other => Err(format!(
2888                "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
2889                generation.id, generation.slot,
2890            )
2891            .into()),
2892        }
2893    }
2894}
2895
2896struct OptiForkSeedGeneration {
2897    h_seed: CudaSlice<f32>,
2898    fill_prev: CudaSlice<f32>,
2899    scratch_len: usize,
2900}
2901
2902/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
2903/// generic cache helper accepts one device and therefore cannot copy GDN state split across
2904/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
2905/// device ownership.
2906fn opti_snapshot_stage_owned(
2907    e: &Engine,
2908    cache: &Cache,
2909    rt: &'static crate::pp::PpNRt,
2910    fence: &[usize],
2911) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
2912    let n = cache.kv.len();
2913    let mut snapshot = crate::cache::CacheSnapshot {
2914        kv_len: vec![None; n],
2915        tp_kv_len: vec![None; n],
2916        conv: (0..n).map(|_| None).collect(),
2917        ssm: (0..n).map(|_| None).collect(),
2918        pos: cache.pos,
2919    };
2920    opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
2921    Ok(snapshot)
2922}
2923
2924fn opti_snapshot_stage_owned_into(
2925    e: &Engine,
2926    cache: &Cache,
2927    rt: &'static crate::pp::PpNRt,
2928    fence: &[usize],
2929    snapshot: &mut crate::cache::CacheSnapshot,
2930) -> Result<(), Box<dyn std::error::Error>> {
2931    if fence.len() != rt.n_stages() + 1
2932        || snapshot.kv_len.len() != cache.kv.len()
2933        || snapshot.tp_kv_len.len() != cache.tp_kv.len()
2934    {
2935        return Err("optipipe stage-owned snapshot shape mismatch".into());
2936    }
2937    for stage in 0..rt.n_stages() {
2938        opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
2939    }
2940    snapshot.pos = cache.pos;
2941    Ok(())
2942}
2943
2944/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
2945/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
2946/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
2947/// either point would capture one side of the fork at the wrong generation.
2948fn opti_snapshot_one_stage_owned_into(
2949    e: &Engine,
2950    cache: &Cache,
2951    rt: &'static crate::pp::PpNRt,
2952    fence: &[usize],
2953    stage: usize,
2954    snapshot: &mut crate::cache::CacheSnapshot,
2955) -> Result<(), Box<dyn std::error::Error>> {
2956    if fence.len() != rt.n_stages() + 1
2957        || snapshot.kv_len.len() != cache.kv.len()
2958        || snapshot.tp_kv_len.len() != cache.tp_kv.len()
2959        || stage >= rt.n_stages()
2960    {
2961        return Err("optipipe single-stage snapshot shape mismatch".into());
2962    }
2963    let _scope = rt.enter(stage);
2964    let owner = rt.engine(stage, e);
2965    for il in fence[stage]..fence[stage + 1] {
2966        snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
2967        snapshot.tp_kv_len[il] = cache.tp_kv[il]
2968            .as_ref()
2969            .map(crate::tp::ResidentTpKvCache::committed_len);
2970        match &cache.recur[il] {
2971            Some(recur) => {
2972                match snapshot.conv[il].as_mut() {
2973                    Some(dst) => {
2974                        owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
2975                    }
2976                    None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
2977                }
2978                match snapshot.ssm[il].as_mut() {
2979                    Some(dst) => {
2980                        owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
2981                    }
2982                    None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
2983                }
2984            }
2985            None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
2986                return Err(
2987                    format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
2988                );
2989            }
2990            None => {}
2991        }
2992    }
2993    snapshot.pos = cache.pos;
2994    Ok(())
2995}
2996
2997/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
2998/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
2999/// resolve, so the reconcile tables and conditional restores are stage-local.
3000struct OptiForkState {
3001    mode: OptiForkGateMode,
3002    controller: Option<OptiControllerPolicy>,
3003    generations: OptiForkGenerationTracker,
3004    active_snapshot_slot: usize,
3005    alternate_snapshot: crate::cache::CacheSnapshot,
3006    seeds: [OptiForkSeedGeneration; 2],
3007    rt: &'static crate::pp::PpNRt,
3008    fence: [usize; 3],
3009    split: usize,
3010    len_ptrs: CudaSlice<u64>,
3011    saved_lens: CudaSlice<i32>,
3012    forced_acc: CudaSlice<u32>,
3013    valid: CudaSlice<u32>,
3014    stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
3015    logical_payload_bytes: [usize; 2],
3016}
3017
3018struct OptiForkTicket {
3019    generation: OptiForkGeneration,
3020    boundary: Option<VerifyBoundaryTicket>,
3021    drain: std::sync::Arc<cudarc::driver::CudaStream>,
3022    settled: bool,
3023}
3024
3025struct OptiControllerTicket {
3026    generation: OptiForkGeneration,
3027    boundary: Option<VerifyBoundaryTicket>,
3028    ckpt: Option<VerifyCkpt>,
3029    verify_tokens: [u32; 2],
3030    draft_prob: f32,
3031    eager_seed: Option<CudaSlice<f32>>,
3032    q_proxy: f32,
3033    scratch_len: usize,
3034    issued_at: std::time::Instant,
3035    drain: std::sync::Arc<cudarc::driver::CudaStream>,
3036    settled: bool,
3037}
3038
3039struct OptiControllerPrepared {
3040    verify_tokens: [u32; 2],
3041    draft_prob: f32,
3042    eager_seed: Option<CudaSlice<f32>>,
3043    q_proxy: f32,
3044    scratch_len: usize,
3045}
3046
3047impl OptiControllerTicket {
3048    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
3049        self.boundary
3050            .take()
3051            .expect("controller boundary ticket already consumed")
3052    }
3053
3054    fn take_ckpt(&mut self) -> VerifyCkpt {
3055        self.ckpt
3056            .take()
3057            .expect("controller verify checkpoint already consumed")
3058    }
3059
3060    fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
3061        self.eager_seed.take()
3062    }
3063
3064    fn settle(&mut self) {
3065        self.settled = true;
3066    }
3067}
3068
3069impl Drop for OptiControllerTicket {
3070    fn drop(&mut self) {
3071        if !self.settled {
3072            let _ = self.drain.synchronize();
3073            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3074        }
3075    }
3076}
3077
3078impl OptiForkTicket {
3079    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
3080        self.boundary
3081            .take()
3082            .expect("fork ticket boundary already consumed")
3083    }
3084
3085    fn settle(&mut self) {
3086        self.settled = true;
3087    }
3088}
3089
3090impl Drop for OptiForkTicket {
3091    fn drop(&mut self) {
3092        if !self.settled {
3093            let _ = self.drain.synchronize();
3094            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3095        }
3096    }
3097}
3098
3099impl OptiForkState {
3100    #[allow(clippy::too_many_arguments)]
3101    fn new(
3102        e: &Engine,
3103        cache: &Cache,
3104        mode: OptiForkGateMode,
3105        alternate_snapshot: crate::cache::CacheSnapshot,
3106        h_seed: &CudaSlice<f32>,
3107        fill_prev: &CudaSlice<f32>,
3108        rt: &'static crate::pp::PpNRt,
3109        split: usize,
3110        n_layer: usize,
3111    ) -> Result<Self, Box<dyn std::error::Error>> {
3112        let fence = [0, split, n_layer];
3113        let mut logical_payload_bytes = [0usize; 2];
3114        for stage in 0..2 {
3115            for il in fence[stage]..fence[stage + 1] {
3116                logical_payload_bytes[stage] += alternate_snapshot.conv[il]
3117                    .as_ref()
3118                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
3119                logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
3120                    .as_ref()
3121                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
3122            }
3123        }
3124        let seeds = [
3125            OptiForkSeedGeneration {
3126                h_seed: e.clone_dtod(h_seed)?,
3127                fill_prev: e.clone_dtod(fill_prev)?,
3128                scratch_len: 0,
3129            },
3130            OptiForkSeedGeneration {
3131                h_seed: e.clone_dtod(h_seed)?,
3132                fill_prev: e.clone_dtod(fill_prev)?,
3133                scratch_len: 0,
3134            },
3135        ];
3136        let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
3137            let _stage = rt.enter(0);
3138            let e0 = rt.engine(0, e);
3139            (
3140                crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
3141                e0.htod_i32(&vec![0; split])?,
3142                e0.alloc_u32_zeroed(2)?,
3143                e0.alloc_u32_zeroed(1)?,
3144                e0.stream(),
3145            )
3146        };
3147        logical_payload_bytes[0] += seeds
3148            .iter()
3149            .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
3150            .sum::<usize>();
3151        logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
3152            + saved_lens.len() * std::mem::size_of::<i32>()
3153            + forced_acc.len() * std::mem::size_of::<u32>()
3154            + valid.len() * std::mem::size_of::<u32>();
3155        Ok(Self {
3156            mode,
3157            controller: (mode == OptiForkGateMode::Controller)
3158                .then(OptiControllerPolicy::configured),
3159            generations: OptiForkGenerationTracker::default(),
3160            active_snapshot_slot: 0,
3161            alternate_snapshot,
3162            seeds,
3163            rt,
3164            fence,
3165            split,
3166            len_ptrs,
3167            saved_lens,
3168            forced_acc,
3169            valid,
3170            stage0_stream,
3171            logical_payload_bytes,
3172        })
3173    }
3174
3175    fn reserve(
3176        &mut self,
3177        current_snapshot: &mut crate::cache::CacheSnapshot,
3178    ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
3179        let generation = self.generations.reserve()?;
3180        if generation.slot != self.active_snapshot_slot {
3181            std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
3182            self.active_snapshot_slot = generation.slot;
3183        }
3184        Ok(generation)
3185    }
3186
3187    fn capture_seed(
3188        &mut self,
3189        e: &Engine,
3190        generation: OptiForkGeneration,
3191        h_seed: &CudaSlice<f32>,
3192        fill_prev: &CudaSlice<f32>,
3193        scratch_len: usize,
3194    ) -> Result<(), Box<dyn std::error::Error>> {
3195        let seed = &mut self.seeds[generation.slot];
3196        e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
3197        e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
3198        seed.scratch_len = scratch_len;
3199        Ok(())
3200    }
3201
3202    fn ticket(
3203        &self,
3204        generation: OptiForkGeneration,
3205        boundary: VerifyBoundaryTicket,
3206    ) -> OptiForkTicket {
3207        OptiForkTicket {
3208            generation,
3209            boundary: Some(boundary),
3210            drain: self.stage0_stream.clone(),
3211            settled: false,
3212        }
3213    }
3214
3215    #[allow(clippy::too_many_arguments)]
3216    fn controller_ticket(
3217        &self,
3218        generation: OptiForkGeneration,
3219        boundary: VerifyBoundaryTicket,
3220        ckpt: VerifyCkpt,
3221        verify_tokens: [u32; 2],
3222        draft_prob: f32,
3223        eager_seed: Option<CudaSlice<f32>>,
3224        q_proxy: f32,
3225        scratch_len: usize,
3226    ) -> OptiControllerTicket {
3227        OptiControllerTicket {
3228            generation,
3229            boundary: Some(boundary),
3230            ckpt: Some(ckpt),
3231            verify_tokens,
3232            draft_prob,
3233            eager_seed,
3234            q_proxy,
3235            scratch_len,
3236            issued_at: std::time::Instant::now(),
3237            drain: self.stage0_stream.clone(),
3238            settled: false,
3239        }
3240    }
3241
3242    fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
3243        self.generations.reserve()
3244    }
3245
3246    fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
3247        &mut self.alternate_snapshot
3248    }
3249
3250    fn promote_successor_snapshot(
3251        &mut self,
3252        current_snapshot: &mut crate::cache::CacheSnapshot,
3253        generation: OptiForkGeneration,
3254    ) {
3255        std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
3256        self.active_snapshot_slot = generation.slot;
3257    }
3258
3259    fn queue_actual_reconcile(
3260        &mut self,
3261        e: &Engine,
3262        snapshot: &crate::cache::CacheSnapshot,
3263        acc: &CudaSlice<u32>,
3264        optimistic_pending: u32,
3265        base: usize,
3266    ) -> Result<(), Box<dyn std::error::Error>> {
3267        let saved: Vec<i32> = (0..self.split)
3268            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
3269            .collect();
3270        // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
3271        // decision point there and append a wait to stage 0 after its optimistic successor/TX;
3272        // the validity/reconcile kernels must never peer-read acc before it is written. The
3273        // increment-1 harness uses primary stage 0, where stream order already provides this.
3274        if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
3275            self.rt.fence_stages_behind(&e.stream())?;
3276        }
3277        let _stage = self.rt.enter(0);
3278        let e0 = self.rt.engine(0, e);
3279        e0.htod_i32_into(&mut self.saved_lens, &saved)?;
3280        e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
3281        e0.spec_fork_reconcile_kv(
3282            &self.len_ptrs,
3283            &self.saved_lens,
3284            acc,
3285            &self.valid,
3286            base,
3287            self.split,
3288        )
3289    }
3290
3291    fn finish_actual_reconcile(
3292        &mut self,
3293        e: &Engine,
3294        cache: &mut Cache,
3295        snapshot: &crate::cache::CacheSnapshot,
3296        n_acc: usize,
3297        base: usize,
3298        hit: bool,
3299    ) -> Result<(), Box<dyn std::error::Error>> {
3300        if hit {
3301            return Ok(());
3302        }
3303        let len_delta = base + n_acc;
3304        for il in 0..self.split {
3305            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3306                kv.len = saved + len_delta;
3307            }
3308        }
3309        {
3310            let _stage = self.rt.enter(1);
3311            let e1 = self.rt.engine(1, e);
3312            for il in self.split..self.fence[2] {
3313                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3314                    kv.len = saved + len_delta;
3315                    e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3316                }
3317            }
3318        }
3319        self.rt.publish_to(0, &e.stream())?;
3320        Ok(())
3321    }
3322
3323    fn cancel_controller_ticket(
3324        &mut self,
3325        e: &Engine,
3326        cache: &mut Cache,
3327        scratch: &mut MtpScratch,
3328        snapshot: &crate::cache::CacheSnapshot,
3329        ticket: &mut OptiControllerTicket,
3330    ) -> Result<(), Box<dyn std::error::Error>> {
3331        {
3332            let _stage = self.rt.enter(0);
3333            let e0 = self.rt.engine(0, e);
3334            for il in 0..self.split {
3335                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3336                    kv.len = saved;
3337                    e0.set_i32_one(&mut kv.len_d, saved as i32)?;
3338                }
3339            }
3340        }
3341        scratch.set_len(e, snapshot.pos)?;
3342        ticket.settle();
3343        self.generations.retire(ticket.generation)?;
3344        OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3345        OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
3346        eprintln!(
3347            "[opti-controller] tail-drain generation={} slot={}",
3348            ticket.generation.id, ticket.generation.slot,
3349        );
3350        Ok(())
3351    }
3352
3353    #[allow(clippy::too_many_arguments)]
3354    fn reconcile(
3355        &mut self,
3356        e: &Engine,
3357        cache: &mut Cache,
3358        scratch: &mut MtpScratch,
3359        snapshot: &crate::cache::CacheSnapshot,
3360        h_seed: &mut CudaSlice<f32>,
3361        fill_prev: &mut CudaSlice<f32>,
3362        generation: OptiForkGeneration,
3363        action: OptiForkAction,
3364        optimistic_pending: u32,
3365    ) -> Result<(), Box<dyn std::error::Error>> {
3366        debug_assert!(action != OptiForkAction::Abort);
3367        let miss_started = std::time::Instant::now();
3368        let keep = action == OptiForkAction::Hit;
3369        let saved: Vec<i32> = (0..self.split)
3370            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
3371            .collect();
3372        let seed = &self.seeds[generation.slot];
3373        {
3374            let _stage = self.rt.enter(0);
3375            let e0 = self.rt.engine(0, e);
3376            e0.htod_i32_into(&mut self.saved_lens, &saved)?;
3377            let forced = if keep {
3378                [1u32, optimistic_pending]
3379            } else {
3380                [0u32, optimistic_pending]
3381            };
3382            e0.htod_u32_into(&mut self.forced_acc, &forced)?;
3383            e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
3384            e0.spec_fork_reconcile_kv(
3385                &self.len_ptrs,
3386                &self.saved_lens,
3387                &self.forced_acc,
3388                &self.valid,
3389                0,
3390                self.split,
3391            )?;
3392            for il in 0..self.split {
3393                if let Some(recur) = cache.recur[il].as_mut() {
3394                    let conv = snapshot.conv[il]
3395                        .as_ref()
3396                        .ok_or("optipipe stage0 snapshot missing conv state")?;
3397                    let ssm = snapshot.ssm[il]
3398                        .as_ref()
3399                        .ok_or("optipipe stage0 snapshot missing ssm state")?;
3400                    e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
3401                    e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
3402                }
3403            }
3404            e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
3405            e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
3406        }
3407
3408        if keep {
3409            OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3410            return Ok(());
3411        }
3412
3413        for il in 0..self.split {
3414            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3415                kv.len = saved;
3416            }
3417        }
3418        scratch.set_len(e, seed.scratch_len)?;
3419        // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
3420        // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
3421        let caller = e.stream();
3422        self.rt.publish_to(0, &caller)?;
3423        caller.synchronize()?;
3424        let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
3425        eprintln!(
3426            "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
3427            generation.id, generation.slot,
3428        );
3429        OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3430        Ok(())
3431    }
3432
3433    fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
3434        self.generations.retire(generation)
3435    }
3436}
3437
3438fn rewind_tp_kv_verified_prefix(
3439    tp_kv: &mut [Option<crate::tp::ResidentTpKvCache>],
3440    saved_lens: &[Option<usize>],
3441    accepted: usize,
3442) -> Result<(), Box<dyn std::error::Error>> {
3443    if tp_kv.len() != saved_lens.len() {
3444        return Err("spec TP KV snapshot shape mismatch".into());
3445    }
3446    for (layer, (cache, saved)) in tp_kv.iter_mut().zip(saved_lens).enumerate() {
3447        match (cache.as_mut(), *saved) {
3448            (Some(cache), Some(saved)) => {
3449                let target = saved
3450                    .checked_add(accepted)
3451                    .ok_or("spec TP KV committed length overflow")?;
3452                cache.rewind_to(target)?;
3453            }
3454            (None, None) => {}
3455            _ => {
3456                return Err(
3457                    format!("spec TP KV layer {layer} changed shape since its snapshot").into(),
3458                );
3459            }
3460        }
3461    }
3462    Ok(())
3463}
3464
3465impl HybridModel {
3466    fn mtp_head_count(&self) -> usize {
3467        usize::from(self.mtp.is_some()) + self.mtp_extra.len()
3468    }
3469
3470    fn mtp_head_at(&self, index: usize) -> &MtpHead {
3471        if index == 0 {
3472            self.mtp.as_ref().expect("MTP head 0 is unavailable")
3473        } else {
3474            &self.mtp_extra[index - 1]
3475        }
3476    }
3477
3478    fn new_mtp_scratch(
3479        &self,
3480        e: &Engine,
3481        cap: usize,
3482    ) -> Result<MtpScratch, Box<dyn std::error::Error>> {
3483        let mut scratch = MtpScratch::new(
3484            e,
3485            &self.cfg,
3486            &self.plan,
3487            cap,
3488            self.mtp.as_ref().and_then(|head| head.geom.as_ref()),
3489        )?;
3490        for head in &self.mtp_extra {
3491            scratch.push_plane(e, &self.cfg, &self.plan, head.geom.as_ref())?;
3492        }
3493        Ok(scratch)
3494    }
3495
3496    fn opti_graph_draft_step(
3497        &self,
3498        e: &Engine,
3499        mtp: &MtpHead,
3500        dctx: &mut DraftGraphCtx,
3501        scratch: &mut MtpScratch,
3502        d_vocab: usize,
3503    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
3504        dctx.graph
3505            .as_ref()
3506            .ok_or("optipipe controller requires the greedy draft graph")?
3507            .launch()?;
3508        scratch.kv.len += 1;
3509        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
3510        if (idx as usize) >= d_vocab {
3511            return Err(
3512                format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
3513            );
3514        }
3515        let probability = e.dtoh(&dctx.g_p)?[0];
3516        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
3517            return Err(format!("optipipe draft probability is invalid: {probability}").into());
3518        }
3519        let token = match &mtp.d2t {
3520            Some(map) => map[idx as usize],
3521            None => idx,
3522        };
3523        if token != idx {
3524            e.set_u32_one(&mut dctx.g_tok, token)?;
3525        }
3526        Ok((token, probability))
3527    }
3528
3529    #[allow(clippy::too_many_arguments)]
3530    fn opti_controller_draft_step(
3531        &self,
3532        e: &Engine,
3533        mtp: &MtpHead,
3534        dctx: &mut DraftGraphCtx,
3535        scratch: &mut MtpScratch,
3536        d_vocab: usize,
3537        eager_state: &mut Option<(u32, CudaSlice<f32>)>,
3538        eager_pos: usize,
3539        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3540    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
3541        if dctx.graph.is_some() {
3542            return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
3543        }
3544        let (input_token, input_seed) = eager_state
3545            .take()
3546            .ok_or("optipipe eager continuation seed is unavailable")?;
3547        let (logits, next_seed) = self.mtp_head_forward_dev(
3548            e,
3549            mtp,
3550            input_token,
3551            &input_seed,
3552            scratch,
3553            eager_pos,
3554            embd_dev,
3555            None,
3556        )?;
3557        let token_d = e.argmax_token_device(&logits, d_vocab)?;
3558        let idx = e.dtoh_u32_one(&token_d)?;
3559        if (idx as usize) >= d_vocab {
3560            return Err(format!(
3561                "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
3562            )
3563            .into());
3564        }
3565        let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
3566        let probability = e.dtoh(&probability_d)?[0];
3567        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
3568            return Err(
3569                format!("optipipe eager draft probability is invalid: {probability}").into(),
3570            );
3571        }
3572        let token = match &mtp.d2t {
3573            Some(map) => map[idx as usize],
3574            None => idx,
3575        };
3576        *eager_state = Some((token, next_seed));
3577        Ok((token, probability))
3578    }
3579
3580    /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
3581    /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
3582    /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
3583    /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
3584    /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
3585    /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
3586    /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
3587    /// transfer + host argmax per draft token from the K-token draft chain.
3588    #[allow(clippy::too_many_arguments)]
3589    fn mtp_head_forward_dev(
3590        &self,
3591        e: &Engine,
3592        mtp: &MtpHead,
3593        e_tok: u32,
3594        h_seed: &CudaSlice<f32>,
3595        scratch: &mut MtpScratch,
3596        mtp_pos: usize,
3597        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3598        mask: Option<(&CudaSlice<u32>, usize)>,
3599    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3600        self.mtp_head_forward_dev_at(e, mtp, e_tok, h_seed, scratch, 0, mtp_pos, embd_dev, mask)
3601    }
3602
3603    #[allow(clippy::too_many_arguments)]
3604    fn mtp_head_forward_dev_at(
3605        &self,
3606        e: &Engine,
3607        mtp: &MtpHead,
3608        e_tok: u32,
3609        h_seed: &CudaSlice<f32>,
3610        scratch: &mut MtpScratch,
3611        scratch_index: usize,
3612        mtp_pos: usize,
3613        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3614        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
3615        // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
3616        // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
3617        mask: Option<(&CudaSlice<u32>, usize)>,
3618    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3619        // MEMRA_SPEC_ANATOMY=1 — eager-step phase timers (diagnostic only). Phase boundaries
3620        // sync the stream, so absolute time inflates; the BREAKDOWN is the signal. Cumulative
3621        // summary on stderr every 128 steps: glue (embed..attn_norm), attn, ffn, head.
3622        use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
3623        static ANAT_NS: [AtomicU64; 5] = [
3624            AtomicU64::new(0),
3625            AtomicU64::new(0),
3626            AtomicU64::new(0),
3627            AtomicU64::new(0),
3628            AtomicU64::new(0),
3629        ];
3630        static ANAT_STEPS: AtomicU64 = AtomicU64::new(0);
3631        let anat = {
3632            static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3633            *ON.get_or_init(|| std::env::var("MEMRA_SPEC_ANATOMY").as_deref() == Ok("1"))
3634        };
3635        if anat {
3636            e.stream().synchronize()?; // drain prior queue so phase 0 starts clean
3637        }
3638        let t_all = std::time::Instant::now();
3639        let mut t_ph = std::time::Instant::now();
3640        let mut anat_mark = |i: usize,
3641                             e: &Engine,
3642                             t: &mut std::time::Instant|
3643         -> Result<(), Box<dyn std::error::Error>> {
3644            if anat {
3645                e.stream().synchronize()?;
3646                ANAT_NS[i].fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
3647                *t = std::time::Instant::now();
3648            }
3649            Ok(())
3650        };
3651        let cfg = &self.cfg;
3652        let n_embd = cfg.n_embd as usize;
3653        // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
3654        // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
3655        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3656        let eps = cfg.rms_eps;
3657        let pos_d = e.htod_i32(&[mtp_pos as i32])?;
3658
3659        // op A: a resident table transfers one 4B token id. The exact host-row capacity path
3660        // expands this one row on CPU and transfers n_embd f32 values instead.
3661        let e_emb = match embd_dev {
3662            Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
3663            None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
3664        };
3665
3666        // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
3667        let mut e_norm = e.zeros(n_embd)?;
3668        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
3669        let mut h_norm = e.zeros(n_embd)?;
3670        e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
3671
3672        // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
3673        let mut concat = e.zeros(2 * n_embd)?;
3674        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
3675        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
3676
3677        // op 4: inpSA = eh_proj @ concat  (eh_proj [2*n_embd, n_embd]) -> [n_embd]
3678        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
3679
3680        // op 5: a_norm = RMSNorm(inpSA, attn_norm)
3681        let mut a_norm = e.zeros(di)?;
3682        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
3683        anat_mark(0, e, &mut t_ph)?;
3684
3685        // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
3686        // scratch.cap, length from the device len_d) so eager drafts match graph drafts
3687        // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
3688        // advances only the device counter).
3689        let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
3690            // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
3691            // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
3692            // Advances BOTH the host len and the device counter itself (unlike the dc arm,
3693            // whose host-side mirror the caller does).
3694            (Mixer::Full(fa), Some(g)) => {
3695                self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch, scratch_index)?
3696            }
3697            (Mixer::Full(fa), None) => {
3698                let out = self.mtp_full_attn_dc(
3699                    e,
3700                    fa,
3701                    &a_norm,
3702                    &pos_d,
3703                    scratch,
3704                    scratch_index,
3705                    mtp.geom.as_ref(),
3706                )?;
3707                scratch.plane_mut(scratch_index).0.len += 1;
3708                out
3709            }
3710            (Mixer::Linear(_), _) => {
3711                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3712            }
3713            (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
3714        };
3715        anat_mark(1, e, &mut t_ph)?;
3716
3717        // op 7: x1 = inpSA + attn_out
3718        let mut x1 = e.zeros(di)?;
3719        e.add(&inp_sa, &attn_out, &mut x1, di)?;
3720
3721        // op 8: z = RMSNorm(x1, post_attn_norm)  (pre-FFN norm)
3722        let mut z = e.zeros(di)?;
3723        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
3724
3725        // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
3726        let ffn_out = match &mtp.ffn {
3727            crate::hybrid::Ffn::Dense {
3728                ffn_gate,
3729                ffn_up,
3730                ffn_down,
3731            } => {
3732                let n_ff = ffn_gate.out_features();
3733                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
3734                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
3735                    (
3736                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
3737                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
3738                    )
3739                } else {
3740                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
3741                };
3742                let mut act = e.zeros(n_ff)?;
3743                // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
3744                // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
3745                // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
3746                // passes None, which is `ffn_act`'s dispatch verbatim.
3747                Self::ffn_act_lim(
3748                    e,
3749                    &self.cfg,
3750                    &gate,
3751                    &up,
3752                    1.0,
3753                    1.0,
3754                    mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
3755                    &mut act,
3756                    n_ff,
3757                )?;
3758                e.matmul(ffn_down, &act, 1)?
3759            }
3760            // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
3761            // so they never alias trunk layer 0's cache keys.
3762            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
3763        };
3764        anat_mark(2, e, &mut t_ph)?;
3765
3766        // op 10: h_nextn = x1 + ffn_out (at di)
3767        let mut h_inner = e.zeros(di)?;
3768        e.add(&x1, &ffn_out, &mut h_inner, di)?;
3769
3770        // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
3771        // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
3772        let h_nextn = match mtp.geom.as_ref() {
3773            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
3774            None => h_inner,
3775        };
3776
3777        // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
3778        let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
3779        let mut final_h = e.zeros(n_embd)?;
3780        e.rms_norm(
3781            &h_nextn,
3782            final_norm.float_data(),
3783            &mut final_h,
3784            n_embd,
3785            1,
3786            eps,
3787        )?;
3788
3789        // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
3790        let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
3791        let mut logits = e.matmul(head, &final_h, 1)?;
3792        // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
3793        // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
3794        if let Some((mask_d, mw)) = mask {
3795            let d_vocab = head.out_features();
3796            e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
3797        }
3798        anat_mark(3, e, &mut t_ph)?;
3799        if anat {
3800            ANAT_NS[4].fetch_add(t_all.elapsed().as_nanos() as u64, Relaxed);
3801            let n = ANAT_STEPS.fetch_add(1, Relaxed) + 1;
3802            if n % 128 == 0 {
3803                let us = |i: usize| ANAT_NS[i].load(Relaxed) / n / 1000;
3804                eprintln!(
3805                    "[spec-anatomy] steps={n} avg us/step: glue={} attn={} ffn={} head={} total={}",
3806                    us(0),
3807                    us(1),
3808                    us(2),
3809                    us(3),
3810                    us(4)
3811                );
3812            }
3813        }
3814        // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
3815        // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
3816        Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
3817    }
3818
3819    #[allow(clippy::too_many_arguments)]
3820    fn mtp_chain_forward_dev(
3821        &self,
3822        e: &Engine,
3823        tokens: &[u32],
3824        seeds: &[CudaSlice<f32>],
3825        scratch: &mut MtpScratch,
3826        committed_scratch_len: usize,
3827        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3828        mask: Option<(&CudaSlice<u32>, usize)>,
3829    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3830        if tokens.is_empty() || tokens.len() != seeds.len() {
3831            return Err("multi-head MTP prefix tokens/seeds are malformed".into());
3832        }
3833        let index = mtp_chain_head_index(tokens.len() - 1, self.mtp_head_count());
3834        let head = self.mtp_head_at(index);
3835        scratch.set_plane_len(e, index, committed_scratch_len)?;
3836
3837        let mut last = None;
3838        for row in 0..tokens.len() {
3839            let is_last = row + 1 == tokens.len();
3840            last = Some(self.mtp_head_forward_dev_at(
3841                e,
3842                head,
3843                tokens[row],
3844                &seeds[row],
3845                scratch,
3846                index,
3847                committed_scratch_len + row + 1,
3848                embd_dev,
3849                if is_last { mask } else { None },
3850            )?);
3851        }
3852        Ok(last.expect("non-empty MTP prefix produced no row"))
3853    }
3854
3855    /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
3856    /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
3857    /// the dc path, and all three are properties of this arch's MTP block:
3858    ///
3859    /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
3860    ///    window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
3861    ///    cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
3862    ///    mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
3863    ///    windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
3864    ///    starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
3865    ///    new kernel. That is deliberately not built here: see the CUDA-graph note below.
3866    /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
3867    ///    on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
3868    ///    trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
3869    ///    resolved `Step35MtpGeom`, never from `cfg`.
3870    /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
3871    ///    sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
3872    ///    fused-into-wq `q_gate_split` form the dc arm handles.
3873    ///
3874    /// WHY EAGER-ONLY IS NOT A GAP TODAY: `mtp_head_forward_cap` refuses step35 heads
3875    /// explicitly (the SWA-window refusal below), so the graph draft never engages for step35
3876    /// models regardless of eligibility — the eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
3877    /// than silently capturing a window-less (wrong past `win` draft rows) graph.
3878    ///
3879    /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
3880    /// caller must not mirror.
3881    fn mtp_step35_attn(
3882        &self,
3883        e: &Engine,
3884        fa: &FullAttnLayer,
3885        g: &crate::hybrid::Step35MtpGeom,
3886        h: &CudaSlice<f32>,
3887        pos_d: &CudaSlice<i32>,
3888        scratch: &mut MtpScratch,
3889        scratch_index: usize,
3890    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3891        let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
3892        let eps = self.cfg.rms_eps;
3893        let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
3894        let n_embd = self.cfg.n_embd as usize;
3895        let gw = fa
3896            .attn_gate
3897            .as_ref()
3898            .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
3899
3900        let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
3901            && e.uses_q8_1_fast(&fa.wk)
3902            && e.uses_q8_1_fast(&fa.wv)
3903            && e.uses_q8_1_fast(gw)
3904        {
3905            let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
3906            let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
3907                Some(t3) => t3,
3908                None => (
3909                    e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
3910                    e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
3911                    e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
3912                ),
3913            };
3914            (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
3915        } else {
3916            (
3917                e.matmul(&fa.wq, h, 1)?,
3918                e.matmul(&fa.wk, h, 1)?,
3919                e.matmul(&fa.wv, h, 1)?,
3920                e.matmul(gw, h, 1)?,
3921            )
3922        };
3923
3924        let mut q = e.uninit(nh * hd)?;
3925        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
3926        let mut k = e.uninit(nkv * hd)?;
3927        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
3928        // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
3929        // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
3930        // the resolved flag, not the constant, so an all-full sibling stays correct.
3931        let ff = if g.swa {
3932            None
3933        } else {
3934            self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
3935        };
3936        #[cfg(debug_assertions)]
3937        if let Some(ff) = ff {
3938            crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
3939        }
3940        e.rope_neox2(
3941            &mut q,
3942            &mut k,
3943            pos_d,
3944            hd,
3945            g.n_rot,
3946            nh,
3947            nkv,
3948            1,
3949            g.rope_base,
3950            1.0,
3951            ff,
3952        )?;
3953
3954        // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
3955        // length on the host anyway, and the windowed view below needs it there to compute the
3956        // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
3957        // dc-family consumer of this scratch still agree.
3958        let (kv, scratch_cap) = scratch.plane_mut(scratch_index);
3959        assert!(
3960            kv.len < scratch_cap,
3961            "step35 MTP scratch overflow ({} >= {})",
3962            kv.len,
3963            scratch_cap
3964        );
3965        let next_len = kv.len + 1;
3966        let (off, t_kv) = if g.swa && next_len > g.window {
3967            (next_len - g.window, g.window)
3968        } else {
3969            (0, next_len)
3970        };
3971        let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
3972        e.append_kv_quantized(
3973            &k,
3974            &v0,
3975            &mut kv.k,
3976            &mut kv.v,
3977            write_row,
3978            kv.kv_dim_k,
3979            kv.kv_dim_v,
3980            kv.k_tok_bytes,
3981            kv.v_tok_bytes,
3982            false,
3983        )?;
3984        kv.len = next_len;
3985        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3986        // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
3987        // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
3988        // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
3989        // therefore live, not theoretical.
3990        let physical = kv.physical_rows(off, off + t_kv)?;
3991        let k_view = e.view_u8_range(
3992            &kv.k,
3993            physical.start * kv.k_tok_bytes,
3994            physical.end * kv.k_tok_bytes,
3995        );
3996        let v_view = e.view_u8_range(
3997            &kv.v,
3998            physical.start * kv.v_tok_bytes,
3999            physical.end * kv.v_tok_bytes,
4000        );
4001        let mut attn = e.uninit(nh * hd)?;
4002        e.fa_decode_kvmod(
4003            &q,
4004            &k_view,
4005            &v_view,
4006            &mut attn,
4007            hd,
4008            nh,
4009            nkv,
4010            t_kv,
4011            scale,
4012            kv.k_tok_bytes,
4013            kv.v_tok_bytes,
4014            false,
4015        )?;
4016
4017        let mut ag = e.uninit(nh * hd)?;
4018        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
4019        Ok(e.matmul(&fa.wo, &ag, 1)?)
4020    }
4021
4022    /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
4023    /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
4024    /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
4025    /// chain, and replays keep seeing KV growth through the device counter (no recapture).
4026    /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
4027    /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
4028    /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
4029    /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
4030    /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
4031    fn mtp_full_attn_dc(
4032        &self,
4033        e: &Engine,
4034        fa: &FullAttnLayer,
4035        h: &CudaSlice<f32>,
4036        pos_d: &CudaSlice<i32>,
4037        scratch: &mut MtpScratch,
4038        scratch_index: usize,
4039        geom: Option<&crate::hybrid::DraftGeom>,
4040    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4041        let cfg = &self.cfg;
4042        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
4043        let geometry = cfg.full_attention_geometry_at(mtp_il);
4044        let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
4045        let n_head_kv = geom
4046            .map(|g| g.n_head_kv)
4047            .unwrap_or(geometry.n_head_kv as usize);
4048        let head_dim = geometry.head_dim_k as usize;
4049        let eps = cfg.rms_eps;
4050        let scale = geometry.attention_scale();
4051        let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
4052        let bucket_max = scratch.plane(scratch_index).1;
4053
4054        let (qf, mut k, v) =
4055            if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
4056                let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
4057                (
4058                    e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
4059                    e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
4060                    e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
4061                )
4062            } else {
4063                (
4064                    e.matmul(&fa.wq, h, 1)?,
4065                    e.matmul(&fa.wk, h, 1)?,
4066                    e.matmul(&fa.wv, h, 1)?,
4067                )
4068            };
4069        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
4070        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
4071        let (mut q, gate) = if gated {
4072            let mut q = e.zeros(n_head * head_dim)?;
4073            let mut gate = e.zeros(n_head * head_dim)?;
4074            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
4075            (q, Some(gate))
4076        } else {
4077            (qf, None)
4078        };
4079
4080        let mut qn = e.zeros(n_head * head_dim)?;
4081        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
4082        q = qn;
4083        let mut kn = e.zeros(n_head_kv * head_dim)?;
4084        e.rms_norm(
4085            &k,
4086            fa.k_norm.float_data(),
4087            &mut kn,
4088            head_dim,
4089            n_head_kv,
4090            eps,
4091        )?;
4092        k = kn;
4093        let rope_dims = geometry.n_rot as usize;
4094        e.rope_neox(
4095            &mut q,
4096            pos_d,
4097            head_dim,
4098            rope_dims,
4099            n_head,
4100            1,
4101            geometry.rope_base,
4102            1.0,
4103        )?;
4104        e.rope_neox(
4105            &mut k,
4106            pos_d,
4107            head_dim,
4108            rope_dims,
4109            n_head_kv,
4110            1,
4111            geometry.rope_base,
4112            1.0,
4113        )?;
4114
4115        let kv = scratch.plane_mut(scratch_index).0;
4116        // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
4117        e.append_kv_quantized_dc(
4118            &k,
4119            &v,
4120            &mut kv.k,
4121            &mut kv.v,
4122            &kv.len_d,
4123            kv.kv_dim_k,
4124            kv.kv_dim_v,
4125            kv.k_tok_bytes,
4126            kv.v_tok_bytes,
4127            false,
4128        )?;
4129        e.inc_seqlen(&mut kv.len_d)?;
4130        // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
4131        // key range from the device counter.
4132        let k_view = e.view_u8(&kv.k, kv.k.len());
4133        let v_view = e.view_u8(&kv.v, kv.v.len());
4134        let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
4135        let mut attn = e.zeros(n_head * head_dim)?;
4136        e.fa_decode_dc(
4137            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
4138            scale, ktb, vtb, false,
4139        )?;
4140
4141        let attn_g = match &gate {
4142            Some(gate) => {
4143                let mut gsig = e.zeros(n_head * head_dim)?;
4144                e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
4145                let mut ag = e.zeros(n_head * head_dim)?;
4146                e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
4147                ag
4148            }
4149            None => attn,
4150        };
4151        Ok(e.matmul(&fa.wo, &attn_g, 1)?)
4152    }
4153
4154    /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
4155    /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
4156    /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
4157    /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
4158    /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
4159    /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
4160    /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
4161    /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
4162    #[allow(clippy::too_many_arguments)]
4163    fn mtp_kv_fill_at(
4164        &self,
4165        e: &Engine,
4166        mtp: &MtpHead,
4167        tokens: &[u32],
4168        h: &CudaSlice<f32>,
4169        pos0: usize,
4170        scratch: &mut MtpScratch,
4171        scratch_index: usize,
4172        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4173    ) -> Result<(), Box<dyn std::error::Error>> {
4174        let cfg = &self.cfg;
4175        let n_embd = cfg.n_embd as usize;
4176        let eps = cfg.rms_eps;
4177        let t = tokens.len();
4178        let (scratch_kv, scratch_cap) = scratch.plane(scratch_index);
4179        assert_eq!(scratch_kv.len, pos0, "mtp_kv_fill: append slot mismatch");
4180        assert!(pos0 + t <= scratch_cap, "mtp_kv_fill: scratch overflow");
4181        let Mixer::Full(fa) = &mtp.mixer else {
4182            panic!("MTP block is full-attn in qwen35; linear MTP not supported")
4183        };
4184        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
4185        let pos_d = e.htod_i32(&pos_vec)?;
4186
4187        // ops A/1/2: embed + the two input norms, T-wide.
4188        let e_emb = match embd_dev {
4189            Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
4190            None => e.htod(&self.embd.gather(n_embd, tokens))?,
4191        };
4192        let mut e_norm = e.zeros(t * n_embd)?;
4193        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
4194        let mut h_norm = e.zeros(t * n_embd)?;
4195        e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
4196
4197        // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
4198        let mut concat = e.zeros(t * 2 * n_embd)?;
4199        for i in 0..t {
4200            e.copy_view_into(
4201                &mut concat,
4202                i * 2 * n_embd,
4203                &e_norm.slice(i * n_embd..(i + 1) * n_embd),
4204                n_embd,
4205            )?;
4206            e.copy_view_into(
4207                &mut concat,
4208                i * 2 * n_embd + n_embd,
4209                &h_norm.slice(i * n_embd..(i + 1) * n_embd),
4210                n_embd,
4211            )?;
4212        }
4213
4214        // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
4215        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
4216        let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
4217        let mut a_norm = e.zeros(t * di)?;
4218        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
4219
4220        // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
4221        // the fill only has to leave correct K/V rows behind for later chains to attend over.
4222        let n_head_kv = mtp
4223            .geom
4224            .as_ref()
4225            .map(|g| g.n_head_kv)
4226            .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
4227            .unwrap_or_else(|| {
4228                let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
4229                cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
4230            });
4231        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
4232        let geometry = cfg.full_attention_geometry_at(mtp_il);
4233        let head_dim = geometry.head_dim_k as usize;
4234        let mut k = e.matmul(&fa.wk, &a_norm, t)?;
4235        let v = e.matmul(&fa.wv, &a_norm, t)?;
4236        let mut kn = e.zeros(t * n_head_kv * head_dim)?;
4237        e.rms_norm(
4238            &k,
4239            fa.k_norm.float_data(),
4240            &mut kn,
4241            head_dim,
4242            n_head_kv * t,
4243            eps,
4244        )?;
4245        k = kn;
4246        // step35: rotary width AND base are per-layer, and the MTP block's values come from the
4247        // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
4248        // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
4249        // writes K rows the attention arm then re-derives at a different theta: correct-looking
4250        // output with dead acceptance, invisible to the exactness gates.
4251        let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
4252            Some(s) => (
4253                s.n_rot,
4254                s.rope_base,
4255                if s.swa {
4256                    None
4257                } else {
4258                    self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
4259                },
4260            ),
4261            None => (geometry.n_rot as usize, geometry.rope_base, None),
4262        };
4263        #[cfg(debug_assertions)]
4264        if let Some(ff) = ff {
4265            crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
4266        }
4267        match ff {
4268            Some(f) => e.rope_neox_ff(
4269                &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
4270            )?,
4271            None => e.rope_neox(
4272                &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
4273            )?,
4274        }
4275
4276        let kv = scratch.plane_mut(scratch_index).0;
4277        // Match the trunk prime contract: a chunk may need the aligned window immediately before
4278        // its first row, so preserve that prefix when the physical tail rebases at wrap.
4279        let retain_from = kv
4280            .ring
4281            .as_ref()
4282            .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
4283            .unwrap_or(0);
4284        let write_row = e.prepare_kv_append(kv, retain_from, t)?;
4285        for i in 0..t {
4286            let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
4287            let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
4288            e.append_kv_quantized_view(
4289                &k_row,
4290                &v_row,
4291                &mut kv.k,
4292                &mut kv.v,
4293                write_row + i,
4294                kv.kv_dim_k,
4295                kv.kv_dim_v,
4296                kv.k_tok_bytes,
4297                kv.v_tok_bytes,
4298                false,
4299            )?;
4300        }
4301        kv.len = pos0 + t;
4302        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
4303        Ok(())
4304    }
4305
4306    #[allow(clippy::too_many_arguments)]
4307    fn mtp_kv_fill_all(
4308        &self,
4309        e: &Engine,
4310        tokens: &[u32],
4311        h: &CudaSlice<f32>,
4312        pos0: usize,
4313        scratch: &mut MtpScratch,
4314        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4315    ) -> Result<(), Box<dyn std::error::Error>> {
4316        debug_assert_eq!(self.mtp_head_count(), scratch.plane_count());
4317        for index in 0..self.mtp_head_count() {
4318            self.mtp_kv_fill_at(
4319                e,
4320                self.mtp_head_at(index),
4321                tokens,
4322                h,
4323                pos0,
4324                scratch,
4325                index,
4326                embd_dev,
4327            )?;
4328        }
4329        Ok(())
4330    }
4331
4332    /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
4333    /// every varying input device-resident —
4334    ///   - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
4335    ///     so the chain feeds itself; the host reads the same 4 bytes for the draft list),
4336    ///   - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
4337    ///   - rope pos from the persistent `pos_d` counter (inc'd in-graph),
4338    ///   - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
4339    /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
4340    /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
4341    /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
4342    /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
4343    /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
4344    /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
4345    /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
4346    /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
4347    /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
4348    /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
4349    /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
4350    /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
4351    /// seed/temp are capture-time constants (fixed per generate call, like p_min).
4352    #[allow(clippy::too_many_arguments)]
4353    fn mtp_head_forward_cap(
4354        &self,
4355        e: &Engine,
4356        mtp: &MtpHead,
4357        tok_d: &mut CudaSlice<u32>,
4358        pos_d: &mut CudaSlice<i32>,
4359        h_seed_d: &mut CudaSlice<f32>,
4360        p_d: &mut CudaSlice<f32>,
4361        scratch: &mut MtpScratch,
4362        with_prob: bool,
4363        with_head: bool,
4364        embd_gpu: &CudaSlice<u8>,
4365        embd_qt: i32,
4366        embd_rb: usize,
4367        d_vocab: usize,
4368        sampled_cap: Option<(
4369            &mut CudaSlice<u32>,
4370            &mut CudaSlice<f32>,
4371            &mut CudaSlice<f32>,
4372            u64,
4373            f32,
4374        )>,
4375        stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
4376        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
4377        // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
4378        // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
4379        // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
4380        // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
4381        mask_cap: Option<(&CudaSlice<u32>, usize)>,
4382    ) -> Result<(), Box<dyn std::error::Error>> {
4383        let cfg = &self.cfg;
4384        let n_embd = cfg.n_embd as usize;
4385        // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
4386        // whose device-counter key bound always starts at row 0 — it cannot express this block's
4387        // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
4388        // persistent scratch passes 512 rows. Nothing is lost today: `mtp_head_forward_cap`
4389        // refuses step35 heads explicitly (SWA refusal), so the eager chain
4390        // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
4391        // panic) is what the two capture sites and the round-stream capture already handle by
4392        // degrading to eager / stream-off.
4393        if mtp.step35.is_some() {
4394            return Err(
4395                "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
4396                        block's SWA view offset; same root cause as the dc decode refusal) — the \
4397                        eager draft chain serves this arch"
4398                    .into(),
4399            );
4400        }
4401        // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
4402        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
4403        let eps = cfg.rms_eps;
4404        let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
4405        let mut e_norm = e.zeros(n_embd)?;
4406        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
4407        let mut h_norm = e.zeros(n_embd)?;
4408        e.rms_norm(
4409            &*h_seed_d,
4410            mtp.hnorm.float_data(),
4411            &mut h_norm,
4412            n_embd,
4413            1,
4414            eps,
4415        )?;
4416        let mut concat = e.zeros(2 * n_embd)?;
4417        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
4418        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
4419        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
4420        let mut a_norm = e.zeros(di)?;
4421        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
4422        let attn_out = match &mtp.mixer {
4423            Mixer::Full(fa) => {
4424                self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, 0, mtp.geom.as_ref())?
4425            }
4426            Mixer::Linear(_) => {
4427                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
4428            }
4429            Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4430        };
4431        let mut x1 = e.zeros(di)?;
4432        e.add(&inp_sa, &attn_out, &mut x1, di)?;
4433        let mut z = e.zeros(di)?;
4434        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
4435        let ffn_out = match &mtp.ffn {
4436            crate::hybrid::Ffn::Dense {
4437                ffn_gate,
4438                ffn_up,
4439                ffn_down,
4440            } => {
4441                let n_ff = ffn_gate.out_features();
4442                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
4443                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
4444                    (
4445                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
4446                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
4447                    )
4448                } else {
4449                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
4450                };
4451                let mut act = e.zeros(n_ff)?;
4452                Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
4453                e.matmul(ffn_down, &act, 1)?
4454            }
4455            // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
4456            // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
4457            // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
4458            // error arm degrades the caller to eager/stream-off.
4459            crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
4460                self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
4461            }
4462            crate::hybrid::Ffn::Moe(_) => {
4463                return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into());
4464            }
4465        };
4466        let mut h_inner = e.zeros(di)?;
4467        e.add(&x1, &ffn_out, &mut h_inner, di)?;
4468        // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
4469        let h_nextn = match mtp.geom.as_ref() {
4470            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
4471            None => h_inner,
4472        };
4473        // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
4474        let final_h = if with_head || spec_hpost() {
4475            let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
4476            let mut fh = e.zeros(n_embd)?;
4477            e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
4478            Some(fh)
4479        } else {
4480            None
4481        };
4482        if with_head {
4483            let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
4484            let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
4485            // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
4486            // before the argmax — proposals become legal by construction. Contents-only
4487            // per-replay upload keeps the capture valid.
4488            if let Some((mask_d, mw)) = mask_cap {
4489                e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
4490            }
4491            if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
4492                // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
4493                // own buffer is pool-recycled after the capture body returns, so it can't be the
4494                // retention target), bump the device event counter, gumbel-perturb reading it,
4495                // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
4496                e.copy_into(q_out_d, 0, &logits, d_vocab)?;
4497                e.sctr_inc(ctr_d)?;
4498                e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
4499                e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
4500                // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
4501                // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
4502                if with_prob {
4503                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
4504                }
4505            } else {
4506                // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
4507                e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
4508                // p-min under a draft mask reads the MASKED row: confidence relative to the
4509                // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
4510                // is the right semantics for "does the drafter know what comes next here" and
4511                // the same row the pick came from. Draft-quality only — verify arbitrates.
4512                if with_prob {
4513                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
4514                }
4515            }
4516        }
4517        // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
4518        // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
4519        if let Some((out, slot, d2t)) = stream_pack {
4520            e.pack_tok_p(tok_d, p_d, out, slot)?;
4521            if let Some(map) = d2t {
4522                e.tok_map_u32(tok_d, map)?;
4523            }
4524        }
4525        // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
4526        if spec_hpost() {
4527            e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
4528        } else {
4529            e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
4530        }
4531        // advance the draft rope position in-graph.
4532        e.inc_seqlen(pos_d)?;
4533        Ok(())
4534    }
4535
4536    /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
4537    /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
4538    /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
4539    /// Advances `cache.pos` by T.
4540    pub fn decode_step_t(
4541        &self,
4542        e: &Engine,
4543        tokens: &[u32],
4544        pos0: usize,
4545        cache: &mut Cache,
4546    ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
4547        if self.is_gemma4_e4b() {
4548            return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
4549        }
4550        if self.gemma_batch_program() {
4551            return self.gemma4_decode_step_t(e, tokens, pos0, cache);
4552        }
4553        Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
4554    }
4555
4556    /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
4557    /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
4558    /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
4559    /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
4560    pub fn decode_step_t_h(
4561        &self,
4562        e: &Engine,
4563        tokens: &[u32],
4564        pos0: usize,
4565        cache: &mut Cache,
4566    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4567        self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
4568    }
4569
4570    /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
4571    /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
4572    pub fn decode_step_t_h_emb(
4573        &self,
4574        e: &Engine,
4575        tokens: &[u32],
4576        pos0: usize,
4577        cache: &mut Cache,
4578        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4579    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4580        let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
4581        Ok((e.dtoh(&logits_d)?, h_seed))
4582    }
4583
4584    /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
4585    /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
4586    /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
4587    /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
4588    /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
4589    pub fn decode_step_t_h_emb_dev(
4590        &self,
4591        e: &Engine,
4592        tokens: &[u32],
4593        pos0: usize,
4594        cache: &mut Cache,
4595        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4596    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4597        let n_embd = self.cfg.n_embd as usize;
4598        let t = tokens.len();
4599        let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
4600        // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
4601        let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
4602        e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
4603        Ok((logits, hs))
4604    }
4605
4606    /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
4607    /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
4608    /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
4609    /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
4610    /// retains/copies — they never change what any kernel computes).
4611    fn decode_step_t_core(
4612        &self,
4613        e: &Engine,
4614        tokens: &[u32],
4615        pos0: usize,
4616        cache: &mut Cache,
4617        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4618        mut ckpt: Option<&mut VerifyCkpt>,
4619    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4620        self.decode_step_t_core_stream(
4621            e,
4622            tokens,
4623            pos0,
4624            cache,
4625            embd_dev,
4626            ckpt.take(),
4627            None,
4628            None,
4629            None,
4630            None,
4631        )
4632    }
4633
4634    /// [`Self::decode_step_t_core`] with the MTP route's verify-graph pool armed
4635    /// (`MEMRA_SPEC_VERIFY_GRAPH`). `graphs: None` reproduces `decode_step_t_core`
4636    /// argument-for-argument, so the eager walk stays the byte-identical fallback.
4637    fn decode_step_t_core_vg(
4638        &self,
4639        e: &Engine,
4640        tokens: &[u32],
4641        pos0: usize,
4642        cache: &mut Cache,
4643        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4644        mut ckpt: Option<&mut VerifyCkpt>,
4645        graphs: Option<&mut DsparkVerifyGraphs>,
4646    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4647        self.decode_step_t_core_stream(
4648            e,
4649            tokens,
4650            pos0,
4651            cache,
4652            embd_dev,
4653            ckpt.take(),
4654            None,
4655            None,
4656            None,
4657            graphs,
4658        )
4659    }
4660
4661    /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
4662    /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
4663    fn decode_step_t_core_pipelined(
4664        &self,
4665        e: &Engine,
4666        tokens: &[u32],
4667        pos0: usize,
4668        cache: &mut Cache,
4669        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4670        mut ckpt: Option<&mut VerifyCkpt>,
4671        pipe: &SpecPipeLane,
4672        round: usize,
4673    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4674        let fence = crate::pp::pp_cuts(self.layers.len())
4675            .ok_or("two-session speculative pipeline requires a PP stage cut")?;
4676        if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
4677            return Err("two-session speculative pipeline requires the PP verify split".into());
4678        }
4679        let interval_fence = pipe.stage0_begin(round)?;
4680        let ticket = self.verify_stage0_issue(
4681            e,
4682            tokens,
4683            pos0,
4684            cache,
4685            embd_dev,
4686            ckpt.as_deref_mut(),
4687            None,
4688            &fence,
4689            Some(interval_fence),
4690            pipe.trace(round),
4691        )?;
4692        pipe.stage0_end(round);
4693        pipe.stage1_begin(round)?;
4694        let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
4695        pipe.verify_end(round);
4696        Ok(result)
4697    }
4698
4699    /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
4700    /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
4701    /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
4702    /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
4703    /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
4704    /// `vtok_dev` (engine-bundle slice 2): device verify tokens for the EMBED only —
4705    /// unlike `stream` mode it changes nothing else (host pos iota, host-len KV appends).
4706    /// `tokens` then only sizes buffers (the dummy-slice pattern the round-stream arm uses).
4707    #[allow(clippy::too_many_arguments)]
4708    fn decode_step_t_core_stream(
4709        &self,
4710        e: &Engine,
4711        tokens: &[u32],
4712        pos0: usize,
4713        cache: &mut Cache,
4714        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4715        mut ckpt: Option<&mut VerifyCkpt>,
4716        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4717        pp_pipe: Option<bool>,
4718        vtok_dev: Option<&CudaSlice<u32>>,
4719        graphs: Option<&mut DsparkVerifyGraphs>,
4720    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4721        // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
4722        // exactly as the eager and batched steps do. This is the single funnel every verify
4723        // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
4724        // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
4725        // is untouched.
4726        //
4727        // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
4728        // walk was unsplit on one stream and a sharded cross-device placement peer-read every
4729        // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
4730        // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
4731        // or a placement whose PpNRt fails to build — so a config that would still walk the
4732        // whole trunk on one stream refuses instead of regressing 28x.
4733        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
4734            if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
4735                if vtok_dev.is_some() {
4736                    return Err(
4737                        "device-token dspark verify (slice-2 deferred readback) has no PP \
4738                         stage-split arm; set MEMRA_DSPARK_DEFER_READBACK=0 or run the dspark \
4739                         route on one device"
4740                            .into(),
4741                    );
4742                }
4743                return self.decode_step_t_core_ppn(
4744                    e,
4745                    tokens,
4746                    pos0,
4747                    cache,
4748                    embd_dev,
4749                    ckpt.take(),
4750                    stream,
4751                    &fence,
4752                    pp_pipe,
4753                );
4754            }
4755        }
4756        crate::pp::refuse_unsplit_if_remote(
4757            "decode_step_t (spec verify)",
4758            "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
4759             split (decode_step_t_core_ppn); or run spec on one device",
4760        )?;
4761        let cfg = &self.cfg;
4762        let n_embd = cfg.n_embd as usize;
4763        let eps = cfg.rms_eps;
4764        let t = tokens.len();
4765        let pos_d = match stream {
4766            Some((_, ctr)) => {
4767                let mut p = e.alloc_uninit::<i32>(t)?;
4768                e.pos_iota(ctr, &mut p, t)?;
4769                p
4770            }
4771            None => {
4772                let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4773                e.htod_i32(&pos_vec)?
4774            }
4775        };
4776
4777        // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
4778        let x = match (stream, embd_dev) {
4779            (Some((vtok, _)), Some((g, qt, rb))) => {
4780                e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
4781            }
4782            (None, Some((g, qt, rb))) => match vtok_dev {
4783                // slice 2: device verify tokens, same embed_gather_u32_t kernel —
4784                // bit-identical rows to the host-token arm (same per-dtype deq).
4785                Some(vt_d) => e.embed_gather_device_td(g, vt_d, t, n_embd, qt, rb)?,
4786                None => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
4787            },
4788            _ => {
4789                assert!(
4790                    vtok_dev.is_none(),
4791                    "device-token verify requires the resident embed table (embd_dev)"
4792                );
4793                e.htod(&self.embd.gather(n_embd, tokens))?
4794            }
4795        };
4796
4797        // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
4798        // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
4799        // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
4800        let x = self.verify_layers(
4801            e,
4802            x,
4803            0,
4804            self.layers.len(),
4805            &pos_d,
4806            pos0,
4807            t,
4808            cache,
4809            ckpt.take(),
4810            stream,
4811            graphs,
4812        )?;
4813
4814        let mut hn = vbuf(e, t * n_embd)?;
4815        // Stage-A door: with the serving-class row-outer verify walk, the TAIL must be the
4816        // t=1 decode program per row too (rms_norm t=1 + the single-row bf16 head — the
4817        // split head's concat is receipted bit-identical to it). The batched cuBLASLt head
4818        // is a different ULP class and flips near-tie argmaxes off the greedy tape.
4819        let eager_tail = self.sliding_gated_moe_batch_program()
4820            && std::env::var("MEMRA_SPEC_VERIFY_EAGER").as_deref() == Ok("1");
4821        if eager_tail {
4822            let n_vocab = self.cfg.n_vocab as usize;
4823            let mut logits = vbuf(e, t * n_vocab)?;
4824            for r in 0..t {
4825                let mut row = e.uninit(n_embd)?;
4826                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
4827                let mut hr = e.uninit(n_embd)?;
4828                e.rms_norm(&row, self.output_norm.float_data(), &mut hr, n_embd, 1, eps)?;
4829                let lr = e.matmul(&self.output, &hr, 1)?;
4830                e.dtod_copy_into(&lr, &mut logits, r * n_vocab)?;
4831                e.dtod_copy_into(&hr, &mut hn, r * n_embd)?;
4832            }
4833            if stream.is_none() {
4834                cache.pos += t;
4835            }
4836            return Ok((logits, if spec_hpost() { hn } else { x }));
4837        }
4838        let serving_head =
4839            self.sliding_gated_moe_batch_program() || self.batched_serving_numeric_class();
4840        let logits = if serving_head {
4841            // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
4842            // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
4843            // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
4844            // serve one batched numeric class at every live width, including B=1. Keep the
4845            // verify head in that same class; other generic families retain the decode-exact
4846            // head that their run-spec contract pins.
4847            e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4848            e.matmul(&self.output, &hn, t)?
4849        } else {
4850            e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4851            e.matmul_decode_exact(&self.output, &hn, t)?
4852        };
4853        // stream: the device pos counter owns position; host mirror reconciles at drain.
4854        if stream.is_none() {
4855            cache.pos += t;
4856        }
4857        // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
4858        Ok((logits, if spec_hpost() { hn } else { x }))
4859    }
4860
4861    /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
4862    /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
4863    /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
4864    /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
4865    /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
4866    /// the payload).
4867    ///
4868    /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
4869    /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
4870    /// receipts):
4871    ///
4872    /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
4873    ///    (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
4874    ///    DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
4875    ///    (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
4876    ///    s>0 its own Engine even on the primary device; honouring it here is what scopes the
4877    ///    pools. The verify path allocates MORE of that scratch than eager decode does (FA at
4878    ///    m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
4879    ///
4880    /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
4881    ///    buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
4882    ///    stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
4883    ///    read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
4884    ///    stage derives the identical iota, and each stage's own output buffer is stream-local.
4885    ///
4886    /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
4887    ///    sharded loader leaves the table with stage 0 by construction).
4888    ///
4889    /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
4890    ///    both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
4891    ///    n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
4892    ///    model, every round.
4893    ///
4894    /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
4895    /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
4896    /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
4897    /// through the primary context by UVA — the same read the batched serving epilogue's
4898    /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
4899    /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
4900    ///
4901    /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
4902    /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
4903    /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
4904    ///
4905    /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
4906    /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
4907    /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
4908    /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
4909    /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
4910    /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
4911    /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
4912    /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
4913    #[allow(clippy::too_many_arguments)]
4914    fn decode_step_t_core_ppn(
4915        &self,
4916        e: &Engine,
4917        tokens: &[u32],
4918        pos0: usize,
4919        cache: &mut Cache,
4920        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4921        mut ckpt: Option<&mut VerifyCkpt>,
4922        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4923        fence: &[usize],
4924        pp_pipe: Option<bool>,
4925    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4926        let ticket = self.verify_stage0_issue(
4927            e,
4928            tokens,
4929            pos0,
4930            cache,
4931            embd_dev,
4932            ckpt.as_deref_mut(),
4933            stream,
4934            fence,
4935            pp_pipe,
4936            None,
4937        )?;
4938        self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
4939    }
4940
4941    /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
4942    /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
4943    #[allow(clippy::too_many_arguments)]
4944    fn verify_stage0_issue(
4945        &self,
4946        e: &Engine,
4947        tokens: &[u32],
4948        pos0: usize,
4949        cache: &mut Cache,
4950        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4951        mut ckpt: Option<&mut VerifyCkpt>,
4952        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4953        fence: &[usize],
4954        pp_pipe: Option<bool>,
4955        trace: Option<SpecPipeTraceCtx>,
4956    ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
4957        assert!(
4958            !self.is_gemma4_e4b() && !self.gemma_batch_program(),
4959            "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
4960             (the gemma4 arms have their own decode_step_t twins)"
4961        );
4962        if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
4963            return Err(
4964                "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
4965                 boundary itself is host-staged, but device-resident verify still peer-reads \
4966                 primary-device token/position/embedding buffers from stage 0. Run plain PP \
4967                 serving on this host class; spec requires local per-stage inputs first."
4968                    .into(),
4969            );
4970        }
4971        let rt = crate::pp::PpNRt::get(e)?;
4972        let n_st = fence.len() - 1;
4973        assert_eq!(
4974            rt.n_stages(),
4975            n_st,
4976            "PpNRt stage count {} != fence stages {n_st}",
4977            rt.n_stages()
4978        );
4979        let n_embd = self.cfg.n_embd as usize;
4980        let t = tokens.len();
4981        let payload = t * n_embd;
4982        if pp_pipe.is_some() {
4983            assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
4984        }
4985        // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
4986        // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
4987        // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
4988        // the report below names exactly two stages and must never imply it measured middle ones.
4989        let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
4990        let pp_started = std::time::Instant::now();
4991        let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
4992        // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
4993        // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
4994        // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
4995        // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
4996        // stage stream and the wait would self-order into a no-op.
4997        let caller_stream = e.stream();
4998        // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
4999        // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
5000        // the primary stream still holds queued reads of them — with event tracking elided,
5001        // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
5002        // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
5003        // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
5004        // stage stream behind the caller before enqueueing new stage work.
5005        let reverse_started = std::time::Instant::now();
5006        if pp_pipe != Some(false) {
5007            rt.fence_stages_behind(&caller_stream)?;
5008        }
5009        if pp_pipe == Some(true) {
5010            // Both session verifies must alternate boundary slots even when the ordinary
5011            // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
5012            // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
5013            rt.prepare_overlap_slots(0, payload)?;
5014        }
5015        if pp_anatomy {
5016            // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
5017            // prices any primary-stream rollback/refresh tail inherited from the prior round.
5018            for s in 0..n_st {
5019                let _st = rt.enter(s);
5020                rt.engine(s, e).stream().synchronize()?;
5021            }
5022            reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
5023        }
5024
5025        // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
5026        // stream mode each stage's own `pos_iota` over the shared read-only device counter.
5027        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
5028            match stream {
5029                Some((_, ctr)) => {
5030                    let mut p = es.alloc_uninit::<i32>(t)?;
5031                    es.pos_iota(ctr, &mut p, t)?;
5032                    Ok(p)
5033                }
5034                None => {
5035                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
5036                    es.htod_i32(&pos_vec)
5037                }
5038            }
5039        };
5040
5041        // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
5042        let slot = {
5043            let _st0 = rt.enter(0);
5044            let e0 = rt.engine(0, e);
5045            enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
5046            let stage0_started = std::time::Instant::now();
5047            let pos_d = stage_pos(e0)?;
5048            let x = match (stream, embd_dev) {
5049                (Some((vtok, _)), Some((g, qt, rb))) => {
5050                    e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
5051                }
5052                (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
5053                _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
5054            };
5055            let x = self.verify_layers(
5056                e0,
5057                x,
5058                fence[0],
5059                fence[1],
5060                &pos_d,
5061                pos0,
5062                t,
5063                cache,
5064                ckpt.as_deref_mut(),
5065                stream,
5066                None,
5067            )?;
5068            if pp_anatomy {
5069                e0.stream().synchronize()?;
5070                stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
5071            }
5072            let tx_started = std::time::Instant::now();
5073            let slot = if pp_pipe.is_some() {
5074                rt.tx_pipelined(0, &x, payload)?
5075            } else {
5076                rt.tx(0, &x, payload)?
5077            };
5078            enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
5079            if pp_anatomy {
5080                e0.stream().synchronize()?;
5081                tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
5082            }
5083            slot
5084            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
5085        };
5086
5087        Ok(VerifyBoundaryTicket {
5088            rt,
5089            caller_stream,
5090            slot,
5091            pos0,
5092            t,
5093            payload,
5094            n_st,
5095            pipelined: pp_pipe.is_some(),
5096            pp_anatomy,
5097            pp_started,
5098            reverse_ms,
5099            stage0_ms,
5100            tx_ms,
5101            trace,
5102        })
5103    }
5104
5105    /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
5106    /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
5107    #[allow(clippy::too_many_arguments)]
5108    fn verify_stage1_finish(
5109        &self,
5110        e: &Engine,
5111        ticket: VerifyBoundaryTicket,
5112        cache: &mut Cache,
5113        mut ckpt: Option<&mut VerifyCkpt>,
5114        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5115        fence: &[usize],
5116        publish_to_caller: bool,
5117    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5118        let VerifyBoundaryTicket {
5119            rt,
5120            caller_stream,
5121            slot,
5122            pos0,
5123            t,
5124            payload,
5125            n_st,
5126            pipelined,
5127            pp_anatomy,
5128            pp_started,
5129            reverse_ms,
5130            stage0_ms,
5131            tx_ms,
5132            trace,
5133        } = ticket;
5134        let n_embd = self.cfg.n_embd as usize;
5135        let eps = self.cfg.rms_eps;
5136        let mut slot = slot;
5137        let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
5138        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
5139            match stream {
5140                Some((_, ctr)) => {
5141                    let mut p = es.alloc_uninit::<i32>(t)?;
5142                    es.pos_iota(ctr, &mut p, t)?;
5143                    Ok(p)
5144                }
5145                None => {
5146                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
5147                    es.htod_i32(&pos_vec)
5148                }
5149            }
5150        };
5151
5152        // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
5153        for s in 1..n_st - 1 {
5154            let _st = rt.enter(s);
5155            let es = rt.engine(s, e);
5156            let pos_d = stage_pos(es)?;
5157            let x = rt.rx(s - 1, slot, payload)?;
5158            let x = self.verify_layers(
5159                es,
5160                x,
5161                fence[s],
5162                fence[s + 1],
5163                &pos_d,
5164                pos0,
5165                t,
5166                cache,
5167                ckpt.as_deref_mut(),
5168                stream,
5169                None,
5170            )?;
5171            slot = if pipelined {
5172                rt.tx_pipelined(s, &x, payload)?
5173            } else {
5174                rt.tx(s, &x, payload)?
5175            };
5176        }
5177
5178        // ---- LAST STAGE: RX + final range + output_norm + lm head ----
5179        let _stl = rt.enter(n_st - 1);
5180        let el = rt.engine(n_st - 1, e);
5181        let pos_d = stage_pos(el)?;
5182        let rx_started = std::time::Instant::now();
5183        let x = rt.rx(n_st - 2, slot, payload)?;
5184        if pp_anatomy {
5185            el.stream().synchronize()?;
5186            rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
5187        }
5188        enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
5189        let stage1_started = std::time::Instant::now();
5190        let x = self.verify_layers(
5191            el,
5192            x,
5193            fence[n_st - 1],
5194            fence[n_st],
5195            &pos_d,
5196            pos0,
5197            t,
5198            cache,
5199            ckpt.as_deref_mut(),
5200            stream,
5201            None,
5202        )?;
5203
5204        let mut hn = vbuf(el, payload)?;
5205        let logits = if self.sliding_gated_moe_batch_program() {
5206            // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
5207            // Verify must not switch numeric class merely because the same session speculates.
5208            el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
5209            el.matmul(&self.output, &hn, t)?
5210        } else {
5211            el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
5212            el.matmul_decode_exact(&self.output, &hn, t)?
5213        };
5214        enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
5215        if pp_anatomy {
5216            el.stream().synchronize()?;
5217            stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
5218        }
5219        // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
5220        // stream. Order the caller's stream behind that work before the buffers escape this
5221        // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
5222        // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
5223        // the following arm's KV in the same process).
5224        if publish_to_caller {
5225            rt.publish_to(n_st - 1, &caller_stream)?;
5226        }
5227        if pp_anatomy {
5228            if publish_to_caller {
5229                caller_stream.synchronize()?;
5230            }
5231            eprintln!(
5232                "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
5233                 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
5234                pp_started.elapsed().as_secs_f64() * 1e3,
5235            );
5236        }
5237        // stream: the device pos counter owns position; host mirror reconciles at drain.
5238        if stream.is_none() {
5239            cache.pos += t;
5240        }
5241        Ok((logits, if spec_hpost() { hn } else { x }))
5242    }
5243
5244    /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
5245    ///
5246    /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
5247    /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
5248    /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
5249    /// Those classes are individually stable, but a near-tie prompt can choose different greedy
5250    /// bytes when a request moves from batched plain serving into speculative verify. Run the
5251    /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
5252    /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
5253    /// every norm/projection/FFN uses exactly the live serving dispatch.
5254    #[allow(clippy::too_many_arguments)]
5255    fn step35_verify_batch_layers(
5256        &self,
5257        e: &Engine,
5258        mut x: CudaSlice<f32>,
5259        lo: usize,
5260        hi: usize,
5261        pos0: usize,
5262        t: usize,
5263        cache: &mut Cache,
5264    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5265        let n_embd = self.cfg.n_embd as usize;
5266        if !self.uses_sliding_gated_moe_program() {
5267            return Err(
5268                "serving-class verify requires sliding-gated-MoE canonical operations".into(),
5269            );
5270        }
5271        // SERVING-CLASS VERIFY (MEMRA_SPEC_VERIFY_EAGER=1, step37 MTP bring-up): each verify
5272        // column rides decode_layers_eager — the EXACT t=1 program live serving runs (all TP2
5273        // doors) — row-outer, so row r's appends land before row r+1 attends: bit-equal to
5274        // plain greedy by construction. Only the unsplit full-range walk qualifies; PP splits
5275        // and the tap path keep the batch-layer class.
5276        static VE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5277        let eager_verify = *VE
5278            .get_or_init(|| std::env::var("MEMRA_SPEC_VERIFY_EAGER").as_deref() == Ok("1"))
5279            && lo == 0
5280            && hi == self.layers.len();
5281        if eager_verify {
5282            // T-COLUMN LAYER-OUTER WALK (MEMRA_SPEC_VERIFY_TCOL=1): per layer, one t-grid
5283            // attn norm + ONE weight-amortized QKV(+gate) over all T columns, then each
5284            // column runs the UNMODIFIED t=1 attention program via the col-select door and
5285            // the ordinary residual/FFN body. Values per column are bit-equal to the
5286            // row-outer walk: rms over the materialized residual == the fused add+norm
5287            // (kernel_check identity), the tcol kernel's per-column FP order == the t=1
5288            // kernel, and every downstream op IS the t=1 program.
5289            static TCOL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5290            let tcol =
5291                *TCOL.get_or_init(|| std::env::var("MEMRA_SPEC_VERIFY_TCOL").as_deref() == Ok("1"));
5292            if tcol && t >= 2 && t <= 8 {
5293                // MEMRA_TCOL_PROF=1: synchronized per-segment wall profile of the walk
5294                // (norm+QKV precompute / per-col attention / per-col residual+FFN). The
5295                // syncs serialize the stream, so the split is for TARGETING amortization
5296                // work only — never a perf claim.
5297                static PROF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5298                let prof =
5299                    *PROF.get_or_init(|| std::env::var("MEMRA_TCOL_PROF").as_deref() == Ok("1"));
5300                let mut prof_ms = [0f64; 3];
5301                let eps = self.cfg.rms_eps;
5302                let mut x_t = x;
5303                let mut h_t = e.uninit(t * n_embd)?;
5304                let mut h_row = e.uninit(n_embd)?; // real row: the non-dcw fallback reads it
5305                // Per-column pos buffers hoisted out of the layer loop (a per-col-per-layer
5306                // pageable htod was an in-stream engine turnaround x t x 45).
5307                let mut pos_rows = Vec::with_capacity(t);
5308                for r in 0..t {
5309                    pos_rows.push(e.htod_i32(&[(pos0 + r) as i32])?);
5310                }
5311                let mut ok = true;
5312                // MEMRA_TCOL_OPROJ=1: defer each column's o_proj — the finish seam
5313                // stashes `gated` instead of joining per column; one b4_tcol per rank +
5314                // one slab join produce every column's `mixed` after the attention pass.
5315                // Bit-exact per column (t=1 b4 program per column; elementwise join).
5316                // MEMRA_TCOL_FFN=1 (implies the o_proj defer): when every column of a
5317                // MoE layer deferred, the residual norm runs as one t-grid launch
5318                // (per-row program == t=1) and the FFN as ONE two-column device-routed
5319                // sweep + per-column shexp — the two columns' expert weights dedup
5320                // through L2 instead of reading HBM twice.
5321                static FFN2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5322                let ffn_batch =
5323                    *FFN2.get_or_init(|| std::env::var("MEMRA_TCOL_FFN").as_deref() == Ok("1"));
5324                let oproj_batch = crate::tp::tcol_oproj_on() || ffn_batch;
5325                // MEMRA_SPEC_FA2=1 (T=2 only): eligible layers defer BOTH columns' fa —
5326                // the per-column pass norms/ropes/appends and stashes q+gate, then one
5327                // shared-KV fa_decode_dcw2 per rank + the o_proj join produce the
5328                // [2, o_out] mixed slab. The precheck runs before arming (stashing is
5329                // unrecoverable); ineligible/boundary layers run the ordinary program.
5330                let fa2 = crate::tp::spec_fa2_on() && t == 2;
5331                let mut mixed_row = e.uninit(n_embd)?;
5332                for il in lo..hi {
5333                    let layer = &self.layers[il];
5334                    let fa2_layer = fa2 && self.step35_spec_fa2_precheck(cache, il, pos0)?;
5335                    let mut seg = std::time::Instant::now();
5336                    e.rms_norm(&x_t, layer.attn_norm.float_data(), &mut h_t, n_embd, t, eps)?;
5337                    if !self.step35_verify_qkv_precompute(e, il, &h_t, t)? {
5338                        ok = false;
5339                        break;
5340                    }
5341                    if prof {
5342                        e.stream().synchronize()?;
5343                        prof_ms[0] += seg.elapsed().as_secs_f64() * 1e3;
5344                        seg = std::time::Instant::now();
5345                    }
5346                    let mut next = e.uninit(t * n_embd)?;
5347                    // Columns whose o_proj was deferred (their FFN runs after the join).
5348                    // A NON-deferred column's FFN must run INSIDE the column loop: the
5349                    // oproj-tail handoff is a single cell that the same column's
5350                    // residual_norm_ffn consumes before the next column's finish.
5351                    let mut deferred: Vec<usize> = Vec::new();
5352                    let mut fa2_deferred: Vec<usize> = Vec::new();
5353                    let mut ffn_col =
5354                        |r: usize,
5355                         mixed: &CudaSlice<f32>,
5356                         next: &mut CudaSlice<f32>|
5357                         -> Result<(), Box<dyn std::error::Error>> {
5358                            let mut x_row = e.uninit(n_embd)?;
5359                            e.dtod_copy_view(&x_t.slice(r * n_embd..(r + 1) * n_embd), &mut x_row)?;
5360                            let (x1, ffn_out) =
5361                                self.residual_norm_ffn(e, layer, &x_row, mixed, n_embd, il, eps)?;
5362                            let mut x2 = e.uninit(n_embd)?;
5363                            e.add(&x1, &ffn_out, &mut x2, n_embd)?;
5364                            e.dtod_copy_into(&x2, next, r * n_embd)?;
5365                            Ok(())
5366                        };
5367                    for r in 0..t {
5368                        e.dtod_copy_view(&h_t.slice(r * n_embd..(r + 1) * n_embd), &mut h_row)?;
5369                        let row_pos = &pos_rows[r];
5370                        crate::tp::set_verify_tcol(Some(r));
5371                        if fa2_layer {
5372                            crate::tp::set_spec_fa2_defer(Some(r));
5373                        } else if oproj_batch {
5374                            crate::tp::set_tcol_oproj_defer(Some(r));
5375                        }
5376                        let mixed = match &layer.mixer {
5377                            crate::hybrid::Mixer::Full(fa) => {
5378                                self.full_attn_decode(e, fa, &h_row, row_pos, pos0 + r, cache, il)
5379                            }
5380                            _ => Err("step35 verify expects full attention".into()),
5381                        };
5382                        crate::tp::set_verify_tcol(None);
5383                        crate::tp::set_spec_fa2_defer(None);
5384                        crate::tp::set_tcol_oproj_defer(None);
5385                        let mixed = mixed?;
5386                        if fa2_layer && crate::tp::take_spec_fa2_stashed() {
5387                            fa2_deferred.push(r);
5388                        } else if oproj_batch && crate::tp::take_tcol_oproj_stashed() {
5389                            deferred.push(r);
5390                        } else {
5391                            ffn_col(r, &mixed, &mut next)?;
5392                        }
5393                    }
5394                    if !fa2_deferred.is_empty() && fa2_deferred.len() != t {
5395                        // The precheck guarantees both columns stash or neither; a strict
5396                        // subset means a column's output was never produced anywhere.
5397                        return Err("spec fa2 stash engaged for a subset of columns".into());
5398                    }
5399                    if prof {
5400                        e.stream().synchronize()?;
5401                        prof_ms[1] += seg.elapsed().as_secs_f64() * 1e3;
5402                        seg = std::time::Instant::now();
5403                    }
5404                    if !fa2_deferred.is_empty() {
5405                        deferred = fa2_deferred;
5406                    }
5407                    if !deferred.is_empty() {
5408                        let mixed_t = if fa2_layer {
5409                            self.step35_verify_spec_fa2_join(e, il, cache, pos0)?
5410                        } else {
5411                            self.step35_verify_oproj_tcol(e, il, t)?
5412                        };
5413                        let o_out = mixed_t.len() / t;
5414                        // Batched t=2 residual+MoE: one t-grid add_rms_norm (per-row
5415                        // program == t=1; bit-identical to the oproj-tail join per the
5416                        // M2 verbatim-program contract) feeding the two-column routed
5417                        // sweep. Ineligible layers (dense FFN, non-nvfp4) fall through
5418                        // to the per-column body.
5419                        let mut batched = false;
5420                        if ffn_batch && t == 2 && deferred.len() == t && o_out == n_embd {
5421                            let mut x1_t = e.uninit(t * n_embd)?;
5422                            let mut z_t = e.uninit(t * n_embd)?;
5423                            e.add_rms_norm(
5424                                &x_t,
5425                                &mixed_t,
5426                                layer.post_attn_norm.float_data(),
5427                                &mut x1_t,
5428                                &mut z_t,
5429                                n_embd,
5430                                t,
5431                                eps,
5432                            )?;
5433                            if let Some(ffn_t) = self.step35_verify_moe_t2(e, il, &z_t)? {
5434                                let mut x2_t = e.uninit(t * n_embd)?;
5435                                e.add(&x1_t, &ffn_t, &mut x2_t, t * n_embd)?;
5436                                next = x2_t;
5437                                batched = true;
5438                            }
5439                        }
5440                        if !batched {
5441                            for &r in &deferred {
5442                                e.dtod_copy_view(
5443                                    &mixed_t.slice(r * o_out..(r + 1) * o_out),
5444                                    &mut mixed_row,
5445                                )?;
5446                                ffn_col(r, &mixed_row, &mut next)?;
5447                            }
5448                        }
5449                    }
5450                    if prof {
5451                        e.stream().synchronize()?;
5452                        prof_ms[2] += seg.elapsed().as_secs_f64() * 1e3;
5453                    }
5454                    drop(ffn_col);
5455                    x_t = next;
5456                }
5457                if prof {
5458                    eprintln!(
5459                        "[tcol-prof] t={t} norm+qkv={:.3}ms attn={:.3}ms ffn={:.3}ms",
5460                        prof_ms[0], prof_ms[1], prof_ms[2]
5461                    );
5462                }
5463                if ok {
5464                    return Ok(x_t);
5465                }
5466                // fall through to the row-outer walk on ineligible layers
5467                x = x_t;
5468            }
5469            let mut next = e.uninit(t * n_embd)?;
5470            for r in 0..t {
5471                let mut row = e.uninit(n_embd)?;
5472                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
5473                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
5474                let out = self.decode_layers_eager(e, row, lo, hi, &row_pos, pos0 + r, cache)?;
5475                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
5476            }
5477            // dflash taps are NOT produced on this arm (they need per-layer hiddens the
5478            // row-outer walk does not materialize); the door is a step37 MTP bring-up
5479            // surface where taps are unused.
5480            return Ok(next);
5481        }
5482        let mut ph_last = std::time::Instant::now();
5483        for il in lo..hi {
5484            let mut next = e.uninit(t * n_embd)?;
5485            for r in 0..t {
5486                let mut row = e.uninit(n_embd)?;
5487                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
5488                // The caller owns this verify's position. During controller overlap, cache.pos
5489                // still describes generation N while this stage-0 walk belongs to N+1.
5490                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
5491                let mut one = [&mut *cache];
5492                let out = self.step35_decode_batch_layers(
5493                    e,
5494                    row,
5495                    &mut one,
5496                    &[(pos0 + r) as i32],
5497                    &row_pos,
5498                    il,
5499                    il + 1,
5500                    &mut ph_last,
5501                )?;
5502                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
5503            }
5504            self.dflash_tap(e, cache, il, &next, t)?;
5505            x = next;
5506        }
5507        Ok(x)
5508    }
5509
5510    /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
5511    /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
5512    /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
5513    /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
5514    /// prefix-keep, not all-or-nothing).
5515    pub(crate) fn dspark_verify_t_am(
5516        &self,
5517        e: &Engine,
5518        tokens: &[u32],
5519        pos0: usize,
5520        cache: &mut Cache,
5521    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
5522        let (logits, _hn) = self.decode_step_t_core_stream(
5523            e, tokens, pos0, cache, None, None, None, None, None, None,
5524        )?;
5525        let t = tokens.len();
5526        let v = self.output.out_features();
5527        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
5528        for r in 0..t {
5529            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
5530        }
5531        Ok(e.dtoh_u32(&am_d)?)
5532    }
5533
5534    /// DSpark verify returning the RAW verify logits [t, n_vocab] (device-resident) instead
5535    /// of per-row argmaxes — the sampled-admission arm's input (rejection-sampling accept
5536    /// gathers filtered p from these columns; lane/dspark-sampled-admission-20260820). Same
5537    /// forward as `dspark_verify_t_am`; the greedy arm keeps its argmax wrapper untouched.
5538    pub(crate) fn dspark_verify_t_logits(
5539        &self,
5540        e: &Engine,
5541        tokens: &[u32],
5542        pos0: usize,
5543        cache: &mut Cache,
5544    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5545        let (logits, _hn) = self.decode_step_t_core_stream(
5546            e, tokens, pos0, cache, None, None, None, None, None, None,
5547        )?;
5548        Ok(logits)
5549    }
5550
5551    /// DSpark verify with the MTP column-stash armed: identical forward to
5552    /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
5553    /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
5554    /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
5555    pub(crate) fn dspark_verify_t_am_ckpt(
5556        &self,
5557        e: &Engine,
5558        tokens: &[u32],
5559        pos0: usize,
5560        cache: &mut Cache,
5561    ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
5562        let mut ck = VerifyCkpt::new(self.layers.len());
5563        let (logits, _hn) = self.decode_step_t_core_stream(
5564            e,
5565            tokens,
5566            pos0,
5567            cache,
5568            None,
5569            Some(&mut ck),
5570            None,
5571            None,
5572            None,
5573            None,
5574        )?;
5575        let t = tokens.len();
5576        let v = self.output.out_features();
5577        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
5578        for r in 0..t {
5579            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
5580        }
5581        Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
5582    }
5583
5584    /// Engine-bundle slice 2: `dspark_verify_t_am_ckpt` with DEVICE tokens and NO readback.
5585    /// The verify tokens are the round's `chain_d` (cand layout: [anchor, drafts...]); the
5586    /// embed gathers its first `t` entries on-device (`embed_gather_u32_t` — bit-identical
5587    /// rows to the host arm), so the host never blocks on the draft chain before dispatching
5588    /// verify. Returns the device per-row argmax buffer; the caller merges its readback with
5589    /// the chain's into ONE sync. Forward, ckpt fill and argmax walk are `_ckpt` verbatim.
5590    pub(crate) fn dspark_verify_t_am_ckpt_dev(
5591        &self,
5592        e: &Engine,
5593        vtok: &CudaSlice<u32>,
5594        t: usize,
5595        pos0: usize,
5596        cache: &mut Cache,
5597        embd_dev: (&CudaSlice<u8>, i32, usize),
5598        graphs: Option<&mut DsparkVerifyGraphs>,
5599    ) -> Result<(CudaSlice<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
5600        debug_assert!(
5601            vtok.len() >= t,
5602            "verify window exceeds the device token buffer"
5603        );
5604        // The slab flag is a per-round statement: clear it here so a verify that never
5605        // reaches the graphs door (rowwise env, a non-tparallel arm) cannot leave a
5606        // stale `true` steering the commit at slabs the round never wrote.
5607        let mut graphs = graphs;
5608        if let Some(g) = graphs.as_deref_mut() {
5609            g.round_slab = false;
5610        }
5611        let mut ck = VerifyCkpt::new(self.layers.len());
5612        // Dummy host tokens size the funnel; the embed reads `vtok` (the round-stream
5613        // arm's established pattern — spec.rs stream-mode verify does the same).
5614        let dummy = vec![0u32; t];
5615        let (logits, _hn) = self.decode_step_t_core_stream(
5616            e,
5617            &dummy,
5618            pos0,
5619            cache,
5620            Some(embd_dev),
5621            Some(&mut ck),
5622            None,
5623            None,
5624            Some(vtok),
5625            graphs,
5626        )?;
5627        let v = self.output.out_features();
5628        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
5629        for r in 0..t {
5630            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
5631        }
5632        Ok((am_d, DsparkVerifyCkpt(ck)))
5633    }
5634
5635    /// Ckpt-armed twin of [`Self::dspark_verify_t_logits`] (sampled-admission arm).
5636    pub(crate) fn dspark_verify_t_logits_ckpt(
5637        &self,
5638        e: &Engine,
5639        tokens: &[u32],
5640        pos0: usize,
5641        cache: &mut Cache,
5642    ) -> Result<(CudaSlice<f32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
5643        let mut ck = VerifyCkpt::new(self.layers.len());
5644        let (logits, _hn) = self.decode_step_t_core_stream(
5645            e,
5646            tokens,
5647            pos0,
5648            cache,
5649            None,
5650            Some(&mut ck),
5651            None,
5652            None,
5653            None,
5654            None,
5655        )?;
5656        Ok((logits, DsparkVerifyCkpt(ck)))
5657    }
5658
5659    /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
5660    /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
5661    /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
5662    pub(crate) fn dspark_commit_prefix(
5663        &self,
5664        e: &Engine,
5665        cache: &mut Cache,
5666        snap: &crate::cache::CacheSnapshot,
5667        ckpt: &DsparkVerifyCkpt,
5668        keep: usize,
5669    ) -> Result<(), Box<dyn std::error::Error>> {
5670        self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
5671    }
5672
5673    /// Slice-3 commit twin: restore to `keep` accepted columns when the round's linear
5674    /// column stash lives in the graphs ctx's persistent slabs (`DsparkVerifyGraphs`) —
5675    /// the cols arm's exact semantics (KV lens + pos from the snapshot, GDN conv/ssm
5676    /// from the stash of column keep-1), slab-addressed and batched into two copy
5677    /// launches. `MEMRA_STATE_COPY_BATCH=0` falls back to per-layer view copies.
5678    pub(crate) fn dspark_commit_prefix_slab(
5679        &self,
5680        e: &Engine,
5681        cache: &mut Cache,
5682        snap: &crate::cache::CacheSnapshot,
5683        ctx: &DsparkVerifyGraphs,
5684        keep: usize,
5685    ) -> Result<(), Box<dyn std::error::Error>> {
5686        use cudarc::driver::DevicePtr;
5687        debug_assert!(keep >= 1, "keep==0 rounds take the legacy rollback");
5688        let mut conv_src: Vec<u64> = Vec::new();
5689        let mut ssm_src: Vec<u64> = Vec::new();
5690        let mut conv_dst: Vec<u64> = Vec::new();
5691        let mut ssm_dst: Vec<u64> = Vec::new();
5692        for il in 0..self.layers.len() {
5693            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
5694                kvl.len = saved + keep;
5695                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
5696            }
5697            if let Some(rl) = cache.recur[il].as_ref() {
5698                let (pc, ps, _cw, _sw) = ctx
5699                    .slab_row(e, il, keep - 1)
5700                    .ok_or("slab commit: linear layer missing from the graphs ctx")?;
5701                conv_src.push(pc);
5702                ssm_src.push(ps);
5703                let st = &e.gpu.stream();
5704                let (dc, _g0) = rl.conv_state.device_ptr(st);
5705                let (ds, _g1) = rl.ssm_state.device_ptr(st);
5706                conv_dst.push(dc as u64);
5707                ssm_dst.push(ds as u64);
5708            }
5709        }
5710        let n = conv_src.len();
5711        if n > 0 {
5712            if state_copy_batch_on() {
5713                let mut tt = vec![0u64; 2 * n];
5714                tt[..n].copy_from_slice(&conv_src);
5715                tt[n..].copy_from_slice(&conv_dst);
5716                let ct = e.htod_u64(&tt)?;
5717                tt[..n].copy_from_slice(&ssm_src);
5718                tt[n..].copy_from_slice(&ssm_dst);
5719                let st = e.htod_u64(&tt)?;
5720                e.copy_batch_uniform_f32(&ct, n, ctx.conv_words)?;
5721                e.copy_batch_uniform_f32(&st, n, ctx.ssm_words)?;
5722            } else {
5723                let (cw, sw) = (ctx.conv_words, ctx.ssm_words);
5724                let row = keep - 1;
5725                for il in 0..self.layers.len() {
5726                    let Some(rl) = cache.recur[il].as_mut() else {
5727                        continue;
5728                    };
5729                    let k = ctx.lin_pos[&il];
5730                    {
5731                        let sv = e.view(&ctx.stash_conv[k], (row + 1) * cw);
5732                        let win = sv.slice(row * cw..(row + 1) * cw);
5733                        e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
5734                    }
5735                    {
5736                        let sv = e.view(&ctx.stash_ssm[k], (row + 1) * sw);
5737                        let win = sv.slice(row * sw..(row + 1) * sw);
5738                        e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
5739                    }
5740                }
5741            }
5742        }
5743        cache.pos = snap.pos + keep;
5744        Ok(())
5745    }
5746
5747    /// Qwen35-family verify trunk in the live serving numeric class.
5748    ///
5749    /// Serving intentionally keeps this architecture in the generic batched program even at
5750    /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
5751    ///
5752    /// Two arms, one numeric class:
5753    /// - DENSE GDN (`DenseMlp`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
5754    ///   projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
5755    ///   program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
5756    ///   == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
5757    ///   append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
5758    ///   row's own t_kv-driven arm pick (the straddle law: every row executes the exact
5759    ///   program its isolated serving step would). One weight read per layer per round
5760    ///   instead of T — this is what makes MTP profitable in the exact class (the per-row
5761    ///   walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
5762    /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
5763    ///   serving layer body, preserving single-session autoregressive cache order (the
5764    ///   correctness reference; also the rollback seam for the t-parallel arm).
5765    ///
5766    /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
5767    /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
5768    #[allow(clippy::too_many_arguments)]
5769    fn qwen35_verify_batch_layers(
5770        &self,
5771        e: &Engine,
5772        x: CudaSlice<f32>,
5773        lo: usize,
5774        hi: usize,
5775        pos0: usize,
5776        t: usize,
5777        cache: &mut Cache,
5778        ckpt: Option<&mut VerifyCkpt>,
5779        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5780        graphs: Option<&mut DsparkVerifyGraphs>,
5781    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5782        // Qwen35Moe admitted 2026-08-20 (lane/draftcost-moe): the t-parallel arm already
5783        // carries the MoE FFN (`moe_ffn_il_zq8` at m=T) and the GDN per-row state loop; the
5784        // arch fence was a qualification gate, not a mechanism gap. Measured disease on the
5785        // 35B-A3B class: rowwise verify ~= 5.6 ms per drafted token (one full trunk step
5786        // each) — the same (K+1)-plain-steps wall the dense admission fixed on 2026-08-15.
5787        // Rollback seam unchanged: MEMRA_SPEC_VERIFY_ROWWISE=1.
5788        let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
5789            || !self.batched_serving_numeric_class()
5790            || t > 16;
5791        if rowwise {
5792            if stream.is_some() {
5793                // rowwise replays per row with host cache.pos — irreconcilable with a
5794                // device position counter. Burst callers must keep t <= 16 and the
5795                // ROWWISE env unset; refusing beats silently mispositioned rows.
5796                return Err("qwen35 rowwise verify has no ROUND-STREAM arm \
5797                            (t > 16 or MEMRA_SPEC_VERIFY_ROWWISE=1)"
5798                    .into());
5799            }
5800            self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
5801        } else {
5802            self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt, stream, graphs)
5803        }
5804    }
5805
5806    /// The per-row correctness reference: replay each verify row through the authoritative
5807    /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
5808    #[allow(clippy::too_many_arguments)]
5809    fn qwen35_verify_rowwise(
5810        &self,
5811        e: &Engine,
5812        mut x: CudaSlice<f32>,
5813        lo: usize,
5814        hi: usize,
5815        pos0: usize,
5816        t: usize,
5817        cache: &mut Cache,
5818        mut ckpt: Option<&mut VerifyCkpt>,
5819    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5820        let n_embd = self.cfg.n_embd as usize;
5821        let saved_pos = cache.pos;
5822        let mut ph_last = std::time::Instant::now();
5823        for il in lo..hi {
5824            let mut next = e.uninit(t * n_embd)?;
5825            let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
5826                if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
5827                    Some(Vec::with_capacity(t - 1))
5828                } else {
5829                    None
5830                };
5831            for r in 0..t {
5832                cache.pos = pos0 + r;
5833                let mut row = e.uninit(n_embd)?;
5834                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
5835                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
5836                let mut one = [&mut *cache];
5837                let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
5838                let out = match self.decode_batch_layers(
5839                    e,
5840                    row,
5841                    &mut one,
5842                    &ctx,
5843                    &row_pos,
5844                    &mut ph_last,
5845                ) {
5846                    Ok(out) => out,
5847                    Err(error) => {
5848                        cache.pos = saved_pos;
5849                        return Err(error);
5850                    }
5851                };
5852                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
5853                if r + 1 < t {
5854                    if let Some(states) = col_states.as_mut() {
5855                        let recur = cache.recur[il]
5856                            .as_ref()
5857                            .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
5858                        states.push((
5859                            e.clone_dtod(&recur.conv_state)?,
5860                            e.clone_dtod(&recur.ssm_state)?,
5861                        ));
5862                    }
5863                }
5864            }
5865            if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
5866                checkpoint.cols[il] = Some(states);
5867            }
5868            x = next;
5869        }
5870        cache.pos = saved_pos;
5871        Ok(x)
5872    }
5873
5874    /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
5875    ///
5876    /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
5877    /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
5878    /// pins the serving batch tier already carries:
5879    ///   * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
5880    ///     kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
5881    ///     alone;
5882    ///   * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
5883    ///     `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
5884    ///     launch is the per-row program (same pin the generic verify's fused norms rely on).
5885    /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
5886    /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
5887    /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
5888    /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
5889    /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
5890    /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
5891    /// program its isolated B=1 serving step would.
5892    ///
5893    /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
5894    /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
5895    #[allow(clippy::too_many_arguments)]
5896    fn qwen35_verify_tparallel(
5897        &self,
5898        e: &Engine,
5899        mut x: CudaSlice<f32>,
5900        lo: usize,
5901        hi: usize,
5902        pos0: usize,
5903        t: usize,
5904        cache: &mut Cache,
5905        mut ckpt: Option<&mut VerifyCkpt>,
5906        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5907        mut graphs: Option<&mut DsparkVerifyGraphs>,
5908    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5909        let seqs_append =
5910            std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
5911        let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
5912
5913        // Merge guard (v0.98 train, re-affirmed on the v0.100 train over slice 4c): the
5914        // ROUND-STREAM arm (lane/draftcost-moe, device position counter) and the dspark
5915        // verify graphs (engine-bundle slice 3 / trunk slice 4c) have no common caller —
5916        // stream rides the qwen35moe burst, graphs ride the dspark route. If a future
5917        // caller arms both, refuse loudly instead of silently dropping the graphs ctx
5918        // (the stream linear arm takes linear_attn_verify_t, not the graphed segment or
5919        // full-verify bodies).
5920        if stream.is_some() && graphs.is_some() {
5921            return Err(
5922                "qwen35 tparallel verify: ROUND-STREAM and dspark verify graphs \
5923                        cannot arm together"
5924                    .into(),
5925            );
5926        }
5927        // Engine-bundle slice 3 + slice 4c: with a graphs ctx armed, pointer tables are
5928        // refreshed once per verify (the gdn ping-pong moves handles; a fresh generation
5929        // moves the kv caches). Then:
5930        //  - slice 4c: when the WHOLE round rides one seqs rung (every row batchable, one
5931        //    split-ladder step, rung covers the round), the ENTIRE walk replays as ONE
5932        //    full-verify graph per (vt, rung) — linear layers through the shared
5933        //    `qwen35_tparallel_linear_layer` body, full-attention layers through the
5934        //    shared `qwen35_tparallel_fa_layer` body in graph mode.
5935        //  - fallback (straddle rounds, below the vec floor, partial walks): runs of
5936        //    consecutive LINEAR layers replay the slice-3 per-(segment, vt) graphs and
5937        //    the full-attention layers run eager (batched rows when eligible).
5938        if let Some(g) = graphs.as_deref_mut() {
5939            g.refresh_tables(e, cache)?;
5940            g.round_slab = false;
5941            if let Some(rung) = g.full_rung(self, cache, lo, hi, t, seqs_append && batch_fa_on) {
5942                // Pool ceiling (dspark_vg_cap): an existing key always replays; a NEW
5943                // full capture past the ceiling falls through to the segment/eager arms.
5944                if g.full.contains_key(&(t, rung, hi)) || g.can_capture() {
5945                    let out = g.run_full(self, e, lo, hi, &x, t, pos0, rung, cache)?;
5946                    g.round_slab = true;
5947                    return Ok(out);
5948                }
5949            }
5950            // Round-atomic ceiling check for the segment door: if any linear run in this
5951            // walk would need a NEW capture past the ceiling, the whole round runs the
5952            // eager cols-ckpt walk (mixing slab- and cols-stashed layers in one round
5953            // would corrupt the commit).
5954            if !g.segments_ready(self, lo, hi, t) {
5955                graphs = None;
5956            }
5957        }
5958        // STREAM (2b, lane/draftcost-moe): positions come from the device round counter
5959        // (pos_iota / i32_copy_add) so a burst round needs no host position knowledge.
5960        let pos_d = match stream {
5961            Some((_, ctr)) => {
5962                let mut p = e.alloc_uninit::<i32>(t)?;
5963                e.pos_iota(ctr, &mut p, t)?;
5964                p
5965            }
5966            None => {
5967                let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
5968                e.htod_i32(&pos_host)?
5969            }
5970        };
5971        // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
5972        // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
5973        // LAZY since slice 4: the batched fa/append arm never touches them — they are built
5974        // on the first per-row fallback layer only (stream-aware there; the stream FA arm
5975        // rides the dc rows kernels and never reaches the fallback).
5976        let mut pos_rows: Option<Vec<CudaSlice<i32>>> = None;
5977        let mut il = lo;
5978        while il < hi {
5979            if graphs.is_some() && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
5980                let mut end = il;
5981                while end < hi && matches!(self.layers[end].mixer, Mixer::Linear(_)) {
5982                    end += 1;
5983                }
5984                let g = graphs.as_deref_mut().expect("checked above");
5985                x = g.run_segment(self, e, il, end, &x, t, cache)?;
5986                g.round_slab = true;
5987                il = end;
5988                continue;
5989            }
5990            let layer = &self.layers[il];
5991            if stream.is_none() && matches!(layer.mixer, Mixer::Linear(_)) {
5992                // Eager linear layer (no graphs ctx): the shared body, legacy cols-ckpt arm.
5993                // Under ROUND-STREAM the linear layers ride the fa-body match's stream arm
5994                // below (linear_attn_verify_t — the stream COMMIT needs its GdnStash).
5995                x = self.qwen35_tparallel_linear_layer(
5996                    e,
5997                    il,
5998                    &x,
5999                    t,
6000                    cache,
6001                    ckpt.as_deref_mut(),
6002                    None,
6003                    None,
6004                )?;
6005                il += 1;
6006                continue;
6007            }
6008            // Full-attention (or stream-Linear, or MLA-refusing) layer: the extracted
6009            // shared body — eager arm (fresh per-verify pos/table, exact t_kv sizing,
6010            // in-body len bump). The slice-4c captured full-verify graphs run the SAME
6011            // body in graph mode; under ROUND-STREAM the body's dc-rows / GDN stream arms
6012            // run (lane/draftcost-moe).
6013            x = self.qwen35_tparallel_fa_layer(
6014                e,
6015                il,
6016                &x,
6017                t,
6018                cache,
6019                FaLayerArgs {
6020                    pos_d: &pos_d,
6021                    pos_rows: &mut pos_rows,
6022                    pos0,
6023                    seqs_append,
6024                    batch_fa_on,
6025                    graph_cap: None,
6026                    stream,
6027                    ckpt: ckpt.as_deref_mut(),
6028                },
6029            )?;
6030            il += 1;
6031        }
6032        Ok(x)
6033    }
6034
6035    /// SHARED dense-FFN body for the qwen35 t-parallel layers (trunk-kernels slice B) —
6036    /// ONE copy for the fa and linear layer bodies (the verify_layers extraction lesson).
6037    /// Dual arm (MEMRA_TK_FFN_DUAL, default on): gate+up in ONE dual launch from the
6038    /// pre-quantized activation with macro-scales DEFERRED into the fused SwiGLU+q8_1
6039    /// epilogue, then ffn_down from the fused (aq, ad) — the q27 verify chain verbatim.
6040    /// Every door is the bit-identical proven one: `matmul_decode_exact_dual_pre` (per
6041    /// (tensor,token,row) == the two singles), `silu_mul_scaled_q8_1` (y*s inline == the
6042    /// scale_inplace store, value-exact; fused quantize == quantize_q8_1 bytes),
6043    /// `matmul_decode_exact_pre` (dispatch mirror of the singles' q8_1-fast tail).
6044    /// Dual-refused (t outside 2..=7, non-NVFP4, layout mismatch) or seam off -> the
6045    /// original singles chain, byte-for-byte.
6046    #[allow(clippy::too_many_arguments)]
6047    fn qwen35_tparallel_dense_ffn(
6048        &self,
6049        e: &Engine,
6050        ffn_gate: &crate::model::GpuTensor,
6051        ffn_up: &crate::model::GpuTensor,
6052        ffn_down: &crate::model::GpuTensor,
6053        zn: &CudaSlice<f32>,
6054        t: usize,
6055        n_embd: usize,
6056    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6057        let n_ff = ffn_gate.out_features();
6058        let (zq, zd) = e.quantize_q8_1(zn, t, n_embd)?;
6059        if Engine::tk_ffn_dual_on() {
6060            if let Some(((g, gs), (u, us))) =
6061                e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, &zq, &zd, t)?
6062            {
6063                if e.uses_q8_1_fast(ffn_down) {
6064                    let (aq, ad) = e.silu_mul_scaled_q8_1(&g, &u, gs, us, t * n_ff)?;
6065                    return e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t);
6066                }
6067                let mut act = e.uninit(t * n_ff)?;
6068                e.silu_mul_scaled(&g, &u, gs, us, &mut act, t * n_ff)?;
6069                let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
6070                return e.matmul_pre(ffn_down, &aq, &ad, &act, t);
6071            }
6072        }
6073        // v1 singles chain (seam off or dual-refused) — the pre-slice-B body verbatim.
6074        let g = e.matmul_pre(ffn_gate, &zq, &zd, zn, t)?;
6075        let u = e.matmul_pre(ffn_up, &zq, &zd, zn, t)?;
6076        let mut act = e.uninit(t * n_ff)?;
6077        e.silu_mul(&g, &u, &mut act, t * n_ff)?;
6078        let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
6079        e.matmul_pre(ffn_down, &aq, &ad, &act, t)
6080    }
6081
6082    /// ONE t-parallel FULL-ATTENTION layer (attn_norm + fa mixer + post_attn_norm + FFN +
6083    /// tap) — extracted from the walk exactly like `qwen35_tparallel_linear_layer` so the
6084    /// eager walk and the slice-4c captured full-verify graphs execute the SAME body (a
6085    /// second copy is how dispatch mirrors drift — the verify_layers extraction lesson).
6086    ///
6087    /// `args.graph_cap = Some((table, off, rung_end))` is the captured-graph mode:
6088    /// - kv base-pointer pairs come from the ctx-owned persistent table at `off` (a fresh
6089    ///   generation's cache lands at new addresses that only the per-verify table refresh
6090    ///   knows — the slice-3 baked-address lesson);
6091    /// - the seqs twins size partials/grid at `rung_end` and pin `split_keys` to the
6092    ///   rung's ladder value: `n_splits_max` is pure stride, splits >= ns_eff write the
6093    ///   EMPTY partial the combine never reads, and every per-row T_kv derives in-kernel
6094    ///   from `pos_seq[z]` — so one captured launch replays bit-identically for every
6095    ///   round whose rows all sit inside the rung;
6096    /// - the host len bump moves to the replay caller (captured host code does not
6097    ///   re-run at replay).
6098    /// Graph mode REFUSES any round the batched arm cannot take: the per-row fallback
6099    /// host-branches on t_kv and must never be captured.
6100    #[allow(clippy::too_many_arguments)]
6101    fn qwen35_tparallel_fa_layer(
6102        &self,
6103        e: &Engine,
6104        il: usize,
6105        x: &CudaSlice<f32>,
6106        t: usize,
6107        cache: &mut Cache,
6108        args: FaLayerArgs<'_>,
6109    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6110        use cudarc::driver::DevicePtr;
6111        let cfg = &self.cfg;
6112        let n_embd = cfg.n_embd as usize;
6113        let eps = cfg.rms_eps;
6114        let head_dim_global = cfg.head_dim_k as usize;
6115        let layer = &self.layers[il];
6116        let FaLayerArgs {
6117            pos_d,
6118            pos_rows,
6119            pos0,
6120            seqs_append,
6121            batch_fa_on,
6122            graph_cap,
6123            stream,
6124            mut ckpt,
6125        } = args;
6126
6127        // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
6128        let anorm = layer.attn_norm.float_data();
6129        let mut xn = e.uninit(t * n_embd)?;
6130        e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
6131        let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
6132
6133        let mixed: CudaSlice<f32> = match &layer.mixer {
6134            Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
6135            // STREAM ARM (2b, lane/draftcost-moe): under a device position counter the
6136            // per-row serving-kernel chain cannot run (host state swaps keyed on host
6137            // row index are fine, but the stream COMMIT needs the GdnStash for its _dc
6138            // rebuild — the per-row chain only produces per-column clones). GDN rides
6139            // `linear_attn_verify_t`: batched q8_1-class projections, stash-producing,
6140            // and its one-scan recurrence is pinned bit-identical to T chained T=1
6141            // steps (its header + kernel-check). Position-independent, so no counter
6142            // plumbing is needed. Guards mirror the generic call site exactly.
6143            Mixer::Linear(la) if stream.is_some() => {
6144                if !(t >= 3 || (t == 2 && spec_m2()))
6145                    || !self.mixer_in_q8_1_fast(e, &layer.mixer)
6146                    || !e.uses_q8_1_fast(&la.ssm_out)
6147                {
6148                    return Err("qwen35 stream verify: GDN batched arm requires t>=3 \
6149                                (or MEMRA_SPEC_M2 at t=2) and q8_1-fast projections"
6150                        .into());
6151                }
6152                let want = ckpt.is_some();
6153                let (out, stash) =
6154                    self.linear_attn_verify_t(e, la, &xn, Some((&hq, &hd)), t, cache, il, want)?;
6155                if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
6156                    ck.gdn[il] = Some(st);
6157                }
6158                out
6159            }
6160            Mixer::Linear(_) => {
6161                unreachable!("linear layers ride qwen35_tparallel_linear_layer")
6162            }
6163            Mixer::Full(fa) => {
6164                let geometry = cfg.full_attention_geometry_at(il as u32);
6165                let n_head = geometry.n_head as usize;
6166                let n_head_kv = geometry.n_head_kv as usize;
6167                let head_dim = geometry.head_dim_k as usize;
6168                let rope_dims = geometry.n_rot as usize;
6169                let rope_base = geometry.rope_base;
6170                let scale = geometry.attention_scale();
6171                // Batched projections: one weight read serves all T rows.
6172                // GROUP-3 twin (trunk-kernels slice D): q/k/v in ONE launch — the group4
6173                // kernel with n3=0, bit-identical per (tensor, token, row) to the three
6174                // singles; refused or MEMRA_TK_FA_GROUP=0 -> singles byte-for-byte.
6175                let (qf, mut k, v) = match e.matmul_decode_exact_group3_pre(
6176                    [&fa.wq, &fa.wk, &fa.wv],
6177                    &hq,
6178                    &hd,
6179                    t,
6180                )? {
6181                    Some(mut g3) => {
6182                        let v = g3.pop().unwrap();
6183                        let k = g3.pop().unwrap();
6184                        let qf = g3.pop().unwrap();
6185                        (qf, k, v)
6186                    }
6187                    None => (
6188                        e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?,
6189                        e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?,
6190                        e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?,
6191                    ),
6192                };
6193                let gated =
6194                    geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
6195                let (mut q, gate) = if gated {
6196                    let mut qs = e.uninit(t * n_head * head_dim)?;
6197                    let mut gs = e.uninit(t * n_head * head_dim)?;
6198                    e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
6199                    (qs, Some(gs))
6200                } else {
6201                    (qf, None)
6202                };
6203                let mut qn = e.uninit(t * n_head * head_dim)?;
6204                e.rms_norm(
6205                    &q,
6206                    fa.q_norm.float_data(),
6207                    &mut qn,
6208                    head_dim,
6209                    t * n_head,
6210                    eps,
6211                )?;
6212                q = qn;
6213                let mut kn = e.uninit(t * n_head_kv * head_dim)?;
6214                e.rms_norm(
6215                    &k,
6216                    fa.k_norm.float_data(),
6217                    &mut kn,
6218                    head_dim,
6219                    t * n_head_kv,
6220                    eps,
6221                )?;
6222                k = kn;
6223                e.rope_neox(
6224                    &mut q, pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
6225                )?;
6226                e.rope_neox(
6227                    &mut k, pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
6228                )?;
6229
6230                // Per-row append + attend: row r sees rows 0..r in KV (causal within the
6231                // draft), each through the b_n=1 serving kernels at its own t_kv.
6232                let q_dim = n_head * head_dim;
6233                let kv_dim = n_head_kv * head_dim;
6234                let mut attn = e.uninit(t * q_dim)?;
6235                let (kdk, kdv, ktb, vtb, len0, kv_local) = {
6236                    let kvl = cache.kv[il].as_ref().unwrap();
6237                    // [2T] interleaved k,v base pointers: entry pair z serves row z of
6238                    // the batched twins; the per-row fallback reads pair 0 (same cache
6239                    // for every row of one layer). Graph mode reads the ctx table.
6240                    let local: Option<CudaSlice<u64>> = match graph_cap {
6241                        Some(_) => None,
6242                        None => {
6243                            let s = &e.gpu.stream();
6244                            let (pk, _g) = kvl.k.device_ptr(s);
6245                            let (pv, _g2) = kvl.v.device_ptr(s);
6246                            let mut tbl = Vec::with_capacity(2 * t);
6247                            for _ in 0..t {
6248                                tbl.push(pk as u64);
6249                                tbl.push(pv as u64);
6250                            }
6251                            Some(e.htod_u64(&tbl)?)
6252                        }
6253                    };
6254                    (
6255                        kvl.kv_dim_k,
6256                        kvl.kv_dim_v,
6257                        kvl.k_tok_bytes,
6258                        kvl.v_tok_bytes,
6259                        kvl.len,
6260                        local,
6261                    )
6262                };
6263                let (kv_tbl, kv_off): (&CudaSlice<u64>, usize) = match graph_cap {
6264                    Some((tb, off, _)) => (tb, off),
6265                    None => (kv_local.as_ref().expect("built above"), 0),
6266                };
6267                // Slice 4 (fa/append rows — see dspark_fa_rows_on): the whole per-row
6268                // section batches into the z-batched serving twins when every row of
6269                // this round takes the v4-seqs arm on ONE fa_split_keys rung. Both
6270                // guards are evaluated at the round's FIRST and LAST t_kv — the
6271                // eligibility window (vec floor .. v4 max) and each split-ladder rung
6272                // are intervals in t_kv, so ends-inside means all-inside (the straddle
6273                // law). Appending all T rows before any attend is read-equivalent to
6274                // the interleaved order: row r's walk reads keys 0..len0+r only, and
6275                // rows > r land at slots it never touches; every written cache row is
6276                // the per-token appender's exact warp program (kernel-check pinned).
6277                let t_kv_first = len0 + 1;
6278                let t_kv_last = len0 + t;
6279                let rows_batched = t >= 2
6280                    && seqs_append
6281                    && batch_fa_on
6282                    && dspark_fa_rows_on()
6283                    // the z-batched twins read stacked rows at the CACHE's kv dims;
6284                    // the projection stack is [T, n_head_kv*head_dim] — they must be
6285                    // the same stride or row z misaligns (true for this family; the
6286                    // guard keeps any asymmetric-kv model on the per-row loop).
6287                    && kdk == kv_dim
6288                    && kdv == kv_dim
6289                    && crate::fa_seqs_eligible(t_kv_first, head_dim_global)
6290                    && crate::fa_seqs_eligible(t_kv_last, head_dim_global)
6291                    && crate::fa_split_keys(t_kv_first, cfg.n_head_kv as usize)
6292                        == crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize);
6293                // Sizing: eager = exact round bound; graph mode = the rung end (stride +
6294                // grid only — bytes proven equal above). Capture-time invariants refuse
6295                // loudly rather than bake a divergent body.
6296                let (size_kv_max, sp) = match graph_cap {
6297                    Some((_, _, rung)) => {
6298                        if !rows_batched {
6299                            return Err(format!(
6300                                "fa graph capture: layer {il} round is not batchable \
6301                                 (t_kv {t_kv_first}..{t_kv_last}) — the per-row fallback \
6302                                 must never be captured"
6303                            )
6304                            .into());
6305                        }
6306                        let sp_r = crate::fa_split_keys(rung, cfg.n_head_kv as usize);
6307                        if t_kv_last > rung
6308                            || sp_r != crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize)
6309                        {
6310                            return Err(format!(
6311                                "fa graph capture: rung {rung} does not cover round \
6312                                 t_kv {t_kv_first}..{t_kv_last} on one split ladder step"
6313                            )
6314                            .into());
6315                        }
6316                        (rung, sp_r)
6317                    }
6318                    None => (
6319                        t_kv_last,
6320                        crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize),
6321                    ),
6322                };
6323                if let Some((_, ctr)) = stream {
6324                    // STREAM ARM (2b): one batched dc append + the multi-row dc attention
6325                    // — the generic stream arm's exact shape (rows kernels are pinned
6326                    // byte-identical to the per-row programs by kernel-check). Host len
6327                    // stays a stale lower bound; the burst drain reconciles it.
6328                    let kvl = cache.kv[il].as_mut().unwrap();
6329                    e.append_kv_quantized_rows_dc(
6330                        &k,
6331                        &v,
6332                        &mut kvl.k,
6333                        &mut kvl.v,
6334                        ctr,
6335                        t,
6336                        kdk,
6337                        kdv,
6338                        ktb,
6339                        vtb,
6340                        Engine::kv_fp8_on(),
6341                    )?;
6342                    let upper = (kvl.len + t + 64).min(cache.max_ctx);
6343                    let k_view = e.view_u8(&kvl.k, upper * ktb);
6344                    let v_view = e.view_u8(&kvl.v, upper * vtb);
6345                    e.fa_decode_rows_dc(
6346                        &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, ctr, upper,
6347                        t, scale, ktb, vtb, 0, false,
6348                    )?;
6349                } else if rows_batched {
6350                    e.append_kv_quantized_seqs(
6351                        &k,
6352                        &v,
6353                        &kv_tbl.slice(kv_off..kv_off + 2 * t),
6354                        pos_d,
6355                        t,
6356                        kdk,
6357                        kdv,
6358                        ktb,
6359                        vtb,
6360                    )?;
6361                    if graph_cap.is_none() {
6362                        cache.kv[il].as_mut().unwrap().len += t;
6363                    }
6364                    e.fa_decode_batch_seqs_v4(
6365                        &q,
6366                        &kv_tbl.slice(kv_off..kv_off + 2 * t),
6367                        pos_d,
6368                        &mut attn,
6369                        head_dim,
6370                        n_head,
6371                        n_head_kv,
6372                        t,
6373                        size_kv_max,
6374                        scale,
6375                        sp,
6376                        ktb,
6377                        vtb,
6378                    )?;
6379                } else {
6380                    if pos_rows.is_none() {
6381                        // Stream-aware for symmetry with pos_d (the stream FA arm rides
6382                        // the dc rows kernels above and never reaches this fallback).
6383                        *pos_rows = Some(match stream {
6384                            Some((_, ctr)) => (0..t)
6385                                .map(|r| {
6386                                    let mut b = e.alloc_uninit::<i32>(1)?;
6387                                    e.i32_copy_add(ctr, &mut b, r as i32)?;
6388                                    Ok(b)
6389                                })
6390                                .collect::<Result<_, Box<dyn std::error::Error>>>()?,
6391                            None => (0..t)
6392                                .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
6393                                .collect::<Result<_, _>>()?,
6394                        });
6395                    }
6396                    let pos_rows = pos_rows.as_ref().unwrap();
6397                    for r in 0..t {
6398                        // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
6399                        // whose row 0 is this row (arithmetic-free materialization copies,
6400                        // same as decode's per-seq fallback arm).
6401                        let mut k_row = e.uninit(kv_dim)?;
6402                        e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
6403                        let mut v_row = e.uninit(kv_dim)?;
6404                        e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
6405                        let pos_row = &pos_rows[r];
6406                        let kvl = cache.kv[il].as_mut().unwrap();
6407                        if seqs_append {
6408                            e.append_kv_quantized_seqs(
6409                                &k_row,
6410                                &v_row,
6411                                &kv_tbl.slice(kv_off..kv_off + 2),
6412                                pos_row,
6413                                1,
6414                                kdk,
6415                                kdv,
6416                                ktb,
6417                                vtb,
6418                            )?;
6419                            kvl.len += 1;
6420                        } else {
6421                            e.append_kv_quantized_view(
6422                                &k_row.slice(0..kv_dim),
6423                                &v_row.slice(0..kv_dim),
6424                                &mut kvl.k,
6425                                &mut kvl.v,
6426                                kvl.len,
6427                                kvl.kv_dim_k,
6428                                kvl.kv_dim_v,
6429                                kvl.k_tok_bytes,
6430                                kvl.v_tok_bytes,
6431                                Engine::kv_fp8_on(),
6432                            )?;
6433                            kvl.len += 1;
6434                        }
6435                        let t_kv = kvl.len;
6436                        let mut q_row = e.uninit(q_dim)?;
6437                        e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
6438                        let mut a_row = e.uninit(q_dim)?;
6439                        if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
6440                            let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
6441                            e.fa_decode_batch_seqs_v4(
6442                                &q_row,
6443                                &kv_tbl.slice(kv_off..kv_off + 2),
6444                                pos_row,
6445                                &mut a_row,
6446                                head_dim,
6447                                n_head,
6448                                n_head_kv,
6449                                1,
6450                                t_kv,
6451                                scale,
6452                                sp0_r,
6453                                ktb,
6454                                vtb,
6455                            )?;
6456                        } else {
6457                            let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
6458                            let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
6459                            let mut a_view = a_row.slice_mut(0..q_dim);
6460                            e.fa_decode_kvmod_view(
6461                                &q_row.slice(0..q_dim),
6462                                &k_view,
6463                                &v_view,
6464                                &mut a_view,
6465                                head_dim,
6466                                n_head,
6467                                n_head_kv,
6468                                t_kv,
6469                                scale,
6470                                kvl.k_tok_bytes,
6471                                kvl.v_tok_bytes,
6472                                Engine::kv_fp8_on(),
6473                            )?;
6474                        }
6475                        e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
6476                    }
6477                }
6478
6479                // Output gate (element-wise) + o-proj at m=T.
6480                let attn_g = match &gate {
6481                    Some(g) => {
6482                        let n = t * q_dim;
6483                        let mut gsig = e.uninit(n)?;
6484                        e.sigmoid(g, &mut gsig, n)?;
6485                        let mut ag = e.uninit(n)?;
6486                        e.mul(&attn, &gsig, &mut ag, n)?;
6487                        ag
6488                    }
6489                    None => attn,
6490                };
6491                e.matmul(&fa.wo, &attn_g, t)?
6492            }
6493        };
6494
6495        // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
6496        let pnorm = layer.post_attn_norm.float_data();
6497        let mut x1 = e.uninit(t * n_embd)?;
6498        let mut zn = e.uninit(t * n_embd)?;
6499        e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
6500        let ffn_out = match &layer.ffn {
6501            crate::hybrid::Ffn::Dense {
6502                ffn_gate,
6503                ffn_up,
6504                ffn_down,
6505            } => {
6506                assert!(
6507                    self.cfg.m3.is_none(),
6508                    "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
6509                );
6510                self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
6511            }
6512            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
6513        };
6514        let mut x2 = e.uninit(t * n_embd)?;
6515        e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
6516        // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
6517        self.dflash_tap(e, cache, il, &x2, t)?;
6518        Ok(x2)
6519    }
6520
6521    /// ONE t-parallel LINEAR layer (attn_norm + gdn mixer + post_attn_norm + FFN + tap) —
6522    /// the exact body the old in-loop Linear arm ran, extracted so the eager walk and the
6523    /// slice-3 captured segments execute the SAME code (a second copy is how dispatch
6524    /// mirrors drift — the verify_layers extraction lesson). Two deliberate changes, both
6525    /// bit-identical by construction:
6526    /// - the gdn ping-pong host swap moves from per-row to ONE end-of-body swap (t odd):
6527    ///   the device sequence is driven entirely by the 6-entry pointer table, which
6528    ///   already encodes both parities; the ckpt stash reads name row r's out buffer
6529    ///   directly (r even -> alt handle, odd -> canonical) — the same physical bytes the
6530    ///   legacy post-swap clone read.
6531    /// - `stash` (slice-3 ctx): persistent per-layer slabs written by copy_into instead of
6532    ///   per-row clone_dtod allocs — same bytes, capture-legal (no per-round host objects).
6533    /// `table_src` = (persistent pointer table, offset) when the ctx owns the tables;
6534    /// None builds the per-verify table exactly as before.
6535    #[allow(clippy::too_many_arguments)]
6536    fn qwen35_tparallel_linear_layer(
6537        &self,
6538        e: &Engine,
6539        il: usize,
6540        x: &CudaSlice<f32>,
6541        t: usize,
6542        cache: &mut Cache,
6543        mut ckpt: Option<&mut VerifyCkpt>,
6544        stash: Option<(&mut CudaSlice<f32>, &mut CudaSlice<f32>)>,
6545        table_src: Option<(&CudaSlice<u64>, usize)>,
6546    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6547        use cudarc::driver::DevicePtr;
6548        let cfg = &self.cfg;
6549        let n_embd = cfg.n_embd as usize;
6550        let eps = cfg.rms_eps;
6551        let layer = &self.layers[il];
6552        let Mixer::Linear(la) = &layer.mixer else {
6553            return Err("qwen35_tparallel_linear_layer on a non-linear layer".into());
6554        };
6555        // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
6556        let anorm = layer.attn_norm.float_data();
6557        let mut xn = e.uninit(t * n_embd)?;
6558        e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
6559        let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
6560
6561        let geometry = la.geometry;
6562        let d_state = geometry.key_head_dim as usize;
6563        let num_k = geometry.key_heads as usize;
6564        let num_v = geometry.value_heads as usize;
6565        let d_conv = geometry.conv_kernel as usize;
6566        let key_dim = d_state * num_k;
6567        let value_dim = geometry.value_head_dim as usize * num_v;
6568        let conv_dim = key_dim * 2 + value_dim;
6569        let gdn_scale = 1.0 / (d_state as f32).sqrt();
6570
6571        // ---- batched projections: one weight read for all T rows ----
6572        // GROUP-4 twin (trunk-kernels slice C): the whole 4-tuple in ONE launch, bit-identical
6573        // per (tensor, token, row) to the four singles; refused (layout/tier) or
6574        // MEMRA_TK_GDN_GROUP=0 -> the singles chain byte-for-byte.
6575        let (qkv_mixed, z, beta_raw, alpha) = match e.matmul_decode_exact_group4_pre(
6576            [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha],
6577            &hq,
6578            &hd,
6579            t,
6580        )? {
6581            Some(mut g4) => {
6582                let alpha = g4.pop().unwrap();
6583                let beta_raw = g4.pop().unwrap();
6584                let z = g4.pop().unwrap();
6585                let qkv_mixed = g4.pop().unwrap();
6586                (qkv_mixed, z, beta_raw, alpha)
6587            }
6588            None => (
6589                e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?,
6590                e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?,
6591                e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?,
6592                e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?,
6593            ),
6594        };
6595        let beta_w = la.ssm_beta.out_features();
6596        let alpha_w = la.ssm_alpha.out_features();
6597        let qkv_w = la.wqkv.out_features();
6598
6599        // ---- per-row state chain through the b_n=1 serving kernels ----
6600        // 6-entry alternating pointer table expresses the ping-pong without a rebuild per
6601        // row: even rows scan s0 -> s1, odd rows s1 -> s0.
6602        let table_local: Option<CudaSlice<u64>> = match table_src {
6603            Some(_) => None,
6604            None => {
6605                let rl = cache.recur[il].as_ref().unwrap();
6606                let s = &e.gpu.stream();
6607                let (pc, _g0) = rl.conv_state.device_ptr(s);
6608                let (p0, _g1) = rl.ssm_state.device_ptr(s);
6609                let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
6610                Some(e.htod_u64(&[
6611                    pc as u64, p0 as u64, p1 as u64, pc as u64, p1 as u64, p0 as u64,
6612                ])?)
6613            }
6614        };
6615        let (table, toff): (&CudaSlice<u64>, usize) = match table_src {
6616            Some((tb, off)) => (tb, off),
6617            None => (table_local.as_ref().unwrap(), 0),
6618        };
6619        let mut o_all = e.uninit(t * value_dim)?;
6620        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
6621            if ckpt.is_some() && stash.is_none() && t >= 2 {
6622                Some(Vec::with_capacity(t - 1))
6623            } else {
6624                None
6625            };
6626        let mut stash = stash;
6627        // Per-row scratch reused across rows (uninit is cheap but not free at
6628        // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
6629        // [T, ...] buffers — zero arithmetic-free copies in this loop.
6630        let mut conv_out = e.uninit(conv_dim)?;
6631        let mut q_l2 = e.uninit(value_dim)?;
6632        let mut k_l2 = e.uninit(value_dim)?;
6633        let mut v_gd = e.uninit(value_dim)?;
6634        let mut beta_b = e.uninit(num_v)?;
6635        let mut g_log = e.uninit(num_v)?;
6636        for r in 0..t {
6637            let base = toff + if r % 2 == 0 { 0 } else { 3 };
6638            let conv_view = table.slice(base..base + 1);
6639            let in_view = table.slice(base + 1..base + 2);
6640            let out_view = table.slice(base + 2..base + 3);
6641            e.ssm_conv1d_fused_decode_b_view(
6642                &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
6643                &conv_view,
6644                la.ssm_conv1d.float_data(),
6645                &mut conv_out,
6646                conv_dim,
6647                d_conv,
6648                1,
6649            )?;
6650            e.gdn_prep_decode_b_view(
6651                &conv_out,
6652                &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
6653                &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
6654                la.ssm_dt.float_data(),
6655                la.ssm_a.float_data(),
6656                &mut q_l2,
6657                &mut k_l2,
6658                &mut v_gd,
6659                &mut beta_b,
6660                &mut g_log,
6661                d_state,
6662                num_v,
6663                num_k,
6664                key_dim,
6665                eps,
6666                conv_dim,
6667                1,
6668            )?;
6669            let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
6670            e.gdn_scan_s128_batched_view(
6671                &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row, num_v, 1,
6672                gdn_scale,
6673            )?;
6674            if r + 1 < t {
6675                // Row r's out buffer: even rows write s1 (the alt handle — no swaps ran),
6676                // odd rows write s0 — the same physical state the legacy post-swap
6677                // canonical clone read.
6678                let rl = cache.recur[il]
6679                    .as_ref()
6680                    .ok_or("qwen35 linear verify layer has no recurrent state")?;
6681                let ssm_src = if r % 2 == 0 {
6682                    &rl.ssm_state_alt
6683                } else {
6684                    &rl.ssm_state
6685                };
6686                match stash.as_mut() {
6687                    Some((conv_slab, ssm_slab)) => {
6688                        // BOTH stash reads go through the pointer table at run time: the
6689                        // ssm handles ping-pong between rounds, and the ctx (with its
6690                        // captured graphs) outlives the Cache — a fresh generation's
6691                        // conv/ssm buffers land at new addresses that only the per-round
6692                        // table refresh knows. A baked direct copy would read freed
6693                        // memory (parity was the slice-3 smoke divergence; cache
6694                        // lifetime is the cross-generation twin).
6695                        e.copy_indirect_src_f32(
6696                            &conv_view,
6697                            conv_slab,
6698                            r * conv_dim * (d_conv - 1),
6699                            conv_dim * (d_conv - 1),
6700                        )?;
6701                        // The ssm handles PING-PONG between rounds: a captured direct
6702                        // copy would bake the capture-time physical buffer and read the
6703                        // wrong parity after any odd-vt round (the slice-3 smoke
6704                        // divergence). Read the src address from row r's OUT table
6705                        // entry at run time — the same entry the scan just wrote.
6706                        e.copy_indirect_src_f32(
6707                            &out_view,
6708                            ssm_slab,
6709                            r * d_state * d_state * num_v,
6710                            d_state * d_state * num_v,
6711                        )?;
6712                    }
6713                    None => {
6714                        if let Some(states) = col_states.as_mut() {
6715                            states.push((e.clone_dtod(&rl.conv_state)?, e.clone_dtod(ssm_src)?));
6716                        }
6717                    }
6718                }
6719            }
6720        }
6721        // ONE end-of-body parity swap (t odd) — the legacy loop swapped per row; the net
6722        // handle motion is identical and the device sequence never read the handles.
6723        if t % 2 == 1 {
6724            let rl = cache.recur[il].as_mut().unwrap();
6725            std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
6726        }
6727        if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
6728            checkpoint.cols[il] = Some(states);
6729        }
6730
6731        // ---- batched gated norm + out-projection at m=T ----
6732        let mixed = if e.uses_q8_1_fast(&la.ssm_out) {
6733            let (gq, gd) = e.gated_rmsnorm_q8_1(
6734                &o_all,
6735                la.ssm_norm.float_data(),
6736                &z,
6737                d_state,
6738                t * num_v,
6739                eps,
6740            )?;
6741            let g0 = e.zeros(0)?;
6742            e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
6743        } else {
6744            let mut gn = e.uninit(t * value_dim)?;
6745            e.gated_rmsnorm(
6746                &o_all,
6747                la.ssm_norm.float_data(),
6748                &z,
6749                &mut gn,
6750                d_state,
6751                t * num_v,
6752                eps,
6753            )?;
6754            e.matmul(&la.ssm_out, &gn, t)?
6755        };
6756
6757        // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
6758        let pnorm = layer.post_attn_norm.float_data();
6759        let mut x1 = e.uninit(t * n_embd)?;
6760        let mut zn = e.uninit(t * n_embd)?;
6761        e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
6762        let ffn_out = match &layer.ffn {
6763            crate::hybrid::Ffn::Dense {
6764                ffn_gate,
6765                ffn_up,
6766                ffn_down,
6767            } => {
6768                assert!(
6769                    self.cfg.m3.is_none(),
6770                    "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
6771                );
6772                self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
6773            }
6774            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
6775        };
6776        let mut x2 = e.uninit(t * n_embd)?;
6777        e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
6778        // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
6779        self.dflash_tap(e, cache, il, &x2, t)?;
6780        Ok(x2)
6781    }
6782
6783    /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
6784    /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
6785    /// carried in from outside the range) and exits with the range's final residual materialized
6786    /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
6787    /// instead of one.
6788    ///
6789    /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
6790    /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
6791    /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
6792    /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
6793    /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
6794    /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
6795    /// code — there is no "split version" of the verify math.
6796    ///
6797    /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
6798    /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
6799    /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
6800    /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
6801    #[allow(clippy::too_many_arguments)]
6802    fn verify_layers(
6803        &self,
6804        e: &Engine,
6805        mut x: CudaSlice<f32>,
6806        lo: usize,
6807        hi: usize,
6808        pos_d: &CudaSlice<i32>,
6809        pos0: usize,
6810        t: usize,
6811        cache: &mut Cache,
6812        mut ckpt: Option<&mut VerifyCkpt>,
6813        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6814        graphs: Option<&mut DsparkVerifyGraphs>,
6815    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6816        if self.sliding_gated_moe_batch_program() {
6817            if stream.is_some() {
6818                return Err(
6819                    "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
6820                            cannot express the SWA offset KV view)"
6821                        .into(),
6822                );
6823            }
6824            return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
6825        }
6826        if self.batched_serving_numeric_class() {
6827            return self.qwen35_verify_batch_layers(
6828                e,
6829                x,
6830                lo,
6831                hi,
6832                pos0,
6833                t,
6834                cache,
6835                ckpt.take(),
6836                stream,
6837                graphs,
6838            );
6839        }
6840        let n_embd = self.cfg.n_embd as usize;
6841        let eps = self.cfg.rms_eps;
6842        // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
6843        // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
6844        // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
6845        // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
6846        // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
6847        // residual the next layer needs) as its `res` output. Falls back to the separate add
6848        // when the next layer is off the fused-q8 path.
6849        let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
6850        for il in lo..hi {
6851            let layer = &self.layers[il];
6852            // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
6853            // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
6854            // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
6855            // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
6856            // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
6857            // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
6858            // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
6859            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
6860            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
6861            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
6862            // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
6863            // projections only; Linear mixer: the batched arm — the per-column fallback needs
6864            // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
6865            // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
6866            // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
6867            // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
6868            // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
6869            // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
6870            // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
6871            // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
6872            let lin_q8_only = match &layer.mixer {
6873                Mixer::Linear(la) => {
6874                    (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
6875                }
6876                Mixer::Full(_) if self.sliding_gated_moe_batch_program() => false,
6877                _ => true,
6878            };
6879            // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
6880            // a non-fused layer still performs the residual add.
6881            let taken = pending.take();
6882            let (h, h_q8) = if norm_fused && lin_q8_only {
6883                let pair = match taken {
6884                    // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
6885                    // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
6886                    Some((x1p, f1p)) => {
6887                        let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
6888                        let p = e.add_rms_norm_q8_1(
6889                            &x1p,
6890                            &f1p,
6891                            layer.attn_norm.float_data(),
6892                            &mut x2,
6893                            n_embd,
6894                            t,
6895                            eps,
6896                        )?;
6897                        x = x2;
6898                        p
6899                    }
6900                    None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
6901                };
6902                (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
6903            } else {
6904                if let Some((x1p, f1p)) = taken {
6905                    let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
6906                    e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
6907                    x = x2;
6908                }
6909                let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
6910                if norm_fused {
6911                    e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
6912                } else {
6913                    e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
6914                }
6915                (h, None)
6916            };
6917            let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
6918
6919            let mixed = match &layer.mixer {
6920                Mixer::Full(fa) => self.full_attn_verify(
6921                    e,
6922                    fa,
6923                    &h,
6924                    h_q8_ref,
6925                    pos_d,
6926                    t,
6927                    cache,
6928                    il,
6929                    stream.map(|(_, c)| c),
6930                )?,
6931                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
6932                Mixer::Linear(la) => {
6933                    // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
6934                    // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
6935                    // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
6936                    // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
6937                    // chained T=1 steps (bit-identical). Falls back to the sequential per-column
6938                    // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
6939                    // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
6940                    // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
6941                    // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
6942                    // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
6943                    // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
6944                    if (t >= 3 || (t == 2 && spec_m2()))
6945                        && mixer_fast
6946                        && e.uses_q8_1_fast(&la.ssm_out)
6947                    {
6948                        let want = ckpt.is_some();
6949                        let (out, stash) =
6950                            self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
6951                        if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
6952                            ck.gdn[il] = Some(st);
6953                        }
6954                        out
6955                    } else {
6956                        let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
6957                        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
6958                            if ckpt.is_some() && t >= 2 {
6959                                Some(Vec::with_capacity(t - 1))
6960                            } else {
6961                                None
6962                            };
6963                        for col in 0..t {
6964                            let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
6965                            let src = h.slice(col * n_embd..(col + 1) * n_embd);
6966                            e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
6967                            let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
6968                            e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
6969                            // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
6970                            // (pure dtod — cannot change any computed value). Last column skipped:
6971                            // rebuild targets are j <= t-1 columns.
6972                            if let Some(cs) = col_states.as_mut() {
6973                                if col + 1 < t {
6974                                    let rl = cache.recur[il].as_ref().unwrap();
6975                                    cs.push((
6976                                        e.clone_dtod(&rl.conv_state)?,
6977                                        e.clone_dtod(&rl.ssm_state)?,
6978                                    ));
6979                                }
6980                            }
6981                        }
6982                        if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
6983                            // ReplaySSM-assessment instrumentation (2026-07-30): the
6984                            // per-column clones are the only true state snapshots left in
6985                            // the verify (the batched path stashes INPUTS and replays).
6986                            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
6987                                static ONCE: std::sync::Once = std::sync::Once::new();
6988                                let bytes: usize =
6989                                    cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
6990                                ONCE.call_once(|| eprintln!(
6991                                    "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
6992                                    cs.len(), bytes as f64 / 1e6));
6993                            }
6994                            ck.cols[il] = Some(cs);
6995                        }
6996                        out
6997                    }
6998                }
6999            };
7000
7001            // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
7002            // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
7003            // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
7004            let ffn_fuse = match &layer.ffn {
7005                crate::hybrid::Ffn::Dense {
7006                    ffn_gate, ffn_up, ..
7007                } => {
7008                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
7009                        && e.uses_q8_1_fast(ffn_gate)
7010                        && e.uses_q8_1_fast(ffn_up)
7011                }
7012                crate::hybrid::Ffn::Moe(_) => false,
7013            };
7014            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
7015            // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
7016            // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
7017            // per-row m=1 program; kernel-check pins bit-identity vs the unfused
7018            // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
7019            // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
7020            // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
7021            // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
7022            // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
7023            // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
7024            // mirror decode's dispatch or spec self-consistency fails.
7025            let dense_lim = self.cfg.clamp_shexp_at(il as u32);
7026            let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
7027            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
7028            let mut z = e.zeros(0)?; // replaced below on the unfused arms
7029            let z_q8 = if fuse_q8 {
7030                Some(e.add_rms_norm_q8_1(
7031                    &x,
7032                    &mixed,
7033                    layer.post_attn_norm.float_data(),
7034                    &mut x1,
7035                    n_embd,
7036                    t,
7037                    eps,
7038                )?)
7039            } else {
7040                let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
7041                if ffn_fuse {
7042                    e.add(&x, &mixed, &mut x1, t * n_embd)?;
7043                    e.rms_norm_decode(
7044                        &x1,
7045                        layer.post_attn_norm.float_data(),
7046                        &mut zf,
7047                        n_embd,
7048                        t,
7049                        eps,
7050                    )?;
7051                } else {
7052                    e.add_rms_norm(
7053                        &x,
7054                        &mixed,
7055                        layer.post_attn_norm.float_data(),
7056                        &mut x1,
7057                        &mut zf,
7058                        n_embd,
7059                        t,
7060                        eps,
7061                    )?;
7062                }
7063                z = zf;
7064                None
7065            };
7066            // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
7067            // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
7068            // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
7069            let ffn_out = match &layer.ffn {
7070                crate::hybrid::Ffn::Dense {
7071                    ffn_gate,
7072                    ffn_up,
7073                    ffn_down,
7074                } => {
7075                    let n_ff = ffn_gate.out_features();
7076                    if let Some((zq, zd)) = z_q8.as_ref() {
7077                        // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
7078                        // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
7079                        // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
7080                        // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
7081                        // scale_inplace store, value-exact) — the exact m=1 decode epilogue
7082                        // structure at nrows=t.
7083                        let pair =
7084                            match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
7085                                Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
7086                                None => None,
7087                            };
7088                        let (gate, gs, up, us) = match pair {
7089                            Some(x4) => x4,
7090                            None => (
7091                                e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
7092                                1.0, // scale already applied inside _pre
7093                                e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
7094                                1.0,
7095                            ),
7096                        };
7097                        if e.uses_q8_1_fast(ffn_down) {
7098                            let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
7099                            e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
7100                        } else {
7101                            let mut act = vbuf(e, t * n_ff)?;
7102                            e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
7103                            e.matmul_decode_exact(ffn_down, &act, t)?
7104                        }
7105                    } else {
7106                        // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
7107                        // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
7108                        // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
7109                        // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
7110                        // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
7111                        let (gate, up) =
7112                            match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
7113                                Some(pair) => pair,
7114                                None => (
7115                                    e.matmul_decode_exact(ffn_gate, &z, t)?,
7116                                    e.matmul_decode_exact(ffn_up, &z, t)?,
7117                                ),
7118                            };
7119                        let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
7120                        Self::ffn_act_lim(
7121                            e,
7122                            &self.cfg,
7123                            &gate,
7124                            &up,
7125                            1.0,
7126                            1.0,
7127                            dense_lim,
7128                            &mut act,
7129                            t * n_ff,
7130                        )?;
7131                        e.matmul_decode_exact(ffn_down, &act, t)?
7132                    }
7133                }
7134                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
7135            };
7136            // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
7137            // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
7138            // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
7139            pending = Some((x1, ffn_out));
7140        }
7141        // RANGE's final add (no next norm INSIDE the range to fuse with; for the
7142        // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
7143        if let Some((x1p, f1p)) = pending.take() {
7144            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
7145            e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
7146            x = x2;
7147        }
7148        Ok(x)
7149    }
7150    /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
7151    /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
7152    /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
7153    /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
7154    /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
7155    /// ssm state exactly like T sequential decode steps.
7156    /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
7157    /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
7158    #[allow(clippy::too_many_arguments)]
7159    fn linear_attn_verify_t(
7160        &self,
7161        e: &Engine,
7162        la: &LinearAttnLayer,
7163        h: &CudaSlice<f32>,
7164        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
7165        t: usize,
7166        cache: &mut Cache,
7167        il: usize,
7168        want_stash: bool,
7169    ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
7170        let cfg = &self.cfg;
7171        let geometry = la.geometry;
7172        let d_state = geometry.key_head_dim as usize;
7173        let num_k = geometry.key_heads as usize;
7174        let num_v = geometry.value_heads as usize;
7175        let d_conv = geometry.conv_kernel as usize;
7176        let key_dim = d_state * num_k;
7177        let conv_dim = key_dim * 2 + geometry.value_head_dim as usize * num_v;
7178        let eps = cfg.rms_eps;
7179        let scale = 1.0 / (d_state as f32).sqrt();
7180
7181        // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
7182        // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
7183        // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
7184        // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
7185        // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
7186        // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
7187        // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
7188        // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
7189        // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
7190        // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
7191        // Bit-identical per (tensor,token,row) — see spec_fused_t().
7192        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
7193        // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
7194        // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
7195        // and feeds every projection; the caller guaranteed all four input projections are
7196        // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
7197        let h_q8_t = if h_q8.is_none()
7198            && spec_fused_t()
7199            && (2..=4).contains(&t)
7200            && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
7201                || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
7202        {
7203            Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
7204        } else {
7205            None
7206        };
7207        // one view: the caller's fused-norm q8 or this fn's own shared quantize.
7208        let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
7209            h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
7210        let (qkv_mixed, z) = {
7211            let mut fused = None;
7212            if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
7213                let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
7214                fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
7215            } else if let Some((hq, hd)) = hq8_any {
7216                if spec_fused_t() && (2..=4).contains(&t) {
7217                    fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
7218                }
7219            }
7220            match (fused, hq8_any) {
7221                (Some(pair), _) => pair,
7222                (None, Some((hq, hd))) if h_q8.is_some() => (
7223                    e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
7224                    e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
7225                ),
7226                (None, _) => (
7227                    e.matmul_decode_exact(&la.wqkv, h, t)?,
7228                    e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
7229                ),
7230            }
7231        };
7232        // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
7233        // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
7234        // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
7235        // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
7236        let (beta_raw, alpha) = if t == 1 {
7237            let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
7238            match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
7239                Some(((mut b, bs), (mut a, as_))) => {
7240                    if bs != 1.0 {
7241                        e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
7242                    }
7243                    if as_ != 1.0 {
7244                        e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
7245                    }
7246                    (b, a)
7247                }
7248                // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
7249                // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
7250                // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
7251                None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
7252                    Some((b, a)) => (b, a),
7253                    None => (
7254                        e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
7255                        e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
7256                    ),
7257                },
7258            }
7259        } else {
7260            // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
7261            // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
7262            let mut nvfp4_fused = None;
7263            let mut q8_fused = None;
7264            if let Some((hq, hd)) = hq8_any {
7265                if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
7266                    nvfp4_fused =
7267                        e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
7268                    if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
7269                        static ONCE: std::sync::Once = std::sync::Once::new();
7270                        ONCE.call_once(|| {
7271                            eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
7272                        });
7273                    }
7274                }
7275                if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
7276                    q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
7277                }
7278            }
7279            if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
7280                if bs != 1.0 {
7281                    e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
7282                }
7283                if as_ != 1.0 {
7284                    e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
7285                }
7286                (b, a)
7287            } else if let Some(pair) = q8_fused {
7288                pair
7289            } else {
7290                match hq8_any {
7291                    Some((hq, hd)) if h_q8.is_some() => (
7292                        e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
7293                        e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
7294                    ),
7295                    _ => (
7296                        e.matmul_decode_exact(&la.ssm_beta, h, t)?,
7297                        e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
7298                    ),
7299                }
7300            }
7301        };
7302
7303        // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
7304        // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
7305        let rl = cache.recur[il].as_mut().unwrap();
7306        let mut conv_out = e.uninit(conv_dim * t)?;
7307        e.ssm_conv1d_tm_state(
7308            &qkv_mixed,
7309            &mut rl.conv_state,
7310            la.ssm_conv1d.float_data(),
7311            &mut conv_out,
7312            conv_dim,
7313            t,
7314            d_conv,
7315        )?;
7316
7317        // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
7318        let mut q_g = e.uninit(d_state * num_v * t)?;
7319        let mut k_g = e.uninit(d_state * num_v * t)?;
7320        let mut v_g = e.uninit(d_state * num_v * t)?;
7321        e.qkv_to_gdn_repack(
7322            &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
7323        )?;
7324        let mut q_l2 = e.uninit(d_state * num_v * t)?;
7325        e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
7326        let mut k_l2 = e.uninit(d_state * num_v * t)?;
7327        e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
7328        let mut beta = e.uninit(t * num_v)?;
7329        e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
7330        let mut g_log = e.uninit(t * num_v)?;
7331        e.gdn_glog(
7332            &alpha,
7333            la.ssm_dt.float_data(),
7334            la.ssm_a.float_data(),
7335            &mut g_log,
7336            num_v,
7337            t,
7338        )?;
7339
7340        // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
7341        // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
7342        let mut o = e.uninit(d_state * num_v * t)?;
7343        {
7344            let crate::cache::RecurLayer {
7345                ssm_state,
7346                ssm_state_alt,
7347                ..
7348            } = rl;
7349            e.gdn_scan_s128(
7350                &q_l2,
7351                &k_l2,
7352                &v_g,
7353                &g_log,
7354                &beta,
7355                ssm_state,
7356                ssm_state_alt,
7357                &mut o,
7358                num_v,
7359                t,
7360                scale,
7361            )?;
7362        }
7363        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
7364
7365        // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
7366        // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
7367        // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
7368        // T-wide launch is the per-row program; kernel-check pins bit-identity vs
7369        // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
7370        // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
7371        let out = if e.uses_q8_1_fast(&la.ssm_out) {
7372            let (gq, gd) =
7373                e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
7374            e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
7375        } else {
7376            let mut gn = e.uninit(d_state * num_v * t)?;
7377            e.gated_rmsnorm(
7378                &o,
7379                la.ssm_norm.float_data(),
7380                &z,
7381                &mut gn,
7382                d_state,
7383                num_v * t,
7384                eps,
7385            )?;
7386            // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
7387            // would fall to dp4a with a different FP reduction order — same class of bug as
7388            // the input projs).
7389            e.matmul_decode_exact(&la.ssm_out, &gn, t)?
7390        };
7391        let stash = if want_stash {
7392            Some(GdnStash {
7393                qkv_mixed,
7394                q_l2,
7395                k_l2,
7396                v_g,
7397                g_log,
7398                beta,
7399            })
7400        } else {
7401            None
7402        };
7403        Ok((out, stash))
7404    }
7405
7406    /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
7407    /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
7408    /// - Full-attn KV: truncate both the owning-stage shadow and every TP rank to snapshot + j.
7409    ///   The verify's appended rows for those columns are bit-identical to what an eager T=1
7410    ///   chain writes (the decode-exact contract the verify-probe gates), so keeping them ==
7411    ///   replaying them.
7412    /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
7413    ///   columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
7414    ///   snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
7415    ///   registers and writes it once at the end, so iterations 0..j-1 are independent of T:
7416    ///   bit-identical to the verify's own state after j tokens == the eager chain state.
7417    /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
7418    /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
7419    fn commit_verified_prefix(
7420        &self,
7421        e: &Engine,
7422        cache: &mut Cache,
7423        snap: &crate::cache::CacheSnapshot,
7424        ckpt: &VerifyCkpt,
7425        j: usize,
7426        kv_lens_done: bool,
7427        dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
7428    ) -> Result<(), Box<dyn std::error::Error>> {
7429        // GDN geometry derives lazily inside recurrent-layer arms. Full-attention plans carry no
7430        // recurrent state and must never be forced through a synthetic SSM geometry.
7431        // Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1): the per-column-arm restores
7432        // are 2 tiny D2D copies per linear layer (~96 dispatches/partial round on the q38
7433        // route). When every cols-arm layer shares uniform state sizes (single ssm cfg —
7434        // always true today), batch them into two `copy_batch_uniform_f32` launches. Bytes,
7435        // buffers and stream order are identical to the per-layer memcpy sequence; the
7436        // kernel-rebuild (gdn-stash) arm below is untouched. MEMRA_STATE_COPY_BATCH=0 reverts.
7437        let mut batched_cols = false;
7438        if state_copy_batch_on() && dev_j.is_none() {
7439            use cudarc::driver::DevicePtr;
7440            let s = &e.gpu.stream();
7441            let mut conv_pairs: Vec<(u64, u64)> = Vec::new();
7442            let mut ssm_pairs: Vec<(u64, u64)> = Vec::new();
7443            let (mut conv_words, mut ssm_words) = (0usize, 0usize);
7444            let mut uniform = true;
7445            for il in 0..self.layers.len() {
7446                let Some(rl) = cache.recur[il].as_ref() else {
7447                    continue;
7448                };
7449                if ckpt.gdn[il].is_some() {
7450                    continue; // kernel-rebuild arm restores below, per layer
7451                }
7452                let Some(cols) = &ckpt.cols[il] else {
7453                    continue; // missing-ckpt error surfaces in the main loop
7454                };
7455                let (c, st) = &cols[j - 1];
7456                if conv_pairs.is_empty() {
7457                    conv_words = c.len();
7458                    ssm_words = st.len();
7459                } else if c.len() != conv_words || st.len() != ssm_words {
7460                    uniform = false;
7461                    break;
7462                }
7463                let (pc, _g0) = c.device_ptr(s);
7464                let (dc, _g1) = rl.conv_state.device_ptr(s);
7465                let (ps, _g2) = st.device_ptr(s);
7466                let (ds, _g3) = rl.ssm_state.device_ptr(s);
7467                conv_pairs.push((pc as u64, dc as u64));
7468                ssm_pairs.push((ps as u64, ds as u64));
7469            }
7470            if uniform && !conv_pairs.is_empty() {
7471                let n = conv_pairs.len();
7472                let mut t = vec![0u64; 2 * n];
7473                for (k, &(src, dst)) in conv_pairs.iter().enumerate() {
7474                    t[k] = src;
7475                    t[n + k] = dst;
7476                }
7477                let conv_t = e.htod_u64(&t)?;
7478                for (k, &(src, dst)) in ssm_pairs.iter().enumerate() {
7479                    t[k] = src;
7480                    t[n + k] = dst;
7481                }
7482                let ssm_t = e.htod_u64(&t)?;
7483                e.copy_batch_uniform_f32(&conv_t, n, conv_words)?;
7484                e.copy_batch_uniform_f32(&ssm_t, n, ssm_words)?;
7485                batched_cols = true;
7486            }
7487        }
7488        rewind_tp_kv_verified_prefix(&mut cache.tp_kv, &snap.tp_kv_len, j)?;
7489        for il in 0..self.layers.len() {
7490            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
7491                kvl.len = saved + j;
7492                // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
7493                if !kv_lens_done {
7494                    e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
7495                }
7496            }
7497            if let Some(rl) = cache.recur[il].as_mut() {
7498                let Mixer::Linear(linear) = &self.layers[il].mixer else {
7499                    return Err(format!("recurrent cache layer {il} has no GDN plan").into());
7500                };
7501                let geometry = linear.geometry;
7502                let d_state = geometry.key_head_dim as usize;
7503                let num_k = geometry.key_heads as usize;
7504                let num_v = geometry.value_heads as usize;
7505                let d_conv = geometry.conv_kernel as usize;
7506                let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
7507                let scale = 1.0 / (d_state as f32).sqrt();
7508                if let Some(st) = &ckpt.gdn[il] {
7509                    let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
7510                    let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
7511                    if let Some((acc, base, t_v)) = dev_j {
7512                        // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
7513                        e.ssm_conv_ring_rebuild_dc(
7514                            &st.qkv_mixed,
7515                            ring_old,
7516                            &mut rl.conv_state,
7517                            conv_dim,
7518                            acc,
7519                            base,
7520                            t_v,
7521                            d_conv,
7522                        )?;
7523                        let mut o = e.uninit(d_state * num_v * j.max(1))?;
7524                        e.gdn_scan_s128_dc(
7525                            &st.q_l2,
7526                            &st.k_l2,
7527                            &st.v_g,
7528                            &st.g_log,
7529                            &st.beta,
7530                            state_in,
7531                            &mut rl.ssm_state,
7532                            &mut o,
7533                            num_v,
7534                            acc,
7535                            base,
7536                            t_v,
7537                            scale,
7538                        )?;
7539                    } else {
7540                        e.ssm_conv_ring_rebuild(
7541                            &st.qkv_mixed,
7542                            ring_old,
7543                            &mut rl.conv_state,
7544                            conv_dim,
7545                            j,
7546                            d_conv,
7547                        )?;
7548                        let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
7549                        e.gdn_scan_s128(
7550                            &st.q_l2,
7551                            &st.k_l2,
7552                            &st.v_g,
7553                            &st.g_log,
7554                            &st.beta,
7555                            state_in,
7556                            &mut rl.ssm_state,
7557                            &mut o,
7558                            num_v,
7559                            j,
7560                            scale,
7561                        )?;
7562                    }
7563                } else if let Some(cols) = &ckpt.cols[il] {
7564                    if !batched_cols {
7565                        let (c, s) = &cols[j - 1];
7566                        e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
7567                        e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
7568                    }
7569                } else {
7570                    return Err(
7571                        "commit_verified_prefix: verify ckpt missing for linear layer".into(),
7572                    );
7573                }
7574            }
7575        }
7576        cache.pos = snap.pos + j;
7577        Ok(())
7578    }
7579
7580    /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
7581    /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
7582    fn commit_verified_prefix_stream(
7583        &self,
7584        e: &Engine,
7585        cache: &mut Cache,
7586        snap: &crate::cache::CacheSnapshot,
7587        ckpt: &VerifyCkpt,
7588        acc: &CudaSlice<u32>,
7589        base: usize,
7590        t_v: usize,
7591    ) -> Result<(), Box<dyn std::error::Error>> {
7592        for il in 0..self.layers.len() {
7593            if let Some(rl) = cache.recur[il].as_mut() {
7594                let Mixer::Linear(linear) = &self.layers[il].mixer else {
7595                    return Err(format!("recurrent cache layer {il} has no GDN plan").into());
7596                };
7597                let geometry = linear.geometry;
7598                let d_state = geometry.key_head_dim as usize;
7599                let num_k = geometry.key_heads as usize;
7600                let num_v = geometry.value_heads as usize;
7601                let d_conv = geometry.conv_kernel as usize;
7602                let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
7603                let scale = 1.0 / (d_state as f32).sqrt();
7604                let st = ckpt.gdn[il]
7605                    .as_ref()
7606                    .ok_or("stream restore: batched-linear stash missing")?;
7607                let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
7608                let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
7609                e.ssm_conv_ring_rebuild_dc(
7610                    &st.qkv_mixed,
7611                    ring_old,
7612                    &mut rl.conv_state,
7613                    conv_dim,
7614                    acc,
7615                    base,
7616                    t_v,
7617                    d_conv,
7618                )?;
7619                let mut o = e.uninit(d_state * num_v * t_v)?;
7620                e.gdn_scan_s128_dc(
7621                    &st.q_l2,
7622                    &st.k_l2,
7623                    &st.v_g,
7624                    &st.g_log,
7625                    &st.beta,
7626                    state_in,
7627                    &mut rl.ssm_state,
7628                    &mut o,
7629                    num_v,
7630                    acc,
7631                    base,
7632                    t_v,
7633                    scale,
7634                )?;
7635            }
7636        }
7637        Ok(())
7638    }
7639
7640    /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
7641    /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
7642    /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
7643    /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
7644    /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
7645    pub fn decode_step_t_aux2(
7646        &self,
7647        e: &Engine,
7648        tokens: &[u32],
7649        pos0: usize,
7650        cache: &mut Cache,
7651        aux_layers: &[usize],
7652        pred_col: Option<usize>,
7653    ) -> Result<
7654        (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
7655        Box<dyn std::error::Error>,
7656    > {
7657        let cfg = &self.cfg;
7658        let n_embd = cfg.n_embd as usize;
7659        let eps = cfg.rms_eps;
7660        let t = tokens.len();
7661        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
7662        let pos_d = e.htod_i32(&pos_vec)?;
7663        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
7664        let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
7665        let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
7666        let want_pred = pred_col.is_some();
7667
7668        for (il, layer) in self.layers.iter().enumerate() {
7669            // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
7670            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
7671            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
7672            let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
7673            if norm_fused {
7674                e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7675            } else {
7676                e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7677            }
7678            let mixed = match &layer.mixer {
7679                Mixer::Full(fa) => {
7680                    self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
7681                }
7682                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
7683                Mixer::Linear(la) => {
7684                    let mut out = e.zeros(t * n_embd)?;
7685                    for col in 0..t {
7686                        let mut h_col = e.zeros(n_embd)?;
7687                        let src = h.slice(col * n_embd..(col + 1) * n_embd);
7688                        e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
7689                        let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
7690                        e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
7691                    }
7692                    out
7693                }
7694            };
7695            let ffn_fuse = match &layer.ffn {
7696                crate::hybrid::Ffn::Dense {
7697                    ffn_gate, ffn_up, ..
7698                } => {
7699                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
7700                        && e.uses_q8_1_fast(ffn_gate)
7701                        && e.uses_q8_1_fast(ffn_up)
7702                }
7703                crate::hybrid::Ffn::Moe(_) => false,
7704            };
7705            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
7706            let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
7707            if ffn_fuse {
7708                e.add(&x, &mixed, &mut x1, t * n_embd)?;
7709                e.rms_norm_decode(
7710                    &x1,
7711                    layer.post_attn_norm.float_data(),
7712                    &mut z,
7713                    n_embd,
7714                    t,
7715                    eps,
7716                )?;
7717            } else {
7718                e.add_rms_norm(
7719                    &x,
7720                    &mixed,
7721                    layer.post_attn_norm.float_data(),
7722                    &mut x1,
7723                    &mut z,
7724                    n_embd,
7725                    t,
7726                    eps,
7727                )?;
7728            }
7729            let ffn_out = match &layer.ffn {
7730                crate::hybrid::Ffn::Dense {
7731                    ffn_gate,
7732                    ffn_up,
7733                    ffn_down,
7734                } => {
7735                    let n_ff = ffn_gate.out_features();
7736                    let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
7737                    let up = e.matmul_decode_exact(ffn_up, &z, t)?;
7738                    let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
7739                    // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
7740                    Self::ffn_act_lim(
7741                        e,
7742                        &self.cfg,
7743                        &gate,
7744                        &up,
7745                        1.0,
7746                        1.0,
7747                        self.cfg.clamp_shexp_at(il as u32),
7748                        &mut act,
7749                        t * n_ff,
7750                    )?;
7751                    e.matmul_decode_exact(ffn_down, &act, t)?
7752                }
7753                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
7754            };
7755            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
7756            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
7757            if aux_layers.contains(&il) {
7758                let mut a = e.zeros(n_embd)?;
7759                e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
7760                aux_last.push(a);
7761                if let Some(pc) = pred_col {
7762                    let mut ap = e.zeros(n_embd)?;
7763                    e.copy_view_into(
7764                        &mut ap,
7765                        0,
7766                        &x2.slice(pc * n_embd..(pc + 1) * n_embd),
7767                        n_embd,
7768                    )?;
7769                    aux_pred.push(ap);
7770                }
7771            }
7772            x = x2;
7773        }
7774        let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
7775        e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
7776        let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
7777        let host = e.dtoh(&logits)?;
7778        cache.pos += t;
7779        Ok((
7780            host,
7781            aux_last,
7782            if want_pred { Some(aux_pred) } else { None },
7783        ))
7784    }
7785
7786    /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
7787    /// `step35_decode_attn`.
7788    ///
7789    /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
7790    /// the eager decode would have computed for the same tokens; that is what makes greedy spec
7791    /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
7792    /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
7793    /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
7794    /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
7795    /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
7796    /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
7797    /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
7798    /// position of each query row. A batched twin would have to reproduce all of that AND the
7799    /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
7800    /// take one `base_len`, not a per-row offset).
7801    ///
7802    /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
7803    /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
7804    /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
7805    /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
7806    /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
7807    /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
7808    /// step35 twin is a perf lane's job and must be gated against this arm.
7809    ///
7810    /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
7811    /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
7812    /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
7813    /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
7814    /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
7815    #[allow(clippy::too_many_arguments)]
7816    fn step35_verify(
7817        &self,
7818        e: &Engine,
7819        fa: &FullAttnLayer,
7820        h: &CudaSlice<f32>,
7821        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
7822        t: usize,
7823        cache: &mut Cache,
7824        il: usize,
7825    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7826        let n_embd = self.cfg.n_embd as usize;
7827        // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
7828        // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
7829        // site by the sliding-gated-MoE `Mixer::Full(_) => false` arm of
7830        // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
7831        // cannot regress it into silently reading an empty buffer.
7832        assert_eq!(
7833            h.len(),
7834            t * n_embd,
7835            "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
7836             fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
7837            h_q8.is_some()
7838        );
7839        // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
7840        // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
7841        // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
7842        // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
7843        // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
7844        // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
7845        let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
7846        for r in 0..t {
7847            // Absolute position of this query row. `cache.pos` is the committed length at round
7848            // start and every row before r has already been appended by this loop, so the r-th
7849            // verify token sits at cache.pos + r — the same position eager decode would give it.
7850            let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
7851            let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
7852            e.copy_view_into(
7853                &mut h_row,
7854                0,
7855                &h.slice(r * n_embd..(r + 1) * n_embd),
7856                n_embd,
7857            )?;
7858            // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
7859            // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
7860            let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
7861            debug_assert_eq!(
7862                o.len(),
7863                n_embd,
7864                "step35_decode_attn returns post-wo [n_embd]"
7865            );
7866            e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
7867        }
7868        Ok(out)
7869    }
7870
7871    /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
7872    /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
7873    /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
7874    #[allow(clippy::too_many_arguments)]
7875    fn full_attn_verify(
7876        &self,
7877        e: &Engine,
7878        fa: &FullAttnLayer,
7879        h: &CudaSlice<f32>,
7880        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
7881        pos_d: &CudaSlice<i32>,
7882        t: usize,
7883        cache: &mut Cache,
7884        il: usize,
7885        stream_ctr: Option<&CudaSlice<i32>>,
7886    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7887        // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
7888        // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
7889        // its own arm. A verify that silently computes different attention than decode defeats the
7890        // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
7891        // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
7892        // shape and not laziness.
7893        if self.sliding_gated_moe_batch_program() {
7894            if stream_ctr.is_some() {
7895                return Err(
7896                    "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
7897                            cannot express the SWA offset KV view; same root cause as the dc \
7898                            decode refusal) — run spec without the stream arm"
7899                        .into(),
7900                );
7901            }
7902            return self.step35_verify(e, fa, h, h_q8, t, cache, il);
7903        }
7904        let cfg = &self.cfg;
7905        let geometry = cfg.full_attention_geometry_at(il as u32);
7906        let n_head = geometry.n_head as usize;
7907        let n_head_kv = geometry.n_head_kv as usize;
7908        let head_dim = geometry.head_dim_k as usize;
7909        let eps = cfg.rms_eps;
7910        let scale = geometry.attention_scale();
7911        let n_embd = cfg.n_embd as usize;
7912
7913        // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
7914        // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
7915        // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
7916        // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
7917        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
7918        // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
7919        // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
7920        // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
7921        let (qf, mut k, v) = {
7922            let mut fused = None;
7923            let qkv_fast =
7924                e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
7925            if t == 1 && qkv_fast {
7926                let (hq_o, hd_o);
7927                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
7928                    Some(p) => p,
7929                    None => {
7930                        (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
7931                        (&hq_o, &hd_o)
7932                    }
7933                };
7934                fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
7935            } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
7936                // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
7937                // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
7938                // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
7939                let (hq_o, hd_o);
7940                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
7941                    Some(p) => p,
7942                    None => {
7943                        (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
7944                        (&hq_o, &hd_o)
7945                    }
7946                };
7947                fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
7948            }
7949            match (fused, h_q8) {
7950                (Some(triple), _) => triple,
7951                // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
7952                // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
7953                (None, Some((hq, hd))) if qkv_fast => (
7954                    e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
7955                    e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
7956                    e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
7957                ),
7958                (None, _) => (
7959                    e.matmul_decode_exact(&fa.wq, h, t)?,
7960                    e.matmul_decode_exact(&fa.wk, h, t)?,
7961                    e.matmul_decode_exact(&fa.wv, h, t)?,
7962                ),
7963            }
7964        };
7965        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
7966        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
7967        let (mut q, gate) = if gated {
7968            let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
7969            let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
7970            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
7971            (q, Some(gate))
7972        } else {
7973            (qf, None)
7974        };
7975
7976        let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
7977        e.rms_norm(
7978            &q,
7979            fa.q_norm.float_data(),
7980            &mut qn,
7981            head_dim,
7982            n_head * t,
7983            eps,
7984        )?;
7985        q = qn;
7986        let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
7987        e.rms_norm(
7988            &k,
7989            fa.k_norm.float_data(),
7990            &mut kn,
7991            head_dim,
7992            n_head_kv * t,
7993            eps,
7994        )?;
7995        k = kn;
7996        let rope_dims = geometry.n_rot as usize;
7997        e.rope_neox(
7998            &mut q,
7999            pos_d,
8000            head_dim,
8001            rope_dims,
8002            n_head,
8003            t,
8004            geometry.rope_base,
8005            1.0,
8006        )?;
8007        e.rope_neox(
8008            &mut k,
8009            pos_d,
8010            head_dim,
8011            rope_dims,
8012            n_head_kv,
8013            t,
8014            geometry.rope_base,
8015            1.0,
8016        )?;
8017
8018        // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
8019        // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
8020        let kvl = cache.kv[il].as_mut().unwrap();
8021        let (kv_dim_k, kv_dim_v, ktb, vtb) =
8022            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
8023        if let Some(ctr) = stream_ctr {
8024            // stream: ONE batched append at the device counter (rows kernel = the per-view warp
8025            // math on a (block, token) grid, documented byte-identical); host len is a stale
8026            // LOWER BOUND under pre-issue (drain reconciles it).
8027            e.append_kv_quantized_rows_dc(
8028                &k,
8029                &v,
8030                &mut kvl.k,
8031                &mut kvl.v,
8032                ctr,
8033                t,
8034                kv_dim_k,
8035                kv_dim_v,
8036                ktb,
8037                vtb,
8038                crate::Engine::kv_fp8_on(),
8039            )?;
8040        } else {
8041            for i in 0..t {
8042                let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
8043                let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
8044                e.append_kv_quantized_view(
8045                    &k_row,
8046                    &v_row,
8047                    &mut kvl.k,
8048                    &mut kvl.v,
8049                    kvl.len + i,
8050                    kv_dim_k,
8051                    kv_dim_v,
8052                    ktb,
8053                    vtb,
8054                    crate::Engine::kv_fp8_on(),
8055                )?;
8056            }
8057            kvl.len += t;
8058        }
8059
8060        // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
8061        // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
8062        // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
8063        // which changes FP summation order and can flip argmax at tight logit margins. Query row r
8064        // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
8065        // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
8066        // keys. The verify appends all T tokens first but bounds the key range per row.
8067        //
8068        // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
8069        // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
8070        // per-row program for all T rows (grid.z = row, per-row n_splits from the same
8071        // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
8072        // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
8073        // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
8074        // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
8075        // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
8076        let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
8077        let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
8078        // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
8079        // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
8080        // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
8081        // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
8082        // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
8083        // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
8084        // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
8085        // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
8086        if let Some(ctr) = stream_ctr {
8087            // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
8088            // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
8089            // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
8090            let upper = kvl.len + t + 64;
8091            let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
8092            let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
8093            e.fa_decode_rows_dc(
8094                &q,
8095                &k_view,
8096                &v_view,
8097                &mut attn,
8098                head_dim,
8099                n_head,
8100                n_head_kv,
8101                ctr,
8102                upper.min(cache.max_ctx),
8103                t,
8104                scale,
8105                ktb,
8106                vtb,
8107                0,
8108                false,
8109            )?;
8110        } else if spec_lean() && t == 1 {
8111            let t_kv = base_len + 1;
8112            let k_view = e.view_u8(&kvl.k, t_kv * ktb);
8113            let v_view = e.view_u8(&kvl.v, t_kv * vtb);
8114            e.fa_decode_kvmod(
8115                &q,
8116                &k_view,
8117                &v_view,
8118                &mut attn,
8119                head_dim,
8120                n_head,
8121                n_head_kv,
8122                t_kv,
8123                scale,
8124                ktb,
8125                vtb,
8126                crate::Engine::kv_fp8_on(),
8127            )?;
8128        } else if e.fa_rows_eligible(base_len, head_dim) {
8129            let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
8130            let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
8131            e.fa_decode_rows(
8132                &q,
8133                &k_view,
8134                &v_view,
8135                &mut attn,
8136                head_dim,
8137                n_head,
8138                n_head_kv,
8139                base_len,
8140                t,
8141                scale,
8142                ktb,
8143                vtb,
8144                None,
8145                false,
8146                crate::Engine::kv_fp8_on(),
8147                None,
8148            )?;
8149        } else {
8150            for r in 0..t {
8151                let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
8152                let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
8153                let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
8154                // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
8155                let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
8156                let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
8157                e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
8158                let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
8159                e.fa_decode_kvmod(
8160                    &q_row,
8161                    &k_view_r,
8162                    &v_view_r,
8163                    &mut attn_row,
8164                    head_dim,
8165                    n_head,
8166                    n_head_kv,
8167                    t_kv_r,
8168                    scale,
8169                    ktb,
8170                    vtb,
8171                    crate::Engine::kv_fp8_on(),
8172                )?;
8173                e.copy_into(
8174                    &mut attn,
8175                    r * n_head * head_dim,
8176                    &attn_row,
8177                    n_head * head_dim,
8178                )?;
8179            }
8180        }
8181
8182        let attn_g = match &gate {
8183            Some(gate) => {
8184                let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
8185                e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
8186                let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
8187                e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
8188                ag
8189            }
8190            None => attn,
8191        };
8192        // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
8193        // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
8194        Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
8195    }
8196
8197    /// Context-linear bytes for a plain serving session's trunk cache.
8198    pub fn plain_session_kv_bytes_per_token(&self) -> usize {
8199        crate::cache::cache_bytes_per_token_for_plan(
8200            &self.cfg,
8201            &self.plan,
8202            0,
8203            self.plan.layers.len(),
8204        )
8205    }
8206
8207    /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
8208    pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
8209        (
8210            self.plain_session_kv_bytes_per_token(),
8211            crate::cache::cache_ring_bytes_per_token_for_plan(
8212                &self.cfg,
8213                &self.plan,
8214                0,
8215                self.plan.layers.len(),
8216            ),
8217            crate::cache::cache_ring_row_cap_for_plan(&self.plan),
8218        )
8219    }
8220
8221    /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
8222    /// scratch. With no MTP head this equals the plain coefficient.
8223    pub fn spec_session_kv_bytes_per_token(&self) -> usize {
8224        let scratch = self
8225            .mtp
8226            .iter()
8227            .chain(self.mtp_extra.iter())
8228            .map(|mtp| {
8229                let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
8230                k + v
8231            })
8232            .sum::<usize>();
8233        self.plain_session_kv_bytes_per_token()
8234            .saturating_add(scratch)
8235    }
8236
8237    /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
8238    /// capped by the same SWA ring rows as the trunk.
8239    pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
8240        let total = self.spec_session_kv_bytes_per_token();
8241        let (_, mut ring, rows) = self.plain_session_kv_shape();
8242        if rows > 0 {
8243            ring = ring.saturating_add(
8244                self.mtp
8245                    .iter()
8246                    .chain(self.mtp_extra.iter())
8247                    .map(|mtp| {
8248                        let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
8249                        k + v
8250                    })
8251                    .sum::<usize>(),
8252            );
8253        }
8254        (total, ring, rows)
8255    }
8256
8257    /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
8258    /// the NextN head to draft K tokens then verifies them in one batched target forward.
8259    /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
8260    /// acceptance rate. `k` = draft length per round.
8261    ///
8262    /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
8263    /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
8264    /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
8265    /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
8266    /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
8267    /// captured graph references is event-free; the spec loop is strictly single-stream.
8268    /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
8269    /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
8270    /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
8271    /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
8272    /// generate_spec_inner2.
8273    /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
8274    /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
8275    /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
8276    /// hybrid linear-attn states are in-place (no position index), so a session can extend but
8277    /// never rewind — `committed` is the exact token list whose state the caches hold (includes
8278    /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
8279    pub fn new_session(
8280        &self,
8281        e: &Engine,
8282        max_ctx: usize,
8283    ) -> Result<SpecSession, Box<dyn std::error::Error>> {
8284        Ok(SpecSession {
8285            // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
8286            // is the SERVING spec-session path, and with the ppN door open across two cards a
8287            // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
8288            // round — the wrong-card class already fixed on the two batched serving paths
8289            // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
8290            // branch, same allocations), so single-device behavior is byte-unchanged.
8291            cache: crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?,
8292            scratch: self.new_mtp_scratch(e, max_ctx)?,
8293            committed: Vec::new(),
8294            last_h: None,
8295            next_pred: None,
8296            sctr: 0,
8297            uctr: 0,
8298            draft_ctx: None,
8299            pending_tok: None,
8300            turn_ckpt: None,
8301            telem: SpecTelemetryCounters::default(),
8302            capture_at: None,
8303            boundary_captures: Vec::new(),
8304            ckpt_at: None,
8305        })
8306    }
8307
8308    /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
8309    /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
8310    /// SpecSession around a trunk cache the worker already restored from a prefix-cache
8311    /// entry, re-installing the entry's published draft plane as the MTP scratch rows
8312    /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
8313    /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
8314    /// worker always receives a fully-warm continuation session (committed = whole
8315    /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
8316    /// boundary logits on the empty-suffix shape).
8317    ///
8318    /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
8319    /// gate): the identity target for a converted hit is the PLAIN hit serving the same
8320    /// request, and plain feeds a carried suffix via eager `decode_step` below
8321    /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
8322    /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
8323    /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
8324    /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
8325    /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
8326    /// burst prime.
8327    ///
8328    /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
8329    /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
8330    /// EXACTLY the rule the cold burst entry applies to its own first token from the same
8331    /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
8332    /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
8333    /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
8334    /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
8335    /// cold session draws from the identical row at counter 0 and then runs its rounds from
8336    /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
8337    /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
8338    /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
8339    /// span the session: `committed` here is the WHOLE prompt, so the restored session's
8340    /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
8341    ///
8342    /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
8343    /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
8344    /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
8345    /// and are never routed here.
8346    ///
8347    /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
8348    /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
8349    /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
8350    /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
8351    /// entry stays published for the next request.
8352    #[allow(clippy::too_many_arguments)]
8353    pub fn spec_session_from_restored(
8354        &self,
8355        e: &Engine,
8356        mut cache: Cache,
8357        prefix: Vec<u32>,
8358        suffix: &[u32],
8359        draft_k: &CudaSlice<u8>,
8360        draft_v: &CudaSlice<u8>,
8361        draft_k_tok_bytes: usize,
8362        draft_v_tok_bytes: usize,
8363        draft_len: usize,
8364        last_h: &[f32],
8365        // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
8366        // when a suffix follows — the feed's own logits are the boundary then.
8367        boundary_logits: &[f32],
8368        // The request's sampler, or None for greedy. Owned here so the seed rule lives in
8369        // ONE place instead of being half-applied by the worker.
8370        sampling: Option<SpecSampling>,
8371        require_anchor: bool,
8372        max_ctx: usize,
8373        // STABLE-BOUNDARY REPUBLICATION (lane/frspec-multiturn-cache, 2026-08-21): ABSOLUTE
8374        // prompt position to split the suffix feed at and capture the extended-entry
8375        // publication + this session's `turn_ckpt` — the worker's stable pre-generation
8376        // boundary (`plain_checkpoint_boundary`). None = legacy prompt-end republication.
8377        // WHY: the prompt-end capture below includes the template's live generation header
8378        // (`<|im_start|>assistant\n<think>\n`), which the next turn's re-render replaces, so
8379        // for a hybrid (whole-entry restores only) every extended entry's last ~2 tokens
8380        // diverged from every future prompt and the hit boundary FROZE at the first
8381        // lcp-split entry forever (measured: cached 6811 of 38228 by turn 8, B4).
8382        republish_at: Option<usize>,
8383    ) -> Result<SpecSession, (Option<Cache>, String)> {
8384        let pos = prefix.len();
8385        let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
8386            Err((Some(cache), msg))
8387        };
8388        if self.mtp.is_none() {
8389            return fail(cache, "no MTP head attached (nothing to draft with)".into());
8390        }
8391        if pos == 0 {
8392            return fail(cache, "empty committed prefix".into());
8393        }
8394        if cache.pos != pos {
8395            let msg = format!(
8396                "restored cache pos {} != restored prefix len {pos}",
8397                cache.pos
8398            );
8399            return fail(cache, msg);
8400        }
8401        if draft_len != pos {
8402            return fail(
8403                cache,
8404                format!("draft plane len {draft_len} != restored prefix len {pos}"),
8405            );
8406        }
8407        if pos + suffix.len() >= max_ctx {
8408            return fail(
8409                cache,
8410                format!(
8411                    "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
8412                    pos + suffix.len(),
8413                ),
8414            );
8415        }
8416        let mut scratch = match MtpScratch::new(
8417            e,
8418            &self.cfg,
8419            &self.plan,
8420            max_ctx,
8421            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
8422        ) {
8423            Ok(s) => s,
8424            Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
8425        };
8426        if scratch.kv.ring.is_some() {
8427            return fail(
8428                cache,
8429                "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
8430            );
8431        }
8432        if scratch.kv.k_tok_bytes != draft_k_tok_bytes
8433            || scratch.kv.v_tok_bytes != draft_v_tok_bytes
8434        {
8435            return fail(
8436                cache,
8437                format!(
8438                    "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
8439                     {}/{} bytes/token (stale entry across a format change)",
8440                    scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
8441                ),
8442            );
8443        }
8444        if pos > scratch.cap {
8445            return fail(
8446                cache,
8447                format!(
8448                    "draft plane rows {pos} exceed scratch capacity {}",
8449                    scratch.cap
8450                ),
8451            );
8452        }
8453        let kb = pos * draft_k_tok_bytes;
8454        let vb = pos * draft_v_tok_bytes;
8455        if draft_k.len() < kb || draft_v.len() < vb {
8456            return fail(
8457                cache,
8458                format!(
8459                    "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
8460                    draft_k.len(),
8461                    draft_v.len(),
8462                ),
8463            );
8464        }
8465        if kb > 0 {
8466            if let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb) {
8467                return fail(cache, format!("draft K restore copy failed: {err}"));
8468            }
8469        }
8470        if vb > 0 {
8471            if let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb) {
8472                return fail(cache, format!("draft V restore copy failed: {err}"));
8473            }
8474        }
8475        if let Err(err) = scratch.set_len(e, pos) {
8476            return fail(cache, format!("draft scratch len set failed: {err}"));
8477        }
8478        let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
8479            // anchor upload failure is acceptance-only when a suffix feed follows (fill
8480            // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
8481            // burst entry asserts committed + last_h + next_pred) — the caller says which.
8482            e.htod(last_h).ok()
8483        } else {
8484            None
8485        };
8486        if require_anchor && last_h_dev.is_none() {
8487            return fail(
8488                cache,
8489                "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
8490            );
8491        }
8492        let mut committed = prefix;
8493        // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
8494        // what the empty-suffix continuation assert in the burst entry requires.
8495        let next_pred;
8496        // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
8497        // consumes counter 0 and leaves 1, which is the state a cold session reaches after
8498        // drawing its own first token from the same row.
8499        let mut sctr = 0u32;
8500        let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
8501        // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
8502        // prompt, which is what the cold session's own burst sees (Item 2's window). Built
8503        // after the suffix joins `committed` below.
8504        let mut boundary_captures: Vec<SpecBoundaryCapture> = Vec::new();
8505        let mut restored_turn_ckpt: Option<SpecCheckpoint> = None;
8506        if !suffix.is_empty() {
8507            // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
8508            // From here on the trunk cache mutates: failures return Err((None, _)) and
8509            // the worker serves the request cold-plain instead of reusing the carrier.
8510            let dirty =
8511                |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
8512            let n_embd = self.cfg.n_embd as usize;
8513            let t = suffix.len();
8514            let mut h_rows = match e.uninit(t * n_embd) {
8515                Ok(b) => b,
8516                Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
8517            };
8518            // STABLE-BOUNDARY split (see `republish_at`): feed stops at the boundary so the
8519            // in-place GDN conv/ssm state can be snapshotted there — the only moment it
8520            // exists (the cold prime-split law). suffix-relative; None = one-segment legacy.
8521            let b_rel = republish_at
8522                .and_then(|abs| abs.checked_sub(pos))
8523                .filter(|&r| r > 0 && r < t);
8524            let mut feed_logits = Vec::new();
8525            let tokenwise_env = std::env::var("MEMRA_PRIME_TOKENWISE").is_ok()
8526                || e.frozen_cpu_experts_prefer_tokenwise_prime();
8527            let mut fed = 0usize;
8528            for seg_end in [b_rel, Some(t)].into_iter().flatten() {
8529                if seg_end <= fed {
8530                    continue;
8531                }
8532                let seg = &suffix[fed..seg_end];
8533                let batched = seg.len() >= crate::hybrid_forward::PRIME_MIN_T && !tokenwise_env;
8534                if batched {
8535                    // prefill_tick's prime arm: request-level prime_cache call; tokens still
8536                    // queued after this segment ride `queued_after` so Step35 arm selection
8537                    // stays keyed to the request's end (tick-seg law).
8538                    match self.prime_cache(e, seg, &mut cache, t - seg_end) {
8539                        Ok((l, _h_seed, hiddens)) => {
8540                            if let Err(err) =
8541                                e.copy_into(&mut h_rows, fed * n_embd, &hiddens, seg.len() * n_embd)
8542                            {
8543                                return dirty(format!("suffix hidden copy: {err}"));
8544                            }
8545                            feed_logits = l;
8546                        }
8547                        Err(err) => return dirty(format!("suffix prime failed: {err}")),
8548                    }
8549                } else {
8550                    // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
8551                    for (i, &tok) in seg.iter().enumerate() {
8552                        match self.decode_step_h(e, tok, &mut cache) {
8553                            Ok((l, h)) => {
8554                                if let Err(err) =
8555                                    e.copy_into(&mut h_rows, (fed + i) * n_embd, &h, n_embd)
8556                                {
8557                                    return dirty(format!("suffix hidden copy: {err}"));
8558                                }
8559                                feed_logits = l;
8560                            }
8561                            Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
8562                        }
8563                    }
8564                }
8565                fed = seg_end;
8566                if Some(seg_end) == b_rel {
8567                    // The stable pre-generation boundary: capture the extended-entry
8568                    // publication AND this session's own turn checkpoint here instead of at
8569                    // prompt-end (both would otherwise carry the volatile live-header tail
8570                    // the next re-render replaces). Failure silent, turn_ckpt convention.
8571                    debug_assert_eq!(
8572                        cache.pos,
8573                        pos + seg_end,
8574                        "stable-boundary capture off the feed split"
8575                    );
8576                    if spec_restore_republish_on() {
8577                        if let Ok(snap) = cache.snapshot(e) {
8578                            boundary_captures.push(SpecBoundaryCapture {
8579                                snap,
8580                                pos: pos + seg_end,
8581                                logits: feed_logits.clone(),
8582                                last_h: capture_boundary_hidden(e, &h_rows, seg_end, n_embd),
8583                            });
8584                        }
8585                    }
8586                    let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
8587                        e.uninit(n_embd).and_then(|mut a| {
8588                            e.copy_view_into(
8589                                &mut a,
8590                                0,
8591                                &h_rows.slice((seg_end - 1) * n_embd..seg_end * n_embd),
8592                                n_embd,
8593                            )?;
8594                            Ok(a)
8595                        });
8596                    if let (Ok(snap), Ok(last_h)) = (cache.snapshot(e), anchor) {
8597                        restored_turn_ckpt = Some(SpecCheckpoint {
8598                            snap,
8599                            pos: pos + seg_end,
8600                            last_h,
8601                        });
8602                    }
8603                }
8604            }
8605            // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
8606            // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
8607            // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
8608            // with T). Fill failures are acceptance-only — truncate to the restored rows
8609            // and continue; the burst's own set_len keeps the invariant.
8610            let mtp = self.mtp.as_ref().expect("mtp checked above");
8611            let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
8612            let embd_gpu = if spec_host_embd() {
8613                None
8614            } else {
8615                Some(
8616                    self.embd_gpu
8617                        .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
8618                )
8619            };
8620            let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
8621            let fill_chunk = 4096usize;
8622            let mut filled = true;
8623            let mut start = 0usize;
8624            'fill: while start < t {
8625                let end = (start + fill_chunk).min(t);
8626                let tc = end - start;
8627                let Ok(mut phs) = e.zeros(tc * n_embd) else {
8628                    filled = false;
8629                    break 'fill;
8630                };
8631                let (src_lo, dst_off, n_copy) = if start == 0 {
8632                    (0, n_embd, (tc - 1) * n_embd)
8633                } else {
8634                    ((start - 1) * n_embd, 0, tc * n_embd)
8635                };
8636                if start == 0 {
8637                    if let Some(lh) = last_h_dev.as_ref() {
8638                        if e.copy_into(&mut phs, 0, lh, n_embd).is_err() {
8639                            filled = false;
8640                            break 'fill;
8641                        }
8642                    }
8643                }
8644                if n_copy > 0
8645                    && e.copy_view_into(
8646                        &mut phs,
8647                        dst_off,
8648                        &h_rows.slice(src_lo..src_lo + n_copy),
8649                        n_copy,
8650                    )
8651                    .is_err()
8652                {
8653                    filled = false;
8654                    break 'fill;
8655                }
8656                if self
8657                    .mtp_kv_fill_all(
8658                        e,
8659                        &suffix[start..end],
8660                        &phs,
8661                        pos + start,
8662                        &mut scratch,
8663                        embd_dev,
8664                    )
8665                    .is_err()
8666                {
8667                    filled = false;
8668                    break 'fill;
8669                }
8670                start = end;
8671            }
8672            if !filled {
8673                // acceptance-only: drafts over missing suffix rows are cheap and wrong,
8674                // so keep only the restored rows resident and let verify arbitrate.
8675                if let Err(err) = scratch.set_len(e, pos) {
8676                    return dirty(format!("scratch truncation after failed fill: {err}"));
8677                }
8678            }
8679            // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
8680            // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
8681            // finding (d)). Pre-lane, publication was armed only for COLD sessions
8682            // (`spec_resumed == 0` in the worker) and both engine capture sites require a
8683            // non-continuation burst — but a converted hit's first burst IS a continuation,
8684            // so a growing conversation learned exactly ONE boundary and turn 3 could never
8685            // hit a longer prefix than turn 2 did.
8686            //
8687            // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
8688            // line — the trunk is primed over the whole prompt, nothing is generated, and the
8689            // draft plane rows [0..prompt) are filled just above. That is a complete
8690            // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
8691            // publishes; the worker's existing publication sweep picks it up because it is
8692            // keyed on non-empty `boundary_captures` and is sampler- and resume-independent.
8693            // NOT the partial-restore hazard: the boundary is this session's own prompt END,
8694            // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
8695            // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
8696            // publication is an optimization, never a correctness dependency.
8697            //
8698            // SUPERSEDED WHEN `republish_at` FIRED (lane/frspec-multiturn-cache): a prompt-end
8699            // entry's tail is the live generation header the next re-render replaces, so on a
8700            // hybrid (whole-entry restores) it can never serve the conversation's next turn —
8701            // the stable-boundary capture above IS this publication, minus the poisoned tail.
8702            if spec_restore_republish_on() && boundary_captures.is_empty() {
8703                debug_assert_eq!(
8704                    cache.pos,
8705                    pos + t,
8706                    "extended-entry capture must sit at the restored session's prompt end",
8707                );
8708                if let Ok(snap) = cache.snapshot(e) {
8709                    boundary_captures.push(SpecBoundaryCapture {
8710                        snap,
8711                        pos: pos + t,
8712                        logits: feed_logits.clone(),
8713                        last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
8714                    });
8715                }
8716            }
8717            // continuation seed: the feed's boundary logits ARE the plain path's boundary
8718            // logits (same program), so greedy's argmax here is plain's first emitted token,
8719            // and the sampled draw is the cold sampled session's own first token.
8720            next_pred = Some(if sampled {
8721                let sp = sampling.expect("sampled implies a sampler");
8722                // `committed` is still the restored prefix here; the suffix joins it below —
8723                // so this is the last-N window over the WHOLE prompt, exactly the cold
8724                // session's own window at its first token.
8725                let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
8726                match sample_boundary_token(
8727                    e,
8728                    &feed_logits,
8729                    &sp,
8730                    &hist,
8731                    &mut sctr,
8732                    "restore-suffix-feed",
8733                ) {
8734                    Ok(t) => t,
8735                    // the trunk is already fed: hand nothing back, the worker serves the
8736                    // request cold-plain. Never fall back to an argmax — that would put a
8737                    // greedy token in a sampled stream to save a slow path.
8738                    Err(err) => {
8739                        return dirty(format!("boundary token draw failed: {err}"));
8740                    }
8741                }
8742            } else {
8743                argmax(&feed_logits) as u32
8744            });
8745            let mut lh = match e.uninit(n_embd) {
8746                Ok(b) => b,
8747                Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
8748            };
8749            if let Err(err) = e.copy_view_into(
8750                &mut lh,
8751                0,
8752                &h_rows.slice((t - 1) * n_embd..t * n_embd),
8753                n_embd,
8754            ) {
8755                return dirty(format!("boundary hidden copy: {err}"));
8756            }
8757            last_h_dev = Some(lh);
8758            committed.extend_from_slice(suffix);
8759        } else {
8760            // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
8761            // ENTRY's boundary logits are the boundary row, and this is the token the cold
8762            // session emits from that same row. Owned here rather than in the worker so the
8763            // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
8764            if boundary_logits.is_empty() {
8765                return fail(
8766                    cache,
8767                    "full-cover restore without the entry's boundary logits".into(),
8768                );
8769            }
8770            next_pred = Some(if sampled {
8771                let sp = sampling.expect("sampled implies a sampler");
8772                let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
8773                match sample_boundary_token(
8774                    e,
8775                    boundary_logits,
8776                    &sp,
8777                    &hist,
8778                    &mut sctr,
8779                    "restore-full-cover",
8780                ) {
8781                    Ok(t) => t,
8782                    // nothing has been mutated on this shape — hand the carrier back and let
8783                    // the hit serve PLAIN (the banked pre-lane path).
8784                    Err(err) => {
8785                        return fail(cache, format!("boundary token draw failed: {err}"));
8786                    }
8787                }
8788            } else {
8789                argmax(boundary_logits) as u32
8790            });
8791        }
8792        Ok(SpecSession {
8793            cache,
8794            scratch,
8795            committed,
8796            last_h: last_h_dev,
8797            next_pred,
8798            sctr,
8799            uctr: 0,
8800            draft_ctx: None,
8801            pending_tok: None,
8802            // Stable-boundary capture from the split feed above (None on the legacy shape):
8803            // a restored session previously parked WITHOUT a checkpoint, so the next turn's
8804            // affinity probe declined ("no turn checkpoint retained") and the conversation
8805            // fell back to the frozen prefix entry forever.
8806            turn_ckpt: restored_turn_ckpt,
8807            telem: SpecTelemetryCounters::default(),
8808            capture_at: None,
8809            boundary_captures,
8810            ckpt_at: None,
8811        })
8812    }
8813
8814    /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
8815    /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
8816    /// snapshot, or draft-KV row that only corrupts the following round.
8817    pub fn optipipe_compare_session_state(
8818        &self,
8819        e: &Engine,
8820        reference: &SpecSession,
8821        candidate: &SpecSession,
8822    ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
8823        fn fail(what: &str) -> Box<dyn std::error::Error> {
8824            format!("optipipe state mismatch: {what}").into()
8825        }
8826        fn same_f32(a: &[f32], b: &[f32]) -> bool {
8827            a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
8828        }
8829        fn compare_layers(
8830            es: &Engine,
8831            range: std::ops::Range<usize>,
8832            reference: &SpecSession,
8833            candidate: &SpecSession,
8834            report: &mut OptiForkStateIdentity,
8835        ) -> Result<(), Box<dyn std::error::Error>> {
8836            for il in range {
8837                match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
8838                    (Some(a), Some(b)) => {
8839                        if a.len != b.len {
8840                            return Err(fail(&format!(
8841                                "layer {il} host KV len {} != {}",
8842                                a.len, b.len
8843                            )));
8844                        }
8845                        let ad = es.dtoh_i32(&a.len_d)?;
8846                        let bd = es.dtoh_i32(&b.len_d)?;
8847                        if ad != bd || ad.first().copied() != Some(a.len as i32) {
8848                            return Err(fail(&format!(
8849                                "layer {il} device KV len {ad:?} != {bd:?} (host={})",
8850                                a.len,
8851                            )));
8852                        }
8853                        let kb = a.len * a.k_tok_bytes;
8854                        let vb = a.len * a.v_tok_bytes;
8855                        if kb > 0 {
8856                            let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
8857                            let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
8858                            if ak != bk {
8859                                let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
8860                                return Err(fail(&format!(
8861                                    "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
8862                                    at / a.k_tok_bytes,
8863                                    at % a.k_tok_bytes,
8864                                    ak[at],
8865                                    bk[at],
8866                                )));
8867                            }
8868                        }
8869                        if vb > 0 {
8870                            let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
8871                            let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
8872                            if av != bv {
8873                                let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
8874                                return Err(fail(&format!(
8875                                    "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
8876                                    at / a.v_tok_bytes,
8877                                    at % a.v_tok_bytes,
8878                                    av[at],
8879                                    bv[at],
8880                                )));
8881                            }
8882                        }
8883                        report.trunk_kv_bytes += kb + vb;
8884                    }
8885                    (None, None) => {}
8886                    _ => return Err(fail(&format!("layer {il} KV presence"))),
8887                }
8888                match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
8889                    (Some(a), Some(b)) => {
8890                        let ac = es.dtoh(&a.conv_state)?;
8891                        let bc = es.dtoh(&b.conv_state)?;
8892                        if !same_f32(&ac, &bc) {
8893                            return Err(fail(&format!("layer {il} conv state")));
8894                        }
8895                        let as_ = es.dtoh(&a.ssm_state)?;
8896                        let bs = es.dtoh(&b.ssm_state)?;
8897                        if !same_f32(&as_, &bs) {
8898                            return Err(fail(&format!("layer {il} SSM state")));
8899                        }
8900                        report.recurrent_bytes += (ac.len() + as_.len()) * 4;
8901                    }
8902                    (None, None) => {}
8903                    _ => return Err(fail(&format!("layer {il} recurrent presence"))),
8904                }
8905            }
8906            Ok(())
8907        }
8908
8909        if reference.committed != candidate.committed {
8910            return Err(fail("committed token ids"));
8911        }
8912        if reference.cache.pos != candidate.cache.pos
8913            || reference.cache.max_ctx != candidate.cache.max_ctx
8914        {
8915            return Err(fail("cache pos/capacity"));
8916        }
8917        if reference.pending_tok != candidate.pending_tok
8918            || reference.next_pred != candidate.next_pred
8919            || reference.sctr != candidate.sctr
8920            || reference.uctr != candidate.uctr
8921        {
8922            return Err(fail("pending/prediction/counter tail"));
8923        }
8924
8925        let mut report = OptiForkStateIdentity::default();
8926        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
8927            let rt = crate::pp::PpNRt::get(e)?;
8928            for stage in 0..rt.n_stages() {
8929                let _scope = rt.enter(stage);
8930                compare_layers(
8931                    rt.engine(stage, e),
8932                    fence[stage]..fence[stage + 1],
8933                    reference,
8934                    candidate,
8935                    &mut report,
8936                )?;
8937            }
8938        } else {
8939            compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
8940        }
8941
8942        if reference.scratch.plane_count() != candidate.scratch.plane_count() {
8943            return Err(fail("draft scratch plane count"));
8944        }
8945        for index in 0..reference.scratch.plane_count() {
8946            let (a, _) = reference.scratch.plane(index);
8947            let (b, _) = candidate.scratch.plane(index);
8948            if a.len != b.len
8949                || a.kv_dim_k != b.kv_dim_k
8950                || a.kv_dim_v != b.kv_dim_v
8951                || a.k_tok_bytes != b.k_tok_bytes
8952                || a.v_tok_bytes != b.v_tok_bytes
8953                || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)?
8954            {
8955                return Err(fail(&format!("draft scratch plane {index} length/layout")));
8956            }
8957            let kb = a.len * a.k_tok_bytes;
8958            let vb = a.len * a.v_tok_bytes;
8959            if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
8960                return Err(fail(&format!("draft scratch plane {index} K bytes")));
8961            }
8962            if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
8963                return Err(fail(&format!("draft scratch plane {index} V bytes")));
8964            }
8965            report.scratch_kv_bytes += kb + vb;
8966        }
8967
8968        match (&reference.last_h, &candidate.last_h) {
8969            (Some(a), Some(b)) => {
8970                let ah = e.dtoh(a)?;
8971                let bh = e.dtoh(b)?;
8972                if !same_f32(&ah, &bh) {
8973                    return Err(fail("last hidden/seed bytes"));
8974                }
8975                report.hidden_bytes = ah.len() * 4;
8976            }
8977            (None, None) => {}
8978            _ => return Err(fail("last hidden/seed presence")),
8979        }
8980        Ok(report)
8981    }
8982
8983    /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
8984    /// retained prompt-end checkpoint, so a request whose prompt matches
8985    /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
8986    ///
8987    /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
8988    /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
8989    /// restored from the device copy taken there, draft scratch length reset, `committed`
8990    /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
8991    /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
8992    /// every burst after it are identical to a cold run of the same token stream — the
8993    /// committed-tokens-authoritative contract.
8994    ///
8995    /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
8996    /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
8997    /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
8998    /// continue). The persistent draft graph survives: it bakes only session-stable pointers
8999    /// (the scratch KV, the resident embedding), none of which the rewind moves.
9000    ///
9001    /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
9002    /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
9003    /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
9004    pub fn spec_rewind_to_checkpoint(
9005        &self,
9006        e: &Engine,
9007        sess: &mut SpecSession,
9008    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
9009        if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
9010            !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
9011        }) {
9012            return Err(
9013                "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
9014            );
9015        }
9016        let Some(ckpt) = sess.turn_ckpt.take() else {
9017            return Ok(None);
9018        };
9019        assert!(
9020            ckpt.pos <= sess.committed.len(),
9021            "checkpoint past committed ({} > {})",
9022            ckpt.pos,
9023            sess.committed.len()
9024        );
9025        // Restore through each layer's owning engine. A single primary-engine rollback is not
9026        // sufficient when the serving cache is stage-owned under cross-device PP.
9027        crate::pp::restore_cache_checkpoint(e, self, None, &mut sess.cache, &ckpt.snap)?;
9028        debug_assert_eq!(
9029            sess.cache.pos, ckpt.pos,
9030            "rollback landed off the checkpoint"
9031        );
9032        sess.scratch.set_len(e, ckpt.pos)?;
9033        sess.committed.truncate(ckpt.pos);
9034        sess.last_h = Some(ckpt.last_h);
9035        sess.next_pred = None;
9036        sess.pending_tok = None;
9037        Ok(Some(ckpt.pos))
9038    }
9039
9040    /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
9041    /// checkpoint without re-priming the checkpoint prefix.
9042    ///
9043    /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
9044    /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
9045    /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
9046    /// remain authoritative, so they are copied into a fresh larger scratch before its length is
9047    /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
9048    ///
9049    /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
9050    /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
9051    pub fn spec_grow_and_rewind_to_checkpoint(
9052        &self,
9053        e: &Engine,
9054        sess: &mut SpecSession,
9055        target_cap: usize,
9056    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
9057        if target_cap <= sess.cache.max_ctx {
9058            return self.spec_rewind_to_checkpoint(e, sess);
9059        }
9060        let Some(ckpt) = sess.turn_ckpt.as_ref() else {
9061            return Ok(None);
9062        };
9063        if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
9064            return Err(format!(
9065                "checkpoint pos {} outside committed length {}",
9066                ckpt.pos,
9067                sess.committed.len(),
9068            )
9069            .into());
9070        }
9071        if ckpt.pos > target_cap {
9072            return Err(format!(
9073                "checkpoint pos {} exceeds grown capacity {target_cap}",
9074                ckpt.pos,
9075            )
9076            .into());
9077        }
9078
9079        let mut grown_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, target_cap)?;
9080        let mut grown_scratch = self.new_mtp_scratch(e, target_cap)?;
9081        crate::pp::restore_cache_checkpoint(
9082            e,
9083            self,
9084            Some(&sess.cache),
9085            &mut grown_cache,
9086            &ckpt.snap,
9087        )?;
9088
9089        if sess.scratch.plane_count() != grown_scratch.plane_count() {
9090            return Err("checkpoint draft plane count mismatch".into());
9091        }
9092        for index in 0..sess.scratch.plane_count() {
9093            let (src, _) = sess.scratch.plane(index);
9094            let (dst, _) = grown_scratch.plane_mut(index);
9095            if ckpt.pos > src.len
9096                || src.kv_dim_k != dst.kv_dim_k
9097                || src.kv_dim_v != dst.kv_dim_v
9098                || src.k_tok_bytes != dst.k_tok_bytes
9099                || src.v_tok_bytes != dst.v_tok_bytes
9100            {
9101                return Err(format!(
9102                    "checkpoint draft plane {index} layout mismatch (pos {}, source len {})",
9103                    ckpt.pos, src.len,
9104                )
9105                .into());
9106            }
9107            let kb = ckpt.pos * src.k_tok_bytes;
9108            let vb = ckpt.pos * src.v_tok_bytes;
9109            if kb > 0 {
9110                e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
9111            }
9112            if vb > 0 {
9113                e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
9114            }
9115        }
9116        grown_scratch.set_len(e, ckpt.pos)?;
9117        // The old scratch is dropped immediately after publication below. Bound its D2D reads
9118        // first; growth happens once per rewritten turn, outside the decode hot loop.
9119        e.stream().synchronize()?;
9120
9121        let ckpt = sess
9122            .turn_ckpt
9123            .take()
9124            .expect("checkpoint remained present through transactional grow");
9125        let pos = ckpt.pos;
9126        sess.cache = grown_cache;
9127        sess.scratch = grown_scratch;
9128        sess.committed.truncate(pos);
9129        sess.last_h = Some(ckpt.last_h);
9130        sess.next_pred = None;
9131        sess.pending_tok = None;
9132        sess.draft_ctx = None;
9133        debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
9134        debug_assert!(
9135            (0..sess.scratch.plane_count()).all(|index| sess.scratch.plane(index).0.len == pos),
9136            "grown draft rewind landed off checkpoint"
9137        );
9138        Ok(Some(pos))
9139    }
9140
9141    /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
9142    /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
9143    /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
9144    /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
9145    /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
9146    /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
9147    /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
9148    /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
9149    /// park-time flush is a future request whose sampler is not knowable here (residual
9150    /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
9151    pub fn spec_flush_pending(
9152        &self,
9153        e: &Engine,
9154        sess: &mut SpecSession,
9155        sampling: Option<SpecSampling>,
9156    ) -> Result<(), Box<dyn std::error::Error>> {
9157        let Some(b) = sess.pending_tok.take() else {
9158            return Ok(());
9159        };
9160        if self.mtp.is_none() {
9161            return Err("pending carry requires an MTP head".into());
9162        }
9163        let n_embd = self.cfg.n_embd as usize;
9164        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
9165        let embd_gpu = if spec_host_embd() {
9166            None
9167        } else {
9168            Some(
9169                self.embd_gpu
9170                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
9171            )
9172        };
9173        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
9174        let pos_b = sess.cache.pos;
9175        sess.scratch.set_len(e, pos_b)?;
9176        let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
9177        sess.next_pred = Some(match sampling {
9178            Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
9179                // window includes `b` itself: it is committed by this pass, and the pre-lane
9180                // code never counted a boundary token in the penalty history at all.
9181                let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
9182                sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
9183            }
9184            _ => argmax(&lg_b) as u32,
9185        });
9186        let anchor = sess
9187            .last_h
9188            .as_ref()
9189            .expect("pending carry requires last_h (the predecessor-row anchor)");
9190        self.mtp_kv_fill_all(e, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
9191        sess.last_h = Some(hb);
9192        sess.committed.push(b);
9193        Ok(())
9194    }
9195
9196    /// Solo target feed used only at speculative round boundaries. Step35 serving made its
9197    /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
9198    /// rounds through that same graph. Other model families keep their eager T=1 contract.
9199    fn spec_target_step_h(
9200        &self,
9201        e: &Engine,
9202        token: u32,
9203        cache: &mut Cache,
9204    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9205        if !self.sliding_gated_moe_batch_program() && !self.batched_serving_numeric_class() {
9206            return self.decode_step_h(e, token, cache);
9207        }
9208        let pos0 = cache.pos;
9209        let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
9210        Ok((e.dtoh(&logits)?, hidden))
9211    }
9212
9213    /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
9214    /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
9215    /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
9216    /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
9217    /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
9218    /// carries the drift until a near-tie flips deep in generation. One predicate so the five
9219    /// dispatch sites cannot drift apart again.
9220    /// Draft-graph head admissibility (lane/draftcost-moe, 2026-08-20): the capture body
9221    /// (`mtp_head_forward_cap`) supports Dense heads AND resident-MoE heads
9222    /// (`Ffn::Moe(m) if m.dev_exps.is_some()`); non-resident MoE still refuses inside the
9223    /// capture and the caller falls back to the eager chain by design. Trunk FFN class is
9224    /// irrelevant — the graph body is the HEAD forward only. One predicate for all three
9225    /// eligibility sites so they cannot drift (the serving numeric-class lesson).
9226    fn mtp_graph_capturable(&self) -> bool {
9227        self.mtp
9228            .as_ref()
9229            .map(|m| match &m.ffn {
9230                crate::hybrid::Ffn::Dense { .. } => true,
9231                crate::hybrid::Ffn::Moe(mo) => mo.dev_exps.is_some(),
9232            })
9233            .unwrap_or(false)
9234    }
9235
9236    fn batched_serving_numeric_class(&self) -> bool {
9237        self.plan
9238            .trunk_operations()
9239            .contains(&memra_gguf::model_plan::OperationKind::GatedDeltaNet)
9240    }
9241
9242    /// The family the MTP verify-graph default was measured on: GatedDeltaNet state layers
9243    /// (a `recur` mixer) together with a routed-MoE FFN — Ornith-1.5-35B-A3B and its kin. The
9244    /// server-side twin of this test is `model_forces_spec_replay` (GatedDeltaNet + MoeMlp);
9245    /// keeping the engine's own version structural rather than name-based means a new
9246    /// checkpoint of the same shape inherits the default, and a different shape does not.
9247    fn vgraph_family_default(&self) -> bool {
9248        let has_linear = self
9249            .layers
9250            .iter()
9251            .any(|l| matches!(l.mixer, Mixer::Linear(_)));
9252        let has_moe = self
9253            .layers
9254            .iter()
9255            .any(|l| matches!(l.ffn, crate::hybrid::Ffn::Moe(_)));
9256        has_linear && has_moe
9257    }
9258
9259    fn sliding_gated_moe_batch_program(&self) -> bool {
9260        self.uses_sliding_gated_moe_program()
9261    }
9262
9263    fn gemma_batch_program(&self) -> bool {
9264        self.uses_gemma_program()
9265    }
9266
9267    /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
9268    /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
9269    /// session already exist.
9270    pub fn spec_pipe_available(&self, e: &Engine) -> bool {
9271        if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
9272            || !spec_devacc()
9273            || spec_replay_env_enabled()
9274            || spec_stream()
9275            || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
9276            || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
9277            || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
9278            || std::env::var("MEMRA_SPEC_PMIN")
9279                .ok()
9280                .and_then(|v| v.parse::<f32>().ok())
9281                .unwrap_or(0.0)
9282                > 0.0
9283            || self.is_gemma4_e4b()
9284            || self.gemma_batch_program()
9285            || self.mtp.is_none()
9286            || !self.mtp_extra.is_empty()
9287        {
9288            return false;
9289        }
9290        let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
9291            return false;
9292        };
9293        if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
9294            return false;
9295        }
9296        crate::pp::PpNRt::get(e)
9297            .map(|rt| rt.n_stages() == 2 && rt.cross_device())
9298            .unwrap_or(false)
9299    }
9300
9301    /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
9302    /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
9303    /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
9304    #[allow(clippy::too_many_arguments)]
9305    pub fn generate_spec_session_pair(
9306        &self,
9307        e: &Engine,
9308        sess_a: &mut SpecSession,
9309        max_new_a: usize,
9310        k_a: usize,
9311        sess_b: &mut SpecSession,
9312        max_new_b: usize,
9313        k_b: usize,
9314    ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
9315    {
9316        if !self.spec_pipe_available(e) {
9317            return Err("two-session speculative pipeline is outside its reduced matrix".into());
9318        }
9319        if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
9320            return Err(
9321                "two-session speculative pipeline requires non-empty positive-K bursts".into(),
9322            );
9323        }
9324        for sess in [&*sess_a, &*sess_b] {
9325            if sess.committed.is_empty()
9326                || sess.last_h.is_none()
9327                || (sess.next_pred.is_none() && sess.pending_tok.is_none())
9328            {
9329                return Err("two-session speculative pipeline requires warm continuations".into());
9330            }
9331        }
9332
9333        let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
9334            && !spec_host_embd()
9335            && self.mtp_graph_capturable()
9336            && self.mtp_extra.is_empty()
9337            && !crate::model::full_prec_enabled();
9338        let graph_a = graph_ok && k_a + 2 < 96;
9339        let graph_b = graph_ok && k_b + 2 < 96;
9340        let was_tracking = e.ctx().is_event_tracking();
9341        if (graph_a || graph_b) && was_tracking {
9342            unsafe {
9343                e.ctx().disable_event_tracking();
9344            }
9345        }
9346
9347        static LOGGED: std::sync::Once = std::sync::Once::new();
9348        LOGGED.call_once(|| {
9349            eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
9350        });
9351        let sync = std::sync::Arc::new(SpecPipeSync::new());
9352        let lane_a = SpecPipeLane {
9353            sync: sync.clone(),
9354            lane: 0,
9355        };
9356        let lane_b = SpecPipeLane { sync, lane: 1 };
9357        let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
9358        let (result_a, result_b) = std::thread::scope(|scope| {
9359            let b = scope.spawn(move || {
9360                let mut finish = SpecPipeFinish::new(&lane_b);
9361                let sess_b = unsafe { sess_b_ptr.get_mut() };
9362                let result = e
9363                    .ctx()
9364                    .bind_to_thread()
9365                    .map_err(|err| err.to_string())
9366                    .and_then(|_| {
9367                        self.generate_spec_inner2(
9368                            e,
9369                            &[],
9370                            max_new_b,
9371                            k_b,
9372                            graph_b,
9373                            Some(sess_b),
9374                            None,
9375                            None,
9376                            None,
9377                            None,
9378                            Some(&lane_b),
9379                        )
9380                        .map_err(|err| err.to_string())
9381                    });
9382                finish.close(result.is_err());
9383                result
9384            });
9385            let mut finish = SpecPipeFinish::new(&lane_a);
9386            let result_a = self.generate_spec_inner2(
9387                e,
9388                &[],
9389                max_new_a,
9390                k_a,
9391                graph_a,
9392                Some(sess_a),
9393                None,
9394                None,
9395                None,
9396                None,
9397                Some(&lane_a),
9398            );
9399            finish.close(result_a.is_err());
9400            let result_b = b
9401                .join()
9402                .map_err(|_| "paired speculative session B panicked".to_string())
9403                .and_then(|r| r);
9404            (result_a, result_b)
9405        });
9406
9407        if (graph_a || graph_b) && was_tracking {
9408            unsafe {
9409                e.ctx().enable_event_tracking();
9410            }
9411        }
9412        let result_a = result_a?;
9413        let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
9414        Ok((result_a, result_b))
9415    }
9416
9417    /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
9418    /// message rendered through the chat template continuation). Returns (new tokens emitted,
9419    /// drafted, accepted); session.committed grows by suffix + emitted.
9420    pub fn generate_spec_session(
9421        &self,
9422        e: &Engine,
9423        sess: &mut SpecSession,
9424        suffix: &[u32],
9425        max_new: usize,
9426        k: usize,
9427    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9428        self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
9429    }
9430
9431    /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
9432    /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
9433    /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
9434    /// for the filtered target (feat/filtered-spec).
9435    ///
9436    /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
9437    /// output — once right after the prime's first token, then once per round commit — so a
9438    /// streaming caller can flush text at round cadence instead of once per burst. The slices
9439    /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
9440    /// timing only: token bytes, session state, and exactness are untouched.
9441    ///
9442    /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
9443    /// the burst at the current round boundary, exactly as if `max_new` had been reached —
9444    /// the caller's scheduler regains control without waiting the burst out. Burst size is
9445    /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
9446    /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
9447    /// drains and the defensive tail flush can land with nothing new committed).
9448    #[allow(clippy::too_many_arguments)]
9449    pub fn generate_spec_session_sampled(
9450        &self,
9451        e: &Engine,
9452        sess: &mut SpecSession,
9453        suffix: &[u32],
9454        max_new: usize,
9455        k: usize,
9456        sampling: Option<SpecSampling>,
9457        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9458    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9459        self.generate_spec_session_sampled_prime_split(
9460            e, sess, suffix, max_new, k, sampling, None, on_commit,
9461        )
9462    }
9463
9464    /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
9465    /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
9466    /// pass `None` and stay on the existing zero-prime path.
9467    #[allow(clippy::too_many_arguments)]
9468    pub fn generate_spec_session_sampled_prime_split(
9469        &self,
9470        e: &Engine,
9471        sess: &mut SpecSession,
9472        suffix: &[u32],
9473        max_new: usize,
9474        k: usize,
9475        sampling: Option<SpecSampling>,
9476        prime_split: Option<usize>,
9477        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9478    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9479        self.generate_spec_session_constrained_prime_split(
9480            e,
9481            sess,
9482            suffix,
9483            max_new,
9484            k,
9485            sampling,
9486            None,
9487            prime_split,
9488            on_commit,
9489        )
9490    }
9491
9492    /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
9493    /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
9494    /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
9495    /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
9496    /// column — token-identical to constrained plain greedy decode. GREEDY only (the
9497    /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
9498    /// may drop (drafter is unconstrained); that is measured, not hidden.
9499    #[allow(clippy::too_many_arguments)]
9500    pub fn generate_spec_session_constrained(
9501        &self,
9502        e: &Engine,
9503        sess: &mut SpecSession,
9504        suffix: &[u32],
9505        max_new: usize,
9506        k: usize,
9507        sampling: Option<SpecSampling>,
9508        constraint: Option<&mut dyn SpecConstraint>,
9509        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9510    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9511        self.generate_spec_session_constrained_prime_split(
9512            e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
9513        )
9514    }
9515
9516    #[allow(clippy::too_many_arguments)]
9517    pub fn generate_spec_session_constrained_prime_split(
9518        &self,
9519        e: &Engine,
9520        sess: &mut SpecSession,
9521        suffix: &[u32],
9522        max_new: usize,
9523        k: usize,
9524        sampling: Option<SpecSampling>,
9525        constraint: Option<&mut dyn SpecConstraint>,
9526        prime_split: Option<usize>,
9527        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9528    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9529        if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
9530            return Err(
9531                "constrained spec decode is greedy-only (worker routes sampled \
9532                        constrained to plain decode)"
9533                    .into(),
9534            );
9535        }
9536        // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
9537        // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
9538        // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
9539        // serve continuation case — consume the carry in-loop with zero solo passes.
9540        if sess.pending_tok.is_some()
9541            && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
9542        {
9543            self.spec_flush_pending(e, sess, sampling)?;
9544        }
9545
9546        // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
9547        // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
9548        // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
9549        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
9550            && !spec_host_embd()
9551            && self.mtp_graph_capturable()
9552            && self.mtp_extra.is_empty()
9553            && k + 2 < 96
9554            && !crate::model::full_prec_enabled();
9555        let was_tracking = e.ctx().is_event_tracking();
9556        if graph_draft && was_tracking {
9557            unsafe {
9558                e.ctx().disable_event_tracking();
9559            }
9560        }
9561        let r = self.generate_spec_inner2(
9562            e,
9563            suffix,
9564            max_new,
9565            k,
9566            graph_draft,
9567            Some(sess),
9568            sampling,
9569            constraint,
9570            on_commit,
9571            prime_split,
9572            None,
9573        );
9574        if graph_draft && was_tracking {
9575            unsafe {
9576                e.ctx().enable_event_tracking();
9577            }
9578        }
9579        let (out, d, a) = r?;
9580        Ok((out, d, a))
9581    }
9582
9583    pub fn generate_spec(
9584        &self,
9585        e: &Engine,
9586        prompt: &[u32],
9587        max_new: usize,
9588        k: usize,
9589    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9590        if crate::pp::pp_cuts(self.layers.len()).is_some()
9591            && !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::Pipeline)
9592        {
9593            return Err("pipeline rewrite is not qualified for speculative decode".into());
9594        }
9595        if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::MtpSpec) {
9596            return Err("speculative rewrite is not qualified for this ModelPlan".into());
9597        }
9598        // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
9599        // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
9600        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
9601            && !spec_host_embd()
9602            && self.mtp_graph_capturable()
9603            && self.mtp_extra.is_empty()
9604            && k + 2 < 96
9605            && !crate::model::full_prec_enabled();
9606        if !graph_draft {
9607            return self.generate_spec_inner2(
9608                e, prompt, max_new, k, false, None, None, None, None, None, None,
9609            );
9610        }
9611        let was_tracking = e.ctx().is_event_tracking();
9612        if was_tracking {
9613            unsafe {
9614                e.ctx().disable_event_tracking();
9615            }
9616        }
9617        let r = self.generate_spec_inner2(
9618            e, prompt, max_new, k, true, None, None, None, None, None, None,
9619        );
9620        if was_tracking {
9621            unsafe {
9622                e.ctx().enable_event_tracking();
9623            }
9624        }
9625        r
9626    }
9627
9628    fn generate_spec_inner2(
9629        &self,
9630        e: &Engine,
9631        prompt: &[u32],
9632        max_new: usize,
9633        k: usize,
9634        graph_draft: bool,
9635        mut sess: Option<&mut SpecSession>,
9636        sampling: Option<SpecSampling>,
9637        mut constraint: Option<&mut dyn SpecConstraint>,
9638        mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9639        prime_split: Option<usize>,
9640        pipe: Option<&SpecPipeLane>,
9641    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9642        assert!(k >= 1, "k must be >= 1");
9643        if let Some(p) = pipe {
9644            p.setup_begin()?;
9645        }
9646        // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
9647        let mut flushed = 0usize;
9648        // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
9649        // at the next round boundary (same exit as max_new reached — the session tail runs).
9650        // Initialized by the unconditional post-prime flush below.
9651        let mut keep_going;
9652        let mtp = self
9653            .mtp
9654            .as_ref()
9655            .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
9656        let n_vocab = self.output.out_features();
9657        // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
9658        // over the draft vocab and the winning index maps through d2t to a TARGET token id.
9659        // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
9660        let d_vocab = mtp
9661            .shared_head_head
9662            .as_ref()
9663            .unwrap_or(&self.output)
9664            .out_features();
9665        if !self.mtp_extra.is_empty() {
9666            if self.plan.draft_source != memra_gguf::model_plan::DraftSourcePlan::Embedded
9667                || self.plan.mtp_blocks.len() != self.mtp_head_count()
9668                || mtp.d2t.is_some()
9669            {
9670                return Err(
9671                    "multi-head MTP requires one embedded canonical block per loaded head".into(),
9672                );
9673            }
9674            for (offset, head) in self.mtp_extra.iter().enumerate() {
9675                if head.d2t.is_some()
9676                    || head
9677                        .shared_head_head
9678                        .as_ref()
9679                        .unwrap_or(&self.output)
9680                        .out_features()
9681                        != d_vocab
9682                {
9683                    return Err(format!(
9684                        "embedded MTP head {} has incompatible draft vocabulary",
9685                        offset + 1
9686                    )
9687                    .into());
9688                }
9689            }
9690            eprintln!(
9691                "[mtp-chain] heads={} policy=step-modulo prefix-replay kv=per-head",
9692                self.mtp_head_count()
9693            );
9694        }
9695        let n_embd = self.cfg.n_embd as usize;
9696        // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
9697        // already committed (their state is in the caches); 0 = fresh single-shot call.
9698        let session_mode = sess.is_some();
9699        let max_ctx = match sess.as_ref() {
9700            Some(s) => s.cache.max_ctx,
9701            None => prompt.len() + max_new + k + 8,
9702        };
9703        let mut own_cache;
9704        let mut own_scratch;
9705        // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
9706        // (requested split, destination list). Single-shot per burst; fresh calls have none.
9707        let mut sess_capture: Option<(Option<usize>, &mut Vec<SpecBoundaryCapture>)> = None;
9708        // STABLE-BOUNDARY turn-checkpoint request (lane/frspec-multiturn-cache): ABSOLUTE
9709        // committed-length position; consumed one-shot like `capture_at`. None = legacy
9710        // prompt-end capture below.
9711        let mut ckpt_req: Option<usize> = None;
9712        let (
9713            cache,
9714            scratch,
9715            mut sess_tail,
9716            mut sess_draft_slot,
9717            mut sess_pending_slot,
9718            sess_ckpt_slot,
9719            sess_telem,
9720        ): (
9721            &mut Cache,
9722            &mut MtpScratch,
9723            Option<(
9724                &mut Vec<u32>,
9725                &mut Option<CudaSlice<f32>>,
9726                &mut Option<u32>,
9727                &mut u32,
9728                &mut u32,
9729            )>,
9730            Option<&mut Option<DraftGraphCtx>>,
9731            Option<&mut Option<u32>>,
9732            Option<&mut Option<SpecCheckpoint>>,
9733            Option<&SpecTelemetryCounters>,
9734        ) = match sess.take() {
9735            Some(sr) => {
9736                let SpecSession {
9737                    cache,
9738                    scratch,
9739                    committed,
9740                    last_h,
9741                    next_pred,
9742                    sctr: s_sctr,
9743                    uctr: s_uctr,
9744                    draft_ctx,
9745                    pending_tok,
9746                    turn_ckpt,
9747                    telem,
9748                    capture_at,
9749                    boundary_captures,
9750                    ckpt_at,
9751                } = sr;
9752                sess_capture = Some((capture_at.take(), boundary_captures));
9753                ckpt_req = ckpt_at.take();
9754                (
9755                    cache,
9756                    scratch,
9757                    Some((committed, last_h, next_pred, s_sctr, s_uctr)),
9758                    Some(draft_ctx),
9759                    Some(pending_tok),
9760                    Some(turn_ckpt),
9761                    Some(telem),
9762                )
9763            }
9764            None => {
9765                // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
9766                // `Cache::new` verbatim.
9767                own_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?;
9768                // Persistent scratch = max_ctx rows (~2KB/token quantized).
9769                own_scratch = self.new_mtp_scratch(e, max_ctx)?;
9770                (
9771                    &mut own_cache,
9772                    &mut own_scratch,
9773                    None,
9774                    None,
9775                    None,
9776                    None,
9777                    None,
9778                )
9779            }
9780        };
9781        if scratch.plane_count() != self.mtp_head_count() {
9782            return Err(format!(
9783                "MTP scratch/head count mismatch ({}/{})",
9784                scratch.plane_count(),
9785                self.mtp_head_count()
9786            )
9787            .into());
9788        }
9789        let base = cache.pos;
9790        // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
9791        // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
9792        // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
9793        // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
9794        let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
9795        // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
9796        // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
9797        // acceptance-only — exactness is verify's job either way).
9798        // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
9799        // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
9800        // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
9801        // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
9802        // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
9803        // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
9804        // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
9805        // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
9806        // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
9807        // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
9808        // per round on top of the acceptance win). Draft-quality-only: exactness stays the
9809        // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
9810        // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
9811        // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
9812        // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
9813        // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
9814        // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
9815        // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
9816        // + fallback seam).
9817        // Qwen35-MoE replay pin LIFTED (lane/draftcost-moe, 2026-08-20). The pin's stated
9818        // bar — the retained verify-state commit proven equivalent to sequential serving —
9819        // was waiting on this arch running the serving batched verify class, which the
9820        // t-parallel admission (this lane, increment 1) provided: the VerifyCkpt the
9821        // replay-free commit consumes is now produced by the SAME serving-class verify that
9822        // qualified dense qwen35 on 2026-08-15 (where the per-round duplicate replay
9823        // measured 69 -> 30 tok/s). Qualification receipts (run-spec K=1..8 both arms,
9824        // 8-prompt replay-vs-replay-free canary, long-prompt cell):
9825        // research/draftcost-moe-20260820/RECEIPTS.md. MEMRA_SPEC_REPLAY=1 stays the
9826        // rollback + A/B seam.
9827        let spec_replay = spec_replay_env_enabled();
9828        if constraint.is_some() && spec_replay {
9829            return Err(
9830                "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
9831                        (legacy replay commits an unmasked bonus)"
9832                    .into(),
9833            );
9834        }
9835        // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
9836        // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
9837        // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
9838        let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
9839        if !refresh && !self.mtp_extra.is_empty() {
9840            return Err("multi-head MTP requires exact accepted-prefix refresh".into());
9841        }
9842
9843        // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
9844        // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
9845        // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
9846        // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
9847        // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
9848        // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
9849        // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
9850        // generation exactly where the last turn stopped — no prime at all. The stashed
9851        // `next_pred` plays prime_logits' role: it is the token produced from the logits after
9852        // committed.last() by the same rule this entry applies to a cold prime's last row —
9853        // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
9854        // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
9855        // where the sampler and the session's Philox counters were live). `last_h` seeds the
9856        // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
9857        let continuation = prompt.is_empty();
9858        if continuation {
9859            assert!(session_mode, "empty prompt requires a session");
9860            assert!(
9861                sess_tail
9862                    .as_ref()
9863                    .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
9864                        && lh.is_some()
9865                        && (np.is_some() || carried_pending.is_some())),
9866                "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
9867            );
9868        }
9869        let mut prime_logits;
9870        let mut prompt_h: Option<CudaSlice<f32>> = None;
9871        let t_prime = std::time::Instant::now();
9872        let batched_prime = !continuation
9873            && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
9874            && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
9875            && !e.frozen_cpu_experts_prefer_tokenwise_prime();
9876        let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
9877        if prime_split.is_some() && continuation {
9878            return Err("spec prime split requires a non-empty prime".into());
9879        }
9880        // STABLE-BOUNDARY TURN CHECKPOINT stop (lane/frspec-multiturn-cache, 2026-08-21):
9881        // the worker's `ckpt_at` request, ABSOLUTE -> prompt-relative. On WARM bursts
9882        // (base != 0, an affinity-rewound or pool-resumed session priming its own delta)
9883        // this is the only stop; on COLD bursts it usually coincides with `prime_split`
9884        // (both are the plain tier's stable pre-generation boundary). A boundary the prime
9885        // cannot honor (outside this prime's range) silently drops the capture — the
9886        // turn_ckpt convention: the next turn re-primes in full, never a wrong resume.
9887        let ckpt_rel = if continuation {
9888            None
9889        } else {
9890            ckpt_req
9891                .and_then(|abs| abs.checked_sub(base))
9892                .filter(|&r| r > 0 && r < prompt.len())
9893        };
9894        // Prime stops, ordered: each is a boundary the prime halts at so the in-place GDN
9895        // conv/ssm state can be snapshotted there (the only moment it exists). One stop =
9896        // the legacy single-split program, byte-for-byte.
9897        let mut stops: Vec<usize> = Vec::new();
9898        for b in [prime_split, ckpt_rel].into_iter().flatten() {
9899            if !stops.contains(&b) {
9900                stops.push(b);
9901            }
9902        }
9903        stops.sort_unstable();
9904        // Captured at the ckpt stop, installed into the session slot post-prime (replacing
9905        // the legacy prompt-end capture). Some(None) = capture attempted and failed -> the
9906        // slot is cleared (a stale checkpoint would rewind to the WRONG boundary).
9907        let mut ckpt_early: Option<Option<SpecCheckpoint>> = None;
9908        if continuation {
9909            prime_logits = Vec::new();
9910        } else if !stops.is_empty() {
9911            if let Some(&first) = stops.first() {
9912                if prime_split == Some(first) && first < crate::hybrid_forward::PRIME_MIN_T {
9913                    return Err(format!(
9914                        "spec prime split {first} is below PRIME_MIN_T {}",
9915                        crate::hybrid_forward::PRIME_MIN_T,
9916                    )
9917                    .into());
9918                }
9919            }
9920            // Mirror the plain worker's boundary stops exactly. Each segment is a
9921            // request-level prime (`queued_after` keeps Step35 arm selection independent of
9922            // the stops — tick-seg law); a segment below PRIME_MIN_T (and the final tail
9923            // under MEMRA_PRIME_TOKENWISE) takes the same eager tokenwise continuation as
9924            // prefill_tick. Retain every hidden row so the draft scratch fill remains one
9925            // coherent prompt.
9926            let mut h_all = e.uninit(prompt.len() * n_embd)?;
9927            prime_logits = Vec::new();
9928            let mut prev = 0usize;
9929            for seg_end in stops.iter().copied().chain(std::iter::once(prompt.len())) {
9930                if seg_end <= prev {
9931                    continue;
9932                }
9933                let seg = &prompt[prev..seg_end];
9934                let is_final = seg_end == prompt.len();
9935                let batched_seg = seg.len() >= crate::hybrid_forward::PRIME_MIN_T
9936                    && (!is_final
9937                        || (std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
9938                            && !e.frozen_cpu_experts_prefer_tokenwise_prime()));
9939                if batched_seg {
9940                    let (l, _, h_seg) =
9941                        self.prime_cache(e, seg, &mut *cache, prompt.len() - seg_end)?;
9942                    e.copy_into(&mut h_all, prev * n_embd, &h_seg, seg.len() * n_embd)?;
9943                    prime_logits = l;
9944                } else {
9945                    for (i, &tok) in seg.iter().enumerate() {
9946                        let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
9947                        e.copy_into(&mut h_all, (prev + i) * n_embd, &h, n_embd)?;
9948                        prime_logits = l;
9949                    }
9950                }
9951                prev = seg_end;
9952                if is_final {
9953                    break;
9954                }
9955                debug_assert_eq!(cache.pos, base + seg_end, "prime stop landed off boundary");
9956                // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm
9957                // states are about to be advanced in place by the next segment, so this is
9958                // the ONLY moment the boundary's recurrent state exists. Capture iff the
9959                // worker requested exactly this stop (cold sessions only — `capture_at` is
9960                // never armed warm). A failed snapshot is silent (turn_ckpt convention) —
9961                // publication is an optimization, never a correctness dependency.
9962                if base == 0 {
9963                    if let Some((requested, slot)) = sess_capture.as_mut() {
9964                        // Publish at the requested miss-LCP stop (the shared-prefix class)
9965                        // AND at the stable-boundary stop (the next-turn re-render class,
9966                        // lane/frspec-multiturn-cache) — the same boundary set the plain
9967                        // prefill tick learns. Without the second entry, the turn after a
9968                        // cold re-park could only hit the OLDER lcp entry (the measured
9969                        // one-turn transient: t3 restored 607 of 24122 while the plain arm
9970                        // rewound to 15222). Dedupe is the worker sweep's has_key.
9971                        if *requested == Some(seg_end) || ckpt_rel == Some(seg_end) {
9972                            if let Ok(snap) = cache.snapshot(e) {
9973                                slot.push(SpecBoundaryCapture {
9974                                    snap,
9975                                    pos: seg_end,
9976                                    logits: prime_logits.clone(),
9977                                    // rows [0..seg_end) of h_all are primed — the following
9978                                    // segments append, never overwrite.
9979                                    last_h: capture_boundary_hidden(e, &h_all, seg_end, n_embd),
9980                                });
9981                            }
9982                        }
9983                    }
9984                }
9985                // SESSION-AFFINITY TURN CHECKPOINT at the STABLE boundary (see `ckpt_at`):
9986                // same snapshot mechanics, installed post-prime in place of the prompt-end
9987                // capture the re-render class always diverged below.
9988                if ckpt_rel == Some(seg_end) {
9989                    let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
9990                        e.uninit(n_embd).and_then(|mut a| {
9991                            e.copy_view_into(
9992                                &mut a,
9993                                0,
9994                                &h_all.slice((seg_end - 1) * n_embd..seg_end * n_embd),
9995                                n_embd,
9996                            )?;
9997                            Ok(a)
9998                        });
9999                    ckpt_early = Some(match (cache.snapshot(e), anchor) {
10000                        (Ok(snap), Ok(last_h)) => Some(SpecCheckpoint {
10001                            snap,
10002                            pos: base + seg_end,
10003                            last_h,
10004                        }),
10005                        _ => None,
10006                    });
10007                }
10008            }
10009            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
10010                eprintln!(
10011                    "[spec-prime] stops={stops:?} tail={}",
10012                    prompt.len() - stops.last().copied().unwrap_or(0)
10013                );
10014            }
10015            prompt_h = Some(h_all);
10016        } else if batched_prime {
10017            let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
10018            prime_logits = l;
10019            prompt_h = Some(hiddens);
10020        } else {
10021            prime_logits = Vec::new();
10022            prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
10023            for (i, &tok) in prompt.iter().enumerate() {
10024                let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
10025                if let Some(ph) = prompt_h.as_mut() {
10026                    e.copy_into(ph, i * n_embd, &h, n_embd)?;
10027                }
10028                prime_logits = l;
10029            }
10030        }
10031        e.stream().synchronize()?;
10032        // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
10033        // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
10034        // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
10035        // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
10036        // prime_split. The mid-prompt capture above already consumed the request if it matched.
10037        if !continuation && base == 0 {
10038            if let Some((requested, slot)) = sess_capture.as_mut() {
10039                if *requested == Some(prompt.len()) && slot.is_empty() {
10040                    debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
10041                    if let Ok(snap) = cache.snapshot(e) {
10042                        slot.push(SpecBoundaryCapture {
10043                            snap,
10044                            pos: prompt.len(),
10045                            logits: prime_logits.clone(),
10046                            last_h: prompt_h
10047                                .as_ref()
10048                                .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
10049                                .unwrap_or_default(),
10050                        });
10051                    }
10052                }
10053            }
10054        }
10055        // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
10056        // prime-subtraction hack.
10057        crate::PRIME_NANOS.store(
10058            t_prime.elapsed().as_nanos() as u64,
10059            std::sync::atomic::Ordering::Relaxed,
10060        );
10061
10062        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10063        // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
10064        // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
10065        let host_embd = spec_host_embd();
10066        let embd_gpu = if host_embd {
10067            None
10068        } else {
10069            Some(
10070                self.embd_gpu
10071                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10072            )
10073        };
10074        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10075        if host_embd {
10076            eprintln!(
10077                "[spec] host-row embedding: {} bytes kept off HBM",
10078                self.embd.raw.len()
10079            );
10080        }
10081        let mut out: Vec<u32> = Vec::with_capacity(max_new);
10082        let mut total_drafted = 0usize;
10083        let mut total_accepted = 0usize;
10084
10085        // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
10086        // The sampler config, the session's Philox counters and the penalty window are parsed
10087        // HERE, above the boundary-token selection, because the boundary token must be drawn
10088        // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
10089        // selection, which is the whole mechanical reason the boundary token was an argmax:
10090        // the sampler state was not in scope yet. Nothing here depends on the round loop, so
10091        // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
10092        // below takes the argmax path it always took).
10093        // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
10094        // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
10095        // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
10096        // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
10097        let sp = sampling.unwrap_or_else(|| SpecSampling {
10098            temp: std::env::var("MEMRA_SPEC_TEMP")
10099                .ok()
10100                .and_then(|v| v.parse().ok())
10101                .unwrap_or(0.0),
10102            seed: std::env::var("MEMRA_SEED")
10103                .ok()
10104                .and_then(|v| v.parse().ok())
10105                .unwrap_or(42),
10106            top_k: std::env::var("MEMRA_TOP_K")
10107                .ok()
10108                .and_then(|v| v.parse().ok())
10109                .unwrap_or(0),
10110            top_p: std::env::var("MEMRA_TOP_P")
10111                .ok()
10112                .and_then(|v| v.parse().ok())
10113                .unwrap_or(1.0),
10114            min_p: std::env::var("MEMRA_MIN_P")
10115                .ok()
10116                .and_then(|v| v.parse().ok())
10117                .unwrap_or(0.0),
10118            penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
10119                .ok()
10120                .and_then(|v| v.parse().ok())
10121                .unwrap_or(0),
10122            penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
10123                .ok()
10124                .and_then(|v| v.parse().ok())
10125                .unwrap_or(1.0),
10126            penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
10127                .ok()
10128                .and_then(|v| v.parse().ok())
10129                .unwrap_or(0.0),
10130            penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
10131                .ok()
10132                .and_then(|v| v.parse().ok())
10133                .unwrap_or(0.0),
10134        });
10135        let (sp_temp, sp_seed) = (sp.temp, sp.seed);
10136        let sampled = sp_temp > 0.0;
10137        // Counters resume from the session (burst continuity: randomness must never repeat
10138        // across generate_spec_session calls); one-shot callers start at (0,0). Read through
10139        // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
10140        let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
10141        let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
10142        // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
10143        // for the penalized+filtered target). History = generated tokens, host-tracked window.
10144        let pen_on = sampled
10145            && sp.penalty_last_n > 0
10146            && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
10147        // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
10148        // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
10149        // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
10150        // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
10151        // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
10152        // which is what the API contract says and what the plain sampler's own `history` does.
10153        // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
10154        let mut pen_hist: Vec<u32> = if pen_on {
10155            let sess_hist: &[u32] = if spec_pen_session_on() {
10156                sess_tail
10157                    .as_ref()
10158                    .map(|(c, ..)| c.as_slice())
10159                    .unwrap_or(&[])
10160            } else {
10161                &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
10162            };
10163            pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
10164        } else {
10165            Vec::new()
10166        };
10167        // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
10168        // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
10169        // request's own filtered/penalized target through the session's Philox stream
10170        // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
10171        // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
10172        // Emit it, then FEED it to establish the loop invariant below.
10173        // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
10174        // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
10175        // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
10176        // prompt's last logits (plain constrained-greedy identity); a continuation without
10177        // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
10178        // worker never resumes constrained sessions from the pool, so this cannot fire).
10179        if let Some(c) = constraint.as_deref_mut() {
10180            if continuation && carried_pending.is_none() {
10181                return Err("constrained spec continuation requires a carried pending \
10182                            (pool resume is unconstrained-only)"
10183                    .into());
10184            }
10185            if !continuation {
10186                c.mask_logits(&mut prime_logits)
10187                    .map_err(|e2| format!("constraint: {e2}"))?;
10188            }
10189        }
10190        let mut last_token = if let Some(b) = carried_pending {
10191            b
10192        } else if continuation {
10193            // A continuation's boundary token was DRAWN by the burst that stashed it (the
10194            // session tail below), or by `spec_session_from_restored` for a converted
10195            // prefix-cache hit — in both cases from the correct logits row with this same
10196            // session's Philox stream, which is why it can be consumed here as-is.
10197            sess_tail.as_ref().unwrap().2.unwrap()
10198        } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
10199            sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
10200        } else {
10201            // greedy (byte contract), the rollback door, or constrained (masked-argmax
10202            // identity — the worker routes sampled+constrained to the plain path, and this
10203            // function refuses the combination outright above).
10204            argmax(&prime_logits) as u32
10205        };
10206        if pen_on {
10207            // The boundary token is a GENERATED token: the plain sampler `accept()`s every
10208            // emitted token into its penalty history, and pre-lane the burst's first token
10209            // was invisible to penalties forever (never pushed, and never in `committed`
10210            // until this burst's tail). Covers the carry/continuation seeds too — neither is
10211            // in `committed` yet.
10212            pen_hist.push(last_token);
10213        }
10214        if carried_pending.is_none() {
10215            out.push(last_token);
10216            // grammar advances with every emitted token (carried pendings were consumed
10217            // by the burst that emitted them).
10218            if let Some(c) = constraint.as_deref_mut() {
10219                c.consume(last_token)
10220                    .map_err(|e2| format!("constraint: {e2}"))?;
10221            }
10222        }
10223        if continuation {
10224            // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
10225            // overhang so the chain's first append lands at slot base (== committed.len()).
10226            scratch.set_len(e, base)?;
10227        }
10228        // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
10229        // concatenating to the full `out`). Called after the prime's first token and after each
10230        // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
10231        // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
10232        // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
10233        fn flush_commit(
10234            cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
10235            out: &[u32],
10236            flushed: &mut usize,
10237        ) -> bool {
10238            if let Some(f) = cb.as_mut() {
10239                let keep = f(&out[*flushed..]);
10240                *flushed = out.len();
10241                keep
10242            } else {
10243                true
10244            }
10245        }
10246        keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
10247        // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
10248        // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
10249        // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
10250        // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
10251        // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
10252        // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
10253        // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
10254        // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
10255        // those, so their residual mass is p(x), correct by construction).
10256        let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
10257            match &mtp.d2t {
10258                Some(map) => Some(e.htod_u32_v(map)?),
10259                None => None,
10260            }
10261        } else {
10262            None
10263        };
10264        let mut q_full_buf: Option<CudaSlice<f32>> = None;
10265        // host Philox4x32-10 accept-test uniforms: module fn `host_u01` (shared with the
10266        // dspark sampled-admission walk); byte-identical to the closure it replaces.
10267        let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
10268        let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
10269        let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
10270        let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
10271        let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
10272        let mut pen_hist_d: Option<CudaSlice<u32>> = None;
10273        let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
10274        // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
10275        // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
10276        // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
10277        let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
10278        let t_ent = std::time::Instant::now();
10279
10280        // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
10281        // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
10282        // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
10283        // the one that matters (a history-rewriting client mutates what the session GENERATED,
10284        // so the next turn's prompt agrees with this one up to exactly here).
10285        //
10286        // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
10287        // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
10288        // hold exactly `base + prompt.len()` rows and nothing generated.
10289        //
10290        // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
10291        // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
10292        // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
10293        // `<think>` block the client strips, so every later turn's diff diverged exactly one
10294        // token below the checkpoint and affinity declined 100% of the time. Measured on the
10295        // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
10296        // whole mechanism inert while looking, from the outside, like a working
10297        // correctness-declines-safely path — hence the decline log carries the offsets.
10298        //
10299        // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
10300        // state (the reason a spec session could not rewind before). The draft scratch needs no
10301        // copy: rows below the boundary are rewritten by the next turn's own fill.
10302        //
10303        // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
10304        // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
10305        // checkpoint rather than replacing it with a strictly worse one.
10306        //
10307        // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
10308        // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
10309        // fail the burst that is already running — so the error is swallowed, loud only under
10310        // MEMRA_DEBUG_SPEC.
10311        //
10312        // STABLE-BOUNDARY OVERRIDE (lane/frspec-multiturn-cache, 2026-08-21): the prompt-end
10313        // posture above was DISPROVED for the think-posture template class — the prompt's own
10314        // tail is the live generation header (`<|im_start|>assistant\n<think>\n`) that the
10315        // next turn's re-render replaces, so the diff diverged a couple tokens BELOW the
10316        // checkpoint and affinity declined 100% of multi-turn agent traffic (the same class
10317        // the plain tier fixed on 2026-08-09 via `plain_checkpoint_boundary`; the port to the
10318        // spec tier is this lane). When the worker armed `ckpt_at`, the capture happened at
10319        // that stop inside the prime above (`ckpt_early`) and is installed here instead;
10320        // capture-attempted-but-failed clears the slot exactly like the legacy arm.
10321        if let Some(slot) = sess_ckpt_slot {
10322            if let Some(early) = ckpt_early {
10323                if early.is_none() && std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
10324                    eprintln!(
10325                        "[spec] stable-boundary turn checkpoint skipped; \
10326                               next turn re-primes in full"
10327                    );
10328                }
10329                *slot = early;
10330            } else if !continuation {
10331                let pos = cache.pos;
10332                debug_assert_eq!(
10333                    pos,
10334                    base + prompt.len(),
10335                    "turn checkpoint must sit at the prompt end, before the init feed"
10336                );
10337                let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
10338                    if let Some(ph) = &prompt_h {
10339                        // hidden of the LAST primed row = the predecessor anchor at this
10340                        // boundary (exactly what a fresh prime of committed[..pos] leaves in
10341                        // last_h, and what the next prime's fill reads for its first row).
10342                        let np = prompt.len();
10343                        e.uninit(n_embd).and_then(|mut a| {
10344                            e.copy_view_into(
10345                                &mut a,
10346                                0,
10347                                &ph.slice((np - 1) * n_embd..np * n_embd),
10348                                n_embd,
10349                            )?;
10350                            Ok(a)
10351                        })
10352                    } else {
10353                        Err("no prompt hiddens".into())
10354                    };
10355                match (cache.snapshot(e), anchor) {
10356                    (Ok(snap), Ok(last_h)) => {
10357                        *slot = Some(SpecCheckpoint { snap, pos, last_h });
10358                    }
10359                    (s, a) => {
10360                        *slot = None; // a stale checkpoint would rewind to the WRONG boundary
10361                        if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
10362                            let err = s
10363                                .err()
10364                                .map(|e| e.to_string())
10365                                .or_else(|| a.err().map(|e| e.to_string()))
10366                                .unwrap_or_default();
10367                            eprintln!(
10368                                "[spec] turn checkpoint skipped ({err}); \
10369                                       next turn re-primes in full"
10370                            );
10371                        }
10372                    }
10373                }
10374            }
10375        }
10376        // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
10377        // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
10378        // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
10379        // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
10380        let mut last_pred = 0u32;
10381        let mut last_col_logits: Option<CudaSlice<f32>> = None;
10382        // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
10383        // recompute in the grammar-truncation walk — retained host-side, round 0 only.
10384        let mut init_logits_host: Option<Vec<f32>> = None;
10385        let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
10386            let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
10387            last_pred = argmax(&init_logits) as u32;
10388            if constraint.is_some() {
10389                init_logits_host = Some(init_logits.clone());
10390            }
10391            // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
10392            if sampled {
10393                last_col_logits = Some(e.htod(&init_logits)?);
10394            }
10395            h
10396        } else {
10397            // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
10398            let lh = sess_tail
10399                .as_ref()
10400                .unwrap()
10401                .1
10402                .as_ref()
10403                .expect("pending carry requires last_h");
10404            e.clone_dtod(lh)?
10405        };
10406        let t_init = t_ent.elapsed();
10407        let mut last_col_stats: Option<(f32, f32, f32)> = None;
10408        // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
10409        // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
10410        // stable pointer for the graph-draft round-start copy.
10411        let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
10412        // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
10413        // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
10414        // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
10415        // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
10416        // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
10417        // overwritten below).
10418        let mut fill_prev = e.clone_dtod(&h_seed0)?;
10419        {
10420            if let Some(ph) = &prompt_h {
10421                let np = prompt.len();
10422                e.copy_view_into(
10423                    &mut h_seed_buf,
10424                    0,
10425                    &ph.slice((np - 1) * n_embd..np * n_embd),
10426                    n_embd,
10427                )?;
10428            } else if continuation {
10429                if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
10430                    if let Some(lh) = lh.as_ref() {
10431                        e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
10432                    }
10433                }
10434            }
10435        }
10436        // Persistent device prediction slots for the accept walk (max k+1 verify columns).
10437        let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
10438
10439        let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
10440        let fork_mode = OptiForkGateMode::configured();
10441        // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
10442        // the end. Metric normalization vs the reference engine: BOTH engines count
10443        // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
10444        // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
10445        let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
10446        let mut st_drafted = vec![0usize; k];
10447        let mut st_accepted = vec![0usize; k];
10448        let mut st_len_hist = vec![0usize; k + 1];
10449        let mut st_full = 0usize;
10450        // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
10451        // stop the draft chain early when the head's softmax confidence in its own pick drops
10452        // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
10453        static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
10454        let p_min = *PMIN.get_or_init(|| {
10455            std::env::var("MEMRA_SPEC_PMIN")
10456                .ok()
10457                .and_then(|v| v.parse().ok())
10458                .unwrap_or(0.0)
10459        });
10460        // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
10461        // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
10462        // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
10463        // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
10464        // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
10465        // verify batch is not); the j==0 exemption stays for pending-less rounds.
10466        let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
10467            .map(|v| v == "1")
10468            .unwrap_or(false);
10469
10470        // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
10471        // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
10472        // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
10473        // cuBLAS path in an exotic head) falls back to the eager draft chain.
10474        // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
10475        // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
10476        // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
10477        // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
10478        // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
10479        // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
10480        // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
10481        // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
10482        let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
10483            Some(c) => c,
10484            None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
10485        };
10486        // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
10487        // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
10488        if sampled && dctx.g_q.len() < d_vocab {
10489            dctx.g_q = e.zeros(d_vocab)?;
10490            dctx.g_perturb = e.zeros(d_vocab)?;
10491        }
10492        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
10493        // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
10494        // truncation (the correctness backstop) stops cutting every tight-schema round.
10495        // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
10496        // shape, so a parked graph of the other shape is dropped and recaptured.
10497        let dmask_on = constraint
10498            .as_deref()
10499            .is_some_and(|c| c.draft_mask_enabled());
10500        let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
10501        if dmask_on && dctx.g_dmask.len() < dmask_words {
10502            dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
10503            dctx.graph = None; // the old capture baked the old (or no) mask pointer
10504            dctx.failed.clear_greedy();
10505            dctx.keeper.clear();
10506        }
10507        if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
10508            dctx.graph = None;
10509            dctx.failed.clear_greedy();
10510            dctx.keeper.clear();
10511        }
10512        if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
10513            let DraftGraphCtx {
10514                g_tok,
10515                g_pos,
10516                g_seed,
10517                g_p,
10518                g_dmask,
10519                ..
10520            } = &mut dctx;
10521            // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
10522            // host uploads the position's real words, so the warmups stay grammar-free.
10523            if dmask_on {
10524                e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
10525            }
10526            let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
10527            // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
10528            // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
10529            // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
10530            // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
10531            // passes (and, in serve, other sessions) recycle those addresses and the replay then
10532            // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
10533            let cap_res = e.capture_graph_retained(|e| {
10534                self.mtp_head_forward_cap(
10535                    e,
10536                    mtp,
10537                    g_tok,
10538                    g_pos,
10539                    g_seed,
10540                    g_p,
10541                    &mut *scratch,
10542                    p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
10543                    true,
10544                    embd_gpu.expect("graph draft requires resident embedding"),
10545                    embd_qt,
10546                    embd_rb,
10547                    d_vocab,
10548                    None,
10549                    None,
10550                    if dmask_on {
10551                        Some((g_dmask_ro, dmask_words))
10552                    } else {
10553                        None
10554                    },
10555                )
10556            });
10557            match cap_res {
10558                Ok((g, keep)) => {
10559                    scratch.set_len(e, base)?;
10560                    dctx.graph = Some(g);
10561                    dctx.graph_masked = dmask_on;
10562                    dctx.keeper = keep;
10563                }
10564                Err(err) => {
10565                    scratch.set_len(e, base)?;
10566                    // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
10567                    // silent. Once per flip — mark returns None on an already-failed ctx.
10568                    if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
10569                        eprintln!("{line}");
10570                    }
10571                }
10572            }
10573        }
10574        // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
10575        // graph object, built only when sampled && graph-eligible — the greedy capture above is
10576        // untouched (and skipped when sampled: its graph would never be launched). Same head
10577        // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
10578        // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
10579        // once per round); the raw head logits land in the persistent g_q for the host's
10580        // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
10581        // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
10582        // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
10583        // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
10584        // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
10585        // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
10586        // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
10587        // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
10588        // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
10589        // this compare misses at most ONCE per resumed request — the first burst recaptures
10590        // and every later burst in that request replays. A client that wants the parked graph
10591        // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
10592        // stable across its whole conversation.
10593        // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
10594        // softmax — it can hold neither per-row filter stats nor the varying penalty history.
10595        // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
10596        // force the eager draft (which computes stats/penalties per row).
10597        // KEY THE WHOLE REGIME, not just the baked constants (lane/graph-s-key-exactness-
10598        // 20260819). `s_key` used to be `(seed, temp, k)`; the filters and penalties were left
10599        // out, so a filtered request resuming a session that parked a PURE-TEMP graph kept it —
10600        // and the launch site never re-asked `pure_temp`. See [`SampledGraphKey`] for what that
10601        // costs (an unconditional accept of out-of-head draft tokens, i.e. an exactness bug on
10602        // the request shape the vendor-default flip makes the majority).
10603        let s_key = SampledGraphKey::new(sp_seed, sp_temp, k, sp.top_k, sp.top_p, sp.min_p, pen_on);
10604        let pure_temp = s_key.pure_temp();
10605        if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
10606            dctx.graph_s = None;
10607            dctx.failed.clear_sampled();
10608            dctx.s_key = None;
10609            dctx.q_slots.clear();
10610            dctx.keeper_s.clear();
10611        }
10612        if graph_draft
10613            && sampled
10614            && pure_temp
10615            && dctx.graph_s.is_none()
10616            && !dctx.failed.sampled_failed()
10617        {
10618            let DraftGraphCtx {
10619                g_tok,
10620                g_pos,
10621                g_seed,
10622                g_p,
10623                g_ctr,
10624                g_perturb,
10625                g_q,
10626                ..
10627            } = &mut dctx;
10628            // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
10629            let cap_res = e.capture_graph_retained(|e| {
10630                self.mtp_head_forward_cap(
10631                    e,
10632                    mtp,
10633                    g_tok,
10634                    g_pos,
10635                    g_seed,
10636                    g_p,
10637                    &mut *scratch,
10638                    p_min > 0.0,
10639                    true,
10640                    embd_gpu.expect("graph draft requires resident embedding"),
10641                    embd_qt,
10642                    embd_rb,
10643                    d_vocab,
10644                    Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
10645                    None,
10646                    None, // constrained spec is greedy-only — sampled never carries a hook
10647                )
10648            });
10649            match cap_res {
10650                Ok((g, keep)) => {
10651                    scratch.set_len(e, base)?;
10652                    for _ in 0..k {
10653                        dctx.q_slots.push(e.zeros(d_vocab)?);
10654                    }
10655                    dctx.graph_s = Some(g);
10656                    dctx.s_key = Some(s_key);
10657                    dctx.keeper_s = keep;
10658                }
10659                Err(err) => {
10660                    scratch.set_len(e, base)?;
10661                    // LOUD flip (audit Q2): same contract as the greedy capture above.
10662                    if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
10663                        eprintln!("{line}");
10664                    }
10665                }
10666            }
10667        }
10668        // ---- EXACTNESS GUARD, the enforceable half (lane/graph-s-key-exactness-20260819) ----
10669        // With the filters and penalties in `s_key`, a graph that SURVIVED the drop above was
10670        // captured under this request's exact regime, and capture requires `pure_temp` — so a
10671        // parked graph implies `pure_temp`. That implication is the whole exactness argument for
10672        // the graph arm, so it is asserted here rather than assumed: a future change that widens
10673        // the capture condition, narrows the key, or copies a `DraftGraphCtx` across regimes
10674        // fails LOUDLY at this line instead of silently drafting from the raw softmax while the
10675        // verify applies filter stats. Release builds refuse the graph (drop it, draft eager)
10676        // rather than launching it; the launch site re-tests `pure_temp` independently.
10677        if sampled && !pure_temp && dctx.graph_s.is_some() {
10678            debug_assert!(
10679                false,
10680                "sampled draft graph parked under {:?} survived into a FILTERED request \
10681                 (top_k={} top_p={} min_p={} pen_on={}): the in-graph chain draws from the RAW \
10682                 softmax, so the verify's filtered q would test a distribution the draft was \
10683                 never sampled from",
10684                dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
10685            );
10686            eprintln!(
10687                "[spec] BUG: dropping a parked sampled draft graph that outlived its capture \
10688                 regime (s_key={:?}, request top_k={} top_p={} min_p={} pen_on={}); drafting \
10689                 EAGER — the key must carry every field that shapes q",
10690                dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
10691            );
10692            dctx.graph_s = None;
10693            dctx.s_key = None;
10694            dctx.q_slots.clear();
10695            dctx.keeper_s.clear();
10696        }
10697        // SKEY PROBE (MEMRA_SKEY_PROBE=1): the burst-entry facts the reachability question turns
10698        // on — is this request sampled, is it in the pure-temp regime the sampled graph is only
10699        // legal in, and is a graph PARKED from an earlier request of the same session? The launch
10700        // arms below print which chain actually ran, so the probe never restates the condition.
10701        if skey_probe() {
10702            eprintln!(
10703                "[skey] burst sampled={} pure_temp={} temp={} top_k={} top_p={} min_p={} \
10704                 pen_on={} k={} graph_draft={} graph_s_parked={} s_key_parked={:?}",
10705                sampled as u8,
10706                pure_temp as u8,
10707                sp_temp,
10708                sp.top_k,
10709                sp.top_p,
10710                sp.min_p,
10711                pen_on as u8,
10712                k,
10713                graph_draft as u8,
10714                dctx.graph_s.is_some() as u8,
10715                dctx.s_key,
10716            );
10717        }
10718        let t_cap = t_ent.elapsed();
10719        // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
10720        // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
10721        // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
10722        // fill: the first chain step processes it and appends its entry at slot prompt.len().
10723        if let Some(ph) = &prompt_h {
10724            // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
10725            // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
10726            // global positions [base..base+tp). Fresh call: base==0, identical to before.
10727            scratch.set_len(e, base)?;
10728            // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
10729            // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
10730            // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
10731            // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
10732            let tp = prompt.len();
10733            let fill_chunk: usize = if crate::cache::swa_ring_on() {
10734                crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
10735            } else {
10736                // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
10737                // meaning one monolithic fill.
10738                std::env::var("MEMRA_PRIME_CHUNK")
10739                    .ok()
10740                    .and_then(|v| v.parse().ok())
10741                    .unwrap_or(4096)
10742            };
10743            let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
10744            let mut start = 0usize;
10745            while start < tp {
10746                let end = (start + fill_chunk).min(tp);
10747                let tc = end - start;
10748                {
10749                    // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
10750                    // reference engine's initial pending-h is zeroed too); a session turn's row 0
10751                    // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
10752                    // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
10753                    let mut phs = e.zeros(tc * n_embd)?;
10754                    let (src_lo, dst_off) = if start == 0 {
10755                        (0, n_embd)
10756                    } else {
10757                        ((start - 1) * n_embd, 0)
10758                    };
10759                    let n_copy = if start == 0 {
10760                        (tc - 1) * n_embd
10761                    } else {
10762                        tc * n_embd
10763                    };
10764                    if start == 0 {
10765                        if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
10766                            if let Some(lh) = lh.as_ref() {
10767                                e.copy_into(&mut phs, 0, lh, n_embd)?;
10768                            }
10769                        }
10770                    }
10771                    if n_copy > 0 {
10772                        e.copy_view_into(
10773                            &mut phs,
10774                            dst_off,
10775                            &ph.slice(src_lo..src_lo + n_copy),
10776                            n_copy,
10777                        )?;
10778                    }
10779                    self.mtp_kv_fill_all(
10780                        e,
10781                        &prompt[start..end],
10782                        &phs,
10783                        base + start,
10784                        &mut *scratch,
10785                        embd_dev,
10786                    )?;
10787                }
10788                start = end;
10789            }
10790        }
10791        // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
10792        // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
10793        // (=1 brackets the whole call in run_spec.rs, prime included.)
10794        if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
10795            unsafe extern "C" {
10796                fn cudaProfilerStart() -> i32;
10797            }
10798            unsafe {
10799                cudaProfilerStart();
10800            }
10801        }
10802        // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
10803        // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
10804        // consume each other's device outputs; the host drains the ring every M rounds. v1
10805        // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
10806        // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
10807        // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
10808        // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
10809        // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
10810        let stream_on = crate::spec::spec_stream()
10811            && !sampled
10812            && !spec_replay
10813            && self.mtp_extra.is_empty()
10814            && constraint.is_none()
10815            && !session_mode
10816            && embd_gpu.is_some()
10817            && !crate::model::full_prec_enabled()
10818            && k + 2 < 96;
10819        let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
10820        let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
10821        if stream_on {
10822            let cap = e.capture_graph(|e| {
10823                for j in 0..k.max(1) {
10824                    self.mtp_head_forward_cap(
10825                        e,
10826                        mtp,
10827                        &mut dctx.g_tok,
10828                        &mut dctx.g_pos,
10829                        &mut dctx.g_seed,
10830                        &mut dctx.g_p,
10831                        &mut *scratch,
10832                        true,
10833                        true,
10834                        embd_gpu.expect("round stream requires resident embedding"),
10835                        embd_qt,
10836                        embd_rb,
10837                        d_vocab,
10838                        None,
10839                        Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
10840                        None, // round-stream requires constraint.is_none() (see stream_on)
10841                    )?;
10842                }
10843                Ok(())
10844            });
10845            match cap {
10846                Ok(g) => {
10847                    scratch.set_len(e, 0)?;
10848                    stream_graph = Some(g);
10849                }
10850                Err(err) => {
10851                    scratch.set_len(e, 0)?;
10852                    if debug_spec {
10853                        eprintln!("[spec] stream-graph capture failed ({err}); stream off");
10854                    }
10855                }
10856            }
10857        }
10858        let stream_active = stream_on && stream_graph.is_some();
10859        if debug_spec {
10860            eprintln!(
10861                "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
10862                crate::spec::spec_stream(),
10863                dctx.graph.is_some(),
10864                stream_graph.is_some()
10865            );
10866        }
10867        let t_v_s = k + 1;
10868        // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
10869        // module (extracted 2026-07-12; the gemma burst reuses them).
10870        let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
10871        let crate::round_stream::StreamBufs {
10872            mut vtok_d,
10873            mut brk_d,
10874            mut pend_d,
10875            last_pred_d,
10876            mut pos_ctr,
10877            mut pos_start_d,
10878            mut ring_d,
10879            acc_d: mut stream_acc,
10880            m_rounds,
10881            k: _,
10882        } = sb;
10883        let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
10884            Some(crate::round_stream::kv_len_ptr_table(
10885                e,
10886                cache,
10887                Some(&pos_ctr),
10888            )?)
10889        } else {
10890            None
10891        };
10892
10893        let t_fill = t_ent.elapsed();
10894        let mut round = 0usize;
10895        // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
10896        // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
10897        // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
10898        // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
10899        // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
10900        // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
10901        // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
10902        // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
10903        // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
10904        // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
10905        // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
10906        // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
10907        // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
10908        // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
10909        // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
10910        // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
10911        // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
10912        // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
10913        // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
10914        // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
10915        // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
10916        // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
10917        // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
10918        // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
10919        // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
10920        // K=1..8 self-consistency PASS both models with the law ON (exactness held).
10921        let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
10922        // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
10923        // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
10924        let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
10925            .ok()
10926            .and_then(|v| v.parse().ok());
10927        let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
10928            4
10929        } else if self.cfg.n_embd as usize >= 2500 {
10930            2
10931        } else {
10932            1
10933        };
10934        let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
10935        // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
10936        // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
10937        // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
10938        let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
10939            .ok()
10940            .and_then(|v| v.parse().ok())
10941            .unwrap_or(1024);
10942        let floor_at = |pos: usize| -> usize {
10943            if adapt_floor_env.is_some() || pos < floor_ctx {
10944                adapt_floor
10945            } else if adapt_floor >= 4 {
10946                1
10947            } else {
10948                adapt_floor
10949            }
10950        };
10951        // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
10952        // fixed-K default path is untouched by this whole block.
10953        let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
10954            .ok()
10955            .and_then(|v| v.parse().ok())
10956            .unwrap_or(7);
10957        let k_cap = k.min(cap_max).max(1);
10958        let mut kc = k_cap;
10959        let mut opti_fork: Option<OptiForkState> = None;
10960        let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
10961        if fork_mode != OptiForkGateMode::Disabled {
10962            let fence = crate::pp::pp_cuts(self.layers.len());
10963            let refusal = if !session_mode {
10964                Some("not-session")
10965            } else if k != 1 || adapt {
10966                Some("requires-fixed-k1")
10967            } else if sampled || constraint.is_some() || spec_replay {
10968                Some("sampled-constrained-or-replay")
10969            } else if pipe.is_some() {
10970                Some("two-session-pipeline")
10971            } else if !spec_devacc() {
10972                Some("requires-device-accept")
10973            } else if stream_active || crate::spec::spec_stream() {
10974                Some("round-stream")
10975            } else if !self.mtp_extra.is_empty() {
10976                Some("multi-head-mtp")
10977            } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
10978                Some("swa-ring")
10979            } else if crate::pp::pp_host_bounce_active() {
10980                Some("host-bounce")
10981            } else if fork_mode == OptiForkGateMode::Controller
10982                && cache.recur.iter().any(Option::is_some)
10983            {
10984                Some("controller-requires-zero-recurrent-state")
10985            } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
10986                Some("requires-pp2")
10987            } else {
10988                None
10989            };
10990            if let Some(reason) = refusal {
10991                OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10992                eprintln!("[opti-fork] refused reason={reason}");
10993            } else {
10994                let fence = fence.expect("validated PP-2 fence");
10995                let rt = crate::pp::PpNRt::get(e)?;
10996                let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
10997                let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
10998                let primary_supported =
10999                    primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
11000                if !rt.cross_device() || !primary_supported {
11001                    OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11002                    eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
11003                } else {
11004                    // Both recurrent snapshots and both seed generations are allocated before
11005                    // the first fork, each through its owning PP stage. Allocation failure
11006                    // therefore happens before any optimistic state mutation can occur.
11007                    let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
11008                    let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
11009                    let fork = OptiForkState::new(
11010                        e,
11011                        cache,
11012                        fork_mode,
11013                        alternate_snapshot,
11014                        &h_seed_buf,
11015                        &fill_prev,
11016                        rt,
11017                        fence[1],
11018                        self.layers.len(),
11019                    )?;
11020                    eprintln!(
11021                        "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
11022                         payload_dev0={} payload_dev1={} q_threshold={:.3}",
11023                        fence[1],
11024                        fork.logical_payload_bytes[0],
11025                        fork.logical_payload_bytes[1],
11026                        fork.controller.map_or(0.0, |policy| policy.threshold),
11027                    );
11028                    fork_snapshot = Some(current_snapshot);
11029                    opti_fork = Some(fork);
11030                }
11031            }
11032        }
11033        // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
11034        // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
11035        let mut snap = match fork_snapshot {
11036            Some(snapshot) => snapshot,
11037            None => cache.snapshot(e)?,
11038        };
11039        let mut carried_opti: Option<OptiControllerTicket> = None;
11040        // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
11041        // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
11042        let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
11043            Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
11044        } else {
11045            None
11046        };
11047        // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
11048        // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
11049        // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
11050        // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
11051        // pass of any kind). Verify still
11052        // checks every emitted token against the target -> exactness holds by construction; only
11053        // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
11054        // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
11055        // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
11056        let mut pending: Option<u32> = carried_pending;
11057        // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
11058        // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
11059        // the verify accept readback). Printed once at loop end via spec-stats.
11060        let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
11061        let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
11062        // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
11063        // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
11064        let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
11065        // grammar-truncation counters: how many rounds the verify-side cut fired and how many
11066        // already-verified tokens it threw away. THIS is the quantity draft masking targets.
11067        let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
11068        let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
11069        let mut ph_wait = 0f64;
11070        let mut ph_commit = 0f64;
11071        let mut ph_t = std::time::Instant::now();
11072        let mut ph_mark = |acc: &mut f64, on: bool| {
11073            if on {
11074                let now = std::time::Instant::now();
11075                *acc += (now - ph_t).as_secs_f64();
11076                ph_t = now;
11077            }
11078        };
11079        // MTP-ROUTE VERIFY GRAPHS (`MEMRA_SPEC_VERIFY_GRAPH`, see the flag doc): the
11080        // model-owned capture pool, locked for the whole burst exactly as the dspark serve
11081        // arm holds it — the slab stash is live verify -> commit inside a round, and the
11082        // worker drives rounds from one scheduler thread. PERSISTENT across generations on
11083        // the model (rebuilding per call re-captures the pool per prompt, which is the
11084        // measured way to lose more than the launches cost); the captured bodies are
11085        // cache-independent, every state read going through per-round refreshed pointer
11086        // tables. None = the eager walk, byte-identical.
11087        //
11088        // Never armed together with ROUND-STREAM: the tparallel verify refuses that pair
11089        // loudly, and `stream_active` owns the burst arm above, so the door stays shut
11090        // whenever the stream is live rather than relying on that refusal.
11091        // The lock is taken ONLY when the door is armed: with the flag off this whole block
11092        // is inert, so the default path cannot serialize two spec generations behind a mutex
11093        // it never reads.
11094        let vg_armed =
11095            crate::spec::spec_verify_graph_env().unwrap_or_else(|| self.vgraph_family_default());
11096        let mut vg_guard = if vg_armed && !stream_active {
11097            let mut g = self.dspark_vgraphs.lock().unwrap();
11098            if g.is_none() {
11099                // Size by the WIDEST verify this run can present, which is k+1 and NOT
11100                // k_cap+1: the sampled arm's own window is `t_v_s = k + 1`, so a pool built
11101                // from a smaller adaptive cap gets sliced past its stash rows (a `slice_mut`
11102                // panic in the sampled ON arm, measured before this line said k+1).
11103                let vt_cap = (k.max(k_cap) + 1).max(2);
11104                *g = DsparkVerifyGraphs::new(e, cache, vt_cap, n_embd)?;
11105                if g.is_some() {
11106                    // Engagement receipt (the dead-arm lesson): prove the door is LIVE rather
11107                    // than trusting that a flag set means a pool built.
11108                    eprintln!("[spec-vg] MTP verify-graph pool ENGAGED (vt_cap={vt_cap})");
11109                } else {
11110                    eprintln!(
11111                        "[spec-vg] MTP verify-graph pool declined (no linear layers, \
11112                         non-uniform state, or vt_cap < 2) — eager walk"
11113                    );
11114                }
11115            }
11116            Some(g)
11117        } else {
11118            None
11119        };
11120        // Capacity fail-safe: a round wider than the pool was built for must take the eager
11121        // walk, not slice the stash past its rows. The sizing above already covers every
11122        // round this run can present; this keeps a future caller (or a k that grows behind
11123        // the pool's back) on the byte-identical fallback instead of a panic.
11124        let vg_t_cap = vg_guard
11125            .as_ref()
11126            .and_then(|g| g.as_ref())
11127            .map(|g| g.t_capacity())
11128            .unwrap_or(0);
11129        if let Some(p) = pipe {
11130            p.setup_end();
11131        }
11132        while keep_going && out.len() < max_new {
11133            // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
11134            // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
11135            if let (true, Some(sg), Some(ptrs)) = (
11136                stream_active && round >= 1 && pending.is_some(),
11137                &stream_graph,
11138                &stream_ptrs,
11139            ) {
11140                if debug_spec {
11141                    static ONCE: std::sync::Once = std::sync::Once::new();
11142                    ONCE.call_once(|| {
11143                        eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
11144                    });
11145                }
11146                e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
11147                e.set_u32_one(&mut pend_d, pending.unwrap())?;
11148                e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
11149                for _mi in 0..m_rounds {
11150                    e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
11151                    cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
11152                    e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
11153                    e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
11154                    e.u32_copy(&pend_d, &mut dctx.g_tok)?;
11155                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
11156                    sg.launch()?;
11157                    e.spec_assemble_verify(
11158                        &g_tokp2k,
11159                        &pend_d,
11160                        d2t_dev.as_ref(),
11161                        &mut vtok_d,
11162                        &mut brk_d,
11163                        p_min,
11164                        k,
11165                        pmin0,
11166                    )?;
11167                    let mut ck = VerifyCkpt::new(self.layers.len());
11168                    let dummy = vec![0u32; t_v_s];
11169                    let (tl_d, vx) = self.decode_step_t_core_stream(
11170                        e,
11171                        &dummy,
11172                        0,
11173                        &mut *cache,
11174                        embd_dev,
11175                        Some(&mut ck),
11176                        Some((&vtok_d, &pos_ctr)),
11177                        None,
11178                        None,
11179                        None,
11180                    )?;
11181                    for j in 0..t_v_s {
11182                        e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
11183                    }
11184                    e.spec_accept_greedy_dc(
11185                        &preds_d,
11186                        &vtok_d,
11187                        &last_pred_d,
11188                        &brk_d,
11189                        &mut stream_acc,
11190                    )?;
11191                    e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
11192                    e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
11193                    self.commit_verified_prefix_stream(
11194                        e,
11195                        &mut *cache,
11196                        &snap,
11197                        &ck,
11198                        &stream_acc,
11199                        1,
11200                        t_v_s,
11201                    )?;
11202                    e.spec_rollback_stream(
11203                        ptrs,
11204                        &pos_start_d,
11205                        &stream_acc,
11206                        1,
11207                        self.layers.len() + 1,
11208                    )?;
11209                    e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
11210                }
11211                e.stream().synchronize()?;
11212                let ring_h = e.dtoh_u32(&ring_d)?;
11213                let cnt = ring_h[0] as usize;
11214                for i in 0..cnt {
11215                    if out.len() < max_new {
11216                        out.push(ring_h[1 + i]);
11217                    }
11218                }
11219                let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
11220                for il in 0..self.layers.len() {
11221                    if let Some(kvl) = cache.kv[il].as_mut() {
11222                        kvl.len = pos_h;
11223                    }
11224                }
11225                cache.pos = pos_h;
11226                scratch.kv.len = pos_h;
11227                pending = Some(ring_h[cnt]); // last drained token = the live bonus
11228                last_token = ring_h[cnt];
11229                total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
11230                total_accepted += cnt.saturating_sub(m_rounds);
11231                if let Some(t) = sess_telem {
11232                    // totals only — the burst's per-round accept counts stayed on device
11233                    // (that is the point of the round-stream arm). pos_* untouched.
11234                    t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
11235                }
11236                round += m_rounds;
11237                // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
11238                keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
11239                continue;
11240            }
11241            let pipe_draft = match pipe {
11242                Some(p) => Some(p.draft_begin(round)?),
11243                None => None,
11244            };
11245            let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
11246            let mut current_opti = carried_opti.take();
11247            let mut fork_generation = if current_opti.is_none() && pending.is_some() {
11248                match opti_fork.as_mut() {
11249                    Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
11250                    None => None,
11251                    Some(_) => None,
11252                }
11253            } else {
11254                None
11255            };
11256            if current_opti.is_none() {
11257                if let Some(fork) = opti_fork.as_ref() {
11258                    opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
11259                } else {
11260                    cache.snapshot_into(e, &mut snap)?;
11261                }
11262            } else if snap.pos != pos {
11263                return Err(format!(
11264                    "optipipe carried snapshot pos {} != current pos {pos}",
11265                    snap.pos
11266                )
11267                .into());
11268            } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
11269            ph_mark(&mut ph_rest, phase_on);
11270
11271            // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
11272            // p-min semantics (both paths): stop the chain early when the head's confidence in
11273            // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
11274            // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
11275            let base0 = if pending.is_some() { 1usize } else { 0usize };
11276            // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
11277            // accepted run + 1 (the gemma law — see the setup block above the loop).
11278            let k_this = if adapt { kc } else { k };
11279            let mut draft: Vec<u32> = Vec::with_capacity(k);
11280            let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
11281            let mut controller_draft_prob: Option<f32> = None;
11282            let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
11283            if let Some(ticket) = current_opti.as_mut() {
11284                let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
11285                if ticket.verify_tokens[0] != carried_pending {
11286                    return Err(format!(
11287                        "optipipe carried pending mismatch: ticket={} live={carried_pending}",
11288                        ticket.verify_tokens[0],
11289                    )
11290                    .into());
11291                }
11292                draft.push(ticket.verify_tokens[1]);
11293                controller_draft_prob = Some(ticket.draft_prob);
11294                controller_eager_state = ticket
11295                    .take_eager_seed()
11296                    .map(|seed| (ticket.verify_tokens[1], seed));
11297            } else {
11298                // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
11299                // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
11300                // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
11301                // rejected drafts and p-min extras via the len mechanism).
11302                scratch.set_len(e, pos + base0 - 1)?;
11303                if pen_on {
11304                    // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
11305                    // device dedup: `penalty_last_n` is usize::MAX for any serve request with
11306                    // a penalty, so without the cap this grew with the whole session.
11307                    let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
11308                    let w0 = pen_hist.len().saturating_sub(win);
11309                    pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
11310                }
11311                if sampled {
11312                    draft_logits.clear();
11313                    draft_stats.clear();
11314                }
11315                // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
11316                // position's mask is computed on that clone and advanced by the PROPOSED token. The
11317                // real state moves only on emission (verify's job), so the emitted stream is
11318                // unchanged — the mask only removes tokens the verify would have truncated anyway.
11319                let mut dmask_live = dmask_on;
11320                if dmask_live {
11321                    let t_c = std::time::Instant::now();
11322                    constraint
11323                        .as_deref_mut()
11324                        .unwrap()
11325                        .draft_begin()
11326                        .map_err(|e2| format!("constraint: {e2}"))?;
11327                    dm_clone_ns += t_c.elapsed().as_nanos();
11328                    dm_rounds += 1;
11329                }
11330                if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
11331                    // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
11332                    // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
11333                    // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
11334                    e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
11335                    e.set_u32_one(&mut dctx.g_tok, last_token)?;
11336                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
11337                    for j in 0..k_this {
11338                        // per-position mask upload (contents only — the graph's baked pointer is
11339                        // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
11340                        // mask node degrades to a no-op ban instead of needing a second graph.
11341                        if dmask_live
11342                            && !upload_draft_mask(
11343                                e,
11344                                constraint.as_deref_mut().unwrap(),
11345                                &mut dctx.g_dmask,
11346                                mtp.d2t.as_ref(),
11347                                d_vocab,
11348                                dmask_words,
11349                            )?
11350                        {
11351                            // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
11352                            // genuinely miss the legal set): neutralize the captured mask node and
11353                            // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
11354                            e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
11355                            dmask_live = false;
11356                        }
11357                        gr.launch()?;
11358                        scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
11359                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
11360                        // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
11361                        // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
11362                        // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
11363                        // replay's embed node, and the MMU fault kills the CUDA context for the
11364                        // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
11365                        // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
11366                        // buffer (g_seed = the verify-side handoff vs head-side compute).
11367                        if (idx as usize) >= d_vocab {
11368                            // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
11369                            // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
11370                            // seed, untouched since the round-start copy — the pair discriminates
11371                            // "seed arrived poisoned" from "head forward produced NaN".
11372                            let seed_h = e.dtoh(&dctx.g_seed)?;
11373                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
11374                            let in_h = e.dtoh(&h_seed_buf)?;
11375                            let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
11376                            return Err(format!(
11377                                "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
11378                             round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
11379                             round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
11380                             the embed row (#87 trap)"
11381                            )
11382                            .into());
11383                        }
11384                        // trimmed draft vocab -> target token id (identity when no d2t map)
11385                        let d = match &mtp.d2t {
11386                            Some(map) => map[idx as usize],
11387                            None => idx,
11388                        };
11389                        let draft_p = if p_min > 0.0
11390                            || opti_fork
11391                                .as_ref()
11392                                .is_some_and(|fork| fork.controller.is_some())
11393                        {
11394                            Some(e.dtoh(&dctx.g_p)?[0])
11395                        } else {
11396                            None
11397                        };
11398                        if j == 0 {
11399                            controller_draft_prob = draft_p;
11400                        }
11401                        if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
11402                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
11403                                break;
11404                            }
11405                        }
11406                        draft.push(d);
11407                        // with a trimmed head the NEXT embed must read the TARGET id, not the draft
11408                        // index the argmax wrote — patch the persistent token buffer (4B htod).
11409                        if d != idx {
11410                            e.set_u32_one(&mut dctx.g_tok, d)?;
11411                        }
11412                        // advance the SPECULATIVE state with the proposal; a dead chain drops to
11413                        // unmasked drafting for the remaining positions (verify still arbitrates).
11414                        // speculative advance; a chain the grammar can no longer follow (EOS
11415                        // proposed) ends here. The captured mask node always runs, so a dead chain
11416                        // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
11417                        if dmask_live
11418                            && !constraint
11419                                .as_deref_mut()
11420                                .unwrap()
11421                                .draft_advance(d)
11422                                .map_err(|e2| format!("constraint: {e2}"))?
11423                        {
11424                            e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
11425                            break;
11426                        }
11427                    }
11428                // PURE-TEMP RE-TEST (lane/graph-s-key-exactness-20260819): the sampled graph is
11429                // legal ONLY in the regime it was captured in. The condition used to read
11430                // `(sampled, &dctx.graph_s)` and trusted `s_key` to have dropped anything else —
11431                // which it could not, because the key omitted the filters. Both halves are now
11432                // enforced: the key drops a stale graph, and this site refuses to launch one.
11433                } else if let (true, Some(gr)) = (sampled && pure_temp, &dctx.graph_s) {
11434                    if skey_probe() {
11435                        eprintln!(
11436                            "[skey] chain=graph_s round={round} pure_temp={} top_k={} \
11437                             top_p={} min_p={} s_key_parked={:?}",
11438                            pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
11439                        );
11440                    }
11441                    // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
11442                    // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
11443                    // and decides the break. Event-counter continuity: g_ctr is host-seeded to
11444                    // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
11445                    // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
11446                    // stream. Host sctr advances in lockstep (computed, no readback needed).
11447                    e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
11448                    e.set_u32_one(&mut dctx.g_tok, last_token)?;
11449                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
11450                    e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
11451                    for j in 0..k_this {
11452                        gr.launch()?;
11453                        scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
11454                        sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
11455                        // counts the p-min-discarded token too)
11456                        // q retention: ONE async D2D of the persistent head-logits buffer into this
11457                        // round's slot j (stream-ordered after the replay, before the next one).
11458                        e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
11459                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
11460                        // #87 SENTINEL TRAP (see the greedy graph arm above).
11461                        if (idx as usize) >= d_vocab {
11462                            let seed_h = e.dtoh(&dctx.g_seed)?;
11463                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
11464                            return Err(format!(
11465                                "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
11466                             {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
11467                             {seed_nan}/{n_embd} — refusing to dereference the embed row \
11468                             (#87 trap)"
11469                            )
11470                            .into());
11471                        }
11472                        let d = match &mtp.d2t {
11473                            Some(map) => map[idx as usize],
11474                            None => idx,
11475                        };
11476                        draft_idx.push(idx);
11477                        if p_min > 0.0 {
11478                            let p = e.dtoh(&dctx.g_p)?[0];
11479                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
11480                                break;
11481                            }
11482                        }
11483                        draft.push(d);
11484                        // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
11485                        if d != idx {
11486                            e.set_u32_one(&mut dctx.g_tok, d)?;
11487                        }
11488                    }
11489                    // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
11490                    // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
11491                    for j in 0..draft.len().max(draft_idx.len()) {
11492                        let rows0 = e.htod_i32(&[0])?;
11493                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
11494                        e.filter_stats(
11495                            &dctx.q_slots[j],
11496                            d_vocab,
11497                            &rows0,
11498                            &mut th_d,
11499                            &mut z_d,
11500                            &mut mx_d,
11501                            d_vocab,
11502                            1,
11503                            sp_temp,
11504                            sp.top_k,
11505                            sp.top_p,
11506                            sp.min_p,
11507                        )?;
11508                        draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
11509                    }
11510                } else {
11511                    if skey_probe() && sampled {
11512                        eprintln!(
11513                            "[skey] chain=eager round={round} pure_temp={} top_k={} \
11514                             top_p={} min_p={} s_key_parked={:?}",
11515                            pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
11516                        );
11517                    }
11518                    // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
11519                    let chain_heads = !self.mtp_extra.is_empty();
11520                    let mut e_tok = last_token;
11521                    let mut d_seed = e.clone_dtod(&h_seed_buf)?;
11522                    let mut chain_tokens = if chain_heads {
11523                        vec![last_token]
11524                    } else {
11525                        Vec::new()
11526                    };
11527                    let mut chain_seeds = if chain_heads {
11528                        vec![e.clone_dtod(&h_seed_buf)?]
11529                    } else {
11530                        Vec::new()
11531                    };
11532                    for j in 0..k_this {
11533                        // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
11534                        // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
11535                        let mtp_pos = pos + base0 + j;
11536                        // draft-side grammar mask (eager twin of the graph arm's in-graph node).
11537                        // A position with no legal draft-vocab row drops to unmasked drafting for
11538                        // the rest of the chain (pre-lane behaviour; verify still arbitrates).
11539                        if dmask_live {
11540                            dmask_live = upload_draft_mask(
11541                                e,
11542                                constraint.as_deref_mut().unwrap(),
11543                                &mut dctx.g_dmask,
11544                                mtp.d2t.as_ref(),
11545                                d_vocab,
11546                                dmask_words,
11547                            )?;
11548                        }
11549                        let mask = if dmask_live {
11550                            Some((&dctx.g_dmask, dmask_words))
11551                        } else {
11552                            None
11553                        };
11554                        let (dl_d, h_nextn) = if chain_heads {
11555                            if debug_spec {
11556                                eprintln!(
11557                                    "[mtp-chain-step] round={round} j={j} head={} replay_rows={}",
11558                                    mtp_chain_head_index(j, self.mtp_head_count()),
11559                                    chain_tokens.len(),
11560                                );
11561                            }
11562                            self.mtp_chain_forward_dev(
11563                                e,
11564                                &chain_tokens,
11565                                &chain_seeds,
11566                                &mut *scratch,
11567                                pos + base0 - 1,
11568                                embd_dev,
11569                                mask,
11570                            )?
11571                        } else {
11572                            self.mtp_head_forward_dev(
11573                                e,
11574                                mtp,
11575                                e_tok,
11576                                &d_seed,
11577                                &mut *scratch,
11578                                mtp_pos,
11579                                embd_dev,
11580                                mask,
11581                            )?
11582                        };
11583                        let tok_d = if sampled {
11584                            // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
11585                            // the filtered softmax (filters off => th=0, exact v1 semantics).
11586                            if perturb_buf.is_none() {
11587                                perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
11588                            }
11589                            let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
11590                            if pen_on {
11591                                let h = pen_hist_d.as_ref().unwrap();
11592                                let nh = h.len();
11593                                e.penalize_logits(
11594                                    &mut q_row,
11595                                    h,
11596                                    nh,
11597                                    sp.penalty_repeat,
11598                                    sp.penalty_freq,
11599                                    sp.penalty_present,
11600                                    d_vocab,
11601                                )?;
11602                            }
11603                            let rows0 = e.htod_i32(&[0])?;
11604                            let (mut th_d, mut z_d, mut mx_d) =
11605                                (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
11606                            e.filter_stats(
11607                                &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
11608                                1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
11609                            )?;
11610                            let (th, z, mx) =
11611                                (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
11612                            let pb = perturb_buf.as_mut().unwrap();
11613                            e.gumbel_perturb_filtered(
11614                                &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
11615                            )?;
11616                            sctr += 1;
11617                            draft_logits.push(q_row);
11618                            draft_stats.push((mx, th, z));
11619                            e.argmax_token_device(pb, d_vocab)?
11620                        } else {
11621                            e.argmax_token_device(&dl_d, d_vocab)?
11622                        };
11623                        let idx = e.dtoh_u32_one(&tok_d)?;
11624                        // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
11625                        // here because the eager chain's operands are all readable: dl_d (the head
11626                        // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
11627                        if (idx as usize) >= d_vocab {
11628                            let dl_h = e.dtoh(&dl_d)?;
11629                            let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
11630                            let seed_h = if chain_heads {
11631                                e.dtoh(chain_seeds.last().unwrap())?
11632                            } else {
11633                                e.dtoh(&d_seed)?
11634                            };
11635                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
11636                            return Err(format!(
11637                                "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
11638                             round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
11639                             step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
11640                             embed row (#87 trap)"
11641                            )
11642                            .into());
11643                        }
11644                        let d = match &mtp.d2t {
11645                            Some(map) => map[idx as usize],
11646                            None => idx,
11647                        };
11648                        if sampled {
11649                            draft_idx.push(idx);
11650                        }
11651                        let draft_p = if p_min > 0.0
11652                            || opti_fork
11653                                .as_ref()
11654                                .is_some_and(|fork| fork.controller.is_some())
11655                        {
11656                            let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
11657                            Some(e.dtoh(&p_d)?[0])
11658                        } else {
11659                            None
11660                        };
11661                        if j == 0 {
11662                            controller_draft_prob = draft_p;
11663                        }
11664                        if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
11665                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
11666                                break;
11667                            }
11668                        }
11669                        draft.push(d);
11670                        if chain_heads {
11671                            chain_tokens.push(d);
11672                            chain_seeds.push(h_nextn);
11673                        } else {
11674                            e_tok = d;
11675                            d_seed = h_nextn;
11676                        }
11677                        // speculative advance; a chain the grammar can no longer follow (EOS
11678                        // proposed) ends here — the prefix already proposed still rides verify.
11679                        if dmask_live
11680                            && !constraint
11681                                .as_deref_mut()
11682                                .unwrap()
11683                                .draft_advance(d)
11684                                .map_err(|e2| format!("constraint: {e2}"))?
11685                        {
11686                            break;
11687                        }
11688                    }
11689                    if !chain_heads
11690                        && opti_fork
11691                            .as_ref()
11692                            .is_some_and(|fork| fork.controller.is_some())
11693                    {
11694                        controller_eager_state = Some((e_tok, d_seed));
11695                    }
11696                }
11697            }
11698            let k_round = draft.len();
11699            if let Some(p) = pipe {
11700                p.draft_end(round);
11701            }
11702            drop(pipe_draft);
11703
11704            ph_mark(&mut ph_draft, phase_on);
11705            // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
11706            //         (committing its KV/recur inside the SAME weight read); drafts follow. ---
11707            let verify_tokens: Vec<u32> = match pending {
11708                Some(b) => {
11709                    let mut v = Vec::with_capacity(k_round + 1);
11710                    v.push(b);
11711                    v.extend_from_slice(&draft);
11712                    v
11713                }
11714                None => draft.clone(),
11715            };
11716            let base = if pending.is_some() { 1 } else { 0 };
11717            // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
11718            // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
11719            let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
11720                Some(ticket.take_ckpt())
11721            } else if spec_replay {
11722                None
11723            } else {
11724                Some(VerifyCkpt::new(self.layers.len()))
11725            };
11726            let controller_can_probe = base == 1
11727                && k_round == 1
11728                && out.len().saturating_add(2) < max_new
11729                && controller_draft_prob.is_some()
11730                && opti_fork
11731                    .as_ref()
11732                    .and_then(|fork| fork.controller.as_ref())
11733                    .is_some_and(|policy| !policy.breaker_tripped);
11734            let mut successor_attempt: Option<OptiControllerTicket> = None;
11735            let mut rejected_probe: Option<(f32, u32)> = None;
11736            let mut controller_prepared: Option<OptiControllerPrepared> = None;
11737            if controller_can_probe {
11738                // Prepare d2/q and, on admission, d3 before either current verify half is
11739                // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
11740                // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
11741                // the primary stream after N stage 1 would serialize the supposed pipeline.
11742                let eager_pos = scratch.kv.len + 1;
11743                let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
11744                    e,
11745                    mtp,
11746                    &mut dctx,
11747                    &mut *scratch,
11748                    d_vocab,
11749                    &mut controller_eager_state,
11750                    eager_pos,
11751                    embd_dev,
11752                )?;
11753                let first_probability = controller_draft_prob
11754                    .ok_or("optipipe controller probe lost first-token probability")?;
11755                let q_proxy = first_probability * pending_probability;
11756                OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11757                OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11758                let admitted = opti_fork
11759                    .as_ref()
11760                    .and_then(|fork| fork.controller.as_ref())
11761                    .ok_or("optipipe controller policy disappeared")?
11762                    .admit(q_proxy);
11763                if admitted {
11764                    OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11765                    let eager_pos = scratch.kv.len + 1;
11766                    let (optimistic_draft, optimistic_draft_probability) = self
11767                        .opti_controller_draft_step(
11768                            e,
11769                            mtp,
11770                            &mut dctx,
11771                            &mut *scratch,
11772                            d_vocab,
11773                            &mut controller_eager_state,
11774                            eager_pos,
11775                            embd_dev,
11776                        )?;
11777                    OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11778                    let eager_seed = controller_eager_state.take().map(|(token, seed)| {
11779                        debug_assert_eq!(token, optimistic_draft);
11780                        seed
11781                    });
11782                    controller_prepared = Some(OptiControllerPrepared {
11783                        verify_tokens: [optimistic_pending, optimistic_draft],
11784                        draft_prob: optimistic_draft_probability,
11785                        eager_seed,
11786                        q_proxy,
11787                        scratch_len: scratch.kv.len,
11788                    });
11789                } else {
11790                    OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11791                    OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11792                    rejected_probe = Some((q_proxy, optimistic_pending));
11793                    eprintln!(
11794                        "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
11795                        opti_fork
11796                            .as_ref()
11797                            .and_then(|fork| fork.controller.as_ref())
11798                            .expect("controller policy")
11799                            .threshold,
11800                    );
11801                }
11802            }
11803            let fork_attempt = match fork_generation.take() {
11804                Some(generation) if base == 1 && k_round == 1 => Some(generation),
11805                Some(generation) => {
11806                    opti_fork
11807                        .as_mut()
11808                        .expect("fork generation without fork state")
11809                        .retire(generation)?;
11810                    None
11811                }
11812                None => None,
11813            };
11814            let (tlogits_d, vx) = if let Some(p) = pipe {
11815                self.decode_step_t_core_pipelined(
11816                    e,
11817                    &verify_tokens,
11818                    pos,
11819                    &mut *cache,
11820                    embd_dev,
11821                    ckpt.as_mut(),
11822                    p,
11823                    round,
11824                )?
11825            } else if controller_can_probe {
11826                let fence = opti_fork
11827                    .as_ref()
11828                    .ok_or("optipipe controller probe lost fork state")?
11829                    .fence;
11830                let boundary = match current_opti.as_mut() {
11831                    Some(ticket) => ticket.take_boundary(),
11832                    None => self.verify_stage0_issue(
11833                        e,
11834                        &verify_tokens,
11835                        pos,
11836                        &mut *cache,
11837                        embd_dev,
11838                        ckpt.as_mut(),
11839                        None,
11840                        &fence,
11841                        Some(true),
11842                        None,
11843                    )?,
11844                };
11845                if let Some(prepared) = controller_prepared.take() {
11846                    let generation = {
11847                        let fork = opti_fork
11848                            .as_mut()
11849                            .ok_or("optipipe controller admission lost fork state")?;
11850                        let generation = fork.reserve_successor()?;
11851                        let rt = fork.rt;
11852                        let snapshot_fence = fork.fence;
11853                        opti_snapshot_one_stage_owned_into(
11854                            e,
11855                            cache,
11856                            rt,
11857                            &snapshot_fence,
11858                            0,
11859                            fork.successor_snapshot_mut(),
11860                        )?;
11861                        generation
11862                    };
11863                    let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
11864                    let successor_boundary = self.verify_stage0_issue(
11865                        e,
11866                        &prepared.verify_tokens,
11867                        pos + verify_tokens.len(),
11868                        &mut *cache,
11869                        embd_dev,
11870                        Some(&mut successor_ckpt),
11871                        None,
11872                        &fence,
11873                        Some(false),
11874                        None,
11875                    )?;
11876                    OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11877                    let fork = opti_fork
11878                        .as_ref()
11879                        .ok_or("optipipe controller ticket lost fork state")?;
11880                    successor_attempt = Some(fork.controller_ticket(
11881                        generation,
11882                        successor_boundary,
11883                        successor_ckpt,
11884                        prepared.verify_tokens,
11885                        prepared.draft_prob,
11886                        prepared.eager_seed,
11887                        prepared.q_proxy,
11888                        prepared.scratch_len,
11889                    ));
11890                    eprintln!(
11891                        "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
11892                         verify={:?}",
11893                        generation.id,
11894                        prepared.q_proxy,
11895                        fork.controller.expect("controller policy").threshold,
11896                        prepared.verify_tokens,
11897                    );
11898                }
11899                let result = self.verify_stage1_finish(
11900                    e,
11901                    boundary,
11902                    &mut *cache,
11903                    ckpt.as_mut(),
11904                    None,
11905                    &fence,
11906                    successor_attempt.is_none(),
11907                )?;
11908                if let Some(ticket) = current_opti.as_mut() {
11909                    ticket.settle();
11910                }
11911                if successor_attempt.is_some() {
11912                    let fork = opti_fork
11913                        .as_mut()
11914                        .ok_or("optipipe successor snapshot lost fork state")?;
11915                    let rt = fork.rt;
11916                    let snapshot_fence = fork.fence;
11917                    opti_snapshot_one_stage_owned_into(
11918                        e,
11919                        cache,
11920                        rt,
11921                        &snapshot_fence,
11922                        1,
11923                        fork.successor_snapshot_mut(),
11924                    )?;
11925                    // Publish N only after both independent successor-state queues are complete.
11926                    fork.rt.publish_to(1, &e.stream())?;
11927                }
11928                result
11929            } else if let Some(ticket) = current_opti.as_mut() {
11930                let fork = opti_fork
11931                    .as_mut()
11932                    .ok_or("optipipe carried controller ticket lost fork state")?;
11933                let boundary = ticket.take_boundary();
11934                let result = self.verify_stage1_finish(
11935                    e,
11936                    boundary,
11937                    &mut *cache,
11938                    ckpt.as_mut(),
11939                    None,
11940                    &fork.fence,
11941                    true,
11942                )?;
11943                ticket.settle();
11944                result
11945            } else if let Some(generation) = fork_attempt {
11946                let fork = opti_fork
11947                    .as_mut()
11948                    .expect("fork generation without fork state");
11949                fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
11950                let action = fork.mode.action(generation.id);
11951                let boundary = self.verify_stage0_issue(
11952                    e,
11953                    &verify_tokens,
11954                    pos,
11955                    &mut *cache,
11956                    embd_dev,
11957                    ckpt.as_mut(),
11958                    None,
11959                    &fork.fence,
11960                    Some(true),
11961                    None,
11962                )?;
11963                OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11964                let mut ticket = fork.ticket(generation, boundary);
11965                if action == OptiForkAction::Abort {
11966                    return Err(format!(
11967                        "optipipe forced abort with generation {} stage0 in flight",
11968                        generation.id,
11969                    )
11970                    .into());
11971                }
11972                fork.reconcile(
11973                    e,
11974                    &mut *cache,
11975                    &mut *scratch,
11976                    &snap,
11977                    &mut h_seed_buf,
11978                    &mut fill_prev,
11979                    generation,
11980                    action,
11981                    verify_tokens[0],
11982                )?;
11983                let result = if action == OptiForkAction::Hit {
11984                    let boundary = ticket.take_boundary();
11985                    self.verify_stage1_finish(
11986                        e,
11987                        boundary,
11988                        &mut *cache,
11989                        ckpt.as_mut(),
11990                        None,
11991                        &fork.fence,
11992                        true,
11993                    )?
11994                } else {
11995                    // The optimistic boundary slot has no reader. Re-run the unchanged serial
11996                    // verify only after E_restart published the restored stage-0 state.
11997                    self.decode_step_t_core(
11998                        e,
11999                        &verify_tokens,
12000                        pos,
12001                        &mut *cache,
12002                        embd_dev,
12003                        ckpt.as_mut(),
12004                    )?
12005                };
12006                ticket.settle();
12007                debug_assert_eq!(ticket.generation, generation);
12008                fork.retire(generation)?;
12009                result
12010            } else {
12011                // The serial verify every non-fork round takes — the MTP route's
12012                // verify-graph door. The pool is None unless MEMRA_SPEC_VERIFY_GRAPH armed
12013                // a pool above, and then the walk replays the captured trunk instead of
12014                // re-issuing it launch by launch.
12015                let vg_round = if verify_tokens.len() <= vg_t_cap {
12016                    vg_guard.as_mut().and_then(|g| g.as_mut())
12017                } else {
12018                    if let Some(g) = vg_guard.as_mut().and_then(|g| g.as_mut()) {
12019                        // The commit reads this flag to pick its arm; a round that declines
12020                        // the pool must not inherit a stale `true` from the round before it.
12021                        g.round_slab = false;
12022                    }
12023                    None
12024                };
12025                self.decode_step_t_core_vg(
12026                    e,
12027                    &verify_tokens,
12028                    pos,
12029                    &mut *cache,
12030                    embd_dev,
12031                    ckpt.as_mut(),
12032                    vg_round,
12033                )?
12034            };
12035            let pipe_accept = match pipe {
12036                Some(p) => Some(p.accept_begin(round)?),
12037                None => None,
12038            };
12039
12040            ph_mark(&mut ph_verify, phase_on);
12041            // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
12042            // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
12043            // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
12044            // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
12045            // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
12046            // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
12047            // (== the bonus), so every index shifts by `base` and last_pred is unused.
12048            let t_v = verify_tokens.len();
12049            let mut preds: Vec<u32> = Vec::new();
12050            if !sampled {
12051                for j in 0..t_v {
12052                    e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
12053                }
12054                preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
12055                // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
12056                // next round's last_token = the next chain's embed lookup. Catch it at the
12057                // source with the column named — an all-NaN VERIFY column implicates the
12058                // stage-split trunk (decode_step_t_core_ppn), not the draft head.
12059                if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
12060                    let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
12061                    let mut probe = e.zeros(n_vocab)?;
12062                    e.copy_view_into(&mut probe, 0, col, n_vocab)?;
12063                    let col_h = e.dtoh(&probe)?;
12064                    let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
12065                    return Err(format!(
12066                        "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
12067                         col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
12068                         — the stage-split verify produced a poisoned column (#87 trap)",
12069                        preds[bad]
12070                    )
12071                    .into());
12072                }
12073            }
12074            ph_mark(&mut ph_wait, phase_on);
12075            let t_pred = |j: usize| -> u32 {
12076                if j == 0 && base == 0 {
12077                    last_pred
12078                } else {
12079                    // GREEDY-ONLY: `preds` is filled under `if !sampled` above. The debug print
12080                    // used to call this from the sampled arm and panicked the worker; it now goes
12081                    // through `debug_t_pred0`. Keep the strict index here — in the greedy walk an
12082                    // out-of-range pred is a real bug, not something to paper over.
12083                    debug_assert!(
12084                        !sampled,
12085                        "t_pred is greedy-only: `preds` is empty in the sampled arm"
12086                    );
12087                    preds[base + j - 1]
12088                }
12089            };
12090            let mut devacc_seeded = false;
12091            let mut devacc_acc: Option<CudaSlice<u32>> = None;
12092            let (n_acc, bonus) = if !sampled {
12093                // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
12094                // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
12095                // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
12096                // gated on token identity vs the host walk (the arms below are bit-equal rules).
12097                if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
12098                {
12099                    let draft_d = e.htod_u32_v(&draft)?;
12100                    let mut acc_out = e.alloc_u32_zeroed(2)?;
12101                    e.spec_accept_greedy(
12102                        &preds_d,
12103                        &draft_d,
12104                        last_pred,
12105                        base,
12106                        k_round,
12107                        &mut acc_out,
12108                    )?;
12109                    devacc_acc = Some(acc_out.clone());
12110                    // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
12111                    // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
12112                    // non-replay commit arms skip their host-offset seed copies (guarded below);
12113                    // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
12114                    // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
12115                    // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
12116                    // the update lands after the arms (devacc_seeded guard below).
12117                    e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
12118                    // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
12119                    // unified rule; full accept rewrites the verify-left value). Host mirrors
12120                    // update after the readback; commit_verified_prefix skips its len_d writes.
12121                    if let Some(successor) = successor_attempt.as_ref() {
12122                        opti_fork
12123                            .as_mut()
12124                            .ok_or("optipipe successor reconcile lost fork state")?
12125                            .queue_actual_reconcile(
12126                                e,
12127                                &snap,
12128                                &acc_out,
12129                                successor.verify_tokens[0],
12130                                base,
12131                            )?;
12132                    } else if let Some(ptrs) = &kv_len_ptrs {
12133                        let saved: Vec<i32> = (0..self.layers.len())
12134                            .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
12135                            .collect();
12136                        let saved_d = e.htod_i32(&saved)?;
12137                        e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
12138                    }
12139                    devacc_seeded = true;
12140                    let ab = e.dtoh_u32(&acc_out)?;
12141                    (ab[0] as usize, ab[1])
12142                } else {
12143                    let mut n_acc = 0usize;
12144                    for j in 0..k_round {
12145                        if t_pred(j) == draft[j] {
12146                            n_acc += 1;
12147                        } else {
12148                            break;
12149                        }
12150                    }
12151                    // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
12152                    // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
12153                    (n_acc, t_pred(n_acc))
12154                }
12155            } else {
12156                // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
12157                if col_buf.is_none() {
12158                    col_buf = Some(e.zeros(n_vocab)?);
12159                }
12160                // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
12161                // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
12162                let mut pj = vec![0f32; k_round.max(1)];
12163                let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
12164                if k_round > 0 {
12165                    let mut ids: Vec<u32> = Vec::new();
12166                    let mut rows: Vec<i32> = Vec::new();
12167                    for j in 0..k_round {
12168                        if j > 0 || base == 1 {
12169                            ids.push(draft[j]);
12170                            rows.push((base + j) as i32 - 1);
12171                        }
12172                    }
12173                    if !ids.is_empty() {
12174                        let nr = rows.len();
12175                        // penalties: materialize the used columns into one contiguous penalized
12176                        // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
12177                        // penalties: materialize used columns contiguously, penalize all rows in
12178                        // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
12179                        let p_rows: Vec<i32> = if pen_on {
12180                            (0..nr as i32).collect()
12181                        } else {
12182                            rows.clone()
12183                        };
12184                        if pen_on {
12185                            if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
12186                                pcol_buf = Some(e.zeros(nr * n_vocab)?);
12187                            }
12188                            let pc = pcol_buf.as_mut().unwrap();
12189                            for (i2, &r) in rows.iter().enumerate() {
12190                                let c = r as usize;
12191                                e.copy_view_into(
12192                                    pc,
12193                                    i2 * n_vocab,
12194                                    &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
12195                                    n_vocab,
12196                                )?;
12197                            }
12198                            let h = pen_hist_d.as_ref().unwrap();
12199                            let nh = h.len();
12200                            e.penalize_logits_rows(
12201                                pc,
12202                                h,
12203                                nh,
12204                                sp.penalty_repeat,
12205                                sp.penalty_freq,
12206                                sp.penalty_present,
12207                                n_vocab,
12208                                nr,
12209                            )?;
12210                        }
12211                        let p_src: &CudaSlice<f32> = if pen_on {
12212                            pcol_buf.as_ref().unwrap()
12213                        } else {
12214                            &tlogits_d
12215                        };
12216                        let rowsd = e.htod_i32(&p_rows)?;
12217                        let (mut th_d, mut z_d, mut mx_d) =
12218                            (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
12219                        e.filter_stats(
12220                            p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
12221                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
12222                        )?;
12223                        let idsd = e.htod_u32_v(&ids)?;
12224                        let mut outd = e.zeros(nr)?;
12225                        e.softmax_gather_filtered(
12226                            p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
12227                            sp_temp,
12228                        )?;
12229                        let outv = e.dtoh(&outd)?;
12230                        let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
12231                        let mut oi = 0usize;
12232                        for j in 0..k_round {
12233                            if j > 0 || base == 1 {
12234                                pj[j] = outv[oi];
12235                                oi += 1;
12236                            }
12237                        }
12238                        col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
12239                    }
12240                    if base == 0 {
12241                        let lc: &CudaSlice<f32> = if pen_on {
12242                            if col_buf.is_none() {
12243                                col_buf = Some(e.zeros(n_vocab)?);
12244                            }
12245                            let cb = col_buf.as_mut().unwrap();
12246                            e.copy_into(
12247                                cb,
12248                                0,
12249                                last_col_logits
12250                                    .as_ref()
12251                                    .expect("sampled: last_col_logits unset"),
12252                                n_vocab,
12253                            )?;
12254                            let h = pen_hist_d.as_ref().unwrap();
12255                            let nh = h.len();
12256                            e.penalize_logits(
12257                                cb,
12258                                h,
12259                                nh,
12260                                sp.penalty_repeat,
12261                                sp.penalty_freq,
12262                                sp.penalty_present,
12263                                n_vocab,
12264                            )?;
12265                            col_buf.as_ref().unwrap()
12266                        } else {
12267                            last_col_logits
12268                                .as_ref()
12269                                .expect("sampled: last_col_logits unset")
12270                        };
12271                        let rows0 = e.htod_i32(&[0])?;
12272                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
12273                        e.filter_stats(
12274                            lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
12275                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
12276                        )?;
12277                        let idsd = e.htod_u32_v(&[draft[0]])?;
12278                        let mut outd = e.zeros(1)?;
12279                        e.softmax_gather_filtered(
12280                            lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
12281                        )?;
12282                        pj[0] = e.dtoh(&outd)?[0];
12283                        last_col_stats =
12284                            Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
12285                    }
12286                }
12287                // q source: the graph arm retained the head logits in the persistent q_slots;
12288                // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
12289                // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
12290                // computes them post-replay — graph engages only filter/penalty-free, so the
12291                // stats degenerate to th=0/full-Z there, keeping ONE accept path).
12292                let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
12293                    &dctx.q_slots
12294                } else {
12295                    &draft_logits
12296                };
12297                let mut n_acc = 0usize;
12298                for j in 0..k_round {
12299                    let (qmx, qth, qz) = draft_stats[j];
12300                    let idsd = e.htod_u32_v(&[draft_idx[j]])?;
12301                    let rowsd = e.htod_i32(&[0])?;
12302                    let thd = e.htod(&[qth])?;
12303                    let zd = e.htod(&[qz])?;
12304                    let _ = qmx;
12305                    let mut outd = e.zeros(1)?;
12306                    e.softmax_gather_filtered(
12307                        &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
12308                        sp_temp,
12309                    )?;
12310                    let qj = e.dtoh(&outd)?[0];
12311                    let u = host_u01(sp_seed, uctr);
12312                    uctr += 1;
12313                    let accept = (u as f64) * (qj as f64) < pj[j] as f64;
12314                    // SKEY PROBE: q == 0 for the token the draft actually proposed is the
12315                    // exactness signature (see `skey_probe`). Impossible when the draft was
12316                    // drawn from the same filtered distribution the verify reconstructs here;
12317                    // `u * 0 < p` makes it an UNCONDITIONAL accept whenever p > 0.
12318                    if skey_probe() && qj == 0.0 {
12319                        eprintln!(
12320                            "[skey] EXACTNESS q=0 round={round} j={j} draft_tok={} \
12321                             draft_idx={} p={:e} u={u} accepted={} th_z={:?}",
12322                            draft[j], draft_idx[j], pj[j], accept as u8, draft_stats[j],
12323                        );
12324                    }
12325                    if accept {
12326                        n_acc += 1;
12327                    } else {
12328                        break;
12329                    }
12330                }
12331                let bonus = if n_acc == k_round {
12332                    // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
12333                    let col = base + k_round - 1;
12334                    let cb = col_buf.as_mut().unwrap();
12335                    e.copy_view_into(
12336                        cb,
12337                        0,
12338                        &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
12339                        n_vocab,
12340                    )?;
12341                    if pen_on {
12342                        let h = pen_hist_d.as_ref().unwrap();
12343                        let nh = h.len();
12344                        e.penalize_logits(
12345                            cb,
12346                            h,
12347                            nh,
12348                            sp.penalty_repeat,
12349                            sp.penalty_freq,
12350                            sp.penalty_present,
12351                            n_vocab,
12352                        )?;
12353                    }
12354                    if perturb_buf.is_none() {
12355                        perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
12356                    }
12357                    // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
12358                    // truncation-fix; receipts research/sampfix-20260805/). The old code reused
12359                    // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
12360                    // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
12361                    // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
12362                    // last gathered column, in both base arms. `th` is a threshold in e-units of
12363                    // its OWN row's max, so feeding a neighbour's (row_max, th) into
12364                    // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
12365                    // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
12366                    // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
12367                    // falls through to its smallest-index tie-break => token id 0 ("!") spliced
12368                    // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
12369                    // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
12370                    // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
12371                    // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
12372                    // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
12373                    // and row_max is unused once nothing is masked), so this fix is a byte-level
12374                    // no-op for the untruncated serve default. One extra one-block filter_stats
12375                    // per full-accept round is the whole cost.
12376                    let (mx, th) = {
12377                        let rows0 = e.htod_i32(&[0])?;
12378                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
12379                        let cb0 = col_buf.as_ref().unwrap();
12380                        e.filter_stats(
12381                            cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
12382                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
12383                        )?;
12384                        (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
12385                    };
12386                    let pb = perturb_buf.as_mut().unwrap();
12387                    let cb2 = col_buf.as_ref().unwrap();
12388                    e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
12389                    sctr += 1;
12390                    let td = e.argmax_token_device(pb, n_vocab)?;
12391                    e.dtoh_u32_one(&td)?
12392                } else {
12393                    // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
12394                    let cb = col_buf.as_mut().unwrap();
12395                    if n_acc > 0 || base == 1 {
12396                        let col = base + n_acc - 1;
12397                        e.copy_view_into(
12398                            cb,
12399                            0,
12400                            &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
12401                            n_vocab,
12402                        )?;
12403                    } else {
12404                        let lc = last_col_logits.as_ref().unwrap();
12405                        e.copy_into(cb, 0, lc, n_vocab)?;
12406                    }
12407                    if pen_on {
12408                        let h = pen_hist_d.as_ref().unwrap();
12409                        let nh = h.len();
12410                        e.penalize_logits(
12411                            cb,
12412                            h,
12413                            nh,
12414                            sp.penalty_repeat,
12415                            sp.penalty_freq,
12416                            sp.penalty_present,
12417                            n_vocab,
12418                        )?;
12419                    }
12420                    let cb2 = col_buf.as_ref().unwrap();
12421                    let sc = sctr;
12422                    sctr += 1;
12423                    // p-stats for the reject column: from col_stats when the col was gathered,
12424                    // else (j==0&&base==0) from last_col_stats.
12425                    let p_stats = if n_acc > 0 || base == 1 {
12426                        // col index within the gathered set == number of gathered cols before n_acc
12427                        let gi = if base == 1 { n_acc } else { n_acc - 1 };
12428                        col_stats.get(gi).copied().unwrap_or_else(|| {
12429                            (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
12430                        })
12431                    } else {
12432                        last_col_stats.expect("sampled: last_col_stats unset at reject")
12433                    };
12434                    let q_stats = draft_stats[n_acc];
12435                    if let Some(map) = &d2t_dev {
12436                        if q_full_buf.is_none() {
12437                            q_full_buf = Some(e.zeros(n_vocab)?);
12438                        }
12439                        let qf = q_full_buf.as_mut().unwrap();
12440                        e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
12441                        let qf2 = q_full_buf.as_ref().unwrap();
12442                        e.residual_sample_filtered(
12443                            cb2,
12444                            Some(qf2),
12445                            n_vocab,
12446                            sp_temp,
12447                            sp_seed,
12448                            sc,
12449                            p_stats,
12450                            q_stats,
12451                            &mut sample_tok,
12452                        )?;
12453                    } else {
12454                        e.residual_sample_filtered(
12455                            cb2,
12456                            Some(&q_bufs[n_acc]),
12457                            n_vocab,
12458                            sp_temp,
12459                            sp_seed,
12460                            sc,
12461                            p_stats,
12462                            q_stats,
12463                            &mut sample_tok,
12464                        )?;
12465                    }
12466                    e.dtoh_u32(&sample_tok)?[0]
12467                };
12468                (n_acc, bonus)
12469            };
12470            // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
12471            // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
12472            // ordering). Walk the accepted drafts through the grammar in commit order; the
12473            // first illegal token truncates acceptance at its slot, and that slot's emission
12474            // is recomputed as the MASKED argmax of the target's own verify column — token-
12475            // identical to constrained plain greedy decode (an unmasked argmax that is
12476            // grammar-legal IS the masked argmax: masking only removes competitors). The
12477            // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
12478            // measured in acceptance numbers, never hidden.
12479            let (n_acc, bonus) = match constraint.as_deref_mut() {
12480                None => (n_acc, bonus),
12481                Some(c) => {
12482                    fn ce(e2: String) -> Box<dyn std::error::Error> {
12483                        format!("constraint: {e2}").into()
12484                    }
12485                    let mut na = n_acc;
12486                    let mut cut = false;
12487                    for (j, &d) in draft.iter().enumerate().take(n_acc) {
12488                        if c.is_allowed(d).map_err(ce)? {
12489                            c.consume(d).map_err(ce)?;
12490                        } else {
12491                            na = j;
12492                            cut = true;
12493                            dm_cut_tokens += n_acc - j;
12494                            break;
12495                        }
12496                    }
12497                    if cut {
12498                        dm_cuts += 1;
12499                    }
12500                    let mut bo = bonus;
12501                    if cut || !c.is_allowed(bo).map_err(ce)? {
12502                        let mut row = if na == 0 && base == 0 {
12503                            init_logits_host
12504                                .clone()
12505                                .ok_or("constraint: init logits missing (round-0 cut)")?
12506                        } else {
12507                            e.dtoh_view(
12508                                &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
12509                            )?
12510                        };
12511                        c.mask_logits(&mut row).map_err(ce)?;
12512                        bo = argmax(&row) as u32;
12513                    }
12514                    c.consume(bo).map_err(ce)?;
12515                    (na, bo)
12516                }
12517            };
12518            let mut successor_valid = false;
12519            if let Some((q_proxy, expected_d2)) = rejected_probe {
12520                let v_n = n_acc == 1 && bonus == expected_d2;
12521                eprintln!(
12522                    "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
12523                     expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
12524                );
12525            }
12526            if let Some(successor) = successor_attempt.as_ref() {
12527                successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
12528                let generation = successor.generation;
12529                let q_proxy = successor.q_proxy;
12530                let expected_pending = successor.verify_tokens[0];
12531                let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
12532                let fork = opti_fork
12533                    .as_mut()
12534                    .ok_or("optipipe successor resolution lost fork state")?;
12535                fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
12536                if successor_valid {
12537                    OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12538                } else {
12539                    OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12540                    OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12541                    OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
12542                }
12543                let breaker_tripped = fork
12544                    .controller
12545                    .as_mut()
12546                    .expect("controller policy")
12547                    .resolve(successor_valid);
12548                if breaker_tripped {
12549                    OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12550                }
12551                eprintln!(
12552                    "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
12553                     expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
12554                     resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
12555                    generation.id, successor_valid, !successor_valid, breaker_tripped,
12556                );
12557                if !successor_valid {
12558                    let mut successor = successor_attempt
12559                        .take()
12560                        .expect("controller successor disappeared on miss");
12561                    successor.settle();
12562                    fork.retire(generation)?;
12563                }
12564            }
12565            total_drafted += k_round;
12566            total_accepted += n_acc;
12567            if let Some(t) = sess_telem {
12568                // Greedy, rejection-sampling, and grammar truncation all converge here after
12569                // the accept decision is already on host. Fixed-size relaxed atomics only.
12570                t.record_round(k_round, n_acc);
12571            }
12572            if spec_stats {
12573                st_len_hist[k_round] += 1;
12574                for j in 0..k_round {
12575                    st_drafted[j] += 1;
12576                }
12577                for j in 0..n_acc {
12578                    st_accepted[j] += 1;
12579                }
12580                if n_acc == k_round {
12581                    st_full += 1;
12582                }
12583            }
12584
12585            if debug_spec {
12586                eprintln!(
12587                    "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
12588                    out.len(),
12589                    // NOT `t_pred(0)`: `preds` is filled only under `if !sampled` above, so on a
12590                    // sampled request round >= 1 (base == 1) indexed an EMPTY vector and PANICKED
12591                    // the GPU worker thread — a debug flag that killed the exact regime you would
12592                    // set it to investigate. See `debug_t_pred0`.
12593                    debug_t_pred0(sampled, base, last_pred, &preds)
12594                );
12595            }
12596
12597            // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
12598            let commit_started = std::time::Instant::now();
12599            // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
12600            // of them (overshoot past max_new included) or `committed` under-counts the cache rows
12601            // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
12602            // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
12603            for j in 0..n_acc {
12604                if !session_mode && out.len() >= max_new {
12605                    break;
12606                }
12607                out.push(draft[j]);
12608            }
12609            if pen_on {
12610                pen_hist.extend_from_slice(&draft[0..n_acc]);
12611                pen_hist.push(bonus);
12612            }
12613            let bonus_emitted = session_mode || out.len() < max_new;
12614            if bonus_emitted {
12615                out.push(bonus);
12616            }
12617            last_token = bonus;
12618
12619            // --- 5. ROLLBACK + advance (§C) ---
12620            if n_acc == k_round && !spec_replay {
12621                // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
12622                // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
12623                // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
12624                // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
12625                // last_pred is dead in the pending path (t_pred reads verify col 0).
12626                //
12627                // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
12628                // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
12629                // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
12630                // trunk hidden (the last verify column). set_len first: a p-min break may have
12631                // left one extra chain append at that slot. Partial accepts need NO fill (the
12632                // chain already covered every accepted position; round-start set_len truncates).
12633                let mut vh_seed = e.zeros(n_embd)?;
12634                e.copy_view_into(
12635                    &mut vh_seed,
12636                    0,
12637                    &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
12638                    n_embd,
12639                )?;
12640                if refresh {
12641                    // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
12642                    // overwrite ALL committed positions' scratch entries with K/V from their EXACT
12643                    // verify hiddens — the reference engine's mtp_update fills from true hiddens;
12644                    // the full stack (vx) is already resident from the verify. Replaces both the
12645                    // chain-approximate entries AND the old last-token-only fill. Acceptance-only
12646                    // (draft attention quality); exactness stays the verify's job.
12647                    scratch.set_len(e, pos)?;
12648                    // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
12649                    // (hidden of the last committed row before this verify batch).
12650                    let mut vxs = e.zeros(t_v * n_embd)?;
12651                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
12652                    if t_v > 1 {
12653                        e.copy_view_into(
12654                            &mut vxs,
12655                            n_embd,
12656                            &vx.slice(0..(t_v - 1) * n_embd),
12657                            (t_v - 1) * n_embd,
12658                        )?;
12659                    }
12660                    self.mtp_kv_fill_all(e, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
12661                } else {
12662                    scratch.set_len(e, pos + base + k_round - 1)?;
12663                    // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
12664                    let mut hp = e.zeros(n_embd)?;
12665                    if t_v >= 2 {
12666                        e.copy_view_into(
12667                            &mut hp,
12668                            0,
12669                            &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
12670                            n_embd,
12671                        )?;
12672                    } else {
12673                        e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
12674                    }
12675                    self.mtp_kv_fill_all(
12676                        e,
12677                        &[draft[k_round - 1]],
12678                        &hp,
12679                        pos + base + k_round - 1,
12680                        &mut *scratch,
12681                        embd_dev,
12682                    )?;
12683                }
12684                // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
12685                // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
12686                // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
12687                // col). Saves one MTP-block pass per round on top of the pairing fix.
12688                if !devacc_seeded {
12689                    e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
12690                    e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
12691                }
12692                pending = Some(bonus);
12693                if debug_spec {
12694                    eprintln!("  -> FULL ACCEPT (bonus pending, prev-h seed)");
12695                }
12696            } else if !spec_replay && base + n_acc >= 1 {
12697                // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
12698                // the verify's first j = base+n_acc columns ARE the committed sequence, computed
12699                // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
12700                // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
12701                // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
12702                // full-accept path — the legacy duplicate trunk replay is gone. The next chain
12703                // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
12704                // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
12705                // accept (never compounds: the next verify recomputes true hiddens for all
12706                // committed columns).
12707                let j = base + n_acc;
12708                // VERIFY-GRAPH SLAB COMMIT: when the captured trunk ran, the linear layers'
12709                // column stash was written into the graphs ctx's persistent slabs as in-graph
12710                // memcpy nodes, NOT into the per-column VerifyCkpt the cols arm reads — so the
12711                // commit must take the slab twin (same semantics, slab-addressed sources). The
12712                // ctx states which of the two this round produced via `round_slab`; trusting the
12713                // flag rather than the env keeps a round that fell back to the eager walk (a
12714                // capture that declined, a t the pool never captured) on the cols arm.
12715                let slab_commit = vg_guard
12716                    .as_ref()
12717                    .and_then(|g| g.as_ref())
12718                    .map(|g| g.round_slab)
12719                    .unwrap_or(false);
12720                if slab_commit {
12721                    self.dspark_commit_prefix_slab(
12722                        e,
12723                        &mut *cache,
12724                        &snap,
12725                        vg_guard
12726                            .as_ref()
12727                            .and_then(|g| g.as_ref())
12728                            .expect("slab_commit implies a graphs ctx"),
12729                        j,
12730                    )?;
12731                } else {
12732                    self.commit_verified_prefix(
12733                        e,
12734                        &mut *cache,
12735                        &snap,
12736                        ckpt.as_ref().unwrap(),
12737                        j,
12738                        devacc_seeded,
12739                        if devacc_seeded {
12740                            devacc_acc.as_ref().map(|a| (a, base, t_v))
12741                        } else {
12742                            None
12743                        },
12744                    )?;
12745                }
12746                let mut seed = e.zeros(n_embd)?;
12747                e.copy_view_into(
12748                    &mut seed,
12749                    0,
12750                    &vx.slice((j - 1) * n_embd..j * n_embd),
12751                    n_embd,
12752                )?;
12753                // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
12754                // branch); without it the chain entries stand and only the tail truncates. Either
12755                // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
12756                // (persistent mode), rope pos+j+1 (chain convention).
12757                if refresh {
12758                    scratch.set_len(e, pos)?;
12759                    let mut vxs = e.zeros(j * n_embd)?;
12760                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
12761                    if j > 1 {
12762                        e.copy_view_into(
12763                            &mut vxs,
12764                            n_embd,
12765                            &vx.slice(0..(j - 1) * n_embd),
12766                            (j - 1) * n_embd,
12767                        )?;
12768                    }
12769                    self.mtp_kv_fill_all(
12770                        e,
12771                        &verify_tokens[0..j],
12772                        &vxs,
12773                        pos,
12774                        &mut *scratch,
12775                        embd_dev,
12776                    )?;
12777                } else {
12778                    scratch.set_len(e, pos + j)?;
12779                }
12780                // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
12781                // bonus's predecessor (verify col j-1); no pseudo pass.
12782                if !devacc_seeded {
12783                    e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
12784                    e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
12785                }
12786                pending = Some(bonus);
12787                if debug_spec {
12788                    eprintln!("  -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
12789                }
12790            } else if !spec_replay {
12791                // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
12792                // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
12793                // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
12794                // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
12795                // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
12796                // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
12797                // base=1 pending machinery, bit-identical by the decode-exact verify contract.
12798                // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
12799                // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
12800                cache.rollback(e, &snap, 0)?;
12801                scratch.set_len(e, pos)?;
12802                e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
12803                pending = Some(bonus);
12804                if debug_spec {
12805                    eprintln!("  -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
12806                }
12807            } else {
12808                // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
12809                // this round survives, only possible before the first pending exists, ~round 0):
12810                // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
12811                // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
12812                // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
12813                // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
12814                // trunk hidden.
12815                cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
12816                let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
12817                if let Some(b) = pending.take() {
12818                    replay.push(b);
12819                }
12820                replay.extend_from_slice(&draft[0..n_acc]);
12821                replay.push(bonus);
12822                // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
12823                // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
12824                // last col exactly as before (byte-identical to the old _h_emb_dev call).
12825                let (rl_d, rx) = if self.batched_serving_numeric_class() {
12826                    let mut logits = Vec::with_capacity(replay.len() * n_vocab);
12827                    let mut hidden = e.uninit(replay.len() * n_embd)?;
12828                    for (row, &token) in replay.iter().enumerate() {
12829                        let (row_logits, row_hidden) =
12830                            self.spec_target_step_h(e, token, &mut *cache)?;
12831                        logits.extend_from_slice(&row_logits);
12832                        e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
12833                    }
12834                    (e.htod(&logits)?, hidden)
12835                } else {
12836                    self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
12837                };
12838                // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
12839                // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
12840                e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
12841                last_pred = e.dtoh_u32(&preds_d)?[0];
12842                if sampled {
12843                    let lr0 = replay.len();
12844                    let lc = last_col_logits
12845                        .as_mut()
12846                        .expect("sampled: last_col_logits unset");
12847                    e.copy_view_into(
12848                        lc,
12849                        0,
12850                        &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
12851                        n_vocab,
12852                    )?;
12853                }
12854                let lr = replay.len();
12855                if lr >= 2 {
12856                    e.copy_view_into(
12857                        &mut h_seed_buf,
12858                        0,
12859                        &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
12860                        n_embd,
12861                    )?;
12862                } else {
12863                    // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
12864                    // last_token, whose own-row hidden fill_prev still holds.
12865                    e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
12866                }
12867                // the bonus is COMMITTED here — it becomes the last committed row.
12868                let mut rh_last = e.zeros(n_embd)?;
12869                e.copy_view_into(
12870                    &mut rh_last,
12871                    0,
12872                    &rx.slice((lr - 1) * n_embd..lr * n_embd),
12873                    n_embd,
12874                )?;
12875                e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
12876                if debug_spec {
12877                    eprintln!("  -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
12878                }
12879            }
12880            if devacc_seeded {
12881                // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
12882                // consumed the old value (both slots carry the same value in every non-replay arm).
12883                e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
12884            }
12885            if successor_valid {
12886                let optimistic_scratch_len = successor_attempt
12887                    .as_ref()
12888                    .expect("valid controller successor disappeared")
12889                    .scratch_len;
12890                // The normal current-round commit refreshed/truncated the logical scratch tail.
12891                // Its optimistic successor row was already written physically, so restoring only
12892                // the retained logical length makes that row live for the carried round.
12893                scratch.set_len(e, optimistic_scratch_len)?;
12894            }
12895            if let Some(current) = current_opti.take() {
12896                opti_fork
12897                    .as_mut()
12898                    .ok_or("optipipe current retirement lost fork state")?
12899                    .retire(current.generation)?;
12900            }
12901            if successor_valid {
12902                let successor = successor_attempt
12903                    .take()
12904                    .expect("valid controller successor disappeared before promotion");
12905                let generation = successor.generation;
12906                opti_fork
12907                    .as_mut()
12908                    .ok_or("optipipe successor promotion lost fork state")?
12909                    .promote_successor_snapshot(&mut snap, generation);
12910                carried_opti = Some(successor);
12911            }
12912            if anatomy_on {
12913                // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
12914                // only for this diagnostic so it does not disappear into the following draft's
12915                // first token readback.
12916                e.stream().synchronize()?;
12917                ph_commit += commit_started.elapsed().as_secs_f64();
12918            }
12919            // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
12920            // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
12921            // final position — the floor's position key reads the committed depth). Burst
12922            // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
12923            // like gemma's burst arm.
12924            if adapt {
12925                let fl_now = floor_at(cache.pos);
12926                kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
12927            }
12928            ph_mark(&mut ph_rest, phase_on);
12929            if let Some(p) = pipe {
12930                p.accept_end(round);
12931            }
12932            drop(pipe_accept);
12933            round += 1;
12934            // sse-cadence: this round's accepted drafts + bonus are committed (out is
12935            // append-only past step 4) — flush at round cadence.
12936            keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
12937        }
12938        if let Some(mut ticket) = carried_opti.take() {
12939            opti_fork
12940                .as_mut()
12941                .ok_or("optipipe tail drain lost fork state")?
12942                .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
12943        }
12944        // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
12945        // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
12946        let _ = flush_commit(&mut on_commit, &out, &mut flushed);
12947
12948        if spec_stats {
12949            let per_slot: Vec<String> = (0..k)
12950                .map(|j| {
12951                    if st_drafted[j] > 0 {
12952                        format!(
12953                            "{}/{}={:.3}",
12954                            st_accepted[j],
12955                            st_drafted[j],
12956                            st_accepted[j] as f64 / st_drafted[j] as f64
12957                        )
12958                    } else {
12959                        "0/0".into()
12960                    }
12961                })
12962                .collect();
12963            let acc = if total_drafted > 0 {
12964                total_accepted as f64 / total_drafted as f64
12965            } else {
12966                0.0
12967            };
12968            eprintln!(
12969                "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
12970                       per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
12971                       tok_per_round={:.3}",
12972                per_slot.join(" "),
12973                (total_accepted + round) as f64 / round.max(1) as f64
12974            );
12975        }
12976        if constraint.is_some() {
12977            eprintln!(
12978                "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
12979                 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
12980                dm_clone_ns as f64 / 1e6,
12981                dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
12982            );
12983        }
12984        if phase_on {
12985            let tot = ph_draft + ph_verify + ph_wait + ph_rest;
12986            eprintln!(
12987                "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
12988                ph_draft * 1e3,
12989                ph_draft / tot * 100.0,
12990                ph_verify * 1e3,
12991                ph_verify / tot * 100.0,
12992                ph_wait * 1e3,
12993                ph_wait / tot * 100.0,
12994                ph_rest * 1e3,
12995                ph_rest / tot * 100.0
12996            );
12997        }
12998        if anatomy_on {
12999            let rounds_f = round.max(1) as f64;
13000            let other = (ph_rest - ph_commit).max(0.0);
13001            eprintln!(
13002                "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
13003                 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
13004                ph_draft * 1e3 / rounds_f,
13005                ph_verify * 1e3 / rounds_f,
13006                ph_wait * 1e3 / rounds_f,
13007                ph_commit * 1e3 / rounds_f,
13008                other * 1e3 / rounds_f,
13009            );
13010        }
13011        let _pipe_tail = pipe.map(|p| p.primary());
13012        // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
13013        // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
13014        // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
13015        // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
13016        if let Some(slot) = sess_draft_slot.take() {
13017            *slot = Some(dctx);
13018        }
13019        let t_rounds = t_ent.elapsed();
13020        if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
13021            // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
13022            // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
13023            // HERE, where the sampler, the session Philox counters and the penalty window are
13024            // all live and the boundary logits row still exists — that is the "make the state
13025            // available" half of the fix; the consuming burst then just emits it. `sctr` is
13026            // written to the session BELOW the draws so the advance is never lost.
13027            *next_pred_slot = Some(last_pred);
13028            let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
13029            let mut stashed_pending = false;
13030            if let Some(b) = pending.take() {
13031                if !sampled {
13032                    // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
13033                    // committing it with a solo T=1 pass — the next empty-suffix greedy burst
13034                    // consumes it as round-0 verify col 0 (a plain round edge; the old tail
13035                    // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
13036                    // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
13037                    // OUT of `committed` (cache rows == committed); the consuming call
13038                    // prepends it once its verify commits the row. next_pred is unknowable
13039                    // without the commit pass — None; callers gate on pending_tok too.
13040                    debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
13041                    if let Some(slot) = sess_pending_slot.take() {
13042                        *slot = Some(b);
13043                    }
13044                    *next_pred_slot = None;
13045                    // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
13046                    // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
13047                    *last_h = Some(e.clone_dtod(&fill_prev)?);
13048                    stashed_pending = true;
13049                } else {
13050                    // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
13051                    // the sampled round-0 accept needs this pass's logits (last_col_logits).
13052                    let pos_b = cache.pos;
13053                    scratch.set_len(e, pos_b)?;
13054                    let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
13055                    // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
13056                    // itself — the prediction AFTER the bonus never materialized; it would have
13057                    // been the next round's verify col 0). The commit's logits ARE that
13058                    // prediction — so they are also the row the next burst's boundary token
13059                    // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
13060                    *next_pred_slot = Some(if sample_boundary {
13061                        sample_boundary_token(
13062                            e,
13063                            &lg_b,
13064                            &sp,
13065                            &pen_hist,
13066                            &mut sctr,
13067                            "burst-tail-commit",
13068                        )?
13069                    } else {
13070                        argmax(&lg_b) as u32
13071                    });
13072                    self.mtp_kv_fill_all(e, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
13073                    *last_h = Some(hb);
13074                }
13075            } else {
13076                // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
13077                *last_h = Some(e.clone_dtod(&fill_prev)?);
13078                if sample_boundary {
13079                    // No pending to commit, so the boundary row is the one `last_pred` was
13080                    // argmaxed from and the sampled path keeps it on device: the init feed's
13081                    // logits when the burst ran zero rounds, else the legacy-replay path's
13082                    // last verify column (both predict the token AFTER the last committed
13083                    // row). It is retained precisely because round 0's accept test needs it,
13084                    // so the draw costs no extra D2H of the [n_vocab] row.
13085                    match last_col_logits.as_ref() {
13086                        Some(lc) => {
13087                            *next_pred_slot = Some(sample_boundary_token_dev(
13088                                e,
13089                                lc,
13090                                n_vocab,
13091                                &sp,
13092                                &pen_hist,
13093                                &mut sctr,
13094                                "burst-tail-nopending",
13095                            )?);
13096                        }
13097                        // NAME THE FALLBACK (house standard): unreachable today — a sampled
13098                        // burst always feeds or replays, so the row exists — but if it ever
13099                        // is, the stream takes a greedy token and SAYS so rather than
13100                        // silently regressing to the pre-lane behaviour.
13101                        None => eprintln!(
13102                            "[spec-boundary] sampled tail kept the ARGMAX boundary token \
13103                             (reason: no retained boundary logits row)"
13104                        ),
13105                    }
13106                }
13107            }
13108            *sctr_slot = sctr;
13109            *uctr_slot = uctr;
13110            committed.extend_from_slice(prompt);
13111            if let Some(cb) = carried_pending {
13112                // the consumed carry's cache row landed in round 0's verify (every pending
13113                // round commits col 0) — it joins `committed` here, in sequence order.
13114                committed.push(cb);
13115            }
13116            if stashed_pending {
13117                // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
13118                // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
13119                // 18446744073709551615 out of range for slice of length 0", killing the
13120                // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
13121                // stream". Reachable because `pending` starts as `carried_pending` (a bonus
13122                // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
13123                // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
13124                // did). So a burst that stashes a pending without emitting anything of its own —
13125                // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
13126                // guard skipping every token under a tight budget — arrives here with
13127                // out.len() == 0 and stashed_pending == true.
13128                //
13129                // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
13130                // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
13131                // just above is already accounted. Saturating, not a min/assert: an empty `out`
13132                // here is a legitimate burst shape, not a corrupt state.
13133                let emitted = out.len().saturating_sub(1);
13134                committed.extend_from_slice(&out[..emitted]);
13135            } else {
13136                committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
13137            }
13138            debug_assert_eq!(
13139                cache.pos,
13140                committed.len(),
13141                "session invariant: cache rows == committed tokens"
13142            );
13143            if setup_trace {
13144                e.stream().synchronize()?; // bound the async tail fill in the trace
13145                let t_tail = t_ent.elapsed();
13146                eprintln!(
13147                    "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
13148                    t_init.as_secs_f64() * 1e3,
13149                    (t_cap - t_init).as_secs_f64() * 1e3,
13150                    (t_fill - t_cap).as_secs_f64() * 1e3,
13151                    (t_rounds - t_fill).as_secs_f64() * 1e3,
13152                    (t_tail - t_rounds).as_secs_f64() * 1e3,
13153                    t_tail.as_secs_f64() * 1e3,
13154                    out.len(),
13155                    continuation
13156                );
13157            }
13158            return Ok((out, total_drafted, total_accepted));
13159        }
13160        out.truncate(max_new);
13161        Ok((out, total_drafted, total_accepted))
13162    }
13163
13164    /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
13165    /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
13166    /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
13167    pub fn extract_dspark_anchors(
13168        &self,
13169        e: &Engine,
13170        tokens: &[u32],
13171        anchor_positions: &[usize],
13172        gamma: usize,
13173        top_k: usize,
13174        chunk: usize,
13175        temperature: f32,
13176    ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
13177        if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
13178            return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
13179        }
13180        if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
13181            return Err("DSpark anchor positions must be sorted and unique".into());
13182        }
13183        for &position in anchor_positions {
13184            if position == 0 || position + gamma >= tokens.len() {
13185                return Err(format!(
13186                    "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
13187                    tokens.len()
13188                )
13189                .into());
13190            }
13191        }
13192
13193        let n_vocab = self.output.out_features();
13194        let n_embd = self.cfg.n_embd as usize;
13195        let mut cache =
13196            crate::pp::new_cache_planned(e, &self.cfg, &self.plan, tokens.len() + gamma + 8)?;
13197        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
13198        let embd_gpu = if spec_host_embd() {
13199            None
13200        } else {
13201            Some(
13202                self.embd_gpu
13203                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
13204            )
13205        };
13206        let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
13207
13208        struct PendingRecord {
13209            position: usize,
13210            hidden: Option<Vec<f32>>,
13211            tokens: Vec<u32>,
13212            target_top_ids: Vec<Option<Vec<u32>>>,
13213            target_top_logits: Vec<Option<Vec<f32>>>,
13214            target_top_probs: Vec<Option<Vec<f32>>>,
13215            target_tail_probs: Vec<Option<f32>>,
13216        }
13217
13218        let mut pending: Vec<PendingRecord> = anchor_positions
13219            .iter()
13220            .map(|&position| PendingRecord {
13221                position,
13222                hidden: None,
13223                tokens: tokens[position..=position + gamma].to_vec(),
13224                target_top_ids: vec![None; gamma],
13225                target_top_logits: vec![None; gamma],
13226                target_top_probs: vec![None; gamma],
13227                target_tail_probs: vec![None; gamma],
13228            })
13229            .collect();
13230
13231        let mut start = 0usize;
13232        while start < tokens.len() {
13233            let end = (start + chunk).min(tokens.len());
13234            let chunk_tokens = &tokens[start..end];
13235            let (target_logits, hidden_rows) =
13236                self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
13237            for record in &mut pending {
13238                let hidden_position = record.position - 1;
13239                if hidden_position >= start && hidden_position < end {
13240                    let local = hidden_position - start;
13241                    record.hidden = Some(
13242                        e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
13243                    );
13244                }
13245                for slot in 0..gamma {
13246                    let target_row = record.position + slot;
13247                    if target_row < start || target_row >= end {
13248                        continue;
13249                    }
13250                    let local = target_row - start;
13251                    let logits =
13252                        e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
13253                    let (ids, top_logits, probs, tail) =
13254                        dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
13255                    record.target_top_ids[slot] = Some(ids);
13256                    record.target_top_logits[slot] = Some(top_logits);
13257                    record.target_top_probs[slot] = Some(probs);
13258                    record.target_tail_probs[slot] = Some(tail);
13259                }
13260            }
13261            start = end;
13262        }
13263
13264        pending
13265            .into_iter()
13266            .map(|record| {
13267                let hidden = record
13268                    .hidden
13269                    .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
13270                let target_top_ids =
13271                    flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
13272                let target_top_logits = flatten_dspark_rows(
13273                    record.target_top_logits,
13274                    record.position,
13275                    "target logits",
13276                )?;
13277                let target_top_probs =
13278                    flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
13279                let target_tail_probs = record
13280                    .target_tail_probs
13281                    .into_iter()
13282                    .enumerate()
13283                    .map(|(slot, value)| {
13284                        value.ok_or_else(|| {
13285                            format!("missing DSpark tail at {} slot {slot}", record.position)
13286                        })
13287                    })
13288                    .collect::<Result<Vec<_>, _>>()?;
13289                Ok(DsparkAnchorRecord {
13290                    position: record.position,
13291                    hidden,
13292                    tokens: record.tokens,
13293                    target_top_ids,
13294                    target_top_logits,
13295                    target_top_probs,
13296                    target_tail_probs,
13297                })
13298            })
13299            .collect()
13300    }
13301
13302    /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
13303    /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
13304    /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
13305    /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
13306    /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
13307    /// quant-induced head/hidden-state mismatch from text drift.
13308    ///
13309    /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
13310    ///   draft_j  = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
13311    ///              eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
13312    ///   target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
13313    ///              at forced context tokens[0..p+j]). For j==0 this equals live spec
13314    ///              acceptance; for j>=1 live verify would condition on the drafts, here it
13315    ///              conditions on the corpus — deterministic and arm-comparable by design.
13316    ///
13317    /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
13318    /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
13319    /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
13320    ///
13321    /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
13322    /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
13323    /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
13324    /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
13325    /// agreement vs this path — not usable as a training-data source).
13326    pub fn replay_acceptance(
13327        &self,
13328        e: &Engine,
13329        tokens: &[u32],
13330        k: usize,
13331        stride: usize,
13332        chunk: usize,
13333        mut hdump: Option<&mut std::fs::File>,
13334    ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
13335        assert!(k >= 1 && stride >= 1 && chunk >= 2);
13336        let mtp = self
13337            .mtp
13338            .as_ref()
13339            .expect("replay_acceptance requires an MTP head");
13340        let n_vocab = self.output.out_features();
13341        let d_vocab = mtp
13342            .shared_head_head
13343            .as_ref()
13344            .unwrap_or(&self.output)
13345            .out_features();
13346        let n_embd = self.cfg.n_embd as usize;
13347        let t_total = tokens.len();
13348        assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
13349        // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
13350        let mut cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, t_total + k + 8)?;
13351        let mut scratch = self.new_mtp_scratch(e, t_total + k + 8)?;
13352        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
13353        let embd_gpu = if spec_host_embd() {
13354            None
13355        } else {
13356            Some(
13357                self.embd_gpu
13358                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
13359            )
13360        };
13361        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
13362
13363        // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
13364        let mut bg: Vec<u32> = vec![0; t_total + 1];
13365        let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
13366        let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
13367        let mut seed_buf = e.zeros(n_embd)?;
13368        let mut preds_d = e.alloc_u32_zeroed(chunk)?;
13369        let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
13370        let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
13371        let mut s = 0usize;
13372        while s < t_total {
13373            let cend = (s + chunk).min(t_total);
13374            let tc = cend - s;
13375            let ch = &tokens[s..cend];
13376            // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
13377            //    the chunk's true hiddens.
13378            let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
13379            for j in 0..tc {
13380                e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
13381            }
13382            let preds = e.dtoh_u32(&preds_d)?;
13383            for j in 0..tc {
13384                bg[s + j + 1] = preds[j];
13385            }
13386            // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
13387            // checkpoint-quality metric (position j's logits score the GOLD next token).
13388            if nll_on {
13389                let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
13390                if jmax > 0 {
13391                    let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
13392                    let rows: Vec<i32> = (0..jmax as i32).collect();
13393                    let idsd = e.htod_u32_v(&ids)?;
13394                    let rowsd = e.htod_i32(&rows)?;
13395                    let mut outd = e.zeros(jmax)?;
13396                    e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
13397                    for pr in e.dtoh(&outd)? {
13398                        nll_sum += -((pr.max(1e-30)) as f64).ln();
13399                        nll_cnt += 1;
13400                    }
13401                }
13402            }
13403            if let Some(f) = hdump.as_deref_mut() {
13404                use std::io::Write;
13405                let host: Vec<f32> = e.dtoh(&vx)?;
13406                // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
13407                // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
13408                let mut bytes = Vec::with_capacity(tc * n_embd * 2);
13409                for v in &host[..tc * n_embd] {
13410                    let b = v.to_bits();
13411                    let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
13412                    bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
13413                }
13414                f.write_all(&bytes)?;
13415            }
13416            // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
13417            // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
13418            // per token saved; the forced trunk pass + hdump is all the mode needs).
13419            let chainless = stride > t_total;
13420            if chainless {
13421                e.copy_view_into(
13422                    &mut prev_last_h,
13423                    0,
13424                    &vx.slice((tc - 1) * n_embd..tc * n_embd),
13425                    n_embd,
13426                )?;
13427                s = cend;
13428                continue;
13429            }
13430            // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
13431            //    row s reads the previous chunk's last true hidden, zeros at corpus start).
13432            let mut vxs = e.zeros(tc * n_embd)?;
13433            e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
13434            if tc > 1 {
13435                e.copy_view_into(
13436                    &mut vxs,
13437                    n_embd,
13438                    &vx.slice(0..(tc - 1) * n_embd),
13439                    (tc - 1) * n_embd,
13440                )?;
13441            }
13442            scratch.set_len(e, s)?;
13443            self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
13444            // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
13445            //    [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
13446            //    truncates those approximate appends before they can ever be read.
13447            let ps: Vec<usize> = (s..cend)
13448                .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
13449                .collect();
13450            for &p in ps.iter().rev() {
13451                scratch.set_len(e, p)?;
13452                if p == s {
13453                    e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
13454                } else {
13455                    e.copy_view_into(
13456                        &mut seed_buf,
13457                        0,
13458                        &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
13459                        n_embd,
13460                    )?;
13461                }
13462                let mut e_tok = tokens[p];
13463                let mut d_seed = e.clone_dtod(&seed_buf)?;
13464                let chain_heads = !self.mtp_extra.is_empty();
13465                let mut chain_tokens = if chain_heads {
13466                    vec![tokens[p]]
13467                } else {
13468                    Vec::new()
13469                };
13470                let mut chain_seeds = if chain_heads {
13471                    vec![e.clone_dtod(&seed_buf)?]
13472                } else {
13473                    Vec::new()
13474                };
13475                let mut drafts: Vec<u32> = Vec::with_capacity(k);
13476                for j in 0..k {
13477                    let (dl_d, h_nextn) = if chain_heads {
13478                        self.mtp_chain_forward_dev(
13479                            e,
13480                            &chain_tokens,
13481                            &chain_seeds,
13482                            &mut scratch,
13483                            p,
13484                            embd_dev,
13485                            None,
13486                        )?
13487                    } else {
13488                        self.mtp_head_forward_dev(
13489                            e,
13490                            mtp,
13491                            e_tok,
13492                            &d_seed,
13493                            &mut scratch,
13494                            p + 1 + j,
13495                            embd_dev,
13496                            None,
13497                        )?
13498                    };
13499                    let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
13500                    let idx = e.dtoh_u32_one(&tok_d)?;
13501                    let d = match &mtp.d2t {
13502                        Some(map) => map[idx as usize],
13503                        None => idx,
13504                    };
13505                    drafts.push(d);
13506                    if chain_heads {
13507                        chain_tokens.push(d);
13508                        chain_seeds.push(h_nextn);
13509                    } else {
13510                        e_tok = d;
13511                        d_seed = h_nextn;
13512                    }
13513                }
13514                // targets may live in a LATER chunk's bg — resolved after the walk.
13515                rows.push((p, drafts, Vec::new()));
13516            }
13517            // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
13518            //    expect scratch.len == cend with exact rows).
13519            scratch.set_len(e, s)?;
13520            self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
13521            e.copy_view_into(
13522                &mut prev_last_h,
13523                0,
13524                &vx.slice((tc - 1) * n_embd..tc * n_embd),
13525                n_embd,
13526            )?;
13527            s = cend;
13528        }
13529        for (p, drafts, targets) in rows.iter_mut() {
13530            for j in 0..drafts.len() {
13531                targets.push(bg[*p + 1 + j]);
13532            }
13533        }
13534        rows.sort_by_key(|r| r.0);
13535        if nll_cnt > 0 {
13536            let mean = nll_sum / nll_cnt as f64;
13537            println!(
13538                "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
13539                mean.exp()
13540            );
13541        }
13542        Ok((rows, bg))
13543    }
13544}
13545
13546#[cfg(test)]
13547mod mtp_chain_tests {
13548    use super::mtp_chain_head_index;
13549
13550    #[test]
13551    fn embedded_step_heads_cycle_in_declared_order() {
13552        let actual: Vec<usize> = (0..8).map(|step| mtp_chain_head_index(step, 3)).collect();
13553        assert_eq!(actual, [0, 1, 2, 0, 1, 2, 0, 1]);
13554    }
13555
13556    #[test]
13557    fn standalone_draft_remains_single_head() {
13558        assert!((0..8).all(|step| mtp_chain_head_index(step, 1) == 0));
13559    }
13560}
13561
13562#[cfg(test)]
13563mod tp_verified_prefix_tests {
13564    use super::rewind_tp_kv_verified_prefix;
13565    use crate::tp::ResidentTpKvCache;
13566
13567    fn cache_with_committed_len(committed: usize) -> ResidentTpKvCache {
13568        let mut cache = ResidentTpKvCache::new(Vec::new(), 1, 1, 1, 1, 8);
13569        let transaction = cache.begin_transaction().unwrap();
13570        let target = cache.append_target(transaction, committed).unwrap();
13571        cache.publish_append(transaction, target).unwrap();
13572        let target = cache.commit_target(transaction, committed).unwrap();
13573        cache.publish_finalize(transaction, target).unwrap();
13574        cache
13575    }
13576
13577    #[test]
13578    fn replay_free_prefix_rewinds_tp_visibility_to_snapshot_plus_accepts() {
13579        let mut layers = vec![Some(cache_with_committed_len(5)), None];
13580        rewind_tp_kv_verified_prefix(&mut layers, &[Some(2), None], 1).unwrap();
13581        let cache = layers[0].as_ref().unwrap();
13582        assert_eq!(cache.committed_len(), 3);
13583        assert_eq!(cache.staged_len(), 3);
13584    }
13585
13586    #[test]
13587    fn replay_free_prefix_rejects_a_changed_tp_cache_shape() {
13588        let mut layers = vec![Some(cache_with_committed_len(1))];
13589        let error = rewind_tp_kv_verified_prefix(&mut layers, &[None], 1)
13590            .unwrap_err()
13591            .to_string();
13592        assert!(error.contains("changed shape"), "unexpected error: {error}");
13593    }
13594}
13595
13596#[cfg(test)]
13597mod dspark_sparse_tests {
13598    use super::dspark_sparse_softmax_topk;
13599
13600    #[test]
13601    fn topk_keeps_full_softmax_mass_and_stable_ties() {
13602        let logits = [1.0f32, 3.0, 3.0, -2.0];
13603        let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
13604        assert_eq!(ids, vec![1, 2]);
13605        assert_eq!(top_logits, vec![3.0, 3.0]);
13606        let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
13607        let expected = 1.0 / denominator;
13608        assert!((probs[0] - expected).abs() < 1.0e-6);
13609        assert!((probs[1] - expected).abs() < 1.0e-6);
13610        assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
13611        assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
13612    }
13613}
13614
13615#[cfg(test)]
13616mod spec_replay_env_tests {
13617    use super::spec_replay_env_on;
13618
13619    #[test]
13620    fn replay_requires_literal_one() {
13621        assert!(!spec_replay_env_on(None));
13622        assert!(!spec_replay_env_on(Some("")));
13623        assert!(!spec_replay_env_on(Some("0")));
13624        assert!(!spec_replay_env_on(Some("true")));
13625        assert!(!spec_replay_env_on(Some("2")));
13626        assert!(spec_replay_env_on(Some("1")));
13627    }
13628}
13629
13630#[cfg(test)]
13631mod telem_tests {
13632    use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
13633
13634    #[test]
13635    fn synthetic_accept_masks_produce_tau_and_position_histogram() {
13636        let counters = SpecTelemetryCounters::default();
13637        for mask in [
13638            [true, true, true],
13639            [true, true, false],
13640            [true, false, false],
13641            [false, false, false],
13642        ] {
13643            let accepted = mask.iter().take_while(|&&value| value).count();
13644            counters.record_round(mask.len(), accepted);
13645        }
13646
13647        let snapshot = counters.snapshot();
13648        assert_eq!(
13649            (snapshot.rounds, snapshot.drafted, snapshot.accepted),
13650            (4, 12, 6)
13651        );
13652        assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
13653        assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
13654        assert_eq!(snapshot.tau(), 1.5);
13655        assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
13656        assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
13657    }
13658
13659    /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
13660    /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
13661    #[test]
13662    fn delta_isolates_burst_contribution() {
13663        let mut t = SpecTelemetry::default();
13664        // "previous request": 2 rounds of k=3, accepts 3 then 1.
13665        for (kr, na) in [(3usize, 3usize), (3, 1)] {
13666            t.rounds += 1;
13667            t.drafted += kr as u64;
13668            t.accepted += na as u64;
13669            for j in 0..kr {
13670                t.pos_drafted[j] += 1;
13671            }
13672            for j in 0..na {
13673                t.pos_accepted[j] += 1;
13674            }
13675        }
13676        let before = t;
13677        // "this burst": 1 round k=3, accepts 2.
13678        t.rounds += 1;
13679        t.drafted += 3;
13680        t.accepted += 2;
13681        for j in 0..3 {
13682            t.pos_drafted[j] += 1;
13683        }
13684        for j in 0..2 {
13685            t.pos_accepted[j] += 1;
13686        }
13687        let d = t.delta_since(&before);
13688        assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
13689        assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
13690        assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
13691        assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
13692    }
13693
13694    /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
13695    /// aggregation invariant.
13696    #[test]
13697    fn merge_accumulates_fieldwise() {
13698        let mut agg = SpecTelemetry::default();
13699        let mut d1 = SpecTelemetry {
13700            rounds: 2,
13701            drafted: 6,
13702            accepted: 4,
13703            ..Default::default()
13704        };
13705        d1.pos_drafted[0] = 2;
13706        d1.pos_accepted[0] = 2;
13707        let mut d2 = SpecTelemetry {
13708            rounds: 1,
13709            drafted: 3,
13710            accepted: 1,
13711            ..Default::default()
13712        };
13713        d2.pos_drafted[0] = 1;
13714        d2.pos_accepted[0] = 1;
13715        d2.pos_drafted[1] = 1;
13716        agg.merge(&d1);
13717        agg.merge(&d2);
13718        assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
13719        assert_eq!(agg.pos_drafted[0], 3);
13720        assert_eq!(agg.pos_accepted[0], 3);
13721        assert_eq!(agg.pos_drafted[1], 1);
13722        assert_eq!(agg.pos_accepted[1], 0);
13723    }
13724
13725    /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
13726    /// public metrics surface and must never publish a u64-wrapped garbage value.
13727    #[test]
13728    fn delta_saturates_never_wraps() {
13729        let small = SpecTelemetry {
13730            rounds: 1,
13731            drafted: 2,
13732            accepted: 1,
13733            ..Default::default()
13734        };
13735        let big = SpecTelemetry {
13736            rounds: 5,
13737            drafted: 15,
13738            accepted: 9,
13739            ..Default::default()
13740        };
13741        let d = small.delta_since(&big);
13742        assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
13743    }
13744}
13745
13746#[cfg(test)]
13747mod opti_fork_tests {
13748    use super::{
13749        OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
13750    };
13751
13752    #[test]
13753    fn controller_threshold_and_three_miss_breaker_are_exact() {
13754        let mut policy = OptiControllerPolicy {
13755            threshold: 0.7,
13756            consecutive_misses: 0,
13757            breaker_tripped: false,
13758        };
13759        assert!(!policy.admit(0.699_999));
13760        assert!(policy.admit(0.7));
13761        assert!(!policy.resolve(false));
13762        assert!(!policy.resolve(false));
13763        assert!(policy.resolve(false));
13764        assert!(policy.breaker_tripped);
13765        assert!(!policy.admit(1.0));
13766        assert!(
13767            !policy.resolve(true),
13768            "a resolved hit cannot re-arm a tripped request"
13769        );
13770        assert!(policy.breaker_tripped);
13771    }
13772
13773    #[test]
13774    fn zero_threshold_is_the_true_unconditional_measurement_arm() {
13775        let mut policy = OptiControllerPolicy {
13776            threshold: 0.0,
13777            consecutive_misses: 0,
13778            breaker_tripped: false,
13779        };
13780        for _ in 0..16 {
13781            assert!(policy.admit(0.0));
13782            assert!(!policy.resolve(false));
13783        }
13784        for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
13785            assert!(
13786                !policy.admit(invalid),
13787                "invalid q proxy must fail closed: {invalid}"
13788            );
13789        }
13790        assert!(!policy.breaker_tripped);
13791        assert_eq!(policy.consecutive_misses, 0);
13792    }
13793
13794    #[test]
13795    fn alternating_mode_flips_by_generation_not_round_parity() {
13796        assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
13797        assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
13798        assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
13799        assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
13800    }
13801
13802    #[test]
13803    fn live_generation_cannot_be_overwritten() {
13804        let mut tracker = OptiForkGenerationTracker::default();
13805        let g0 = tracker.reserve().unwrap();
13806        let g1 = tracker.reserve().unwrap();
13807        let err = tracker.reserve().unwrap_err().to_string();
13808        assert!(
13809            err.contains("still owns generation 0"),
13810            "unexpected error: {err}"
13811        );
13812        tracker.retire(g0).unwrap();
13813        let g2 = tracker.reserve().unwrap();
13814        assert_eq!((g2.id, g2.slot), (2, 0));
13815        tracker.retire(g1).unwrap();
13816        tracker.retire(g2).unwrap();
13817    }
13818
13819    #[test]
13820    fn teardown_rejects_a_stale_generation_tag() {
13821        let mut tracker = OptiForkGenerationTracker::default();
13822        let g0 = tracker.reserve().unwrap();
13823        tracker.retire(g0).unwrap();
13824        let err = tracker.retire(g0).unwrap_err().to_string();
13825        assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
13826    }
13827}
13828
13829#[cfg(test)]
13830mod draft_graph_fallback_tests {
13831    use super::DraftGraphFallback;
13832
13833    /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
13834    #[test]
13835    fn flip_is_loud_once_and_memoized_after() {
13836        let mut f = DraftGraphFallback::default();
13837        let line = f
13838            .mark_greedy("out of memory")
13839            .expect("first flip must return the warn line");
13840        assert!(
13841            line.contains("WARN"),
13842            "flip line must be warn-level: {line}"
13843        );
13844        assert!(
13845            line.contains("out of memory"),
13846            "flip line must carry the reason: {line}"
13847        );
13848        assert!(f.greedy_failed());
13849        // re-marking an already-failed graph is the memoization: quiet, still failed.
13850        assert!(f.mark_greedy("out of memory").is_none());
13851        assert!(f.greedy_failed());
13852        // the two graphs' flags are independent (greedy flip leaves sampled capturable).
13853        assert!(!f.sampled_failed());
13854        let line_s = f
13855            .mark_sampled("capture unsupported")
13856            .expect("sampled flip is its own flip");
13857        assert!(
13858            line_s.contains("sampled"),
13859            "sampled flip names itself: {line_s}"
13860        );
13861        assert!(f.mark_sampled("capture unsupported").is_none());
13862    }
13863
13864    /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
13865    /// and says so exactly when there was something to reset.
13866    #[test]
13867    fn reset_on_resume_clears_flags_and_logs_once() {
13868        let mut f = DraftGraphFallback::default();
13869        // clean session: resume is silent, nothing to reset.
13870        assert!(f.reset_on_resume().is_none());
13871        f.mark_greedy("oom").unwrap();
13872        f.mark_sampled("oom").unwrap();
13873        let note = f
13874            .reset_on_resume()
13875            .expect("a set flag must produce the reset note");
13876        assert!(
13877            note.contains("greedy+sampled"),
13878            "note names what was reset: {note}"
13879        );
13880        assert!(
13881            !f.greedy_failed() && !f.sampled_failed(),
13882            "both flags cleared"
13883        );
13884        // and the NEXT failure after a reset is a fresh flip — loud again.
13885        assert!(f.mark_greedy("oom again").is_some());
13886        let note2 = f.reset_on_resume().expect("greedy-only reset");
13887        assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
13888    }
13889
13890    /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
13891    /// they precede a fresh capture attempt whose own failure re-flips loudly.
13892    #[test]
13893    fn shape_change_clears_are_silent() {
13894        let mut f = DraftGraphFallback::default();
13895        f.mark_greedy("oom").unwrap();
13896        f.clear_greedy();
13897        assert!(!f.greedy_failed());
13898        f.mark_sampled("oom").unwrap();
13899        f.clear_sampled();
13900        assert!(!f.sampled_failed());
13901        // after a silent clear there is nothing left for resume to report.
13902        assert!(f.reset_on_resume().is_none());
13903    }
13904}
13905
13906/// SAMPLED DRAFT-GRAPH KEY (lane/graph-s-key-exactness-20260819).
13907///
13908/// These are the CPU teeth for an exactness bug whose live reproduction needs a GPU, a trunk, a
13909/// drafter and a two-turn session: the key itself. Every test below fails against the pre-fix key
13910/// `(seed, temp.to_bits(), k)` — `legacy_key` restates it so the collision is explicit rather
13911/// than remembered.
13912#[cfg(test)]
13913mod sampled_graph_key_tests {
13914    use super::{SampledGraphKey, debug_t_pred0};
13915
13916    /// The pre-fix key, verbatim: `let s_key = (sp_seed, sp_temp.to_bits(), k);`
13917    fn legacy_key(k: &SampledGraphKey) -> (u64, u32, usize) {
13918        (k.seed, k.temp_bits, k.k)
13919    }
13920
13921    fn pure_temp_key() -> SampledGraphKey {
13922        // temperature 1.0, filters off — today's serve default, the shape that parks a graph.
13923        SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, false)
13924    }
13925
13926    /// THE COLLISION. Two requests that differ ONLY in the truncation filters shared one key, so
13927    /// a parked pure-temp graph survived into a filtered request and the launch site launched it.
13928    #[test]
13929    fn vendor_filters_change_the_key() {
13930        let parked = pure_temp_key();
13931        // qwen3.8 generation_config.json — what the vendor-default flip makes the default shape.
13932        let vendor = SampledGraphKey::new(12345, 1.0, 3, 20, 0.95, 0.0, false);
13933        assert_eq!(
13934            legacy_key(&parked),
13935            legacy_key(&vendor),
13936            "pre-fix key collided: this is the bug, and the reason a test asserts on it",
13937        );
13938        assert_ne!(parked, vendor, "post-fix key must separate the two regimes");
13939        assert!(parked.pure_temp());
13940        assert!(!vendor.pure_temp());
13941    }
13942
13943    /// Each distribution-shaping field alone is enough to drop the parked graph.
13944    #[test]
13945    fn every_filter_field_is_keyed() {
13946        let base = pure_temp_key();
13947        for (what, other) in [
13948            (
13949                "top_k",
13950                SampledGraphKey::new(12345, 1.0, 3, 20, 1.0, 0.0, false),
13951            ),
13952            (
13953                "top_p",
13954                SampledGraphKey::new(12345, 1.0, 3, 0, 0.95, 0.0, false),
13955            ),
13956            (
13957                "min_p",
13958                SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.05, false),
13959            ),
13960            (
13961                "penalties",
13962                SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, true),
13963            ),
13964        ] {
13965            assert_ne!(base, other, "{what} must be part of the key");
13966            assert!(!other.pure_temp(), "{what} leaves the pure-temp regime");
13967            assert_eq!(
13968                legacy_key(&base),
13969                legacy_key(&other),
13970                "{what} was invisible to the pre-fix key",
13971            );
13972        }
13973    }
13974
13975    /// The baked constants stay keyed (this half was always right — regression cover for it).
13976    #[test]
13977    fn baked_constants_stay_keyed() {
13978        let base = pure_temp_key();
13979        assert_ne!(
13980            base,
13981            SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false),
13982            "seed"
13983        );
13984        assert_ne!(
13985            base,
13986            SampledGraphKey::new(12345, 0.7, 3, 0, 1.0, 0.0, false),
13987            "temp"
13988        );
13989        assert_ne!(
13990            base,
13991            SampledGraphKey::new(12345, 1.0, 4, 0, 1.0, 0.0, false),
13992            "k"
13993        );
13994        // bitwise on temperature: 0.7f32 vs the same value re-derived must NOT differ.
13995        assert_eq!(
13996            SampledGraphKey::new(1, 0.7, 3, 0, 1.0, 0.0, false),
13997            SampledGraphKey::new(1, 7.0 / 10.0, 3, 0, 1.0, 0.0, false),
13998        );
13999    }
14000
14001    /// THE LOAD-BEARING HALF OF THE SEED DECISION (lane/session-resume-sampler-predicate-
14002    /// 20260820). The whole-session resume predicate deliberately does NOT compare `seed`: an
14003    /// omitted serve `seed` draws fresh per-request entropy, so comparing it would refuse every
14004    /// seed-omitting sampled conversation. That is only sound because the one piece of parked state
14005    /// that BAKES the seed — this graph — is re-keyed on it, so a seed change drops and recaptures.
14006    ///
14007    /// This test is the other end of that argument, asserted here rather than remembered in a
14008    /// comment: if a future change dropped `seed` from the key, the resume predicate's exclusion
14009    /// would silently become the unsound thing it is documented not to be.
14010    /// (Paired with `seed_alone_does_not_refuse` in `memra-sampling`.)
14011    #[test]
14012    fn seed_alone_still_rekeys_the_draft_graph() {
14013        let parked = pure_temp_key();
14014        let reseeded = SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false);
14015        assert_ne!(
14016            parked, reseeded,
14017            "a seed-only change MUST drop the parked sampled graph — the resume predicate's \
14018             decision not to compare seed rests on exactly this",
14019        );
14020        // Same regime on both sides: the drop is a recapture, not a fall to the eager chain
14021        // because of a filter difference.
14022        assert!(parked.pure_temp() && reseeded.pure_temp());
14023    }
14024
14025    /// `pure_temp()` is the capture guard's predicate, computed from the key so the two cannot
14026    /// drift. The equality below is the invariant the launch-site guard asserts: identical keys
14027    /// agree on the regime, so a graph that survives the drop is legal to launch.
14028    #[test]
14029    fn equal_keys_agree_on_the_regime() {
14030        let a = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
14031        let b = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
14032        assert_eq!(a, b);
14033        assert_eq!(a.pure_temp(), b.pure_temp());
14034        // top_p slightly above 1.0 (a client sending 1.0 exactly, or an operator default) is
14035        // still the unfiltered regime, matching the original `sp.top_p >= 1.0` test.
14036        assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.0, 0.0, false).pure_temp());
14037        assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.5, -1.0, false).pure_temp());
14038    }
14039
14040    /// MEMRA_DEBUG_SPEC on a SAMPLED spec request past round 0: the print must render without
14041    /// indexing the empty greedy `preds` vector (it panicked the GPU worker before this lane).
14042    #[test]
14043    fn debug_print_survives_the_sampled_arm() {
14044        // round >= 1 with a pending bonus == base 1, sampled == `preds` empty.
14045        assert_eq!(debug_t_pred0(true, 1, 4242, &[]), "n/a");
14046        assert_eq!(debug_t_pred0(true, 2, 4242, &[]), "n/a");
14047        // round 0 without a pending bonus still reports last_pred, in both arms.
14048        assert_eq!(debug_t_pred0(true, 0, 4242, &[]), "4242");
14049        assert_eq!(debug_t_pred0(false, 0, 4242, &[7, 8]), "4242");
14050        // greedy keeps the real prediction it always printed.
14051        assert_eq!(debug_t_pred0(false, 1, 4242, &[7, 8]), "7");
14052        assert_eq!(debug_t_pred0(false, 2, 4242, &[7, 8]), "8");
14053    }
14054}