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 memra_gguf::config::SwigluClamp;
17use std::sync::atomic::{AtomicU64, Ordering};
18
19/// Parse the documented `MEMRA_SPEC_REPLAY=1` rollback seam.
20///
21/// Keep this shared with serving admission so `=0` cannot select replay in one
22/// layer while another layer treats it as disabled.
23pub fn spec_replay_env_on(value: Option<&str>) -> bool {
24    value == Some("1")
25}
26
27pub fn spec_replay_env_enabled() -> bool {
28    let value = std::env::var("MEMRA_SPEC_REPLAY").ok();
29    spec_replay_env_on(value.as_deref())
30}
31
32/// step35 dcw draft-chain door (lane/step37-draft-graph-20260829). ON routes the step35 MTP
33/// block's draft attention through the WINDOWED device-counter family
34/// (`append_kv_quantized_dcw` + `fa_decode_dcw`, the step TP graph arc's kernels), which
35/// derives the SWA view entirely from device state (len_d, base_d, window): exactly the view
36/// offset the old capture refusal said `fa_decode_dc` could not express. BOTH draft modes
37/// switch together: eager and captured run the ONE launcher at the ONE bucket
38/// (min(cap, window)), so graph-vs-eager draft parity holds by construction (the
39/// `mtp_full_attn_dc` precedent).
40///
41/// DEFAULT ON since lane/step37-draft-graph-serving-20260830: the 20260829 lane shipped it
42/// OFF because it enabled nothing at the shipping head count (capture was structurally
43/// unreachable at heads=3); with the multi-head chain capture and the in-graph filtered
44/// sampler landed, this door is the kernel prerequisite for the captured chain on the
45/// QUALIFIED serving shape, and the exactness battery (greedy K=1..8 identity, per-K
46/// acceptance identity, seeded sampled twins) banks on the ON arm. Rollback seam:
47/// MEMRA_STEP35_DRAFT_DCW=0 restores the host-len eager arm (`mtp_step35_attn`) plus the
48/// named capture refusal, byte-for-byte the pre-lane serving; no state survives restart.
49fn step35_draft_dcw_on() -> bool {
50    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
51    *ON.get_or_init(|| std::env::var("MEMRA_STEP35_DRAFT_DCW").as_deref() != Ok("0"))
52}
53
54/// Multi-head MTP draft-chain capture door (lane/step37-draft-graph-serving-20260830,
55/// default ON — receipts in the lane RESULTS). ON lets the step-modulo prefix-replay chain
56/// (`mtp_extra` non-empty, the step37 3-head shipping shape) capture per-head single-row
57/// CUDA graphs and replay them in the exact eager launch order; the chain POLICY (head
58/// selection, prefix length, seed history) stays host-side, so graph-vs-eager drafts are
59/// bit-identical by construction. A failed capture degrades LOUDLY to the eager chain (the
60/// draft-graph WARN contract). OFF (=0) keeps the eager chain as the only multi-head path —
61/// the pre-lane serving byte-for-byte. Single-head capture is untouched by this door.
62fn mtp_chain_graph_on() -> bool {
63    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
64    *ON.get_or_init(|| std::env::var("MEMRA_MTP_CHAIN_GRAPH").as_deref() != Ok("0"))
65}
66
67/// In-graph FILTERED sampled draft door (lane/step37-draft-graph-serving-20260830, default
68/// ON — receipts in the lane RESULTS). ON widens the sampled draft-graph capture from the
69/// pure-temp regime to every truncation-filtered regime (top_k / top_p / min_p): the capture
70/// body runs `filter_stats` + `gumbel_perturb_filtered_ctr` IN-GRAPH, so the draft draws
71/// from the SAME filtered distribution the verify's accept test reconstructs (the
72/// graph-s-key exactness law, now satisfied inside the graph instead of by refusing it).
73/// Penalties stay eager either way (the history varies per round and cannot be baked).
74/// The pure-temp capture body is UNTOUCHED by this door (byte-identical to the pre-lane
75/// graph). OFF (=0) restores the pure-temp-only capture guard: filtered requests draft
76/// eager, byte-for-byte the pre-lane behavior.
77fn spec_graph_filtered_on() -> bool {
78    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
79    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_GRAPH_FILTERED").as_deref() != Ok("0"))
80}
81
82fn parse_prime_trows_width(value: Option<&str>) -> Result<usize, String> {
83    let Some(raw) = value else {
84        return Ok(8);
85    };
86    let width = raw
87        .parse::<usize>()
88        .map_err(|_| format!("MEMRA_PRIME_TROWS_T must be an integer in 2..=8, got {raw:?}"))?;
89    if !(2..=8).contains(&width) {
90        return Err(format!("MEMRA_PRIME_TROWS_T must be in 2..=8, got {width}"));
91    }
92    Ok(width)
93}
94
95#[cfg(test)]
96mod prime_trows_width_tests {
97    #[test]
98    fn width_defaults_to_eight_and_refuses_invalid_operator_values() {
99        assert_eq!(super::parse_prime_trows_width(None), Ok(8));
100        assert_eq!(super::parse_prime_trows_width(Some("2")), Ok(2));
101        assert_eq!(super::parse_prime_trows_width(Some("8")), Ok(8));
102        for invalid in ["", "1", "9", "32", "wide"] {
103            let err = super::parse_prime_trows_width(Some(invalid)).unwrap_err();
104            assert!(err.contains("MEMRA_PRIME_TROWS_T"), "{err}");
105            assert!(err.contains("2..=8"), "{err}");
106        }
107    }
108}
109
110/// One compact, anchor-bounded DSpark supervision record. `tokens[0]` is the anchor at p and
111/// `hidden` is its predecessor carrier h[p-1], matching the live NextN/DSpark pairing. Target
112/// rows p..p+gamma-1 score tokens p+1..p+gamma. They are the full-target softmax's top-k
113/// entries; `target_tail_probs[j]` is the probability mass outside those rows. All flattened
114/// target arrays are `[gamma, top_k]` in row-major order.
115pub struct DsparkAnchorRecord {
116    pub position: usize,
117    pub hidden: Vec<f32>,
118    pub tokens: Vec<u32>,
119    pub target_top_ids: Vec<u32>,
120    pub target_top_logits: Vec<f32>,
121    pub target_top_probs: Vec<f32>,
122    pub target_tail_probs: Vec<f32>,
123}
124
125#[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
126fn dspark_sparse_softmax_topk(
127    logits: &[f32],
128    top_k: usize,
129    temperature: f32,
130) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>, f32), Box<dyn std::error::Error>> {
131    if logits.is_empty() || top_k == 0 || top_k > logits.len() || temperature <= 0.0 {
132        return Err("invalid DSpark sparse-softmax shape or temperature".into());
133    }
134    if logits.iter().any(|value| !value.is_finite()) {
135        return Err("DSpark target logits contain a non-finite value".into());
136    }
137    let mut ranked: Vec<(u32, f32)> = logits
138        .iter()
139        .copied()
140        .enumerate()
141        .map(|(index, value)| (index as u32, value))
142        .collect();
143    let compare = |left: &(u32, f32), right: &(u32, f32)| {
144        right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
145    };
146    ranked.select_nth_unstable_by(top_k - 1, compare);
147    ranked[..top_k].sort_unstable_by(compare);
148
149    let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
150    let inv_temperature = 1.0f64 / temperature as f64;
151    let denominator: f64 = logits
152        .iter()
153        .map(|value| (((*value - max_logit) as f64) * inv_temperature).exp())
154        .sum();
155    let ids: Vec<u32> = ranked[..top_k].iter().map(|(index, _)| *index).collect();
156    let top_logits: Vec<f32> = ranked[..top_k].iter().map(|(_, value)| *value).collect();
157    let top_probs: Vec<f32> = top_logits
158        .iter()
159        .map(|value| ((((value - max_logit) as f64) * inv_temperature).exp() / denominator) as f32)
160        .collect();
161    let top_mass: f64 = top_probs.iter().map(|value| *value as f64).sum();
162    let tail = (1.0f64 - top_mass).clamp(0.0, 1.0) as f32;
163    Ok((ids, top_logits, top_probs, tail))
164}
165
166fn flatten_dspark_rows<T>(
167    rows: Vec<Option<Vec<T>>>,
168    position: usize,
169    label: &str,
170) -> Result<Vec<T>, Box<dyn std::error::Error>> {
171    let mut flattened = Vec::new();
172    for (slot, row) in rows.into_iter().enumerate() {
173        flattened.extend(
174            row.ok_or_else(|| format!("missing DSpark {label} at {position} slot {slot}"))?,
175        );
176    }
177    Ok(flattened)
178}
179
180/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
181/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
182/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
183/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
184/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
185/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
186/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
187/// `MEMRA_SPEC_HEAD_ROWS=1` — batch the verify tail's LM head over its t columns instead of running
188/// it at m=1 once per column. See the call site in `decode_step_t_core_stream` for why the batched
189/// form is the same per-row arithmetic (the bf16/q8 rows twins, not cuBLASLt) and what it costs
190/// today: the head is re-streamed t times per verify pass. Default off until the byte tape says so.
191pub(crate) fn head_rows_on() -> bool {
192    static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
193    crate::step37_door(&ENV, "MEMRA_SPEC_HEAD_ROWS")
194}
195
196/// The serving walk's own doors, tri-stated the same way (owner flip 2026-08-27): env forces,
197/// unset takes the step37 family default. Call sites are the t-row verify walk itself.
198pub(crate) fn spec_verify_eager_on() -> bool {
199    static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
200    crate::step37_door(&ENV, "MEMRA_SPEC_VERIFY_EAGER")
201}
202
203pub(crate) fn spec_verify_tcol_on() -> bool {
204    static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
205    crate::step37_door(&ENV, "MEMRA_SPEC_VERIFY_TCOL")
206}
207
208/// NOT family-armed (2026-08-27): the walk's prime leaves its sub-32 TAIL chunk out of the
209/// DISTRIBUTED kv, so the server refuses before decode with "cache lengths diverged
210/// local=N distributed=floor(N/32)*32" for every prompt whose token count is not a multiple of
211/// 32 — i.e. nearly all real traffic. Isolated on the server route: defaults ERR (local=445
212/// distributed=416), MEMRA_PRIME_TROWS=0 OK. It was default-OFF before the 2026-08-27 flip and
213/// goes back to opt-in until the tail append is fixed and gated ON THE SERVER ROUTE, not just
214/// run-gen (run-gen calls decode_step_t on the whole prompt and never exercises this path — the
215/// reason a run-gen-only receipt could not see it). The GEMM prime supersedes it on this route.
216pub(crate) fn prime_trows_on() -> bool {
217    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
218    *ON.get_or_init(|| std::env::var("MEMRA_PRIME_TROWS").as_deref() == Ok("1"))
219}
220
221pub(crate) fn tcol_ffn_on() -> bool {
222    static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
223    crate::step37_door(&ENV, "MEMRA_TCOL_FFN")
224}
225
226pub(crate) fn spec_hpost() -> bool {
227    static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
228    *H.get_or_init(|| {
229        std::env::var("MEMRA_SPEC_HPOST")
230            .map(|v| v != "0")
231            .unwrap_or(false)
232    })
233}
234
235/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
236/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
237/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
238/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
239/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
240/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
241/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
242/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
243/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
244pub(crate) fn spec_lean() -> bool {
245    static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
246    // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
247    // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
248    // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
249    *L.get_or_init(|| {
250        std::env::var("MEMRA_SPEC_LEAN")
251            .map(|v| v != "0")
252            .unwrap_or(true)
253    })
254}
255
256/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
257/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
258/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
259/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
260/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
261/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
262///     ring — the ring stores raw input columns); every arithmetic kernel is the same one the
263///     t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
264///     t-loop == chained T=1 steps);
265/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
266///     pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
267/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
268pub(crate) fn spec_m2() -> bool {
269    static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
270    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
271    // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
272    // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
273    // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
274    *M.get_or_init(|| {
275        std::env::var("MEMRA_SPEC_M2")
276            .map(|v| v != "0")
277            .unwrap_or(true)
278    })
279}
280pub(crate) fn spec_stream() -> bool {
281    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
282    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
283}
284pub(crate) fn spec_stream_m() -> usize {
285    static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
286    *M.get_or_init(|| {
287        std::env::var("MEMRA_SPEC_STREAM_M")
288            .ok()
289            .and_then(|v| v.parse().ok())
290            .unwrap_or(4)
291    })
292}
293pub(crate) fn spec_devacc() -> bool {
294    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
295    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
296}
297/// Engine-bundle slice 2 (DSF-ROUNDCOST-20260820 §1.1 host/device round trips + §2 rows 2-3),
298/// DEFAULT ON (`MEMRA_DSPARK_DEFER_READBACK=0` reverts): the dspark round's draft-chain DtoH
299/// is DEFERRED past verify dispatch and merged with the verify-argmax readback into ONE host
300/// sync (2 blocking DtoH/round -> 1). Verify embeds DEVICE tokens (`chain_d`) through the
301/// resident embed table — `embed_gather_u32_t`, bit-identical rows to the host gather by its
302/// own pinned contract. The host therefore dispatches snap + the whole verify while the DRAFT
303/// is still executing, instead of blocking ~1.7 ms on the chain and letting the device drain.
304/// Ladder arm only: the confidence policies size vt from a pre-verify head readback (their
305/// chain readback merges into that same sync instead). Exactness unchanged BY CONSTRUCTION —
306/// same tokens, same kernels, same order; E2E + accept-bank gates arbitrate.
307pub(crate) fn dspark_defer_readback_on() -> bool {
308    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
309    *ON.get_or_init(|| {
310        std::env::var("MEMRA_DSPARK_DEFER_READBACK")
311            .map(|v| v != "0")
312            .unwrap_or(true)
313    })
314}
315/// Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1, lane/dspark-engine-bundle-20260820),
316/// DEFAULT ON (`MEMRA_STATE_COPY_BATCH=0` reverts): batch the dspark round's GDN state
317/// snapshot and partial-accept restore into single `copy_batch_uniform_f32` launches
318/// instead of ~2 memcpy dispatches (+2 alloc_zeros on the snap side) per linear layer per
319/// round — measured 0.67 ms/round snap + 0.25 ms/round commit of pure dispatch on the q38
320/// route. Launch-structure only: bytes, buffers and stream order are unchanged, so
321/// acceptance and streams stay bit-identical (E2E-gated on the B1 packs).
322pub(crate) fn state_copy_batch_on() -> bool {
323    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
324    *ON.get_or_init(|| {
325        std::env::var("MEMRA_STATE_COPY_BATCH")
326            .map(|v| v != "0")
327            .unwrap_or(true)
328    })
329}
330/// Engine-bundle slice 3 + fa-execupdate slice 4c (DSF-ROUNDCOST-20260820 §5 rank 1),
331/// DEFAULT OFF — `MEMRA_DSPARK_VERIFY_GRAPH=1` opts in: per-(segment, vt) CUDA graphs
332/// for the LINEAR-layer runs, plus the full-verify single graph per (vt, rung) when a
333/// round's rows all ride one seqs rung — see [`DsparkVerifyGraphs`]. Requires the
334/// slice-2 deferred path (device tokens); the eager walk is the byte-identical fallback.
335///
336/// MEASURED disposition (box6 card0, agentic pack, 2026-08-20, both slices): exactness
337/// holds everywhere (ALL EXACT, accept lines byte-match the banks, ckpt-gate oracle
338/// green over the graph + slab-commit paths). Slice-3's AUTO_FREE launch-scan limiter
339/// (25.6 us x 16 launches ≈ 0.41 ms/round) is FIXED — the captured bodies' alloc nodes
340/// are balanced by in-graph frees (census 84/84 per segment, 1776/1776 full) so graphs
341/// instantiate USE_NODE_PRIORITY and the scan is gone. What remains at gate scale:
342/// segment graphs +0.1 tok/s over the batched-rows default (114.4 vs 114.3 x5
343/// interleaved — the linear launch overhead was only ~0.1 ms); the FULL-verify graph is
344/// NET NEGATIVE at gate scale (110.6 vs 114.2: ~14-21 (vt, rung) captures/process at
345/// 2 full-walk executions + ~2.9k-node instantiate each eat far more than the ~0.2-0.3
346/// ms/round of remaining launch overhead). The orchestration ceiling of §1.3 is spent —
347/// the fa/append recovery landed DEFAULT-ON as the batched rows arm
348/// (`dspark_fa_rows_on`), not as a graph. The serve-lifetime cell (DSF-ROUNDCOST §9,
349/// nj-ws-solo) measured the amortization: crossover K≈33 requests, steady −0.246
350/// ms/round, −1.25% session wall over 240 requests — and the graphs-serve lane wired
351/// the door into the session arm (`dspark_spec_session_burst`) as a model-owned
352/// capture pool shared across sessions. Stays opt-in pending the owner's default-ON
353/// ratification on the serve-surface battery.
354pub(crate) fn dspark_verify_graph_on() -> bool {
355    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
356    *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() == Ok("1"))
357}
358/// MTP-ROUTE verify graphs, DEFAULT ON for the GDN+MoE family since 2026-08-23
359/// (`MEMRA_SPEC_VERIFY_GRAPH=0` is the kill switch, `=1` opts other families in).
360///
361/// The slice-4c capture already lived inside `qwen35_verify_tparallel` and said so in its own
362/// comment — "stream rides the qwen35moe burst, graphs ride the dspark route" — with no caller
363/// on this route. The MTP spec round is that caller.
364///
365/// WHY it is worth a default (receipts: `research/orndecode-20260822/VGRAPH.md`). With
366/// `MEMRA_SPEC_PHASE=1` this route's round reads verify-ISSUE 44-58% and verify-WAIT **0.0%**:
367/// the host is never waiting for the device, it is spending its own time launching the trunk.
368/// Replay collapses that into one graph launch and the phase all but disappears (55-62 ms ->
369/// 8-10 ms per burst).
370///
371/// MEASURED, two host generations, forced ON/OFF, balanced 4+4 boots in both orders:
372///   * current-generation host (9950X, the serving class): OFF 266.0-266.5, ON 318.8-319.5
373///     tok/s — **+19.7%**, no overlap, sub-1% spread per arm; per-round 6.9 -> 5.7 ms.
374///   * Zen 3 host: +3-9% (that rig's own clock drift is wider than the effect, so the ratio
375///     comes from per-round phase totals, which are internal to each boot).
376///     The ON arm lands at ~320 tok/s on BOTH hosts while OFF tracks host speed — the arm moves
377///     the round off the host and onto the device, which is the whole point.
378///
379/// EXACTNESS is structural (same kernels, same order) and gated anyway: a fixed-seed SAMPLED
380/// completion hashes identically ON vs OFF **and across both hosts** (`08941d5bb9762b21`),
381/// greedy seed-pinned likewise, `run-spec` K=1..8 PASS on both arms with identical acceptance
382/// at every K, kernel-check ALL GREEN.
383///
384/// SCOPE, deliberately narrow: default ON only where it was measured — the GatedDeltaNet +
385/// MoE family (`vgraph_family_default`). Qwen3.8-27B is GDN + DENSE mlp and would otherwise
386/// inherit this default unmeasured, which is the family-by-family law this repo keeps; it can
387/// opt in with `=1` once it has its own interleave. Also never armed together with
388/// ROUND-STREAM, and a round wider than the pool declines it for the eager walk.
389pub(crate) fn spec_verify_graph_env() -> Option<bool> {
390    static ON: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
391    *ON.get_or_init(
392        || match std::env::var("MEMRA_SPEC_VERIFY_GRAPH").as_deref() {
393            Ok("1") => Some(true),
394            Ok("0") => Some(false),
395            _ => None,
396        },
397    )
398}
399/// SERVE-ROUTE twin of [`dspark_verify_graph_on`], DEFAULT ON — owner-ratified
400/// 2026-08-22 on the §10 serve-lifetime battery (DSF-ROUNDCOST-20260820 §10.3:
401/// crossover K=36–43, steady −0.357 ms/round, session wall −1.55..−1.65%, byte-exact
402/// 240/240 ×3 pairs, pool bounded at 8,852 MiB under `MEMRA_DSPARK_VG_MAX`). The env
403/// stays as the kill-switch: `MEMRA_DSPARK_VERIFY_GRAPH=0` restores the eager walk
404/// (byte-identical body); `MEMRA_DSPARK_VG_MAX=0` is the finer freeze valve. The BIN
405/// arm keeps its own opt-in default (`dspark_verify_graph_on`): at gate scale the
406/// capture toll is never repaid (§8 measured disposition — 14–21 captures over a
407/// 256-token run vs the serve session's thousands of rounds), and the two
408/// instruments must keep their own measured dispositions rather than share one flag.
409pub(crate) fn dspark_verify_graph_serve_on() -> bool {
410    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
411    *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() != Ok("0"))
412}
413/// Capture-count ceiling for the dspark verify-graph pool (graphs-serve lane) — the
414/// pool's memory policy STATED instead of silently unbounded. The keyspace is
415/// intrinsically finite — segment keys (run_start, vt) ≤ 16 runs x 7 windows, full
416/// keys (vt, rung, hi) ≤ 7 windows x the split-rung ladder (8 rungs at 32k ctx), ~168
417/// on the q38 export — so the default (256) never engages there; the knob is the
418/// safety valve for a future export with a wider ladder. At the ceiling the pool
419/// FREEZES: existing keys keep replaying, rounds needing a new capture run the eager
420/// walk byte-identically (round-atomic — a partial refusal would mix slab- and
421/// cols-stashed layers inside one commit). No eviction by design: destroying a live
422/// exec graph re-opens the stale-address class the indirect tables exist to close,
423/// and the bounded keyspace makes reclaim worthless.
424pub(crate) fn dspark_vg_cap() -> usize {
425    static CAP: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
426    *CAP.get_or_init(|| {
427        std::env::var("MEMRA_DSPARK_VG_MAX")
428            .ok()
429            .and_then(|v| v.parse().ok())
430            .unwrap_or(256)
431    })
432}
433
434/// PROJECTED REMAINING GROWTH of the verify-graph pool, in bytes (lane/hermes-perf-fixes,
435/// 2026-08-23 — the admission accounting the "pool dwarfs spec admission reserve" finding
436/// asks for). The pool was measured at 8,852 MiB at storm-complete on the q38 export while
437/// admission's transient floor (`SPEC_SHRINK_RESERVE`) is 1.5 GiB and never charged for it:
438/// sessions admitted while the pool is cold overcommit VRAM the pool WILL hold, because the
439/// pool grows monotonically (no eviction by design) and is model-owned across sessions.
440///
441/// SELF-MEASURING, no per-model constant (generic-model law — the 8,852 MiB is a q38 number
442/// and proves nothing about another export): the debt is remaining capture slots x the
443/// MARGINAL bytes a capture adds to this device's graph mem pool.
444///
445/// MARGINAL, NOT MEAN — measured correction (box9 on-box receipt, 2026-08-23). The first
446/// version of this used the mean (`reserved / captures`) and the live serve log showed why
447/// that is wrong: with the pool's reservation flat at ~33.6 MiB across captures 1..3, the
448/// mean-based debt printed **8,556 MB, then 4,261, then 2,830** — it extrapolated capture
449/// #1's ONE-TIME shared allocation (staging buffers, stash slabs, pointer tables: sized
450/// once per pool, shared by every key) across all 256 slots. An 8.5 GB phantom reserve at
451/// boot can refuse admissions that would have fit, which is a worse defect than the
452/// under-charge this accounting exists to remove. The marginal reading prices what an
453/// ADDITIONAL key actually costs: two observations `(captures, reserved)` give
454/// `(r1 - r0) / (c1 - c0)`, which is ~0 on an export whose pool does not grow per key and
455/// tracks real growth on one that does.
456///
457/// BOOTSTRAP (only one observation so far, so growth is unmeasurable): reserve one more
458/// pool's worth — `min(remaining x mean, reserved)`. "We have measured `reserved` bytes for
459/// `captures` keys; until growth is measurable, assume at most a doubling" is fail-safe in
460/// the same direction as the old rule without the 255x extrapolation.
461///
462/// Before the FIRST capture the debt is 0 (a single capture lands well inside the existing
463/// 1.5 GiB floor). `cap` is the intrinsic freeze ceiling (`MEMRA_DSPARK_VG_MAX`; =0 freeze
464/// valve => the pool cannot grow => debt 0); at or past the cap the pool FREEZES, so the
465/// debt is 0 there too.
466pub fn dspark_vg_debt_projection(
467    captures: usize,
468    cap: usize,
469    reserved_bytes: usize,
470    prev: Option<(usize, usize)>,
471) -> usize {
472    if captures == 0 || cap == 0 {
473        return 0;
474    }
475    let remaining = cap.saturating_sub(captures);
476    if remaining == 0 {
477        return 0;
478    }
479    match prev {
480        // marginal growth between two observations of the same pool
481        Some((c0, r0)) if captures > c0 => {
482            let marginal = reserved_bytes.saturating_sub(r0) / (captures - c0);
483            remaining.saturating_mul(marginal)
484        }
485        // bootstrap: at most one more pool's worth
486        _ => remaining
487            .saturating_mul(reserved_bytes / captures)
488            .min(reserved_bytes),
489    }
490}
491/// PRE-CAPTURE VRAM RESERVE CHECK door (lane/step37-vram-admission-20260830), DEFAULT ON.
492/// A draft-graph capture attempt on a tight card used to be try-and-fail: the 2 warmup
493/// forwards + instantiate grew the pool to the edge BEFORE the OOM surfaced, and the
494/// "eager fallback" then ran on a card the failed attempt had just exhausted (the owner's
495/// single-session second-prompt OOM: capture WARN followed by 28 step-OOM engine errors,
496/// device at 5 MiB free). With the gate ON, a capture is attempted only when the device's
497/// effective free (driver free + async-pool cached) covers the capture's expected appetite
498/// PLUS a post-capture safety floor — otherwise the session falls back to eager EARLY,
499/// with headroom intact, through the same LOUD once-per-flip WARN. `=0` restores
500/// try-and-fail (diagnostics door; the trim-on-OOM recovery below stays active either way).
501pub fn spec_capture_gate_on() -> bool {
502    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
503    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_CAPTURE_GATE").as_deref() != Ok("0"))
504}
505
506/// Post-capture safety floor the reserve check keeps free ON TOP of the capture's own
507/// appetite: the same measured constant class as the admission transient floor
508/// (capture arenas + verify activations — the admit-oom control fit). A capture that
509/// would leave less than this behind is not worth its eager-coverage risk.
510pub(crate) const CAPTURE_HEADROOM_FLOOR: usize = 1536 << 20;
511
512/// Pure verdict half of the pre-capture reserve check (unit-testable): given the device's
513/// driver-free and pool-cached bytes and the capture's expected `need`, returns
514/// `Some((required, effective))` when the capture must be REFUSED, `None` when it fits.
515pub(crate) fn capture_headroom_verdict(
516    driver_free: usize,
517    pool_cached: usize,
518    need: usize,
519    floor: usize,
520) -> Option<(usize, usize)> {
521    let effective = driver_free.saturating_add(pool_cached);
522    let required = need.saturating_add(floor);
523    (effective < required).then_some((required, effective))
524}
525
526/// Expected device appetite of a draft-graph capture attempt when no measurement exists
527/// yet (bootstrap only — the model-owned high-water gauge takes over after the first
528/// observed capture). Deliberately conservative and shape-derived, never a per-family
529/// constant: per (head, mode) capture the two warmups + capture each walk one head
530/// forward whose dominant transients are a handful of `n_embd` rows and one `d_vocab`
531/// logits row, retained by the keeper; the sampled tail additionally parks
532/// `k` q-slots + perturb/q buffers of `d_vocab` each.
533pub(crate) fn draft_capture_bootstrap_estimate(
534    heads: usize,
535    k: usize,
536    d_vocab: usize,
537    n_embd: usize,
538) -> usize {
539    let per_capture = 3usize // 2 warmups + capture body, each retaining its transients
540        .saturating_mul(d_vocab.saturating_add(8 * n_embd))
541        .saturating_mul(4)
542        .max(32 << 20); // instantiate + driver-side graph backing per capture, floor
543    let captures = heads.max(1).saturating_mul(2); // interior + last per head
544    let sampled_slots = (k.saturating_add(2))
545        .saturating_mul(d_vocab)
546        .saturating_mul(4);
547    captures
548        .saturating_mul(per_capture)
549        .saturating_add(sampled_slots)
550        .max(64 << 20)
551}
552
553/// OOM predicate for capture-failure recovery (engine-side twin of the worker's
554/// `is_cuda_oom` — the same quoted-text contract).
555pub(crate) fn capture_err_is_oom(reason: &str) -> bool {
556    reason.contains("CUDA_ERROR_OUT_OF_MEMORY") || reason.contains("out of memory")
557}
558
559/// Impure half of the pre-capture reserve check: reads the device, trims the async pool
560/// when the driver alone is short but cached blocks would cover it (graph instantiate and
561/// cuBLAS workspaces allocate from the DRIVER, not from our pool — a pool sitting on freed
562/// blocks starves them), and returns the refusal reason line when the capture must not be
563/// attempted. `None` = go ahead.
564pub(crate) fn capture_headroom_refusal(e: &Engine, need: usize) -> Option<String> {
565    let Ok((driver_free, _total)) = e.ctx().mem_get_info() else {
566        return None; // unreadable device: keep the historical try-and-fail behavior
567    };
568    let pool_cached = e.pool_cached_bytes();
569    // A capture may take AT MOST HALF the discretionary headroom: required =
570    // 2x appetite + two floors (owner's contract: "fall back to eager EARLY with headroom
571    // intact"). Measured escalation on the owner-shape cells: one floor of slack let the
572    // capture walk the card to the edge and the burst step-OOM'd immediately; two floors
573    // still allowed a capture whose session then OOM'd on its own admission-charged work,
574    // because the capture had consumed the memory the charge was counting on. Requiring
575    // the appetite TWICE means the card retains a whole capture's worth of room after the
576    // capture lands - enough for the session's charged classes and its peers' bursts. The
577    // capture is an optimization worth ~2-3 ms of TTFT (draft-graph lane receipts); at the
578    // margin it is never worth an OOM incident.
579    let floor = CAPTURE_HEADROOM_FLOOR.saturating_mul(2);
580    let required_need = need.saturating_mul(2);
581    let required = required_need.saturating_add(floor);
582    match capture_headroom_verdict(driver_free, pool_cached, required_need, floor) {
583        Some((required, effective)) => Some(format!(
584            "insufficient VRAM headroom for capture: effective free {}MB (driver {}MB + pool-cached \
585             {}MB) < required {}MB (2x appetite {}MB + floor {}MB); capture skipped pre-attempt",
586            effective / (1 << 20),
587            driver_free / (1 << 20),
588            pool_cached / (1 << 20),
589            required / (1 << 20),
590            need / (1 << 20),
591            floor / (1 << 20),
592        )),
593        None => {
594            if driver_free < required && pool_cached > 0 {
595                let trimmed = e.pool_trim_to_zero();
596                if trimmed > 0 {
597                    eprintln!(
598                        "[spec] pre-capture pool trim: released {}MB cached back to the driver \
599                         (driver free {}MB < required {}MB; instantiate allocates from the driver)",
600                        trimmed / (1 << 20),
601                        driver_free / (1 << 20),
602                        required / (1 << 20),
603                    );
604                }
605            }
606            None
607        }
608    }
609}
610
611/// GRAPH-LAUNCH HEADROOM FLOOR (lane/step37-vram-admission-20260830, defect 3 root
612/// cause): `cuGraphLaunch` SEGFAULTS inside libcuda (offset +0x27c87f, a null internal
613/// dereference at address 0x60) when a captured graph is dispatched into a
614/// driver-exhausted card — reproduced on this lane's box with core dumps on BOTH the
615/// pre-lane and lane binaries (multi-active step-OOM squeeze; the crashing thread sits in
616/// `CudaGraph::launch` inside `generate_spec_inner2`). The eager arms fail RECOVERABLY on
617/// the same card (a quoted CUDA OOM the park path handles), so below this driver-free
618/// floor every graph arm yields to eager for the round. A named constant, not a knob: the
619/// winning value is the default and the guard exists to make a driver segfault
620/// unreachable, not to tune anything.
621pub(crate) const GRAPH_LAUNCH_MIN_FREE: usize = 256 << 20;
622
623/// Per-round guard for the floor above. Read failure keeps serving (never a false
624/// refusal from an unreadable device); one `mem_get_info` (~microseconds) per ~25ms round.
625pub(crate) fn graph_launch_headroom_ok(e: &Engine) -> bool {
626    match e.ctx().mem_get_info() {
627        Ok((free, _total)) => free >= GRAPH_LAUNCH_MIN_FREE,
628        Err(_) => true,
629    }
630}
631
632/// One grep-stable suspension line per ROUTE (each call site holds its own
633/// process-lifetime `Once`): every captured-graph launch route below the floor names
634/// itself in the tag while keeping the same `graph replay suspended:` key the step37
635/// admission lane's squeeze cell greps for. The spec-round guard keeps its original
636/// per-generation `[spec]` line; the sweep routes (graph-launch-guard-sweep lane,
637/// 2026-08-31) note once per process — presence is what the gates assert, and a
638/// suspended round is otherwise byte-identical to its eager twin.
639pub(crate) fn graph_replay_suspended_note(route: &str) {
640    eprintln!(
641        "[{route}] graph replay suspended: driver free below the {}MB launch floor \
642         (eager arms serve; cuGraphLaunch segfaults into an exhausted card)",
643        GRAPH_LAUNCH_MIN_FREE / (1 << 20)
644    );
645}
646
647/// Engine-bundle slice 4 (fa-execupdate lane, DSF-ROUNDCOST-20260820 §6 close: "the
648/// residual gap lives in the FULL-ATTENTION per-row section"), DEFAULT ON —
649/// `MEMRA_DSPARK_FA_ROWS=0` reverts to the per-row loop: when every row of a verify
650/// round takes the v4-seqs arm on ONE `fa_split_keys` rung (the straddle law, evaluated
651/// at the round's first and last t_kv — both eligibility gates are intervals in t_kv),
652/// the qwen35 t-parallel verify's per-row KV-append + fa-decode loop collapses into the
653/// z-batched serving twins: ONE `append_quantize_kv_q8_0_q5_1_seqs` + ONE
654/// `fa_decode_vec_q_seqs_v4` + ONE combine per full-attention layer, replacing
655/// T x (4 dtod row copies + append + 3 memsets + main + combine) launches. Bytes are
656/// pinned by the batched-tick increment-2 kernel-check (seqs-vs-per-seq-loop bit
657/// identity: per-row T_kv derives in-kernel from pos_seq[z]; splits >= ns_eff write the
658/// empty partial the combine never reads, so the shared n_splits_max stride changes no
659/// bytes) and re-gated e2e by this lane's battery.
660pub(crate) fn dspark_fa_rows_on() -> bool {
661    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
662    *ON.get_or_init(|| {
663        std::env::var("MEMRA_DSPARK_FA_ROWS")
664            .map(|v| v != "0")
665            .unwrap_or(true)
666    })
667}
668
669/// `t_pred0` for the `MEMRA_DEBUG_SPEC` per-round print, sampled-safe.
670///
671/// `generate_spec_inner2` fills its `preds` vector ONLY on the greedy path (`if !sampled`), and
672/// the per-round debug print was the sole consumer in the sampled arm: `t_pred(0)` survives round
673/// 0 (`base == 0` returns `last_pred`) and from round 1 (`base == 1`, a pending bonus) indexes an
674/// EMPTY vector — `index out of bounds: the len is 0 but the index is 0`, in the GPU worker
675/// thread, which then respawns and reloads weights while the request dies. So any sampled spec
676/// request longer than one round used to kill the worker whenever `MEMRA_DEBUG_SPEC` was set:
677/// the flag crashed precisely the regime it exists to investigate.
678///
679/// Fixed at the print site, not inside the closure, so the greedy accept walk keeps its strict
680/// indexing (an out-of-range pred there is a real bug and must still be loud).
681fn debug_t_pred0(sampled: bool, base: usize, last_pred: u32, preds: &[u32]) -> String {
682    if base == 0 {
683        return last_pred.to_string();
684    }
685    match preds.get(base - 1) {
686        Some(p) => p.to_string(),
687        // sampled: the greedy per-column argmax was never run for this round.
688        None => {
689            debug_assert!(
690                sampled,
691                "greedy spec: preds[{}] missing at base {base}",
692                base - 1
693            );
694            "n/a".to_string()
695        }
696    }
697}
698
699/// `MEMRA_SKEY_PROBE=1` — sampled-draft-graph key probe (lane/graph-s-key-exactness-20260819).
700///
701/// Reports, per burst and per round, which draft chain the sampled arm chose and under which
702/// filter regime, plus the ONE observable that separates a legal filtered draft from a stale
703/// pure-temp graph replayed under filters: an accept test whose gathered `q` is exactly 0.
704/// A draft token sampled from the FILTERED softmax can never gather q=0 (it was drawn from the
705/// kept set), so `q=0` in the verify means the draft came from a distribution the verify does
706/// not believe in — and `u * 0 < p` then accepts it unconditionally.
707///
708/// Its own env var, deliberately NOT `MEMRA_DEBUG_SPEC`: that flag panicked the GPU worker on
709/// any sampled spec request past round 0 until this lane fixed it (§2 of the bank note).
710pub(crate) fn skey_probe() -> bool {
711    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
712    *ON.get_or_init(|| std::env::var("MEMRA_SKEY_PROBE").as_deref() == Ok("1"))
713}
714
715/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
716/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
717/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
718/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
719/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
720/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
721/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
722/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
723/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
724pub trait SpecConstraint {
725    /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
726    /// masked argmax).
727    fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
728    /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
729    fn mask_words(&mut self) -> Result<Vec<u32>, String>;
730    /// Is `tok` consumable in the CURRENT state?
731    fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
732    /// Advance the state with an emitted token.
733    fn consume(&mut self, tok: u32) -> Result<(), String>;
734
735    // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
736    // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
737    // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
738    // loose, research/constrained-full-20260803). These three methods let the engine mask the
739    // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
740    // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
741    // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
742    // stays the correctness backstop and the emitted stream is unchanged by construction
743    // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
744    // argmax; a cut slot is recomputed as the masked argmax either way).
745    // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
746
747    /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
748    /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
749    fn draft_mask_enabled(&self) -> bool {
750        false
751    }
752    /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
753    /// slot. Called once per spec round, before the first draft position.
754    fn draft_begin(&mut self) -> Result<(), String> {
755        Ok(())
756    }
757    /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
758    /// for the draft position about to be sampled. `None` = draft masking off (no-op).
759    fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
760        Ok(None)
761    }
762    /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
763    /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
764    /// engine stops drafting; the token already pushed still goes through verify.
765    fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
766        Ok(false)
767    }
768}
769
770/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
771/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
772/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
773/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
774/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
775/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
776/// verify emits the masked argmax as usual).
777fn upload_draft_mask(
778    e: &Engine,
779    c: &mut dyn SpecConstraint,
780    dst: &mut CudaSlice<u32>,
781    d2t: Option<&Vec<u32>>,
782    d_vocab: usize,
783    words: usize,
784) -> Result<bool, Box<dyn std::error::Error>> {
785    let Some(tw) = c
786        .draft_mask_words()
787        .map_err(|e2| format!("constraint: {e2}"))?
788    else {
789        return Ok(false);
790    };
791    let bit = |t: usize| -> bool {
792        let w = t >> 5;
793        w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
794    };
795    let mut buf = vec![0u32; words];
796    match d2t {
797        // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
798        Some(map) => {
799            for (i, &t) in map.iter().enumerate().take(d_vocab) {
800                if bit(t as usize) {
801                    buf[i >> 5] |= 1u32 << (i & 31);
802                }
803            }
804        }
805        // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
806        // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
807        None => {
808            let n = tw.len().min(words);
809            buf[..n].copy_from_slice(&tw[..n]);
810        }
811    }
812    if buf.iter().all(|w| *w == 0) {
813        return Ok(false);
814    }
815    e.htod_u32_into(dst, &buf)?;
816    Ok(true)
817}
818
819/// Keep the full token-embedding table in host memory and upload only the rows needed by each
820/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
821/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
822/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
823pub(crate) fn spec_host_embd() -> bool {
824    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
825    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
826}
827
828/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
829/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
830/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
831/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
832/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
833/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
834/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
835/// run-spec K=1..8 + acceptance identity arbitrate e2e).
836pub(crate) fn spec_fused_t() -> bool {
837    static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
838    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
839    // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
840    // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
841    *F.get_or_init(|| {
842        std::env::var("MEMRA_SPEC_FUSED_T")
843            .map(|v| v != "0")
844            .unwrap_or(true)
845    })
846}
847
848/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
849/// Only call this on such buffers — the lean contract is "identical bytes by construction".
850/// TOKEN-ID GUARD for every id that reaches an embed gather (#87 family).
851///
852/// A device argmax seeds its running index with 0x7FFFFFFF and replaces it only through
853/// comparisons, all of which are FALSE against NaN. An all-NaN logits row therefore returns
854/// the sentinel, and the next thing done with a token id is `embed_row(id)` — table +
855/// ~4.6 TB, never mapped, an MMU fault that kills the CUDA context for the whole process
856/// (research/pp2spec-crash-20260807). The draft chain and the GREEDY verify walk already
857/// trap this; the SAMPLED verify bonus, the boundary sampler and the replay arm's last_pred
858/// did not, which is why the recoverable fault on the greedy instrument is a TERMINAL one on
859/// the vendor-default sampled shape we actually serve.
860pub(crate) fn guard_vocab_token(
861    tok: u32,
862    n_vocab: usize,
863    what: &str,
864) -> Result<u32, Box<dyn std::error::Error>> {
865    if (tok as usize) >= n_vocab {
866        return Err(format!(
867            "{what}: token id 0x{tok:08x} >= n_vocab {n_vocab} — an all-NaN logits row left \
868             the device argmax's init sentinel in place; refusing to dereference the embed \
869             row (#87 trap)"
870        )
871        .into());
872    }
873    Ok(tok)
874}
875
876/// SPEC NaN-ORIGIN SCAN (`MEMRA_SPEC_NAN_SCAN=1`, DEFAULT OFF, diagnostic only).
877///
878/// The `#87` trap reports an all-NaN VERIFY logits column, which says the poison reached the
879/// head but not where it entered. With the scan armed the verify walk syncs and reads back
880/// every layer's output, so the FIRST layer whose residual carries a NaN names itself with the
881/// round's row and position. Off by default and never on a serving path: it costs one host
882/// sync + one `t*n_embd` D2H per layer, and the syncs change scheduling (so a run that stops
883/// reproducing under the scan is itself a datum, not an all-clear).
884///
885/// Rollback seam: unset `MEMRA_SPEC_NAN_SCAN` (or set it to 0). Every call site is behind
886/// `spec_nan_scan()`, so the default path keeps the exact launch sequence it had.
887pub(crate) fn spec_nan_scan() -> bool {
888    spec_nan_scan_level() > 0
889}
890
891/// `MEMRA_SPEC_NAN_SCAN` as a LEVEL, not a boolean. `1` scans each layer's residual, which
892/// names the layer. `2` also scans INSIDE the t-column layer body — the per-column attention
893/// output, the deferred-column o-proj/fa2 join, the post-attention norm and the routed-MoE
894/// output — because "layer 20 poisons row 0" does not say whether the attention or the routed
895/// MoE produced it, and those are different bugs with different fixes.
896pub(crate) fn spec_nan_scan_level() -> u8 {
897    static LVL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
898    *LVL.get_or_init(|| match std::env::var("MEMRA_SPEC_NAN_SCAN").as_deref() {
899        Ok("1") => 1,
900        Ok("2") => 2,
901        _ => 0,
902    })
903}
904
905/// Read back `[rows, cols]` and fail with the first NaN's coordinates. `what` names the
906/// producer (layer index, walk arm) so the error line is the localization.
907/// VERIFY-ARM RECEIPT (rides `MEMRA_SPEC_NAN_SCAN>=1`, bounded to 200 lines).
908///
909/// Names, per trunk layer, WHICH attention arm the t-column walk actually took. This exists
910/// because the level-1 residual scan below sat only on the non-fused tail: the fused
911/// rope+append+fa arm ends in `continue`, so every layer that fused was NEVER SCANNED and
912/// silently read as "clean". A poisoned residual therefore first reported at the next
913/// non-fused layer, which is how "layer 20 creates the poison" could be true of the scan and
914/// false of the engine. Also carries the row-table lookup counter, so "the fused path never
915/// ran" is distinguishable from "it ran and was innocent".
916/// KV-PLANE SCAN (`MEMRA_KV_PLANE_SCAN=1`, DEFAULT OFF, diagnostic only).
917///
918/// Reads back the STAGED rows of a layer's distributed K/V planes and reports the first row
919/// whose quantization scale is not finite. No kernel required: q8_0 blocks are
920/// `[half d][32 x i8]` and q5_1 blocks carry `half d` then `half m`, so the fp16 scale at the
921/// head of each block is host-checkable straight out of the byte plane.
922///
923/// It exists because the level-2 bad-row bitmap says EVERY verify row is non-finite at a
924/// global-attention layer's join, and row r attends a strict superset of row r-1's keys: that
925/// implicates the shared KV history those rows walk, not per-column staging. "The attention
926/// output is NaN" and "the KV history it attends is already NaN" are different bugs with
927/// different owners, and nothing measured so far separates them. A first-corrupt-row index
928/// also dates the corruption against the prime/decode boundary.
929///
930/// Bounded hard: only layers whose geometry has NO window (the global planes), only the first
931/// `MEMRA_KV_PLANE_SCAN_ROUNDS` verify rounds of a process (default 2), and it copies only
932/// `[0, staged_len)`, which is ~1.6 MB at the 1480-token repro rather than the 262144-row
933/// provision. It still syncs per layer, so it is never a serving or a measured-perf arm.
934pub(crate) fn kv_plane_scan_on() -> bool {
935    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
936    *ON.get_or_init(|| std::env::var("MEMRA_KV_PLANE_SCAN").as_deref() == Ok("1"))
937}
938
939fn kv_plane_scan_rounds() -> usize {
940    static R: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
941    *R.get_or_init(|| {
942        std::env::var("MEMRA_KV_PLANE_SCAN_ROUNDS")
943            .ok()
944            .and_then(|v| v.parse().ok())
945            .unwrap_or(2)
946    })
947}
948
949/// First non-finite fp16 block scale in `bytes`, as (block index, raw u16), scanning one
950/// scale every `stride` bytes. Returns None when every block scale is finite.
951fn first_bad_scale(bytes: &[u8], stride: usize) -> Option<(usize, u16)> {
952    if stride == 0 {
953        return None;
954    }
955    for (i, blk) in bytes.chunks_exact(stride).enumerate() {
956        let raw = u16::from_le_bytes([blk[0], blk[1]]);
957        if half_is_non_finite(raw) {
958            return Some((i, raw));
959        }
960    }
961    None
962}
963
964/// IEEE binary16: exponent all ones is Inf or NaN, whatever the mantissa says.
965fn half_is_non_finite(raw: u16) -> bool {
966    (raw & 0x7C00) == 0x7C00
967}
968
969/// Scan one layer's staged K/V planes for a non-finite quantization scale. Returns the
970/// receipt line, or None when the layer is out of scope or every scale is finite.
971pub(crate) fn scan_kv_plane(
972    e: &crate::Engine,
973    distributed: &memra_kv::ResidentTpKvCache,
974    il: usize,
975    pos0: usize,
976) -> Result<(), Box<dyn std::error::Error>> {
977    // One "round" is one pos0, not one layer: the walk visits 45 layers per verify. The
978    // default of 2 rounds is for a fault that shows up immediately; the step37 repro does not
979    // fire until rep 3 or later, i.e. round ~60 of the process, so that arm MUST raise
980    // MEMRA_KV_PLANE_SCAN_ROUNDS or it will scan only the two rounds that were never going to
981    // be poisoned and report a clean history it never looked at.
982    static ROUNDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
983    static LAST_POS: std::sync::atomic::AtomicUsize =
984        std::sync::atomic::AtomicUsize::new(usize::MAX);
985    if LAST_POS.swap(pos0, std::sync::atomic::Ordering::Relaxed) != pos0 {
986        ROUNDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
987    }
988    if ROUNDS.load(std::sync::atomic::Ordering::Relaxed) > kv_plane_scan_rounds() {
989        return Ok(());
990    }
991    let staged = distributed.staged_len();
992    if staged == 0 {
993        return Ok(());
994    }
995    // ENGAGEMENT RECEIPT. This scan prints only on corruption, so `kvbad=0` in a cell would
996    // read the same whether the history was clean or the scan never ran once. Bounded so a
997    // 45-layer walk cannot flood the log.
998    static SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
999    let seen = SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1000    let (ktb, vtb) = (distributed.k_tok_bytes(), distributed.v_tok_bytes());
1001    if seen < 4 {
1002        eprintln!(
1003            "[kv-plane] engaged #{seen} layer {il} pos0={pos0} staged={staged} \
1004             ktok={ktb} vtok={vtb} (scan armed; a corrupt plane prints its own line)"
1005        );
1006    }
1007    for rank in 0..distributed.ranks().len() {
1008        let Some(rc) = distributed.rank(rank) else {
1009            continue;
1010        };
1011        // q8_0 K blocks are [half d][32 x i8] = 34B; q5_1 V blocks lead with half d then half m.
1012        let kbytes = e.dtoh_u8_view(&rc.k().slice(0..staged * ktb))?;
1013        let vbytes = e.dtoh_u8_view(&rc.v().slice(0..staged * vtb))?;
1014        let kbad = first_bad_scale(&kbytes, 34);
1015        let vbad = first_bad_scale(&vbytes, 24);
1016        if kbad.is_some() || vbad.is_some() {
1017            let row = |b: Option<(usize, u16)>, tok: usize| {
1018                b.map(|(i, raw)| format!("blk {i} (row {}) raw={raw:#06x}", i * 34 / tok.max(1)))
1019                    .unwrap_or_else(|| "clean".into())
1020            };
1021            eprintln!(
1022                "[kv-plane] layer {il} rank {rank} pos0={pos0} staged={staged}                  K={} V={} - the attended KV history is ALREADY non-finite, so a non-finite                  attention output here is a symptom and not the origin",
1023                row(kbad, ktb),
1024                row(vbad, vtb)
1025            );
1026            return Ok(());
1027        }
1028    }
1029    Ok(())
1030}
1031
1032pub(crate) fn verify_arm_receipt(
1033    arm: &str,
1034    il: usize,
1035    pos0: usize,
1036    t: usize,
1037    staged: Option<usize>,
1038) {
1039    static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1040    if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 200 {
1041        return;
1042    }
1043    eprintln!(
1044        "[verify-arm] layer {il} arm={arm} pos0={pos0} t={t} staged_len={} rows_tab_lookups={}",
1045        staged.map(|v| v as i64).unwrap_or(-1),
1046        crate::tp::ROWS_TAB_ENGAGED.load(std::sync::atomic::Ordering::Relaxed)
1047    );
1048}
1049
1050pub(crate) fn nan_scan_rows(
1051    e: &Engine,
1052    buf: &CudaSlice<f32>,
1053    rows: usize,
1054    cols: usize,
1055    what: &str,
1056) -> Result<(), Box<dyn std::error::Error>> {
1057    // The readback is also the ATTRIBUTION point for an asynchronous fault: a
1058    // CUDA_ERROR_ILLEGAL_ADDRESS raised by any launch since the previous scan surfaces on this
1059    // sync, and the bare DriverError names nothing. Wrapping it with `what` turns "the process
1060    // died somewhere" into "it died at or before this layer, on this row, at this position".
1061    let host = e.dtoh(buf).map_err(|err| -> Box<dyn std::error::Error> {
1062        format!(
1063            "spec nan-scan: sync at {what} FAILED: {err} — the fault is at or before \
1064                     this point in the walk"
1065        )
1066        .into()
1067    })?;
1068    if host.len() < rows * cols {
1069        return Err(format!(
1070            "nan-scan {what}: buffer holds {} < {rows}x{cols}",
1071            host.len()
1072        )
1073        .into());
1074    }
1075    // SCAN EVERY ROW BEFORE REPORTING. A first-hit return says "row 0 is bad" and leaves the
1076    // other rows UNEXAMINED, which is exactly the bit that discriminates the two mechanisms: in
1077    // the t-column verify, row 0 attends keys [0..p+1) and row 1 attends [0..p+2), a strict
1078    // superset, so poison in the SHARED KV history must appear in BOTH rows, while poison in
1079    // per-column staging can appear in one. Report the whole map.
1080    let mut per_row: Vec<usize> = Vec::with_capacity(rows);
1081    let mut first_bad: Option<(usize, usize)> = None;
1082    for r in 0..rows {
1083        let row = &host[r * cols..(r + 1) * cols];
1084        let bad = row.iter().filter(|v| !v.is_finite()).count();
1085        per_row.push(bad);
1086        if bad > 0 && first_bad.is_none() {
1087            first_bad = Some((r, row.iter().position(|v| !v.is_finite()).unwrap_or(0)));
1088        }
1089    }
1090    if let Some((r0, c0)) = first_bad {
1091        let map: String = per_row
1092            .iter()
1093            .map(|&b| if b == 0 { '.' } else { 'X' })
1094            .collect();
1095        return Err(format!(
1096            "spec nan-scan: {what} produced non-finite values — rows[{rows}] map={map} \
1097             counts={per_row:?} of {cols} each; first at row {r0} element {c0}. Both rows bad \
1098             implicates shared state (the KV history this layer reads); one row bad implicates \
1099             per-column staging."
1100        )
1101        .into());
1102    }
1103    Ok(())
1104}
1105
1106fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1107    if spec_lean() { e.uninit(n) } else { e.zeros(n) }
1108}
1109
1110/// Scratch KV for the MTP block (one full-attn layer).
1111///
1112/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
1113/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
1114/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
1115/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
1116/// engine's "mtp_update" design). Entries come from two sources:
1117///   - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
1118///     hidden chain-approximate — the reference engine accepts the same);
1119///   - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
1120///     from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
1121///     Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
1122///     `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
1123///     Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
1124///     the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
1125///     suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
1126///     then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
1127///     committed row across turns (the predecessor-pairing seed + fill anchor).
1128///     Per-request sampling config for the sampled-spec serve path.
1129#[derive(Clone, Copy, Debug)]
1130pub struct SpecSampling {
1131    pub temp: f32,
1132    pub seed: u64,
1133    pub top_k: i32,            // 0 = off
1134    pub top_p: f32,            // 1.0 = off
1135    pub min_p: f32,            // 0.0 = off
1136    pub penalty_last_n: usize, // 0 = penalties off
1137    pub penalty_repeat: f32,
1138    pub penalty_freq: f32,
1139    pub penalty_present: f32,
1140}
1141
1142impl SpecSampling {
1143    /// Non-identity penalties requested — THE `pen_on` predicate (one definition; the
1144    /// same group-off rule `SamplerIdentity::of` canonicalizes: a window with neutral
1145    /// coefficients is penalties-absent). Both spec routes and the dspark accept walk
1146    /// key their penalty arms off this.
1147    pub fn pen_on(&self) -> bool {
1148        self.penalty_last_n > 0
1149            && (self.penalty_repeat != 1.0
1150                || self.penalty_freq != 0.0
1151                || self.penalty_present != 0.0)
1152    }
1153}
1154
1155/// `MEMRA_SPEC_PMIN` break semantics over per-slot draft confidences (the chain break this
1156/// module's drafting loops apply inline: `p < p_min && (j > 0 || pmin0)`): keep the longest
1157/// prefix whose every slot clears `p_min`; slot 0 survives a miss unless PMIN0 arms
1158/// zero-draft rounds. Prefix truncation is forced by the accept rule anyway (a kept slot
1159/// after a dropped one could never commit — the dspark confidence-slot argument). Pure so
1160/// the rule is CPU-gateable; the SHARED K-policy surface every spec family consumes
1161/// (hoisted from the glm5 loop, lane/glm5-extract-general).
1162pub fn spec_conf_keep(q: &[f32], p_min: f32, pmin0: bool) -> usize {
1163    if p_min <= 0.0 {
1164        return q.len();
1165    }
1166    let mut kept = 0usize;
1167    for (j, &qj) in q.iter().enumerate() {
1168        if qj < p_min && (j > 0 || pmin0) {
1169            break;
1170        }
1171        kept += 1;
1172    }
1173    kept
1174}
1175
1176/// Host Philox4x32-10 uniform in (0,1) — mirrors spec_sample.cu's `philox4`/`u01` with the
1177/// ctr_lo tag 0xFFFF_FFFE, so the host accept-test stream never collides with any device
1178/// sampling event (device Gumbel uses (i>>2, stream_pos); device residual uses 0xFFFF_FFFD).
1179/// One value per (seed, ctr) EVENT; callers own the counter discipline. Extracted verbatim
1180/// from generate_spec_inner2's closure for the dspark sampled-admission walk (the two paths
1181/// MUST consume the identical stream construction — two ad-hoc Philox copies drifting apart
1182/// is a distributional bug, not a style problem).
1183pub(crate) fn host_u01(seed: u64, ctr: u32) -> f32 {
1184    let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
1185    let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
1186    let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
1187    for _ in 0..10 {
1188        let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
1189        let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
1190        let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
1191        c0 = n0;
1192        c1 = n1;
1193        c2 = n2;
1194        c3 = n3;
1195        k0 = k0.wrapping_add(0x9E3779B9);
1196        k1 = k1.wrapping_add(0xBB67AE85);
1197    }
1198    (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
1199}
1200
1201/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
1202/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
1203pub const SPEC_TELEM_POS: usize = 8;
1204
1205/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
1206/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
1207/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
1208/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
1209/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
1210/// in NEITHER drafted nor accepted.
1211#[derive(Clone, Copy, Default, Debug)]
1212pub struct SpecTelemetry {
1213    /// verify rounds completed (a round-stream burst counts each of its M rounds).
1214    pub rounds: u64,
1215    /// tokens drafted / accepted across all rounds.
1216    pub drafted: u64,
1217    pub accepted: u64,
1218    /// how often draft position j (0-based within a round's chain) was offered / accepted.
1219    /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
1220    /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
1221    /// arrays cover the standard-path rounds only and their sums may undercount the totals.
1222    pub pos_drafted: [u64; SPEC_TELEM_POS],
1223    pub pos_accepted: [u64; SPEC_TELEM_POS],
1224}
1225
1226impl SpecTelemetry {
1227    /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
1228    /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
1229    /// a wrapped counter.
1230    pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
1231        let mut d = SpecTelemetry {
1232            rounds: self.rounds.saturating_sub(prev.rounds),
1233            drafted: self.drafted.saturating_sub(prev.drafted),
1234            accepted: self.accepted.saturating_sub(prev.accepted),
1235            ..Default::default()
1236        };
1237        for j in 0..SPEC_TELEM_POS {
1238            d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
1239            d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
1240        }
1241        d
1242    }
1243    /// Fieldwise `self += d` — the worker's per-model aggregation.
1244    pub fn merge(&mut self, d: &SpecTelemetry) {
1245        self.rounds += d.rounds;
1246        self.drafted += d.drafted;
1247        self.accepted += d.accepted;
1248        for j in 0..SPEC_TELEM_POS {
1249            self.pos_drafted[j] += d.pos_drafted[j];
1250            self.pos_accepted[j] += d.pos_accepted[j];
1251        }
1252    }
1253
1254    /// Mean accepted draft-prefix length per verify round (tau).
1255    pub fn tau(&self) -> f64 {
1256        if self.rounds > 0 {
1257            self.accepted as f64 / self.rounds as f64
1258        } else {
1259            0.0
1260        }
1261    }
1262}
1263
1264/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
1265/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
1266/// launch, synchronization, allocation, or ordering dependency to the numeric path.
1267struct SpecTelemetryCounters {
1268    rounds: AtomicU64,
1269    drafted: AtomicU64,
1270    accepted: AtomicU64,
1271    pos_drafted: [AtomicU64; SPEC_TELEM_POS],
1272    pos_accepted: [AtomicU64; SPEC_TELEM_POS],
1273}
1274
1275impl Default for SpecTelemetryCounters {
1276    fn default() -> Self {
1277        Self {
1278            rounds: AtomicU64::new(0),
1279            drafted: AtomicU64::new(0),
1280            accepted: AtomicU64::new(0),
1281            pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
1282            pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
1283        }
1284    }
1285}
1286
1287impl SpecTelemetryCounters {
1288    fn record_round(&self, drafted: usize, accepted: usize) {
1289        debug_assert!(accepted <= drafted);
1290        self.rounds.fetch_add(1, Ordering::Relaxed);
1291        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
1292        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
1293        for counter in self.pos_drafted.iter().take(drafted) {
1294            counter.fetch_add(1, Ordering::Relaxed);
1295        }
1296        for counter in self.pos_accepted.iter().take(accepted) {
1297            counter.fetch_add(1, Ordering::Relaxed);
1298        }
1299    }
1300
1301    /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
1302    /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
1303    fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
1304        self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
1305        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
1306        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
1307    }
1308
1309    fn snapshot(&self) -> SpecTelemetry {
1310        SpecTelemetry {
1311            rounds: self.rounds.load(Ordering::Relaxed),
1312            drafted: self.drafted.load(Ordering::Relaxed),
1313            accepted: self.accepted.load(Ordering::Relaxed),
1314            pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
1315            pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
1316        }
1317    }
1318}
1319
1320pub struct SpecSession {
1321    pub(crate) cache: Cache,
1322    pub(crate) scratch: MtpScratch,
1323    /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
1324    /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
1325    /// session must count them. Callers render output from this, not from their own echo.
1326    pub committed: Vec<u32>,
1327    /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
1328    pub(crate) last_h: Option<CudaSlice<f32>>,
1329    /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
1330    /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
1331    /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
1332    pub next_pred: Option<u32>,
1333    /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
1334    /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
1335    pub sctr: u32,
1336    pub uctr: u32,
1337    /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
1338    /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
1339    /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
1340    /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
1341    /// research/spec-serving-20260801). None before the first turn; error paths drop it
1342    /// (next burst recaptures — serve retires errored sessions anyway).
1343    pub(crate) draft_ctx: Option<DraftGraphCtx>,
1344    /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
1345    /// emitted by the last round but NOT committed to the caches. The old tail committed it with
1346    /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
1347    /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
1348    /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
1349    /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
1350    /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
1351    /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
1352    /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
1353    /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
1354    /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
1355    pub pending_tok: Option<u32>,
1356    /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
1357    /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
1358    /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
1359    /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
1360    pub(crate) turn_ckpt: Option<SpecCheckpoint>,
1361    /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
1362    /// accounting the loop already does — no syncs, no allocation. NOTE a
1363    /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
1364    /// diff with [`SpecTelemetry::delta_since`] around each burst.
1365    telem: SpecTelemetryCounters,
1366    /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
1367    /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
1368    /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
1369    /// prime, result lands in `boundary_captures`.
1370    pub capture_at: Option<usize>,
1371    /// The captures the last prime produced (see [`SpecBoundaryCapture`]). Worker drains them
1372    /// post-burst to assemble prefix entries. A failed capture is silent, like `turn_ckpt` —
1373    /// publication just isn't available for that request. Plural since
1374    /// lane/frspec-multiturn-cache (2026-08-21): a cold burst can capture BOTH the miss-LCP
1375    /// split (the shared-prefix class) and the stable pre-generation boundary (the
1376    /// next-turn re-render class) — one entry per stop, exactly the boundary set the plain
1377    /// prefill tick publishes/checkpoints.
1378    pub boundary_captures: Vec<SpecBoundaryCapture>,
1379    /// STABLE-BOUNDARY TURN CHECKPOINT REQUEST (lane/frspec-multiturn-cache, 2026-08-21): the
1380    /// ABSOLUTE committed-length position the next non-empty prime should capture `turn_ckpt`
1381    /// at, instead of prompt-end. The worker sets it to the STABLE PRE-GENERATION boundary
1382    /// (`plain_checkpoint_boundary` — before the live generation header the client rewrites),
1383    /// porting the 2026-08-09 plain-tier fix: a prompt-end spec checkpoint includes the
1384    /// template's live assistant-generation header (`<|im_start|>assistant\n<think>\n`), which
1385    /// the NEXT turn's re-render replaces, so `affinity_match` diverged a couple tokens below
1386    /// the checkpoint and the spec pool declined 100% of multi-turn agent traffic (measured:
1387    /// `spec-affinity: declined (history diverged at 6811 of checkpoint 6813)`,
1388    /// research/multiturn-cache-20260821 B4). One-shot, `capture_at` convention; None = legacy
1389    /// prompt-end capture.
1390    pub ckpt_at: Option<usize>,
1391    /// FAIL-SAFE (lane/step37-vram-admission-20260830, external-review corroboration): set
1392    /// by the worker on a session serving a step-OOM park REPLAY. The burst entry pre-marks
1393    /// the draft-graph fallback so the replay never re-enters the capture path — the capture
1394    /// appetite is part of what drove the card to the OOM, and a replay that recaptures
1395    /// re-runs the incident. If the eager replay still cannot fit, the bounded retry budget
1396    /// exhausts into the honest recoverable Overloaded error instead of looping.
1397    pub capture_disabled: bool,
1398}
1399impl SpecSession {
1400    /// Context capacity of the session's caches (the server's ContextFull guard).
1401    pub fn cache_max_ctx(&self) -> usize {
1402        self.cache.max_ctx
1403    }
1404    /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
1405    /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
1406    /// those rows are append-only for the session's lifetime (rollbacks never truncate below
1407    /// the prime boundary), so no copy was taken at prime time.
1408    pub fn cache_ref(&self) -> &Cache {
1409        &self.cache
1410    }
1411    /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
1412    /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
1413    /// like the trunk KV — draft rows below the prompt end are append-only for the
1414    /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
1415    /// committed length, never below the prime boundary, and the true-hidden refresh
1416    /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
1417    /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
1418    /// prefix-addressable; the prefix cache already refuses that class end to end).
1419    pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
1420        if self.scratch.kv.ring.is_some() {
1421            return None;
1422        }
1423        Some((
1424            &self.scratch.kv.k,
1425            &self.scratch.kv.v,
1426            self.scratch.kv.k_tok_bytes,
1427            self.scratch.kv.v_tok_bytes,
1428        ))
1429    }
1430    /// Snapshot the session's process-local acceptance counters for per-burst diffing.
1431    pub fn telemetry(&self) -> SpecTelemetry {
1432        self.telem.snapshot()
1433    }
1434    /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
1435    /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
1436    /// `spec_rewind_to_checkpoint`.
1437    pub fn rewind_pos(&self) -> Option<usize> {
1438        self.turn_ckpt.as_ref().map(|c| c.pos)
1439    }
1440    /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
1441    pub fn rewind_is_resident(&self) -> bool {
1442        self.turn_ckpt.as_ref().is_some_and(|ckpt| {
1443            self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
1444        })
1445    }
1446    /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
1447    /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
1448    /// session has never run a turn and has no prediction to hand over.
1449    pub fn demote_ready(&self) -> bool {
1450        self.pending_tok.is_none() && self.next_pred.is_some()
1451    }
1452    /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
1453    pub fn has_pending(&self) -> bool {
1454        self.pending_tok.is_some()
1455    }
1456    /// Committed row count == cache rows (the session invariant), for the caller's own
1457    /// `fed`-length cross-check at a handoff boundary.
1458    pub fn committed_len(&self) -> usize {
1459        self.committed.len()
1460    }
1461    /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
1462    /// cache + next-token prediction to the plain batched-decode path.
1463    ///
1464    /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
1465    /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
1466    /// tokenwise prime of the same `committed` sequence would have left it (that is the
1467    /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
1468    /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
1469    /// committed row — and verify-column logits are bit-identical to plain decode's logits at
1470    /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
1471    /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
1472    /// a state indistinguishable from one the batched path produced itself: the batched tick
1473    /// emits `next_pred`, feeds it into this same cache, and decodes on.
1474    ///
1475    /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
1476    /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
1477    /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
1478    /// path would silently skip a token.
1479    ///
1480    /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
1481    /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
1482    /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
1483    /// would mean an `mtp_kv_fill` over the whole committed history).
1484    pub fn into_demoted(self) -> Option<(Cache, u32)> {
1485        if self.pending_tok.is_some() || self.cache.tainted {
1486            return None;
1487        }
1488        let np = self.next_pred?;
1489        debug_assert_eq!(
1490            self.cache.pos,
1491            self.committed.len(),
1492            "demotion handoff: cache rows != committed tokens"
1493        );
1494        Some((self.cache, np))
1495    }
1496    /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
1497    /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
1498    /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
1499    /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
1500    pub fn reset_graph_fallback_on_resume(&mut self) {
1501        if let Some(line) = self
1502            .draft_ctx
1503            .as_mut()
1504            .and_then(|c| c.failed.reset_on_resume())
1505        {
1506            eprintln!("{line}");
1507        }
1508    }
1509}
1510
1511/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
1512///
1513/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
1514/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
1515/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
1516/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
1517/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
1518/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
1519///
1520/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
1521/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
1522/// position index, so it must be a real device COPY — that copy is the entire reason a spec
1523/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
1524/// below the boundary were written by this turn's fill and are never revisited (the per-round
1525/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
1526/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
1527/// predecessor-pairing anchor the next prime's fill reads for its first row.
1528///
1529/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
1530pub(crate) struct SpecCheckpoint {
1531    snap: crate::cache::CacheSnapshot,
1532    /// Committed length at the boundary (== cache.pos there, the session invariant).
1533    pos: usize,
1534    /// Pre-output_norm hidden of row `pos - 1`.
1535    last_h: CudaSlice<f32>,
1536}
1537
1538/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
1539/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
1540/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
1541/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
1542/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
1543/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
1544/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
1545/// so the worker slices those from the live caches post-burst instead of copying at prime time.
1546pub struct SpecBoundaryCapture {
1547    pub snap: crate::cache::CacheSnapshot,
1548    /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
1549    pub pos: usize,
1550    /// Full-vocab logits after the prefix prime — the entry's boundary logits.
1551    pub logits: Vec<f32>,
1552    /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
1553    /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
1554    /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
1555    /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
1556    pub last_h: Vec<f32>,
1557}
1558
1559/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
1560/// spec boundary capture carries for later restored-session fills. Failure is silent
1561/// (`turn_ckpt` convention): the capture publishes without an anchor.
1562fn capture_boundary_hidden(
1563    e: &Engine,
1564    h_rows: &CudaSlice<f32>,
1565    pos: usize,
1566    n_embd: usize,
1567) -> Vec<f32> {
1568    if pos == 0 || h_rows.len() < pos * n_embd {
1569        return Vec::new();
1570    }
1571    let Ok(mut row) = e.uninit(n_embd) else {
1572        return Vec::new();
1573    };
1574    if e.copy_view_into(
1575        &mut row,
1576        0,
1577        &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
1578        n_embd,
1579    )
1580    .is_err()
1581    {
1582        return Vec::new();
1583    }
1584    e.dtoh(&row).unwrap_or_default()
1585}
1586
1587/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
1588/// Default ON: the token a burst emits at its own boundary is drawn from the request's
1589/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
1590/// every boundary) without touching greedy, which is byte-unaffected either way.
1591pub fn spec_sampled_boundary_on() -> bool {
1592    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1593    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
1594}
1595
1596/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
1597/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
1598/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
1599/// restores the pre-lane posture (each burst restarts the window from its own prompt
1600/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
1601/// must keep refusing penalized sampled prefix-cache restores, because the restored
1602/// session's continuation burst is handed no prompt slice at all.
1603pub fn spec_pen_session_on() -> bool {
1604    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1605    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
1606}
1607
1608/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
1609/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
1610/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
1611/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
1612/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
1613/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
1614pub fn spec_restore_republish_on() -> bool {
1615    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1616    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
1617}
1618
1619/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
1620/// the argmax the pre-lane code would have emitted from the same row. This is how the
1621/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
1622fn spec_boundary_trace() -> bool {
1623    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1624    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
1625}
1626
1627/// llama-parity floor for the penalty window when the request does not ask for a bigger
1628/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = PEN_WINDOW_MAX` for any
1629/// non-identity penalty, so this floor only matters to explicit small windows and to the
1630/// CLI env path.
1631const PEN_WINDOW_FLOOR: usize = 64;
1632
1633/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
1634/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
1635/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
1636/// p column, the bonus column). The serve API uses this same bound for every non-identity
1637/// penalty so host/plain, sparse-device, and speculative sampling cannot change logits on
1638/// admission demotion. An uncapped 128k-token history would put ~1.7e10
1639/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
1640/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
1641/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
1642/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
1643/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
1644/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
1645/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route's accept walk and
1646/// the dspark_sample_gate binary trim their uploads with the SAME cap — a second constant
1647/// is a second thing to drift.
1648pub const PEN_WINDOW_MAX: usize = 8192;
1649
1650/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
1651/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
1652/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
1653/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
1654/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
1655/// client actually asked us to penalize, where the pre-lane code had NOTHING.
1656/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route seeds its session
1657/// window through the SAME function (one definition of "the window" across both spec
1658/// routes and the gate binary's trunk-only reference arm).
1659pub fn pen_window_seed(
1660    session_committed: &[u32],
1661    burst_prompt: &[u32],
1662    penalty_last_n: usize,
1663) -> Vec<u32> {
1664    let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
1665    let take_prompt = burst_prompt.len().min(win);
1666    let take_sess = (win - take_prompt).min(session_committed.len());
1667    let mut hist = Vec::with_capacity(take_sess + take_prompt);
1668    hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
1669    hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
1670    hist
1671}
1672
1673/// Draw a BOUNDARY token from the target distribution the request asked for
1674/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
1675/// every burst boundary".
1676///
1677/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
1678/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
1679/// row after the last committed token on a continuation burst; the prefix-cache entry's
1680/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
1681/// regimes, so a sampled stream took a greedy token once per burst — measured, not
1682/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
1683/// customer asked for a sampled token, so this draws one.
1684///
1685/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
1686/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
1687/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
1688/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
1689/// composition means `sample_check`'s distributional oracle covers this draw too, and the
1690/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
1691///
1692/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
1693/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
1694/// stream the accept walk uses — never a second, independently seeded stream (which would be
1695/// a new distributional bug: two streams from one seed correlate wherever their counters
1696/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
1697/// to the cold session's own first draw from the same logits row, which is what preserves the
1698/// sampled-hit lane's per-seed hit==cold byte identity.
1699#[allow(clippy::too_many_arguments)]
1700pub fn sample_boundary_token_dev(
1701    e: &Engine,
1702    logits: &CudaSlice<f32>,
1703    n_vocab: usize,
1704    sp: &SpecSampling,
1705    pen_hist: &[u32],
1706    sctr: &mut u32,
1707    site: &str,
1708) -> Result<u32, Box<dyn std::error::Error>> {
1709    debug_assert!(
1710        sp.temp > 0.0,
1711        "boundary sampling is the sampled regime only"
1712    );
1713    // Own copy: penalize_logits mutates in place and the caller's row is live state
1714    // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
1715    let mut col = e.zeros(n_vocab)?;
1716    e.copy_into(&mut col, 0, logits, n_vocab)?;
1717    let pen_on = sp.penalty_last_n > 0
1718        && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
1719    if pen_on && !pen_hist.is_empty() {
1720        // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
1721        let w0 = pen_hist
1722            .len()
1723            .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
1724        let hist = &pen_hist[w0..];
1725        let hd = e.htod_u32_v(hist)?;
1726        e.penalize_logits(
1727            &mut col,
1728            &hd,
1729            hist.len(),
1730            sp.penalty_repeat,
1731            sp.penalty_freq,
1732            sp.penalty_present,
1733            n_vocab,
1734        )?;
1735    }
1736    let rows0 = e.htod_i32(&[0])?;
1737    let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
1738    e.filter_stats(
1739        &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
1740        sp.top_p, sp.min_p,
1741    )?;
1742    let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
1743    let mut perturb = e.zeros(n_vocab)?;
1744    e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
1745    *sctr = sctr.wrapping_add(1);
1746    let td = e.argmax_token_device(&perturb, n_vocab)?;
1747    let tok = guard_vocab_token(
1748        e.dtoh_u32_one(&td)?,
1749        n_vocab,
1750        &format!("sampled boundary token (site={site})"),
1751    )?;
1752    if spec_boundary_trace() {
1753        // the pre-lane token, from the SAME row, so the deviation rate is measurable.
1754        let raw = e.argmax_token_device(logits, n_vocab)?;
1755        let greedy = e.dtoh_u32_one(&raw)?;
1756        eprintln!(
1757            "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
1758             deviates={} temp={} sctr={}",
1759            (tok != greedy) as u8,
1760            sp.temp,
1761            sctr.wrapping_sub(1),
1762        );
1763    }
1764    Ok(tok)
1765}
1766
1767/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
1768/// host `Vec<f32>`).
1769#[allow(clippy::too_many_arguments)]
1770pub fn sample_boundary_token(
1771    e: &Engine,
1772    logits: &[f32],
1773    sp: &SpecSampling,
1774    pen_hist: &[u32],
1775    sctr: &mut u32,
1776    site: &str,
1777) -> Result<u32, Box<dyn std::error::Error>> {
1778    let n_vocab = logits.len();
1779    let d = e.htod(logits)?;
1780    sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
1781}
1782
1783struct SpecPipeTraceClock {
1784    pair: usize,
1785    started: std::time::Instant,
1786}
1787
1788#[derive(Clone)]
1789struct SpecPipeTraceCtx {
1790    clock: std::sync::Arc<SpecPipeTraceClock>,
1791    round: usize,
1792    lane: usize,
1793}
1794
1795struct SpecPipeTraceMarker {
1796    trace: SpecPipeTraceCtx,
1797    phase: &'static str,
1798    edge: &'static str,
1799    slot: Option<usize>,
1800}
1801
1802unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
1803    let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
1804    let lane = if marker.trace.lane == 0 { "A" } else { "B" };
1805    let slot = marker
1806        .slot
1807        .map(|v| v.to_string())
1808        .unwrap_or_else(|| "-".into());
1809    let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
1810    use std::io::Write as _;
1811    let stderr = std::io::stderr();
1812    let mut stderr = stderr.lock();
1813    let _ = writeln!(
1814        stderr,
1815        "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
1816         slot={slot} t_ms={t_ms:.3}",
1817        marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
1818    );
1819}
1820
1821fn enqueue_spec_pipe_trace_marker(
1822    stream: &cudarc::driver::CudaStream,
1823    trace: Option<&SpecPipeTraceCtx>,
1824    phase: &'static str,
1825    edge: &'static str,
1826    slot: Option<usize>,
1827) -> Result<(), Box<dyn std::error::Error>> {
1828    let Some(trace) = trace else {
1829        return Ok(());
1830    };
1831    let marker = Box::new(SpecPipeTraceMarker {
1832        trace: trace.clone(),
1833        phase,
1834        edge,
1835        slot,
1836    });
1837    let raw = Box::into_raw(marker);
1838    let result = unsafe {
1839        cudarc::driver::result::stream::launch_host_function(
1840            stream.cu_stream(),
1841            spec_pipe_trace_marker,
1842            raw.cast(),
1843        )
1844    };
1845    if let Err(err) = result {
1846        unsafe {
1847            drop(Box::from_raw(raw));
1848        }
1849        return Err(err.into());
1850    }
1851    Ok(())
1852}
1853
1854#[derive(Default)]
1855struct SpecPipeProgress {
1856    setup_done: [bool; 2],
1857    draft_done: [usize; 2],
1858    stage0_done: [usize; 2],
1859    verify_done: [usize; 2],
1860    accept_done: [usize; 2],
1861    finished: [bool; 2],
1862    aborted: bool,
1863}
1864
1865/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
1866/// keeps its existing call stack and round locals; this object only orders phase entry. The
1867/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
1868/// cannot be interleaved by the two host threads.
1869struct SpecPipeSync {
1870    progress: std::sync::Mutex<SpecPipeProgress>,
1871    changed: std::sync::Condvar,
1872    primary: std::sync::Mutex<()>,
1873    trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
1874}
1875
1876impl SpecPipeSync {
1877    fn new() -> Self {
1878        static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1879        let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
1880            std::sync::Arc::new(SpecPipeTraceClock {
1881                pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1882                started: std::time::Instant::now(),
1883            })
1884        });
1885        Self {
1886            progress: std::sync::Mutex::new(SpecPipeProgress::default()),
1887            changed: std::sync::Condvar::new(),
1888            primary: std::sync::Mutex::new(()),
1889            trace,
1890        }
1891    }
1892}
1893
1894#[derive(Clone)]
1895struct SpecPipeLane {
1896    sync: std::sync::Arc<SpecPipeSync>,
1897    lane: usize,
1898    rt: &'static crate::pp::PpNRt,
1899    walk_permit: crate::pp::PpWalkPermit,
1900}
1901
1902struct SpecPipePrimaryGuard<'a> {
1903    _primary: std::sync::MutexGuard<'a, ()>,
1904    _walk: crate::pp::PpWalkBorrowGuard,
1905}
1906
1907impl SpecPipeLane {
1908    fn peer(&self) -> usize {
1909        1 - self.lane
1910    }
1911
1912    fn aborted() -> Box<dyn std::error::Error> {
1913        "paired speculative peer aborted".into()
1914    }
1915
1916    fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
1917        self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
1918            clock: clock.clone(),
1919            round,
1920            lane: self.lane,
1921        })
1922    }
1923
1924    fn setup_begin(&self) -> Result<crate::pp::PpWalkBorrowGuard, Box<dyn std::error::Error>> {
1925        let mut p = self.sync.progress.lock().unwrap();
1926        while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
1927            p = self.sync.changed.wait(p).unwrap();
1928        }
1929        if p.aborted {
1930            Err(Self::aborted())
1931        } else {
1932            drop(p);
1933            self.rt.borrow_walk(&self.walk_permit, "spec_pipe/setup")
1934        }
1935    }
1936
1937    fn setup_end(&self) {
1938        let mut p = self.sync.progress.lock().unwrap();
1939        p.setup_done[self.lane] = true;
1940        self.sync.changed.notify_all();
1941    }
1942
1943    fn draft_begin(
1944        &self,
1945        round: usize,
1946    ) -> Result<SpecPipePrimaryGuard<'_>, Box<dyn std::error::Error>> {
1947        let peer = self.peer();
1948        let mut p = self.sync.progress.lock().unwrap();
1949        loop {
1950            if p.aborted {
1951                return Err(Self::aborted());
1952            }
1953            let setup_ready =
1954                (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
1955            let prior_ready = p.accept_done[self.lane] >= round
1956                && (p.accept_done[peer] >= round || p.finished[peer]);
1957            let turn_ready = if self.lane == 0 {
1958                true
1959            } else {
1960                p.draft_done[0] > round || p.finished[0]
1961            };
1962            if setup_ready && prior_ready && turn_ready {
1963                break;
1964            }
1965            p = self.sync.changed.wait(p).unwrap();
1966        }
1967        drop(p);
1968        let primary = self.sync.primary.lock().unwrap();
1969        let walk = self.rt.borrow_walk(&self.walk_permit, "spec_pipe/draft")?;
1970        Ok(SpecPipePrimaryGuard {
1971            _primary: primary,
1972            _walk: walk,
1973        })
1974    }
1975
1976    fn draft_end(&self, round: usize) {
1977        let mut p = self.sync.progress.lock().unwrap();
1978        p.draft_done[self.lane] = round + 1;
1979        self.sync.changed.notify_all();
1980    }
1981
1982    /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
1983    /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
1984    fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
1985        let peer = self.peer();
1986        let mut p = self.sync.progress.lock().unwrap();
1987        loop {
1988            if p.aborted {
1989                return Err(Self::aborted());
1990            }
1991            let ready = if self.lane == 0 {
1992                p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
1993            } else {
1994                p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
1995            };
1996            if ready {
1997                return Ok(self.lane == 0 || p.finished[peer]);
1998            }
1999            p = self.sync.changed.wait(p).unwrap();
2000        }
2001    }
2002
2003    fn stage0_end(&self, round: usize) {
2004        let mut p = self.sync.progress.lock().unwrap();
2005        p.stage0_done[self.lane] = round + 1;
2006        self.sync.changed.notify_all();
2007    }
2008
2009    /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
2010    /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
2011    fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
2012        let mut p = self.sync.progress.lock().unwrap();
2013        while !p.aborted
2014            && !(p.stage0_done[self.lane] > round
2015                && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
2016        {
2017            p = self.sync.changed.wait(p).unwrap();
2018        }
2019        if p.aborted {
2020            Err(Self::aborted())
2021        } else {
2022            Ok(())
2023        }
2024    }
2025
2026    fn verify_end(&self, round: usize) {
2027        let mut p = self.sync.progress.lock().unwrap();
2028        p.verify_done[self.lane] = round + 1;
2029        self.sync.changed.notify_all();
2030    }
2031
2032    fn accept_begin(
2033        &self,
2034        round: usize,
2035    ) -> Result<SpecPipePrimaryGuard<'_>, Box<dyn std::error::Error>> {
2036        let mut p = self.sync.progress.lock().unwrap();
2037        loop {
2038            if p.aborted {
2039                return Err(Self::aborted());
2040            }
2041            let ready = if self.lane == 0 {
2042                p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
2043            } else {
2044                p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
2045            };
2046            if ready {
2047                break;
2048            }
2049            p = self.sync.changed.wait(p).unwrap();
2050        }
2051        drop(p);
2052        let primary = self.sync.primary.lock().unwrap();
2053        let walk = self.rt.borrow_walk(&self.walk_permit, "spec_pipe/accept")?;
2054        Ok(SpecPipePrimaryGuard {
2055            _primary: primary,
2056            _walk: walk,
2057        })
2058    }
2059
2060    fn accept_end(&self, round: usize) {
2061        let mut p = self.sync.progress.lock().unwrap();
2062        p.accept_done[self.lane] = round + 1;
2063        self.sync.changed.notify_all();
2064    }
2065
2066    fn primary(&self) -> Result<SpecPipePrimaryGuard<'_>, Box<dyn std::error::Error>> {
2067        let primary = self.sync.primary.lock().unwrap();
2068        let walk = self.rt.borrow_walk(&self.walk_permit, "spec_pipe/tail")?;
2069        Ok(SpecPipePrimaryGuard {
2070            _primary: primary,
2071            _walk: walk,
2072        })
2073    }
2074
2075    fn coordinated_walk(&self) -> Result<crate::pp::PpWalkBorrowGuard, Box<dyn std::error::Error>> {
2076        self.rt
2077            .borrow_walk(&self.walk_permit, "spec_pipe/coordinated_verify")
2078    }
2079
2080    fn finish(&self, failed: bool) {
2081        let mut p = self.sync.progress.lock().unwrap();
2082        p.finished[self.lane] = true;
2083        p.aborted |= failed;
2084        self.sync.changed.notify_all();
2085    }
2086}
2087
2088struct SpecPipeFinish<'a> {
2089    lane: &'a SpecPipeLane,
2090    closed: bool,
2091}
2092
2093impl<'a> SpecPipeFinish<'a> {
2094    fn new(lane: &'a SpecPipeLane) -> Self {
2095        Self {
2096            lane,
2097            closed: false,
2098        }
2099    }
2100
2101    fn close(&mut self, failed: bool) {
2102        self.lane.finish(failed);
2103        self.closed = true;
2104    }
2105}
2106
2107impl Drop for SpecPipeFinish<'_> {
2108    fn drop(&mut self) {
2109        if !self.closed {
2110            self.lane.finish(true);
2111        }
2112    }
2113}
2114
2115/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
2116/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
2117/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
2118/// binds that context before touching the session, joins before returning, and never aliases the
2119/// pointer. Keep this exception local to the experimental pair call instead of marking the public
2120/// session type Send.
2121struct SpecPipeSessionPtr(*mut SpecSession);
2122
2123unsafe impl Send for SpecPipeSessionPtr {}
2124
2125impl SpecPipeSessionPtr {
2126    unsafe fn get_mut(&mut self) -> &mut SpecSession {
2127        unsafe { &mut *self.0 }
2128    }
2129}
2130
2131/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
2132/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
2133/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
2134/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
2135/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
2136/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
2137/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
2138/// so the eager fallback doesn't pay a doomed capture attempt every burst.
2139/// Capture identity of the parked SAMPLED draft graph (`DraftGraphCtx::graph_s`).
2140///
2141/// EXACTNESS, not perf (lane/graph-s-key-exactness-20260819; receipts
2142/// `research/spec-cache-20260818/GRAPH-S-KEY.md`). Two classes of field live here, both
2143/// load-bearing:
2144///
2145/// - **Baked constants.** `seed` and `temp` are capture-time constants INSIDE the graph and `k`
2146///   sizes the q slots its replays write. A resumed request changing any of them must recapture.
2147///   This is all the key used to carry.
2148/// - **Regime fields.** `top_k`/`top_p`/`min_p`/`pen_on` are not baked, but they decide whether
2149///   the captured graph is a legal draft chain AT ALL. The in-graph draw is one gumbel-max over
2150///   the RAW softmax (`gumbel_perturb_ctr`, unfiltered by construction), while the verify builds
2151///   the accept test's `q` from `filter_stats(q_slots, top_k, top_p, min_p)`. If those disagree
2152///   the accept test evaluates a distribution the draft was never sampled from: a draft token
2153///   below the filter threshold gathers `q = 0` (`softmax_gather_filtered_f32`,
2154///   `cu/spec_sample.cu`) and `u * 0 < p` accepts it UNCONDITIONALLY.
2155///
2156/// Omitting the regime fields was reachable — not through the prefix-cache spec restore (that
2157/// path is greedy-only, `memra-server` `spec_restore_convertible`), but through WHOLE-SESSION
2158/// spec reuse: a parked `SpecSession` carries this `DraftGraphCtx`, and the pool-resume probe
2159/// applies no sampler predicate at all. Turn 1 pure-temp parks a graph; turn 2 of the same
2160/// conversation, same explicit seed and temperature, adds `top_p`/`top_k` and inherits it.
2161#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2162pub(crate) struct SampledGraphKey {
2163    seed: u64,
2164    temp_bits: u32,
2165    k: usize,
2166    top_k: i32,
2167    top_p_bits: u32,
2168    min_p_bits: u32,
2169    pen_on: bool,
2170}
2171
2172impl SampledGraphKey {
2173    pub(crate) fn new(
2174        seed: u64,
2175        temp: f32,
2176        k: usize,
2177        top_k: i32,
2178        top_p: f32,
2179        min_p: f32,
2180        pen_on: bool,
2181    ) -> Self {
2182        SampledGraphKey {
2183            seed,
2184            temp_bits: temp.to_bits(),
2185            k,
2186            top_k,
2187            top_p_bits: top_p.to_bits(),
2188            min_p_bits: min_p.to_bits(),
2189            pen_on,
2190        }
2191    }
2192
2193    /// The one regime the PURE-TEMP in-graph sampled chain may stand in for the eager one:
2194    /// nothing but temperature shapes `q`. Computed FROM THE KEY so the capture guard, the
2195    /// launch guard and the key can never drift apart (they were three separate expressions
2196    /// before this lane, and the launch site simply forgot to ask).
2197    pub(crate) fn pure_temp(&self) -> bool {
2198        self.top_k == 0
2199            && f32::from_bits(self.top_p_bits) >= 1.0
2200            && f32::from_bits(self.min_p_bits) <= 0.0
2201            && !self.pen_on
2202    }
2203
2204    /// Truncation filters active — the capture body needs the IN-GRAPH filter nodes
2205    /// (`filter_stats` + `gumbel_perturb_filtered_ctr`) so the draft draws from the same
2206    /// filtered distribution the accept test reconstructs. Meaningful only when
2207    /// `graph_capturable`; penalties never reach a capture body.
2208    pub(crate) fn filtered(&self) -> bool {
2209        !self.pure_temp()
2210    }
2211
2212    /// May the sampled draft graph be CAPTURED (and a parked one LAUNCHED) for this regime?
2213    /// Pure-temp always; filtered regimes when the filtered-capture door is on
2214    /// (lane/step37-draft-graph-serving-20260830); penalties never — the per-round history
2215    /// cannot be baked into a graph, and composing a raw-softmax (or stale-history) draw
2216    /// with a penalized accept test is the unconditional-accept exactness bug. Computed FROM
2217    /// THE KEY for the same no-drift reason as `pure_temp`.
2218    pub(crate) fn graph_capturable(&self) -> bool {
2219        !self.pen_on && (self.pure_temp() || spec_graph_filtered_on())
2220    }
2221}
2222
2223/// Per-head captured graphs for the MULTI-HEAD MTP draft chain (step-modulo prefix-replay,
2224/// lane/step37-draft-graph-serving-20260830). The chain POLICY — which head serves step j,
2225/// how long the replayed prefix is, which stored seed feeds row r — stays HOST-SIDE in the
2226/// launch loop, exactly `mtp_chain_forward_dev`'s order; the graphs capture ONE head-row
2227/// forward each, on the head's OWN scratch plane:
2228/// - `interior[i]`: head i, `with_head=false` — KV append + carrier only. Interior rows'
2229///   logits are dead in the eager chain too (`mtp_chain_forward_dev` keeps only the last
2230///   row), so skipping the head matmul changes no consumed byte and removes the eager
2231///   chain's per-replay-row full-vocab matmul.
2232/// - `last[i]`: head i, `with_head=true` + the mode's tail (greedy argmax, or the sampled
2233///   gumbel draw — filtered in-graph when the request carries filters).
2234///
2235/// One `DraftChainGraphs` per MODE (greedy vs sampled), owning its keeper: dropping the
2236/// sampled chain on an s_key change never invalidates the greedy one.
2237struct DraftChainGraphs {
2238    interior: Vec<cudarc::driver::CudaGraph>,
2239    last: Vec<cudarc::driver::CudaGraph>,
2240    /// Never read: exists to OWN the captured graphs' backing buffers for as long as the
2241    /// graphs replay (the capture-retain law; same class as `DsparkSegGraph::_keeper`).
2242    _keeper: Vec<Box<dyn std::any::Any + Send>>,
2243}
2244
2245/// Sampled-tail capture pack for `mtp_head_forward_cap`: the persistent buffers and baked
2246/// constants of the in-graph categorical draw. `filt: None` = the PURE-TEMP body (gumbel
2247/// over the raw softmax), byte-identical to the pre-lane capture; `Some` adds the in-graph
2248/// truncation filter (`filter_stats` + `gumbel_perturb_filtered_ctr`) so the draft draws
2249/// from the same filtered distribution the accept test reconstructs
2250/// (lane/step37-draft-graph-serving-20260830).
2251struct SampledCapArgs<'a> {
2252    ctr: &'a mut CudaSlice<u32>,
2253    perturb: &'a mut CudaSlice<f32>,
2254    q_out: &'a mut CudaSlice<f32>,
2255    seed: u64,
2256    temp: f32,
2257    filt: Option<SampledCapFilter<'a>>,
2258}
2259
2260/// In-graph truncation-filter nodes: the stat slots `filter_stats` fills and the perturb
2261/// reads, plus the filter constants baked into the capture (they live in `s_key`, so a
2262/// request whose filters differ drops the parked graph before this ever goes stale).
2263struct SampledCapFilter<'a> {
2264    rows0: &'a CudaSlice<i32>,
2265    th: &'a mut CudaSlice<f32>,
2266    z: &'a mut CudaSlice<f32>,
2267    mx: &'a mut CudaSlice<f32>,
2268    top_k: i32,
2269    top_p: f32,
2270    min_p: f32,
2271}
2272
2273pub(crate) struct DraftGraphCtx {
2274    g_tok: CudaSlice<u32>,
2275    g_pos: CudaSlice<i32>,
2276    g_seed: CudaSlice<f32>,
2277    g_p: CudaSlice<f32>,
2278    g_ctr: CudaSlice<u32>,
2279    g_q: CudaSlice<f32>,
2280    g_perturb: CudaSlice<f32>,
2281    /// IN-GRAPH filter-stat slots (filtered sampled capture): `filter_stats` writes
2282    /// (th, z, mx) here inside the graph; `gumbel_perturb_filtered_ctr` reads (mx, th) from
2283    /// the same slots. Persistent so the baked pointers survive replays. `g_rows0` is the
2284    /// constant row-index-0 the single-row `filter_stats` launch reads (a captured memcpy
2285    /// source must not be a host temporary).
2286    g_rows0: CudaSlice<i32>,
2287    g_th: CudaSlice<f32>,
2288    g_z: CudaSlice<f32>,
2289    g_mx: CudaSlice<f32>,
2290    q_slots: Vec<CudaSlice<f32>>,
2291    /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
2292    /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
2293    /// per-position contents the host re-uploads before each replay (the graph-promote
2294    /// pattern from decode.rs). Empty unless the session drafts under a grammar.
2295    g_dmask: CudaSlice<u32>,
2296    /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
2297    /// Covers the multi-head `chain` too (single-head and chain are mutually exclusive for a
2298    /// given model, so one flag serves whichever is active).
2299    graph_masked: bool,
2300    graph: Option<cudarc::driver::CudaGraph>,
2301    graph_s: Option<cudarc::driver::CudaGraph>,
2302    /// Multi-head chain graphs (see [`DraftChainGraphs`]): greedy and sampled chains, the
2303    /// chain twins of `graph` / `graph_s`. `chain_s`'s capture identity is `s_key` (shared
2304    /// with `graph_s` — a session is either single-head or chain, never both), and it obeys
2305    /// the same drop rules (key mismatch, penalty regime, mask-shape change).
2306    chain: Option<DraftChainGraphs>,
2307    chain_s: Option<DraftChainGraphs>,
2308    /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
2309    /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
2310    failed: DraftGraphFallback,
2311    /// Capture identity of `graph_s` — see [`SampledGraphKey`]. `None` iff no sampled graph is
2312    /// parked; a request whose key differs drops the parked graph (and its q slots/keeper).
2313    s_key: Option<SampledGraphKey>,
2314    /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
2315    /// pool addresses the captured graph(s) bake. Without these, the transients return to the
2316    /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
2317    /// co-served session in the worker) reuses those addresses — the persisted graph's replay
2318    /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
2319    /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
2320    /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
2321    /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
2322    keeper: Vec<Box<dyn std::any::Any + Send>>,
2323    keeper_s: Vec<Box<dyn std::any::Any + Send>>,
2324}
2325
2326/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
2327/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
2328///
2329/// Three contracts:
2330/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
2331///   (returned, not printed, so the once-per-flip contract is unit-testable); the caller
2332///   `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
2333///   an already-failed graph returns None (the per-burst memoization that keeps the eager
2334///   fallback from paying a doomed capture attempt every burst).
2335/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
2336///   NEW request gets one fresh capture chance instead of carrying a transient-pressure
2337///   failure for the pool's whole lifetime. Returns the note line only when a flag was
2338///   actually set (quiet on the common clean-resume path).
2339/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
2340///   capture attempt whose own failure would re-flip loudly.
2341#[derive(Default)]
2342pub(crate) struct DraftGraphFallback {
2343    greedy: bool,
2344    sampled: bool,
2345}
2346impl DraftGraphFallback {
2347    fn mark_greedy(&mut self, reason: &str) -> Option<String> {
2348        if self.greedy {
2349            return None;
2350        }
2351        self.greedy = true;
2352        Some(format!(
2353            "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
2354        ))
2355    }
2356    fn mark_sampled(&mut self, reason: &str) -> Option<String> {
2357        if self.sampled {
2358            return None;
2359        }
2360        self.sampled = true;
2361        Some(format!(
2362            "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
2363        ))
2364    }
2365    fn greedy_failed(&self) -> bool {
2366        self.greedy
2367    }
2368    fn sampled_failed(&self) -> bool {
2369        self.sampled
2370    }
2371    fn clear_greedy(&mut self) {
2372        self.greedy = false;
2373    }
2374    fn clear_sampled(&mut self) {
2375        self.sampled = false;
2376    }
2377    /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
2378    /// was set (so clean resumes stay quiet).
2379    pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
2380        if !self.greedy && !self.sampled {
2381            return None;
2382        }
2383        let which = match (self.greedy, self.sampled) {
2384            (true, true) => "greedy+sampled",
2385            (true, false) => "greedy",
2386            _ => "sampled",
2387        };
2388        self.greedy = false;
2389        self.sampled = false;
2390        Some(format!(
2391            "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
2392        ))
2393    }
2394}
2395
2396impl DraftGraphCtx {
2397    fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
2398        Ok(DraftGraphCtx {
2399            g_tok: e.alloc_u32_zeroed(1)?,
2400            g_pos: e.htod_i32(&[0])?,
2401            g_seed: e.zeros(n_embd)?,
2402            g_p: e.zeros(1)?,
2403            g_ctr: e.alloc_u32_zeroed(1)?,
2404            g_q: e.zeros(qlen)?,
2405            g_perturb: e.zeros(qlen)?,
2406            g_rows0: e.htod_i32(&[0])?,
2407            g_th: e.zeros(1)?,
2408            g_z: e.zeros(1)?,
2409            g_mx: e.zeros(1)?,
2410            q_slots: Vec::new(),
2411            g_dmask: e.alloc_u32_zeroed(1)?,
2412            graph_masked: false,
2413            graph: None,
2414            graph_s: None,
2415            chain: None,
2416            chain_s: None,
2417            failed: DraftGraphFallback::default(),
2418            s_key: None,
2419            keeper: Vec::new(),
2420            keeper_s: Vec::new(),
2421        })
2422    }
2423}
2424
2425pub(crate) struct MtpScratch {
2426    kv: KvLayer,
2427    /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
2428    /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
2429    /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
2430    /// smaller host-indexed SWA ring instead.
2431    cap: usize,
2432    extra: Vec<MtpScratchPlane>,
2433}
2434
2435struct MtpScratchPlane {
2436    kv: KvLayer,
2437    cap: usize,
2438}
2439
2440fn mtp_scratch_layout(
2441    cfg: &memra_gguf::config::ModelConfig,
2442    geom: Option<&crate::hybrid::DraftGeom>,
2443) -> (usize, usize, usize, usize) {
2444    // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
2445    let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
2446    let head_dim_k = cfg.head_dim_k as usize;
2447    let head_dim_v = cfg.head_dim_v as usize;
2448    assert!(
2449        head_dim_k.is_multiple_of(32) && head_dim_v.is_multiple_of(32),
2450        "KVQUANT requires head_dim%32==0 (MTP scratch)"
2451    );
2452    let kv_dim_k = head_dim_k * n_head_kv;
2453    let kv_dim_v = head_dim_v * n_head_kv;
2454    // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
2455    // policy shared with `MtpScratch::new` so admission scales the same allocation.
2456    let (kbb, vbb) = crate::kv_blk_bytes();
2457    let k_tok_bytes = (kv_dim_k / 32) * kbb;
2458    let v_tok_bytes = (kv_dim_v / 32) * vbb;
2459    (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
2460}
2461
2462fn mtp_chain_head_index(step: usize, head_count: usize) -> usize {
2463    assert!(head_count > 0, "MTP chain requires at least one head");
2464    step % head_count
2465}
2466
2467impl MtpScratch {
2468    fn alloc_plane(
2469        e: &Engine,
2470        cfg: &memra_gguf::config::ModelConfig,
2471        plan: &memra_gguf::model_plan::ModelPlan,
2472        cap: usize,
2473        geom: Option<&crate::hybrid::DraftGeom>,
2474    ) -> Result<MtpScratchPlane, Box<dyn std::error::Error>> {
2475        let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
2476        let ring = if crate::cache::swa_ring_on()
2477            && crate::plan_backend::decode_batch_program(plan)
2478                == crate::plan_backend::DecodeBatchProgram::SlidingGatedMoe
2479        {
2480            let window = plan
2481                .layers
2482                .iter()
2483                .find_map(|layer| match layer.attention {
2484                    memra_gguf::model_plan::AttentionPlan::SlidingWindow { window, .. } => {
2485                        Some(window as usize)
2486                    }
2487                    _ => None,
2488                })
2489                .ok_or("sliding-gated-MoE draft scratch has no sliding-window layer")?;
2490            Some(crate::cache::KvRing::new(
2491                crate::cache::swa_ring_rows(window, cap),
2492                window,
2493            ))
2494        } else {
2495            None
2496        };
2497        let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
2498        // Ring-backed planes arm the device base mirror for the dcw draft arm (see
2499        // KvLayer::base_d): the captured chain derives its physical rows from
2500        // (len_d, base_d, window) with zero per-token node updates.
2501        let base_d = match ring.as_ref() {
2502            Some(_) => Some(e.htod_i32(&[0])?),
2503            None => None,
2504        };
2505        Ok(MtpScratchPlane {
2506            kv: KvLayer {
2507                k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
2508                v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
2509                kv_dim_k,
2510                kv_dim_v,
2511                k_tok_bytes,
2512                v_tok_bytes,
2513                len: 0,
2514                ring,
2515                len_d: e.htod_i32(&[0])?,
2516                base_d,
2517            },
2518            cap,
2519        })
2520    }
2521
2522    fn new(
2523        e: &Engine,
2524        cfg: &memra_gguf::config::ModelConfig,
2525        plan: &memra_gguf::model_plan::ModelPlan,
2526        cap: usize,
2527        geom: Option<&crate::hybrid::DraftGeom>,
2528    ) -> Result<Self, Box<dyn std::error::Error>> {
2529        // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
2530        // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
2531        // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
2532        // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
2533        let primary = Self::alloc_plane(e, cfg, plan, cap, geom)?;
2534        Ok(MtpScratch {
2535            kv: primary.kv,
2536            cap: primary.cap,
2537            extra: Vec::new(),
2538        })
2539    }
2540
2541    fn push_plane(
2542        &mut self,
2543        e: &Engine,
2544        cfg: &memra_gguf::config::ModelConfig,
2545        plan: &memra_gguf::model_plan::ModelPlan,
2546        geom: Option<&crate::hybrid::DraftGeom>,
2547    ) -> Result<(), Box<dyn std::error::Error>> {
2548        self.extra
2549            .push(Self::alloc_plane(e, cfg, plan, self.cap, geom)?);
2550        Ok(())
2551    }
2552
2553    fn plane_count(&self) -> usize {
2554        1 + self.extra.len()
2555    }
2556
2557    fn plane(&self, index: usize) -> (&KvLayer, usize) {
2558        if index == 0 {
2559            (&self.kv, self.cap)
2560        } else {
2561            let plane = &self.extra[index - 1];
2562            (&plane.kv, plane.cap)
2563        }
2564    }
2565
2566    fn plane_mut(&mut self, index: usize) -> (&mut KvLayer, usize) {
2567        if index == 0 {
2568            (&mut self.kv, self.cap)
2569        } else {
2570            let plane = &mut self.extra[index - 1];
2571            (&mut plane.kv, plane.cap)
2572        }
2573    }
2574
2575    // #[track_caller]: set_len/set_plane_len have eight call sites (checkpoint restore, spec
2576    // rollback, session grow, seed replay ...) and the lap failure needs to say WHICH one, not
2577    // just that a rewind was refused.
2578    #[track_caller]
2579    fn set_plane_len(
2580        &mut self,
2581        e: &Engine,
2582        index: usize,
2583        n: usize,
2584    ) -> Result<(), Box<dyn std::error::Error>> {
2585        let caller = std::panic::Location::caller();
2586        let (kv, cap) = self.plane_mut(index);
2587        if let Some(ring) = kv.ring.as_ref()
2588            && !ring.can_rewind_to(n)
2589        {
2590            // NAME THE NUMBERS (2026-08-28). This error is a step37 serving blocker on the
2591            // vendor-default shape and it fires from more than one call path with more than
2592            // one trigger: a long generation walks the checkpoint out of the ring, but a
2593            // ~4.5k-token prompt also fails within 5 s of prime, which accumulation cannot
2594            // explain. A bare message forced two rounds of guessing; the operands make each
2595            // trigger name itself.
2596            let raw = n.saturating_sub(ring.window().saturating_sub(1));
2597            return Err(format!(
2598                    "SWA ring MTP checkpoint has been lapped; full re-prime required (plane={index} rewind_to={n} window={} base={} rows={} cap={cap} needed_view_start={} < base, called from {caller})",
2599                    ring.window(),
2600                    ring.base(),
2601                    ring.rows(),
2602                    raw & !31usize,
2603                )
2604                .into());
2605        }
2606        kv.len = n;
2607        e.set_i32_one(&mut kv.len_d, n as i32)
2608    }
2609
2610    /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
2611    /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
2612    /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
2613    #[track_caller]
2614    fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
2615        let caller = std::panic::Location::caller();
2616        if !self.can_rewind_to(n) {
2617            // set_plane_len re-checks and reports the operands; call it so the failure carries
2618            // which plane refused and why, instead of this bare aggregate.
2619            for index in 0..self.plane_count() {
2620                self.set_plane_len(e, index, n)?;
2621            }
2622            return Err(format!(
2623                "SWA ring MTP checkpoint has been lapped; full re-prime required (aggregate rewind_to={n}, no single plane reported, called from {caller})"
2624            )
2625            .into());
2626        }
2627        for index in 0..self.plane_count() {
2628            self.set_plane_len(e, index, n)?;
2629        }
2630        Ok(())
2631    }
2632
2633    fn can_rewind_to(&self, n: usize) -> bool {
2634        (0..self.plane_count()).all(|index| {
2635            self.plane(index)
2636                .0
2637                .ring
2638                .as_ref()
2639                .is_none_or(|ring| ring.can_rewind_to(n))
2640        })
2641    }
2642
2643    /// Pre-arm ring headroom for `rows` upcoming DEVICE-COUNTER appends (the dcw draft arm):
2644    /// a captured chain cannot rebase mid-replay, so any rebase the coming appends could need
2645    /// happens HERE, host-side, before the capture warmups or the round's replays (the rebase
2646    /// arm of `prepare_kv_append` also refreshes the plane's `base_d` device mirror). No-op on
2647    /// flat planes and when the ring already has room; `len` is untouched either way.
2648    fn ensure_dcw_headroom(
2649        &mut self,
2650        e: &Engine,
2651        rows: usize,
2652    ) -> Result<(), Box<dyn std::error::Error>> {
2653        for index in 0..self.plane_count() {
2654            let (kv, _) = self.plane_mut(index);
2655            let Some(ring) = kv.ring.as_ref() else {
2656                continue;
2657            };
2658            let retain = memra_kv::swa_retain_from(kv.len, ring.window(), ring.base());
2659            e.prepare_kv_append(kv, retain, rows)?;
2660        }
2661        Ok(())
2662    }
2663}
2664
2665/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
2666/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
2667/// full weight reads per round — recomputing columns the verify had already produced
2668/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
2669/// to "after the first j verify columns" WITHOUT re-running the trunk:
2670/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
2671///   consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
2672///   to the first j iterations of the verify's scan — the kernel's t-loop carries state in
2673///   registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
2674///   pure-copy ring rebuild.
2675/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
2676///   column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
2677///   target: j <= t-1).
2678///   Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
2679///   decode-exact contract; verify-probe pins it), so rollback = len truncation.
2680struct GdnStash {
2681    qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
2682    q_l2: CudaSlice<f32>,
2683    k_l2: CudaSlice<f32>,
2684    v_g: CudaSlice<f32>, // [t, num_v, d_state]
2685    g_log: CudaSlice<f32>,
2686    beta: CudaSlice<f32>, // [t, num_v]
2687}
2688pub(crate) struct VerifyCkpt {
2689    gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
2690    #[allow(clippy::type_complexity)]
2691    // allow: one-shot composite type; naming it would hide the shape that matters at the call site
2692    cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
2693}
2694/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
2695pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
2696
2697/// Engine-bundle slice 3 (DSF-ROUNDCOST-20260820 §2 row 4 / §5 rank 1): bucketed CUDA
2698/// graphs for the dspark verify's LINEAR-layer segments. The measured verify is ~2,800
2699/// eager launches whose residual cost is DEVICE-side per-launch overhead (slice 2 proved
2700/// host dispatch is not the binder: fully-deferred dispatch bought ~0 wall). The 48 GDN
2701/// layers between full-attention layers are shape-static given vt — no positions, no
2702/// t_kv, state addressed through pointer tables — so runs of them capture per
2703/// (segment, vt) and replay as ONE graph launch each. Full-attention layers stay eager
2704/// (their per-row append/fa arm picks are t_kv-driven — the exec-update extension).
2705///
2706/// Per round out-of-graph: one pointer-table refresh (gdn ping-pong moves the canonical
2707/// handles), one input-staging copy per segment, host parity bookkeeping. Captured via
2708/// `capture_graph_retained` (2 warmups + capture, keeper retains warmup transients so
2709/// pool addresses stay stable); the warmups EXECUTE, so segment conv/ssm state is saved
2710/// before and restored after — the graph's first real launch starts from the exact
2711/// pre-round state. The ckpt column stash rides persistent slabs (written inside the
2712/// graph as memcpy nodes); commit reads them via `dspark_commit_prefix_slab`.
2713/// `MEMRA_DSPARK_VERIFY_GRAPH=0` reverts to the eager walk (byte-identical body).
2714pub(crate) struct DsparkVerifyGraphs {
2715    /// Linear-attention layer indices ascending; `lin_pos[il]` = index into the vecs.
2716    lin: Vec<usize>,
2717    lin_pos: std::collections::HashMap<usize, usize>,
2718    /// [n_lin x 6] pointer table (conv, s0, s1, conv, s1, s0 per layer), refreshed per
2719    /// verify from the live handles; layer il's slice starts at lin_pos[il]*6.
2720    table_all: CudaSlice<u64>,
2721    host_table: Vec<u64>,
2722    /// Persistent per-layer ckpt stash slabs: row r of the verify at slab offset
2723    /// r*words. Shared by every (segment, vt) bucket — one verify runs at a time.
2724    stash_conv: Vec<CudaSlice<f32>>,
2725    stash_ssm: Vec<CudaSlice<f32>>,
2726    conv_words: usize,
2727    ssm_words: usize,
2728    /// Per-vt input/output staging (stable addresses the graphs bake).
2729    stage: std::collections::HashMap<usize, (CudaSlice<f32>, CudaSlice<f32>)>,
2730    /// Per-vt dflash tap-sink buffers — the captured segments bake the tap dst address,
2731    /// so the sink buffer must live (and persist) with the graphs, not with the round.
2732    pub(crate) tap_bufs: std::collections::HashMap<usize, CudaSlice<f32>>,
2733    graphs: std::collections::HashMap<(usize, usize), DsparkSegGraph>,
2734    /// Warmup-corruption guard scratch: pre-capture conv/ssm of every linear layer
2735    /// (sized n_lin — the slice-4c full-verify warmups execute the whole walk).
2736    save_conv: CudaSlice<f32>,
2737    save_ssm: CudaSlice<f32>,
2738    max_run: usize,
2739    n_embd: usize,
2740    /// Set by the verify walk: this round's linear ckpt lives in the slabs (the caller
2741    /// commits through `dspark_commit_prefix_slab` instead of the cols arm).
2742    pub(crate) round_slab: bool,
2743    // ---- slice 4c: full-verify single graph per (vt, rung) ----
2744    /// Full-attention layer indices ascending; `fa_pos[il]` = index into the vec.
2745    fa: Vec<usize>,
2746    fa_pos: std::collections::HashMap<usize, usize>,
2747    /// [n_fa x 2 x t_cap] interleaved (k,v) base-pointer pairs, refreshed per verify;
2748    /// layer il's slice starts at `fa_pos[il] * 2 * t_cap` (the seqs twins read pairs
2749    /// [2z], z < t <= t_cap, so one t_cap-sized table serves every vt).
2750    fa_table: CudaSlice<u64>,
2751    fa_host_table: Vec<u64>,
2752    t_cap: usize,
2753    /// Per-vt position staging for the captured bodies — contents refreshed per round
2754    /// (rope reads row r; the seqs twins derive append slot and T_kv per z from it).
2755    pos_stage: std::collections::HashMap<usize, CudaSlice<i32>>,
2756    /// Full-verify graphs keyed (vt, rung_end, hi).
2757    full: std::collections::HashMap<(usize, usize, usize), DsparkSegGraph>,
2758    /// Largest n with every layer in [0, n) linear or full-attention (walk coverage).
2759    covered: usize,
2760    /// Every layer in [0, n) is linear or full-attention (no MLA/unknown mixers) — the
2761    /// full-verify capture walks all of them.
2762    walk_uniform: bool,
2763    /// Last `(captures, device graph-mem reserved bytes)` reading taken by
2764    /// `HybridModel::dspark_vg_admission_debt` — the two-point base of the MARGINAL debt
2765    /// projection (see `dspark_vg_debt_projection`; a mean-based reading extrapolated the
2766    /// pool's one-time shared allocation and reserved 8.5 GB of phantom VRAM).
2767    debt_obs: Option<(usize, usize)>,
2768}
2769
2770struct DsparkSegGraph {
2771    graph: cudarc::driver::CudaGraph,
2772    _keeper: Vec<Box<dyn std::any::Any + Send>>,
2773}
2774
2775/// Per-call arguments of [`HybridModel::qwen35_tparallel_fa_layer`] — one struct so the
2776/// eager walk and the slice-4c captured full-verify graphs hand the SAME body its two
2777/// modes without a second copy of the math.
2778pub(crate) struct FaLayerArgs<'a> {
2779    /// [T] per-row positions (device): rope reads them row-indexed; the seqs twins read
2780    /// them per-z (append slot = pos, T_kv = pos + 1).
2781    pub pos_d: &'a CudaSlice<i32>,
2782    /// Verify-level lazy per-row 1-element position buffers — only the per-row fallback
2783    /// arm builds/uses them (graph mode refuses that arm).
2784    pub pos_rows: &'a mut Option<Vec<CudaSlice<i32>>>,
2785    pub pos0: usize,
2786    pub seqs_append: bool,
2787    pub batch_fa_on: bool,
2788    /// Some((kv pointer table, offset-in-u64s, rung_end)) = captured-graph mode.
2789    pub graph_cap: Option<(&'a CudaSlice<u64>, usize, usize)>,
2790    /// ROUND-STREAM (lane/draftcost-moe, v0.100 train merge): Some((token stream, device
2791    /// round counter)) routes the FA attend through the dc rows kernels and the Linear
2792    /// mixer through `linear_attn_verify_t` (the stream arms the old inline body carried).
2793    /// Never armed together with `graph_cap` (the verify-level merge guard refuses).
2794    pub stream: Option<(&'a CudaSlice<u32>, &'a CudaSlice<i32>)>,
2795    /// VerifyCkpt for the stream-Linear arm's GdnStash install; None in graph mode and
2796    /// for FA layers that never touch it.
2797    pub ckpt: Option<&'a mut VerifyCkpt>,
2798}
2799
2800// SAFETY: `CudaGraph` is not marked Send by cudarc because its raw driver handles carry
2801// no automatic trait; CUDA driver graph handles are context-scoped rather than
2802// OS-thread-affine (the SpecPipeSessionPtr precedent above). The ctx lives in
2803// `HybridModel::dspark_vgraphs` behind a Mutex and every touch happens on the engine's
2804// single decode-stream thread.
2805unsafe impl Send for DsparkVerifyGraphs {}
2806
2807impl DsparkVerifyGraphs {
2808    /// Live capture count (segment + full graphs) — the denominator of
2809    /// [`dspark_vg_debt_projection`]'s observed bytes/capture mean.
2810    pub(crate) fn captures(&self) -> usize {
2811        self.graphs.len() + self.full.len()
2812    }
2813
2814    /// Take the marginal-growth debt reading and record this observation for the next one.
2815    /// Called under the pool mutex by `HybridModel::dspark_vg_admission_debt`.
2816    pub(crate) fn admission_debt(&mut self, reserved_bytes: usize) -> usize {
2817        let captures = self.captures();
2818        let debt =
2819            dspark_vg_debt_projection(captures, dspark_vg_cap(), reserved_bytes, self.debt_obs);
2820        if captures > 0 {
2821            match self.debt_obs {
2822                Some((c0, _)) if captures <= c0 => {}
2823                _ => self.debt_obs = Some((captures, reserved_bytes)),
2824            }
2825        }
2826        debt
2827    }
2828
2829    /// Build for this cache's shape. None when there are no linear layers, sizes are
2830    /// non-uniform, or the trunk keeps a gemma4 config (never on the qwen35 family).
2831    pub(crate) fn new(
2832        e: &Engine,
2833        cache: &Cache,
2834        t_max: usize,
2835        n_embd: usize,
2836    ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
2837        let lin: Vec<usize> = (0..cache.recur.len())
2838            .filter(|&il| cache.recur[il].is_some())
2839            .collect();
2840        if lin.is_empty() || t_max < 2 {
2841            return Ok(None);
2842        }
2843        let first = cache.recur[lin[0]].as_ref().unwrap();
2844        let (conv_words, ssm_words) = (first.conv_state.len(), first.ssm_state.len());
2845        for &il in &lin {
2846            let rl = cache.recur[il].as_ref().unwrap();
2847            if rl.conv_state.len() != conv_words || rl.ssm_state.len() != ssm_words {
2848                return Ok(None);
2849            }
2850        }
2851        let n = lin.len();
2852        let mut lin_pos = std::collections::HashMap::with_capacity(n);
2853        for (k, &il) in lin.iter().enumerate() {
2854            lin_pos.insert(il, k);
2855        }
2856        // longest run of consecutive linear layers (save-scratch sizing)
2857        let mut max_run = 1usize;
2858        let mut run = 1usize;
2859        for w in lin.windows(2) {
2860            if w[1] == w[0] + 1 {
2861                run += 1;
2862                max_run = max_run.max(run);
2863            } else {
2864                run = 1;
2865            }
2866        }
2867        let rows = t_max - 1;
2868        let mut stash_conv = Vec::with_capacity(n);
2869        let mut stash_ssm = Vec::with_capacity(n);
2870        for _ in 0..n {
2871            stash_conv.push(e.uninit(rows * conv_words)?);
2872            stash_ssm.push(e.uninit(rows * ssm_words)?);
2873        }
2874        let host_table = vec![0u64; n * 6];
2875        let table_all = e.htod_u64(&host_table)?;
2876        // slice 4c: full-attention census for the full-verify graphs.
2877        let fa: Vec<usize> = (0..cache.kv.len())
2878            .filter(|&il| cache.kv[il].is_some())
2879            .collect();
2880        let mut fa_pos = std::collections::HashMap::with_capacity(fa.len());
2881        for (k, &il) in fa.iter().enumerate() {
2882            fa_pos.insert(il, k);
2883        }
2884        let n_layers = cache.kv.len().max(cache.recur.len());
2885        // exactly one of (linear state, kv cache) per layer — no MLA/unknown mixers.
2886        let walk_uniform = (0..n_layers).all(|il| {
2887            cache.recur.get(il).is_some_and(|r| r.is_some())
2888                != cache.kv.get(il).is_some_and(|k| k.is_some())
2889        });
2890        // Contiguous covered prefix: the largest n such that every layer in [0, n) is
2891        // linear or full-attention. The TRUNK walk is [0, layers.len()) and the cache
2892        // vecs can carry EXTRA state slots past it (the q38 export keeps the MTP head
2893        // layer's kv at the tail — hi == lin+fa never held, the s4c battery's zero
2894        // 'full' captures). The full-graph guard is walk coverage, not slot arithmetic.
2895        let covered = (0..n_layers)
2896            .take_while(|il| lin_pos.contains_key(il) || fa_pos.contains_key(il))
2897            .count();
2898        let t_cap = t_max;
2899        let fa_host_table = vec![0u64; fa.len() * 2 * t_cap];
2900        let fa_table = e.htod_u64(&fa_host_table)?;
2901        Ok(Some(Self {
2902            lin,
2903            lin_pos,
2904            table_all,
2905            host_table,
2906            stash_conv,
2907            stash_ssm,
2908            conv_words,
2909            ssm_words,
2910            stage: std::collections::HashMap::new(),
2911            tap_bufs: std::collections::HashMap::new(),
2912            graphs: std::collections::HashMap::new(),
2913            save_conv: e.uninit(n * conv_words)?,
2914            save_ssm: e.uninit(n * ssm_words)?,
2915            max_run,
2916            n_embd,
2917            round_slab: false,
2918            fa,
2919            fa_pos,
2920            fa_table,
2921            fa_host_table,
2922            t_cap,
2923            pos_stage: std::collections::HashMap::new(),
2924            full: std::collections::HashMap::new(),
2925            covered,
2926            walk_uniform,
2927            debt_obs: None,
2928        }))
2929    }
2930
2931    /// Rebuild the pointer tables from the live handles (once per verify — the gdn
2932    /// ping-pong swaps the canonical/alt handles between rounds; a fresh generation's
2933    /// cache buffers land at new addresses; a stale table would read the wrong state).
2934    pub(crate) fn refresh_tables(
2935        &mut self,
2936        e: &Engine,
2937        cache: &Cache,
2938    ) -> Result<(), Box<dyn std::error::Error>> {
2939        use cudarc::driver::DevicePtr;
2940        {
2941            let s = &e.gpu.stream();
2942            for (k, &il) in self.lin.iter().enumerate() {
2943                let rl = cache.recur[il].as_ref().unwrap();
2944                let (pc, _g0) = rl.conv_state.device_ptr(s);
2945                let (p0, _g1) = rl.ssm_state.device_ptr(s);
2946                let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
2947                let o = k * 6;
2948                self.host_table[o] = pc;
2949                self.host_table[o + 1] = p0;
2950                self.host_table[o + 2] = p1;
2951                self.host_table[o + 3] = pc;
2952                self.host_table[o + 4] = p1;
2953                self.host_table[o + 5] = p0;
2954            }
2955            for (k, &il) in self.fa.iter().enumerate() {
2956                let kvl = cache.kv[il].as_ref().unwrap();
2957                let (pk, _g0) = kvl.k.device_ptr(s);
2958                let (pv, _g1) = kvl.v.device_ptr(s);
2959                let o = k * 2 * self.t_cap;
2960                for z in 0..self.t_cap {
2961                    self.fa_host_table[o + 2 * z] = pk;
2962                    self.fa_host_table[o + 2 * z + 1] = pv;
2963                }
2964            }
2965        }
2966        e.htod_u64_into(&self.host_table, &mut self.table_all)?;
2967        if !self.fa_host_table.is_empty() {
2968            e.htod_u64_into(&self.fa_host_table, &mut self.fa_table)?;
2969        }
2970        Ok(())
2971    }
2972
2973    /// Slice 4c eligibility: Some(rung_end) when this round can replay (or capture) a
2974    /// full-verify graph — the whole walk [lo, hi) is covered, every layer is linear or
2975    /// full-attention, and ALL of the round's per-row t_kv values take the v4-seqs arm
2976    /// on ONE `fa_split_keys` ladder step that the rung also sits on (the straddle law;
2977    /// both gates are t_kv intervals, so ends-inside means all-inside). The rung is the
2978    /// round's next power of two — grid/partial sizing only (`n_splits_max` is pure
2979    /// stride; splits >= ns_eff write the empty partial the combine never reads), so one
2980    /// captured graph is bit-identical for every round the rung covers.
2981    #[allow(clippy::too_many_arguments)]
2982    pub(crate) fn full_rung(
2983        &self,
2984        model: &crate::hybrid::HybridModel,
2985        cache: &Cache,
2986        lo: usize,
2987        hi: usize,
2988        t: usize,
2989        seqs_arms_on: bool,
2990    ) -> Option<usize> {
2991        if std::env::var("MEMRA_DSPARK_FULLG_DEBUG").as_deref() == Ok("1") {
2992            static ONCE: std::sync::Once = std::sync::Once::new();
2993            let len0 = self
2994                .fa
2995                .first()
2996                .and_then(|&il| cache.kv[il].as_ref())
2997                .map(|k| k.len);
2998            ONCE.call_once(|| {
2999                eprintln!(
3000                    "[fullg-debug] walk_uniform={} covered={} seqs_arms_on={} fa_rows_on={} t={} lo={} hi={} lin={} fa={} t_cap={} len0={:?}",
3001                    self.walk_uniform, self.covered, seqs_arms_on, dspark_fa_rows_on(), t, lo, hi,
3002                    self.lin.len(), self.fa.len(), self.t_cap, len0
3003                );
3004            });
3005        }
3006        if !self.walk_uniform
3007            || !seqs_arms_on
3008            || !dspark_fa_rows_on()
3009            || t < 2
3010            || lo != 0
3011            || hi > self.covered
3012            || t > self.t_cap
3013            || self.fa.is_empty()
3014        {
3015            return None;
3016        }
3017        let cfg = &model.cfg;
3018        let head_dim_global = cfg.head_dim_k as usize;
3019        let nkv = cfg.n_head_kv as usize;
3020        let kvl0 = cache.kv[self.fa[0]].as_ref().unwrap();
3021        // the z-batched twins read stacked rows at the cache's kv dims — must equal the
3022        // projection stride (the body's guard, hoisted so ineligible models fall back
3023        // instead of refusing mid-capture).
3024        let geom = cfg.full_attention_geometry_at(self.fa[0] as u32);
3025        let kv_dim = geom.n_head_kv as usize * geom.head_dim_k as usize;
3026        if kvl0.kv_dim_k != kv_dim || kvl0.kv_dim_v != kv_dim {
3027            return None;
3028        }
3029        let len0 = kvl0.len;
3030        let (t_kv_first, t_kv_last) = (len0 + 1, len0 + t);
3031        if !crate::fa_seqs_eligible(t_kv_first, head_dim_global)
3032            || !crate::fa_seqs_eligible(t_kv_last, head_dim_global)
3033            || crate::fa_split_keys(t_kv_first, nkv) != crate::fa_split_keys(t_kv_last, nkv)
3034        {
3035            return None;
3036        }
3037        let rung = t_kv_last.next_power_of_two().max(256);
3038        if crate::fa_split_keys(rung, nkv) != crate::fa_split_keys(t_kv_last, nkv) {
3039            return None;
3040        }
3041        Some(rung)
3042    }
3043
3044    /// Run the WHOLE verify walk [lo, hi) as one captured graph at (vt=t, rung): stage
3045    /// the residual + refresh the per-vt position staging, capture on first encounter
3046    /// (2 executing warmups bracketed by a full linear-state save/restore; KV warmup
3047    /// appends write the exact slots the replay writes — idempotent), launch, then apply
3048    /// the host bookkeeping the captured body skipped (per-linear-layer parity swap for
3049    /// odd t, per-fa-layer len bump). Returns the fresh residual.
3050    #[allow(clippy::too_many_arguments)]
3051    #[allow(clippy::map_entry)] // allow: the init body is fallible (`?`); Entry::or_insert_with cannot propagate errors
3052    pub(crate) fn run_full(
3053        &mut self,
3054        model: &crate::hybrid::HybridModel,
3055        e: &Engine,
3056        lo: usize,
3057        hi: usize,
3058        x: &CudaSlice<f32>,
3059        t: usize,
3060        pos0: usize,
3061        rung: usize,
3062        cache: &mut Cache,
3063    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3064        let n_embd = self.n_embd;
3065        if !self.stage.contains_key(&t) {
3066            let xin = e.uninit(t * n_embd)?;
3067            let xout = e.uninit(t * n_embd)?;
3068            self.stage.insert(t, (xin, xout));
3069        }
3070        if !self.pos_stage.contains_key(&t) {
3071            self.pos_stage.insert(t, e.htod_i32(&vec![0i32; t])?);
3072        }
3073        // Per-round refresh: position contents + input staging (both addresses are baked
3074        // by the captured bodies; only their CONTENTS change round to round).
3075        {
3076            let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
3077            let pb = self.pos_stage.get_mut(&t).unwrap();
3078            e.htod_i32_into(pb, &pos_host)?;
3079            let (xin, _) = self.stage.get_mut(&t).unwrap();
3080            e.copy_into(xin, 0, x, t * n_embd)?;
3081        }
3082        let key = (t, rung, hi);
3083        if !self.full.contains_key(&key) {
3084            // The warmups EXECUTE the whole walk on live state — save every linear
3085            // layer's conv + canonical ssm first, restore after (KV needs no restore:
3086            // graph mode never bumps host lens and the appends write this round's own
3087            // slots).
3088            for (k, &il) in self.lin.iter().enumerate() {
3089                let rl = cache.recur[il].as_ref().unwrap();
3090                e.copy_into(
3091                    &mut self.save_conv,
3092                    k * self.conv_words,
3093                    &rl.conv_state,
3094                    self.conv_words,
3095                )?;
3096                e.copy_into(
3097                    &mut self.save_ssm,
3098                    k * self.ssm_words,
3099                    &rl.ssm_state,
3100                    self.ssm_words,
3101                )?;
3102            }
3103            let (graph, keeper) = {
3104                let table_all = &self.table_all;
3105                let lin_pos = &self.lin_pos;
3106                let fa_pos = &self.fa_pos;
3107                let fa_table = &self.fa_table;
3108                let t_cap = self.t_cap;
3109                let stash_conv = &mut self.stash_conv;
3110                let stash_ssm = &mut self.stash_ssm;
3111                let pos_d: &CudaSlice<i32> = &self.pos_stage[&t];
3112                let (xin, xout) = self
3113                    .stage
3114                    .get_mut(&t)
3115                    .map(|(a, b)| (&*a, b))
3116                    .expect("stage bucket created above");
3117                let cache_ref: &mut Cache = cache;
3118                let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
3119                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
3120                } else {
3121                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
3122                };
3123                e.capture_graph_retained_flags(iflag, move |e| {
3124                    let mut xc: Option<CudaSlice<f32>> = None;
3125                    for il in lo..hi {
3126                        let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
3127                        let nx = if let Some(&k) = lin_pos.get(&il) {
3128                            model.qwen35_tparallel_linear_layer(
3129                                e,
3130                                il,
3131                                xr,
3132                                t,
3133                                cache_ref,
3134                                None,
3135                                Some((&mut stash_conv[k], &mut stash_ssm[k])),
3136                                Some((table_all, k * 6)),
3137                            )?
3138                        } else if let Some(&kf) = fa_pos.get(&il) {
3139                            let mut no_rows: Option<Vec<CudaSlice<i32>>> = None;
3140                            model.qwen35_tparallel_fa_layer(
3141                                e,
3142                                il,
3143                                xr,
3144                                t,
3145                                cache_ref,
3146                                FaLayerArgs {
3147                                    pos_d,
3148                                    pos_rows: &mut no_rows,
3149                                    pos0,
3150                                    seqs_append: true,
3151                                    batch_fa_on: true,
3152                                    graph_cap: Some((fa_table, kf * 2 * t_cap, rung)),
3153                                    stream: None,
3154                                    ckpt: None,
3155                                },
3156                            )?
3157                        } else {
3158                            return Err(format!(
3159                                "run_full: layer {il} is neither linear nor full-attention"
3160                            )
3161                            .into());
3162                        };
3163                        xc = Some(nx);
3164                    }
3165                    e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
3166                    Ok(())
3167                })?
3168            };
3169            // Undo the net host parity motion of the 3 body runs (each run swaps iff t
3170            // is odd -> 3 runs = net one swap), then restore the device state the
3171            // warmups consumed (walk scope only — layers past hi never executed). The
3172            // launch below then behaves exactly like one run.
3173            if t % 2 == 1 {
3174                for &il in &self.lin {
3175                    if il < lo || il >= hi {
3176                        continue;
3177                    }
3178                    let rl = cache.recur[il].as_mut().unwrap();
3179                    std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3180                }
3181            }
3182            for (k, &il) in self.lin.iter().enumerate() {
3183                if il < lo || il >= hi {
3184                    continue;
3185                }
3186                let rl = cache.recur[il].as_mut().unwrap();
3187                let (cw, sw) = (self.conv_words, self.ssm_words);
3188                {
3189                    let sv = e.view(&self.save_conv, self.lin.len() * cw);
3190                    let win = sv.slice(k * cw..(k + 1) * cw);
3191                    e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
3192                }
3193                {
3194                    let sv = e.view(&self.save_ssm, self.lin.len() * sw);
3195                    let win = sv.slice(k * sw..(k + 1) * sw);
3196                    e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
3197                }
3198            }
3199            if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1")
3200                && let Ok(c) = crate::graph_update::node_census(&graph)
3201            {
3202                eprintln!("[dspark-vg-census] full vt={t} rung={rung} {c:?}");
3203            }
3204            self.full.insert(
3205                key,
3206                DsparkSegGraph {
3207                    graph,
3208                    _keeper: keeper,
3209                },
3210            );
3211        }
3212        self.full[&key].graph.launch()?;
3213        // Host bookkeeping for the replayed body (captured host code does not re-run):
3214        // gdn parity swap per linear layer (t odd), kv len bump per fa layer — scoped
3215        // to the WALK [lo, hi): the cache can carry extra state slots past it (the MTP
3216        // head layer's kv) that the walk never touches.
3217        if t % 2 == 1 {
3218            for &il in &self.lin {
3219                if il < lo || il >= hi {
3220                    continue;
3221                }
3222                let rl = cache.recur[il].as_mut().unwrap();
3223                std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3224            }
3225        }
3226        for &il in &self.fa {
3227            if il < lo || il >= hi {
3228                continue;
3229            }
3230            cache.kv[il].as_mut().unwrap().len += t;
3231        }
3232        let (_, xout) = self.stage.get(&t).unwrap();
3233        let mut out = e.uninit(t * n_embd)?;
3234        e.copy_into(&mut out, 0, xout, t * n_embd)?;
3235        Ok(out)
3236    }
3237
3238    /// Run layers [start, end) (all linear) as one captured graph at this vt: stage the
3239    /// residual into the bucket's x_in, capture on first encounter (2 executing warmups
3240    /// bracketed by a segment state save/restore), launch, then apply the host parity
3241    /// bookkeeping the captured body would have done. Returns the fresh residual.
3242    #[allow(clippy::too_many_arguments)]
3243    #[allow(clippy::map_entry)] // allow: the init body is fallible (`?`); Entry::or_insert_with cannot propagate errors
3244    fn run_segment(
3245        &mut self,
3246        model: &crate::hybrid::HybridModel,
3247        e: &Engine,
3248        start: usize,
3249        end: usize,
3250        x: &CudaSlice<f32>,
3251        t: usize,
3252        cache: &mut Cache,
3253    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3254        let n_embd = self.n_embd;
3255        debug_assert!(end - start <= self.max_run);
3256        if !self.stage.contains_key(&t) {
3257            let xin = e.uninit(t * n_embd)?;
3258            let xout = e.uninit(t * n_embd)?;
3259            self.stage.insert(t, (xin, xout));
3260        }
3261        // Stage the residual at the bucket's baked input address.
3262        {
3263            let (xin, _) = self.stage.get_mut(&t).unwrap();
3264            e.copy_into(xin, 0, x, t * n_embd)?;
3265        }
3266        let key = (start, t);
3267        if !self.graphs.contains_key(&key) {
3268            // The 2 warmups EXECUTE the segment on live state — save conv + the canonical
3269            // ssm of every segment layer first, restore after, so the graph's first real
3270            // launch starts from the exact pre-round state (bytes gated e2e).
3271            for (k, il) in (start..end).enumerate() {
3272                let rl = cache.recur[il].as_ref().unwrap();
3273                e.copy_into(
3274                    &mut self.save_conv,
3275                    k * self.conv_words,
3276                    &rl.conv_state,
3277                    self.conv_words,
3278                )?;
3279                e.copy_into(
3280                    &mut self.save_ssm,
3281                    k * self.ssm_words,
3282                    &rl.ssm_state,
3283                    self.ssm_words,
3284                )?;
3285            }
3286            let (graph, keeper) = {
3287                let table_all = &self.table_all;
3288                let lin_pos = &self.lin_pos;
3289                let stash_conv = &mut self.stash_conv;
3290                let stash_ssm = &mut self.stash_ssm;
3291                let (xin, xout) = self
3292                    .stage
3293                    .get_mut(&t)
3294                    .map(|(a, b)| (&*a, b))
3295                    .expect("stage bucket created above");
3296                let cache_ref: &mut Cache = cache;
3297                // Slice 4 (fa-execupdate lane): USE_NODE_PRIORITY instead of
3298                // AUTO_FREE_ON_LAUNCH. The slice-3 measured limiter was AUTO_FREE's
3299                // launch-time mem-pool scan — 25.6 us per cuGraphLaunch x 16 segments
3300                // = ~0.41 ms/round, most of the eager-launch savings. The captured
3301                // body's cuMemAllocAsync transients are BALANCED by in-graph frees
3302                // (every transient drops inside the capture region — the generic
3303                // capture path's census precedent, 1589/1589), so AUTO_FREE has
3304                // nothing to reclaim and the graph is legal to instantiate without
3305                // it; PRIORITY is the flag the gemma slotted door ships for exactly
3306                // this reason (both alternatives drop the scan; UPLOAD via
3307                // cuGraphInstantiateWithFlags is WithParams-only and refused).
3308                // MEMRA_DSPARK_VG_AUTOFREE=1 reverts; MEMRA_GRAPH_CENSUS=1 prints
3309                // the node census at capture (the ALLOC==FREE receipt).
3310                let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
3311                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
3312                } else {
3313                    cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
3314                };
3315                e.capture_graph_retained_flags(iflag, move |e| {
3316                    let mut xc: Option<CudaSlice<f32>> = None;
3317                    for il in start..end {
3318                        let k = lin_pos[&il];
3319                        let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
3320                        let nx = model.qwen35_tparallel_linear_layer(
3321                            e,
3322                            il,
3323                            xr,
3324                            t,
3325                            cache_ref,
3326                            None,
3327                            Some((&mut stash_conv[k], &mut stash_ssm[k])),
3328                            Some((table_all, k * 6)),
3329                        )?;
3330                        xc = Some(nx);
3331                    }
3332                    e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
3333                    Ok(())
3334                })?
3335            };
3336            // Undo the net host parity motion of the 3 body runs (each run swaps iff t
3337            // is odd -> 3 runs = net one swap), then restore the device state the
3338            // warmups consumed. The launch below then behaves exactly like one run.
3339            if t % 2 == 1 {
3340                for il in start..end {
3341                    let rl = cache.recur[il].as_mut().unwrap();
3342                    std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3343                }
3344            }
3345            for (k, il) in (start..end).enumerate() {
3346                let rl = cache.recur[il].as_mut().unwrap();
3347                let (cw, sw) = (self.conv_words, self.ssm_words);
3348                {
3349                    let sv = e.view(&self.save_conv, self.lin.len() * cw);
3350                    let win = sv.slice(k * cw..(k + 1) * cw);
3351                    e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
3352                }
3353                {
3354                    let sv = e.view(&self.save_ssm, self.lin.len() * sw);
3355                    let win = sv.slice(k * sw..(k + 1) * sw);
3356                    e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
3357                }
3358            }
3359            if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1")
3360                && let Ok(c) = crate::graph_update::node_census(&graph)
3361            {
3362                eprintln!("[dspark-vg-census] seg={start}..{end} vt={t} {c:?}");
3363            }
3364            self.graphs.insert(
3365                key,
3366                DsparkSegGraph {
3367                    graph,
3368                    _keeper: keeper,
3369                },
3370            );
3371        }
3372        self.graphs[&key].graph.launch()?;
3373        // Host parity bookkeeping for the replayed body (the captured host swaps do not
3374        // re-run at replay).
3375        if t % 2 == 1 {
3376            for il in start..end {
3377                let rl = cache.recur[il].as_mut().unwrap();
3378                std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3379            }
3380        }
3381        let (_, xout) = self.stage.get(&t).unwrap();
3382        let mut out = e.uninit(t * n_embd)?;
3383        e.copy_into(&mut out, 0, xout, t * n_embd)?;
3384        Ok(out)
3385    }
3386
3387    /// Pool freeze check (`dspark_vg_cap`): below the ceiling new keys may capture.
3388    fn can_capture(&self) -> bool {
3389        self.graphs.len() + self.full.len() < dspark_vg_cap()
3390    }
3391
3392    /// Round-atomic segment-door readiness: TRUE when this round's walk can ride the
3393    /// per-(segment, vt) graphs without a NEW capture past the pool ceiling — every
3394    /// linear run in [lo, hi) already has its (run_start, t) key, or capture is still
3395    /// allowed. FALSE sends the WHOLE round down the eager cols-ckpt walk: a partial
3396    /// refusal would stash some layers in the ctx slabs and others in the round's cols
3397    /// while one commit reads only one of them.
3398    pub(crate) fn segments_ready(
3399        &self,
3400        model: &crate::hybrid::HybridModel,
3401        lo: usize,
3402        hi: usize,
3403        t: usize,
3404    ) -> bool {
3405        if self.can_capture() {
3406            return true;
3407        }
3408        let mut il = lo;
3409        while il < hi {
3410            if matches!(model.layers[il].mixer, Mixer::Linear(_)) {
3411                let start = il;
3412                while il < hi && matches!(model.layers[il].mixer, Mixer::Linear(_)) {
3413                    il += 1;
3414                }
3415                if !self.graphs.contains_key(&(start, t)) {
3416                    return false;
3417                }
3418            } else {
3419                il += 1;
3420            }
3421        }
3422        true
3423    }
3424
3425    /// Widest verify window this pool was built for. A caller whose round exceeds it must
3426    /// take the eager walk: the stash slabs hold `t_capacity() - 1` column rows, and slicing
3427    /// past them is a panic rather than a refusal.
3428    pub(crate) fn t_capacity(&self) -> usize {
3429        self.t_cap
3430    }
3431
3432    /// Slab row (conv, ssm) device pointers + lengths for the commit restore of column
3433    /// `row` (0-based) of layer `il`. None for non-linear layers.
3434    pub(crate) fn slab_row(
3435        &self,
3436        e: &Engine,
3437        il: usize,
3438        row: usize,
3439    ) -> Option<(u64, u64, usize, usize)> {
3440        use cudarc::driver::DevicePtr;
3441        let k = *self.lin_pos.get(&il)?;
3442        let s = &e.gpu.stream();
3443        let (pc, _g0) = self.stash_conv[k].device_ptr(s);
3444        let (ps, _g1) = self.stash_ssm[k].device_ptr(s);
3445        Some((
3446            pc + (row * self.conv_words * 4) as u64,
3447            ps + (row * self.ssm_words * 4) as u64,
3448            self.conv_words,
3449            self.ssm_words,
3450        ))
3451    }
3452}
3453
3454impl VerifyCkpt {
3455    fn new(n_layer: usize) -> Self {
3456        VerifyCkpt {
3457            gdn: (0..n_layer).map(|_| None).collect(),
3458            cols: (0..n_layer).map(|_| None).collect(),
3459        }
3460    }
3461}
3462
3463/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
3464/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
3465/// a logical round number.
3466struct VerifyBoundaryTicket {
3467    rt: &'static crate::pp::PpNRt,
3468    caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
3469    slot: usize,
3470    pos0: usize,
3471    t: usize,
3472    payload: usize,
3473    n_st: usize,
3474    pipelined: bool,
3475    pp_anatomy: bool,
3476    pp_started: std::time::Instant,
3477    reverse_ms: f64,
3478    stage0_ms: f64,
3479    tx_ms: f64,
3480    trace: Option<SpecPipeTraceCtx>,
3481    _walk_owner: crate::pp::PpWalkLease,
3482}
3483
3484/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
3485/// increment-2 controller can also be armed by the server's fresh-process research door.
3486#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3487pub enum OptiForkGateMode {
3488    Disabled,
3489    Hit,
3490    Miss,
3491    Alternate,
3492    Abort,
3493    Controller,
3494}
3495
3496static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3497static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
3498    std::sync::atomic::AtomicU32::new(0);
3499static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3500static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3501static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3502static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3503static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3504static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3505static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3506static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3507static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3508static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
3509    std::sync::atomic::AtomicU64::new(0);
3510static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
3511    std::sync::atomic::AtomicU64::new(0);
3512static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3513
3514impl OptiForkGateMode {
3515    fn code(self) -> u8 {
3516        match self {
3517            Self::Disabled => 0,
3518            Self::Hit => 1,
3519            Self::Miss => 2,
3520            Self::Alternate => 3,
3521            Self::Abort => 4,
3522            Self::Controller => 5,
3523        }
3524    }
3525
3526    fn configured() -> Self {
3527        match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
3528            1 => Self::Hit,
3529            2 => Self::Miss,
3530            3 => Self::Alternate,
3531            4 => Self::Abort,
3532            5 => Self::Controller,
3533            _ => Self::Disabled,
3534        }
3535    }
3536
3537    fn action(self, generation: u64) -> OptiForkAction {
3538        match self {
3539            Self::Hit => OptiForkAction::Hit,
3540            Self::Miss => OptiForkAction::Miss,
3541            Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
3542            Self::Alternate => OptiForkAction::Miss,
3543            Self::Abort => OptiForkAction::Abort,
3544            Self::Disabled | Self::Controller => {
3545                unreachable!("non-forced mode cannot choose a forced fork action")
3546            }
3547        }
3548    }
3549
3550    fn is_forced(self) -> bool {
3551        matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
3552    }
3553}
3554
3555/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
3556pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
3557    OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
3558}
3559
3560/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
3561/// two-token draft-probability product. Serving can call this only through its explicit
3562/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
3563pub fn set_optipipe_controller_threshold(threshold: f32) {
3564    assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
3565    OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
3566    set_optipipe_gate_mode(OptiForkGateMode::Controller);
3567}
3568
3569#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3570pub struct OptiForkGateStats {
3571    pub attempts: u64,
3572    pub hits: u64,
3573    pub misses: u64,
3574    pub abort_drains: u64,
3575    pub refusals: u64,
3576    pub gate_checks: u64,
3577    pub gate_admits: u64,
3578    pub gate_rejects: u64,
3579    pub reconciles: u64,
3580    pub wasted_draft_tokens: u64,
3581    pub shadow_draft_tokens: u64,
3582    pub breaker_trips: u64,
3583}
3584
3585#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3586pub struct OptiForkStateIdentity {
3587    pub trunk_kv_bytes: usize,
3588    pub recurrent_bytes: usize,
3589    pub scratch_kv_bytes: usize,
3590    pub hidden_bytes: usize,
3591}
3592
3593pub fn reset_optipipe_gate_stats() {
3594    for counter in [
3595        &OPTI_FORK_ATTEMPTS,
3596        &OPTI_FORK_HITS,
3597        &OPTI_FORK_MISSES,
3598        &OPTI_FORK_ABORT_DRAINS,
3599        &OPTI_FORK_REFUSALS,
3600        &OPTI_GATE_CHECKS,
3601        &OPTI_GATE_ADMITS,
3602        &OPTI_GATE_REJECTS,
3603        &OPTI_RECONCILES,
3604        &OPTI_WASTED_DRAFT_TOKENS,
3605        &OPTI_SHADOW_DRAFT_TOKENS,
3606        &OPTI_BREAKER_TRIPS,
3607    ] {
3608        counter.store(0, std::sync::atomic::Ordering::Relaxed);
3609    }
3610}
3611
3612pub fn optipipe_gate_stats() -> OptiForkGateStats {
3613    let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
3614    OptiForkGateStats {
3615        attempts: load(&OPTI_FORK_ATTEMPTS),
3616        hits: load(&OPTI_FORK_HITS),
3617        misses: load(&OPTI_FORK_MISSES),
3618        abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
3619        refusals: load(&OPTI_FORK_REFUSALS),
3620        gate_checks: load(&OPTI_GATE_CHECKS),
3621        gate_admits: load(&OPTI_GATE_ADMITS),
3622        gate_rejects: load(&OPTI_GATE_REJECTS),
3623        reconciles: load(&OPTI_RECONCILES),
3624        wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
3625        shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
3626        breaker_trips: load(&OPTI_BREAKER_TRIPS),
3627    }
3628}
3629
3630#[derive(Clone, Copy, Debug)]
3631struct OptiControllerPolicy {
3632    threshold: f32,
3633    consecutive_misses: u8,
3634    breaker_tripped: bool,
3635}
3636
3637impl OptiControllerPolicy {
3638    fn configured() -> Self {
3639        Self {
3640            threshold: f32::from_bits(
3641                OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
3642            ),
3643            consecutive_misses: 0,
3644            breaker_tripped: false,
3645        }
3646    }
3647
3648    fn admit(&self, q_proxy: f32) -> bool {
3649        q_proxy.is_finite()
3650            && (0.0..=1.0).contains(&q_proxy)
3651            && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
3652    }
3653
3654    /// Returns true exactly when this resolution newly trips the three-miss breaker.
3655    fn resolve(&mut self, hit: bool) -> bool {
3656        // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
3657        // every optimistic opportunity, so the safety breaker is measured separately and must
3658        // not silently turn this arm into "three attempts then serial".
3659        if self.threshold == 0.0 {
3660            self.consecutive_misses = 0;
3661            return false;
3662        }
3663        if hit {
3664            self.consecutive_misses = 0;
3665            return false;
3666        }
3667        self.consecutive_misses = self.consecutive_misses.saturating_add(1);
3668        if !self.breaker_tripped && self.consecutive_misses >= 3 {
3669            self.breaker_tripped = true;
3670            return true;
3671        }
3672        false
3673    }
3674}
3675
3676#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3677enum OptiForkAction {
3678    Hit,
3679    Miss,
3680    Abort,
3681}
3682
3683#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3684struct OptiForkGeneration {
3685    id: u64,
3686    slot: usize,
3687}
3688
3689#[derive(Default)]
3690struct OptiForkGenerationTracker {
3691    next: u64,
3692    live: [Option<u64>; 2],
3693}
3694
3695impl OptiForkGenerationTracker {
3696    fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
3697        let generation = OptiForkGeneration {
3698            id: self.next,
3699            slot: (self.next & 1) as usize,
3700        };
3701        if let Some(live) = self.live[generation.slot] {
3702            return Err(format!(
3703                "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
3704                generation.slot,
3705            )
3706            .into());
3707        }
3708        self.next += 1;
3709        self.live[generation.slot] = Some(generation.id);
3710        Ok(generation)
3711    }
3712
3713    fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
3714        match self.live[generation.slot] {
3715            Some(id) if id == generation.id => {
3716                self.live[generation.slot] = None;
3717                Ok(())
3718            }
3719            other => Err(format!(
3720                "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
3721                generation.id, generation.slot,
3722            )
3723            .into()),
3724        }
3725    }
3726}
3727
3728struct OptiForkSeedGeneration {
3729    h_seed: CudaSlice<f32>,
3730    fill_prev: CudaSlice<f32>,
3731    scratch_len: usize,
3732}
3733
3734/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
3735/// generic cache helper accepts one device and therefore cannot copy GDN state split across
3736/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
3737/// device ownership.
3738fn opti_snapshot_stage_owned(
3739    e: &Engine,
3740    cache: &Cache,
3741    rt: &'static crate::pp::PpNRt,
3742    fence: &[usize],
3743) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
3744    let n = cache.kv.len();
3745    let mut snapshot = crate::cache::CacheSnapshot {
3746        kv_len: vec![None; n],
3747        tp_kv_len: vec![None; n],
3748        conv: (0..n).map(|_| None).collect(),
3749        ssm: (0..n).map(|_| None).collect(),
3750        pos: cache.pos,
3751    };
3752    opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
3753    Ok(snapshot)
3754}
3755
3756fn opti_snapshot_stage_owned_into(
3757    e: &Engine,
3758    cache: &Cache,
3759    rt: &'static crate::pp::PpNRt,
3760    fence: &[usize],
3761    snapshot: &mut crate::cache::CacheSnapshot,
3762) -> Result<(), Box<dyn std::error::Error>> {
3763    if fence.len() != rt.n_stages() + 1
3764        || snapshot.kv_len.len() != cache.kv.len()
3765        || snapshot.tp_kv_len.len() != cache.tp_kv.len()
3766    {
3767        return Err("optipipe stage-owned snapshot shape mismatch".into());
3768    }
3769    for stage in 0..rt.n_stages() {
3770        opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
3771    }
3772    snapshot.pos = cache.pos;
3773    Ok(())
3774}
3775
3776/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
3777/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
3778/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
3779/// either point would capture one side of the fork at the wrong generation.
3780fn opti_snapshot_one_stage_owned_into(
3781    e: &Engine,
3782    cache: &Cache,
3783    rt: &'static crate::pp::PpNRt,
3784    fence: &[usize],
3785    stage: usize,
3786    snapshot: &mut crate::cache::CacheSnapshot,
3787) -> Result<(), Box<dyn std::error::Error>> {
3788    if fence.len() != rt.n_stages() + 1
3789        || snapshot.kv_len.len() != cache.kv.len()
3790        || snapshot.tp_kv_len.len() != cache.tp_kv.len()
3791        || stage >= rt.n_stages()
3792    {
3793        return Err("optipipe single-stage snapshot shape mismatch".into());
3794    }
3795    let _scope = rt.enter(stage);
3796    let owner = rt.engine(stage, e);
3797    for il in fence[stage]..fence[stage + 1] {
3798        snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
3799        snapshot.tp_kv_len[il] = cache.tp_kv[il]
3800            .as_ref()
3801            .map(crate::tp::ResidentTpKvCache::committed_len);
3802        match &cache.recur[il] {
3803            Some(recur) => {
3804                match snapshot.conv[il].as_mut() {
3805                    Some(dst) => {
3806                        owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
3807                    }
3808                    None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
3809                }
3810                match snapshot.ssm[il].as_mut() {
3811                    Some(dst) => {
3812                        owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
3813                    }
3814                    None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
3815                }
3816            }
3817            None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
3818                return Err(
3819                    format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
3820                );
3821            }
3822            None => {}
3823        }
3824    }
3825    snapshot.pos = cache.pos;
3826    Ok(())
3827}
3828
3829/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
3830/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
3831/// resolve, so the reconcile tables and conditional restores are stage-local.
3832struct OptiForkState {
3833    mode: OptiForkGateMode,
3834    controller: Option<OptiControllerPolicy>,
3835    generations: OptiForkGenerationTracker,
3836    active_snapshot_slot: usize,
3837    alternate_snapshot: crate::cache::CacheSnapshot,
3838    seeds: [OptiForkSeedGeneration; 2],
3839    rt: &'static crate::pp::PpNRt,
3840    fence: [usize; 3],
3841    split: usize,
3842    len_ptrs: CudaSlice<u64>,
3843    saved_lens: CudaSlice<i32>,
3844    forced_acc: CudaSlice<u32>,
3845    valid: CudaSlice<u32>,
3846    stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
3847    logical_payload_bytes: [usize; 2],
3848}
3849
3850struct OptiForkTicket {
3851    generation: OptiForkGeneration,
3852    boundary: Option<VerifyBoundaryTicket>,
3853    drain: std::sync::Arc<cudarc::driver::CudaStream>,
3854    settled: bool,
3855}
3856
3857struct OptiControllerTicket {
3858    generation: OptiForkGeneration,
3859    boundary: Option<VerifyBoundaryTicket>,
3860    ckpt: Option<VerifyCkpt>,
3861    verify_tokens: [u32; 2],
3862    draft_prob: f32,
3863    eager_seed: Option<CudaSlice<f32>>,
3864    q_proxy: f32,
3865    scratch_len: usize,
3866    issued_at: std::time::Instant,
3867    drain: std::sync::Arc<cudarc::driver::CudaStream>,
3868    settled: bool,
3869}
3870
3871struct OptiControllerPrepared {
3872    verify_tokens: [u32; 2],
3873    draft_prob: f32,
3874    eager_seed: Option<CudaSlice<f32>>,
3875    q_proxy: f32,
3876    scratch_len: usize,
3877}
3878
3879impl OptiControllerTicket {
3880    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
3881        self.boundary
3882            .take()
3883            .expect("controller boundary ticket already consumed")
3884    }
3885
3886    fn take_ckpt(&mut self) -> VerifyCkpt {
3887        self.ckpt
3888            .take()
3889            .expect("controller verify checkpoint already consumed")
3890    }
3891
3892    fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
3893        self.eager_seed.take()
3894    }
3895
3896    fn settle(&mut self) {
3897        self.settled = true;
3898    }
3899}
3900
3901impl Drop for OptiControllerTicket {
3902    fn drop(&mut self) {
3903        if !self.settled {
3904            let _ = self.drain.synchronize();
3905            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3906        }
3907    }
3908}
3909
3910impl OptiForkTicket {
3911    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
3912        self.boundary
3913            .take()
3914            .expect("fork ticket boundary already consumed")
3915    }
3916
3917    fn settle(&mut self) {
3918        self.settled = true;
3919    }
3920}
3921
3922impl Drop for OptiForkTicket {
3923    fn drop(&mut self) {
3924        if !self.settled {
3925            let _ = self.drain.synchronize();
3926            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3927        }
3928    }
3929}
3930
3931impl OptiForkState {
3932    #[allow(clippy::too_many_arguments)]
3933    fn new(
3934        e: &Engine,
3935        cache: &Cache,
3936        mode: OptiForkGateMode,
3937        alternate_snapshot: crate::cache::CacheSnapshot,
3938        h_seed: &CudaSlice<f32>,
3939        fill_prev: &CudaSlice<f32>,
3940        rt: &'static crate::pp::PpNRt,
3941        split: usize,
3942        n_layer: usize,
3943    ) -> Result<Self, Box<dyn std::error::Error>> {
3944        let fence = [0, split, n_layer];
3945        let mut logical_payload_bytes = [0usize; 2];
3946        for stage in 0..2 {
3947            for il in fence[stage]..fence[stage + 1] {
3948                logical_payload_bytes[stage] += alternate_snapshot.conv[il]
3949                    .as_ref()
3950                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
3951                logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
3952                    .as_ref()
3953                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
3954            }
3955        }
3956        let seeds = [
3957            OptiForkSeedGeneration {
3958                h_seed: e.clone_dtod(h_seed)?,
3959                fill_prev: e.clone_dtod(fill_prev)?,
3960                scratch_len: 0,
3961            },
3962            OptiForkSeedGeneration {
3963                h_seed: e.clone_dtod(h_seed)?,
3964                fill_prev: e.clone_dtod(fill_prev)?,
3965                scratch_len: 0,
3966            },
3967        ];
3968        let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
3969            let _stage = rt.enter(0);
3970            let e0 = rt.engine(0, e);
3971            (
3972                crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
3973                e0.htod_i32(&vec![0; split])?,
3974                e0.alloc_u32_zeroed(2)?,
3975                e0.alloc_u32_zeroed(1)?,
3976                e0.stream(),
3977            )
3978        };
3979        logical_payload_bytes[0] += seeds
3980            .iter()
3981            .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
3982            .sum::<usize>();
3983        logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
3984            + saved_lens.len() * std::mem::size_of::<i32>()
3985            + forced_acc.len() * std::mem::size_of::<u32>()
3986            + valid.len() * std::mem::size_of::<u32>();
3987        Ok(Self {
3988            mode,
3989            controller: (mode == OptiForkGateMode::Controller)
3990                .then(OptiControllerPolicy::configured),
3991            generations: OptiForkGenerationTracker::default(),
3992            active_snapshot_slot: 0,
3993            alternate_snapshot,
3994            seeds,
3995            rt,
3996            fence,
3997            split,
3998            len_ptrs,
3999            saved_lens,
4000            forced_acc,
4001            valid,
4002            stage0_stream,
4003            logical_payload_bytes,
4004        })
4005    }
4006
4007    fn reserve(
4008        &mut self,
4009        current_snapshot: &mut crate::cache::CacheSnapshot,
4010    ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
4011        let generation = self.generations.reserve()?;
4012        if generation.slot != self.active_snapshot_slot {
4013            std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
4014            self.active_snapshot_slot = generation.slot;
4015        }
4016        Ok(generation)
4017    }
4018
4019    fn capture_seed(
4020        &mut self,
4021        e: &Engine,
4022        generation: OptiForkGeneration,
4023        h_seed: &CudaSlice<f32>,
4024        fill_prev: &CudaSlice<f32>,
4025        scratch_len: usize,
4026    ) -> Result<(), Box<dyn std::error::Error>> {
4027        let seed = &mut self.seeds[generation.slot];
4028        e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
4029        e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
4030        seed.scratch_len = scratch_len;
4031        Ok(())
4032    }
4033
4034    fn ticket(
4035        &self,
4036        generation: OptiForkGeneration,
4037        boundary: VerifyBoundaryTicket,
4038    ) -> OptiForkTicket {
4039        OptiForkTicket {
4040            generation,
4041            boundary: Some(boundary),
4042            drain: self.stage0_stream.clone(),
4043            settled: false,
4044        }
4045    }
4046
4047    #[allow(clippy::too_many_arguments)]
4048    fn controller_ticket(
4049        &self,
4050        generation: OptiForkGeneration,
4051        boundary: VerifyBoundaryTicket,
4052        ckpt: VerifyCkpt,
4053        verify_tokens: [u32; 2],
4054        draft_prob: f32,
4055        eager_seed: Option<CudaSlice<f32>>,
4056        q_proxy: f32,
4057        scratch_len: usize,
4058    ) -> OptiControllerTicket {
4059        OptiControllerTicket {
4060            generation,
4061            boundary: Some(boundary),
4062            ckpt: Some(ckpt),
4063            verify_tokens,
4064            draft_prob,
4065            eager_seed,
4066            q_proxy,
4067            scratch_len,
4068            issued_at: std::time::Instant::now(),
4069            drain: self.stage0_stream.clone(),
4070            settled: false,
4071        }
4072    }
4073
4074    fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
4075        self.generations.reserve()
4076    }
4077
4078    fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
4079        &mut self.alternate_snapshot
4080    }
4081
4082    fn promote_successor_snapshot(
4083        &mut self,
4084        current_snapshot: &mut crate::cache::CacheSnapshot,
4085        generation: OptiForkGeneration,
4086    ) {
4087        std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
4088        self.active_snapshot_slot = generation.slot;
4089    }
4090
4091    fn queue_actual_reconcile(
4092        &mut self,
4093        e: &Engine,
4094        snapshot: &crate::cache::CacheSnapshot,
4095        acc: &CudaSlice<u32>,
4096        optimistic_pending: u32,
4097        base: usize,
4098    ) -> Result<(), Box<dyn std::error::Error>> {
4099        let saved: Vec<i32> = (0..self.split)
4100            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
4101            .collect();
4102        // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
4103        // decision point there and append a wait to stage 0 after its optimistic successor/TX;
4104        // the validity/reconcile kernels must never peer-read acc before it is written. The
4105        // increment-1 harness uses primary stage 0, where stream order already provides this.
4106        if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
4107            self.rt.fence_stages_behind(&e.stream())?;
4108        }
4109        let _stage = self.rt.enter(0);
4110        let e0 = self.rt.engine(0, e);
4111        e0.htod_i32_into(&mut self.saved_lens, &saved)?;
4112        e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
4113        e0.spec_fork_reconcile_kv(
4114            &self.len_ptrs,
4115            &self.saved_lens,
4116            acc,
4117            &self.valid,
4118            base,
4119            self.split,
4120        )
4121    }
4122
4123    fn finish_actual_reconcile(
4124        &mut self,
4125        e: &Engine,
4126        cache: &mut Cache,
4127        snapshot: &crate::cache::CacheSnapshot,
4128        n_acc: usize,
4129        base: usize,
4130        hit: bool,
4131    ) -> Result<(), Box<dyn std::error::Error>> {
4132        if hit {
4133            return Ok(());
4134        }
4135        let len_delta = base + n_acc;
4136        for il in 0..self.split {
4137            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4138                kv.len = saved + len_delta;
4139            }
4140        }
4141        {
4142            let _stage = self.rt.enter(1);
4143            let e1 = self.rt.engine(1, e);
4144            for il in self.split..self.fence[2] {
4145                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4146                    kv.len = saved + len_delta;
4147                    e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
4148                }
4149            }
4150        }
4151        self.rt.publish_to(0, &e.stream())?;
4152        Ok(())
4153    }
4154
4155    fn cancel_controller_ticket(
4156        &mut self,
4157        e: &Engine,
4158        cache: &mut Cache,
4159        scratch: &mut MtpScratch,
4160        snapshot: &crate::cache::CacheSnapshot,
4161        ticket: &mut OptiControllerTicket,
4162    ) -> Result<(), Box<dyn std::error::Error>> {
4163        {
4164            let _stage = self.rt.enter(0);
4165            let e0 = self.rt.engine(0, e);
4166            for il in 0..self.split {
4167                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4168                    kv.len = saved;
4169                    e0.set_i32_one(&mut kv.len_d, saved as i32)?;
4170                }
4171            }
4172        }
4173        scratch.set_len(e, snapshot.pos)?;
4174        ticket.settle();
4175        self.generations.retire(ticket.generation)?;
4176        OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4177        OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
4178        eprintln!(
4179            "[opti-controller] tail-drain generation={} slot={}",
4180            ticket.generation.id, ticket.generation.slot,
4181        );
4182        Ok(())
4183    }
4184
4185    #[allow(clippy::too_many_arguments)]
4186    fn reconcile(
4187        &mut self,
4188        e: &Engine,
4189        cache: &mut Cache,
4190        scratch: &mut MtpScratch,
4191        snapshot: &crate::cache::CacheSnapshot,
4192        h_seed: &mut CudaSlice<f32>,
4193        fill_prev: &mut CudaSlice<f32>,
4194        generation: OptiForkGeneration,
4195        action: OptiForkAction,
4196        optimistic_pending: u32,
4197    ) -> Result<(), Box<dyn std::error::Error>> {
4198        debug_assert!(action != OptiForkAction::Abort);
4199        let miss_started = std::time::Instant::now();
4200        let keep = action == OptiForkAction::Hit;
4201        let saved: Vec<i32> = (0..self.split)
4202            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
4203            .collect();
4204        let seed = &self.seeds[generation.slot];
4205        {
4206            let _stage = self.rt.enter(0);
4207            let e0 = self.rt.engine(0, e);
4208            e0.htod_i32_into(&mut self.saved_lens, &saved)?;
4209            let forced = if keep {
4210                [1u32, optimistic_pending]
4211            } else {
4212                [0u32, optimistic_pending]
4213            };
4214            e0.htod_u32_into(&mut self.forced_acc, &forced)?;
4215            e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
4216            e0.spec_fork_reconcile_kv(
4217                &self.len_ptrs,
4218                &self.saved_lens,
4219                &self.forced_acc,
4220                &self.valid,
4221                0,
4222                self.split,
4223            )?;
4224            for il in 0..self.split {
4225                if let Some(recur) = cache.recur[il].as_mut() {
4226                    let conv = snapshot.conv[il]
4227                        .as_ref()
4228                        .ok_or("optipipe stage0 snapshot missing conv state")?;
4229                    let ssm = snapshot.ssm[il]
4230                        .as_ref()
4231                        .ok_or("optipipe stage0 snapshot missing ssm state")?;
4232                    e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
4233                    e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
4234                }
4235            }
4236            e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
4237            e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
4238        }
4239
4240        if keep {
4241            OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4242            return Ok(());
4243        }
4244
4245        for il in 0..self.split {
4246            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4247                kv.len = saved;
4248            }
4249        }
4250        scratch.set_len(e, seed.scratch_len)?;
4251        // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
4252        // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
4253        let caller = e.stream();
4254        self.rt.publish_to(0, &caller)?;
4255        caller.synchronize()?;
4256        let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
4257        eprintln!(
4258            "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
4259            generation.id, generation.slot,
4260        );
4261        OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4262        Ok(())
4263    }
4264
4265    fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
4266        self.generations.retire(generation)
4267    }
4268}
4269
4270fn rewind_tp_kv_verified_prefix(
4271    tp_kv: &mut [Option<crate::tp::ResidentTpKvCache>],
4272    saved_lens: &[Option<usize>],
4273    accepted: usize,
4274) -> Result<(), Box<dyn std::error::Error>> {
4275    if tp_kv.len() != saved_lens.len() {
4276        return Err("spec TP KV snapshot shape mismatch".into());
4277    }
4278    for (layer, (cache, saved)) in tp_kv.iter_mut().zip(saved_lens).enumerate() {
4279        match (cache.as_mut(), *saved) {
4280            (Some(cache), Some(saved)) => {
4281                let target = saved
4282                    .checked_add(accepted)
4283                    .ok_or("spec TP KV committed length overflow")?;
4284                cache.rewind_to(target)?;
4285            }
4286            (None, None) => {}
4287            _ => {
4288                return Err(
4289                    format!("spec TP KV layer {layer} changed shape since its snapshot").into(),
4290                );
4291            }
4292        }
4293    }
4294    Ok(())
4295}
4296
4297/// MEMRA_SPEC_ROUND_PROF counters: whole-round wall, so the round can be weighed against the
4298/// draft-step ([spec-anatomy]) and verify-walk ([tcol-prof]) splits we already print.
4299static ROUND_PROF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4300static ROUND_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
4301static ROUND_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
4302
4303impl HybridModel {
4304    fn mtp_head_count(&self) -> usize {
4305        usize::from(self.mtp.is_some()) + self.mtp_extra.len()
4306    }
4307
4308    fn mtp_head_at(&self, index: usize) -> &MtpHead {
4309        if index == 0 {
4310            self.mtp.as_ref().expect("MTP head 0 is unavailable")
4311        } else {
4312            &self.mtp_extra[index - 1]
4313        }
4314    }
4315
4316    fn new_mtp_scratch(
4317        &self,
4318        e: &Engine,
4319        cap: usize,
4320    ) -> Result<MtpScratch, Box<dyn std::error::Error>> {
4321        let mut scratch = MtpScratch::new(
4322            e,
4323            &self.cfg,
4324            &self.plan,
4325            cap,
4326            self.mtp.as_ref().and_then(|head| head.geom.as_ref()),
4327        )?;
4328        for head in &self.mtp_extra {
4329            scratch.push_plane(e, &self.cfg, &self.plan, head.geom.as_ref())?;
4330        }
4331        Ok(scratch)
4332    }
4333
4334    fn opti_graph_draft_step(
4335        &self,
4336        e: &Engine,
4337        mtp: &MtpHead,
4338        dctx: &mut DraftGraphCtx,
4339        scratch: &mut MtpScratch,
4340        d_vocab: usize,
4341    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
4342        // dcw door: one replay appends one device-counter row; pre-arm ring headroom
4343        // host-side before launching (no-op on flat planes).
4344        if step35_draft_dcw_on() {
4345            scratch.ensure_dcw_headroom(e, 2)?;
4346        }
4347        dctx.graph
4348            .as_ref()
4349            .ok_or("optipipe controller requires the greedy draft graph")?
4350            .launch()?;
4351        scratch.kv.len += 1;
4352        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
4353        if (idx as usize) >= d_vocab {
4354            return Err(
4355                format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
4356            );
4357        }
4358        let probability = e.dtoh(&dctx.g_p)?[0];
4359        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
4360            return Err(format!("optipipe draft probability is invalid: {probability}").into());
4361        }
4362        let token = match &mtp.d2t {
4363            Some(map) => map[idx as usize],
4364            None => idx,
4365        };
4366        if token != idx {
4367            e.set_u32_one(&mut dctx.g_tok, token)?;
4368        }
4369        Ok((token, probability))
4370    }
4371
4372    #[allow(clippy::too_many_arguments)]
4373    fn opti_controller_draft_step(
4374        &self,
4375        e: &Engine,
4376        mtp: &MtpHead,
4377        dctx: &mut DraftGraphCtx,
4378        scratch: &mut MtpScratch,
4379        d_vocab: usize,
4380        eager_state: &mut Option<(u32, CudaSlice<f32>)>,
4381        eager_pos: usize,
4382        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4383        round_graph_ok: bool,
4384    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
4385        // GRAPH-LAUNCH HEADROOM GUARD (see GRAPH_LAUNCH_MIN_FREE): `round_graph_ok` is
4386        // the round's headroom snapshot. Below the floor the main draft arm already ran
4387        // eager (13651-class gate), which seeded `eager_state`, so the controller probe
4388        // rides its eager twin below instead of replaying the draft graph into an
4389        // exhausted card. The seed-unavailable Err beneath stays the recoverable
4390        // fail-closed for the shapes that never seed it.
4391        if dctx.graph.is_some() && round_graph_ok {
4392            return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
4393        }
4394        let (input_token, input_seed) = eager_state
4395            .take()
4396            .ok_or("optipipe eager continuation seed is unavailable")?;
4397        let (logits, next_seed) = self.mtp_head_forward_dev(
4398            e,
4399            mtp,
4400            input_token,
4401            &input_seed,
4402            scratch,
4403            eager_pos,
4404            embd_dev,
4405            None,
4406        )?;
4407        let token_d = e.argmax_token_device(&logits, d_vocab)?;
4408        let idx = e.dtoh_u32_one(&token_d)?;
4409        if (idx as usize) >= d_vocab {
4410            return Err(format!(
4411                "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
4412            )
4413            .into());
4414        }
4415        let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
4416        let probability = e.dtoh(&probability_d)?[0];
4417        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
4418            return Err(
4419                format!("optipipe eager draft probability is invalid: {probability}").into(),
4420            );
4421        }
4422        let token = match &mtp.d2t {
4423            Some(map) => map[idx as usize],
4424            None => idx,
4425        };
4426        *eager_state = Some((token, next_seed));
4427        Ok((token, probability))
4428    }
4429
4430    /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
4431    /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
4432    /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
4433    /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
4434    /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
4435    /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
4436    /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
4437    /// transfer + host argmax per draft token from the K-token draft chain.
4438    #[allow(clippy::too_many_arguments)]
4439    fn mtp_head_forward_dev(
4440        &self,
4441        e: &Engine,
4442        mtp: &MtpHead,
4443        e_tok: u32,
4444        h_seed: &CudaSlice<f32>,
4445        scratch: &mut MtpScratch,
4446        mtp_pos: usize,
4447        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4448        mask: Option<(&CudaSlice<u32>, usize)>,
4449    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4450        self.mtp_head_forward_dev_at(e, mtp, e_tok, h_seed, scratch, 0, mtp_pos, embd_dev, mask)
4451    }
4452
4453    #[allow(clippy::too_many_arguments)]
4454    fn mtp_head_forward_dev_at(
4455        &self,
4456        e: &Engine,
4457        mtp: &MtpHead,
4458        e_tok: u32,
4459        h_seed: &CudaSlice<f32>,
4460        scratch: &mut MtpScratch,
4461        scratch_index: usize,
4462        mtp_pos: usize,
4463        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4464        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
4465        // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
4466        // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
4467        mask: Option<(&CudaSlice<u32>, usize)>,
4468    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4469        // MEMRA_SPEC_ANATOMY=1 — eager-step phase timers (diagnostic only). Phase boundaries
4470        // sync the stream, so absolute time inflates; the BREAKDOWN is the signal. Cumulative
4471        // summary on stderr every 128 steps: glue (embed..attn_norm), attn, ffn, head.
4472        use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
4473        static ANAT_NS: [AtomicU64; 5] = [
4474            AtomicU64::new(0),
4475            AtomicU64::new(0),
4476            AtomicU64::new(0),
4477            AtomicU64::new(0),
4478            AtomicU64::new(0),
4479        ];
4480        static ANAT_STEPS: AtomicU64 = AtomicU64::new(0);
4481        let anat = {
4482            static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4483            *ON.get_or_init(|| std::env::var("MEMRA_SPEC_ANATOMY").as_deref() == Ok("1"))
4484        };
4485        if anat {
4486            e.stream().synchronize()?; // drain prior queue so phase 0 starts clean
4487        }
4488        let t_all = std::time::Instant::now();
4489        let mut t_ph = std::time::Instant::now();
4490        let anat_mark = |i: usize,
4491                         e: &Engine,
4492                         t: &mut std::time::Instant|
4493         -> Result<(), Box<dyn std::error::Error>> {
4494            if anat {
4495                e.stream().synchronize()?;
4496                ANAT_NS[i].fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
4497                *t = std::time::Instant::now();
4498            }
4499            Ok(())
4500        };
4501        let cfg = &self.cfg;
4502        let n_embd = cfg.n_embd as usize;
4503        // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
4504        // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
4505        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
4506        let eps = cfg.rms_eps;
4507        let pos_d = e.htod_i32(&[mtp_pos as i32])?;
4508
4509        // op A: a resident table transfers one 4B token id. The exact host-row capacity path
4510        // expands this one row on CPU and transfers n_embd f32 values instead.
4511        let e_emb = match embd_dev {
4512            Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
4513            None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
4514        };
4515
4516        // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
4517        let mut e_norm = e.zeros(n_embd)?;
4518        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
4519        let mut h_norm = e.zeros(n_embd)?;
4520        e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
4521
4522        // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
4523        let mut concat = e.zeros(2 * n_embd)?;
4524        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
4525        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
4526
4527        // op 4: inpSA = eh_proj @ concat  (eh_proj [2*n_embd, n_embd]) -> [n_embd]
4528        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
4529
4530        // op 5: a_norm = RMSNorm(inpSA, attn_norm)
4531        let mut a_norm = e.zeros(di)?;
4532        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
4533        anat_mark(0, e, &mut t_ph)?;
4534
4535        // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
4536        // scratch.cap, length from the device len_d) so eager drafts match graph drafts
4537        // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
4538        // advances only the device counter).
4539        let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
4540            // step35 MTP block, dcw door armed: the SAME windowed device-counter launcher as
4541            // the captured chain (draft parity by construction). Per-step ring headroom runs
4542            // HERE (eager is host-len work, a rebase is legal); host len mirrored like the
4543            // plain dc arm below.
4544            (Mixer::Full(fa), Some(g))
4545                if self.step35_dcw_eligible(g, scratch.plane(scratch_index).1) =>
4546            {
4547                {
4548                    let (kv, _) = scratch.plane_mut(scratch_index);
4549                    let retain = match kv.ring.as_ref() {
4550                        Some(ring) => memra_kv::swa_retain_from(kv.len, ring.window(), ring.base()),
4551                        None => 0,
4552                    };
4553                    e.prepare_kv_append(kv, retain, 1)?;
4554                }
4555                let out =
4556                    self.mtp_step35_attn_dcw(e, fa, g, &a_norm, &pos_d, scratch, scratch_index)?;
4557                scratch.plane_mut(scratch_index).0.len += 1;
4558                out
4559            }
4560            // step35 MTP block, door off (MEMRA_STEP35_DRAFT_DCW=0 rollback) or class-
4561            // ineligible: PER-LAYER geometry + a separate head-wise gate + an SWA window,
4562            // none of which the plain dc launcher can express (see `mtp_step35_attn`).
4563            // Host-len arm. Advances BOTH the
4564            // host len and the device counter itself (unlike the dc arm, whose host-side
4565            // mirror the caller does).
4566            (Mixer::Full(fa), Some(g)) => {
4567                self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch, scratch_index)?
4568            }
4569            (Mixer::Full(fa), None) => {
4570                let out = self.mtp_full_attn_dc(
4571                    e,
4572                    fa,
4573                    &a_norm,
4574                    &pos_d,
4575                    scratch,
4576                    scratch_index,
4577                    mtp.geom.as_ref(),
4578                )?;
4579                scratch.plane_mut(scratch_index).0.len += 1;
4580                out
4581            }
4582            (Mixer::Linear(_), _) => {
4583                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
4584            }
4585            (Mixer::Mla(_), _) => crate::hybrid::mla_path_unimplemented("MTP head forward"),
4586            (Mixer::Kda(_), _) => crate::hybrid::kda_path_unimplemented("MTP head forward"),
4587        };
4588        anat_mark(1, e, &mut t_ph)?;
4589
4590        // op 7: x1 = inpSA + attn_out
4591        let mut x1 = e.zeros(di)?;
4592        e.add(&inp_sa, &attn_out, &mut x1, di)?;
4593
4594        // op 8: z = RMSNorm(x1, post_attn_norm)  (pre-FFN norm)
4595        let mut z = e.zeros(di)?;
4596        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
4597
4598        // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
4599        let ffn_out = match &mtp.ffn {
4600            crate::hybrid::Ffn::Dense {
4601                ffn_gate,
4602                ffn_up,
4603                ffn_down,
4604            } => {
4605                let n_ff = ffn_gate.out_features();
4606                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
4607                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
4608                    (
4609                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
4610                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
4611                    )
4612                } else {
4613                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
4614                };
4615                let mut act = e.zeros(n_ff)?;
4616                // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
4617                // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
4618                // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
4619                // passes None, which is `ffn_act`'s dispatch verbatim.
4620                Self::ffn_act_lim(
4621                    e,
4622                    &self.cfg,
4623                    &gate,
4624                    &up,
4625                    1.0,
4626                    1.0,
4627                    mtp.step35
4628                        .as_ref()
4629                        .and_then(|s| s.clamp_shexp)
4630                        .map(SwigluClamp::Post),
4631                    &mut act,
4632                    n_ff,
4633                )?;
4634                e.matmul(ffn_down, &act, 1)?
4635            }
4636            // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
4637            // so they never alias trunk layer 0's cache keys.
4638            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
4639        };
4640        anat_mark(2, e, &mut t_ph)?;
4641
4642        // op 10: h_nextn = x1 + ffn_out (at di)
4643        let mut h_inner = e.zeros(di)?;
4644        e.add(&x1, &ffn_out, &mut h_inner, di)?;
4645
4646        // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
4647        // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
4648        let h_nextn = match mtp.geom.as_ref() {
4649            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
4650            None => h_inner,
4651        };
4652
4653        // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
4654        let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
4655        let mut final_h = e.zeros(n_embd)?;
4656        e.rms_norm(
4657            &h_nextn,
4658            final_norm.float_data(),
4659            &mut final_h,
4660            n_embd,
4661            1,
4662            eps,
4663        )?;
4664
4665        // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
4666        let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
4667        let mut logits = e.matmul(head, &final_h, 1)?;
4668        // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
4669        // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
4670        if let Some((mask_d, mw)) = mask {
4671            let d_vocab = head.out_features();
4672            e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
4673        }
4674        anat_mark(3, e, &mut t_ph)?;
4675        if anat {
4676            ANAT_NS[4].fetch_add(t_all.elapsed().as_nanos() as u64, Relaxed);
4677            let n = ANAT_STEPS.fetch_add(1, Relaxed) + 1;
4678            if n.is_multiple_of(128) {
4679                let us = |i: usize| ANAT_NS[i].load(Relaxed) / n / 1000;
4680                eprintln!(
4681                    "[spec-anatomy] steps={n} avg us/step: glue={} attn={} ffn={} head={} total={}",
4682                    us(0),
4683                    us(1),
4684                    us(2),
4685                    us(3),
4686                    us(4)
4687                );
4688            }
4689        }
4690        // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
4691        // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
4692        Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
4693    }
4694
4695    /// One NextN/MTP draft step for an **MLA-mixer** MTP block (glm5_next class: MLA + own
4696    /// k-pool indexer + MoE, serial residual — the NextN layer carries no hc_* tensors), on
4697    /// the model `Cache`'s own MTP latent plane rather than the full-attn `MtpScratch` the
4698    /// qwen35/step35 chain uses. Gate: `glm5_mtp_head_gpu` (engine vs `memra_reference`
4699    /// `execute_mtp`, teacher-forced walk, eh_proj-transpose and h_seed-off-by-one red arms).
4700    ///
4701    /// The interface, stated precisely for the verify arc:
4702    /// - `h_seed`: `[n_embd]` f32 device — the trunk's COLLAPSED PRE-output_norm hidden of
4703    ///   the position whose next token is being drafted (MTP-PLAN §A; exactly what
4704    ///   `prime_cache`/`decode_step` return for hc models). `MEMRA_SPEC_HPOST` flips both
4705    ///   this producer and the returned carrier to the post-norm variant, same as the dev path.
4706    /// - `e_tok`: the token at the seeded position's SUCCESSOR — the token the trunk just
4707    ///   sampled/accepted (reference oracle pairing: `fused[i] = eh_proj([enorm(embed(ids[i]));
4708    ///   hnorm(trunk_hidden[i])])`, i.e. this call with `e_tok = ids[i]`, `h_seed = h[i]`,
4709    ///   `mtp_pos = i` reproduces the reference's row `i`).
4710    /// - `mtp_pos`: the absolute position this step appends to the MTP block's latent plane;
4711    ///   must equal that plane's current length (the plane advances by ONE row per call inside
4712    ///   `mla_attn_cached`; rollback on rejection = the verify arc's latent-plane len reset).
4713    /// - returns `(draft_logits [n_vocab], carrier [n_embd])` on device. glm5_next ships no
4714    ///   private MTP head, so the logits ride the trunk `lm_head` (full vocab, no d2t).
4715    pub fn mtp_head_forward_mla_cached(
4716        &self,
4717        e: &Engine,
4718        depth: usize,
4719        e_tok: u32,
4720        h_seed: &CudaSlice<f32>,
4721        cache: &mut Cache,
4722        mtp_pos: usize,
4723    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4724        if depth >= self.mtp_head_count() {
4725            return Err(format!(
4726                "MTP depth {depth} out of range: {} embedded head(s) loaded \
4727                 (is MEMRA_GLM5_MTP=1 set for a glm5_next model?)",
4728                self.mtp_head_count()
4729            )
4730            .into());
4731        }
4732        let mtp = self.mtp_head_at(depth);
4733        let block = self
4734            .plan
4735            .mtp_blocks
4736            .get(depth)
4737            .ok_or_else(|| format!("ModelPlan declares no MTP block at depth {depth}"))?;
4738        let il = block.layer.index as usize;
4739        let Mixer::Mla(mla) = &mtp.mixer else {
4740            return Err(
4741                "mtp_head_forward_mla_cached serves MLA-mixer MTP blocks only; full-attn \
4742                 blocks take mtp_head_forward_dev's scratch path"
4743                    .into(),
4744            );
4745        };
4746        if matches!(mtp.ffn, crate::hybrid::Ffn::Dense { .. }) {
4747            return Err(
4748                "MLA-mixer MTP block with a Dense FFN has no gated arm yet (glm5_next and \
4749                 glm-dsa NextN blocks are MoE); refusing rather than running ungated math"
4750                    .into(),
4751            );
4752        }
4753        let plane_len = cache
4754            .latent
4755            .get(il)
4756            .and_then(|plane| plane.as_ref())
4757            .map(|plane| plane.len)
4758            .ok_or_else(|| {
4759                format!(
4760                    "MTP block layer {il} has no latent cache plane — the Cache must be \
4761                     built from a plan whose mtp_blocks declare StatePlan::LatentKvCache"
4762                )
4763            })?;
4764        if mtp_pos != plane_len {
4765            return Err(format!(
4766                "MTP draft position {mtp_pos} != the MTP latent plane's length {plane_len} — \
4767                 the plane advances one row per draft step and rolls back by len reset; a \
4768                 skipped or repeated position would attend the wrong horizon"
4769            )
4770            .into());
4771        }
4772
4773        let cfg = &self.cfg;
4774        let n_embd = cfg.n_embd as usize;
4775        let eps = cfg.rms_eps;
4776        let pos_d = e.htod_i32(&[mtp_pos as i32])?;
4777
4778        // Same op chain as `mtp_head_forward_dev_at` (ops 1-12), same kernels — only the
4779        // attention arm differs: `mla_attn_cached` on the plan's own MTP plane instead of
4780        // `mtp_full_attn_dc` on the MtpScratch.
4781        let e_emb = e.htod(&self.embd.gather(n_embd, &[e_tok]))?;
4782        let mut e_norm = e.zeros(n_embd)?;
4783        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
4784        let mut h_norm = e.zeros(n_embd)?;
4785        e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
4786
4787        let mut concat = e.zeros(2 * n_embd)?;
4788        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
4789        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
4790        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
4791
4792        let mut a_norm = e.zeros(n_embd)?;
4793        e.rms_norm(
4794            &inp_sa,
4795            mtp.attn_norm.float_data(),
4796            &mut a_norm,
4797            n_embd,
4798            1,
4799            eps,
4800        )?;
4801        let attn_out = self.mla_attn_cached(e, mla, &a_norm, &pos_d, 1, il, cache)?;
4802
4803        let mut x1 = e.zeros(n_embd)?;
4804        e.add(&inp_sa, &attn_out, &mut x1, n_embd)?;
4805        let mut z = e.zeros(n_embd)?;
4806        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, n_embd, 1, eps)?;
4807        let ffn_out = match &mtp.ffn {
4808            // Distinct block — key its experts off the trunk layers' cache keys (dev-path rule).
4809            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
4810            crate::hybrid::Ffn::Dense { .. } => unreachable!("refused above"),
4811        };
4812        let mut h_nextn = e.zeros(n_embd)?;
4813        e.add(&x1, &ffn_out, &mut h_nextn, n_embd)?;
4814
4815        let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
4816        let mut final_h = e.zeros(n_embd)?;
4817        e.rms_norm(
4818            &h_nextn,
4819            final_norm.float_data(),
4820            &mut final_h,
4821            n_embd,
4822            1,
4823            eps,
4824        )?;
4825        let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
4826        let logits = e.matmul(head, &final_h, 1)?;
4827        Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
4828    }
4829
4830    #[allow(clippy::too_many_arguments)]
4831    fn mtp_chain_forward_dev(
4832        &self,
4833        e: &Engine,
4834        tokens: &[u32],
4835        seeds: &[CudaSlice<f32>],
4836        scratch: &mut MtpScratch,
4837        committed_scratch_len: usize,
4838        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4839        mask: Option<(&CudaSlice<u32>, usize)>,
4840    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4841        if tokens.is_empty() || tokens.len() != seeds.len() {
4842            return Err("multi-head MTP prefix tokens/seeds are malformed".into());
4843        }
4844        let index = mtp_chain_head_index(tokens.len() - 1, self.mtp_head_count());
4845        let head = self.mtp_head_at(index);
4846        scratch.set_plane_len(e, index, committed_scratch_len)?;
4847
4848        let mut last = None;
4849        for row in 0..tokens.len() {
4850            let is_last = row + 1 == tokens.len();
4851            last = Some(self.mtp_head_forward_dev_at(
4852                e,
4853                head,
4854                tokens[row],
4855                &seeds[row],
4856                scratch,
4857                index,
4858                committed_scratch_len + row + 1,
4859                embd_dev,
4860                if is_last { mask } else { None },
4861            )?);
4862        }
4863        Ok(last.expect("non-empty MTP prefix produced no row"))
4864    }
4865
4866    /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
4867    /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
4868    /// the dc path, and all three are properties of this arch's MTP block:
4869    ///
4870    /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
4871    ///    window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
4872    ///    cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
4873    ///    mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
4874    ///    windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
4875    ///    starts at row 0 — it cannot express a nonzero offset. The windowed dc arm is
4876    ///    `mtp_step35_attn_dcw` (`fa_decode_dcw`, doored via MEMRA_STEP35_DRAFT_DCW —
4877    ///    default ON since lane/step37-draft-graph-serving-20260830); this host-len arm is
4878    ///    the =0 rollback and the class-ineligibility fallback.
4879    /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
4880    ///    on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
4881    ///    trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
4882    ///    resolved `Step35MtpGeom`, never from `cfg`.
4883    /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
4884    ///    sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
4885    ///    fused-into-wq `q_gate_split` form the dc arm handles.
4886    ///
4887    /// DOOR STATE: with MEMRA_STEP35_DRAFT_DCW=0 (or a sub-eligible kernel class),
4888    /// `mtp_head_forward_cap` refuses step35 heads explicitly (rather than silently capturing
4889    /// a window-less, wrong-past-`win` graph) and this eager chain IS the served path. With
4890    /// the door armed (the default), BOTH draft modes run the `mtp_step35_attn_dcw` twin
4891    /// instead of this arm.
4892    ///
4893    /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
4894    /// caller must not mirror.
4895    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
4896    fn mtp_step35_attn(
4897        &self,
4898        e: &Engine,
4899        fa: &FullAttnLayer,
4900        g: &crate::hybrid::Step35MtpGeom,
4901        h: &CudaSlice<f32>,
4902        pos_d: &CudaSlice<i32>,
4903        scratch: &mut MtpScratch,
4904        scratch_index: usize,
4905    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4906        let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
4907        // MTP-GEOM RECEIPT, once per process, on the SERVED draft path. Slot-0 acceptance is
4908        // 0.725 here against 0.994 for vLLM MTP3 on the same checkpoint family and card class, and
4909        // the first three explanations for that gap were all wrong: head assignment (step-modulo
4910        // is index 0 at K=1, correct), MEMRA_SPEC_HPOST (identical 84/116 both arms), and this
4911        // block's geometry. Geometry was the one that could have failed SILENTLY — a wrong window
4912        // makes the draft attend the whole context instead of Step-3.7's 512, stays fluent, and
4913        // shows up only as acceptance — so it gets a standing receipt rather than another reading
4914        // of the source. Prints the resolved Step35MtpGeom the served path actually runs on;
4915        // `full_attention_geometry_at`'s missing-row fallback (window: None) does NOT reach here.
4916        {
4917            static ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
4918            ONCE.get_or_init(|| {
4919                eprintln!(
4920                    "[mtp-geom] arm=eager block={} swa={} window={} n_head={nh} n_head_kv={nkv} \
4921                     head_dim_k={hd} n_rot={} rope_base={} clamp_shexp={:?}",
4922                    g.il, g.swa, g.window, g.n_rot, g.rope_base, g.clamp_shexp,
4923                );
4924            });
4925        }
4926        let eps = self.cfg.rms_eps;
4927        let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
4928        let n_embd = self.cfg.n_embd as usize;
4929        let gw = fa
4930            .attn_gate
4931            .as_ref()
4932            .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
4933
4934        let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
4935            && e.uses_q8_1_fast(&fa.wk)
4936            && e.uses_q8_1_fast(&fa.wv)
4937            && e.uses_q8_1_fast(gw)
4938        {
4939            let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
4940            let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
4941                Some(t3) => t3,
4942                None => (
4943                    e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
4944                    e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
4945                    e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
4946                ),
4947            };
4948            (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
4949        } else {
4950            (
4951                e.matmul(&fa.wq, h, 1)?,
4952                e.matmul(&fa.wk, h, 1)?,
4953                e.matmul(&fa.wv, h, 1)?,
4954                e.matmul(gw, h, 1)?,
4955            )
4956        };
4957
4958        let mut q = e.uninit(nh * hd)?;
4959        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
4960        let mut k = e.uninit(nkv * hd)?;
4961        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
4962        // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
4963        // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
4964        // the resolved flag, not the constant, so an all-full sibling stays correct.
4965        let ff = if g.swa {
4966            None
4967        } else {
4968            self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
4969        };
4970        #[cfg(debug_assertions)]
4971        if let Some(ff) = ff {
4972            crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
4973        }
4974        e.rope_neox2(
4975            &mut q,
4976            &mut k,
4977            pos_d,
4978            hd,
4979            g.n_rot,
4980            nh,
4981            nkv,
4982            1,
4983            g.rope_base,
4984            1.0,
4985            ff,
4986        )?;
4987
4988        // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
4989        // length on the host anyway, and the windowed view below needs it there to compute the
4990        // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
4991        // dc-family consumer of this scratch still agree.
4992        let (kv, scratch_cap) = scratch.plane_mut(scratch_index);
4993        assert!(
4994            kv.len < scratch_cap,
4995            "step35 MTP scratch overflow ({} >= {})",
4996            kv.len,
4997            scratch_cap
4998        );
4999        let next_len = kv.len + 1;
5000        let (off, t_kv) = if g.swa && next_len > g.window {
5001            (next_len - g.window, g.window)
5002        } else {
5003            (0, next_len)
5004        };
5005        // `off`/`t_kv` stay the ATTENTION view; the retain is a separate, lower bound so the
5006        // rewind that follows this append is still resident. THIS is the only site that rebases
5007        // this plane (MEMRA_KV_REBASE_TRACE, one run: 1 rebase, all from here), so it is the site
5008        // that decides `base` for everyone.
5009        let retain_from = match kv.ring.as_ref() {
5010            Some(ring) => memra_kv::swa_retain_from(kv.len, ring.window(), ring.base()),
5011            None => off & !31usize,
5012        };
5013        let write_row = e.prepare_kv_append(kv, retain_from, 1)?;
5014        e.append_kv_quantized(
5015            &k,
5016            &v0,
5017            &mut kv.k,
5018            &mut kv.v,
5019            write_row,
5020            kv.kv_dim_k,
5021            kv.kv_dim_v,
5022            kv.k_tok_bytes,
5023            kv.v_tok_bytes,
5024            false,
5025        )?;
5026        kv.len = next_len;
5027        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
5028        // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
5029        // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
5030        // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
5031        // therefore live, not theoretical.
5032        let physical = kv.physical_rows(off, off + t_kv)?;
5033        let k_view = e.view_u8_range(
5034            &kv.k,
5035            physical.start * kv.k_tok_bytes,
5036            physical.end * kv.k_tok_bytes,
5037        );
5038        let v_view = e.view_u8_range(
5039            &kv.v,
5040            physical.start * kv.v_tok_bytes,
5041            physical.end * kv.v_tok_bytes,
5042        );
5043        let mut attn = e.uninit(nh * hd)?;
5044        e.fa_decode_kvmod(
5045            &q,
5046            &k_view,
5047            &v_view,
5048            &mut attn,
5049            hd,
5050            nh,
5051            nkv,
5052            t_kv,
5053            scale,
5054            kv.k_tok_bytes,
5055            kv.v_tok_bytes,
5056            false,
5057        )?;
5058
5059        let mut ag = e.uninit(nh * hd)?;
5060        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
5061        e.matmul(&fa.wo, &ag, 1)
5062    }
5063
5064    /// The dcw draft arm's kernel-class precondition, mirrored from `fa_decode_dcw`'s own
5065    /// refusal plus the v3 walk's format contract (`fa_v3_active`), so the DEV dispatch can
5066    /// never pick an arm the launcher would refuse mid-chain (the eager chain has no graceful
5067    /// fallback point) and the CAP site refuses with the named reason instead.
5068    ///
5069    /// `cap` = the SESSION's scratch-plane row capacity: the launcher's vec gate reads
5070    /// `bucket_max = min(window, cap)`, so a SMALL session (tiny prompt + tiny max_tokens,
5071    /// e.g. a max_tokens=8 probe: cap ~62 < the 96 vec floor) is OUTSIDE the dcw domain even
5072    /// though the WINDOW clears the floor. Mirroring the window alone shipped exactly that
5073    /// hole when the door default flipped ON (2026-08-30, vision-cell receipt: sampled
5074    /// capture WARN + `[engine-error] fa_decode_dcw supports the default v3-vec class only`
5075    /// hard-failing the burst — the eager dcw arm has no graceful fallback point). Sub-floor
5076    /// sessions now take the host-len kvmod arm, byte-for-byte the door-off serving.
5077    fn step35_dcw_eligible(&self, g: &crate::hybrid::Step35MtpGeom, cap: usize) -> bool {
5078        let hd = self.cfg.head_dim_k as usize;
5079        step35_draft_dcw_on()
5080            && g.swa
5081            && g.window.min(cap) >= crate::fa_vec_min_tkv()
5082            && std::env::var("MEMRA_NO_FA_VEC").is_err()
5083            && crate::fa_v3_active(hd)
5084            && hd <= 256
5085            && hd.is_multiple_of(32)
5086    }
5087
5088    /// step35 MTP-block attention, T=1, on the scratch KV: the WINDOWED DEVICE-COUNTER twin
5089    /// of `mtp_step35_attn`, serving BOTH draft paths when `step35_draft_dcw_on`. Write slot,
5090    /// key bound and SWA view offset all derive from device state (`len_d`, `base_d` written
5091    /// only at host-side rebases, and the block's `window`), so ONE captured graph serves the
5092    /// whole chain and replays see KV growth through the counter: the `mtp_full_attn_dc`
5093    /// contract plus the view offset the plain `_dc` kernel could not express (the old
5094    /// capture-refusal root cause). The three step35 properties stay per-geom exactly as in
5095    /// the eager twin: nh/nkv from `Step35MtpGeom`, the separate head-wise gate
5096    /// (`attn_head_gate`), per-layer rope width/base with SWA passing null freqs.
5097    ///
5098    /// bucket_max = min(cap, window): the windowed view never exceeds `window` rows, so the
5099    /// capture-time grid stays valid for every replayed len, and the kernel derives ns_eff
5100    /// from the LIVE T_kv at the fixed split_keys (one-partition law). Both arms call THIS
5101    /// launcher at THIS bucket, so eager and captured drafts are bit-identical by
5102    /// construction; vs the retired-by-flag `mtp_step35_attn` the only numeric-class deltas
5103    /// are the sub-vec-floor region (t_kv < 96: kvmod ran scalar, dcw stays vec) and any
5104    /// live-len split-ladder rung below the bucket's, both draft-side only (the verify
5105    /// arbitrates emitted bytes; acceptance is gated by the battery).
5106    ///
5107    /// Host len is NOT advanced here (graph contract); callers mirror. The EAGER caller runs
5108    /// `prepare_kv_append` per step (ring headroom, rebase legal there); the CAPTURED path
5109    /// pre-arms headroom at capture time and round start (`MtpScratch::ensure_dcw_headroom`)
5110    /// because a rebase is host work no captured chain may contain.
5111    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the capture/call contract; bundling into a struct is a refactor, not a lint fix
5112    fn mtp_step35_attn_dcw(
5113        &self,
5114        e: &Engine,
5115        fa: &FullAttnLayer,
5116        g: &crate::hybrid::Step35MtpGeom,
5117        h: &CudaSlice<f32>,
5118        pos_d: &CudaSlice<i32>,
5119        scratch: &mut MtpScratch,
5120        scratch_index: usize,
5121    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5122        let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
5123        // MTP-GEOM RECEIPT (dcw twin of the `mtp_step35_attn` receipt): once per process,
5124        // naming the arm, so a serving log proves WHICH draft attention program ran (the
5125        // engagement receipt for the flag door, both directions).
5126        {
5127            static ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
5128            ONCE.get_or_init(|| {
5129                eprintln!(
5130                    "[mtp-geom] arm=dcw block={} swa={} window={} n_head={nh} n_head_kv={nkv} \
5131                     head_dim_k={hd} n_rot={} rope_base={} clamp_shexp={:?}",
5132                    g.il, g.swa, g.window, g.n_rot, g.rope_base, g.clamp_shexp,
5133                );
5134            });
5135        }
5136        let eps = self.cfg.rms_eps;
5137        let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
5138        let n_embd = self.cfg.n_embd as usize;
5139        let gw = fa
5140            .attn_gate
5141            .as_ref()
5142            .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
5143
5144        let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
5145            && e.uses_q8_1_fast(&fa.wk)
5146            && e.uses_q8_1_fast(&fa.wv)
5147            && e.uses_q8_1_fast(gw)
5148        {
5149            let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
5150            let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
5151                Some(t3) => t3,
5152                None => (
5153                    e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
5154                    e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
5155                    e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
5156                ),
5157            };
5158            (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
5159        } else {
5160            (
5161                e.matmul(&fa.wq, h, 1)?,
5162                e.matmul(&fa.wk, h, 1)?,
5163                e.matmul(&fa.wv, h, 1)?,
5164                e.matmul(gw, h, 1)?,
5165            )
5166        };
5167
5168        let mut q = e.zeros(nh * hd)?;
5169        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
5170        let mut k = e.zeros(nkv * hd)?;
5171        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
5172        // rope_freqs (llama3 factors) apply to the FULL-attn layers ONLY; SWA passes null
5173        // (the eager twin's rule, resolved from the flag, not the constant).
5174        let ff = if g.swa {
5175            None
5176        } else {
5177            self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
5178        };
5179        #[cfg(debug_assertions)]
5180        if let Some(ff) = ff {
5181            crate::debug_assert_tensor_stream_device(
5182                ff,
5183                &e.stream(),
5184                "mtp_step35_attn_dcw.rope_freqs",
5185            );
5186        }
5187        e.rope_neox2(
5188            &mut q,
5189            &mut k,
5190            pos_d,
5191            hd,
5192            g.n_rot,
5193            nh,
5194            nkv,
5195            1,
5196            g.rope_base,
5197            1.0,
5198            ff,
5199        )?;
5200
5201        let (kv, cap) = scratch.plane_mut(scratch_index);
5202        // Append at the DEVICE slot's PHYSICAL row (len_d - base_d), then advance the counter
5203        // in-graph. Physical room is the callers' headroom contract (see the fn doc).
5204        e.append_kv_quantized_dcw(
5205            &k,
5206            &v0,
5207            &mut kv.k,
5208            &mut kv.v,
5209            &kv.len_d,
5210            kv.base_d.as_ref(),
5211            kv.kv_dim_k,
5212            kv.kv_dim_v,
5213            kv.k_tok_bytes,
5214            kv.v_tok_bytes,
5215        )?;
5216        e.inc_seqlen(&mut kv.len_d)?;
5217        // Full-buffer views (any in-round physical row stays in range under the headroom
5218        // contract); the kernel bounds and offsets the key range from (len_d, base_d, window).
5219        let k_view = e.view_u8(&kv.k, kv.k.len());
5220        let v_view = e.view_u8(&kv.v, kv.v.len());
5221        let bucket = g.window.min(cap);
5222        let mut attn = e.zeros(nh * hd)?;
5223        e.fa_decode_dcw(
5224            &q,
5225            &k_view,
5226            &v_view,
5227            &mut attn,
5228            hd,
5229            nh,
5230            nkv,
5231            &kv.len_d,
5232            kv.base_d.as_ref(),
5233            if g.swa { g.window } else { 0 },
5234            bucket,
5235            scale,
5236            kv.k_tok_bytes,
5237            kv.v_tok_bytes,
5238            None,
5239        )?;
5240
5241        let mut ag = e.zeros(nh * hd)?;
5242        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
5243        e.matmul(&fa.wo, &ag, 1)
5244    }
5245
5246    /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
5247    /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
5248    /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
5249    /// chain, and replays keep seeing KV growth through the device counter (no recapture).
5250    /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
5251    /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
5252    /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
5253    /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
5254    /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
5255    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
5256    fn mtp_full_attn_dc(
5257        &self,
5258        e: &Engine,
5259        fa: &FullAttnLayer,
5260        h: &CudaSlice<f32>,
5261        pos_d: &CudaSlice<i32>,
5262        scratch: &mut MtpScratch,
5263        scratch_index: usize,
5264        geom: Option<&crate::hybrid::DraftGeom>,
5265    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5266        let cfg = &self.cfg;
5267        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
5268        let geometry = cfg.full_attention_geometry_at(mtp_il);
5269        let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
5270        let n_head_kv = geom
5271            .map(|g| g.n_head_kv)
5272            .unwrap_or(geometry.n_head_kv as usize);
5273        let head_dim = geometry.head_dim_k as usize;
5274        let eps = cfg.rms_eps;
5275        let scale = geometry.attention_scale();
5276        let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
5277        let bucket_max = scratch.plane(scratch_index).1;
5278
5279        let (qf, mut k, v) =
5280            if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
5281                let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
5282                (
5283                    e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
5284                    e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
5285                    e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
5286                )
5287            } else {
5288                (
5289                    e.matmul(&fa.wq, h, 1)?,
5290                    e.matmul(&fa.wk, h, 1)?,
5291                    e.matmul(&fa.wv, h, 1)?,
5292                )
5293            };
5294        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
5295        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
5296        let (mut q, gate) = if gated {
5297            let mut q = e.zeros(n_head * head_dim)?;
5298            let mut gate = e.zeros(n_head * head_dim)?;
5299            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
5300            (q, Some(gate))
5301        } else {
5302            (qf, None)
5303        };
5304
5305        let mut qn = e.zeros(n_head * head_dim)?;
5306        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
5307        q = qn;
5308        let mut kn = e.zeros(n_head_kv * head_dim)?;
5309        e.rms_norm(
5310            &k,
5311            fa.k_norm.float_data(),
5312            &mut kn,
5313            head_dim,
5314            n_head_kv,
5315            eps,
5316        )?;
5317        k = kn;
5318        let rope_dims = geometry.n_rot as usize;
5319        e.rope_neox(
5320            &mut q,
5321            pos_d,
5322            head_dim,
5323            rope_dims,
5324            n_head,
5325            1,
5326            geometry.rope_base,
5327            1.0,
5328        )?;
5329        e.rope_neox(
5330            &mut k,
5331            pos_d,
5332            head_dim,
5333            rope_dims,
5334            n_head_kv,
5335            1,
5336            geometry.rope_base,
5337            1.0,
5338        )?;
5339
5340        let kv = scratch.plane_mut(scratch_index).0;
5341        // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
5342        e.append_kv_quantized_dc(
5343            &k,
5344            &v,
5345            &mut kv.k,
5346            &mut kv.v,
5347            &kv.len_d,
5348            kv.kv_dim_k,
5349            kv.kv_dim_v,
5350            kv.k_tok_bytes,
5351            kv.v_tok_bytes,
5352            false,
5353        )?;
5354        e.inc_seqlen(&mut kv.len_d)?;
5355        // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
5356        // key range from the device counter.
5357        let k_view = e.view_u8(&kv.k, kv.k.len());
5358        let v_view = e.view_u8(&kv.v, kv.v.len());
5359        let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
5360        let mut attn = e.zeros(n_head * head_dim)?;
5361        e.fa_decode_dc(
5362            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
5363            scale, ktb, vtb, false,
5364        )?;
5365
5366        let attn_g = match &gate {
5367            Some(gate) => {
5368                let mut gsig = e.zeros(n_head * head_dim)?;
5369                e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
5370                let mut ag = e.zeros(n_head * head_dim)?;
5371                e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
5372                ag
5373            }
5374            None => attn,
5375        };
5376        e.matmul(&fa.wo, &attn_g, 1)
5377    }
5378
5379    /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
5380    /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
5381    /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
5382    /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
5383    /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
5384    /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
5385    /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
5386    /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
5387    #[allow(clippy::too_many_arguments)]
5388    fn mtp_kv_fill_at(
5389        &self,
5390        e: &Engine,
5391        mtp: &MtpHead,
5392        tokens: &[u32],
5393        h: &CudaSlice<f32>,
5394        pos0: usize,
5395        scratch: &mut MtpScratch,
5396        scratch_index: usize,
5397        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5398    ) -> Result<(), Box<dyn std::error::Error>> {
5399        let cfg = &self.cfg;
5400        let n_embd = cfg.n_embd as usize;
5401        let eps = cfg.rms_eps;
5402        let t = tokens.len();
5403        let (scratch_kv, scratch_cap) = scratch.plane(scratch_index);
5404        assert_eq!(scratch_kv.len, pos0, "mtp_kv_fill: append slot mismatch");
5405        assert!(pos0 + t <= scratch_cap, "mtp_kv_fill: scratch overflow");
5406        let Mixer::Full(fa) = &mtp.mixer else {
5407            panic!("MTP block is full-attn in qwen35; linear MTP not supported")
5408        };
5409        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
5410        let pos_d = e.htod_i32(&pos_vec)?;
5411
5412        // ops A/1/2: embed + the two input norms, T-wide.
5413        let e_emb = match embd_dev {
5414            Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
5415            None => e.htod(&self.embd.gather(n_embd, tokens))?,
5416        };
5417        let mut e_norm = e.zeros(t * n_embd)?;
5418        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
5419        let mut h_norm = e.zeros(t * n_embd)?;
5420        e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
5421
5422        // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
5423        let mut concat = e.zeros(t * 2 * n_embd)?;
5424        for i in 0..t {
5425            e.copy_view_into(
5426                &mut concat,
5427                i * 2 * n_embd,
5428                &e_norm.slice(i * n_embd..(i + 1) * n_embd),
5429                n_embd,
5430            )?;
5431            e.copy_view_into(
5432                &mut concat,
5433                i * 2 * n_embd + n_embd,
5434                &h_norm.slice(i * n_embd..(i + 1) * n_embd),
5435                n_embd,
5436            )?;
5437        }
5438
5439        // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
5440        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
5441        let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
5442        let mut a_norm = e.zeros(t * di)?;
5443        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
5444
5445        // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
5446        // the fill only has to leave correct K/V rows behind for later chains to attend over.
5447        let n_head_kv = mtp
5448            .geom
5449            .as_ref()
5450            .map(|g| g.n_head_kv)
5451            .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
5452            .unwrap_or_else(|| {
5453                let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
5454                cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
5455            });
5456        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
5457        let geometry = cfg.full_attention_geometry_at(mtp_il);
5458        let head_dim = geometry.head_dim_k as usize;
5459        let mut k = e.matmul(&fa.wk, &a_norm, t)?;
5460        let v = e.matmul(&fa.wv, &a_norm, t)?;
5461        let mut kn = e.zeros(t * n_head_kv * head_dim)?;
5462        e.rms_norm(
5463            &k,
5464            fa.k_norm.float_data(),
5465            &mut kn,
5466            head_dim,
5467            n_head_kv * t,
5468            eps,
5469        )?;
5470        k = kn;
5471        // step35: rotary width AND base are per-layer, and the MTP block's values come from the
5472        // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
5473        // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
5474        // writes K rows the attention arm then re-derives at a different theta: correct-looking
5475        // output with dead acceptance, invisible to the exactness gates.
5476        let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
5477            Some(s) => (
5478                s.n_rot,
5479                s.rope_base,
5480                if s.swa {
5481                    None
5482                } else {
5483                    self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
5484                },
5485            ),
5486            None => (geometry.n_rot as usize, geometry.rope_base, None),
5487        };
5488        #[cfg(debug_assertions)]
5489        if let Some(ff) = ff {
5490            crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
5491        }
5492        match ff {
5493            Some(f) => e.rope_neox_ff(
5494                &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
5495            )?,
5496            None => e.rope_neox(
5497                &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
5498            )?,
5499        }
5500
5501        let kv = scratch.plane_mut(scratch_index).0;
5502        // Match the trunk prime contract: a chunk may need the aligned window immediately before
5503        // its first row, so preserve that prefix when the physical tail rebases at wrap.
5504        let retain_from = kv
5505            .ring
5506            .as_ref()
5507            .map(|ring| memra_kv::swa_retain_from(pos0, ring.window(), ring.base()))
5508            .unwrap_or(0);
5509        let write_row = e.prepare_kv_append(kv, retain_from, t)?;
5510        for i in 0..t {
5511            let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
5512            let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
5513            e.append_kv_quantized_view(
5514                &k_row,
5515                &v_row,
5516                &mut kv.k,
5517                &mut kv.v,
5518                write_row + i,
5519                kv.kv_dim_k,
5520                kv.kv_dim_v,
5521                kv.k_tok_bytes,
5522                kv.v_tok_bytes,
5523                false,
5524            )?;
5525        }
5526        kv.len = pos0 + t;
5527        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
5528        Ok(())
5529    }
5530
5531    #[allow(clippy::too_many_arguments)]
5532    fn mtp_kv_fill_all(
5533        &self,
5534        e: &Engine,
5535        tokens: &[u32],
5536        h: &CudaSlice<f32>,
5537        pos0: usize,
5538        scratch: &mut MtpScratch,
5539        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5540    ) -> Result<(), Box<dyn std::error::Error>> {
5541        debug_assert_eq!(self.mtp_head_count(), scratch.plane_count());
5542        for index in 0..self.mtp_head_count() {
5543            self.mtp_kv_fill_at(
5544                e,
5545                self.mtp_head_at(index),
5546                tokens,
5547                h,
5548                pos0,
5549                scratch,
5550                index,
5551                embd_dev,
5552            )?;
5553        }
5554        Ok(())
5555    }
5556
5557    /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
5558    /// every varying input device-resident —
5559    ///   - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
5560    ///     so the chain feeds itself; the host reads the same 4 bytes for the draft list),
5561    ///   - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
5562    ///   - rope pos from the persistent `pos_d` counter (inc'd in-graph),
5563    ///   - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
5564    ///     The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
5565    ///     Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
5566    ///     (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
5567    ///     `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
5568    ///     the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
5569    ///     (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
5570    ///     untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
5571    ///     `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
5572    ///     (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
5573    ///     (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
5574    ///     bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
5575    ///     replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
5576    ///     seed/temp are capture-time constants (fixed per generate call, like p_min).
5577    #[allow(clippy::too_many_arguments)]
5578    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
5579    fn mtp_head_forward_cap(
5580        &self,
5581        e: &Engine,
5582        mtp: &MtpHead,
5583        tok_d: &mut CudaSlice<u32>,
5584        pos_d: &mut CudaSlice<i32>,
5585        h_seed_d: &mut CudaSlice<f32>,
5586        p_d: &mut CudaSlice<f32>,
5587        scratch: &mut MtpScratch,
5588        // Which scratch plane this head appends to / attends over: 0 for the single-head
5589        // chain (every pre-lane caller), the head's own plane index for the multi-head
5590        // chain graphs (each head owns one plane — `mtp_chain_forward_dev`'s contract).
5591        scratch_index: usize,
5592        with_prob: bool,
5593        with_head: bool,
5594        embd_gpu: &CudaSlice<u8>,
5595        embd_qt: i32,
5596        embd_rb: usize,
5597        d_vocab: usize,
5598        sampled_cap: Option<SampledCapArgs<'_>>,
5599        stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
5600        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
5601        // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
5602        // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
5603        // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
5604        // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
5605        mask_cap: Option<(&CudaSlice<u32>, usize)>,
5606    ) -> Result<(), Box<dyn std::error::Error>> {
5607        let cfg = &self.cfg;
5608        let n_embd = cfg.n_embd as usize;
5609        // step35: capturable through the WINDOWED device-counter arm (`mtp_step35_attn_dcw`)
5610        // once the dcw door is armed and the v3-vec class is live. Without the door this stays
5611        // the deliberate, named refusal: the plain `_dc` attention's key bound always starts at
5612        // row 0, cannot express this block's SWA view offset, and a captured chain would
5613        // silently attend OUTSIDE the window once the persistent scratch passes 512 rows.
5614        // Returning Err (not a panic) is what the capture sites already handle by degrading to
5615        // the eager chain (`mtp_head_forward_dev` -> `mtp_step35_attn`).
5616        // ROUND-STREAM stays refused EITHER WAY: the stream VERIFY has no step35 twin (see the
5617        // step35_verify refusal), so a stream capture that succeeded here would only move the
5618        // failure from capture time (graceful stream-off) to serve time (a failed round).
5619        if let Some(g) = mtp.step35.as_ref() {
5620            if stream_pack.is_some() {
5621                return Err(
5622                    "step35 has no ROUND-STREAM draft arm (the stream verify has no step35 \
5623                     twin); stream off"
5624                        .into(),
5625                );
5626            }
5627            if !self.step35_dcw_eligible(g, scratch.plane(scratch_index).1) {
5628                return Err(format!(
5629                    "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
5630                        block's SWA view offset; the windowed dcw capture needs \
5631                        MEMRA_STEP35_DRAFT_DCW armed [default ON, =0 disarms] and the v3-vec \
5632                        class live at bucket=min(window {}, scratch cap {})) - the eager draft \
5633                        chain serves this shape",
5634                    g.window,
5635                    scratch.plane(scratch_index).1,
5636                )
5637                .into());
5638            }
5639        }
5640        // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
5641        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
5642        let eps = cfg.rms_eps;
5643        let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
5644        let mut e_norm = e.zeros(n_embd)?;
5645        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
5646        let mut h_norm = e.zeros(n_embd)?;
5647        e.rms_norm(
5648            &*h_seed_d,
5649            mtp.hnorm.float_data(),
5650            &mut h_norm,
5651            n_embd,
5652            1,
5653            eps,
5654        )?;
5655        let mut concat = e.zeros(2 * n_embd)?;
5656        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
5657        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
5658        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
5659        let mut a_norm = e.zeros(di)?;
5660        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
5661        let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
5662            // step35 (eligibility already enforced by the refusal above): the windowed dcw
5663            // arm, the SAME launcher the eager dev arm runs when the door is armed. No host
5664            // work here (this is the capture body); headroom is the callers' pre-arm.
5665            (Mixer::Full(fa), Some(g)) => {
5666                self.mtp_step35_attn_dcw(e, fa, g, &a_norm, pos_d, scratch, scratch_index)?
5667            }
5668            (Mixer::Full(fa), None) => self.mtp_full_attn_dc(
5669                e,
5670                fa,
5671                &a_norm,
5672                pos_d,
5673                scratch,
5674                scratch_index,
5675                mtp.geom.as_ref(),
5676            )?,
5677            (Mixer::Linear(_), _) => {
5678                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
5679            }
5680            (Mixer::Mla(_), _) => {
5681                crate::hybrid::mla_path_unimplemented("captured MTP head forward")
5682            }
5683            (Mixer::Kda(_), _) => {
5684                crate::hybrid::kda_path_unimplemented("captured MTP head forward")
5685            }
5686        };
5687        let mut x1 = e.zeros(di)?;
5688        e.add(&inp_sa, &attn_out, &mut x1, di)?;
5689        let mut z = e.zeros(di)?;
5690        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
5691        let ffn_out = match &mtp.ffn {
5692            crate::hybrid::Ffn::Dense {
5693                ffn_gate,
5694                ffn_up,
5695                ffn_down,
5696            } => {
5697                let n_ff = ffn_gate.out_features();
5698                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
5699                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
5700                    (
5701                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
5702                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
5703                    )
5704                } else {
5705                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
5706                };
5707                let mut act = e.zeros(n_ff)?;
5708                // step35: the dense FFN reads the per-layer SHEXP clamp, resolved for the MTP
5709                // block's own index (the mtp_head_forward_dev rule; None for every other arch,
5710                // which is `ffn_act`'s dispatch verbatim). The eager and captured chains must
5711                // run the ONE activation program.
5712                Self::ffn_act_lim(
5713                    e,
5714                    &self.cfg,
5715                    &gate,
5716                    &up,
5717                    1.0,
5718                    1.0,
5719                    mtp.step35
5720                        .as_ref()
5721                        .and_then(|s| s.clamp_shexp)
5722                        .map(SwigluClamp::Post),
5723                    &mut act,
5724                    n_ff,
5725                )?;
5726                e.matmul(ffn_down, &act, 1)?
5727            }
5728            // ROUND-STREAM: a softmax-routed resident MoE takes the zero-D2H device router +
5729            // expert program and is capture-legal. Sigmoid-routed MoE (Hy3/M3/Step) still
5730            // selects through the host-visible sigmoid router; capturing that stream sync
5731            // invalidates CUDA capture, so it stays on the eager draft chain even when every
5732            // expert is resident. Non-resident (SLRU-lock) is likewise rejected.
5733            crate::hybrid::Ffn::Moe(m)
5734                if m.dev_exps.is_some() && self.cfg.sigmoid_router().is_none() =>
5735            {
5736                self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
5737            }
5738            crate::hybrid::Ffn::Moe(_) => {
5739                return Err(
5740                    "graph draft requires a Dense or device-routed resident-MoE MTP FFN".into(),
5741                );
5742            }
5743        };
5744        let mut h_inner = e.zeros(di)?;
5745        e.add(&x1, &ffn_out, &mut h_inner, di)?;
5746        // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
5747        let h_nextn = match mtp.geom.as_ref() {
5748            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
5749            None => h_inner,
5750        };
5751        // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
5752        let final_h = if with_head || spec_hpost() {
5753            let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
5754            let mut fh = e.zeros(n_embd)?;
5755            e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
5756            Some(fh)
5757        } else {
5758            None
5759        };
5760        if with_head {
5761            let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
5762            let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
5763            // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
5764            // before the argmax — proposals become legal by construction. Contents-only
5765            // per-replay upload keeps the capture valid.
5766            if let Some((mask_d, mw)) = mask_cap {
5767                e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
5768            }
5769            if let Some(SampledCapArgs {
5770                ctr: ctr_d,
5771                perturb: perturb_d,
5772                q_out: q_out_d,
5773                seed,
5774                temp,
5775                filt,
5776            }) = sampled_cap
5777            {
5778                // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
5779                // own buffer is pool-recycled after the capture body returns, so it can't be the
5780                // retention target), bump the device event counter, gumbel-perturb reading it,
5781                // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
5782                e.copy_into(q_out_d, 0, &logits, d_vocab)?;
5783                e.sctr_inc(ctr_d)?;
5784                match filt {
5785                    // PURE-TEMP: gumbel over the raw softmax — byte-identical to the
5786                    // pre-lane capture body.
5787                    None => e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?,
5788                    // FILTERED (lane/step37-draft-graph-serving-20260830): the SAME
5789                    // filter_stats program the eager arm and the accept path run (the
5790                    // wrapper's coop/plain choice is deployment-keyed, never per-call), then
5791                    // the device-stat/device-counter perturb twin — the draft draws from the
5792                    // exact filtered distribution the verify gathers `q` from. q was
5793                    // retained ABOVE, pre-perturb, so the accept path's post-replay stats
5794                    // recompute (same kernel, same bits) reconstructs these th/z exactly.
5795                    Some(f) => {
5796                        e.filter_stats(
5797                            &logits, d_vocab, f.rows0, f.th, f.z, f.mx, d_vocab, 1, temp, f.top_k,
5798                            f.top_p, f.min_p,
5799                        )?;
5800                        e.gumbel_perturb_filtered_ctr(
5801                            &logits, perturb_d, d_vocab, seed, ctr_d, temp, f.mx, f.th,
5802                        )?;
5803                    }
5804                }
5805                e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
5806                // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
5807                // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
5808                if with_prob {
5809                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
5810                }
5811            } else {
5812                // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
5813                e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
5814                // p-min under a draft mask reads the MASKED row: confidence relative to the
5815                // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
5816                // is the right semantics for "does the drafter know what comes next here" and
5817                // the same row the pick came from. Draft-quality only — verify arbitrates.
5818                if with_prob {
5819                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
5820                }
5821            }
5822        }
5823        // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
5824        // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
5825        if let Some((out, slot, d2t)) = stream_pack {
5826            e.pack_tok_p(tok_d, p_d, out, slot)?;
5827            if let Some(map) = d2t {
5828                e.tok_map_u32(tok_d, map)?;
5829            }
5830        }
5831        // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
5832        if spec_hpost() {
5833            e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
5834        } else {
5835            e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
5836        }
5837        // advance the draft rope position in-graph.
5838        e.inc_seqlen(pos_d)?;
5839        Ok(())
5840    }
5841
5842    /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
5843    /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
5844    /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
5845    /// Advances `cache.pos` by T.
5846    pub fn decode_step_t(
5847        &self,
5848        e: &Engine,
5849        tokens: &[u32],
5850        pos0: usize,
5851        cache: &mut Cache,
5852    ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
5853        if self.is_gemma4_e4b() {
5854            return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
5855        }
5856        if self.gemma_batch_program() {
5857            return self.gemma4_decode_step_t(e, tokens, pos0, cache);
5858        }
5859        Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
5860    }
5861
5862    /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
5863    /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
5864    /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
5865    /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
5866    pub fn decode_step_t_h(
5867        &self,
5868        e: &Engine,
5869        tokens: &[u32],
5870        pos0: usize,
5871        cache: &mut Cache,
5872    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5873        self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
5874    }
5875
5876    /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
5877    /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
5878    pub fn decode_step_t_h_emb(
5879        &self,
5880        e: &Engine,
5881        tokens: &[u32],
5882        pos0: usize,
5883        cache: &mut Cache,
5884        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5885    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5886        let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
5887        Ok((e.dtoh(&logits_d)?, h_seed))
5888    }
5889
5890    /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
5891    /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
5892    /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
5893    /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
5894    /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
5895    pub fn decode_step_t_h_emb_dev(
5896        &self,
5897        e: &Engine,
5898        tokens: &[u32],
5899        pos0: usize,
5900        cache: &mut Cache,
5901        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5902    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5903        cache.ensure_usable("decode_step_t")?;
5904        let n_embd = self.cfg.n_embd as usize;
5905        let t = tokens.len();
5906        let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
5907        // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
5908        let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
5909        e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
5910        Ok((logits, hs))
5911    }
5912
5913    /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
5914    /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
5915    /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
5916    /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
5917    /// retains/copies — they never change what any kernel computes).
5918    fn decode_step_t_core(
5919        &self,
5920        e: &Engine,
5921        tokens: &[u32],
5922        pos0: usize,
5923        cache: &mut Cache,
5924        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5925        mut ckpt: Option<&mut VerifyCkpt>,
5926    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5927        self.decode_step_t_core_stream(
5928            e,
5929            tokens,
5930            pos0,
5931            cache,
5932            embd_dev,
5933            ckpt.take(),
5934            None,
5935            None,
5936            None,
5937            None,
5938        )
5939    }
5940
5941    /// [`Self::decode_step_t_core`] with the MTP route's verify-graph pool armed
5942    /// (`MEMRA_SPEC_VERIFY_GRAPH`). `graphs: None` reproduces `decode_step_t_core`
5943    /// argument-for-argument, so the eager walk stays the byte-identical fallback.
5944    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
5945    fn decode_step_t_core_vg(
5946        &self,
5947        e: &Engine,
5948        tokens: &[u32],
5949        pos0: usize,
5950        cache: &mut Cache,
5951        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5952        mut ckpt: Option<&mut VerifyCkpt>,
5953        graphs: Option<&mut DsparkVerifyGraphs>,
5954    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5955        self.decode_step_t_core_stream(
5956            e,
5957            tokens,
5958            pos0,
5959            cache,
5960            embd_dev,
5961            ckpt.take(),
5962            None,
5963            None,
5964            None,
5965            graphs,
5966        )
5967    }
5968
5969    /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
5970    /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
5971    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
5972    fn decode_step_t_core_pipelined(
5973        &self,
5974        e: &Engine,
5975        tokens: &[u32],
5976        pos0: usize,
5977        cache: &mut Cache,
5978        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5979        mut ckpt: Option<&mut VerifyCkpt>,
5980        pipe: &SpecPipeLane,
5981        round: usize,
5982    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5983        let fence = crate::pp::pp_cuts(self.layers.len())
5984            .ok_or("two-session speculative pipeline requires a PP stage cut")?;
5985        if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
5986            return Err("two-session speculative pipeline requires the PP verify split".into());
5987        }
5988        let interval_fence = pipe.stage0_begin(round)?;
5989        let _walk = pipe.coordinated_walk()?;
5990        let ticket = self.verify_stage0_issue(
5991            e,
5992            tokens,
5993            pos0,
5994            cache,
5995            embd_dev,
5996            ckpt.as_deref_mut(),
5997            None,
5998            &fence,
5999            Some(interval_fence),
6000            pipe.trace(round),
6001        )?;
6002        pipe.stage0_end(round);
6003        pipe.stage1_begin(round)?;
6004        let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
6005        pipe.verify_end(round);
6006        Ok(result)
6007    }
6008
6009    /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
6010    /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
6011    /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
6012    /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
6013    /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
6014    /// `vtok_dev` (engine-bundle slice 2): device verify tokens for the EMBED only —
6015    /// unlike `stream` mode it changes nothing else (host pos iota, host-len KV appends).
6016    /// `tokens` then only sizes buffers (the dummy-slice pattern the round-stream arm uses).
6017    #[allow(clippy::too_many_arguments)]
6018    fn decode_step_t_core_stream(
6019        &self,
6020        e: &Engine,
6021        tokens: &[u32],
6022        pos0: usize,
6023        cache: &mut Cache,
6024        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6025        mut ckpt: Option<&mut VerifyCkpt>,
6026        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6027        pp_pipe: Option<bool>,
6028        vtok_dev: Option<&CudaSlice<u32>>,
6029        graphs: Option<&mut DsparkVerifyGraphs>,
6030    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6031        // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
6032        // exactly as the eager and batched steps do. This is the single funnel every verify
6033        // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
6034        // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
6035        // is untouched.
6036        //
6037        // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
6038        // walk was unsplit on one stream and a sharded cross-device placement peer-read every
6039        // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
6040        // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
6041        // or a placement whose PpNRt fails to build — so a config that would still walk the
6042        // whole trunk on one stream refuses instead of regressing 28x.
6043        if let Some(fence) = crate::pp::pp_cuts(self.layers.len())
6044            && !crate::pp::pp2_streams_off()
6045            && crate::pp::spec_pp_on()
6046        {
6047            if vtok_dev.is_some() {
6048                return Err(
6049                    "device-token dspark verify (slice-2 deferred readback) has no PP \
6050                         stage-split arm; set MEMRA_DSPARK_DEFER_READBACK=0 or run the dspark \
6051                         route on one device"
6052                        .into(),
6053                );
6054            }
6055            return self.decode_step_t_core_ppn(
6056                e,
6057                tokens,
6058                pos0,
6059                cache,
6060                embd_dev,
6061                ckpt.take(),
6062                stream,
6063                &fence,
6064                pp_pipe,
6065            );
6066        }
6067        crate::pp::refuse_unsplit_if_remote(
6068            "decode_step_t (spec verify)",
6069            "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
6070             split (decode_step_t_core_ppn); or run spec on one device",
6071        )?;
6072        let cfg = &self.cfg;
6073        let n_embd = cfg.n_embd as usize;
6074        let eps = cfg.rms_eps;
6075        let t = tokens.len();
6076        let pos_d = match stream {
6077            Some((_, ctr)) => {
6078                let mut p = e.alloc_uninit::<i32>(t)?;
6079                e.pos_iota(ctr, &mut p, t)?;
6080                p
6081            }
6082            None => {
6083                let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6084                e.htod_i32(&pos_vec)?
6085            }
6086        };
6087
6088        // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
6089        let x = match (stream, embd_dev) {
6090            (Some((vtok, _)), Some((g, qt, rb))) => {
6091                e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
6092            }
6093            (None, Some((g, qt, rb))) => match vtok_dev {
6094                // slice 2: device verify tokens, same embed_gather_u32_t kernel —
6095                // bit-identical rows to the host-token arm (same per-dtype deq).
6096                Some(vt_d) => e.embed_gather_device_td(g, vt_d, t, n_embd, qt, rb)?,
6097                None => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
6098            },
6099            _ => {
6100                assert!(
6101                    vtok_dev.is_none(),
6102                    "device-token verify requires the resident embed table (embd_dev)"
6103                );
6104                e.htod(&self.embd.gather(n_embd, tokens))?
6105            }
6106        };
6107
6108        // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
6109        // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
6110        // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
6111        let x = self.verify_layers(
6112            e,
6113            x,
6114            0,
6115            self.layers.len(),
6116            &pos_d,
6117            pos0,
6118            t,
6119            cache,
6120            ckpt.take(),
6121            stream,
6122            graphs,
6123        )?;
6124        if spec_nan_scan() {
6125            nan_scan_rows(e, &x, t, n_embd, &format!("verify trunk exit pos0={pos0}"))?;
6126        }
6127
6128        let mut hn = vbuf(e, t * n_embd)?;
6129        // Stage-A door: with the serving-class row-outer verify walk, the TAIL must be the
6130        // t=1 decode program per row too (rms_norm t=1 + the single-row bf16 head — the
6131        // split head's concat is receipted bit-identical to it). The batched cuBLASLt head
6132        // is a different ULP class and flips near-tie argmaxes off the greedy tape.
6133        let eager_tail = self.sliding_gated_moe_batch_program() && spec_verify_eager_on();
6134        if eager_tail {
6135            let n_vocab = self.cfg.n_vocab as usize;
6136            // MEMRA_SPEC_HEAD_ROWS=1 — THE VERIFY TAIL'S REDUNDANT HEAD READ.
6137            //
6138            // The loop below runs the head at m=1 once PER COLUMN, so the LM head's weights are
6139            // streamed t times per verify pass. On step37 that head is ~0.49 GiB per card after the
6140            // rank split, ~1.07 ms of pure re-read at t=2 and worse at every wider t — which is a
6141            // large part of why the fixed K ladder LOSES (K=1 81.2 > K=2 73.1 > K=3 62.7 tok/s).
6142            //
6143            // The loop's justification is the comment above: the batched cuBLASLt head is a
6144            // different ULP class and flips near-tie argmaxes off the greedy tape. That is true of
6145            // cuBLASLt and it does NOT apply here, because a FloatBf16 head at 1..=32 rows never
6146            // reaches cuBLASLt: `matmul` routes it to `matvec_bf16_rows_into` (lib.rs:12248), whose
6147            // own doc says `matvec_bf16_f32acc_x4_rows` "runs the t=1 decode head program PER ROW
6148            // (identical dot + reduce), so decode/verify tiers keep the t=1 numeric class". Under
6149            // the W8 doors both widths route to the q8 mirror instead, and the t-column mirror is
6150            // documented "bit-identical to t single-row calls". So the batched form is the SAME
6151            // arithmetic per row on both paths, with one weight read instead of t.
6152            //
6153            // rms_norm is row-wise, so norm(t) is per-row identical to t x norm(1) by construction.
6154            //
6155            // DEFAULT OFF for exactly one turn of the crank: "bit-identical by two documented
6156            // claims" is still an argument. The greedy byte tape decides, and the door flips only
6157            // once the tape is a receipt.
6158            if head_rows_on() {
6159                e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6160                let logits = e.matmul(&self.output, &hn, t)?;
6161                if stream.is_none() {
6162                    cache.pos += t;
6163                }
6164                return Ok((logits, if spec_hpost() { hn } else { x }));
6165            }
6166            let mut logits = vbuf(e, t * n_vocab)?;
6167            for r in 0..t {
6168                let mut row = e.uninit(n_embd)?;
6169                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
6170                let mut hr = e.uninit(n_embd)?;
6171                e.rms_norm(&row, self.output_norm.float_data(), &mut hr, n_embd, 1, eps)?;
6172                let lr = e.matmul(&self.output, &hr, 1)?;
6173                e.dtod_copy_into(&lr, &mut logits, r * n_vocab)?;
6174                e.dtod_copy_into(&hr, &mut hn, r * n_embd)?;
6175            }
6176            if stream.is_none() {
6177                cache.pos += t;
6178            }
6179            return Ok((logits, if spec_hpost() { hn } else { x }));
6180        }
6181        let serving_head =
6182            self.sliding_gated_moe_batch_program() || self.batched_serving_numeric_class();
6183        let logits = if serving_head {
6184            // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
6185            // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
6186            // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
6187            // serve one batched numeric class at every live width, including B=1. Keep the
6188            // verify head in that same class; other generic families retain the decode-exact
6189            // head that their run-spec contract pins.
6190            e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6191            e.matmul(&self.output, &hn, t)?
6192        } else {
6193            e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6194            e.matmul_decode_exact(&self.output, &hn, t)?
6195        };
6196        // stream: the device pos counter owns position; host mirror reconciles at drain.
6197        if stream.is_none() {
6198            cache.pos += t;
6199        }
6200        // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
6201        Ok((logits, if spec_hpost() { hn } else { x }))
6202    }
6203
6204    /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
6205    /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
6206    /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
6207    /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
6208    /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
6209    /// the payload).
6210    ///
6211    /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
6212    /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
6213    /// receipts):
6214    ///
6215    /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
6216    ///    (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
6217    ///    DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
6218    ///    (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
6219    ///    s>0 its own Engine even on the primary device; honouring it here is what scopes the
6220    ///    pools. The verify path allocates MORE of that scratch than eager decode does (FA at
6221    ///    m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
6222    ///
6223    /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
6224    ///    buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
6225    ///    stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
6226    ///    read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
6227    ///    stage derives the identical iota, and each stage's own output buffer is stream-local.
6228    ///
6229    /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
6230    ///    sharded loader leaves the table with stage 0 by construction).
6231    ///
6232    /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
6233    ///    both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
6234    ///    n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
6235    ///    model, every round.
6236    ///
6237    /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
6238    /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
6239    /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
6240    /// through the primary context by UVA — the same read the batched serving epilogue's
6241    /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
6242    /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
6243    ///
6244    /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
6245    /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
6246    /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
6247    ///
6248    /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
6249    /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
6250    /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
6251    /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
6252    /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
6253    /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
6254    /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
6255    /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
6256    #[allow(clippy::too_many_arguments)]
6257    fn decode_step_t_core_ppn(
6258        &self,
6259        e: &Engine,
6260        tokens: &[u32],
6261        pos0: usize,
6262        cache: &mut Cache,
6263        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6264        mut ckpt: Option<&mut VerifyCkpt>,
6265        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6266        fence: &[usize],
6267        pp_pipe: Option<bool>,
6268    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6269        let ticket = self.verify_stage0_issue(
6270            e,
6271            tokens,
6272            pos0,
6273            cache,
6274            embd_dev,
6275            ckpt.as_deref_mut(),
6276            stream,
6277            fence,
6278            pp_pipe,
6279            None,
6280        )?;
6281        self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
6282    }
6283
6284    /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
6285    /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
6286    #[allow(clippy::too_many_arguments)]
6287    fn verify_stage0_issue(
6288        &self,
6289        e: &Engine,
6290        tokens: &[u32],
6291        pos0: usize,
6292        cache: &mut Cache,
6293        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6294        ckpt: Option<&mut VerifyCkpt>,
6295        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6296        fence: &[usize],
6297        pp_pipe: Option<bool>,
6298        trace: Option<SpecPipeTraceCtx>,
6299    ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
6300        assert!(
6301            !self.is_gemma4_e4b() && !self.gemma_batch_program(),
6302            "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
6303             (the gemma4 arms have their own decode_step_t twins)"
6304        );
6305        if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
6306            return Err(
6307                "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
6308                 boundary itself is host-staged, but device-resident verify still peer-reads \
6309                 primary-device token/position/embedding buffers from stage 0. Run plain PP \
6310                 serving on this host class; spec requires local per-stage inputs first."
6311                    .into(),
6312            );
6313        }
6314        let rt = crate::pp::PpNRt::get(e)?;
6315        // Pipelined callers do not bypass ownership: their explicit coordinator borrow makes
6316        // this acquire clone the same active generation. Ordinary callers acquire a fresh lease.
6317        let walk_owner = rt.acquire_walk("verify_stage0_issue")?;
6318        let n_st = fence.len() - 1;
6319        assert_eq!(
6320            rt.n_stages(),
6321            n_st,
6322            "PpNRt stage count {} != fence stages {n_st}",
6323            rt.n_stages()
6324        );
6325        let n_embd = self.cfg.n_embd as usize;
6326        let t = tokens.len();
6327        let payload = t * n_embd;
6328        if pp_pipe.is_some() {
6329            assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
6330        }
6331        // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
6332        // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
6333        // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
6334        // the report below names exactly two stages and must never imply it measured middle ones.
6335        let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
6336        let pp_started = std::time::Instant::now();
6337        let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
6338        // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
6339        // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
6340        // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
6341        // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
6342        // stage stream and the wait would self-order into a no-op.
6343        let caller_stream = e.stream();
6344        // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
6345        // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
6346        // the primary stream still holds queued reads of them — with event tracking elided,
6347        // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
6348        // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
6349        // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
6350        // stage stream behind the caller before enqueueing new stage work.
6351        let reverse_started = std::time::Instant::now();
6352        if pp_pipe != Some(false) {
6353            rt.fence_stages_behind(&caller_stream)?;
6354        }
6355        if pp_pipe == Some(true) {
6356            // Both session verifies must alternate boundary slots even when the ordinary
6357            // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
6358            // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
6359            rt.prepare_overlap_slots(0, payload)?;
6360        }
6361        if pp_anatomy {
6362            // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
6363            // prices any primary-stream rollback/refresh tail inherited from the prior round.
6364            for s in 0..n_st {
6365                let _st = rt.enter(s);
6366                rt.engine(s, e).stream().synchronize()?;
6367            }
6368            reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
6369        }
6370
6371        // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
6372        // stream mode each stage's own `pos_iota` over the shared read-only device counter.
6373        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
6374            match stream {
6375                Some((_, ctr)) => {
6376                    let mut p = es.alloc_uninit::<i32>(t)?;
6377                    es.pos_iota(ctr, &mut p, t)?;
6378                    Ok(p)
6379                }
6380                None => {
6381                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6382                    es.htod_i32(&pos_vec)
6383                }
6384            }
6385        };
6386
6387        // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
6388        let slot = {
6389            let _st0 = rt.enter(0);
6390            let e0 = rt.engine(0, e);
6391            enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
6392            let stage0_started = std::time::Instant::now();
6393            let pos_d = stage_pos(e0)?;
6394            let x = match (stream, embd_dev) {
6395                (Some((vtok, _)), Some((g, qt, rb))) => {
6396                    e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
6397                }
6398                (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
6399                _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
6400            };
6401            let x = self.verify_layers(
6402                e0, x, fence[0], fence[1], &pos_d, pos0, t, cache, ckpt, stream, None,
6403            )?;
6404            if pp_anatomy {
6405                e0.stream().synchronize()?;
6406                stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
6407            }
6408            let tx_started = std::time::Instant::now();
6409            let slot = if pp_pipe.is_some() {
6410                rt.tx_pipelined(0, &x, payload)?
6411            } else {
6412                rt.tx(0, &x, payload)?
6413            };
6414            enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
6415            if pp_anatomy {
6416                e0.stream().synchronize()?;
6417                tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
6418            }
6419            slot
6420            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
6421        };
6422
6423        Ok(VerifyBoundaryTicket {
6424            rt,
6425            caller_stream,
6426            slot,
6427            pos0,
6428            t,
6429            payload,
6430            n_st,
6431            pipelined: pp_pipe.is_some(),
6432            pp_anatomy,
6433            pp_started,
6434            reverse_ms,
6435            stage0_ms,
6436            tx_ms,
6437            trace,
6438            _walk_owner: walk_owner,
6439        })
6440    }
6441
6442    /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
6443    /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
6444    #[allow(clippy::too_many_arguments)]
6445    fn verify_stage1_finish(
6446        &self,
6447        e: &Engine,
6448        ticket: VerifyBoundaryTicket,
6449        cache: &mut Cache,
6450        mut ckpt: Option<&mut VerifyCkpt>,
6451        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6452        fence: &[usize],
6453        publish_to_caller: bool,
6454    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6455        let VerifyBoundaryTicket {
6456            rt,
6457            caller_stream,
6458            slot,
6459            pos0,
6460            t,
6461            payload,
6462            n_st,
6463            pipelined,
6464            pp_anatomy,
6465            pp_started,
6466            reverse_ms,
6467            stage0_ms,
6468            tx_ms,
6469            trace,
6470            _walk_owner,
6471        } = ticket;
6472        let n_embd = self.cfg.n_embd as usize;
6473        let eps = self.cfg.rms_eps;
6474        let mut slot = slot;
6475        let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
6476        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
6477            match stream {
6478                Some((_, ctr)) => {
6479                    let mut p = es.alloc_uninit::<i32>(t)?;
6480                    es.pos_iota(ctr, &mut p, t)?;
6481                    Ok(p)
6482                }
6483                None => {
6484                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6485                    es.htod_i32(&pos_vec)
6486                }
6487            }
6488        };
6489
6490        // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
6491        for s in 1..n_st - 1 {
6492            let _st = rt.enter(s);
6493            let es = rt.engine(s, e);
6494            let pos_d = stage_pos(es)?;
6495            let x = rt.rx(s - 1, slot, payload)?;
6496            let x = self.verify_layers(
6497                es,
6498                x,
6499                fence[s],
6500                fence[s + 1],
6501                &pos_d,
6502                pos0,
6503                t,
6504                cache,
6505                ckpt.as_deref_mut(),
6506                stream,
6507                None,
6508            )?;
6509            slot = if pipelined {
6510                rt.tx_pipelined(s, &x, payload)?
6511            } else {
6512                rt.tx(s, &x, payload)?
6513            };
6514        }
6515
6516        // ---- LAST STAGE: RX + final range + output_norm + lm head ----
6517        let _stl = rt.enter(n_st - 1);
6518        let el = rt.engine(n_st - 1, e);
6519        let pos_d = stage_pos(el)?;
6520        let rx_started = std::time::Instant::now();
6521        let x = rt.rx(n_st - 2, slot, payload)?;
6522        if pp_anatomy {
6523            el.stream().synchronize()?;
6524            rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
6525        }
6526        enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
6527        let stage1_started = std::time::Instant::now();
6528        let x = self.verify_layers(
6529            el,
6530            x,
6531            fence[n_st - 1],
6532            fence[n_st],
6533            &pos_d,
6534            pos0,
6535            t,
6536            cache,
6537            ckpt,
6538            stream,
6539            None,
6540        )?;
6541
6542        let mut hn = vbuf(el, payload)?;
6543        let logits = if self.sliding_gated_moe_batch_program() {
6544            // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
6545            // Verify must not switch numeric class merely because the same session speculates.
6546            el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6547            el.matmul(&self.output, &hn, t)?
6548        } else {
6549            el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6550            el.matmul_decode_exact(&self.output, &hn, t)?
6551        };
6552        enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
6553        if pp_anatomy {
6554            el.stream().synchronize()?;
6555            stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
6556        }
6557        // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
6558        // stream. Order the caller's stream behind that work before the buffers escape this
6559        // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
6560        // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
6561        // the following arm's KV in the same process).
6562        if publish_to_caller {
6563            rt.publish_to(n_st - 1, &caller_stream)?;
6564        }
6565        if pp_anatomy {
6566            if publish_to_caller {
6567                caller_stream.synchronize()?;
6568            }
6569            eprintln!(
6570                "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
6571                 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
6572                pp_started.elapsed().as_secs_f64() * 1e3,
6573            );
6574        }
6575        // stream: the device pos counter owns position; host mirror reconciles at drain.
6576        if stream.is_none() {
6577            cache.pos += t;
6578        }
6579        Ok((logits, if spec_hpost() { hn } else { x }))
6580    }
6581
6582    /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
6583    ///
6584    /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
6585    /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
6586    /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
6587    /// Those classes are individually stable, but a near-tie prompt can choose different greedy
6588    /// bytes when a request moves from batched plain serving into speculative verify. Run the
6589    /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
6590    /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
6591    /// every norm/projection/FFN uses exactly the live serving dispatch.
6592    #[allow(clippy::too_many_arguments)]
6593    /// PRIME-BY-T-ROWS (MEMRA_PRIME_TROWS=1): prefill the prompt through the same-session
6594    /// t-row walk in 32-row chunks — every row runs the t=1 decode program bit-for-bit
6595    /// (the TOKENWISE-prime ORACLE class), so this door is exact against the exactness
6596    /// reference while replacing the host-canonical per-token prime. Requires the walk
6597    /// doors (MEMRA_SPEC_VERIFY_EAGER/TCOL); returns the prime contract trio.
6598    #[allow(clippy::type_complexity)]
6599    pub(crate) fn step35_prime_trows(
6600        &self,
6601        e: &Engine,
6602        tokens: &[u32],
6603        cache: &mut Cache,
6604    ) -> Result<Option<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>>
6605    {
6606        let dbg = std::env::var("MEMRA_SPEC_FA2_DEBUG").as_deref() == Ok("1");
6607        if !prime_trows_on() {
6608            return Ok(None);
6609        }
6610        if !self.uses_sliding_gated_moe_program()
6611            || cache.pos != 0
6612            || cache.dflash_taps.is_some()
6613            || !spec_verify_eager_on()
6614            || !spec_verify_tcol_on()
6615        {
6616            if dbg {
6617                eprintln!(
6618                    "[prime-trows] refuse: program={} pos={} taps={} eager={:?} tcol={:?}",
6619                    self.uses_sliding_gated_moe_program(),
6620                    cache.pos,
6621                    cache.dflash_taps.is_some(),
6622                    std::env::var("MEMRA_SPEC_VERIFY_EAGER").ok(),
6623                    std::env::var("MEMRA_SPEC_VERIFY_TCOL").ok()
6624                );
6625            }
6626            return Ok(None);
6627        }
6628        let n_embd = self.cfg.n_embd as usize;
6629        let n_layers = self.layers.len();
6630        let t_total = tokens.len();
6631        let Some(embd_gpu) = self.embd_gpu_try(e) else {
6632            if dbg {
6633                eprintln!("[prime-trows] refuse: no device embed table");
6634            }
6635            return Ok(None);
6636        };
6637        let embd_qtype = match self.embd.ggml_type {
6638            memra_gguf::GgmlType::BF16 => crate::QT_BF16,
6639            memra_gguf::GgmlType::Q8_0 => crate::QT_Q8_0,
6640            other => {
6641                if dbg {
6642                    eprintln!("[prime-trows] refuse: embed dtype {other:?}");
6643                }
6644                return Ok(None);
6645            }
6646        };
6647        let embd_row_bytes = self.embd.raw.len() / self.cfg.n_vocab as usize;
6648        // Chunk plan: 32-row chunks; a 1-token tail folds into the previous chunk
6649        // (the walk floor is t >= 2).
6650        let mut bounds = Vec::new();
6651        let mut start = 0usize;
6652        while start < t_total {
6653            let mut end = (start + 32).min(t_total);
6654            if t_total - end == 1 {
6655                end -= 1;
6656            }
6657            bounds.push((start, end));
6658            start = end;
6659        }
6660        if bounds.iter().any(|(a, b)| b - a < 2) {
6661            return Ok(None); // degenerate short prompt keeps the ordinary prime
6662        }
6663        let mut hiddens = e.uninit(t_total * n_embd)?;
6664        let mut last: Option<CudaSlice<f32>> = None;
6665        for &(a, b) in &bounds {
6666            let tc = b - a;
6667            let tok_d = e.stream().clone_htod(&tokens[a..b])?;
6668            let x =
6669                e.embed_gather_device_td(embd_gpu, &tok_d, tc, n_embd, embd_qtype, embd_row_bytes)?;
6670            let out = self.step35_verify_batch_layers(e, x, 0, n_layers, a, tc, cache)?;
6671            e.copy_into(&mut hiddens, a * n_embd, &out, tc * n_embd)?;
6672            if b == t_total {
6673                let mut h = e.uninit(n_embd)?;
6674                e.dtod_copy_view(&out.slice((tc - 1) * n_embd..tc * n_embd), &mut h)?;
6675                last = Some(h);
6676            }
6677        }
6678        let h_seed = last.expect("last chunk produced the seed row");
6679        let mut hn = e.uninit(n_embd)?;
6680        e.rms_norm_decode(
6681            &h_seed,
6682            self.output_norm.float_data(),
6683            &mut hn,
6684            n_embd,
6685            1,
6686            self.cfg.rms_eps,
6687        )?;
6688        let logits_d = e.matmul_decode_exact(&self.output, &hn, 1)?;
6689        let logits = e.dtoh(&logits_d)?;
6690        cache.pos = t_total;
6691        Ok(Some((logits, h_seed, hiddens)))
6692    }
6693
6694    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
6695    fn step35_verify_batch_layers(
6696        &self,
6697        e: &Engine,
6698        mut x: CudaSlice<f32>,
6699        lo: usize,
6700        hi: usize,
6701        pos0: usize,
6702        t: usize,
6703        cache: &mut Cache,
6704    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6705        let n_embd = self.cfg.n_embd as usize;
6706        if !self.uses_sliding_gated_moe_program() {
6707            return Err(
6708                "serving-class verify requires sliding-gated-MoE canonical operations".into(),
6709            );
6710        }
6711        // SERVING-CLASS VERIFY (MEMRA_SPEC_VERIFY_EAGER=1, step37 MTP bring-up): each verify
6712        // column rides decode_layers_eager — the EXACT t=1 program live serving runs (all TP2
6713        // doors) — row-outer, so row r's appends land before row r+1 attends: bit-equal to
6714        // plain greedy by construction. Only the unsplit full-range walk qualifies; PP splits
6715        // and the tap path keep the batch-layer class.
6716        static VE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6717        let eager_verify =
6718            *VE.get_or_init(spec_verify_eager_on) && lo == 0 && hi == self.layers.len();
6719        if eager_verify {
6720            // T-COLUMN LAYER-OUTER WALK (MEMRA_SPEC_VERIFY_TCOL=1): per layer, one t-grid
6721            // attn norm + ONE weight-amortized QKV(+gate) over all T columns, then each
6722            // column runs the UNMODIFIED t=1 attention program via the col-select door and
6723            // the ordinary residual/FFN body. Values per column are bit-equal to the
6724            // row-outer walk: rms over the materialized residual == the fused add+norm
6725            // (kernel_check identity), the tcol kernel's per-column FP order == the t=1
6726            // kernel, and every downstream op IS the t=1 program.
6727            static TCOL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6728            let tcol = *TCOL.get_or_init(spec_verify_tcol_on);
6729            // T > 32 (prefill-class): run the SAME walk in 32-row chunks — each chunk's
6730            // rows are the t=1 program bit-for-bit and the rope pass advances the cache,
6731            // so a chunked call is value-identical to the row-outer loop it replaces.
6732            static TROWS_PREFILL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6733            // MEMRA_STEP_GEMM_PRIME outranks the walk: with the grouped GEMM prime armed, the
6734            // t-row walk defers so the batch path (GEMM trunk + grouped MoE) takes the prompt —
6735            // flag precedence between two existing doors, not a new flag. Without this, both
6736            // doors ON meant the walk still won and the GEMM prime needed PRIME_TROWS=0 by hand.
6737            let trows_prefill =
6738                *TROWS_PREFILL.get_or_init(|| prime_trows_on() && !crate::step_gemm_prime_on());
6739            // MEMRA_PRIME_TROWS_T=<w>: chunk width, default 8 = the REAL cap of this walk.
6740            // The workspace slabs go to 32 rows, but `matvec_bf16_qkvg_tcol_into` refuses
6741            // t > 8 (compile-time-T twins exist for 2/4/8 only; the runtime-t kernel spills
6742            // its accumulators to local memory), so a wider chunk fails the request with
6743            // "matvec_bf16_qkvg_tcol geometry" — which is exactly how the first server-path
6744            // TROWS arm died. Measured at 193 tokens: w=8 2.459 s, w=4 2.574 s.
6745            static TROWS_W: std::sync::OnceLock<Result<usize, String>> = std::sync::OnceLock::new();
6746            let trows_w = match TROWS_W.get_or_init(|| {
6747                let value = std::env::var("MEMRA_PRIME_TROWS_T").ok();
6748                parse_prime_trows_width(value.as_deref())
6749            }) {
6750                Ok(width) => *width,
6751                Err(err) => return Err(err.clone().into()),
6752            };
6753            if tcol && trows_prefill && t > trows_w {
6754                // One-time engagement receipt: without it a prefill gate cannot tell a
6755                // chunked walk from the row-outer fallback it is supposed to replace
6756                // (the first PRIME_TROWS gate passed vacuously on exactly that).
6757                static SEEN: std::sync::atomic::AtomicBool =
6758                    std::sync::atomic::AtomicBool::new(false);
6759                if !SEEN.swap(true, std::sync::atomic::Ordering::Relaxed) {
6760                    eprintln!(
6761                        "[prime-trows] ENGAGED t={t} width={trows_w} chunks={} layers={}..{}",
6762                        t.div_ceil(trows_w),
6763                        lo,
6764                        hi
6765                    );
6766                }
6767                let mut out = e.uninit(t * n_embd)?;
6768                let mut start = 0usize;
6769                while start < t {
6770                    let mut end = (start + trows_w).min(t);
6771                    if t - end == 1 {
6772                        end -= 1;
6773                    }
6774                    let tc = end - start;
6775                    let mut xc = e.uninit(tc * n_embd)?;
6776                    e.dtod_copy_view(&x.slice(start * n_embd..end * n_embd), &mut xc)?;
6777                    let oc =
6778                        self.step35_verify_batch_layers(e, xc, lo, hi, pos0 + start, tc, cache)?;
6779                    e.copy_into(&mut out, start * n_embd, &oc, tc * n_embd)?;
6780                    start = end;
6781                }
6782                return Ok(out);
6783            }
6784            if tcol && (2..=32).contains(&t) {
6785                // MEMRA_TCOL_PROF=1: synchronized per-segment wall profile of the walk
6786                // (norm+QKV precompute / per-col attention / per-col residual+FFN). The
6787                // syncs serialize the stream, so the split is for TARGETING amortization
6788                // work only — never a perf claim.
6789                static PROF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6790                let prof =
6791                    *PROF.get_or_init(|| std::env::var("MEMRA_TCOL_PROF").as_deref() == Ok("1"));
6792                let mut prof_ms = [0f64; 3];
6793                let eps = self.cfg.rms_eps;
6794                let mut x_t = x;
6795                let mut h_t = e.uninit(t * n_embd)?;
6796                let mut h_row = e.uninit(n_embd)?; // real row: the non-dcw fallback reads it
6797                // Per-column pos buffers hoisted out of the layer loop (a per-col-per-layer
6798                // pageable htod was an in-stream engine turnaround x t x 45).
6799                let mut pos_rows = Vec::with_capacity(t);
6800                for r in 0..t {
6801                    pos_rows.push(e.htod_i32(&[(pos0 + r) as i32])?);
6802                }
6803                let mut ok = true;
6804                // MEMRA_TCOL_OPROJ=1: defer each column's o_proj — the finish seam
6805                // stashes `gated` instead of joining per column; one b4_tcol per rank +
6806                // one slab join produce every column's `mixed` after the attention pass.
6807                // Bit-exact per column (t=1 b4 program per column; elementwise join).
6808                // MEMRA_TCOL_FFN=1: today this only IMPLIES the o_proj defer above. Its
6809                // named feature, the two-column device-routed FFN sweep, rode the
6810                // slot-major v2 TP banks and was REMOVED with the MEMRA_NVFP4_BANK_V2 door
6811                // (2026-08-29, research/step37-bankv2-removal-20260829): the v2 layout
6812                // changed generated text in serving. The flag itself stays because it is
6813                // family-armed in the step37 serving defaults and killing it here would
6814                // silently drop the o_proj defer from the qualified serving shape.
6815                static FFN2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6816                let ffn_batch = *FFN2.get_or_init(tcol_ffn_on);
6817                let oproj_batch = crate::tp::tcol_oproj_on() || ffn_batch;
6818                // MEMRA_SPEC_FA2=1 (T=2 only): eligible layers defer BOTH columns' fa —
6819                // the per-column pass norms/ropes/appends and stashes q+gate, then one
6820                // shared-KV fa_decode_dcw2 per rank + the o_proj join produce the
6821                // [2, o_out] mixed slab. The precheck runs before arming (stashing is
6822                // unrecoverable); ineligible/boundary layers run the ordinary program.
6823                let fa2 = crate::tp::spec_fa2_on() && t <= 32;
6824                let mut mixed_row = e.uninit(n_embd)?;
6825                let mut pos_staged = false;
6826                for il in lo..hi {
6827                    let layer = &self.layers[il];
6828                    // BEFORE this layer touches its planes: is the history it is about to
6829                    // attend already poisoned? Global (non-ring) layers only, which are the
6830                    // ones the level-2 bitmap implicates.
6831                    if kv_plane_scan_on()
6832                        && self.step35_geom(il).window.is_none()
6833                        && let Some(distributed) = cache.tp_kv[il].as_ref()
6834                    {
6835                        scan_kv_plane(e, distributed, il, pos0)?;
6836                    }
6837                    let fa2_layer = fa2 && self.step35_fa_rows_precheck(cache, il, pos0, t)?;
6838                    let mut seg = std::time::Instant::now();
6839                    e.rms_norm(&x_t, layer.attn_norm.float_data(), &mut h_t, n_embd, t, eps)?;
6840                    if !self.step35_verify_qkv_precompute(e, il, &h_t, t)? {
6841                        ok = false;
6842                        break;
6843                    }
6844                    // FULL t-row attention pass (rope/append + fa + combine + o_proj in
6845                    // 3 launches/rank): same-session rows, slot = len-base+r, one len
6846                    // advance by t. Host cache bookkeeping mirrors the per-column tail.
6847                    if fa2_layer
6848                        && let Some(mixed_t) =
6849                            self.step35_verify_rope_fa_pass(e, il, cache, pos0, t, !pos_staged)?
6850                    {
6851                        pos_staged = true;
6852                        {
6853                            let tp_kv = cache.tp_kv[il]
6854                                .as_mut()
6855                                .expect("precheck verified the distributed cache");
6856                            let transaction = tp_kv.begin_transaction()?;
6857                            let crate::hybrid::Mixer::Full(fa) = &layer.mixer else {
6858                                return Err("verify rope pass expects full attention".into());
6859                            };
6860                            let tp = fa
6861                                .step_tp_qkv
6862                                .as_ref()
6863                                .ok_or("verify rope pass lost its TP state")?;
6864                            let empty: [CudaSlice<f32>; 0] = [];
6865                            tp.runtime.append_tp_kv_transaction_inner(
6866                                tp_kv,
6867                                transaction,
6868                                &empty,
6869                                &empty,
6870                                t,
6871                                true,
6872                            )?;
6873                            tp.runtime
6874                                .commit_tp_kv_transaction_external(tp_kv, transaction, t)?;
6875                            if let Some(local) = cache.kv[il].as_mut() {
6876                                local.len = pos0 + t;
6877                                if !crate::tp::len_mirror_lazy_on() {
6878                                    e.set_i32_one(&mut local.len_d, local.len as i32)?;
6879                                }
6880                            }
6881                        }
6882                        if prof {
6883                            e.stream().synchronize()?;
6884                            prof_ms[1] += seg.elapsed().as_secs_f64() * 1e3;
6885                            seg = std::time::Instant::now();
6886                        }
6887                        let o_out = mixed_t.len() / t;
6888                        let mut next = e.uninit(t * n_embd)?;
6889                        {
6890                            for r in 0..t {
6891                                e.dtod_copy_view(
6892                                    &mixed_t.slice(r * o_out..(r + 1) * o_out),
6893                                    &mut mixed_row,
6894                                )?;
6895                                let mut x_row = e.uninit(n_embd)?;
6896                                e.dtod_copy_view(
6897                                    &x_t.slice(r * n_embd..(r + 1) * n_embd),
6898                                    &mut x_row,
6899                                )?;
6900                                let (x1, ffn_out) = self.residual_norm_ffn(
6901                                    e, layer, &x_row, &mixed_row, n_embd, il, eps,
6902                                )?;
6903                                let mut x2 = e.uninit(n_embd)?;
6904                                e.add(&x1, &ffn_out, &mut x2, n_embd)?;
6905                                e.dtod_copy_into(&x2, &mut next, r * n_embd)?;
6906                            }
6907                        }
6908                        if prof {
6909                            e.stream().synchronize()?;
6910                            prof_ms[2] += seg.elapsed().as_secs_f64() * 1e3;
6911                        }
6912                        x_t = next;
6913                        if spec_nan_scan() {
6914                            // The scan MUST sit on this arm too. It used to live only on
6915                            // the non-fused tail, so a fused layer's poison was first
6916                            // reported by the next non-fused layer.
6917                            verify_arm_receipt(
6918                                "fused",
6919                                il,
6920                                pos0,
6921                                t,
6922                                cache.tp_kv[il].as_ref().map(|d| d.staged_len()),
6923                            );
6924                            nan_scan_rows(
6925                                e,
6926                                &x_t,
6927                                t,
6928                                n_embd,
6929                                &format!("tcol layer {il} pos0={pos0} arm=fused"),
6930                            )?;
6931                        }
6932                        continue;
6933                    }
6934                    if prof {
6935                        e.stream().synchronize()?;
6936                        prof_ms[0] += seg.elapsed().as_secs_f64() * 1e3;
6937                        seg = std::time::Instant::now();
6938                    }
6939                    let mut next = e.uninit(t * n_embd)?;
6940                    // Columns whose o_proj was deferred (their FFN runs after the join).
6941                    // A NON-deferred column's FFN must run INSIDE the column loop: the
6942                    // oproj-tail handoff is a single cell that the same column's
6943                    // residual_norm_ffn consumes before the next column's finish.
6944                    let mut deferred: Vec<usize> = Vec::new();
6945                    let mut fa2_deferred: Vec<usize> = Vec::new();
6946                    let ffn_col = |r: usize,
6947                                   mixed: &CudaSlice<f32>,
6948                                   next: &mut CudaSlice<f32>|
6949                     -> Result<(), Box<dyn std::error::Error>> {
6950                        let mut x_row = e.uninit(n_embd)?;
6951                        e.dtod_copy_view(&x_t.slice(r * n_embd..(r + 1) * n_embd), &mut x_row)?;
6952                        let (x1, ffn_out) =
6953                            self.residual_norm_ffn(e, layer, &x_row, mixed, n_embd, il, eps)?;
6954                        if spec_nan_scan_level() >= 2 {
6955                            nan_scan_rows(
6956                                e,
6957                                &ffn_out,
6958                                1,
6959                                n_embd,
6960                                &format!("tcol layer {il} col {r} per-column FFN out"),
6961                            )?;
6962                        }
6963                        let mut x2 = e.uninit(n_embd)?;
6964                        e.add(&x1, &ffn_out, &mut x2, n_embd)?;
6965                        e.dtod_copy_into(&x2, next, r * n_embd)?;
6966                        Ok(())
6967                    };
6968                    #[allow(clippy::needless_range_loop)]
6969                    // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
6970                    for r in 0..t {
6971                        e.dtod_copy_view(&h_t.slice(r * n_embd..(r + 1) * n_embd), &mut h_row)?;
6972                        let row_pos = &pos_rows[r];
6973                        crate::tp::set_verify_tcol(Some(r));
6974                        if fa2_layer {
6975                            crate::tp::set_spec_fa2_defer(Some(r));
6976                        } else if oproj_batch {
6977                            crate::tp::set_tcol_oproj_defer(Some(r));
6978                        }
6979                        let mixed = match &layer.mixer {
6980                            crate::hybrid::Mixer::Full(fa) => {
6981                                self.full_attn_decode(e, fa, &h_row, row_pos, pos0 + r, cache, il)
6982                            }
6983                            _ => Err("step35 verify expects full attention".into()),
6984                        };
6985                        crate::tp::set_verify_tcol(None);
6986                        crate::tp::set_spec_fa2_defer(None);
6987                        crate::tp::set_tcol_oproj_defer(None);
6988                        let mixed = mixed?;
6989                        if fa2_layer && crate::tp::take_spec_fa2_stashed() {
6990                            fa2_deferred.push(r);
6991                        } else if oproj_batch && crate::tp::take_tcol_oproj_stashed() {
6992                            deferred.push(r);
6993                        } else {
6994                            if spec_nan_scan_level() >= 2 {
6995                                let cols = mixed.len();
6996                                nan_scan_rows(
6997                                    e,
6998                                    &mixed,
6999                                    1,
7000                                    cols,
7001                                    &format!("tcol layer {il} col {r} per-column ATTN out"),
7002                                )?;
7003                            }
7004                            ffn_col(r, &mixed, &mut next)?;
7005                        }
7006                    }
7007                    if !fa2_deferred.is_empty() && fa2_deferred.len() != t {
7008                        // The precheck guarantees both columns stash or neither; a strict
7009                        // subset means a column's output was never produced anywhere.
7010                        return Err("spec fa2 stash engaged for a subset of columns".into());
7011                    }
7012                    if prof {
7013                        e.stream().synchronize()?;
7014                        prof_ms[1] += seg.elapsed().as_secs_f64() * 1e3;
7015                        seg = std::time::Instant::now();
7016                    }
7017                    if !fa2_deferred.is_empty() {
7018                        deferred = fa2_deferred;
7019                    }
7020                    if !deferred.is_empty() {
7021                        let mixed_t = if fa2_layer {
7022                            self.step35_verify_fa_rows_join(e, il, cache, pos0, t)?
7023                        } else {
7024                            self.step35_verify_oproj_tcol(e, il, t)?
7025                        };
7026                        let o_out = mixed_t.len() / t;
7027                        if spec_nan_scan_level() >= 2 {
7028                            nan_scan_rows(
7029                                e,
7030                                &mixed_t,
7031                                t,
7032                                o_out,
7033                                &format!("tcol layer {il} JOINED attn over deferred cols"),
7034                            )?;
7035                        }
7036                        // Batched t=2 residual+MoE: one t-grid add_rms_norm (per-row
7037                        // program == t=1; bit-identical to the oproj-tail join per the
7038                        // M2 verbatim-program contract) feeding the two-column routed
7039                        // sweep. Ineligible layers (dense FFN, non-nvfp4) fall through
7040                        // to the per-column body.
7041                        {
7042                            for &r in &deferred {
7043                                e.dtod_copy_view(
7044                                    &mixed_t.slice(r * o_out..(r + 1) * o_out),
7045                                    &mut mixed_row,
7046                                )?;
7047                                ffn_col(r, &mixed_row, &mut next)?;
7048                            }
7049                        }
7050                    }
7051                    if prof {
7052                        e.stream().synchronize()?;
7053                        prof_ms[2] += seg.elapsed().as_secs_f64() * 1e3;
7054                    }
7055                    x_t = next;
7056                    if spec_nan_scan() {
7057                        verify_arm_receipt(
7058                            if fa2_layer { "join" } else { "percol" },
7059                            il,
7060                            pos0,
7061                            t,
7062                            cache.tp_kv[il].as_ref().map(|d| d.staged_len()),
7063                        );
7064                        nan_scan_rows(
7065                            e,
7066                            &x_t,
7067                            t,
7068                            n_embd,
7069                            &format!(
7070                                "tcol layer {il} pos0={pos0} arm={}",
7071                                if fa2_layer { "join" } else { "percol" }
7072                            ),
7073                        )?;
7074                    }
7075                }
7076                if prof {
7077                    eprintln!(
7078                        "[tcol-prof] t={t} norm+qkv={:.3}ms attn={:.3}ms ffn={:.3}ms",
7079                        prof_ms[0], prof_ms[1], prof_ms[2]
7080                    );
7081                }
7082                if ok {
7083                    return Ok(x_t);
7084                }
7085                // fall through to the row-outer walk on ineligible layers
7086                x = x_t;
7087            }
7088            let mut next = e.uninit(t * n_embd)?;
7089            let scan = spec_nan_scan();
7090            for r in 0..t {
7091                let mut row = e.uninit(n_embd)?;
7092                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
7093                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
7094                let out = if scan {
7095                    // Diagnostic arm: the same range walked one layer at a time so the first
7096                    // poisoned layer names itself. `decode_layers_eager(lo, hi)` is range-scoped
7097                    // and executes its trailing residual add, so a per-layer chain is the same
7098                    // program with the cross-layer add+norm fusion unrolled.
7099                    nan_scan_rows(
7100                        e,
7101                        &row,
7102                        1,
7103                        n_embd,
7104                        &format!("embed row r={r} pos={}", pos0 + r),
7105                    )?;
7106                    let mut acc = row;
7107                    for il in lo..hi {
7108                        acc = self.decode_layers_eager(
7109                            e,
7110                            acc,
7111                            il,
7112                            il + 1,
7113                            &row_pos,
7114                            pos0 + r,
7115                            cache,
7116                        )?;
7117                        nan_scan_rows(
7118                            e,
7119                            &acc,
7120                            1,
7121                            n_embd,
7122                            &format!("row-outer layer {il} r={r} pos={}", pos0 + r),
7123                        )?;
7124                    }
7125                    acc
7126                } else {
7127                    self.decode_layers_eager(e, row, lo, hi, &row_pos, pos0 + r, cache)?
7128                };
7129                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
7130            }
7131            // dflash taps are NOT produced on this arm (they need per-layer hiddens the
7132            // row-outer walk does not materialize); the door is a step37 MTP bring-up
7133            // surface where taps are unused.
7134            return Ok(next);
7135        }
7136        let mut ph_last = std::time::Instant::now();
7137        for il in lo..hi {
7138            let mut next = e.uninit(t * n_embd)?;
7139            for r in 0..t {
7140                let mut row = e.uninit(n_embd)?;
7141                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
7142                // The caller owns this verify's position. During controller overlap, cache.pos
7143                // still describes generation N while this stage-0 walk belongs to N+1.
7144                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
7145                let mut one = [&mut *cache];
7146                let out = self.step35_decode_batch_layers(
7147                    e,
7148                    row,
7149                    &mut one,
7150                    &[(pos0 + r) as i32],
7151                    &row_pos,
7152                    il,
7153                    il + 1,
7154                    &mut ph_last,
7155                )?;
7156                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
7157            }
7158            self.dflash_tap(e, cache, il, &next, t)?;
7159            x = next;
7160            if spec_nan_scan() {
7161                nan_scan_rows(e, &x, t, n_embd, &format!("batch-layer {il} pos0={pos0}"))?;
7162            }
7163        }
7164        Ok(x)
7165    }
7166
7167    /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
7168    /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
7169    /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
7170    /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
7171    /// prefix-keep, not all-or-nothing).
7172    pub(crate) fn dspark_verify_t_am(
7173        &self,
7174        e: &Engine,
7175        tokens: &[u32],
7176        pos0: usize,
7177        cache: &mut Cache,
7178    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
7179        let (logits, _hn) = self.decode_step_t_core_stream(
7180            e, tokens, pos0, cache, None, None, None, None, None, None,
7181        )?;
7182        let t = tokens.len();
7183        let v = self.output.out_features();
7184        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
7185        for r in 0..t {
7186            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
7187        }
7188        e.dtoh_u32(&am_d)
7189    }
7190
7191    /// DSpark verify returning the RAW verify logits [t, n_vocab] (device-resident) instead
7192    /// of per-row argmaxes — the sampled-admission arm's input (rejection-sampling accept
7193    /// gathers filtered p from these columns; lane/dspark-sampled-admission-20260820). Same
7194    /// forward as `dspark_verify_t_am`; the greedy arm keeps its argmax wrapper untouched.
7195    pub(crate) fn dspark_verify_t_logits(
7196        &self,
7197        e: &Engine,
7198        tokens: &[u32],
7199        pos0: usize,
7200        cache: &mut Cache,
7201    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7202        let (logits, _hn) = self.decode_step_t_core_stream(
7203            e, tokens, pos0, cache, None, None, None, None, None, None,
7204        )?;
7205        Ok(logits)
7206    }
7207
7208    /// DSpark verify with the MTP column-stash armed: identical forward to
7209    /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
7210    /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
7211    /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
7212    pub(crate) fn dspark_verify_t_am_ckpt(
7213        &self,
7214        e: &Engine,
7215        tokens: &[u32],
7216        pos0: usize,
7217        cache: &mut Cache,
7218    ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
7219        let mut ck = VerifyCkpt::new(self.layers.len());
7220        let (logits, _hn) = self.decode_step_t_core_stream(
7221            e,
7222            tokens,
7223            pos0,
7224            cache,
7225            None,
7226            Some(&mut ck),
7227            None,
7228            None,
7229            None,
7230            None,
7231        )?;
7232        let t = tokens.len();
7233        let v = self.output.out_features();
7234        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
7235        for r in 0..t {
7236            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
7237        }
7238        Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
7239    }
7240
7241    /// Engine-bundle slice 2: `dspark_verify_t_am_ckpt` with DEVICE tokens and NO readback.
7242    /// The verify tokens are the round's `chain_d` (cand layout: [anchor, drafts...]); the
7243    /// embed gathers its first `t` entries on-device (`embed_gather_u32_t` — bit-identical
7244    /// rows to the host arm), so the host never blocks on the draft chain before dispatching
7245    /// verify. Returns the device per-row argmax buffer; the caller merges its readback with
7246    /// the chain's into ONE sync. Forward, ckpt fill and argmax walk are `_ckpt` verbatim.
7247    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
7248    pub(crate) fn dspark_verify_t_am_ckpt_dev(
7249        &self,
7250        e: &Engine,
7251        vtok: &CudaSlice<u32>,
7252        t: usize,
7253        pos0: usize,
7254        cache: &mut Cache,
7255        embd_dev: (&CudaSlice<u8>, i32, usize),
7256        graphs: Option<&mut DsparkVerifyGraphs>,
7257    ) -> Result<(CudaSlice<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
7258        debug_assert!(
7259            vtok.len() >= t,
7260            "verify window exceeds the device token buffer"
7261        );
7262        // The slab flag is a per-round statement: clear it here so a verify that never
7263        // reaches the graphs door (rowwise env, a non-tparallel arm) cannot leave a
7264        // stale `true` steering the commit at slabs the round never wrote.
7265        let mut graphs = graphs;
7266        if let Some(g) = graphs.as_deref_mut() {
7267            g.round_slab = false;
7268        }
7269        let mut ck = VerifyCkpt::new(self.layers.len());
7270        // Dummy host tokens size the funnel; the embed reads `vtok` (the round-stream
7271        // arm's established pattern — spec.rs stream-mode verify does the same).
7272        let dummy = vec![0u32; t];
7273        let (logits, _hn) = self.decode_step_t_core_stream(
7274            e,
7275            &dummy,
7276            pos0,
7277            cache,
7278            Some(embd_dev),
7279            Some(&mut ck),
7280            None,
7281            None,
7282            Some(vtok),
7283            graphs,
7284        )?;
7285        let v = self.output.out_features();
7286        let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
7287        for r in 0..t {
7288            e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
7289        }
7290        Ok((am_d, DsparkVerifyCkpt(ck)))
7291    }
7292
7293    /// Ckpt-armed twin of [`Self::dspark_verify_t_logits`] (sampled-admission arm).
7294    pub(crate) fn dspark_verify_t_logits_ckpt(
7295        &self,
7296        e: &Engine,
7297        tokens: &[u32],
7298        pos0: usize,
7299        cache: &mut Cache,
7300    ) -> Result<(CudaSlice<f32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
7301        let mut ck = VerifyCkpt::new(self.layers.len());
7302        let (logits, _hn) = self.decode_step_t_core_stream(
7303            e,
7304            tokens,
7305            pos0,
7306            cache,
7307            None,
7308            Some(&mut ck),
7309            None,
7310            None,
7311            None,
7312            None,
7313        )?;
7314        Ok((logits, DsparkVerifyCkpt(ck)))
7315    }
7316
7317    /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
7318    /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
7319    /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
7320    pub(crate) fn dspark_commit_prefix(
7321        &self,
7322        e: &Engine,
7323        cache: &mut Cache,
7324        snap: &crate::cache::CacheSnapshot,
7325        ckpt: &DsparkVerifyCkpt,
7326        keep: usize,
7327    ) -> Result<(), Box<dyn std::error::Error>> {
7328        self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
7329    }
7330
7331    /// Slice-3 commit twin: restore to `keep` accepted columns when the round's linear
7332    /// column stash lives in the graphs ctx's persistent slabs (`DsparkVerifyGraphs`) —
7333    /// the cols arm's exact semantics (KV lens + pos from the snapshot, GDN conv/ssm
7334    /// from the stash of column keep-1), slab-addressed and batched into two copy
7335    /// launches. `MEMRA_STATE_COPY_BATCH=0` falls back to per-layer view copies.
7336    pub(crate) fn dspark_commit_prefix_slab(
7337        &self,
7338        e: &Engine,
7339        cache: &mut Cache,
7340        snap: &crate::cache::CacheSnapshot,
7341        ctx: &DsparkVerifyGraphs,
7342        keep: usize,
7343    ) -> Result<(), Box<dyn std::error::Error>> {
7344        use cudarc::driver::DevicePtr;
7345        debug_assert!(keep >= 1, "keep==0 rounds take the legacy rollback");
7346        let mut conv_src: Vec<u64> = Vec::new();
7347        let mut ssm_src: Vec<u64> = Vec::new();
7348        let mut conv_dst: Vec<u64> = Vec::new();
7349        let mut ssm_dst: Vec<u64> = Vec::new();
7350        for il in 0..self.layers.len() {
7351            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
7352                kvl.len = saved + keep;
7353                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
7354            }
7355            if let Some(rl) = cache.recur[il].as_ref() {
7356                let (pc, ps, _cw, _sw) = ctx
7357                    .slab_row(e, il, keep - 1)
7358                    .ok_or("slab commit: linear layer missing from the graphs ctx")?;
7359                conv_src.push(pc);
7360                ssm_src.push(ps);
7361                let st = &e.gpu.stream();
7362                let (dc, _g0) = rl.conv_state.device_ptr(st);
7363                let (ds, _g1) = rl.ssm_state.device_ptr(st);
7364                conv_dst.push(dc);
7365                ssm_dst.push(ds);
7366            }
7367        }
7368        let n = conv_src.len();
7369        if n > 0 {
7370            if state_copy_batch_on() {
7371                let mut tt = vec![0u64; 2 * n];
7372                tt[..n].copy_from_slice(&conv_src);
7373                tt[n..].copy_from_slice(&conv_dst);
7374                let ct = e.htod_u64(&tt)?;
7375                tt[..n].copy_from_slice(&ssm_src);
7376                tt[n..].copy_from_slice(&ssm_dst);
7377                let st = e.htod_u64(&tt)?;
7378                e.copy_batch_uniform_f32(&ct, n, ctx.conv_words)?;
7379                e.copy_batch_uniform_f32(&st, n, ctx.ssm_words)?;
7380            } else {
7381                let (cw, sw) = (ctx.conv_words, ctx.ssm_words);
7382                let row = keep - 1;
7383                for il in 0..self.layers.len() {
7384                    let Some(rl) = cache.recur[il].as_mut() else {
7385                        continue;
7386                    };
7387                    let k = ctx.lin_pos[&il];
7388                    {
7389                        let sv = e.view(&ctx.stash_conv[k], (row + 1) * cw);
7390                        let win = sv.slice(row * cw..(row + 1) * cw);
7391                        e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
7392                    }
7393                    {
7394                        let sv = e.view(&ctx.stash_ssm[k], (row + 1) * sw);
7395                        let win = sv.slice(row * sw..(row + 1) * sw);
7396                        e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
7397                    }
7398                }
7399            }
7400        }
7401        cache.pos = snap.pos + keep;
7402        Ok(())
7403    }
7404
7405    /// Qwen35-family verify trunk in the live serving numeric class.
7406    ///
7407    /// Serving intentionally keeps this architecture in the generic batched program even at
7408    /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
7409    ///
7410    /// Two arms, one numeric class:
7411    /// - DENSE GDN (`DenseMlp`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
7412    ///   projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
7413    ///   program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
7414    ///   == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
7415    ///   append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
7416    ///   row's own t_kv-driven arm pick (the straddle law: every row executes the exact
7417    ///   program its isolated serving step would). One weight read per layer per round
7418    ///   instead of T — this is what makes MTP profitable in the exact class (the per-row
7419    ///   walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
7420    /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
7421    ///   serving layer body, preserving single-session autoregressive cache order (the
7422    ///   correctness reference; also the rollback seam for the t-parallel arm).
7423    ///
7424    /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
7425    /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
7426    #[allow(clippy::too_many_arguments)]
7427    fn qwen35_verify_batch_layers(
7428        &self,
7429        e: &Engine,
7430        x: CudaSlice<f32>,
7431        lo: usize,
7432        hi: usize,
7433        pos0: usize,
7434        t: usize,
7435        cache: &mut Cache,
7436        ckpt: Option<&mut VerifyCkpt>,
7437        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
7438        graphs: Option<&mut DsparkVerifyGraphs>,
7439    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7440        // Qwen35Moe admitted 2026-08-20 (lane/draftcost-moe): the t-parallel arm already
7441        // carries the MoE FFN (`moe_ffn_il_zq8` at m=T) and the GDN per-row state loop; the
7442        // arch fence was a qualification gate, not a mechanism gap. Measured disease on the
7443        // 35B-A3B class: rowwise verify ~= 5.6 ms per drafted token (one full trunk step
7444        // each) — the same (K+1)-plain-steps wall the dense admission fixed on 2026-08-15.
7445        // Rollback seam unchanged: MEMRA_SPEC_VERIFY_ROWWISE=1.
7446        let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
7447            || !self.batched_serving_numeric_class()
7448            || t > 16;
7449        if rowwise {
7450            if stream.is_some() {
7451                // rowwise replays per row with host cache.pos — irreconcilable with a
7452                // device position counter. Burst callers must keep t <= 16 and the
7453                // ROWWISE env unset; refusing beats silently mispositioned rows.
7454                return Err("qwen35 rowwise verify has no ROUND-STREAM arm \
7455                            (t > 16 or MEMRA_SPEC_VERIFY_ROWWISE=1)"
7456                    .into());
7457            }
7458            self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
7459        } else {
7460            self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt, stream, graphs)
7461        }
7462    }
7463
7464    /// The per-row correctness reference: replay each verify row through the authoritative
7465    /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
7466    #[allow(clippy::too_many_arguments)]
7467    fn qwen35_verify_rowwise(
7468        &self,
7469        e: &Engine,
7470        mut x: CudaSlice<f32>,
7471        lo: usize,
7472        hi: usize,
7473        pos0: usize,
7474        t: usize,
7475        cache: &mut Cache,
7476        mut ckpt: Option<&mut VerifyCkpt>,
7477    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7478        let n_embd = self.cfg.n_embd as usize;
7479        let saved_pos = cache.pos;
7480        let mut ph_last = std::time::Instant::now();
7481        for il in lo..hi {
7482            let mut next = e.uninit(t * n_embd)?;
7483            let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
7484                if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
7485                    Some(Vec::with_capacity(t - 1))
7486                } else {
7487                    None
7488                };
7489            for r in 0..t {
7490                cache.pos = pos0 + r;
7491                let mut row = e.uninit(n_embd)?;
7492                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
7493                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
7494                let mut one = [&mut *cache];
7495                let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
7496                let out = match self.decode_batch_layers(
7497                    e,
7498                    row,
7499                    &mut one,
7500                    &ctx,
7501                    &row_pos,
7502                    &mut ph_last,
7503                ) {
7504                    Ok(out) => out,
7505                    Err(error) => {
7506                        cache.pos = saved_pos;
7507                        return Err(error);
7508                    }
7509                };
7510                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
7511                if r + 1 < t
7512                    && let Some(states) = col_states.as_mut()
7513                {
7514                    let recur = cache.recur[il]
7515                        .as_ref()
7516                        .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
7517                    states.push((
7518                        e.clone_dtod(&recur.conv_state)?,
7519                        e.clone_dtod(&recur.ssm_state)?,
7520                    ));
7521                }
7522            }
7523            if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
7524                checkpoint.cols[il] = Some(states);
7525            }
7526            x = next;
7527        }
7528        cache.pos = saved_pos;
7529        Ok(x)
7530    }
7531
7532    /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
7533    ///
7534    /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
7535    /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
7536    /// pins the serving batch tier already carries:
7537    ///   * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
7538    ///     kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
7539    ///     alone;
7540    ///   * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
7541    ///     `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
7542    ///     launch is the per-row program (same pin the generic verify's fused norms rely on).
7543    ///     The sequential dependencies keep their exact serving order: the conv ring / gdn scan
7544    ///     chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
7545    ///     alternating pointer table, host handles swapped per row so VerifyCkpt clones the
7546    ///     canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
7547    ///     picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
7548    ///     `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
7549    ///     program its isolated B=1 serving step would.
7550    ///
7551    /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
7552    /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
7553    #[allow(clippy::too_many_arguments)]
7554    fn qwen35_verify_tparallel(
7555        &self,
7556        e: &Engine,
7557        mut x: CudaSlice<f32>,
7558        lo: usize,
7559        hi: usize,
7560        pos0: usize,
7561        t: usize,
7562        cache: &mut Cache,
7563        mut ckpt: Option<&mut VerifyCkpt>,
7564        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
7565        mut graphs: Option<&mut DsparkVerifyGraphs>,
7566    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7567        let seqs_append =
7568            std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
7569        let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
7570
7571        // Merge guard (v0.98 train, re-affirmed on the v0.100 train over slice 4c): the
7572        // ROUND-STREAM arm (lane/draftcost-moe, device position counter) and the dspark
7573        // verify graphs (engine-bundle slice 3 / trunk slice 4c) have no common caller —
7574        // stream rides the qwen35moe burst, graphs ride the dspark route. If a future
7575        // caller arms both, refuse loudly instead of silently dropping the graphs ctx
7576        // (the stream linear arm takes linear_attn_verify_t, not the graphed segment or
7577        // full-verify bodies).
7578        if stream.is_some() && graphs.is_some() {
7579            return Err(
7580                "qwen35 tparallel verify: ROUND-STREAM and dspark verify graphs \
7581                        cannot arm together"
7582                    .into(),
7583            );
7584        }
7585        // Engine-bundle slice 3 + slice 4c: with a graphs ctx armed, pointer tables are
7586        // refreshed once per verify (the gdn ping-pong moves handles; a fresh generation
7587        // moves the kv caches). Then:
7588        //  - slice 4c: when the WHOLE round rides one seqs rung (every row batchable, one
7589        //    split-ladder step, rung covers the round), the ENTIRE walk replays as ONE
7590        //    full-verify graph per (vt, rung) — linear layers through the shared
7591        //    `qwen35_tparallel_linear_layer` body, full-attention layers through the
7592        //    shared `qwen35_tparallel_fa_layer` body in graph mode.
7593        //  - fallback (straddle rounds, below the vec floor, partial walks): runs of
7594        //    consecutive LINEAR layers replay the slice-3 per-(segment, vt) graphs and
7595        //    the full-attention layers run eager (batched rows when eligible).
7596        //
7597        // GRAPH-LAUNCH HEADROOM GUARD (see GRAPH_LAUNCH_MIN_FREE): the dspark verify
7598        // graphs replay through this walk from THREE callers — the MTP spec round's vg
7599        // door (already dropped per round by `graph_round_ok` before it gets here), the
7600        // dspark one-shot, and the dspark SERVE round (default ON since v0.108). Below
7601        // the driver-free floor the WHOLE round takes the byte-identical eager
7602        // cols-ckpt walk — the same drop-the-ctx fallback the pool ceiling already
7603        // takes — instead of feeding cuGraphLaunch a card it segfaults on.
7604        if let Some(g) = graphs.as_deref_mut()
7605            && !graph_launch_headroom_ok(e)
7606        {
7607            g.round_slab = false;
7608            graphs = None;
7609            static NOTED: std::sync::Once = std::sync::Once::new();
7610            NOTED.call_once(|| graph_replay_suspended_note("dspark-vg"));
7611        }
7612        if let Some(g) = graphs.as_deref_mut() {
7613            g.refresh_tables(e, cache)?;
7614            g.round_slab = false;
7615            if let Some(rung) = g.full_rung(self, cache, lo, hi, t, seqs_append && batch_fa_on) {
7616                // Pool ceiling (dspark_vg_cap): an existing key always replays; a NEW
7617                // full capture past the ceiling falls through to the segment/eager arms.
7618                if g.full.contains_key(&(t, rung, hi)) || g.can_capture() {
7619                    let out = g.run_full(self, e, lo, hi, &x, t, pos0, rung, cache)?;
7620                    g.round_slab = true;
7621                    return Ok(out);
7622                }
7623            }
7624            // Round-atomic ceiling check for the segment door: if any linear run in this
7625            // walk would need a NEW capture past the ceiling, the whole round runs the
7626            // eager cols-ckpt walk (mixing slab- and cols-stashed layers in one round
7627            // would corrupt the commit).
7628            if !g.segments_ready(self, lo, hi, t) {
7629                graphs = None;
7630            }
7631        }
7632        // STREAM (2b, lane/draftcost-moe): positions come from the device round counter
7633        // (pos_iota / i32_copy_add) so a burst round needs no host position knowledge.
7634        let pos_d = match stream {
7635            Some((_, ctr)) => {
7636                let mut p = e.alloc_uninit::<i32>(t)?;
7637                e.pos_iota(ctr, &mut p, t)?;
7638                p
7639            }
7640            None => {
7641                let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
7642                e.htod_i32(&pos_host)?
7643            }
7644        };
7645        // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
7646        // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
7647        // LAZY since slice 4: the batched fa/append arm never touches them — they are built
7648        // on the first per-row fallback layer only (stream-aware there; the stream FA arm
7649        // rides the dc rows kernels and never reaches the fallback).
7650        let mut pos_rows: Option<Vec<CudaSlice<i32>>> = None;
7651        let mut il = lo;
7652        while il < hi {
7653            if graphs.is_some() && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
7654                let mut end = il;
7655                while end < hi && matches!(self.layers[end].mixer, Mixer::Linear(_)) {
7656                    end += 1;
7657                }
7658                let g = graphs.as_deref_mut().expect("checked above");
7659                x = g.run_segment(self, e, il, end, &x, t, cache)?;
7660                g.round_slab = true;
7661                il = end;
7662                continue;
7663            }
7664            let layer = &self.layers[il];
7665            if stream.is_none() && matches!(layer.mixer, Mixer::Linear(_)) {
7666                // Eager linear layer (no graphs ctx): the shared body, legacy cols-ckpt arm.
7667                // Under ROUND-STREAM the linear layers ride the fa-body match's stream arm
7668                // below (linear_attn_verify_t — the stream COMMIT needs its GdnStash).
7669                x = self.qwen35_tparallel_linear_layer(
7670                    e,
7671                    il,
7672                    &x,
7673                    t,
7674                    cache,
7675                    ckpt.as_deref_mut(),
7676                    None,
7677                    None,
7678                )?;
7679                il += 1;
7680                continue;
7681            }
7682            // Full-attention (or stream-Linear, or MLA-refusing) layer: the extracted
7683            // shared body — eager arm (fresh per-verify pos/table, exact t_kv sizing,
7684            // in-body len bump). The slice-4c captured full-verify graphs run the SAME
7685            // body in graph mode; under ROUND-STREAM the body's dc-rows / GDN stream arms
7686            // run (lane/draftcost-moe).
7687            x = self.qwen35_tparallel_fa_layer(
7688                e,
7689                il,
7690                &x,
7691                t,
7692                cache,
7693                FaLayerArgs {
7694                    pos_d: &pos_d,
7695                    pos_rows: &mut pos_rows,
7696                    pos0,
7697                    seqs_append,
7698                    batch_fa_on,
7699                    graph_cap: None,
7700                    stream,
7701                    ckpt: ckpt.as_deref_mut(),
7702                },
7703            )?;
7704            il += 1;
7705        }
7706        Ok(x)
7707    }
7708
7709    /// SHARED dense-FFN body for the qwen35 t-parallel layers (trunk-kernels slice B) —
7710    /// ONE copy for the fa and linear layer bodies (the verify_layers extraction lesson).
7711    /// Dual arm (MEMRA_TK_FFN_DUAL, default on): gate+up in ONE dual launch from the
7712    /// pre-quantized activation with macro-scales DEFERRED into the fused SwiGLU+q8_1
7713    /// epilogue, then ffn_down from the fused (aq, ad) — the q27 verify chain verbatim.
7714    /// Every door is the bit-identical proven one: `matmul_decode_exact_dual_pre` (per
7715    /// (tensor,token,row) == the two singles), `silu_mul_scaled_q8_1` (y*s inline == the
7716    /// scale_inplace store, value-exact; fused quantize == quantize_q8_1 bytes),
7717    /// `matmul_decode_exact_pre` (dispatch mirror of the singles' q8_1-fast tail).
7718    /// Dual-refused (t outside 2..=7, non-NVFP4, layout mismatch) or seam off -> the
7719    /// original singles chain, byte-for-byte.
7720    #[allow(clippy::too_many_arguments)]
7721    fn qwen35_tparallel_dense_ffn(
7722        &self,
7723        e: &Engine,
7724        ffn_gate: &crate::model::GpuTensor,
7725        ffn_up: &crate::model::GpuTensor,
7726        ffn_down: &crate::model::GpuTensor,
7727        zn: &CudaSlice<f32>,
7728        t: usize,
7729        n_embd: usize,
7730    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7731        let n_ff = ffn_gate.out_features();
7732        let (zq, zd) = e.quantize_q8_1(zn, t, n_embd)?;
7733        if Engine::tk_ffn_dual_on()
7734            && let Some(((g, gs), (u, us))) =
7735                e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, &zq, &zd, t)?
7736        {
7737            if e.uses_q8_1_fast(ffn_down) {
7738                let (aq, ad) = e.silu_mul_scaled_q8_1(&g, &u, gs, us, t * n_ff)?;
7739                return e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t);
7740            }
7741            let mut act = e.uninit(t * n_ff)?;
7742            e.silu_mul_scaled(&g, &u, gs, us, &mut act, t * n_ff)?;
7743            let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
7744            return e.matmul_pre(ffn_down, &aq, &ad, &act, t);
7745        }
7746        // v1 singles chain (seam off or dual-refused) — the pre-slice-B body verbatim.
7747        let g = e.matmul_pre(ffn_gate, &zq, &zd, zn, t)?;
7748        let u = e.matmul_pre(ffn_up, &zq, &zd, zn, t)?;
7749        let mut act = e.uninit(t * n_ff)?;
7750        e.silu_mul(&g, &u, &mut act, t * n_ff)?;
7751        let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
7752        e.matmul_pre(ffn_down, &aq, &ad, &act, t)
7753    }
7754
7755    /// ONE t-parallel FULL-ATTENTION layer (attn_norm + fa mixer + post_attn_norm + FFN +
7756    /// tap) — extracted from the walk exactly like `qwen35_tparallel_linear_layer` so the
7757    /// eager walk and the slice-4c captured full-verify graphs execute the SAME body (a
7758    /// second copy is how dispatch mirrors drift — the verify_layers extraction lesson).
7759    ///
7760    /// `args.graph_cap = Some((table, off, rung_end))` is the captured-graph mode:
7761    /// - kv base-pointer pairs come from the ctx-owned persistent table at `off` (a fresh
7762    ///   generation's cache lands at new addresses that only the per-verify table refresh
7763    ///   knows — the slice-3 baked-address lesson);
7764    /// - the seqs twins size partials/grid at `rung_end` and pin `split_keys` to the
7765    ///   rung's ladder value: `n_splits_max` is pure stride, splits >= ns_eff write the
7766    ///   EMPTY partial the combine never reads, and every per-row T_kv derives in-kernel
7767    ///   from `pos_seq[z]` — so one captured launch replays bit-identically for every
7768    ///   round whose rows all sit inside the rung;
7769    /// - the host len bump moves to the replay caller (captured host code does not
7770    ///   re-run at replay).
7771    ///   Graph mode REFUSES any round the batched arm cannot take: the per-row fallback
7772    ///   host-branches on t_kv and must never be captured.
7773    #[allow(clippy::too_many_arguments)]
7774    fn qwen35_tparallel_fa_layer(
7775        &self,
7776        e: &Engine,
7777        il: usize,
7778        x: &CudaSlice<f32>,
7779        t: usize,
7780        cache: &mut Cache,
7781        args: FaLayerArgs<'_>,
7782    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7783        use cudarc::driver::DevicePtr;
7784        let cfg = &self.cfg;
7785        let n_embd = cfg.n_embd as usize;
7786        let eps = cfg.rms_eps;
7787        let head_dim_global = cfg.head_dim_k as usize;
7788        let layer = &self.layers[il];
7789        let FaLayerArgs {
7790            pos_d,
7791            pos_rows,
7792            pos0,
7793            seqs_append,
7794            batch_fa_on,
7795            graph_cap,
7796            stream,
7797            ckpt,
7798        } = args;
7799
7800        // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
7801        let anorm = layer.attn_norm.float_data();
7802        let mut xn = e.uninit(t * n_embd)?;
7803        e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
7804        let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
7805
7806        let mixed: CudaSlice<f32> = match &layer.mixer {
7807            Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("tensor-parallel attention"),
7808            Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("T-parallel attention"),
7809            // STREAM ARM (2b, lane/draftcost-moe): under a device position counter the
7810            // per-row serving-kernel chain cannot run (host state swaps keyed on host
7811            // row index are fine, but the stream COMMIT needs the GdnStash for its _dc
7812            // rebuild — the per-row chain only produces per-column clones). GDN rides
7813            // `linear_attn_verify_t`: batched q8_1-class projections, stash-producing,
7814            // and its one-scan recurrence is pinned bit-identical to T chained T=1
7815            // steps (its header + kernel-check). Position-independent, so no counter
7816            // plumbing is needed. Guards mirror the generic call site exactly.
7817            Mixer::Linear(la) if stream.is_some() => {
7818                if !(t >= 3 || (t == 2 && spec_m2()))
7819                    || !self.mixer_in_q8_1_fast(e, &layer.mixer)
7820                    || !e.uses_q8_1_fast(&la.ssm_out)
7821                {
7822                    return Err("qwen35 stream verify: GDN batched arm requires t>=3 \
7823                                (or MEMRA_SPEC_M2 at t=2) and q8_1-fast projections"
7824                        .into());
7825                }
7826                let want = ckpt.is_some();
7827                let (out, stash) =
7828                    self.linear_attn_verify_t(e, la, &xn, Some((&hq, &hd)), t, cache, il, want)?;
7829                if let (Some(ck), Some(st)) = (ckpt, stash) {
7830                    ck.gdn[il] = Some(st);
7831                }
7832                out
7833            }
7834            Mixer::Linear(_) => {
7835                unreachable!("linear layers ride qwen35_tparallel_linear_layer")
7836            }
7837            Mixer::Full(fa) => {
7838                let geometry = cfg.full_attention_geometry_at(il as u32);
7839                let n_head = geometry.n_head as usize;
7840                let n_head_kv = geometry.n_head_kv as usize;
7841                let head_dim = geometry.head_dim_k as usize;
7842                let rope_dims = geometry.n_rot as usize;
7843                let rope_base = geometry.rope_base;
7844                let scale = geometry.attention_scale();
7845                // Batched projections: one weight read serves all T rows.
7846                // GROUP-3 twin (trunk-kernels slice D): q/k/v in ONE launch — the group4
7847                // kernel with n3=0, bit-identical per (tensor, token, row) to the three
7848                // singles; refused or MEMRA_TK_FA_GROUP=0 -> singles byte-for-byte.
7849                let (qf, mut k, v) = match e.matmul_decode_exact_group3_pre(
7850                    [&fa.wq, &fa.wk, &fa.wv],
7851                    &hq,
7852                    &hd,
7853                    t,
7854                )? {
7855                    Some(mut g3) => {
7856                        let v = g3.pop().unwrap();
7857                        let k = g3.pop().unwrap();
7858                        let qf = g3.pop().unwrap();
7859                        (qf, k, v)
7860                    }
7861                    None => (
7862                        e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?,
7863                        e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?,
7864                        e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?,
7865                    ),
7866                };
7867                let gated =
7868                    geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
7869                let (mut q, gate) = if gated {
7870                    let mut qs = e.uninit(t * n_head * head_dim)?;
7871                    let mut gs = e.uninit(t * n_head * head_dim)?;
7872                    e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
7873                    (qs, Some(gs))
7874                } else {
7875                    (qf, None)
7876                };
7877                let mut qn = e.uninit(t * n_head * head_dim)?;
7878                e.rms_norm(
7879                    &q,
7880                    fa.q_norm.float_data(),
7881                    &mut qn,
7882                    head_dim,
7883                    t * n_head,
7884                    eps,
7885                )?;
7886                q = qn;
7887                let mut kn = e.uninit(t * n_head_kv * head_dim)?;
7888                e.rms_norm(
7889                    &k,
7890                    fa.k_norm.float_data(),
7891                    &mut kn,
7892                    head_dim,
7893                    t * n_head_kv,
7894                    eps,
7895                )?;
7896                k = kn;
7897                e.rope_neox(
7898                    &mut q, pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
7899                )?;
7900                e.rope_neox(
7901                    &mut k, pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
7902                )?;
7903
7904                // Per-row append + attend: row r sees rows 0..r in KV (causal within the
7905                // draft), each through the b_n=1 serving kernels at its own t_kv.
7906                let q_dim = n_head * head_dim;
7907                let kv_dim = n_head_kv * head_dim;
7908                let mut attn = e.uninit(t * q_dim)?;
7909                let (kdk, kdv, ktb, vtb, len0, kv_local) = {
7910                    let kvl = cache.kv[il].as_ref().unwrap();
7911                    // [2T] interleaved k,v base pointers: entry pair z serves row z of
7912                    // the batched twins; the per-row fallback reads pair 0 (same cache
7913                    // for every row of one layer). Graph mode reads the ctx table.
7914                    let local: Option<CudaSlice<u64>> = match graph_cap {
7915                        Some(_) => None,
7916                        None => {
7917                            let s = &e.gpu.stream();
7918                            let (pk, _g) = kvl.k.device_ptr(s);
7919                            let (pv, _g2) = kvl.v.device_ptr(s);
7920                            let mut tbl = Vec::with_capacity(2 * t);
7921                            for _ in 0..t {
7922                                tbl.push(pk);
7923                                tbl.push(pv);
7924                            }
7925                            Some(e.htod_u64(&tbl)?)
7926                        }
7927                    };
7928                    (
7929                        kvl.kv_dim_k,
7930                        kvl.kv_dim_v,
7931                        kvl.k_tok_bytes,
7932                        kvl.v_tok_bytes,
7933                        kvl.len,
7934                        local,
7935                    )
7936                };
7937                let (kv_tbl, kv_off): (&CudaSlice<u64>, usize) = match graph_cap {
7938                    Some((tb, off, _)) => (tb, off),
7939                    None => (kv_local.as_ref().expect("built above"), 0),
7940                };
7941                // Slice 4 (fa/append rows — see dspark_fa_rows_on): the whole per-row
7942                // section batches into the z-batched serving twins when every row of
7943                // this round takes the v4-seqs arm on ONE fa_split_keys rung. Both
7944                // guards are evaluated at the round's FIRST and LAST t_kv — the
7945                // eligibility window (vec floor .. v4 max) and each split-ladder rung
7946                // are intervals in t_kv, so ends-inside means all-inside (the straddle
7947                // law). Appending all T rows before any attend is read-equivalent to
7948                // the interleaved order: row r's walk reads keys 0..len0+r only, and
7949                // rows > r land at slots it never touches; every written cache row is
7950                // the per-token appender's exact warp program (kernel-check pinned).
7951                let t_kv_first = len0 + 1;
7952                let t_kv_last = len0 + t;
7953                let rows_batched = t >= 2
7954                    && seqs_append
7955                    && batch_fa_on
7956                    && dspark_fa_rows_on()
7957                    // the z-batched twins read stacked rows at the CACHE's kv dims;
7958                    // the projection stack is [T, n_head_kv*head_dim] — they must be
7959                    // the same stride or row z misaligns (true for this family; the
7960                    // guard keeps any asymmetric-kv model on the per-row loop).
7961                    && kdk == kv_dim
7962                    && kdv == kv_dim
7963                    && crate::fa_seqs_eligible(t_kv_first, head_dim_global)
7964                    && crate::fa_seqs_eligible(t_kv_last, head_dim_global)
7965                    && crate::fa_split_keys(t_kv_first, cfg.n_head_kv as usize)
7966                        == crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize);
7967                // Sizing: eager = exact round bound; graph mode = the rung end (stride +
7968                // grid only — bytes proven equal above). Capture-time invariants refuse
7969                // loudly rather than bake a divergent body.
7970                let (size_kv_max, sp) = match graph_cap {
7971                    Some((_, _, rung)) => {
7972                        if !rows_batched {
7973                            return Err(format!(
7974                                "fa graph capture: layer {il} round is not batchable \
7975                                 (t_kv {t_kv_first}..{t_kv_last}) — the per-row fallback \
7976                                 must never be captured"
7977                            )
7978                            .into());
7979                        }
7980                        let sp_r = crate::fa_split_keys(rung, cfg.n_head_kv as usize);
7981                        if t_kv_last > rung
7982                            || sp_r != crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize)
7983                        {
7984                            return Err(format!(
7985                                "fa graph capture: rung {rung} does not cover round \
7986                                 t_kv {t_kv_first}..{t_kv_last} on one split ladder step"
7987                            )
7988                            .into());
7989                        }
7990                        (rung, sp_r)
7991                    }
7992                    None => (
7993                        t_kv_last,
7994                        crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize),
7995                    ),
7996                };
7997                if let Some((_, ctr)) = stream {
7998                    // STREAM ARM (2b): one batched dc append + the multi-row dc attention
7999                    // — the generic stream arm's exact shape (rows kernels are pinned
8000                    // byte-identical to the per-row programs by kernel-check). Host len
8001                    // stays a stale lower bound; the burst drain reconciles it.
8002                    let kvl = cache.kv[il].as_mut().unwrap();
8003                    e.append_kv_quantized_rows_dc(
8004                        &k,
8005                        &v,
8006                        &mut kvl.k,
8007                        &mut kvl.v,
8008                        ctr,
8009                        t,
8010                        kdk,
8011                        kdv,
8012                        ktb,
8013                        vtb,
8014                        Engine::kv_fp8_on(),
8015                    )?;
8016                    let upper = (kvl.len + t + 64).min(cache.max_ctx);
8017                    let k_view = e.view_u8(&kvl.k, upper * ktb);
8018                    let v_view = e.view_u8(&kvl.v, upper * vtb);
8019                    e.fa_decode_rows_dc(
8020                        &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, ctr, upper,
8021                        t, scale, ktb, vtb, 0, false,
8022                    )?;
8023                } else if rows_batched {
8024                    e.append_kv_quantized_seqs(
8025                        &k,
8026                        &v,
8027                        &kv_tbl.slice(kv_off..kv_off + 2 * t),
8028                        pos_d,
8029                        t,
8030                        kdk,
8031                        kdv,
8032                        ktb,
8033                        vtb,
8034                    )?;
8035                    if graph_cap.is_none() {
8036                        cache.kv[il].as_mut().unwrap().len += t;
8037                    }
8038                    e.fa_decode_batch_seqs_v4(
8039                        &q,
8040                        &kv_tbl.slice(kv_off..kv_off + 2 * t),
8041                        pos_d,
8042                        &mut attn,
8043                        head_dim,
8044                        n_head,
8045                        n_head_kv,
8046                        t,
8047                        size_kv_max,
8048                        scale,
8049                        sp,
8050                        ktb,
8051                        vtb,
8052                    )?;
8053                } else {
8054                    if pos_rows.is_none() {
8055                        // Stream-aware for symmetry with pos_d (the stream FA arm rides
8056                        // the dc rows kernels above and never reaches this fallback).
8057                        *pos_rows = Some(match stream {
8058                            Some((_, ctr)) => (0..t)
8059                                .map(|r| {
8060                                    let mut b = e.alloc_uninit::<i32>(1)?;
8061                                    e.i32_copy_add(ctr, &mut b, r as i32)?;
8062                                    Ok(b)
8063                                })
8064                                .collect::<Result<_, Box<dyn std::error::Error>>>()?,
8065                            None => (0..t)
8066                                .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
8067                                .collect::<Result<_, _>>()?,
8068                        });
8069                    }
8070                    let pos_rows = pos_rows.as_ref().unwrap();
8071                    #[allow(clippy::needless_range_loop)]
8072                    // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
8073                    for r in 0..t {
8074                        // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
8075                        // whose row 0 is this row (arithmetic-free materialization copies,
8076                        // same as decode's per-seq fallback arm).
8077                        let mut k_row = e.uninit(kv_dim)?;
8078                        e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
8079                        let mut v_row = e.uninit(kv_dim)?;
8080                        e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
8081                        let pos_row = &pos_rows[r];
8082                        let kvl = cache.kv[il].as_mut().unwrap();
8083                        if seqs_append {
8084                            e.append_kv_quantized_seqs(
8085                                &k_row,
8086                                &v_row,
8087                                &kv_tbl.slice(kv_off..kv_off + 2),
8088                                pos_row,
8089                                1,
8090                                kdk,
8091                                kdv,
8092                                ktb,
8093                                vtb,
8094                            )?;
8095                            kvl.len += 1;
8096                        } else {
8097                            e.append_kv_quantized_view(
8098                                &k_row.slice(0..kv_dim),
8099                                &v_row.slice(0..kv_dim),
8100                                &mut kvl.k,
8101                                &mut kvl.v,
8102                                kvl.len,
8103                                kvl.kv_dim_k,
8104                                kvl.kv_dim_v,
8105                                kvl.k_tok_bytes,
8106                                kvl.v_tok_bytes,
8107                                Engine::kv_fp8_on(),
8108                            )?;
8109                            kvl.len += 1;
8110                        }
8111                        let t_kv = kvl.len;
8112                        let mut q_row = e.uninit(q_dim)?;
8113                        e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
8114                        let mut a_row = e.uninit(q_dim)?;
8115                        if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
8116                            let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
8117                            e.fa_decode_batch_seqs_v4(
8118                                &q_row,
8119                                &kv_tbl.slice(kv_off..kv_off + 2),
8120                                pos_row,
8121                                &mut a_row,
8122                                head_dim,
8123                                n_head,
8124                                n_head_kv,
8125                                1,
8126                                t_kv,
8127                                scale,
8128                                sp0_r,
8129                                ktb,
8130                                vtb,
8131                            )?;
8132                        } else {
8133                            let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
8134                            let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
8135                            let mut a_view = a_row.slice_mut(0..q_dim);
8136                            e.fa_decode_kvmod_view(
8137                                &q_row.slice(0..q_dim),
8138                                &k_view,
8139                                &v_view,
8140                                &mut a_view,
8141                                head_dim,
8142                                n_head,
8143                                n_head_kv,
8144                                t_kv,
8145                                scale,
8146                                kvl.k_tok_bytes,
8147                                kvl.v_tok_bytes,
8148                                Engine::kv_fp8_on(),
8149                            )?;
8150                        }
8151                        e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
8152                    }
8153                }
8154
8155                // Output gate (element-wise) + o-proj at m=T.
8156                let attn_g = match &gate {
8157                    Some(g) => {
8158                        let n = t * q_dim;
8159                        let mut gsig = e.uninit(n)?;
8160                        e.sigmoid(g, &mut gsig, n)?;
8161                        let mut ag = e.uninit(n)?;
8162                        e.mul(&attn, &gsig, &mut ag, n)?;
8163                        ag
8164                    }
8165                    None => attn,
8166                };
8167                e.matmul(&fa.wo, &attn_g, t)?
8168            }
8169        };
8170
8171        // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
8172        let pnorm = layer.post_attn_norm.float_data();
8173        let mut x1 = e.uninit(t * n_embd)?;
8174        let mut zn = e.uninit(t * n_embd)?;
8175        e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
8176        let ffn_out = match &layer.ffn {
8177            crate::hybrid::Ffn::Dense {
8178                ffn_gate,
8179                ffn_up,
8180                ffn_down,
8181            } => {
8182                assert!(
8183                    self.cfg.m3.is_none(),
8184                    "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
8185                );
8186                self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
8187            }
8188            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
8189        };
8190        let mut x2 = e.uninit(t * n_embd)?;
8191        e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
8192        // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
8193        self.dflash_tap(e, cache, il, &x2, t)?;
8194        Ok(x2)
8195    }
8196
8197    /// ONE t-parallel LINEAR layer (attn_norm + gdn mixer + post_attn_norm + FFN + tap) —
8198    /// the exact body the old in-loop Linear arm ran, extracted so the eager walk and the
8199    /// slice-3 captured segments execute the SAME code (a second copy is how dispatch
8200    /// mirrors drift — the verify_layers extraction lesson). Two deliberate changes, both
8201    /// bit-identical by construction:
8202    /// - the gdn ping-pong host swap moves from per-row to ONE end-of-body swap (t odd):
8203    ///   the device sequence is driven entirely by the 6-entry pointer table, which
8204    ///   already encodes both parities; the ckpt stash reads name row r's out buffer
8205    ///   directly (r even -> alt handle, odd -> canonical) — the same physical bytes the
8206    ///   legacy post-swap clone read.
8207    /// - `stash` (slice-3 ctx): persistent per-layer slabs written by copy_into instead of
8208    ///   per-row clone_dtod allocs — same bytes, capture-legal (no per-round host objects).
8209    ///   `table_src` = (persistent pointer table, offset) when the ctx owns the tables;
8210    ///   None builds the per-verify table exactly as before.
8211    #[allow(clippy::too_many_arguments)]
8212    fn qwen35_tparallel_linear_layer(
8213        &self,
8214        e: &Engine,
8215        il: usize,
8216        x: &CudaSlice<f32>,
8217        t: usize,
8218        cache: &mut Cache,
8219        ckpt: Option<&mut VerifyCkpt>,
8220        stash: Option<(&mut CudaSlice<f32>, &mut CudaSlice<f32>)>,
8221        table_src: Option<(&CudaSlice<u64>, usize)>,
8222    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8223        use cudarc::driver::DevicePtr;
8224        let cfg = &self.cfg;
8225        let n_embd = cfg.n_embd as usize;
8226        let eps = cfg.rms_eps;
8227        let layer = &self.layers[il];
8228        let Mixer::Linear(la) = &layer.mixer else {
8229            return Err("qwen35_tparallel_linear_layer on a non-linear layer".into());
8230        };
8231        // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
8232        let anorm = layer.attn_norm.float_data();
8233        let mut xn = e.uninit(t * n_embd)?;
8234        e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
8235        let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
8236
8237        let geometry = la.geometry;
8238        let d_state = geometry.key_head_dim as usize;
8239        let num_k = geometry.key_heads as usize;
8240        let num_v = geometry.value_heads as usize;
8241        let d_conv = geometry.conv_kernel as usize;
8242        let key_dim = d_state * num_k;
8243        let value_dim = geometry.value_head_dim as usize * num_v;
8244        let conv_dim = key_dim * 2 + value_dim;
8245        let gdn_scale = 1.0 / (d_state as f32).sqrt();
8246
8247        // ---- batched projections: one weight read for all T rows ----
8248        // GROUP-4 twin (trunk-kernels slice C): the whole 4-tuple in ONE launch, bit-identical
8249        // per (tensor, token, row) to the four singles; refused (layout/tier) or
8250        // MEMRA_TK_GDN_GROUP=0 -> the singles chain byte-for-byte.
8251        let (qkv_mixed, z, beta_raw, alpha) = match e.matmul_decode_exact_group4_pre(
8252            [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha],
8253            &hq,
8254            &hd,
8255            t,
8256        )? {
8257            Some(mut g4) => {
8258                let alpha = g4.pop().unwrap();
8259                let beta_raw = g4.pop().unwrap();
8260                let z = g4.pop().unwrap();
8261                let qkv_mixed = g4.pop().unwrap();
8262                (qkv_mixed, z, beta_raw, alpha)
8263            }
8264            None => (
8265                e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?,
8266                e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?,
8267                e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?,
8268                e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?,
8269            ),
8270        };
8271        let beta_w = la.ssm_beta.out_features();
8272        let alpha_w = la.ssm_alpha.out_features();
8273        let qkv_w = la.wqkv.out_features();
8274
8275        // ---- per-row state chain through the b_n=1 serving kernels ----
8276        // 6-entry alternating pointer table expresses the ping-pong without a rebuild per
8277        // row: even rows scan s0 -> s1, odd rows s1 -> s0.
8278        let table_local: Option<CudaSlice<u64>> = match table_src {
8279            Some(_) => None,
8280            None => {
8281                let rl = cache.recur[il].as_ref().unwrap();
8282                let s = &e.gpu.stream();
8283                let (pc, _g0) = rl.conv_state.device_ptr(s);
8284                let (p0, _g1) = rl.ssm_state.device_ptr(s);
8285                let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
8286                Some(e.htod_u64(&[pc, p0, p1, pc, p1, p0])?)
8287            }
8288        };
8289        let (table, toff): (&CudaSlice<u64>, usize) = match table_src {
8290            Some((tb, off)) => (tb, off),
8291            None => (table_local.as_ref().unwrap(), 0),
8292        };
8293        let mut o_all = e.uninit(t * value_dim)?;
8294        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
8295            if ckpt.is_some() && stash.is_none() && t >= 2 {
8296                Some(Vec::with_capacity(t - 1))
8297            } else {
8298                None
8299            };
8300        let mut stash = stash;
8301        // Per-row scratch reused across rows (uninit is cheap but not free at
8302        // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
8303        // [T, ...] buffers — zero arithmetic-free copies in this loop.
8304        let mut conv_out = e.uninit(conv_dim)?;
8305        let mut q_l2 = e.uninit(value_dim)?;
8306        let mut k_l2 = e.uninit(value_dim)?;
8307        let mut v_gd = e.uninit(value_dim)?;
8308        let mut beta_b = e.uninit(num_v)?;
8309        let mut g_log = e.uninit(num_v)?;
8310        for r in 0..t {
8311            let base = toff + if r % 2 == 0 { 0 } else { 3 };
8312            let conv_view = table.slice(base..base + 1);
8313            let in_view = table.slice(base + 1..base + 2);
8314            let out_view = table.slice(base + 2..base + 3);
8315            e.ssm_conv1d_fused_decode_b_view(
8316                &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
8317                &conv_view,
8318                la.ssm_conv1d.float_data(),
8319                &mut conv_out,
8320                conv_dim,
8321                d_conv,
8322                1,
8323            )?;
8324            e.gdn_prep_decode_b_view(
8325                &conv_out,
8326                &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
8327                &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
8328                la.ssm_dt.float_data(),
8329                la.ssm_a.float_data(),
8330                &mut q_l2,
8331                &mut k_l2,
8332                &mut v_gd,
8333                &mut beta_b,
8334                &mut g_log,
8335                d_state,
8336                num_v,
8337                num_k,
8338                key_dim,
8339                eps,
8340                conv_dim,
8341                1,
8342            )?;
8343            let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
8344            e.gdn_scan_s128_batched_view(
8345                &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row, num_v, 1,
8346                gdn_scale,
8347            )?;
8348            if r + 1 < t {
8349                // Row r's out buffer: even rows write s1 (the alt handle — no swaps ran),
8350                // odd rows write s0 — the same physical state the legacy post-swap
8351                // canonical clone read.
8352                let rl = cache.recur[il]
8353                    .as_ref()
8354                    .ok_or("qwen35 linear verify layer has no recurrent state")?;
8355                let ssm_src = if r % 2 == 0 {
8356                    &rl.ssm_state_alt
8357                } else {
8358                    &rl.ssm_state
8359                };
8360                match stash.as_mut() {
8361                    Some((conv_slab, ssm_slab)) => {
8362                        // BOTH stash reads go through the pointer table at run time: the
8363                        // ssm handles ping-pong between rounds, and the ctx (with its
8364                        // captured graphs) outlives the Cache — a fresh generation's
8365                        // conv/ssm buffers land at new addresses that only the per-round
8366                        // table refresh knows. A baked direct copy would read freed
8367                        // memory (parity was the slice-3 smoke divergence; cache
8368                        // lifetime is the cross-generation twin).
8369                        e.copy_indirect_src_f32(
8370                            &conv_view,
8371                            conv_slab,
8372                            r * conv_dim * (d_conv - 1),
8373                            conv_dim * (d_conv - 1),
8374                        )?;
8375                        // The ssm handles PING-PONG between rounds: a captured direct
8376                        // copy would bake the capture-time physical buffer and read the
8377                        // wrong parity after any odd-vt round (the slice-3 smoke
8378                        // divergence). Read the src address from row r's OUT table
8379                        // entry at run time — the same entry the scan just wrote.
8380                        e.copy_indirect_src_f32(
8381                            &out_view,
8382                            ssm_slab,
8383                            r * d_state * d_state * num_v,
8384                            d_state * d_state * num_v,
8385                        )?;
8386                    }
8387                    None => {
8388                        if let Some(states) = col_states.as_mut() {
8389                            states.push((e.clone_dtod(&rl.conv_state)?, e.clone_dtod(ssm_src)?));
8390                        }
8391                    }
8392                }
8393            }
8394        }
8395        // ONE end-of-body parity swap (t odd) — the legacy loop swapped per row; the net
8396        // handle motion is identical and the device sequence never read the handles.
8397        if t % 2 == 1 {
8398            let rl = cache.recur[il].as_mut().unwrap();
8399            std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
8400        }
8401        if let (Some(checkpoint), Some(states)) = (ckpt, col_states) {
8402            checkpoint.cols[il] = Some(states);
8403        }
8404
8405        // ---- batched gated norm + out-projection at m=T ----
8406        let mixed = if e.uses_q8_1_fast(&la.ssm_out) {
8407            let (gq, gd) = e.gated_rmsnorm_q8_1(
8408                &o_all,
8409                la.ssm_norm.float_data(),
8410                &z,
8411                d_state,
8412                t * num_v,
8413                eps,
8414            )?;
8415            let g0 = e.zeros(0)?;
8416            e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
8417        } else {
8418            let mut gn = e.uninit(t * value_dim)?;
8419            e.gated_rmsnorm(
8420                &o_all,
8421                la.ssm_norm.float_data(),
8422                &z,
8423                &mut gn,
8424                d_state,
8425                t * num_v,
8426                eps,
8427            )?;
8428            e.matmul(&la.ssm_out, &gn, t)?
8429        };
8430
8431        // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
8432        let pnorm = layer.post_attn_norm.float_data();
8433        let mut x1 = e.uninit(t * n_embd)?;
8434        let mut zn = e.uninit(t * n_embd)?;
8435        e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
8436        let ffn_out = match &layer.ffn {
8437            crate::hybrid::Ffn::Dense {
8438                ffn_gate,
8439                ffn_up,
8440                ffn_down,
8441            } => {
8442                assert!(
8443                    self.cfg.m3.is_none(),
8444                    "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
8445                );
8446                self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
8447            }
8448            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
8449        };
8450        let mut x2 = e.uninit(t * n_embd)?;
8451        e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
8452        // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
8453        self.dflash_tap(e, cache, il, &x2, t)?;
8454        Ok(x2)
8455    }
8456
8457    /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
8458    /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
8459    /// carried in from outside the range) and exits with the range's final residual materialized
8460    /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
8461    /// instead of one.
8462    ///
8463    /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
8464    /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
8465    /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
8466    /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
8467    /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
8468    /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
8469    /// code — there is no "split version" of the verify math.
8470    ///
8471    /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
8472    /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
8473    /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
8474    /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
8475    #[allow(clippy::too_many_arguments)]
8476    fn verify_layers(
8477        &self,
8478        e: &Engine,
8479        mut x: CudaSlice<f32>,
8480        lo: usize,
8481        hi: usize,
8482        pos_d: &CudaSlice<i32>,
8483        pos0: usize,
8484        t: usize,
8485        cache: &mut Cache,
8486        mut ckpt: Option<&mut VerifyCkpt>,
8487        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
8488        graphs: Option<&mut DsparkVerifyGraphs>,
8489    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8490        if self.sliding_gated_moe_batch_program() {
8491            if stream.is_some() {
8492                return Err(
8493                    "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
8494                            cannot express the SWA offset KV view)"
8495                        .into(),
8496                );
8497            }
8498            return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
8499        }
8500        if self.batched_serving_numeric_class() {
8501            return self.qwen35_verify_batch_layers(
8502                e,
8503                x,
8504                lo,
8505                hi,
8506                pos0,
8507                t,
8508                cache,
8509                ckpt.take(),
8510                stream,
8511                graphs,
8512            );
8513        }
8514        let n_embd = self.cfg.n_embd as usize;
8515        let eps = self.cfg.rms_eps;
8516        // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
8517        // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
8518        // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
8519        // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
8520        // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
8521        // residual the next layer needs) as its `res` output. Falls back to the separate add
8522        // when the next layer is off the fused-q8 path.
8523        let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
8524        for il in lo..hi {
8525            let layer = &self.layers[il];
8526            // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
8527            // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
8528            // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
8529            // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
8530            // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
8531            // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
8532            // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
8533            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
8534            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
8535            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
8536            // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
8537            // projections only; Linear mixer: the batched arm — the per-column fallback needs
8538            // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
8539            // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
8540            // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
8541            // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
8542            // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
8543            // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
8544            // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
8545            // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
8546            let lin_q8_only = match &layer.mixer {
8547                Mixer::Linear(la) => {
8548                    (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
8549                }
8550                Mixer::Full(_) if self.sliding_gated_moe_batch_program() => false,
8551                _ => true,
8552            };
8553            // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
8554            // a non-fused layer still performs the residual add.
8555            let taken = pending.take();
8556            let (h, h_q8) = if norm_fused && lin_q8_only {
8557                let pair = match taken {
8558                    // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
8559                    // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
8560                    Some((x1p, f1p)) => {
8561                        let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
8562                        let p = e.add_rms_norm_q8_1(
8563                            &x1p,
8564                            &f1p,
8565                            layer.attn_norm.float_data(),
8566                            &mut x2,
8567                            n_embd,
8568                            t,
8569                            eps,
8570                        )?;
8571                        x = x2;
8572                        p
8573                    }
8574                    None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
8575                };
8576                (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
8577            } else {
8578                if let Some((x1p, f1p)) = taken {
8579                    let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
8580                    e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
8581                    x = x2;
8582                }
8583                let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
8584                if norm_fused {
8585                    e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
8586                } else {
8587                    e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
8588                }
8589                (h, None)
8590            };
8591            let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
8592
8593            let mixed = match &layer.mixer {
8594                Mixer::Full(fa) => self.full_attn_verify(
8595                    e,
8596                    fa,
8597                    &h,
8598                    h_q8_ref,
8599                    pos_d,
8600                    t,
8601                    cache,
8602                    il,
8603                    stream.map(|(_, c)| c),
8604                )?,
8605                Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("speculative verify"),
8606                Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("speculative verify"),
8607                Mixer::Linear(la) => {
8608                    // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
8609                    // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
8610                    // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
8611                    // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
8612                    // chained T=1 steps (bit-identical). Falls back to the sequential per-column
8613                    // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
8614                    // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
8615                    // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
8616                    // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
8617                    // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
8618                    // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
8619                    if (t >= 3 || (t == 2 && spec_m2()))
8620                        && mixer_fast
8621                        && e.uses_q8_1_fast(&la.ssm_out)
8622                    {
8623                        let want = ckpt.is_some();
8624                        let (out, stash) =
8625                            self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
8626                        if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
8627                            ck.gdn[il] = Some(st);
8628                        }
8629                        out
8630                    } else {
8631                        let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
8632                        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
8633                            if ckpt.is_some() && t >= 2 {
8634                                Some(Vec::with_capacity(t - 1))
8635                            } else {
8636                                None
8637                            };
8638                        for col in 0..t {
8639                            let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
8640                            let src = h.slice(col * n_embd..(col + 1) * n_embd);
8641                            e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
8642                            let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
8643                            e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
8644                            // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
8645                            // (pure dtod — cannot change any computed value). Last column skipped:
8646                            // rebuild targets are j <= t-1 columns.
8647                            if let Some(cs) = col_states.as_mut()
8648                                && col + 1 < t
8649                            {
8650                                let rl = cache.recur[il].as_ref().unwrap();
8651                                cs.push((
8652                                    e.clone_dtod(&rl.conv_state)?,
8653                                    e.clone_dtod(&rl.ssm_state)?,
8654                                ));
8655                            }
8656                        }
8657                        if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
8658                            // ReplaySSM-assessment instrumentation (2026-07-30): the
8659                            // per-column clones are the only true state snapshots left in
8660                            // the verify (the batched path stashes INPUTS and replays).
8661                            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
8662                                static ONCE: std::sync::Once = std::sync::Once::new();
8663                                let bytes: usize =
8664                                    cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
8665                                ONCE.call_once(|| eprintln!(
8666                                    "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
8667                                    cs.len(), bytes as f64 / 1e6));
8668                            }
8669                            ck.cols[il] = Some(cs);
8670                        }
8671                        out
8672                    }
8673                }
8674            };
8675            if spec_nan_scan_level() >= 2 {
8676                let mixed_width = mixed.len() / t;
8677                nan_scan_rows(
8678                    e,
8679                    &mixed,
8680                    t,
8681                    mixed_width,
8682                    &format!("verify layer {il} batched ATTN out pos0={pos0}"),
8683                )?;
8684            }
8685
8686            // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
8687            // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
8688            // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
8689            let ffn_fuse = match &layer.ffn {
8690                crate::hybrid::Ffn::Dense {
8691                    ffn_gate, ffn_up, ..
8692                } => {
8693                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
8694                        && e.uses_q8_1_fast(ffn_gate)
8695                        && e.uses_q8_1_fast(ffn_up)
8696                }
8697                crate::hybrid::Ffn::Moe(_) => false,
8698            };
8699            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
8700            // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
8701            // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
8702            // per-row m=1 program; kernel-check pins bit-identity vs the unfused
8703            // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
8704            // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
8705            // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
8706            // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
8707            // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
8708            // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
8709            // mirror decode's dispatch or spec self-consistency fails.
8710            let dense_lim = self.cfg.clamp_shexp_at(il as u32);
8711            let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
8712            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
8713            let mut z = e.zeros(0)?; // replaced below on the unfused arms
8714            let z_q8 = if fuse_q8 {
8715                Some(e.add_rms_norm_q8_1(
8716                    &x,
8717                    &mixed,
8718                    layer.post_attn_norm.float_data(),
8719                    &mut x1,
8720                    n_embd,
8721                    t,
8722                    eps,
8723                )?)
8724            } else {
8725                let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
8726                if ffn_fuse {
8727                    e.add(&x, &mixed, &mut x1, t * n_embd)?;
8728                    e.rms_norm_decode(
8729                        &x1,
8730                        layer.post_attn_norm.float_data(),
8731                        &mut zf,
8732                        n_embd,
8733                        t,
8734                        eps,
8735                    )?;
8736                } else {
8737                    e.add_rms_norm(
8738                        &x,
8739                        &mixed,
8740                        layer.post_attn_norm.float_data(),
8741                        &mut x1,
8742                        &mut zf,
8743                        n_embd,
8744                        t,
8745                        eps,
8746                    )?;
8747                }
8748                z = zf;
8749                None
8750            };
8751            if spec_nan_scan_level() >= 2 && !z.is_empty() {
8752                nan_scan_rows(
8753                    e,
8754                    &z,
8755                    t,
8756                    n_embd,
8757                    &format!("verify layer {il} post-attn norm z pos0={pos0}"),
8758                )?;
8759            }
8760            // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
8761            // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
8762            // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
8763            let ffn_out = match &layer.ffn {
8764                crate::hybrid::Ffn::Dense {
8765                    ffn_gate,
8766                    ffn_up,
8767                    ffn_down,
8768                } => {
8769                    let n_ff = ffn_gate.out_features();
8770                    if let Some((zq, zd)) = z_q8.as_ref() {
8771                        // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
8772                        // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
8773                        // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
8774                        // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
8775                        // scale_inplace store, value-exact) — the exact m=1 decode epilogue
8776                        // structure at nrows=t.
8777                        let pair = e
8778                            .matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)?
8779                            .map(|((g, gs), (u, us))| (g, gs, u, us));
8780                        let (gate, gs, up, us) = match pair {
8781                            Some(x4) => x4,
8782                            None => (
8783                                e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
8784                                1.0, // scale already applied inside _pre
8785                                e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
8786                                1.0,
8787                            ),
8788                        };
8789                        if e.uses_q8_1_fast(ffn_down) {
8790                            let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
8791                            e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
8792                        } else {
8793                            let mut act = vbuf(e, t * n_ff)?;
8794                            e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
8795                            e.matmul_decode_exact(ffn_down, &act, t)?
8796                        }
8797                    } else {
8798                        // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
8799                        // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
8800                        // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
8801                        // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
8802                        // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
8803                        let (gate, up) =
8804                            match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
8805                                Some(pair) => pair,
8806                                None => (
8807                                    e.matmul_decode_exact(ffn_gate, &z, t)?,
8808                                    e.matmul_decode_exact(ffn_up, &z, t)?,
8809                                ),
8810                            };
8811                        let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
8812                        Self::ffn_act_lim(
8813                            e,
8814                            &self.cfg,
8815                            &gate,
8816                            &up,
8817                            1.0,
8818                            1.0,
8819                            dense_lim,
8820                            &mut act,
8821                            t * n_ff,
8822                        )?;
8823                        e.matmul_decode_exact(ffn_down, &act, t)?
8824                    }
8825                }
8826                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
8827            };
8828            if spec_nan_scan_level() >= 2 {
8829                nan_scan_rows(
8830                    e,
8831                    &ffn_out,
8832                    t,
8833                    n_embd,
8834                    &format!("verify layer {il} batched FFN out pos0={pos0}"),
8835                )?;
8836            }
8837            if spec_nan_scan() {
8838                let mut residual = vbuf(e, t * n_embd)?;
8839                e.add(&x1, &ffn_out, &mut residual, t * n_embd)?;
8840                nan_scan_rows(
8841                    e,
8842                    &residual,
8843                    t,
8844                    n_embd,
8845                    &format!("verify layer {il} residual pos0={pos0}"),
8846                )?;
8847            }
8848            // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
8849            // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
8850            // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
8851            pending = Some((x1, ffn_out));
8852        }
8853        // RANGE's final add (no next norm INSIDE the range to fuse with; for the
8854        // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
8855        if let Some((x1p, f1p)) = pending.take() {
8856            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
8857            e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
8858            x = x2;
8859        }
8860        Ok(x)
8861    }
8862    /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
8863    /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
8864    /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
8865    /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
8866    /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
8867    /// ssm state exactly like T sequential decode steps.
8868    /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
8869    /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
8870    #[allow(clippy::too_many_arguments)]
8871    fn linear_attn_verify_t(
8872        &self,
8873        e: &Engine,
8874        la: &LinearAttnLayer,
8875        h: &CudaSlice<f32>,
8876        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
8877        t: usize,
8878        cache: &mut Cache,
8879        il: usize,
8880        want_stash: bool,
8881    ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
8882        let cfg = &self.cfg;
8883        let geometry = la.geometry;
8884        let d_state = geometry.key_head_dim as usize;
8885        let num_k = geometry.key_heads as usize;
8886        let num_v = geometry.value_heads as usize;
8887        let d_conv = geometry.conv_kernel as usize;
8888        let key_dim = d_state * num_k;
8889        let conv_dim = key_dim * 2 + geometry.value_head_dim as usize * num_v;
8890        let eps = cfg.rms_eps;
8891        let scale = 1.0 / (d_state as f32).sqrt();
8892
8893        // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
8894        // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
8895        // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
8896        // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
8897        // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
8898        // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
8899        // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
8900        // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
8901        // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
8902        // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
8903        // Bit-identical per (tensor,token,row) — see spec_fused_t().
8904        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
8905        // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
8906        // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
8907        // and feeds every projection; the caller guaranteed all four input projections are
8908        // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
8909        let h_q8_t = if h_q8.is_none()
8910            && spec_fused_t()
8911            && (2..=4).contains(&t)
8912            && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
8913                || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
8914        {
8915            Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
8916        } else {
8917            None
8918        };
8919        // one view: the caller's fused-norm q8 or this fn's own shared quantize.
8920        let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
8921            h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
8922        let (qkv_mixed, z) = {
8923            let mut fused = None;
8924            if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
8925                let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
8926                fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
8927            } else if let Some((hq, hd)) = hq8_any
8928                && spec_fused_t()
8929                && (2..=4).contains(&t)
8930            {
8931                fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
8932            }
8933            match (fused, hq8_any) {
8934                (Some(pair), _) => pair,
8935                (None, Some((hq, hd))) if h_q8.is_some() => (
8936                    e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
8937                    e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
8938                ),
8939                (None, _) => (
8940                    e.matmul_decode_exact(&la.wqkv, h, t)?,
8941                    e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
8942                ),
8943            }
8944        };
8945        // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
8946        // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
8947        // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
8948        // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
8949        let (beta_raw, alpha) = if t == 1 {
8950            let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
8951            match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
8952                Some(((mut b, bs), (mut a, as_))) => {
8953                    if bs != 1.0 {
8954                        e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
8955                    }
8956                    if as_ != 1.0 {
8957                        e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
8958                    }
8959                    (b, a)
8960                }
8961                // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
8962                // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
8963                // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
8964                None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
8965                    Some((b, a)) => (b, a),
8966                    None => (
8967                        e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
8968                        e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
8969                    ),
8970                },
8971            }
8972        } else {
8973            // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
8974            // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
8975            let mut nvfp4_fused = None;
8976            let mut q8_fused = None;
8977            if let Some((hq, hd)) = hq8_any {
8978                if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
8979                    nvfp4_fused =
8980                        e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
8981                    if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
8982                        static ONCE: std::sync::Once = std::sync::Once::new();
8983                        ONCE.call_once(|| {
8984                            eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
8985                        });
8986                    }
8987                }
8988                if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
8989                    q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
8990                }
8991            }
8992            if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
8993                if bs != 1.0 {
8994                    e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
8995                }
8996                if as_ != 1.0 {
8997                    e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
8998                }
8999                (b, a)
9000            } else if let Some(pair) = q8_fused {
9001                pair
9002            } else {
9003                match hq8_any {
9004                    Some((hq, hd)) if h_q8.is_some() => (
9005                        e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
9006                        e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
9007                    ),
9008                    _ => (
9009                        e.matmul_decode_exact(&la.ssm_beta, h, t)?,
9010                        e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
9011                    ),
9012                }
9013            }
9014        };
9015
9016        // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
9017        // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
9018        let rl = cache.recur[il].as_mut().unwrap();
9019        let mut conv_out = e.uninit(conv_dim * t)?;
9020        e.ssm_conv1d_tm_state(
9021            &qkv_mixed,
9022            &mut rl.conv_state,
9023            la.ssm_conv1d.float_data(),
9024            &mut conv_out,
9025            conv_dim,
9026            t,
9027            d_conv,
9028        )?;
9029
9030        // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
9031        let mut q_g = e.uninit(d_state * num_v * t)?;
9032        let mut k_g = e.uninit(d_state * num_v * t)?;
9033        let mut v_g = e.uninit(d_state * num_v * t)?;
9034        e.qkv_to_gdn_repack(
9035            &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
9036        )?;
9037        let mut q_l2 = e.uninit(d_state * num_v * t)?;
9038        e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
9039        let mut k_l2 = e.uninit(d_state * num_v * t)?;
9040        e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
9041        let mut beta = e.uninit(t * num_v)?;
9042        e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
9043        let mut g_log = e.uninit(t * num_v)?;
9044        e.gdn_glog(
9045            &alpha,
9046            la.ssm_dt.float_data(),
9047            la.ssm_a.float_data(),
9048            &mut g_log,
9049            num_v,
9050            t,
9051        )?;
9052
9053        // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
9054        // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
9055        let mut o = e.uninit(d_state * num_v * t)?;
9056        {
9057            let crate::cache::RecurLayer {
9058                ssm_state,
9059                ssm_state_alt,
9060                ..
9061            } = rl;
9062            e.gdn_scan_s128(
9063                &q_l2,
9064                &k_l2,
9065                &v_g,
9066                &g_log,
9067                &beta,
9068                ssm_state,
9069                ssm_state_alt,
9070                &mut o,
9071                num_v,
9072                t,
9073                scale,
9074            )?;
9075        }
9076        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
9077
9078        // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
9079        // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
9080        // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
9081        // T-wide launch is the per-row program; kernel-check pins bit-identity vs
9082        // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
9083        // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
9084        let out = if e.uses_q8_1_fast(&la.ssm_out) {
9085            let (gq, gd) =
9086                e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
9087            e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
9088        } else {
9089            let mut gn = e.uninit(d_state * num_v * t)?;
9090            e.gated_rmsnorm(
9091                &o,
9092                la.ssm_norm.float_data(),
9093                &z,
9094                &mut gn,
9095                d_state,
9096                num_v * t,
9097                eps,
9098            )?;
9099            // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
9100            // would fall to dp4a with a different FP reduction order — same class of bug as
9101            // the input projs).
9102            e.matmul_decode_exact(&la.ssm_out, &gn, t)?
9103        };
9104        let stash = if want_stash {
9105            Some(GdnStash {
9106                qkv_mixed,
9107                q_l2,
9108                k_l2,
9109                v_g,
9110                g_log,
9111                beta,
9112            })
9113        } else {
9114            None
9115        };
9116        Ok((out, stash))
9117    }
9118
9119    /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
9120    /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
9121    /// - Full-attn KV: truncate both the owning-stage shadow and every TP rank to snapshot + j.
9122    ///   The verify's appended rows for those columns are bit-identical to what an eager T=1
9123    ///   chain writes (the decode-exact contract the verify-probe gates), so keeping them ==
9124    ///   replaying them.
9125    /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
9126    ///   columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
9127    ///   snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
9128    ///   registers and writes it once at the end, so iterations 0..j-1 are independent of T:
9129    ///   bit-identical to the verify's own state after j tokens == the eager chain state.
9130    /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
9131    ///   Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
9132    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
9133    fn commit_verified_prefix(
9134        &self,
9135        e: &Engine,
9136        cache: &mut Cache,
9137        snap: &crate::cache::CacheSnapshot,
9138        ckpt: &VerifyCkpt,
9139        j: usize,
9140        kv_lens_done: bool,
9141        dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
9142    ) -> Result<(), Box<dyn std::error::Error>> {
9143        // GDN geometry derives lazily inside recurrent-layer arms. Full-attention plans carry no
9144        // recurrent state and must never be forced through a synthetic SSM geometry.
9145        // Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1): the per-column-arm restores
9146        // are 2 tiny D2D copies per linear layer (~96 dispatches/partial round on the q38
9147        // route). When every cols-arm layer shares uniform state sizes (single ssm cfg —
9148        // always true today), batch them into two `copy_batch_uniform_f32` launches. Bytes,
9149        // buffers and stream order are identical to the per-layer memcpy sequence; the
9150        // kernel-rebuild (gdn-stash) arm below is untouched. MEMRA_STATE_COPY_BATCH=0 reverts.
9151        let mut batched_cols = false;
9152        if state_copy_batch_on() && dev_j.is_none() {
9153            use cudarc::driver::DevicePtr;
9154            let s = &e.gpu.stream();
9155            let mut conv_pairs: Vec<(u64, u64)> = Vec::new();
9156            let mut ssm_pairs: Vec<(u64, u64)> = Vec::new();
9157            let (mut conv_words, mut ssm_words) = (0usize, 0usize);
9158            let mut uniform = true;
9159            for il in 0..self.layers.len() {
9160                let Some(rl) = cache.recur[il].as_ref() else {
9161                    continue;
9162                };
9163                if ckpt.gdn[il].is_some() {
9164                    continue; // kernel-rebuild arm restores below, per layer
9165                }
9166                let Some(cols) = &ckpt.cols[il] else {
9167                    continue; // missing-ckpt error surfaces in the main loop
9168                };
9169                let (c, st) = &cols[j - 1];
9170                if conv_pairs.is_empty() {
9171                    conv_words = c.len();
9172                    ssm_words = st.len();
9173                } else if c.len() != conv_words || st.len() != ssm_words {
9174                    uniform = false;
9175                    break;
9176                }
9177                let (pc, _g0) = c.device_ptr(s);
9178                let (dc, _g1) = rl.conv_state.device_ptr(s);
9179                let (ps, _g2) = st.device_ptr(s);
9180                let (ds, _g3) = rl.ssm_state.device_ptr(s);
9181                conv_pairs.push((pc, dc));
9182                ssm_pairs.push((ps, ds));
9183            }
9184            if uniform && !conv_pairs.is_empty() {
9185                let n = conv_pairs.len();
9186                let mut t = vec![0u64; 2 * n];
9187                for (k, &(src, dst)) in conv_pairs.iter().enumerate() {
9188                    t[k] = src;
9189                    t[n + k] = dst;
9190                }
9191                let conv_t = e.htod_u64(&t)?;
9192                for (k, &(src, dst)) in ssm_pairs.iter().enumerate() {
9193                    t[k] = src;
9194                    t[n + k] = dst;
9195                }
9196                let ssm_t = e.htod_u64(&t)?;
9197                e.copy_batch_uniform_f32(&conv_t, n, conv_words)?;
9198                e.copy_batch_uniform_f32(&ssm_t, n, ssm_words)?;
9199                batched_cols = true;
9200            }
9201        }
9202        rewind_tp_kv_verified_prefix(&mut cache.tp_kv, &snap.tp_kv_len, j)?;
9203        for il in 0..self.layers.len() {
9204            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
9205                kvl.len = saved + j;
9206                // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
9207                if !kv_lens_done {
9208                    e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
9209                }
9210            }
9211            if let Some(rl) = cache.recur[il].as_mut() {
9212                let Mixer::Linear(linear) = &self.layers[il].mixer else {
9213                    return Err(format!("recurrent cache layer {il} has no GDN plan").into());
9214                };
9215                let geometry = linear.geometry;
9216                let d_state = geometry.key_head_dim as usize;
9217                let num_k = geometry.key_heads as usize;
9218                let num_v = geometry.value_heads as usize;
9219                let d_conv = geometry.conv_kernel as usize;
9220                let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
9221                let scale = 1.0 / (d_state as f32).sqrt();
9222                if let Some(st) = &ckpt.gdn[il] {
9223                    let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
9224                    let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
9225                    if let Some((acc, base, t_v)) = dev_j {
9226                        // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
9227                        e.ssm_conv_ring_rebuild_dc(
9228                            &st.qkv_mixed,
9229                            ring_old,
9230                            &mut rl.conv_state,
9231                            conv_dim,
9232                            acc,
9233                            base,
9234                            t_v,
9235                            d_conv,
9236                        )?;
9237                        let mut o = e.uninit(d_state * num_v * j.max(1))?;
9238                        e.gdn_scan_s128_dc(
9239                            &st.q_l2,
9240                            &st.k_l2,
9241                            &st.v_g,
9242                            &st.g_log,
9243                            &st.beta,
9244                            state_in,
9245                            &mut rl.ssm_state,
9246                            &mut o,
9247                            num_v,
9248                            acc,
9249                            base,
9250                            t_v,
9251                            scale,
9252                        )?;
9253                    } else {
9254                        e.ssm_conv_ring_rebuild(
9255                            &st.qkv_mixed,
9256                            ring_old,
9257                            &mut rl.conv_state,
9258                            conv_dim,
9259                            j,
9260                            d_conv,
9261                        )?;
9262                        let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
9263                        e.gdn_scan_s128(
9264                            &st.q_l2,
9265                            &st.k_l2,
9266                            &st.v_g,
9267                            &st.g_log,
9268                            &st.beta,
9269                            state_in,
9270                            &mut rl.ssm_state,
9271                            &mut o,
9272                            num_v,
9273                            j,
9274                            scale,
9275                        )?;
9276                    }
9277                } else if let Some(cols) = &ckpt.cols[il] {
9278                    if !batched_cols {
9279                        let (c, s) = &cols[j - 1];
9280                        e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
9281                        e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
9282                    }
9283                } else {
9284                    return Err(
9285                        "commit_verified_prefix: verify ckpt missing for linear layer".into(),
9286                    );
9287                }
9288            }
9289        }
9290        cache.pos = snap.pos + j;
9291        Ok(())
9292    }
9293
9294    /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
9295    /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
9296    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
9297    fn commit_verified_prefix_stream(
9298        &self,
9299        e: &Engine,
9300        cache: &mut Cache,
9301        snap: &crate::cache::CacheSnapshot,
9302        ckpt: &VerifyCkpt,
9303        acc: &CudaSlice<u32>,
9304        base: usize,
9305        t_v: usize,
9306    ) -> Result<(), Box<dyn std::error::Error>> {
9307        for il in 0..self.layers.len() {
9308            if let Some(rl) = cache.recur[il].as_mut() {
9309                let Mixer::Linear(linear) = &self.layers[il].mixer else {
9310                    return Err(format!("recurrent cache layer {il} has no GDN plan").into());
9311                };
9312                let geometry = linear.geometry;
9313                let d_state = geometry.key_head_dim as usize;
9314                let num_k = geometry.key_heads as usize;
9315                let num_v = geometry.value_heads as usize;
9316                let d_conv = geometry.conv_kernel as usize;
9317                let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
9318                let scale = 1.0 / (d_state as f32).sqrt();
9319                let st = ckpt.gdn[il]
9320                    .as_ref()
9321                    .ok_or("stream restore: batched-linear stash missing")?;
9322                let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
9323                let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
9324                e.ssm_conv_ring_rebuild_dc(
9325                    &st.qkv_mixed,
9326                    ring_old,
9327                    &mut rl.conv_state,
9328                    conv_dim,
9329                    acc,
9330                    base,
9331                    t_v,
9332                    d_conv,
9333                )?;
9334                let mut o = e.uninit(d_state * num_v * t_v)?;
9335                e.gdn_scan_s128_dc(
9336                    &st.q_l2,
9337                    &st.k_l2,
9338                    &st.v_g,
9339                    &st.g_log,
9340                    &st.beta,
9341                    state_in,
9342                    &mut rl.ssm_state,
9343                    &mut o,
9344                    num_v,
9345                    acc,
9346                    base,
9347                    t_v,
9348                    scale,
9349                )?;
9350            }
9351        }
9352        Ok(())
9353    }
9354
9355    /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
9356    /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
9357    /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
9358    /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
9359    /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
9360    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
9361    pub fn decode_step_t_aux2(
9362        &self,
9363        e: &Engine,
9364        tokens: &[u32],
9365        pos0: usize,
9366        cache: &mut Cache,
9367        aux_layers: &[usize],
9368        pred_col: Option<usize>,
9369    ) -> Result<
9370        (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
9371        Box<dyn std::error::Error>,
9372    > {
9373        cache.ensure_usable("decode_step_t_aux2")?;
9374        let cfg = &self.cfg;
9375        let n_embd = cfg.n_embd as usize;
9376        let eps = cfg.rms_eps;
9377        let t = tokens.len();
9378        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
9379        let pos_d = e.htod_i32(&pos_vec)?;
9380        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
9381        let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
9382        let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
9383        let want_pred = pred_col.is_some();
9384
9385        for (il, layer) in self.layers.iter().enumerate() {
9386            // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
9387            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
9388            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
9389            let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
9390            if norm_fused {
9391                e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
9392            } else {
9393                e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
9394            }
9395            let mixed = match &layer.mixer {
9396                Mixer::Full(fa) => {
9397                    self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
9398                }
9399                Mixer::Mla(_) => {
9400                    crate::hybrid::mla_path_unimplemented("auxiliary T-parallel decode")
9401                }
9402                Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("aux decode step"),
9403                Mixer::Linear(la) => {
9404                    let mut out = e.zeros(t * n_embd)?;
9405                    for col in 0..t {
9406                        let mut h_col = e.zeros(n_embd)?;
9407                        let src = h.slice(col * n_embd..(col + 1) * n_embd);
9408                        e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
9409                        let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
9410                        e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
9411                    }
9412                    out
9413                }
9414            };
9415            let ffn_fuse = match &layer.ffn {
9416                crate::hybrid::Ffn::Dense {
9417                    ffn_gate, ffn_up, ..
9418                } => {
9419                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
9420                        && e.uses_q8_1_fast(ffn_gate)
9421                        && e.uses_q8_1_fast(ffn_up)
9422                }
9423                crate::hybrid::Ffn::Moe(_) => false,
9424            };
9425            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
9426            let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
9427            if ffn_fuse {
9428                e.add(&x, &mixed, &mut x1, t * n_embd)?;
9429                e.rms_norm_decode(
9430                    &x1,
9431                    layer.post_attn_norm.float_data(),
9432                    &mut z,
9433                    n_embd,
9434                    t,
9435                    eps,
9436                )?;
9437            } else {
9438                e.add_rms_norm(
9439                    &x,
9440                    &mixed,
9441                    layer.post_attn_norm.float_data(),
9442                    &mut x1,
9443                    &mut z,
9444                    n_embd,
9445                    t,
9446                    eps,
9447                )?;
9448            }
9449            let ffn_out = match &layer.ffn {
9450                crate::hybrid::Ffn::Dense {
9451                    ffn_gate,
9452                    ffn_up,
9453                    ffn_down,
9454                } => {
9455                    let n_ff = ffn_gate.out_features();
9456                    let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
9457                    let up = e.matmul_decode_exact(ffn_up, &z, t)?;
9458                    let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
9459                    // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
9460                    Self::ffn_act_lim(
9461                        e,
9462                        &self.cfg,
9463                        &gate,
9464                        &up,
9465                        1.0,
9466                        1.0,
9467                        self.cfg.clamp_shexp_at(il as u32),
9468                        &mut act,
9469                        t * n_ff,
9470                    )?;
9471                    e.matmul_decode_exact(ffn_down, &act, t)?
9472                }
9473                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
9474            };
9475            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
9476            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
9477            if aux_layers.contains(&il) {
9478                let mut a = e.zeros(n_embd)?;
9479                e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
9480                aux_last.push(a);
9481                if let Some(pc) = pred_col {
9482                    let mut ap = e.zeros(n_embd)?;
9483                    e.copy_view_into(
9484                        &mut ap,
9485                        0,
9486                        &x2.slice(pc * n_embd..(pc + 1) * n_embd),
9487                        n_embd,
9488                    )?;
9489                    aux_pred.push(ap);
9490                }
9491            }
9492            x = x2;
9493        }
9494        let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
9495        e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
9496        let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
9497        let host = e.dtoh(&logits)?;
9498        cache.pos += t;
9499        Ok((
9500            host,
9501            aux_last,
9502            if want_pred { Some(aux_pred) } else { None },
9503        ))
9504    }
9505
9506    /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
9507    /// `step35_decode_attn`.
9508    ///
9509    /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
9510    /// the eager decode would have computed for the same tokens; that is what makes greedy spec
9511    /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
9512    /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
9513    /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
9514    /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
9515    /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
9516    /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
9517    /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
9518    /// position of each query row. A batched twin would have to reproduce all of that AND the
9519    /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
9520    /// take one `base_len`, not a per-row offset).
9521    ///
9522    /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
9523    /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
9524    /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
9525    /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
9526    /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
9527    /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
9528    /// step35 twin is a perf lane's job and must be gated against this arm.
9529    ///
9530    /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
9531    /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
9532    /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
9533    /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
9534    /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
9535    #[allow(clippy::too_many_arguments)]
9536    fn step35_verify(
9537        &self,
9538        e: &Engine,
9539        fa: &FullAttnLayer,
9540        h: &CudaSlice<f32>,
9541        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
9542        t: usize,
9543        cache: &mut Cache,
9544        il: usize,
9545    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9546        let n_embd = self.cfg.n_embd as usize;
9547        // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
9548        // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
9549        // site by the sliding-gated-MoE `Mixer::Full(_) => false` arm of
9550        // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
9551        // cannot regress it into silently reading an empty buffer.
9552        assert_eq!(
9553            h.len(),
9554            t * n_embd,
9555            "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
9556             fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
9557            h_q8.is_some()
9558        );
9559        // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
9560        // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
9561        // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
9562        // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
9563        // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
9564        // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
9565        let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
9566        for r in 0..t {
9567            // Absolute position of this query row. `cache.pos` is the committed length at round
9568            // start and every row before r has already been appended by this loop, so the r-th
9569            // verify token sits at cache.pos + r — the same position eager decode would give it.
9570            let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
9571            let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
9572            e.copy_view_into(
9573                &mut h_row,
9574                0,
9575                &h.slice(r * n_embd..(r + 1) * n_embd),
9576                n_embd,
9577            )?;
9578            // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
9579            // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
9580            let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
9581            debug_assert_eq!(
9582                o.len(),
9583                n_embd,
9584                "step35_decode_attn returns post-wo [n_embd]"
9585            );
9586            e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
9587        }
9588        Ok(out)
9589    }
9590
9591    /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
9592    /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
9593    /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
9594    #[allow(clippy::too_many_arguments)]
9595    fn full_attn_verify(
9596        &self,
9597        e: &Engine,
9598        fa: &FullAttnLayer,
9599        h: &CudaSlice<f32>,
9600        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
9601        pos_d: &CudaSlice<i32>,
9602        t: usize,
9603        cache: &mut Cache,
9604        il: usize,
9605        stream_ctr: Option<&CudaSlice<i32>>,
9606    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9607        // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
9608        // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
9609        // its own arm. A verify that silently computes different attention than decode defeats the
9610        // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
9611        // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
9612        // shape and not laziness.
9613        if self.sliding_gated_moe_batch_program() {
9614            if stream_ctr.is_some() {
9615                return Err(
9616                    "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
9617                            cannot express the SWA offset KV view; same root cause as the dc \
9618                            decode refusal) — run spec without the stream arm"
9619                        .into(),
9620                );
9621            }
9622            return self.step35_verify(e, fa, h, h_q8, t, cache, il);
9623        }
9624        let cfg = &self.cfg;
9625        let geometry = cfg.full_attention_geometry_at(il as u32);
9626        let n_head = geometry.n_head as usize;
9627        let n_head_kv = geometry.n_head_kv as usize;
9628        let head_dim = geometry.head_dim_k as usize;
9629        let eps = cfg.rms_eps;
9630        let scale = geometry.attention_scale();
9631        let n_embd = cfg.n_embd as usize;
9632
9633        // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
9634        // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
9635        // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
9636        // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
9637        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
9638        // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
9639        // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
9640        // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
9641        let (qf, mut k, v) = if let Some(mut qkv) = self.full_attn_tp_qkv(e, fa, h, t)? {
9642            let v = qkv.pop().ok_or("full-attention TP verify QKV omitted V")?;
9643            let k = qkv.pop().ok_or("full-attention TP verify QKV omitted K")?;
9644            let q = qkv.pop().ok_or("full-attention TP verify QKV omitted Q")?;
9645            if !qkv.is_empty() {
9646                return Err("full-attention TP verify QKV returned extra projections".into());
9647            }
9648            (q, k, v)
9649        } else {
9650            let mut fused = None;
9651            let qkv_fast =
9652                e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
9653            if t == 1 && qkv_fast {
9654                let (hq_o, hd_o);
9655                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
9656                    Some(p) => p,
9657                    None => {
9658                        (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
9659                        (&hq_o, &hd_o)
9660                    }
9661                };
9662                fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
9663            } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
9664                // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
9665                // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
9666                // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
9667                let (hq_o, hd_o);
9668                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
9669                    Some(p) => p,
9670                    None => {
9671                        (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
9672                        (&hq_o, &hd_o)
9673                    }
9674                };
9675                fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
9676            }
9677            match (fused, h_q8) {
9678                (Some(triple), _) => triple,
9679                // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
9680                // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
9681                (None, Some((hq, hd))) if qkv_fast => (
9682                    e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
9683                    e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
9684                    e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
9685                ),
9686                (None, _) => (
9687                    e.matmul_decode_exact(&fa.wq, h, t)?,
9688                    e.matmul_decode_exact(&fa.wk, h, t)?,
9689                    e.matmul_decode_exact(&fa.wv, h, t)?,
9690                ),
9691            }
9692        };
9693        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
9694        let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
9695        let (mut q, gate) = if gated {
9696            let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
9697            let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
9698            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
9699            (q, Some(gate))
9700        } else {
9701            (qf, None)
9702        };
9703
9704        let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
9705        e.rms_norm(
9706            &q,
9707            fa.q_norm.float_data(),
9708            &mut qn,
9709            head_dim,
9710            n_head * t,
9711            eps,
9712        )?;
9713        q = qn;
9714        let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
9715        e.rms_norm(
9716            &k,
9717            fa.k_norm.float_data(),
9718            &mut kn,
9719            head_dim,
9720            n_head_kv * t,
9721            eps,
9722        )?;
9723        k = kn;
9724        let rope_dims = geometry.n_rot as usize;
9725        e.rope_neox(
9726            &mut q,
9727            pos_d,
9728            head_dim,
9729            rope_dims,
9730            n_head,
9731            t,
9732            geometry.rope_base,
9733            1.0,
9734        )?;
9735        e.rope_neox(
9736            &mut k,
9737            pos_d,
9738            head_dim,
9739            rope_dims,
9740            n_head_kv,
9741            t,
9742            geometry.rope_base,
9743            1.0,
9744        )?;
9745
9746        // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
9747        // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
9748        let kvl = cache.kv[il].as_mut().unwrap();
9749        let (kv_dim_k, kv_dim_v, ktb, vtb) =
9750            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
9751        if let Some(ctr) = stream_ctr {
9752            // stream: ONE batched append at the device counter (rows kernel = the per-view warp
9753            // math on a (block, token) grid, documented byte-identical); host len is a stale
9754            // LOWER BOUND under pre-issue (drain reconciles it).
9755            e.append_kv_quantized_rows_dc(
9756                &k,
9757                &v,
9758                &mut kvl.k,
9759                &mut kvl.v,
9760                ctr,
9761                t,
9762                kv_dim_k,
9763                kv_dim_v,
9764                ktb,
9765                vtb,
9766                crate::Engine::kv_fp8_on(),
9767            )?;
9768        } else {
9769            for i in 0..t {
9770                let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
9771                let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
9772                e.append_kv_quantized_view(
9773                    &k_row,
9774                    &v_row,
9775                    &mut kvl.k,
9776                    &mut kvl.v,
9777                    kvl.len + i,
9778                    kv_dim_k,
9779                    kv_dim_v,
9780                    ktb,
9781                    vtb,
9782                    crate::Engine::kv_fp8_on(),
9783                )?;
9784            }
9785            kvl.len += t;
9786        }
9787
9788        // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
9789        // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
9790        // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
9791        // which changes FP summation order and can flip argmax at tight logit margins. Query row r
9792        // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
9793        // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
9794        // keys. The verify appends all T tokens first but bounds the key range per row.
9795        //
9796        // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
9797        // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
9798        // per-row program for all T rows (grid.z = row, per-row n_splits from the same
9799        // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
9800        // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
9801        // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
9802        // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
9803        // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
9804        let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
9805        let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
9806        // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
9807        // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
9808        // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
9809        // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
9810        // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
9811        // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
9812        // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
9813        // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
9814        if let Some(ctr) = stream_ctr {
9815            // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
9816            // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
9817            // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
9818            let upper = kvl.len + t + 64;
9819            let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
9820            let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
9821            e.fa_decode_rows_dc(
9822                &q,
9823                &k_view,
9824                &v_view,
9825                &mut attn,
9826                head_dim,
9827                n_head,
9828                n_head_kv,
9829                ctr,
9830                upper.min(cache.max_ctx),
9831                t,
9832                scale,
9833                ktb,
9834                vtb,
9835                0,
9836                false,
9837            )?;
9838        } else if spec_lean() && t == 1 {
9839            let t_kv = base_len + 1;
9840            let k_view = e.view_u8(&kvl.k, t_kv * ktb);
9841            let v_view = e.view_u8(&kvl.v, t_kv * vtb);
9842            e.fa_decode_kvmod(
9843                &q,
9844                &k_view,
9845                &v_view,
9846                &mut attn,
9847                head_dim,
9848                n_head,
9849                n_head_kv,
9850                t_kv,
9851                scale,
9852                ktb,
9853                vtb,
9854                crate::Engine::kv_fp8_on(),
9855            )?;
9856        } else if e.fa_rows_eligible(base_len, head_dim) {
9857            let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
9858            let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
9859            e.fa_decode_rows(
9860                &q,
9861                &k_view,
9862                &v_view,
9863                &mut attn,
9864                head_dim,
9865                n_head,
9866                n_head_kv,
9867                base_len,
9868                t,
9869                scale,
9870                ktb,
9871                vtb,
9872                None,
9873                false,
9874                crate::Engine::kv_fp8_on(),
9875                None,
9876            )?;
9877        } else {
9878            for r in 0..t {
9879                let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
9880                let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
9881                let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
9882                // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
9883                let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
9884                let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
9885                e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
9886                let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
9887                e.fa_decode_kvmod(
9888                    &q_row,
9889                    &k_view_r,
9890                    &v_view_r,
9891                    &mut attn_row,
9892                    head_dim,
9893                    n_head,
9894                    n_head_kv,
9895                    t_kv_r,
9896                    scale,
9897                    ktb,
9898                    vtb,
9899                    crate::Engine::kv_fp8_on(),
9900                )?;
9901                e.copy_into(
9902                    &mut attn,
9903                    r * n_head * head_dim,
9904                    &attn_row,
9905                    n_head * head_dim,
9906                )?;
9907            }
9908        }
9909
9910        let attn_g = match &gate {
9911            Some(gate) => {
9912                let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
9913                e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
9914                let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
9915                e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
9916                ag
9917            }
9918            None => attn,
9919        };
9920        // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
9921        // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
9922        match self.full_attn_tp_o(e, fa, &attn_g, t)? {
9923            Some(output) => Ok(output),
9924            None => Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?),
9925        }
9926    }
9927
9928    /// Context-linear bytes for a plain serving session's trunk cache.
9929    pub fn plain_session_kv_bytes_per_token(&self) -> usize {
9930        crate::cache::cache_bytes_per_token_for_plan(
9931            &self.cfg,
9932            &self.plan,
9933            0,
9934            self.plan.layers.len(),
9935        )
9936    }
9937
9938    /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
9939    pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
9940        (
9941            self.plain_session_kv_bytes_per_token(),
9942            crate::cache::cache_ring_bytes_per_token_for_plan(
9943                &self.cfg,
9944                &self.plan,
9945                0,
9946                self.plan.layers.len(),
9947            ),
9948            crate::cache::cache_ring_row_cap_for_plan(&self.plan),
9949        )
9950    }
9951
9952    /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
9953    /// scratch. With no MTP head this equals the plain coefficient.
9954    pub fn spec_session_kv_bytes_per_token(&self) -> usize {
9955        let scratch = self
9956            .mtp
9957            .iter()
9958            .chain(self.mtp_extra.iter())
9959            .map(|mtp| {
9960                let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
9961                k + v
9962            })
9963            .sum::<usize>();
9964        self.plain_session_kv_bytes_per_token()
9965            .saturating_add(scratch)
9966    }
9967
9968    /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
9969    /// capped by the same SWA ring rows as the trunk.
9970    pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
9971        let total = self.spec_session_kv_bytes_per_token();
9972        let (_, mut ring, rows) = self.plain_session_kv_shape();
9973        if rows > 0 {
9974            ring = ring.saturating_add(
9975                self.mtp
9976                    .iter()
9977                    .chain(self.mtp_extra.iter())
9978                    .map(|mtp| {
9979                        let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
9980                        k + v
9981                    })
9982                    .sum::<usize>(),
9983            );
9984        }
9985        (total, ring, rows)
9986    }
9987
9988    /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
9989    /// the NextN head to draft K tokens then verifies them in one batched target forward.
9990    /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
9991    /// acceptance rate. `k` = draft length per round.
9992    ///
9993    /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
9994    /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
9995    /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
9996    /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
9997    /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
9998    /// captured graph references is event-free; the spec loop is strictly single-stream.
9999    /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
10000    /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
10001    /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
10002    /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
10003    /// generate_spec_inner2.
10004    /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
10005    /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
10006    /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
10007    /// hybrid linear-attn states are in-place (no position index), so a session can extend but
10008    /// never rewind — `committed` is the exact token list whose state the caches hold (includes
10009    /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
10010    pub fn new_session(
10011        &self,
10012        e: &Engine,
10013        max_ctx: usize,
10014    ) -> Result<SpecSession, Box<dyn std::error::Error>> {
10015        Ok(SpecSession {
10016            // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
10017            // is the SERVING spec-session path, and with the ppN door open across two cards a
10018            // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
10019            // round — the wrong-card class already fixed on the two batched serving paths
10020            // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
10021            // branch, same allocations), so single-device behavior is byte-unchanged.
10022            cache: crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?,
10023            scratch: self.new_mtp_scratch(e, max_ctx)?,
10024            committed: Vec::new(),
10025            last_h: None,
10026            next_pred: None,
10027            sctr: 0,
10028            uctr: 0,
10029            draft_ctx: None,
10030            pending_tok: None,
10031            turn_ckpt: None,
10032            telem: SpecTelemetryCounters::default(),
10033            capture_at: None,
10034            boundary_captures: Vec::new(),
10035            ckpt_at: None,
10036            capture_disabled: false,
10037        })
10038    }
10039
10040    /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
10041    /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
10042    /// SpecSession around a trunk cache the worker already restored from a prefix-cache
10043    /// entry, re-installing the entry's published draft plane as the MTP scratch rows
10044    /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
10045    /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
10046    /// worker always receives a fully-warm continuation session (committed = whole
10047    /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
10048    /// boundary logits on the empty-suffix shape).
10049    ///
10050    /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
10051    /// gate): the identity target for a converted hit is the PLAIN hit serving the same
10052    /// request, and plain feeds a carried suffix via eager `decode_step` below
10053    /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
10054    /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
10055    /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
10056    /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
10057    /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
10058    /// burst prime.
10059    ///
10060    /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
10061    /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
10062    /// EXACTLY the rule the cold burst entry applies to its own first token from the same
10063    /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
10064    /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
10065    /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
10066    /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
10067    /// cold session draws from the identical row at counter 0 and then runs its rounds from
10068    /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
10069    /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
10070    /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
10071    /// span the session: `committed` here is the WHOLE prompt, so the restored session's
10072    /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
10073    ///
10074    /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
10075    /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
10076    /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
10077    /// and are never routed here.
10078    ///
10079    /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
10080    /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
10081    /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
10082    /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
10083    /// entry stays published for the next request.
10084    #[allow(clippy::too_many_arguments)]
10085    #[allow(clippy::result_large_err)] // allow: the fat error type is the diagnostic contract here; boxing it would change the error surface
10086    pub fn spec_session_from_restored(
10087        &self,
10088        e: &Engine,
10089        mut cache: Cache,
10090        prefix: Vec<u32>,
10091        suffix: &[u32],
10092        draft_k: &CudaSlice<u8>,
10093        draft_v: &CudaSlice<u8>,
10094        draft_k_tok_bytes: usize,
10095        draft_v_tok_bytes: usize,
10096        draft_len: usize,
10097        last_h: &[f32],
10098        // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
10099        // when a suffix follows — the feed's own logits are the boundary then.
10100        boundary_logits: &[f32],
10101        // The request's sampler, or None for greedy. Owned here so the seed rule lives in
10102        // ONE place instead of being half-applied by the worker.
10103        sampling: Option<SpecSampling>,
10104        require_anchor: bool,
10105        max_ctx: usize,
10106        // STABLE-BOUNDARY REPUBLICATION (lane/frspec-multiturn-cache, 2026-08-21): ABSOLUTE
10107        // prompt position to split the suffix feed at and capture the extended-entry
10108        // publication + this session's `turn_ckpt` — the worker's stable pre-generation
10109        // boundary (`plain_checkpoint_boundary`). None = legacy prompt-end republication.
10110        // WHY: the prompt-end capture below includes the template's live generation header
10111        // (`<|im_start|>assistant\n<think>\n`), which the next turn's re-render replaces, so
10112        // for a hybrid (whole-entry restores only) every extended entry's last ~2 tokens
10113        // diverged from every future prompt and the hit boundary FROZE at the first
10114        // lcp-split entry forever (measured: cached 6811 of 38228 by turn 8, B4).
10115        republish_at: Option<usize>,
10116    ) -> Result<SpecSession, (Option<Cache>, String)> {
10117        let pos = prefix.len();
10118        let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
10119            Err((Some(cache), msg))
10120        };
10121        if let Err(error) = cache.ensure_usable("spec_session_from_restored") {
10122            drop(cache);
10123            return Err((None, error.to_string()));
10124        }
10125        if self.mtp.is_none() {
10126            return fail(cache, "no MTP head attached (nothing to draft with)".into());
10127        }
10128        if pos == 0 {
10129            return fail(cache, "empty committed prefix".into());
10130        }
10131        if cache.pos != pos {
10132            let msg = format!(
10133                "restored cache pos {} != restored prefix len {pos}",
10134                cache.pos
10135            );
10136            return fail(cache, msg);
10137        }
10138        if draft_len != pos {
10139            return fail(
10140                cache,
10141                format!("draft plane len {draft_len} != restored prefix len {pos}"),
10142            );
10143        }
10144        if pos + suffix.len() >= max_ctx {
10145            return fail(
10146                cache,
10147                format!(
10148                    "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
10149                    pos + suffix.len(),
10150                ),
10151            );
10152        }
10153        let mut scratch = match MtpScratch::new(
10154            e,
10155            &self.cfg,
10156            &self.plan,
10157            max_ctx,
10158            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
10159        ) {
10160            Ok(s) => s,
10161            Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
10162        };
10163        if scratch.kv.ring.is_some() {
10164            return fail(
10165                cache,
10166                "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
10167            );
10168        }
10169        if scratch.kv.k_tok_bytes != draft_k_tok_bytes
10170            || scratch.kv.v_tok_bytes != draft_v_tok_bytes
10171        {
10172            return fail(
10173                cache,
10174                format!(
10175                    "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
10176                     {}/{} bytes/token (stale entry across a format change)",
10177                    scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
10178                ),
10179            );
10180        }
10181        if pos > scratch.cap {
10182            return fail(
10183                cache,
10184                format!(
10185                    "draft plane rows {pos} exceed scratch capacity {}",
10186                    scratch.cap
10187                ),
10188            );
10189        }
10190        let kb = pos * draft_k_tok_bytes;
10191        let vb = pos * draft_v_tok_bytes;
10192        if draft_k.len() < kb || draft_v.len() < vb {
10193            return fail(
10194                cache,
10195                format!(
10196                    "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
10197                    draft_k.len(),
10198                    draft_v.len(),
10199                ),
10200            );
10201        }
10202        if kb > 0
10203            && let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb)
10204        {
10205            return fail(cache, format!("draft K restore copy failed: {err}"));
10206        }
10207        if vb > 0
10208            && let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb)
10209        {
10210            return fail(cache, format!("draft V restore copy failed: {err}"));
10211        }
10212        if let Err(err) = scratch.set_len(e, pos) {
10213            return fail(cache, format!("draft scratch len set failed: {err}"));
10214        }
10215        let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
10216            // anchor upload failure is acceptance-only when a suffix feed follows (fill
10217            // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
10218            // burst entry asserts committed + last_h + next_pred) — the caller says which.
10219            e.htod(last_h).ok()
10220        } else {
10221            None
10222        };
10223        if require_anchor && last_h_dev.is_none() {
10224            return fail(
10225                cache,
10226                "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
10227            );
10228        }
10229        let mut committed = prefix;
10230        // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
10231        // what the empty-suffix continuation assert in the burst entry requires.
10232        let next_pred;
10233        // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
10234        // consumes counter 0 and leaves 1, which is the state a cold session reaches after
10235        // drawing its own first token from the same row.
10236        let mut sctr = 0u32;
10237        let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
10238        // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
10239        // prompt, which is what the cold session's own burst sees (Item 2's window). Built
10240        // after the suffix joins `committed` below.
10241        let mut boundary_captures: Vec<SpecBoundaryCapture> = Vec::new();
10242        let mut restored_turn_ckpt: Option<SpecCheckpoint> = None;
10243        if !suffix.is_empty() {
10244            // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
10245            // From here on the trunk cache mutates: failures return Err((None, _)) and
10246            // the worker serves the request cold-plain instead of reusing the carrier.
10247            let dirty =
10248                |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
10249            let n_embd = self.cfg.n_embd as usize;
10250            let t = suffix.len();
10251            let mut h_rows = match e.uninit(t * n_embd) {
10252                Ok(b) => b,
10253                Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
10254            };
10255            // STABLE-BOUNDARY split (see `republish_at`): feed stops at the boundary so the
10256            // in-place GDN conv/ssm state can be snapshotted there — the only moment it
10257            // exists (the cold prime-split law). suffix-relative; None = one-segment legacy.
10258            let b_rel = republish_at
10259                .and_then(|abs| abs.checked_sub(pos))
10260                .filter(|&r| r > 0 && r < t);
10261            let mut feed_logits = Vec::new();
10262            let tokenwise_env = std::env::var("MEMRA_PRIME_TOKENWISE").is_ok()
10263                || e.frozen_cpu_experts_prefer_tokenwise_prime();
10264            let mut fed = 0usize;
10265            for seg_end in [b_rel, Some(t)].into_iter().flatten() {
10266                if seg_end <= fed {
10267                    continue;
10268                }
10269                let seg = &suffix[fed..seg_end];
10270                let batched = seg.len() >= crate::hybrid_forward::PRIME_MIN_T && !tokenwise_env;
10271                if batched {
10272                    // prefill_tick's prime arm: request-level prime_cache call; tokens still
10273                    // queued after this segment ride `queued_after` so Step35 arm selection
10274                    // stays keyed to the request's end (tick-seg law).
10275                    match self.prime_cache(e, seg, &mut cache, t - seg_end) {
10276                        Ok((l, _h_seed, hiddens)) => {
10277                            if let Err(err) =
10278                                e.copy_into(&mut h_rows, fed * n_embd, &hiddens, seg.len() * n_embd)
10279                            {
10280                                return dirty(format!("suffix hidden copy: {err}"));
10281                            }
10282                            feed_logits = l;
10283                        }
10284                        Err(err) => return dirty(format!("suffix prime failed: {err}")),
10285                    }
10286                } else {
10287                    // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
10288                    for (i, &tok) in seg.iter().enumerate() {
10289                        match self.decode_step_h(e, tok, &mut cache) {
10290                            Ok((l, h)) => {
10291                                if let Err(err) =
10292                                    e.copy_into(&mut h_rows, (fed + i) * n_embd, &h, n_embd)
10293                                {
10294                                    return dirty(format!("suffix hidden copy: {err}"));
10295                                }
10296                                feed_logits = l;
10297                            }
10298                            Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
10299                        }
10300                    }
10301                }
10302                fed = seg_end;
10303                if Some(seg_end) == b_rel {
10304                    // The stable pre-generation boundary: capture the extended-entry
10305                    // publication AND this session's own turn checkpoint here instead of at
10306                    // prompt-end (both would otherwise carry the volatile live-header tail
10307                    // the next re-render replaces). Failure silent, turn_ckpt convention.
10308                    debug_assert_eq!(
10309                        cache.pos,
10310                        pos + seg_end,
10311                        "stable-boundary capture off the feed split"
10312                    );
10313                    if spec_restore_republish_on()
10314                        && let Ok(snap) = cache.snapshot(e)
10315                    {
10316                        boundary_captures.push(SpecBoundaryCapture {
10317                            snap,
10318                            pos: pos + seg_end,
10319                            logits: feed_logits.clone(),
10320                            last_h: capture_boundary_hidden(e, &h_rows, seg_end, n_embd),
10321                        });
10322                    }
10323                    let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
10324                        e.uninit(n_embd).and_then(|mut a| {
10325                            e.copy_view_into(
10326                                &mut a,
10327                                0,
10328                                &h_rows.slice((seg_end - 1) * n_embd..seg_end * n_embd),
10329                                n_embd,
10330                            )?;
10331                            Ok(a)
10332                        });
10333                    if let (Ok(snap), Ok(last_h)) = (cache.snapshot(e), anchor) {
10334                        restored_turn_ckpt = Some(SpecCheckpoint {
10335                            snap,
10336                            pos: pos + seg_end,
10337                            last_h,
10338                        });
10339                    }
10340                }
10341            }
10342            // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
10343            // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
10344            // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
10345            // with T). Fill failures are acceptance-only — truncate to the restored rows
10346            // and continue; the burst's own set_len keeps the invariant.
10347            let _mtp = self.mtp.as_ref().expect("mtp checked above"); // invariant check only; the fill below re-reads self.mtp
10348            let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10349            let embd_gpu = if spec_host_embd() {
10350                None
10351            } else {
10352                Some(
10353                    self.embd_gpu
10354                        .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10355                )
10356            };
10357            let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10358            let fill_chunk = 4096usize;
10359            let mut filled = true;
10360            let mut start = 0usize;
10361            'fill: while start < t {
10362                let end = (start + fill_chunk).min(t);
10363                let tc = end - start;
10364                let Ok(mut phs) = e.zeros(tc * n_embd) else {
10365                    filled = false;
10366                    break 'fill;
10367                };
10368                let (src_lo, dst_off, n_copy) = if start == 0 {
10369                    (0, n_embd, (tc - 1) * n_embd)
10370                } else {
10371                    ((start - 1) * n_embd, 0, tc * n_embd)
10372                };
10373                if start == 0
10374                    && let Some(lh) = last_h_dev.as_ref()
10375                    && e.copy_into(&mut phs, 0, lh, n_embd).is_err()
10376                {
10377                    filled = false;
10378                    break 'fill;
10379                }
10380                if n_copy > 0
10381                    && e.copy_view_into(
10382                        &mut phs,
10383                        dst_off,
10384                        &h_rows.slice(src_lo..src_lo + n_copy),
10385                        n_copy,
10386                    )
10387                    .is_err()
10388                {
10389                    filled = false;
10390                    break 'fill;
10391                }
10392                if self
10393                    .mtp_kv_fill_all(
10394                        e,
10395                        &suffix[start..end],
10396                        &phs,
10397                        pos + start,
10398                        &mut scratch,
10399                        embd_dev,
10400                    )
10401                    .is_err()
10402                {
10403                    filled = false;
10404                    break 'fill;
10405                }
10406                start = end;
10407            }
10408            if !filled {
10409                // acceptance-only: drafts over missing suffix rows are cheap and wrong,
10410                // so keep only the restored rows resident and let verify arbitrate.
10411                if let Err(err) = scratch.set_len(e, pos) {
10412                    return dirty(format!("scratch truncation after failed fill: {err}"));
10413                }
10414            }
10415            // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
10416            // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
10417            // finding (d)). Pre-lane, publication was armed only for COLD sessions
10418            // (`spec_resumed == 0` in the worker) and both engine capture sites require a
10419            // non-continuation burst — but a converted hit's first burst IS a continuation,
10420            // so a growing conversation learned exactly ONE boundary and turn 3 could never
10421            // hit a longer prefix than turn 2 did.
10422            //
10423            // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
10424            // line — the trunk is primed over the whole prompt, nothing is generated, and the
10425            // draft plane rows [0..prompt) are filled just above. That is a complete
10426            // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
10427            // publishes; the worker's existing publication sweep picks it up because it is
10428            // keyed on non-empty `boundary_captures` and is sampler- and resume-independent.
10429            // NOT the partial-restore hazard: the boundary is this session's own prompt END,
10430            // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
10431            // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
10432            // publication is an optimization, never a correctness dependency.
10433            //
10434            // SUPERSEDED WHEN `republish_at` FIRED (lane/frspec-multiturn-cache): a prompt-end
10435            // entry's tail is the live generation header the next re-render replaces, so on a
10436            // hybrid (whole-entry restores) it can never serve the conversation's next turn —
10437            // the stable-boundary capture above IS this publication, minus the poisoned tail.
10438            if spec_restore_republish_on() && boundary_captures.is_empty() {
10439                debug_assert_eq!(
10440                    cache.pos,
10441                    pos + t,
10442                    "extended-entry capture must sit at the restored session's prompt end",
10443                );
10444                if let Ok(snap) = cache.snapshot(e) {
10445                    boundary_captures.push(SpecBoundaryCapture {
10446                        snap,
10447                        pos: pos + t,
10448                        logits: feed_logits.clone(),
10449                        last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
10450                    });
10451                }
10452            }
10453            // continuation seed: the feed's boundary logits ARE the plain path's boundary
10454            // logits (same program), so greedy's argmax here is plain's first emitted token,
10455            // and the sampled draw is the cold sampled session's own first token.
10456            next_pred = Some(if sampled {
10457                let sp = sampling.expect("sampled implies a sampler");
10458                // `committed` is still the restored prefix here; the suffix joins it below —
10459                // so this is the last-N window over the WHOLE prompt, exactly the cold
10460                // session's own window at its first token.
10461                let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
10462                match sample_boundary_token(
10463                    e,
10464                    &feed_logits,
10465                    &sp,
10466                    &hist,
10467                    &mut sctr,
10468                    "restore-suffix-feed",
10469                ) {
10470                    Ok(t) => t,
10471                    // the trunk is already fed: hand nothing back, the worker serves the
10472                    // request cold-plain. Never fall back to an argmax — that would put a
10473                    // greedy token in a sampled stream to save a slow path.
10474                    Err(err) => {
10475                        return dirty(format!("boundary token draw failed: {err}"));
10476                    }
10477                }
10478            } else {
10479                argmax(&feed_logits) as u32
10480            });
10481            let mut lh = match e.uninit(n_embd) {
10482                Ok(b) => b,
10483                Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
10484            };
10485            if let Err(err) = e.copy_view_into(
10486                &mut lh,
10487                0,
10488                &h_rows.slice((t - 1) * n_embd..t * n_embd),
10489                n_embd,
10490            ) {
10491                return dirty(format!("boundary hidden copy: {err}"));
10492            }
10493            last_h_dev = Some(lh);
10494            committed.extend_from_slice(suffix);
10495        } else {
10496            // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
10497            // ENTRY's boundary logits are the boundary row, and this is the token the cold
10498            // session emits from that same row. Owned here rather than in the worker so the
10499            // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
10500            if boundary_logits.is_empty() {
10501                return fail(
10502                    cache,
10503                    "full-cover restore without the entry's boundary logits".into(),
10504                );
10505            }
10506            next_pred = Some(if sampled {
10507                let sp = sampling.expect("sampled implies a sampler");
10508                let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
10509                match sample_boundary_token(
10510                    e,
10511                    boundary_logits,
10512                    &sp,
10513                    &hist,
10514                    &mut sctr,
10515                    "restore-full-cover",
10516                ) {
10517                    Ok(t) => t,
10518                    // nothing has been mutated on this shape — hand the carrier back and let
10519                    // the hit serve PLAIN (the banked pre-lane path).
10520                    Err(err) => {
10521                        return fail(cache, format!("boundary token draw failed: {err}"));
10522                    }
10523                }
10524            } else {
10525                argmax(boundary_logits) as u32
10526            });
10527        }
10528        Ok(SpecSession {
10529            cache,
10530            scratch,
10531            committed,
10532            last_h: last_h_dev,
10533            next_pred,
10534            sctr,
10535            uctr: 0,
10536            draft_ctx: None,
10537            pending_tok: None,
10538            // Stable-boundary capture from the split feed above (None on the legacy shape):
10539            // a restored session previously parked WITHOUT a checkpoint, so the next turn's
10540            // affinity probe declined ("no turn checkpoint retained") and the conversation
10541            // fell back to the frozen prefix entry forever.
10542            turn_ckpt: restored_turn_ckpt,
10543            telem: SpecTelemetryCounters::default(),
10544            capture_at: None,
10545            boundary_captures,
10546            ckpt_at: None,
10547            capture_disabled: false,
10548        })
10549    }
10550
10551    /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
10552    /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
10553    /// snapshot, or draft-KV row that only corrupts the following round.
10554    pub fn optipipe_compare_session_state(
10555        &self,
10556        e: &Engine,
10557        reference: &SpecSession,
10558        candidate: &SpecSession,
10559    ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
10560        fn fail(what: &str) -> Box<dyn std::error::Error> {
10561            format!("optipipe state mismatch: {what}").into()
10562        }
10563        fn same_f32(a: &[f32], b: &[f32]) -> bool {
10564            a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
10565        }
10566        fn compare_layers(
10567            es: &Engine,
10568            range: std::ops::Range<usize>,
10569            reference: &SpecSession,
10570            candidate: &SpecSession,
10571            report: &mut OptiForkStateIdentity,
10572        ) -> Result<(), Box<dyn std::error::Error>> {
10573            for il in range {
10574                match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
10575                    (Some(a), Some(b)) => {
10576                        if a.len != b.len {
10577                            return Err(fail(&format!(
10578                                "layer {il} host KV len {} != {}",
10579                                a.len, b.len
10580                            )));
10581                        }
10582                        let ad = es.dtoh_i32(&a.len_d)?;
10583                        let bd = es.dtoh_i32(&b.len_d)?;
10584                        if ad != bd || ad.first().copied() != Some(a.len as i32) {
10585                            return Err(fail(&format!(
10586                                "layer {il} device KV len {ad:?} != {bd:?} (host={})",
10587                                a.len,
10588                            )));
10589                        }
10590                        let kb = a.len * a.k_tok_bytes;
10591                        let vb = a.len * a.v_tok_bytes;
10592                        if kb > 0 {
10593                            let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
10594                            let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
10595                            if ak != bk {
10596                                let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
10597                                return Err(fail(&format!(
10598                                    "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
10599                                    at / a.k_tok_bytes,
10600                                    at % a.k_tok_bytes,
10601                                    ak[at],
10602                                    bk[at],
10603                                )));
10604                            }
10605                        }
10606                        if vb > 0 {
10607                            let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
10608                            let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
10609                            if av != bv {
10610                                let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
10611                                return Err(fail(&format!(
10612                                    "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
10613                                    at / a.v_tok_bytes,
10614                                    at % a.v_tok_bytes,
10615                                    av[at],
10616                                    bv[at],
10617                                )));
10618                            }
10619                        }
10620                        report.trunk_kv_bytes += kb + vb;
10621                    }
10622                    (None, None) => {}
10623                    _ => return Err(fail(&format!("layer {il} KV presence"))),
10624                }
10625                match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
10626                    (Some(a), Some(b)) => {
10627                        let ac = es.dtoh(&a.conv_state)?;
10628                        let bc = es.dtoh(&b.conv_state)?;
10629                        if !same_f32(&ac, &bc) {
10630                            return Err(fail(&format!("layer {il} conv state")));
10631                        }
10632                        let as_ = es.dtoh(&a.ssm_state)?;
10633                        let bs = es.dtoh(&b.ssm_state)?;
10634                        if !same_f32(&as_, &bs) {
10635                            return Err(fail(&format!("layer {il} SSM state")));
10636                        }
10637                        report.recurrent_bytes += (ac.len() + as_.len()) * 4;
10638                    }
10639                    (None, None) => {}
10640                    _ => return Err(fail(&format!("layer {il} recurrent presence"))),
10641                }
10642            }
10643            Ok(())
10644        }
10645
10646        if reference.committed != candidate.committed {
10647            return Err(fail("committed token ids"));
10648        }
10649        if reference.cache.pos != candidate.cache.pos
10650            || reference.cache.max_ctx != candidate.cache.max_ctx
10651        {
10652            return Err(fail("cache pos/capacity"));
10653        }
10654        if reference.pending_tok != candidate.pending_tok
10655            || reference.next_pred != candidate.next_pred
10656            || reference.sctr != candidate.sctr
10657            || reference.uctr != candidate.uctr
10658        {
10659            return Err(fail("pending/prediction/counter tail"));
10660        }
10661
10662        let mut report = OptiForkStateIdentity::default();
10663        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
10664            let rt = crate::pp::PpNRt::get(e)?;
10665            for stage in 0..rt.n_stages() {
10666                let _scope = rt.enter(stage);
10667                compare_layers(
10668                    rt.engine(stage, e),
10669                    fence[stage]..fence[stage + 1],
10670                    reference,
10671                    candidate,
10672                    &mut report,
10673                )?;
10674            }
10675        } else {
10676            compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
10677        }
10678
10679        if reference.scratch.plane_count() != candidate.scratch.plane_count() {
10680            return Err(fail("draft scratch plane count"));
10681        }
10682        for index in 0..reference.scratch.plane_count() {
10683            let (a, _) = reference.scratch.plane(index);
10684            let (b, _) = candidate.scratch.plane(index);
10685            if a.len != b.len
10686                || a.kv_dim_k != b.kv_dim_k
10687                || a.kv_dim_v != b.kv_dim_v
10688                || a.k_tok_bytes != b.k_tok_bytes
10689                || a.v_tok_bytes != b.v_tok_bytes
10690                || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)?
10691            {
10692                return Err(fail(&format!("draft scratch plane {index} length/layout")));
10693            }
10694            let kb = a.len * a.k_tok_bytes;
10695            let vb = a.len * a.v_tok_bytes;
10696            if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
10697                return Err(fail(&format!("draft scratch plane {index} K bytes")));
10698            }
10699            if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
10700                return Err(fail(&format!("draft scratch plane {index} V bytes")));
10701            }
10702            report.scratch_kv_bytes += kb + vb;
10703        }
10704
10705        match (&reference.last_h, &candidate.last_h) {
10706            (Some(a), Some(b)) => {
10707                let ah = e.dtoh(a)?;
10708                let bh = e.dtoh(b)?;
10709                if !same_f32(&ah, &bh) {
10710                    return Err(fail("last hidden/seed bytes"));
10711                }
10712                report.hidden_bytes = ah.len() * 4;
10713            }
10714            (None, None) => {}
10715            _ => return Err(fail("last hidden/seed presence")),
10716        }
10717        Ok(report)
10718    }
10719
10720    /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
10721    /// retained prompt-end checkpoint, so a request whose prompt matches
10722    /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
10723    ///
10724    /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
10725    /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
10726    /// restored from the device copy taken there, draft scratch length reset, `committed`
10727    /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
10728    /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
10729    /// every burst after it are identical to a cold run of the same token stream — the
10730    /// committed-tokens-authoritative contract.
10731    ///
10732    /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
10733    /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
10734    /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
10735    /// continue). The persistent draft graph survives: it bakes only session-stable pointers
10736    /// (the scratch KV, the resident embedding), none of which the rewind moves.
10737    ///
10738    /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
10739    /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
10740    /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
10741    pub fn spec_rewind_to_checkpoint(
10742        &self,
10743        e: &Engine,
10744        sess: &mut SpecSession,
10745    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
10746        if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
10747            !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
10748        }) {
10749            return Err(
10750                "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
10751            );
10752        }
10753        let Some(ckpt) = sess.turn_ckpt.take() else {
10754            return Ok(None);
10755        };
10756        assert!(
10757            ckpt.pos <= sess.committed.len(),
10758            "checkpoint past committed ({} > {})",
10759            ckpt.pos,
10760            sess.committed.len()
10761        );
10762        // Restore through each layer's owning engine. A single primary-engine rollback is not
10763        // sufficient when the serving cache is stage-owned under cross-device PP.
10764        crate::pp::restore_cache_checkpoint(e, self, None, &mut sess.cache, &ckpt.snap)?;
10765        debug_assert_eq!(
10766            sess.cache.pos, ckpt.pos,
10767            "rollback landed off the checkpoint"
10768        );
10769        sess.scratch.set_len(e, ckpt.pos)?;
10770        sess.committed.truncate(ckpt.pos);
10771        sess.last_h = Some(ckpt.last_h);
10772        sess.next_pred = None;
10773        sess.pending_tok = None;
10774        Ok(Some(ckpt.pos))
10775    }
10776
10777    /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
10778    /// checkpoint without re-priming the checkpoint prefix.
10779    ///
10780    /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
10781    /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
10782    /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
10783    /// remain authoritative, so they are copied into a fresh larger scratch before its length is
10784    /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
10785    ///
10786    /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
10787    /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
10788    pub fn spec_grow_and_rewind_to_checkpoint(
10789        &self,
10790        e: &Engine,
10791        sess: &mut SpecSession,
10792        target_cap: usize,
10793    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
10794        if target_cap <= sess.cache.max_ctx {
10795            return self.spec_rewind_to_checkpoint(e, sess);
10796        }
10797        let Some(ckpt) = sess.turn_ckpt.as_ref() else {
10798            return Ok(None);
10799        };
10800        if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
10801            return Err(format!(
10802                "checkpoint pos {} outside committed length {}",
10803                ckpt.pos,
10804                sess.committed.len(),
10805            )
10806            .into());
10807        }
10808        if ckpt.pos > target_cap {
10809            return Err(format!(
10810                "checkpoint pos {} exceeds grown capacity {target_cap}",
10811                ckpt.pos,
10812            )
10813            .into());
10814        }
10815
10816        let mut grown_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, target_cap)?;
10817        let mut grown_scratch = self.new_mtp_scratch(e, target_cap)?;
10818        crate::pp::restore_cache_checkpoint(
10819            e,
10820            self,
10821            Some(&sess.cache),
10822            &mut grown_cache,
10823            &ckpt.snap,
10824        )?;
10825
10826        if sess.scratch.plane_count() != grown_scratch.plane_count() {
10827            return Err("checkpoint draft plane count mismatch".into());
10828        }
10829        for index in 0..sess.scratch.plane_count() {
10830            let (src, _) = sess.scratch.plane(index);
10831            let (dst, _) = grown_scratch.plane_mut(index);
10832            if ckpt.pos > src.len
10833                || src.kv_dim_k != dst.kv_dim_k
10834                || src.kv_dim_v != dst.kv_dim_v
10835                || src.k_tok_bytes != dst.k_tok_bytes
10836                || src.v_tok_bytes != dst.v_tok_bytes
10837            {
10838                return Err(format!(
10839                    "checkpoint draft plane {index} layout mismatch (pos {}, source len {})",
10840                    ckpt.pos, src.len,
10841                )
10842                .into());
10843            }
10844            match (&src.ring, dst.ring.as_ref()) {
10845                (Some(sring), Some(_)) => {
10846                    // Ring-backed draft plane (step35): `ckpt.pos` is absolute and exceeds the
10847                    // physical rows once lapped — same class as the trunk-KV restore panic
10848                    // (2026-08-29 warm-turn-at-40k). Copy the aligned live window, rebase.
10849                    let (new_base, phys) = sring.restore_plan(ckpt.pos).map_err(|err| {
10850                        format!("checkpoint draft plane {index} SWA restore refused: {err}")
10851                    })?;
10852                    let rows = phys.len();
10853                    let kb = rows * src.k_tok_bytes;
10854                    let vb = rows * src.v_tok_bytes;
10855                    if kb > 0 {
10856                        e.copy_u8_range_into(
10857                            &mut dst.k,
10858                            0,
10859                            &src.k,
10860                            phys.start * src.k_tok_bytes,
10861                            kb,
10862                        )?;
10863                    }
10864                    if vb > 0 {
10865                        e.copy_u8_range_into(
10866                            &mut dst.v,
10867                            0,
10868                            &src.v,
10869                            phys.start * src.v_tok_bytes,
10870                            vb,
10871                        )?;
10872                    }
10873                    dst.ring
10874                        .as_mut()
10875                        .expect("ring presence checked above")
10876                        .apply_rebase(new_base);
10877                    if let Some(base_d) = dst.base_d.as_mut() {
10878                        e.set_i32_one(base_d, new_base as i32)?;
10879                    }
10880                }
10881                (None, None) => {
10882                    let kb = ckpt.pos * src.k_tok_bytes;
10883                    let vb = ckpt.pos * src.v_tok_bytes;
10884                    if kb > 0 {
10885                        e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
10886                    }
10887                    if vb > 0 {
10888                        e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
10889                    }
10890                }
10891                _ => {
10892                    return Err(format!("checkpoint draft plane {index} ring/flat mismatch").into());
10893                }
10894            }
10895        }
10896        grown_scratch.set_len(e, ckpt.pos)?;
10897        // The old scratch is dropped immediately after publication below. Bound its D2D reads
10898        // first; growth happens once per rewritten turn, outside the decode hot loop.
10899        e.stream().synchronize()?;
10900
10901        let ckpt = sess
10902            .turn_ckpt
10903            .take()
10904            .expect("checkpoint remained present through transactional grow");
10905        let pos = ckpt.pos;
10906        sess.cache = grown_cache;
10907        sess.scratch = grown_scratch;
10908        sess.committed.truncate(pos);
10909        sess.last_h = Some(ckpt.last_h);
10910        sess.next_pred = None;
10911        sess.pending_tok = None;
10912        sess.draft_ctx = None;
10913        debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
10914        debug_assert!(
10915            (0..sess.scratch.plane_count()).all(|index| sess.scratch.plane(index).0.len == pos),
10916            "grown draft rewind landed off checkpoint"
10917        );
10918        Ok(Some(pos))
10919    }
10920
10921    /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
10922    /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
10923    /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
10924    /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
10925    /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
10926    /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
10927    /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
10928    /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
10929    /// park-time flush is a future request whose sampler is not knowable here (residual
10930    /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
10931    pub fn spec_flush_pending(
10932        &self,
10933        e: &Engine,
10934        sess: &mut SpecSession,
10935        sampling: Option<SpecSampling>,
10936    ) -> Result<(), Box<dyn std::error::Error>> {
10937        sess.cache.ensure_usable("spec_flush_pending")?;
10938        let Some(b) = sess.pending_tok.take() else {
10939            return Ok(());
10940        };
10941        if self.mtp.is_none() {
10942            return Err("pending carry requires an MTP head".into());
10943        }
10944        let n_embd = self.cfg.n_embd as usize;
10945        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10946        let embd_gpu = if spec_host_embd() {
10947            None
10948        } else {
10949            Some(
10950                self.embd_gpu
10951                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10952            )
10953        };
10954        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10955        let pos_b = sess.cache.pos;
10956        sess.scratch.set_len(e, pos_b)?;
10957        let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
10958        sess.next_pred = Some(match sampling {
10959            Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
10960                // window includes `b` itself: it is committed by this pass, and the pre-lane
10961                // code never counted a boundary token in the penalty history at all.
10962                let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
10963                sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
10964            }
10965            _ => argmax(&lg_b) as u32,
10966        });
10967        let anchor = sess
10968            .last_h
10969            .as_ref()
10970            .expect("pending carry requires last_h (the predecessor-row anchor)");
10971        self.mtp_kv_fill_all(e, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
10972        sess.last_h = Some(hb);
10973        sess.committed.push(b);
10974        Ok(())
10975    }
10976
10977    /// Solo target feed used only at speculative round boundaries. Step35 serving made its
10978    /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
10979    /// rounds through that same graph. Other model families keep their eager T=1 contract.
10980    fn spec_target_step_h(
10981        &self,
10982        e: &Engine,
10983        token: u32,
10984        cache: &mut Cache,
10985    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
10986        cache.ensure_usable("spec_target_step_h")?;
10987        if !self.sliding_gated_moe_batch_program() && !self.batched_serving_numeric_class() {
10988            return self.decode_step_h(e, token, cache);
10989        }
10990        let pos0 = cache.pos;
10991        let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
10992        Ok((e.dtoh(&logits)?, hidden))
10993    }
10994
10995    /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
10996    /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
10997    /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
10998    /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
10999    /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
11000    /// carries the drift until a near-tie flips deep in generation. One predicate so the five
11001    /// dispatch sites cannot drift apart again.
11002    /// Draft-graph head admissibility (lane/draftcost-moe, 2026-08-20): the capture body
11003    /// (`mtp_head_forward_cap`) supports Dense heads and SOFTMAX device-routed resident-MoE
11004    /// heads. Residency alone is insufficient: Hy3/M3/Step sigmoid routing returns selected
11005    /// experts through a host synchronization, which is capture-illegal. Those heads use the
11006    /// exact eager draft chain until a device-only sigmoid expert program lands. Trunk FFN class
11007    /// is irrelevant — the graph body is the HEAD forward only. One predicate for all three
11008    /// eligibility sites so they cannot drift (the serving numeric-class lesson).
11009    fn mtp_graph_capturable(&self) -> bool {
11010        let sigmoid_router = self.cfg.sigmoid_router().is_some();
11011        for head in self.mtp.iter().chain(self.mtp_extra.iter()) {
11012            let reason = match &head.ffn {
11013                crate::hybrid::Ffn::Dense { .. } => None,
11014                crate::hybrid::Ffn::Moe(mo) if mo.dev_exps.is_none() => {
11015                    Some("non-resident MoE MTP head")
11016                }
11017                crate::hybrid::Ffn::Moe(_) if sigmoid_router => {
11018                    Some("sigmoid-router MoE MTP head requires host-visible routing")
11019                }
11020                crate::hybrid::Ffn::Moe(_) => None,
11021            };
11022            if let Some(reason) = reason {
11023                static NOTICE: std::sync::Once = std::sync::Once::new();
11024                NOTICE.call_once(|| {
11025                    eprintln!(
11026                        "[spec] draft graph unavailable: {reason}; eager draft chain engaged"
11027                    );
11028                });
11029                return false;
11030            }
11031        }
11032        self.mtp.is_some()
11033    }
11034
11035    fn batched_serving_numeric_class(&self) -> bool {
11036        self.plan
11037            .trunk_operations()
11038            .contains(&memra_gguf::model_plan::OperationKind::GatedDeltaNet)
11039    }
11040
11041    /// The family the MTP verify-graph default was measured on: GatedDeltaNet state layers
11042    /// (a `recur` mixer) together with a routed-MoE FFN — Ornith-1.5-35B-A3B and its kin. The
11043    /// server-side twin of this test is `model_forces_spec_replay` (GatedDeltaNet + MoeMlp);
11044    /// keeping the engine's own version structural rather than name-based means a new
11045    /// checkpoint of the same shape inherits the default, and a different shape does not.
11046    /// pub(crate) since lane/graph-launch-guard-sweep-20260831: `dspark_vg_admission_debt`
11047    /// consults it so the MTP-route pool stops escaping the admission charge.
11048    pub(crate) fn vgraph_family_default(&self) -> bool {
11049        let has_linear = self
11050            .layers
11051            .iter()
11052            .any(|l| matches!(l.mixer, Mixer::Linear(_)));
11053        let has_moe = self
11054            .layers
11055            .iter()
11056            .any(|l| matches!(l.ffn, crate::hybrid::Ffn::Moe(_)));
11057        has_linear && has_moe
11058    }
11059
11060    fn sliding_gated_moe_batch_program(&self) -> bool {
11061        self.uses_sliding_gated_moe_program()
11062    }
11063
11064    fn gemma_batch_program(&self) -> bool {
11065        self.uses_gemma_program()
11066    }
11067
11068    /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
11069    /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
11070    /// session already exist.
11071    pub fn spec_pipe_available(&self, e: &Engine) -> bool {
11072        if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
11073            || !spec_devacc()
11074            || spec_replay_env_enabled()
11075            || spec_stream()
11076            || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
11077            || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
11078            || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
11079            || std::env::var("MEMRA_SPEC_PMIN")
11080                .ok()
11081                .and_then(|v| v.parse::<f32>().ok())
11082                .unwrap_or(0.0)
11083                > 0.0
11084            || self.is_gemma4_e4b()
11085            || self.gemma_batch_program()
11086            || self.mtp.is_none()
11087            || !self.mtp_extra.is_empty()
11088            // Both paired lanes would otherwise hold the model-global verify-graph mutex across
11089            // setup and wait for each other. Independent graph pools are future work; the pair
11090            // requires the explicit eager-verify arm today.
11091            || crate::spec::spec_verify_graph_env()
11092                .unwrap_or_else(|| self.vgraph_family_default())
11093        {
11094            return false;
11095        }
11096        let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
11097            return false;
11098        };
11099        if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
11100            return false;
11101        }
11102        crate::pp::PpNRt::get(e)
11103            .map(|rt| rt.n_stages() == 2 && rt.cross_device())
11104            .unwrap_or(false)
11105    }
11106
11107    /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
11108    /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
11109    /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
11110    #[allow(clippy::too_many_arguments)]
11111    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11112    pub fn generate_spec_session_pair(
11113        &self,
11114        e: &Engine,
11115        sess_a: &mut SpecSession,
11116        max_new_a: usize,
11117        k_a: usize,
11118        sess_b: &mut SpecSession,
11119        max_new_b: usize,
11120        k_b: usize,
11121    ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
11122    {
11123        self.refuse_hyper("generate_spec_session_pair")?;
11124        if !self.spec_pipe_available(e) {
11125            return Err("two-session speculative pipeline is outside its reduced matrix".into());
11126        }
11127        let rt = crate::pp::PpNRt::get(e)?;
11128        let pp_walk = rt.acquire_walk("generate_spec_session_pair")?;
11129        let pp_permit = rt.walk_permit(&pp_walk, "generate_spec_session_pair")?;
11130        if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
11131            return Err(
11132                "two-session speculative pipeline requires non-empty positive-K bursts".into(),
11133            );
11134        }
11135        for sess in [&*sess_a, &*sess_b] {
11136            if sess.committed.is_empty()
11137                || sess.last_h.is_none()
11138                || (sess.next_pred.is_none() && sess.pending_tok.is_none())
11139            {
11140                return Err("two-session speculative pipeline requires warm continuations".into());
11141            }
11142        }
11143
11144        let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
11145            && !spec_host_embd()
11146            && self.mtp_graph_capturable()
11147            && self.mtp_extra.is_empty()
11148            && !crate::model::full_prec_enabled();
11149        let graph_a = graph_ok && k_a + 2 < 96;
11150        let graph_b = graph_ok && k_b + 2 < 96;
11151        let was_tracking = e.ctx().is_event_tracking();
11152        if (graph_a || graph_b) && was_tracking {
11153            unsafe {
11154                e.ctx().disable_event_tracking();
11155            }
11156        }
11157
11158        static LOGGED: std::sync::Once = std::sync::Once::new();
11159        LOGGED.call_once(|| {
11160            eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
11161        });
11162        let sync = std::sync::Arc::new(SpecPipeSync::new());
11163        let lane_a = SpecPipeLane {
11164            sync: sync.clone(),
11165            lane: 0,
11166            rt,
11167            walk_permit: pp_permit.clone(),
11168        };
11169        let lane_b = SpecPipeLane {
11170            sync,
11171            lane: 1,
11172            rt,
11173            walk_permit: pp_permit,
11174        };
11175        let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
11176        let (result_a, result_b) = std::thread::scope(|scope| {
11177            let b = scope.spawn(move || {
11178                let mut finish = SpecPipeFinish::new(&lane_b);
11179                let sess_b = unsafe { sess_b_ptr.get_mut() };
11180                let result = (|| -> Result<_, String> {
11181                    e.ctx().bind_to_thread().map_err(|err| err.to_string())?;
11182                    self.generate_spec_inner2(
11183                        e,
11184                        &[],
11185                        max_new_b,
11186                        k_b,
11187                        graph_b,
11188                        Some(sess_b),
11189                        None,
11190                        None,
11191                        None,
11192                        None,
11193                        Some(&lane_b),
11194                    )
11195                    .map_err(|err| err.to_string())
11196                })();
11197                finish.close(result.is_err());
11198                result
11199            });
11200            let mut finish = SpecPipeFinish::new(&lane_a);
11201            let result_a = self.generate_spec_inner2(
11202                e,
11203                &[],
11204                max_new_a,
11205                k_a,
11206                graph_a,
11207                Some(sess_a),
11208                None,
11209                None,
11210                None,
11211                None,
11212                Some(&lane_a),
11213            );
11214            finish.close(result_a.is_err());
11215            let result_b = b
11216                .join()
11217                .map_err(|_| "paired speculative session B panicked".to_string())
11218                .and_then(|r| r);
11219            (result_a, result_b)
11220        });
11221
11222        if (graph_a || graph_b) && was_tracking {
11223            unsafe {
11224                e.ctx().enable_event_tracking();
11225            }
11226        }
11227        let result_a = result_a?;
11228        let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
11229        Ok((result_a, result_b))
11230    }
11231
11232    /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
11233    /// message rendered through the chat template continuation). Returns (new tokens emitted,
11234    /// drafted, accepted); session.committed grows by suffix + emitted.
11235    pub fn generate_spec_session(
11236        &self,
11237        e: &Engine,
11238        sess: &mut SpecSession,
11239        suffix: &[u32],
11240        max_new: usize,
11241        k: usize,
11242    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11243        self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
11244    }
11245
11246    /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
11247    /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
11248    /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
11249    /// for the filtered target (feat/filtered-spec).
11250    ///
11251    /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
11252    /// output — once right after the prime's first token, then once per round commit — so a
11253    /// streaming caller can flush text at round cadence instead of once per burst. The slices
11254    /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
11255    /// timing only: token bytes, session state, and exactness are untouched.
11256    ///
11257    /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
11258    /// the burst at the current round boundary, exactly as if `max_new` had been reached —
11259    /// the caller's scheduler regains control without waiting the burst out. Burst size is
11260    /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
11261    /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
11262    /// drains and the defensive tail flush can land with nothing new committed).
11263    #[allow(clippy::too_many_arguments)]
11264    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11265    pub fn generate_spec_session_sampled(
11266        &self,
11267        e: &Engine,
11268        sess: &mut SpecSession,
11269        suffix: &[u32],
11270        max_new: usize,
11271        k: usize,
11272        sampling: Option<SpecSampling>,
11273        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11274    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11275        self.generate_spec_session_sampled_prime_split(
11276            e, sess, suffix, max_new, k, sampling, None, on_commit,
11277        )
11278    }
11279
11280    /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
11281    /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
11282    /// pass `None` and stay on the existing zero-prime path.
11283    #[allow(clippy::too_many_arguments)]
11284    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11285    pub fn generate_spec_session_sampled_prime_split(
11286        &self,
11287        e: &Engine,
11288        sess: &mut SpecSession,
11289        suffix: &[u32],
11290        max_new: usize,
11291        k: usize,
11292        sampling: Option<SpecSampling>,
11293        prime_split: Option<usize>,
11294        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11295    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11296        self.generate_spec_session_constrained_prime_split(
11297            e,
11298            sess,
11299            suffix,
11300            max_new,
11301            k,
11302            sampling,
11303            None,
11304            prime_split,
11305            on_commit,
11306        )
11307    }
11308
11309    /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
11310    /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
11311    /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
11312    /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
11313    /// column — token-identical to constrained plain greedy decode. GREEDY only (the
11314    /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
11315    /// may drop (drafter is unconstrained); that is measured, not hidden.
11316    #[allow(clippy::too_many_arguments)]
11317    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11318    pub fn generate_spec_session_constrained(
11319        &self,
11320        e: &Engine,
11321        sess: &mut SpecSession,
11322        suffix: &[u32],
11323        max_new: usize,
11324        k: usize,
11325        sampling: Option<SpecSampling>,
11326        constraint: Option<&mut dyn SpecConstraint>,
11327        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11328    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11329        self.generate_spec_session_constrained_prime_split(
11330            e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
11331        )
11332    }
11333
11334    #[allow(clippy::too_many_arguments)]
11335    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11336    pub fn generate_spec_session_constrained_prime_split(
11337        &self,
11338        e: &Engine,
11339        sess: &mut SpecSession,
11340        suffix: &[u32],
11341        max_new: usize,
11342        k: usize,
11343        sampling: Option<SpecSampling>,
11344        constraint: Option<&mut dyn SpecConstraint>,
11345        prime_split: Option<usize>,
11346        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11347    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11348        if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
11349            return Err(
11350                "constrained spec decode is greedy-only (worker routes sampled \
11351                        constrained to plain decode)"
11352                    .into(),
11353            );
11354        }
11355        // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
11356        // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
11357        // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
11358        // serve continuation case — consume the carry in-loop with zero solo passes.
11359        if sess.pending_tok.is_some()
11360            && (!suffix.is_empty() || sampling.is_some_and(|s| s.temp > 0.0))
11361        {
11362            self.spec_flush_pending(e, sess, sampling)?;
11363        }
11364
11365        // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
11366        // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
11367        // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
11368        // Multi-head MTP (mtp_extra non-empty) no longer disqualifies: the chain captures
11369        // per-head graphs (lane/step37-draft-graph-serving-20260830, MEMRA_MTP_CHAIN_GRAPH).
11370        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
11371            && !spec_host_embd()
11372            && self.mtp_graph_capturable()
11373            && k + 2 < 96
11374            && !crate::model::full_prec_enabled();
11375        let was_tracking = e.ctx().is_event_tracking();
11376        if graph_draft && was_tracking {
11377            unsafe {
11378                e.ctx().disable_event_tracking();
11379            }
11380        }
11381        let r = self.generate_spec_inner2(
11382            e,
11383            suffix,
11384            max_new,
11385            k,
11386            graph_draft,
11387            Some(sess),
11388            sampling,
11389            constraint,
11390            on_commit,
11391            prime_split,
11392            None,
11393        );
11394        if graph_draft && was_tracking {
11395            unsafe {
11396                e.ctx().enable_event_tracking();
11397            }
11398        }
11399        let (out, d, a) = r?;
11400        Ok((out, d, a))
11401    }
11402
11403    pub fn generate_spec(
11404        &self,
11405        e: &Engine,
11406        prompt: &[u32],
11407        max_new: usize,
11408        k: usize,
11409    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11410        // glm5 T-parallel verify door (lane/glm5-tparallel-verify): an hc trunk with a
11411        // loaded DRAFT SOURCE — the embedded MTP head OR the DFlash2 drafter
11412        // (lane/glm5-dflash-draft-src) — routes to the glm5 draft->verify->rollback loop —
11413        // MEMRA_GLM5_SPEC=1 only (default OFF; flag row in FLAGS.md). Unset/0 falls
11414        // through to the standing named refusal below, byte-identical to the pre-lane
11415        // binary. Same fail-closed manifest stance as the generic path: an unqualified
11416        // MtpSpec rewrite refuses before any drafting.
11417        if self.hyper.is_some()
11418            && crate::glm_spec::glm5_spec_on()
11419            && (self.mtp.is_some() || self.glm5_dflash.is_some())
11420        {
11421            if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::MtpSpec) {
11422                return Err("speculative rewrite is not qualified for this ModelPlan".into());
11423            }
11424            return self.generate_spec_glm5(e, prompt, max_new, k);
11425        }
11426        self.refuse_hyper("generate_spec")?;
11427        if crate::pp::pp_cuts(self.layers.len()).is_some()
11428            && !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::Pipeline)
11429        {
11430            return Err("pipeline rewrite is not qualified for speculative decode".into());
11431        }
11432        if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::MtpSpec) {
11433            return Err("speculative rewrite is not qualified for this ModelPlan".into());
11434        }
11435        // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
11436        // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
11437        // Multi-head MTP no longer disqualifies (chain graphs; see generate_spec_session).
11438        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
11439            && !spec_host_embd()
11440            && self.mtp_graph_capturable()
11441            && k + 2 < 96
11442            && !crate::model::full_prec_enabled();
11443        if !graph_draft {
11444            return self.generate_spec_inner2(
11445                e, prompt, max_new, k, false, None, None, None, None, None, None,
11446            );
11447        }
11448        let was_tracking = e.ctx().is_event_tracking();
11449        if was_tracking {
11450            unsafe {
11451                e.ctx().disable_event_tracking();
11452            }
11453        }
11454        let r = self.generate_spec_inner2(
11455            e, prompt, max_new, k, true, None, None, None, None, None, None,
11456        );
11457        if was_tracking {
11458            unsafe {
11459                e.ctx().enable_event_tracking();
11460            }
11461        }
11462        r
11463    }
11464
11465    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11466    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
11467    fn generate_spec_inner2(
11468        &self,
11469        e: &Engine,
11470        prompt: &[u32],
11471        max_new: usize,
11472        k: usize,
11473        graph_draft: bool,
11474        mut sess: Option<&mut SpecSession>,
11475        sampling: Option<SpecSampling>,
11476        mut constraint: Option<&mut dyn SpecConstraint>,
11477        mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11478        prime_split: Option<usize>,
11479        pipe: Option<&SpecPipeLane>,
11480    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11481        assert!(k >= 1, "k must be >= 1");
11482        let pipe_setup_walk = match pipe {
11483            Some(p) => Some(p.setup_begin()?),
11484            None => None,
11485        };
11486        // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
11487        let mut flushed = 0usize;
11488        // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
11489        // at the next round boundary (same exit as max_new reached — the session tail runs).
11490        // Initialized by the unconditional post-prime flush below.
11491        let mut keep_going;
11492        let mtp = self
11493            .mtp
11494            .as_ref()
11495            .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
11496        let n_vocab = self.output.out_features();
11497        // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
11498        // over the draft vocab and the winning index maps through d2t to a TARGET token id.
11499        // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
11500        let d_vocab = mtp
11501            .shared_head_head
11502            .as_ref()
11503            .unwrap_or(&self.output)
11504            .out_features();
11505        if !self.mtp_extra.is_empty() {
11506            if self.plan.draft_source != memra_gguf::model_plan::DraftSourcePlan::Embedded
11507                || self.plan.mtp_blocks.len() != self.mtp_head_count()
11508            {
11509                return Err(
11510                    "multi-head MTP requires one embedded canonical block per loaded head".into(),
11511                );
11512            }
11513            // TRIMMED chains (2026-08-27): every head must carry the SAME d2t — the ranking is
11514            // token-frequency and head-independent, and every downstream remap (per-step argmax,
11515            // stream pack, sampled d2t_dev) reads head 0's map, so equality is what makes that
11516            // single map correct for the whole chain. Mixed trimmed/untrimmed is refused.
11517            for (offset, head) in self.mtp_extra.iter().enumerate() {
11518                if head.d2t != mtp.d2t
11519                    || head
11520                        .shared_head_head
11521                        .as_ref()
11522                        .unwrap_or(&self.output)
11523                        .out_features()
11524                        != d_vocab
11525                {
11526                    return Err(format!(
11527                        "embedded MTP head {} has incompatible draft vocabulary",
11528                        offset + 1
11529                    )
11530                    .into());
11531                }
11532            }
11533            eprintln!(
11534                "[mtp-chain] heads={} policy=step-modulo prefix-replay kv=per-head",
11535                self.mtp_head_count()
11536            );
11537        }
11538        let n_embd = self.cfg.n_embd as usize;
11539        // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
11540        // already committed (their state is in the caches); 0 = fresh single-shot call.
11541        let session_mode = sess.is_some();
11542        let max_ctx = match sess.as_ref() {
11543            Some(s) => s.cache.max_ctx,
11544            None => prompt.len() + max_new + k + 8,
11545        };
11546        let mut own_cache;
11547        let mut own_scratch;
11548        // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
11549        // (requested split, destination list). Single-shot per burst; fresh calls have none.
11550        let mut sess_capture: Option<(Option<usize>, &mut Vec<SpecBoundaryCapture>)> = None;
11551        // STABLE-BOUNDARY turn-checkpoint request (lane/frspec-multiturn-cache): ABSOLUTE
11552        // committed-length position; consumed one-shot like `capture_at`. None = legacy
11553        // prompt-end capture below.
11554        let mut ckpt_req: Option<usize> = None;
11555        // FAIL-SAFE bit threaded out of the session (see `SpecSession::capture_disabled`).
11556        let mut sess_capture_disabled = false;
11557        let (
11558            cache,
11559            scratch,
11560            mut sess_tail,
11561            mut sess_draft_slot,
11562            mut sess_pending_slot,
11563            sess_ckpt_slot,
11564            sess_telem,
11565        ): (
11566            &mut Cache,
11567            &mut MtpScratch,
11568            Option<(
11569                &mut Vec<u32>,
11570                &mut Option<CudaSlice<f32>>,
11571                &mut Option<u32>,
11572                &mut u32,
11573                &mut u32,
11574            )>,
11575            Option<&mut Option<DraftGraphCtx>>,
11576            Option<&mut Option<u32>>,
11577            Option<&mut Option<SpecCheckpoint>>,
11578            Option<&SpecTelemetryCounters>,
11579        ) = match sess.take() {
11580            Some(sr) => {
11581                let SpecSession {
11582                    cache,
11583                    scratch,
11584                    committed,
11585                    last_h,
11586                    next_pred,
11587                    sctr: s_sctr,
11588                    uctr: s_uctr,
11589                    draft_ctx,
11590                    pending_tok,
11591                    turn_ckpt,
11592                    telem,
11593                    capture_at,
11594                    boundary_captures,
11595                    ckpt_at,
11596                    capture_disabled,
11597                } = sr;
11598                sess_capture_disabled = *capture_disabled;
11599                sess_capture = Some((capture_at.take(), boundary_captures));
11600                ckpt_req = ckpt_at.take();
11601                (
11602                    cache,
11603                    scratch,
11604                    Some((committed, last_h, next_pred, s_sctr, s_uctr)),
11605                    Some(draft_ctx),
11606                    Some(pending_tok),
11607                    Some(turn_ckpt),
11608                    Some(telem),
11609                )
11610            }
11611            None => {
11612                // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
11613                // `Cache::new` verbatim.
11614                own_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?;
11615                // Persistent scratch = max_ctx rows (~2KB/token quantized).
11616                own_scratch = self.new_mtp_scratch(e, max_ctx)?;
11617                (
11618                    &mut own_cache,
11619                    &mut own_scratch,
11620                    None,
11621                    None,
11622                    None,
11623                    None,
11624                    None,
11625                )
11626            }
11627        };
11628        cache.ensure_usable("generate_spec")?;
11629        if scratch.plane_count() != self.mtp_head_count() {
11630            return Err(format!(
11631                "MTP scratch/head count mismatch ({}/{})",
11632                scratch.plane_count(),
11633                self.mtp_head_count()
11634            )
11635            .into());
11636        }
11637        let base = cache.pos;
11638        // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
11639        // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
11640        // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
11641        // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
11642        let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
11643        // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
11644        // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
11645        // acceptance-only — exactness is verify's job either way).
11646        // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
11647        // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
11648        // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
11649        // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
11650        // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
11651        // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
11652        // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
11653        // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
11654        // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
11655        // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
11656        // per round on top of the acceptance win). Draft-quality-only: exactness stays the
11657        // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
11658        // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
11659        // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
11660        // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
11661        // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
11662        // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
11663        // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
11664        // + fallback seam).
11665        // Qwen35-MoE replay pin LIFTED (lane/draftcost-moe, 2026-08-20). The pin's stated
11666        // bar — the retained verify-state commit proven equivalent to sequential serving —
11667        // was waiting on this arch running the serving batched verify class, which the
11668        // t-parallel admission (this lane, increment 1) provided: the VerifyCkpt the
11669        // replay-free commit consumes is now produced by the SAME serving-class verify that
11670        // qualified dense qwen35 on 2026-08-15 (where the per-round duplicate replay
11671        // measured 69 -> 30 tok/s). Qualification receipts (run-spec K=1..8 both arms,
11672        // 8-prompt replay-vs-replay-free canary, long-prompt cell):
11673        // research/draftcost-moe-20260820/RECEIPTS.md. MEMRA_SPEC_REPLAY=1 stays the
11674        // rollback + A/B seam.
11675        let spec_replay = spec_replay_env_enabled();
11676        if constraint.is_some() && spec_replay {
11677            return Err(
11678                "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
11679                        (legacy replay commits an unmasked bonus)"
11680                    .into(),
11681            );
11682        }
11683        // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
11684        // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
11685        // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
11686        let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
11687        if !refresh && !self.mtp_extra.is_empty() {
11688            return Err("multi-head MTP requires exact accepted-prefix refresh".into());
11689        }
11690
11691        // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
11692        // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
11693        // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
11694        // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
11695        // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
11696        // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
11697        // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
11698        // generation exactly where the last turn stopped — no prime at all. The stashed
11699        // `next_pred` plays prime_logits' role: it is the token produced from the logits after
11700        // committed.last() by the same rule this entry applies to a cold prime's last row —
11701        // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
11702        // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
11703        // where the sampler and the session's Philox counters were live). `last_h` seeds the
11704        // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
11705        let continuation = prompt.is_empty();
11706        if continuation {
11707            assert!(session_mode, "empty prompt requires a session");
11708            assert!(
11709                sess_tail
11710                    .as_ref()
11711                    .is_some_and(|(c, lh, np, _, _)| !c.is_empty()
11712                        && lh.is_some()
11713                        && (np.is_some() || carried_pending.is_some())),
11714                "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
11715            );
11716        }
11717        let mut prime_logits;
11718        let mut prompt_h: Option<CudaSlice<f32>> = None;
11719        let t_prime = std::time::Instant::now();
11720        let batched_prime = !continuation
11721            && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
11722            && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
11723            && !e.frozen_cpu_experts_prefer_tokenwise_prime();
11724        let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
11725        if prime_split.is_some() && continuation {
11726            return Err("spec prime split requires a non-empty prime".into());
11727        }
11728        // STABLE-BOUNDARY TURN CHECKPOINT stop (lane/frspec-multiturn-cache, 2026-08-21):
11729        // the worker's `ckpt_at` request, ABSOLUTE -> prompt-relative. On WARM bursts
11730        // (base != 0, an affinity-rewound or pool-resumed session priming its own delta)
11731        // this is the only stop; on COLD bursts it usually coincides with `prime_split`
11732        // (both are the plain tier's stable pre-generation boundary). A boundary the prime
11733        // cannot honor (outside this prime's range) silently drops the capture — the
11734        // turn_ckpt convention: the next turn re-primes in full, never a wrong resume.
11735        let ckpt_rel = if continuation {
11736            None
11737        } else {
11738            ckpt_req
11739                .and_then(|abs| abs.checked_sub(base))
11740                .filter(|&r| r > 0 && r < prompt.len())
11741        };
11742        // Prime stops, ordered: each is a boundary the prime halts at so the in-place GDN
11743        // conv/ssm state can be snapshotted there (the only moment it exists). One stop =
11744        // the legacy single-split program, byte-for-byte.
11745        let mut stops: Vec<usize> = Vec::new();
11746        for b in [prime_split, ckpt_rel].into_iter().flatten() {
11747            if !stops.contains(&b) {
11748                stops.push(b);
11749            }
11750        }
11751        stops.sort_unstable();
11752        // Captured at the ckpt stop, installed into the session slot post-prime (replacing
11753        // the legacy prompt-end capture). Some(None) = capture attempted and failed -> the
11754        // slot is cleared (a stale checkpoint would rewind to the WRONG boundary).
11755        let mut ckpt_early: Option<Option<SpecCheckpoint>> = None;
11756        if continuation {
11757            prime_logits = Vec::new();
11758        } else if !stops.is_empty() {
11759            if let Some(&first) = stops.first()
11760                && prime_split == Some(first)
11761                && first < crate::hybrid_forward::PRIME_MIN_T
11762            {
11763                return Err(format!(
11764                    "spec prime split {first} is below PRIME_MIN_T {}",
11765                    crate::hybrid_forward::PRIME_MIN_T,
11766                )
11767                .into());
11768            }
11769            // Mirror the plain worker's boundary stops exactly. Each segment is a
11770            // request-level prime (`queued_after` keeps Step35 arm selection independent of
11771            // the stops — tick-seg law); a segment below PRIME_MIN_T (and the final tail
11772            // under MEMRA_PRIME_TOKENWISE) takes the same eager tokenwise continuation as
11773            // prefill_tick. Retain every hidden row so the draft scratch fill remains one
11774            // coherent prompt.
11775            let mut h_all = e.uninit(prompt.len() * n_embd)?;
11776            prime_logits = Vec::new();
11777            let mut prev = 0usize;
11778            for seg_end in stops.iter().copied().chain(std::iter::once(prompt.len())) {
11779                if seg_end <= prev {
11780                    continue;
11781                }
11782                let seg = &prompt[prev..seg_end];
11783                let is_final = seg_end == prompt.len();
11784                let batched_seg = seg.len() >= crate::hybrid_forward::PRIME_MIN_T
11785                    && (!is_final
11786                        || (std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
11787                            && !e.frozen_cpu_experts_prefer_tokenwise_prime()));
11788                if batched_seg {
11789                    let (l, _, h_seg) =
11790                        self.prime_cache(e, seg, &mut *cache, prompt.len() - seg_end)?;
11791                    e.copy_into(&mut h_all, prev * n_embd, &h_seg, seg.len() * n_embd)?;
11792                    prime_logits = l;
11793                } else {
11794                    for (i, &tok) in seg.iter().enumerate() {
11795                        let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
11796                        e.copy_into(&mut h_all, (prev + i) * n_embd, &h, n_embd)?;
11797                        prime_logits = l;
11798                    }
11799                }
11800                prev = seg_end;
11801                if is_final {
11802                    break;
11803                }
11804                debug_assert_eq!(cache.pos, base + seg_end, "prime stop landed off boundary");
11805                // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm
11806                // states are about to be advanced in place by the next segment, so this is
11807                // the ONLY moment the boundary's recurrent state exists. Capture iff the
11808                // worker requested exactly this stop (cold sessions only — `capture_at` is
11809                // never armed warm). A failed snapshot is silent (turn_ckpt convention) —
11810                // publication is an optimization, never a correctness dependency.
11811                if base == 0
11812                    && let Some((requested, slot)) = sess_capture.as_mut()
11813                {
11814                    // Publish at the requested miss-LCP stop (the shared-prefix class)
11815                    // AND at the stable-boundary stop (the next-turn re-render class,
11816                    // lane/frspec-multiturn-cache) — the same boundary set the plain
11817                    // prefill tick learns. Without the second entry, the turn after a
11818                    // cold re-park could only hit the OLDER lcp entry (the measured
11819                    // one-turn transient: t3 restored 607 of 24122 while the plain arm
11820                    // rewound to 15222). Dedupe is the worker sweep's has_key.
11821                    if (*requested == Some(seg_end) || ckpt_rel == Some(seg_end))
11822                        && let Ok(snap) = cache.snapshot(e)
11823                    {
11824                        slot.push(SpecBoundaryCapture {
11825                            snap,
11826                            pos: seg_end,
11827                            logits: prime_logits.clone(),
11828                            // rows [0..seg_end) of h_all are primed — the following
11829                            // segments append, never overwrite.
11830                            last_h: capture_boundary_hidden(e, &h_all, seg_end, n_embd),
11831                        });
11832                    }
11833                }
11834                // SESSION-AFFINITY TURN CHECKPOINT at the STABLE boundary (see `ckpt_at`):
11835                // same snapshot mechanics, installed post-prime in place of the prompt-end
11836                // capture the re-render class always diverged below.
11837                if ckpt_rel == Some(seg_end) {
11838                    let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
11839                        e.uninit(n_embd).and_then(|mut a| {
11840                            e.copy_view_into(
11841                                &mut a,
11842                                0,
11843                                &h_all.slice((seg_end - 1) * n_embd..seg_end * n_embd),
11844                                n_embd,
11845                            )?;
11846                            Ok(a)
11847                        });
11848                    ckpt_early = Some(match (cache.snapshot(e), anchor) {
11849                        (Ok(snap), Ok(last_h)) => Some(SpecCheckpoint {
11850                            snap,
11851                            pos: base + seg_end,
11852                            last_h,
11853                        }),
11854                        _ => None,
11855                    });
11856                }
11857            }
11858            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
11859                eprintln!(
11860                    "[spec-prime] stops={stops:?} tail={}",
11861                    prompt.len() - stops.last().copied().unwrap_or(0)
11862                );
11863            }
11864            prompt_h = Some(h_all);
11865        } else if batched_prime {
11866            let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
11867            prime_logits = l;
11868            prompt_h = Some(hiddens);
11869        } else {
11870            prime_logits = Vec::new();
11871            prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
11872            for (i, &tok) in prompt.iter().enumerate() {
11873                let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
11874                if let Some(ph) = prompt_h.as_mut() {
11875                    e.copy_into(ph, i * n_embd, &h, n_embd)?;
11876                }
11877                prime_logits = l;
11878            }
11879        }
11880        e.stream().synchronize()?;
11881        // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
11882        // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
11883        // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
11884        // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
11885        // prime_split. The mid-prompt capture above already consumed the request if it matched.
11886        if !continuation
11887            && base == 0
11888            && let Some((requested, slot)) = sess_capture.as_mut()
11889            && *requested == Some(prompt.len())
11890            && slot.is_empty()
11891        {
11892            debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
11893            if let Ok(snap) = cache.snapshot(e) {
11894                slot.push(SpecBoundaryCapture {
11895                    snap,
11896                    pos: prompt.len(),
11897                    logits: prime_logits.clone(),
11898                    last_h: prompt_h
11899                        .as_ref()
11900                        .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
11901                        .unwrap_or_default(),
11902                });
11903            }
11904        }
11905        // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
11906        // prime-subtraction hack.
11907        crate::PRIME_NANOS.store(
11908            t_prime.elapsed().as_nanos() as u64,
11909            std::sync::atomic::Ordering::Relaxed,
11910        );
11911
11912        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
11913        // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
11914        // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
11915        let host_embd = spec_host_embd();
11916        let embd_gpu = if host_embd {
11917            None
11918        } else {
11919            Some(
11920                self.embd_gpu
11921                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
11922            )
11923        };
11924        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
11925        if host_embd {
11926            eprintln!(
11927                "[spec] host-row embedding: {} bytes kept off HBM",
11928                self.embd.raw.len()
11929            );
11930        }
11931        let mut out: Vec<u32> = Vec::with_capacity(max_new);
11932        let mut total_drafted = 0usize;
11933        let mut total_accepted = 0usize;
11934
11935        // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
11936        // The sampler config, the session's Philox counters and the penalty window are parsed
11937        // HERE, above the boundary-token selection, because the boundary token must be drawn
11938        // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
11939        // selection, which is the whole mechanical reason the boundary token was an argmax:
11940        // the sampler state was not in scope yet. Nothing here depends on the round loop, so
11941        // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
11942        // below takes the argmax path it always took).
11943        // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
11944        // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
11945        // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
11946        // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
11947        let sp = sampling.unwrap_or_else(|| SpecSampling {
11948            temp: std::env::var("MEMRA_SPEC_TEMP")
11949                .ok()
11950                .and_then(|v| v.parse().ok())
11951                .unwrap_or(0.0),
11952            seed: std::env::var("MEMRA_SEED")
11953                .ok()
11954                .and_then(|v| v.parse().ok())
11955                .unwrap_or(42),
11956            top_k: std::env::var("MEMRA_TOP_K")
11957                .ok()
11958                .and_then(|v| v.parse().ok())
11959                .unwrap_or(0),
11960            top_p: std::env::var("MEMRA_TOP_P")
11961                .ok()
11962                .and_then(|v| v.parse().ok())
11963                .unwrap_or(1.0),
11964            min_p: std::env::var("MEMRA_MIN_P")
11965                .ok()
11966                .and_then(|v| v.parse().ok())
11967                .unwrap_or(0.0),
11968            penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
11969                .ok()
11970                .and_then(|v| v.parse().ok())
11971                .unwrap_or(0),
11972            penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
11973                .ok()
11974                .and_then(|v| v.parse().ok())
11975                .unwrap_or(1.0),
11976            penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
11977                .ok()
11978                .and_then(|v| v.parse().ok())
11979                .unwrap_or(0.0),
11980            penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
11981                .ok()
11982                .and_then(|v| v.parse().ok())
11983                .unwrap_or(0.0),
11984        });
11985        let (sp_temp, sp_seed) = (sp.temp, sp.seed);
11986        let sampled = sp_temp > 0.0;
11987        // Counters resume from the session (burst continuity: randomness must never repeat
11988        // across generate_spec_session calls); one-shot callers start at (0,0). Read through
11989        // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
11990        let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
11991        let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
11992        // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
11993        // for the penalized+filtered target). History = generated tokens, host-tracked window.
11994        let pen_on = sampled
11995            && sp.penalty_last_n > 0
11996            && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
11997        // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
11998        // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
11999        // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
12000        // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
12001        // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
12002        // which is what the API contract says and what the plain sampler's own `history` does.
12003        // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
12004        let mut pen_hist: Vec<u32> = if pen_on {
12005            let sess_hist: &[u32] = if spec_pen_session_on() {
12006                sess_tail
12007                    .as_ref()
12008                    .map(|(c, ..)| c.as_slice())
12009                    .unwrap_or(&[])
12010            } else {
12011                &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
12012            };
12013            pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
12014        } else {
12015            Vec::new()
12016        };
12017        // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
12018        // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
12019        // request's own filtered/penalized target through the session's Philox stream
12020        // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
12021        // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
12022        // Emit it, then FEED it to establish the loop invariant below.
12023        // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
12024        // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
12025        // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
12026        // prompt's last logits (plain constrained-greedy identity); a continuation without
12027        // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
12028        // worker never resumes constrained sessions from the pool, so this cannot fire).
12029        if let Some(c) = constraint.as_deref_mut() {
12030            if continuation && carried_pending.is_none() {
12031                return Err("constrained spec continuation requires a carried pending \
12032                            (pool resume is unconstrained-only)"
12033                    .into());
12034            }
12035            if !continuation {
12036                c.mask_logits(&mut prime_logits)
12037                    .map_err(|e2| format!("constraint: {e2}"))?;
12038            }
12039        }
12040        let mut last_token = if let Some(b) = carried_pending {
12041            b
12042        } else if continuation {
12043            // A continuation's boundary token was DRAWN by the burst that stashed it (the
12044            // session tail below), or by `spec_session_from_restored` for a converted
12045            // prefix-cache hit — in both cases from the correct logits row with this same
12046            // session's Philox stream, which is why it can be consumed here as-is.
12047            sess_tail.as_ref().unwrap().2.unwrap()
12048        } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
12049            sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
12050        } else {
12051            // greedy (byte contract), the rollback door, or constrained (masked-argmax
12052            // identity — the worker routes sampled+constrained to the plain path, and this
12053            // function refuses the combination outright above).
12054            argmax(&prime_logits) as u32
12055        };
12056        if pen_on {
12057            // The boundary token is a GENERATED token: the plain sampler `accept()`s every
12058            // emitted token into its penalty history, and pre-lane the burst's first token
12059            // was invisible to penalties forever (never pushed, and never in `committed`
12060            // until this burst's tail). Covers the carry/continuation seeds too — neither is
12061            // in `committed` yet.
12062            pen_hist.push(last_token);
12063        }
12064        if carried_pending.is_none() {
12065            out.push(last_token);
12066            // grammar advances with every emitted token (carried pendings were consumed
12067            // by the burst that emitted them).
12068            if let Some(c) = constraint.as_deref_mut() {
12069                c.consume(last_token)
12070                    .map_err(|e2| format!("constraint: {e2}"))?;
12071            }
12072        }
12073        if continuation {
12074            // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
12075            // overhang so the chain's first append lands at slot base (== committed.len()).
12076            scratch.set_len(e, base)?;
12077        }
12078        // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
12079        // concatenating to the full `out`). Called after the prime's first token and after each
12080        // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
12081        // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
12082        // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
12083        #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
12084        fn flush_commit(
12085            cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
12086            out: &[u32],
12087            flushed: &mut usize,
12088        ) -> bool {
12089            if let Some(f) = cb.as_mut() {
12090                let keep = f(&out[*flushed..]);
12091                *flushed = out.len();
12092                keep
12093            } else {
12094                true
12095            }
12096        }
12097        keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
12098        // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
12099        // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
12100        // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
12101        // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
12102        // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
12103        // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
12104        // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
12105        // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
12106        // those, so their residual mass is p(x), correct by construction).
12107        let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
12108            match &mtp.d2t {
12109                Some(map) => Some(e.htod_u32_v(map)?),
12110                None => None,
12111            }
12112        } else {
12113            None
12114        };
12115        let mut q_full_buf: Option<CudaSlice<f32>> = None;
12116        // host Philox4x32-10 accept-test uniforms: module fn `host_u01` (shared with the
12117        // dspark sampled-admission walk); byte-identical to the closure it replaces.
12118        let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
12119        let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
12120        let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
12121        let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
12122        let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
12123        let mut pen_hist_d: Option<CudaSlice<u32>> = None;
12124        let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
12125        // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
12126        // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
12127        // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
12128        let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
12129        let t_ent = std::time::Instant::now();
12130
12131        // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
12132        // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
12133        // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
12134        // the one that matters (a history-rewriting client mutates what the session GENERATED,
12135        // so the next turn's prompt agrees with this one up to exactly here).
12136        //
12137        // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
12138        // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
12139        // hold exactly `base + prompt.len()` rows and nothing generated.
12140        //
12141        // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
12142        // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
12143        // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
12144        // `<think>` block the client strips, so every later turn's diff diverged exactly one
12145        // token below the checkpoint and affinity declined 100% of the time. Measured on the
12146        // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
12147        // whole mechanism inert while looking, from the outside, like a working
12148        // correctness-declines-safely path — hence the decline log carries the offsets.
12149        //
12150        // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
12151        // state (the reason a spec session could not rewind before). The draft scratch needs no
12152        // copy: rows below the boundary are rewritten by the next turn's own fill.
12153        //
12154        // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
12155        // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
12156        // checkpoint rather than replacing it with a strictly worse one.
12157        //
12158        // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
12159        // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
12160        // fail the burst that is already running — so the error is swallowed, loud only under
12161        // MEMRA_DEBUG_SPEC.
12162        //
12163        // STABLE-BOUNDARY OVERRIDE (lane/frspec-multiturn-cache, 2026-08-21): the prompt-end
12164        // posture above was DISPROVED for the think-posture template class — the prompt's own
12165        // tail is the live generation header (`<|im_start|>assistant\n<think>\n`) that the
12166        // next turn's re-render replaces, so the diff diverged a couple tokens BELOW the
12167        // checkpoint and affinity declined 100% of multi-turn agent traffic (the same class
12168        // the plain tier fixed on 2026-08-09 via `plain_checkpoint_boundary`; the port to the
12169        // spec tier is this lane). When the worker armed `ckpt_at`, the capture happened at
12170        // that stop inside the prime above (`ckpt_early`) and is installed here instead;
12171        // capture-attempted-but-failed clears the slot exactly like the legacy arm.
12172        if let Some(slot) = sess_ckpt_slot {
12173            if let Some(early) = ckpt_early {
12174                if early.is_none() && std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
12175                    eprintln!(
12176                        "[spec] stable-boundary turn checkpoint skipped; \
12177                               next turn re-primes in full"
12178                    );
12179                }
12180                *slot = early;
12181            } else if !continuation {
12182                let pos = cache.pos;
12183                debug_assert_eq!(
12184                    pos,
12185                    base + prompt.len(),
12186                    "turn checkpoint must sit at the prompt end, before the init feed"
12187                );
12188                let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
12189                    if let Some(ph) = &prompt_h {
12190                        // hidden of the LAST primed row = the predecessor anchor at this
12191                        // boundary (exactly what a fresh prime of committed[..pos] leaves in
12192                        // last_h, and what the next prime's fill reads for its first row).
12193                        let np = prompt.len();
12194                        e.uninit(n_embd).and_then(|mut a| {
12195                            e.copy_view_into(
12196                                &mut a,
12197                                0,
12198                                &ph.slice((np - 1) * n_embd..np * n_embd),
12199                                n_embd,
12200                            )?;
12201                            Ok(a)
12202                        })
12203                    } else {
12204                        Err("no prompt hiddens".into())
12205                    };
12206                match (cache.snapshot(e), anchor) {
12207                    (Ok(snap), Ok(last_h)) => {
12208                        *slot = Some(SpecCheckpoint { snap, pos, last_h });
12209                    }
12210                    (s, a) => {
12211                        *slot = None; // a stale checkpoint would rewind to the WRONG boundary
12212                        if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
12213                            let err = s
12214                                .err()
12215                                .map(|e| e.to_string())
12216                                .or_else(|| a.err().map(|e| e.to_string()))
12217                                .unwrap_or_default();
12218                            eprintln!(
12219                                "[spec] turn checkpoint skipped ({err}); \
12220                                       next turn re-primes in full"
12221                            );
12222                        }
12223                    }
12224                }
12225            }
12226        }
12227        // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
12228        // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
12229        // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
12230        // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
12231        let mut last_pred = 0u32;
12232        let mut last_col_logits: Option<CudaSlice<f32>> = None;
12233        // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
12234        // recompute in the grammar-truncation walk — retained host-side, round 0 only.
12235        let mut init_logits_host: Option<Vec<f32>> = None;
12236        let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
12237            let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
12238            last_pred = argmax(&init_logits) as u32;
12239            if constraint.is_some() {
12240                init_logits_host = Some(init_logits.clone());
12241            }
12242            // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
12243            if sampled {
12244                last_col_logits = Some(e.htod(&init_logits)?);
12245            }
12246            h
12247        } else {
12248            // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
12249            let lh = sess_tail
12250                .as_ref()
12251                .unwrap()
12252                .1
12253                .as_ref()
12254                .expect("pending carry requires last_h");
12255            e.clone_dtod(lh)?
12256        };
12257        let t_init = t_ent.elapsed();
12258        let mut last_col_stats: Option<(f32, f32, f32)> = None;
12259        // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
12260        // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
12261        // stable pointer for the graph-draft round-start copy.
12262        let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
12263        // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
12264        // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
12265        // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
12266        // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
12267        // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
12268        // overwritten below).
12269        let mut fill_prev = e.clone_dtod(&h_seed0)?;
12270        {
12271            if let Some(ph) = &prompt_h {
12272                let np = prompt.len();
12273                e.copy_view_into(
12274                    &mut h_seed_buf,
12275                    0,
12276                    &ph.slice((np - 1) * n_embd..np * n_embd),
12277                    n_embd,
12278                )?;
12279            } else if continuation
12280                && let Some((_, lh, _, _, _)) = sess_tail.as_ref()
12281                && let Some(lh) = lh.as_ref()
12282            {
12283                e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
12284            }
12285        }
12286        // Persistent device prediction slots for the accept walk (max k+1 verify columns).
12287        let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
12288
12289        let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
12290        let fork_mode = OptiForkGateMode::configured();
12291        // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
12292        // the end. Metric normalization vs the reference engine: BOTH engines count
12293        // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
12294        // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
12295        let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
12296        let mut st_drafted = vec![0usize; k];
12297        let mut st_accepted = vec![0usize; k];
12298        let mut st_len_hist = vec![0usize; k + 1];
12299        let mut st_full = 0usize;
12300        // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
12301        // stop the draft chain early when the head's softmax confidence in its own pick drops
12302        // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
12303        static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
12304        let p_min = *PMIN.get_or_init(|| {
12305            std::env::var("MEMRA_SPEC_PMIN")
12306                .ok()
12307                .and_then(|v| v.parse().ok())
12308                .unwrap_or(0.0)
12309        });
12310        // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
12311        // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
12312        // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
12313        // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
12314        // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
12315        // verify batch is not); the j==0 exemption stays for pending-less rounds.
12316        let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
12317            .map(|v| v == "1")
12318            .unwrap_or(false);
12319
12320        // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
12321        // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
12322        // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
12323        // cuBLAS path in an exotic head) falls back to the eager draft chain.
12324        // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
12325        // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
12326        // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
12327        // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
12328        // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
12329        // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
12330        // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
12331        // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
12332        let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
12333            Some(c) => c,
12334            None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
12335        };
12336        // FAIL-SAFE (step-OOM park replay): pre-mark both fallback flags so no capture arm
12337        // below can fire — LOUD once per replayed session through the standard WARN line.
12338        if sess_capture_disabled {
12339            let reason =
12340                "session replayed after a step-OOM park; draft capture disabled (fail-safe)";
12341            let flip = dctx.failed.mark_greedy(reason);
12342            let flip_s = dctx.failed.mark_sampled(reason);
12343            if let Some(line) = flip.or(flip_s) {
12344                eprintln!("{line}");
12345            }
12346        }
12347        // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
12348        // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
12349        if sampled && dctx.g_q.len() < d_vocab {
12350            dctx.g_q = e.zeros(d_vocab)?;
12351            dctx.g_perturb = e.zeros(d_vocab)?;
12352        }
12353        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
12354        // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
12355        // truncation (the correctness backstop) stops cutting every tight-schema round.
12356        // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
12357        // shape, so a parked graph of the other shape is dropped and recaptured.
12358        let dmask_on = constraint
12359            .as_deref()
12360            .is_some_and(|c| c.draft_mask_enabled());
12361        let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
12362        if dmask_on && dctx.g_dmask.len() < dmask_words {
12363            dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
12364            dctx.graph = None; // the old capture baked the old (or no) mask pointer
12365            dctx.chain = None; // chain last-row graphs bake the same pointer
12366            dctx.failed.clear_greedy();
12367            dctx.keeper.clear();
12368        }
12369        if (dctx.graph.is_some() || dctx.chain.is_some()) && dctx.graph_masked != dmask_on {
12370            dctx.graph = None;
12371            dctx.chain = None;
12372            dctx.failed.clear_greedy();
12373            dctx.keeper.clear();
12374        }
12375        // MULTI-HEAD CHAIN mode (mtp_extra non-empty — step37's 3-head shipping shape): the
12376        // step-modulo prefix-replay chain captures PER-HEAD single-row graphs
12377        // (`DraftChainGraphs`) instead of the one self-feeding graph below; the single-head
12378        // capture arms are untouched and unreachable in this mode (the launch arms branch the
12379        // same way). This removes the historical `mtp_extra.is_empty()` capture exclusion —
12380        // and with it the silent no-attempt hole: a chain capture that FAILS now trips the
12381        // same LOUD draft-graph WARN as a single-head failure.
12382        let chain_mode = !self.mtp_extra.is_empty();
12383        // ---- PRE-CAPTURE VRAM RESERVE CHECK + PER-SESSION DRAFT-STATE MEASUREMENT ----
12384        // (lane/step37-vram-admission-20260830). `cap_eff0` opens the measurement bracket:
12385        // when any capture succeeds in THIS call, the effective-free delta across the whole
12386        // capture section is recorded as the model's per-session draft-state high-water
12387        // (admission charges it per spec-capable session — this state was charged at ZERO
12388        // before the lane). The reserve check runs BEFORE any capture arm can allocate: a
12389        // refused capture trips the same LOUD once-per-flip WARN class as a failed one, but
12390        // with the card's headroom still intact (the owner's single-session OOM was a capture
12391        // attempt walking the card to the edge and stranding the eager fallback at 5 MiB free).
12392        let cap_eff0 = e
12393            .ctx()
12394            .mem_get_info()
12395            .ok()
12396            .map(|(f, _)| f.saturating_add(e.pool_cached_bytes()));
12397        // Peak instrument for the same bracket: the CAPTURE-TIME peak (warmup transients +
12398        // instantiate scratch, alive together) dwarfs the parked delta — measured on the
12399        // owner shape: a capture whose PARKED state reads ~2.6GB walked a ~7GB-free card to
12400        // OOM mid-capture. Reset the pool watermark here; read it at bracket end.
12401        let _ = e.pool_high_water_reset();
12402        let cap_used0 = e.pool_reserved_used().1;
12403        let mut captured_now = false;
12404        let mut capture_oom_entry_eff: Option<usize> = None;
12405        let capture_need = {
12406            let observed = self.draft_session_admission_bytes();
12407            if observed > 0 {
12408                observed
12409            } else {
12410                draft_capture_bootstrap_estimate(
12411                    if chain_mode { self.mtp_head_count() } else { 1 },
12412                    k,
12413                    d_vocab,
12414                    n_embd,
12415                )
12416            }
12417        };
12418        if spec_capture_gate_on()
12419            && graph_draft
12420            && !sampled
12421            && !dctx.failed.greedy_failed()
12422            && ((chain_mode && dctx.chain.is_none() && mtp_chain_graph_on())
12423                || (!chain_mode && dctx.graph.is_none()))
12424            && let Some(reason) = capture_headroom_refusal(e, capture_need)
12425            && let Some(line) = dctx.failed.mark_greedy(&reason)
12426        {
12427            eprintln!("{line}");
12428        }
12429        if graph_draft
12430            && !sampled
12431            && chain_mode
12432            && dctx.chain.is_none()
12433            && !dctx.failed.greedy_failed()
12434        {
12435            if mtp_chain_graph_on() {
12436                let heads_n = self.mtp_head_count();
12437                let DraftGraphCtx {
12438                    g_tok,
12439                    g_pos,
12440                    g_seed,
12441                    g_p,
12442                    g_dmask,
12443                    ..
12444                } = &mut dctx;
12445                if dmask_on {
12446                    e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
12447                }
12448                let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
12449                let with_prob = p_min > 0.0;
12450                // CAPTURE-RETAIN (#68 fix): one keeper for the whole chain — every graph's
12451                // warmup transients stay pinned as long as any of them replays.
12452                let cap_res = (|| -> Result<DraftChainGraphs, Box<dyn std::error::Error>> {
12453                    // dcw door: same warmup headroom pre-arm as the single-head capture
12454                    // below — every plane, because each head's capture warmups append on
12455                    // its OWN plane. INSIDE the fallible closure (vram-admission lane): an
12456                    // OOM here used to `?` out of the whole burst as a step error; now it
12457                    // is a capture failure — LOUD WARN, eager chain serves.
12458                    if step35_draft_dcw_on() {
12459                        scratch.ensure_dcw_headroom(e, k + 2)?;
12460                    }
12461                    let mut interior = Vec::with_capacity(heads_n);
12462                    let mut last = Vec::with_capacity(heads_n);
12463                    let mut keeper: Vec<Box<dyn std::any::Any + Send>> = Vec::new();
12464                    for hi in 0..heads_n {
12465                        let head = self.mtp_head_at(hi);
12466                        // interior row: KV append + carrier only (`with_head=false` — the
12467                        // eager chain discards interior logits too, so this is the same
12468                        // consumed-byte program minus the dead full-vocab head matmul).
12469                        let (g, keep) = e.capture_graph_retained(|e| {
12470                            self.mtp_head_forward_cap(
12471                                e,
12472                                head,
12473                                g_tok,
12474                                g_pos,
12475                                g_seed,
12476                                g_p,
12477                                &mut *scratch,
12478                                hi,
12479                                false,
12480                                false,
12481                                embd_gpu.expect("graph draft requires resident embedding"),
12482                                embd_qt,
12483                                embd_rb,
12484                                d_vocab,
12485                                None,
12486                                None,
12487                                None,
12488                            )
12489                        })?;
12490                        // the warmups appended rows on plane hi; rewind before the next
12491                        // capture so successive warmups never outrun the pre-armed headroom.
12492                        scratch.set_plane_len(e, hi, base)?;
12493                        interior.push(g);
12494                        keeper.extend(keep);
12495                        // last row: head matmul + greedy argmax tail (+ p when the policy
12496                        // reads it, + the grammar-mask node when constrained).
12497                        let (g2, keep2) = e.capture_graph_retained(|e| {
12498                            self.mtp_head_forward_cap(
12499                                e,
12500                                head,
12501                                g_tok,
12502                                g_pos,
12503                                g_seed,
12504                                g_p,
12505                                &mut *scratch,
12506                                hi,
12507                                with_prob,
12508                                true,
12509                                embd_gpu.expect("graph draft requires resident embedding"),
12510                                embd_qt,
12511                                embd_rb,
12512                                d_vocab,
12513                                None,
12514                                None,
12515                                if dmask_on {
12516                                    Some((g_dmask_ro, dmask_words))
12517                                } else {
12518                                    None
12519                                },
12520                            )
12521                        })?;
12522                        scratch.set_plane_len(e, hi, base)?;
12523                        last.push(g2);
12524                        keeper.extend(keep2);
12525                    }
12526                    Ok(DraftChainGraphs {
12527                        interior,
12528                        last,
12529                        _keeper: keeper,
12530                    })
12531                })();
12532                match cap_res {
12533                    Ok(cg) => {
12534                        scratch.set_len(e, base)?;
12535                        // POSITIVE engagement receipt (the 3a lesson: a WARN-free boot is
12536                        // NOT evidence of capture — the captured state must name itself).
12537                        eprintln!(
12538                            "[mtp-chain-graph] captured mode=greedy heads={heads_n} \
12539                             interior={heads_n} last={heads_n} masked={}",
12540                            dmask_on as u8
12541                        );
12542                        dctx.chain = Some(cg);
12543                        dctx.graph_masked = dmask_on;
12544                        captured_now = true;
12545                    }
12546                    Err(err) => {
12547                        scratch.set_len(e, base)?;
12548                        // LOUD flip (audit Q2): a dropped draft graph is a coverage loss,
12549                        // never silent — now including the multi-head shipping shape.
12550                        // OOM RECOVERY (vram-admission lane): a failed attempt's freed
12551                        // transients sit CACHED in the async pool where the driver cannot
12552                        // see them; trim them back so the eager fallback (and any driver-
12553                        // side allocation) actually has the headroom the free suggests.
12554                        let mut reason = err.to_string();
12555                        if capture_err_is_oom(&reason) {
12556                            capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
12557                            let trimmed = e.pool_trim_to_zero();
12558                            if trimmed > 0 {
12559                                reason.push_str(&format!(
12560                                    "; pool trimmed {}MB back to the driver",
12561                                    trimmed / (1 << 20)
12562                                ));
12563                            }
12564                        }
12565                        if let Some(line) = dctx.failed.mark_greedy(&reason) {
12566                            eprintln!("{line}");
12567                        }
12568                    }
12569                }
12570            } else {
12571                // Disarmed by MEMRA_MTP_CHAIN_GRAPH=0: say so once per process — the OFF arm
12572                // must be attributable in a boot log, never inferable from silence.
12573                static NOTE: std::sync::Once = std::sync::Once::new();
12574                NOTE.call_once(|| {
12575                    eprintln!(
12576                        "[spec] multi-head draft-chain capture disarmed \
12577                         (MEMRA_MTP_CHAIN_GRAPH=0); eager chain serves this shape"
12578                    );
12579                });
12580            }
12581        }
12582        if graph_draft
12583            && !sampled
12584            && !chain_mode
12585            && dctx.graph.is_none()
12586            && !dctx.failed.greedy_failed()
12587        {
12588            let DraftGraphCtx {
12589                g_tok,
12590                g_pos,
12591                g_seed,
12592                g_p,
12593                g_dmask,
12594                ..
12595            } = &mut dctx;
12596            // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
12597            // host uploads the position's real words, so the warmups stay grammar-free.
12598            if dmask_on {
12599                e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
12600            }
12601            let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
12602            // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
12603            // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
12604            // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
12605            // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
12606            // passes (and, in serve, other sessions) recycle those addresses and the replay then
12607            // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
12608            let cap_res = (|| {
12609                // dcw door: the capture warmups append device-counter rows the capture body
12610                // cannot rebase for; pre-arm ring headroom host-side (no-op on flat planes /
12611                // room-enough rings, and the door-off path is untouched). INSIDE the fallible
12612                // closure (vram-admission lane): an OOM here is a capture failure, not a
12613                // burst-killing step error.
12614                if step35_draft_dcw_on() {
12615                    scratch.ensure_dcw_headroom(e, k + 2)?;
12616                }
12617                e.capture_graph_retained(|e| {
12618                    self.mtp_head_forward_cap(
12619                        e,
12620                        mtp,
12621                        g_tok,
12622                        g_pos,
12623                        g_seed,
12624                        g_p,
12625                        &mut *scratch,
12626                        0,
12627                        p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
12628                        true,
12629                        embd_gpu.expect("graph draft requires resident embedding"),
12630                        embd_qt,
12631                        embd_rb,
12632                        d_vocab,
12633                        None,
12634                        None,
12635                        if dmask_on {
12636                            Some((g_dmask_ro, dmask_words))
12637                        } else {
12638                            None
12639                        },
12640                    )
12641                })
12642            })();
12643            match cap_res {
12644                Ok((g, keep)) => {
12645                    scratch.set_len(e, base)?;
12646                    dctx.graph = Some(g);
12647                    dctx.graph_masked = dmask_on;
12648                    dctx.keeper = keep;
12649                    captured_now = true;
12650                }
12651                Err(err) => {
12652                    scratch.set_len(e, base)?;
12653                    // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
12654                    // silent. Once per flip — mark returns None on an already-failed ctx.
12655                    let mut reason = err.to_string();
12656                    if capture_err_is_oom(&reason) {
12657                        capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
12658                        let trimmed = e.pool_trim_to_zero();
12659                        if trimmed > 0 {
12660                            reason.push_str(&format!(
12661                                "; pool trimmed {}MB back to the driver",
12662                                trimmed / (1 << 20)
12663                            ));
12664                        }
12665                    }
12666                    if let Some(line) = dctx.failed.mark_greedy(&reason) {
12667                        eprintln!("{line}");
12668                    }
12669                }
12670            }
12671        }
12672        // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
12673        // graph object, built only when sampled && graph-eligible — the greedy capture above is
12674        // untouched (and skipped when sampled: its graph would never be launched). Same head
12675        // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
12676        // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
12677        // once per round); the raw head logits land in the persistent g_q for the host's
12678        // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
12679        // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
12680        // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
12681        // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
12682        // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
12683        // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
12684        // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
12685        // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
12686        // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
12687        // this compare misses at most ONCE per resumed request — the first burst recaptures
12688        // and every later burst in that request replays. A client that wants the parked graph
12689        // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
12690        // stable across its whole conversation.
12691        // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
12692        // softmax — it can hold neither per-row filter stats nor the varying penalty history.
12693        // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
12694        // force the eager draft (which computes stats/penalties per row).
12695        // KEY THE WHOLE REGIME, not just the baked constants (lane/graph-s-key-exactness-
12696        // 20260819). `s_key` used to be `(seed, temp, k)`; the filters and penalties were left
12697        // out, so a filtered request resuming a session that parked a PURE-TEMP graph kept it —
12698        // and the launch site never re-asked `pure_temp`. See [`SampledGraphKey`] for what that
12699        // costs (an unconditional accept of out-of-head draft tokens, i.e. an exactness bug on
12700        // the request shape the vendor-default flip makes the majority).
12701        let s_key = SampledGraphKey::new(sp_seed, sp_temp, k, sp.top_k, sp.top_p, sp.min_p, pen_on);
12702        let pure_temp = s_key.pure_temp();
12703        // The regime the sampled graph may be captured/launched in: pure-temp always;
12704        // truncation-filtered when the filtered-capture door is on (the filter runs
12705        // IN-GRAPH — lane/step37-draft-graph-serving-20260830); penalties never.
12706        let s_capturable = s_key.graph_capturable();
12707        if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
12708            dctx.graph_s = None;
12709            dctx.chain_s = None;
12710            dctx.failed.clear_sampled();
12711            dctx.s_key = None;
12712            dctx.q_slots.clear();
12713            dctx.keeper_s.clear();
12714        }
12715        // PRE-CAPTURE VRAM RESERVE CHECK, sampled arms (vram-admission lane): same contract
12716        // as the greedy check above — refuse BEFORE allocating, LOUD once, eager serves.
12717        if spec_capture_gate_on()
12718            && graph_draft
12719            && sampled
12720            && s_capturable
12721            && !dctx.failed.sampled_failed()
12722            && ((chain_mode && dctx.chain_s.is_none() && mtp_chain_graph_on())
12723                || (!chain_mode && dctx.graph_s.is_none()))
12724            && let Some(reason) = capture_headroom_refusal(e, capture_need)
12725            && let Some(line) = dctx.failed.mark_sampled(&reason)
12726        {
12727            eprintln!("{line}");
12728        }
12729        // FILTERED capture nodes need q slots sized d_vocab AND the stat slots; the pure-temp
12730        // body leaves g_th/g_z/g_mx untouched (they exist from ctx creation either way).
12731        if graph_draft
12732            && sampled
12733            && s_capturable
12734            && chain_mode
12735            && dctx.chain_s.is_none()
12736            && !dctx.failed.sampled_failed()
12737        {
12738            if mtp_chain_graph_on() {
12739                let heads_n = self.mtp_head_count();
12740                let filtered = s_key.filtered();
12741                let DraftGraphCtx {
12742                    g_tok,
12743                    g_pos,
12744                    g_seed,
12745                    g_p,
12746                    g_ctr,
12747                    g_perturb,
12748                    g_q,
12749                    g_rows0,
12750                    g_th,
12751                    g_z,
12752                    g_mx,
12753                    ..
12754                } = &mut dctx;
12755                let with_prob = p_min > 0.0;
12756                let cap_res = (|| -> Result<DraftChainGraphs, Box<dyn std::error::Error>> {
12757                    // dcw pre-arm INSIDE the fallible closure (vram-admission lane): an OOM
12758                    // here is a capture failure with the LOUD WARN, never a step error.
12759                    if step35_draft_dcw_on() {
12760                        scratch.ensure_dcw_headroom(e, k + 2)?;
12761                    }
12762                    let mut interior = Vec::with_capacity(heads_n);
12763                    let mut last = Vec::with_capacity(heads_n);
12764                    let mut keeper: Vec<Box<dyn std::any::Any + Send>> = Vec::new();
12765                    for hi in 0..heads_n {
12766                        let head = self.mtp_head_at(hi);
12767                        // interior row: no head, no draw — shared shape with the greedy
12768                        // chain's interior, captured per mode for keeper-lifetime hygiene.
12769                        let (g, keep) = e.capture_graph_retained(|e| {
12770                            self.mtp_head_forward_cap(
12771                                e,
12772                                head,
12773                                g_tok,
12774                                g_pos,
12775                                g_seed,
12776                                g_p,
12777                                &mut *scratch,
12778                                hi,
12779                                false,
12780                                false,
12781                                embd_gpu.expect("graph draft requires resident embedding"),
12782                                embd_qt,
12783                                embd_rb,
12784                                d_vocab,
12785                                None,
12786                                None,
12787                                None,
12788                            )
12789                        })?;
12790                        scratch.set_plane_len(e, hi, base)?;
12791                        interior.push(g);
12792                        keeper.extend(keep);
12793                        // last row: head matmul + the in-graph categorical draw (filtered
12794                        // nodes when the request carries filters).
12795                        let (g2, keep2) = e.capture_graph_retained(|e| {
12796                            self.mtp_head_forward_cap(
12797                                e,
12798                                head,
12799                                g_tok,
12800                                g_pos,
12801                                g_seed,
12802                                g_p,
12803                                &mut *scratch,
12804                                hi,
12805                                with_prob,
12806                                true,
12807                                embd_gpu.expect("graph draft requires resident embedding"),
12808                                embd_qt,
12809                                embd_rb,
12810                                d_vocab,
12811                                Some(SampledCapArgs {
12812                                    ctr: &mut *g_ctr,
12813                                    perturb: &mut *g_perturb,
12814                                    q_out: &mut *g_q,
12815                                    seed: sp_seed,
12816                                    temp: sp_temp,
12817                                    filt: if filtered {
12818                                        Some(SampledCapFilter {
12819                                            rows0: &*g_rows0,
12820                                            th: &mut *g_th,
12821                                            z: &mut *g_z,
12822                                            mx: &mut *g_mx,
12823                                            top_k: sp.top_k,
12824                                            top_p: sp.top_p,
12825                                            min_p: sp.min_p,
12826                                        })
12827                                    } else {
12828                                        None
12829                                    },
12830                                }),
12831                                None,
12832                                None, // constrained spec is greedy-only
12833                            )
12834                        })?;
12835                        scratch.set_plane_len(e, hi, base)?;
12836                        last.push(g2);
12837                        keeper.extend(keep2);
12838                    }
12839                    Ok(DraftChainGraphs {
12840                        interior,
12841                        last,
12842                        _keeper: keeper,
12843                    })
12844                })();
12845                match cap_res {
12846                    Ok(cg) => {
12847                        scratch.set_len(e, base)?;
12848                        // NO STRANDED PARTIAL STATE (vram-admission lane): the q-slot allocs
12849                        // after a successful capture are themselves fallible on a tight card.
12850                        // A mid-loop failure used to `?` out as a step error, leaving orphan
12851                        // slots parked on the ctx (wrong count, stale contents) for the next
12852                        // capture attempt to stack onto. Allocate all-or-nothing: on failure
12853                        // drop the fresh graphs AND the partial slots, mark the LOUD fallback.
12854                        dctx.q_slots.clear();
12855                        let slots = (0..k)
12856                            .map(|_| e.zeros(d_vocab))
12857                            .collect::<Result<Vec<_>, _>>();
12858                        match slots {
12859                            Ok(slots) => {
12860                                dctx.q_slots = slots;
12861                                eprintln!(
12862                                    "[mtp-chain-graph] captured mode=sampled heads={heads_n} \
12863                                     interior={heads_n} last={heads_n} filtered={} key={s_key:?}",
12864                                    s_key.filtered() as u8
12865                                );
12866                                dctx.chain_s = Some(cg);
12867                                dctx.s_key = Some(s_key);
12868                                captured_now = true;
12869                            }
12870                            Err(err) => {
12871                                drop(cg);
12872                                dctx.q_slots.clear();
12873                                let mut reason = format!("q-slot alloc failed: {err}");
12874                                if capture_err_is_oom(&reason) {
12875                                    capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
12876                                    let trimmed = e.pool_trim_to_zero();
12877                                    if trimmed > 0 {
12878                                        reason.push_str(&format!(
12879                                            "; pool trimmed {}MB back to the driver",
12880                                            trimmed / (1 << 20)
12881                                        ));
12882                                    }
12883                                }
12884                                if let Some(line) = dctx.failed.mark_sampled(&reason) {
12885                                    eprintln!("{line}");
12886                                }
12887                            }
12888                        }
12889                    }
12890                    Err(err) => {
12891                        scratch.set_len(e, base)?;
12892                        let mut reason = err.to_string();
12893                        if capture_err_is_oom(&reason) {
12894                            capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
12895                            let trimmed = e.pool_trim_to_zero();
12896                            if trimmed > 0 {
12897                                reason.push_str(&format!(
12898                                    "; pool trimmed {}MB back to the driver",
12899                                    trimmed / (1 << 20)
12900                                ));
12901                            }
12902                        }
12903                        if let Some(line) = dctx.failed.mark_sampled(&reason) {
12904                            eprintln!("{line}");
12905                        }
12906                    }
12907                }
12908            } else {
12909                static NOTE_S: std::sync::Once = std::sync::Once::new();
12910                NOTE_S.call_once(|| {
12911                    eprintln!(
12912                        "[spec] multi-head draft-chain capture disarmed \
12913                         (MEMRA_MTP_CHAIN_GRAPH=0); eager chain serves this shape"
12914                    );
12915                });
12916            }
12917        }
12918        if graph_draft
12919            && sampled
12920            && s_capturable
12921            && !chain_mode
12922            && dctx.graph_s.is_none()
12923            && !dctx.failed.sampled_failed()
12924        {
12925            let filtered = s_key.filtered();
12926            let DraftGraphCtx {
12927                g_tok,
12928                g_pos,
12929                g_seed,
12930                g_p,
12931                g_ctr,
12932                g_perturb,
12933                g_q,
12934                g_rows0,
12935                g_th,
12936                g_z,
12937                g_mx,
12938                ..
12939            } = &mut dctx;
12940            // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
12941            let cap_res = (|| {
12942                // dcw pre-arm INSIDE the fallible closure (vram-admission lane): an OOM
12943                // here is a capture failure with the LOUD WARN, never a step error.
12944                if step35_draft_dcw_on() {
12945                    scratch.ensure_dcw_headroom(e, k + 2)?;
12946                }
12947                e.capture_graph_retained(|e| {
12948                    self.mtp_head_forward_cap(
12949                        e,
12950                        mtp,
12951                        g_tok,
12952                        g_pos,
12953                        g_seed,
12954                        g_p,
12955                        &mut *scratch,
12956                        0,
12957                        p_min > 0.0,
12958                        true,
12959                        embd_gpu.expect("graph draft requires resident embedding"),
12960                        embd_qt,
12961                        embd_rb,
12962                        d_vocab,
12963                        Some(SampledCapArgs {
12964                            ctr: &mut *g_ctr,
12965                            perturb: &mut *g_perturb,
12966                            q_out: &mut *g_q,
12967                            seed: sp_seed,
12968                            temp: sp_temp,
12969                            filt: if filtered {
12970                                Some(SampledCapFilter {
12971                                    rows0: &*g_rows0,
12972                                    th: &mut *g_th,
12973                                    z: &mut *g_z,
12974                                    mx: &mut *g_mx,
12975                                    top_k: sp.top_k,
12976                                    top_p: sp.top_p,
12977                                    min_p: sp.min_p,
12978                                })
12979                            } else {
12980                                None
12981                            },
12982                        }),
12983                        None,
12984                        None, // constrained spec is greedy-only — sampled never carries a hook
12985                    )
12986                })
12987            })();
12988            match cap_res {
12989                Ok((g, keep)) => {
12990                    scratch.set_len(e, base)?;
12991                    // NO STRANDED PARTIAL STATE: all-or-nothing q slots, same contract as
12992                    // the chain arm above.
12993                    dctx.q_slots.clear();
12994                    let slots = (0..k)
12995                        .map(|_| e.zeros(d_vocab))
12996                        .collect::<Result<Vec<_>, _>>();
12997                    match slots {
12998                        Ok(slots) => {
12999                            dctx.q_slots = slots;
13000                            dctx.graph_s = Some(g);
13001                            dctx.s_key = Some(s_key);
13002                            dctx.keeper_s = keep;
13003                            captured_now = true;
13004                        }
13005                        Err(err) => {
13006                            drop(g);
13007                            drop(keep);
13008                            dctx.q_slots.clear();
13009                            let mut reason = format!("q-slot alloc failed: {err}");
13010                            if capture_err_is_oom(&reason) {
13011                                capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
13012                                let trimmed = e.pool_trim_to_zero();
13013                                if trimmed > 0 {
13014                                    reason.push_str(&format!(
13015                                        "; pool trimmed {}MB back to the driver",
13016                                        trimmed / (1 << 20)
13017                                    ));
13018                                }
13019                            }
13020                            if let Some(line) = dctx.failed.mark_sampled(&reason) {
13021                                eprintln!("{line}");
13022                            }
13023                        }
13024                    }
13025                }
13026                Err(err) => {
13027                    scratch.set_len(e, base)?;
13028                    // LOUD flip (audit Q2): same contract as the greedy capture above.
13029                    let mut reason = err.to_string();
13030                    if capture_err_is_oom(&reason) {
13031                        capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
13032                        let trimmed = e.pool_trim_to_zero();
13033                        if trimmed > 0 {
13034                            reason.push_str(&format!(
13035                                "; pool trimmed {}MB back to the driver",
13036                                trimmed / (1 << 20)
13037                            ));
13038                        }
13039                    }
13040                    if let Some(line) = dctx.failed.mark_sampled(&reason) {
13041                        eprintln!("{line}");
13042                    }
13043                }
13044            }
13045        }
13046        // ---- PER-SESSION DRAFT-STATE MEASUREMENT bracket end (vram-admission lane): when a
13047        // capture landed in THIS call, the effective-free delta across the capture section is
13048        // this session's parked draft-graph state (keepers + q slots + instantiated graphs'
13049        // backing). Recorded as a model-owned high-water; admission charges it per
13050        // spec-capable session (see `draft_session_admission_bytes`).
13051        if captured_now
13052            && let Some(eff0) = cap_eff0
13053            && let Ok((f1, _)) = e.ctx().mem_get_info()
13054        {
13055            let eff1 = f1.saturating_add(e.pool_cached_bytes());
13056            let parked_delta = eff0.saturating_sub(eff1);
13057            let (_res_high, used_high) = e.pool_high_water_reset();
13058            let peak_delta = used_high.saturating_sub(cap_used0);
13059            let observed = parked_delta.max(peak_delta);
13060            if observed > 0
13061                && let Some(hw) = self.record_draft_state_bytes(observed)
13062            {
13063                eprintln!(
13064                    "[spec] draft-session state high-water: {}MB (max of parked delta {}MB \
13065                     and capture-time pool peak {}MB; charged per spec admission and gating \
13066                     future captures)",
13067                    hw / (1 << 20),
13068                    parked_delta / (1 << 20),
13069                    peak_delta / (1 << 20),
13070                );
13071            }
13072        }
13073        // FAILURE IS AN OBSERVATION TOO: a capture that OOM'd at entry-effective E proved
13074        // the capture-time peak exceeds E. Feed E into the gauge so every future gate
13075        // refuses at or below the headroom that just failed (self-healing even when the
13076        // boot probe is disarmed and the bootstrap estimate was blind).
13077        if let Some(entry_eff) = capture_oom_entry_eff
13078            && let Some(hw) = self.record_draft_state_bytes(entry_eff)
13079        {
13080            eprintln!(
13081                "[spec] draft-session capture appetite floor raised to {}MB: a capture \
13082                 attempt OOM'd with that much effective free (failure-observed bound)",
13083                hw / (1 << 20)
13084            );
13085        }
13086        // ---- EXACTNESS GUARD, the enforceable half (lane/graph-s-key-exactness-20260819,
13087        // widened by lane/step37-draft-graph-serving-20260830) ----
13088        // With the filters and penalties in `s_key`, a graph that SURVIVED the drop above was
13089        // captured under THIS request's exact regime, and capture requires `graph_capturable`
13090        // (pure-temp, or filtered with the in-graph filter nodes; never penalties) — so a
13091        // parked graph implies both. That implication is the whole exactness argument for the
13092        // graph arm, so it is asserted here rather than assumed: a future change that widens
13093        // the capture condition, narrows the key, or copies a `DraftGraphCtx` across regimes
13094        // fails LOUDLY at this line instead of silently drafting from a distribution the
13095        // verify never reconstructs. Release builds refuse the graph (drop it, draft eager)
13096        // rather than launching it; the launch site re-tests the regime independently.
13097        if sampled
13098            && (dctx.graph_s.is_some() || dctx.chain_s.is_some())
13099            && (!s_capturable || dctx.s_key != Some(s_key))
13100        {
13101            debug_assert!(
13102                false,
13103                "sampled draft graph parked under {:?} survived into a request outside its \
13104                 capture regime (top_k={} top_p={} min_p={} pen_on={} capturable={}): the \
13105                 in-graph draw and the verify's accept test would see different distributions",
13106                dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on, s_capturable,
13107            );
13108            eprintln!(
13109                "[spec] BUG: dropping a parked sampled draft graph that outlived its capture \
13110                 regime (s_key={:?}, request top_k={} top_p={} min_p={} pen_on={} \
13111                 capturable={}); drafting EAGER — the key must carry every field that shapes q",
13112                dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on, s_capturable,
13113            );
13114            dctx.graph_s = None;
13115            dctx.chain_s = None;
13116            dctx.s_key = None;
13117            dctx.q_slots.clear();
13118            dctx.keeper_s.clear();
13119        }
13120        // SKEY PROBE (MEMRA_SKEY_PROBE=1): the burst-entry facts the reachability question turns
13121        // on — is this request sampled, is it in a regime the sampled graph is legal in, and is
13122        // a graph PARKED from an earlier request of the same session? The launch arms below
13123        // print which chain actually ran, so the probe never restates the condition.
13124        if skey_probe() {
13125            eprintln!(
13126                "[skey] burst sampled={} pure_temp={} capturable={} temp={} top_k={} top_p={} \
13127                 min_p={} pen_on={} k={} graph_draft={} graph_s_parked={} chain_s_parked={} \
13128                 s_key_parked={:?}",
13129                sampled as u8,
13130                pure_temp as u8,
13131                s_capturable as u8,
13132                sp_temp,
13133                sp.top_k,
13134                sp.top_p,
13135                sp.min_p,
13136                pen_on as u8,
13137                k,
13138                graph_draft as u8,
13139                dctx.graph_s.is_some() as u8,
13140                dctx.chain_s.is_some() as u8,
13141                dctx.s_key,
13142            );
13143        }
13144        let t_cap = t_ent.elapsed();
13145        // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
13146        // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
13147        // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
13148        // fill: the first chain step processes it and appends its entry at slot prompt.len().
13149        if let Some(ph) = &prompt_h {
13150            // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
13151            // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
13152            // global positions [base..base+tp). Fresh call: base==0, identical to before.
13153            scratch.set_len(e, base)?;
13154            // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
13155            // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
13156            // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
13157            // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
13158            let tp = prompt.len();
13159            let fill_chunk: usize = if crate::cache::swa_ring_on() {
13160                crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
13161            } else {
13162                // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
13163                // meaning one monolithic fill.
13164                std::env::var("MEMRA_PRIME_CHUNK")
13165                    .ok()
13166                    .and_then(|v| v.parse().ok())
13167                    .unwrap_or(4096)
13168            };
13169            let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
13170            let mut start = 0usize;
13171            while start < tp {
13172                let end = (start + fill_chunk).min(tp);
13173                let tc = end - start;
13174                {
13175                    // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
13176                    // reference engine's initial pending-h is zeroed too); a session turn's row 0
13177                    // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
13178                    // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
13179                    let mut phs = e.zeros(tc * n_embd)?;
13180                    let (src_lo, dst_off) = if start == 0 {
13181                        (0, n_embd)
13182                    } else {
13183                        ((start - 1) * n_embd, 0)
13184                    };
13185                    let n_copy = if start == 0 {
13186                        (tc - 1) * n_embd
13187                    } else {
13188                        tc * n_embd
13189                    };
13190                    if start == 0
13191                        && let Some((_, lh, _, _, _)) = sess_tail.as_ref()
13192                        && let Some(lh) = lh.as_ref()
13193                    {
13194                        e.copy_into(&mut phs, 0, lh, n_embd)?;
13195                    }
13196                    if n_copy > 0 {
13197                        e.copy_view_into(
13198                            &mut phs,
13199                            dst_off,
13200                            &ph.slice(src_lo..src_lo + n_copy),
13201                            n_copy,
13202                        )?;
13203                    }
13204                    self.mtp_kv_fill_all(
13205                        e,
13206                        &prompt[start..end],
13207                        &phs,
13208                        base + start,
13209                        &mut *scratch,
13210                        embd_dev,
13211                    )?;
13212                }
13213                start = end;
13214            }
13215        }
13216        // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
13217        // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
13218        // (=1 brackets the whole call in run_spec.rs, prime included.)
13219        if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
13220            unsafe extern "C" {
13221                fn cudaProfilerStart() -> i32;
13222            }
13223            unsafe {
13224                cudaProfilerStart();
13225            }
13226        }
13227        // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
13228        // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
13229        // consume each other's device outputs; the host drains the ring every M rounds. v1
13230        // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
13231        // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
13232        // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
13233        // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
13234        // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
13235        let stream_on = crate::spec::spec_stream()
13236            && !sampled
13237            && !spec_replay
13238            && self.mtp_extra.is_empty()
13239            && constraint.is_none()
13240            && !session_mode
13241            && embd_gpu.is_some()
13242            && !crate::model::full_prec_enabled()
13243            && k + 2 < 96;
13244        let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
13245        let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
13246        if stream_on {
13247            let cap = e.capture_graph(|e| {
13248                for j in 0..k.max(1) {
13249                    self.mtp_head_forward_cap(
13250                        e,
13251                        mtp,
13252                        &mut dctx.g_tok,
13253                        &mut dctx.g_pos,
13254                        &mut dctx.g_seed,
13255                        &mut dctx.g_p,
13256                        &mut *scratch,
13257                        0,
13258                        true,
13259                        true,
13260                        embd_gpu.expect("round stream requires resident embedding"),
13261                        embd_qt,
13262                        embd_rb,
13263                        d_vocab,
13264                        None,
13265                        Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
13266                        None, // round-stream requires constraint.is_none() (see stream_on)
13267                    )?;
13268                }
13269                Ok(())
13270            });
13271            match cap {
13272                Ok(g) => {
13273                    scratch.set_len(e, 0)?;
13274                    stream_graph = Some(g);
13275                }
13276                Err(err) => {
13277                    scratch.set_len(e, 0)?;
13278                    if debug_spec {
13279                        eprintln!("[spec] stream-graph capture failed ({err}); stream off");
13280                    }
13281                }
13282            }
13283        }
13284        let stream_active = stream_on && stream_graph.is_some();
13285        if debug_spec {
13286            eprintln!(
13287                "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
13288                crate::spec::spec_stream(),
13289                dctx.graph.is_some(),
13290                stream_graph.is_some()
13291            );
13292        }
13293        let t_v_s = k + 1;
13294        // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
13295        // module (extracted 2026-07-12; the gemma burst reuses them).
13296        let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
13297        let crate::round_stream::StreamBufs {
13298            mut vtok_d,
13299            mut brk_d,
13300            mut pend_d,
13301            last_pred_d,
13302            mut pos_ctr,
13303            mut pos_start_d,
13304            mut ring_d,
13305            acc_d: mut stream_acc,
13306            m_rounds,
13307            k: _,
13308        } = sb;
13309        let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
13310            Some(crate::round_stream::kv_len_ptr_table(
13311                e,
13312                cache,
13313                Some(&pos_ctr),
13314            )?)
13315        } else {
13316            None
13317        };
13318
13319        let t_fill = t_ent.elapsed();
13320        let mut round = 0usize;
13321        // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
13322        // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
13323        // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
13324        // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
13325        // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
13326        // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
13327        // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
13328        // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
13329        // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
13330        // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
13331        // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
13332        // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
13333        // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
13334        // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
13335        // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
13336        // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
13337        // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
13338        // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
13339        // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
13340        // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
13341        // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
13342        // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
13343        // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
13344        // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
13345        // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
13346        // K=1..8 self-consistency PASS both models with the law ON (exactness held).
13347        let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
13348        // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
13349        // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
13350        let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
13351            .ok()
13352            .and_then(|v| v.parse().ok());
13353        let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
13354            4
13355        } else if self.cfg.n_embd as usize >= 2500 {
13356            2
13357        } else {
13358            1
13359        };
13360        let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
13361        // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
13362        // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
13363        // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
13364        let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
13365            .ok()
13366            .and_then(|v| v.parse().ok())
13367            .unwrap_or(1024);
13368        let floor_at = |pos: usize| -> usize {
13369            if adapt_floor_env.is_some() || pos < floor_ctx {
13370                adapt_floor
13371            } else if adapt_floor >= 4 {
13372                1
13373            } else {
13374                adapt_floor
13375            }
13376        };
13377        // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
13378        // fixed-K default path is untouched by this whole block.
13379        let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
13380            .ok()
13381            .and_then(|v| v.parse().ok())
13382            .unwrap_or(7);
13383        let k_cap = k.min(cap_max).max(1);
13384        let mut kc = k_cap;
13385        let mut opti_fork: Option<OptiForkState> = None;
13386        let mut _opti_walk: Option<crate::pp::PpWalkLease> = None;
13387        let mut _opti_walk_borrow: Option<crate::pp::PpWalkBorrowGuard> = None;
13388        let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
13389        if fork_mode != OptiForkGateMode::Disabled {
13390            let fence = crate::pp::pp_cuts(self.layers.len());
13391            let refusal = if !session_mode {
13392                Some("not-session")
13393            } else if k != 1 || adapt {
13394                Some("requires-fixed-k1")
13395            } else if sampled || constraint.is_some() || spec_replay {
13396                Some("sampled-constrained-or-replay")
13397            } else if pipe.is_some() {
13398                Some("two-session-pipeline")
13399            } else if !spec_devacc() {
13400                Some("requires-device-accept")
13401            } else if stream_active || crate::spec::spec_stream() {
13402                Some("round-stream")
13403            } else if !self.mtp_extra.is_empty() {
13404                Some("multi-head-mtp")
13405            } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
13406                Some("swa-ring")
13407            } else if crate::pp::pp_host_bounce_active() {
13408                Some("host-bounce")
13409            } else if fork_mode == OptiForkGateMode::Controller
13410                && cache.recur.iter().any(Option::is_some)
13411            {
13412                Some("controller-requires-zero-recurrent-state")
13413            } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
13414                Some("requires-pp2")
13415            } else {
13416                None
13417            };
13418            if let Some(reason) = refusal {
13419                OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13420                eprintln!("[opti-fork] refused reason={reason}");
13421            } else {
13422                let fence = fence.expect("validated PP-2 fence");
13423                let rt = crate::pp::PpNRt::get(e)?;
13424                let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
13425                let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
13426                let primary_supported =
13427                    primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
13428                if !rt.cross_device() || !primary_supported {
13429                    OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13430                    eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
13431                } else {
13432                    // The optimistic controller can keep two boundary tickets in flight. Give
13433                    // every nested verify an explicit borrow of one whole-walk generation; no
13434                    // `pp_pipe` boolean is allowed to bypass ownership on its own.
13435                    let walk = rt.acquire_walk("opti_fork_coordinator")?;
13436                    let permit = rt.walk_permit(&walk, "opti_fork_coordinator")?;
13437                    let borrow = rt.borrow_walk(&permit, "opti_fork_coordinator")?;
13438                    // Both recurrent snapshots and both seed generations are allocated before
13439                    // the first fork, each through its owning PP stage. Allocation failure
13440                    // therefore happens before any optimistic state mutation can occur.
13441                    let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
13442                    let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
13443                    let fork = OptiForkState::new(
13444                        e,
13445                        cache,
13446                        fork_mode,
13447                        alternate_snapshot,
13448                        &h_seed_buf,
13449                        &fill_prev,
13450                        rt,
13451                        fence[1],
13452                        self.layers.len(),
13453                    )?;
13454                    eprintln!(
13455                        "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
13456                         payload_dev0={} payload_dev1={} q_threshold={:.3}",
13457                        fence[1],
13458                        fork.logical_payload_bytes[0],
13459                        fork.logical_payload_bytes[1],
13460                        fork.controller.map_or(0.0, |policy| policy.threshold),
13461                    );
13462                    fork_snapshot = Some(current_snapshot);
13463                    opti_fork = Some(fork);
13464                    _opti_walk = Some(walk);
13465                    _opti_walk_borrow = Some(borrow);
13466                }
13467            }
13468        }
13469        // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
13470        // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
13471        let mut snap = match fork_snapshot {
13472            Some(snapshot) => snapshot,
13473            None => cache.snapshot(e)?,
13474        };
13475        let mut carried_opti: Option<OptiControllerTicket> = None;
13476        // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
13477        // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
13478        let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
13479            Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
13480        } else {
13481            None
13482        };
13483        // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
13484        // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
13485        // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
13486        // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
13487        // pass of any kind). Verify still
13488        // checks every emitted token against the target -> exactness holds by construction; only
13489        // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
13490        // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
13491        // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
13492        let mut pending: Option<u32> = carried_pending;
13493        // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
13494        // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
13495        // the verify accept readback). Printed once at loop end via spec-stats.
13496        let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
13497        let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
13498        // MEMRA_SPEC_PHASE_SYNC=1 — reads the phase split correctly, and proves it. `ph_mark` is a
13499        // bare Instant, so `verify-issue` is the host QUEUEING the walk (the GPU is already running
13500        // under it) and `verify-wait` is only the residual drain at the accept readback: one
13501        // overlapped interval cut at the first blocking call, NOT "GPU time" beside "host time".
13502        // Syncing right after the walk is issued moves the whole GPU wall into `verify-issue`. If
13503        // the walk's GPU total is really issue+wait, then with this on verify-issue jumps to that
13504        // sum, verify-wait collapses to the readback alone, and the ROUND WALL DOES NOT MOVE —
13505        // which is what says the queueing time was hidden and is not a target. Diagnostic only.
13506        let phase_sync = std::env::var("MEMRA_SPEC_PHASE_SYNC").as_deref() == Ok("1");
13507        // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
13508        // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
13509        let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
13510        // grammar-truncation counters: how many rounds the verify-side cut fired and how many
13511        // already-verified tokens it threw away. THIS is the quantity draft masking targets.
13512        let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
13513        let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
13514        let mut ph_wait = 0f64;
13515        let mut ph_commit = 0f64;
13516        let mut ph_t = std::time::Instant::now();
13517        let mut ph_mark = |acc: &mut f64, on: bool| {
13518            if on {
13519                let now = std::time::Instant::now();
13520                *acc += (now - ph_t).as_secs_f64();
13521                ph_t = now;
13522            }
13523        };
13524        // MTP-ROUTE VERIFY GRAPHS (`MEMRA_SPEC_VERIFY_GRAPH`, see the flag doc): the
13525        // model-owned capture pool, locked for the whole burst exactly as the dspark serve
13526        // arm holds it — the slab stash is live verify -> commit inside a round, and the
13527        // worker drives rounds from one scheduler thread. PERSISTENT across generations on
13528        // the model (rebuilding per call re-captures the pool per prompt, which is the
13529        // measured way to lose more than the launches cost); the captured bodies are
13530        // cache-independent, every state read going through per-round refreshed pointer
13531        // tables. None = the eager walk, byte-identical.
13532        //
13533        // Never armed together with ROUND-STREAM: the tparallel verify refuses that pair
13534        // loudly, and `stream_active` owns the burst arm above, so the door stays shut
13535        // whenever the stream is live rather than relying on that refusal.
13536        // The lock is taken ONLY when the door is armed: with the flag off this whole block
13537        // is inert, so the default path cannot serialize two spec generations behind a mutex
13538        // it never reads.
13539        let vg_armed =
13540            crate::spec::spec_verify_graph_env().unwrap_or_else(|| self.vgraph_family_default());
13541        let mut vg_guard = if vg_armed && !stream_active {
13542            let mut g = self.dspark_vgraphs.lock().unwrap();
13543            if g.is_none() {
13544                // Size by the WIDEST verify this run can present, which is k+1 and NOT
13545                // k_cap+1: the sampled arm's own window is `t_v_s = k + 1`, so a pool built
13546                // from a smaller adaptive cap gets sliced past its stash rows (a `slice_mut`
13547                // panic in the sampled ON arm, measured before this line said k+1).
13548                let vt_cap = (k.max(k_cap) + 1).max(2);
13549                *g = DsparkVerifyGraphs::new(e, cache, vt_cap, n_embd)?;
13550                if g.is_some() {
13551                    // Engagement receipt (the dead-arm lesson): prove the door is LIVE rather
13552                    // than trusting that a flag set means a pool built.
13553                    eprintln!("[spec-vg] MTP verify-graph pool ENGAGED (vt_cap={vt_cap})");
13554                } else {
13555                    eprintln!(
13556                        "[spec-vg] MTP verify-graph pool declined (no linear layers, \
13557                         non-uniform state, or vt_cap < 2) — eager walk"
13558                    );
13559                }
13560            }
13561            Some(g)
13562        } else {
13563            None
13564        };
13565        // Capacity fail-safe: a round wider than the pool was built for must take the eager
13566        // walk, not slice the stash past its rows. The sizing above already covers every
13567        // round this run can present; this keeps a future caller (or a k that grows behind
13568        // the pool's back) on the byte-identical fallback instead of a panic.
13569        let vg_t_cap = vg_guard
13570            .as_ref()
13571            .and_then(|g| g.as_ref())
13572            .map(|g| g.t_capacity())
13573            .unwrap_or(0);
13574        if let Some(p) = pipe {
13575            p.setup_end();
13576        }
13577        drop(pipe_setup_walk);
13578        let mut graph_guard_noted = false;
13579        while keep_going && out.len() < max_new {
13580            // GRAPH-LAUNCH HEADROOM GUARD (see GRAPH_LAUNCH_MIN_FREE): below the floor,
13581            // every captured-graph arm in this round yields to its byte-identical eager
13582            // twin instead of feeding cuGraphLaunch a card it segfaults on.
13583            let graph_round_ok = graph_launch_headroom_ok(e);
13584            if !graph_round_ok && !graph_guard_noted {
13585                graph_guard_noted = true;
13586                eprintln!(
13587                    "[spec] graph replay suspended: driver free below the {}MB launch floor \
13588                     (eager arms serve; cuGraphLaunch segfaults into an exhausted card)",
13589                    GRAPH_LAUNCH_MIN_FREE / (1 << 20)
13590                );
13591            }
13592            // MEMRA_SPEC_ROUND_PROF=1: wall of the WHOLE round against the pieces we already
13593            // instrument. Needed because the parts do not add up: the draft step measures 1.27 ms
13594            // ([spec-anatomy] glue 92 / attn 280 / ffn 222 / head 670 us) and the t=2 verify walk
13595            // 25.6 ms ([tcol-prof] attn 10.1 + ffn 15.3), yet a K=1 round takes 177 ms on the
13596            // step37 TP2 stack. This prints where the other ~150 ms lives.
13597            let round_prof = ROUND_PROF
13598                .get_or_init(|| std::env::var("MEMRA_SPEC_ROUND_PROF").as_deref() == Ok("1"));
13599            let round_t0 = round_prof.then(std::time::Instant::now);
13600            // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
13601            // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
13602            if let (true, Some(sg), Some(ptrs)) = (
13603                stream_active && round >= 1 && pending.is_some() && graph_round_ok,
13604                &stream_graph,
13605                &stream_ptrs,
13606            ) {
13607                if debug_spec {
13608                    static ONCE: std::sync::Once = std::sync::Once::new();
13609                    ONCE.call_once(|| {
13610                        eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
13611                    });
13612                }
13613                e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
13614                e.set_u32_one(&mut pend_d, pending.unwrap())?;
13615                e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
13616                for _mi in 0..m_rounds {
13617                    e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
13618                    cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
13619                    e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
13620                    e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
13621                    e.u32_copy(&pend_d, &mut dctx.g_tok)?;
13622                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
13623                    sg.launch()?;
13624                    e.spec_assemble_verify(
13625                        &g_tokp2k,
13626                        &pend_d,
13627                        d2t_dev.as_ref(),
13628                        &mut vtok_d,
13629                        &mut brk_d,
13630                        p_min,
13631                        k,
13632                        pmin0,
13633                    )?;
13634                    let mut ck = VerifyCkpt::new(self.layers.len());
13635                    let dummy = vec![0u32; t_v_s];
13636                    let (tl_d, vx) = self.decode_step_t_core_stream(
13637                        e,
13638                        &dummy,
13639                        0,
13640                        &mut *cache,
13641                        embd_dev,
13642                        Some(&mut ck),
13643                        Some((&vtok_d, &pos_ctr)),
13644                        None,
13645                        None,
13646                        None,
13647                    )?;
13648                    for j in 0..t_v_s {
13649                        e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
13650                    }
13651                    e.spec_accept_greedy_dc(
13652                        &preds_d,
13653                        &vtok_d,
13654                        &last_pred_d,
13655                        &brk_d,
13656                        &mut stream_acc,
13657                    )?;
13658                    e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
13659                    e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
13660                    self.commit_verified_prefix_stream(
13661                        e,
13662                        &mut *cache,
13663                        &snap,
13664                        &ck,
13665                        &stream_acc,
13666                        1,
13667                        t_v_s,
13668                    )?;
13669                    e.spec_rollback_stream(
13670                        ptrs,
13671                        &pos_start_d,
13672                        &stream_acc,
13673                        1,
13674                        self.layers.len() + 1,
13675                    )?;
13676                    e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
13677                }
13678                e.stream().synchronize()?;
13679                let ring_h = e.dtoh_u32(&ring_d)?;
13680                let cnt = ring_h[0] as usize;
13681                for i in 0..cnt {
13682                    if out.len() < max_new {
13683                        out.push(ring_h[1 + i]);
13684                    }
13685                }
13686                let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
13687                for il in 0..self.layers.len() {
13688                    if let Some(kvl) = cache.kv[il].as_mut() {
13689                        kvl.len = pos_h;
13690                    }
13691                }
13692                cache.pos = pos_h;
13693                scratch.kv.len = pos_h;
13694                pending = Some(ring_h[cnt]); // last drained token = the live bonus
13695                last_token = ring_h[cnt];
13696                total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
13697                total_accepted += cnt.saturating_sub(m_rounds);
13698                if let Some(t) = sess_telem {
13699                    // totals only — the burst's per-round accept counts stayed on device
13700                    // (that is the point of the round-stream arm). pos_* untouched.
13701                    t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
13702                }
13703                round += m_rounds;
13704                // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
13705                keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
13706                continue;
13707            }
13708            let pipe_draft = match pipe {
13709                Some(p) => Some(p.draft_begin(round)?),
13710                None => None,
13711            };
13712            let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
13713            let mut current_opti = carried_opti.take();
13714            let mut fork_generation = if current_opti.is_none() && pending.is_some() {
13715                match opti_fork.as_mut() {
13716                    Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
13717                    None => None,
13718                    Some(_) => None,
13719                }
13720            } else {
13721                None
13722            };
13723            if current_opti.is_none() {
13724                if let Some(fork) = opti_fork.as_ref() {
13725                    opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
13726                } else {
13727                    cache.snapshot_into(e, &mut snap)?;
13728                }
13729            } else if snap.pos != pos {
13730                return Err(format!(
13731                    "optipipe carried snapshot pos {} != current pos {pos}",
13732                    snap.pos
13733                )
13734                .into());
13735            } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
13736            ph_mark(&mut ph_rest, phase_on);
13737
13738            // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
13739            // p-min semantics (both paths): stop the chain early when the head's confidence in
13740            // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
13741            // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
13742            let base0 = if pending.is_some() { 1usize } else { 0usize };
13743            // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
13744            // accepted run + 1 (the gemma law — see the setup block above the loop).
13745            let k_this = if adapt { kc } else { k };
13746            let mut draft: Vec<u32> = Vec::with_capacity(k);
13747            let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
13748            let mut controller_draft_prob: Option<f32> = None;
13749            let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
13750            if let Some(ticket) = current_opti.as_mut() {
13751                let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
13752                if ticket.verify_tokens[0] != carried_pending {
13753                    return Err(format!(
13754                        "optipipe carried pending mismatch: ticket={} live={carried_pending}",
13755                        ticket.verify_tokens[0],
13756                    )
13757                    .into());
13758                }
13759                draft.push(ticket.verify_tokens[1]);
13760                controller_draft_prob = Some(ticket.draft_prob);
13761                controller_eager_state = ticket
13762                    .take_eager_seed()
13763                    .map(|seed| (ticket.verify_tokens[1], seed));
13764            } else {
13765                // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
13766                // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
13767                // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
13768                // rejected drafts and p-min extras via the len mechanism).
13769                scratch.set_len(e, pos + base0 - 1)?;
13770                // dcw door: a captured chain appends k_this device-counter rows (plus the
13771                // pseudo-seed replay) with no host intervention; any ring rebase those appends
13772                // could need happens HERE, host-side, before the replays. The eager arm keeps
13773                // its own per-step prepare, so this is graph-path-only work.
13774                if step35_draft_dcw_on()
13775                    && (dctx.graph.is_some()
13776                        || dctx.graph_s.is_some()
13777                        || dctx.chain.is_some()
13778                        || dctx.chain_s.is_some())
13779                {
13780                    scratch.ensure_dcw_headroom(e, k_this + 2)?;
13781                }
13782                if pen_on {
13783                    // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
13784                    // device dedup: the serve window is already PEN_WINDOW_MAX, and this
13785                    // defensive min also bounds non-server callers.
13786                    let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
13787                    let w0 = pen_hist.len().saturating_sub(win);
13788                    pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
13789                }
13790                if sampled {
13791                    draft_logits.clear();
13792                    draft_stats.clear();
13793                }
13794                // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
13795                // position's mask is computed on that clone and advanced by the PROPOSED token. The
13796                // real state moves only on emission (verify's job), so the emitted stream is
13797                // unchanged — the mask only removes tokens the verify would have truncated anyway.
13798                let mut dmask_live = dmask_on;
13799                if dmask_live {
13800                    let t_c = std::time::Instant::now();
13801                    constraint
13802                        .as_deref_mut()
13803                        .unwrap()
13804                        .draft_begin()
13805                        .map_err(|e2| format!("constraint: {e2}"))?;
13806                    dm_clone_ns += t_c.elapsed().as_nanos();
13807                    dm_rounds += 1;
13808                }
13809                if let (false, Some(cg)) = (sampled || pen_on || !graph_round_ok, &dctx.chain) {
13810                    // GREEDY CHAIN GRAPH (lane/step37-draft-graph-serving-20260830): the
13811                    // eager multi-head chain's EXACT launch order — step j rewinds head
13812                    // (j % heads)'s plane to the committed length and replays rows 0..=j —
13813                    // with each row's whole head-forward as ONE graph launch. The chain
13814                    // POLICY (head choice, prefix length, stored-seed feed) is host-side,
13815                    // identical to `mtp_chain_forward_dev`, so graph-vs-eager drafts are
13816                    // bit-identical by construction (same launcher, same bucket — the dcw
13817                    // parity contract). Interior rows launch the head-less graph: their
13818                    // logits are dead in the eager chain too, so the consumed bytes match.
13819                    let heads_n = self.mtp_head_count();
13820                    let committed = pos + base0 - 1;
13821                    let mut chain_tokens: Vec<u32> = vec![last_token];
13822                    let mut chain_seed_bufs: Vec<CudaSlice<f32>> = vec![e.clone_dtod(&h_seed_buf)?];
13823                    for j in 0..k_this {
13824                        let index = mtp_chain_head_index(j, heads_n);
13825                        if debug_spec {
13826                            eprintln!(
13827                                "[mtp-chain-step] round={round} j={j} head={index} \
13828                                 replay_rows={} arm=graph",
13829                                chain_tokens.len(),
13830                            );
13831                        }
13832                        scratch.set_plane_len(e, index, committed)?;
13833                        e.set_i32_one(&mut dctx.g_pos, (committed + 1) as i32)?;
13834                        for row in 0..=j {
13835                            e.set_u32_one(&mut dctx.g_tok, chain_tokens[row])?;
13836                            e.copy_into(&mut dctx.g_seed, 0, &chain_seed_bufs[row], n_embd)?;
13837                            if row < j {
13838                                cg.interior[index].launch()?;
13839                            } else {
13840                                // per-position mask upload before the LAST row only — the
13841                                // eager chain applies the mask on is_last exactly the same.
13842                                if dmask_live
13843                                    && !upload_draft_mask(
13844                                        e,
13845                                        constraint.as_deref_mut().unwrap(),
13846                                        &mut dctx.g_dmask,
13847                                        mtp.d2t.as_ref(),
13848                                        d_vocab,
13849                                        dmask_words,
13850                                    )?
13851                                {
13852                                    e.htod_u32_into(
13853                                        &mut dctx.g_dmask,
13854                                        &vec![u32::MAX; dmask_words],
13855                                    )?;
13856                                    dmask_live = false;
13857                                }
13858                                cg.last[index].launch()?;
13859                            }
13860                            // host mirror (len_d advanced in-graph by the dcw append)
13861                            scratch.plane_mut(index).0.len += 1;
13862                        }
13863                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
13864                        // #87 SENTINEL TRAP (see the single-head graph arm below).
13865                        if (idx as usize) >= d_vocab {
13866                            let seed_h = e.dtoh(&dctx.g_seed)?;
13867                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
13868                            return Err(format!(
13869                                "draft(chain-graph) argmax sentinel 0x{idx:08x} >= d_vocab \
13870                             {d_vocab} at round {round} j={j} head={index} pos={pos}: \
13871                             head-out NaN {seed_nan}/{n_embd} — refusing to dereference \
13872                             the embed row (#87 trap)"
13873                            )
13874                            .into());
13875                        }
13876                        // multi-head MTP forbids a trimmed head (validated at entry), so the
13877                        // draft index IS the target id; keep the map for uniformity.
13878                        let d = match &mtp.d2t {
13879                            Some(map) => map[idx as usize],
13880                            None => idx,
13881                        };
13882                        let draft_p = if p_min > 0.0 {
13883                            Some(e.dtoh(&dctx.g_p)?[0])
13884                        } else {
13885                            None
13886                        };
13887                        if j == 0 {
13888                            controller_draft_prob = draft_p;
13889                        }
13890                        if let Some(p) = draft_p.filter(|_| p_min > 0.0)
13891                            && p < p_min
13892                            && (j > 0 || (pmin0 && base0 == 1))
13893                        {
13894                            break;
13895                        }
13896                        draft.push(d);
13897                        chain_tokens.push(d);
13898                        // step j's h_nextn: the last-row graph self-fed it into g_seed —
13899                        // snapshot it as the chain history seed for row j+1 (stream-ordered
13900                        // after the launch, exactly the eager chain's chain_seeds push).
13901                        chain_seed_bufs.push(e.clone_dtod(&dctx.g_seed)?);
13902                        // speculative grammar advance (see the single-head graph arm).
13903                        if dmask_live
13904                            && !constraint
13905                                .as_deref_mut()
13906                                .unwrap()
13907                                .draft_advance(d)
13908                                .map_err(|e2| format!("constraint: {e2}"))?
13909                        {
13910                            e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
13911                            break;
13912                        }
13913                    }
13914                } else if let (true, Some(cg)) = (
13915                    sampled && s_capturable && dctx.s_key == Some(s_key) && graph_round_ok,
13916                    &dctx.chain_s,
13917                ) {
13918                    if skey_probe() {
13919                        eprintln!(
13920                            "[skey] chain=graph_chain_s round={round} capturable={} top_k={} \
13921                             top_p={} min_p={} s_key_parked={:?}",
13922                            s_capturable as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
13923                        );
13924                    }
13925                    // SAMPLED CHAIN GRAPH: the greedy chain arm's launch order with the
13926                    // sampled last-row graphs — in-graph counter bump + (filtered) gumbel
13927                    // draw + argmax; q retained per step into q_slots exactly like the
13928                    // single-head sampled graph arm. Counter continuity: g_ctr host-seeded
13929                    // to sctr-1 once per ROUND; each step's last-row graph bumps it BEFORE
13930                    // the perturb, so step j consumes counter sctr+j — the eager Philox
13931                    // stream (interior rows never draw, never bump).
13932                    let heads_n = self.mtp_head_count();
13933                    let committed = pos + base0 - 1;
13934                    let filtered_stats_in_graph = s_key.filtered();
13935                    let mut chain_tokens: Vec<u32> = vec![last_token];
13936                    let mut chain_seed_bufs: Vec<CudaSlice<f32>> = vec![e.clone_dtod(&h_seed_buf)?];
13937                    e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
13938                    for j in 0..k_this {
13939                        let index = mtp_chain_head_index(j, heads_n);
13940                        if debug_spec {
13941                            eprintln!(
13942                                "[mtp-chain-step] round={round} j={j} head={index} \
13943                                 replay_rows={} arm=graph_s",
13944                                chain_tokens.len(),
13945                            );
13946                        }
13947                        scratch.set_plane_len(e, index, committed)?;
13948                        e.set_i32_one(&mut dctx.g_pos, (committed + 1) as i32)?;
13949                        for row in 0..=j {
13950                            e.set_u32_one(&mut dctx.g_tok, chain_tokens[row])?;
13951                            e.copy_into(&mut dctx.g_seed, 0, &chain_seed_bufs[row], n_embd)?;
13952                            if row < j {
13953                                cg.interior[index].launch()?;
13954                            } else {
13955                                cg.last[index].launch()?;
13956                            }
13957                            scratch.plane_mut(index).0.len += 1;
13958                        }
13959                        sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
13960                        // counts the p-min-discarded token too)
13961                        // q retention: ONE async D2D of the persistent head-logits buffer
13962                        // into this round's slot j (stream-ordered after the replay).
13963                        e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
13964                        // FILTERED capture: read the in-graph filter_stats scalars back per
13965                        // replay instead of a second full-vocab filter_stats per slot post-
13966                        // chain — bit-exact (the values the in-graph perturb consumed) and
13967                        // measured worth ~5% of vendor-default serving tok/s at K=3. Before
13968                        // the p-min break so the discarded slot's stats land too.
13969                        if filtered_stats_in_graph {
13970                            draft_stats.push((
13971                                e.dtoh(&dctx.g_mx)?[0],
13972                                e.dtoh(&dctx.g_th)?[0],
13973                                e.dtoh(&dctx.g_z)?[0],
13974                            ));
13975                        }
13976                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
13977                        // #87 SENTINEL TRAP (see the single-head graph arms).
13978                        if (idx as usize) >= d_vocab {
13979                            let seed_h = e.dtoh(&dctx.g_seed)?;
13980                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
13981                            return Err(format!(
13982                                "draft(chain-graph-sampled) argmax sentinel 0x{idx:08x} >= \
13983                             d_vocab {d_vocab} at round {round} j={j} head={index} pos={pos}: \
13984                             head-out NaN {seed_nan}/{n_embd} — refusing to dereference the \
13985                             embed row (#87 trap)"
13986                            )
13987                            .into());
13988                        }
13989                        let d = match &mtp.d2t {
13990                            Some(map) => map[idx as usize],
13991                            None => idx,
13992                        };
13993                        draft_idx.push(idx);
13994                        if p_min > 0.0 {
13995                            let p = e.dtoh(&dctx.g_p)?[0];
13996                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
13997                                break;
13998                            }
13999                        }
14000                        draft.push(d);
14001                        chain_tokens.push(d);
14002                        chain_seed_bufs.push(e.clone_dtod(&dctx.g_seed)?);
14003                    }
14004                    // PURE-TEMP accept path: stats per used slot recomputed from the RETAINED
14005                    // q with the SAME filter_stats program the eager arm runs (deployment-
14006                    // keyed coop/plain choice, same input bits). The FILTERED graph read its
14007                    // stats back per replay above.
14008                    if !filtered_stats_in_graph {
14009                        for j in 0..draft.len().max(draft_idx.len()) {
14010                            let rows0 = e.htod_i32(&[0])?;
14011                            let (mut th_d, mut z_d, mut mx_d) =
14012                                (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
14013                            e.filter_stats(
14014                                &dctx.q_slots[j],
14015                                d_vocab,
14016                                &rows0,
14017                                &mut th_d,
14018                                &mut z_d,
14019                                &mut mx_d,
14020                                d_vocab,
14021                                1,
14022                                sp_temp,
14023                                sp.top_k,
14024                                sp.top_p,
14025                                sp.min_p,
14026                            )?;
14027                            draft_stats.push((
14028                                e.dtoh(&mx_d)?[0],
14029                                e.dtoh(&th_d)?[0],
14030                                e.dtoh(&z_d)?[0],
14031                            ));
14032                        }
14033                    }
14034                } else if let (false, Some(gr)) =
14035                    (sampled || pen_on || !graph_round_ok, &dctx.graph)
14036                {
14037                    // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
14038                    // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
14039                    // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
14040                    e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
14041                    e.set_u32_one(&mut dctx.g_tok, last_token)?;
14042                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
14043                    for j in 0..k_this {
14044                        // per-position mask upload (contents only — the graph's baked pointer is
14045                        // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
14046                        // mask node degrades to a no-op ban instead of needing a second graph.
14047                        if dmask_live
14048                            && !upload_draft_mask(
14049                                e,
14050                                constraint.as_deref_mut().unwrap(),
14051                                &mut dctx.g_dmask,
14052                                mtp.d2t.as_ref(),
14053                                d_vocab,
14054                                dmask_words,
14055                            )?
14056                        {
14057                            // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
14058                            // genuinely miss the legal set): neutralize the captured mask node and
14059                            // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
14060                            e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
14061                            dmask_live = false;
14062                        }
14063                        gr.launch()?;
14064                        scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
14065                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
14066                        // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
14067                        // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
14068                        // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
14069                        // replay's embed node, and the MMU fault kills the CUDA context for the
14070                        // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
14071                        // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
14072                        // buffer (g_seed = the verify-side handoff vs head-side compute).
14073                        if (idx as usize) >= d_vocab {
14074                            // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
14075                            // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
14076                            // seed, untouched since the round-start copy — the pair discriminates
14077                            // "seed arrived poisoned" from "head forward produced NaN".
14078                            let seed_h = e.dtoh(&dctx.g_seed)?;
14079                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
14080                            let in_h = e.dtoh(&h_seed_buf)?;
14081                            let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
14082                            return Err(format!(
14083                                "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
14084                             round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
14085                             round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
14086                             the embed row (#87 trap)"
14087                            )
14088                            .into());
14089                        }
14090                        // trimmed draft vocab -> target token id (identity when no d2t map)
14091                        let d = match &mtp.d2t {
14092                            Some(map) => map[idx as usize],
14093                            None => idx,
14094                        };
14095                        let draft_p = if p_min > 0.0
14096                            || opti_fork
14097                                .as_ref()
14098                                .is_some_and(|fork| fork.controller.is_some())
14099                        {
14100                            Some(e.dtoh(&dctx.g_p)?[0])
14101                        } else {
14102                            None
14103                        };
14104                        if j == 0 {
14105                            controller_draft_prob = draft_p;
14106                        }
14107                        if let Some(p) = draft_p.filter(|_| p_min > 0.0)
14108                            && p < p_min
14109                            && (j > 0 || (pmin0 && base0 == 1))
14110                        {
14111                            break;
14112                        }
14113                        draft.push(d);
14114                        // with a trimmed head the NEXT embed must read the TARGET id, not the draft
14115                        // index the argmax wrote — patch the persistent token buffer (4B htod).
14116                        if d != idx {
14117                            e.set_u32_one(&mut dctx.g_tok, d)?;
14118                        }
14119                        // advance the SPECULATIVE state with the proposal; a dead chain drops to
14120                        // unmasked drafting for the remaining positions (verify still arbitrates).
14121                        // speculative advance; a chain the grammar can no longer follow (EOS
14122                        // proposed) ends here. The captured mask node always runs, so a dead chain
14123                        // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
14124                        if dmask_live
14125                            && !constraint
14126                                .as_deref_mut()
14127                                .unwrap()
14128                                .draft_advance(d)
14129                                .map_err(|e2| format!("constraint: {e2}"))?
14130                        {
14131                            e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
14132                            break;
14133                        }
14134                    }
14135                // REGIME RE-TEST (lane/graph-s-key-exactness-20260819, widened by
14136                // lane/step37-draft-graph-serving-20260830): the sampled graph is legal ONLY
14137                // in the regime it was captured in. The condition used to read
14138                // `(sampled, &dctx.graph_s)` and trusted `s_key` to have dropped anything
14139                // else — which it could not, because the key omitted the filters. Both
14140                // halves are enforced: the key drops a stale graph, and this site refuses to
14141                // launch one whose key differs or whose regime is uncapturable (penalties).
14142                } else if let (true, Some(gr)) = (
14143                    sampled && s_capturable && dctx.s_key == Some(s_key) && graph_round_ok,
14144                    &dctx.graph_s,
14145                ) {
14146                    if skey_probe() {
14147                        eprintln!(
14148                            "[skey] chain=graph_s round={round} pure_temp={} capturable={} \
14149                             top_k={} top_p={} min_p={} s_key_parked={:?}",
14150                            pure_temp as u8,
14151                            s_capturable as u8,
14152                            sp.top_k,
14153                            sp.top_p,
14154                            sp.min_p,
14155                            dctx.s_key,
14156                        );
14157                    }
14158                    // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
14159                    // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
14160                    // and decides the break. Event-counter continuity: g_ctr is host-seeded to
14161                    // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
14162                    // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
14163                    // stream. Host sctr advances in lockstep (computed, no readback needed).
14164                    e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
14165                    e.set_u32_one(&mut dctx.g_tok, last_token)?;
14166                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
14167                    e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
14168                    let filtered_stats_in_graph = s_key.filtered();
14169                    for j in 0..k_this {
14170                        gr.launch()?;
14171                        scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
14172                        sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
14173                        // counts the p-min-discarded token too)
14174                        // q retention: ONE async D2D of the persistent head-logits buffer into this
14175                        // round's slot j (stream-ordered after the replay, before the next one).
14176                        e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
14177                        // FILTERED capture: the replay's own filter_stats node already computed
14178                        // (th, z, mx) — read the three scalars back instead of paying a SECOND
14179                        // full-vocab filter_stats per slot post-chain (measured ~5% of vendor-
14180                        // default serving tok/s at K=3). Bit-exact by construction: these are
14181                        // the very values the in-graph perturb consumed. Read BEFORE the p-min
14182                        // break so the discarded slot's stats land too (accept-path indexing).
14183                        if filtered_stats_in_graph {
14184                            draft_stats.push((
14185                                e.dtoh(&dctx.g_mx)?[0],
14186                                e.dtoh(&dctx.g_th)?[0],
14187                                e.dtoh(&dctx.g_z)?[0],
14188                            ));
14189                        }
14190                        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
14191                        // #87 SENTINEL TRAP (see the greedy graph arm above).
14192                        if (idx as usize) >= d_vocab {
14193                            let seed_h = e.dtoh(&dctx.g_seed)?;
14194                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
14195                            return Err(format!(
14196                                "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
14197                             {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
14198                             {seed_nan}/{n_embd} — refusing to dereference the embed row \
14199                             (#87 trap)"
14200                            )
14201                            .into());
14202                        }
14203                        let d = match &mtp.d2t {
14204                            Some(map) => map[idx as usize],
14205                            None => idx,
14206                        };
14207                        draft_idx.push(idx);
14208                        if p_min > 0.0 {
14209                            let p = e.dtoh(&dctx.g_p)?[0];
14210                            if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
14211                                break;
14212                            }
14213                        }
14214                        draft.push(d);
14215                        // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
14216                        if d != idx {
14217                            e.set_u32_one(&mut dctx.g_tok, d)?;
14218                        }
14219                    }
14220                    // PURE-TEMP accept path: fill draft_stats per used slot post-chain (the
14221                    // stats degenerate to th=0 / full-Z; one filter_stats launch per slot).
14222                    // The FILTERED graph read its stats back per replay above.
14223                    if !filtered_stats_in_graph {
14224                        for j in 0..draft.len().max(draft_idx.len()) {
14225                            let rows0 = e.htod_i32(&[0])?;
14226                            let (mut th_d, mut z_d, mut mx_d) =
14227                                (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
14228                            e.filter_stats(
14229                                &dctx.q_slots[j],
14230                                d_vocab,
14231                                &rows0,
14232                                &mut th_d,
14233                                &mut z_d,
14234                                &mut mx_d,
14235                                d_vocab,
14236                                1,
14237                                sp_temp,
14238                                sp.top_k,
14239                                sp.top_p,
14240                                sp.min_p,
14241                            )?;
14242                            draft_stats.push((
14243                                e.dtoh(&mx_d)?[0],
14244                                e.dtoh(&th_d)?[0],
14245                                e.dtoh(&z_d)?[0],
14246                            ));
14247                        }
14248                    }
14249                } else {
14250                    if skey_probe() && sampled {
14251                        eprintln!(
14252                            "[skey] chain=eager round={round} pure_temp={} top_k={} \
14253                             top_p={} min_p={} s_key_parked={:?}",
14254                            pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
14255                        );
14256                    }
14257                    // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
14258                    let chain_heads = !self.mtp_extra.is_empty();
14259                    let mut e_tok = last_token;
14260                    let mut d_seed = e.clone_dtod(&h_seed_buf)?;
14261                    let mut chain_tokens = if chain_heads {
14262                        vec![last_token]
14263                    } else {
14264                        Vec::new()
14265                    };
14266                    let mut chain_seeds = if chain_heads {
14267                        vec![e.clone_dtod(&h_seed_buf)?]
14268                    } else {
14269                        Vec::new()
14270                    };
14271                    for j in 0..k_this {
14272                        // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
14273                        // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
14274                        let mtp_pos = pos + base0 + j;
14275                        // draft-side grammar mask (eager twin of the graph arm's in-graph node).
14276                        // A position with no legal draft-vocab row drops to unmasked drafting for
14277                        // the rest of the chain (pre-lane behaviour; verify still arbitrates).
14278                        if dmask_live {
14279                            dmask_live = upload_draft_mask(
14280                                e,
14281                                constraint.as_deref_mut().unwrap(),
14282                                &mut dctx.g_dmask,
14283                                mtp.d2t.as_ref(),
14284                                d_vocab,
14285                                dmask_words,
14286                            )?;
14287                        }
14288                        let mask = if dmask_live {
14289                            Some((&dctx.g_dmask, dmask_words))
14290                        } else {
14291                            None
14292                        };
14293                        let (dl_d, h_nextn) = if chain_heads {
14294                            if debug_spec {
14295                                eprintln!(
14296                                    "[mtp-chain-step] round={round} j={j} head={} replay_rows={}",
14297                                    mtp_chain_head_index(j, self.mtp_head_count()),
14298                                    chain_tokens.len(),
14299                                );
14300                            }
14301                            self.mtp_chain_forward_dev(
14302                                e,
14303                                &chain_tokens,
14304                                &chain_seeds,
14305                                &mut *scratch,
14306                                pos + base0 - 1,
14307                                embd_dev,
14308                                mask,
14309                            )?
14310                        } else {
14311                            self.mtp_head_forward_dev(
14312                                e,
14313                                mtp,
14314                                e_tok,
14315                                &d_seed,
14316                                &mut *scratch,
14317                                mtp_pos,
14318                                embd_dev,
14319                                mask,
14320                            )?
14321                        };
14322                        let tok_d = if sampled {
14323                            // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
14324                            // the filtered softmax (filters off => th=0, exact v1 semantics).
14325                            if perturb_buf.is_none() {
14326                                perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
14327                            }
14328                            let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
14329                            if pen_on {
14330                                let h = pen_hist_d.as_ref().unwrap();
14331                                let nh = h.len();
14332                                e.penalize_logits(
14333                                    &mut q_row,
14334                                    h,
14335                                    nh,
14336                                    sp.penalty_repeat,
14337                                    sp.penalty_freq,
14338                                    sp.penalty_present,
14339                                    d_vocab,
14340                                )?;
14341                            }
14342                            let rows0 = e.htod_i32(&[0])?;
14343                            let (mut th_d, mut z_d, mut mx_d) =
14344                                (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
14345                            e.filter_stats(
14346                                &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
14347                                1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
14348                            )?;
14349                            let (th, z, mx) =
14350                                (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
14351                            let pb = perturb_buf.as_mut().unwrap();
14352                            e.gumbel_perturb_filtered(
14353                                &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
14354                            )?;
14355                            sctr += 1;
14356                            draft_logits.push(q_row);
14357                            draft_stats.push((mx, th, z));
14358                            e.argmax_token_device(pb, d_vocab)?
14359                        } else {
14360                            e.argmax_token_device(&dl_d, d_vocab)?
14361                        };
14362                        let idx = e.dtoh_u32_one(&tok_d)?;
14363                        // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
14364                        // here because the eager chain's operands are all readable: dl_d (the head
14365                        // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
14366                        if (idx as usize) >= d_vocab {
14367                            let dl_h = e.dtoh(&dl_d)?;
14368                            let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
14369                            let seed_h = if chain_heads {
14370                                e.dtoh(chain_seeds.last().unwrap())?
14371                            } else {
14372                                e.dtoh(&d_seed)?
14373                            };
14374                            let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
14375                            return Err(format!(
14376                                "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
14377                             round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
14378                             step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
14379                             embed row (#87 trap)"
14380                            )
14381                            .into());
14382                        }
14383                        let d = match &mtp.d2t {
14384                            Some(map) => map[idx as usize],
14385                            None => idx,
14386                        };
14387                        if sampled {
14388                            draft_idx.push(idx);
14389                        }
14390                        let draft_p = if p_min > 0.0
14391                            || opti_fork
14392                                .as_ref()
14393                                .is_some_and(|fork| fork.controller.is_some())
14394                        {
14395                            let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
14396                            Some(e.dtoh(&p_d)?[0])
14397                        } else {
14398                            None
14399                        };
14400                        if j == 0 {
14401                            controller_draft_prob = draft_p;
14402                        }
14403                        if let Some(p) = draft_p.filter(|_| p_min > 0.0)
14404                            && p < p_min
14405                            && (j > 0 || (pmin0 && base0 == 1))
14406                        {
14407                            break;
14408                        }
14409                        draft.push(d);
14410                        if chain_heads {
14411                            chain_tokens.push(d);
14412                            chain_seeds.push(h_nextn);
14413                        } else {
14414                            e_tok = d;
14415                            d_seed = h_nextn;
14416                        }
14417                        // speculative advance; a chain the grammar can no longer follow (EOS
14418                        // proposed) ends here — the prefix already proposed still rides verify.
14419                        if dmask_live
14420                            && !constraint
14421                                .as_deref_mut()
14422                                .unwrap()
14423                                .draft_advance(d)
14424                                .map_err(|e2| format!("constraint: {e2}"))?
14425                        {
14426                            break;
14427                        }
14428                    }
14429                    if !chain_heads
14430                        && opti_fork
14431                            .as_ref()
14432                            .is_some_and(|fork| fork.controller.is_some())
14433                    {
14434                        controller_eager_state = Some((e_tok, d_seed));
14435                    }
14436                }
14437            }
14438            let k_round = draft.len();
14439            if let Some(p) = pipe {
14440                p.draft_end(round);
14441            }
14442            drop(pipe_draft);
14443
14444            ph_mark(&mut ph_draft, phase_on);
14445            // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
14446            //         (committing its KV/recur inside the SAME weight read); drafts follow. ---
14447            let verify_tokens: Vec<u32> = match pending {
14448                Some(b) => {
14449                    let mut v = Vec::with_capacity(k_round + 1);
14450                    v.push(b);
14451                    v.extend_from_slice(&draft);
14452                    v
14453                }
14454                None => draft.clone(),
14455            };
14456            let base = if pending.is_some() { 1 } else { 0 };
14457            // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
14458            // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
14459            let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
14460                Some(ticket.take_ckpt())
14461            } else if spec_replay {
14462                None
14463            } else {
14464                Some(VerifyCkpt::new(self.layers.len()))
14465            };
14466            let controller_can_probe = base == 1
14467                && k_round == 1
14468                && out.len().saturating_add(2) < max_new
14469                && controller_draft_prob.is_some()
14470                && opti_fork
14471                    .as_ref()
14472                    .and_then(|fork| fork.controller.as_ref())
14473                    .is_some_and(|policy| !policy.breaker_tripped);
14474            let mut successor_attempt: Option<OptiControllerTicket> = None;
14475            let mut rejected_probe: Option<(f32, u32)> = None;
14476            let mut controller_prepared: Option<OptiControllerPrepared> = None;
14477            if controller_can_probe {
14478                // Prepare d2/q and, on admission, d3 before either current verify half is
14479                // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
14480                // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
14481                // the primary stream after N stage 1 would serialize the supposed pipeline.
14482                let eager_pos = scratch.kv.len + 1;
14483                let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
14484                    e,
14485                    mtp,
14486                    &mut dctx,
14487                    &mut *scratch,
14488                    d_vocab,
14489                    &mut controller_eager_state,
14490                    eager_pos,
14491                    embd_dev,
14492                    graph_round_ok,
14493                )?;
14494                let first_probability = controller_draft_prob
14495                    .ok_or("optipipe controller probe lost first-token probability")?;
14496                let q_proxy = first_probability * pending_probability;
14497                OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14498                OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14499                let admitted = opti_fork
14500                    .as_ref()
14501                    .and_then(|fork| fork.controller.as_ref())
14502                    .ok_or("optipipe controller policy disappeared")?
14503                    .admit(q_proxy);
14504                if admitted {
14505                    OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14506                    let eager_pos = scratch.kv.len + 1;
14507                    let (optimistic_draft, optimistic_draft_probability) = self
14508                        .opti_controller_draft_step(
14509                            e,
14510                            mtp,
14511                            &mut dctx,
14512                            &mut *scratch,
14513                            d_vocab,
14514                            &mut controller_eager_state,
14515                            eager_pos,
14516                            embd_dev,
14517                            graph_round_ok,
14518                        )?;
14519                    OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14520                    let eager_seed = controller_eager_state.take().map(|(token, seed)| {
14521                        debug_assert_eq!(token, optimistic_draft);
14522                        seed
14523                    });
14524                    controller_prepared = Some(OptiControllerPrepared {
14525                        verify_tokens: [optimistic_pending, optimistic_draft],
14526                        draft_prob: optimistic_draft_probability,
14527                        eager_seed,
14528                        q_proxy,
14529                        scratch_len: scratch.kv.len,
14530                    });
14531                } else {
14532                    OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14533                    OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14534                    rejected_probe = Some((q_proxy, optimistic_pending));
14535                    eprintln!(
14536                        "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
14537                        opti_fork
14538                            .as_ref()
14539                            .and_then(|fork| fork.controller.as_ref())
14540                            .expect("controller policy")
14541                            .threshold,
14542                    );
14543                }
14544            }
14545            let fork_attempt = match fork_generation.take() {
14546                Some(generation) if base == 1 && k_round == 1 => Some(generation),
14547                Some(generation) => {
14548                    opti_fork
14549                        .as_mut()
14550                        .expect("fork generation without fork state")
14551                        .retire(generation)?;
14552                    None
14553                }
14554                None => None,
14555            };
14556            let (tlogits_d, vx) = if let Some(p) = pipe {
14557                self.decode_step_t_core_pipelined(
14558                    e,
14559                    &verify_tokens,
14560                    pos,
14561                    &mut *cache,
14562                    embd_dev,
14563                    ckpt.as_mut(),
14564                    p,
14565                    round,
14566                )?
14567            } else if controller_can_probe {
14568                let fence = opti_fork
14569                    .as_ref()
14570                    .ok_or("optipipe controller probe lost fork state")?
14571                    .fence;
14572                let boundary = match current_opti.as_mut() {
14573                    Some(ticket) => ticket.take_boundary(),
14574                    None => self.verify_stage0_issue(
14575                        e,
14576                        &verify_tokens,
14577                        pos,
14578                        &mut *cache,
14579                        embd_dev,
14580                        ckpt.as_mut(),
14581                        None,
14582                        &fence,
14583                        Some(true),
14584                        None,
14585                    )?,
14586                };
14587                if let Some(prepared) = controller_prepared.take() {
14588                    let generation = {
14589                        let fork = opti_fork
14590                            .as_mut()
14591                            .ok_or("optipipe controller admission lost fork state")?;
14592                        let generation = fork.reserve_successor()?;
14593                        let rt = fork.rt;
14594                        let snapshot_fence = fork.fence;
14595                        opti_snapshot_one_stage_owned_into(
14596                            e,
14597                            cache,
14598                            rt,
14599                            &snapshot_fence,
14600                            0,
14601                            fork.successor_snapshot_mut(),
14602                        )?;
14603                        generation
14604                    };
14605                    let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
14606                    let successor_boundary = self.verify_stage0_issue(
14607                        e,
14608                        &prepared.verify_tokens,
14609                        pos + verify_tokens.len(),
14610                        &mut *cache,
14611                        embd_dev,
14612                        Some(&mut successor_ckpt),
14613                        None,
14614                        &fence,
14615                        Some(false),
14616                        None,
14617                    )?;
14618                    OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14619                    let fork = opti_fork
14620                        .as_ref()
14621                        .ok_or("optipipe controller ticket lost fork state")?;
14622                    successor_attempt = Some(fork.controller_ticket(
14623                        generation,
14624                        successor_boundary,
14625                        successor_ckpt,
14626                        prepared.verify_tokens,
14627                        prepared.draft_prob,
14628                        prepared.eager_seed,
14629                        prepared.q_proxy,
14630                        prepared.scratch_len,
14631                    ));
14632                    eprintln!(
14633                        "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
14634                         verify={:?}",
14635                        generation.id,
14636                        prepared.q_proxy,
14637                        fork.controller.expect("controller policy").threshold,
14638                        prepared.verify_tokens,
14639                    );
14640                }
14641                let result = self.verify_stage1_finish(
14642                    e,
14643                    boundary,
14644                    &mut *cache,
14645                    ckpt.as_mut(),
14646                    None,
14647                    &fence,
14648                    successor_attempt.is_none(),
14649                )?;
14650                if let Some(ticket) = current_opti.as_mut() {
14651                    ticket.settle();
14652                }
14653                if successor_attempt.is_some() {
14654                    let fork = opti_fork
14655                        .as_mut()
14656                        .ok_or("optipipe successor snapshot lost fork state")?;
14657                    let rt = fork.rt;
14658                    let snapshot_fence = fork.fence;
14659                    opti_snapshot_one_stage_owned_into(
14660                        e,
14661                        cache,
14662                        rt,
14663                        &snapshot_fence,
14664                        1,
14665                        fork.successor_snapshot_mut(),
14666                    )?;
14667                    // Publish N only after both independent successor-state queues are complete.
14668                    fork.rt.publish_to(1, &e.stream())?;
14669                }
14670                result
14671            } else if let Some(ticket) = current_opti.as_mut() {
14672                let fork = opti_fork
14673                    .as_mut()
14674                    .ok_or("optipipe carried controller ticket lost fork state")?;
14675                let boundary = ticket.take_boundary();
14676                let result = self.verify_stage1_finish(
14677                    e,
14678                    boundary,
14679                    &mut *cache,
14680                    ckpt.as_mut(),
14681                    None,
14682                    &fork.fence,
14683                    true,
14684                )?;
14685                ticket.settle();
14686                result
14687            } else if let Some(generation) = fork_attempt {
14688                let fork = opti_fork
14689                    .as_mut()
14690                    .expect("fork generation without fork state");
14691                fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
14692                let action = fork.mode.action(generation.id);
14693                let boundary = self.verify_stage0_issue(
14694                    e,
14695                    &verify_tokens,
14696                    pos,
14697                    &mut *cache,
14698                    embd_dev,
14699                    ckpt.as_mut(),
14700                    None,
14701                    &fork.fence,
14702                    Some(true),
14703                    None,
14704                )?;
14705                OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14706                let mut ticket = fork.ticket(generation, boundary);
14707                if action == OptiForkAction::Abort {
14708                    return Err(format!(
14709                        "optipipe forced abort with generation {} stage0 in flight",
14710                        generation.id,
14711                    )
14712                    .into());
14713                }
14714                fork.reconcile(
14715                    e,
14716                    &mut *cache,
14717                    &mut *scratch,
14718                    &snap,
14719                    &mut h_seed_buf,
14720                    &mut fill_prev,
14721                    generation,
14722                    action,
14723                    verify_tokens[0],
14724                )?;
14725                let result = if action == OptiForkAction::Hit {
14726                    let boundary = ticket.take_boundary();
14727                    self.verify_stage1_finish(
14728                        e,
14729                        boundary,
14730                        &mut *cache,
14731                        ckpt.as_mut(),
14732                        None,
14733                        &fork.fence,
14734                        true,
14735                    )?
14736                } else {
14737                    // The optimistic boundary slot has no reader. Re-run the unchanged serial
14738                    // verify only after E_restart published the restored stage-0 state.
14739                    self.decode_step_t_core(
14740                        e,
14741                        &verify_tokens,
14742                        pos,
14743                        &mut *cache,
14744                        embd_dev,
14745                        ckpt.as_mut(),
14746                    )?
14747                };
14748                ticket.settle();
14749                debug_assert_eq!(ticket.generation, generation);
14750                fork.retire(generation)?;
14751                result
14752            } else {
14753                // The serial verify every non-fork round takes — the MTP route's
14754                // verify-graph door. The pool is None unless MEMRA_SPEC_VERIFY_GRAPH armed
14755                // a pool above, and then the walk replays the captured trunk instead of
14756                // re-issuing it launch by launch. `graph_round_ok` is the round's
14757                // headroom snapshot (see GRAPH_LAUNCH_MIN_FREE): below the floor the
14758                // round declines the pool exactly like an over-cap round and rides the
14759                // byte-identical eager walk — the `[spec]` suspension line above
14760                // already named the round.
14761                let vg_round = if verify_tokens.len() <= vg_t_cap && graph_round_ok {
14762                    vg_guard.as_mut().and_then(|g| g.as_mut())
14763                } else {
14764                    if let Some(g) = vg_guard.as_mut().and_then(|g| g.as_mut()) {
14765                        // The commit reads this flag to pick its arm; a round that declines
14766                        // the pool must not inherit a stale `true` from the round before it.
14767                        g.round_slab = false;
14768                    }
14769                    None
14770                };
14771                self.decode_step_t_core_vg(
14772                    e,
14773                    &verify_tokens,
14774                    pos,
14775                    &mut *cache,
14776                    embd_dev,
14777                    ckpt.as_mut(),
14778                    vg_round,
14779                )?
14780            };
14781            let pipe_accept = match pipe {
14782                Some(p) => Some(p.accept_begin(round)?),
14783                None => None,
14784            };
14785
14786            if phase_sync {
14787                e.stream().synchronize()?;
14788            }
14789            ph_mark(&mut ph_verify, phase_on);
14790            // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
14791            // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
14792            // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
14793            // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
14794            // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
14795            // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
14796            // (== the bonus), so every index shifts by `base` and last_pred is unused.
14797            let t_v = verify_tokens.len();
14798            let mut preds: Vec<u32> = Vec::new();
14799            if !sampled {
14800                for j in 0..t_v {
14801                    e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
14802                }
14803                preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
14804                // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
14805                // next round's last_token = the next chain's embed lookup. Catch it at the
14806                // source with the column named — an all-NaN VERIFY column implicates the
14807                // stage-split trunk (decode_step_t_core_ppn), not the draft head.
14808                if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
14809                    let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
14810                    let mut probe = e.zeros(n_vocab)?;
14811                    e.copy_view_into(&mut probe, 0, col, n_vocab)?;
14812                    let col_h = e.dtoh(&probe)?;
14813                    let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
14814                    return Err(format!(
14815                        "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
14816                         col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
14817                         — the verify TRUNK produced a poisoned column (#87 trap). Run \
14818                         MEMRA_SPEC_NAN_SCAN=1 to name the layer that creates it (=2 to split \
14819                         that layer into attention and routed MoE). NOT the draft head, and NOT \
14820                         the PP stage split this message used to name: pp_cuts() returns None \
14821                         without MEMRA_PP_STAGES, so decode_step_t_core_ppn never runs unless \
14822                         that variable is set.",
14823                        preds[bad]
14824                    )
14825                    .into());
14826                }
14827            }
14828            ph_mark(&mut ph_wait, phase_on);
14829            let t_pred = |j: usize| -> u32 {
14830                if j == 0 && base == 0 {
14831                    last_pred
14832                } else {
14833                    // GREEDY-ONLY: `preds` is filled under `if !sampled` above. The debug print
14834                    // used to call this from the sampled arm and panicked the worker; it now goes
14835                    // through `debug_t_pred0`. Keep the strict index here — in the greedy walk an
14836                    // out-of-range pred is a real bug, not something to paper over.
14837                    debug_assert!(
14838                        !sampled,
14839                        "t_pred is greedy-only: `preds` is empty in the sampled arm"
14840                    );
14841                    preds[base + j - 1]
14842                }
14843            };
14844            let mut devacc_seeded = false;
14845            let mut devacc_acc: Option<CudaSlice<u32>> = None;
14846            let (n_acc, bonus) = if !sampled {
14847                // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
14848                // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
14849                // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
14850                // gated on token identity vs the host walk (the arms below are bit-equal rules).
14851                if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
14852                {
14853                    let draft_d = e.htod_u32_v(&draft)?;
14854                    let mut acc_out = e.alloc_u32_zeroed(2)?;
14855                    e.spec_accept_greedy(
14856                        &preds_d,
14857                        &draft_d,
14858                        last_pred,
14859                        base,
14860                        k_round,
14861                        &mut acc_out,
14862                    )?;
14863                    devacc_acc = Some(acc_out.clone());
14864                    // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
14865                    // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
14866                    // non-replay commit arms skip their host-offset seed copies (guarded below);
14867                    // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
14868                    // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
14869                    // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
14870                    // the update lands after the arms (devacc_seeded guard below).
14871                    e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
14872                    // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
14873                    // unified rule; full accept rewrites the verify-left value). Host mirrors
14874                    // update after the readback; commit_verified_prefix skips its len_d writes.
14875                    if let Some(successor) = successor_attempt.as_ref() {
14876                        opti_fork
14877                            .as_mut()
14878                            .ok_or("optipipe successor reconcile lost fork state")?
14879                            .queue_actual_reconcile(
14880                                e,
14881                                &snap,
14882                                &acc_out,
14883                                successor.verify_tokens[0],
14884                                base,
14885                            )?;
14886                    } else if let Some(ptrs) = &kv_len_ptrs {
14887                        let saved: Vec<i32> = (0..self.layers.len())
14888                            .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
14889                            .collect();
14890                        let saved_d = e.htod_i32(&saved)?;
14891                        e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
14892                    }
14893                    devacc_seeded = true;
14894                    let ab = e.dtoh_u32(&acc_out)?;
14895                    (ab[0] as usize, ab[1])
14896                } else {
14897                    let mut n_acc = 0usize;
14898                    #[allow(clippy::needless_range_loop)]
14899                    // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
14900                    for j in 0..k_round {
14901                        if t_pred(j) == draft[j] {
14902                            n_acc += 1;
14903                        } else {
14904                            break;
14905                        }
14906                    }
14907                    // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
14908                    // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
14909                    (n_acc, t_pred(n_acc))
14910                }
14911            } else {
14912                // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
14913                if col_buf.is_none() {
14914                    col_buf = Some(e.zeros(n_vocab)?);
14915                }
14916                // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
14917                // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
14918                let mut pj = vec![0f32; k_round.max(1)];
14919                let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
14920                if k_round > 0 {
14921                    let mut ids: Vec<u32> = Vec::new();
14922                    let mut rows: Vec<i32> = Vec::new();
14923                    #[allow(clippy::needless_range_loop)]
14924                    // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
14925                    for j in 0..k_round {
14926                        if j > 0 || base == 1 {
14927                            ids.push(draft[j]);
14928                            rows.push((base + j) as i32 - 1);
14929                        }
14930                    }
14931                    if !ids.is_empty() {
14932                        let nr = rows.len();
14933                        // penalties: materialize the used columns into one contiguous penalized
14934                        // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
14935                        // penalties: materialize used columns contiguously, penalize all rows in
14936                        // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
14937                        let p_rows: Vec<i32> = if pen_on {
14938                            (0..nr as i32).collect()
14939                        } else {
14940                            rows.clone()
14941                        };
14942                        if pen_on {
14943                            if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
14944                                pcol_buf = Some(e.zeros(nr * n_vocab)?);
14945                            }
14946                            let pc = pcol_buf.as_mut().unwrap();
14947                            for (i2, &r) in rows.iter().enumerate() {
14948                                let c = r as usize;
14949                                e.copy_view_into(
14950                                    pc,
14951                                    i2 * n_vocab,
14952                                    &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
14953                                    n_vocab,
14954                                )?;
14955                            }
14956                            let h = pen_hist_d.as_ref().unwrap();
14957                            let nh = h.len();
14958                            e.penalize_logits_rows(
14959                                pc,
14960                                h,
14961                                nh,
14962                                sp.penalty_repeat,
14963                                sp.penalty_freq,
14964                                sp.penalty_present,
14965                                n_vocab,
14966                                nr,
14967                            )?;
14968                        }
14969                        let p_src: &CudaSlice<f32> = if pen_on {
14970                            pcol_buf.as_ref().unwrap()
14971                        } else {
14972                            &tlogits_d
14973                        };
14974                        let rowsd = e.htod_i32(&p_rows)?;
14975                        let (mut th_d, mut z_d, mut mx_d) =
14976                            (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
14977                        e.filter_stats(
14978                            p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
14979                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
14980                        )?;
14981                        let idsd = e.htod_u32_v(&ids)?;
14982                        let mut outd = e.zeros(nr)?;
14983                        e.softmax_gather_filtered(
14984                            p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
14985                            sp_temp,
14986                        )?;
14987                        let outv = e.dtoh(&outd)?;
14988                        let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
14989                        let mut oi = 0usize;
14990                        #[allow(clippy::needless_range_loop)]
14991                        // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
14992                        for j in 0..k_round {
14993                            if j > 0 || base == 1 {
14994                                pj[j] = outv[oi];
14995                                oi += 1;
14996                            }
14997                        }
14998                        col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
14999                    }
15000                    if base == 0 {
15001                        let lc: &CudaSlice<f32> = if pen_on {
15002                            if col_buf.is_none() {
15003                                col_buf = Some(e.zeros(n_vocab)?);
15004                            }
15005                            let cb = col_buf.as_mut().unwrap();
15006                            e.copy_into(
15007                                cb,
15008                                0,
15009                                last_col_logits
15010                                    .as_ref()
15011                                    .expect("sampled: last_col_logits unset"),
15012                                n_vocab,
15013                            )?;
15014                            let h = pen_hist_d.as_ref().unwrap();
15015                            let nh = h.len();
15016                            e.penalize_logits(
15017                                cb,
15018                                h,
15019                                nh,
15020                                sp.penalty_repeat,
15021                                sp.penalty_freq,
15022                                sp.penalty_present,
15023                                n_vocab,
15024                            )?;
15025                            col_buf.as_ref().unwrap()
15026                        } else {
15027                            last_col_logits
15028                                .as_ref()
15029                                .expect("sampled: last_col_logits unset")
15030                        };
15031                        let rows0 = e.htod_i32(&[0])?;
15032                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
15033                        e.filter_stats(
15034                            lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
15035                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
15036                        )?;
15037                        let idsd = e.htod_u32_v(&[draft[0]])?;
15038                        let mut outd = e.zeros(1)?;
15039                        e.softmax_gather_filtered(
15040                            lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
15041                        )?;
15042                        pj[0] = e.dtoh(&outd)?[0];
15043                        last_col_stats =
15044                            Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
15045                    }
15046                }
15047                // q source: the graph arms (single-head AND chain) retained the head logits
15048                // in the persistent q_slots; the eager arm in per-round draft_logits clones.
15049                // Same raw-logit values either way. FILTERED q_j: stats from draft_stats
15050                // (eager pushes in-chain; the graph arms compute them post-replay from the
15051                // retained q with the same filter_stats program — bit-identical to the
15052                // in-graph stats that shaped the draw, keeping ONE accept path).
15053                let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() || dctx.chain_s.is_some()
15054                {
15055                    &dctx.q_slots
15056                } else {
15057                    &draft_logits
15058                };
15059                let mut n_acc = 0usize;
15060                for j in 0..k_round {
15061                    let (qmx, qth, qz) = draft_stats[j];
15062                    let idsd = e.htod_u32_v(&[draft_idx[j]])?;
15063                    let rowsd = e.htod_i32(&[0])?;
15064                    let thd = e.htod(&[qth])?;
15065                    let zd = e.htod(&[qz])?;
15066                    let _ = qmx;
15067                    let mut outd = e.zeros(1)?;
15068                    e.softmax_gather_filtered(
15069                        &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
15070                        sp_temp,
15071                    )?;
15072                    let qj = e.dtoh(&outd)?[0];
15073                    let u = host_u01(sp_seed, uctr);
15074                    uctr += 1;
15075                    let accept = (u as f64) * (qj as f64) < pj[j] as f64;
15076                    // SKEY PROBE: q == 0 for the token the draft actually proposed is the
15077                    // exactness signature (see `skey_probe`). Impossible when the draft was
15078                    // drawn from the same filtered distribution the verify reconstructs here;
15079                    // `u * 0 < p` makes it an UNCONDITIONAL accept whenever p > 0.
15080                    if skey_probe() && qj == 0.0 {
15081                        eprintln!(
15082                            "[skey] EXACTNESS q=0 round={round} j={j} draft_tok={} \
15083                             draft_idx={} p={:e} u={u} accepted={} th_z={:?}",
15084                            draft[j], draft_idx[j], pj[j], accept as u8, draft_stats[j],
15085                        );
15086                    }
15087                    if accept {
15088                        n_acc += 1;
15089                    } else {
15090                        break;
15091                    }
15092                }
15093                let bonus = if n_acc == k_round {
15094                    // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
15095                    let col = base + k_round - 1;
15096                    let cb = col_buf.as_mut().unwrap();
15097                    e.copy_view_into(
15098                        cb,
15099                        0,
15100                        &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
15101                        n_vocab,
15102                    )?;
15103                    if pen_on {
15104                        let h = pen_hist_d.as_ref().unwrap();
15105                        let nh = h.len();
15106                        e.penalize_logits(
15107                            cb,
15108                            h,
15109                            nh,
15110                            sp.penalty_repeat,
15111                            sp.penalty_freq,
15112                            sp.penalty_present,
15113                            n_vocab,
15114                        )?;
15115                    }
15116                    if perturb_buf.is_none() {
15117                        perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
15118                    }
15119                    // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
15120                    // truncation-fix; receipts research/sampfix-20260805/). The old code reused
15121                    // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
15122                    // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
15123                    // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
15124                    // last gathered column, in both base arms. `th` is a threshold in e-units of
15125                    // its OWN row's max, so feeding a neighbour's (row_max, th) into
15126                    // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
15127                    // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
15128                    // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
15129                    // falls through to its smallest-index tie-break => token id 0 ("!") spliced
15130                    // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
15131                    // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
15132                    // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
15133                    // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
15134                    // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
15135                    // and row_max is unused once nothing is masked), so this fix is a byte-level
15136                    // no-op for the untruncated serve default. One extra one-block filter_stats
15137                    // per full-accept round is the whole cost.
15138                    let (mx, th) = {
15139                        let rows0 = e.htod_i32(&[0])?;
15140                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
15141                        let cb0 = col_buf.as_ref().unwrap();
15142                        e.filter_stats(
15143                            cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
15144                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
15145                        )?;
15146                        (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
15147                    };
15148                    let pb = perturb_buf.as_mut().unwrap();
15149                    let cb2 = col_buf.as_ref().unwrap();
15150                    e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
15151                    sctr += 1;
15152                    let td = e.argmax_token_device(pb, n_vocab)?;
15153                    e.dtoh_u32_one(&td)?
15154                } else {
15155                    // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
15156                    let cb = col_buf.as_mut().unwrap();
15157                    if n_acc > 0 || base == 1 {
15158                        let col = base + n_acc - 1;
15159                        e.copy_view_into(
15160                            cb,
15161                            0,
15162                            &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
15163                            n_vocab,
15164                        )?;
15165                    } else {
15166                        let lc = last_col_logits.as_ref().unwrap();
15167                        e.copy_into(cb, 0, lc, n_vocab)?;
15168                    }
15169                    if pen_on {
15170                        let h = pen_hist_d.as_ref().unwrap();
15171                        let nh = h.len();
15172                        e.penalize_logits(
15173                            cb,
15174                            h,
15175                            nh,
15176                            sp.penalty_repeat,
15177                            sp.penalty_freq,
15178                            sp.penalty_present,
15179                            n_vocab,
15180                        )?;
15181                    }
15182                    let cb2 = col_buf.as_ref().unwrap();
15183                    let sc = sctr;
15184                    sctr += 1;
15185                    // p-stats for the reject column: from col_stats when the col was gathered,
15186                    // else (j==0&&base==0) from last_col_stats.
15187                    let p_stats = if n_acc > 0 || base == 1 {
15188                        // col index within the gathered set == number of gathered cols before n_acc
15189                        let gi = if base == 1 { n_acc } else { n_acc - 1 };
15190                        col_stats.get(gi).copied().unwrap_or({
15191                            (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
15192                        })
15193                    } else {
15194                        last_col_stats.expect("sampled: last_col_stats unset at reject")
15195                    };
15196                    let q_stats = draft_stats[n_acc];
15197                    if let Some(map) = &d2t_dev {
15198                        if q_full_buf.is_none() {
15199                            q_full_buf = Some(e.zeros(n_vocab)?);
15200                        }
15201                        let qf = q_full_buf.as_mut().unwrap();
15202                        e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
15203                        let qf2 = q_full_buf.as_ref().unwrap();
15204                        e.residual_sample_filtered(
15205                            cb2,
15206                            Some(qf2),
15207                            n_vocab,
15208                            sp_temp,
15209                            sp_seed,
15210                            sc,
15211                            p_stats,
15212                            q_stats,
15213                            &mut sample_tok,
15214                        )?;
15215                    } else {
15216                        e.residual_sample_filtered(
15217                            cb2,
15218                            Some(&q_bufs[n_acc]),
15219                            n_vocab,
15220                            sp_temp,
15221                            sp_seed,
15222                            sc,
15223                            p_stats,
15224                            q_stats,
15225                            &mut sample_tok,
15226                        )?;
15227                    }
15228                    e.dtoh_u32(&sample_tok)?[0]
15229                };
15230                (
15231                    n_acc,
15232                    guard_vocab_token(
15233                        bonus,
15234                        n_vocab,
15235                        &format!("sampled verify bonus at round {round} pos={pos} n_acc={n_acc}"),
15236                    )?,
15237                )
15238            };
15239            // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
15240            // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
15241            // ordering). Walk the accepted drafts through the grammar in commit order; the
15242            // first illegal token truncates acceptance at its slot, and that slot's emission
15243            // is recomputed as the MASKED argmax of the target's own verify column — token-
15244            // identical to constrained plain greedy decode (an unmasked argmax that is
15245            // grammar-legal IS the masked argmax: masking only removes competitors). The
15246            // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
15247            // measured in acceptance numbers, never hidden.
15248            let (n_acc, bonus) = match constraint.as_deref_mut() {
15249                None => (n_acc, bonus),
15250                Some(c) => {
15251                    fn ce(e2: String) -> Box<dyn std::error::Error> {
15252                        format!("constraint: {e2}").into()
15253                    }
15254                    let mut na = n_acc;
15255                    let mut cut = false;
15256                    for (j, &d) in draft.iter().enumerate().take(n_acc) {
15257                        if c.is_allowed(d).map_err(ce)? {
15258                            c.consume(d).map_err(ce)?;
15259                        } else {
15260                            na = j;
15261                            cut = true;
15262                            dm_cut_tokens += n_acc - j;
15263                            break;
15264                        }
15265                    }
15266                    if cut {
15267                        dm_cuts += 1;
15268                    }
15269                    let mut bo = bonus;
15270                    if cut || !c.is_allowed(bo).map_err(ce)? {
15271                        let mut row = if na == 0 && base == 0 {
15272                            init_logits_host
15273                                .clone()
15274                                .ok_or("constraint: init logits missing (round-0 cut)")?
15275                        } else {
15276                            e.dtoh_view(
15277                                &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
15278                            )?
15279                        };
15280                        c.mask_logits(&mut row).map_err(ce)?;
15281                        bo = argmax(&row) as u32;
15282                    }
15283                    c.consume(bo).map_err(ce)?;
15284                    (na, bo)
15285                }
15286            };
15287            let mut successor_valid = false;
15288            if let Some((q_proxy, expected_d2)) = rejected_probe {
15289                let v_n = n_acc == 1 && bonus == expected_d2;
15290                eprintln!(
15291                    "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
15292                     expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
15293                );
15294            }
15295            if let Some(successor) = successor_attempt.as_ref() {
15296                successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
15297                let generation = successor.generation;
15298                let q_proxy = successor.q_proxy;
15299                let expected_pending = successor.verify_tokens[0];
15300                let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
15301                let fork = opti_fork
15302                    .as_mut()
15303                    .ok_or("optipipe successor resolution lost fork state")?;
15304                fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
15305                if successor_valid {
15306                    OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15307                } else {
15308                    OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15309                    OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15310                    OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
15311                }
15312                let breaker_tripped = fork
15313                    .controller
15314                    .as_mut()
15315                    .expect("controller policy")
15316                    .resolve(successor_valid);
15317                if breaker_tripped {
15318                    OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15319                }
15320                eprintln!(
15321                    "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
15322                     expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
15323                     resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
15324                    generation.id, successor_valid, !successor_valid, breaker_tripped,
15325                );
15326                if !successor_valid {
15327                    let mut successor = successor_attempt
15328                        .take()
15329                        .expect("controller successor disappeared on miss");
15330                    successor.settle();
15331                    fork.retire(generation)?;
15332                }
15333            }
15334            total_drafted += k_round;
15335            total_accepted += n_acc;
15336            if let Some(t) = sess_telem {
15337                // Greedy, rejection-sampling, and grammar truncation all converge here after
15338                // the accept decision is already on host. Fixed-size relaxed atomics only.
15339                t.record_round(k_round, n_acc);
15340            }
15341            if spec_stats {
15342                st_len_hist[k_round] += 1;
15343                #[allow(clippy::needless_range_loop)]
15344                // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15345                for j in 0..k_round {
15346                    st_drafted[j] += 1;
15347                }
15348                #[allow(clippy::needless_range_loop)]
15349                // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15350                for j in 0..n_acc {
15351                    st_accepted[j] += 1;
15352                }
15353                if n_acc == k_round {
15354                    st_full += 1;
15355                }
15356            }
15357
15358            if debug_spec {
15359                eprintln!(
15360                    "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
15361                    out.len(),
15362                    // NOT `t_pred(0)`: `preds` is filled only under `if !sampled` above, so on a
15363                    // sampled request round >= 1 (base == 1) indexed an EMPTY vector and PANICKED
15364                    // the GPU worker thread — a debug flag that killed the exact regime you would
15365                    // set it to investigate. See `debug_t_pred0`.
15366                    debug_t_pred0(sampled, base, last_pred, &preds)
15367                );
15368            }
15369
15370            // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
15371            let commit_started = std::time::Instant::now();
15372            // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
15373            // of them (overshoot past max_new included) or `committed` under-counts the cache rows
15374            // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
15375            // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
15376            #[allow(clippy::needless_range_loop)]
15377            // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15378            for j in 0..n_acc {
15379                if !session_mode && out.len() >= max_new {
15380                    break;
15381                }
15382                out.push(draft[j]);
15383            }
15384            if pen_on {
15385                pen_hist.extend_from_slice(&draft[0..n_acc]);
15386                pen_hist.push(bonus);
15387            }
15388            let bonus_emitted = session_mode || out.len() < max_new;
15389            if bonus_emitted {
15390                out.push(bonus);
15391            }
15392            last_token = bonus;
15393
15394            // --- 5. ROLLBACK + advance (§C) ---
15395            if n_acc == k_round && !spec_replay {
15396                // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
15397                // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
15398                // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
15399                // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
15400                // last_pred is dead in the pending path (t_pred reads verify col 0).
15401                //
15402                // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
15403                // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
15404                // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
15405                // trunk hidden (the last verify column). set_len first: a p-min break may have
15406                // left one extra chain append at that slot. Partial accepts need NO fill (the
15407                // chain already covered every accepted position; round-start set_len truncates).
15408                let mut vh_seed = e.zeros(n_embd)?;
15409                e.copy_view_into(
15410                    &mut vh_seed,
15411                    0,
15412                    &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
15413                    n_embd,
15414                )?;
15415                if refresh {
15416                    // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
15417                    // overwrite ALL committed positions' scratch entries with K/V from their EXACT
15418                    // verify hiddens — the reference engine's mtp_update fills from true hiddens;
15419                    // the full stack (vx) is already resident from the verify. Replaces both the
15420                    // chain-approximate entries AND the old last-token-only fill. Acceptance-only
15421                    // (draft attention quality); exactness stays the verify's job.
15422                    scratch.set_len(e, pos)?;
15423                    // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
15424                    // (hidden of the last committed row before this verify batch).
15425                    let mut vxs = e.zeros(t_v * n_embd)?;
15426                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
15427                    if t_v > 1 {
15428                        e.copy_view_into(
15429                            &mut vxs,
15430                            n_embd,
15431                            &vx.slice(0..(t_v - 1) * n_embd),
15432                            (t_v - 1) * n_embd,
15433                        )?;
15434                    }
15435                    self.mtp_kv_fill_all(e, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
15436                } else {
15437                    scratch.set_len(e, pos + base + k_round - 1)?;
15438                    // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
15439                    let mut hp = e.zeros(n_embd)?;
15440                    if t_v >= 2 {
15441                        e.copy_view_into(
15442                            &mut hp,
15443                            0,
15444                            &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
15445                            n_embd,
15446                        )?;
15447                    } else {
15448                        e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
15449                    }
15450                    self.mtp_kv_fill_all(
15451                        e,
15452                        &[draft[k_round - 1]],
15453                        &hp,
15454                        pos + base + k_round - 1,
15455                        &mut *scratch,
15456                        embd_dev,
15457                    )?;
15458                }
15459                // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
15460                // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
15461                // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
15462                // col). Saves one MTP-block pass per round on top of the pairing fix.
15463                if !devacc_seeded {
15464                    e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
15465                    e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
15466                }
15467                pending = Some(bonus);
15468                if debug_spec {
15469                    eprintln!("  -> FULL ACCEPT (bonus pending, prev-h seed)");
15470                }
15471            } else if !spec_replay && base + n_acc >= 1 {
15472                // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
15473                // the verify's first j = base+n_acc columns ARE the committed sequence, computed
15474                // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
15475                // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
15476                // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
15477                // full-accept path — the legacy duplicate trunk replay is gone. The next chain
15478                // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
15479                // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
15480                // accept (never compounds: the next verify recomputes true hiddens for all
15481                // committed columns).
15482                let j = base + n_acc;
15483                // VERIFY-GRAPH SLAB COMMIT: when the captured trunk ran, the linear layers'
15484                // column stash was written into the graphs ctx's persistent slabs as in-graph
15485                // memcpy nodes, NOT into the per-column VerifyCkpt the cols arm reads — so the
15486                // commit must take the slab twin (same semantics, slab-addressed sources). The
15487                // ctx states which of the two this round produced via `round_slab`; trusting the
15488                // flag rather than the env keeps a round that fell back to the eager walk (a
15489                // capture that declined, a t the pool never captured) on the cols arm.
15490                let slab_commit = vg_guard
15491                    .as_ref()
15492                    .and_then(|g| g.as_ref())
15493                    .map(|g| g.round_slab)
15494                    .unwrap_or(false);
15495                if slab_commit {
15496                    self.dspark_commit_prefix_slab(
15497                        e,
15498                        &mut *cache,
15499                        &snap,
15500                        vg_guard
15501                            .as_ref()
15502                            .and_then(|g| g.as_ref())
15503                            .expect("slab_commit implies a graphs ctx"),
15504                        j,
15505                    )?;
15506                } else {
15507                    self.commit_verified_prefix(
15508                        e,
15509                        &mut *cache,
15510                        &snap,
15511                        ckpt.as_ref().unwrap(),
15512                        j,
15513                        devacc_seeded,
15514                        if devacc_seeded {
15515                            devacc_acc.as_ref().map(|a| (a, base, t_v))
15516                        } else {
15517                            None
15518                        },
15519                    )?;
15520                }
15521                let mut seed = e.zeros(n_embd)?;
15522                e.copy_view_into(
15523                    &mut seed,
15524                    0,
15525                    &vx.slice((j - 1) * n_embd..j * n_embd),
15526                    n_embd,
15527                )?;
15528                // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
15529                // branch); without it the chain entries stand and only the tail truncates. Either
15530                // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
15531                // (persistent mode), rope pos+j+1 (chain convention).
15532                if refresh {
15533                    scratch.set_len(e, pos)?;
15534                    let mut vxs = e.zeros(j * n_embd)?;
15535                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
15536                    if j > 1 {
15537                        e.copy_view_into(
15538                            &mut vxs,
15539                            n_embd,
15540                            &vx.slice(0..(j - 1) * n_embd),
15541                            (j - 1) * n_embd,
15542                        )?;
15543                    }
15544                    self.mtp_kv_fill_all(
15545                        e,
15546                        &verify_tokens[0..j],
15547                        &vxs,
15548                        pos,
15549                        &mut *scratch,
15550                        embd_dev,
15551                    )?;
15552                } else {
15553                    scratch.set_len(e, pos + j)?;
15554                }
15555                // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
15556                // bonus's predecessor (verify col j-1); no pseudo pass.
15557                if !devacc_seeded {
15558                    e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
15559                    e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
15560                }
15561                pending = Some(bonus);
15562                if debug_spec {
15563                    eprintln!("  -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
15564                }
15565            } else if !spec_replay {
15566                // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
15567                // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
15568                // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
15569                // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
15570                // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
15571                // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
15572                // base=1 pending machinery, bit-identical by the decode-exact verify contract.
15573                // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
15574                // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
15575                cache.rollback(e, &snap, 0)?;
15576                scratch.set_len(e, pos)?;
15577                e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
15578                pending = Some(bonus);
15579                if debug_spec {
15580                    eprintln!("  -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
15581                }
15582            } else {
15583                // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
15584                // this round survives, only possible before the first pending exists, ~round 0):
15585                // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
15586                // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
15587                // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
15588                // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
15589                // trunk hidden.
15590                cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
15591                let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
15592                if let Some(b) = pending.take() {
15593                    replay.push(b);
15594                }
15595                replay.extend_from_slice(&draft[0..n_acc]);
15596                replay.push(bonus);
15597                // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
15598                // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
15599                // last col exactly as before (byte-identical to the old _h_emb_dev call).
15600                let (rl_d, rx) = if self.batched_serving_numeric_class() {
15601                    let mut logits = Vec::with_capacity(replay.len() * n_vocab);
15602                    let mut hidden = e.uninit(replay.len() * n_embd)?;
15603                    for (row, &token) in replay.iter().enumerate() {
15604                        let (row_logits, row_hidden) =
15605                            self.spec_target_step_h(e, token, &mut *cache)?;
15606                        logits.extend_from_slice(&row_logits);
15607                        e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
15608                    }
15609                    (e.htod(&logits)?, hidden)
15610                } else {
15611                    self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
15612                };
15613                // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
15614                // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
15615                e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
15616                last_pred = guard_vocab_token(
15617                    e.dtoh_u32(&preds_d)?[0],
15618                    n_vocab,
15619                    &format!("replay last_pred at round {round} pos={pos}"),
15620                )?;
15621                if sampled {
15622                    let lr0 = replay.len();
15623                    let lc = last_col_logits
15624                        .as_mut()
15625                        .expect("sampled: last_col_logits unset");
15626                    e.copy_view_into(
15627                        lc,
15628                        0,
15629                        &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
15630                        n_vocab,
15631                    )?;
15632                }
15633                let lr = replay.len();
15634                if lr >= 2 {
15635                    e.copy_view_into(
15636                        &mut h_seed_buf,
15637                        0,
15638                        &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
15639                        n_embd,
15640                    )?;
15641                } else {
15642                    // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
15643                    // last_token, whose own-row hidden fill_prev still holds.
15644                    e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
15645                }
15646                // the bonus is COMMITTED here — it becomes the last committed row.
15647                let mut rh_last = e.zeros(n_embd)?;
15648                e.copy_view_into(
15649                    &mut rh_last,
15650                    0,
15651                    &rx.slice((lr - 1) * n_embd..lr * n_embd),
15652                    n_embd,
15653                )?;
15654                e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
15655                if debug_spec {
15656                    eprintln!("  -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
15657                }
15658            }
15659            if devacc_seeded {
15660                // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
15661                // consumed the old value (both slots carry the same value in every non-replay arm).
15662                e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
15663            }
15664            if successor_valid {
15665                let optimistic_scratch_len = successor_attempt
15666                    .as_ref()
15667                    .expect("valid controller successor disappeared")
15668                    .scratch_len;
15669                // The normal current-round commit refreshed/truncated the logical scratch tail.
15670                // Its optimistic successor row was already written physically, so restoring only
15671                // the retained logical length makes that row live for the carried round.
15672                scratch.set_len(e, optimistic_scratch_len)?;
15673            }
15674            if let Some(current) = current_opti.take() {
15675                opti_fork
15676                    .as_mut()
15677                    .ok_or("optipipe current retirement lost fork state")?
15678                    .retire(current.generation)?;
15679            }
15680            if successor_valid {
15681                let successor = successor_attempt
15682                    .take()
15683                    .expect("valid controller successor disappeared before promotion");
15684                let generation = successor.generation;
15685                opti_fork
15686                    .as_mut()
15687                    .ok_or("optipipe successor promotion lost fork state")?
15688                    .promote_successor_snapshot(&mut snap, generation);
15689                carried_opti = Some(successor);
15690            }
15691            if anatomy_on {
15692                // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
15693                // only for this diagnostic so it does not disappear into the following draft's
15694                // first token readback.
15695                e.stream().synchronize()?;
15696                ph_commit += commit_started.elapsed().as_secs_f64();
15697            }
15698            // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
15699            // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
15700            // final position — the floor's position key reads the committed depth). Burst
15701            // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
15702            // like gemma's burst arm.
15703            if adapt {
15704                let fl_now = floor_at(cache.pos);
15705                kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
15706            }
15707            ph_mark(&mut ph_rest, phase_on);
15708            if let Some(p) = pipe {
15709                p.accept_end(round);
15710            }
15711            drop(pipe_accept);
15712            if let Some(t0) = round_t0 {
15713                let ms = t0.elapsed().as_secs_f64() * 1e3;
15714                ROUND_MS.fetch_add((ms * 1e3) as u64, std::sync::atomic::Ordering::Relaxed);
15715                let n = ROUND_N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
15716                if n.is_multiple_of(32) {
15717                    eprintln!(
15718                        "[spec-round] rounds={n} avg round wall={:.2} ms (emitted={} drafted so far)",
15719                        ROUND_MS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e3 / n as f64,
15720                        out.len()
15721                    );
15722                }
15723            }
15724            round += 1;
15725            // sse-cadence: this round's accepted drafts + bonus are committed (out is
15726            // append-only past step 4) — flush at round cadence.
15727            keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
15728        }
15729        if let Some(mut ticket) = carried_opti.take() {
15730            opti_fork
15731                .as_mut()
15732                .ok_or("optipipe tail drain lost fork state")?
15733                .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
15734        }
15735        // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
15736        // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
15737        let _ = flush_commit(&mut on_commit, &out, &mut flushed);
15738
15739        if spec_stats {
15740            let per_slot: Vec<String> = (0..k)
15741                .map(|j| {
15742                    if st_drafted[j] > 0 {
15743                        format!(
15744                            "{}/{}={:.3}",
15745                            st_accepted[j],
15746                            st_drafted[j],
15747                            st_accepted[j] as f64 / st_drafted[j] as f64
15748                        )
15749                    } else {
15750                        "0/0".into()
15751                    }
15752                })
15753                .collect();
15754            let acc = if total_drafted > 0 {
15755                total_accepted as f64 / total_drafted as f64
15756            } else {
15757                0.0
15758            };
15759            eprintln!(
15760                "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
15761                       per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
15762                       tok_per_round={:.3}",
15763                per_slot.join(" "),
15764                (total_accepted + round) as f64 / round.max(1) as f64
15765            );
15766        }
15767        if constraint.is_some() {
15768            eprintln!(
15769                "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
15770                 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
15771                dm_clone_ns as f64 / 1e6,
15772                dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
15773            );
15774        }
15775        if phase_on {
15776            let tot = ph_draft + ph_verify + ph_wait + ph_rest;
15777            eprintln!(
15778                "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
15779                ph_draft * 1e3,
15780                ph_draft / tot * 100.0,
15781                ph_verify * 1e3,
15782                ph_verify / tot * 100.0,
15783                ph_wait * 1e3,
15784                ph_wait / tot * 100.0,
15785                ph_rest * 1e3,
15786                ph_rest / tot * 100.0
15787            );
15788        }
15789        if anatomy_on {
15790            let rounds_f = round.max(1) as f64;
15791            let other = (ph_rest - ph_commit).max(0.0);
15792            eprintln!(
15793                "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
15794                 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
15795                ph_draft * 1e3 / rounds_f,
15796                ph_verify * 1e3 / rounds_f,
15797                ph_wait * 1e3 / rounds_f,
15798                ph_commit * 1e3 / rounds_f,
15799                other * 1e3 / rounds_f,
15800            );
15801        }
15802        let _pipe_tail = pipe.map(|p| p.primary()).transpose()?;
15803        // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
15804        // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
15805        // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
15806        // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
15807        if let Some(slot) = sess_draft_slot.take() {
15808            *slot = Some(dctx);
15809        }
15810        let t_rounds = t_ent.elapsed();
15811        if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
15812            // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
15813            // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
15814            // HERE, where the sampler, the session Philox counters and the penalty window are
15815            // all live and the boundary logits row still exists — that is the "make the state
15816            // available" half of the fix; the consuming burst then just emits it. `sctr` is
15817            // written to the session BELOW the draws so the advance is never lost.
15818            *next_pred_slot = Some(last_pred);
15819            let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
15820            let mut stashed_pending = false;
15821            if let Some(b) = pending.take() {
15822                if !sampled {
15823                    // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
15824                    // committing it with a solo T=1 pass — the next empty-suffix greedy burst
15825                    // consumes it as round-0 verify col 0 (a plain round edge; the old tail
15826                    // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
15827                    // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
15828                    // OUT of `committed` (cache rows == committed); the consuming call
15829                    // prepends it once its verify commits the row. next_pred is unknowable
15830                    // without the commit pass — None; callers gate on pending_tok too.
15831                    debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
15832                    if let Some(slot) = sess_pending_slot.take() {
15833                        *slot = Some(b);
15834                    }
15835                    *next_pred_slot = None;
15836                    // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
15837                    // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
15838                    *last_h = Some(e.clone_dtod(&fill_prev)?);
15839                    stashed_pending = true;
15840                } else {
15841                    // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
15842                    // the sampled round-0 accept needs this pass's logits (last_col_logits).
15843                    let pos_b = cache.pos;
15844                    scratch.set_len(e, pos_b)?;
15845                    let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
15846                    // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
15847                    // itself — the prediction AFTER the bonus never materialized; it would have
15848                    // been the next round's verify col 0). The commit's logits ARE that
15849                    // prediction — so they are also the row the next burst's boundary token
15850                    // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
15851                    *next_pred_slot = Some(if sample_boundary {
15852                        sample_boundary_token(
15853                            e,
15854                            &lg_b,
15855                            &sp,
15856                            &pen_hist,
15857                            &mut sctr,
15858                            "burst-tail-commit",
15859                        )?
15860                    } else {
15861                        argmax(&lg_b) as u32
15862                    });
15863                    self.mtp_kv_fill_all(e, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
15864                    *last_h = Some(hb);
15865                }
15866            } else {
15867                // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
15868                *last_h = Some(e.clone_dtod(&fill_prev)?);
15869                if sample_boundary {
15870                    // No pending to commit, so the boundary row is the one `last_pred` was
15871                    // argmaxed from and the sampled path keeps it on device: the init feed's
15872                    // logits when the burst ran zero rounds, else the legacy-replay path's
15873                    // last verify column (both predict the token AFTER the last committed
15874                    // row). It is retained precisely because round 0's accept test needs it,
15875                    // so the draw costs no extra D2H of the [n_vocab] row.
15876                    match last_col_logits.as_ref() {
15877                        Some(lc) => {
15878                            *next_pred_slot = Some(sample_boundary_token_dev(
15879                                e,
15880                                lc,
15881                                n_vocab,
15882                                &sp,
15883                                &pen_hist,
15884                                &mut sctr,
15885                                "burst-tail-nopending",
15886                            )?);
15887                        }
15888                        // NAME THE FALLBACK (house standard): unreachable today — a sampled
15889                        // burst always feeds or replays, so the row exists — but if it ever
15890                        // is, the stream takes a greedy token and SAYS so rather than
15891                        // silently regressing to the pre-lane behaviour.
15892                        None => eprintln!(
15893                            "[spec-boundary] sampled tail kept the ARGMAX boundary token \
15894                             (reason: no retained boundary logits row)"
15895                        ),
15896                    }
15897                }
15898            }
15899            *sctr_slot = sctr;
15900            *uctr_slot = uctr;
15901            committed.extend_from_slice(prompt);
15902            if let Some(cb) = carried_pending {
15903                // the consumed carry's cache row landed in round 0's verify (every pending
15904                // round commits col 0) — it joins `committed` here, in sequence order.
15905                committed.push(cb);
15906            }
15907            if stashed_pending {
15908                // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
15909                // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
15910                // 18446744073709551615 out of range for slice of length 0", killing the
15911                // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
15912                // stream". Reachable because `pending` starts as `carried_pending` (a bonus
15913                // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
15914                // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
15915                // did). So a burst that stashes a pending without emitting anything of its own —
15916                // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
15917                // guard skipping every token under a tight budget — arrives here with
15918                // out.len() == 0 and stashed_pending == true.
15919                //
15920                // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
15921                // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
15922                // just above is already accounted. Saturating, not a min/assert: an empty `out`
15923                // here is a legitimate burst shape, not a corrupt state.
15924                let emitted = out.len().saturating_sub(1);
15925                committed.extend_from_slice(&out[..emitted]);
15926            } else {
15927                committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
15928            }
15929            debug_assert_eq!(
15930                cache.pos,
15931                committed.len(),
15932                "session invariant: cache rows == committed tokens"
15933            );
15934            if setup_trace {
15935                e.stream().synchronize()?; // bound the async tail fill in the trace
15936                let t_tail = t_ent.elapsed();
15937                eprintln!(
15938                    "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
15939                    t_init.as_secs_f64() * 1e3,
15940                    (t_cap - t_init).as_secs_f64() * 1e3,
15941                    (t_fill - t_cap).as_secs_f64() * 1e3,
15942                    (t_rounds - t_fill).as_secs_f64() * 1e3,
15943                    (t_tail - t_rounds).as_secs_f64() * 1e3,
15944                    t_tail.as_secs_f64() * 1e3,
15945                    out.len(),
15946                    continuation
15947                );
15948            }
15949            return Ok((out, total_drafted, total_accepted));
15950        }
15951        out.truncate(max_new);
15952        Ok((out, total_drafted, total_accepted))
15953    }
15954
15955    /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
15956    /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
15957    /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
15958    #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
15959    pub fn extract_dspark_anchors(
15960        &self,
15961        e: &Engine,
15962        tokens: &[u32],
15963        anchor_positions: &[usize],
15964        gamma: usize,
15965        top_k: usize,
15966        chunk: usize,
15967        temperature: f32,
15968    ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
15969        if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
15970            return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
15971        }
15972        if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
15973            return Err("DSpark anchor positions must be sorted and unique".into());
15974        }
15975        for &position in anchor_positions {
15976            if position == 0 || position + gamma >= tokens.len() {
15977                return Err(format!(
15978                    "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
15979                    tokens.len()
15980                )
15981                .into());
15982            }
15983        }
15984
15985        let n_vocab = self.output.out_features();
15986        let n_embd = self.cfg.n_embd as usize;
15987        let mut cache =
15988            crate::pp::new_cache_planned(e, &self.cfg, &self.plan, tokens.len() + gamma + 8)?;
15989        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
15990        let embd_gpu = if spec_host_embd() {
15991            None
15992        } else {
15993            Some(
15994                self.embd_gpu
15995                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
15996            )
15997        };
15998        let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
15999
16000        struct PendingRecord {
16001            position: usize,
16002            hidden: Option<Vec<f32>>,
16003            tokens: Vec<u32>,
16004            target_top_ids: Vec<Option<Vec<u32>>>,
16005            target_top_logits: Vec<Option<Vec<f32>>>,
16006            target_top_probs: Vec<Option<Vec<f32>>>,
16007            target_tail_probs: Vec<Option<f32>>,
16008        }
16009
16010        let mut pending: Vec<PendingRecord> = anchor_positions
16011            .iter()
16012            .map(|&position| PendingRecord {
16013                position,
16014                hidden: None,
16015                tokens: tokens[position..=position + gamma].to_vec(),
16016                target_top_ids: vec![None; gamma],
16017                target_top_logits: vec![None; gamma],
16018                target_top_probs: vec![None; gamma],
16019                target_tail_probs: vec![None; gamma],
16020            })
16021            .collect();
16022
16023        let mut start = 0usize;
16024        while start < tokens.len() {
16025            let end = (start + chunk).min(tokens.len());
16026            let chunk_tokens = &tokens[start..end];
16027            let (target_logits, hidden_rows) =
16028                self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
16029            for record in &mut pending {
16030                let hidden_position = record.position - 1;
16031                if hidden_position >= start && hidden_position < end {
16032                    let local = hidden_position - start;
16033                    record.hidden = Some(
16034                        e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
16035                    );
16036                }
16037                for slot in 0..gamma {
16038                    let target_row = record.position + slot;
16039                    if target_row < start || target_row >= end {
16040                        continue;
16041                    }
16042                    let local = target_row - start;
16043                    let logits =
16044                        e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
16045                    let (ids, top_logits, probs, tail) =
16046                        dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
16047                    record.target_top_ids[slot] = Some(ids);
16048                    record.target_top_logits[slot] = Some(top_logits);
16049                    record.target_top_probs[slot] = Some(probs);
16050                    record.target_tail_probs[slot] = Some(tail);
16051                }
16052            }
16053            start = end;
16054        }
16055
16056        pending
16057            .into_iter()
16058            .map(|record| {
16059                let hidden = record
16060                    .hidden
16061                    .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
16062                let target_top_ids =
16063                    flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
16064                let target_top_logits = flatten_dspark_rows(
16065                    record.target_top_logits,
16066                    record.position,
16067                    "target logits",
16068                )?;
16069                let target_top_probs =
16070                    flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
16071                let target_tail_probs = record
16072                    .target_tail_probs
16073                    .into_iter()
16074                    .enumerate()
16075                    .map(|(slot, value)| {
16076                        value.ok_or_else(|| {
16077                            format!("missing DSpark tail at {} slot {slot}", record.position)
16078                        })
16079                    })
16080                    .collect::<Result<Vec<_>, _>>()?;
16081                Ok(DsparkAnchorRecord {
16082                    position: record.position,
16083                    hidden,
16084                    tokens: record.tokens,
16085                    target_top_ids,
16086                    target_top_logits,
16087                    target_top_probs,
16088                    target_tail_probs,
16089                })
16090            })
16091            .collect()
16092    }
16093
16094    /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
16095    /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
16096    /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
16097    /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
16098    /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
16099    /// quant-induced head/hidden-state mismatch from text drift.
16100    ///
16101    /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
16102    ///   draft_j  = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
16103    ///              eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
16104    ///   target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
16105    ///              at forced context tokens[0..p+j]). For j==0 this equals live spec
16106    ///              acceptance; for j>=1 live verify would condition on the drafts, here it
16107    ///              conditions on the corpus — deterministic and arm-comparable by design.
16108    ///
16109    /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
16110    /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
16111    /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
16112    ///
16113    /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
16114    /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
16115    /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
16116    /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
16117    /// agreement vs this path — not usable as a training-data source).
16118    #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
16119    pub fn replay_acceptance(
16120        &self,
16121        e: &Engine,
16122        tokens: &[u32],
16123        k: usize,
16124        stride: usize,
16125        chunk: usize,
16126        mut hdump: Option<&mut std::fs::File>,
16127    ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
16128        assert!(k >= 1 && stride >= 1 && chunk >= 2);
16129        let mtp = self
16130            .mtp
16131            .as_ref()
16132            .expect("replay_acceptance requires an MTP head");
16133        let n_vocab = self.output.out_features();
16134        let d_vocab = mtp
16135            .shared_head_head
16136            .as_ref()
16137            .unwrap_or(&self.output)
16138            .out_features();
16139        let n_embd = self.cfg.n_embd as usize;
16140        let t_total = tokens.len();
16141        assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
16142        // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
16143        let mut cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, t_total + k + 8)?;
16144        let mut scratch = self.new_mtp_scratch(e, t_total + k + 8)?;
16145        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
16146        let embd_gpu = if spec_host_embd() {
16147            None
16148        } else {
16149            Some(
16150                self.embd_gpu
16151                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
16152            )
16153        };
16154        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
16155
16156        // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
16157        let mut bg: Vec<u32> = vec![0; t_total + 1];
16158        let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
16159        let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
16160        let mut seed_buf = e.zeros(n_embd)?;
16161        let mut preds_d = e.alloc_u32_zeroed(chunk)?;
16162        let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
16163        let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
16164        let mut s = 0usize;
16165        while s < t_total {
16166            let cend = (s + chunk).min(t_total);
16167            let tc = cend - s;
16168            let ch = &tokens[s..cend];
16169            // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
16170            //    the chunk's true hiddens.
16171            let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
16172            for j in 0..tc {
16173                e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
16174            }
16175            let preds = e.dtoh_u32(&preds_d)?;
16176            for j in 0..tc {
16177                bg[s + j + 1] = preds[j];
16178            }
16179            // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
16180            // checkpoint-quality metric (position j's logits score the GOLD next token).
16181            if nll_on {
16182                let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
16183                if jmax > 0 {
16184                    let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
16185                    let rows: Vec<i32> = (0..jmax as i32).collect();
16186                    let idsd = e.htod_u32_v(&ids)?;
16187                    let rowsd = e.htod_i32(&rows)?;
16188                    let mut outd = e.zeros(jmax)?;
16189                    e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
16190                    for pr in e.dtoh(&outd)? {
16191                        nll_sum += -((pr.max(1e-30)) as f64).ln();
16192                        nll_cnt += 1;
16193                    }
16194                }
16195            }
16196            if let Some(f) = hdump.as_deref_mut() {
16197                use std::io::Write;
16198                let host: Vec<f32> = e.dtoh(&vx)?;
16199                // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
16200                // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
16201                let mut bytes = Vec::with_capacity(tc * n_embd * 2);
16202                for v in &host[..tc * n_embd] {
16203                    let b = v.to_bits();
16204                    let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
16205                    bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
16206                }
16207                f.write_all(&bytes)?;
16208            }
16209            // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
16210            // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
16211            // per token saved; the forced trunk pass + hdump is all the mode needs).
16212            let chainless = stride > t_total;
16213            if chainless {
16214                e.copy_view_into(
16215                    &mut prev_last_h,
16216                    0,
16217                    &vx.slice((tc - 1) * n_embd..tc * n_embd),
16218                    n_embd,
16219                )?;
16220                s = cend;
16221                continue;
16222            }
16223            // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
16224            //    row s reads the previous chunk's last true hidden, zeros at corpus start).
16225            let mut vxs = e.zeros(tc * n_embd)?;
16226            e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
16227            if tc > 1 {
16228                e.copy_view_into(
16229                    &mut vxs,
16230                    n_embd,
16231                    &vx.slice(0..(tc - 1) * n_embd),
16232                    (tc - 1) * n_embd,
16233                )?;
16234            }
16235            scratch.set_len(e, s)?;
16236            self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
16237            // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
16238            //    [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
16239            //    truncates those approximate appends before they can ever be read.
16240            let ps: Vec<usize> = (s..cend)
16241                .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
16242                .collect();
16243            for &p in ps.iter().rev() {
16244                scratch.set_len(e, p)?;
16245                if p == s {
16246                    e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
16247                } else {
16248                    e.copy_view_into(
16249                        &mut seed_buf,
16250                        0,
16251                        &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
16252                        n_embd,
16253                    )?;
16254                }
16255                let mut e_tok = tokens[p];
16256                let mut d_seed = e.clone_dtod(&seed_buf)?;
16257                let chain_heads = !self.mtp_extra.is_empty();
16258                let mut chain_tokens = if chain_heads {
16259                    vec![tokens[p]]
16260                } else {
16261                    Vec::new()
16262                };
16263                let mut chain_seeds = if chain_heads {
16264                    vec![e.clone_dtod(&seed_buf)?]
16265                } else {
16266                    Vec::new()
16267                };
16268                let mut drafts: Vec<u32> = Vec::with_capacity(k);
16269                for j in 0..k {
16270                    let (dl_d, h_nextn) = if chain_heads {
16271                        self.mtp_chain_forward_dev(
16272                            e,
16273                            &chain_tokens,
16274                            &chain_seeds,
16275                            &mut scratch,
16276                            p,
16277                            embd_dev,
16278                            None,
16279                        )?
16280                    } else {
16281                        self.mtp_head_forward_dev(
16282                            e,
16283                            mtp,
16284                            e_tok,
16285                            &d_seed,
16286                            &mut scratch,
16287                            p + 1 + j,
16288                            embd_dev,
16289                            None,
16290                        )?
16291                    };
16292                    let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
16293                    let idx = e.dtoh_u32_one(&tok_d)?;
16294                    let d = match &mtp.d2t {
16295                        Some(map) => map[idx as usize],
16296                        None => idx,
16297                    };
16298                    drafts.push(d);
16299                    if chain_heads {
16300                        chain_tokens.push(d);
16301                        chain_seeds.push(h_nextn);
16302                    } else {
16303                        e_tok = d;
16304                        d_seed = h_nextn;
16305                    }
16306                }
16307                // targets may live in a LATER chunk's bg — resolved after the walk.
16308                rows.push((p, drafts, Vec::new()));
16309            }
16310            // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
16311            //    expect scratch.len == cend with exact rows).
16312            scratch.set_len(e, s)?;
16313            self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
16314            e.copy_view_into(
16315                &mut prev_last_h,
16316                0,
16317                &vx.slice((tc - 1) * n_embd..tc * n_embd),
16318                n_embd,
16319            )?;
16320            s = cend;
16321        }
16322        for (p, drafts, targets) in rows.iter_mut() {
16323            for j in 0..drafts.len() {
16324                targets.push(bg[*p + 1 + j]);
16325            }
16326        }
16327        rows.sort_by_key(|r| r.0);
16328        if nll_cnt > 0 {
16329            let mean = nll_sum / nll_cnt as f64;
16330            println!(
16331                "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
16332                mean.exp()
16333            );
16334        }
16335        Ok((rows, bg))
16336    }
16337}
16338
16339#[cfg(test)]
16340mod vg_debt_tests {
16341    use super::dspark_vg_debt_projection;
16342
16343    /// TOOTH for the verify-graph admission accounting: the pool's projected remaining
16344    /// growth must be charged (pre-fix, admission charged 0 for a pool measured at
16345    /// 8,852 MiB), the projection must price the MARGINAL cost of one more key rather than
16346    /// extrapolating the pool's one-time shared allocation, and the doors that make growth
16347    /// impossible must zero the debt.
16348    #[test]
16349    fn vg_debt_projects_remaining_growth_and_respects_the_freeze_valves() {
16350        const MIB: usize = 1 << 20;
16351        let d = dspark_vg_debt_projection;
16352        // cold pool: nothing observed, one capture fits inside SPEC_SHRINK_RESERVE.
16353        assert_eq!(d(0, 256, 0, None), 0);
16354        // freeze valve MEMRA_DSPARK_VG_MAX=0: the pool cannot grow.
16355        assert_eq!(d(10, 0, 500 * MIB, None), 0);
16356        // saturated pool: at/past the cap the pool FREEZES, nothing left to reserve.
16357        assert_eq!(d(256, 256, 8852 * MIB, None), 0);
16358        assert_eq!(d(300, 256, 8852 * MIB, None), 0);
16359
16360        // BOOTSTRAP (one observation, growth unmeasurable): at most one more pool's worth.
16361        // The pre-fix mean rule extrapolated 255x here — the measured 8.5 GB phantom.
16362        assert_eq!(d(1, 256, 33 * MIB, None), 33 * MIB);
16363
16364        // MARGINAL, flat pool (the box9 receipt: reserved stayed ~33.6 MiB across captures
16365        // 1..3, so an additional key costs ~nothing and the debt must collapse to ~0 —
16366        // NOT the 8,556/4,261/2,830 MB the mean rule printed).
16367        assert_eq!(d(3, 256, 33 * MIB, Some((1, 33 * MIB))), 0);
16368
16369        // MARGINAL, genuinely growing pool: 40 MiB per new key over 2 keys, 250 slots left.
16370        let debt = d(6, 256, 273 * MIB, Some((4, 193 * MIB)));
16371        assert_eq!(debt, 250 * (40 * MIB));
16372        assert!(
16373            debt > 3 * (1536 * MIB),
16374            "real growth must dwarf SPEC_SHRINK_RESERVE"
16375        );
16376
16377        // a shrinking/recycled reading never becomes a negative charge.
16378        assert_eq!(d(6, 256, 10 * MIB, Some((4, 99 * MIB))), 0);
16379        // a stale observation at the same capture count falls back to bootstrap.
16380        assert_eq!(d(4, 256, 80 * MIB, Some((4, 80 * MIB))), 80 * MIB);
16381    }
16382}
16383
16384#[cfg(test)]
16385mod capture_headroom_tests {
16386    use super::{
16387        CAPTURE_HEADROOM_FLOOR, capture_err_is_oom, capture_headroom_verdict,
16388        draft_capture_bootstrap_estimate,
16389    };
16390
16391    /// TOOTH for the pre-capture reserve check (lane/step37-vram-admission-20260830): a
16392    /// capture attempt must be refused BEFORE it allocates when the device cannot cover its
16393    /// appetite plus the post-capture floor — and pool-cached bytes count as headroom
16394    /// (driver `free` alone under-counts, the wrong direction for a gate that drops
16395    /// coverage).
16396    #[test]
16397    fn capture_reserve_check_refuses_short_devices_and_counts_pool_cache() {
16398        const MIB: usize = 1 << 20;
16399        let need = 900 * MIB;
16400        // Plenty of room: no refusal.
16401        assert_eq!(
16402            capture_headroom_verdict(8_000 * MIB, 0, need, CAPTURE_HEADROOM_FLOOR),
16403            None
16404        );
16405        // The owner's shape: capture appetite would walk the card to the edge — refused,
16406        // with the arithmetic surfaced for the WARN line.
16407        let (required, effective) =
16408            capture_headroom_verdict(1_200 * MIB, 0, need, CAPTURE_HEADROOM_FLOOR)
16409                .expect("short device must refuse");
16410        assert_eq!(required, need + CAPTURE_HEADROOM_FLOOR);
16411        assert_eq!(effective, 1_200 * MIB);
16412        // Pool-cached bytes are real headroom (the trim path makes them driver-visible).
16413        assert_eq!(
16414            capture_headroom_verdict(1_200 * MIB, 7_000 * MIB, need, CAPTURE_HEADROOM_FLOOR),
16415            None
16416        );
16417        // Boundary: exactly enough is enough (>=, never a fencepost refusal).
16418        assert_eq!(
16419            capture_headroom_verdict(
16420                need + CAPTURE_HEADROOM_FLOOR,
16421                0,
16422                need,
16423                CAPTURE_HEADROOM_FLOOR
16424            ),
16425            None
16426        );
16427        // POLICY at the call site (owner-shape receipts, escalated twice on-box): the
16428        // refusal fn is handed 2x the appetite plus TWO floors — a capture may take at
16429        // most half the discretionary headroom, so the card retains a whole capture's
16430        // worth of room after it lands. One floor of slack above one appetite (the shape
16431        // that step-OOM'd on the owner cell) must therefore REFUSE under the call-site
16432        // requirement.
16433        assert!(
16434            capture_headroom_verdict(
16435                need + CAPTURE_HEADROOM_FLOOR + (100 << 20),
16436                0,
16437                2 * need,
16438                CAPTURE_HEADROOM_FLOOR * 2
16439            )
16440            .is_some()
16441        );
16442    }
16443
16444    #[test]
16445    fn bootstrap_estimate_scales_with_heads_and_never_underflows() {
16446        // 3-head chain on a step37-shaped vocab must expect strictly more than one head.
16447        let one = draft_capture_bootstrap_estimate(1, 3, 128_896, 4_096);
16448        let three = draft_capture_bootstrap_estimate(3, 3, 128_896, 4_096);
16449        assert!(three > one);
16450        // Degenerate shapes keep a sane minimum (the estimate feeds a refusal gate; a
16451        // zero-need gate refuses nothing).
16452        assert!(draft_capture_bootstrap_estimate(0, 0, 0, 0) >= 64 << 20);
16453    }
16454
16455    #[test]
16456    fn capture_oom_predicate_matches_the_quoted_driver_text() {
16457        assert!(capture_err_is_oom(
16458            "DriverError(CUDA_ERROR_OUT_OF_MEMORY, \"out of memory\")"
16459        ));
16460        assert!(capture_err_is_oom("allocation failed: out of memory"));
16461        assert!(!capture_err_is_oom("capture produced no graph"));
16462    }
16463}
16464
16465#[cfg(test)]
16466mod mtp_chain_tests {
16467    use super::mtp_chain_head_index;
16468
16469    #[test]
16470    fn embedded_step_heads_cycle_in_declared_order() {
16471        let actual: Vec<usize> = (0..8).map(|step| mtp_chain_head_index(step, 3)).collect();
16472        assert_eq!(actual, [0, 1, 2, 0, 1, 2, 0, 1]);
16473    }
16474
16475    #[test]
16476    fn standalone_draft_remains_single_head() {
16477        assert!((0..8).all(|step| mtp_chain_head_index(step, 1) == 0));
16478    }
16479}
16480
16481#[cfg(test)]
16482mod tp_verified_prefix_tests {
16483    use super::rewind_tp_kv_verified_prefix;
16484    use crate::tp::ResidentTpKvCache;
16485
16486    fn cache_with_committed_len(committed: usize) -> ResidentTpKvCache {
16487        let mut cache = ResidentTpKvCache::new(Vec::new(), 1, 1, 1, 1, 8);
16488        let transaction = cache.begin_transaction().unwrap();
16489        let target = cache.append_target(transaction, committed).unwrap();
16490        cache.publish_append(transaction, target).unwrap();
16491        let target = cache.commit_target(transaction, committed).unwrap();
16492        cache.publish_finalize(transaction, target).unwrap();
16493        cache
16494    }
16495
16496    #[test]
16497    fn replay_free_prefix_rewinds_tp_visibility_to_snapshot_plus_accepts() {
16498        let mut layers = vec![Some(cache_with_committed_len(5)), None];
16499        rewind_tp_kv_verified_prefix(&mut layers, &[Some(2), None], 1).unwrap();
16500        let cache = layers[0].as_ref().unwrap();
16501        assert_eq!(cache.committed_len(), 3);
16502        assert_eq!(cache.staged_len(), 3);
16503    }
16504
16505    #[test]
16506    fn replay_free_prefix_rejects_a_changed_tp_cache_shape() {
16507        let mut layers = vec![Some(cache_with_committed_len(1))];
16508        let error = rewind_tp_kv_verified_prefix(&mut layers, &[None], 1)
16509            .unwrap_err()
16510            .to_string();
16511        assert!(error.contains("changed shape"), "unexpected error: {error}");
16512    }
16513}
16514
16515#[cfg(test)]
16516mod dspark_sparse_tests {
16517    use super::dspark_sparse_softmax_topk;
16518
16519    #[test]
16520    fn topk_keeps_full_softmax_mass_and_stable_ties() {
16521        let logits = [1.0f32, 3.0, 3.0, -2.0];
16522        let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
16523        assert_eq!(ids, vec![1, 2]);
16524        assert_eq!(top_logits, vec![3.0, 3.0]);
16525        let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
16526        let expected = 1.0 / denominator;
16527        assert!((probs[0] - expected).abs() < 1.0e-6);
16528        assert!((probs[1] - expected).abs() < 1.0e-6);
16529        assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
16530        assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
16531    }
16532}
16533
16534#[cfg(test)]
16535mod spec_replay_env_tests {
16536    use super::spec_replay_env_on;
16537
16538    #[test]
16539    fn replay_requires_literal_one() {
16540        assert!(!spec_replay_env_on(None));
16541        assert!(!spec_replay_env_on(Some("")));
16542        assert!(!spec_replay_env_on(Some("0")));
16543        assert!(!spec_replay_env_on(Some("true")));
16544        assert!(!spec_replay_env_on(Some("2")));
16545        assert!(spec_replay_env_on(Some("1")));
16546    }
16547}
16548
16549#[cfg(test)]
16550mod telem_tests {
16551    use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
16552
16553    #[test]
16554    fn synthetic_accept_masks_produce_tau_and_position_histogram() {
16555        let counters = SpecTelemetryCounters::default();
16556        for mask in [
16557            [true, true, true],
16558            [true, true, false],
16559            [true, false, false],
16560            [false, false, false],
16561        ] {
16562            let accepted = mask.iter().take_while(|&&value| value).count();
16563            counters.record_round(mask.len(), accepted);
16564        }
16565
16566        let snapshot = counters.snapshot();
16567        assert_eq!(
16568            (snapshot.rounds, snapshot.drafted, snapshot.accepted),
16569            (4, 12, 6)
16570        );
16571        assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
16572        assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
16573        assert_eq!(snapshot.tau(), 1.5);
16574        assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
16575        assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
16576    }
16577
16578    /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
16579    /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
16580    #[test]
16581    fn delta_isolates_burst_contribution() {
16582        let mut t = SpecTelemetry::default();
16583        // "previous request": 2 rounds of k=3, accepts 3 then 1.
16584        for (kr, na) in [(3usize, 3usize), (3, 1)] {
16585            t.rounds += 1;
16586            t.drafted += kr as u64;
16587            t.accepted += na as u64;
16588            for j in 0..kr {
16589                t.pos_drafted[j] += 1;
16590            }
16591            for j in 0..na {
16592                t.pos_accepted[j] += 1;
16593            }
16594        }
16595        let before = t;
16596        // "this burst": 1 round k=3, accepts 2.
16597        t.rounds += 1;
16598        t.drafted += 3;
16599        t.accepted += 2;
16600        for j in 0..3 {
16601            t.pos_drafted[j] += 1;
16602        }
16603        for j in 0..2 {
16604            t.pos_accepted[j] += 1;
16605        }
16606        let d = t.delta_since(&before);
16607        assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
16608        assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
16609        assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
16610        assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
16611    }
16612
16613    /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
16614    /// aggregation invariant.
16615    #[test]
16616    fn merge_accumulates_fieldwise() {
16617        let mut agg = SpecTelemetry::default();
16618        let mut d1 = SpecTelemetry {
16619            rounds: 2,
16620            drafted: 6,
16621            accepted: 4,
16622            ..Default::default()
16623        };
16624        d1.pos_drafted[0] = 2;
16625        d1.pos_accepted[0] = 2;
16626        let mut d2 = SpecTelemetry {
16627            rounds: 1,
16628            drafted: 3,
16629            accepted: 1,
16630            ..Default::default()
16631        };
16632        d2.pos_drafted[0] = 1;
16633        d2.pos_accepted[0] = 1;
16634        d2.pos_drafted[1] = 1;
16635        agg.merge(&d1);
16636        agg.merge(&d2);
16637        assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
16638        assert_eq!(agg.pos_drafted[0], 3);
16639        assert_eq!(agg.pos_accepted[0], 3);
16640        assert_eq!(agg.pos_drafted[1], 1);
16641        assert_eq!(agg.pos_accepted[1], 0);
16642    }
16643
16644    /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
16645    /// public metrics surface and must never publish a u64-wrapped garbage value.
16646    #[test]
16647    fn delta_saturates_never_wraps() {
16648        let small = SpecTelemetry {
16649            rounds: 1,
16650            drafted: 2,
16651            accepted: 1,
16652            ..Default::default()
16653        };
16654        let big = SpecTelemetry {
16655            rounds: 5,
16656            drafted: 15,
16657            accepted: 9,
16658            ..Default::default()
16659        };
16660        let d = small.delta_since(&big);
16661        assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
16662    }
16663}
16664
16665#[cfg(test)]
16666mod opti_fork_tests {
16667    use super::{
16668        OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
16669    };
16670
16671    #[test]
16672    fn controller_threshold_and_three_miss_breaker_are_exact() {
16673        let mut policy = OptiControllerPolicy {
16674            threshold: 0.7,
16675            consecutive_misses: 0,
16676            breaker_tripped: false,
16677        };
16678        assert!(!policy.admit(0.699_999));
16679        assert!(policy.admit(0.7));
16680        assert!(!policy.resolve(false));
16681        assert!(!policy.resolve(false));
16682        assert!(policy.resolve(false));
16683        assert!(policy.breaker_tripped);
16684        assert!(!policy.admit(1.0));
16685        assert!(
16686            !policy.resolve(true),
16687            "a resolved hit cannot re-arm a tripped request"
16688        );
16689        assert!(policy.breaker_tripped);
16690    }
16691
16692    #[test]
16693    fn zero_threshold_is_the_true_unconditional_measurement_arm() {
16694        let mut policy = OptiControllerPolicy {
16695            threshold: 0.0,
16696            consecutive_misses: 0,
16697            breaker_tripped: false,
16698        };
16699        for _ in 0..16 {
16700            assert!(policy.admit(0.0));
16701            assert!(!policy.resolve(false));
16702        }
16703        for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
16704            assert!(
16705                !policy.admit(invalid),
16706                "invalid q proxy must fail closed: {invalid}"
16707            );
16708        }
16709        assert!(!policy.breaker_tripped);
16710        assert_eq!(policy.consecutive_misses, 0);
16711    }
16712
16713    #[test]
16714    fn alternating_mode_flips_by_generation_not_round_parity() {
16715        assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
16716        assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
16717        assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
16718        assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
16719    }
16720
16721    #[test]
16722    fn live_generation_cannot_be_overwritten() {
16723        let mut tracker = OptiForkGenerationTracker::default();
16724        let g0 = tracker.reserve().unwrap();
16725        let g1 = tracker.reserve().unwrap();
16726        let err = tracker.reserve().unwrap_err().to_string();
16727        assert!(
16728            err.contains("still owns generation 0"),
16729            "unexpected error: {err}"
16730        );
16731        tracker.retire(g0).unwrap();
16732        let g2 = tracker.reserve().unwrap();
16733        assert_eq!((g2.id, g2.slot), (2, 0));
16734        tracker.retire(g1).unwrap();
16735        tracker.retire(g2).unwrap();
16736    }
16737
16738    #[test]
16739    fn teardown_rejects_a_stale_generation_tag() {
16740        let mut tracker = OptiForkGenerationTracker::default();
16741        let g0 = tracker.reserve().unwrap();
16742        tracker.retire(g0).unwrap();
16743        let err = tracker.retire(g0).unwrap_err().to_string();
16744        assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
16745    }
16746}
16747
16748#[cfg(test)]
16749mod draft_graph_fallback_tests {
16750    use super::DraftGraphFallback;
16751
16752    /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
16753    #[test]
16754    fn flip_is_loud_once_and_memoized_after() {
16755        let mut f = DraftGraphFallback::default();
16756        let line = f
16757            .mark_greedy("out of memory")
16758            .expect("first flip must return the warn line");
16759        assert!(
16760            line.contains("WARN"),
16761            "flip line must be warn-level: {line}"
16762        );
16763        assert!(
16764            line.contains("out of memory"),
16765            "flip line must carry the reason: {line}"
16766        );
16767        assert!(f.greedy_failed());
16768        // re-marking an already-failed graph is the memoization: quiet, still failed.
16769        assert!(f.mark_greedy("out of memory").is_none());
16770        assert!(f.greedy_failed());
16771        // the two graphs' flags are independent (greedy flip leaves sampled capturable).
16772        assert!(!f.sampled_failed());
16773        let line_s = f
16774            .mark_sampled("capture unsupported")
16775            .expect("sampled flip is its own flip");
16776        assert!(
16777            line_s.contains("sampled"),
16778            "sampled flip names itself: {line_s}"
16779        );
16780        assert!(f.mark_sampled("capture unsupported").is_none());
16781    }
16782
16783    /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
16784    /// and says so exactly when there was something to reset.
16785    #[test]
16786    fn reset_on_resume_clears_flags_and_logs_once() {
16787        let mut f = DraftGraphFallback::default();
16788        // clean session: resume is silent, nothing to reset.
16789        assert!(f.reset_on_resume().is_none());
16790        f.mark_greedy("oom").unwrap();
16791        f.mark_sampled("oom").unwrap();
16792        let note = f
16793            .reset_on_resume()
16794            .expect("a set flag must produce the reset note");
16795        assert!(
16796            note.contains("greedy+sampled"),
16797            "note names what was reset: {note}"
16798        );
16799        assert!(
16800            !f.greedy_failed() && !f.sampled_failed(),
16801            "both flags cleared"
16802        );
16803        // and the NEXT failure after a reset is a fresh flip — loud again.
16804        assert!(f.mark_greedy("oom again").is_some());
16805        let note2 = f.reset_on_resume().expect("greedy-only reset");
16806        assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
16807    }
16808
16809    /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
16810    /// they precede a fresh capture attempt whose own failure re-flips loudly.
16811    #[test]
16812    fn shape_change_clears_are_silent() {
16813        let mut f = DraftGraphFallback::default();
16814        f.mark_greedy("oom").unwrap();
16815        f.clear_greedy();
16816        assert!(!f.greedy_failed());
16817        f.mark_sampled("oom").unwrap();
16818        f.clear_sampled();
16819        assert!(!f.sampled_failed());
16820        // after a silent clear there is nothing left for resume to report.
16821        assert!(f.reset_on_resume().is_none());
16822    }
16823}
16824
16825/// SAMPLED DRAFT-GRAPH KEY (lane/graph-s-key-exactness-20260819).
16826///
16827/// These are the CPU teeth for an exactness bug whose live reproduction needs a GPU, a trunk, a
16828/// drafter and a two-turn session: the key itself. Every test below fails against the pre-fix key
16829/// `(seed, temp.to_bits(), k)` — `legacy_key` restates it so the collision is explicit rather
16830/// than remembered.
16831#[cfg(test)]
16832mod sampled_graph_key_tests {
16833    use super::{SampledGraphKey, debug_t_pred0};
16834
16835    /// The pre-fix key, verbatim: `let s_key = (sp_seed, sp_temp.to_bits(), k);`
16836    fn legacy_key(k: &SampledGraphKey) -> (u64, u32, usize) {
16837        (k.seed, k.temp_bits, k.k)
16838    }
16839
16840    fn pure_temp_key() -> SampledGraphKey {
16841        // temperature 1.0, filters off — today's serve default, the shape that parks a graph.
16842        SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, false)
16843    }
16844
16845    /// THE COLLISION. Two requests that differ ONLY in the truncation filters shared one key, so
16846    /// a parked pure-temp graph survived into a filtered request and the launch site launched it.
16847    #[test]
16848    fn vendor_filters_change_the_key() {
16849        let parked = pure_temp_key();
16850        // qwen3.8 generation_config.json — what the vendor-default flip makes the default shape.
16851        let vendor = SampledGraphKey::new(12345, 1.0, 3, 20, 0.95, 0.0, false);
16852        assert_eq!(
16853            legacy_key(&parked),
16854            legacy_key(&vendor),
16855            "pre-fix key collided: this is the bug, and the reason a test asserts on it",
16856        );
16857        assert_ne!(parked, vendor, "post-fix key must separate the two regimes");
16858        assert!(parked.pure_temp());
16859        assert!(!vendor.pure_temp());
16860    }
16861
16862    /// Each distribution-shaping field alone is enough to drop the parked graph.
16863    #[test]
16864    fn every_filter_field_is_keyed() {
16865        let base = pure_temp_key();
16866        for (what, other) in [
16867            (
16868                "top_k",
16869                SampledGraphKey::new(12345, 1.0, 3, 20, 1.0, 0.0, false),
16870            ),
16871            (
16872                "top_p",
16873                SampledGraphKey::new(12345, 1.0, 3, 0, 0.95, 0.0, false),
16874            ),
16875            (
16876                "min_p",
16877                SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.05, false),
16878            ),
16879            (
16880                "penalties",
16881                SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, true),
16882            ),
16883        ] {
16884            assert_ne!(base, other, "{what} must be part of the key");
16885            assert!(!other.pure_temp(), "{what} leaves the pure-temp regime");
16886            assert_eq!(
16887                legacy_key(&base),
16888                legacy_key(&other),
16889                "{what} was invisible to the pre-fix key",
16890            );
16891        }
16892    }
16893
16894    /// The baked constants stay keyed (this half was always right — regression cover for it).
16895    #[test]
16896    fn baked_constants_stay_keyed() {
16897        let base = pure_temp_key();
16898        assert_ne!(
16899            base,
16900            SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false),
16901            "seed"
16902        );
16903        assert_ne!(
16904            base,
16905            SampledGraphKey::new(12345, 0.7, 3, 0, 1.0, 0.0, false),
16906            "temp"
16907        );
16908        assert_ne!(
16909            base,
16910            SampledGraphKey::new(12345, 1.0, 4, 0, 1.0, 0.0, false),
16911            "k"
16912        );
16913        // bitwise on temperature: 0.7f32 vs the same value re-derived must NOT differ.
16914        assert_eq!(
16915            SampledGraphKey::new(1, 0.7, 3, 0, 1.0, 0.0, false),
16916            SampledGraphKey::new(1, 7.0 / 10.0, 3, 0, 1.0, 0.0, false),
16917        );
16918    }
16919
16920    /// THE LOAD-BEARING HALF OF THE SEED DECISION (lane/session-resume-sampler-predicate-
16921    /// 20260820). The whole-session resume predicate deliberately does NOT compare `seed`: an
16922    /// omitted serve `seed` draws fresh per-request entropy, so comparing it would refuse every
16923    /// seed-omitting sampled conversation. That is only sound because the one piece of parked state
16924    /// that BAKES the seed — this graph — is re-keyed on it, so a seed change drops and recaptures.
16925    ///
16926    /// This test is the other end of that argument, asserted here rather than remembered in a
16927    /// comment: if a future change dropped `seed` from the key, the resume predicate's exclusion
16928    /// would silently become the unsound thing it is documented not to be.
16929    /// (Paired with `seed_alone_does_not_refuse` in `memra-sampling`.)
16930    #[test]
16931    fn seed_alone_still_rekeys_the_draft_graph() {
16932        let parked = pure_temp_key();
16933        let reseeded = SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false);
16934        assert_ne!(
16935            parked, reseeded,
16936            "a seed-only change MUST drop the parked sampled graph — the resume predicate's \
16937             decision not to compare seed rests on exactly this",
16938        );
16939        // Same regime on both sides: the drop is a recapture, not a fall to the eager chain
16940        // because of a filter difference.
16941        assert!(parked.pure_temp() && reseeded.pure_temp());
16942    }
16943
16944    /// `pure_temp()` is the capture guard's predicate, computed from the key so the two cannot
16945    /// drift. The equality below is the invariant the launch-site guard asserts: identical keys
16946    /// agree on the regime, so a graph that survives the drop is legal to launch.
16947    #[test]
16948    fn equal_keys_agree_on_the_regime() {
16949        let a = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
16950        let b = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
16951        assert_eq!(a, b);
16952        assert_eq!(a.pure_temp(), b.pure_temp());
16953        // top_p slightly above 1.0 (a client sending 1.0 exactly, or an operator default) is
16954        // still the unfiltered regime, matching the original `sp.top_p >= 1.0` test.
16955        assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.0, 0.0, false).pure_temp());
16956        assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.5, -1.0, false).pure_temp());
16957    }
16958
16959    /// The WIDENED capture regime (lane/step37-draft-graph-serving-20260830): truncation-
16960    /// filtered shapes are capturable — the filter runs IN-GRAPH (`filter_stats` +
16961    /// `gumbel_perturb_filtered_ctr`), so the draft draws from the same filtered
16962    /// distribution the accept test reconstructs. Penalties never are: the per-round
16963    /// history cannot be baked. The step37 vendor-default shape (temp 0.5 / top_p 0.9) is
16964    /// exactly the previously-excluded regime this lane exists to capture.
16965    #[test]
16966    fn filtered_regimes_are_capturable_penalties_never() {
16967        let vendor = SampledGraphKey::new(12345, 0.5, 3, 0, 0.9, 0.0, false);
16968        assert!(!vendor.pure_temp());
16969        assert!(vendor.filtered());
16970        assert!(
16971            vendor.graph_capturable(),
16972            "the vendor-default filtered shape must be capturable (default door state)",
16973        );
16974        assert!(pure_temp_key().graph_capturable());
16975        assert!(
16976            !pure_temp_key().filtered(),
16977            "pure-temp takes the legacy (filterless) capture body",
16978        );
16979        let pen = SampledGraphKey::new(12345, 0.5, 3, 0, 0.9, 0.0, true);
16980        assert!(
16981            !pen.graph_capturable(),
16982            "penalty history varies per round and can never be baked into a graph",
16983        );
16984    }
16985
16986    /// MEMRA_DEBUG_SPEC on a SAMPLED spec request past round 0: the print must render without
16987    /// indexing the empty greedy `preds` vector (it panicked the GPU worker before this lane).
16988    #[test]
16989    fn debug_print_survives_the_sampled_arm() {
16990        // round >= 1 with a pending bonus == base 1, sampled == `preds` empty.
16991        assert_eq!(debug_t_pred0(true, 1, 4242, &[]), "n/a");
16992        assert_eq!(debug_t_pred0(true, 2, 4242, &[]), "n/a");
16993        // round 0 without a pending bonus still reports last_pred, in both arms.
16994        assert_eq!(debug_t_pred0(true, 0, 4242, &[]), "4242");
16995        assert_eq!(debug_t_pred0(false, 0, 4242, &[7, 8]), "4242");
16996        // greedy keeps the real prediction it always printed.
16997        assert_eq!(debug_t_pred0(false, 1, 4242, &[7, 8]), "7");
16998        assert_eq!(debug_t_pred0(false, 2, 4242, &[7, 8]), "8");
16999    }
17000}