Skip to main content

memra_engine/
spec.rs

1//! Qwen3.5 MTP (NextN) greedy speculative decode (research/mtp/MTP-PLAN.md §A/§B/§C/§D).
2//!
3//! Greedy spec decode is MATHEMATICALLY EXACT: the accepted+bonus token stream is token-for-token
4//! identical to plain greedy `generate`. This module provides:
5//!   - `mtp_head_forward`  (§A, T=1): one NextN draft-token forward.
6//!   - `decode_step_t`     (§D.3, T=K+1): batched target verify forward, all-column logits.
7//!   - `generate_spec`     (§B): the draft/verify/accept/rollback orchestrator.
8//! Cache snapshot/rollback lives in cache.rs (§D.4). The MTP head uses its OWN scratch KV (§D.6),
9//! PERSISTENT over the committed sequence (see `MtpScratch`).
10
11use crate::cache::{Cache, KvLayer};
12use crate::forward::argmax;
13use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer, MtpHead};
14use crate::Engine;
15use cudarc::driver::CudaSlice;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18/// One compact, anchor-bounded DSpark supervision record. `tokens[0]` is the anchor at p and
19/// `hidden` is its predecessor carrier h[p-1], matching the live NextN/DSpark pairing. Target
20/// rows p..p+gamma-1 score tokens p+1..p+gamma. They are the full-target softmax's top-k
21/// entries; `target_tail_probs[j]` is the probability mass outside those rows. All flattened
22/// target arrays are `[gamma, top_k]` in row-major order.
23pub struct DsparkAnchorRecord {
24    pub position: usize,
25    pub hidden: Vec<f32>,
26    pub tokens: Vec<u32>,
27    pub target_top_ids: Vec<u32>,
28    pub target_top_logits: Vec<f32>,
29    pub target_top_probs: Vec<f32>,
30    pub target_tail_probs: Vec<f32>,
31}
32
33fn dspark_sparse_softmax_topk(
34    logits: &[f32],
35    top_k: usize,
36    temperature: f32,
37) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>, f32), Box<dyn std::error::Error>> {
38    if logits.is_empty() || top_k == 0 || top_k > logits.len() || temperature <= 0.0 {
39        return Err("invalid DSpark sparse-softmax shape or temperature".into());
40    }
41    if logits.iter().any(|value| !value.is_finite()) {
42        return Err("DSpark target logits contain a non-finite value".into());
43    }
44    let mut ranked: Vec<(u32, f32)> = logits
45        .iter()
46        .copied()
47        .enumerate()
48        .map(|(index, value)| (index as u32, value))
49        .collect();
50    let compare = |left: &(u32, f32), right: &(u32, f32)| {
51        right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
52    };
53    ranked.select_nth_unstable_by(top_k - 1, compare);
54    ranked[..top_k].sort_unstable_by(compare);
55
56    let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
57    let inv_temperature = 1.0f64 / temperature as f64;
58    let denominator: f64 = logits
59        .iter()
60        .map(|value| (((*value - max_logit) as f64) * inv_temperature).exp())
61        .sum();
62    let ids: Vec<u32> = ranked[..top_k].iter().map(|(index, _)| *index).collect();
63    let top_logits: Vec<f32> = ranked[..top_k].iter().map(|(_, value)| *value).collect();
64    let top_probs: Vec<f32> = top_logits
65        .iter()
66        .map(|value| {
67            ((((value - max_logit) as f64) * inv_temperature).exp() / denominator) as f32
68        })
69        .collect();
70    let top_mass: f64 = top_probs.iter().map(|value| *value as f64).sum();
71    let tail = (1.0f64 - top_mass).clamp(0.0, 1.0) as f32;
72    Ok((ids, top_logits, top_probs, tail))
73}
74
75fn flatten_dspark_rows<T>(
76    rows: Vec<Option<Vec<T>>>,
77    position: usize,
78    label: &str,
79) -> Result<Vec<T>, Box<dyn std::error::Error>> {
80    let mut flattened = Vec::new();
81    for (slot, row) in rows.into_iter().enumerate() {
82        flattened.extend(
83            row.ok_or_else(|| format!("missing DSpark {label} at {position} slot {slot}"))?,
84        );
85    }
86    Ok(flattened)
87}
88
89/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
90/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
91/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
92/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
93/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
94/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
95/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
96pub(crate) fn spec_hpost() -> bool {
97    static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
98    *H.get_or_init(|| {
99        std::env::var("MEMRA_SPEC_HPOST")
100            .map(|v| v != "0")
101            .unwrap_or(false)
102    })
103}
104
105/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
106/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
107/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
108/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
109/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
110/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
111/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
112/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
113/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
114pub(crate) fn spec_lean() -> bool {
115    static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
116    // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
117    // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
118    // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
119    *L.get_or_init(|| {
120        std::env::var("MEMRA_SPEC_LEAN")
121            .map(|v| v != "0")
122            .unwrap_or(true)
123    })
124}
125
126/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
127/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
128/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
129/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
130/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
131/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
132///     ring — the ring stores raw input columns); every arithmetic kernel is the same one the
133///     t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
134///     t-loop == chained T=1 steps);
135/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
136///     pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
137/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
138pub(crate) fn spec_m2() -> bool {
139    static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
140    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
141    // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
142    // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
143    // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
144    *M.get_or_init(|| {
145        std::env::var("MEMRA_SPEC_M2")
146            .map(|v| v != "0")
147            .unwrap_or(true)
148    })
149}
150pub(crate) fn spec_stream() -> bool {
151    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
152    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
153}
154pub(crate) fn spec_stream_m() -> usize {
155    static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
156    *M.get_or_init(|| {
157        std::env::var("MEMRA_SPEC_STREAM_M")
158            .ok()
159            .and_then(|v| v.parse().ok())
160            .unwrap_or(4)
161    })
162}
163pub(crate) fn spec_devacc() -> bool {
164    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
165    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
166}
167
168/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
169/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
170/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
171/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
172/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
173/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
174/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
175/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
176/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
177pub trait SpecConstraint {
178    /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
179    /// masked argmax).
180    fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
181    /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
182    fn mask_words(&mut self) -> Result<Vec<u32>, String>;
183    /// Is `tok` consumable in the CURRENT state?
184    fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
185    /// Advance the state with an emitted token.
186    fn consume(&mut self, tok: u32) -> Result<(), String>;
187
188    // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
189    // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
190    // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
191    // loose, research/constrained-full-20260803). These three methods let the engine mask the
192    // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
193    // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
194    // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
195    // stays the correctness backstop and the emitted stream is unchanged by construction
196    // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
197    // argmax; a cut slot is recomputed as the masked argmax either way).
198    // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
199
200    /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
201    /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
202    fn draft_mask_enabled(&self) -> bool {
203        false
204    }
205    /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
206    /// slot. Called once per spec round, before the first draft position.
207    fn draft_begin(&mut self) -> Result<(), String> {
208        Ok(())
209    }
210    /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
211    /// for the draft position about to be sampled. `None` = draft masking off (no-op).
212    fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
213        Ok(None)
214    }
215    /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
216    /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
217    /// engine stops drafting; the token already pushed still goes through verify.
218    fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
219        Ok(false)
220    }
221}
222
223/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
224/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
225/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
226/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
227/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
228/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
229/// verify emits the masked argmax as usual).
230fn upload_draft_mask(
231    e: &Engine,
232    c: &mut dyn SpecConstraint,
233    dst: &mut CudaSlice<u32>,
234    d2t: Option<&Vec<u32>>,
235    d_vocab: usize,
236    words: usize,
237) -> Result<bool, Box<dyn std::error::Error>> {
238    let Some(tw) = c.draft_mask_words().map_err(|e2| format!("constraint: {e2}"))? else {
239        return Ok(false);
240    };
241    let bit = |t: usize| -> bool {
242        let w = t >> 5;
243        w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
244    };
245    let mut buf = vec![0u32; words];
246    match d2t {
247        // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
248        Some(map) => {
249            for (i, &t) in map.iter().enumerate().take(d_vocab) {
250                if bit(t as usize) {
251                    buf[i >> 5] |= 1u32 << (i & 31);
252                }
253            }
254        }
255        // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
256        // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
257        None => {
258            let n = tw.len().min(words);
259            buf[..n].copy_from_slice(&tw[..n]);
260        }
261    }
262    if buf.iter().all(|w| *w == 0) {
263        return Ok(false);
264    }
265    e.htod_u32_into(dst, &buf)?;
266    Ok(true)
267}
268
269/// Keep the full token-embedding table in host memory and upload only the rows needed by each
270/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
271/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
272/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
273pub(crate) fn spec_host_embd() -> bool {
274    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
275    *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
276}
277
278/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
279/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
280/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
281/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
282/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
283/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
284/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
285/// run-spec K=1..8 + acceptance identity arbitrate e2e).
286pub(crate) fn spec_fused_t() -> bool {
287    static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
288    // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
289    // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
290    // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
291    *F.get_or_init(|| {
292        std::env::var("MEMRA_SPEC_FUSED_T")
293            .map(|v| v != "0")
294            .unwrap_or(true)
295    })
296}
297
298/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
299/// Only call this on such buffers — the lean contract is "identical bytes by construction".
300fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
301    if spec_lean() {
302        e.uninit(n)
303    } else {
304        e.zeros(n)
305    }
306}
307
308/// Scratch KV for the MTP block (one full-attn layer).
309///
310/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
311/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
312/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
313/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
314/// engine's "mtp_update" design). Entries come from two sources:
315///   - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
316///     hidden chain-approximate — the reference engine accepts the same);
317///   - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
318///     from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
319/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
320/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
321/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
322/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
323/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
324/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
325/// committed row across turns (the predecessor-pairing seed + fill anchor).
326/// Per-request sampling config for the sampled-spec serve path.
327#[derive(Clone, Copy, Debug)]
328pub struct SpecSampling {
329    pub temp: f32,
330    pub seed: u64,
331    pub top_k: i32,            // 0 = off
332    pub top_p: f32,            // 1.0 = off
333    pub min_p: f32,            // 0.0 = off
334    pub penalty_last_n: usize, // 0 = penalties off
335    pub penalty_repeat: f32,
336    pub penalty_freq: f32,
337    pub penalty_present: f32,
338}
339
340/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
341/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
342pub const SPEC_TELEM_POS: usize = 8;
343
344/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
345/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
346/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
347/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
348/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
349/// in NEITHER drafted nor accepted.
350#[derive(Clone, Copy, Default, Debug)]
351pub struct SpecTelemetry {
352    /// verify rounds completed (a round-stream burst counts each of its M rounds).
353    pub rounds: u64,
354    /// tokens drafted / accepted across all rounds.
355    pub drafted: u64,
356    pub accepted: u64,
357    /// how often draft position j (0-based within a round's chain) was offered / accepted.
358    /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
359    /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
360    /// arrays cover the standard-path rounds only and their sums may undercount the totals.
361    pub pos_drafted: [u64; SPEC_TELEM_POS],
362    pub pos_accepted: [u64; SPEC_TELEM_POS],
363}
364
365impl SpecTelemetry {
366    /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
367    /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
368    /// a wrapped counter.
369    pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
370        let mut d = SpecTelemetry {
371            rounds: self.rounds.saturating_sub(prev.rounds),
372            drafted: self.drafted.saturating_sub(prev.drafted),
373            accepted: self.accepted.saturating_sub(prev.accepted),
374            ..Default::default()
375        };
376        for j in 0..SPEC_TELEM_POS {
377            d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
378            d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
379        }
380        d
381    }
382    /// Fieldwise `self += d` — the worker's per-model aggregation.
383    pub fn merge(&mut self, d: &SpecTelemetry) {
384        self.rounds += d.rounds;
385        self.drafted += d.drafted;
386        self.accepted += d.accepted;
387        for j in 0..SPEC_TELEM_POS {
388            self.pos_drafted[j] += d.pos_drafted[j];
389            self.pos_accepted[j] += d.pos_accepted[j];
390        }
391    }
392
393    /// Mean accepted draft-prefix length per verify round (tau).
394    pub fn tau(&self) -> f64 {
395        if self.rounds > 0 {
396            self.accepted as f64 / self.rounds as f64
397        } else {
398            0.0
399        }
400    }
401}
402
403/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
404/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
405/// launch, synchronization, allocation, or ordering dependency to the numeric path.
406struct SpecTelemetryCounters {
407    rounds: AtomicU64,
408    drafted: AtomicU64,
409    accepted: AtomicU64,
410    pos_drafted: [AtomicU64; SPEC_TELEM_POS],
411    pos_accepted: [AtomicU64; SPEC_TELEM_POS],
412}
413
414impl Default for SpecTelemetryCounters {
415    fn default() -> Self {
416        Self {
417            rounds: AtomicU64::new(0),
418            drafted: AtomicU64::new(0),
419            accepted: AtomicU64::new(0),
420            pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
421            pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
422        }
423    }
424}
425
426impl SpecTelemetryCounters {
427    fn record_round(&self, drafted: usize, accepted: usize) {
428        debug_assert!(accepted <= drafted);
429        self.rounds.fetch_add(1, Ordering::Relaxed);
430        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
431        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
432        for counter in self.pos_drafted.iter().take(drafted) {
433            counter.fetch_add(1, Ordering::Relaxed);
434        }
435        for counter in self.pos_accepted.iter().take(accepted) {
436            counter.fetch_add(1, Ordering::Relaxed);
437        }
438    }
439
440    /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
441    /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
442    fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
443        self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
444        self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
445        self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
446    }
447
448    fn snapshot(&self) -> SpecTelemetry {
449        SpecTelemetry {
450            rounds: self.rounds.load(Ordering::Relaxed),
451            drafted: self.drafted.load(Ordering::Relaxed),
452            accepted: self.accepted.load(Ordering::Relaxed),
453            pos_drafted: std::array::from_fn(|j| {
454                self.pos_drafted[j].load(Ordering::Relaxed)
455            }),
456            pos_accepted: std::array::from_fn(|j| {
457                self.pos_accepted[j].load(Ordering::Relaxed)
458            }),
459        }
460    }
461}
462
463pub struct SpecSession {
464    pub(crate) cache: Cache,
465    pub(crate) scratch: MtpScratch,
466    /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
467    /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
468    /// session must count them. Callers render output from this, not from their own echo.
469    pub committed: Vec<u32>,
470    /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
471    pub(crate) last_h: Option<CudaSlice<f32>>,
472    /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
473    /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
474    /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
475    pub next_pred: Option<u32>,
476    /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
477    /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
478    pub sctr: u32,
479    pub uctr: u32,
480    /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
481    /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
482    /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
483    /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
484    /// research/spec-serving-20260801). None before the first turn; error paths drop it
485    /// (next burst recaptures — serve retires errored sessions anyway).
486    pub(crate) draft_ctx: Option<DraftGraphCtx>,
487    /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
488    /// emitted by the last round but NOT committed to the caches. The old tail committed it with
489    /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
490    /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
491    /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
492    /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
493    /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
494    /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
495    /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
496    /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
497    /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
498    pub pending_tok: Option<u32>,
499    /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
500    /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
501    /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
502    /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
503    pub(crate) turn_ckpt: Option<SpecCheckpoint>,
504    /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
505    /// accounting the loop already does — no syncs, no allocation. NOTE a
506    /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
507    /// diff with [`SpecTelemetry::delta_since`] around each burst.
508    telem: SpecTelemetryCounters,
509}
510impl SpecSession {
511    /// Context capacity of the session's caches (the server's ContextFull guard).
512    pub fn cache_max_ctx(&self) -> usize {
513        self.cache.max_ctx
514    }
515    /// Snapshot the session's process-local acceptance counters for per-burst diffing.
516    pub fn telemetry(&self) -> SpecTelemetry {
517        self.telem.snapshot()
518    }
519    /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
520    /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
521    /// `spec_rewind_to_checkpoint`.
522    pub fn rewind_pos(&self) -> Option<usize> {
523        self.turn_ckpt.as_ref().map(|c| c.pos)
524    }
525    /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
526    pub fn rewind_is_resident(&self) -> bool {
527        self.turn_ckpt.as_ref().is_some_and(|ckpt| {
528            self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
529        })
530    }
531    /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
532    /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
533    /// session has never run a turn and has no prediction to hand over.
534    pub fn demote_ready(&self) -> bool {
535        self.pending_tok.is_none() && self.next_pred.is_some()
536    }
537    /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
538    pub fn has_pending(&self) -> bool {
539        self.pending_tok.is_some()
540    }
541    /// Committed row count == cache rows (the session invariant), for the caller's own
542    /// `fed`-length cross-check at a handoff boundary.
543    pub fn committed_len(&self) -> usize {
544        self.committed.len()
545    }
546    /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
547    /// cache + next-token prediction to the plain batched-decode path.
548    ///
549    /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
550    /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
551    /// tokenwise prime of the same `committed` sequence would have left it (that is the
552    /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
553    /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
554    /// committed row — and verify-column logits are bit-identical to plain decode's logits at
555    /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
556    /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
557    /// a state indistinguishable from one the batched path produced itself: the batched tick
558    /// emits `next_pred`, feeds it into this same cache, and decodes on.
559    ///
560    /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
561    /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
562    /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
563    /// path would silently skip a token.
564    ///
565    /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
566    /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
567    /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
568    /// would mean an `mtp_kv_fill` over the whole committed history).
569    pub fn into_demoted(self) -> Option<(Cache, u32)> {
570        if self.pending_tok.is_some() {
571            return None;
572        }
573        let np = self.next_pred?;
574        debug_assert_eq!(
575            self.cache.pos,
576            self.committed.len(),
577            "demotion handoff: cache rows != committed tokens"
578        );
579        Some((self.cache, np))
580    }
581    /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
582    /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
583    /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
584    /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
585    pub fn reset_graph_fallback_on_resume(&mut self) {
586        if let Some(line) = self
587            .draft_ctx
588            .as_mut()
589            .and_then(|c| c.failed.reset_on_resume())
590        {
591            eprintln!("{line}");
592        }
593    }
594}
595
596/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
597///
598/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
599/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
600/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
601/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
602/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
603/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
604///
605/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
606/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
607/// position index, so it must be a real device COPY — that copy is the entire reason a spec
608/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
609/// below the boundary were written by this turn's fill and are never revisited (the per-round
610/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
611/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
612/// predecessor-pairing anchor the next prime's fill reads for its first row.
613///
614/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
615pub(crate) struct SpecCheckpoint {
616    snap: crate::cache::CacheSnapshot,
617    /// Committed length at the boundary (== cache.pos there, the session invariant).
618    pos: usize,
619    /// Pre-output_norm hidden of row `pos - 1`.
620    last_h: CudaSlice<f32>,
621}
622
623struct SpecPipeTraceClock {
624    pair: usize,
625    started: std::time::Instant,
626}
627
628#[derive(Clone)]
629struct SpecPipeTraceCtx {
630    clock: std::sync::Arc<SpecPipeTraceClock>,
631    round: usize,
632    lane: usize,
633}
634
635struct SpecPipeTraceMarker {
636    trace: SpecPipeTraceCtx,
637    phase: &'static str,
638    edge: &'static str,
639    slot: Option<usize>,
640}
641
642unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
643    let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
644    let lane = if marker.trace.lane == 0 { "A" } else { "B" };
645    let slot = marker
646        .slot
647        .map(|v| v.to_string())
648        .unwrap_or_else(|| "-".into());
649    let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
650    use std::io::Write as _;
651    let stderr = std::io::stderr();
652    let mut stderr = stderr.lock();
653    let _ = writeln!(
654        stderr,
655        "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
656         slot={slot} t_ms={t_ms:.3}",
657        marker.trace.clock.pair,
658        marker.trace.round,
659        marker.phase,
660        marker.edge,
661    );
662}
663
664fn enqueue_spec_pipe_trace_marker(
665    stream: &cudarc::driver::CudaStream,
666    trace: Option<&SpecPipeTraceCtx>,
667    phase: &'static str,
668    edge: &'static str,
669    slot: Option<usize>,
670) -> Result<(), Box<dyn std::error::Error>> {
671    let Some(trace) = trace else {
672        return Ok(());
673    };
674    let marker = Box::new(SpecPipeTraceMarker {
675        trace: trace.clone(),
676        phase,
677        edge,
678        slot,
679    });
680    let raw = Box::into_raw(marker);
681    let result = unsafe {
682        cudarc::driver::result::stream::launch_host_function(
683            stream.cu_stream(),
684            spec_pipe_trace_marker,
685            raw.cast(),
686        )
687    };
688    if let Err(err) = result {
689        unsafe {
690            drop(Box::from_raw(raw));
691        }
692        return Err(err.into());
693    }
694    Ok(())
695}
696
697#[derive(Default)]
698struct SpecPipeProgress {
699    setup_done: [bool; 2],
700    draft_done: [usize; 2],
701    stage0_done: [usize; 2],
702    verify_done: [usize; 2],
703    accept_done: [usize; 2],
704    finished: [bool; 2],
705    aborted: bool,
706}
707
708/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
709/// keeps its existing call stack and round locals; this object only orders phase entry. The
710/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
711/// cannot be interleaved by the two host threads.
712struct SpecPipeSync {
713    progress: std::sync::Mutex<SpecPipeProgress>,
714    changed: std::sync::Condvar,
715    primary: std::sync::Mutex<()>,
716    trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
717}
718
719impl SpecPipeSync {
720    fn new() -> Self {
721        static TRACE_PAIR: std::sync::atomic::AtomicUsize =
722            std::sync::atomic::AtomicUsize::new(0);
723        let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
724            std::sync::Arc::new(SpecPipeTraceClock {
725                pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
726                started: std::time::Instant::now(),
727            })
728        });
729        Self {
730            progress: std::sync::Mutex::new(SpecPipeProgress::default()),
731            changed: std::sync::Condvar::new(),
732            primary: std::sync::Mutex::new(()),
733            trace,
734        }
735    }
736}
737
738#[derive(Clone)]
739struct SpecPipeLane {
740    sync: std::sync::Arc<SpecPipeSync>,
741    lane: usize,
742}
743
744impl SpecPipeLane {
745    fn peer(&self) -> usize {
746        1 - self.lane
747    }
748
749    fn aborted() -> Box<dyn std::error::Error> {
750        "paired speculative peer aborted".into()
751    }
752
753    fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
754        self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
755            clock: clock.clone(),
756            round,
757            lane: self.lane,
758        })
759    }
760
761    fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
762        let mut p = self.sync.progress.lock().unwrap();
763        while !p.aborted
764            && self.lane == 1
765            && !p.setup_done[0]
766            && !p.finished[0]
767        {
768            p = self.sync.changed.wait(p).unwrap();
769        }
770        if p.aborted { Err(Self::aborted()) } else { Ok(()) }
771    }
772
773    fn setup_end(&self) {
774        let mut p = self.sync.progress.lock().unwrap();
775        p.setup_done[self.lane] = true;
776        self.sync.changed.notify_all();
777    }
778
779    fn draft_begin(
780        &self,
781        round: usize,
782    ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
783        let peer = self.peer();
784        let mut p = self.sync.progress.lock().unwrap();
785        loop {
786            if p.aborted {
787                return Err(Self::aborted());
788            }
789            let setup_ready = (p.setup_done[0] || p.finished[0])
790                && (p.setup_done[1] || p.finished[1]);
791            let prior_ready = p.accept_done[self.lane] >= round
792                && (p.accept_done[peer] >= round || p.finished[peer]);
793            let turn_ready = if self.lane == 0 {
794                true
795            } else {
796                p.draft_done[0] > round || p.finished[0]
797            };
798            if setup_ready && prior_ready && turn_ready {
799                break;
800            }
801            p = self.sync.changed.wait(p).unwrap();
802        }
803        drop(p);
804        Ok(self.sync.primary.lock().unwrap())
805    }
806
807    fn draft_end(&self, round: usize) {
808        let mut p = self.sync.progress.lock().unwrap();
809        p.draft_done[self.lane] = round + 1;
810        self.sync.changed.notify_all();
811    }
812
813    /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
814    /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
815    fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
816        let peer = self.peer();
817        let mut p = self.sync.progress.lock().unwrap();
818        loop {
819            if p.aborted {
820                return Err(Self::aborted());
821            }
822            let ready = if self.lane == 0 {
823                p.draft_done[0] > round
824                    && (p.draft_done[1] > round || p.finished[1])
825            } else {
826                p.draft_done[1] > round
827                    && (p.stage0_done[0] > round || p.finished[0])
828            };
829            if ready {
830                return Ok(self.lane == 0 || p.finished[peer]);
831            }
832            p = self.sync.changed.wait(p).unwrap();
833        }
834    }
835
836    fn stage0_end(&self, round: usize) {
837        let mut p = self.sync.progress.lock().unwrap();
838        p.stage0_done[self.lane] = round + 1;
839        self.sync.changed.notify_all();
840    }
841
842    /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
843    /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
844    fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
845        let mut p = self.sync.progress.lock().unwrap();
846        while !p.aborted
847            && !(p.stage0_done[self.lane] > round
848                && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
849        {
850            p = self.sync.changed.wait(p).unwrap();
851        }
852        if p.aborted { Err(Self::aborted()) } else { Ok(()) }
853    }
854
855    fn verify_end(&self, round: usize) {
856        let mut p = self.sync.progress.lock().unwrap();
857        p.verify_done[self.lane] = round + 1;
858        self.sync.changed.notify_all();
859    }
860
861    fn accept_begin(
862        &self,
863        round: usize,
864    ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
865        let mut p = self.sync.progress.lock().unwrap();
866        loop {
867            if p.aborted {
868                return Err(Self::aborted());
869            }
870            let ready = if self.lane == 0 {
871                p.verify_done[0] > round
872                    && (p.verify_done[1] > round || p.finished[1])
873            } else {
874                p.verify_done[1] > round
875                    && (p.accept_done[0] > round || p.finished[0])
876            };
877            if ready {
878                break;
879            }
880            p = self.sync.changed.wait(p).unwrap();
881        }
882        drop(p);
883        Ok(self.sync.primary.lock().unwrap())
884    }
885
886    fn accept_end(&self, round: usize) {
887        let mut p = self.sync.progress.lock().unwrap();
888        p.accept_done[self.lane] = round + 1;
889        self.sync.changed.notify_all();
890    }
891
892    fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
893        self.sync.primary.lock().unwrap()
894    }
895
896    fn finish(&self, failed: bool) {
897        let mut p = self.sync.progress.lock().unwrap();
898        p.finished[self.lane] = true;
899        p.aborted |= failed;
900        self.sync.changed.notify_all();
901    }
902}
903
904struct SpecPipeFinish<'a> {
905    lane: &'a SpecPipeLane,
906    closed: bool,
907}
908
909impl<'a> SpecPipeFinish<'a> {
910    fn new(lane: &'a SpecPipeLane) -> Self {
911        Self { lane, closed: false }
912    }
913
914    fn close(&mut self, failed: bool) {
915        self.lane.finish(failed);
916        self.closed = true;
917    }
918}
919
920impl Drop for SpecPipeFinish<'_> {
921    fn drop(&mut self) {
922        if !self.closed {
923            self.lane.finish(true);
924        }
925    }
926}
927
928/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
929/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
930/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
931/// binds that context before touching the session, joins before returning, and never aliases the
932/// pointer. Keep this exception local to the experimental pair call instead of marking the public
933/// session type Send.
934struct SpecPipeSessionPtr(*mut SpecSession);
935
936unsafe impl Send for SpecPipeSessionPtr {}
937
938impl SpecPipeSessionPtr {
939    unsafe fn get_mut(&mut self) -> &mut SpecSession {
940        unsafe { &mut *self.0 }
941    }
942}
943
944/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
945/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
946/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
947/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
948/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
949/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
950/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
951/// so the eager fallback doesn't pay a doomed capture attempt every burst.
952pub(crate) struct DraftGraphCtx {
953    g_tok: CudaSlice<u32>,
954    g_pos: CudaSlice<i32>,
955    g_seed: CudaSlice<f32>,
956    g_p: CudaSlice<f32>,
957    g_ctr: CudaSlice<u32>,
958    g_q: CudaSlice<f32>,
959    g_perturb: CudaSlice<f32>,
960    q_slots: Vec<CudaSlice<f32>>,
961    /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
962    /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
963    /// per-position contents the host re-uploads before each replay (the graph-promote
964    /// pattern from decode.rs). Empty unless the session drafts under a grammar.
965    g_dmask: CudaSlice<u32>,
966    /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
967    graph_masked: bool,
968    graph: Option<cudarc::driver::CudaGraph>,
969    graph_s: Option<cudarc::driver::CudaGraph>,
970    /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
971    /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
972    failed: DraftGraphFallback,
973    /// (seed, temp.to_bits(), k) baked into graph_s at its capture.
974    s_key: Option<(u64, u32, usize)>,
975    /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
976    /// pool addresses the captured graph(s) bake. Without these, the transients return to the
977    /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
978    /// co-served session in the worker) reuses those addresses — the persisted graph's replay
979    /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
980    /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
981    /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
982    /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
983    keeper: Vec<Box<dyn std::any::Any + Send>>,
984    keeper_s: Vec<Box<dyn std::any::Any + Send>>,
985}
986
987/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
988/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
989///
990/// Three contracts:
991/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
992///   (returned, not printed, so the once-per-flip contract is unit-testable); the caller
993///   `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
994///   an already-failed graph returns None (the per-burst memoization that keeps the eager
995///   fallback from paying a doomed capture attempt every burst).
996/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
997///   NEW request gets one fresh capture chance instead of carrying a transient-pressure
998///   failure for the pool's whole lifetime. Returns the note line only when a flag was
999///   actually set (quiet on the common clean-resume path).
1000/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1001///   capture attempt whose own failure would re-flip loudly.
1002#[derive(Default)]
1003pub(crate) struct DraftGraphFallback {
1004    greedy: bool,
1005    sampled: bool,
1006}
1007impl DraftGraphFallback {
1008    fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1009        if self.greedy {
1010            return None;
1011        }
1012        self.greedy = true;
1013        Some(format!(
1014            "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1015        ))
1016    }
1017    fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1018        if self.sampled {
1019            return None;
1020        }
1021        self.sampled = true;
1022        Some(format!(
1023            "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1024        ))
1025    }
1026    fn greedy_failed(&self) -> bool {
1027        self.greedy
1028    }
1029    fn sampled_failed(&self) -> bool {
1030        self.sampled
1031    }
1032    fn clear_greedy(&mut self) {
1033        self.greedy = false;
1034    }
1035    fn clear_sampled(&mut self) {
1036        self.sampled = false;
1037    }
1038    /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1039    /// was set (so clean resumes stay quiet).
1040    pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1041        if !self.greedy && !self.sampled {
1042            return None;
1043        }
1044        let which = match (self.greedy, self.sampled) {
1045            (true, true) => "greedy+sampled",
1046            (true, false) => "greedy",
1047            _ => "sampled",
1048        };
1049        self.greedy = false;
1050        self.sampled = false;
1051        Some(format!(
1052            "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1053        ))
1054    }
1055}
1056
1057impl DraftGraphCtx {
1058    fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1059        Ok(DraftGraphCtx {
1060            g_tok: e.alloc_u32_zeroed(1)?,
1061            g_pos: e.htod_i32(&[0])?,
1062            g_seed: e.zeros(n_embd)?,
1063            g_p: e.zeros(1)?,
1064            g_ctr: e.alloc_u32_zeroed(1)?,
1065            g_q: e.zeros(qlen)?,
1066            g_perturb: e.zeros(qlen)?,
1067            q_slots: Vec::new(),
1068            g_dmask: e.alloc_u32_zeroed(1)?,
1069            graph_masked: false,
1070            graph: None,
1071            graph_s: None,
1072            failed: DraftGraphFallback::default(),
1073            s_key: None,
1074            keeper: Vec::new(),
1075            keeper_s: Vec::new(),
1076        })
1077    }
1078}
1079
1080pub(crate) struct MtpScratch {
1081    kv: KvLayer,
1082    /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1083    /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1084    /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1085    /// smaller host-indexed SWA ring instead.
1086    cap: usize,
1087}
1088
1089fn mtp_scratch_layout(
1090    cfg: &memra_gguf::config::ModelConfig,
1091    geom: Option<&crate::hybrid::DraftGeom>,
1092) -> (usize, usize, usize, usize) {
1093    // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1094    let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1095    let head_dim_k = cfg.head_dim_k as usize;
1096    let head_dim_v = cfg.head_dim_v as usize;
1097    assert!(
1098        head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1099        "KVQUANT requires head_dim%32==0 (MTP scratch)"
1100    );
1101    let kv_dim_k = head_dim_k * n_head_kv;
1102    let kv_dim_v = head_dim_v * n_head_kv;
1103    // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1104    // policy shared with `MtpScratch::new` so admission scales the same allocation.
1105    let (kbb, vbb) = crate::kv_blk_bytes();
1106    let k_tok_bytes = (kv_dim_k / 32) * kbb;
1107    let v_tok_bytes = (kv_dim_v / 32) * vbb;
1108    (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1109}
1110
1111impl MtpScratch {
1112    fn new(
1113        e: &Engine,
1114        cfg: &memra_gguf::config::ModelConfig,
1115        cap: usize,
1116        geom: Option<&crate::hybrid::DraftGeom>,
1117    ) -> Result<Self, Box<dyn std::error::Error>> {
1118        // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1119        // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1120        // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1121        // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1122        let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) =
1123            mtp_scratch_layout(cfg, geom);
1124        let ring = if crate::cache::swa_ring_on() && cfg.arch.is_step35() {
1125            let window = cfg.step35.as_ref().unwrap().sliding_window as usize;
1126            Some(crate::cache::KvRing::new(
1127                crate::cache::swa_ring_rows(window, cap),
1128                window,
1129            ))
1130        } else {
1131            None
1132        };
1133        let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1134        Ok(MtpScratch {
1135            kv: KvLayer {
1136                k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1137                v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1138                kv_dim_k,
1139                kv_dim_v,
1140                k_tok_bytes,
1141                v_tok_bytes,
1142                len: 0,
1143                ring,
1144                len_d: e.htod_i32(&[0])?,
1145            },
1146            cap,
1147        })
1148    }
1149    /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1150    /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1151    /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1152    fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1153        if self.kv.ring.as_ref().is_some_and(|ring| !ring.can_rewind_to(n)) {
1154            return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1155        }
1156        self.kv.len = n;
1157        e.set_i32_one(&mut self.kv.len_d, n as i32)
1158    }
1159
1160    fn can_rewind_to(&self, n: usize) -> bool {
1161        self.kv.ring.as_ref().is_none_or(|ring| ring.can_rewind_to(n))
1162    }
1163}
1164
1165/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1166/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1167/// full weight reads per round — recomputing columns the verify had already produced
1168/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1169/// to "after the first j verify columns" WITHOUT re-running the trunk:
1170/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1171///   consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1172///   to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1173///   registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1174///   pure-copy ring rebuild.
1175/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1176///   column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1177///   target: j <= t-1).
1178/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1179/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1180struct GdnStash {
1181    qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1182    q_l2: CudaSlice<f32>,
1183    k_l2: CudaSlice<f32>,
1184    v_g: CudaSlice<f32>, // [t, num_v, d_state]
1185    g_log: CudaSlice<f32>,
1186    beta: CudaSlice<f32>, // [t, num_v]
1187}
1188struct VerifyCkpt {
1189    gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1190    cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1191}
1192impl VerifyCkpt {
1193    fn new(n_layer: usize) -> Self {
1194        VerifyCkpt {
1195            gdn: (0..n_layer).map(|_| None).collect(),
1196            cols: (0..n_layer).map(|_| None).collect(),
1197        }
1198    }
1199}
1200
1201/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
1202/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
1203/// a logical round number.
1204struct VerifyBoundaryTicket {
1205    rt: &'static crate::pp::PpNRt,
1206    caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1207    slot: usize,
1208    pos0: usize,
1209    t: usize,
1210    payload: usize,
1211    n_st: usize,
1212    pipelined: bool,
1213    pp_anatomy: bool,
1214    pp_started: std::time::Instant,
1215    reverse_ms: f64,
1216    stage0_ms: f64,
1217    tx_ms: f64,
1218    trace: Option<SpecPipeTraceCtx>,
1219}
1220
1221/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
1222/// increment-2 controller can also be armed by the server's fresh-process research door.
1223#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1224pub enum OptiForkGateMode {
1225    Disabled,
1226    Hit,
1227    Miss,
1228    Alternate,
1229    Abort,
1230    Controller,
1231}
1232
1233static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 =
1234    std::sync::atomic::AtomicU8::new(0);
1235static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
1236    std::sync::atomic::AtomicU32::new(0);
1237static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 =
1238    std::sync::atomic::AtomicU64::new(0);
1239static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 =
1240    std::sync::atomic::AtomicU64::new(0);
1241static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 =
1242    std::sync::atomic::AtomicU64::new(0);
1243static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 =
1244    std::sync::atomic::AtomicU64::new(0);
1245static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 =
1246    std::sync::atomic::AtomicU64::new(0);
1247static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 =
1248    std::sync::atomic::AtomicU64::new(0);
1249static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 =
1250    std::sync::atomic::AtomicU64::new(0);
1251static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 =
1252    std::sync::atomic::AtomicU64::new(0);
1253static OPTI_RECONCILES: std::sync::atomic::AtomicU64 =
1254    std::sync::atomic::AtomicU64::new(0);
1255static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1256    std::sync::atomic::AtomicU64::new(0);
1257static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1258    std::sync::atomic::AtomicU64::new(0);
1259static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 =
1260    std::sync::atomic::AtomicU64::new(0);
1261
1262impl OptiForkGateMode {
1263    fn code(self) -> u8 {
1264        match self {
1265            Self::Disabled => 0,
1266            Self::Hit => 1,
1267            Self::Miss => 2,
1268            Self::Alternate => 3,
1269            Self::Abort => 4,
1270            Self::Controller => 5,
1271        }
1272    }
1273
1274    fn configured() -> Self {
1275        match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
1276            1 => Self::Hit,
1277            2 => Self::Miss,
1278            3 => Self::Alternate,
1279            4 => Self::Abort,
1280            5 => Self::Controller,
1281            _ => Self::Disabled,
1282        }
1283    }
1284
1285    fn action(self, generation: u64) -> OptiForkAction {
1286        match self {
1287            Self::Hit => OptiForkAction::Hit,
1288            Self::Miss => OptiForkAction::Miss,
1289            Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
1290            Self::Alternate => OptiForkAction::Miss,
1291            Self::Abort => OptiForkAction::Abort,
1292            Self::Disabled | Self::Controller => {
1293                unreachable!("non-forced mode cannot choose a forced fork action")
1294            }
1295        }
1296    }
1297
1298    fn is_forced(self) -> bool {
1299        matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
1300    }
1301}
1302
1303/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
1304pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
1305    OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
1306}
1307
1308/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
1309/// two-token draft-probability product. Serving can call this only through its explicit
1310/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
1311pub fn set_optipipe_controller_threshold(threshold: f32) {
1312    assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
1313    OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
1314    set_optipipe_gate_mode(OptiForkGateMode::Controller);
1315}
1316
1317#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1318pub struct OptiForkGateStats {
1319    pub attempts: u64,
1320    pub hits: u64,
1321    pub misses: u64,
1322    pub abort_drains: u64,
1323    pub refusals: u64,
1324    pub gate_checks: u64,
1325    pub gate_admits: u64,
1326    pub gate_rejects: u64,
1327    pub reconciles: u64,
1328    pub wasted_draft_tokens: u64,
1329    pub shadow_draft_tokens: u64,
1330    pub breaker_trips: u64,
1331}
1332
1333#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1334pub struct OptiForkStateIdentity {
1335    pub trunk_kv_bytes: usize,
1336    pub recurrent_bytes: usize,
1337    pub scratch_kv_bytes: usize,
1338    pub hidden_bytes: usize,
1339}
1340
1341pub fn reset_optipipe_gate_stats() {
1342    for counter in [
1343        &OPTI_FORK_ATTEMPTS,
1344        &OPTI_FORK_HITS,
1345        &OPTI_FORK_MISSES,
1346        &OPTI_FORK_ABORT_DRAINS,
1347        &OPTI_FORK_REFUSALS,
1348        &OPTI_GATE_CHECKS,
1349        &OPTI_GATE_ADMITS,
1350        &OPTI_GATE_REJECTS,
1351        &OPTI_RECONCILES,
1352        &OPTI_WASTED_DRAFT_TOKENS,
1353        &OPTI_SHADOW_DRAFT_TOKENS,
1354        &OPTI_BREAKER_TRIPS,
1355    ] {
1356        counter.store(0, std::sync::atomic::Ordering::Relaxed);
1357    }
1358}
1359
1360pub fn optipipe_gate_stats() -> OptiForkGateStats {
1361    let load = |v: &std::sync::atomic::AtomicU64| {
1362        v.load(std::sync::atomic::Ordering::Relaxed)
1363    };
1364    OptiForkGateStats {
1365        attempts: load(&OPTI_FORK_ATTEMPTS),
1366        hits: load(&OPTI_FORK_HITS),
1367        misses: load(&OPTI_FORK_MISSES),
1368        abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
1369        refusals: load(&OPTI_FORK_REFUSALS),
1370        gate_checks: load(&OPTI_GATE_CHECKS),
1371        gate_admits: load(&OPTI_GATE_ADMITS),
1372        gate_rejects: load(&OPTI_GATE_REJECTS),
1373        reconciles: load(&OPTI_RECONCILES),
1374        wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
1375        shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
1376        breaker_trips: load(&OPTI_BREAKER_TRIPS),
1377    }
1378}
1379
1380#[derive(Clone, Copy, Debug)]
1381struct OptiControllerPolicy {
1382    threshold: f32,
1383    consecutive_misses: u8,
1384    breaker_tripped: bool,
1385}
1386
1387impl OptiControllerPolicy {
1388    fn configured() -> Self {
1389        Self {
1390            threshold: f32::from_bits(
1391                OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
1392            ),
1393            consecutive_misses: 0,
1394            breaker_tripped: false,
1395        }
1396    }
1397
1398    fn admit(&self, q_proxy: f32) -> bool {
1399        q_proxy.is_finite()
1400            && (0.0..=1.0).contains(&q_proxy)
1401            && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
1402    }
1403
1404    /// Returns true exactly when this resolution newly trips the three-miss breaker.
1405    fn resolve(&mut self, hit: bool) -> bool {
1406        // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
1407        // every optimistic opportunity, so the safety breaker is measured separately and must
1408        // not silently turn this arm into "three attempts then serial".
1409        if self.threshold == 0.0 {
1410            self.consecutive_misses = 0;
1411            return false;
1412        }
1413        if hit {
1414            self.consecutive_misses = 0;
1415            return false;
1416        }
1417        self.consecutive_misses = self.consecutive_misses.saturating_add(1);
1418        if !self.breaker_tripped && self.consecutive_misses >= 3 {
1419            self.breaker_tripped = true;
1420            return true;
1421        }
1422        false
1423    }
1424}
1425
1426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1427enum OptiForkAction {
1428    Hit,
1429    Miss,
1430    Abort,
1431}
1432
1433#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1434struct OptiForkGeneration {
1435    id: u64,
1436    slot: usize,
1437}
1438
1439#[derive(Default)]
1440struct OptiForkGenerationTracker {
1441    next: u64,
1442    live: [Option<u64>; 2],
1443}
1444
1445impl OptiForkGenerationTracker {
1446    fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1447        let generation = OptiForkGeneration {
1448            id: self.next,
1449            slot: (self.next & 1) as usize,
1450        };
1451        if let Some(live) = self.live[generation.slot] {
1452            return Err(format!(
1453                "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
1454                generation.slot,
1455            )
1456            .into());
1457        }
1458        self.next += 1;
1459        self.live[generation.slot] = Some(generation.id);
1460        Ok(generation)
1461    }
1462
1463    fn retire(&mut self, generation: OptiForkGeneration)
1464              -> Result<(), Box<dyn std::error::Error>> {
1465        match self.live[generation.slot] {
1466            Some(id) if id == generation.id => {
1467                self.live[generation.slot] = None;
1468                Ok(())
1469            }
1470            other => Err(format!(
1471                "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
1472                generation.id, generation.slot,
1473            )
1474            .into()),
1475        }
1476    }
1477}
1478
1479struct OptiForkSeedGeneration {
1480    h_seed: CudaSlice<f32>,
1481    fill_prev: CudaSlice<f32>,
1482    scratch_len: usize,
1483}
1484
1485/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
1486/// generic cache helper accepts one device and therefore cannot copy GDN state split across
1487/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
1488/// device ownership.
1489fn opti_snapshot_stage_owned(
1490    e: &Engine,
1491    cache: &Cache,
1492    rt: &'static crate::pp::PpNRt,
1493    fence: &[usize],
1494) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
1495    let n = cache.kv.len();
1496    let mut snapshot = crate::cache::CacheSnapshot {
1497        kv_len: vec![None; n],
1498        conv: (0..n).map(|_| None).collect(),
1499        ssm: (0..n).map(|_| None).collect(),
1500        pos: cache.pos,
1501    };
1502    opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
1503    Ok(snapshot)
1504}
1505
1506fn opti_snapshot_stage_owned_into(
1507    e: &Engine,
1508    cache: &Cache,
1509    rt: &'static crate::pp::PpNRt,
1510    fence: &[usize],
1511    snapshot: &mut crate::cache::CacheSnapshot,
1512) -> Result<(), Box<dyn std::error::Error>> {
1513    if fence.len() != rt.n_stages() + 1 || snapshot.kv_len.len() != cache.kv.len() {
1514        return Err("optipipe stage-owned snapshot shape mismatch".into());
1515    }
1516    for stage in 0..rt.n_stages() {
1517        opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
1518    }
1519    snapshot.pos = cache.pos;
1520    Ok(())
1521}
1522
1523/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
1524/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
1525/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
1526/// either point would capture one side of the fork at the wrong generation.
1527fn opti_snapshot_one_stage_owned_into(
1528    e: &Engine,
1529    cache: &Cache,
1530    rt: &'static crate::pp::PpNRt,
1531    fence: &[usize],
1532    stage: usize,
1533    snapshot: &mut crate::cache::CacheSnapshot,
1534) -> Result<(), Box<dyn std::error::Error>> {
1535    if fence.len() != rt.n_stages() + 1
1536        || snapshot.kv_len.len() != cache.kv.len()
1537        || stage >= rt.n_stages()
1538    {
1539        return Err("optipipe single-stage snapshot shape mismatch".into());
1540    }
1541    let _scope = rt.enter(stage);
1542    let owner = rt.engine(stage, e);
1543    for il in fence[stage]..fence[stage + 1] {
1544        snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
1545        match &cache.recur[il] {
1546            Some(recur) => {
1547                match snapshot.conv[il].as_mut() {
1548                    Some(dst) => owner.copy_into(
1549                        dst,
1550                        0,
1551                        &recur.conv_state,
1552                        recur.conv_state.len(),
1553                    )?,
1554                    None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
1555                }
1556                match snapshot.ssm[il].as_mut() {
1557                    Some(dst) => owner.copy_into(
1558                        dst,
1559                        0,
1560                        &recur.ssm_state,
1561                        recur.ssm_state.len(),
1562                    )?,
1563                    None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
1564                }
1565            }
1566            None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
1567                return Err(
1568                    format!("optipipe stage-owned snapshot layer {il} changed shape").into()
1569                );
1570            }
1571            None => {}
1572        }
1573    }
1574    snapshot.pos = cache.pos;
1575    Ok(())
1576}
1577
1578/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
1579/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
1580/// resolve, so the reconcile tables and conditional restores are stage-local.
1581struct OptiForkState {
1582    mode: OptiForkGateMode,
1583    controller: Option<OptiControllerPolicy>,
1584    generations: OptiForkGenerationTracker,
1585    active_snapshot_slot: usize,
1586    alternate_snapshot: crate::cache::CacheSnapshot,
1587    seeds: [OptiForkSeedGeneration; 2],
1588    rt: &'static crate::pp::PpNRt,
1589    fence: [usize; 3],
1590    split: usize,
1591    len_ptrs: CudaSlice<u64>,
1592    saved_lens: CudaSlice<i32>,
1593    forced_acc: CudaSlice<u32>,
1594    valid: CudaSlice<u32>,
1595    stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1596    logical_payload_bytes: [usize; 2],
1597}
1598
1599struct OptiForkTicket {
1600    generation: OptiForkGeneration,
1601    boundary: Option<VerifyBoundaryTicket>,
1602    drain: std::sync::Arc<cudarc::driver::CudaStream>,
1603    settled: bool,
1604}
1605
1606struct OptiControllerTicket {
1607    generation: OptiForkGeneration,
1608    boundary: Option<VerifyBoundaryTicket>,
1609    ckpt: Option<VerifyCkpt>,
1610    verify_tokens: [u32; 2],
1611    draft_prob: f32,
1612    eager_seed: Option<CudaSlice<f32>>,
1613    q_proxy: f32,
1614    scratch_len: usize,
1615    issued_at: std::time::Instant,
1616    drain: std::sync::Arc<cudarc::driver::CudaStream>,
1617    settled: bool,
1618}
1619
1620struct OptiControllerPrepared {
1621    verify_tokens: [u32; 2],
1622    draft_prob: f32,
1623    eager_seed: Option<CudaSlice<f32>>,
1624    q_proxy: f32,
1625    scratch_len: usize,
1626}
1627
1628impl OptiControllerTicket {
1629    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
1630        self.boundary
1631            .take()
1632            .expect("controller boundary ticket already consumed")
1633    }
1634
1635    fn take_ckpt(&mut self) -> VerifyCkpt {
1636        self.ckpt
1637            .take()
1638            .expect("controller verify checkpoint already consumed")
1639    }
1640
1641    fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
1642        self.eager_seed.take()
1643    }
1644
1645    fn settle(&mut self) {
1646        self.settled = true;
1647    }
1648}
1649
1650impl Drop for OptiControllerTicket {
1651    fn drop(&mut self) {
1652        if !self.settled {
1653            let _ = self.drain.synchronize();
1654            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1655        }
1656    }
1657}
1658
1659impl OptiForkTicket {
1660    fn take_boundary(&mut self) -> VerifyBoundaryTicket {
1661        self.boundary.take().expect("fork ticket boundary already consumed")
1662    }
1663
1664    fn settle(&mut self) {
1665        self.settled = true;
1666    }
1667}
1668
1669impl Drop for OptiForkTicket {
1670    fn drop(&mut self) {
1671        if !self.settled {
1672            let _ = self.drain.synchronize();
1673            OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1674        }
1675    }
1676}
1677
1678impl OptiForkState {
1679    #[allow(clippy::too_many_arguments)]
1680    fn new(
1681        e: &Engine,
1682        cache: &Cache,
1683        mode: OptiForkGateMode,
1684        alternate_snapshot: crate::cache::CacheSnapshot,
1685        h_seed: &CudaSlice<f32>,
1686        fill_prev: &CudaSlice<f32>,
1687        rt: &'static crate::pp::PpNRt,
1688        split: usize,
1689        n_layer: usize,
1690    ) -> Result<Self, Box<dyn std::error::Error>> {
1691        let fence = [0, split, n_layer];
1692        let mut logical_payload_bytes = [0usize; 2];
1693        for stage in 0..2 {
1694            for il in fence[stage]..fence[stage + 1] {
1695                logical_payload_bytes[stage] += alternate_snapshot.conv[il]
1696                    .as_ref()
1697                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
1698                logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
1699                    .as_ref()
1700                    .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
1701            }
1702        }
1703        let seeds = [
1704            OptiForkSeedGeneration {
1705                h_seed: e.clone_dtod(h_seed)?,
1706                fill_prev: e.clone_dtod(fill_prev)?,
1707                scratch_len: 0,
1708            },
1709            OptiForkSeedGeneration {
1710                h_seed: e.clone_dtod(h_seed)?,
1711                fill_prev: e.clone_dtod(fill_prev)?,
1712                scratch_len: 0,
1713            },
1714        ];
1715        let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
1716            let _stage = rt.enter(0);
1717            let e0 = rt.engine(0, e);
1718            (
1719                crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
1720                e0.htod_i32(&vec![0; split])?,
1721                e0.alloc_u32_zeroed(2)?,
1722                e0.alloc_u32_zeroed(1)?,
1723                e0.stream(),
1724            )
1725        };
1726        logical_payload_bytes[0] += seeds
1727            .iter()
1728            .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
1729            .sum::<usize>();
1730        logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
1731            + saved_lens.len() * std::mem::size_of::<i32>()
1732            + forced_acc.len() * std::mem::size_of::<u32>()
1733            + valid.len() * std::mem::size_of::<u32>();
1734        Ok(Self {
1735            mode,
1736            controller: (mode == OptiForkGateMode::Controller)
1737                .then(OptiControllerPolicy::configured),
1738            generations: OptiForkGenerationTracker::default(),
1739            active_snapshot_slot: 0,
1740            alternate_snapshot,
1741            seeds,
1742            rt,
1743            fence,
1744            split,
1745            len_ptrs,
1746            saved_lens,
1747            forced_acc,
1748            valid,
1749            stage0_stream,
1750            logical_payload_bytes,
1751        })
1752    }
1753
1754    fn reserve(&mut self, current_snapshot: &mut crate::cache::CacheSnapshot)
1755               -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1756        let generation = self.generations.reserve()?;
1757        if generation.slot != self.active_snapshot_slot {
1758            std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
1759            self.active_snapshot_slot = generation.slot;
1760        }
1761        Ok(generation)
1762    }
1763
1764    fn capture_seed(
1765        &mut self,
1766        e: &Engine,
1767        generation: OptiForkGeneration,
1768        h_seed: &CudaSlice<f32>,
1769        fill_prev: &CudaSlice<f32>,
1770        scratch_len: usize,
1771    ) -> Result<(), Box<dyn std::error::Error>> {
1772        let seed = &mut self.seeds[generation.slot];
1773        e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
1774        e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
1775        seed.scratch_len = scratch_len;
1776        Ok(())
1777    }
1778
1779    fn ticket(&self, generation: OptiForkGeneration, boundary: VerifyBoundaryTicket)
1780              -> OptiForkTicket {
1781        OptiForkTicket {
1782            generation,
1783            boundary: Some(boundary),
1784            drain: self.stage0_stream.clone(),
1785            settled: false,
1786        }
1787    }
1788
1789    #[allow(clippy::too_many_arguments)]
1790    fn controller_ticket(
1791        &self,
1792        generation: OptiForkGeneration,
1793        boundary: VerifyBoundaryTicket,
1794        ckpt: VerifyCkpt,
1795        verify_tokens: [u32; 2],
1796        draft_prob: f32,
1797        eager_seed: Option<CudaSlice<f32>>,
1798        q_proxy: f32,
1799        scratch_len: usize,
1800    ) -> OptiControllerTicket {
1801        OptiControllerTicket {
1802            generation,
1803            boundary: Some(boundary),
1804            ckpt: Some(ckpt),
1805            verify_tokens,
1806            draft_prob,
1807            eager_seed,
1808            q_proxy,
1809            scratch_len,
1810            issued_at: std::time::Instant::now(),
1811            drain: self.stage0_stream.clone(),
1812            settled: false,
1813        }
1814    }
1815
1816    fn reserve_successor(&mut self)
1817                         -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1818        self.generations.reserve()
1819    }
1820
1821    fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
1822        &mut self.alternate_snapshot
1823    }
1824
1825    fn promote_successor_snapshot(
1826        &mut self,
1827        current_snapshot: &mut crate::cache::CacheSnapshot,
1828        generation: OptiForkGeneration,
1829    ) {
1830        std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
1831        self.active_snapshot_slot = generation.slot;
1832    }
1833
1834    fn queue_actual_reconcile(
1835        &mut self,
1836        e: &Engine,
1837        snapshot: &crate::cache::CacheSnapshot,
1838        acc: &CudaSlice<u32>,
1839        optimistic_pending: u32,
1840        base: usize,
1841    ) -> Result<(), Box<dyn std::error::Error>> {
1842        let saved: Vec<i32> = (0..self.split)
1843            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
1844            .collect();
1845        // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
1846        // decision point there and append a wait to stage 0 after its optimistic successor/TX;
1847        // the validity/reconcile kernels must never peer-read acc before it is written. The
1848        // increment-1 harness uses primary stage 0, where stream order already provides this.
1849        if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
1850            self.rt.fence_stages_behind(&e.stream())?;
1851        }
1852        let _stage = self.rt.enter(0);
1853        let e0 = self.rt.engine(0, e);
1854        e0.htod_i32_into(&mut self.saved_lens, &saved)?;
1855        e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
1856        e0.spec_fork_reconcile_kv(
1857            &self.len_ptrs,
1858            &self.saved_lens,
1859            acc,
1860            &self.valid,
1861            base,
1862            self.split,
1863        )
1864    }
1865
1866    fn finish_actual_reconcile(
1867        &mut self,
1868        e: &Engine,
1869        cache: &mut Cache,
1870        snapshot: &crate::cache::CacheSnapshot,
1871        n_acc: usize,
1872        base: usize,
1873        hit: bool,
1874    ) -> Result<(), Box<dyn std::error::Error>> {
1875        if hit {
1876            return Ok(());
1877        }
1878        let len_delta = base + n_acc;
1879        for il in 0..self.split {
1880            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
1881                kv.len = saved + len_delta;
1882            }
1883        }
1884        {
1885            let _stage = self.rt.enter(1);
1886            let e1 = self.rt.engine(1, e);
1887            for il in self.split..self.fence[2] {
1888                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
1889                    kv.len = saved + len_delta;
1890                    e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
1891                }
1892            }
1893        }
1894        self.rt.publish_to(0, &e.stream())?;
1895        Ok(())
1896    }
1897
1898    fn cancel_controller_ticket(
1899        &mut self,
1900        e: &Engine,
1901        cache: &mut Cache,
1902        scratch: &mut MtpScratch,
1903        snapshot: &crate::cache::CacheSnapshot,
1904        ticket: &mut OptiControllerTicket,
1905    ) -> Result<(), Box<dyn std::error::Error>> {
1906        {
1907            let _stage = self.rt.enter(0);
1908            let e0 = self.rt.engine(0, e);
1909            for il in 0..self.split {
1910                if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
1911                    kv.len = saved;
1912                    e0.set_i32_one(&mut kv.len_d, saved as i32)?;
1913                }
1914            }
1915        }
1916        scratch.set_len(e, snapshot.pos)?;
1917        ticket.settle();
1918        self.generations.retire(ticket.generation)?;
1919        OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1920        OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
1921        eprintln!(
1922            "[opti-controller] tail-drain generation={} slot={}",
1923            ticket.generation.id, ticket.generation.slot,
1924        );
1925        Ok(())
1926    }
1927
1928    #[allow(clippy::too_many_arguments)]
1929    fn reconcile(
1930        &mut self,
1931        e: &Engine,
1932        cache: &mut Cache,
1933        scratch: &mut MtpScratch,
1934        snapshot: &crate::cache::CacheSnapshot,
1935        h_seed: &mut CudaSlice<f32>,
1936        fill_prev: &mut CudaSlice<f32>,
1937        generation: OptiForkGeneration,
1938        action: OptiForkAction,
1939        optimistic_pending: u32,
1940    ) -> Result<(), Box<dyn std::error::Error>> {
1941        debug_assert!(action != OptiForkAction::Abort);
1942        let miss_started = std::time::Instant::now();
1943        let keep = action == OptiForkAction::Hit;
1944        let saved: Vec<i32> = (0..self.split)
1945            .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
1946            .collect();
1947        let seed = &self.seeds[generation.slot];
1948        {
1949            let _stage = self.rt.enter(0);
1950            let e0 = self.rt.engine(0, e);
1951            e0.htod_i32_into(&mut self.saved_lens, &saved)?;
1952            let forced = if keep {
1953                [1u32, optimistic_pending]
1954            } else {
1955                [0u32, optimistic_pending]
1956            };
1957            e0.htod_u32_into(&mut self.forced_acc, &forced)?;
1958            e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
1959            e0.spec_fork_reconcile_kv(
1960                &self.len_ptrs,
1961                &self.saved_lens,
1962                &self.forced_acc,
1963                &self.valid,
1964                0,
1965                self.split,
1966            )?;
1967            for il in 0..self.split {
1968                if let Some(recur) = cache.recur[il].as_mut() {
1969                    let conv = snapshot.conv[il]
1970                        .as_ref()
1971                        .ok_or("optipipe stage0 snapshot missing conv state")?;
1972                    let ssm = snapshot.ssm[il]
1973                        .as_ref()
1974                        .ok_or("optipipe stage0 snapshot missing ssm state")?;
1975                    e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
1976                    e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
1977                }
1978            }
1979            e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
1980            e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
1981        }
1982
1983        if keep {
1984            OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1985            return Ok(());
1986        }
1987
1988        for il in 0..self.split {
1989            if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
1990                kv.len = saved;
1991            }
1992        }
1993        scratch.set_len(e, seed.scratch_len)?;
1994        // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
1995        // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
1996        let caller = e.stream();
1997        self.rt.publish_to(0, &caller)?;
1998        caller.synchronize()?;
1999        let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
2000        eprintln!(
2001            "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
2002            generation.id, generation.slot,
2003        );
2004        OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2005        Ok(())
2006    }
2007
2008    fn retire(&mut self, generation: OptiForkGeneration)
2009              -> Result<(), Box<dyn std::error::Error>> {
2010        self.generations.retire(generation)
2011    }
2012}
2013
2014impl HybridModel {
2015    fn opti_graph_draft_step(
2016        &self,
2017        e: &Engine,
2018        mtp: &MtpHead,
2019        dctx: &mut DraftGraphCtx,
2020        scratch: &mut MtpScratch,
2021        d_vocab: usize,
2022    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2023        dctx.graph
2024            .as_ref()
2025            .ok_or("optipipe controller requires the greedy draft graph")?
2026            .launch()?;
2027        scratch.kv.len += 1;
2028        let idx = e.dtoh_u32_one(&dctx.g_tok)?;
2029        if (idx as usize) >= d_vocab {
2030            return Err(format!(
2031                "optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
2032            )
2033            .into());
2034        }
2035        let probability = e.dtoh(&dctx.g_p)?[0];
2036        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2037            return Err(format!("optipipe draft probability is invalid: {probability}").into());
2038        }
2039        let token = match &mtp.d2t {
2040            Some(map) => map[idx as usize],
2041            None => idx,
2042        };
2043        if token != idx {
2044            e.set_u32_one(&mut dctx.g_tok, token)?;
2045        }
2046        Ok((token, probability))
2047    }
2048
2049    #[allow(clippy::too_many_arguments)]
2050    fn opti_controller_draft_step(
2051        &self,
2052        e: &Engine,
2053        mtp: &MtpHead,
2054        dctx: &mut DraftGraphCtx,
2055        scratch: &mut MtpScratch,
2056        d_vocab: usize,
2057        eager_state: &mut Option<(u32, CudaSlice<f32>)>,
2058        eager_pos: usize,
2059        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2060    ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2061        if dctx.graph.is_some() {
2062            return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
2063        }
2064        let (input_token, input_seed) = eager_state
2065            .take()
2066            .ok_or("optipipe eager continuation seed is unavailable")?;
2067        let (logits, next_seed) = self.mtp_head_forward_dev(
2068            e,
2069            mtp,
2070            input_token,
2071            &input_seed,
2072            scratch,
2073            eager_pos,
2074            embd_dev,
2075            None,
2076        )?;
2077        let token_d = e.argmax_token_device(&logits, d_vocab)?;
2078        let idx = e.dtoh_u32_one(&token_d)?;
2079        if (idx as usize) >= d_vocab {
2080            return Err(format!(
2081                "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
2082            )
2083            .into());
2084        }
2085        let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
2086        let probability = e.dtoh(&probability_d)?[0];
2087        if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2088            return Err(
2089                format!("optipipe eager draft probability is invalid: {probability}").into()
2090            );
2091        }
2092        let token = match &mtp.d2t {
2093            Some(map) => map[idx as usize],
2094            None => idx,
2095        };
2096        *eager_state = Some((token, next_seed));
2097        Ok((token, probability))
2098    }
2099
2100    /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
2101    /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
2102    /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
2103    /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
2104    /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
2105    /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
2106    /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
2107    /// transfer + host argmax per draft token from the K-token draft chain.
2108    #[allow(clippy::too_many_arguments)]
2109    fn mtp_head_forward_dev(
2110        &self,
2111        e: &Engine,
2112        mtp: &MtpHead,
2113        e_tok: u32,
2114        h_seed: &CudaSlice<f32>,
2115        scratch: &mut MtpScratch,
2116        mtp_pos: usize,
2117        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2118        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
2119        // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
2120        // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
2121        mask: Option<(&CudaSlice<u32>, usize)>,
2122    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2123        let cfg = &self.cfg;
2124        let n_embd = cfg.n_embd as usize;
2125        // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
2126        // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
2127        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2128        let eps = cfg.rms_eps;
2129        let pos_d = e.htod_i32(&[mtp_pos as i32])?;
2130
2131        // op A: a resident table transfers one 4B token id. The exact host-row capacity path
2132        // expands this one row on CPU and transfers n_embd f32 values instead.
2133        let e_emb = match embd_dev {
2134            Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
2135            None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
2136        };
2137
2138        // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
2139        let mut e_norm = e.zeros(n_embd)?;
2140        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
2141        let mut h_norm = e.zeros(n_embd)?;
2142        e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
2143
2144        // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
2145        let mut concat = e.zeros(2 * n_embd)?;
2146        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
2147        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
2148
2149        // op 4: inpSA = eh_proj @ concat  (eh_proj [2*n_embd, n_embd]) -> [n_embd]
2150        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
2151
2152        // op 5: a_norm = RMSNorm(inpSA, attn_norm)
2153        let mut a_norm = e.zeros(di)?;
2154        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
2155
2156        // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
2157        // scratch.cap, length from the device len_d) so eager drafts match graph drafts
2158        // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
2159        // advances only the device counter).
2160        let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
2161            // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
2162            // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
2163            // Advances BOTH the host len and the device counter itself (unlike the dc arm,
2164            // whose host-side mirror the caller does).
2165            (Mixer::Full(fa), Some(g)) => self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?,
2166            (Mixer::Full(fa), None) => {
2167                let out =
2168                    self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
2169                scratch.kv.len += 1;
2170                out
2171            }
2172            (Mixer::Linear(_), _) => {
2173                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2174            }
2175            (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
2176        };
2177
2178        // op 7: x1 = inpSA + attn_out
2179        let mut x1 = e.zeros(di)?;
2180        e.add(&inp_sa, &attn_out, &mut x1, di)?;
2181
2182        // op 8: z = RMSNorm(x1, post_attn_norm)  (pre-FFN norm)
2183        let mut z = e.zeros(di)?;
2184        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
2185
2186        // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
2187        let ffn_out = match &mtp.ffn {
2188            crate::hybrid::Ffn::Dense {
2189                ffn_gate,
2190                ffn_up,
2191                ffn_down,
2192            } => {
2193                let n_ff = ffn_gate.out_features();
2194                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
2195                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
2196                    (
2197                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
2198                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
2199                    )
2200                } else {
2201                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
2202                };
2203                let mut act = e.zeros(n_ff)?;
2204                // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
2205                // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
2206                // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
2207                // passes None, which is `ffn_act`'s dispatch verbatim.
2208                Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
2209                                  mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
2210                                  &mut act, n_ff)?;
2211                e.matmul(ffn_down, &act, 1)?
2212            }
2213            // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
2214            // so they never alias trunk layer 0's cache keys.
2215            crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
2216        };
2217
2218        // op 10: h_nextn = x1 + ffn_out (at di)
2219        let mut h_inner = e.zeros(di)?;
2220        e.add(&x1, &ffn_out, &mut h_inner, di)?;
2221
2222        // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
2223        // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
2224        let h_nextn = match mtp.geom.as_ref() {
2225            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
2226            None => h_inner,
2227        };
2228
2229        // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
2230        let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
2231        let mut final_h = e.zeros(n_embd)?;
2232        e.rms_norm(
2233            &h_nextn,
2234            final_norm.float_data(),
2235            &mut final_h,
2236            n_embd,
2237            1,
2238            eps,
2239        )?;
2240
2241        // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
2242        let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
2243        let mut logits = e.matmul(head, &final_h, 1)?;
2244        // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
2245        // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
2246        if let Some((mask_d, mw)) = mask {
2247            let d_vocab = head.out_features();
2248            e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
2249        }
2250        // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
2251        // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
2252        Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
2253    }
2254
2255    /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
2256    /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
2257    /// the dc path, and all three are properties of this arch's MTP block:
2258    ///
2259    /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
2260    ///    window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
2261    ///    cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
2262    ///    mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
2263    ///    windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
2264    ///    starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
2265    ///    new kernel. That is deliberately not built here: see the CUDA-graph note below.
2266    /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
2267    ///    on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
2268    ///    trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
2269    ///    resolved `Step35MtpGeom`, never from `cfg`.
2270    /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
2271    ///    sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
2272    ///    fused-into-wq `q_gate_split` form the dc arm handles.
2273    ///
2274    /// WHY EAGER-ONLY IS NOT A GAP TODAY: `graph_draft` requires `trunk_dense`, and this SKU's
2275    /// trunk is a 288-expert MoE, so the graph draft is already off for every step35 model — the
2276    /// eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
2277    /// than silently capturing a window-less (wrong past `win` draft rows) graph.
2278    ///
2279    /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
2280    /// caller must not mirror.
2281    fn mtp_step35_attn(
2282        &self,
2283        e: &Engine,
2284        fa: &FullAttnLayer,
2285        g: &crate::hybrid::Step35MtpGeom,
2286        h: &CudaSlice<f32>,
2287        pos_d: &CudaSlice<i32>,
2288        scratch: &mut MtpScratch,
2289    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2290        let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
2291        let eps = self.cfg.rms_eps;
2292        let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
2293        let n_embd = self.cfg.n_embd as usize;
2294        let gw = fa.attn_gate.as_ref()
2295            .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
2296
2297        let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk)
2298            && e.uses_q8_1_fast(&fa.wv) && e.uses_q8_1_fast(gw)
2299        {
2300            let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
2301            let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
2302                Some(t3) => t3,
2303                None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
2304                         e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
2305                         e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?),
2306            };
2307            (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
2308        } else {
2309            (e.matmul(&fa.wq, h, 1)?, e.matmul(&fa.wk, h, 1)?,
2310             e.matmul(&fa.wv, h, 1)?, e.matmul(gw, h, 1)?)
2311        };
2312
2313        let mut q = e.uninit(nh * hd)?;
2314        e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
2315        let mut k = e.uninit(nkv * hd)?;
2316        e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
2317        // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
2318        // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
2319        // the resolved flag, not the constant, so an all-full sibling stays correct.
2320        let ff = if g.swa { None } else {
2321            self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
2322        };
2323        #[cfg(debug_assertions)]
2324        if let Some(ff) = ff {
2325            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
2326                                                       "mtp_step35_attn.rope_freqs");
2327        }
2328        e.rope_neox2(&mut q, &mut k, pos_d, hd, g.n_rot, nh, nkv, 1, g.rope_base, 1.0, ff)?;
2329
2330        // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
2331        // length on the host anyway, and the windowed view below needs it there to compute the
2332        // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
2333        // dc-family consumer of this scratch still agree.
2334        let kv = &mut scratch.kv;
2335        assert!(kv.len < scratch.cap, "step35 MTP scratch overflow ({} >= {})", kv.len, scratch.cap);
2336        let next_len = kv.len + 1;
2337        let (off, t_kv) = if g.swa && next_len > g.window {
2338            (next_len - g.window, g.window)
2339        } else {
2340            (0, next_len)
2341        };
2342        let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
2343        e.append_kv_quantized(&k, &v0, &mut kv.k, &mut kv.v, write_row,
2344                              kv.kv_dim_k, kv.kv_dim_v, kv.k_tok_bytes, kv.v_tok_bytes, false)?;
2345        kv.len = next_len;
2346        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2347        // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
2348        // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
2349        // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
2350        // therefore live, not theoretical.
2351        let physical = kv.physical_rows(off, off + t_kv)?;
2352        let k_view = e.view_u8_range(&kv.k, physical.start * kv.k_tok_bytes,
2353                                     physical.end * kv.k_tok_bytes);
2354        let v_view = e.view_u8_range(&kv.v, physical.start * kv.v_tok_bytes,
2355                                     physical.end * kv.v_tok_bytes);
2356        let mut attn = e.uninit(nh * hd)?;
2357        e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
2358                          kv.k_tok_bytes, kv.v_tok_bytes, false)?;
2359
2360        let mut ag = e.uninit(nh * hd)?;
2361        e.attn_head_gate(&attn, &gt, &mut ag, None, hd, nh, 1)?;
2362        Ok(e.matmul(&fa.wo, &ag, 1)?)
2363    }
2364
2365    /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
2366    /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
2367    /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
2368    /// chain, and replays keep seeing KV growth through the device counter (no recapture).
2369    /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
2370    /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
2371    /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
2372    /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
2373    /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
2374    fn mtp_full_attn_dc(
2375        &self,
2376        e: &Engine,
2377        fa: &FullAttnLayer,
2378        h: &CudaSlice<f32>,
2379        pos_d: &CudaSlice<i32>,
2380        scratch: &mut MtpScratch,
2381        geom: Option<&crate::hybrid::DraftGeom>,
2382    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2383        let cfg = &self.cfg;
2384        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2385        let geometry = cfg.full_attention_geometry_at(mtp_il);
2386        let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
2387        let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(geometry.n_head_kv as usize);
2388        let head_dim = geometry.head_dim_k as usize;
2389        let eps = cfg.rms_eps;
2390        let scale = geometry.attention_scale();
2391        let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
2392        let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
2393
2394        let (qf, mut k, v) =
2395            if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
2396                let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
2397                (
2398                    e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
2399                    e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
2400                    e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
2401                )
2402            } else {
2403                (
2404                    e.matmul(&fa.wq, h, 1)?,
2405                    e.matmul(&fa.wk, h, 1)?,
2406                    e.matmul(&fa.wv, h, 1)?,
2407                )
2408            };
2409        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2410        let gated = geometry.attention_gate
2411            == memra_gguf::config::AttentionGateKind::FusedQ;
2412        let (mut q, gate) = if gated {
2413            let mut q = e.zeros(n_head * head_dim)?;
2414            let mut gate = e.zeros(n_head * head_dim)?;
2415            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
2416            (q, Some(gate))
2417        } else {
2418            (qf, None)
2419        };
2420
2421        let mut qn = e.zeros(n_head * head_dim)?;
2422        e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
2423        q = qn;
2424        let mut kn = e.zeros(n_head_kv * head_dim)?;
2425        e.rms_norm(
2426            &k,
2427            fa.k_norm.float_data(),
2428            &mut kn,
2429            head_dim,
2430            n_head_kv,
2431            eps,
2432        )?;
2433        k = kn;
2434        let rope_dims = geometry.n_rot as usize;
2435        e.rope_neox(
2436            &mut q,
2437            pos_d,
2438            head_dim,
2439            rope_dims,
2440            n_head,
2441            1,
2442            geometry.rope_base,
2443            1.0,
2444        )?;
2445        e.rope_neox(
2446            &mut k,
2447            pos_d,
2448            head_dim,
2449            rope_dims,
2450            n_head_kv,
2451            1,
2452            geometry.rope_base,
2453            1.0,
2454        )?;
2455
2456        let kv = &mut scratch.kv;
2457        // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
2458        e.append_kv_quantized_dc(
2459            &k,
2460            &v,
2461            &mut kv.k,
2462            &mut kv.v,
2463            &kv.len_d,
2464            kv.kv_dim_k,
2465            kv.kv_dim_v,
2466            kv.k_tok_bytes,
2467            kv.v_tok_bytes,
2468            false,
2469        )?;
2470        e.inc_seqlen(&mut kv.len_d)?;
2471        // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
2472        // key range from the device counter.
2473        let k_view = e.view_u8(&kv.k, kv.k.len());
2474        let v_view = e.view_u8(&kv.v, kv.v.len());
2475        let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
2476        let mut attn = e.zeros(n_head * head_dim)?;
2477        e.fa_decode_dc(
2478            &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
2479            scale, ktb, vtb, false,
2480        )?;
2481
2482        let attn_g = match &gate {
2483            Some(gate) => {
2484                let mut gsig = e.zeros(n_head * head_dim)?;
2485                e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2486                let mut ag = e.zeros(n_head * head_dim)?;
2487                e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2488                ag
2489            }
2490            None => attn,
2491        };
2492        Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2493    }
2494
2495    /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
2496    /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
2497    /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
2498    /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
2499    /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
2500    /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
2501    /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
2502    /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
2503    #[allow(clippy::too_many_arguments)]
2504    fn mtp_kv_fill(
2505        &self,
2506        e: &Engine,
2507        mtp: &MtpHead,
2508        tokens: &[u32],
2509        h: &CudaSlice<f32>,
2510        pos0: usize,
2511        scratch: &mut MtpScratch,
2512        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2513    ) -> Result<(), Box<dyn std::error::Error>> {
2514        let cfg = &self.cfg;
2515        let n_embd = cfg.n_embd as usize;
2516        let eps = cfg.rms_eps;
2517        let t = tokens.len();
2518        assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
2519        assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
2520        let Mixer::Full(fa) = &mtp.mixer else {
2521            panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2522        };
2523        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
2524        let pos_d = e.htod_i32(&pos_vec)?;
2525
2526        // ops A/1/2: embed + the two input norms, T-wide.
2527        let e_emb = match embd_dev {
2528            Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
2529            None => e.htod(&self.embd.gather(n_embd, tokens))?,
2530        };
2531        let mut e_norm = e.zeros(t * n_embd)?;
2532        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
2533        let mut h_norm = e.zeros(t * n_embd)?;
2534        e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
2535
2536        // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
2537        let mut concat = e.zeros(t * 2 * n_embd)?;
2538        for i in 0..t {
2539            e.copy_view_into(
2540                &mut concat,
2541                i * 2 * n_embd,
2542                &e_norm.slice(i * n_embd..(i + 1) * n_embd),
2543                n_embd,
2544            )?;
2545            e.copy_view_into(
2546                &mut concat,
2547                i * 2 * n_embd + n_embd,
2548                &h_norm.slice(i * n_embd..(i + 1) * n_embd),
2549                n_embd,
2550            )?;
2551        }
2552
2553        // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
2554        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2555        let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
2556        let mut a_norm = e.zeros(t * di)?;
2557        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
2558
2559        // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
2560        // the fill only has to leave correct K/V rows behind for later chains to attend over.
2561        let n_head_kv = mtp
2562            .geom
2563            .as_ref()
2564            .map(|g| g.n_head_kv)
2565            .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
2566            .unwrap_or_else(|| {
2567                let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2568                cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
2569            });
2570        let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2571        let geometry = cfg.full_attention_geometry_at(mtp_il);
2572        let head_dim = geometry.head_dim_k as usize;
2573        let mut k = e.matmul(&fa.wk, &a_norm, t)?;
2574        let v = e.matmul(&fa.wv, &a_norm, t)?;
2575        let mut kn = e.zeros(t * n_head_kv * head_dim)?;
2576        e.rms_norm(
2577            &k,
2578            fa.k_norm.float_data(),
2579            &mut kn,
2580            head_dim,
2581            n_head_kv * t,
2582            eps,
2583        )?;
2584        k = kn;
2585        // step35: rotary width AND base are per-layer, and the MTP block's values come from the
2586        // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
2587        // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
2588        // writes K rows the attention arm then re-derives at a different theta: correct-looking
2589        // output with dead acceptance, invisible to the exactness gates.
2590        let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
2591            Some(s) => (
2592                s.n_rot,
2593                s.rope_base,
2594                if s.swa { None } else {
2595                    self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
2596                },
2597            ),
2598            None => (geometry.n_rot as usize, geometry.rope_base, None),
2599        };
2600        #[cfg(debug_assertions)]
2601        if let Some(ff) = ff {
2602            crate::debug_assert_tensor_stream_device(ff, &e.stream(),
2603                                                       "mtp_kv_fill.rope_freqs");
2604        }
2605        match ff {
2606            Some(f) => e.rope_neox_ff(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, t,
2607                                      rope_base, 1.0, f)?,
2608            None => e.rope_neox(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, t,
2609                                rope_base, 1.0)?,
2610        }
2611
2612        let kv = &mut scratch.kv;
2613        // Match the trunk prime contract: a chunk may need the aligned window immediately before
2614        // its first row, so preserve that prefix when the physical tail rebases at wrap.
2615        let retain_from = kv
2616            .ring
2617            .as_ref()
2618            .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
2619            .unwrap_or(0);
2620        let write_row = e.prepare_kv_append(kv, retain_from, t)?;
2621        for i in 0..t {
2622            let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
2623            let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
2624            e.append_kv_quantized_view(
2625                &k_row,
2626                &v_row,
2627                &mut kv.k,
2628                &mut kv.v,
2629                write_row + i,
2630                kv.kv_dim_k,
2631                kv.kv_dim_v,
2632                kv.k_tok_bytes,
2633                kv.v_tok_bytes,
2634                false,
2635            )?;
2636        }
2637        kv.len = pos0 + t;
2638        e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2639        Ok(())
2640    }
2641
2642    /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
2643    /// every varying input device-resident —
2644    ///   - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
2645    ///     so the chain feeds itself; the host reads the same 4 bytes for the draft list),
2646    ///   - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
2647    ///   - rope pos from the persistent `pos_d` counter (inc'd in-graph),
2648    ///   - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
2649    /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
2650    /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
2651    /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
2652    /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
2653    /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
2654    /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
2655    /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
2656    /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
2657    /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
2658    /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
2659    /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
2660    /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
2661    /// seed/temp are capture-time constants (fixed per generate call, like p_min).
2662    #[allow(clippy::too_many_arguments)]
2663    fn mtp_head_forward_cap(
2664        &self,
2665        e: &Engine,
2666        mtp: &MtpHead,
2667        tok_d: &mut CudaSlice<u32>,
2668        pos_d: &mut CudaSlice<i32>,
2669        h_seed_d: &mut CudaSlice<f32>,
2670        p_d: &mut CudaSlice<f32>,
2671        scratch: &mut MtpScratch,
2672        with_prob: bool,
2673        with_head: bool,
2674        embd_gpu: &CudaSlice<u8>,
2675        embd_qt: i32,
2676        embd_rb: usize,
2677        d_vocab: usize,
2678        sampled_cap: Option<(
2679            &mut CudaSlice<u32>,
2680            &mut CudaSlice<f32>,
2681            &mut CudaSlice<f32>,
2682            u64,
2683            f32,
2684        )>,
2685        stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
2686        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
2687        // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
2688        // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
2689        // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
2690        // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
2691        mask_cap: Option<(&CudaSlice<u32>, usize)>,
2692    ) -> Result<(), Box<dyn std::error::Error>> {
2693        let cfg = &self.cfg;
2694        let n_embd = cfg.n_embd as usize;
2695        // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
2696        // whose device-counter key bound always starts at row 0 — it cannot express this block's
2697        // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
2698        // persistent scratch passes 512 rows. Nothing is lost today: `graph_draft` also requires
2699        // `trunk_dense`, and step35's trunk is a 288-expert MoE, so the eager chain
2700        // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
2701        // panic) is what the two capture sites and the round-stream capture already handle by
2702        // degrading to eager / stream-off.
2703        if mtp.step35.is_some() {
2704            return Err("step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
2705                        block's SWA view offset; same root cause as the dc decode refusal) — the \
2706                        eager draft chain serves this arch".into());
2707        }
2708        // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
2709        let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2710        let eps = cfg.rms_eps;
2711        let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
2712        let mut e_norm = e.zeros(n_embd)?;
2713        e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
2714        let mut h_norm = e.zeros(n_embd)?;
2715        e.rms_norm(
2716            &*h_seed_d,
2717            mtp.hnorm.float_data(),
2718            &mut h_norm,
2719            n_embd,
2720            1,
2721            eps,
2722        )?;
2723        let mut concat = e.zeros(2 * n_embd)?;
2724        e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
2725        e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
2726        let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
2727        let mut a_norm = e.zeros(di)?;
2728        e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
2729        let attn_out = match &mtp.mixer {
2730            Mixer::Full(fa) => {
2731                self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
2732            }
2733            Mixer::Linear(_) => {
2734                panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2735            }
2736            Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
2737        };
2738        let mut x1 = e.zeros(di)?;
2739        e.add(&inp_sa, &attn_out, &mut x1, di)?;
2740        let mut z = e.zeros(di)?;
2741        e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
2742        let ffn_out = match &mtp.ffn {
2743            crate::hybrid::Ffn::Dense {
2744                ffn_gate,
2745                ffn_up,
2746                ffn_down,
2747            } => {
2748                let n_ff = ffn_gate.out_features();
2749                let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
2750                    let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
2751                    (
2752                        e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
2753                        e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
2754                    )
2755                } else {
2756                    (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
2757                };
2758                let mut act = e.zeros(n_ff)?;
2759                Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
2760                e.matmul(ffn_down, &act, 1)?
2761            }
2762            // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
2763            // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
2764            // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
2765            // error arm degrades the caller to eager/stream-off.
2766            crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
2767                self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
2768            }
2769            crate::hybrid::Ffn::Moe(_) => {
2770                return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into())
2771            }
2772        };
2773        let mut h_inner = e.zeros(di)?;
2774        e.add(&x1, &ffn_out, &mut h_inner, di)?;
2775        // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
2776        let h_nextn = match mtp.geom.as_ref() {
2777            Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
2778            None => h_inner,
2779        };
2780        // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
2781        let final_h = if with_head || spec_hpost() {
2782            let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
2783            let mut fh = e.zeros(n_embd)?;
2784            e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
2785            Some(fh)
2786        } else {
2787            None
2788        };
2789        if with_head {
2790            let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
2791            let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
2792            // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
2793            // before the argmax — proposals become legal by construction. Contents-only
2794            // per-replay upload keeps the capture valid.
2795            if let Some((mask_d, mw)) = mask_cap {
2796                e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
2797            }
2798            if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
2799                // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
2800                // own buffer is pool-recycled after the capture body returns, so it can't be the
2801                // retention target), bump the device event counter, gumbel-perturb reading it,
2802                // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
2803                e.copy_into(q_out_d, 0, &logits, d_vocab)?;
2804                e.sctr_inc(ctr_d)?;
2805                e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
2806                e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
2807                // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
2808                // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
2809                if with_prob {
2810                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
2811                }
2812            } else {
2813                // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
2814                e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
2815                // p-min under a draft mask reads the MASKED row: confidence relative to the
2816                // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
2817                // is the right semantics for "does the drafter know what comes next here" and
2818                // the same row the pick came from. Draft-quality only — verify arbitrates.
2819                if with_prob {
2820                    e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
2821                }
2822            }
2823        }
2824        // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
2825        // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
2826        if let Some((out, slot, d2t)) = stream_pack {
2827            e.pack_tok_p(tok_d, p_d, out, slot)?;
2828            if let Some(map) = d2t {
2829                e.tok_map_u32(tok_d, map)?;
2830            }
2831        }
2832        // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
2833        if spec_hpost() {
2834            e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
2835        } else {
2836            e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
2837        }
2838        // advance the draft rope position in-graph.
2839        e.inc_seqlen(pos_d)?;
2840        Ok(())
2841    }
2842
2843    /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
2844    /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
2845    /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
2846    /// Advances `cache.pos` by T.
2847    pub fn decode_step_t(&self, e: &Engine, tokens: &[u32], pos0: usize, cache: &mut Cache)
2848                         -> Result<Vec<f32>, Box<dyn std::error::Error>> {
2849        if self.is_gemma4_e4b() {
2850            return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
2851        }
2852        if self.cfg.gemma4.is_some() {
2853            return self.gemma4_decode_step_t(e, tokens, pos0, cache);
2854        }
2855        Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
2856    }
2857
2858    /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
2859    /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
2860    /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
2861    /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
2862    pub fn decode_step_t_h(
2863        &self,
2864        e: &Engine,
2865        tokens: &[u32],
2866        pos0: usize,
2867        cache: &mut Cache,
2868    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2869        self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
2870    }
2871
2872    /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
2873    /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
2874    pub fn decode_step_t_h_emb(
2875        &self,
2876        e: &Engine,
2877        tokens: &[u32],
2878        pos0: usize,
2879        cache: &mut Cache,
2880        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2881    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2882        let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
2883        Ok((e.dtoh(&logits_d)?, h_seed))
2884    }
2885
2886    /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
2887    /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
2888    /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
2889    /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
2890    /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
2891    pub fn decode_step_t_h_emb_dev(
2892        &self,
2893        e: &Engine,
2894        tokens: &[u32],
2895        pos0: usize,
2896        cache: &mut Cache,
2897        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2898    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2899        let n_embd = self.cfg.n_embd as usize;
2900        let t = tokens.len();
2901        let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
2902        // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
2903        let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
2904        e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
2905        Ok((logits, hs))
2906    }
2907
2908    /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
2909    /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
2910    /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
2911    /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
2912    /// retains/copies — they never change what any kernel computes).
2913    fn decode_step_t_core(
2914        &self,
2915        e: &Engine,
2916        tokens: &[u32],
2917        pos0: usize,
2918        cache: &mut Cache,
2919        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2920        mut ckpt: Option<&mut VerifyCkpt>,
2921    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2922        self.decode_step_t_core_stream(
2923            e, tokens, pos0, cache, embd_dev, ckpt.take(), None, None,
2924        )
2925    }
2926
2927    /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
2928    /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
2929    fn decode_step_t_core_pipelined(
2930        &self,
2931        e: &Engine,
2932        tokens: &[u32],
2933        pos0: usize,
2934        cache: &mut Cache,
2935        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2936        mut ckpt: Option<&mut VerifyCkpt>,
2937        pipe: &SpecPipeLane,
2938        round: usize,
2939    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2940        let fence = crate::pp::pp_cuts(self.layers.len())
2941            .ok_or("two-session speculative pipeline requires a PP stage cut")?;
2942        if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
2943            return Err("two-session speculative pipeline requires the PP verify split".into());
2944        }
2945        let interval_fence = pipe.stage0_begin(round)?;
2946        let ticket = self.verify_stage0_issue(
2947            e,
2948            tokens,
2949            pos0,
2950            cache,
2951            embd_dev,
2952            ckpt.as_deref_mut(),
2953            None,
2954            &fence,
2955            Some(interval_fence),
2956            pipe.trace(round),
2957        )?;
2958        pipe.stage0_end(round);
2959        pipe.stage1_begin(round)?;
2960        let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
2961        pipe.verify_end(round);
2962        Ok(result)
2963    }
2964
2965    /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
2966    /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
2967    /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
2968    /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
2969    /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
2970    #[allow(clippy::too_many_arguments)]
2971    fn decode_step_t_core_stream(
2972        &self,
2973        e: &Engine,
2974        tokens: &[u32],
2975        pos0: usize,
2976        cache: &mut Cache,
2977        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2978        mut ckpt: Option<&mut VerifyCkpt>,
2979        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
2980        pp_pipe: Option<bool>,
2981    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2982        // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
2983        // exactly as the eager and batched steps do. This is the single funnel every verify
2984        // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
2985        // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
2986        // is untouched.
2987        //
2988        // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
2989        // walk was unsplit on one stream and a sharded cross-device placement peer-read every
2990        // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
2991        // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
2992        // or a placement whose PpNRt fails to build — so a config that would still walk the
2993        // whole trunk on one stream refuses instead of regressing 28x.
2994        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
2995            if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
2996                return self.decode_step_t_core_ppn(
2997                    e, tokens, pos0, cache, embd_dev, ckpt.take(), stream, &fence, pp_pipe,
2998                );
2999            }
3000        }
3001        crate::pp::refuse_unsplit_if_remote(
3002            "decode_step_t (spec verify)",
3003            "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
3004             split (decode_step_t_core_ppn); or run spec on one device",
3005        )?;
3006        let cfg = &self.cfg;
3007        let n_embd = cfg.n_embd as usize;
3008        let eps = cfg.rms_eps;
3009        let t = tokens.len();
3010        let pos_d = match stream {
3011            Some((_, ctr)) => {
3012                let mut p = e.alloc_uninit::<i32>(t)?;
3013                e.pos_iota(ctr, &mut p, t)?;
3014                p
3015            }
3016            None => {
3017                let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3018                e.htod_i32(&pos_vec)?
3019            }
3020        };
3021
3022        // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
3023        let x = match (stream, embd_dev) {
3024            (Some((vtok, _)), Some((g, qt, rb))) => {
3025                e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3026            }
3027            (None, Some((g, qt, rb))) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3028            _ => e.htod(&self.embd.gather(n_embd, tokens))?,
3029        };
3030
3031        // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
3032        // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
3033        // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
3034        let x = self.verify_layers(
3035            e, x, 0, self.layers.len(), &pos_d, pos0, t, cache, ckpt.take(), stream,
3036        )?;
3037
3038        let mut hn = vbuf(e, t * n_embd)?;
3039        let logits = if self.cfg.step35.is_some() {
3040            // Step35 serving uses one batched numeric class at every live width, including
3041            // B=1. Keep the verify head in that same class; the generic families retain the
3042            // decode-exact head that their run-spec contract pins.
3043            e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3044            e.matmul(&self.output, &hn, t)?
3045        } else {
3046            e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3047            e.matmul_decode_exact(&self.output, &hn, t)?
3048        };
3049        // stream: the device pos counter owns position; host mirror reconciles at drain.
3050        if stream.is_none() {
3051            cache.pos += t;
3052        }
3053        // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
3054        Ok((logits, if spec_hpost() { hn } else { x }))
3055    }
3056
3057    /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
3058    /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
3059    /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
3060    /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
3061    /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
3062    /// the payload).
3063    ///
3064    /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
3065    /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
3066    /// receipts):
3067    ///
3068    /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
3069    ///    (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
3070    ///    DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
3071    ///    (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
3072    ///    s>0 its own Engine even on the primary device; honouring it here is what scopes the
3073    ///    pools. The verify path allocates MORE of that scratch than eager decode does (FA at
3074    ///    m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
3075    ///
3076    /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
3077    ///    buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
3078    ///    stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
3079    ///    read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
3080    ///    stage derives the identical iota, and each stage's own output buffer is stream-local.
3081    ///
3082    /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
3083    ///    sharded loader leaves the table with stage 0 by construction).
3084    ///
3085    /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
3086    ///    both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
3087    ///    n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
3088    ///    model, every round.
3089    ///
3090    /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
3091    /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
3092    /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
3093    /// through the primary context by UVA — the same read the batched serving epilogue's
3094    /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
3095    /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
3096    ///
3097    /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
3098    /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
3099    /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
3100    ///
3101    /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
3102    /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
3103    /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
3104    /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
3105    /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
3106    /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
3107    /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
3108    /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
3109    #[allow(clippy::too_many_arguments)]
3110    fn decode_step_t_core_ppn(
3111        &self,
3112        e: &Engine,
3113        tokens: &[u32],
3114        pos0: usize,
3115        cache: &mut Cache,
3116        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3117        mut ckpt: Option<&mut VerifyCkpt>,
3118        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3119        fence: &[usize],
3120        pp_pipe: Option<bool>,
3121    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3122        let ticket = self.verify_stage0_issue(
3123            e,
3124            tokens,
3125            pos0,
3126            cache,
3127            embd_dev,
3128            ckpt.as_deref_mut(),
3129            stream,
3130            fence,
3131            pp_pipe,
3132            None,
3133        )?;
3134        self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
3135    }
3136
3137    /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
3138    /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
3139    #[allow(clippy::too_many_arguments)]
3140    fn verify_stage0_issue(
3141        &self,
3142        e: &Engine,
3143        tokens: &[u32],
3144        pos0: usize,
3145        cache: &mut Cache,
3146        embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3147        mut ckpt: Option<&mut VerifyCkpt>,
3148        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3149        fence: &[usize],
3150        pp_pipe: Option<bool>,
3151        trace: Option<SpecPipeTraceCtx>,
3152    ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
3153        assert!(
3154            !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
3155            "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
3156             (the gemma4 arms have their own decode_step_t twins)"
3157        );
3158        if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
3159            return Err(
3160                "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
3161                 boundary itself is host-staged, but device-resident verify still peer-reads \
3162                 primary-device token/position/embedding buffers from stage 0. Run plain PP \
3163                 serving on this host class; spec requires local per-stage inputs first."
3164                    .into(),
3165            );
3166        }
3167        let rt = crate::pp::PpNRt::get(e)?;
3168        let n_st = fence.len() - 1;
3169        assert_eq!(
3170            rt.n_stages(), n_st,
3171            "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
3172        );
3173        let n_embd = self.cfg.n_embd as usize;
3174        let t = tokens.len();
3175        let payload = t * n_embd;
3176        if pp_pipe.is_some() {
3177            assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
3178        }
3179        // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
3180        // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
3181        // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
3182        // the report below names exactly two stages and must never imply it measured middle ones.
3183        let pp_anatomy = n_st == 2
3184            && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
3185        let pp_started = std::time::Instant::now();
3186        let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
3187        // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
3188        // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
3189        // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
3190        // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
3191        // stage stream and the wait would self-order into a no-op.
3192        let caller_stream = e.stream();
3193        // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
3194        // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
3195        // the primary stream still holds queued reads of them — with event tracking elided,
3196        // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
3197        // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
3198        // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
3199        // stage stream behind the caller before enqueueing new stage work.
3200        let reverse_started = std::time::Instant::now();
3201        if pp_pipe != Some(false) {
3202            rt.fence_stages_behind(&caller_stream)?;
3203        }
3204        if pp_pipe == Some(true) {
3205            // Both session verifies must alternate boundary slots even when the ordinary
3206            // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
3207            // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
3208            rt.prepare_overlap_slots(0, payload)?;
3209        }
3210        if pp_anatomy {
3211            // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
3212            // prices any primary-stream rollback/refresh tail inherited from the prior round.
3213            for s in 0..n_st {
3214                let _st = rt.enter(s);
3215                rt.engine(s, e).stream().synchronize()?;
3216            }
3217            reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
3218        }
3219
3220        // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
3221        // stream mode each stage's own `pos_iota` over the shared read-only device counter.
3222        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3223            match stream {
3224                Some((_, ctr)) => {
3225                    let mut p = es.alloc_uninit::<i32>(t)?;
3226                    es.pos_iota(ctr, &mut p, t)?;
3227                    Ok(p)
3228                }
3229                None => {
3230                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3231                    es.htod_i32(&pos_vec)
3232                }
3233            }
3234        };
3235
3236        // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
3237        let slot = {
3238            let _st0 = rt.enter(0);
3239            let e0 = rt.engine(0, e);
3240            enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
3241            let stage0_started = std::time::Instant::now();
3242            let pos_d = stage_pos(e0)?;
3243            let x = match (stream, embd_dev) {
3244                (Some((vtok, _)), Some((g, qt, rb))) => {
3245                    e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3246                }
3247                (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3248                _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
3249            };
3250            let x = self.verify_layers(
3251                e0, x, fence[0], fence[1], &pos_d, pos0, t, cache, ckpt.as_deref_mut(), stream,
3252            )?;
3253            if pp_anatomy {
3254                e0.stream().synchronize()?;
3255                stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
3256            }
3257            let tx_started = std::time::Instant::now();
3258            let slot = if pp_pipe.is_some() {
3259                rt.tx_pipelined(0, &x, payload)?
3260            } else {
3261                rt.tx(0, &x, payload)?
3262            };
3263            enqueue_spec_pipe_trace_marker(
3264                &e0.stream(),
3265                trace.as_ref(),
3266                "S0",
3267                "end",
3268                Some(slot),
3269            )?;
3270            if pp_anatomy {
3271                e0.stream().synchronize()?;
3272                tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
3273            }
3274            slot
3275            // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
3276        };
3277
3278        Ok(VerifyBoundaryTicket {
3279            rt,
3280            caller_stream,
3281            slot,
3282            pos0,
3283            t,
3284            payload,
3285            n_st,
3286            pipelined: pp_pipe.is_some(),
3287            pp_anatomy,
3288            pp_started,
3289            reverse_ms,
3290            stage0_ms,
3291            tx_ms,
3292            trace,
3293        })
3294    }
3295
3296    /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
3297    /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
3298    #[allow(clippy::too_many_arguments)]
3299    fn verify_stage1_finish(
3300        &self,
3301        e: &Engine,
3302        ticket: VerifyBoundaryTicket,
3303        cache: &mut Cache,
3304        mut ckpt: Option<&mut VerifyCkpt>,
3305        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3306        fence: &[usize],
3307        publish_to_caller: bool,
3308    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3309        let VerifyBoundaryTicket {
3310            rt,
3311            caller_stream,
3312            slot,
3313            pos0,
3314            t,
3315            payload,
3316            n_st,
3317            pipelined,
3318            pp_anatomy,
3319            pp_started,
3320            reverse_ms,
3321            stage0_ms,
3322            tx_ms,
3323            trace,
3324        } = ticket;
3325        let n_embd = self.cfg.n_embd as usize;
3326        let eps = self.cfg.rms_eps;
3327        let mut slot = slot;
3328        let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
3329        let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3330            match stream {
3331                Some((_, ctr)) => {
3332                    let mut p = es.alloc_uninit::<i32>(t)?;
3333                    es.pos_iota(ctr, &mut p, t)?;
3334                    Ok(p)
3335                }
3336                None => {
3337                    let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3338                    es.htod_i32(&pos_vec)
3339                }
3340            }
3341        };
3342
3343        // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
3344        for s in 1..n_st - 1 {
3345            let _st = rt.enter(s);
3346            let es = rt.engine(s, e);
3347            let pos_d = stage_pos(es)?;
3348            let x = rt.rx(s - 1, slot, payload)?;
3349            let x = self.verify_layers(
3350                es, x, fence[s], fence[s + 1], &pos_d, pos0, t, cache,
3351                ckpt.as_deref_mut(), stream,
3352            )?;
3353            slot = if pipelined {
3354                rt.tx_pipelined(s, &x, payload)?
3355            } else {
3356                rt.tx(s, &x, payload)?
3357            };
3358        }
3359
3360        // ---- LAST STAGE: RX + final range + output_norm + lm head ----
3361        let _stl = rt.enter(n_st - 1);
3362        let el = rt.engine(n_st - 1, e);
3363        let pos_d = stage_pos(el)?;
3364        let rx_started = std::time::Instant::now();
3365        let x = rt.rx(n_st - 2, slot, payload)?;
3366        if pp_anatomy {
3367            el.stream().synchronize()?;
3368            rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
3369        }
3370        enqueue_spec_pipe_trace_marker(
3371            &el.stream(),
3372            trace.as_ref(),
3373            "S1",
3374            "start",
3375            Some(slot),
3376        )?;
3377        let stage1_started = std::time::Instant::now();
3378        let x = self.verify_layers(
3379            el, x, fence[n_st - 1], fence[n_st], &pos_d, pos0, t, cache,
3380            ckpt.as_deref_mut(), stream,
3381        )?;
3382
3383        let mut hn = vbuf(el, payload)?;
3384        let logits = if self.cfg.step35.is_some() {
3385            // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
3386            // Verify must not switch numeric class merely because the same session speculates.
3387            el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3388            el.matmul(&self.output, &hn, t)?
3389        } else {
3390            el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3391            el.matmul_decode_exact(&self.output, &hn, t)?
3392        };
3393        enqueue_spec_pipe_trace_marker(
3394            &el.stream(),
3395            trace.as_ref(),
3396            "S1",
3397            "end",
3398            Some(slot),
3399        )?;
3400        if pp_anatomy {
3401            el.stream().synchronize()?;
3402            stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
3403        }
3404        // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
3405        // stream. Order the caller's stream behind that work before the buffers escape this
3406        // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
3407        // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
3408        // the following arm's KV in the same process).
3409        if publish_to_caller {
3410            rt.publish_to(n_st - 1, &caller_stream)?;
3411        }
3412        if pp_anatomy {
3413            if publish_to_caller {
3414                caller_stream.synchronize()?;
3415            }
3416            eprintln!(
3417                "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
3418                 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
3419                pp_started.elapsed().as_secs_f64() * 1e3,
3420            );
3421        }
3422        // stream: the device pos counter owns position; host mirror reconciles at drain.
3423        if stream.is_none() {
3424            cache.pos += t;
3425        }
3426        Ok((logits, if spec_hpost() { hn } else { x }))
3427    }
3428
3429    /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
3430    ///
3431    /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
3432    /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
3433    /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
3434    /// Those classes are individually stable, but a near-tie prompt can choose different greedy
3435    /// bytes when a request moves from batched plain serving into speculative verify. Run the
3436    /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
3437    /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
3438    /// every norm/projection/FFN uses exactly the live serving dispatch.
3439    #[allow(clippy::too_many_arguments)]
3440    fn step35_verify_batch_layers(
3441        &self,
3442        e: &Engine,
3443        mut x: CudaSlice<f32>,
3444        lo: usize,
3445        hi: usize,
3446        pos0: usize,
3447        t: usize,
3448        cache: &mut Cache,
3449    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3450        let n_embd = self.cfg.n_embd as usize;
3451        self.cfg.step35.as_ref().ok_or("step35 verify batch requires step35 cfg")?;
3452        let mut ph_last = std::time::Instant::now();
3453        for il in lo..hi {
3454            let mut next = e.uninit(t * n_embd)?;
3455            for r in 0..t {
3456                let mut row = e.uninit(n_embd)?;
3457                e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
3458                // The caller owns this verify's position. During controller overlap, cache.pos
3459                // still describes generation N while this stage-0 walk belongs to N+1.
3460                let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
3461                let mut one = [&mut *cache];
3462                let out = self.step35_decode_batch_layers(
3463                    e,
3464                    row,
3465                    &mut one,
3466                    &row_pos,
3467                    il,
3468                    il + 1,
3469                    &mut ph_last,
3470                )?;
3471                e.dtod_copy_into(&out, &mut next, r * n_embd)?;
3472            }
3473            x = next;
3474        }
3475        Ok(x)
3476    }
3477
3478    /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
3479    /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
3480    /// carried in from outside the range) and exits with the range's final residual materialized
3481    /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
3482    /// instead of one.
3483    ///
3484    /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
3485    /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
3486    /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
3487    /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
3488    /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
3489    /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
3490    /// code — there is no "split version" of the verify math.
3491    ///
3492    /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
3493    /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
3494    /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
3495    /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
3496    #[allow(clippy::too_many_arguments)]
3497    fn verify_layers(
3498        &self,
3499        e: &Engine,
3500        mut x: CudaSlice<f32>,
3501        lo: usize,
3502        hi: usize,
3503        pos_d: &CudaSlice<i32>,
3504        pos0: usize,
3505        t: usize,
3506        cache: &mut Cache,
3507        mut ckpt: Option<&mut VerifyCkpt>,
3508        stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3509    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3510        if self.cfg.step35.is_some() {
3511            if stream.is_some() {
3512                return Err("step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
3513                            cannot express the SWA offset KV view)".into());
3514            }
3515            return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
3516        }
3517        let n_embd = self.cfg.n_embd as usize;
3518        let eps = self.cfg.rms_eps;
3519        // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
3520        // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
3521        // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
3522        // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
3523        // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
3524        // residual the next layer needs) as its `res` output. Falls back to the separate add
3525        // when the next layer is off the fused-q8 path.
3526        let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
3527        for il in lo..hi {
3528            let layer = &self.layers[il];
3529            // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
3530            // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
3531            // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
3532            // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
3533            // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
3534            // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
3535            // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
3536            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
3537            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
3538            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
3539            // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
3540            // projections only; Linear mixer: the batched arm — the per-column fallback needs
3541            // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
3542            // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
3543            // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
3544            // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
3545            // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
3546            // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
3547            // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
3548            // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
3549            let lin_q8_only = match &layer.mixer {
3550                Mixer::Linear(la) => {
3551                    (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
3552                }
3553                Mixer::Full(_) if self.cfg.step35.is_some() => false,
3554                _ => true,
3555            };
3556            // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
3557            // a non-fused layer still performs the residual add.
3558            let taken = pending.take();
3559            let (h, h_q8) = if norm_fused && lin_q8_only {
3560                let pair = match taken {
3561                    // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
3562                    // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
3563                    Some((x1p, f1p)) => {
3564                        let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
3565                        let p = e.add_rms_norm_q8_1(
3566                            &x1p, &f1p, layer.attn_norm.float_data(), &mut x2, n_embd, t, eps,
3567                        )?;
3568                        x = x2;
3569                        p
3570                    }
3571                    None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
3572                };
3573                (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
3574            } else {
3575                if let Some((x1p, f1p)) = taken {
3576                    let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
3577                    e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
3578                    x = x2;
3579                }
3580                let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
3581                if norm_fused {
3582                    e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
3583                } else {
3584                    e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
3585                }
3586                (h, None)
3587            };
3588            let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
3589
3590            let mixed = match &layer.mixer {
3591                Mixer::Full(fa) => {
3592                    self.full_attn_verify(e, fa, &h, h_q8_ref, pos_d, t, cache, il,
3593                                          stream.map(|(_, c)| c))?
3594                }
3595                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
3596                Mixer::Linear(la) => {
3597                    // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
3598                    // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
3599                    // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
3600                    // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
3601                    // chained T=1 steps (bit-identical). Falls back to the sequential per-column
3602                    // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
3603                    // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
3604                    // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
3605                    // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
3606                    // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
3607                    // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
3608                    if (t >= 3 || (t == 2 && spec_m2()))
3609                        && mixer_fast
3610                        && e.uses_q8_1_fast(&la.ssm_out)
3611                    {
3612                        let want = ckpt.is_some();
3613                        let (out, stash) =
3614                            self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
3615                        if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
3616                            ck.gdn[il] = Some(st);
3617                        }
3618                        out
3619                    } else {
3620                        let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
3621                        let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
3622                            if ckpt.is_some() && t >= 2 {
3623                                Some(Vec::with_capacity(t - 1))
3624                            } else {
3625                                None
3626                            };
3627                        for col in 0..t {
3628                            let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
3629                            let src = h.slice(col * n_embd..(col + 1) * n_embd);
3630                            e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
3631                            let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
3632                            e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
3633                            // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
3634                            // (pure dtod — cannot change any computed value). Last column skipped:
3635                            // rebuild targets are j <= t-1 columns.
3636                            if let Some(cs) = col_states.as_mut() {
3637                                if col + 1 < t {
3638                                    let rl = cache.recur[il].as_ref().unwrap();
3639                                    cs.push((
3640                                        e.clone_dtod(&rl.conv_state)?,
3641                                        e.clone_dtod(&rl.ssm_state)?,
3642                                    ));
3643                                }
3644                            }
3645                        }
3646                        if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
3647                            // ReplaySSM-assessment instrumentation (2026-07-30): the
3648                            // per-column clones are the only true state snapshots left in
3649                            // the verify (the batched path stashes INPUTS and replays).
3650                            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
3651                                static ONCE: std::sync::Once = std::sync::Once::new();
3652                                let bytes: usize = cs.iter()
3653                                    .map(|(c, s)| (c.len() + s.len()) * 4).sum();
3654                                ONCE.call_once(|| eprintln!(
3655                                    "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
3656                                    cs.len(), bytes as f64 / 1e6));
3657                            }
3658                            ck.cols[il] = Some(cs);
3659                        }
3660                        out
3661                    }
3662                }
3663            };
3664
3665            // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
3666            // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
3667            // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
3668            let ffn_fuse = match &layer.ffn {
3669                crate::hybrid::Ffn::Dense {
3670                    ffn_gate, ffn_up, ..
3671                } => {
3672                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
3673                        && e.uses_q8_1_fast(ffn_gate)
3674                        && e.uses_q8_1_fast(ffn_up)
3675                }
3676                crate::hybrid::Ffn::Moe(_) => false,
3677            };
3678            // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
3679            // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
3680            // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
3681            // per-row m=1 program; kernel-check pins bit-identity vs the unfused
3682            // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
3683            // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
3684            // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
3685            // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
3686            // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
3687            // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
3688            // mirror decode's dispatch or spec self-consistency fails.
3689            let dense_lim = self.cfg.clamp_shexp_at(il as u32);
3690            let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
3691            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
3692            let mut z = e.zeros(0)?; // replaced below on the unfused arms
3693            let z_q8 = if fuse_q8 {
3694                Some(e.add_rms_norm_q8_1(
3695                    &x,
3696                    &mixed,
3697                    layer.post_attn_norm.float_data(),
3698                    &mut x1,
3699                    n_embd,
3700                    t,
3701                    eps,
3702                )?)
3703            } else {
3704                let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
3705                if ffn_fuse {
3706                    e.add(&x, &mixed, &mut x1, t * n_embd)?;
3707                    e.rms_norm_decode(
3708                        &x1,
3709                        layer.post_attn_norm.float_data(),
3710                        &mut zf,
3711                        n_embd,
3712                        t,
3713                        eps,
3714                    )?;
3715                } else {
3716                    e.add_rms_norm(
3717                        &x,
3718                        &mixed,
3719                        layer.post_attn_norm.float_data(),
3720                        &mut x1,
3721                        &mut zf,
3722                        n_embd,
3723                        t,
3724                        eps,
3725                    )?;
3726                }
3727                z = zf;
3728                None
3729            };
3730            // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
3731            // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
3732            // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
3733            let ffn_out = match &layer.ffn {
3734                crate::hybrid::Ffn::Dense {
3735                    ffn_gate,
3736                    ffn_up,
3737                    ffn_down,
3738                } => {
3739                    let n_ff = ffn_gate.out_features();
3740                    if let Some((zq, zd)) = z_q8.as_ref() {
3741                        // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
3742                        // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
3743                        // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
3744                        // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
3745                        // scale_inplace store, value-exact) — the exact m=1 decode epilogue
3746                        // structure at nrows=t.
3747                        let pair = match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
3748                            Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
3749                            None => None,
3750                        };
3751                        let (gate, gs, up, us) = match pair {
3752                            Some(x4) => x4,
3753                            None => (
3754                                e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
3755                                1.0, // scale already applied inside _pre
3756                                e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
3757                                1.0,
3758                            ),
3759                        };
3760                        if e.uses_q8_1_fast(ffn_down) {
3761                            let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
3762                            e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
3763                        } else {
3764                            let mut act = vbuf(e, t * n_ff)?;
3765                            e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
3766                            e.matmul_decode_exact(ffn_down, &act, t)?
3767                        }
3768                    } else {
3769                        // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
3770                        // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
3771                        // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
3772                        // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
3773                        // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
3774                        let (gate, up) = match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
3775                            Some(pair) => pair,
3776                            None => (
3777                                e.matmul_decode_exact(ffn_gate, &z, t)?,
3778                                e.matmul_decode_exact(ffn_up, &z, t)?,
3779                            ),
3780                        };
3781                        let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
3782                        Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0, dense_lim,
3783                                          &mut act, t * n_ff)?;
3784                        e.matmul_decode_exact(ffn_down, &act, t)?
3785                    }
3786                }
3787                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
3788            };
3789            // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
3790            // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
3791            // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
3792            pending = Some((x1, ffn_out));
3793        }
3794        // RANGE's final add (no next norm INSIDE the range to fuse with; for the
3795        // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
3796        if let Some((x1p, f1p)) = pending.take() {
3797            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
3798            e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
3799            x = x2;
3800        }
3801        Ok(x)
3802    }
3803    /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
3804    /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
3805    /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
3806    /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
3807    /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
3808    /// ssm state exactly like T sequential decode steps.
3809    /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
3810    /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
3811    #[allow(clippy::too_many_arguments)]
3812    fn linear_attn_verify_t(
3813        &self,
3814        e: &Engine,
3815        la: &LinearAttnLayer,
3816        h: &CudaSlice<f32>,
3817        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
3818        t: usize,
3819        cache: &mut Cache,
3820        il: usize,
3821        want_stash: bool,
3822    ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
3823        let cfg = &self.cfg;
3824        let ssm = cfg.ssm.as_ref().unwrap();
3825        let d_state = ssm.state_size as usize;
3826        let num_k = ssm.group_count as usize;
3827        let num_v = ssm.time_step_rank as usize;
3828        let d_conv = ssm.conv_kernel as usize;
3829        let key_dim = d_state * num_k;
3830        let conv_dim = key_dim * 2 + d_state * num_v;
3831        let eps = cfg.rms_eps;
3832        let scale = 1.0 / (d_state as f32).sqrt();
3833
3834        // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
3835        // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
3836        // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
3837        // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
3838        // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
3839        // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
3840        // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
3841        // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
3842        // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
3843        // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
3844        // Bit-identical per (tensor,token,row) — see spec_fused_t().
3845        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
3846        // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
3847        // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
3848        // and feeds every projection; the caller guaranteed all four input projections are
3849        // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
3850        let h_q8_t = if h_q8.is_none()
3851            && spec_fused_t()
3852            && (2..=4).contains(&t)
3853            && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
3854                || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
3855        {
3856            Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
3857        } else {
3858            None
3859        };
3860        // one view: the caller's fused-norm q8 or this fn's own shared quantize.
3861        let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
3862            h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
3863        let (qkv_mixed, z) = {
3864            let mut fused = None;
3865            if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
3866                let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
3867                fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
3868            } else if let Some((hq, hd)) = hq8_any {
3869                if spec_fused_t() && (2..=4).contains(&t) {
3870                    fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
3871                }
3872            }
3873            match (fused, hq8_any) {
3874                (Some(pair), _) => pair,
3875                (None, Some((hq, hd))) if h_q8.is_some() => (
3876                    e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
3877                    e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
3878                ),
3879                (None, _) => (
3880                    e.matmul_decode_exact(&la.wqkv, h, t)?,
3881                    e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
3882                ),
3883            }
3884        };
3885        // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
3886        // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
3887        // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
3888        // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
3889        let (beta_raw, alpha) = if t == 1 {
3890            let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
3891            match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
3892                Some(((mut b, bs), (mut a, as_))) => {
3893                    if bs != 1.0 {
3894                        e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
3895                    }
3896                    if as_ != 1.0 {
3897                        e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
3898                    }
3899                    (b, a)
3900                }
3901                // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
3902                // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
3903                // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
3904                None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
3905                    Some((b, a)) => (b, a),
3906                    None => (
3907                        e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
3908                        e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
3909                    ),
3910                },
3911            }
3912        } else {
3913            // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
3914            // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
3915            let mut nvfp4_fused = None;
3916            let mut q8_fused = None;
3917            if let Some((hq, hd)) = hq8_any {
3918                if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
3919                    nvfp4_fused = e.matmul_decode_exact_dual_pre(
3920                        &la.ssm_beta,
3921                        &la.ssm_alpha,
3922                        hq,
3923                        hd,
3924                        t,
3925                    )?;
3926                    if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
3927                        static ONCE: std::sync::Once = std::sync::Once::new();
3928                        ONCE.call_once(|| eprintln!(
3929                            "[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})"
3930                        ));
3931                    }
3932                }
3933                if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
3934                    q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
3935                }
3936            }
3937            if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
3938                    if bs != 1.0 {
3939                        e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
3940                    }
3941                    if as_ != 1.0 {
3942                        e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
3943                    }
3944                    (b, a)
3945            } else if let Some(pair) = q8_fused {
3946                pair
3947            } else { match hq8_any {
3948                Some((hq, hd)) if h_q8.is_some() => (
3949                    e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
3950                    e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
3951                ),
3952                _ => (
3953                    e.matmul_decode_exact(&la.ssm_beta, h, t)?,
3954                    e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
3955                ),
3956            }}
3957        };
3958
3959        // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
3960        // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
3961        let rl = cache.recur[il].as_mut().unwrap();
3962        let mut conv_out = e.uninit(conv_dim * t)?;
3963        e.ssm_conv1d_tm_state(
3964            &qkv_mixed,
3965            &mut rl.conv_state,
3966            la.ssm_conv1d.float_data(),
3967            &mut conv_out,
3968            conv_dim,
3969            t,
3970            d_conv,
3971        )?;
3972
3973        // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
3974        let mut q_g = e.uninit(d_state * num_v * t)?;
3975        let mut k_g = e.uninit(d_state * num_v * t)?;
3976        let mut v_g = e.uninit(d_state * num_v * t)?;
3977        e.qkv_to_gdn_repack(
3978            &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
3979        )?;
3980        let mut q_l2 = e.uninit(d_state * num_v * t)?;
3981        e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
3982        let mut k_l2 = e.uninit(d_state * num_v * t)?;
3983        e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
3984        let mut beta = e.uninit(t * num_v)?;
3985        e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
3986        let mut g_log = e.uninit(t * num_v)?;
3987        e.gdn_glog(
3988            &alpha,
3989            la.ssm_dt.float_data(),
3990            la.ssm_a.float_data(),
3991            &mut g_log,
3992            num_v,
3993            t,
3994        )?;
3995
3996        // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
3997        // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
3998        let mut o = e.uninit(d_state * num_v * t)?;
3999        {
4000            let crate::cache::RecurLayer {
4001                ssm_state,
4002                ssm_state_alt,
4003                ..
4004            } = rl;
4005            e.gdn_scan_s128(
4006                &q_l2,
4007                &k_l2,
4008                &v_g,
4009                &g_log,
4010                &beta,
4011                ssm_state,
4012                ssm_state_alt,
4013                &mut o,
4014                num_v,
4015                t,
4016                scale,
4017            )?;
4018        }
4019        std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
4020
4021        // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
4022        // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
4023        // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
4024        // T-wide launch is the per-row program; kernel-check pins bit-identity vs
4025        // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
4026        // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
4027        let out = if e.uses_q8_1_fast(&la.ssm_out) {
4028            let (gq, gd) =
4029                e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
4030            e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
4031        } else {
4032            let mut gn = e.uninit(d_state * num_v * t)?;
4033            e.gated_rmsnorm(
4034                &o,
4035                la.ssm_norm.float_data(),
4036                &z,
4037                &mut gn,
4038                d_state,
4039                num_v * t,
4040                eps,
4041            )?;
4042            // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
4043            // would fall to dp4a with a different FP reduction order — same class of bug as
4044            // the input projs).
4045            e.matmul_decode_exact(&la.ssm_out, &gn, t)?
4046        };
4047        let stash = if want_stash {
4048            Some(GdnStash {
4049                qkv_mixed,
4050                q_l2,
4051                k_l2,
4052                v_g,
4053                g_log,
4054                beta,
4055            })
4056        } else {
4057            None
4058        };
4059        Ok((out, stash))
4060    }
4061
4062    /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
4063    /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
4064    /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
4065    ///   are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
4066    ///   verify-probe gates), so keeping them == replaying them.
4067    /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
4068    ///   columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
4069    ///   snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
4070    ///   registers and writes it once at the end, so iterations 0..j-1 are independent of T:
4071    ///   bit-identical to the verify's own state after j tokens == the eager chain state.
4072    /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
4073    /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
4074    fn commit_verified_prefix(
4075        &self,
4076        e: &Engine,
4077        cache: &mut Cache,
4078        snap: &crate::cache::CacheSnapshot,
4079        ckpt: &VerifyCkpt,
4080        j: usize,
4081        kv_lens_done: bool,
4082        dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
4083    ) -> Result<(), Box<dyn std::error::Error>> {
4084        let cfg = &self.cfg;
4085        let ssm = cfg.ssm.as_ref().unwrap();
4086        let d_state = ssm.state_size as usize;
4087        let num_k = ssm.group_count as usize;
4088        let num_v = ssm.time_step_rank as usize;
4089        let d_conv = ssm.conv_kernel as usize;
4090        let conv_dim = d_state * num_k * 2 + d_state * num_v;
4091        let scale = 1.0 / (d_state as f32).sqrt();
4092        for il in 0..self.layers.len() {
4093            if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
4094                kvl.len = saved + j;
4095                // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
4096                if !kv_lens_done {
4097                    e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
4098                }
4099            }
4100            if let Some(rl) = cache.recur[il].as_mut() {
4101                if let Some(st) = &ckpt.gdn[il] {
4102                    let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
4103                    let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
4104                    if let Some((acc, base, t_v)) = dev_j {
4105                        // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
4106                        e.ssm_conv_ring_rebuild_dc(
4107                            &st.qkv_mixed,
4108                            ring_old,
4109                            &mut rl.conv_state,
4110                            conv_dim,
4111                            acc,
4112                            base,
4113                            t_v,
4114                            d_conv,
4115                        )?;
4116                        let mut o = e.uninit(d_state * num_v * j.max(1))?;
4117                        e.gdn_scan_s128_dc(
4118                            &st.q_l2,
4119                            &st.k_l2,
4120                            &st.v_g,
4121                            &st.g_log,
4122                            &st.beta,
4123                            state_in,
4124                            &mut rl.ssm_state,
4125                            &mut o,
4126                            num_v,
4127                            acc,
4128                            base,
4129                            t_v,
4130                            scale,
4131                        )?;
4132                    } else {
4133                        e.ssm_conv_ring_rebuild(
4134                            &st.qkv_mixed,
4135                            ring_old,
4136                            &mut rl.conv_state,
4137                            conv_dim,
4138                            j,
4139                            d_conv,
4140                        )?;
4141                        let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
4142                        e.gdn_scan_s128(
4143                            &st.q_l2,
4144                            &st.k_l2,
4145                            &st.v_g,
4146                            &st.g_log,
4147                            &st.beta,
4148                            state_in,
4149                            &mut rl.ssm_state,
4150                            &mut o,
4151                            num_v,
4152                            j,
4153                            scale,
4154                        )?;
4155                    }
4156                } else if let Some(cols) = &ckpt.cols[il] {
4157                    let (c, s) = &cols[j - 1];
4158                    e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
4159                    e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
4160                } else {
4161                    return Err(
4162                        "commit_verified_prefix: verify ckpt missing for linear layer".into(),
4163                    );
4164                }
4165            }
4166        }
4167        cache.pos = snap.pos + j;
4168        Ok(())
4169    }
4170
4171    /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
4172    /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
4173    fn commit_verified_prefix_stream(
4174        &self,
4175        e: &Engine,
4176        cache: &mut Cache,
4177        snap: &crate::cache::CacheSnapshot,
4178        ckpt: &VerifyCkpt,
4179        acc: &CudaSlice<u32>,
4180        base: usize,
4181        t_v: usize,
4182    ) -> Result<(), Box<dyn std::error::Error>> {
4183        let cfg = &self.cfg;
4184        let ssm = cfg.ssm.as_ref().unwrap();
4185        let d_state = ssm.state_size as usize;
4186        let num_k = ssm.group_count as usize;
4187        let num_v = ssm.time_step_rank as usize;
4188        let d_conv = ssm.conv_kernel as usize;
4189        let conv_dim = d_state * num_k * 2 + d_state * num_v;
4190        let scale = 1.0 / (d_state as f32).sqrt();
4191        for il in 0..self.layers.len() {
4192            if let Some(rl) = cache.recur[il].as_mut() {
4193                let st = ckpt.gdn[il]
4194                    .as_ref()
4195                    .ok_or("stream restore: batched-linear stash missing")?;
4196                let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
4197                let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
4198                e.ssm_conv_ring_rebuild_dc(
4199                    &st.qkv_mixed,
4200                    ring_old,
4201                    &mut rl.conv_state,
4202                    conv_dim,
4203                    acc,
4204                    base,
4205                    t_v,
4206                    d_conv,
4207                )?;
4208                let mut o = e.uninit(d_state * num_v * t_v)?;
4209                e.gdn_scan_s128_dc(
4210                    &st.q_l2,
4211                    &st.k_l2,
4212                    &st.v_g,
4213                    &st.g_log,
4214                    &st.beta,
4215                    state_in,
4216                    &mut rl.ssm_state,
4217                    &mut o,
4218                    num_v,
4219                    acc,
4220                    base,
4221                    t_v,
4222                    scale,
4223                )?;
4224            }
4225        }
4226        Ok(())
4227    }
4228
4229    /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
4230    /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
4231    /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
4232    /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
4233    /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
4234    pub fn decode_step_t_aux2(
4235        &self,
4236        e: &Engine,
4237        tokens: &[u32],
4238        pos0: usize,
4239        cache: &mut Cache,
4240        aux_layers: &[usize],
4241        pred_col: Option<usize>,
4242    ) -> Result<
4243        (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
4244        Box<dyn std::error::Error>,
4245    > {
4246        let cfg = &self.cfg;
4247        let n_embd = cfg.n_embd as usize;
4248        let eps = cfg.rms_eps;
4249        let t = tokens.len();
4250        let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4251        let pos_d = e.htod_i32(&pos_vec)?;
4252        let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
4253        let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
4254        let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
4255        let want_pred = pred_col.is_some();
4256
4257        for (il, layer) in self.layers.iter().enumerate() {
4258            // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
4259            let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
4260            let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
4261            let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
4262            if norm_fused {
4263                e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4264            } else {
4265                e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4266            }
4267            let mixed = match &layer.mixer {
4268                Mixer::Full(fa) => {
4269                    self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
4270                }
4271                Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4272                Mixer::Linear(la) => {
4273                    let mut out = e.zeros(t * n_embd)?;
4274                    for col in 0..t {
4275                        let mut h_col = e.zeros(n_embd)?;
4276                        let src = h.slice(col * n_embd..(col + 1) * n_embd);
4277                        e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
4278                        let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
4279                        e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
4280                    }
4281                    out
4282                }
4283            };
4284            let ffn_fuse = match &layer.ffn {
4285                crate::hybrid::Ffn::Dense {
4286                    ffn_gate, ffn_up, ..
4287                } => {
4288                    std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
4289                        && e.uses_q8_1_fast(ffn_gate)
4290                        && e.uses_q8_1_fast(ffn_up)
4291                }
4292                crate::hybrid::Ffn::Moe(_) => false,
4293            };
4294            let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
4295            let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
4296            if ffn_fuse {
4297                e.add(&x, &mixed, &mut x1, t * n_embd)?;
4298                e.rms_norm_decode(
4299                    &x1,
4300                    layer.post_attn_norm.float_data(),
4301                    &mut z,
4302                    n_embd,
4303                    t,
4304                    eps,
4305                )?;
4306            } else {
4307                e.add_rms_norm(
4308                    &x,
4309                    &mixed,
4310                    layer.post_attn_norm.float_data(),
4311                    &mut x1,
4312                    &mut z,
4313                    n_embd,
4314                    t,
4315                    eps,
4316                )?;
4317            }
4318            let ffn_out = match &layer.ffn {
4319                crate::hybrid::Ffn::Dense {
4320                    ffn_gate,
4321                    ffn_up,
4322                    ffn_down,
4323                } => {
4324                    let n_ff = ffn_gate.out_features();
4325                    let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
4326                    let up = e.matmul_decode_exact(ffn_up, &z, t)?;
4327                    let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
4328                    // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
4329                    Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
4330                                      self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
4331                    e.matmul_decode_exact(ffn_down, &act, t)?
4332                }
4333                crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
4334            };
4335            let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
4336            e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
4337            if aux_layers.contains(&il) {
4338                let mut a = e.zeros(n_embd)?;
4339                e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
4340                aux_last.push(a);
4341                if let Some(pc) = pred_col {
4342                    let mut ap = e.zeros(n_embd)?;
4343                    e.copy_view_into(
4344                        &mut ap,
4345                        0,
4346                        &x2.slice(pc * n_embd..(pc + 1) * n_embd),
4347                        n_embd,
4348                    )?;
4349                    aux_pred.push(ap);
4350                }
4351            }
4352            x = x2;
4353        }
4354        let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
4355        e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4356        let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
4357        let host = e.dtoh(&logits)?;
4358        cache.pos += t;
4359        Ok((
4360            host,
4361            aux_last,
4362            if want_pred { Some(aux_pred) } else { None },
4363        ))
4364    }
4365
4366    /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
4367    /// `step35_decode_attn`.
4368    ///
4369    /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
4370    /// the eager decode would have computed for the same tokens; that is what makes greedy spec
4371    /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
4372    /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
4373    /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
4374    /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
4375    /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
4376    /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
4377    /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
4378    /// position of each query row. A batched twin would have to reproduce all of that AND the
4379    /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
4380    /// take one `base_len`, not a per-row offset).
4381    ///
4382    /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
4383    /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
4384    /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
4385    /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
4386    /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
4387    /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
4388    /// step35 twin is a perf lane's job and must be gated against this arm.
4389    ///
4390    /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
4391    /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
4392    /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
4393    /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
4394    /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
4395    #[allow(clippy::too_many_arguments)]
4396    fn step35_verify(
4397        &self,
4398        e: &Engine,
4399        fa: &FullAttnLayer,
4400        h: &CudaSlice<f32>,
4401        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
4402        t: usize,
4403        cache: &mut Cache,
4404        il: usize,
4405    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4406        let n_embd = self.cfg.n_embd as usize;
4407        // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
4408        // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
4409        // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
4410        // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
4411        // cannot regress it into silently reading an empty buffer.
4412        assert_eq!(
4413            h.len(),
4414            t * n_embd,
4415            "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
4416             fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
4417            h_q8.is_some()
4418        );
4419        // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
4420        // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
4421        // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
4422        // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
4423        // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
4424        // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
4425        let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
4426        for r in 0..t {
4427            // Absolute position of this query row. `cache.pos` is the committed length at round
4428            // start and every row before r has already been appended by this loop, so the r-th
4429            // verify token sits at cache.pos + r — the same position eager decode would give it.
4430            let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
4431            let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
4432            e.copy_view_into(&mut h_row, 0, &h.slice(r * n_embd..(r + 1) * n_embd), n_embd)?;
4433            // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
4434            // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
4435            let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
4436            debug_assert_eq!(o.len(), n_embd, "step35_decode_attn returns post-wo [n_embd]");
4437            e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
4438        }
4439        Ok(out)
4440    }
4441
4442    /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
4443    /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
4444    /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
4445    #[allow(clippy::too_many_arguments)]
4446    fn full_attn_verify(
4447        &self,
4448        e: &Engine,
4449        fa: &FullAttnLayer,
4450        h: &CudaSlice<f32>,
4451        h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
4452        pos_d: &CudaSlice<i32>,
4453        t: usize,
4454        cache: &mut Cache,
4455        il: usize,
4456        stream_ctr: Option<&CudaSlice<i32>>,
4457    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4458        // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
4459        // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
4460        // its own arm. A verify that silently computes different attention than decode defeats the
4461        // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
4462        // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
4463        // shape and not laziness.
4464        if self.cfg.step35.is_some() {
4465            if stream_ctr.is_some() {
4466                return Err("step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
4467                            cannot express the SWA offset KV view; same root cause as the dc \
4468                            decode refusal) — run spec without the stream arm".into());
4469            }
4470            return self.step35_verify(e, fa, h, h_q8, t, cache, il);
4471        }
4472        let cfg = &self.cfg;
4473        let geometry = cfg.full_attention_geometry_at(il as u32);
4474        let n_head = geometry.n_head as usize;
4475        let n_head_kv = geometry.n_head_kv as usize;
4476        let head_dim = geometry.head_dim_k as usize;
4477        let eps = cfg.rms_eps;
4478        let scale = geometry.attention_scale();
4479        let n_embd = cfg.n_embd as usize;
4480
4481        // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
4482        // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
4483        // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
4484        // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
4485        // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
4486        // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
4487        // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
4488        // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
4489        let (qf, mut k, v) = {
4490            let mut fused = None;
4491            let qkv_fast = e.uses_q8_1_fast(&fa.wq)
4492                && e.uses_q8_1_fast(&fa.wk)
4493                && e.uses_q8_1_fast(&fa.wv);
4494            if t == 1 && qkv_fast {
4495                let (hq_o, hd_o);
4496                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
4497                    Some(p) => p,
4498                    None => {
4499                        (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
4500                        (&hq_o, &hd_o)
4501                    }
4502                };
4503                fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
4504            } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
4505                // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
4506                // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
4507                // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
4508                let (hq_o, hd_o);
4509                let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
4510                    Some(p) => p,
4511                    None => {
4512                        (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
4513                        (&hq_o, &hd_o)
4514                    }
4515                };
4516                fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
4517            }
4518            match (fused, h_q8) {
4519                (Some(triple), _) => triple,
4520                // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
4521                // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
4522                (None, Some((hq, hd))) if qkv_fast => (
4523                    e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
4524                    e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
4525                    e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
4526                ),
4527                (None, _) => (
4528                    e.matmul_decode_exact(&fa.wq, h, t)?,
4529                    e.matmul_decode_exact(&fa.wk, h, t)?,
4530                    e.matmul_decode_exact(&fa.wv, h, t)?,
4531                ),
4532            }
4533        };
4534        // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
4535        let gated = geometry.attention_gate
4536            == memra_gguf::config::AttentionGateKind::FusedQ;
4537        let (mut q, gate) = if gated {
4538            let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
4539            let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
4540            e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
4541            (q, Some(gate))
4542        } else {
4543            (qf, None)
4544        };
4545
4546        let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
4547        e.rms_norm(
4548            &q,
4549            fa.q_norm.float_data(),
4550            &mut qn,
4551            head_dim,
4552            n_head * t,
4553            eps,
4554        )?;
4555        q = qn;
4556        let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
4557        e.rms_norm(
4558            &k,
4559            fa.k_norm.float_data(),
4560            &mut kn,
4561            head_dim,
4562            n_head_kv * t,
4563            eps,
4564        )?;
4565        k = kn;
4566        let rope_dims = geometry.n_rot as usize;
4567        e.rope_neox(
4568            &mut q,
4569            pos_d,
4570            head_dim,
4571            rope_dims,
4572            n_head,
4573            t,
4574            geometry.rope_base,
4575            1.0,
4576        )?;
4577        e.rope_neox(
4578            &mut k,
4579            pos_d,
4580            head_dim,
4581            rope_dims,
4582            n_head_kv,
4583            t,
4584            geometry.rope_base,
4585            1.0,
4586        )?;
4587
4588        // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
4589        // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
4590        let kvl = cache.kv[il].as_mut().unwrap();
4591        let (kv_dim_k, kv_dim_v, ktb, vtb) =
4592            (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
4593        if let Some(ctr) = stream_ctr {
4594            // stream: ONE batched append at the device counter (rows kernel = the per-view warp
4595            // math on a (block, token) grid, documented byte-identical); host len is a stale
4596            // LOWER BOUND under pre-issue (drain reconciles it).
4597            e.append_kv_quantized_rows_dc(
4598                &k,
4599                &v,
4600                &mut kvl.k,
4601                &mut kvl.v,
4602                ctr,
4603                t,
4604                kv_dim_k,
4605                kv_dim_v,
4606                ktb,
4607                vtb,
4608                crate::Engine::kv_fp8_on(),
4609            )?;
4610        } else {
4611            for i in 0..t {
4612                let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
4613                let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
4614                e.append_kv_quantized_view(
4615                    &k_row,
4616                    &v_row,
4617                    &mut kvl.k,
4618                    &mut kvl.v,
4619                    kvl.len + i,
4620                    kv_dim_k,
4621                    kv_dim_v,
4622                    ktb,
4623                    vtb,
4624                    crate::Engine::kv_fp8_on(),
4625                )?;
4626            }
4627            kvl.len += t;
4628        }
4629
4630        // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
4631        // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
4632        // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
4633        // which changes FP summation order and can flip argmax at tight logit margins. Query row r
4634        // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
4635        // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
4636        // keys. The verify appends all T tokens first but bounds the key range per row.
4637        //
4638        // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
4639        // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
4640        // per-row program for all T rows (grid.z = row, per-row n_splits from the same
4641        // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
4642        // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
4643        // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
4644        // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
4645        // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
4646        let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
4647        let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
4648                                    // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
4649                                    // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
4650                                    // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
4651                                    // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
4652                                    // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
4653                                    // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
4654                                    // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
4655                                    // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
4656        if let Some(ctr) = stream_ctr {
4657            // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
4658            // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
4659            // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
4660            let upper = kvl.len + t + 64;
4661            let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
4662            let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
4663            e.fa_decode_rows_dc(
4664                &q,
4665                &k_view,
4666                &v_view,
4667                &mut attn,
4668                head_dim,
4669                n_head,
4670                n_head_kv,
4671                ctr,
4672                upper.min(cache.max_ctx),
4673                t,
4674                scale,
4675                ktb,
4676                vtb,
4677                0,
4678                false,
4679            )?;
4680        } else if spec_lean() && t == 1 {
4681            let t_kv = base_len + 1;
4682            let k_view = e.view_u8(&kvl.k, t_kv * ktb);
4683            let v_view = e.view_u8(&kvl.v, t_kv * vtb);
4684            e.fa_decode_kvmod(
4685                &q,
4686                &k_view,
4687                &v_view,
4688                &mut attn,
4689                head_dim,
4690                n_head,
4691                n_head_kv,
4692                t_kv,
4693                scale,
4694                ktb,
4695                vtb,
4696                crate::Engine::kv_fp8_on(),
4697            )?;
4698        } else if e.fa_rows_eligible(base_len, head_dim) {
4699            let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
4700            let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
4701            e.fa_decode_rows(
4702                &q,
4703                &k_view,
4704                &v_view,
4705                &mut attn,
4706                head_dim,
4707                n_head,
4708                n_head_kv,
4709                base_len,
4710                t,
4711                scale,
4712                ktb,
4713                vtb,
4714                None,
4715                false,
4716                crate::Engine::kv_fp8_on(),
4717                None,
4718            )?;
4719        } else {
4720            for r in 0..t {
4721                let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
4722                let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
4723                let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
4724                // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
4725                let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
4726                let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
4727                e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
4728                let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
4729                e.fa_decode_kvmod(
4730                    &q_row,
4731                    &k_view_r,
4732                    &v_view_r,
4733                    &mut attn_row,
4734                    head_dim,
4735                    n_head,
4736                    n_head_kv,
4737                    t_kv_r,
4738                    scale,
4739                    ktb,
4740                    vtb,
4741                    crate::Engine::kv_fp8_on(),
4742                )?;
4743                e.copy_into(
4744                    &mut attn,
4745                    r * n_head * head_dim,
4746                    &attn_row,
4747                    n_head * head_dim,
4748                )?;
4749            }
4750        }
4751
4752        let attn_g = match &gate {
4753            Some(gate) => {
4754                let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
4755                e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
4756                let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
4757                e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
4758                ag
4759            }
4760            None => attn,
4761        };
4762        // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
4763        // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
4764        Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
4765    }
4766
4767    /// Context-linear bytes for a plain serving session's trunk cache.
4768    pub fn plain_session_kv_bytes_per_token(&self) -> usize {
4769        crate::cache::cache_bytes_per_token(&self.cfg)
4770    }
4771
4772    /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
4773    pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
4774        (
4775            self.plain_session_kv_bytes_per_token(),
4776            crate::cache::cache_ring_bytes_per_token(&self.cfg),
4777            crate::cache::cache_ring_row_cap(&self.cfg),
4778        )
4779    }
4780
4781    /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
4782    /// scratch. With no MTP head this equals the plain coefficient.
4783    pub fn spec_session_kv_bytes_per_token(&self) -> usize {
4784        let scratch = self
4785            .mtp
4786            .as_ref()
4787            .map(|mtp| {
4788                let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
4789                k + v
4790            })
4791            .unwrap_or(0);
4792        self.plain_session_kv_bytes_per_token()
4793            .saturating_add(scratch)
4794    }
4795
4796    /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
4797    /// capped by the same SWA ring rows as the trunk.
4798    pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
4799        let total = self.spec_session_kv_bytes_per_token();
4800        let (_, mut ring, rows) = self.plain_session_kv_shape();
4801        if rows > 0 {
4802            ring = ring.saturating_add(
4803                self.mtp
4804                    .as_ref()
4805                    .map(|mtp| {
4806                        let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
4807                        k + v
4808                    })
4809                    .unwrap_or(0),
4810            );
4811        }
4812        (total, ring, rows)
4813    }
4814
4815    /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
4816    /// the NextN head to draft K tokens then verifies them in one batched target forward.
4817    /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
4818    /// acceptance rate. `k` = draft length per round.
4819    ///
4820    /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
4821    /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
4822    /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
4823    /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
4824    /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
4825    /// captured graph references is event-free; the spec loop is strictly single-stream.
4826    /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
4827    /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
4828    /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
4829    /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
4830    /// generate_spec_inner2.
4831    /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
4832    /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
4833    /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
4834    /// hybrid linear-attn states are in-place (no position index), so a session can extend but
4835    /// never rewind — `committed` is the exact token list whose state the caches hold (includes
4836    /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
4837    pub fn new_session(
4838        &self,
4839        e: &Engine,
4840        max_ctx: usize,
4841    ) -> Result<SpecSession, Box<dyn std::error::Error>> {
4842        Ok(SpecSession {
4843            // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
4844            // is the SERVING spec-session path, and with the ppN door open across two cards a
4845            // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
4846            // round — the wrong-card class already fixed on the two batched serving paths
4847            // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
4848            // branch, same allocations), so single-device behavior is byte-unchanged.
4849            cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
4850            scratch: MtpScratch::new(
4851                e,
4852                &self.cfg,
4853                max_ctx,
4854                self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
4855            )?,
4856            committed: Vec::new(),
4857            last_h: None,
4858            next_pred: None,
4859            sctr: 0,
4860            uctr: 0,
4861            draft_ctx: None,
4862            pending_tok: None,
4863            turn_ckpt: None,
4864            telem: SpecTelemetryCounters::default(),
4865        })
4866    }
4867
4868    /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
4869    /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
4870    /// snapshot, or draft-KV row that only corrupts the following round.
4871    pub fn optipipe_compare_session_state(
4872        &self,
4873        e: &Engine,
4874        reference: &SpecSession,
4875        candidate: &SpecSession,
4876    ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
4877        fn fail(what: &str) -> Box<dyn std::error::Error> {
4878            format!("optipipe state mismatch: {what}").into()
4879        }
4880        fn same_f32(a: &[f32], b: &[f32]) -> bool {
4881            a.len() == b.len()
4882                && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
4883        }
4884        fn compare_layers(
4885            es: &Engine,
4886            range: std::ops::Range<usize>,
4887            reference: &SpecSession,
4888            candidate: &SpecSession,
4889            report: &mut OptiForkStateIdentity,
4890        ) -> Result<(), Box<dyn std::error::Error>> {
4891            for il in range {
4892                match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
4893                    (Some(a), Some(b)) => {
4894                        if a.len != b.len {
4895                            return Err(fail(&format!("layer {il} host KV len {} != {}", a.len, b.len)));
4896                        }
4897                        let ad = es.dtoh_i32(&a.len_d)?;
4898                        let bd = es.dtoh_i32(&b.len_d)?;
4899                        if ad != bd || ad.first().copied() != Some(a.len as i32) {
4900                            return Err(fail(&format!(
4901                                "layer {il} device KV len {ad:?} != {bd:?} (host={})",
4902                                a.len,
4903                            )));
4904                        }
4905                        let kb = a.len * a.k_tok_bytes;
4906                        let vb = a.len * a.v_tok_bytes;
4907                        if kb > 0 {
4908                            let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
4909                            let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
4910                            if ak != bk {
4911                                let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
4912                                return Err(fail(&format!(
4913                                    "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
4914                                    at / a.k_tok_bytes,
4915                                    at % a.k_tok_bytes,
4916                                    ak[at],
4917                                    bk[at],
4918                                )));
4919                            }
4920                        }
4921                        if vb > 0 {
4922                            let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
4923                            let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
4924                            if av != bv {
4925                                let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
4926                                return Err(fail(&format!(
4927                                    "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
4928                                    at / a.v_tok_bytes,
4929                                    at % a.v_tok_bytes,
4930                                    av[at],
4931                                    bv[at],
4932                                )));
4933                            }
4934                        }
4935                        report.trunk_kv_bytes += kb + vb;
4936                    }
4937                    (None, None) => {}
4938                    _ => return Err(fail(&format!("layer {il} KV presence"))),
4939                }
4940                match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
4941                    (Some(a), Some(b)) => {
4942                        let ac = es.dtoh(&a.conv_state)?;
4943                        let bc = es.dtoh(&b.conv_state)?;
4944                        if !same_f32(&ac, &bc) {
4945                            return Err(fail(&format!("layer {il} conv state")));
4946                        }
4947                        let as_ = es.dtoh(&a.ssm_state)?;
4948                        let bs = es.dtoh(&b.ssm_state)?;
4949                        if !same_f32(&as_, &bs) {
4950                            return Err(fail(&format!("layer {il} SSM state")));
4951                        }
4952                        report.recurrent_bytes += (ac.len() + as_.len()) * 4;
4953                    }
4954                    (None, None) => {}
4955                    _ => return Err(fail(&format!("layer {il} recurrent presence"))),
4956                }
4957            }
4958            Ok(())
4959        }
4960
4961        if reference.committed != candidate.committed {
4962            return Err(fail("committed token ids"));
4963        }
4964        if reference.cache.pos != candidate.cache.pos
4965            || reference.cache.max_ctx != candidate.cache.max_ctx
4966        {
4967            return Err(fail("cache pos/capacity"));
4968        }
4969        if reference.pending_tok != candidate.pending_tok
4970            || reference.next_pred != candidate.next_pred
4971            || reference.sctr != candidate.sctr
4972            || reference.uctr != candidate.uctr
4973        {
4974            return Err(fail("pending/prediction/counter tail"));
4975        }
4976
4977        let mut report = OptiForkStateIdentity::default();
4978        if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
4979            let rt = crate::pp::PpNRt::get(e)?;
4980            for stage in 0..rt.n_stages() {
4981                let _scope = rt.enter(stage);
4982                compare_layers(
4983                    rt.engine(stage, e),
4984                    fence[stage]..fence[stage + 1],
4985                    reference,
4986                    candidate,
4987                    &mut report,
4988                )?;
4989            }
4990        } else {
4991            compare_layers(
4992                e,
4993                0..self.layers.len(),
4994                reference,
4995                candidate,
4996                &mut report,
4997            )?;
4998        }
4999
5000        let (a, b) = (&reference.scratch.kv, &candidate.scratch.kv);
5001        if a.len != b.len || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)? {
5002            return Err(fail("draft scratch length"));
5003        }
5004        let kb = a.len * a.k_tok_bytes;
5005        let vb = a.len * a.v_tok_bytes;
5006        if kb > 0
5007            && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))?
5008        {
5009            return Err(fail("draft scratch K bytes"));
5010        }
5011        if vb > 0
5012            && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))?
5013        {
5014            return Err(fail("draft scratch V bytes"));
5015        }
5016        report.scratch_kv_bytes = kb + vb;
5017
5018        match (&reference.last_h, &candidate.last_h) {
5019            (Some(a), Some(b)) => {
5020                let ah = e.dtoh(a)?;
5021                let bh = e.dtoh(b)?;
5022                if !same_f32(&ah, &bh) {
5023                    return Err(fail("last hidden/seed bytes"));
5024                }
5025                report.hidden_bytes = ah.len() * 4;
5026            }
5027            (None, None) => {}
5028            _ => return Err(fail("last hidden/seed presence")),
5029        }
5030        Ok(report)
5031    }
5032
5033    /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
5034    /// retained prompt-end checkpoint, so a request whose prompt matches
5035    /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
5036    ///
5037    /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
5038    /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
5039    /// restored from the device copy taken there, draft scratch length reset, `committed`
5040    /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
5041    /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
5042    /// every burst after it are identical to a cold run of the same token stream — the
5043    /// committed-tokens-authoritative contract.
5044    ///
5045    /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
5046    /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
5047    /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
5048    /// continue). The persistent draft graph survives: it bakes only session-stable pointers
5049    /// (the scratch KV, the resident embedding), none of which the rewind moves.
5050    ///
5051    /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
5052    /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
5053    /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
5054    pub fn spec_rewind_to_checkpoint(
5055        &self,
5056        e: &Engine,
5057        sess: &mut SpecSession,
5058    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
5059        if sess
5060            .turn_ckpt
5061            .as_ref()
5062            .is_some_and(|ckpt| {
5063                !sess.cache.can_rollback(&ckpt.snap, 0)
5064                    || !sess.scratch.can_rewind_to(ckpt.pos)
5065            })
5066        {
5067            return Err("SWA ring rewind checkpoint has been lapped; full re-prime required".into());
5068        }
5069        let Some(ckpt) = sess.turn_ckpt.take() else {
5070            return Ok(None);
5071        };
5072        assert!(
5073            ckpt.pos <= sess.committed.len(),
5074            "checkpoint past committed ({} > {})",
5075            ckpt.pos,
5076            sess.committed.len()
5077        );
5078        // Restore through each layer's owning engine. A single primary-engine rollback is not
5079        // sufficient when the serving cache is stage-owned under cross-device PP.
5080        crate::pp::restore_cache_checkpoint(e, &self.cfg, None, &mut sess.cache, &ckpt.snap)?;
5081        debug_assert_eq!(sess.cache.pos, ckpt.pos, "rollback landed off the checkpoint");
5082        sess.scratch.set_len(e, ckpt.pos)?;
5083        sess.committed.truncate(ckpt.pos);
5084        sess.last_h = Some(ckpt.last_h);
5085        sess.next_pred = None;
5086        sess.pending_tok = None;
5087        Ok(Some(ckpt.pos))
5088    }
5089
5090    /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
5091    /// checkpoint without re-priming the checkpoint prefix.
5092    ///
5093    /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
5094    /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
5095    /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
5096    /// remain authoritative, so they are copied into a fresh larger scratch before its length is
5097    /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
5098    ///
5099    /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
5100    /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
5101    pub fn spec_grow_and_rewind_to_checkpoint(
5102        &self,
5103        e: &Engine,
5104        sess: &mut SpecSession,
5105        target_cap: usize,
5106    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
5107        if target_cap <= sess.cache.max_ctx {
5108            return self.spec_rewind_to_checkpoint(e, sess);
5109        }
5110        let Some(ckpt) = sess.turn_ckpt.as_ref() else {
5111            return Ok(None);
5112        };
5113        if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
5114            return Err(format!(
5115                "checkpoint pos {} outside committed length {}",
5116                ckpt.pos,
5117                sess.committed.len(),
5118            )
5119            .into());
5120        }
5121        if ckpt.pos > target_cap {
5122            return Err(format!(
5123                "checkpoint pos {} exceeds grown capacity {target_cap}",
5124                ckpt.pos,
5125            )
5126            .into());
5127        }
5128
5129        let mut grown_cache = crate::pp::new_cache(e, &self.cfg, target_cap)?;
5130        let mut grown_scratch = MtpScratch::new(
5131            e,
5132            &self.cfg,
5133            target_cap,
5134            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5135        )?;
5136        crate::pp::restore_cache_checkpoint(
5137            e,
5138            &self.cfg,
5139            Some(&sess.cache),
5140            &mut grown_cache,
5141            &ckpt.snap,
5142        )?;
5143
5144        let src = &sess.scratch.kv;
5145        let dst = &mut grown_scratch.kv;
5146        if ckpt.pos > src.len
5147            || src.kv_dim_k != dst.kv_dim_k
5148            || src.kv_dim_v != dst.kv_dim_v
5149            || src.k_tok_bytes != dst.k_tok_bytes
5150            || src.v_tok_bytes != dst.v_tok_bytes
5151        {
5152            return Err(format!(
5153                "checkpoint draft layout mismatch (pos {}, source len {})",
5154                ckpt.pos, src.len,
5155            )
5156            .into());
5157        }
5158        let kb = ckpt.pos * src.k_tok_bytes;
5159        let vb = ckpt.pos * src.v_tok_bytes;
5160        if kb > 0 {
5161            e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
5162        }
5163        if vb > 0 {
5164            e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
5165        }
5166        grown_scratch.set_len(e, ckpt.pos)?;
5167        // The old scratch is dropped immediately after publication below. Bound its D2D reads
5168        // first; growth happens once per rewritten turn, outside the decode hot loop.
5169        e.stream().synchronize()?;
5170
5171        let ckpt = sess
5172            .turn_ckpt
5173            .take()
5174            .expect("checkpoint remained present through transactional grow");
5175        let pos = ckpt.pos;
5176        sess.cache = grown_cache;
5177        sess.scratch = grown_scratch;
5178        sess.committed.truncate(pos);
5179        sess.last_h = Some(ckpt.last_h);
5180        sess.next_pred = None;
5181        sess.pending_tok = None;
5182        sess.draft_ctx = None;
5183        debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
5184        debug_assert_eq!(sess.scratch.kv.len, pos, "grown draft rewind landed off checkpoint");
5185        Ok(Some(pos))
5186    }
5187
5188    /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
5189    /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
5190    /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
5191    /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
5192    pub fn spec_flush_pending(
5193        &self,
5194        e: &Engine,
5195        sess: &mut SpecSession,
5196    ) -> Result<(), Box<dyn std::error::Error>> {
5197        let Some(b) = sess.pending_tok.take() else {
5198            return Ok(());
5199        };
5200        let mtp = self.mtp.as_ref().expect("pending carry requires an MTP head");
5201        let n_embd = self.cfg.n_embd as usize;
5202        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
5203        let embd_gpu = if spec_host_embd() {
5204            None
5205        } else {
5206            Some(
5207                self.embd_gpu
5208                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
5209            )
5210        };
5211        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
5212        let pos_b = sess.cache.pos;
5213        sess.scratch.set_len(e, pos_b)?;
5214        let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
5215        sess.next_pred = Some(argmax(&lg_b) as u32);
5216        let anchor = sess
5217            .last_h
5218            .as_ref()
5219            .expect("pending carry requires last_h (the predecessor-row anchor)");
5220        self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
5221        sess.last_h = Some(hb);
5222        sess.committed.push(b);
5223        Ok(())
5224    }
5225
5226    /// Solo target feed used only at speculative round boundaries. Step35 serving made its
5227    /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
5228    /// rounds through that same graph. Other model families keep their eager T=1 contract.
5229    fn spec_target_step_h(
5230        &self,
5231        e: &Engine,
5232        token: u32,
5233        cache: &mut Cache,
5234    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5235        if self.cfg.step35.is_none() {
5236            return self.decode_step_h(e, token, cache);
5237        }
5238        let pos0 = cache.pos;
5239        let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
5240        Ok((e.dtoh(&logits)?, hidden))
5241    }
5242
5243    /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
5244    /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
5245    /// session already exist.
5246    pub fn spec_pipe_available(&self, e: &Engine) -> bool {
5247        if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
5248            || !spec_devacc()
5249            || std::env::var("MEMRA_SPEC_REPLAY").is_ok()
5250            || spec_stream()
5251            || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
5252            || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
5253            || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
5254            || std::env::var("MEMRA_SPEC_PMIN")
5255                .ok()
5256                .and_then(|v| v.parse::<f32>().ok())
5257                .unwrap_or(0.0) > 0.0
5258            || self.is_gemma4_e4b()
5259            || self.cfg.gemma4.is_some()
5260            || self.mtp.is_none()
5261        {
5262            return false;
5263        }
5264        let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
5265            return false;
5266        };
5267        if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
5268            return false;
5269        }
5270        crate::pp::PpNRt::get(e)
5271            .map(|rt| rt.n_stages() == 2 && rt.cross_device())
5272            .unwrap_or(false)
5273    }
5274
5275    /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
5276    /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
5277    /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
5278    #[allow(clippy::too_many_arguments)]
5279    pub fn generate_spec_session_pair(
5280        &self,
5281        e: &Engine,
5282        sess_a: &mut SpecSession,
5283        max_new_a: usize,
5284        k_a: usize,
5285        sess_b: &mut SpecSession,
5286        max_new_b: usize,
5287        k_b: usize,
5288    ) -> Result<
5289        ((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)),
5290        Box<dyn std::error::Error>,
5291    > {
5292        if !self.spec_pipe_available(e) {
5293            return Err("two-session speculative pipeline is outside its reduced matrix".into());
5294        }
5295        if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
5296            return Err("two-session speculative pipeline requires non-empty positive-K bursts".into());
5297        }
5298        for sess in [&*sess_a, &*sess_b] {
5299            if sess.committed.is_empty()
5300                || sess.last_h.is_none()
5301                || (sess.next_pred.is_none() && sess.pending_tok.is_none())
5302            {
5303                return Err("two-session speculative pipeline requires warm continuations".into());
5304            }
5305        }
5306
5307        let mtp_dense = self
5308            .mtp
5309            .as_ref()
5310            .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
5311            .unwrap_or(false);
5312        let trunk_dense = self
5313            .layers
5314            .iter()
5315            .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
5316        let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
5317            && !spec_host_embd()
5318            && mtp_dense
5319            && trunk_dense
5320            && !crate::model::full_prec_enabled();
5321        let graph_a = graph_ok && k_a + 2 < 96;
5322        let graph_b = graph_ok && k_b + 2 < 96;
5323        let was_tracking = e.ctx().is_event_tracking();
5324        if (graph_a || graph_b) && was_tracking {
5325            unsafe {
5326                e.ctx().disable_event_tracking();
5327            }
5328        }
5329
5330        static LOGGED: std::sync::Once = std::sync::Once::new();
5331        LOGGED.call_once(|| {
5332            eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
5333        });
5334        let sync = std::sync::Arc::new(SpecPipeSync::new());
5335        let lane_a = SpecPipeLane { sync: sync.clone(), lane: 0 };
5336        let lane_b = SpecPipeLane { sync, lane: 1 };
5337        let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
5338        let (result_a, result_b) = std::thread::scope(|scope| {
5339            let b = scope.spawn(move || {
5340                let mut finish = SpecPipeFinish::new(&lane_b);
5341                let sess_b = unsafe { sess_b_ptr.get_mut() };
5342                let result = e
5343                    .ctx()
5344                    .bind_to_thread()
5345                    .map_err(|err| err.to_string())
5346                    .and_then(|_| {
5347                        self.generate_spec_inner2(
5348                            e,
5349                            &[],
5350                            max_new_b,
5351                            k_b,
5352                            graph_b,
5353                            Some(sess_b),
5354                            None,
5355                            None,
5356                            None,
5357                            None,
5358                            Some(&lane_b),
5359                        )
5360                        .map_err(|err| err.to_string())
5361                    });
5362                finish.close(result.is_err());
5363                result
5364            });
5365            let mut finish = SpecPipeFinish::new(&lane_a);
5366            let result_a = self.generate_spec_inner2(
5367                e,
5368                &[],
5369                max_new_a,
5370                k_a,
5371                graph_a,
5372                Some(sess_a),
5373                None,
5374                None,
5375                None,
5376                None,
5377                Some(&lane_a),
5378            );
5379            finish.close(result_a.is_err());
5380            let result_b = b
5381                .join()
5382                .map_err(|_| "paired speculative session B panicked".to_string())
5383                .and_then(|r| r);
5384            (result_a, result_b)
5385        });
5386
5387        if (graph_a || graph_b) && was_tracking {
5388            unsafe {
5389                e.ctx().enable_event_tracking();
5390            }
5391        }
5392        let result_a = result_a?;
5393        let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
5394        Ok((result_a, result_b))
5395    }
5396
5397    /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
5398    /// message rendered through the chat template continuation). Returns (new tokens emitted,
5399    /// drafted, accepted); session.committed grows by suffix + emitted.
5400    pub fn generate_spec_session(
5401        &self,
5402        e: &Engine,
5403        sess: &mut SpecSession,
5404        suffix: &[u32],
5405        max_new: usize,
5406        k: usize,
5407    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
5408        self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
5409    }
5410
5411    /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
5412    /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
5413    /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
5414    /// for the filtered target (feat/filtered-spec).
5415    ///
5416    /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
5417    /// output — once right after the prime's first token, then once per round commit — so a
5418    /// streaming caller can flush text at round cadence instead of once per burst. The slices
5419    /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
5420    /// timing only: token bytes, session state, and exactness are untouched.
5421    ///
5422    /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
5423    /// the burst at the current round boundary, exactly as if `max_new` had been reached —
5424    /// the caller's scheduler regains control without waiting the burst out. Burst size is
5425    /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
5426    /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
5427    /// drains and the defensive tail flush can land with nothing new committed).
5428    #[allow(clippy::too_many_arguments)]
5429    pub fn generate_spec_session_sampled(
5430        &self,
5431        e: &Engine,
5432        sess: &mut SpecSession,
5433        suffix: &[u32],
5434        max_new: usize,
5435        k: usize,
5436        sampling: Option<SpecSampling>,
5437        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
5438    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
5439        self.generate_spec_session_sampled_prime_split(
5440            e, sess, suffix, max_new, k, sampling, None, on_commit,
5441        )
5442    }
5443
5444    /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
5445    /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
5446    /// pass `None` and stay on the existing zero-prime path.
5447    #[allow(clippy::too_many_arguments)]
5448    pub fn generate_spec_session_sampled_prime_split(
5449        &self,
5450        e: &Engine,
5451        sess: &mut SpecSession,
5452        suffix: &[u32],
5453        max_new: usize,
5454        k: usize,
5455        sampling: Option<SpecSampling>,
5456        prime_split: Option<usize>,
5457        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
5458    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
5459        self.generate_spec_session_constrained_prime_split(
5460            e, sess, suffix, max_new, k, sampling, None, prime_split, on_commit,
5461        )
5462    }
5463
5464    /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
5465    /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
5466    /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
5467    /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
5468    /// column — token-identical to constrained plain greedy decode. GREEDY only (the
5469    /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
5470    /// may drop (drafter is unconstrained); that is measured, not hidden.
5471    #[allow(clippy::too_many_arguments)]
5472    pub fn generate_spec_session_constrained(
5473        &self,
5474        e: &Engine,
5475        sess: &mut SpecSession,
5476        suffix: &[u32],
5477        max_new: usize,
5478        k: usize,
5479        sampling: Option<SpecSampling>,
5480        constraint: Option<&mut dyn SpecConstraint>,
5481        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
5482    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
5483        self.generate_spec_session_constrained_prime_split(
5484            e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
5485        )
5486    }
5487
5488    #[allow(clippy::too_many_arguments)]
5489    pub fn generate_spec_session_constrained_prime_split(
5490        &self,
5491        e: &Engine,
5492        sess: &mut SpecSession,
5493        suffix: &[u32],
5494        max_new: usize,
5495        k: usize,
5496        sampling: Option<SpecSampling>,
5497        constraint: Option<&mut dyn SpecConstraint>,
5498        prime_split: Option<usize>,
5499        on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
5500    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
5501        if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
5502            return Err("constrained spec decode is greedy-only (worker routes sampled \
5503                        constrained to plain decode)".into());
5504        }
5505        // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
5506        // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
5507        // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
5508        // serve continuation case — consume the carry in-loop with zero solo passes.
5509        if sess.pending_tok.is_some()
5510            && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
5511        {
5512            self.spec_flush_pending(e, sess)?;
5513        }
5514        let mtp_dense = self
5515            .mtp
5516            .as_ref()
5517            .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
5518            .unwrap_or(false);
5519        let trunk_dense = self
5520            .layers
5521            .iter()
5522            .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
5523        // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
5524        // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
5525        // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
5526        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
5527            && !spec_host_embd()
5528            && mtp_dense
5529            && trunk_dense
5530            && k + 2 < 96
5531            && !crate::model::full_prec_enabled();
5532        let was_tracking = e.ctx().is_event_tracking();
5533        if graph_draft && was_tracking {
5534            unsafe {
5535                e.ctx().disable_event_tracking();
5536            }
5537        }
5538        let r = self.generate_spec_inner2(
5539            e, suffix, max_new, k, graph_draft, Some(sess), sampling, constraint, on_commit,
5540            prime_split, None,
5541        );
5542        if graph_draft && was_tracking {
5543            unsafe {
5544                e.ctx().enable_event_tracking();
5545            }
5546        }
5547        let (out, d, a) = r?;
5548        Ok((out, d, a))
5549    }
5550
5551    pub fn generate_spec(
5552        &self,
5553        e: &Engine,
5554        prompt: &[u32],
5555        max_new: usize,
5556        k: usize,
5557    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
5558        let mtp_dense = self
5559            .mtp
5560            .as_ref()
5561            .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
5562            .unwrap_or(false);
5563        let trunk_dense = self
5564            .layers
5565            .iter()
5566            .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
5567        // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
5568        // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
5569        let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
5570            && !spec_host_embd()
5571            && mtp_dense
5572            && trunk_dense
5573            && k + 2 < 96
5574            && !crate::model::full_prec_enabled();
5575        if !graph_draft {
5576            return self.generate_spec_inner2(
5577                e, prompt, max_new, k, false, None, None, None, None, None, None,
5578            );
5579        }
5580        let was_tracking = e.ctx().is_event_tracking();
5581        if was_tracking {
5582            unsafe {
5583                e.ctx().disable_event_tracking();
5584            }
5585        }
5586        let r = self.generate_spec_inner2(
5587            e, prompt, max_new, k, true, None, None, None, None, None, None,
5588        );
5589        if was_tracking {
5590            unsafe {
5591                e.ctx().enable_event_tracking();
5592            }
5593        }
5594        r
5595    }
5596
5597    fn generate_spec_inner2(
5598        &self,
5599        e: &Engine,
5600        prompt: &[u32],
5601        max_new: usize,
5602        k: usize,
5603        graph_draft: bool,
5604        mut sess: Option<&mut SpecSession>,
5605        sampling: Option<SpecSampling>,
5606        mut constraint: Option<&mut dyn SpecConstraint>,
5607        mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
5608        prime_split: Option<usize>,
5609        pipe: Option<&SpecPipeLane>,
5610    ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
5611        assert!(k >= 1, "k must be >= 1");
5612        if let Some(p) = pipe {
5613            p.setup_begin()?;
5614        }
5615        // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
5616        let mut flushed = 0usize;
5617        // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
5618        // at the next round boundary (same exit as max_new reached — the session tail runs).
5619        // Initialized by the unconditional post-prime flush below.
5620        let mut keep_going;
5621        let mtp = self
5622            .mtp
5623            .as_ref()
5624            .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
5625        let n_vocab = self.output.out_features();
5626        // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
5627        // over the draft vocab and the winning index maps through d2t to a TARGET token id.
5628        // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
5629        let d_vocab = mtp
5630            .shared_head_head
5631            .as_ref()
5632            .unwrap_or(&self.output)
5633            .out_features();
5634        let n_embd = self.cfg.n_embd as usize;
5635        // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
5636        // already committed (their state is in the caches); 0 = fresh single-shot call.
5637        let session_mode = sess.is_some();
5638        let max_ctx = match sess.as_ref() {
5639            Some(s) => s.cache.max_ctx,
5640            None => prompt.len() + max_new + k + 8,
5641        };
5642        let mut own_cache;
5643        let mut own_scratch;
5644        let (
5645            cache,
5646            scratch,
5647            mut sess_tail,
5648            mut sess_draft_slot,
5649            mut sess_pending_slot,
5650            sess_ckpt_slot,
5651            sess_telem,
5652        ): (
5653            &mut Cache,
5654            &mut MtpScratch,
5655            Option<(
5656                &mut Vec<u32>,
5657                &mut Option<CudaSlice<f32>>,
5658                &mut Option<u32>,
5659                &mut u32,
5660                &mut u32,
5661            )>,
5662            Option<&mut Option<DraftGraphCtx>>,
5663            Option<&mut Option<u32>>,
5664            Option<&mut Option<SpecCheckpoint>>,
5665            Option<&SpecTelemetryCounters>,
5666        ) = match sess.take() {
5667            Some(sr) => {
5668                let SpecSession {
5669                    cache,
5670                    scratch,
5671                    committed,
5672                    last_h,
5673                    next_pred,
5674                    sctr: s_sctr,
5675                    uctr: s_uctr,
5676                    draft_ctx,
5677                    pending_tok,
5678                    turn_ckpt,
5679                    telem,
5680                } = sr;
5681                (
5682                    cache,
5683                    scratch,
5684                    Some((committed, last_h, next_pred, s_sctr, s_uctr)),
5685                    Some(draft_ctx),
5686                    Some(pending_tok),
5687                    Some(turn_ckpt),
5688                    Some(telem),
5689                )
5690            }
5691            None => {
5692                // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
5693                // `Cache::new` verbatim.
5694                own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
5695                // Persistent scratch = max_ctx rows (~2KB/token quantized).
5696                own_scratch = MtpScratch::new(
5697                    e,
5698                    &self.cfg,
5699                    max_ctx,
5700                    self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5701                )?;
5702                (&mut own_cache, &mut own_scratch, None, None, None, None, None)
5703            }
5704        };
5705        let base = cache.pos;
5706        // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
5707        // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
5708        // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
5709        // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
5710        let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
5711        // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
5712        // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
5713        // acceptance-only — exactness is verify's job either way).
5714        // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
5715        // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
5716        // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
5717        // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
5718        // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
5719        // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
5720        // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
5721        // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
5722        // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
5723        // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
5724        // per round on top of the acceptance win). Draft-quality-only: exactness stays the
5725        // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
5726        // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
5727        // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
5728        // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
5729        // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
5730        // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
5731        // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
5732        // + fallback seam).
5733        let spec_replay = std::env::var("MEMRA_SPEC_REPLAY").is_ok();
5734        if constraint.is_some() && spec_replay {
5735            return Err("constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
5736                        (legacy replay commits an unmasked bonus)".into());
5737        }
5738        // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
5739        // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
5740        // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
5741        let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
5742
5743        // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
5744        // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
5745        // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
5746        // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
5747        // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
5748        // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
5749        // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
5750        // generation exactly where the last turn stopped — no prime at all. The stashed
5751        // `next_pred` plays prime_logits' argmax role (it IS the argmax of the logits after
5752        // committed.last()); `last_h` seeds the predecessor pairing below. Fresh calls and
5753        // non-empty suffixes take the normal path.
5754        let continuation = prompt.is_empty();
5755        if continuation {
5756            assert!(session_mode, "empty prompt requires a session");
5757            assert!(
5758                sess_tail
5759                    .as_ref()
5760                    .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
5761                        && lh.is_some()
5762                        && (np.is_some() || carried_pending.is_some())),
5763                "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
5764            );
5765        }
5766        let mut prime_logits;
5767        let mut prompt_h: Option<CudaSlice<f32>> = None;
5768        let t_prime = std::time::Instant::now();
5769        let batched_prime = !continuation
5770            && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
5771            && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
5772            && !e.frozen_cpu_experts_prefer_tokenwise_prime();
5773        let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
5774        if prime_split.is_some() && (continuation || base != 0) {
5775            return Err("spec prime split is cold-session-only".into());
5776        }
5777        if continuation {
5778            prime_logits = Vec::new();
5779        } else if let Some(split) = prime_split {
5780            if split < crate::hybrid_forward::PRIME_MIN_T {
5781                return Err(format!(
5782                    "spec prime split {split} is below PRIME_MIN_T {}",
5783                    crate::hybrid_forward::PRIME_MIN_T,
5784                ).into());
5785            }
5786            // Mirror the plain worker's affinity boundary exactly. The prefix is a request-level
5787            // prime (`queued_after` keeps Step35 arm selection independent of this stop); a tail
5788            // below PRIME_MIN_T then takes the same eager tokenwise continuation as prefill_tick.
5789            // Retain every hidden row so the draft scratch fill remains one coherent prompt.
5790            let mut h_all = e.uninit(prompt.len() * n_embd)?;
5791            let (l, _, h_prefix) =
5792                self.prime_cache(e, &prompt[..split], &mut *cache, prompt.len() - split)?;
5793            e.copy_into(&mut h_all, 0, &h_prefix, split * n_embd)?;
5794            prime_logits = l;
5795            let tail = &prompt[split..];
5796            if tail.len() >= crate::hybrid_forward::PRIME_MIN_T
5797                && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
5798                && !e.frozen_cpu_experts_prefer_tokenwise_prime()
5799            {
5800                let (l, _, h_tail) = self.prime_cache(e, tail, &mut *cache, 0)?;
5801                e.copy_into(&mut h_all, split * n_embd, &h_tail, tail.len() * n_embd)?;
5802                prime_logits = l;
5803            } else {
5804                for (i, &tok) in tail.iter().enumerate() {
5805                    let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
5806                    e.copy_into(&mut h_all, (split + i) * n_embd, &h, n_embd)?;
5807                    prime_logits = l;
5808                }
5809            }
5810            if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
5811                eprintln!("[spec-prime] affinity split={split} tail={}", tail.len());
5812            }
5813            prompt_h = Some(h_all);
5814        } else if batched_prime {
5815            let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
5816            prime_logits = l;
5817            prompt_h = Some(hiddens);
5818        } else {
5819            prime_logits = Vec::new();
5820            prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
5821            for (i, &tok) in prompt.iter().enumerate() {
5822                let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
5823                if let Some(ph) = prompt_h.as_mut() {
5824                    e.copy_into(ph, i * n_embd, &h, n_embd)?;
5825                }
5826                prime_logits = l;
5827            }
5828        }
5829        e.stream().synchronize()?;
5830        // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
5831        // prime-subtraction hack.
5832        crate::PRIME_NANOS.store(
5833            t_prime.elapsed().as_nanos() as u64,
5834            std::sync::atomic::Ordering::Relaxed,
5835        );
5836
5837        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
5838        // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
5839        // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
5840        let host_embd = spec_host_embd();
5841        let embd_gpu = if host_embd {
5842            None
5843        } else {
5844            Some(
5845                self.embd_gpu
5846                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
5847            )
5848        };
5849        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
5850        if host_embd {
5851            eprintln!(
5852                "[spec] host-row embedding: {} bytes kept off HBM",
5853                self.embd.raw.len()
5854            );
5855        }
5856        let mut out: Vec<u32> = Vec::with_capacity(max_new);
5857        let mut total_drafted = 0usize;
5858        let mut total_accepted = 0usize;
5859
5860        // First generated token = argmax of the prompt's last logits (== greedy's first token).
5861        // Emit it, then FEED it to establish the loop invariant below.
5862        // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
5863        // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
5864        // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
5865        // prompt's last logits (plain constrained-greedy identity); a continuation without
5866        // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
5867        // worker never resumes constrained sessions from the pool, so this cannot fire).
5868        if let Some(c) = constraint.as_deref_mut() {
5869            if continuation && carried_pending.is_none() {
5870                return Err("constrained spec continuation requires a carried pending \
5871                            (pool resume is unconstrained-only)".into());
5872            }
5873            if !continuation {
5874                c.mask_logits(&mut prime_logits)
5875                    .map_err(|e2| format!("constraint: {e2}"))?;
5876            }
5877        }
5878        let mut last_token = if let Some(b) = carried_pending {
5879            b
5880        } else if continuation {
5881            sess_tail.as_ref().unwrap().2.unwrap()
5882        } else {
5883            argmax(&prime_logits) as u32
5884        };
5885        if carried_pending.is_none() {
5886            out.push(last_token);
5887            // grammar advances with every emitted token (carried pendings were consumed
5888            // by the burst that emitted them).
5889            if let Some(c) = constraint.as_deref_mut() {
5890                c.consume(last_token).map_err(|e2| format!("constraint: {e2}"))?;
5891            }
5892        }
5893        if continuation {
5894            // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
5895            // overhang so the chain's first append lands at slot base (== committed.len()).
5896            scratch.set_len(e, base)?;
5897        }
5898        // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
5899        // concatenating to the full `out`). Called after the prime's first token and after each
5900        // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
5901        // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
5902        // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
5903        fn flush_commit(
5904            cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
5905            out: &[u32],
5906            flushed: &mut usize,
5907        ) -> bool {
5908            if let Some(f) = cb.as_mut() {
5909                let keep = f(&out[*flushed..]);
5910                *flushed = out.len();
5911                keep
5912            } else {
5913                true
5914            }
5915        }
5916        keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
5917        // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
5918        // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
5919        // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
5920        // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
5921        // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
5922        // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
5923        // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
5924        // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
5925        // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
5926        // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
5927        let sp = sampling.unwrap_or_else(|| SpecSampling {
5928            temp: std::env::var("MEMRA_SPEC_TEMP")
5929                .ok()
5930                .and_then(|v| v.parse().ok())
5931                .unwrap_or(0.0),
5932            seed: std::env::var("MEMRA_SEED")
5933                .ok()
5934                .and_then(|v| v.parse().ok())
5935                .unwrap_or(42),
5936            top_k: std::env::var("MEMRA_TOP_K")
5937                .ok()
5938                .and_then(|v| v.parse().ok())
5939                .unwrap_or(0),
5940            top_p: std::env::var("MEMRA_TOP_P")
5941                .ok()
5942                .and_then(|v| v.parse().ok())
5943                .unwrap_or(1.0),
5944            min_p: std::env::var("MEMRA_MIN_P")
5945                .ok()
5946                .and_then(|v| v.parse().ok())
5947                .unwrap_or(0.0),
5948            penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
5949                .ok()
5950                .and_then(|v| v.parse().ok())
5951                .unwrap_or(0),
5952            penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
5953                .ok()
5954                .and_then(|v| v.parse().ok())
5955                .unwrap_or(1.0),
5956            penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
5957                .ok()
5958                .and_then(|v| v.parse().ok())
5959                .unwrap_or(0.0),
5960            penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
5961                .ok()
5962                .and_then(|v| v.parse().ok())
5963                .unwrap_or(0.0),
5964        });
5965        let (sp_temp, sp_seed) = (sp.temp, sp.seed);
5966        let sampled = sp_temp > 0.0;
5967        // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
5968        // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
5969        // those, so their residual mass is p(x), correct by construction).
5970        let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
5971            match &mtp.d2t {
5972                Some(map) => Some(e.htod_u32_v(map)?),
5973                None => None,
5974            }
5975        } else {
5976            None
5977        };
5978        let mut q_full_buf: Option<CudaSlice<f32>> = None;
5979        // Counters resume from the session (burst continuity: randomness must never repeat
5980        // across generate_spec_session calls); one-shot callers start at (0,0). Read through
5981        // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
5982        let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
5983        let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
5984        // host Philox4x32-10 (mirrors spec_sample.cu; independent stream via ctr_lo tag)
5985        let host_u01 = |seed: u64, ctr: u32| -> f32 {
5986            let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
5987            let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
5988            let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
5989            for _ in 0..10 {
5990                let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
5991                let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
5992                let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
5993                c0 = n0;
5994                c1 = n1;
5995                c2 = n2;
5996                c3 = n3;
5997                k0 = k0.wrapping_add(0x9E3779B9);
5998                k1 = k1.wrapping_add(0xBB67AE85);
5999            }
6000            (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
6001        };
6002        let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
6003        let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
6004        let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
6005        let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
6006        let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
6007                                                        // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
6008                                                        // for the penalized+filtered target). History = generated tokens, host-tracked window.
6009        let pen_on = sampled
6010            && sp.penalty_last_n > 0
6011            && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
6012        let mut pen_hist: Vec<u32> = if pen_on {
6013            prompt.iter().rev().take(64).rev().cloned().collect() // llama-parity: history spans prompt tail too
6014        } else {
6015            Vec::new()
6016        };
6017        let mut pen_hist_d: Option<CudaSlice<u32>> = None;
6018        let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
6019        // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
6020        // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
6021        // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
6022        let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
6023        let t_ent = std::time::Instant::now();
6024
6025        // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
6026        // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
6027        // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
6028        // the one that matters (a history-rewriting client mutates what the session GENERATED,
6029        // so the next turn's prompt agrees with this one up to exactly here).
6030        //
6031        // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
6032        // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
6033        // hold exactly `base + prompt.len()` rows and nothing generated.
6034        //
6035        // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
6036        // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
6037        // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
6038        // `<think>` block the client strips, so every later turn's diff diverged exactly one
6039        // token below the checkpoint and affinity declined 100% of the time. Measured on the
6040        // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
6041        // whole mechanism inert while looking, from the outside, like a working
6042        // correctness-declines-safely path — hence the decline log carries the offsets.
6043        //
6044        // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
6045        // state (the reason a spec session could not rewind before). The draft scratch needs no
6046        // copy: rows below the boundary are rewritten by the next turn's own fill.
6047        //
6048        // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
6049        // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
6050        // checkpoint rather than replacing it with a strictly worse one.
6051        //
6052        // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
6053        // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
6054        // fail the burst that is already running — so the error is swallowed, loud only under
6055        // MEMRA_DEBUG_SPEC.
6056        if let Some(slot) = sess_ckpt_slot {
6057            if !continuation {
6058                let pos = cache.pos;
6059                debug_assert_eq!(
6060                    pos,
6061                    base + prompt.len(),
6062                    "turn checkpoint must sit at the prompt end, before the init feed"
6063                );
6064                let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
6065                    if let Some(ph) = &prompt_h {
6066                        // hidden of the LAST primed row = the predecessor anchor at this
6067                        // boundary (exactly what a fresh prime of committed[..pos] leaves in
6068                        // last_h, and what the next prime's fill reads for its first row).
6069                        let np = prompt.len();
6070                        e.uninit(n_embd).and_then(|mut a| {
6071                            e.copy_view_into(
6072                                &mut a,
6073                                0,
6074                                &ph.slice((np - 1) * n_embd..np * n_embd),
6075                                n_embd,
6076                            )?;
6077                            Ok(a)
6078                        })
6079                    } else {
6080                        Err("no prompt hiddens".into())
6081                    };
6082                match (cache.snapshot(e), anchor) {
6083                    (Ok(snap), Ok(last_h)) => {
6084                        *slot = Some(SpecCheckpoint { snap, pos, last_h });
6085                    }
6086                    (s, a) => {
6087                        *slot = None; // a stale checkpoint would rewind to the WRONG boundary
6088                        if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
6089                            let err = s.err().map(|e| e.to_string())
6090                                .or_else(|| a.err().map(|e| e.to_string()))
6091                                .unwrap_or_default();
6092                            eprintln!("[spec] turn checkpoint skipped ({err}); \
6093                                       next turn re-primes in full");
6094                        }
6095                    }
6096                }
6097            }
6098        }
6099        // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
6100        // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
6101        // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
6102        // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
6103        let mut last_pred = 0u32;
6104        let mut last_col_logits: Option<CudaSlice<f32>> = None;
6105        // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
6106        // recompute in the grammar-truncation walk — retained host-side, round 0 only.
6107        let mut init_logits_host: Option<Vec<f32>> = None;
6108        let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
6109            let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
6110            last_pred = argmax(&init_logits) as u32;
6111            if constraint.is_some() {
6112                init_logits_host = Some(init_logits.clone());
6113            }
6114            // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
6115            if sampled {
6116                last_col_logits = Some(e.htod(&init_logits)?);
6117            }
6118            h
6119        } else {
6120            // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
6121            let lh = sess_tail
6122                .as_ref()
6123                .unwrap()
6124                .1
6125                .as_ref()
6126                .expect("pending carry requires last_h");
6127            e.clone_dtod(lh)?
6128        };
6129        let t_init = t_ent.elapsed();
6130        let mut last_col_stats: Option<(f32, f32, f32)> = None;
6131        // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
6132        // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
6133        // stable pointer for the graph-draft round-start copy.
6134        let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
6135        // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
6136        // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
6137        // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
6138        // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
6139        // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
6140        // overwritten below).
6141        let mut fill_prev = e.clone_dtod(&h_seed0)?;
6142        {
6143            if let Some(ph) = &prompt_h {
6144                let np = prompt.len();
6145                e.copy_view_into(
6146                    &mut h_seed_buf,
6147                    0,
6148                    &ph.slice((np - 1) * n_embd..np * n_embd),
6149                    n_embd,
6150                )?;
6151            } else if continuation {
6152                if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
6153                    if let Some(lh) = lh.as_ref() {
6154                        e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
6155                    }
6156                }
6157            }
6158        }
6159        // Persistent device prediction slots for the accept walk (max k+1 verify columns).
6160        let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
6161
6162        let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
6163        let fork_mode = OptiForkGateMode::configured();
6164        // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
6165        // the end. Metric normalization vs the reference engine: BOTH engines count
6166        // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
6167        // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
6168        let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
6169        let mut st_drafted = vec![0usize; k];
6170        let mut st_accepted = vec![0usize; k];
6171        let mut st_len_hist = vec![0usize; k + 1];
6172        let mut st_full = 0usize;
6173        // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
6174        // stop the draft chain early when the head's softmax confidence in its own pick drops
6175        // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
6176        static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
6177        let p_min = *PMIN.get_or_init(|| {
6178            std::env::var("MEMRA_SPEC_PMIN")
6179                .ok()
6180                .and_then(|v| v.parse().ok())
6181                .unwrap_or(0.0)
6182        });
6183        // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
6184        // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
6185        // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
6186        // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
6187        // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
6188        // verify batch is not); the j==0 exemption stays for pending-less rounds.
6189        let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
6190            .map(|v| v == "1")
6191            .unwrap_or(false);
6192
6193        // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
6194        // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
6195        // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
6196        // cuBLAS path in an exotic head) falls back to the eager draft chain.
6197        // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
6198        // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
6199        // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
6200        // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
6201        // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
6202        // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
6203        // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
6204        // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
6205        let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
6206            Some(c) => c,
6207            None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
6208        };
6209        // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
6210        // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
6211        if sampled && dctx.g_q.len() < d_vocab {
6212            dctx.g_q = e.zeros(d_vocab)?;
6213            dctx.g_perturb = e.zeros(d_vocab)?;
6214        }
6215        // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
6216        // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
6217        // truncation (the correctness backstop) stops cutting every tight-schema round.
6218        // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
6219        // shape, so a parked graph of the other shape is dropped and recaptured.
6220        let dmask_on = constraint.as_deref().is_some_and(|c| c.draft_mask_enabled());
6221        let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
6222        if dmask_on && dctx.g_dmask.len() < dmask_words {
6223            dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
6224            dctx.graph = None; // the old capture baked the old (or no) mask pointer
6225            dctx.failed.clear_greedy();
6226            dctx.keeper.clear();
6227        }
6228        if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
6229            dctx.graph = None;
6230            dctx.failed.clear_greedy();
6231            dctx.keeper.clear();
6232        }
6233        if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
6234            let DraftGraphCtx { g_tok, g_pos, g_seed, g_p, g_dmask, .. } = &mut dctx;
6235            // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
6236            // host uploads the position's real words, so the warmups stay grammar-free.
6237            if dmask_on {
6238                e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
6239            }
6240            let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
6241            // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
6242            // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
6243            // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
6244            // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
6245            // passes (and, in serve, other sessions) recycle those addresses and the replay then
6246            // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
6247            let cap_res = e.capture_graph_retained(|e| {
6248                self.mtp_head_forward_cap(
6249                    e,
6250                    mtp,
6251                    g_tok,
6252                    g_pos,
6253                    g_seed,
6254                    g_p,
6255                    &mut *scratch,
6256                    p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
6257                    true,
6258                    embd_gpu.expect("graph draft requires resident embedding"),
6259                    embd_qt,
6260                    embd_rb,
6261                    d_vocab,
6262                    None,
6263                    None,
6264                    if dmask_on { Some((g_dmask_ro, dmask_words)) } else { None },
6265                )
6266            });
6267            match cap_res {
6268                Ok((g, keep)) => {
6269                    scratch.set_len(e, base)?;
6270                    dctx.graph = Some(g);
6271                    dctx.graph_masked = dmask_on;
6272                    dctx.keeper = keep;
6273                }
6274                Err(err) => {
6275                    scratch.set_len(e, base)?;
6276                    // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
6277                    // silent. Once per flip — mark returns None on an already-failed ctx.
6278                    if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
6279                        eprintln!("{line}");
6280                    }
6281                }
6282            }
6283        }
6284        // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
6285        // graph object, built only when sampled && graph-eligible — the greedy capture above is
6286        // untouched (and skipped when sampled: its graph would never be launched). Same head
6287        // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
6288        // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
6289        // once per round); the raw head logits land in the persistent g_q for the host's
6290        // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
6291        // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
6292        // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
6293        // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
6294        // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
6295        // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
6296        // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
6297        // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
6298        // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
6299        // this compare misses at most ONCE per resumed request — the first burst recaptures
6300        // and every later burst in that request replays. A client that wants the parked graph
6301        // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
6302        // stable across its whole conversation.
6303        // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
6304        // softmax — it can hold neither per-row filter stats nor the varying penalty history.
6305        // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
6306        // force the eager draft (which computes stats/penalties per row).
6307        let pure_temp = sp.top_k == 0 && sp.top_p >= 1.0 && sp.min_p <= 0.0 && !pen_on;
6308        let s_key = (sp_seed, sp_temp.to_bits(), k);
6309        if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
6310            dctx.graph_s = None;
6311            dctx.failed.clear_sampled();
6312            dctx.s_key = None;
6313            dctx.q_slots.clear();
6314            dctx.keeper_s.clear();
6315        }
6316        if graph_draft && sampled && pure_temp && dctx.graph_s.is_none()
6317            && !dctx.failed.sampled_failed()
6318        {
6319            let DraftGraphCtx { g_tok, g_pos, g_seed, g_p, g_ctr, g_perturb, g_q, .. } = &mut dctx;
6320            // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
6321            let cap_res = e.capture_graph_retained(|e| {
6322                self.mtp_head_forward_cap(
6323                    e,
6324                    mtp,
6325                    g_tok,
6326                    g_pos,
6327                    g_seed,
6328                    g_p,
6329                    &mut *scratch,
6330                    p_min > 0.0,
6331                    true,
6332                    embd_gpu.expect("graph draft requires resident embedding"),
6333                    embd_qt,
6334                    embd_rb,
6335                    d_vocab,
6336                    Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
6337                    None,
6338                    None, // constrained spec is greedy-only — sampled never carries a hook
6339                )
6340            });
6341            match cap_res {
6342                Ok((g, keep)) => {
6343                    scratch.set_len(e, base)?;
6344                    for _ in 0..k {
6345                        dctx.q_slots.push(e.zeros(d_vocab)?);
6346                    }
6347                    dctx.graph_s = Some(g);
6348                    dctx.s_key = Some(s_key);
6349                    dctx.keeper_s = keep;
6350                }
6351                Err(err) => {
6352                    scratch.set_len(e, base)?;
6353                    // LOUD flip (audit Q2): same contract as the greedy capture above.
6354                    if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
6355                        eprintln!("{line}");
6356                    }
6357                }
6358            }
6359        }
6360        let t_cap = t_ent.elapsed();
6361        // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
6362        // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
6363        // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
6364        // fill: the first chain step processes it and appends its entry at slot prompt.len().
6365        if let Some(ph) = &prompt_h {
6366            // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
6367            // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
6368            // global positions [base..base+tp). Fresh call: base==0, identical to before.
6369            scratch.set_len(e, base)?;
6370            // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
6371            // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
6372            // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
6373            // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
6374            let tp = prompt.len();
6375            let fill_chunk: usize = if crate::cache::swa_ring_on() {
6376                crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
6377            } else {
6378                // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
6379                // meaning one monolithic fill.
6380                std::env::var("MEMRA_PRIME_CHUNK")
6381                    .ok()
6382                    .and_then(|v| v.parse().ok())
6383                    .unwrap_or(4096)
6384            };
6385            let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
6386            let mut start = 0usize;
6387            while start < tp {
6388                let end = (start + fill_chunk).min(tp);
6389                let tc = end - start;
6390                {
6391                    // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
6392                    // reference engine's initial pending-h is zeroed too); a session turn's row 0
6393                    // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
6394                    // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
6395                    let mut phs = e.zeros(tc * n_embd)?;
6396                    let (src_lo, dst_off) = if start == 0 {
6397                        (0, n_embd)
6398                    } else {
6399                        ((start - 1) * n_embd, 0)
6400                    };
6401                    let n_copy = if start == 0 {
6402                        (tc - 1) * n_embd
6403                    } else {
6404                        tc * n_embd
6405                    };
6406                    if start == 0 {
6407                        if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
6408                            if let Some(lh) = lh.as_ref() {
6409                                e.copy_into(&mut phs, 0, lh, n_embd)?;
6410                            }
6411                        }
6412                    }
6413                    if n_copy > 0 {
6414                        e.copy_view_into(
6415                            &mut phs,
6416                            dst_off,
6417                            &ph.slice(src_lo..src_lo + n_copy),
6418                            n_copy,
6419                        )?;
6420                    }
6421                    self.mtp_kv_fill(
6422                        e,
6423                        mtp,
6424                        &prompt[start..end],
6425                        &phs,
6426                        base + start,
6427                        &mut *scratch,
6428                        embd_dev,
6429                    )?;
6430                }
6431                start = end;
6432            }
6433        }
6434        // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
6435        // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
6436        // (=1 brackets the whole call in run_spec.rs, prime included.)
6437        if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
6438            unsafe extern "C" {
6439                fn cudaProfilerStart() -> i32;
6440            }
6441            unsafe {
6442                cudaProfilerStart();
6443            }
6444        }
6445        // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
6446        // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
6447        // consume each other's device outputs; the host drains the ring every M rounds. v1
6448        // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
6449        // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
6450        // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
6451        // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
6452        // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
6453        let stream_on = crate::spec::spec_stream()
6454            && !sampled
6455            && !spec_replay
6456            && constraint.is_none()
6457            && !session_mode
6458            && embd_gpu.is_some()
6459            && !crate::model::full_prec_enabled()
6460            && k + 2 < 96;
6461        let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
6462        let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
6463        if stream_on {
6464            let cap = e.capture_graph(|e| {
6465                for j in 0..k.max(1) {
6466                    self.mtp_head_forward_cap(
6467                        e,
6468                        mtp,
6469                        &mut dctx.g_tok,
6470                        &mut dctx.g_pos,
6471                        &mut dctx.g_seed,
6472                        &mut dctx.g_p,
6473                        &mut *scratch,
6474                        true,
6475                        true,
6476                        embd_gpu.expect("round stream requires resident embedding"),
6477                        embd_qt,
6478                        embd_rb,
6479                        d_vocab,
6480                        None,
6481                        Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
6482                        None, // round-stream requires constraint.is_none() (see stream_on)
6483                    )?;
6484                }
6485                Ok(())
6486            });
6487            match cap {
6488                Ok(g) => {
6489                    scratch.set_len(e, 0)?;
6490                    stream_graph = Some(g);
6491                }
6492                Err(err) => {
6493                    scratch.set_len(e, 0)?;
6494                    if debug_spec {
6495                        eprintln!("[spec] stream-graph capture failed ({err}); stream off");
6496                    }
6497                }
6498            }
6499        }
6500        let stream_active = stream_on && stream_graph.is_some();
6501        if debug_spec {
6502            eprintln!("[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
6503                      crate::spec::spec_stream(), dctx.graph.is_some(), stream_graph.is_some());
6504        }
6505        let t_v_s = k + 1;
6506        // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
6507        // module (extracted 2026-07-12; the gemma burst reuses them).
6508        let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
6509        let crate::round_stream::StreamBufs {
6510            mut vtok_d,
6511            mut brk_d,
6512            mut pend_d,
6513            last_pred_d,
6514            mut pos_ctr,
6515            mut pos_start_d,
6516            mut ring_d,
6517            acc_d: mut stream_acc,
6518            m_rounds,
6519            k: _,
6520        } = sb;
6521        let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
6522            Some(crate::round_stream::kv_len_ptr_table(
6523                e,
6524                cache,
6525                Some(&pos_ctr),
6526            )?)
6527        } else {
6528            None
6529        };
6530
6531        let t_fill = t_ent.elapsed();
6532        let mut round = 0usize;
6533        // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
6534        // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
6535        // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
6536        // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
6537        // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
6538        // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
6539        // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
6540        // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
6541        // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
6542        // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
6543        // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
6544        // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
6545        // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
6546        // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
6547        // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
6548        // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
6549        // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
6550        // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
6551        // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
6552        // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
6553        // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
6554        // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
6555        // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
6556        // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
6557        // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
6558        // K=1..8 self-consistency PASS both models with the law ON (exactness held).
6559        let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
6560        // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
6561        // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
6562        let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
6563            .ok()
6564            .and_then(|v| v.parse().ok());
6565        let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
6566            4
6567        } else if self.cfg.n_embd as usize >= 2500 {
6568            2
6569        } else {
6570            1
6571        };
6572        let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
6573        // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
6574        // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
6575        // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
6576        let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
6577            .ok()
6578            .and_then(|v| v.parse().ok())
6579            .unwrap_or(1024);
6580        let floor_at = |pos: usize| -> usize {
6581            if adapt_floor_env.is_some() || pos < floor_ctx {
6582                adapt_floor
6583            } else if adapt_floor >= 4 {
6584                1
6585            } else {
6586                adapt_floor
6587            }
6588        };
6589        // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
6590        // fixed-K default path is untouched by this whole block.
6591        let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
6592            .ok()
6593            .and_then(|v| v.parse().ok())
6594            .unwrap_or(7);
6595        let k_cap = k.min(cap_max).max(1);
6596        let mut kc = k_cap;
6597        let mut opti_fork: Option<OptiForkState> = None;
6598        let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
6599        if fork_mode != OptiForkGateMode::Disabled {
6600            let fence = crate::pp::pp_cuts(self.layers.len());
6601            let refusal = if !session_mode {
6602                Some("not-session")
6603            } else if k != 1 || adapt {
6604                Some("requires-fixed-k1")
6605            } else if sampled || constraint.is_some() || spec_replay {
6606                Some("sampled-constrained-or-replay")
6607            } else if pipe.is_some() {
6608                Some("two-session-pipeline")
6609            } else if !spec_devacc() {
6610                Some("requires-device-accept")
6611            } else if stream_active || crate::spec::spec_stream() {
6612                Some("round-stream")
6613            } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
6614                Some("swa-ring")
6615            } else if crate::pp::pp_host_bounce_active() {
6616                Some("host-bounce")
6617            } else if fork_mode == OptiForkGateMode::Controller
6618                && cache.recur.iter().any(Option::is_some)
6619            {
6620                Some("controller-requires-zero-recurrent-state")
6621            } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
6622                Some("requires-pp2")
6623            } else {
6624                None
6625            };
6626            if let Some(reason) = refusal {
6627                OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6628                eprintln!("[opti-fork] refused reason={reason}");
6629            } else {
6630                let fence = fence.expect("validated PP-2 fence");
6631                let rt = crate::pp::PpNRt::get(e)?;
6632                let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
6633                let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
6634                let primary_supported = primary_stage0
6635                    || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
6636                if !rt.cross_device() || !primary_supported {
6637                    OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6638                    eprintln!(
6639                        "[opti-fork] refused reason=requires-supported-primary-cross-device"
6640                    );
6641                } else {
6642                    // Both recurrent snapshots and both seed generations are allocated before
6643                    // the first fork, each through its owning PP stage. Allocation failure
6644                    // therefore happens before any optimistic state mutation can occur.
6645                    let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
6646                    let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
6647                    let fork = OptiForkState::new(
6648                        e,
6649                        cache,
6650                        fork_mode,
6651                        alternate_snapshot,
6652                        &h_seed_buf,
6653                        &fill_prev,
6654                        rt,
6655                        fence[1],
6656                        self.layers.len(),
6657                    )?;
6658                    eprintln!(
6659                        "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
6660                         payload_dev0={} payload_dev1={} q_threshold={:.3}",
6661                        fence[1],
6662                        fork.logical_payload_bytes[0],
6663                        fork.logical_payload_bytes[1],
6664                        fork.controller.map_or(0.0, |policy| policy.threshold),
6665                    );
6666                    fork_snapshot = Some(current_snapshot);
6667                    opti_fork = Some(fork);
6668                }
6669            }
6670        }
6671        // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
6672        // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
6673        let mut snap = match fork_snapshot {
6674            Some(snapshot) => snapshot,
6675            None => cache.snapshot(e)?,
6676        };
6677        let mut carried_opti: Option<OptiControllerTicket> = None;
6678        // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
6679        // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
6680        let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
6681            Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
6682        } else {
6683            None
6684        };
6685        // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
6686        // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
6687        // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
6688        // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
6689        // pass of any kind). Verify still
6690        // checks every emitted token against the target -> exactness holds by construction; only
6691        // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
6692        // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
6693        // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
6694        let mut pending: Option<u32> = carried_pending;
6695                                             // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
6696                                             // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
6697                                             // the verify accept readback). Printed once at loop end via spec-stats.
6698        let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
6699        let phase_on = anatomy_on
6700            || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
6701        // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
6702        // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
6703        let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
6704        // grammar-truncation counters: how many rounds the verify-side cut fired and how many
6705        // already-verified tokens it threw away. THIS is the quantity draft masking targets.
6706        let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
6707        let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
6708        let mut ph_wait = 0f64;
6709        let mut ph_commit = 0f64;
6710        let mut ph_t = std::time::Instant::now();
6711        let mut ph_mark = |acc: &mut f64, on: bool| {
6712            if on {
6713                let now = std::time::Instant::now();
6714                *acc += (now - ph_t).as_secs_f64();
6715                ph_t = now;
6716            }
6717        };
6718        if let Some(p) = pipe {
6719            p.setup_end();
6720        }
6721        while keep_going && out.len() < max_new {
6722            // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
6723            // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
6724            if let (true, Some(sg), Some(ptrs)) = (
6725                stream_active && round >= 1 && pending.is_some(),
6726                &stream_graph,
6727                &stream_ptrs,
6728            ) {
6729                if debug_spec {
6730                    static ONCE: std::sync::Once = std::sync::Once::new();
6731                    ONCE.call_once(|| {
6732                        eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
6733                    });
6734                }
6735                e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
6736                e.set_u32_one(&mut pend_d, pending.unwrap())?;
6737                e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
6738                for _mi in 0..m_rounds {
6739                    e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
6740                    cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
6741                    e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
6742                    e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
6743                    e.u32_copy(&pend_d, &mut dctx.g_tok)?;
6744                    e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
6745                    sg.launch()?;
6746                    e.spec_assemble_verify(
6747                        &g_tokp2k,
6748                        &pend_d,
6749                        d2t_dev.as_ref(),
6750                        &mut vtok_d,
6751                        &mut brk_d,
6752                        p_min,
6753                        k,
6754                        pmin0,
6755                    )?;
6756                    let mut ck = VerifyCkpt::new(self.layers.len());
6757                    let dummy = vec![0u32; t_v_s];
6758                    let (tl_d, vx) = self.decode_step_t_core_stream(
6759                        e,
6760                        &dummy,
6761                        0,
6762                        &mut *cache,
6763                        embd_dev,
6764                        Some(&mut ck),
6765                        Some((&vtok_d, &pos_ctr)),
6766                        None,
6767                    )?;
6768                    for j in 0..t_v_s {
6769                        e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
6770                    }
6771                    e.spec_accept_greedy_dc(
6772                        &preds_d,
6773                        &vtok_d,
6774                        &last_pred_d,
6775                        &brk_d,
6776                        &mut stream_acc,
6777                    )?;
6778                    e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
6779                    e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
6780                    self.commit_verified_prefix_stream(
6781                        e,
6782                        &mut *cache,
6783                        &snap,
6784                        &ck,
6785                        &stream_acc,
6786                        1,
6787                        t_v_s,
6788                    )?;
6789                    e.spec_rollback_stream(
6790                        ptrs,
6791                        &pos_start_d,
6792                        &stream_acc,
6793                        1,
6794                        self.layers.len() + 1,
6795                    )?;
6796                    e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
6797                }
6798                e.stream().synchronize()?;
6799                let ring_h = e.dtoh_u32(&ring_d)?;
6800                let cnt = ring_h[0] as usize;
6801                for i in 0..cnt {
6802                    if out.len() < max_new {
6803                        out.push(ring_h[1 + i]);
6804                    }
6805                }
6806                let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
6807                for il in 0..self.layers.len() {
6808                    if let Some(kvl) = cache.kv[il].as_mut() {
6809                        kvl.len = pos_h;
6810                    }
6811                }
6812                cache.pos = pos_h;
6813                scratch.kv.len = pos_h;
6814                pending = Some(ring_h[cnt]); // last drained token = the live bonus
6815                last_token = ring_h[cnt];
6816                total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
6817                total_accepted += cnt.saturating_sub(m_rounds);
6818                if let Some(t) = sess_telem {
6819                    // totals only — the burst's per-round accept counts stayed on device
6820                    // (that is the point of the round-stream arm). pos_* untouched.
6821                    t.record_totals(
6822                        m_rounds,
6823                        k * m_rounds,
6824                        cnt.saturating_sub(m_rounds),
6825                    );
6826                }
6827                round += m_rounds;
6828                // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
6829                keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
6830                continue;
6831            }
6832            let pipe_draft = match pipe {
6833                Some(p) => Some(p.draft_begin(round)?),
6834                None => None,
6835            };
6836            let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
6837            let mut current_opti = carried_opti.take();
6838            let mut fork_generation = if current_opti.is_none() && pending.is_some() {
6839                match opti_fork.as_mut() {
6840                    Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
6841                    None => None,
6842                    Some(_) => None,
6843                }
6844            } else {
6845                None
6846            };
6847            if current_opti.is_none() {
6848                if let Some(fork) = opti_fork.as_ref() {
6849                    opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
6850                } else {
6851                    cache.snapshot_into(e, &mut snap)?;
6852                }
6853            } else if snap.pos != pos {
6854                return Err(format!(
6855                    "optipipe carried snapshot pos {} != current pos {pos}", snap.pos
6856                )
6857                .into());
6858            } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
6859            ph_mark(&mut ph_rest, phase_on);
6860
6861            // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
6862            // p-min semantics (both paths): stop the chain early when the head's confidence in
6863            // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
6864            // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
6865            let base0 = if pending.is_some() { 1usize } else { 0usize };
6866            // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
6867            // accepted run + 1 (the gemma law — see the setup block above the loop).
6868            let k_this = if adapt { kc } else { k };
6869            let mut draft: Vec<u32> = Vec::with_capacity(k);
6870            let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
6871            let mut controller_draft_prob: Option<f32> = None;
6872            let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
6873            if let Some(ticket) = current_opti.as_mut() {
6874                let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
6875                if ticket.verify_tokens[0] != carried_pending {
6876                    return Err(format!(
6877                        "optipipe carried pending mismatch: ticket={} live={carried_pending}",
6878                        ticket.verify_tokens[0],
6879                    )
6880                    .into());
6881                }
6882                draft.push(ticket.verify_tokens[1]);
6883                controller_draft_prob = Some(ticket.draft_prob);
6884                controller_eager_state = ticket
6885                    .take_eager_seed()
6886                    .map(|seed| (ticket.verify_tokens[1], seed));
6887            } else {
6888            // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
6889            // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
6890            // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
6891            // rejected drafts and p-min extras via the len mechanism).
6892            scratch.set_len(e, pos + base0 - 1)?;
6893            if pen_on {
6894                let w0 = pen_hist.len().saturating_sub(sp.penalty_last_n);
6895                pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
6896            }
6897            if sampled {
6898                draft_logits.clear();
6899                draft_stats.clear();
6900            }
6901            // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
6902            // position's mask is computed on that clone and advanced by the PROPOSED token. The
6903            // real state moves only on emission (verify's job), so the emitted stream is
6904            // unchanged — the mask only removes tokens the verify would have truncated anyway.
6905            let mut dmask_live = dmask_on;
6906            if dmask_live {
6907                let t_c = std::time::Instant::now();
6908                constraint
6909                    .as_deref_mut()
6910                    .unwrap()
6911                    .draft_begin()
6912                    .map_err(|e2| format!("constraint: {e2}"))?;
6913                dm_clone_ns += t_c.elapsed().as_nanos();
6914                dm_rounds += 1;
6915            }
6916            if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
6917                // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
6918                // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
6919                // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
6920                e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
6921                e.set_u32_one(&mut dctx.g_tok, last_token)?;
6922                e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
6923                for j in 0..k_this {
6924                    // per-position mask upload (contents only — the graph's baked pointer is
6925                    // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
6926                    // mask node degrades to a no-op ban instead of needing a second graph.
6927                    if dmask_live
6928                        && !upload_draft_mask(
6929                            e,
6930                            constraint.as_deref_mut().unwrap(),
6931                            &mut dctx.g_dmask,
6932                            mtp.d2t.as_ref(),
6933                            d_vocab,
6934                            dmask_words,
6935                        )?
6936                    {
6937                        // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
6938                        // genuinely miss the legal set): neutralize the captured mask node and
6939                        // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
6940                        e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
6941                        dmask_live = false;
6942                    }
6943                    gr.launch()?;
6944                    scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
6945                    let idx = e.dtoh_u32_one(&dctx.g_tok)?;
6946                    // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
6947                    // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
6948                    // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
6949                    // replay's embed node, and the MMU fault kills the CUDA context for the
6950                    // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
6951                    // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
6952                    // buffer (g_seed = the verify-side handoff vs head-side compute).
6953                    if (idx as usize) >= d_vocab {
6954                        // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
6955                        // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
6956                        // seed, untouched since the round-start copy — the pair discriminates
6957                        // "seed arrived poisoned" from "head forward produced NaN".
6958                        let seed_h = e.dtoh(&dctx.g_seed)?;
6959                        let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
6960                        let in_h = e.dtoh(&h_seed_buf)?;
6961                        let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
6962                        return Err(format!(
6963                            "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
6964                             round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
6965                             round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
6966                             the embed row (#87 trap)"
6967                        )
6968                        .into());
6969                    }
6970                    // trimmed draft vocab -> target token id (identity when no d2t map)
6971                    let d = match &mtp.d2t {
6972                        Some(map) => map[idx as usize],
6973                        None => idx,
6974                    };
6975                    let draft_p = if p_min > 0.0
6976                        || opti_fork.as_ref().is_some_and(|fork| fork.controller.is_some())
6977                    {
6978                        Some(e.dtoh(&dctx.g_p)?[0])
6979                    } else {
6980                        None
6981                    };
6982                    if j == 0 {
6983                        controller_draft_prob = draft_p;
6984                    }
6985                    if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
6986                        if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
6987                            break;
6988                        }
6989                    }
6990                    draft.push(d);
6991                    // with a trimmed head the NEXT embed must read the TARGET id, not the draft
6992                    // index the argmax wrote — patch the persistent token buffer (4B htod).
6993                    if d != idx {
6994                        e.set_u32_one(&mut dctx.g_tok, d)?;
6995                    }
6996                    // advance the SPECULATIVE state with the proposal; a dead chain drops to
6997                    // unmasked drafting for the remaining positions (verify still arbitrates).
6998                    // speculative advance; a chain the grammar can no longer follow (EOS
6999                    // proposed) ends here. The captured mask node always runs, so a dead chain
7000                    // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
7001                    if dmask_live
7002                        && !constraint
7003                            .as_deref_mut()
7004                            .unwrap()
7005                            .draft_advance(d)
7006                            .map_err(|e2| format!("constraint: {e2}"))?
7007                    {
7008                        e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
7009                        break;
7010                    }
7011                }
7012            } else if let (true, Some(gr)) = (sampled, &dctx.graph_s) {
7013                // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
7014                // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
7015                // and decides the break. Event-counter continuity: g_ctr is host-seeded to
7016                // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
7017                // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
7018                // stream. Host sctr advances in lockstep (computed, no readback needed).
7019                e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
7020                e.set_u32_one(&mut dctx.g_tok, last_token)?;
7021                e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
7022                e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
7023                for j in 0..k_this {
7024                    gr.launch()?;
7025                    scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
7026                    sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
7027                               // counts the p-min-discarded token too)
7028                               // q retention: ONE async D2D of the persistent head-logits buffer into this
7029                               // round's slot j (stream-ordered after the replay, before the next one).
7030                    e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
7031                    let idx = e.dtoh_u32_one(&dctx.g_tok)?;
7032                    // #87 SENTINEL TRAP (see the greedy graph arm above).
7033                    if (idx as usize) >= d_vocab {
7034                        let seed_h = e.dtoh(&dctx.g_seed)?;
7035                        let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
7036                        return Err(format!(
7037                            "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
7038                             {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
7039                             {seed_nan}/{n_embd} — refusing to dereference the embed row \
7040                             (#87 trap)"
7041                        )
7042                        .into());
7043                    }
7044                    let d = match &mtp.d2t {
7045                        Some(map) => map[idx as usize],
7046                        None => idx,
7047                    };
7048                    draft_idx.push(idx);
7049                    if p_min > 0.0 {
7050                        let p = e.dtoh(&dctx.g_p)?[0];
7051                        if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
7052                            break;
7053                        }
7054                    }
7055                    draft.push(d);
7056                    // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
7057                    if d != idx {
7058                        e.set_u32_one(&mut dctx.g_tok, d)?;
7059                    }
7060                }
7061                // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
7062                // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
7063                for j in 0..draft.len().max(draft_idx.len()) {
7064                    let rows0 = e.htod_i32(&[0])?;
7065                    let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
7066                    e.filter_stats(
7067                        &dctx.q_slots[j],
7068                        d_vocab,
7069                        &rows0,
7070                        &mut th_d,
7071                        &mut z_d,
7072                        &mut mx_d,
7073                        d_vocab,
7074                        1,
7075                        sp_temp,
7076                        sp.top_k,
7077                        sp.top_p,
7078                        sp.min_p,
7079                    )?;
7080                    draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
7081                }
7082            } else {
7083                // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
7084                let mut e_tok = last_token;
7085                let mut d_seed = e.clone_dtod(&h_seed_buf)?;
7086                for j in 0..k_this {
7087                    // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
7088                    // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
7089                    let mtp_pos = pos + base0 + j;
7090                    // draft-side grammar mask (eager twin of the graph arm's in-graph node).
7091                    // A position with no legal draft-vocab row drops to unmasked drafting for
7092                    // the rest of the chain (pre-lane behaviour; verify still arbitrates).
7093                    if dmask_live {
7094                        dmask_live = upload_draft_mask(
7095                            e,
7096                            constraint.as_deref_mut().unwrap(),
7097                            &mut dctx.g_dmask,
7098                            mtp.d2t.as_ref(),
7099                            d_vocab,
7100                            dmask_words,
7101                        )?;
7102                    }
7103                    let (dl_d, h_nextn) = self.mtp_head_forward_dev(
7104                        e,
7105                        mtp,
7106                        e_tok,
7107                        &d_seed,
7108                        &mut *scratch,
7109                        mtp_pos,
7110                        embd_dev,
7111                        if dmask_live { Some((&dctx.g_dmask, dmask_words)) } else { None },
7112                    )?;
7113                    let tok_d = if sampled {
7114                        // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
7115                        // the filtered softmax (filters off => th=0, exact v1 semantics).
7116                        if perturb_buf.is_none() {
7117                            perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
7118                        }
7119                        let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
7120                        if pen_on {
7121                            let h = pen_hist_d.as_ref().unwrap();
7122                            let nh = h.len();
7123                            e.penalize_logits(
7124                                &mut q_row,
7125                                h,
7126                                nh,
7127                                sp.penalty_repeat,
7128                                sp.penalty_freq,
7129                                sp.penalty_present,
7130                                d_vocab,
7131                            )?;
7132                        }
7133                        let rows0 = e.htod_i32(&[0])?;
7134                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
7135                        e.filter_stats(
7136                            &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab, 1,
7137                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
7138                        )?;
7139                        let (th, z, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
7140                        let pb = perturb_buf.as_mut().unwrap();
7141                        e.gumbel_perturb_filtered(
7142                            &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
7143                        )?;
7144                        sctr += 1;
7145                        draft_logits.push(q_row);
7146                        draft_stats.push((mx, th, z));
7147                        e.argmax_token_device(pb, d_vocab)?
7148                    } else {
7149                        e.argmax_token_device(&dl_d, d_vocab)?
7150                    };
7151                    let idx = e.dtoh_u32_one(&tok_d)?;
7152                    // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
7153                    // here because the eager chain's operands are all readable: dl_d (the head
7154                    // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
7155                    if (idx as usize) >= d_vocab {
7156                        let dl_h = e.dtoh(&dl_d)?;
7157                        let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
7158                        let seed_h = e.dtoh(&d_seed)?;
7159                        let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
7160                        return Err(format!(
7161                            "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
7162                             round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
7163                             step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
7164                             embed row (#87 trap)"
7165                        )
7166                        .into());
7167                    }
7168                    let d = match &mtp.d2t {
7169                        Some(map) => map[idx as usize],
7170                        None => idx,
7171                    };
7172                    if sampled {
7173                        draft_idx.push(idx);
7174                    }
7175                    let draft_p = if p_min > 0.0
7176                        || opti_fork.as_ref().is_some_and(|fork| fork.controller.is_some())
7177                    {
7178                        let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
7179                        Some(e.dtoh(&p_d)?[0])
7180                    } else {
7181                        None
7182                    };
7183                    if j == 0 {
7184                        controller_draft_prob = draft_p;
7185                    }
7186                    if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
7187                        if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
7188                            break;
7189                        }
7190                    }
7191                    draft.push(d);
7192                    e_tok = d;
7193                    d_seed = h_nextn;
7194                    // speculative advance; a chain the grammar can no longer follow (EOS
7195                    // proposed) ends here — the prefix already proposed still rides verify.
7196                    if dmask_live
7197                        && !constraint
7198                            .as_deref_mut()
7199                            .unwrap()
7200                            .draft_advance(d)
7201                            .map_err(|e2| format!("constraint: {e2}"))?
7202                    {
7203                        break;
7204                    }
7205                }
7206                if opti_fork.as_ref().is_some_and(|fork| fork.controller.is_some()) {
7207                    controller_eager_state = Some((e_tok, d_seed));
7208                }
7209            }
7210            }
7211            let k_round = draft.len();
7212            if let Some(p) = pipe {
7213                p.draft_end(round);
7214            }
7215            drop(pipe_draft);
7216
7217            ph_mark(&mut ph_draft, phase_on);
7218            // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
7219            //         (committing its KV/recur inside the SAME weight read); drafts follow. ---
7220            let verify_tokens: Vec<u32> = match pending {
7221                Some(b) => {
7222                    let mut v = Vec::with_capacity(k_round + 1);
7223                    v.push(b);
7224                    v.extend_from_slice(&draft);
7225                    v
7226                }
7227                None => draft.clone(),
7228            };
7229            let base = if pending.is_some() { 1 } else { 0 };
7230            // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
7231            // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
7232            let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
7233                Some(ticket.take_ckpt())
7234            } else if spec_replay {
7235                None
7236            } else {
7237                Some(VerifyCkpt::new(self.layers.len()))
7238            };
7239            let controller_can_probe = base == 1
7240                && k_round == 1
7241                && out.len().saturating_add(2) < max_new
7242                && controller_draft_prob.is_some()
7243                && opti_fork
7244                    .as_ref()
7245                    .and_then(|fork| fork.controller.as_ref())
7246                    .is_some_and(|policy| !policy.breaker_tripped);
7247            let mut successor_attempt: Option<OptiControllerTicket> = None;
7248            let mut rejected_probe: Option<(f32, u32)> = None;
7249            let mut controller_prepared: Option<OptiControllerPrepared> = None;
7250            if controller_can_probe {
7251                // Prepare d2/q and, on admission, d3 before either current verify half is
7252                // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
7253                // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
7254                // the primary stream after N stage 1 would serialize the supposed pipeline.
7255                let eager_pos = scratch.kv.len + 1;
7256                let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
7257                    e,
7258                    mtp,
7259                    &mut dctx,
7260                    &mut *scratch,
7261                    d_vocab,
7262                    &mut controller_eager_state,
7263                    eager_pos,
7264                    embd_dev,
7265                )?;
7266                let first_probability = controller_draft_prob
7267                    .ok_or("optipipe controller probe lost first-token probability")?;
7268                let q_proxy = first_probability * pending_probability;
7269                OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7270                OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7271                let admitted = opti_fork
7272                    .as_ref()
7273                    .and_then(|fork| fork.controller.as_ref())
7274                    .ok_or("optipipe controller policy disappeared")?
7275                    .admit(q_proxy);
7276                if admitted {
7277                    OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7278                    let eager_pos = scratch.kv.len + 1;
7279                    let (optimistic_draft, optimistic_draft_probability) =
7280                        self.opti_controller_draft_step(
7281                            e,
7282                            mtp,
7283                            &mut dctx,
7284                            &mut *scratch,
7285                            d_vocab,
7286                            &mut controller_eager_state,
7287                            eager_pos,
7288                            embd_dev,
7289                        )?;
7290                    OPTI_SHADOW_DRAFT_TOKENS
7291                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7292                    let eager_seed = controller_eager_state.take().map(|(token, seed)| {
7293                        debug_assert_eq!(token, optimistic_draft);
7294                        seed
7295                    });
7296                    controller_prepared = Some(OptiControllerPrepared {
7297                        verify_tokens: [optimistic_pending, optimistic_draft],
7298                        draft_prob: optimistic_draft_probability,
7299                        eager_seed,
7300                        q_proxy,
7301                        scratch_len: scratch.kv.len,
7302                    });
7303                } else {
7304                    OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7305                    OPTI_WASTED_DRAFT_TOKENS
7306                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7307                    rejected_probe = Some((q_proxy, optimistic_pending));
7308                    eprintln!(
7309                        "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
7310                        opti_fork
7311                            .as_ref()
7312                            .and_then(|fork| fork.controller.as_ref())
7313                            .expect("controller policy")
7314                            .threshold,
7315                    );
7316                }
7317            }
7318            let fork_attempt = match fork_generation.take() {
7319                Some(generation) if base == 1 && k_round == 1 => Some(generation),
7320                Some(generation) => {
7321                    opti_fork
7322                        .as_mut()
7323                        .expect("fork generation without fork state")
7324                        .retire(generation)?;
7325                    None
7326                }
7327                None => None,
7328            };
7329            let (tlogits_d, vx) = if let Some(p) = pipe {
7330                self.decode_step_t_core_pipelined(
7331                    e,
7332                    &verify_tokens,
7333                    pos,
7334                    &mut *cache,
7335                    embd_dev,
7336                    ckpt.as_mut(),
7337                    p,
7338                    round,
7339                )?
7340            } else if controller_can_probe {
7341                let fence = opti_fork
7342                    .as_ref()
7343                    .ok_or("optipipe controller probe lost fork state")?
7344                    .fence;
7345                let boundary = match current_opti.as_mut() {
7346                    Some(ticket) => ticket.take_boundary(),
7347                    None => self.verify_stage0_issue(
7348                        e,
7349                        &verify_tokens,
7350                        pos,
7351                        &mut *cache,
7352                        embd_dev,
7353                        ckpt.as_mut(),
7354                        None,
7355                        &fence,
7356                        Some(true),
7357                        None,
7358                    )?,
7359                };
7360                if let Some(prepared) = controller_prepared.take() {
7361                    let generation = {
7362                        let fork = opti_fork
7363                            .as_mut()
7364                            .ok_or("optipipe controller admission lost fork state")?;
7365                        let generation = fork.reserve_successor()?;
7366                        let rt = fork.rt;
7367                        let snapshot_fence = fork.fence;
7368                        opti_snapshot_one_stage_owned_into(
7369                            e,
7370                            cache,
7371                            rt,
7372                            &snapshot_fence,
7373                            0,
7374                            fork.successor_snapshot_mut(),
7375                        )?;
7376                        generation
7377                    };
7378                    let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
7379                    let successor_boundary = self.verify_stage0_issue(
7380                        e,
7381                        &prepared.verify_tokens,
7382                        pos + verify_tokens.len(),
7383                        &mut *cache,
7384                        embd_dev,
7385                        Some(&mut successor_ckpt),
7386                        None,
7387                        &fence,
7388                        Some(false),
7389                        None,
7390                    )?;
7391                    OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7392                    let fork = opti_fork
7393                        .as_ref()
7394                        .ok_or("optipipe controller ticket lost fork state")?;
7395                    successor_attempt = Some(fork.controller_ticket(
7396                        generation,
7397                        successor_boundary,
7398                        successor_ckpt,
7399                        prepared.verify_tokens,
7400                        prepared.draft_prob,
7401                        prepared.eager_seed,
7402                        prepared.q_proxy,
7403                        prepared.scratch_len,
7404                    ));
7405                    eprintln!(
7406                        "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
7407                         verify={:?}",
7408                        generation.id,
7409                        prepared.q_proxy,
7410                        fork.controller.expect("controller policy").threshold,
7411                        prepared.verify_tokens,
7412                    );
7413                }
7414                let result = self.verify_stage1_finish(
7415                    e,
7416                    boundary,
7417                    &mut *cache,
7418                    ckpt.as_mut(),
7419                    None,
7420                    &fence,
7421                    successor_attempt.is_none(),
7422                )?;
7423                if let Some(ticket) = current_opti.as_mut() {
7424                    ticket.settle();
7425                }
7426                if successor_attempt.is_some() {
7427                    let fork = opti_fork
7428                        .as_mut()
7429                        .ok_or("optipipe successor snapshot lost fork state")?;
7430                    let rt = fork.rt;
7431                    let snapshot_fence = fork.fence;
7432                    opti_snapshot_one_stage_owned_into(
7433                        e,
7434                        cache,
7435                        rt,
7436                        &snapshot_fence,
7437                        1,
7438                        fork.successor_snapshot_mut(),
7439                    )?;
7440                    // Publish N only after both independent successor-state queues are complete.
7441                    fork.rt.publish_to(1, &e.stream())?;
7442                }
7443                result
7444            } else if let Some(ticket) = current_opti.as_mut() {
7445                let fork = opti_fork
7446                    .as_mut()
7447                    .ok_or("optipipe carried controller ticket lost fork state")?;
7448                let boundary = ticket.take_boundary();
7449                let result = self.verify_stage1_finish(
7450                    e,
7451                    boundary,
7452                    &mut *cache,
7453                    ckpt.as_mut(),
7454                    None,
7455                    &fork.fence,
7456                    true,
7457                )?;
7458                ticket.settle();
7459                result
7460            } else if let Some(generation) = fork_attempt {
7461                let fork = opti_fork.as_mut().expect("fork generation without fork state");
7462                fork.capture_seed(
7463                    e,
7464                    generation,
7465                    &h_seed_buf,
7466                    &fill_prev,
7467                    scratch.kv.len,
7468                )?;
7469                let action = fork.mode.action(generation.id);
7470                let boundary = self.verify_stage0_issue(
7471                    e,
7472                    &verify_tokens,
7473                    pos,
7474                    &mut *cache,
7475                    embd_dev,
7476                    ckpt.as_mut(),
7477                    None,
7478                    &fork.fence,
7479                    Some(true),
7480                    None,
7481                )?;
7482                OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7483                let mut ticket = fork.ticket(generation, boundary);
7484                if action == OptiForkAction::Abort {
7485                    return Err(format!(
7486                        "optipipe forced abort with generation {} stage0 in flight",
7487                        generation.id,
7488                    )
7489                    .into());
7490                }
7491                fork.reconcile(
7492                    e,
7493                    &mut *cache,
7494                    &mut *scratch,
7495                    &snap,
7496                    &mut h_seed_buf,
7497                    &mut fill_prev,
7498                    generation,
7499                    action,
7500                    verify_tokens[0],
7501                )?;
7502                let result = if action == OptiForkAction::Hit {
7503                    let boundary = ticket.take_boundary();
7504                    self.verify_stage1_finish(
7505                        e,
7506                        boundary,
7507                        &mut *cache,
7508                        ckpt.as_mut(),
7509                        None,
7510                        &fork.fence,
7511                        true,
7512                    )?
7513                } else {
7514                    // The optimistic boundary slot has no reader. Re-run the unchanged serial
7515                    // verify only after E_restart published the restored stage-0 state.
7516                    self.decode_step_t_core(
7517                        e,
7518                        &verify_tokens,
7519                        pos,
7520                        &mut *cache,
7521                        embd_dev,
7522                        ckpt.as_mut(),
7523                    )?
7524                };
7525                ticket.settle();
7526                debug_assert_eq!(ticket.generation, generation);
7527                fork.retire(generation)?;
7528                result
7529            } else {
7530                self.decode_step_t_core(
7531                    e,
7532                    &verify_tokens,
7533                    pos,
7534                    &mut *cache,
7535                    embd_dev,
7536                    ckpt.as_mut(),
7537                )?
7538            };
7539            let pipe_accept = match pipe {
7540                Some(p) => Some(p.accept_begin(round)?),
7541                None => None,
7542            };
7543
7544            ph_mark(&mut ph_verify, phase_on);
7545            // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
7546            // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
7547            // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
7548            // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
7549            // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
7550            // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
7551            // (== the bonus), so every index shifts by `base` and last_pred is unused.
7552            let t_v = verify_tokens.len();
7553            let mut preds: Vec<u32> = Vec::new();
7554            if !sampled {
7555                for j in 0..t_v {
7556                    e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
7557                }
7558                preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
7559                // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
7560                // next round's last_token = the next chain's embed lookup. Catch it at the
7561                // source with the column named — an all-NaN VERIFY column implicates the
7562                // stage-split trunk (decode_step_t_core_ppn), not the draft head.
7563                if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
7564                    let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
7565                    let mut probe = e.zeros(n_vocab)?;
7566                    e.copy_view_into(&mut probe, 0, col, n_vocab)?;
7567                    let col_h = e.dtoh(&probe)?;
7568                    let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
7569                    return Err(format!(
7570                        "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
7571                         col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
7572                         — the stage-split verify produced a poisoned column (#87 trap)",
7573                        preds[bad]
7574                    )
7575                    .into());
7576                }
7577            }
7578            ph_mark(&mut ph_wait, phase_on);
7579            let t_pred = |j: usize| -> u32 {
7580                if j == 0 && base == 0 {
7581                    last_pred
7582                } else {
7583                    preds[base + j - 1]
7584                }
7585            };
7586            let mut devacc_seeded = false;
7587            let mut devacc_acc: Option<CudaSlice<u32>> = None;
7588            let (n_acc, bonus) = if !sampled {
7589                // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
7590                // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
7591                // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
7592                // gated on token identity vs the host walk (the arms below are bit-equal rules).
7593                if crate::spec::spec_devacc() && k_round > 0 && !spec_replay
7594                    && constraint.is_none() {
7595                    let draft_d = e.htod_u32_v(&draft)?;
7596                    let mut acc_out = e.alloc_u32_zeroed(2)?;
7597                    e.spec_accept_greedy(
7598                        &preds_d,
7599                        &draft_d,
7600                        last_pred,
7601                        base,
7602                        k_round,
7603                        &mut acc_out,
7604                    )?;
7605                    devacc_acc = Some(acc_out.clone());
7606                    // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
7607                    // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
7608                    // non-replay commit arms skip their host-offset seed copies (guarded below);
7609                    // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
7610                    // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
7611                    // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
7612                    // the update lands after the arms (devacc_seeded guard below).
7613                    e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
7614                    // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
7615                    // unified rule; full accept rewrites the verify-left value). Host mirrors
7616                    // update after the readback; commit_verified_prefix skips its len_d writes.
7617                    if let Some(successor) = successor_attempt.as_ref() {
7618                        opti_fork
7619                            .as_mut()
7620                            .ok_or("optipipe successor reconcile lost fork state")?
7621                            .queue_actual_reconcile(
7622                                e,
7623                                &snap,
7624                                &acc_out,
7625                                successor.verify_tokens[0],
7626                                base,
7627                            )?;
7628                    } else if let Some(ptrs) = &kv_len_ptrs {
7629                        let saved: Vec<i32> = (0..self.layers.len())
7630                            .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
7631                            .collect();
7632                        let saved_d = e.htod_i32(&saved)?;
7633                        e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
7634                    }
7635                    devacc_seeded = true;
7636                    let ab = e.dtoh_u32(&acc_out)?;
7637                    (ab[0] as usize, ab[1])
7638                } else {
7639                    let mut n_acc = 0usize;
7640                    for j in 0..k_round {
7641                        if t_pred(j) == draft[j] {
7642                            n_acc += 1;
7643                        } else {
7644                            break;
7645                        }
7646                    }
7647                    // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
7648                    // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
7649                    (n_acc, t_pred(n_acc))
7650                }
7651            } else {
7652                // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
7653                if col_buf.is_none() {
7654                    col_buf = Some(e.zeros(n_vocab)?);
7655                }
7656                // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
7657                // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
7658                let mut pj = vec![0f32; k_round.max(1)];
7659                let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
7660                if k_round > 0 {
7661                    let mut ids: Vec<u32> = Vec::new();
7662                    let mut rows: Vec<i32> = Vec::new();
7663                    for j in 0..k_round {
7664                        if j > 0 || base == 1 {
7665                            ids.push(draft[j]);
7666                            rows.push((base + j) as i32 - 1);
7667                        }
7668                    }
7669                    if !ids.is_empty() {
7670                        let nr = rows.len();
7671                        // penalties: materialize the used columns into one contiguous penalized
7672                        // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
7673                        // penalties: materialize used columns contiguously, penalize all rows in
7674                        // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
7675                        let p_rows: Vec<i32> = if pen_on {
7676                            (0..nr as i32).collect()
7677                        } else {
7678                            rows.clone()
7679                        };
7680                        if pen_on {
7681                            if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
7682                                pcol_buf = Some(e.zeros(nr * n_vocab)?);
7683                            }
7684                            let pc = pcol_buf.as_mut().unwrap();
7685                            for (i2, &r) in rows.iter().enumerate() {
7686                                let c = r as usize;
7687                                e.copy_view_into(
7688                                    pc,
7689                                    i2 * n_vocab,
7690                                    &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
7691                                    n_vocab,
7692                                )?;
7693                            }
7694                            let h = pen_hist_d.as_ref().unwrap();
7695                            let nh = h.len();
7696                            e.penalize_logits_rows(
7697                                pc,
7698                                h,
7699                                nh,
7700                                sp.penalty_repeat,
7701                                sp.penalty_freq,
7702                                sp.penalty_present,
7703                                n_vocab,
7704                                nr,
7705                            )?;
7706                        }
7707                        let p_src: &CudaSlice<f32> = if pen_on {
7708                            pcol_buf.as_ref().unwrap()
7709                        } else {
7710                            &tlogits_d
7711                        };
7712                        let rowsd = e.htod_i32(&p_rows)?;
7713                        let (mut th_d, mut z_d, mut mx_d) =
7714                            (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
7715                        e.filter_stats(
7716                            p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
7717                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
7718                        )?;
7719                        let idsd = e.htod_u32_v(&ids)?;
7720                        let mut outd = e.zeros(nr)?;
7721                        e.softmax_gather_filtered(
7722                            p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
7723                            sp_temp,
7724                        )?;
7725                        let outv = e.dtoh(&outd)?;
7726                        let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
7727                        let mut oi = 0usize;
7728                        for j in 0..k_round {
7729                            if j > 0 || base == 1 {
7730                                pj[j] = outv[oi];
7731                                oi += 1;
7732                            }
7733                        }
7734                        col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
7735                    }
7736                    if base == 0 {
7737                        let lc: &CudaSlice<f32> = if pen_on {
7738                            if col_buf.is_none() {
7739                                col_buf = Some(e.zeros(n_vocab)?);
7740                            }
7741                            let cb = col_buf.as_mut().unwrap();
7742                            e.copy_into(
7743                                cb,
7744                                0,
7745                                last_col_logits
7746                                    .as_ref()
7747                                    .expect("sampled: last_col_logits unset"),
7748                                n_vocab,
7749                            )?;
7750                            let h = pen_hist_d.as_ref().unwrap();
7751                            let nh = h.len();
7752                            e.penalize_logits(
7753                                cb,
7754                                h,
7755                                nh,
7756                                sp.penalty_repeat,
7757                                sp.penalty_freq,
7758                                sp.penalty_present,
7759                                n_vocab,
7760                            )?;
7761                            col_buf.as_ref().unwrap()
7762                        } else {
7763                            last_col_logits
7764                                .as_ref()
7765                                .expect("sampled: last_col_logits unset")
7766                        };
7767                        let rows0 = e.htod_i32(&[0])?;
7768                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
7769                        e.filter_stats(
7770                            lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
7771                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
7772                        )?;
7773                        let idsd = e.htod_u32_v(&[draft[0]])?;
7774                        let mut outd = e.zeros(1)?;
7775                        e.softmax_gather_filtered(
7776                            lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
7777                        )?;
7778                        pj[0] = e.dtoh(&outd)?[0];
7779                        last_col_stats =
7780                            Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
7781                    }
7782                }
7783                // q source: the graph arm retained the head logits in the persistent q_slots;
7784                // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
7785                // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
7786                // computes them post-replay — graph engages only filter/penalty-free, so the
7787                // stats degenerate to th=0/full-Z there, keeping ONE accept path).
7788                let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
7789                    &dctx.q_slots
7790                } else {
7791                    &draft_logits
7792                };
7793                let mut n_acc = 0usize;
7794                for j in 0..k_round {
7795                    let (qmx, qth, qz) = draft_stats[j];
7796                    let idsd = e.htod_u32_v(&[draft_idx[j]])?;
7797                    let rowsd = e.htod_i32(&[0])?;
7798                    let thd = e.htod(&[qth])?;
7799                    let zd = e.htod(&[qz])?;
7800                    let _ = qmx;
7801                    let mut outd = e.zeros(1)?;
7802                    e.softmax_gather_filtered(
7803                        &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
7804                        sp_temp,
7805                    )?;
7806                    let qj = e.dtoh(&outd)?[0];
7807                    let u = host_u01(sp_seed, uctr);
7808                    uctr += 1;
7809                    if (u as f64) * (qj as f64) < pj[j] as f64 {
7810                        n_acc += 1;
7811                    } else {
7812                        break;
7813                    }
7814                }
7815                let bonus = if n_acc == k_round {
7816                    // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
7817                    let col = base + k_round - 1;
7818                    let cb = col_buf.as_mut().unwrap();
7819                    e.copy_view_into(
7820                        cb,
7821                        0,
7822                        &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
7823                        n_vocab,
7824                    )?;
7825                    if pen_on {
7826                        let h = pen_hist_d.as_ref().unwrap();
7827                        let nh = h.len();
7828                        e.penalize_logits(
7829                            cb,
7830                            h,
7831                            nh,
7832                            sp.penalty_repeat,
7833                            sp.penalty_freq,
7834                            sp.penalty_present,
7835                            n_vocab,
7836                        )?;
7837                    }
7838                    if perturb_buf.is_none() {
7839                        perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
7840                    }
7841                    // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
7842                    // truncation-fix; receipts research/sampfix-20260805/). The old code reused
7843                    // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
7844                    // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
7845                    // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
7846                    // last gathered column, in both base arms. `th` is a threshold in e-units of
7847                    // its OWN row's max, so feeding a neighbour's (row_max, th) into
7848                    // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
7849                    // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
7850                    // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
7851                    // falls through to its smallest-index tie-break => token id 0 ("!") spliced
7852                    // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
7853                    // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
7854                    // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
7855                    // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
7856                    // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
7857                    // and row_max is unused once nothing is masked), so this fix is a byte-level
7858                    // no-op for the untruncated serve default. One extra one-block filter_stats
7859                    // per full-accept round is the whole cost.
7860                    let (mx, th) = {
7861                        let rows0 = e.htod_i32(&[0])?;
7862                        let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
7863                        let cb0 = col_buf.as_ref().unwrap();
7864                        e.filter_stats(
7865                            cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
7866                            sp_temp, sp.top_k, sp.top_p, sp.min_p,
7867                        )?;
7868                        (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
7869                    };
7870                    let pb = perturb_buf.as_mut().unwrap();
7871                    let cb2 = col_buf.as_ref().unwrap();
7872                    e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
7873                    sctr += 1;
7874                    let td = e.argmax_token_device(pb, n_vocab)?;
7875                    e.dtoh_u32_one(&td)?
7876                } else {
7877                    // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
7878                    let cb = col_buf.as_mut().unwrap();
7879                    if n_acc > 0 || base == 1 {
7880                        let col = base + n_acc - 1;
7881                        e.copy_view_into(
7882                            cb,
7883                            0,
7884                            &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
7885                            n_vocab,
7886                        )?;
7887                    } else {
7888                        let lc = last_col_logits.as_ref().unwrap();
7889                        e.copy_into(cb, 0, lc, n_vocab)?;
7890                    }
7891                    if pen_on {
7892                        let h = pen_hist_d.as_ref().unwrap();
7893                        let nh = h.len();
7894                        e.penalize_logits(
7895                            cb,
7896                            h,
7897                            nh,
7898                            sp.penalty_repeat,
7899                            sp.penalty_freq,
7900                            sp.penalty_present,
7901                            n_vocab,
7902                        )?;
7903                    }
7904                    let cb2 = col_buf.as_ref().unwrap();
7905                    let sc = sctr;
7906                    sctr += 1;
7907                    // p-stats for the reject column: from col_stats when the col was gathered,
7908                    // else (j==0&&base==0) from last_col_stats.
7909                    let p_stats = if n_acc > 0 || base == 1 {
7910                        // col index within the gathered set == number of gathered cols before n_acc
7911                        let gi = if base == 1 { n_acc } else { n_acc - 1 };
7912                        col_stats.get(gi).copied().unwrap_or_else(|| {
7913                            (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
7914                        })
7915                    } else {
7916                        last_col_stats.expect("sampled: last_col_stats unset at reject")
7917                    };
7918                    let q_stats = draft_stats[n_acc];
7919                    if let Some(map) = &d2t_dev {
7920                        if q_full_buf.is_none() {
7921                            q_full_buf = Some(e.zeros(n_vocab)?);
7922                        }
7923                        let qf = q_full_buf.as_mut().unwrap();
7924                        e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
7925                        let qf2 = q_full_buf.as_ref().unwrap();
7926                        e.residual_sample_filtered(
7927                            cb2,
7928                            Some(qf2),
7929                            n_vocab,
7930                            sp_temp,
7931                            sp_seed,
7932                            sc,
7933                            p_stats,
7934                            q_stats,
7935                            &mut sample_tok,
7936                        )?;
7937                    } else {
7938                        e.residual_sample_filtered(
7939                            cb2,
7940                            Some(&q_bufs[n_acc]),
7941                            n_vocab,
7942                            sp_temp,
7943                            sp_seed,
7944                            sc,
7945                            p_stats,
7946                            q_stats,
7947                            &mut sample_tok,
7948                        )?;
7949                    }
7950                    e.dtoh_u32(&sample_tok)?[0]
7951                };
7952                (n_acc, bonus)
7953            };
7954            // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
7955            // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
7956            // ordering). Walk the accepted drafts through the grammar in commit order; the
7957            // first illegal token truncates acceptance at its slot, and that slot's emission
7958            // is recomputed as the MASKED argmax of the target's own verify column — token-
7959            // identical to constrained plain greedy decode (an unmasked argmax that is
7960            // grammar-legal IS the masked argmax: masking only removes competitors). The
7961            // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
7962            // measured in acceptance numbers, never hidden.
7963            let (n_acc, bonus) = match constraint.as_deref_mut() {
7964                None => (n_acc, bonus),
7965                Some(c) => {
7966                    fn ce(e2: String) -> Box<dyn std::error::Error> {
7967                        format!("constraint: {e2}").into()
7968                    }
7969                    let mut na = n_acc;
7970                    let mut cut = false;
7971                    for (j, &d) in draft.iter().enumerate().take(n_acc) {
7972                        if c.is_allowed(d).map_err(ce)? {
7973                            c.consume(d).map_err(ce)?;
7974                        } else {
7975                            na = j;
7976                            cut = true;
7977                            dm_cut_tokens += n_acc - j;
7978                            break;
7979                        }
7980                    }
7981                    if cut {
7982                        dm_cuts += 1;
7983                    }
7984                    let mut bo = bonus;
7985                    if cut || !c.is_allowed(bo).map_err(ce)? {
7986                        let mut row = if na == 0 && base == 0 {
7987                            init_logits_host.clone()
7988                                .ok_or("constraint: init logits missing (round-0 cut)")?
7989                        } else {
7990                            e.dtoh_view(&tlogits_d.slice(
7991                                (base + na - 1) * n_vocab..(base + na) * n_vocab))?
7992                        };
7993                        c.mask_logits(&mut row).map_err(ce)?;
7994                        bo = argmax(&row) as u32;
7995                    }
7996                    c.consume(bo).map_err(ce)?;
7997                    (na, bo)
7998                }
7999            };
8000            let mut successor_valid = false;
8001            if let Some((q_proxy, expected_d2)) = rejected_probe {
8002                let v_n = n_acc == 1 && bonus == expected_d2;
8003                eprintln!(
8004                    "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
8005                     expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
8006                );
8007            }
8008            if let Some(successor) = successor_attempt.as_ref() {
8009                successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
8010                let generation = successor.generation;
8011                let q_proxy = successor.q_proxy;
8012                let expected_pending = successor.verify_tokens[0];
8013                let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
8014                let fork = opti_fork
8015                    .as_mut()
8016                    .ok_or("optipipe successor resolution lost fork state")?;
8017                fork.finish_actual_reconcile(
8018                    e,
8019                    &mut *cache,
8020                    &snap,
8021                    n_acc,
8022                    base,
8023                    successor_valid,
8024                )?;
8025                if successor_valid {
8026                    OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8027                } else {
8028                    OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8029                    OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8030                    OPTI_WASTED_DRAFT_TOKENS
8031                        .fetch_add(2, std::sync::atomic::Ordering::Relaxed);
8032                }
8033                let breaker_tripped = fork
8034                    .controller
8035                    .as_mut()
8036                    .expect("controller policy")
8037                    .resolve(successor_valid);
8038                if breaker_tripped {
8039                    OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8040                }
8041                eprintln!(
8042                    "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
8043                     expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
8044                     resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
8045                    generation.id,
8046                    successor_valid,
8047                    !successor_valid,
8048                    breaker_tripped,
8049                );
8050                if !successor_valid {
8051                    let mut successor = successor_attempt
8052                        .take()
8053                        .expect("controller successor disappeared on miss");
8054                    successor.settle();
8055                    fork.retire(generation)?;
8056                }
8057            }
8058            total_drafted += k_round;
8059            total_accepted += n_acc;
8060            if let Some(t) = sess_telem {
8061                // Greedy, rejection-sampling, and grammar truncation all converge here after
8062                // the accept decision is already on host. Fixed-size relaxed atomics only.
8063                t.record_round(k_round, n_acc);
8064            }
8065            if spec_stats {
8066                st_len_hist[k_round] += 1;
8067                for j in 0..k_round {
8068                    st_drafted[j] += 1;
8069                }
8070                for j in 0..n_acc {
8071                    st_accepted[j] += 1;
8072                }
8073                if n_acc == k_round {
8074                    st_full += 1;
8075                }
8076            }
8077
8078            if debug_spec {
8079                eprintln!("[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}", out.len(), t_pred(0));
8080            }
8081
8082            // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
8083            let commit_started = std::time::Instant::now();
8084            // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
8085            // of them (overshoot past max_new included) or `committed` under-counts the cache rows
8086            // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
8087            // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
8088            for j in 0..n_acc {
8089                if !session_mode && out.len() >= max_new {
8090                    break;
8091                }
8092                out.push(draft[j]);
8093            }
8094            if pen_on {
8095                pen_hist.extend_from_slice(&draft[0..n_acc]);
8096                pen_hist.push(bonus);
8097            }
8098            let bonus_emitted = session_mode || out.len() < max_new;
8099            if bonus_emitted {
8100                out.push(bonus);
8101            }
8102            last_token = bonus;
8103
8104            // --- 5. ROLLBACK + advance (§C) ---
8105            if n_acc == k_round {
8106                // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
8107                // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
8108                // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
8109                // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
8110                // last_pred is dead in the pending path (t_pred reads verify col 0).
8111                //
8112                // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
8113                // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
8114                // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
8115                // trunk hidden (the last verify column). set_len first: a p-min break may have
8116                // left one extra chain append at that slot. Partial accepts need NO fill (the
8117                // chain already covered every accepted position; round-start set_len truncates).
8118                let mut vh_seed = e.zeros(n_embd)?;
8119                e.copy_view_into(
8120                    &mut vh_seed,
8121                    0,
8122                    &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
8123                    n_embd,
8124                )?;
8125                if refresh {
8126                    // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
8127                    // overwrite ALL committed positions' scratch entries with K/V from their EXACT
8128                    // verify hiddens — the reference engine's mtp_update fills from true hiddens;
8129                    // the full stack (vx) is already resident from the verify. Replaces both the
8130                    // chain-approximate entries AND the old last-token-only fill. Acceptance-only
8131                    // (draft attention quality); exactness stays the verify's job.
8132                    scratch.set_len(e, pos)?;
8133                    // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
8134                    // (hidden of the last committed row before this verify batch).
8135                    let mut vxs = e.zeros(t_v * n_embd)?;
8136                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
8137                    if t_v > 1 {
8138                        e.copy_view_into(
8139                            &mut vxs,
8140                            n_embd,
8141                            &vx.slice(0..(t_v - 1) * n_embd),
8142                            (t_v - 1) * n_embd,
8143                        )?;
8144                    }
8145                    self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
8146                } else {
8147                    scratch.set_len(e, pos + base + k_round - 1)?;
8148                    // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
8149                    let mut hp = e.zeros(n_embd)?;
8150                    if t_v >= 2 {
8151                        e.copy_view_into(
8152                            &mut hp,
8153                            0,
8154                            &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
8155                            n_embd,
8156                        )?;
8157                    } else {
8158                        e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
8159                    }
8160                    self.mtp_kv_fill(
8161                        e,
8162                        mtp,
8163                        &[draft[k_round - 1]],
8164                        &hp,
8165                        pos + base + k_round - 1,
8166                        &mut *scratch,
8167                        embd_dev,
8168                    )?;
8169                }
8170                // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
8171                // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
8172                // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
8173                // col). Saves one MTP-block pass per round on top of the pairing fix.
8174                if !devacc_seeded {
8175                    e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
8176                    e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
8177                }
8178                pending = Some(bonus);
8179                if debug_spec {
8180                    eprintln!("  -> FULL ACCEPT (bonus pending, prev-h seed)");
8181                }
8182            } else if !spec_replay && base + n_acc >= 1 {
8183                // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
8184                // the verify's first j = base+n_acc columns ARE the committed sequence, computed
8185                // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
8186                // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
8187                // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
8188                // full-accept path — the legacy duplicate trunk replay is gone. The next chain
8189                // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
8190                // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
8191                // accept (never compounds: the next verify recomputes true hiddens for all
8192                // committed columns).
8193                let j = base + n_acc;
8194                self.commit_verified_prefix(
8195                    e,
8196                    &mut *cache,
8197                    &snap,
8198                    ckpt.as_ref().unwrap(),
8199                    j,
8200                    devacc_seeded,
8201                    if devacc_seeded {
8202                        devacc_acc.as_ref().map(|a| (a, base, t_v))
8203                    } else {
8204                        None
8205                    },
8206                )?;
8207                let mut seed = e.zeros(n_embd)?;
8208                e.copy_view_into(
8209                    &mut seed,
8210                    0,
8211                    &vx.slice((j - 1) * n_embd..j * n_embd),
8212                    n_embd,
8213                )?;
8214                // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
8215                // branch); without it the chain entries stand and only the tail truncates. Either
8216                // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
8217                // (persistent mode), rope pos+j+1 (chain convention).
8218                if refresh {
8219                    scratch.set_len(e, pos)?;
8220                    let mut vxs = e.zeros(j * n_embd)?;
8221                    e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
8222                    if j > 1 {
8223                        e.copy_view_into(
8224                            &mut vxs,
8225                            n_embd,
8226                            &vx.slice(0..(j - 1) * n_embd),
8227                            (j - 1) * n_embd,
8228                        )?;
8229                    }
8230                    self.mtp_kv_fill(
8231                        e,
8232                        mtp,
8233                        &verify_tokens[0..j],
8234                        &vxs,
8235                        pos,
8236                        &mut *scratch,
8237                        embd_dev,
8238                    )?;
8239                } else {
8240                    scratch.set_len(e, pos + j)?;
8241                }
8242                // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
8243                // bonus's predecessor (verify col j-1); no pseudo pass.
8244                if !devacc_seeded {
8245                    e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
8246                    e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
8247                }
8248                pending = Some(bonus);
8249                if debug_spec {
8250                    eprintln!("  -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
8251                }
8252            } else if !spec_replay {
8253                // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
8254                // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
8255                // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
8256                // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
8257                // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
8258                // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
8259                // base=1 pending machinery, bit-identical by the decode-exact verify contract.
8260                // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
8261                // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
8262                cache.rollback(e, &snap, 0)?;
8263                scratch.set_len(e, pos)?;
8264                e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
8265                pending = Some(bonus);
8266                if debug_spec {
8267                    eprintln!("  -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
8268                }
8269            } else {
8270                // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
8271                // this round survives, only possible before the first pending exists, ~round 0):
8272                // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
8273                // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
8274                // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
8275                // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
8276                // trunk hidden.
8277                cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
8278                let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
8279                if let Some(b) = pending.take() {
8280                    replay.push(b);
8281                }
8282                replay.extend_from_slice(&draft[0..n_acc]);
8283                replay.push(bonus);
8284                // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
8285                // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
8286                // last col exactly as before (byte-identical to the old _h_emb_dev call).
8287                let (rl_d, rx) =
8288                    self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?;
8289                // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
8290                // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
8291                e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
8292                last_pred = e.dtoh_u32(&preds_d)?[0];
8293                if sampled {
8294                    let lr0 = replay.len();
8295                    let lc = last_col_logits
8296                        .as_mut()
8297                        .expect("sampled: last_col_logits unset");
8298                    e.copy_view_into(
8299                        lc,
8300                        0,
8301                        &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
8302                        n_vocab,
8303                    )?;
8304                }
8305                let lr = replay.len();
8306                if lr >= 2 {
8307                    e.copy_view_into(
8308                        &mut h_seed_buf,
8309                        0,
8310                        &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
8311                        n_embd,
8312                    )?;
8313                } else {
8314                    // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
8315                    // last_token, whose own-row hidden fill_prev still holds.
8316                    e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
8317                }
8318                // the bonus is COMMITTED here — it becomes the last committed row.
8319                let mut rh_last = e.zeros(n_embd)?;
8320                e.copy_view_into(
8321                    &mut rh_last,
8322                    0,
8323                    &rx.slice((lr - 1) * n_embd..lr * n_embd),
8324                    n_embd,
8325                )?;
8326                e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
8327                if debug_spec {
8328                    eprintln!("  -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
8329                }
8330            }
8331            if devacc_seeded {
8332                // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
8333                // consumed the old value (both slots carry the same value in every non-replay arm).
8334                e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
8335            }
8336            if successor_valid {
8337                let optimistic_scratch_len = successor_attempt
8338                    .as_ref()
8339                    .expect("valid controller successor disappeared")
8340                    .scratch_len;
8341                // The normal current-round commit refreshed/truncated the logical scratch tail.
8342                // Its optimistic successor row was already written physically, so restoring only
8343                // the retained logical length makes that row live for the carried round.
8344                scratch.set_len(e, optimistic_scratch_len)?;
8345            }
8346            if let Some(current) = current_opti.take() {
8347                opti_fork
8348                    .as_mut()
8349                    .ok_or("optipipe current retirement lost fork state")?
8350                    .retire(current.generation)?;
8351            }
8352            if successor_valid {
8353                let successor = successor_attempt
8354                    .take()
8355                    .expect("valid controller successor disappeared before promotion");
8356                let generation = successor.generation;
8357                opti_fork
8358                    .as_mut()
8359                    .ok_or("optipipe successor promotion lost fork state")?
8360                    .promote_successor_snapshot(&mut snap, generation);
8361                carried_opti = Some(successor);
8362            }
8363            if anatomy_on {
8364                // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
8365                // only for this diagnostic so it does not disappear into the following draft's
8366                // first token readback.
8367                e.stream().synchronize()?;
8368                ph_commit += commit_started.elapsed().as_secs_f64();
8369            }
8370            // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
8371            // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
8372            // final position — the floor's position key reads the committed depth). Burst
8373            // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
8374            // like gemma's burst arm.
8375            if adapt {
8376                let fl_now = floor_at(cache.pos);
8377                kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
8378            }
8379            ph_mark(&mut ph_rest, phase_on);
8380            if let Some(p) = pipe {
8381                p.accept_end(round);
8382            }
8383            drop(pipe_accept);
8384            round += 1;
8385            // sse-cadence: this round's accepted drafts + bonus are committed (out is
8386            // append-only past step 4) — flush at round cadence.
8387            keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
8388        }
8389        if let Some(mut ticket) = carried_opti.take() {
8390            opti_fork
8391                .as_mut()
8392                .ok_or("optipipe tail drain lost fork state")?
8393                .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
8394        }
8395        // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
8396        // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
8397        let _ = flush_commit(&mut on_commit, &out, &mut flushed);
8398
8399        if spec_stats {
8400            let per_slot: Vec<String> = (0..k)
8401                .map(|j| {
8402                    if st_drafted[j] > 0 {
8403                        format!(
8404                            "{}/{}={:.3}",
8405                            st_accepted[j],
8406                            st_drafted[j],
8407                            st_accepted[j] as f64 / st_drafted[j] as f64
8408                        )
8409                    } else {
8410                        "0/0".into()
8411                    }
8412                })
8413                .collect();
8414            let acc = if total_drafted > 0 {
8415                total_accepted as f64 / total_drafted as f64
8416            } else {
8417                0.0
8418            };
8419            eprintln!(
8420                "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
8421                       per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
8422                       tok_per_round={:.3}",
8423                per_slot.join(" "),
8424                (total_accepted + round) as f64 / round.max(1) as f64
8425            );
8426        }
8427        if constraint.is_some() {
8428            eprintln!(
8429                "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
8430                 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
8431                dm_clone_ns as f64 / 1e6,
8432                dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
8433            );
8434        }
8435        if phase_on {
8436            let tot = ph_draft + ph_verify + ph_wait + ph_rest;
8437            eprintln!("[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
8438                      ph_draft * 1e3, ph_draft / tot * 100.0,
8439                      ph_verify * 1e3, ph_verify / tot * 100.0,
8440                      ph_wait * 1e3, ph_wait / tot * 100.0,
8441                      ph_rest * 1e3, ph_rest / tot * 100.0);
8442        }
8443        if anatomy_on {
8444            let rounds_f = round.max(1) as f64;
8445            let other = (ph_rest - ph_commit).max(0.0);
8446            eprintln!(
8447                "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
8448                 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
8449                ph_draft * 1e3 / rounds_f,
8450                ph_verify * 1e3 / rounds_f,
8451                ph_wait * 1e3 / rounds_f,
8452                ph_commit * 1e3 / rounds_f,
8453                other * 1e3 / rounds_f,
8454            );
8455        }
8456        let _pipe_tail = pipe.map(|p| p.primary());
8457        // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
8458        // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
8459        // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
8460        // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
8461        if let Some(slot) = sess_draft_slot.take() {
8462            *slot = Some(dctx);
8463        }
8464        let t_rounds = t_ent.elapsed();
8465        if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
8466            *sctr_slot = sctr;
8467            *uctr_slot = uctr;
8468            *next_pred_slot = Some(last_pred);
8469            let mut stashed_pending = false;
8470            if let Some(b) = pending.take() {
8471                if !sampled {
8472                    // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
8473                    // committing it with a solo T=1 pass — the next empty-suffix greedy burst
8474                    // consumes it as round-0 verify col 0 (a plain round edge; the old tail
8475                    // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
8476                    // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
8477                    // OUT of `committed` (cache rows == committed); the consuming call
8478                    // prepends it once its verify commits the row. next_pred is unknowable
8479                    // without the commit pass — None; callers gate on pending_tok too.
8480                    debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
8481                    if let Some(slot) = sess_pending_slot.take() {
8482                        *slot = Some(b);
8483                    }
8484                    *next_pred_slot = None;
8485                    // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
8486                    // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
8487                    *last_h = Some(e.clone_dtod(&fill_prev)?);
8488                    stashed_pending = true;
8489                } else {
8490                    // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
8491                    // the sampled round-0 accept needs this pass's logits (last_col_logits).
8492                    let pos_b = cache.pos;
8493                    scratch.set_len(e, pos_b)?;
8494                    let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
8495                    // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
8496                    // itself — the prediction AFTER the bonus never materialized; it would have
8497                    // been the next round's verify col 0). The commit's logits ARE that
8498                    // prediction.
8499                    *next_pred_slot = Some(argmax(&lg_b) as u32);
8500                    self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
8501                    *last_h = Some(hb);
8502                }
8503            } else {
8504                // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
8505                *last_h = Some(e.clone_dtod(&fill_prev)?);
8506            }
8507            committed.extend_from_slice(prompt);
8508            if let Some(cb) = carried_pending {
8509                // the consumed carry's cache row landed in round 0's verify (every pending
8510                // round commits col 0) — it joins `committed` here, in sequence order.
8511                committed.push(cb);
8512            }
8513            if stashed_pending {
8514                // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
8515                // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
8516                // 18446744073709551615 out of range for slice of length 0", killing the
8517                // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
8518                // stream". Reachable because `pending` starts as `carried_pending` (a bonus
8519                // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
8520                // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
8521                // did). So a burst that stashes a pending without emitting anything of its own —
8522                // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
8523                // guard skipping every token under a tight budget — arrives here with
8524                // out.len() == 0 and stashed_pending == true.
8525                //
8526                // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
8527                // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
8528                // just above is already accounted. Saturating, not a min/assert: an empty `out`
8529                // here is a legitimate burst shape, not a corrupt state.
8530                let emitted = out.len().saturating_sub(1);
8531                committed.extend_from_slice(&out[..emitted]);
8532            } else {
8533                committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
8534            }
8535            debug_assert_eq!(
8536                cache.pos,
8537                committed.len(),
8538                "session invariant: cache rows == committed tokens"
8539            );
8540            if setup_trace {
8541                e.stream().synchronize()?; // bound the async tail fill in the trace
8542                let t_tail = t_ent.elapsed();
8543                eprintln!(
8544                    "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
8545                    t_init.as_secs_f64() * 1e3,
8546                    (t_cap - t_init).as_secs_f64() * 1e3,
8547                    (t_fill - t_cap).as_secs_f64() * 1e3,
8548                    (t_rounds - t_fill).as_secs_f64() * 1e3,
8549                    (t_tail - t_rounds).as_secs_f64() * 1e3,
8550                    t_tail.as_secs_f64() * 1e3,
8551                    out.len(),
8552                    continuation
8553                );
8554            }
8555            return Ok((out, total_drafted, total_accepted));
8556        }
8557        out.truncate(max_new);
8558        Ok((out, total_drafted, total_accepted))
8559    }
8560
8561    /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
8562    /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
8563    /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
8564    pub fn extract_dspark_anchors(
8565        &self,
8566        e: &Engine,
8567        tokens: &[u32],
8568        anchor_positions: &[usize],
8569        gamma: usize,
8570        top_k: usize,
8571        chunk: usize,
8572        temperature: f32,
8573    ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
8574        if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
8575            return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
8576        }
8577        if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
8578            return Err("DSpark anchor positions must be sorted and unique".into());
8579        }
8580        for &position in anchor_positions {
8581            if position == 0 || position + gamma >= tokens.len() {
8582                return Err(format!(
8583                    "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
8584                    tokens.len()
8585                )
8586                .into());
8587            }
8588        }
8589
8590        let n_vocab = self.output.out_features();
8591        let n_embd = self.cfg.n_embd as usize;
8592        let mut cache = crate::pp::new_cache(e, &self.cfg, tokens.len() + gamma + 8)?;
8593        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
8594        let embd_gpu = if spec_host_embd() {
8595            None
8596        } else {
8597            Some(
8598                self.embd_gpu
8599                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
8600            )
8601        };
8602        let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
8603
8604        struct PendingRecord {
8605            position: usize,
8606            hidden: Option<Vec<f32>>,
8607            tokens: Vec<u32>,
8608            target_top_ids: Vec<Option<Vec<u32>>>,
8609            target_top_logits: Vec<Option<Vec<f32>>>,
8610            target_top_probs: Vec<Option<Vec<f32>>>,
8611            target_tail_probs: Vec<Option<f32>>,
8612        }
8613
8614        let mut pending: Vec<PendingRecord> = anchor_positions
8615            .iter()
8616            .map(|&position| PendingRecord {
8617                position,
8618                hidden: None,
8619                tokens: tokens[position..=position + gamma].to_vec(),
8620                target_top_ids: vec![None; gamma],
8621                target_top_logits: vec![None; gamma],
8622                target_top_probs: vec![None; gamma],
8623                target_tail_probs: vec![None; gamma],
8624            })
8625            .collect();
8626
8627        let mut start = 0usize;
8628        while start < tokens.len() {
8629            let end = (start + chunk).min(tokens.len());
8630            let chunk_tokens = &tokens[start..end];
8631            let (target_logits, hidden_rows) =
8632                self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
8633            for record in &mut pending {
8634                let hidden_position = record.position - 1;
8635                if hidden_position >= start && hidden_position < end {
8636                    let local = hidden_position - start;
8637                    record.hidden = Some(e.dtoh_view(
8638                        &hidden_rows.slice(local * n_embd..(local + 1) * n_embd),
8639                    )?);
8640                }
8641                for slot in 0..gamma {
8642                    let target_row = record.position + slot;
8643                    if target_row < start || target_row >= end {
8644                        continue;
8645                    }
8646                    let local = target_row - start;
8647                    let logits = e.dtoh_view(
8648                        &target_logits.slice(local * n_vocab..(local + 1) * n_vocab),
8649                    )?;
8650                    let (ids, top_logits, probs, tail) =
8651                        dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
8652                    record.target_top_ids[slot] = Some(ids);
8653                    record.target_top_logits[slot] = Some(top_logits);
8654                    record.target_top_probs[slot] = Some(probs);
8655                    record.target_tail_probs[slot] = Some(tail);
8656                }
8657            }
8658            start = end;
8659        }
8660
8661        pending
8662            .into_iter()
8663            .map(|record| {
8664                let hidden = record
8665                    .hidden
8666                    .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
8667                let target_top_ids =
8668                    flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
8669                let target_top_logits = flatten_dspark_rows(
8670                    record.target_top_logits,
8671                    record.position,
8672                    "target logits",
8673                )?;
8674                let target_top_probs = flatten_dspark_rows(
8675                    record.target_top_probs,
8676                    record.position,
8677                    "target probs",
8678                )?;
8679                let target_tail_probs = record
8680                    .target_tail_probs
8681                    .into_iter()
8682                    .enumerate()
8683                    .map(|(slot, value)| {
8684                        value.ok_or_else(|| {
8685                            format!("missing DSpark tail at {} slot {slot}", record.position)
8686                        })
8687                    })
8688                    .collect::<Result<Vec<_>, _>>()?;
8689                Ok(DsparkAnchorRecord {
8690                    position: record.position,
8691                    hidden,
8692                    tokens: record.tokens,
8693                    target_top_ids,
8694                    target_top_logits,
8695                    target_top_probs,
8696                    target_tail_probs,
8697                })
8698            })
8699            .collect()
8700    }
8701
8702    /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
8703    /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
8704    /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
8705    /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
8706    /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
8707    /// quant-induced head/hidden-state mismatch from text drift.
8708    ///
8709    /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
8710    ///   draft_j  = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
8711    ///              eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
8712    ///   target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
8713    ///              at forced context tokens[0..p+j]). For j==0 this equals live spec
8714    ///              acceptance; for j>=1 live verify would condition on the drafts, here it
8715    ///              conditions on the corpus — deterministic and arm-comparable by design.
8716    ///
8717    /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
8718    /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
8719    /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
8720    ///
8721    /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
8722    /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
8723    /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
8724    /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
8725    /// agreement vs this path — not usable as a training-data source).
8726    pub fn replay_acceptance(
8727        &self,
8728        e: &Engine,
8729        tokens: &[u32],
8730        k: usize,
8731        stride: usize,
8732        chunk: usize,
8733        mut hdump: Option<&mut std::fs::File>,
8734    ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
8735        assert!(k >= 1 && stride >= 1 && chunk >= 2);
8736        let mtp = self
8737            .mtp
8738            .as_ref()
8739            .expect("replay_acceptance requires an MTP head");
8740        let n_vocab = self.output.out_features();
8741        let d_vocab = mtp
8742            .shared_head_head
8743            .as_ref()
8744            .unwrap_or(&self.output)
8745            .out_features();
8746        let n_embd = self.cfg.n_embd as usize;
8747        let t_total = tokens.len();
8748        assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
8749        // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
8750        let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
8751        let mut scratch = MtpScratch::new(
8752            e,
8753            &self.cfg,
8754            t_total + k + 8,
8755            self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
8756        )?;
8757        let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
8758        let embd_gpu = if spec_host_embd() {
8759            None
8760        } else {
8761            Some(
8762                self.embd_gpu
8763                    .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
8764            )
8765        };
8766        let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
8767
8768        // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
8769        let mut bg: Vec<u32> = vec![0; t_total + 1];
8770        let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
8771        let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
8772        let mut seed_buf = e.zeros(n_embd)?;
8773        let mut preds_d = e.alloc_u32_zeroed(chunk)?;
8774        let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
8775        let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
8776        let mut s = 0usize;
8777        while s < t_total {
8778            let cend = (s + chunk).min(t_total);
8779            let tc = cend - s;
8780            let ch = &tokens[s..cend];
8781            // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
8782            //    the chunk's true hiddens.
8783            let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
8784            for j in 0..tc {
8785                e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
8786            }
8787            let preds = e.dtoh_u32(&preds_d)?;
8788            for j in 0..tc {
8789                bg[s + j + 1] = preds[j];
8790            }
8791            // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
8792            // checkpoint-quality metric (position j's logits score the GOLD next token).
8793            if nll_on {
8794                let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
8795                if jmax > 0 {
8796                    let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
8797                    let rows: Vec<i32> = (0..jmax as i32).collect();
8798                    let idsd = e.htod_u32_v(&ids)?;
8799                    let rowsd = e.htod_i32(&rows)?;
8800                    let mut outd = e.zeros(jmax)?;
8801                    e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
8802                    for pr in e.dtoh(&outd)? {
8803                        nll_sum += -((pr.max(1e-30)) as f64).ln();
8804                        nll_cnt += 1;
8805                    }
8806                }
8807            }
8808            if let Some(f) = hdump.as_deref_mut() {
8809                use std::io::Write;
8810                let host: Vec<f32> = e.dtoh(&vx)?;
8811                // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
8812                // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
8813                let mut bytes = Vec::with_capacity(tc * n_embd * 2);
8814                for v in &host[..tc * n_embd] {
8815                    let b = v.to_bits();
8816                    let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
8817                    bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
8818                }
8819                f.write_all(&bytes)?;
8820            }
8821            // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
8822            // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
8823            // per token saved; the forced trunk pass + hdump is all the mode needs).
8824            let chainless = stride > t_total;
8825            if chainless {
8826                e.copy_view_into(
8827                    &mut prev_last_h,
8828                    0,
8829                    &vx.slice((tc - 1) * n_embd..tc * n_embd),
8830                    n_embd,
8831                )?;
8832                s = cend;
8833                continue;
8834            }
8835            // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
8836            //    row s reads the previous chunk's last true hidden, zeros at corpus start).
8837            let mut vxs = e.zeros(tc * n_embd)?;
8838            e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
8839            if tc > 1 {
8840                e.copy_view_into(
8841                    &mut vxs,
8842                    n_embd,
8843                    &vx.slice(0..(tc - 1) * n_embd),
8844                    (tc - 1) * n_embd,
8845                )?;
8846            }
8847            scratch.set_len(e, s)?;
8848            self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
8849            // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
8850            //    [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
8851            //    truncates those approximate appends before they can ever be read.
8852            let ps: Vec<usize> = (s..cend)
8853                .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
8854                .collect();
8855            for &p in ps.iter().rev() {
8856                scratch.set_len(e, p)?;
8857                if p == s {
8858                    e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
8859                } else {
8860                    e.copy_view_into(
8861                        &mut seed_buf,
8862                        0,
8863                        &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
8864                        n_embd,
8865                    )?;
8866                }
8867                let mut e_tok = tokens[p];
8868                let mut d_seed = e.clone_dtod(&seed_buf)?;
8869                let mut drafts: Vec<u32> = Vec::with_capacity(k);
8870                for j in 0..k {
8871                    let (dl_d, h_nextn) = self.mtp_head_forward_dev(
8872                        e,
8873                        mtp,
8874                        e_tok,
8875                        &d_seed,
8876                        &mut scratch,
8877                        p + 1 + j,
8878                        embd_dev,
8879                        None, // acceptance-oracle walk: no grammar
8880                    )?;
8881                    let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
8882                    let idx = e.dtoh_u32_one(&tok_d)?;
8883                    let d = match &mtp.d2t {
8884                        Some(map) => map[idx as usize],
8885                        None => idx,
8886                    };
8887                    drafts.push(d);
8888                    e_tok = d;
8889                    d_seed = h_nextn;
8890                }
8891                // targets may live in a LATER chunk's bg — resolved after the walk.
8892                rows.push((p, drafts, Vec::new()));
8893            }
8894            // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
8895            //    expect scratch.len == cend with exact rows).
8896            scratch.set_len(e, s)?;
8897            self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
8898            e.copy_view_into(
8899                &mut prev_last_h,
8900                0,
8901                &vx.slice((tc - 1) * n_embd..tc * n_embd),
8902                n_embd,
8903            )?;
8904            s = cend;
8905        }
8906        for (p, drafts, targets) in rows.iter_mut() {
8907            for j in 0..drafts.len() {
8908                targets.push(bg[*p + 1 + j]);
8909            }
8910        }
8911        rows.sort_by_key(|r| r.0);
8912        if nll_cnt > 0 {
8913            let mean = nll_sum / nll_cnt as f64;
8914            println!(
8915                "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
8916                mean.exp()
8917            );
8918        }
8919        Ok((rows, bg))
8920    }
8921}
8922
8923#[cfg(test)]
8924mod dspark_sparse_tests {
8925    use super::dspark_sparse_softmax_topk;
8926
8927    #[test]
8928    fn topk_keeps_full_softmax_mass_and_stable_ties() {
8929        let logits = [1.0f32, 3.0, 3.0, -2.0];
8930        let (ids, top_logits, probs, tail) =
8931            dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
8932        assert_eq!(ids, vec![1, 2]);
8933        assert_eq!(top_logits, vec![3.0, 3.0]);
8934        let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
8935        let expected = 1.0 / denominator;
8936        assert!((probs[0] - expected).abs() < 1.0e-6);
8937        assert!((probs[1] - expected).abs() < 1.0e-6);
8938        assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
8939        assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
8940    }
8941}
8942
8943#[cfg(test)]
8944mod telem_tests {
8945    use super::{SpecTelemetry, SpecTelemetryCounters, SPEC_TELEM_POS};
8946
8947    #[test]
8948    fn synthetic_accept_masks_produce_tau_and_position_histogram() {
8949        let counters = SpecTelemetryCounters::default();
8950        for mask in [
8951            [true, true, true],
8952            [true, true, false],
8953            [true, false, false],
8954            [false, false, false],
8955        ] {
8956            let accepted = mask.iter().take_while(|&&value| value).count();
8957            counters.record_round(mask.len(), accepted);
8958        }
8959
8960        let snapshot = counters.snapshot();
8961        assert_eq!((snapshot.rounds, snapshot.drafted, snapshot.accepted), (4, 12, 6));
8962        assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
8963        assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
8964        assert_eq!(snapshot.tau(), 1.5);
8965        assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
8966        assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
8967    }
8968
8969    /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
8970    /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
8971    #[test]
8972    fn delta_isolates_burst_contribution() {
8973        let mut t = SpecTelemetry::default();
8974        // "previous request": 2 rounds of k=3, accepts 3 then 1.
8975        for (kr, na) in [(3usize, 3usize), (3, 1)] {
8976            t.rounds += 1;
8977            t.drafted += kr as u64;
8978            t.accepted += na as u64;
8979            for j in 0..kr { t.pos_drafted[j] += 1; }
8980            for j in 0..na { t.pos_accepted[j] += 1; }
8981        }
8982        let before = t;
8983        // "this burst": 1 round k=3, accepts 2.
8984        t.rounds += 1;
8985        t.drafted += 3;
8986        t.accepted += 2;
8987        for j in 0..3 { t.pos_drafted[j] += 1; }
8988        for j in 0..2 { t.pos_accepted[j] += 1; }
8989        let d = t.delta_since(&before);
8990        assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
8991        assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
8992        assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
8993        assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
8994    }
8995
8996    /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
8997    /// aggregation invariant.
8998    #[test]
8999    fn merge_accumulates_fieldwise() {
9000        let mut agg = SpecTelemetry::default();
9001        let mut d1 = SpecTelemetry { rounds: 2, drafted: 6, accepted: 4, ..Default::default() };
9002        d1.pos_drafted[0] = 2;
9003        d1.pos_accepted[0] = 2;
9004        let mut d2 = SpecTelemetry { rounds: 1, drafted: 3, accepted: 1, ..Default::default() };
9005        d2.pos_drafted[0] = 1;
9006        d2.pos_accepted[0] = 1;
9007        d2.pos_drafted[1] = 1;
9008        agg.merge(&d1);
9009        agg.merge(&d2);
9010        assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
9011        assert_eq!(agg.pos_drafted[0], 3);
9012        assert_eq!(agg.pos_accepted[0], 3);
9013        assert_eq!(agg.pos_drafted[1], 1);
9014        assert_eq!(agg.pos_accepted[1], 0);
9015    }
9016
9017    /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
9018    /// public metrics surface and must never publish a u64-wrapped garbage value.
9019    #[test]
9020    fn delta_saturates_never_wraps() {
9021        let small = SpecTelemetry { rounds: 1, drafted: 2, accepted: 1, ..Default::default() };
9022        let big = SpecTelemetry { rounds: 5, drafted: 15, accepted: 9, ..Default::default() };
9023        let d = small.delta_since(&big);
9024        assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
9025    }
9026}
9027
9028#[cfg(test)]
9029mod opti_fork_tests {
9030    use super::{
9031        OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
9032    };
9033
9034    #[test]
9035    fn controller_threshold_and_three_miss_breaker_are_exact() {
9036        let mut policy = OptiControllerPolicy {
9037            threshold: 0.7,
9038            consecutive_misses: 0,
9039            breaker_tripped: false,
9040        };
9041        assert!(!policy.admit(0.699_999));
9042        assert!(policy.admit(0.7));
9043        assert!(!policy.resolve(false));
9044        assert!(!policy.resolve(false));
9045        assert!(policy.resolve(false));
9046        assert!(policy.breaker_tripped);
9047        assert!(!policy.admit(1.0));
9048        assert!(!policy.resolve(true), "a resolved hit cannot re-arm a tripped request");
9049        assert!(policy.breaker_tripped);
9050    }
9051
9052    #[test]
9053    fn zero_threshold_is_the_true_unconditional_measurement_arm() {
9054        let mut policy = OptiControllerPolicy {
9055            threshold: 0.0,
9056            consecutive_misses: 0,
9057            breaker_tripped: false,
9058        };
9059        for _ in 0..16 {
9060            assert!(policy.admit(0.0));
9061            assert!(!policy.resolve(false));
9062        }
9063        for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
9064            assert!(!policy.admit(invalid), "invalid q proxy must fail closed: {invalid}");
9065        }
9066        assert!(!policy.breaker_tripped);
9067        assert_eq!(policy.consecutive_misses, 0);
9068    }
9069
9070    #[test]
9071    fn alternating_mode_flips_by_generation_not_round_parity() {
9072        assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
9073        assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
9074        assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
9075        assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
9076    }
9077
9078    #[test]
9079    fn live_generation_cannot_be_overwritten() {
9080        let mut tracker = OptiForkGenerationTracker::default();
9081        let g0 = tracker.reserve().unwrap();
9082        let g1 = tracker.reserve().unwrap();
9083        let err = tracker.reserve().unwrap_err().to_string();
9084        assert!(err.contains("still owns generation 0"), "unexpected error: {err}");
9085        tracker.retire(g0).unwrap();
9086        let g2 = tracker.reserve().unwrap();
9087        assert_eq!((g2.id, g2.slot), (2, 0));
9088        tracker.retire(g1).unwrap();
9089        tracker.retire(g2).unwrap();
9090    }
9091
9092    #[test]
9093    fn teardown_rejects_a_stale_generation_tag() {
9094        let mut tracker = OptiForkGenerationTracker::default();
9095        let g0 = tracker.reserve().unwrap();
9096        tracker.retire(g0).unwrap();
9097        let err = tracker.retire(g0).unwrap_err().to_string();
9098        assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
9099    }
9100}
9101
9102#[cfg(test)]
9103mod draft_graph_fallback_tests {
9104    use super::DraftGraphFallback;
9105
9106    /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
9107    #[test]
9108    fn flip_is_loud_once_and_memoized_after() {
9109        let mut f = DraftGraphFallback::default();
9110        let line = f.mark_greedy("out of memory").expect("first flip must return the warn line");
9111        assert!(line.contains("WARN"), "flip line must be warn-level: {line}");
9112        assert!(line.contains("out of memory"), "flip line must carry the reason: {line}");
9113        assert!(f.greedy_failed());
9114        // re-marking an already-failed graph is the memoization: quiet, still failed.
9115        assert!(f.mark_greedy("out of memory").is_none());
9116        assert!(f.greedy_failed());
9117        // the two graphs' flags are independent (greedy flip leaves sampled capturable).
9118        assert!(!f.sampled_failed());
9119        let line_s = f.mark_sampled("capture unsupported").expect("sampled flip is its own flip");
9120        assert!(line_s.contains("sampled"), "sampled flip names itself: {line_s}");
9121        assert!(f.mark_sampled("capture unsupported").is_none());
9122    }
9123
9124    /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
9125    /// and says so exactly when there was something to reset.
9126    #[test]
9127    fn reset_on_resume_clears_flags_and_logs_once() {
9128        let mut f = DraftGraphFallback::default();
9129        // clean session: resume is silent, nothing to reset.
9130        assert!(f.reset_on_resume().is_none());
9131        f.mark_greedy("oom").unwrap();
9132        f.mark_sampled("oom").unwrap();
9133        let note = f.reset_on_resume().expect("a set flag must produce the reset note");
9134        assert!(note.contains("greedy+sampled"), "note names what was reset: {note}");
9135        assert!(!f.greedy_failed() && !f.sampled_failed(), "both flags cleared");
9136        // and the NEXT failure after a reset is a fresh flip — loud again.
9137        assert!(f.mark_greedy("oom again").is_some());
9138        let note2 = f.reset_on_resume().expect("greedy-only reset");
9139        assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
9140    }
9141
9142    /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
9143    /// they precede a fresh capture attempt whose own failure re-flips loudly.
9144    #[test]
9145    fn shape_change_clears_are_silent() {
9146        let mut f = DraftGraphFallback::default();
9147        f.mark_greedy("oom").unwrap();
9148        f.clear_greedy();
9149        assert!(!f.greedy_failed());
9150        f.mark_sampled("oom").unwrap();
9151        f.clear_sampled();
9152        assert!(!f.sampled_failed());
9153        // after a silent clear there is nothing left for resume to report.
9154        assert!(f.reset_on_resume().is_none());
9155    }
9156}