memra_engine/spec.rs
1//! Qwen3.5 MTP (NextN) greedy speculative decode (research/mtp/MTP-PLAN.md §A/§B/§C/§D).
2//!
3//! Greedy spec decode is MATHEMATICALLY EXACT: the accepted+bonus token stream is token-for-token
4//! identical to plain greedy `generate`. This module provides:
5//! - `mtp_head_forward` (§A, T=1): one NextN draft-token forward.
6//! - `decode_step_t` (§D.3, T=K+1): batched target verify forward, all-column logits.
7//! - `generate_spec` (§B): the draft/verify/accept/rollback orchestrator.
8//! Cache snapshot/rollback lives in cache.rs (§D.4). The MTP head uses its OWN scratch KV (§D.6),
9//! PERSISTENT over the committed sequence (see `MtpScratch`).
10
11use crate::Engine;
12use crate::cache::{Cache, KvLayer};
13use crate::forward::argmax;
14use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer, MtpHead};
15use cudarc::driver::CudaSlice;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18/// Parse the documented `MEMRA_SPEC_REPLAY=1` rollback seam.
19///
20/// Keep this shared with serving admission so `=0` cannot select replay in one
21/// layer while another layer treats it as disabled.
22pub fn spec_replay_env_on(value: Option<&str>) -> bool {
23 value == Some("1")
24}
25
26pub fn spec_replay_env_enabled() -> bool {
27 let value = std::env::var("MEMRA_SPEC_REPLAY").ok();
28 spec_replay_env_on(value.as_deref())
29}
30
31/// One compact, anchor-bounded DSpark supervision record. `tokens[0]` is the anchor at p and
32/// `hidden` is its predecessor carrier h[p-1], matching the live NextN/DSpark pairing. Target
33/// rows p..p+gamma-1 score tokens p+1..p+gamma. They are the full-target softmax's top-k
34/// entries; `target_tail_probs[j]` is the probability mass outside those rows. All flattened
35/// target arrays are `[gamma, top_k]` in row-major order.
36pub struct DsparkAnchorRecord {
37 pub position: usize,
38 pub hidden: Vec<f32>,
39 pub tokens: Vec<u32>,
40 pub target_top_ids: Vec<u32>,
41 pub target_top_logits: Vec<f32>,
42 pub target_top_probs: Vec<f32>,
43 pub target_tail_probs: Vec<f32>,
44}
45
46fn dspark_sparse_softmax_topk(
47 logits: &[f32],
48 top_k: usize,
49 temperature: f32,
50) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>, f32), Box<dyn std::error::Error>> {
51 if logits.is_empty() || top_k == 0 || top_k > logits.len() || temperature <= 0.0 {
52 return Err("invalid DSpark sparse-softmax shape or temperature".into());
53 }
54 if logits.iter().any(|value| !value.is_finite()) {
55 return Err("DSpark target logits contain a non-finite value".into());
56 }
57 let mut ranked: Vec<(u32, f32)> = logits
58 .iter()
59 .copied()
60 .enumerate()
61 .map(|(index, value)| (index as u32, value))
62 .collect();
63 let compare = |left: &(u32, f32), right: &(u32, f32)| {
64 right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
65 };
66 ranked.select_nth_unstable_by(top_k - 1, compare);
67 ranked[..top_k].sort_unstable_by(compare);
68
69 let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
70 let inv_temperature = 1.0f64 / temperature as f64;
71 let denominator: f64 = logits
72 .iter()
73 .map(|value| (((*value - max_logit) as f64) * inv_temperature).exp())
74 .sum();
75 let ids: Vec<u32> = ranked[..top_k].iter().map(|(index, _)| *index).collect();
76 let top_logits: Vec<f32> = ranked[..top_k].iter().map(|(_, value)| *value).collect();
77 let top_probs: Vec<f32> = top_logits
78 .iter()
79 .map(|value| ((((value - max_logit) as f64) * inv_temperature).exp() / denominator) as f32)
80 .collect();
81 let top_mass: f64 = top_probs.iter().map(|value| *value as f64).sum();
82 let tail = (1.0f64 - top_mass).clamp(0.0, 1.0) as f32;
83 Ok((ids, top_logits, top_probs, tail))
84}
85
86fn flatten_dspark_rows<T>(
87 rows: Vec<Option<Vec<T>>>,
88 position: usize,
89 label: &str,
90) -> Result<Vec<T>, Box<dyn std::error::Error>> {
91 let mut flattened = Vec::new();
92 for (slot, row) in rows.into_iter().enumerate() {
93 flattened.extend(
94 row.ok_or_else(|| format!("missing DSpark {label} at {position} slot {slot}"))?,
95 );
96 }
97 Ok(flattened)
98}
99
100/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
101/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
102/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
103/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
104/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
105/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
106/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
107pub(crate) fn spec_hpost() -> bool {
108 static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
109 *H.get_or_init(|| {
110 std::env::var("MEMRA_SPEC_HPOST")
111 .map(|v| v != "0")
112 .unwrap_or(false)
113 })
114}
115
116/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
117/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
118/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
119/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
120/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
121/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
122/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
123/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
124/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
125pub(crate) fn spec_lean() -> bool {
126 static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
127 // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
128 // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
129 // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
130 *L.get_or_init(|| {
131 std::env::var("MEMRA_SPEC_LEAN")
132 .map(|v| v != "0")
133 .unwrap_or(true)
134 })
135}
136
137/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
138/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
139/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
140/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
141/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
142/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
143/// ring — the ring stores raw input columns); every arithmetic kernel is the same one the
144/// t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
145/// t-loop == chained T=1 steps);
146/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
147/// pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
148/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
149pub(crate) fn spec_m2() -> bool {
150 static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
151 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
152 // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
153 // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
154 // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
155 *M.get_or_init(|| {
156 std::env::var("MEMRA_SPEC_M2")
157 .map(|v| v != "0")
158 .unwrap_or(true)
159 })
160}
161pub(crate) fn spec_stream() -> bool {
162 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
163 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
164}
165pub(crate) fn spec_stream_m() -> usize {
166 static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
167 *M.get_or_init(|| {
168 std::env::var("MEMRA_SPEC_STREAM_M")
169 .ok()
170 .and_then(|v| v.parse().ok())
171 .unwrap_or(4)
172 })
173}
174pub(crate) fn spec_devacc() -> bool {
175 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
176 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
177}
178
179/// `t_pred0` for the `MEMRA_DEBUG_SPEC` per-round print, sampled-safe.
180///
181/// `generate_spec_inner2` fills its `preds` vector ONLY on the greedy path (`if !sampled`), and
182/// the per-round debug print was the sole consumer in the sampled arm: `t_pred(0)` survives round
183/// 0 (`base == 0` returns `last_pred`) and from round 1 (`base == 1`, a pending bonus) indexes an
184/// EMPTY vector — `index out of bounds: the len is 0 but the index is 0`, in the GPU worker
185/// thread, which then respawns and reloads weights while the request dies. So any sampled spec
186/// request longer than one round used to kill the worker whenever `MEMRA_DEBUG_SPEC` was set:
187/// the flag crashed precisely the regime it exists to investigate.
188///
189/// Fixed at the print site, not inside the closure, so the greedy accept walk keeps its strict
190/// indexing (an out-of-range pred there is a real bug and must still be loud).
191fn debug_t_pred0(sampled: bool, base: usize, last_pred: u32, preds: &[u32]) -> String {
192 if base == 0 {
193 return last_pred.to_string();
194 }
195 match preds.get(base - 1) {
196 Some(p) => p.to_string(),
197 // sampled: the greedy per-column argmax was never run for this round.
198 None => {
199 debug_assert!(
200 sampled,
201 "greedy spec: preds[{}] missing at base {base}",
202 base - 1
203 );
204 "n/a".to_string()
205 }
206 }
207}
208
209/// `MEMRA_SKEY_PROBE=1` — sampled-draft-graph key probe (lane/graph-s-key-exactness-20260819).
210///
211/// Reports, per burst and per round, which draft chain the sampled arm chose and under which
212/// filter regime, plus the ONE observable that separates a legal filtered draft from a stale
213/// pure-temp graph replayed under filters: an accept test whose gathered `q` is exactly 0.
214/// A draft token sampled from the FILTERED softmax can never gather q=0 (it was drawn from the
215/// kept set), so `q=0` in the verify means the draft came from a distribution the verify does
216/// not believe in — and `u * 0 < p` then accepts it unconditionally.
217///
218/// Its own env var, deliberately NOT `MEMRA_DEBUG_SPEC`: that flag panicked the GPU worker on
219/// any sampled spec request past round 0 until this lane fixed it (§2 of the bank note).
220pub(crate) fn skey_probe() -> bool {
221 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
222 *ON.get_or_init(|| std::env::var("MEMRA_SKEY_PROBE").as_deref() == Ok("1"))
223}
224
225/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
226/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
227/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
228/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
229/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
230/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
231/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
232/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
233/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
234pub trait SpecConstraint {
235 /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
236 /// masked argmax).
237 fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
238 /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
239 fn mask_words(&mut self) -> Result<Vec<u32>, String>;
240 /// Is `tok` consumable in the CURRENT state?
241 fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
242 /// Advance the state with an emitted token.
243 fn consume(&mut self, tok: u32) -> Result<(), String>;
244
245 // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
246 // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
247 // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
248 // loose, research/constrained-full-20260803). These three methods let the engine mask the
249 // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
250 // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
251 // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
252 // stays the correctness backstop and the emitted stream is unchanged by construction
253 // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
254 // argmax; a cut slot is recomputed as the masked argmax either way).
255 // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
256
257 /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
258 /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
259 fn draft_mask_enabled(&self) -> bool {
260 false
261 }
262 /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
263 /// slot. Called once per spec round, before the first draft position.
264 fn draft_begin(&mut self) -> Result<(), String> {
265 Ok(())
266 }
267 /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
268 /// for the draft position about to be sampled. `None` = draft masking off (no-op).
269 fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
270 Ok(None)
271 }
272 /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
273 /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
274 /// engine stops drafting; the token already pushed still goes through verify.
275 fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
276 Ok(false)
277 }
278}
279
280/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
281/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
282/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
283/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
284/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
285/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
286/// verify emits the masked argmax as usual).
287fn upload_draft_mask(
288 e: &Engine,
289 c: &mut dyn SpecConstraint,
290 dst: &mut CudaSlice<u32>,
291 d2t: Option<&Vec<u32>>,
292 d_vocab: usize,
293 words: usize,
294) -> Result<bool, Box<dyn std::error::Error>> {
295 let Some(tw) = c
296 .draft_mask_words()
297 .map_err(|e2| format!("constraint: {e2}"))?
298 else {
299 return Ok(false);
300 };
301 let bit = |t: usize| -> bool {
302 let w = t >> 5;
303 w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
304 };
305 let mut buf = vec![0u32; words];
306 match d2t {
307 // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
308 Some(map) => {
309 for (i, &t) in map.iter().enumerate().take(d_vocab) {
310 if bit(t as usize) {
311 buf[i >> 5] |= 1u32 << (i & 31);
312 }
313 }
314 }
315 // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
316 // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
317 None => {
318 let n = tw.len().min(words);
319 buf[..n].copy_from_slice(&tw[..n]);
320 }
321 }
322 if buf.iter().all(|w| *w == 0) {
323 return Ok(false);
324 }
325 e.htod_u32_into(dst, &buf)?;
326 Ok(true)
327}
328
329/// Keep the full token-embedding table in host memory and upload only the rows needed by each
330/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
331/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
332/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
333pub(crate) fn spec_host_embd() -> bool {
334 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
335 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
336}
337
338/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
339/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
340/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
341/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
342/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
343/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
344/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
345/// run-spec K=1..8 + acceptance identity arbitrate e2e).
346pub(crate) fn spec_fused_t() -> bool {
347 static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
348 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
349 // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
350 // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
351 *F.get_or_init(|| {
352 std::env::var("MEMRA_SPEC_FUSED_T")
353 .map(|v| v != "0")
354 .unwrap_or(true)
355 })
356}
357
358/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
359/// Only call this on such buffers — the lean contract is "identical bytes by construction".
360fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
361 if spec_lean() { e.uninit(n) } else { e.zeros(n) }
362}
363
364/// Scratch KV for the MTP block (one full-attn layer).
365///
366/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
367/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
368/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
369/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
370/// engine's "mtp_update" design). Entries come from two sources:
371/// - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
372/// hidden chain-approximate — the reference engine accepts the same);
373/// - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
374/// from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
375/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
376/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
377/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
378/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
379/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
380/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
381/// committed row across turns (the predecessor-pairing seed + fill anchor).
382/// Per-request sampling config for the sampled-spec serve path.
383#[derive(Clone, Copy, Debug)]
384pub struct SpecSampling {
385 pub temp: f32,
386 pub seed: u64,
387 pub top_k: i32, // 0 = off
388 pub top_p: f32, // 1.0 = off
389 pub min_p: f32, // 0.0 = off
390 pub penalty_last_n: usize, // 0 = penalties off
391 pub penalty_repeat: f32,
392 pub penalty_freq: f32,
393 pub penalty_present: f32,
394}
395
396/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
397/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
398pub const SPEC_TELEM_POS: usize = 8;
399
400/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
401/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
402/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
403/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
404/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
405/// in NEITHER drafted nor accepted.
406#[derive(Clone, Copy, Default, Debug)]
407pub struct SpecTelemetry {
408 /// verify rounds completed (a round-stream burst counts each of its M rounds).
409 pub rounds: u64,
410 /// tokens drafted / accepted across all rounds.
411 pub drafted: u64,
412 pub accepted: u64,
413 /// how often draft position j (0-based within a round's chain) was offered / accepted.
414 /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
415 /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
416 /// arrays cover the standard-path rounds only and their sums may undercount the totals.
417 pub pos_drafted: [u64; SPEC_TELEM_POS],
418 pub pos_accepted: [u64; SPEC_TELEM_POS],
419}
420
421impl SpecTelemetry {
422 /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
423 /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
424 /// a wrapped counter.
425 pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
426 let mut d = SpecTelemetry {
427 rounds: self.rounds.saturating_sub(prev.rounds),
428 drafted: self.drafted.saturating_sub(prev.drafted),
429 accepted: self.accepted.saturating_sub(prev.accepted),
430 ..Default::default()
431 };
432 for j in 0..SPEC_TELEM_POS {
433 d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
434 d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
435 }
436 d
437 }
438 /// Fieldwise `self += d` — the worker's per-model aggregation.
439 pub fn merge(&mut self, d: &SpecTelemetry) {
440 self.rounds += d.rounds;
441 self.drafted += d.drafted;
442 self.accepted += d.accepted;
443 for j in 0..SPEC_TELEM_POS {
444 self.pos_drafted[j] += d.pos_drafted[j];
445 self.pos_accepted[j] += d.pos_accepted[j];
446 }
447 }
448
449 /// Mean accepted draft-prefix length per verify round (tau).
450 pub fn tau(&self) -> f64 {
451 if self.rounds > 0 {
452 self.accepted as f64 / self.rounds as f64
453 } else {
454 0.0
455 }
456 }
457}
458
459/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
460/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
461/// launch, synchronization, allocation, or ordering dependency to the numeric path.
462struct SpecTelemetryCounters {
463 rounds: AtomicU64,
464 drafted: AtomicU64,
465 accepted: AtomicU64,
466 pos_drafted: [AtomicU64; SPEC_TELEM_POS],
467 pos_accepted: [AtomicU64; SPEC_TELEM_POS],
468}
469
470impl Default for SpecTelemetryCounters {
471 fn default() -> Self {
472 Self {
473 rounds: AtomicU64::new(0),
474 drafted: AtomicU64::new(0),
475 accepted: AtomicU64::new(0),
476 pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
477 pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
478 }
479 }
480}
481
482impl SpecTelemetryCounters {
483 fn record_round(&self, drafted: usize, accepted: usize) {
484 debug_assert!(accepted <= drafted);
485 self.rounds.fetch_add(1, Ordering::Relaxed);
486 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
487 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
488 for counter in self.pos_drafted.iter().take(drafted) {
489 counter.fetch_add(1, Ordering::Relaxed);
490 }
491 for counter in self.pos_accepted.iter().take(accepted) {
492 counter.fetch_add(1, Ordering::Relaxed);
493 }
494 }
495
496 /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
497 /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
498 fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
499 self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
500 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
501 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
502 }
503
504 fn snapshot(&self) -> SpecTelemetry {
505 SpecTelemetry {
506 rounds: self.rounds.load(Ordering::Relaxed),
507 drafted: self.drafted.load(Ordering::Relaxed),
508 accepted: self.accepted.load(Ordering::Relaxed),
509 pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
510 pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
511 }
512 }
513}
514
515pub struct SpecSession {
516 pub(crate) cache: Cache,
517 pub(crate) scratch: MtpScratch,
518 /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
519 /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
520 /// session must count them. Callers render output from this, not from their own echo.
521 pub committed: Vec<u32>,
522 /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
523 pub(crate) last_h: Option<CudaSlice<f32>>,
524 /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
525 /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
526 /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
527 pub next_pred: Option<u32>,
528 /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
529 /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
530 pub sctr: u32,
531 pub uctr: u32,
532 /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
533 /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
534 /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
535 /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
536 /// research/spec-serving-20260801). None before the first turn; error paths drop it
537 /// (next burst recaptures — serve retires errored sessions anyway).
538 pub(crate) draft_ctx: Option<DraftGraphCtx>,
539 /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
540 /// emitted by the last round but NOT committed to the caches. The old tail committed it with
541 /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
542 /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
543 /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
544 /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
545 /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
546 /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
547 /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
548 /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
549 /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
550 pub pending_tok: Option<u32>,
551 /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
552 /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
553 /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
554 /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
555 pub(crate) turn_ckpt: Option<SpecCheckpoint>,
556 /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
557 /// accounting the loop already does — no syncs, no allocation. NOTE a
558 /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
559 /// diff with [`SpecTelemetry::delta_since`] around each burst.
560 telem: SpecTelemetryCounters,
561 /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
562 /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
563 /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
564 /// prime, result lands in `boundary_capture`.
565 pub capture_at: Option<usize>,
566 /// The capture the last cold prime produced (see [`SpecBoundaryCapture`]). Worker takes it
567 /// post-burst to assemble the prefix entry. A failed capture is silent, like `turn_ckpt` —
568 /// publication just isn't available for that request.
569 pub boundary_capture: Option<SpecBoundaryCapture>,
570}
571impl SpecSession {
572 /// Context capacity of the session's caches (the server's ContextFull guard).
573 pub fn cache_max_ctx(&self) -> usize {
574 self.cache.max_ctx
575 }
576 /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
577 /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
578 /// those rows are append-only for the session's lifetime (rollbacks never truncate below
579 /// the prime boundary), so no copy was taken at prime time.
580 pub fn cache_ref(&self) -> &Cache {
581 &self.cache
582 }
583 /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
584 /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
585 /// like the trunk KV — draft rows below the prompt end are append-only for the
586 /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
587 /// committed length, never below the prime boundary, and the true-hidden refresh
588 /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
589 /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
590 /// prefix-addressable; the prefix cache already refuses that class end to end).
591 pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
592 if self.scratch.kv.ring.is_some() {
593 return None;
594 }
595 Some((
596 &self.scratch.kv.k,
597 &self.scratch.kv.v,
598 self.scratch.kv.k_tok_bytes,
599 self.scratch.kv.v_tok_bytes,
600 ))
601 }
602 /// Snapshot the session's process-local acceptance counters for per-burst diffing.
603 pub fn telemetry(&self) -> SpecTelemetry {
604 self.telem.snapshot()
605 }
606 /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
607 /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
608 /// `spec_rewind_to_checkpoint`.
609 pub fn rewind_pos(&self) -> Option<usize> {
610 self.turn_ckpt.as_ref().map(|c| c.pos)
611 }
612 /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
613 pub fn rewind_is_resident(&self) -> bool {
614 self.turn_ckpt.as_ref().is_some_and(|ckpt| {
615 self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
616 })
617 }
618 /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
619 /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
620 /// session has never run a turn and has no prediction to hand over.
621 pub fn demote_ready(&self) -> bool {
622 self.pending_tok.is_none() && self.next_pred.is_some()
623 }
624 /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
625 pub fn has_pending(&self) -> bool {
626 self.pending_tok.is_some()
627 }
628 /// Committed row count == cache rows (the session invariant), for the caller's own
629 /// `fed`-length cross-check at a handoff boundary.
630 pub fn committed_len(&self) -> usize {
631 self.committed.len()
632 }
633 /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
634 /// cache + next-token prediction to the plain batched-decode path.
635 ///
636 /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
637 /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
638 /// tokenwise prime of the same `committed` sequence would have left it (that is the
639 /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
640 /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
641 /// committed row — and verify-column logits are bit-identical to plain decode's logits at
642 /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
643 /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
644 /// a state indistinguishable from one the batched path produced itself: the batched tick
645 /// emits `next_pred`, feeds it into this same cache, and decodes on.
646 ///
647 /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
648 /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
649 /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
650 /// path would silently skip a token.
651 ///
652 /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
653 /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
654 /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
655 /// would mean an `mtp_kv_fill` over the whole committed history).
656 pub fn into_demoted(self) -> Option<(Cache, u32)> {
657 if self.pending_tok.is_some() {
658 return None;
659 }
660 let np = self.next_pred?;
661 debug_assert_eq!(
662 self.cache.pos,
663 self.committed.len(),
664 "demotion handoff: cache rows != committed tokens"
665 );
666 Some((self.cache, np))
667 }
668 /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
669 /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
670 /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
671 /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
672 pub fn reset_graph_fallback_on_resume(&mut self) {
673 if let Some(line) = self
674 .draft_ctx
675 .as_mut()
676 .and_then(|c| c.failed.reset_on_resume())
677 {
678 eprintln!("{line}");
679 }
680 }
681}
682
683/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
684///
685/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
686/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
687/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
688/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
689/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
690/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
691///
692/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
693/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
694/// position index, so it must be a real device COPY — that copy is the entire reason a spec
695/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
696/// below the boundary were written by this turn's fill and are never revisited (the per-round
697/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
698/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
699/// predecessor-pairing anchor the next prime's fill reads for its first row.
700///
701/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
702pub(crate) struct SpecCheckpoint {
703 snap: crate::cache::CacheSnapshot,
704 /// Committed length at the boundary (== cache.pos there, the session invariant).
705 pos: usize,
706 /// Pre-output_norm hidden of row `pos - 1`.
707 last_h: CudaSlice<f32>,
708}
709
710/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
711/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
712/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
713/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
714/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
715/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
716/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
717/// so the worker slices those from the live caches post-burst instead of copying at prime time.
718pub struct SpecBoundaryCapture {
719 pub snap: crate::cache::CacheSnapshot,
720 /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
721 pub pos: usize,
722 /// Full-vocab logits after the prefix prime — the entry's boundary logits.
723 pub logits: Vec<f32>,
724 /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
725 /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
726 /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
727 /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
728 pub last_h: Vec<f32>,
729}
730
731/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
732/// spec boundary capture carries for later restored-session fills. Failure is silent
733/// (`turn_ckpt` convention): the capture publishes without an anchor.
734fn capture_boundary_hidden(
735 e: &Engine,
736 h_rows: &CudaSlice<f32>,
737 pos: usize,
738 n_embd: usize,
739) -> Vec<f32> {
740 if pos == 0 || h_rows.len() < pos * n_embd {
741 return Vec::new();
742 }
743 let Ok(mut row) = e.uninit(n_embd) else {
744 return Vec::new();
745 };
746 if e.copy_view_into(
747 &mut row,
748 0,
749 &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
750 n_embd,
751 )
752 .is_err()
753 {
754 return Vec::new();
755 }
756 e.dtoh(&row).unwrap_or_default()
757}
758
759/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
760/// Default ON: the token a burst emits at its own boundary is drawn from the request's
761/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
762/// every boundary) without touching greedy, which is byte-unaffected either way.
763pub fn spec_sampled_boundary_on() -> bool {
764 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
765 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
766}
767
768/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
769/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
770/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
771/// restores the pre-lane posture (each burst restarts the window from its own prompt
772/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
773/// must keep refusing penalized sampled prefix-cache restores, because the restored
774/// session's continuation burst is handed no prompt slice at all.
775pub fn spec_pen_session_on() -> bool {
776 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
777 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
778}
779
780/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
781/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
782/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
783/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
784/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
785/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
786pub fn spec_restore_republish_on() -> bool {
787 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
788 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
789}
790
791/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
792/// the argmax the pre-lane code would have emitted from the same row. This is how the
793/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
794fn spec_boundary_trace() -> bool {
795 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
796 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
797}
798
799/// llama-parity floor for the penalty window when the request does not ask for a bigger
800/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = usize::MAX` for any
801/// non-identity penalty, so this floor only matters to explicit small windows and to the
802/// CLI env path.
803const PEN_WINDOW_FLOOR: usize = 64;
804
805/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
806/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
807/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
808/// p column, the bonus column). The serve API arms `penalty_last_n = usize::MAX` for ANY
809/// non-identity penalty — "the whole context", llama's `repeat_last_n = -1` — so an
810/// uncapped session window would put a 128k-token history through that kernel: ~1.7e10
811/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
812/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
813/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
814/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
815/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
816/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
817const PEN_WINDOW_MAX: usize = 8192;
818
819/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
820/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
821/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
822/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
823/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
824/// client actually asked us to penalize, where the pre-lane code had NOTHING.
825fn pen_window_seed(
826 session_committed: &[u32],
827 burst_prompt: &[u32],
828 penalty_last_n: usize,
829) -> Vec<u32> {
830 let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
831 let take_prompt = burst_prompt.len().min(win);
832 let take_sess = (win - take_prompt).min(session_committed.len());
833 let mut hist = Vec::with_capacity(take_sess + take_prompt);
834 hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
835 hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
836 hist
837}
838
839/// Draw a BOUNDARY token from the target distribution the request asked for
840/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
841/// every burst boundary".
842///
843/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
844/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
845/// row after the last committed token on a continuation burst; the prefix-cache entry's
846/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
847/// regimes, so a sampled stream took a greedy token once per burst — measured, not
848/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
849/// customer asked for a sampled token, so this draws one.
850///
851/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
852/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
853/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
854/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
855/// composition means `sample_check`'s distributional oracle covers this draw too, and the
856/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
857///
858/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
859/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
860/// stream the accept walk uses — never a second, independently seeded stream (which would be
861/// a new distributional bug: two streams from one seed correlate wherever their counters
862/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
863/// to the cold session's own first draw from the same logits row, which is what preserves the
864/// sampled-hit lane's per-seed hit==cold byte identity.
865#[allow(clippy::too_many_arguments)]
866pub fn sample_boundary_token_dev(
867 e: &Engine,
868 logits: &CudaSlice<f32>,
869 n_vocab: usize,
870 sp: &SpecSampling,
871 pen_hist: &[u32],
872 sctr: &mut u32,
873 site: &str,
874) -> Result<u32, Box<dyn std::error::Error>> {
875 debug_assert!(
876 sp.temp > 0.0,
877 "boundary sampling is the sampled regime only"
878 );
879 // Own copy: penalize_logits mutates in place and the caller's row is live state
880 // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
881 let mut col = e.zeros(n_vocab)?;
882 e.copy_into(&mut col, 0, logits, n_vocab)?;
883 let pen_on = sp.penalty_last_n > 0
884 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
885 if pen_on && !pen_hist.is_empty() {
886 // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
887 let w0 = pen_hist
888 .len()
889 .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
890 let hist = &pen_hist[w0..];
891 let hd = e.htod_u32_v(hist)?;
892 e.penalize_logits(
893 &mut col,
894 &hd,
895 hist.len(),
896 sp.penalty_repeat,
897 sp.penalty_freq,
898 sp.penalty_present,
899 n_vocab,
900 )?;
901 }
902 let rows0 = e.htod_i32(&[0])?;
903 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
904 e.filter_stats(
905 &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
906 sp.top_p, sp.min_p,
907 )?;
908 let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
909 let mut perturb = e.zeros(n_vocab)?;
910 e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
911 *sctr = sctr.wrapping_add(1);
912 let td = e.argmax_token_device(&perturb, n_vocab)?;
913 let tok = e.dtoh_u32_one(&td)?;
914 if spec_boundary_trace() {
915 // the pre-lane token, from the SAME row, so the deviation rate is measurable.
916 let raw = e.argmax_token_device(logits, n_vocab)?;
917 let greedy = e.dtoh_u32_one(&raw)?;
918 eprintln!(
919 "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
920 deviates={} temp={} sctr={}",
921 (tok != greedy) as u8,
922 sp.temp,
923 sctr.wrapping_sub(1),
924 );
925 }
926 Ok(tok)
927}
928
929/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
930/// host `Vec<f32>`).
931#[allow(clippy::too_many_arguments)]
932pub fn sample_boundary_token(
933 e: &Engine,
934 logits: &[f32],
935 sp: &SpecSampling,
936 pen_hist: &[u32],
937 sctr: &mut u32,
938 site: &str,
939) -> Result<u32, Box<dyn std::error::Error>> {
940 let n_vocab = logits.len();
941 let d = e.htod(logits)?;
942 sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
943}
944
945struct SpecPipeTraceClock {
946 pair: usize,
947 started: std::time::Instant,
948}
949
950#[derive(Clone)]
951struct SpecPipeTraceCtx {
952 clock: std::sync::Arc<SpecPipeTraceClock>,
953 round: usize,
954 lane: usize,
955}
956
957struct SpecPipeTraceMarker {
958 trace: SpecPipeTraceCtx,
959 phase: &'static str,
960 edge: &'static str,
961 slot: Option<usize>,
962}
963
964unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
965 let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
966 let lane = if marker.trace.lane == 0 { "A" } else { "B" };
967 let slot = marker
968 .slot
969 .map(|v| v.to_string())
970 .unwrap_or_else(|| "-".into());
971 let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
972 use std::io::Write as _;
973 let stderr = std::io::stderr();
974 let mut stderr = stderr.lock();
975 let _ = writeln!(
976 stderr,
977 "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
978 slot={slot} t_ms={t_ms:.3}",
979 marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
980 );
981}
982
983fn enqueue_spec_pipe_trace_marker(
984 stream: &cudarc::driver::CudaStream,
985 trace: Option<&SpecPipeTraceCtx>,
986 phase: &'static str,
987 edge: &'static str,
988 slot: Option<usize>,
989) -> Result<(), Box<dyn std::error::Error>> {
990 let Some(trace) = trace else {
991 return Ok(());
992 };
993 let marker = Box::new(SpecPipeTraceMarker {
994 trace: trace.clone(),
995 phase,
996 edge,
997 slot,
998 });
999 let raw = Box::into_raw(marker);
1000 let result = unsafe {
1001 cudarc::driver::result::stream::launch_host_function(
1002 stream.cu_stream(),
1003 spec_pipe_trace_marker,
1004 raw.cast(),
1005 )
1006 };
1007 if let Err(err) = result {
1008 unsafe {
1009 drop(Box::from_raw(raw));
1010 }
1011 return Err(err.into());
1012 }
1013 Ok(())
1014}
1015
1016#[derive(Default)]
1017struct SpecPipeProgress {
1018 setup_done: [bool; 2],
1019 draft_done: [usize; 2],
1020 stage0_done: [usize; 2],
1021 verify_done: [usize; 2],
1022 accept_done: [usize; 2],
1023 finished: [bool; 2],
1024 aborted: bool,
1025}
1026
1027/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
1028/// keeps its existing call stack and round locals; this object only orders phase entry. The
1029/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
1030/// cannot be interleaved by the two host threads.
1031struct SpecPipeSync {
1032 progress: std::sync::Mutex<SpecPipeProgress>,
1033 changed: std::sync::Condvar,
1034 primary: std::sync::Mutex<()>,
1035 trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
1036}
1037
1038impl SpecPipeSync {
1039 fn new() -> Self {
1040 static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1041 let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
1042 std::sync::Arc::new(SpecPipeTraceClock {
1043 pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1044 started: std::time::Instant::now(),
1045 })
1046 });
1047 Self {
1048 progress: std::sync::Mutex::new(SpecPipeProgress::default()),
1049 changed: std::sync::Condvar::new(),
1050 primary: std::sync::Mutex::new(()),
1051 trace,
1052 }
1053 }
1054}
1055
1056#[derive(Clone)]
1057struct SpecPipeLane {
1058 sync: std::sync::Arc<SpecPipeSync>,
1059 lane: usize,
1060}
1061
1062impl SpecPipeLane {
1063 fn peer(&self) -> usize {
1064 1 - self.lane
1065 }
1066
1067 fn aborted() -> Box<dyn std::error::Error> {
1068 "paired speculative peer aborted".into()
1069 }
1070
1071 fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
1072 self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
1073 clock: clock.clone(),
1074 round,
1075 lane: self.lane,
1076 })
1077 }
1078
1079 fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
1080 let mut p = self.sync.progress.lock().unwrap();
1081 while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
1082 p = self.sync.changed.wait(p).unwrap();
1083 }
1084 if p.aborted {
1085 Err(Self::aborted())
1086 } else {
1087 Ok(())
1088 }
1089 }
1090
1091 fn setup_end(&self) {
1092 let mut p = self.sync.progress.lock().unwrap();
1093 p.setup_done[self.lane] = true;
1094 self.sync.changed.notify_all();
1095 }
1096
1097 fn draft_begin(
1098 &self,
1099 round: usize,
1100 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1101 let peer = self.peer();
1102 let mut p = self.sync.progress.lock().unwrap();
1103 loop {
1104 if p.aborted {
1105 return Err(Self::aborted());
1106 }
1107 let setup_ready =
1108 (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
1109 let prior_ready = p.accept_done[self.lane] >= round
1110 && (p.accept_done[peer] >= round || p.finished[peer]);
1111 let turn_ready = if self.lane == 0 {
1112 true
1113 } else {
1114 p.draft_done[0] > round || p.finished[0]
1115 };
1116 if setup_ready && prior_ready && turn_ready {
1117 break;
1118 }
1119 p = self.sync.changed.wait(p).unwrap();
1120 }
1121 drop(p);
1122 Ok(self.sync.primary.lock().unwrap())
1123 }
1124
1125 fn draft_end(&self, round: usize) {
1126 let mut p = self.sync.progress.lock().unwrap();
1127 p.draft_done[self.lane] = round + 1;
1128 self.sync.changed.notify_all();
1129 }
1130
1131 /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
1132 /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
1133 fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
1134 let peer = self.peer();
1135 let mut p = self.sync.progress.lock().unwrap();
1136 loop {
1137 if p.aborted {
1138 return Err(Self::aborted());
1139 }
1140 let ready = if self.lane == 0 {
1141 p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
1142 } else {
1143 p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
1144 };
1145 if ready {
1146 return Ok(self.lane == 0 || p.finished[peer]);
1147 }
1148 p = self.sync.changed.wait(p).unwrap();
1149 }
1150 }
1151
1152 fn stage0_end(&self, round: usize) {
1153 let mut p = self.sync.progress.lock().unwrap();
1154 p.stage0_done[self.lane] = round + 1;
1155 self.sync.changed.notify_all();
1156 }
1157
1158 /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
1159 /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
1160 fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
1161 let mut p = self.sync.progress.lock().unwrap();
1162 while !p.aborted
1163 && !(p.stage0_done[self.lane] > round
1164 && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
1165 {
1166 p = self.sync.changed.wait(p).unwrap();
1167 }
1168 if p.aborted {
1169 Err(Self::aborted())
1170 } else {
1171 Ok(())
1172 }
1173 }
1174
1175 fn verify_end(&self, round: usize) {
1176 let mut p = self.sync.progress.lock().unwrap();
1177 p.verify_done[self.lane] = round + 1;
1178 self.sync.changed.notify_all();
1179 }
1180
1181 fn accept_begin(
1182 &self,
1183 round: usize,
1184 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1185 let mut p = self.sync.progress.lock().unwrap();
1186 loop {
1187 if p.aborted {
1188 return Err(Self::aborted());
1189 }
1190 let ready = if self.lane == 0 {
1191 p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
1192 } else {
1193 p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
1194 };
1195 if ready {
1196 break;
1197 }
1198 p = self.sync.changed.wait(p).unwrap();
1199 }
1200 drop(p);
1201 Ok(self.sync.primary.lock().unwrap())
1202 }
1203
1204 fn accept_end(&self, round: usize) {
1205 let mut p = self.sync.progress.lock().unwrap();
1206 p.accept_done[self.lane] = round + 1;
1207 self.sync.changed.notify_all();
1208 }
1209
1210 fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
1211 self.sync.primary.lock().unwrap()
1212 }
1213
1214 fn finish(&self, failed: bool) {
1215 let mut p = self.sync.progress.lock().unwrap();
1216 p.finished[self.lane] = true;
1217 p.aborted |= failed;
1218 self.sync.changed.notify_all();
1219 }
1220}
1221
1222struct SpecPipeFinish<'a> {
1223 lane: &'a SpecPipeLane,
1224 closed: bool,
1225}
1226
1227impl<'a> SpecPipeFinish<'a> {
1228 fn new(lane: &'a SpecPipeLane) -> Self {
1229 Self {
1230 lane,
1231 closed: false,
1232 }
1233 }
1234
1235 fn close(&mut self, failed: bool) {
1236 self.lane.finish(failed);
1237 self.closed = true;
1238 }
1239}
1240
1241impl Drop for SpecPipeFinish<'_> {
1242 fn drop(&mut self) {
1243 if !self.closed {
1244 self.lane.finish(true);
1245 }
1246 }
1247}
1248
1249/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
1250/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
1251/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
1252/// binds that context before touching the session, joins before returning, and never aliases the
1253/// pointer. Keep this exception local to the experimental pair call instead of marking the public
1254/// session type Send.
1255struct SpecPipeSessionPtr(*mut SpecSession);
1256
1257unsafe impl Send for SpecPipeSessionPtr {}
1258
1259impl SpecPipeSessionPtr {
1260 unsafe fn get_mut(&mut self) -> &mut SpecSession {
1261 unsafe { &mut *self.0 }
1262 }
1263}
1264
1265/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
1266/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
1267/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
1268/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
1269/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
1270/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
1271/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
1272/// so the eager fallback doesn't pay a doomed capture attempt every burst.
1273/// Capture identity of the parked SAMPLED draft graph (`DraftGraphCtx::graph_s`).
1274///
1275/// EXACTNESS, not perf (lane/graph-s-key-exactness-20260819; receipts
1276/// `research/spec-cache-20260818/GRAPH-S-KEY.md`). Two classes of field live here, both
1277/// load-bearing:
1278///
1279/// - **Baked constants.** `seed` and `temp` are capture-time constants INSIDE the graph and `k`
1280/// sizes the q slots its replays write. A resumed request changing any of them must recapture.
1281/// This is all the key used to carry.
1282/// - **Regime fields.** `top_k`/`top_p`/`min_p`/`pen_on` are not baked, but they decide whether
1283/// the captured graph is a legal draft chain AT ALL. The in-graph draw is one gumbel-max over
1284/// the RAW softmax (`gumbel_perturb_ctr`, unfiltered by construction), while the verify builds
1285/// the accept test's `q` from `filter_stats(q_slots, top_k, top_p, min_p)`. If those disagree
1286/// the accept test evaluates a distribution the draft was never sampled from: a draft token
1287/// below the filter threshold gathers `q = 0` (`softmax_gather_filtered_f32`,
1288/// `cu/spec_sample.cu`) and `u * 0 < p` accepts it UNCONDITIONALLY.
1289///
1290/// Omitting the regime fields was reachable — not through the prefix-cache spec restore (that
1291/// path is greedy-only, `memra-server` `spec_restore_convertible`), but through WHOLE-SESSION
1292/// spec reuse: a parked `SpecSession` carries this `DraftGraphCtx`, and the pool-resume probe
1293/// applies no sampler predicate at all. Turn 1 pure-temp parks a graph; turn 2 of the same
1294/// conversation, same explicit seed and temperature, adds `top_p`/`top_k` and inherits it.
1295#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1296pub(crate) struct SampledGraphKey {
1297 seed: u64,
1298 temp_bits: u32,
1299 k: usize,
1300 top_k: i32,
1301 top_p_bits: u32,
1302 min_p_bits: u32,
1303 pen_on: bool,
1304}
1305
1306impl SampledGraphKey {
1307 pub(crate) fn new(
1308 seed: u64,
1309 temp: f32,
1310 k: usize,
1311 top_k: i32,
1312 top_p: f32,
1313 min_p: f32,
1314 pen_on: bool,
1315 ) -> Self {
1316 SampledGraphKey {
1317 seed,
1318 temp_bits: temp.to_bits(),
1319 k,
1320 top_k,
1321 top_p_bits: top_p.to_bits(),
1322 min_p_bits: min_p.to_bits(),
1323 pen_on,
1324 }
1325 }
1326
1327 /// The one regime the in-graph sampled chain may stand in for the eager one: nothing but
1328 /// temperature shapes `q`. Computed FROM THE KEY so the capture guard, the launch guard and
1329 /// the key can never drift apart (they were three separate expressions before this lane, and
1330 /// the launch site simply forgot to ask).
1331 pub(crate) fn pure_temp(&self) -> bool {
1332 self.top_k == 0
1333 && f32::from_bits(self.top_p_bits) >= 1.0
1334 && f32::from_bits(self.min_p_bits) <= 0.0
1335 && !self.pen_on
1336 }
1337}
1338
1339pub(crate) struct DraftGraphCtx {
1340 g_tok: CudaSlice<u32>,
1341 g_pos: CudaSlice<i32>,
1342 g_seed: CudaSlice<f32>,
1343 g_p: CudaSlice<f32>,
1344 g_ctr: CudaSlice<u32>,
1345 g_q: CudaSlice<f32>,
1346 g_perturb: CudaSlice<f32>,
1347 q_slots: Vec<CudaSlice<f32>>,
1348 /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
1349 /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
1350 /// per-position contents the host re-uploads before each replay (the graph-promote
1351 /// pattern from decode.rs). Empty unless the session drafts under a grammar.
1352 g_dmask: CudaSlice<u32>,
1353 /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
1354 graph_masked: bool,
1355 graph: Option<cudarc::driver::CudaGraph>,
1356 graph_s: Option<cudarc::driver::CudaGraph>,
1357 /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
1358 /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
1359 failed: DraftGraphFallback,
1360 /// Capture identity of `graph_s` — see [`SampledGraphKey`]. `None` iff no sampled graph is
1361 /// parked; a request whose key differs drops the parked graph (and its q slots/keeper).
1362 s_key: Option<SampledGraphKey>,
1363 /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
1364 /// pool addresses the captured graph(s) bake. Without these, the transients return to the
1365 /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
1366 /// co-served session in the worker) reuses those addresses — the persisted graph's replay
1367 /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
1368 /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
1369 /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
1370 /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
1371 keeper: Vec<Box<dyn std::any::Any + Send>>,
1372 keeper_s: Vec<Box<dyn std::any::Any + Send>>,
1373}
1374
1375/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
1376/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
1377///
1378/// Three contracts:
1379/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
1380/// (returned, not printed, so the once-per-flip contract is unit-testable); the caller
1381/// `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
1382/// an already-failed graph returns None (the per-burst memoization that keeps the eager
1383/// fallback from paying a doomed capture attempt every burst).
1384/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
1385/// NEW request gets one fresh capture chance instead of carrying a transient-pressure
1386/// failure for the pool's whole lifetime. Returns the note line only when a flag was
1387/// actually set (quiet on the common clean-resume path).
1388/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1389/// capture attempt whose own failure would re-flip loudly.
1390#[derive(Default)]
1391pub(crate) struct DraftGraphFallback {
1392 greedy: bool,
1393 sampled: bool,
1394}
1395impl DraftGraphFallback {
1396 fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1397 if self.greedy {
1398 return None;
1399 }
1400 self.greedy = true;
1401 Some(format!(
1402 "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1403 ))
1404 }
1405 fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1406 if self.sampled {
1407 return None;
1408 }
1409 self.sampled = true;
1410 Some(format!(
1411 "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1412 ))
1413 }
1414 fn greedy_failed(&self) -> bool {
1415 self.greedy
1416 }
1417 fn sampled_failed(&self) -> bool {
1418 self.sampled
1419 }
1420 fn clear_greedy(&mut self) {
1421 self.greedy = false;
1422 }
1423 fn clear_sampled(&mut self) {
1424 self.sampled = false;
1425 }
1426 /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1427 /// was set (so clean resumes stay quiet).
1428 pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1429 if !self.greedy && !self.sampled {
1430 return None;
1431 }
1432 let which = match (self.greedy, self.sampled) {
1433 (true, true) => "greedy+sampled",
1434 (true, false) => "greedy",
1435 _ => "sampled",
1436 };
1437 self.greedy = false;
1438 self.sampled = false;
1439 Some(format!(
1440 "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1441 ))
1442 }
1443}
1444
1445impl DraftGraphCtx {
1446 fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1447 Ok(DraftGraphCtx {
1448 g_tok: e.alloc_u32_zeroed(1)?,
1449 g_pos: e.htod_i32(&[0])?,
1450 g_seed: e.zeros(n_embd)?,
1451 g_p: e.zeros(1)?,
1452 g_ctr: e.alloc_u32_zeroed(1)?,
1453 g_q: e.zeros(qlen)?,
1454 g_perturb: e.zeros(qlen)?,
1455 q_slots: Vec::new(),
1456 g_dmask: e.alloc_u32_zeroed(1)?,
1457 graph_masked: false,
1458 graph: None,
1459 graph_s: None,
1460 failed: DraftGraphFallback::default(),
1461 s_key: None,
1462 keeper: Vec::new(),
1463 keeper_s: Vec::new(),
1464 })
1465 }
1466}
1467
1468pub(crate) struct MtpScratch {
1469 kv: KvLayer,
1470 /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1471 /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1472 /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1473 /// smaller host-indexed SWA ring instead.
1474 cap: usize,
1475}
1476
1477fn mtp_scratch_layout(
1478 cfg: &memra_gguf::config::ModelConfig,
1479 geom: Option<&crate::hybrid::DraftGeom>,
1480) -> (usize, usize, usize, usize) {
1481 // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1482 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1483 let head_dim_k = cfg.head_dim_k as usize;
1484 let head_dim_v = cfg.head_dim_v as usize;
1485 assert!(
1486 head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1487 "KVQUANT requires head_dim%32==0 (MTP scratch)"
1488 );
1489 let kv_dim_k = head_dim_k * n_head_kv;
1490 let kv_dim_v = head_dim_v * n_head_kv;
1491 // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1492 // policy shared with `MtpScratch::new` so admission scales the same allocation.
1493 let (kbb, vbb) = crate::kv_blk_bytes();
1494 let k_tok_bytes = (kv_dim_k / 32) * kbb;
1495 let v_tok_bytes = (kv_dim_v / 32) * vbb;
1496 (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1497}
1498
1499impl MtpScratch {
1500 fn new(
1501 e: &Engine,
1502 cfg: &memra_gguf::config::ModelConfig,
1503 cap: usize,
1504 geom: Option<&crate::hybrid::DraftGeom>,
1505 ) -> Result<Self, Box<dyn std::error::Error>> {
1506 // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1507 // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1508 // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1509 // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1510 let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
1511 let ring = if crate::cache::swa_ring_on() && cfg.arch.is_step35() {
1512 let window = cfg.step35.as_ref().unwrap().sliding_window as usize;
1513 Some(crate::cache::KvRing::new(
1514 crate::cache::swa_ring_rows(window, cap),
1515 window,
1516 ))
1517 } else {
1518 None
1519 };
1520 let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1521 Ok(MtpScratch {
1522 kv: KvLayer {
1523 k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1524 v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1525 kv_dim_k,
1526 kv_dim_v,
1527 k_tok_bytes,
1528 v_tok_bytes,
1529 len: 0,
1530 ring,
1531 len_d: e.htod_i32(&[0])?,
1532 },
1533 cap,
1534 })
1535 }
1536 /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1537 /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1538 /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1539 fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1540 if self
1541 .kv
1542 .ring
1543 .as_ref()
1544 .is_some_and(|ring| !ring.can_rewind_to(n))
1545 {
1546 return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1547 }
1548 self.kv.len = n;
1549 e.set_i32_one(&mut self.kv.len_d, n as i32)
1550 }
1551
1552 fn can_rewind_to(&self, n: usize) -> bool {
1553 self.kv
1554 .ring
1555 .as_ref()
1556 .is_none_or(|ring| ring.can_rewind_to(n))
1557 }
1558}
1559
1560/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1561/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1562/// full weight reads per round — recomputing columns the verify had already produced
1563/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1564/// to "after the first j verify columns" WITHOUT re-running the trunk:
1565/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1566/// consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1567/// to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1568/// registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1569/// pure-copy ring rebuild.
1570/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1571/// column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1572/// target: j <= t-1).
1573/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1574/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1575struct GdnStash {
1576 qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1577 q_l2: CudaSlice<f32>,
1578 k_l2: CudaSlice<f32>,
1579 v_g: CudaSlice<f32>, // [t, num_v, d_state]
1580 g_log: CudaSlice<f32>,
1581 beta: CudaSlice<f32>, // [t, num_v]
1582}
1583struct VerifyCkpt {
1584 gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1585 cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1586}
1587/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
1588pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
1589
1590impl VerifyCkpt {
1591 fn new(n_layer: usize) -> Self {
1592 VerifyCkpt {
1593 gdn: (0..n_layer).map(|_| None).collect(),
1594 cols: (0..n_layer).map(|_| None).collect(),
1595 }
1596 }
1597}
1598
1599/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
1600/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
1601/// a logical round number.
1602struct VerifyBoundaryTicket {
1603 rt: &'static crate::pp::PpNRt,
1604 caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1605 slot: usize,
1606 pos0: usize,
1607 t: usize,
1608 payload: usize,
1609 n_st: usize,
1610 pipelined: bool,
1611 pp_anatomy: bool,
1612 pp_started: std::time::Instant,
1613 reverse_ms: f64,
1614 stage0_ms: f64,
1615 tx_ms: f64,
1616 trace: Option<SpecPipeTraceCtx>,
1617}
1618
1619/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
1620/// increment-2 controller can also be armed by the server's fresh-process research door.
1621#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1622pub enum OptiForkGateMode {
1623 Disabled,
1624 Hit,
1625 Miss,
1626 Alternate,
1627 Abort,
1628 Controller,
1629}
1630
1631static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1632static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
1633 std::sync::atomic::AtomicU32::new(0);
1634static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1635static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1636static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1637static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1638static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1639static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1640static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1641static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1642static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1643static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1644 std::sync::atomic::AtomicU64::new(0);
1645static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1646 std::sync::atomic::AtomicU64::new(0);
1647static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1648
1649impl OptiForkGateMode {
1650 fn code(self) -> u8 {
1651 match self {
1652 Self::Disabled => 0,
1653 Self::Hit => 1,
1654 Self::Miss => 2,
1655 Self::Alternate => 3,
1656 Self::Abort => 4,
1657 Self::Controller => 5,
1658 }
1659 }
1660
1661 fn configured() -> Self {
1662 match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
1663 1 => Self::Hit,
1664 2 => Self::Miss,
1665 3 => Self::Alternate,
1666 4 => Self::Abort,
1667 5 => Self::Controller,
1668 _ => Self::Disabled,
1669 }
1670 }
1671
1672 fn action(self, generation: u64) -> OptiForkAction {
1673 match self {
1674 Self::Hit => OptiForkAction::Hit,
1675 Self::Miss => OptiForkAction::Miss,
1676 Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
1677 Self::Alternate => OptiForkAction::Miss,
1678 Self::Abort => OptiForkAction::Abort,
1679 Self::Disabled | Self::Controller => {
1680 unreachable!("non-forced mode cannot choose a forced fork action")
1681 }
1682 }
1683 }
1684
1685 fn is_forced(self) -> bool {
1686 matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
1687 }
1688}
1689
1690/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
1691pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
1692 OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
1693}
1694
1695/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
1696/// two-token draft-probability product. Serving can call this only through its explicit
1697/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
1698pub fn set_optipipe_controller_threshold(threshold: f32) {
1699 assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
1700 OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
1701 set_optipipe_gate_mode(OptiForkGateMode::Controller);
1702}
1703
1704#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1705pub struct OptiForkGateStats {
1706 pub attempts: u64,
1707 pub hits: u64,
1708 pub misses: u64,
1709 pub abort_drains: u64,
1710 pub refusals: u64,
1711 pub gate_checks: u64,
1712 pub gate_admits: u64,
1713 pub gate_rejects: u64,
1714 pub reconciles: u64,
1715 pub wasted_draft_tokens: u64,
1716 pub shadow_draft_tokens: u64,
1717 pub breaker_trips: u64,
1718}
1719
1720#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1721pub struct OptiForkStateIdentity {
1722 pub trunk_kv_bytes: usize,
1723 pub recurrent_bytes: usize,
1724 pub scratch_kv_bytes: usize,
1725 pub hidden_bytes: usize,
1726}
1727
1728pub fn reset_optipipe_gate_stats() {
1729 for counter in [
1730 &OPTI_FORK_ATTEMPTS,
1731 &OPTI_FORK_HITS,
1732 &OPTI_FORK_MISSES,
1733 &OPTI_FORK_ABORT_DRAINS,
1734 &OPTI_FORK_REFUSALS,
1735 &OPTI_GATE_CHECKS,
1736 &OPTI_GATE_ADMITS,
1737 &OPTI_GATE_REJECTS,
1738 &OPTI_RECONCILES,
1739 &OPTI_WASTED_DRAFT_TOKENS,
1740 &OPTI_SHADOW_DRAFT_TOKENS,
1741 &OPTI_BREAKER_TRIPS,
1742 ] {
1743 counter.store(0, std::sync::atomic::Ordering::Relaxed);
1744 }
1745}
1746
1747pub fn optipipe_gate_stats() -> OptiForkGateStats {
1748 let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
1749 OptiForkGateStats {
1750 attempts: load(&OPTI_FORK_ATTEMPTS),
1751 hits: load(&OPTI_FORK_HITS),
1752 misses: load(&OPTI_FORK_MISSES),
1753 abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
1754 refusals: load(&OPTI_FORK_REFUSALS),
1755 gate_checks: load(&OPTI_GATE_CHECKS),
1756 gate_admits: load(&OPTI_GATE_ADMITS),
1757 gate_rejects: load(&OPTI_GATE_REJECTS),
1758 reconciles: load(&OPTI_RECONCILES),
1759 wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
1760 shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
1761 breaker_trips: load(&OPTI_BREAKER_TRIPS),
1762 }
1763}
1764
1765#[derive(Clone, Copy, Debug)]
1766struct OptiControllerPolicy {
1767 threshold: f32,
1768 consecutive_misses: u8,
1769 breaker_tripped: bool,
1770}
1771
1772impl OptiControllerPolicy {
1773 fn configured() -> Self {
1774 Self {
1775 threshold: f32::from_bits(
1776 OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
1777 ),
1778 consecutive_misses: 0,
1779 breaker_tripped: false,
1780 }
1781 }
1782
1783 fn admit(&self, q_proxy: f32) -> bool {
1784 q_proxy.is_finite()
1785 && (0.0..=1.0).contains(&q_proxy)
1786 && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
1787 }
1788
1789 /// Returns true exactly when this resolution newly trips the three-miss breaker.
1790 fn resolve(&mut self, hit: bool) -> bool {
1791 // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
1792 // every optimistic opportunity, so the safety breaker is measured separately and must
1793 // not silently turn this arm into "three attempts then serial".
1794 if self.threshold == 0.0 {
1795 self.consecutive_misses = 0;
1796 return false;
1797 }
1798 if hit {
1799 self.consecutive_misses = 0;
1800 return false;
1801 }
1802 self.consecutive_misses = self.consecutive_misses.saturating_add(1);
1803 if !self.breaker_tripped && self.consecutive_misses >= 3 {
1804 self.breaker_tripped = true;
1805 return true;
1806 }
1807 false
1808 }
1809}
1810
1811#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1812enum OptiForkAction {
1813 Hit,
1814 Miss,
1815 Abort,
1816}
1817
1818#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1819struct OptiForkGeneration {
1820 id: u64,
1821 slot: usize,
1822}
1823
1824#[derive(Default)]
1825struct OptiForkGenerationTracker {
1826 next: u64,
1827 live: [Option<u64>; 2],
1828}
1829
1830impl OptiForkGenerationTracker {
1831 fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1832 let generation = OptiForkGeneration {
1833 id: self.next,
1834 slot: (self.next & 1) as usize,
1835 };
1836 if let Some(live) = self.live[generation.slot] {
1837 return Err(format!(
1838 "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
1839 generation.slot,
1840 )
1841 .into());
1842 }
1843 self.next += 1;
1844 self.live[generation.slot] = Some(generation.id);
1845 Ok(generation)
1846 }
1847
1848 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
1849 match self.live[generation.slot] {
1850 Some(id) if id == generation.id => {
1851 self.live[generation.slot] = None;
1852 Ok(())
1853 }
1854 other => Err(format!(
1855 "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
1856 generation.id, generation.slot,
1857 )
1858 .into()),
1859 }
1860 }
1861}
1862
1863struct OptiForkSeedGeneration {
1864 h_seed: CudaSlice<f32>,
1865 fill_prev: CudaSlice<f32>,
1866 scratch_len: usize,
1867}
1868
1869/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
1870/// generic cache helper accepts one device and therefore cannot copy GDN state split across
1871/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
1872/// device ownership.
1873fn opti_snapshot_stage_owned(
1874 e: &Engine,
1875 cache: &Cache,
1876 rt: &'static crate::pp::PpNRt,
1877 fence: &[usize],
1878) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
1879 let n = cache.kv.len();
1880 let mut snapshot = crate::cache::CacheSnapshot {
1881 kv_len: vec![None; n],
1882 conv: (0..n).map(|_| None).collect(),
1883 ssm: (0..n).map(|_| None).collect(),
1884 pos: cache.pos,
1885 };
1886 opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
1887 Ok(snapshot)
1888}
1889
1890fn opti_snapshot_stage_owned_into(
1891 e: &Engine,
1892 cache: &Cache,
1893 rt: &'static crate::pp::PpNRt,
1894 fence: &[usize],
1895 snapshot: &mut crate::cache::CacheSnapshot,
1896) -> Result<(), Box<dyn std::error::Error>> {
1897 if fence.len() != rt.n_stages() + 1 || snapshot.kv_len.len() != cache.kv.len() {
1898 return Err("optipipe stage-owned snapshot shape mismatch".into());
1899 }
1900 for stage in 0..rt.n_stages() {
1901 opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
1902 }
1903 snapshot.pos = cache.pos;
1904 Ok(())
1905}
1906
1907/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
1908/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
1909/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
1910/// either point would capture one side of the fork at the wrong generation.
1911fn opti_snapshot_one_stage_owned_into(
1912 e: &Engine,
1913 cache: &Cache,
1914 rt: &'static crate::pp::PpNRt,
1915 fence: &[usize],
1916 stage: usize,
1917 snapshot: &mut crate::cache::CacheSnapshot,
1918) -> Result<(), Box<dyn std::error::Error>> {
1919 if fence.len() != rt.n_stages() + 1
1920 || snapshot.kv_len.len() != cache.kv.len()
1921 || stage >= rt.n_stages()
1922 {
1923 return Err("optipipe single-stage snapshot shape mismatch".into());
1924 }
1925 let _scope = rt.enter(stage);
1926 let owner = rt.engine(stage, e);
1927 for il in fence[stage]..fence[stage + 1] {
1928 snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
1929 match &cache.recur[il] {
1930 Some(recur) => {
1931 match snapshot.conv[il].as_mut() {
1932 Some(dst) => {
1933 owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
1934 }
1935 None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
1936 }
1937 match snapshot.ssm[il].as_mut() {
1938 Some(dst) => {
1939 owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
1940 }
1941 None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
1942 }
1943 }
1944 None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
1945 return Err(
1946 format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
1947 );
1948 }
1949 None => {}
1950 }
1951 }
1952 snapshot.pos = cache.pos;
1953 Ok(())
1954}
1955
1956/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
1957/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
1958/// resolve, so the reconcile tables and conditional restores are stage-local.
1959struct OptiForkState {
1960 mode: OptiForkGateMode,
1961 controller: Option<OptiControllerPolicy>,
1962 generations: OptiForkGenerationTracker,
1963 active_snapshot_slot: usize,
1964 alternate_snapshot: crate::cache::CacheSnapshot,
1965 seeds: [OptiForkSeedGeneration; 2],
1966 rt: &'static crate::pp::PpNRt,
1967 fence: [usize; 3],
1968 split: usize,
1969 len_ptrs: CudaSlice<u64>,
1970 saved_lens: CudaSlice<i32>,
1971 forced_acc: CudaSlice<u32>,
1972 valid: CudaSlice<u32>,
1973 stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1974 logical_payload_bytes: [usize; 2],
1975}
1976
1977struct OptiForkTicket {
1978 generation: OptiForkGeneration,
1979 boundary: Option<VerifyBoundaryTicket>,
1980 drain: std::sync::Arc<cudarc::driver::CudaStream>,
1981 settled: bool,
1982}
1983
1984struct OptiControllerTicket {
1985 generation: OptiForkGeneration,
1986 boundary: Option<VerifyBoundaryTicket>,
1987 ckpt: Option<VerifyCkpt>,
1988 verify_tokens: [u32; 2],
1989 draft_prob: f32,
1990 eager_seed: Option<CudaSlice<f32>>,
1991 q_proxy: f32,
1992 scratch_len: usize,
1993 issued_at: std::time::Instant,
1994 drain: std::sync::Arc<cudarc::driver::CudaStream>,
1995 settled: bool,
1996}
1997
1998struct OptiControllerPrepared {
1999 verify_tokens: [u32; 2],
2000 draft_prob: f32,
2001 eager_seed: Option<CudaSlice<f32>>,
2002 q_proxy: f32,
2003 scratch_len: usize,
2004}
2005
2006impl OptiControllerTicket {
2007 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
2008 self.boundary
2009 .take()
2010 .expect("controller boundary ticket already consumed")
2011 }
2012
2013 fn take_ckpt(&mut self) -> VerifyCkpt {
2014 self.ckpt
2015 .take()
2016 .expect("controller verify checkpoint already consumed")
2017 }
2018
2019 fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
2020 self.eager_seed.take()
2021 }
2022
2023 fn settle(&mut self) {
2024 self.settled = true;
2025 }
2026}
2027
2028impl Drop for OptiControllerTicket {
2029 fn drop(&mut self) {
2030 if !self.settled {
2031 let _ = self.drain.synchronize();
2032 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2033 }
2034 }
2035}
2036
2037impl OptiForkTicket {
2038 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
2039 self.boundary
2040 .take()
2041 .expect("fork ticket boundary already consumed")
2042 }
2043
2044 fn settle(&mut self) {
2045 self.settled = true;
2046 }
2047}
2048
2049impl Drop for OptiForkTicket {
2050 fn drop(&mut self) {
2051 if !self.settled {
2052 let _ = self.drain.synchronize();
2053 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2054 }
2055 }
2056}
2057
2058impl OptiForkState {
2059 #[allow(clippy::too_many_arguments)]
2060 fn new(
2061 e: &Engine,
2062 cache: &Cache,
2063 mode: OptiForkGateMode,
2064 alternate_snapshot: crate::cache::CacheSnapshot,
2065 h_seed: &CudaSlice<f32>,
2066 fill_prev: &CudaSlice<f32>,
2067 rt: &'static crate::pp::PpNRt,
2068 split: usize,
2069 n_layer: usize,
2070 ) -> Result<Self, Box<dyn std::error::Error>> {
2071 let fence = [0, split, n_layer];
2072 let mut logical_payload_bytes = [0usize; 2];
2073 for stage in 0..2 {
2074 for il in fence[stage]..fence[stage + 1] {
2075 logical_payload_bytes[stage] += alternate_snapshot.conv[il]
2076 .as_ref()
2077 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
2078 logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
2079 .as_ref()
2080 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
2081 }
2082 }
2083 let seeds = [
2084 OptiForkSeedGeneration {
2085 h_seed: e.clone_dtod(h_seed)?,
2086 fill_prev: e.clone_dtod(fill_prev)?,
2087 scratch_len: 0,
2088 },
2089 OptiForkSeedGeneration {
2090 h_seed: e.clone_dtod(h_seed)?,
2091 fill_prev: e.clone_dtod(fill_prev)?,
2092 scratch_len: 0,
2093 },
2094 ];
2095 let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
2096 let _stage = rt.enter(0);
2097 let e0 = rt.engine(0, e);
2098 (
2099 crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
2100 e0.htod_i32(&vec![0; split])?,
2101 e0.alloc_u32_zeroed(2)?,
2102 e0.alloc_u32_zeroed(1)?,
2103 e0.stream(),
2104 )
2105 };
2106 logical_payload_bytes[0] += seeds
2107 .iter()
2108 .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
2109 .sum::<usize>();
2110 logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
2111 + saved_lens.len() * std::mem::size_of::<i32>()
2112 + forced_acc.len() * std::mem::size_of::<u32>()
2113 + valid.len() * std::mem::size_of::<u32>();
2114 Ok(Self {
2115 mode,
2116 controller: (mode == OptiForkGateMode::Controller)
2117 .then(OptiControllerPolicy::configured),
2118 generations: OptiForkGenerationTracker::default(),
2119 active_snapshot_slot: 0,
2120 alternate_snapshot,
2121 seeds,
2122 rt,
2123 fence,
2124 split,
2125 len_ptrs,
2126 saved_lens,
2127 forced_acc,
2128 valid,
2129 stage0_stream,
2130 logical_payload_bytes,
2131 })
2132 }
2133
2134 fn reserve(
2135 &mut self,
2136 current_snapshot: &mut crate::cache::CacheSnapshot,
2137 ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2138 let generation = self.generations.reserve()?;
2139 if generation.slot != self.active_snapshot_slot {
2140 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
2141 self.active_snapshot_slot = generation.slot;
2142 }
2143 Ok(generation)
2144 }
2145
2146 fn capture_seed(
2147 &mut self,
2148 e: &Engine,
2149 generation: OptiForkGeneration,
2150 h_seed: &CudaSlice<f32>,
2151 fill_prev: &CudaSlice<f32>,
2152 scratch_len: usize,
2153 ) -> Result<(), Box<dyn std::error::Error>> {
2154 let seed = &mut self.seeds[generation.slot];
2155 e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
2156 e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
2157 seed.scratch_len = scratch_len;
2158 Ok(())
2159 }
2160
2161 fn ticket(
2162 &self,
2163 generation: OptiForkGeneration,
2164 boundary: VerifyBoundaryTicket,
2165 ) -> OptiForkTicket {
2166 OptiForkTicket {
2167 generation,
2168 boundary: Some(boundary),
2169 drain: self.stage0_stream.clone(),
2170 settled: false,
2171 }
2172 }
2173
2174 #[allow(clippy::too_many_arguments)]
2175 fn controller_ticket(
2176 &self,
2177 generation: OptiForkGeneration,
2178 boundary: VerifyBoundaryTicket,
2179 ckpt: VerifyCkpt,
2180 verify_tokens: [u32; 2],
2181 draft_prob: f32,
2182 eager_seed: Option<CudaSlice<f32>>,
2183 q_proxy: f32,
2184 scratch_len: usize,
2185 ) -> OptiControllerTicket {
2186 OptiControllerTicket {
2187 generation,
2188 boundary: Some(boundary),
2189 ckpt: Some(ckpt),
2190 verify_tokens,
2191 draft_prob,
2192 eager_seed,
2193 q_proxy,
2194 scratch_len,
2195 issued_at: std::time::Instant::now(),
2196 drain: self.stage0_stream.clone(),
2197 settled: false,
2198 }
2199 }
2200
2201 fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2202 self.generations.reserve()
2203 }
2204
2205 fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
2206 &mut self.alternate_snapshot
2207 }
2208
2209 fn promote_successor_snapshot(
2210 &mut self,
2211 current_snapshot: &mut crate::cache::CacheSnapshot,
2212 generation: OptiForkGeneration,
2213 ) {
2214 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
2215 self.active_snapshot_slot = generation.slot;
2216 }
2217
2218 fn queue_actual_reconcile(
2219 &mut self,
2220 e: &Engine,
2221 snapshot: &crate::cache::CacheSnapshot,
2222 acc: &CudaSlice<u32>,
2223 optimistic_pending: u32,
2224 base: usize,
2225 ) -> Result<(), Box<dyn std::error::Error>> {
2226 let saved: Vec<i32> = (0..self.split)
2227 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
2228 .collect();
2229 // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
2230 // decision point there and append a wait to stage 0 after its optimistic successor/TX;
2231 // the validity/reconcile kernels must never peer-read acc before it is written. The
2232 // increment-1 harness uses primary stage 0, where stream order already provides this.
2233 if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
2234 self.rt.fence_stages_behind(&e.stream())?;
2235 }
2236 let _stage = self.rt.enter(0);
2237 let e0 = self.rt.engine(0, e);
2238 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
2239 e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
2240 e0.spec_fork_reconcile_kv(
2241 &self.len_ptrs,
2242 &self.saved_lens,
2243 acc,
2244 &self.valid,
2245 base,
2246 self.split,
2247 )
2248 }
2249
2250 fn finish_actual_reconcile(
2251 &mut self,
2252 e: &Engine,
2253 cache: &mut Cache,
2254 snapshot: &crate::cache::CacheSnapshot,
2255 n_acc: usize,
2256 base: usize,
2257 hit: bool,
2258 ) -> Result<(), Box<dyn std::error::Error>> {
2259 if hit {
2260 return Ok(());
2261 }
2262 let len_delta = base + n_acc;
2263 for il in 0..self.split {
2264 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2265 kv.len = saved + len_delta;
2266 }
2267 }
2268 {
2269 let _stage = self.rt.enter(1);
2270 let e1 = self.rt.engine(1, e);
2271 for il in self.split..self.fence[2] {
2272 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2273 kv.len = saved + len_delta;
2274 e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2275 }
2276 }
2277 }
2278 self.rt.publish_to(0, &e.stream())?;
2279 Ok(())
2280 }
2281
2282 fn cancel_controller_ticket(
2283 &mut self,
2284 e: &Engine,
2285 cache: &mut Cache,
2286 scratch: &mut MtpScratch,
2287 snapshot: &crate::cache::CacheSnapshot,
2288 ticket: &mut OptiControllerTicket,
2289 ) -> Result<(), Box<dyn std::error::Error>> {
2290 {
2291 let _stage = self.rt.enter(0);
2292 let e0 = self.rt.engine(0, e);
2293 for il in 0..self.split {
2294 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2295 kv.len = saved;
2296 e0.set_i32_one(&mut kv.len_d, saved as i32)?;
2297 }
2298 }
2299 }
2300 scratch.set_len(e, snapshot.pos)?;
2301 ticket.settle();
2302 self.generations.retire(ticket.generation)?;
2303 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2304 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
2305 eprintln!(
2306 "[opti-controller] tail-drain generation={} slot={}",
2307 ticket.generation.id, ticket.generation.slot,
2308 );
2309 Ok(())
2310 }
2311
2312 #[allow(clippy::too_many_arguments)]
2313 fn reconcile(
2314 &mut self,
2315 e: &Engine,
2316 cache: &mut Cache,
2317 scratch: &mut MtpScratch,
2318 snapshot: &crate::cache::CacheSnapshot,
2319 h_seed: &mut CudaSlice<f32>,
2320 fill_prev: &mut CudaSlice<f32>,
2321 generation: OptiForkGeneration,
2322 action: OptiForkAction,
2323 optimistic_pending: u32,
2324 ) -> Result<(), Box<dyn std::error::Error>> {
2325 debug_assert!(action != OptiForkAction::Abort);
2326 let miss_started = std::time::Instant::now();
2327 let keep = action == OptiForkAction::Hit;
2328 let saved: Vec<i32> = (0..self.split)
2329 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
2330 .collect();
2331 let seed = &self.seeds[generation.slot];
2332 {
2333 let _stage = self.rt.enter(0);
2334 let e0 = self.rt.engine(0, e);
2335 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
2336 let forced = if keep {
2337 [1u32, optimistic_pending]
2338 } else {
2339 [0u32, optimistic_pending]
2340 };
2341 e0.htod_u32_into(&mut self.forced_acc, &forced)?;
2342 e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
2343 e0.spec_fork_reconcile_kv(
2344 &self.len_ptrs,
2345 &self.saved_lens,
2346 &self.forced_acc,
2347 &self.valid,
2348 0,
2349 self.split,
2350 )?;
2351 for il in 0..self.split {
2352 if let Some(recur) = cache.recur[il].as_mut() {
2353 let conv = snapshot.conv[il]
2354 .as_ref()
2355 .ok_or("optipipe stage0 snapshot missing conv state")?;
2356 let ssm = snapshot.ssm[il]
2357 .as_ref()
2358 .ok_or("optipipe stage0 snapshot missing ssm state")?;
2359 e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
2360 e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
2361 }
2362 }
2363 e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
2364 e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
2365 }
2366
2367 if keep {
2368 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2369 return Ok(());
2370 }
2371
2372 for il in 0..self.split {
2373 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2374 kv.len = saved;
2375 }
2376 }
2377 scratch.set_len(e, seed.scratch_len)?;
2378 // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
2379 // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
2380 let caller = e.stream();
2381 self.rt.publish_to(0, &caller)?;
2382 caller.synchronize()?;
2383 let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
2384 eprintln!(
2385 "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
2386 generation.id, generation.slot,
2387 );
2388 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2389 Ok(())
2390 }
2391
2392 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2393 self.generations.retire(generation)
2394 }
2395}
2396
2397impl HybridModel {
2398 fn opti_graph_draft_step(
2399 &self,
2400 e: &Engine,
2401 mtp: &MtpHead,
2402 dctx: &mut DraftGraphCtx,
2403 scratch: &mut MtpScratch,
2404 d_vocab: usize,
2405 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2406 dctx.graph
2407 .as_ref()
2408 .ok_or("optipipe controller requires the greedy draft graph")?
2409 .launch()?;
2410 scratch.kv.len += 1;
2411 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
2412 if (idx as usize) >= d_vocab {
2413 return Err(
2414 format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
2415 );
2416 }
2417 let probability = e.dtoh(&dctx.g_p)?[0];
2418 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2419 return Err(format!("optipipe draft probability is invalid: {probability}").into());
2420 }
2421 let token = match &mtp.d2t {
2422 Some(map) => map[idx as usize],
2423 None => idx,
2424 };
2425 if token != idx {
2426 e.set_u32_one(&mut dctx.g_tok, token)?;
2427 }
2428 Ok((token, probability))
2429 }
2430
2431 #[allow(clippy::too_many_arguments)]
2432 fn opti_controller_draft_step(
2433 &self,
2434 e: &Engine,
2435 mtp: &MtpHead,
2436 dctx: &mut DraftGraphCtx,
2437 scratch: &mut MtpScratch,
2438 d_vocab: usize,
2439 eager_state: &mut Option<(u32, CudaSlice<f32>)>,
2440 eager_pos: usize,
2441 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2442 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2443 if dctx.graph.is_some() {
2444 return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
2445 }
2446 let (input_token, input_seed) = eager_state
2447 .take()
2448 .ok_or("optipipe eager continuation seed is unavailable")?;
2449 let (logits, next_seed) = self.mtp_head_forward_dev(
2450 e,
2451 mtp,
2452 input_token,
2453 &input_seed,
2454 scratch,
2455 eager_pos,
2456 embd_dev,
2457 None,
2458 )?;
2459 let token_d = e.argmax_token_device(&logits, d_vocab)?;
2460 let idx = e.dtoh_u32_one(&token_d)?;
2461 if (idx as usize) >= d_vocab {
2462 return Err(format!(
2463 "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
2464 )
2465 .into());
2466 }
2467 let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
2468 let probability = e.dtoh(&probability_d)?[0];
2469 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2470 return Err(
2471 format!("optipipe eager draft probability is invalid: {probability}").into(),
2472 );
2473 }
2474 let token = match &mtp.d2t {
2475 Some(map) => map[idx as usize],
2476 None => idx,
2477 };
2478 *eager_state = Some((token, next_seed));
2479 Ok((token, probability))
2480 }
2481
2482 /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
2483 /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
2484 /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
2485 /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
2486 /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
2487 /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
2488 /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
2489 /// transfer + host argmax per draft token from the K-token draft chain.
2490 #[allow(clippy::too_many_arguments)]
2491 fn mtp_head_forward_dev(
2492 &self,
2493 e: &Engine,
2494 mtp: &MtpHead,
2495 e_tok: u32,
2496 h_seed: &CudaSlice<f32>,
2497 scratch: &mut MtpScratch,
2498 mtp_pos: usize,
2499 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2500 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
2501 // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
2502 // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
2503 mask: Option<(&CudaSlice<u32>, usize)>,
2504 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2505 let cfg = &self.cfg;
2506 let n_embd = cfg.n_embd as usize;
2507 // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
2508 // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
2509 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2510 let eps = cfg.rms_eps;
2511 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
2512
2513 // op A: a resident table transfers one 4B token id. The exact host-row capacity path
2514 // expands this one row on CPU and transfers n_embd f32 values instead.
2515 let e_emb = match embd_dev {
2516 Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
2517 None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
2518 };
2519
2520 // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
2521 let mut e_norm = e.zeros(n_embd)?;
2522 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
2523 let mut h_norm = e.zeros(n_embd)?;
2524 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
2525
2526 // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
2527 let mut concat = e.zeros(2 * n_embd)?;
2528 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
2529 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
2530
2531 // op 4: inpSA = eh_proj @ concat (eh_proj [2*n_embd, n_embd]) -> [n_embd]
2532 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
2533
2534 // op 5: a_norm = RMSNorm(inpSA, attn_norm)
2535 let mut a_norm = e.zeros(di)?;
2536 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
2537
2538 // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
2539 // scratch.cap, length from the device len_d) so eager drafts match graph drafts
2540 // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
2541 // advances only the device counter).
2542 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
2543 // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
2544 // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
2545 // Advances BOTH the host len and the device counter itself (unlike the dc arm,
2546 // whose host-side mirror the caller does).
2547 (Mixer::Full(fa), Some(g)) => {
2548 self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?
2549 }
2550 (Mixer::Full(fa), None) => {
2551 let out =
2552 self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
2553 scratch.kv.len += 1;
2554 out
2555 }
2556 (Mixer::Linear(_), _) => {
2557 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2558 }
2559 (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
2560 };
2561
2562 // op 7: x1 = inpSA + attn_out
2563 let mut x1 = e.zeros(di)?;
2564 e.add(&inp_sa, &attn_out, &mut x1, di)?;
2565
2566 // op 8: z = RMSNorm(x1, post_attn_norm) (pre-FFN norm)
2567 let mut z = e.zeros(di)?;
2568 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
2569
2570 // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
2571 let ffn_out = match &mtp.ffn {
2572 crate::hybrid::Ffn::Dense {
2573 ffn_gate,
2574 ffn_up,
2575 ffn_down,
2576 } => {
2577 let n_ff = ffn_gate.out_features();
2578 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
2579 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
2580 (
2581 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
2582 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
2583 )
2584 } else {
2585 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
2586 };
2587 let mut act = e.zeros(n_ff)?;
2588 // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
2589 // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
2590 // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
2591 // passes None, which is `ffn_act`'s dispatch verbatim.
2592 Self::ffn_act_lim(
2593 e,
2594 &self.cfg,
2595 &gate,
2596 &up,
2597 1.0,
2598 1.0,
2599 mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
2600 &mut act,
2601 n_ff,
2602 )?;
2603 e.matmul(ffn_down, &act, 1)?
2604 }
2605 // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
2606 // so they never alias trunk layer 0's cache keys.
2607 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
2608 };
2609
2610 // op 10: h_nextn = x1 + ffn_out (at di)
2611 let mut h_inner = e.zeros(di)?;
2612 e.add(&x1, &ffn_out, &mut h_inner, di)?;
2613
2614 // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
2615 // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
2616 let h_nextn = match mtp.geom.as_ref() {
2617 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
2618 None => h_inner,
2619 };
2620
2621 // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
2622 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
2623 let mut final_h = e.zeros(n_embd)?;
2624 e.rms_norm(
2625 &h_nextn,
2626 final_norm.float_data(),
2627 &mut final_h,
2628 n_embd,
2629 1,
2630 eps,
2631 )?;
2632
2633 // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
2634 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
2635 let mut logits = e.matmul(head, &final_h, 1)?;
2636 // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
2637 // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
2638 if let Some((mask_d, mw)) = mask {
2639 let d_vocab = head.out_features();
2640 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
2641 }
2642 // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
2643 // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
2644 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
2645 }
2646
2647 /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
2648 /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
2649 /// the dc path, and all three are properties of this arch's MTP block:
2650 ///
2651 /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
2652 /// window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
2653 /// cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
2654 /// mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
2655 /// windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
2656 /// starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
2657 /// new kernel. That is deliberately not built here: see the CUDA-graph note below.
2658 /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
2659 /// on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
2660 /// trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
2661 /// resolved `Step35MtpGeom`, never from `cfg`.
2662 /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
2663 /// sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
2664 /// fused-into-wq `q_gate_split` form the dc arm handles.
2665 ///
2666 /// WHY EAGER-ONLY IS NOT A GAP TODAY: `graph_draft` requires `trunk_dense`, and this SKU's
2667 /// trunk is a 288-expert MoE, so the graph draft is already off for every step35 model — the
2668 /// eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
2669 /// than silently capturing a window-less (wrong past `win` draft rows) graph.
2670 ///
2671 /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
2672 /// caller must not mirror.
2673 fn mtp_step35_attn(
2674 &self,
2675 e: &Engine,
2676 fa: &FullAttnLayer,
2677 g: &crate::hybrid::Step35MtpGeom,
2678 h: &CudaSlice<f32>,
2679 pos_d: &CudaSlice<i32>,
2680 scratch: &mut MtpScratch,
2681 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2682 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
2683 let eps = self.cfg.rms_eps;
2684 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
2685 let n_embd = self.cfg.n_embd as usize;
2686 let gw = fa
2687 .attn_gate
2688 .as_ref()
2689 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
2690
2691 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
2692 && e.uses_q8_1_fast(&fa.wk)
2693 && e.uses_q8_1_fast(&fa.wv)
2694 && e.uses_q8_1_fast(gw)
2695 {
2696 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
2697 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
2698 Some(t3) => t3,
2699 None => (
2700 e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
2701 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
2702 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
2703 ),
2704 };
2705 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
2706 } else {
2707 (
2708 e.matmul(&fa.wq, h, 1)?,
2709 e.matmul(&fa.wk, h, 1)?,
2710 e.matmul(&fa.wv, h, 1)?,
2711 e.matmul(gw, h, 1)?,
2712 )
2713 };
2714
2715 let mut q = e.uninit(nh * hd)?;
2716 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
2717 let mut k = e.uninit(nkv * hd)?;
2718 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
2719 // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
2720 // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
2721 // the resolved flag, not the constant, so an all-full sibling stays correct.
2722 let ff = if g.swa {
2723 None
2724 } else {
2725 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
2726 };
2727 #[cfg(debug_assertions)]
2728 if let Some(ff) = ff {
2729 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
2730 }
2731 e.rope_neox2(
2732 &mut q,
2733 &mut k,
2734 pos_d,
2735 hd,
2736 g.n_rot,
2737 nh,
2738 nkv,
2739 1,
2740 g.rope_base,
2741 1.0,
2742 ff,
2743 )?;
2744
2745 // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
2746 // length on the host anyway, and the windowed view below needs it there to compute the
2747 // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
2748 // dc-family consumer of this scratch still agree.
2749 let kv = &mut scratch.kv;
2750 assert!(
2751 kv.len < scratch.cap,
2752 "step35 MTP scratch overflow ({} >= {})",
2753 kv.len,
2754 scratch.cap
2755 );
2756 let next_len = kv.len + 1;
2757 let (off, t_kv) = if g.swa && next_len > g.window {
2758 (next_len - g.window, g.window)
2759 } else {
2760 (0, next_len)
2761 };
2762 let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
2763 e.append_kv_quantized(
2764 &k,
2765 &v0,
2766 &mut kv.k,
2767 &mut kv.v,
2768 write_row,
2769 kv.kv_dim_k,
2770 kv.kv_dim_v,
2771 kv.k_tok_bytes,
2772 kv.v_tok_bytes,
2773 false,
2774 )?;
2775 kv.len = next_len;
2776 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2777 // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
2778 // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
2779 // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
2780 // therefore live, not theoretical.
2781 let physical = kv.physical_rows(off, off + t_kv)?;
2782 let k_view = e.view_u8_range(
2783 &kv.k,
2784 physical.start * kv.k_tok_bytes,
2785 physical.end * kv.k_tok_bytes,
2786 );
2787 let v_view = e.view_u8_range(
2788 &kv.v,
2789 physical.start * kv.v_tok_bytes,
2790 physical.end * kv.v_tok_bytes,
2791 );
2792 let mut attn = e.uninit(nh * hd)?;
2793 e.fa_decode_kvmod(
2794 &q,
2795 &k_view,
2796 &v_view,
2797 &mut attn,
2798 hd,
2799 nh,
2800 nkv,
2801 t_kv,
2802 scale,
2803 kv.k_tok_bytes,
2804 kv.v_tok_bytes,
2805 false,
2806 )?;
2807
2808 let mut ag = e.uninit(nh * hd)?;
2809 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
2810 Ok(e.matmul(&fa.wo, &ag, 1)?)
2811 }
2812
2813 /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
2814 /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
2815 /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
2816 /// chain, and replays keep seeing KV growth through the device counter (no recapture).
2817 /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
2818 /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
2819 /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
2820 /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
2821 /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
2822 fn mtp_full_attn_dc(
2823 &self,
2824 e: &Engine,
2825 fa: &FullAttnLayer,
2826 h: &CudaSlice<f32>,
2827 pos_d: &CudaSlice<i32>,
2828 scratch: &mut MtpScratch,
2829 geom: Option<&crate::hybrid::DraftGeom>,
2830 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2831 let cfg = &self.cfg;
2832 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2833 let geometry = cfg.full_attention_geometry_at(mtp_il);
2834 let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
2835 let n_head_kv = geom
2836 .map(|g| g.n_head_kv)
2837 .unwrap_or(geometry.n_head_kv as usize);
2838 let head_dim = geometry.head_dim_k as usize;
2839 let eps = cfg.rms_eps;
2840 let scale = geometry.attention_scale();
2841 let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
2842 let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
2843
2844 let (qf, mut k, v) =
2845 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
2846 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
2847 (
2848 e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
2849 e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
2850 e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
2851 )
2852 } else {
2853 (
2854 e.matmul(&fa.wq, h, 1)?,
2855 e.matmul(&fa.wk, h, 1)?,
2856 e.matmul(&fa.wv, h, 1)?,
2857 )
2858 };
2859 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2860 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
2861 let (mut q, gate) = if gated {
2862 let mut q = e.zeros(n_head * head_dim)?;
2863 let mut gate = e.zeros(n_head * head_dim)?;
2864 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
2865 (q, Some(gate))
2866 } else {
2867 (qf, None)
2868 };
2869
2870 let mut qn = e.zeros(n_head * head_dim)?;
2871 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
2872 q = qn;
2873 let mut kn = e.zeros(n_head_kv * head_dim)?;
2874 e.rms_norm(
2875 &k,
2876 fa.k_norm.float_data(),
2877 &mut kn,
2878 head_dim,
2879 n_head_kv,
2880 eps,
2881 )?;
2882 k = kn;
2883 let rope_dims = geometry.n_rot as usize;
2884 e.rope_neox(
2885 &mut q,
2886 pos_d,
2887 head_dim,
2888 rope_dims,
2889 n_head,
2890 1,
2891 geometry.rope_base,
2892 1.0,
2893 )?;
2894 e.rope_neox(
2895 &mut k,
2896 pos_d,
2897 head_dim,
2898 rope_dims,
2899 n_head_kv,
2900 1,
2901 geometry.rope_base,
2902 1.0,
2903 )?;
2904
2905 let kv = &mut scratch.kv;
2906 // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
2907 e.append_kv_quantized_dc(
2908 &k,
2909 &v,
2910 &mut kv.k,
2911 &mut kv.v,
2912 &kv.len_d,
2913 kv.kv_dim_k,
2914 kv.kv_dim_v,
2915 kv.k_tok_bytes,
2916 kv.v_tok_bytes,
2917 false,
2918 )?;
2919 e.inc_seqlen(&mut kv.len_d)?;
2920 // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
2921 // key range from the device counter.
2922 let k_view = e.view_u8(&kv.k, kv.k.len());
2923 let v_view = e.view_u8(&kv.v, kv.v.len());
2924 let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
2925 let mut attn = e.zeros(n_head * head_dim)?;
2926 e.fa_decode_dc(
2927 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
2928 scale, ktb, vtb, false,
2929 )?;
2930
2931 let attn_g = match &gate {
2932 Some(gate) => {
2933 let mut gsig = e.zeros(n_head * head_dim)?;
2934 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2935 let mut ag = e.zeros(n_head * head_dim)?;
2936 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2937 ag
2938 }
2939 None => attn,
2940 };
2941 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2942 }
2943
2944 /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
2945 /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
2946 /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
2947 /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
2948 /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
2949 /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
2950 /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
2951 /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
2952 #[allow(clippy::too_many_arguments)]
2953 fn mtp_kv_fill(
2954 &self,
2955 e: &Engine,
2956 mtp: &MtpHead,
2957 tokens: &[u32],
2958 h: &CudaSlice<f32>,
2959 pos0: usize,
2960 scratch: &mut MtpScratch,
2961 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2962 ) -> Result<(), Box<dyn std::error::Error>> {
2963 let cfg = &self.cfg;
2964 let n_embd = cfg.n_embd as usize;
2965 let eps = cfg.rms_eps;
2966 let t = tokens.len();
2967 assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
2968 assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
2969 let Mixer::Full(fa) = &mtp.mixer else {
2970 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2971 };
2972 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
2973 let pos_d = e.htod_i32(&pos_vec)?;
2974
2975 // ops A/1/2: embed + the two input norms, T-wide.
2976 let e_emb = match embd_dev {
2977 Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
2978 None => e.htod(&self.embd.gather(n_embd, tokens))?,
2979 };
2980 let mut e_norm = e.zeros(t * n_embd)?;
2981 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
2982 let mut h_norm = e.zeros(t * n_embd)?;
2983 e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
2984
2985 // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
2986 let mut concat = e.zeros(t * 2 * n_embd)?;
2987 for i in 0..t {
2988 e.copy_view_into(
2989 &mut concat,
2990 i * 2 * n_embd,
2991 &e_norm.slice(i * n_embd..(i + 1) * n_embd),
2992 n_embd,
2993 )?;
2994 e.copy_view_into(
2995 &mut concat,
2996 i * 2 * n_embd + n_embd,
2997 &h_norm.slice(i * n_embd..(i + 1) * n_embd),
2998 n_embd,
2999 )?;
3000 }
3001
3002 // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
3003 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3004 let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
3005 let mut a_norm = e.zeros(t * di)?;
3006 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
3007
3008 // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
3009 // the fill only has to leave correct K/V rows behind for later chains to attend over.
3010 let n_head_kv = mtp
3011 .geom
3012 .as_ref()
3013 .map(|g| g.n_head_kv)
3014 .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
3015 .unwrap_or_else(|| {
3016 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3017 cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
3018 });
3019 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3020 let geometry = cfg.full_attention_geometry_at(mtp_il);
3021 let head_dim = geometry.head_dim_k as usize;
3022 let mut k = e.matmul(&fa.wk, &a_norm, t)?;
3023 let v = e.matmul(&fa.wv, &a_norm, t)?;
3024 let mut kn = e.zeros(t * n_head_kv * head_dim)?;
3025 e.rms_norm(
3026 &k,
3027 fa.k_norm.float_data(),
3028 &mut kn,
3029 head_dim,
3030 n_head_kv * t,
3031 eps,
3032 )?;
3033 k = kn;
3034 // step35: rotary width AND base are per-layer, and the MTP block's values come from the
3035 // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
3036 // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
3037 // writes K rows the attention arm then re-derives at a different theta: correct-looking
3038 // output with dead acceptance, invisible to the exactness gates.
3039 let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
3040 Some(s) => (
3041 s.n_rot,
3042 s.rope_base,
3043 if s.swa {
3044 None
3045 } else {
3046 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
3047 },
3048 ),
3049 None => (geometry.n_rot as usize, geometry.rope_base, None),
3050 };
3051 #[cfg(debug_assertions)]
3052 if let Some(ff) = ff {
3053 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
3054 }
3055 match ff {
3056 Some(f) => e.rope_neox_ff(
3057 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
3058 )?,
3059 None => e.rope_neox(
3060 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
3061 )?,
3062 }
3063
3064 let kv = &mut scratch.kv;
3065 // Match the trunk prime contract: a chunk may need the aligned window immediately before
3066 // its first row, so preserve that prefix when the physical tail rebases at wrap.
3067 let retain_from = kv
3068 .ring
3069 .as_ref()
3070 .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
3071 .unwrap_or(0);
3072 let write_row = e.prepare_kv_append(kv, retain_from, t)?;
3073 for i in 0..t {
3074 let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
3075 let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
3076 e.append_kv_quantized_view(
3077 &k_row,
3078 &v_row,
3079 &mut kv.k,
3080 &mut kv.v,
3081 write_row + i,
3082 kv.kv_dim_k,
3083 kv.kv_dim_v,
3084 kv.k_tok_bytes,
3085 kv.v_tok_bytes,
3086 false,
3087 )?;
3088 }
3089 kv.len = pos0 + t;
3090 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3091 Ok(())
3092 }
3093
3094 /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
3095 /// every varying input device-resident —
3096 /// - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
3097 /// so the chain feeds itself; the host reads the same 4 bytes for the draft list),
3098 /// - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
3099 /// - rope pos from the persistent `pos_d` counter (inc'd in-graph),
3100 /// - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
3101 /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
3102 /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
3103 /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
3104 /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
3105 /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
3106 /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
3107 /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
3108 /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
3109 /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
3110 /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
3111 /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
3112 /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
3113 /// seed/temp are capture-time constants (fixed per generate call, like p_min).
3114 #[allow(clippy::too_many_arguments)]
3115 fn mtp_head_forward_cap(
3116 &self,
3117 e: &Engine,
3118 mtp: &MtpHead,
3119 tok_d: &mut CudaSlice<u32>,
3120 pos_d: &mut CudaSlice<i32>,
3121 h_seed_d: &mut CudaSlice<f32>,
3122 p_d: &mut CudaSlice<f32>,
3123 scratch: &mut MtpScratch,
3124 with_prob: bool,
3125 with_head: bool,
3126 embd_gpu: &CudaSlice<u8>,
3127 embd_qt: i32,
3128 embd_rb: usize,
3129 d_vocab: usize,
3130 sampled_cap: Option<(
3131 &mut CudaSlice<u32>,
3132 &mut CudaSlice<f32>,
3133 &mut CudaSlice<f32>,
3134 u64,
3135 f32,
3136 )>,
3137 stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
3138 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
3139 // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
3140 // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
3141 // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
3142 // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
3143 mask_cap: Option<(&CudaSlice<u32>, usize)>,
3144 ) -> Result<(), Box<dyn std::error::Error>> {
3145 let cfg = &self.cfg;
3146 let n_embd = cfg.n_embd as usize;
3147 // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
3148 // whose device-counter key bound always starts at row 0 — it cannot express this block's
3149 // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
3150 // persistent scratch passes 512 rows. Nothing is lost today: `graph_draft` also requires
3151 // `trunk_dense`, and step35's trunk is a 288-expert MoE, so the eager chain
3152 // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
3153 // panic) is what the two capture sites and the round-stream capture already handle by
3154 // degrading to eager / stream-off.
3155 if mtp.step35.is_some() {
3156 return Err(
3157 "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
3158 block's SWA view offset; same root cause as the dc decode refusal) — the \
3159 eager draft chain serves this arch"
3160 .into(),
3161 );
3162 }
3163 // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
3164 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3165 let eps = cfg.rms_eps;
3166 let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
3167 let mut e_norm = e.zeros(n_embd)?;
3168 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
3169 let mut h_norm = e.zeros(n_embd)?;
3170 e.rms_norm(
3171 &*h_seed_d,
3172 mtp.hnorm.float_data(),
3173 &mut h_norm,
3174 n_embd,
3175 1,
3176 eps,
3177 )?;
3178 let mut concat = e.zeros(2 * n_embd)?;
3179 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
3180 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
3181 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
3182 let mut a_norm = e.zeros(di)?;
3183 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
3184 let attn_out = match &mtp.mixer {
3185 Mixer::Full(fa) => {
3186 self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
3187 }
3188 Mixer::Linear(_) => {
3189 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3190 }
3191 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
3192 };
3193 let mut x1 = e.zeros(di)?;
3194 e.add(&inp_sa, &attn_out, &mut x1, di)?;
3195 let mut z = e.zeros(di)?;
3196 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
3197 let ffn_out = match &mtp.ffn {
3198 crate::hybrid::Ffn::Dense {
3199 ffn_gate,
3200 ffn_up,
3201 ffn_down,
3202 } => {
3203 let n_ff = ffn_gate.out_features();
3204 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
3205 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
3206 (
3207 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
3208 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
3209 )
3210 } else {
3211 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
3212 };
3213 let mut act = e.zeros(n_ff)?;
3214 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
3215 e.matmul(ffn_down, &act, 1)?
3216 }
3217 // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
3218 // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
3219 // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
3220 // error arm degrades the caller to eager/stream-off.
3221 crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
3222 self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
3223 }
3224 crate::hybrid::Ffn::Moe(_) => {
3225 return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into());
3226 }
3227 };
3228 let mut h_inner = e.zeros(di)?;
3229 e.add(&x1, &ffn_out, &mut h_inner, di)?;
3230 // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
3231 let h_nextn = match mtp.geom.as_ref() {
3232 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
3233 None => h_inner,
3234 };
3235 // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
3236 let final_h = if with_head || spec_hpost() {
3237 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
3238 let mut fh = e.zeros(n_embd)?;
3239 e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
3240 Some(fh)
3241 } else {
3242 None
3243 };
3244 if with_head {
3245 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
3246 let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
3247 // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
3248 // before the argmax — proposals become legal by construction. Contents-only
3249 // per-replay upload keeps the capture valid.
3250 if let Some((mask_d, mw)) = mask_cap {
3251 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
3252 }
3253 if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
3254 // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
3255 // own buffer is pool-recycled after the capture body returns, so it can't be the
3256 // retention target), bump the device event counter, gumbel-perturb reading it,
3257 // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
3258 e.copy_into(q_out_d, 0, &logits, d_vocab)?;
3259 e.sctr_inc(ctr_d)?;
3260 e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
3261 e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
3262 // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
3263 // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
3264 if with_prob {
3265 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
3266 }
3267 } else {
3268 // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
3269 e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
3270 // p-min under a draft mask reads the MASKED row: confidence relative to the
3271 // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
3272 // is the right semantics for "does the drafter know what comes next here" and
3273 // the same row the pick came from. Draft-quality only — verify arbitrates.
3274 if with_prob {
3275 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
3276 }
3277 }
3278 }
3279 // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
3280 // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
3281 if let Some((out, slot, d2t)) = stream_pack {
3282 e.pack_tok_p(tok_d, p_d, out, slot)?;
3283 if let Some(map) = d2t {
3284 e.tok_map_u32(tok_d, map)?;
3285 }
3286 }
3287 // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
3288 if spec_hpost() {
3289 e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
3290 } else {
3291 e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
3292 }
3293 // advance the draft rope position in-graph.
3294 e.inc_seqlen(pos_d)?;
3295 Ok(())
3296 }
3297
3298 /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
3299 /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
3300 /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
3301 /// Advances `cache.pos` by T.
3302 pub fn decode_step_t(
3303 &self,
3304 e: &Engine,
3305 tokens: &[u32],
3306 pos0: usize,
3307 cache: &mut Cache,
3308 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
3309 if self.is_gemma4_e4b() {
3310 return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
3311 }
3312 if self.cfg.gemma4.is_some() {
3313 return self.gemma4_decode_step_t(e, tokens, pos0, cache);
3314 }
3315 Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
3316 }
3317
3318 /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
3319 /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
3320 /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
3321 /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
3322 pub fn decode_step_t_h(
3323 &self,
3324 e: &Engine,
3325 tokens: &[u32],
3326 pos0: usize,
3327 cache: &mut Cache,
3328 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3329 self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
3330 }
3331
3332 /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
3333 /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
3334 pub fn decode_step_t_h_emb(
3335 &self,
3336 e: &Engine,
3337 tokens: &[u32],
3338 pos0: usize,
3339 cache: &mut Cache,
3340 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3341 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3342 let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
3343 Ok((e.dtoh(&logits_d)?, h_seed))
3344 }
3345
3346 /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
3347 /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
3348 /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
3349 /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
3350 /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
3351 pub fn decode_step_t_h_emb_dev(
3352 &self,
3353 e: &Engine,
3354 tokens: &[u32],
3355 pos0: usize,
3356 cache: &mut Cache,
3357 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3358 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3359 let n_embd = self.cfg.n_embd as usize;
3360 let t = tokens.len();
3361 let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
3362 // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
3363 let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
3364 e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
3365 Ok((logits, hs))
3366 }
3367
3368 /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
3369 /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
3370 /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
3371 /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
3372 /// retains/copies — they never change what any kernel computes).
3373 fn decode_step_t_core(
3374 &self,
3375 e: &Engine,
3376 tokens: &[u32],
3377 pos0: usize,
3378 cache: &mut Cache,
3379 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3380 mut ckpt: Option<&mut VerifyCkpt>,
3381 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3382 self.decode_step_t_core_stream(e, tokens, pos0, cache, embd_dev, ckpt.take(), None, None)
3383 }
3384
3385 /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
3386 /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
3387 fn decode_step_t_core_pipelined(
3388 &self,
3389 e: &Engine,
3390 tokens: &[u32],
3391 pos0: usize,
3392 cache: &mut Cache,
3393 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3394 mut ckpt: Option<&mut VerifyCkpt>,
3395 pipe: &SpecPipeLane,
3396 round: usize,
3397 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3398 let fence = crate::pp::pp_cuts(self.layers.len())
3399 .ok_or("two-session speculative pipeline requires a PP stage cut")?;
3400 if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
3401 return Err("two-session speculative pipeline requires the PP verify split".into());
3402 }
3403 let interval_fence = pipe.stage0_begin(round)?;
3404 let ticket = self.verify_stage0_issue(
3405 e,
3406 tokens,
3407 pos0,
3408 cache,
3409 embd_dev,
3410 ckpt.as_deref_mut(),
3411 None,
3412 &fence,
3413 Some(interval_fence),
3414 pipe.trace(round),
3415 )?;
3416 pipe.stage0_end(round);
3417 pipe.stage1_begin(round)?;
3418 let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
3419 pipe.verify_end(round);
3420 Ok(result)
3421 }
3422
3423 /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
3424 /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
3425 /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
3426 /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
3427 /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
3428 #[allow(clippy::too_many_arguments)]
3429 fn decode_step_t_core_stream(
3430 &self,
3431 e: &Engine,
3432 tokens: &[u32],
3433 pos0: usize,
3434 cache: &mut Cache,
3435 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3436 mut ckpt: Option<&mut VerifyCkpt>,
3437 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3438 pp_pipe: Option<bool>,
3439 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3440 // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
3441 // exactly as the eager and batched steps do. This is the single funnel every verify
3442 // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
3443 // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
3444 // is untouched.
3445 //
3446 // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
3447 // walk was unsplit on one stream and a sharded cross-device placement peer-read every
3448 // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
3449 // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
3450 // or a placement whose PpNRt fails to build — so a config that would still walk the
3451 // whole trunk on one stream refuses instead of regressing 28x.
3452 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
3453 if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
3454 return self.decode_step_t_core_ppn(
3455 e,
3456 tokens,
3457 pos0,
3458 cache,
3459 embd_dev,
3460 ckpt.take(),
3461 stream,
3462 &fence,
3463 pp_pipe,
3464 );
3465 }
3466 }
3467 crate::pp::refuse_unsplit_if_remote(
3468 "decode_step_t (spec verify)",
3469 "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
3470 split (decode_step_t_core_ppn); or run spec on one device",
3471 )?;
3472 let cfg = &self.cfg;
3473 let n_embd = cfg.n_embd as usize;
3474 let eps = cfg.rms_eps;
3475 let t = tokens.len();
3476 let pos_d = match stream {
3477 Some((_, ctr)) => {
3478 let mut p = e.alloc_uninit::<i32>(t)?;
3479 e.pos_iota(ctr, &mut p, t)?;
3480 p
3481 }
3482 None => {
3483 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3484 e.htod_i32(&pos_vec)?
3485 }
3486 };
3487
3488 // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
3489 let x = match (stream, embd_dev) {
3490 (Some((vtok, _)), Some((g, qt, rb))) => {
3491 e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3492 }
3493 (None, Some((g, qt, rb))) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3494 _ => e.htod(&self.embd.gather(n_embd, tokens))?,
3495 };
3496
3497 // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
3498 // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
3499 // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
3500 let x = self.verify_layers(
3501 e,
3502 x,
3503 0,
3504 self.layers.len(),
3505 &pos_d,
3506 pos0,
3507 t,
3508 cache,
3509 ckpt.take(),
3510 stream,
3511 )?;
3512
3513 let mut hn = vbuf(e, t * n_embd)?;
3514 let serving_head = self.cfg.step35.is_some() || self.qwen35_serving_class();
3515 let logits = if serving_head {
3516 // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
3517 // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
3518 // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
3519 // serve one batched numeric class at every live width, including B=1. Keep the
3520 // verify head in that same class; other generic families retain the decode-exact
3521 // head that their run-spec contract pins.
3522 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3523 e.matmul(&self.output, &hn, t)?
3524 } else {
3525 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3526 e.matmul_decode_exact(&self.output, &hn, t)?
3527 };
3528 // stream: the device pos counter owns position; host mirror reconciles at drain.
3529 if stream.is_none() {
3530 cache.pos += t;
3531 }
3532 // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
3533 Ok((logits, if spec_hpost() { hn } else { x }))
3534 }
3535
3536 /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
3537 /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
3538 /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
3539 /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
3540 /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
3541 /// the payload).
3542 ///
3543 /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
3544 /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
3545 /// receipts):
3546 ///
3547 /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
3548 /// (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
3549 /// DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
3550 /// (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
3551 /// s>0 its own Engine even on the primary device; honouring it here is what scopes the
3552 /// pools. The verify path allocates MORE of that scratch than eager decode does (FA at
3553 /// m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
3554 ///
3555 /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
3556 /// buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
3557 /// stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
3558 /// read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
3559 /// stage derives the identical iota, and each stage's own output buffer is stream-local.
3560 ///
3561 /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
3562 /// sharded loader leaves the table with stage 0 by construction).
3563 ///
3564 /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
3565 /// both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
3566 /// n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
3567 /// model, every round.
3568 ///
3569 /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
3570 /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
3571 /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
3572 /// through the primary context by UVA — the same read the batched serving epilogue's
3573 /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
3574 /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
3575 ///
3576 /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
3577 /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
3578 /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
3579 ///
3580 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
3581 /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
3582 /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
3583 /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
3584 /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
3585 /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
3586 /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
3587 /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
3588 #[allow(clippy::too_many_arguments)]
3589 fn decode_step_t_core_ppn(
3590 &self,
3591 e: &Engine,
3592 tokens: &[u32],
3593 pos0: usize,
3594 cache: &mut Cache,
3595 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3596 mut ckpt: Option<&mut VerifyCkpt>,
3597 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3598 fence: &[usize],
3599 pp_pipe: Option<bool>,
3600 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3601 let ticket = self.verify_stage0_issue(
3602 e,
3603 tokens,
3604 pos0,
3605 cache,
3606 embd_dev,
3607 ckpt.as_deref_mut(),
3608 stream,
3609 fence,
3610 pp_pipe,
3611 None,
3612 )?;
3613 self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
3614 }
3615
3616 /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
3617 /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
3618 #[allow(clippy::too_many_arguments)]
3619 fn verify_stage0_issue(
3620 &self,
3621 e: &Engine,
3622 tokens: &[u32],
3623 pos0: usize,
3624 cache: &mut Cache,
3625 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3626 mut ckpt: Option<&mut VerifyCkpt>,
3627 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3628 fence: &[usize],
3629 pp_pipe: Option<bool>,
3630 trace: Option<SpecPipeTraceCtx>,
3631 ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
3632 assert!(
3633 !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
3634 "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
3635 (the gemma4 arms have their own decode_step_t twins)"
3636 );
3637 if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
3638 return Err(
3639 "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
3640 boundary itself is host-staged, but device-resident verify still peer-reads \
3641 primary-device token/position/embedding buffers from stage 0. Run plain PP \
3642 serving on this host class; spec requires local per-stage inputs first."
3643 .into(),
3644 );
3645 }
3646 let rt = crate::pp::PpNRt::get(e)?;
3647 let n_st = fence.len() - 1;
3648 assert_eq!(
3649 rt.n_stages(),
3650 n_st,
3651 "PpNRt stage count {} != fence stages {n_st}",
3652 rt.n_stages()
3653 );
3654 let n_embd = self.cfg.n_embd as usize;
3655 let t = tokens.len();
3656 let payload = t * n_embd;
3657 if pp_pipe.is_some() {
3658 assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
3659 }
3660 // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
3661 // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
3662 // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
3663 // the report below names exactly two stages and must never imply it measured middle ones.
3664 let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
3665 let pp_started = std::time::Instant::now();
3666 let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
3667 // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
3668 // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
3669 // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
3670 // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
3671 // stage stream and the wait would self-order into a no-op.
3672 let caller_stream = e.stream();
3673 // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
3674 // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
3675 // the primary stream still holds queued reads of them — with event tracking elided,
3676 // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
3677 // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
3678 // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
3679 // stage stream behind the caller before enqueueing new stage work.
3680 let reverse_started = std::time::Instant::now();
3681 if pp_pipe != Some(false) {
3682 rt.fence_stages_behind(&caller_stream)?;
3683 }
3684 if pp_pipe == Some(true) {
3685 // Both session verifies must alternate boundary slots even when the ordinary
3686 // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
3687 // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
3688 rt.prepare_overlap_slots(0, payload)?;
3689 }
3690 if pp_anatomy {
3691 // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
3692 // prices any primary-stream rollback/refresh tail inherited from the prior round.
3693 for s in 0..n_st {
3694 let _st = rt.enter(s);
3695 rt.engine(s, e).stream().synchronize()?;
3696 }
3697 reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
3698 }
3699
3700 // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
3701 // stream mode each stage's own `pos_iota` over the shared read-only device counter.
3702 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3703 match stream {
3704 Some((_, ctr)) => {
3705 let mut p = es.alloc_uninit::<i32>(t)?;
3706 es.pos_iota(ctr, &mut p, t)?;
3707 Ok(p)
3708 }
3709 None => {
3710 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3711 es.htod_i32(&pos_vec)
3712 }
3713 }
3714 };
3715
3716 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
3717 let slot = {
3718 let _st0 = rt.enter(0);
3719 let e0 = rt.engine(0, e);
3720 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
3721 let stage0_started = std::time::Instant::now();
3722 let pos_d = stage_pos(e0)?;
3723 let x = match (stream, embd_dev) {
3724 (Some((vtok, _)), Some((g, qt, rb))) => {
3725 e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3726 }
3727 (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3728 _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
3729 };
3730 let x = self.verify_layers(
3731 e0,
3732 x,
3733 fence[0],
3734 fence[1],
3735 &pos_d,
3736 pos0,
3737 t,
3738 cache,
3739 ckpt.as_deref_mut(),
3740 stream,
3741 )?;
3742 if pp_anatomy {
3743 e0.stream().synchronize()?;
3744 stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
3745 }
3746 let tx_started = std::time::Instant::now();
3747 let slot = if pp_pipe.is_some() {
3748 rt.tx_pipelined(0, &x, payload)?
3749 } else {
3750 rt.tx(0, &x, payload)?
3751 };
3752 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
3753 if pp_anatomy {
3754 e0.stream().synchronize()?;
3755 tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
3756 }
3757 slot
3758 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
3759 };
3760
3761 Ok(VerifyBoundaryTicket {
3762 rt,
3763 caller_stream,
3764 slot,
3765 pos0,
3766 t,
3767 payload,
3768 n_st,
3769 pipelined: pp_pipe.is_some(),
3770 pp_anatomy,
3771 pp_started,
3772 reverse_ms,
3773 stage0_ms,
3774 tx_ms,
3775 trace,
3776 })
3777 }
3778
3779 /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
3780 /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
3781 #[allow(clippy::too_many_arguments)]
3782 fn verify_stage1_finish(
3783 &self,
3784 e: &Engine,
3785 ticket: VerifyBoundaryTicket,
3786 cache: &mut Cache,
3787 mut ckpt: Option<&mut VerifyCkpt>,
3788 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3789 fence: &[usize],
3790 publish_to_caller: bool,
3791 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3792 let VerifyBoundaryTicket {
3793 rt,
3794 caller_stream,
3795 slot,
3796 pos0,
3797 t,
3798 payload,
3799 n_st,
3800 pipelined,
3801 pp_anatomy,
3802 pp_started,
3803 reverse_ms,
3804 stage0_ms,
3805 tx_ms,
3806 trace,
3807 } = ticket;
3808 let n_embd = self.cfg.n_embd as usize;
3809 let eps = self.cfg.rms_eps;
3810 let mut slot = slot;
3811 let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
3812 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3813 match stream {
3814 Some((_, ctr)) => {
3815 let mut p = es.alloc_uninit::<i32>(t)?;
3816 es.pos_iota(ctr, &mut p, t)?;
3817 Ok(p)
3818 }
3819 None => {
3820 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3821 es.htod_i32(&pos_vec)
3822 }
3823 }
3824 };
3825
3826 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
3827 for s in 1..n_st - 1 {
3828 let _st = rt.enter(s);
3829 let es = rt.engine(s, e);
3830 let pos_d = stage_pos(es)?;
3831 let x = rt.rx(s - 1, slot, payload)?;
3832 let x = self.verify_layers(
3833 es,
3834 x,
3835 fence[s],
3836 fence[s + 1],
3837 &pos_d,
3838 pos0,
3839 t,
3840 cache,
3841 ckpt.as_deref_mut(),
3842 stream,
3843 )?;
3844 slot = if pipelined {
3845 rt.tx_pipelined(s, &x, payload)?
3846 } else {
3847 rt.tx(s, &x, payload)?
3848 };
3849 }
3850
3851 // ---- LAST STAGE: RX + final range + output_norm + lm head ----
3852 let _stl = rt.enter(n_st - 1);
3853 let el = rt.engine(n_st - 1, e);
3854 let pos_d = stage_pos(el)?;
3855 let rx_started = std::time::Instant::now();
3856 let x = rt.rx(n_st - 2, slot, payload)?;
3857 if pp_anatomy {
3858 el.stream().synchronize()?;
3859 rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
3860 }
3861 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
3862 let stage1_started = std::time::Instant::now();
3863 let x = self.verify_layers(
3864 el,
3865 x,
3866 fence[n_st - 1],
3867 fence[n_st],
3868 &pos_d,
3869 pos0,
3870 t,
3871 cache,
3872 ckpt.as_deref_mut(),
3873 stream,
3874 )?;
3875
3876 let mut hn = vbuf(el, payload)?;
3877 let logits = if self.cfg.step35.is_some() {
3878 // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
3879 // Verify must not switch numeric class merely because the same session speculates.
3880 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3881 el.matmul(&self.output, &hn, t)?
3882 } else {
3883 el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3884 el.matmul_decode_exact(&self.output, &hn, t)?
3885 };
3886 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
3887 if pp_anatomy {
3888 el.stream().synchronize()?;
3889 stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
3890 }
3891 // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
3892 // stream. Order the caller's stream behind that work before the buffers escape this
3893 // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
3894 // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
3895 // the following arm's KV in the same process).
3896 if publish_to_caller {
3897 rt.publish_to(n_st - 1, &caller_stream)?;
3898 }
3899 if pp_anatomy {
3900 if publish_to_caller {
3901 caller_stream.synchronize()?;
3902 }
3903 eprintln!(
3904 "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
3905 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
3906 pp_started.elapsed().as_secs_f64() * 1e3,
3907 );
3908 }
3909 // stream: the device pos counter owns position; host mirror reconciles at drain.
3910 if stream.is_none() {
3911 cache.pos += t;
3912 }
3913 Ok((logits, if spec_hpost() { hn } else { x }))
3914 }
3915
3916 /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
3917 ///
3918 /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
3919 /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
3920 /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
3921 /// Those classes are individually stable, but a near-tie prompt can choose different greedy
3922 /// bytes when a request moves from batched plain serving into speculative verify. Run the
3923 /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
3924 /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
3925 /// every norm/projection/FFN uses exactly the live serving dispatch.
3926 #[allow(clippy::too_many_arguments)]
3927 fn step35_verify_batch_layers(
3928 &self,
3929 e: &Engine,
3930 mut x: CudaSlice<f32>,
3931 lo: usize,
3932 hi: usize,
3933 pos0: usize,
3934 t: usize,
3935 cache: &mut Cache,
3936 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3937 let n_embd = self.cfg.n_embd as usize;
3938 self.cfg
3939 .step35
3940 .as_ref()
3941 .ok_or("step35 verify batch requires step35 cfg")?;
3942 let mut ph_last = std::time::Instant::now();
3943 for il in lo..hi {
3944 let mut next = e.uninit(t * n_embd)?;
3945 for r in 0..t {
3946 let mut row = e.uninit(n_embd)?;
3947 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
3948 // The caller owns this verify's position. During controller overlap, cache.pos
3949 // still describes generation N while this stage-0 walk belongs to N+1.
3950 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
3951 let mut one = [&mut *cache];
3952 let out = self.step35_decode_batch_layers(
3953 e,
3954 row,
3955 &mut one,
3956 &row_pos,
3957 il,
3958 il + 1,
3959 &mut ph_last,
3960 )?;
3961 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
3962 }
3963 self.dflash_tap(e, cache, il, &next, t)?;
3964 x = next;
3965 }
3966 Ok(x)
3967 }
3968
3969 /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
3970 /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
3971 /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
3972 /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
3973 /// prefix-keep, not all-or-nothing).
3974 pub(crate) fn dspark_verify_t_am(
3975 &self,
3976 e: &Engine,
3977 tokens: &[u32],
3978 pos0: usize,
3979 cache: &mut Cache,
3980 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
3981 let (logits, _hn) =
3982 self.decode_step_t_core_stream(e, tokens, pos0, cache, None, None, None, None)?;
3983 let t = tokens.len();
3984 let v = self.output.out_features();
3985 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
3986 for r in 0..t {
3987 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
3988 }
3989 Ok(e.dtoh_u32(&am_d)?)
3990 }
3991
3992 /// DSpark verify with the MTP column-stash armed: identical forward to
3993 /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
3994 /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
3995 /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
3996 pub(crate) fn dspark_verify_t_am_ckpt(
3997 &self,
3998 e: &Engine,
3999 tokens: &[u32],
4000 pos0: usize,
4001 cache: &mut Cache,
4002 ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
4003 let mut ck = VerifyCkpt::new(self.layers.len());
4004 let (logits, _hn) = self.decode_step_t_core_stream(
4005 e,
4006 tokens,
4007 pos0,
4008 cache,
4009 None,
4010 Some(&mut ck),
4011 None,
4012 None,
4013 )?;
4014 let t = tokens.len();
4015 let v = self.output.out_features();
4016 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
4017 for r in 0..t {
4018 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
4019 }
4020 Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
4021 }
4022
4023 /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
4024 /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
4025 /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
4026 pub(crate) fn dspark_commit_prefix(
4027 &self,
4028 e: &Engine,
4029 cache: &mut Cache,
4030 snap: &crate::cache::CacheSnapshot,
4031 ckpt: &DsparkVerifyCkpt,
4032 keep: usize,
4033 ) -> Result<(), Box<dyn std::error::Error>> {
4034 self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
4035 }
4036
4037 /// Qwen35-family verify trunk in the live serving numeric class.
4038 ///
4039 /// Serving intentionally keeps this architecture in the generic batched program even at
4040 /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
4041 ///
4042 /// Two arms, one numeric class:
4043 /// - DENSE (`Arch::Qwen35`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
4044 /// projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
4045 /// program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
4046 /// == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
4047 /// append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
4048 /// row's own t_kv-driven arm pick (the straddle law: every row executes the exact
4049 /// program its isolated serving step would). One weight read per layer per round
4050 /// instead of T — this is what makes MTP profitable in the exact class (the per-row
4051 /// walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
4052 /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
4053 /// serving layer body, preserving single-session autoregressive cache order (the
4054 /// correctness reference; also the rollback seam for the t-parallel arm).
4055 ///
4056 /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
4057 /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
4058 #[allow(clippy::too_many_arguments)]
4059 fn qwen35_verify_batch_layers(
4060 &self,
4061 e: &Engine,
4062 x: CudaSlice<f32>,
4063 lo: usize,
4064 hi: usize,
4065 pos0: usize,
4066 t: usize,
4067 cache: &mut Cache,
4068 ckpt: Option<&mut VerifyCkpt>,
4069 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4070 let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
4071 || !matches!(self.cfg.arch, memra_gguf::config::Arch::Qwen35)
4072 || t > 16;
4073 if rowwise {
4074 self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
4075 } else {
4076 self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt)
4077 }
4078 }
4079
4080 /// The per-row correctness reference: replay each verify row through the authoritative
4081 /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
4082 #[allow(clippy::too_many_arguments)]
4083 fn qwen35_verify_rowwise(
4084 &self,
4085 e: &Engine,
4086 mut x: CudaSlice<f32>,
4087 lo: usize,
4088 hi: usize,
4089 pos0: usize,
4090 t: usize,
4091 cache: &mut Cache,
4092 mut ckpt: Option<&mut VerifyCkpt>,
4093 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4094 let n_embd = self.cfg.n_embd as usize;
4095 let saved_pos = cache.pos;
4096 let mut ph_last = std::time::Instant::now();
4097 for il in lo..hi {
4098 let mut next = e.uninit(t * n_embd)?;
4099 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4100 if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
4101 Some(Vec::with_capacity(t - 1))
4102 } else {
4103 None
4104 };
4105 for r in 0..t {
4106 cache.pos = pos0 + r;
4107 let mut row = e.uninit(n_embd)?;
4108 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
4109 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
4110 let mut one = [&mut *cache];
4111 let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
4112 let out = match self.decode_batch_layers(
4113 e,
4114 row,
4115 &mut one,
4116 &ctx,
4117 &row_pos,
4118 &mut ph_last,
4119 ) {
4120 Ok(out) => out,
4121 Err(error) => {
4122 cache.pos = saved_pos;
4123 return Err(error);
4124 }
4125 };
4126 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
4127 if r + 1 < t {
4128 if let Some(states) = col_states.as_mut() {
4129 let recur = cache.recur[il]
4130 .as_ref()
4131 .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
4132 states.push((
4133 e.clone_dtod(&recur.conv_state)?,
4134 e.clone_dtod(&recur.ssm_state)?,
4135 ));
4136 }
4137 }
4138 }
4139 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
4140 checkpoint.cols[il] = Some(states);
4141 }
4142 x = next;
4143 }
4144 cache.pos = saved_pos;
4145 Ok(x)
4146 }
4147
4148 /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
4149 ///
4150 /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
4151 /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
4152 /// pins the serving batch tier already carries:
4153 /// * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
4154 /// kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
4155 /// alone;
4156 /// * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
4157 /// `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
4158 /// launch is the per-row program (same pin the generic verify's fused norms rely on).
4159 /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
4160 /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
4161 /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
4162 /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
4163 /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
4164 /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
4165 /// program its isolated B=1 serving step would.
4166 ///
4167 /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
4168 /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
4169 #[allow(clippy::too_many_arguments)]
4170 fn qwen35_verify_tparallel(
4171 &self,
4172 e: &Engine,
4173 mut x: CudaSlice<f32>,
4174 lo: usize,
4175 hi: usize,
4176 pos0: usize,
4177 t: usize,
4178 cache: &mut Cache,
4179 mut ckpt: Option<&mut VerifyCkpt>,
4180 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4181 use cudarc::driver::DevicePtr;
4182 let cfg = &self.cfg;
4183 let n_embd = cfg.n_embd as usize;
4184 let eps = cfg.rms_eps;
4185 let head_dim_global = cfg.head_dim_k as usize;
4186 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
4187 let pos_d = e.htod_i32(&pos_host)?;
4188 // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
4189 // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
4190 let pos_rows: Vec<CudaSlice<i32>> = (0..t)
4191 .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
4192 .collect::<Result<_, _>>()?;
4193 let seqs_append =
4194 std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
4195 let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
4196
4197 for il in lo..hi {
4198 let layer = &self.layers[il];
4199 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
4200 let anorm = layer.attn_norm.float_data();
4201 let mut xn = e.uninit(t * n_embd)?;
4202 e.rms_norm(&x, anorm, &mut xn, n_embd, t, eps)?;
4203 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
4204
4205 let mixed: CudaSlice<f32> = match &layer.mixer {
4206 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4207 Mixer::Full(fa) => {
4208 let geometry = cfg.full_attention_geometry_at(il as u32);
4209 let n_head = geometry.n_head as usize;
4210 let n_head_kv = geometry.n_head_kv as usize;
4211 let head_dim = geometry.head_dim_k as usize;
4212 let rope_dims = geometry.n_rot as usize;
4213 let rope_base = geometry.rope_base;
4214 let scale = geometry.attention_scale();
4215 // Batched projections: one weight read serves all T rows.
4216 let qf = e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?;
4217 let mut k = e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?;
4218 let v = e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?;
4219 let gated =
4220 geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
4221 let (mut q, gate) = if gated {
4222 let mut qs = e.uninit(t * n_head * head_dim)?;
4223 let mut gs = e.uninit(t * n_head * head_dim)?;
4224 e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
4225 (qs, Some(gs))
4226 } else {
4227 (qf, None)
4228 };
4229 let mut qn = e.uninit(t * n_head * head_dim)?;
4230 e.rms_norm(
4231 &q,
4232 fa.q_norm.float_data(),
4233 &mut qn,
4234 head_dim,
4235 t * n_head,
4236 eps,
4237 )?;
4238 q = qn;
4239 let mut kn = e.uninit(t * n_head_kv * head_dim)?;
4240 e.rms_norm(
4241 &k,
4242 fa.k_norm.float_data(),
4243 &mut kn,
4244 head_dim,
4245 t * n_head_kv,
4246 eps,
4247 )?;
4248 k = kn;
4249 e.rope_neox(
4250 &mut q, &pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
4251 )?;
4252 e.rope_neox(
4253 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
4254 )?;
4255
4256 // Per-row append + attend: row r sees rows 0..r in KV (causal within the
4257 // draft), each through the b_n=1 serving kernels at its own t_kv.
4258 let q_dim = n_head * head_dim;
4259 let kv_dim = n_head_kv * head_dim;
4260 let mut attn = e.uninit(t * q_dim)?;
4261 let (kdk, kdv, ktb, vtb, kv_view) = {
4262 let kvl = cache.kv[il].as_ref().unwrap();
4263 let s = &e.gpu.stream();
4264 let (pk, _g) = kvl.k.device_ptr(s);
4265 let (pv, _g2) = kvl.v.device_ptr(s);
4266 (
4267 kvl.kv_dim_k,
4268 kvl.kv_dim_v,
4269 kvl.k_tok_bytes,
4270 kvl.v_tok_bytes,
4271 e.htod_u64(&[pk as u64, pv as u64])?,
4272 )
4273 };
4274 for r in 0..t {
4275 // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
4276 // whose row 0 is this row (arithmetic-free materialization copies,
4277 // same as decode's per-seq fallback arm).
4278 let mut k_row = e.uninit(kv_dim)?;
4279 e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
4280 let mut v_row = e.uninit(kv_dim)?;
4281 e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
4282 let pos_row = &pos_rows[r];
4283 let kvl = cache.kv[il].as_mut().unwrap();
4284 if seqs_append {
4285 e.append_kv_quantized_seqs(
4286 &k_row,
4287 &v_row,
4288 &kv_view.slice(0..2),
4289 pos_row,
4290 1,
4291 kdk,
4292 kdv,
4293 ktb,
4294 vtb,
4295 )?;
4296 kvl.len += 1;
4297 } else {
4298 e.append_kv_quantized_view(
4299 &k_row.slice(0..kv_dim),
4300 &v_row.slice(0..kv_dim),
4301 &mut kvl.k,
4302 &mut kvl.v,
4303 kvl.len,
4304 kvl.kv_dim_k,
4305 kvl.kv_dim_v,
4306 kvl.k_tok_bytes,
4307 kvl.v_tok_bytes,
4308 Engine::kv_fp8_on(),
4309 )?;
4310 kvl.len += 1;
4311 }
4312 let t_kv = kvl.len;
4313 let mut q_row = e.uninit(q_dim)?;
4314 e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
4315 let mut a_row = e.uninit(q_dim)?;
4316 if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
4317 let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
4318 e.fa_decode_batch_seqs_v4(
4319 &q_row,
4320 &kv_view.slice(0..2),
4321 pos_row,
4322 &mut a_row,
4323 head_dim,
4324 n_head,
4325 n_head_kv,
4326 1,
4327 t_kv,
4328 scale,
4329 sp0_r,
4330 ktb,
4331 vtb,
4332 )?;
4333 } else {
4334 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
4335 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
4336 let mut a_view = a_row.slice_mut(0..q_dim);
4337 e.fa_decode_kvmod_view(
4338 &q_row.slice(0..q_dim),
4339 &k_view,
4340 &v_view,
4341 &mut a_view,
4342 head_dim,
4343 n_head,
4344 n_head_kv,
4345 t_kv,
4346 scale,
4347 kvl.k_tok_bytes,
4348 kvl.v_tok_bytes,
4349 Engine::kv_fp8_on(),
4350 )?;
4351 }
4352 e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
4353 }
4354
4355 // Output gate (element-wise) + o-proj at m=T.
4356 let attn_g = match &gate {
4357 Some(g) => {
4358 let n = t * q_dim;
4359 let mut gsig = e.uninit(n)?;
4360 e.sigmoid(g, &mut gsig, n)?;
4361 let mut ag = e.uninit(n)?;
4362 e.mul(&attn, &gsig, &mut ag, n)?;
4363 ag
4364 }
4365 None => attn,
4366 };
4367 e.matmul(&fa.wo, &attn_g, t)?
4368 }
4369 Mixer::Linear(la) => {
4370 let ssm = cfg.ssm.as_ref().expect("linear mixer requires ssm cfg");
4371 let d_state = ssm.state_size as usize;
4372 let num_k = ssm.group_count as usize;
4373 let num_v = ssm.time_step_rank as usize;
4374 let d_conv = ssm.conv_kernel as usize;
4375 let key_dim = d_state * num_k;
4376 let value_dim = d_state * num_v;
4377 let conv_dim = key_dim * 2 + value_dim;
4378 let gdn_scale = 1.0 / (d_state as f32).sqrt();
4379
4380 // ---- batched projections: one weight read for all T rows ----
4381 let qkv_mixed = e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?;
4382 let z = e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?;
4383 let beta_raw = e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?;
4384 let alpha = e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?;
4385 let beta_w = la.ssm_beta.out_features();
4386 let alpha_w = la.ssm_alpha.out_features();
4387 let qkv_w = la.wqkv.out_features();
4388
4389 // ---- per-row state chain through the b_n=1 serving kernels ----
4390 // 6-entry alternating pointer table expresses the ping-pong without a
4391 // rebuild per row: even rows scan s0 -> s1, odd rows s1 -> s0. Host
4392 // handles swap per row so ckpt clones the canonical state (and the
4393 // post-verify canonical handle matches the last write), exactly as the
4394 // rowwise arm leaves them.
4395 let table = {
4396 let rl = cache.recur[il].as_ref().unwrap();
4397 let s = &e.gpu.stream();
4398 let (pc, _g0) = rl.conv_state.device_ptr(s);
4399 let (p0, _g1) = rl.ssm_state.device_ptr(s);
4400 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
4401 e.htod_u64(&[
4402 pc as u64, p0 as u64, p1 as u64, pc as u64, p1 as u64, p0 as u64,
4403 ])?
4404 };
4405 let mut o_all = e.uninit(t * value_dim)?;
4406 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4407 if ckpt.is_some() && t >= 2 {
4408 Some(Vec::with_capacity(t - 1))
4409 } else {
4410 None
4411 };
4412 // Per-row scratch reused across rows (uninit is cheap but not free at
4413 // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
4414 // [T, ...] buffers — zero arithmetic-free copies in this loop.
4415 let mut conv_out = e.uninit(conv_dim)?;
4416 let mut q_l2 = e.uninit(value_dim)?;
4417 let mut k_l2 = e.uninit(value_dim)?;
4418 let mut v_gd = e.uninit(value_dim)?;
4419 let mut beta_b = e.uninit(num_v)?;
4420 let mut g_log = e.uninit(num_v)?;
4421 for r in 0..t {
4422 let base = if r % 2 == 0 { 0 } else { 3 };
4423 let conv_view = table.slice(base..base + 1);
4424 let in_view = table.slice(base + 1..base + 2);
4425 let out_view = table.slice(base + 2..base + 3);
4426 e.ssm_conv1d_fused_decode_b_view(
4427 &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
4428 &conv_view,
4429 la.ssm_conv1d.float_data(),
4430 &mut conv_out,
4431 conv_dim,
4432 d_conv,
4433 1,
4434 )?;
4435 e.gdn_prep_decode_b_view(
4436 &conv_out,
4437 &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
4438 &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
4439 la.ssm_dt.float_data(),
4440 la.ssm_a.float_data(),
4441 &mut q_l2,
4442 &mut k_l2,
4443 &mut v_gd,
4444 &mut beta_b,
4445 &mut g_log,
4446 d_state,
4447 num_v,
4448 num_k,
4449 key_dim,
4450 eps,
4451 conv_dim,
4452 1,
4453 )?;
4454 let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
4455 e.gdn_scan_s128_batched_view(
4456 &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row,
4457 num_v, 1, gdn_scale,
4458 )?;
4459 {
4460 let rl = cache.recur[il].as_mut().unwrap();
4461 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
4462 }
4463 if r + 1 < t {
4464 if let Some(states) = col_states.as_mut() {
4465 let recur = cache.recur[il]
4466 .as_ref()
4467 .ok_or("qwen35 linear verify layer has no recurrent state")?;
4468 states.push((
4469 e.clone_dtod(&recur.conv_state)?,
4470 e.clone_dtod(&recur.ssm_state)?,
4471 ));
4472 }
4473 }
4474 }
4475 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
4476 checkpoint.cols[il] = Some(states);
4477 }
4478
4479 // ---- batched gated norm + out-projection at m=T ----
4480 if e.uses_q8_1_fast(&la.ssm_out) {
4481 let (gq, gd) = e.gated_rmsnorm_q8_1(
4482 &o_all,
4483 la.ssm_norm.float_data(),
4484 &z,
4485 d_state,
4486 t * num_v,
4487 eps,
4488 )?;
4489 let g0 = e.zeros(0)?;
4490 e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
4491 } else {
4492 let mut gn = e.uninit(t * value_dim)?;
4493 e.gated_rmsnorm(
4494 &o_all,
4495 la.ssm_norm.float_data(),
4496 &z,
4497 &mut gn,
4498 d_state,
4499 t * num_v,
4500 eps,
4501 )?;
4502 e.matmul(&la.ssm_out, &gn, t)?
4503 }
4504 }
4505 };
4506
4507 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
4508 let pnorm = layer.post_attn_norm.float_data();
4509 let mut x1 = e.uninit(t * n_embd)?;
4510 let mut zn = e.uninit(t * n_embd)?;
4511 e.add_rms_norm(&x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
4512 let ffn_out = match &layer.ffn {
4513 crate::hybrid::Ffn::Dense {
4514 ffn_gate,
4515 ffn_up,
4516 ffn_down,
4517 } => {
4518 assert!(
4519 self.cfg.m3.is_none(),
4520 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
4521 );
4522 let n_ff = ffn_gate.out_features();
4523 let (zq, zd) = e.quantize_q8_1(&zn, t, n_embd)?;
4524 let g = e.matmul_pre(ffn_gate, &zq, &zd, &zn, t)?;
4525 let u = e.matmul_pre(ffn_up, &zq, &zd, &zn, t)?;
4526 let mut act = e.uninit(t * n_ff)?;
4527 e.silu_mul(&g, &u, &mut act, t * n_ff)?;
4528 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
4529 e.matmul_pre(ffn_down, &aq, &ad, &act, t)?
4530 }
4531 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
4532 };
4533 let mut x2 = e.uninit(t * n_embd)?;
4534 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
4535 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
4536 self.dflash_tap(e, cache, il, &x2, t)?;
4537 x = x2;
4538 }
4539 Ok(x)
4540 }
4541
4542 /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
4543 /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
4544 /// carried in from outside the range) and exits with the range's final residual materialized
4545 /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
4546 /// instead of one.
4547 ///
4548 /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
4549 /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
4550 /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
4551 /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
4552 /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
4553 /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
4554 /// code — there is no "split version" of the verify math.
4555 ///
4556 /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
4557 /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
4558 /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
4559 /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
4560 #[allow(clippy::too_many_arguments)]
4561 fn verify_layers(
4562 &self,
4563 e: &Engine,
4564 mut x: CudaSlice<f32>,
4565 lo: usize,
4566 hi: usize,
4567 pos_d: &CudaSlice<i32>,
4568 pos0: usize,
4569 t: usize,
4570 cache: &mut Cache,
4571 mut ckpt: Option<&mut VerifyCkpt>,
4572 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4573 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4574 if self.cfg.step35.is_some() {
4575 if stream.is_some() {
4576 return Err(
4577 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
4578 cannot express the SWA offset KV view)"
4579 .into(),
4580 );
4581 }
4582 return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
4583 }
4584 if self.qwen35_serving_class() {
4585 if stream.is_some() {
4586 return Err("qwen35-family serving-class verify has no ROUND-STREAM arm".into());
4587 }
4588 return self.qwen35_verify_batch_layers(e, x, lo, hi, pos0, t, cache, ckpt.take());
4589 }
4590 let n_embd = self.cfg.n_embd as usize;
4591 let eps = self.cfg.rms_eps;
4592 // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
4593 // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
4594 // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
4595 // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
4596 // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
4597 // residual the next layer needs) as its `res` output. Falls back to the separate add
4598 // when the next layer is off the fused-q8 path.
4599 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
4600 for il in lo..hi {
4601 let layer = &self.layers[il];
4602 // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
4603 // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
4604 // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
4605 // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
4606 // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
4607 // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
4608 // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
4609 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
4610 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
4611 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
4612 // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
4613 // projections only; Linear mixer: the batched arm — the per-column fallback needs
4614 // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
4615 // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
4616 // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
4617 // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
4618 // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
4619 // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
4620 // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
4621 // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
4622 let lin_q8_only = match &layer.mixer {
4623 Mixer::Linear(la) => {
4624 (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
4625 }
4626 Mixer::Full(_) if self.cfg.step35.is_some() => false,
4627 _ => true,
4628 };
4629 // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
4630 // a non-fused layer still performs the residual add.
4631 let taken = pending.take();
4632 let (h, h_q8) = if norm_fused && lin_q8_only {
4633 let pair = match taken {
4634 // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
4635 // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
4636 Some((x1p, f1p)) => {
4637 let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
4638 let p = e.add_rms_norm_q8_1(
4639 &x1p,
4640 &f1p,
4641 layer.attn_norm.float_data(),
4642 &mut x2,
4643 n_embd,
4644 t,
4645 eps,
4646 )?;
4647 x = x2;
4648 p
4649 }
4650 None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
4651 };
4652 (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
4653 } else {
4654 if let Some((x1p, f1p)) = taken {
4655 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
4656 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
4657 x = x2;
4658 }
4659 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
4660 if norm_fused {
4661 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4662 } else {
4663 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4664 }
4665 (h, None)
4666 };
4667 let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
4668
4669 let mixed = match &layer.mixer {
4670 Mixer::Full(fa) => self.full_attn_verify(
4671 e,
4672 fa,
4673 &h,
4674 h_q8_ref,
4675 pos_d,
4676 t,
4677 cache,
4678 il,
4679 stream.map(|(_, c)| c),
4680 )?,
4681 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4682 Mixer::Linear(la) => {
4683 // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
4684 // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
4685 // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
4686 // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
4687 // chained T=1 steps (bit-identical). Falls back to the sequential per-column
4688 // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
4689 // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
4690 // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
4691 // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
4692 // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
4693 // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
4694 if (t >= 3 || (t == 2 && spec_m2()))
4695 && mixer_fast
4696 && e.uses_q8_1_fast(&la.ssm_out)
4697 {
4698 let want = ckpt.is_some();
4699 let (out, stash) =
4700 self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
4701 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
4702 ck.gdn[il] = Some(st);
4703 }
4704 out
4705 } else {
4706 let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
4707 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4708 if ckpt.is_some() && t >= 2 {
4709 Some(Vec::with_capacity(t - 1))
4710 } else {
4711 None
4712 };
4713 for col in 0..t {
4714 let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
4715 let src = h.slice(col * n_embd..(col + 1) * n_embd);
4716 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
4717 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
4718 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
4719 // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
4720 // (pure dtod — cannot change any computed value). Last column skipped:
4721 // rebuild targets are j <= t-1 columns.
4722 if let Some(cs) = col_states.as_mut() {
4723 if col + 1 < t {
4724 let rl = cache.recur[il].as_ref().unwrap();
4725 cs.push((
4726 e.clone_dtod(&rl.conv_state)?,
4727 e.clone_dtod(&rl.ssm_state)?,
4728 ));
4729 }
4730 }
4731 }
4732 if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
4733 // ReplaySSM-assessment instrumentation (2026-07-30): the
4734 // per-column clones are the only true state snapshots left in
4735 // the verify (the batched path stashes INPUTS and replays).
4736 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
4737 static ONCE: std::sync::Once = std::sync::Once::new();
4738 let bytes: usize =
4739 cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
4740 ONCE.call_once(|| eprintln!(
4741 "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
4742 cs.len(), bytes as f64 / 1e6));
4743 }
4744 ck.cols[il] = Some(cs);
4745 }
4746 out
4747 }
4748 }
4749 };
4750
4751 // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
4752 // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
4753 // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
4754 let ffn_fuse = match &layer.ffn {
4755 crate::hybrid::Ffn::Dense {
4756 ffn_gate, ffn_up, ..
4757 } => {
4758 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
4759 && e.uses_q8_1_fast(ffn_gate)
4760 && e.uses_q8_1_fast(ffn_up)
4761 }
4762 crate::hybrid::Ffn::Moe(_) => false,
4763 };
4764 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
4765 // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
4766 // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
4767 // per-row m=1 program; kernel-check pins bit-identity vs the unfused
4768 // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
4769 // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
4770 // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
4771 // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
4772 // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
4773 // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
4774 // mirror decode's dispatch or spec self-consistency fails.
4775 let dense_lim = self.cfg.clamp_shexp_at(il as u32);
4776 let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
4777 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
4778 let mut z = e.zeros(0)?; // replaced below on the unfused arms
4779 let z_q8 = if fuse_q8 {
4780 Some(e.add_rms_norm_q8_1(
4781 &x,
4782 &mixed,
4783 layer.post_attn_norm.float_data(),
4784 &mut x1,
4785 n_embd,
4786 t,
4787 eps,
4788 )?)
4789 } else {
4790 let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
4791 if ffn_fuse {
4792 e.add(&x, &mixed, &mut x1, t * n_embd)?;
4793 e.rms_norm_decode(
4794 &x1,
4795 layer.post_attn_norm.float_data(),
4796 &mut zf,
4797 n_embd,
4798 t,
4799 eps,
4800 )?;
4801 } else {
4802 e.add_rms_norm(
4803 &x,
4804 &mixed,
4805 layer.post_attn_norm.float_data(),
4806 &mut x1,
4807 &mut zf,
4808 n_embd,
4809 t,
4810 eps,
4811 )?;
4812 }
4813 z = zf;
4814 None
4815 };
4816 // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
4817 // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
4818 // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
4819 let ffn_out = match &layer.ffn {
4820 crate::hybrid::Ffn::Dense {
4821 ffn_gate,
4822 ffn_up,
4823 ffn_down,
4824 } => {
4825 let n_ff = ffn_gate.out_features();
4826 if let Some((zq, zd)) = z_q8.as_ref() {
4827 // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
4828 // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
4829 // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
4830 // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
4831 // scale_inplace store, value-exact) — the exact m=1 decode epilogue
4832 // structure at nrows=t.
4833 let pair =
4834 match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
4835 Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
4836 None => None,
4837 };
4838 let (gate, gs, up, us) = match pair {
4839 Some(x4) => x4,
4840 None => (
4841 e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
4842 1.0, // scale already applied inside _pre
4843 e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
4844 1.0,
4845 ),
4846 };
4847 if e.uses_q8_1_fast(ffn_down) {
4848 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
4849 e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
4850 } else {
4851 let mut act = vbuf(e, t * n_ff)?;
4852 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
4853 e.matmul_decode_exact(ffn_down, &act, t)?
4854 }
4855 } else {
4856 // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
4857 // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
4858 // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
4859 // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
4860 // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
4861 let (gate, up) =
4862 match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
4863 Some(pair) => pair,
4864 None => (
4865 e.matmul_decode_exact(ffn_gate, &z, t)?,
4866 e.matmul_decode_exact(ffn_up, &z, t)?,
4867 ),
4868 };
4869 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
4870 Self::ffn_act_lim(
4871 e,
4872 &self.cfg,
4873 &gate,
4874 &up,
4875 1.0,
4876 1.0,
4877 dense_lim,
4878 &mut act,
4879 t * n_ff,
4880 )?;
4881 e.matmul_decode_exact(ffn_down, &act, t)?
4882 }
4883 }
4884 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
4885 };
4886 // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
4887 // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
4888 // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
4889 pending = Some((x1, ffn_out));
4890 }
4891 // RANGE's final add (no next norm INSIDE the range to fuse with; for the
4892 // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
4893 if let Some((x1p, f1p)) = pending.take() {
4894 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
4895 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
4896 x = x2;
4897 }
4898 Ok(x)
4899 }
4900 /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
4901 /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
4902 /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
4903 /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
4904 /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
4905 /// ssm state exactly like T sequential decode steps.
4906 /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
4907 /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
4908 #[allow(clippy::too_many_arguments)]
4909 fn linear_attn_verify_t(
4910 &self,
4911 e: &Engine,
4912 la: &LinearAttnLayer,
4913 h: &CudaSlice<f32>,
4914 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
4915 t: usize,
4916 cache: &mut Cache,
4917 il: usize,
4918 want_stash: bool,
4919 ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
4920 let cfg = &self.cfg;
4921 let ssm = cfg.ssm.as_ref().unwrap();
4922 let d_state = ssm.state_size as usize;
4923 let num_k = ssm.group_count as usize;
4924 let num_v = ssm.time_step_rank as usize;
4925 let d_conv = ssm.conv_kernel as usize;
4926 let key_dim = d_state * num_k;
4927 let conv_dim = key_dim * 2 + d_state * num_v;
4928 let eps = cfg.rms_eps;
4929 let scale = 1.0 / (d_state as f32).sqrt();
4930
4931 // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
4932 // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
4933 // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
4934 // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
4935 // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
4936 // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
4937 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
4938 // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
4939 // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
4940 // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
4941 // Bit-identical per (tensor,token,row) — see spec_fused_t().
4942 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
4943 // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
4944 // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
4945 // and feeds every projection; the caller guaranteed all four input projections are
4946 // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
4947 let h_q8_t = if h_q8.is_none()
4948 && spec_fused_t()
4949 && (2..=4).contains(&t)
4950 && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
4951 || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
4952 {
4953 Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
4954 } else {
4955 None
4956 };
4957 // one view: the caller's fused-norm q8 or this fn's own shared quantize.
4958 let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
4959 h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
4960 let (qkv_mixed, z) = {
4961 let mut fused = None;
4962 if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
4963 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
4964 fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
4965 } else if let Some((hq, hd)) = hq8_any {
4966 if spec_fused_t() && (2..=4).contains(&t) {
4967 fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
4968 }
4969 }
4970 match (fused, hq8_any) {
4971 (Some(pair), _) => pair,
4972 (None, Some((hq, hd))) if h_q8.is_some() => (
4973 e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
4974 e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
4975 ),
4976 (None, _) => (
4977 e.matmul_decode_exact(&la.wqkv, h, t)?,
4978 e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
4979 ),
4980 }
4981 };
4982 // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
4983 // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
4984 // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
4985 // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
4986 let (beta_raw, alpha) = if t == 1 {
4987 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
4988 match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
4989 Some(((mut b, bs), (mut a, as_))) => {
4990 if bs != 1.0 {
4991 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
4992 }
4993 if as_ != 1.0 {
4994 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
4995 }
4996 (b, a)
4997 }
4998 // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
4999 // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
5000 // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
5001 None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
5002 Some((b, a)) => (b, a),
5003 None => (
5004 e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
5005 e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
5006 ),
5007 },
5008 }
5009 } else {
5010 // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
5011 // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
5012 let mut nvfp4_fused = None;
5013 let mut q8_fused = None;
5014 if let Some((hq, hd)) = hq8_any {
5015 if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
5016 nvfp4_fused =
5017 e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
5018 if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
5019 static ONCE: std::sync::Once = std::sync::Once::new();
5020 ONCE.call_once(|| {
5021 eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
5022 });
5023 }
5024 }
5025 if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
5026 q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
5027 }
5028 }
5029 if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
5030 if bs != 1.0 {
5031 e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
5032 }
5033 if as_ != 1.0 {
5034 e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
5035 }
5036 (b, a)
5037 } else if let Some(pair) = q8_fused {
5038 pair
5039 } else {
5040 match hq8_any {
5041 Some((hq, hd)) if h_q8.is_some() => (
5042 e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
5043 e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
5044 ),
5045 _ => (
5046 e.matmul_decode_exact(&la.ssm_beta, h, t)?,
5047 e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
5048 ),
5049 }
5050 }
5051 };
5052
5053 // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
5054 // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
5055 let rl = cache.recur[il].as_mut().unwrap();
5056 let mut conv_out = e.uninit(conv_dim * t)?;
5057 e.ssm_conv1d_tm_state(
5058 &qkv_mixed,
5059 &mut rl.conv_state,
5060 la.ssm_conv1d.float_data(),
5061 &mut conv_out,
5062 conv_dim,
5063 t,
5064 d_conv,
5065 )?;
5066
5067 // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
5068 let mut q_g = e.uninit(d_state * num_v * t)?;
5069 let mut k_g = e.uninit(d_state * num_v * t)?;
5070 let mut v_g = e.uninit(d_state * num_v * t)?;
5071 e.qkv_to_gdn_repack(
5072 &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
5073 )?;
5074 let mut q_l2 = e.uninit(d_state * num_v * t)?;
5075 e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
5076 let mut k_l2 = e.uninit(d_state * num_v * t)?;
5077 e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
5078 let mut beta = e.uninit(t * num_v)?;
5079 e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
5080 let mut g_log = e.uninit(t * num_v)?;
5081 e.gdn_glog(
5082 &alpha,
5083 la.ssm_dt.float_data(),
5084 la.ssm_a.float_data(),
5085 &mut g_log,
5086 num_v,
5087 t,
5088 )?;
5089
5090 // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
5091 // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
5092 let mut o = e.uninit(d_state * num_v * t)?;
5093 {
5094 let crate::cache::RecurLayer {
5095 ssm_state,
5096 ssm_state_alt,
5097 ..
5098 } = rl;
5099 e.gdn_scan_s128(
5100 &q_l2,
5101 &k_l2,
5102 &v_g,
5103 &g_log,
5104 &beta,
5105 ssm_state,
5106 ssm_state_alt,
5107 &mut o,
5108 num_v,
5109 t,
5110 scale,
5111 )?;
5112 }
5113 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
5114
5115 // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
5116 // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
5117 // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
5118 // T-wide launch is the per-row program; kernel-check pins bit-identity vs
5119 // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
5120 // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
5121 let out = if e.uses_q8_1_fast(&la.ssm_out) {
5122 let (gq, gd) =
5123 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
5124 e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
5125 } else {
5126 let mut gn = e.uninit(d_state * num_v * t)?;
5127 e.gated_rmsnorm(
5128 &o,
5129 la.ssm_norm.float_data(),
5130 &z,
5131 &mut gn,
5132 d_state,
5133 num_v * t,
5134 eps,
5135 )?;
5136 // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
5137 // would fall to dp4a with a different FP reduction order — same class of bug as
5138 // the input projs).
5139 e.matmul_decode_exact(&la.ssm_out, &gn, t)?
5140 };
5141 let stash = if want_stash {
5142 Some(GdnStash {
5143 qkv_mixed,
5144 q_l2,
5145 k_l2,
5146 v_g,
5147 g_log,
5148 beta,
5149 })
5150 } else {
5151 None
5152 };
5153 Ok((out, stash))
5154 }
5155
5156 /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
5157 /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
5158 /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
5159 /// are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
5160 /// verify-probe gates), so keeping them == replaying them.
5161 /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
5162 /// columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
5163 /// snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
5164 /// registers and writes it once at the end, so iterations 0..j-1 are independent of T:
5165 /// bit-identical to the verify's own state after j tokens == the eager chain state.
5166 /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
5167 /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
5168 fn commit_verified_prefix(
5169 &self,
5170 e: &Engine,
5171 cache: &mut Cache,
5172 snap: &crate::cache::CacheSnapshot,
5173 ckpt: &VerifyCkpt,
5174 j: usize,
5175 kv_lens_done: bool,
5176 dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
5177 ) -> Result<(), Box<dyn std::error::Error>> {
5178 let cfg = &self.cfg;
5179 let ssm = cfg.ssm.as_ref().unwrap();
5180 let d_state = ssm.state_size as usize;
5181 let num_k = ssm.group_count as usize;
5182 let num_v = ssm.time_step_rank as usize;
5183 let d_conv = ssm.conv_kernel as usize;
5184 let conv_dim = d_state * num_k * 2 + d_state * num_v;
5185 let scale = 1.0 / (d_state as f32).sqrt();
5186 for il in 0..self.layers.len() {
5187 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
5188 kvl.len = saved + j;
5189 // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
5190 if !kv_lens_done {
5191 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
5192 }
5193 }
5194 if let Some(rl) = cache.recur[il].as_mut() {
5195 if let Some(st) = &ckpt.gdn[il] {
5196 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
5197 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
5198 if let Some((acc, base, t_v)) = dev_j {
5199 // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
5200 e.ssm_conv_ring_rebuild_dc(
5201 &st.qkv_mixed,
5202 ring_old,
5203 &mut rl.conv_state,
5204 conv_dim,
5205 acc,
5206 base,
5207 t_v,
5208 d_conv,
5209 )?;
5210 let mut o = e.uninit(d_state * num_v * j.max(1))?;
5211 e.gdn_scan_s128_dc(
5212 &st.q_l2,
5213 &st.k_l2,
5214 &st.v_g,
5215 &st.g_log,
5216 &st.beta,
5217 state_in,
5218 &mut rl.ssm_state,
5219 &mut o,
5220 num_v,
5221 acc,
5222 base,
5223 t_v,
5224 scale,
5225 )?;
5226 } else {
5227 e.ssm_conv_ring_rebuild(
5228 &st.qkv_mixed,
5229 ring_old,
5230 &mut rl.conv_state,
5231 conv_dim,
5232 j,
5233 d_conv,
5234 )?;
5235 let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
5236 e.gdn_scan_s128(
5237 &st.q_l2,
5238 &st.k_l2,
5239 &st.v_g,
5240 &st.g_log,
5241 &st.beta,
5242 state_in,
5243 &mut rl.ssm_state,
5244 &mut o,
5245 num_v,
5246 j,
5247 scale,
5248 )?;
5249 }
5250 } else if let Some(cols) = &ckpt.cols[il] {
5251 let (c, s) = &cols[j - 1];
5252 e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
5253 e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
5254 } else {
5255 return Err(
5256 "commit_verified_prefix: verify ckpt missing for linear layer".into(),
5257 );
5258 }
5259 }
5260 }
5261 cache.pos = snap.pos + j;
5262 Ok(())
5263 }
5264
5265 /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
5266 /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
5267 fn commit_verified_prefix_stream(
5268 &self,
5269 e: &Engine,
5270 cache: &mut Cache,
5271 snap: &crate::cache::CacheSnapshot,
5272 ckpt: &VerifyCkpt,
5273 acc: &CudaSlice<u32>,
5274 base: usize,
5275 t_v: usize,
5276 ) -> Result<(), Box<dyn std::error::Error>> {
5277 let cfg = &self.cfg;
5278 let ssm = cfg.ssm.as_ref().unwrap();
5279 let d_state = ssm.state_size as usize;
5280 let num_k = ssm.group_count as usize;
5281 let num_v = ssm.time_step_rank as usize;
5282 let d_conv = ssm.conv_kernel as usize;
5283 let conv_dim = d_state * num_k * 2 + d_state * num_v;
5284 let scale = 1.0 / (d_state as f32).sqrt();
5285 for il in 0..self.layers.len() {
5286 if let Some(rl) = cache.recur[il].as_mut() {
5287 let st = ckpt.gdn[il]
5288 .as_ref()
5289 .ok_or("stream restore: batched-linear stash missing")?;
5290 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
5291 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
5292 e.ssm_conv_ring_rebuild_dc(
5293 &st.qkv_mixed,
5294 ring_old,
5295 &mut rl.conv_state,
5296 conv_dim,
5297 acc,
5298 base,
5299 t_v,
5300 d_conv,
5301 )?;
5302 let mut o = e.uninit(d_state * num_v * t_v)?;
5303 e.gdn_scan_s128_dc(
5304 &st.q_l2,
5305 &st.k_l2,
5306 &st.v_g,
5307 &st.g_log,
5308 &st.beta,
5309 state_in,
5310 &mut rl.ssm_state,
5311 &mut o,
5312 num_v,
5313 acc,
5314 base,
5315 t_v,
5316 scale,
5317 )?;
5318 }
5319 }
5320 Ok(())
5321 }
5322
5323 /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
5324 /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
5325 /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
5326 /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
5327 /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
5328 pub fn decode_step_t_aux2(
5329 &self,
5330 e: &Engine,
5331 tokens: &[u32],
5332 pos0: usize,
5333 cache: &mut Cache,
5334 aux_layers: &[usize],
5335 pred_col: Option<usize>,
5336 ) -> Result<
5337 (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
5338 Box<dyn std::error::Error>,
5339 > {
5340 let cfg = &self.cfg;
5341 let n_embd = cfg.n_embd as usize;
5342 let eps = cfg.rms_eps;
5343 let t = tokens.len();
5344 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
5345 let pos_d = e.htod_i32(&pos_vec)?;
5346 let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
5347 let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
5348 let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
5349 let want_pred = pred_col.is_some();
5350
5351 for (il, layer) in self.layers.iter().enumerate() {
5352 // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
5353 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
5354 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
5355 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
5356 if norm_fused {
5357 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5358 } else {
5359 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5360 }
5361 let mixed = match &layer.mixer {
5362 Mixer::Full(fa) => {
5363 self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
5364 }
5365 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
5366 Mixer::Linear(la) => {
5367 let mut out = e.zeros(t * n_embd)?;
5368 for col in 0..t {
5369 let mut h_col = e.zeros(n_embd)?;
5370 let src = h.slice(col * n_embd..(col + 1) * n_embd);
5371 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
5372 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
5373 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
5374 }
5375 out
5376 }
5377 };
5378 let ffn_fuse = match &layer.ffn {
5379 crate::hybrid::Ffn::Dense {
5380 ffn_gate, ffn_up, ..
5381 } => {
5382 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
5383 && e.uses_q8_1_fast(ffn_gate)
5384 && e.uses_q8_1_fast(ffn_up)
5385 }
5386 crate::hybrid::Ffn::Moe(_) => false,
5387 };
5388 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
5389 let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
5390 if ffn_fuse {
5391 e.add(&x, &mixed, &mut x1, t * n_embd)?;
5392 e.rms_norm_decode(
5393 &x1,
5394 layer.post_attn_norm.float_data(),
5395 &mut z,
5396 n_embd,
5397 t,
5398 eps,
5399 )?;
5400 } else {
5401 e.add_rms_norm(
5402 &x,
5403 &mixed,
5404 layer.post_attn_norm.float_data(),
5405 &mut x1,
5406 &mut z,
5407 n_embd,
5408 t,
5409 eps,
5410 )?;
5411 }
5412 let ffn_out = match &layer.ffn {
5413 crate::hybrid::Ffn::Dense {
5414 ffn_gate,
5415 ffn_up,
5416 ffn_down,
5417 } => {
5418 let n_ff = ffn_gate.out_features();
5419 let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
5420 let up = e.matmul_decode_exact(ffn_up, &z, t)?;
5421 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
5422 // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
5423 Self::ffn_act_lim(
5424 e,
5425 &self.cfg,
5426 &gate,
5427 &up,
5428 1.0,
5429 1.0,
5430 self.cfg.clamp_shexp_at(il as u32),
5431 &mut act,
5432 t * n_ff,
5433 )?;
5434 e.matmul_decode_exact(ffn_down, &act, t)?
5435 }
5436 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
5437 };
5438 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
5439 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
5440 if aux_layers.contains(&il) {
5441 let mut a = e.zeros(n_embd)?;
5442 e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
5443 aux_last.push(a);
5444 if let Some(pc) = pred_col {
5445 let mut ap = e.zeros(n_embd)?;
5446 e.copy_view_into(
5447 &mut ap,
5448 0,
5449 &x2.slice(pc * n_embd..(pc + 1) * n_embd),
5450 n_embd,
5451 )?;
5452 aux_pred.push(ap);
5453 }
5454 }
5455 x = x2;
5456 }
5457 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
5458 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
5459 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
5460 let host = e.dtoh(&logits)?;
5461 cache.pos += t;
5462 Ok((
5463 host,
5464 aux_last,
5465 if want_pred { Some(aux_pred) } else { None },
5466 ))
5467 }
5468
5469 /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
5470 /// `step35_decode_attn`.
5471 ///
5472 /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
5473 /// the eager decode would have computed for the same tokens; that is what makes greedy spec
5474 /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
5475 /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
5476 /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
5477 /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
5478 /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
5479 /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
5480 /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
5481 /// position of each query row. A batched twin would have to reproduce all of that AND the
5482 /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
5483 /// take one `base_len`, not a per-row offset).
5484 ///
5485 /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
5486 /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
5487 /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
5488 /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
5489 /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
5490 /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
5491 /// step35 twin is a perf lane's job and must be gated against this arm.
5492 ///
5493 /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
5494 /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
5495 /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
5496 /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
5497 /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
5498 #[allow(clippy::too_many_arguments)]
5499 fn step35_verify(
5500 &self,
5501 e: &Engine,
5502 fa: &FullAttnLayer,
5503 h: &CudaSlice<f32>,
5504 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
5505 t: usize,
5506 cache: &mut Cache,
5507 il: usize,
5508 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5509 let n_embd = self.cfg.n_embd as usize;
5510 // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
5511 // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
5512 // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
5513 // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
5514 // cannot regress it into silently reading an empty buffer.
5515 assert_eq!(
5516 h.len(),
5517 t * n_embd,
5518 "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
5519 fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
5520 h_q8.is_some()
5521 );
5522 // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
5523 // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
5524 // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
5525 // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
5526 // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
5527 // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
5528 let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
5529 for r in 0..t {
5530 // Absolute position of this query row. `cache.pos` is the committed length at round
5531 // start and every row before r has already been appended by this loop, so the r-th
5532 // verify token sits at cache.pos + r — the same position eager decode would give it.
5533 let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
5534 let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
5535 e.copy_view_into(
5536 &mut h_row,
5537 0,
5538 &h.slice(r * n_embd..(r + 1) * n_embd),
5539 n_embd,
5540 )?;
5541 // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
5542 // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
5543 let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
5544 debug_assert_eq!(
5545 o.len(),
5546 n_embd,
5547 "step35_decode_attn returns post-wo [n_embd]"
5548 );
5549 e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
5550 }
5551 Ok(out)
5552 }
5553
5554 /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
5555 /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
5556 /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
5557 #[allow(clippy::too_many_arguments)]
5558 fn full_attn_verify(
5559 &self,
5560 e: &Engine,
5561 fa: &FullAttnLayer,
5562 h: &CudaSlice<f32>,
5563 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
5564 pos_d: &CudaSlice<i32>,
5565 t: usize,
5566 cache: &mut Cache,
5567 il: usize,
5568 stream_ctr: Option<&CudaSlice<i32>>,
5569 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5570 // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
5571 // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
5572 // its own arm. A verify that silently computes different attention than decode defeats the
5573 // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
5574 // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
5575 // shape and not laziness.
5576 if self.cfg.step35.is_some() {
5577 if stream_ctr.is_some() {
5578 return Err(
5579 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
5580 cannot express the SWA offset KV view; same root cause as the dc \
5581 decode refusal) — run spec without the stream arm"
5582 .into(),
5583 );
5584 }
5585 return self.step35_verify(e, fa, h, h_q8, t, cache, il);
5586 }
5587 let cfg = &self.cfg;
5588 let geometry = cfg.full_attention_geometry_at(il as u32);
5589 let n_head = geometry.n_head as usize;
5590 let n_head_kv = geometry.n_head_kv as usize;
5591 let head_dim = geometry.head_dim_k as usize;
5592 let eps = cfg.rms_eps;
5593 let scale = geometry.attention_scale();
5594 let n_embd = cfg.n_embd as usize;
5595
5596 // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
5597 // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
5598 // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
5599 // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
5600 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
5601 // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
5602 // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
5603 // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
5604 let (qf, mut k, v) = {
5605 let mut fused = None;
5606 let qkv_fast =
5607 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
5608 if t == 1 && qkv_fast {
5609 let (hq_o, hd_o);
5610 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
5611 Some(p) => p,
5612 None => {
5613 (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
5614 (&hq_o, &hd_o)
5615 }
5616 };
5617 fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
5618 } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
5619 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
5620 // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
5621 // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
5622 let (hq_o, hd_o);
5623 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
5624 Some(p) => p,
5625 None => {
5626 (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
5627 (&hq_o, &hd_o)
5628 }
5629 };
5630 fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
5631 }
5632 match (fused, h_q8) {
5633 (Some(triple), _) => triple,
5634 // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
5635 // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
5636 (None, Some((hq, hd))) if qkv_fast => (
5637 e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
5638 e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
5639 e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
5640 ),
5641 (None, _) => (
5642 e.matmul_decode_exact(&fa.wq, h, t)?,
5643 e.matmul_decode_exact(&fa.wk, h, t)?,
5644 e.matmul_decode_exact(&fa.wv, h, t)?,
5645 ),
5646 }
5647 };
5648 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
5649 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
5650 let (mut q, gate) = if gated {
5651 let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
5652 let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
5653 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
5654 (q, Some(gate))
5655 } else {
5656 (qf, None)
5657 };
5658
5659 let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
5660 e.rms_norm(
5661 &q,
5662 fa.q_norm.float_data(),
5663 &mut qn,
5664 head_dim,
5665 n_head * t,
5666 eps,
5667 )?;
5668 q = qn;
5669 let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
5670 e.rms_norm(
5671 &k,
5672 fa.k_norm.float_data(),
5673 &mut kn,
5674 head_dim,
5675 n_head_kv * t,
5676 eps,
5677 )?;
5678 k = kn;
5679 let rope_dims = geometry.n_rot as usize;
5680 e.rope_neox(
5681 &mut q,
5682 pos_d,
5683 head_dim,
5684 rope_dims,
5685 n_head,
5686 t,
5687 geometry.rope_base,
5688 1.0,
5689 )?;
5690 e.rope_neox(
5691 &mut k,
5692 pos_d,
5693 head_dim,
5694 rope_dims,
5695 n_head_kv,
5696 t,
5697 geometry.rope_base,
5698 1.0,
5699 )?;
5700
5701 // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
5702 // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
5703 let kvl = cache.kv[il].as_mut().unwrap();
5704 let (kv_dim_k, kv_dim_v, ktb, vtb) =
5705 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
5706 if let Some(ctr) = stream_ctr {
5707 // stream: ONE batched append at the device counter (rows kernel = the per-view warp
5708 // math on a (block, token) grid, documented byte-identical); host len is a stale
5709 // LOWER BOUND under pre-issue (drain reconciles it).
5710 e.append_kv_quantized_rows_dc(
5711 &k,
5712 &v,
5713 &mut kvl.k,
5714 &mut kvl.v,
5715 ctr,
5716 t,
5717 kv_dim_k,
5718 kv_dim_v,
5719 ktb,
5720 vtb,
5721 crate::Engine::kv_fp8_on(),
5722 )?;
5723 } else {
5724 for i in 0..t {
5725 let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
5726 let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
5727 e.append_kv_quantized_view(
5728 &k_row,
5729 &v_row,
5730 &mut kvl.k,
5731 &mut kvl.v,
5732 kvl.len + i,
5733 kv_dim_k,
5734 kv_dim_v,
5735 ktb,
5736 vtb,
5737 crate::Engine::kv_fp8_on(),
5738 )?;
5739 }
5740 kvl.len += t;
5741 }
5742
5743 // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
5744 // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
5745 // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
5746 // which changes FP summation order and can flip argmax at tight logit margins. Query row r
5747 // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
5748 // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
5749 // keys. The verify appends all T tokens first but bounds the key range per row.
5750 //
5751 // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
5752 // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
5753 // per-row program for all T rows (grid.z = row, per-row n_splits from the same
5754 // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
5755 // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
5756 // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
5757 // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
5758 // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
5759 let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
5760 let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
5761 // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
5762 // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
5763 // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
5764 // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
5765 // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
5766 // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
5767 // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
5768 // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
5769 if let Some(ctr) = stream_ctr {
5770 // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
5771 // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
5772 // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
5773 let upper = kvl.len + t + 64;
5774 let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
5775 let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
5776 e.fa_decode_rows_dc(
5777 &q,
5778 &k_view,
5779 &v_view,
5780 &mut attn,
5781 head_dim,
5782 n_head,
5783 n_head_kv,
5784 ctr,
5785 upper.min(cache.max_ctx),
5786 t,
5787 scale,
5788 ktb,
5789 vtb,
5790 0,
5791 false,
5792 )?;
5793 } else if spec_lean() && t == 1 {
5794 let t_kv = base_len + 1;
5795 let k_view = e.view_u8(&kvl.k, t_kv * ktb);
5796 let v_view = e.view_u8(&kvl.v, t_kv * vtb);
5797 e.fa_decode_kvmod(
5798 &q,
5799 &k_view,
5800 &v_view,
5801 &mut attn,
5802 head_dim,
5803 n_head,
5804 n_head_kv,
5805 t_kv,
5806 scale,
5807 ktb,
5808 vtb,
5809 crate::Engine::kv_fp8_on(),
5810 )?;
5811 } else if e.fa_rows_eligible(base_len, head_dim) {
5812 let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
5813 let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
5814 e.fa_decode_rows(
5815 &q,
5816 &k_view,
5817 &v_view,
5818 &mut attn,
5819 head_dim,
5820 n_head,
5821 n_head_kv,
5822 base_len,
5823 t,
5824 scale,
5825 ktb,
5826 vtb,
5827 None,
5828 false,
5829 crate::Engine::kv_fp8_on(),
5830 None,
5831 )?;
5832 } else {
5833 for r in 0..t {
5834 let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
5835 let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
5836 let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
5837 // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
5838 let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
5839 let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
5840 e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
5841 let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
5842 e.fa_decode_kvmod(
5843 &q_row,
5844 &k_view_r,
5845 &v_view_r,
5846 &mut attn_row,
5847 head_dim,
5848 n_head,
5849 n_head_kv,
5850 t_kv_r,
5851 scale,
5852 ktb,
5853 vtb,
5854 crate::Engine::kv_fp8_on(),
5855 )?;
5856 e.copy_into(
5857 &mut attn,
5858 r * n_head * head_dim,
5859 &attn_row,
5860 n_head * head_dim,
5861 )?;
5862 }
5863 }
5864
5865 let attn_g = match &gate {
5866 Some(gate) => {
5867 let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
5868 e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
5869 let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
5870 e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
5871 ag
5872 }
5873 None => attn,
5874 };
5875 // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
5876 // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
5877 Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
5878 }
5879
5880 /// Context-linear bytes for a plain serving session's trunk cache.
5881 pub fn plain_session_kv_bytes_per_token(&self) -> usize {
5882 crate::cache::cache_bytes_per_token(&self.cfg)
5883 }
5884
5885 /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
5886 pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
5887 (
5888 self.plain_session_kv_bytes_per_token(),
5889 crate::cache::cache_ring_bytes_per_token(&self.cfg),
5890 crate::cache::cache_ring_row_cap(&self.cfg),
5891 )
5892 }
5893
5894 /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
5895 /// scratch. With no MTP head this equals the plain coefficient.
5896 pub fn spec_session_kv_bytes_per_token(&self) -> usize {
5897 let scratch = self
5898 .mtp
5899 .as_ref()
5900 .map(|mtp| {
5901 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
5902 k + v
5903 })
5904 .unwrap_or(0);
5905 self.plain_session_kv_bytes_per_token()
5906 .saturating_add(scratch)
5907 }
5908
5909 /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
5910 /// capped by the same SWA ring rows as the trunk.
5911 pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
5912 let total = self.spec_session_kv_bytes_per_token();
5913 let (_, mut ring, rows) = self.plain_session_kv_shape();
5914 if rows > 0 {
5915 ring = ring.saturating_add(
5916 self.mtp
5917 .as_ref()
5918 .map(|mtp| {
5919 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
5920 k + v
5921 })
5922 .unwrap_or(0),
5923 );
5924 }
5925 (total, ring, rows)
5926 }
5927
5928 /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
5929 /// the NextN head to draft K tokens then verifies them in one batched target forward.
5930 /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
5931 /// acceptance rate. `k` = draft length per round.
5932 ///
5933 /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
5934 /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
5935 /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
5936 /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
5937 /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
5938 /// captured graph references is event-free; the spec loop is strictly single-stream.
5939 /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
5940 /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
5941 /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
5942 /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
5943 /// generate_spec_inner2.
5944 /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
5945 /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
5946 /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
5947 /// hybrid linear-attn states are in-place (no position index), so a session can extend but
5948 /// never rewind — `committed` is the exact token list whose state the caches hold (includes
5949 /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
5950 pub fn new_session(
5951 &self,
5952 e: &Engine,
5953 max_ctx: usize,
5954 ) -> Result<SpecSession, Box<dyn std::error::Error>> {
5955 Ok(SpecSession {
5956 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
5957 // is the SERVING spec-session path, and with the ppN door open across two cards a
5958 // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
5959 // round — the wrong-card class already fixed on the two batched serving paths
5960 // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
5961 // branch, same allocations), so single-device behavior is byte-unchanged.
5962 cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
5963 scratch: MtpScratch::new(
5964 e,
5965 &self.cfg,
5966 max_ctx,
5967 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5968 )?,
5969 committed: Vec::new(),
5970 last_h: None,
5971 next_pred: None,
5972 sctr: 0,
5973 uctr: 0,
5974 draft_ctx: None,
5975 pending_tok: None,
5976 turn_ckpt: None,
5977 telem: SpecTelemetryCounters::default(),
5978 capture_at: None,
5979 boundary_capture: None,
5980 })
5981 }
5982
5983 /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
5984 /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
5985 /// SpecSession around a trunk cache the worker already restored from a prefix-cache
5986 /// entry, re-installing the entry's published draft plane as the MTP scratch rows
5987 /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
5988 /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
5989 /// worker always receives a fully-warm continuation session (committed = whole
5990 /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
5991 /// boundary logits on the empty-suffix shape).
5992 ///
5993 /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
5994 /// gate): the identity target for a converted hit is the PLAIN hit serving the same
5995 /// request, and plain feeds a carried suffix via eager `decode_step` below
5996 /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
5997 /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
5998 /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
5999 /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
6000 /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
6001 /// burst prime.
6002 ///
6003 /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
6004 /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
6005 /// EXACTLY the rule the cold burst entry applies to its own first token from the same
6006 /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
6007 /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
6008 /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
6009 /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
6010 /// cold session draws from the identical row at counter 0 and then runs its rounds from
6011 /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
6012 /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
6013 /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
6014 /// span the session: `committed` here is the WHOLE prompt, so the restored session's
6015 /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
6016 ///
6017 /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
6018 /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
6019 /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
6020 /// and are never routed here.
6021 ///
6022 /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
6023 /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
6024 /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
6025 /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
6026 /// entry stays published for the next request.
6027 #[allow(clippy::too_many_arguments)]
6028 pub fn spec_session_from_restored(
6029 &self,
6030 e: &Engine,
6031 mut cache: Cache,
6032 prefix: Vec<u32>,
6033 suffix: &[u32],
6034 draft_k: &CudaSlice<u8>,
6035 draft_v: &CudaSlice<u8>,
6036 draft_k_tok_bytes: usize,
6037 draft_v_tok_bytes: usize,
6038 draft_len: usize,
6039 last_h: &[f32],
6040 // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
6041 // when a suffix follows — the feed's own logits are the boundary then.
6042 boundary_logits: &[f32],
6043 // The request's sampler, or None for greedy. Owned here so the seed rule lives in
6044 // ONE place instead of being half-applied by the worker.
6045 sampling: Option<SpecSampling>,
6046 require_anchor: bool,
6047 max_ctx: usize,
6048 ) -> Result<SpecSession, (Option<Cache>, String)> {
6049 let pos = prefix.len();
6050 let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
6051 Err((Some(cache), msg))
6052 };
6053 if self.mtp.is_none() {
6054 return fail(cache, "no MTP head attached (nothing to draft with)".into());
6055 }
6056 if pos == 0 {
6057 return fail(cache, "empty committed prefix".into());
6058 }
6059 if cache.pos != pos {
6060 let msg = format!(
6061 "restored cache pos {} != restored prefix len {pos}",
6062 cache.pos
6063 );
6064 return fail(cache, msg);
6065 }
6066 if draft_len != pos {
6067 return fail(
6068 cache,
6069 format!("draft plane len {draft_len} != restored prefix len {pos}"),
6070 );
6071 }
6072 if pos + suffix.len() >= max_ctx {
6073 return fail(
6074 cache,
6075 format!(
6076 "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
6077 pos + suffix.len(),
6078 ),
6079 );
6080 }
6081 let mut scratch = match MtpScratch::new(
6082 e,
6083 &self.cfg,
6084 max_ctx,
6085 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
6086 ) {
6087 Ok(s) => s,
6088 Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
6089 };
6090 if scratch.kv.ring.is_some() {
6091 return fail(
6092 cache,
6093 "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
6094 );
6095 }
6096 if scratch.kv.k_tok_bytes != draft_k_tok_bytes
6097 || scratch.kv.v_tok_bytes != draft_v_tok_bytes
6098 {
6099 return fail(
6100 cache,
6101 format!(
6102 "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
6103 {}/{} bytes/token (stale entry across a format change)",
6104 scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
6105 ),
6106 );
6107 }
6108 if pos > scratch.cap {
6109 return fail(
6110 cache,
6111 format!(
6112 "draft plane rows {pos} exceed scratch capacity {}",
6113 scratch.cap
6114 ),
6115 );
6116 }
6117 let kb = pos * draft_k_tok_bytes;
6118 let vb = pos * draft_v_tok_bytes;
6119 if draft_k.len() < kb || draft_v.len() < vb {
6120 return fail(
6121 cache,
6122 format!(
6123 "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
6124 draft_k.len(),
6125 draft_v.len(),
6126 ),
6127 );
6128 }
6129 if kb > 0 {
6130 if let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb) {
6131 return fail(cache, format!("draft K restore copy failed: {err}"));
6132 }
6133 }
6134 if vb > 0 {
6135 if let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb) {
6136 return fail(cache, format!("draft V restore copy failed: {err}"));
6137 }
6138 }
6139 if let Err(err) = scratch.set_len(e, pos) {
6140 return fail(cache, format!("draft scratch len set failed: {err}"));
6141 }
6142 let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
6143 // anchor upload failure is acceptance-only when a suffix feed follows (fill
6144 // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
6145 // burst entry asserts committed + last_h + next_pred) — the caller says which.
6146 e.htod(last_h).ok()
6147 } else {
6148 None
6149 };
6150 if require_anchor && last_h_dev.is_none() {
6151 return fail(
6152 cache,
6153 "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
6154 );
6155 }
6156 let mut committed = prefix;
6157 // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
6158 // what the empty-suffix continuation assert in the burst entry requires.
6159 let next_pred;
6160 // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
6161 // consumes counter 0 and leaves 1, which is the state a cold session reaches after
6162 // drawing its own first token from the same row.
6163 let mut sctr = 0u32;
6164 let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
6165 // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
6166 // prompt, which is what the cold session's own burst sees (Item 2's window). Built
6167 // after the suffix joins `committed` below.
6168 let mut boundary_capture: Option<SpecBoundaryCapture> = None;
6169 if !suffix.is_empty() {
6170 // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
6171 // From here on the trunk cache mutates: failures return Err((None, _)) and
6172 // the worker serves the request cold-plain instead of reusing the carrier.
6173 let dirty =
6174 |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
6175 let n_embd = self.cfg.n_embd as usize;
6176 let t = suffix.len();
6177 let mut h_rows = match e.uninit(t * n_embd) {
6178 Ok(b) => b,
6179 Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
6180 };
6181 let mut feed_logits = Vec::new();
6182 let batched = t >= crate::hybrid_forward::PRIME_MIN_T
6183 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
6184 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
6185 if batched {
6186 // prefill_tick's prime arm: one request-level prime_cache call.
6187 match self.prime_cache(e, suffix, &mut cache, 0) {
6188 Ok((l, _h_seed, hiddens)) => {
6189 if let Err(err) = e.copy_into(&mut h_rows, 0, &hiddens, t * n_embd) {
6190 return dirty(format!("suffix hidden copy: {err}"));
6191 }
6192 feed_logits = l;
6193 }
6194 Err(err) => return dirty(format!("suffix prime failed: {err}")),
6195 }
6196 } else {
6197 // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
6198 for (i, &tok) in suffix.iter().enumerate() {
6199 match self.decode_step_h(e, tok, &mut cache) {
6200 Ok((l, h)) => {
6201 if let Err(err) = e.copy_into(&mut h_rows, i * n_embd, &h, n_embd) {
6202 return dirty(format!("suffix hidden copy: {err}"));
6203 }
6204 feed_logits = l;
6205 }
6206 Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
6207 }
6208 }
6209 }
6210 // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
6211 // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
6212 // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
6213 // with T). Fill failures are acceptance-only — truncate to the restored rows
6214 // and continue; the burst's own set_len keeps the invariant.
6215 let mtp = self.mtp.as_ref().expect("mtp checked above");
6216 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
6217 let embd_gpu = if spec_host_embd() {
6218 None
6219 } else {
6220 Some(
6221 self.embd_gpu
6222 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
6223 )
6224 };
6225 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
6226 let fill_chunk = 4096usize;
6227 let mut filled = true;
6228 let mut start = 0usize;
6229 'fill: while start < t {
6230 let end = (start + fill_chunk).min(t);
6231 let tc = end - start;
6232 let Ok(mut phs) = e.zeros(tc * n_embd) else {
6233 filled = false;
6234 break 'fill;
6235 };
6236 let (src_lo, dst_off, n_copy) = if start == 0 {
6237 (0, n_embd, (tc - 1) * n_embd)
6238 } else {
6239 ((start - 1) * n_embd, 0, tc * n_embd)
6240 };
6241 if start == 0 {
6242 if let Some(lh) = last_h_dev.as_ref() {
6243 if e.copy_into(&mut phs, 0, lh, n_embd).is_err() {
6244 filled = false;
6245 break 'fill;
6246 }
6247 }
6248 }
6249 if n_copy > 0
6250 && e.copy_view_into(
6251 &mut phs,
6252 dst_off,
6253 &h_rows.slice(src_lo..src_lo + n_copy),
6254 n_copy,
6255 )
6256 .is_err()
6257 {
6258 filled = false;
6259 break 'fill;
6260 }
6261 if self
6262 .mtp_kv_fill(
6263 e,
6264 mtp,
6265 &suffix[start..end],
6266 &phs,
6267 pos + start,
6268 &mut scratch,
6269 embd_dev,
6270 )
6271 .is_err()
6272 {
6273 filled = false;
6274 break 'fill;
6275 }
6276 start = end;
6277 }
6278 if !filled {
6279 // acceptance-only: drafts over missing suffix rows are cheap and wrong,
6280 // so keep only the restored rows resident and let verify arbitrate.
6281 if let Err(err) = scratch.set_len(e, pos) {
6282 return dirty(format!("scratch truncation after failed fill: {err}"));
6283 }
6284 }
6285 // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
6286 // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
6287 // finding (d)). Pre-lane, publication was armed only for COLD sessions
6288 // (`spec_resumed == 0` in the worker) and both engine capture sites require a
6289 // non-continuation burst — but a converted hit's first burst IS a continuation,
6290 // so a growing conversation learned exactly ONE boundary and turn 3 could never
6291 // hit a longer prefix than turn 2 did.
6292 //
6293 // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
6294 // line — the trunk is primed over the whole prompt, nothing is generated, and the
6295 // draft plane rows [0..prompt) are filled just above. That is a complete
6296 // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
6297 // publishes; the worker's existing publication sweep picks it up because it is
6298 // keyed on `boundary_capture.is_some()` and is sampler- and resume-independent.
6299 // NOT the partial-restore hazard: the boundary is this session's own prompt END,
6300 // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
6301 // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
6302 // publication is an optimization, never a correctness dependency.
6303 if spec_restore_republish_on() {
6304 debug_assert_eq!(
6305 cache.pos,
6306 pos + t,
6307 "extended-entry capture must sit at the restored session's prompt end",
6308 );
6309 if let Ok(snap) = cache.snapshot(e) {
6310 boundary_capture = Some(SpecBoundaryCapture {
6311 snap,
6312 pos: pos + t,
6313 logits: feed_logits.clone(),
6314 last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
6315 });
6316 }
6317 }
6318 // continuation seed: the feed's boundary logits ARE the plain path's boundary
6319 // logits (same program), so greedy's argmax here is plain's first emitted token,
6320 // and the sampled draw is the cold sampled session's own first token.
6321 next_pred = Some(if sampled {
6322 let sp = sampling.expect("sampled implies a sampler");
6323 // `committed` is still the restored prefix here; the suffix joins it below —
6324 // so this is the last-N window over the WHOLE prompt, exactly the cold
6325 // session's own window at its first token.
6326 let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
6327 match sample_boundary_token(
6328 e,
6329 &feed_logits,
6330 &sp,
6331 &hist,
6332 &mut sctr,
6333 "restore-suffix-feed",
6334 ) {
6335 Ok(t) => t,
6336 // the trunk is already fed: hand nothing back, the worker serves the
6337 // request cold-plain. Never fall back to an argmax — that would put a
6338 // greedy token in a sampled stream to save a slow path.
6339 Err(err) => {
6340 return dirty(format!("boundary token draw failed: {err}"));
6341 }
6342 }
6343 } else {
6344 argmax(&feed_logits) as u32
6345 });
6346 let mut lh = match e.uninit(n_embd) {
6347 Ok(b) => b,
6348 Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
6349 };
6350 if let Err(err) = e.copy_view_into(
6351 &mut lh,
6352 0,
6353 &h_rows.slice((t - 1) * n_embd..t * n_embd),
6354 n_embd,
6355 ) {
6356 return dirty(format!("boundary hidden copy: {err}"));
6357 }
6358 last_h_dev = Some(lh);
6359 committed.extend_from_slice(suffix);
6360 } else {
6361 // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
6362 // ENTRY's boundary logits are the boundary row, and this is the token the cold
6363 // session emits from that same row. Owned here rather than in the worker so the
6364 // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
6365 if boundary_logits.is_empty() {
6366 return fail(
6367 cache,
6368 "full-cover restore without the entry's boundary logits".into(),
6369 );
6370 }
6371 next_pred = Some(if sampled {
6372 let sp = sampling.expect("sampled implies a sampler");
6373 let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
6374 match sample_boundary_token(
6375 e,
6376 boundary_logits,
6377 &sp,
6378 &hist,
6379 &mut sctr,
6380 "restore-full-cover",
6381 ) {
6382 Ok(t) => t,
6383 // nothing has been mutated on this shape — hand the carrier back and let
6384 // the hit serve PLAIN (the banked pre-lane path).
6385 Err(err) => {
6386 return fail(cache, format!("boundary token draw failed: {err}"));
6387 }
6388 }
6389 } else {
6390 argmax(boundary_logits) as u32
6391 });
6392 }
6393 Ok(SpecSession {
6394 cache,
6395 scratch,
6396 committed,
6397 last_h: last_h_dev,
6398 next_pred,
6399 sctr,
6400 uctr: 0,
6401 draft_ctx: None,
6402 pending_tok: None,
6403 turn_ckpt: None,
6404 telem: SpecTelemetryCounters::default(),
6405 capture_at: None,
6406 boundary_capture,
6407 })
6408 }
6409
6410 /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
6411 /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
6412 /// snapshot, or draft-KV row that only corrupts the following round.
6413 pub fn optipipe_compare_session_state(
6414 &self,
6415 e: &Engine,
6416 reference: &SpecSession,
6417 candidate: &SpecSession,
6418 ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
6419 fn fail(what: &str) -> Box<dyn std::error::Error> {
6420 format!("optipipe state mismatch: {what}").into()
6421 }
6422 fn same_f32(a: &[f32], b: &[f32]) -> bool {
6423 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
6424 }
6425 fn compare_layers(
6426 es: &Engine,
6427 range: std::ops::Range<usize>,
6428 reference: &SpecSession,
6429 candidate: &SpecSession,
6430 report: &mut OptiForkStateIdentity,
6431 ) -> Result<(), Box<dyn std::error::Error>> {
6432 for il in range {
6433 match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
6434 (Some(a), Some(b)) => {
6435 if a.len != b.len {
6436 return Err(fail(&format!(
6437 "layer {il} host KV len {} != {}",
6438 a.len, b.len
6439 )));
6440 }
6441 let ad = es.dtoh_i32(&a.len_d)?;
6442 let bd = es.dtoh_i32(&b.len_d)?;
6443 if ad != bd || ad.first().copied() != Some(a.len as i32) {
6444 return Err(fail(&format!(
6445 "layer {il} device KV len {ad:?} != {bd:?} (host={})",
6446 a.len,
6447 )));
6448 }
6449 let kb = a.len * a.k_tok_bytes;
6450 let vb = a.len * a.v_tok_bytes;
6451 if kb > 0 {
6452 let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
6453 let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
6454 if ak != bk {
6455 let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
6456 return Err(fail(&format!(
6457 "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
6458 at / a.k_tok_bytes,
6459 at % a.k_tok_bytes,
6460 ak[at],
6461 bk[at],
6462 )));
6463 }
6464 }
6465 if vb > 0 {
6466 let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
6467 let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
6468 if av != bv {
6469 let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
6470 return Err(fail(&format!(
6471 "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
6472 at / a.v_tok_bytes,
6473 at % a.v_tok_bytes,
6474 av[at],
6475 bv[at],
6476 )));
6477 }
6478 }
6479 report.trunk_kv_bytes += kb + vb;
6480 }
6481 (None, None) => {}
6482 _ => return Err(fail(&format!("layer {il} KV presence"))),
6483 }
6484 match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
6485 (Some(a), Some(b)) => {
6486 let ac = es.dtoh(&a.conv_state)?;
6487 let bc = es.dtoh(&b.conv_state)?;
6488 if !same_f32(&ac, &bc) {
6489 return Err(fail(&format!("layer {il} conv state")));
6490 }
6491 let as_ = es.dtoh(&a.ssm_state)?;
6492 let bs = es.dtoh(&b.ssm_state)?;
6493 if !same_f32(&as_, &bs) {
6494 return Err(fail(&format!("layer {il} SSM state")));
6495 }
6496 report.recurrent_bytes += (ac.len() + as_.len()) * 4;
6497 }
6498 (None, None) => {}
6499 _ => return Err(fail(&format!("layer {il} recurrent presence"))),
6500 }
6501 }
6502 Ok(())
6503 }
6504
6505 if reference.committed != candidate.committed {
6506 return Err(fail("committed token ids"));
6507 }
6508 if reference.cache.pos != candidate.cache.pos
6509 || reference.cache.max_ctx != candidate.cache.max_ctx
6510 {
6511 return Err(fail("cache pos/capacity"));
6512 }
6513 if reference.pending_tok != candidate.pending_tok
6514 || reference.next_pred != candidate.next_pred
6515 || reference.sctr != candidate.sctr
6516 || reference.uctr != candidate.uctr
6517 {
6518 return Err(fail("pending/prediction/counter tail"));
6519 }
6520
6521 let mut report = OptiForkStateIdentity::default();
6522 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
6523 let rt = crate::pp::PpNRt::get(e)?;
6524 for stage in 0..rt.n_stages() {
6525 let _scope = rt.enter(stage);
6526 compare_layers(
6527 rt.engine(stage, e),
6528 fence[stage]..fence[stage + 1],
6529 reference,
6530 candidate,
6531 &mut report,
6532 )?;
6533 }
6534 } else {
6535 compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
6536 }
6537
6538 let (a, b) = (&reference.scratch.kv, &candidate.scratch.kv);
6539 if a.len != b.len || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)? {
6540 return Err(fail("draft scratch length"));
6541 }
6542 let kb = a.len * a.k_tok_bytes;
6543 let vb = a.len * a.v_tok_bytes;
6544 if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
6545 return Err(fail("draft scratch K bytes"));
6546 }
6547 if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
6548 return Err(fail("draft scratch V bytes"));
6549 }
6550 report.scratch_kv_bytes = kb + vb;
6551
6552 match (&reference.last_h, &candidate.last_h) {
6553 (Some(a), Some(b)) => {
6554 let ah = e.dtoh(a)?;
6555 let bh = e.dtoh(b)?;
6556 if !same_f32(&ah, &bh) {
6557 return Err(fail("last hidden/seed bytes"));
6558 }
6559 report.hidden_bytes = ah.len() * 4;
6560 }
6561 (None, None) => {}
6562 _ => return Err(fail("last hidden/seed presence")),
6563 }
6564 Ok(report)
6565 }
6566
6567 /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
6568 /// retained prompt-end checkpoint, so a request whose prompt matches
6569 /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
6570 ///
6571 /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
6572 /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
6573 /// restored from the device copy taken there, draft scratch length reset, `committed`
6574 /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
6575 /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
6576 /// every burst after it are identical to a cold run of the same token stream — the
6577 /// committed-tokens-authoritative contract.
6578 ///
6579 /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
6580 /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
6581 /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
6582 /// continue). The persistent draft graph survives: it bakes only session-stable pointers
6583 /// (the scratch KV, the resident embedding), none of which the rewind moves.
6584 ///
6585 /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
6586 /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
6587 /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
6588 pub fn spec_rewind_to_checkpoint(
6589 &self,
6590 e: &Engine,
6591 sess: &mut SpecSession,
6592 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
6593 if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
6594 !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
6595 }) {
6596 return Err(
6597 "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
6598 );
6599 }
6600 let Some(ckpt) = sess.turn_ckpt.take() else {
6601 return Ok(None);
6602 };
6603 assert!(
6604 ckpt.pos <= sess.committed.len(),
6605 "checkpoint past committed ({} > {})",
6606 ckpt.pos,
6607 sess.committed.len()
6608 );
6609 // Restore through each layer's owning engine. A single primary-engine rollback is not
6610 // sufficient when the serving cache is stage-owned under cross-device PP.
6611 crate::pp::restore_cache_checkpoint(e, &self.cfg, None, &mut sess.cache, &ckpt.snap)?;
6612 debug_assert_eq!(
6613 sess.cache.pos, ckpt.pos,
6614 "rollback landed off the checkpoint"
6615 );
6616 sess.scratch.set_len(e, ckpt.pos)?;
6617 sess.committed.truncate(ckpt.pos);
6618 sess.last_h = Some(ckpt.last_h);
6619 sess.next_pred = None;
6620 sess.pending_tok = None;
6621 Ok(Some(ckpt.pos))
6622 }
6623
6624 /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
6625 /// checkpoint without re-priming the checkpoint prefix.
6626 ///
6627 /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
6628 /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
6629 /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
6630 /// remain authoritative, so they are copied into a fresh larger scratch before its length is
6631 /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
6632 ///
6633 /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
6634 /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
6635 pub fn spec_grow_and_rewind_to_checkpoint(
6636 &self,
6637 e: &Engine,
6638 sess: &mut SpecSession,
6639 target_cap: usize,
6640 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
6641 if target_cap <= sess.cache.max_ctx {
6642 return self.spec_rewind_to_checkpoint(e, sess);
6643 }
6644 let Some(ckpt) = sess.turn_ckpt.as_ref() else {
6645 return Ok(None);
6646 };
6647 if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
6648 return Err(format!(
6649 "checkpoint pos {} outside committed length {}",
6650 ckpt.pos,
6651 sess.committed.len(),
6652 )
6653 .into());
6654 }
6655 if ckpt.pos > target_cap {
6656 return Err(format!(
6657 "checkpoint pos {} exceeds grown capacity {target_cap}",
6658 ckpt.pos,
6659 )
6660 .into());
6661 }
6662
6663 let mut grown_cache = crate::pp::new_cache(e, &self.cfg, target_cap)?;
6664 let mut grown_scratch = MtpScratch::new(
6665 e,
6666 &self.cfg,
6667 target_cap,
6668 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
6669 )?;
6670 crate::pp::restore_cache_checkpoint(
6671 e,
6672 &self.cfg,
6673 Some(&sess.cache),
6674 &mut grown_cache,
6675 &ckpt.snap,
6676 )?;
6677
6678 let src = &sess.scratch.kv;
6679 let dst = &mut grown_scratch.kv;
6680 if ckpt.pos > src.len
6681 || src.kv_dim_k != dst.kv_dim_k
6682 || src.kv_dim_v != dst.kv_dim_v
6683 || src.k_tok_bytes != dst.k_tok_bytes
6684 || src.v_tok_bytes != dst.v_tok_bytes
6685 {
6686 return Err(format!(
6687 "checkpoint draft layout mismatch (pos {}, source len {})",
6688 ckpt.pos, src.len,
6689 )
6690 .into());
6691 }
6692 let kb = ckpt.pos * src.k_tok_bytes;
6693 let vb = ckpt.pos * src.v_tok_bytes;
6694 if kb > 0 {
6695 e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
6696 }
6697 if vb > 0 {
6698 e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
6699 }
6700 grown_scratch.set_len(e, ckpt.pos)?;
6701 // The old scratch is dropped immediately after publication below. Bound its D2D reads
6702 // first; growth happens once per rewritten turn, outside the decode hot loop.
6703 e.stream().synchronize()?;
6704
6705 let ckpt = sess
6706 .turn_ckpt
6707 .take()
6708 .expect("checkpoint remained present through transactional grow");
6709 let pos = ckpt.pos;
6710 sess.cache = grown_cache;
6711 sess.scratch = grown_scratch;
6712 sess.committed.truncate(pos);
6713 sess.last_h = Some(ckpt.last_h);
6714 sess.next_pred = None;
6715 sess.pending_tok = None;
6716 sess.draft_ctx = None;
6717 debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
6718 debug_assert_eq!(
6719 sess.scratch.kv.len, pos,
6720 "grown draft rewind landed off checkpoint"
6721 );
6722 Ok(Some(pos))
6723 }
6724
6725 /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
6726 /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
6727 /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
6728 /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
6729 /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
6730 /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
6731 /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
6732 /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
6733 /// park-time flush is a future request whose sampler is not knowable here (residual
6734 /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
6735 pub fn spec_flush_pending(
6736 &self,
6737 e: &Engine,
6738 sess: &mut SpecSession,
6739 sampling: Option<SpecSampling>,
6740 ) -> Result<(), Box<dyn std::error::Error>> {
6741 let Some(b) = sess.pending_tok.take() else {
6742 return Ok(());
6743 };
6744 let mtp = self
6745 .mtp
6746 .as_ref()
6747 .expect("pending carry requires an MTP head");
6748 let n_embd = self.cfg.n_embd as usize;
6749 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
6750 let embd_gpu = if spec_host_embd() {
6751 None
6752 } else {
6753 Some(
6754 self.embd_gpu
6755 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
6756 )
6757 };
6758 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
6759 let pos_b = sess.cache.pos;
6760 sess.scratch.set_len(e, pos_b)?;
6761 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
6762 sess.next_pred = Some(match sampling {
6763 Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
6764 // window includes `b` itself: it is committed by this pass, and the pre-lane
6765 // code never counted a boundary token in the penalty history at all.
6766 let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
6767 sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
6768 }
6769 _ => argmax(&lg_b) as u32,
6770 });
6771 let anchor = sess
6772 .last_h
6773 .as_ref()
6774 .expect("pending carry requires last_h (the predecessor-row anchor)");
6775 self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
6776 sess.last_h = Some(hb);
6777 sess.committed.push(b);
6778 Ok(())
6779 }
6780
6781 /// Solo target feed used only at speculative round boundaries. Step35 serving made its
6782 /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
6783 /// rounds through that same graph. Other model families keep their eager T=1 contract.
6784 fn spec_target_step_h(
6785 &self,
6786 e: &Engine,
6787 token: u32,
6788 cache: &mut Cache,
6789 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6790 if self.cfg.step35.is_none() && !self.qwen35_serving_class() {
6791 return self.decode_step_h(e, token, cache);
6792 }
6793 let pos0 = cache.pos;
6794 let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
6795 Ok((e.dtoh(&logits)?, hidden))
6796 }
6797
6798 /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
6799 /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
6800 /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
6801 /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
6802 /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
6803 /// carries the drift until a near-tie flips deep in generation. One predicate so the five
6804 /// dispatch sites cannot drift apart again.
6805 fn qwen35_serving_class(&self) -> bool {
6806 matches!(
6807 self.cfg.arch,
6808 memra_gguf::config::Arch::Qwen35 | memra_gguf::config::Arch::Qwen35Moe
6809 )
6810 }
6811
6812 /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
6813 /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
6814 /// session already exist.
6815 pub fn spec_pipe_available(&self, e: &Engine) -> bool {
6816 if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
6817 || !spec_devacc()
6818 || spec_replay_env_enabled()
6819 || spec_stream()
6820 || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
6821 || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
6822 || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
6823 || std::env::var("MEMRA_SPEC_PMIN")
6824 .ok()
6825 .and_then(|v| v.parse::<f32>().ok())
6826 .unwrap_or(0.0)
6827 > 0.0
6828 || self.is_gemma4_e4b()
6829 || self.cfg.gemma4.is_some()
6830 || self.mtp.is_none()
6831 {
6832 return false;
6833 }
6834 let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
6835 return false;
6836 };
6837 if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
6838 return false;
6839 }
6840 crate::pp::PpNRt::get(e)
6841 .map(|rt| rt.n_stages() == 2 && rt.cross_device())
6842 .unwrap_or(false)
6843 }
6844
6845 /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
6846 /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
6847 /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
6848 #[allow(clippy::too_many_arguments)]
6849 pub fn generate_spec_session_pair(
6850 &self,
6851 e: &Engine,
6852 sess_a: &mut SpecSession,
6853 max_new_a: usize,
6854 k_a: usize,
6855 sess_b: &mut SpecSession,
6856 max_new_b: usize,
6857 k_b: usize,
6858 ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
6859 {
6860 if !self.spec_pipe_available(e) {
6861 return Err("two-session speculative pipeline is outside its reduced matrix".into());
6862 }
6863 if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
6864 return Err(
6865 "two-session speculative pipeline requires non-empty positive-K bursts".into(),
6866 );
6867 }
6868 for sess in [&*sess_a, &*sess_b] {
6869 if sess.committed.is_empty()
6870 || sess.last_h.is_none()
6871 || (sess.next_pred.is_none() && sess.pending_tok.is_none())
6872 {
6873 return Err("two-session speculative pipeline requires warm continuations".into());
6874 }
6875 }
6876
6877 let mtp_dense = self
6878 .mtp
6879 .as_ref()
6880 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
6881 .unwrap_or(false);
6882 let trunk_dense = self
6883 .layers
6884 .iter()
6885 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
6886 let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
6887 && !spec_host_embd()
6888 && mtp_dense
6889 && trunk_dense
6890 && !crate::model::full_prec_enabled();
6891 let graph_a = graph_ok && k_a + 2 < 96;
6892 let graph_b = graph_ok && k_b + 2 < 96;
6893 let was_tracking = e.ctx().is_event_tracking();
6894 if (graph_a || graph_b) && was_tracking {
6895 unsafe {
6896 e.ctx().disable_event_tracking();
6897 }
6898 }
6899
6900 static LOGGED: std::sync::Once = std::sync::Once::new();
6901 LOGGED.call_once(|| {
6902 eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
6903 });
6904 let sync = std::sync::Arc::new(SpecPipeSync::new());
6905 let lane_a = SpecPipeLane {
6906 sync: sync.clone(),
6907 lane: 0,
6908 };
6909 let lane_b = SpecPipeLane { sync, lane: 1 };
6910 let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
6911 let (result_a, result_b) = std::thread::scope(|scope| {
6912 let b = scope.spawn(move || {
6913 let mut finish = SpecPipeFinish::new(&lane_b);
6914 let sess_b = unsafe { sess_b_ptr.get_mut() };
6915 let result = e
6916 .ctx()
6917 .bind_to_thread()
6918 .map_err(|err| err.to_string())
6919 .and_then(|_| {
6920 self.generate_spec_inner2(
6921 e,
6922 &[],
6923 max_new_b,
6924 k_b,
6925 graph_b,
6926 Some(sess_b),
6927 None,
6928 None,
6929 None,
6930 None,
6931 Some(&lane_b),
6932 )
6933 .map_err(|err| err.to_string())
6934 });
6935 finish.close(result.is_err());
6936 result
6937 });
6938 let mut finish = SpecPipeFinish::new(&lane_a);
6939 let result_a = self.generate_spec_inner2(
6940 e,
6941 &[],
6942 max_new_a,
6943 k_a,
6944 graph_a,
6945 Some(sess_a),
6946 None,
6947 None,
6948 None,
6949 None,
6950 Some(&lane_a),
6951 );
6952 finish.close(result_a.is_err());
6953 let result_b = b
6954 .join()
6955 .map_err(|_| "paired speculative session B panicked".to_string())
6956 .and_then(|r| r);
6957 (result_a, result_b)
6958 });
6959
6960 if (graph_a || graph_b) && was_tracking {
6961 unsafe {
6962 e.ctx().enable_event_tracking();
6963 }
6964 }
6965 let result_a = result_a?;
6966 let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
6967 Ok((result_a, result_b))
6968 }
6969
6970 /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
6971 /// message rendered through the chat template continuation). Returns (new tokens emitted,
6972 /// drafted, accepted); session.committed grows by suffix + emitted.
6973 pub fn generate_spec_session(
6974 &self,
6975 e: &Engine,
6976 sess: &mut SpecSession,
6977 suffix: &[u32],
6978 max_new: usize,
6979 k: usize,
6980 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6981 self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
6982 }
6983
6984 /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
6985 /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
6986 /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
6987 /// for the filtered target (feat/filtered-spec).
6988 ///
6989 /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
6990 /// output — once right after the prime's first token, then once per round commit — so a
6991 /// streaming caller can flush text at round cadence instead of once per burst. The slices
6992 /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
6993 /// timing only: token bytes, session state, and exactness are untouched.
6994 ///
6995 /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
6996 /// the burst at the current round boundary, exactly as if `max_new` had been reached —
6997 /// the caller's scheduler regains control without waiting the burst out. Burst size is
6998 /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
6999 /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
7000 /// drains and the defensive tail flush can land with nothing new committed).
7001 #[allow(clippy::too_many_arguments)]
7002 pub fn generate_spec_session_sampled(
7003 &self,
7004 e: &Engine,
7005 sess: &mut SpecSession,
7006 suffix: &[u32],
7007 max_new: usize,
7008 k: usize,
7009 sampling: Option<SpecSampling>,
7010 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
7011 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7012 self.generate_spec_session_sampled_prime_split(
7013 e, sess, suffix, max_new, k, sampling, None, on_commit,
7014 )
7015 }
7016
7017 /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
7018 /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
7019 /// pass `None` and stay on the existing zero-prime path.
7020 #[allow(clippy::too_many_arguments)]
7021 pub fn generate_spec_session_sampled_prime_split(
7022 &self,
7023 e: &Engine,
7024 sess: &mut SpecSession,
7025 suffix: &[u32],
7026 max_new: usize,
7027 k: usize,
7028 sampling: Option<SpecSampling>,
7029 prime_split: Option<usize>,
7030 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
7031 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7032 self.generate_spec_session_constrained_prime_split(
7033 e,
7034 sess,
7035 suffix,
7036 max_new,
7037 k,
7038 sampling,
7039 None,
7040 prime_split,
7041 on_commit,
7042 )
7043 }
7044
7045 /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
7046 /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
7047 /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
7048 /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
7049 /// column — token-identical to constrained plain greedy decode. GREEDY only (the
7050 /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
7051 /// may drop (drafter is unconstrained); that is measured, not hidden.
7052 #[allow(clippy::too_many_arguments)]
7053 pub fn generate_spec_session_constrained(
7054 &self,
7055 e: &Engine,
7056 sess: &mut SpecSession,
7057 suffix: &[u32],
7058 max_new: usize,
7059 k: usize,
7060 sampling: Option<SpecSampling>,
7061 constraint: Option<&mut dyn SpecConstraint>,
7062 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
7063 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7064 self.generate_spec_session_constrained_prime_split(
7065 e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
7066 )
7067 }
7068
7069 #[allow(clippy::too_many_arguments)]
7070 pub fn generate_spec_session_constrained_prime_split(
7071 &self,
7072 e: &Engine,
7073 sess: &mut SpecSession,
7074 suffix: &[u32],
7075 max_new: usize,
7076 k: usize,
7077 sampling: Option<SpecSampling>,
7078 constraint: Option<&mut dyn SpecConstraint>,
7079 prime_split: Option<usize>,
7080 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
7081 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7082 if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
7083 return Err(
7084 "constrained spec decode is greedy-only (worker routes sampled \
7085 constrained to plain decode)"
7086 .into(),
7087 );
7088 }
7089 // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
7090 // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
7091 // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
7092 // serve continuation case — consume the carry in-loop with zero solo passes.
7093 if sess.pending_tok.is_some()
7094 && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
7095 {
7096 self.spec_flush_pending(e, sess, sampling)?;
7097 }
7098 let mtp_dense = self
7099 .mtp
7100 .as_ref()
7101 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
7102 .unwrap_or(false);
7103 let trunk_dense = self
7104 .layers
7105 .iter()
7106 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
7107 // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
7108 // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
7109 // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
7110 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
7111 && !spec_host_embd()
7112 && mtp_dense
7113 && trunk_dense
7114 && k + 2 < 96
7115 && !crate::model::full_prec_enabled();
7116 let was_tracking = e.ctx().is_event_tracking();
7117 if graph_draft && was_tracking {
7118 unsafe {
7119 e.ctx().disable_event_tracking();
7120 }
7121 }
7122 let r = self.generate_spec_inner2(
7123 e,
7124 suffix,
7125 max_new,
7126 k,
7127 graph_draft,
7128 Some(sess),
7129 sampling,
7130 constraint,
7131 on_commit,
7132 prime_split,
7133 None,
7134 );
7135 if graph_draft && was_tracking {
7136 unsafe {
7137 e.ctx().enable_event_tracking();
7138 }
7139 }
7140 let (out, d, a) = r?;
7141 Ok((out, d, a))
7142 }
7143
7144 pub fn generate_spec(
7145 &self,
7146 e: &Engine,
7147 prompt: &[u32],
7148 max_new: usize,
7149 k: usize,
7150 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7151 let mtp_dense = self
7152 .mtp
7153 .as_ref()
7154 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
7155 .unwrap_or(false);
7156 let trunk_dense = self
7157 .layers
7158 .iter()
7159 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
7160 // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
7161 // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
7162 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
7163 && !spec_host_embd()
7164 && mtp_dense
7165 && trunk_dense
7166 && k + 2 < 96
7167 && !crate::model::full_prec_enabled();
7168 if !graph_draft {
7169 return self.generate_spec_inner2(
7170 e, prompt, max_new, k, false, None, None, None, None, None, None,
7171 );
7172 }
7173 let was_tracking = e.ctx().is_event_tracking();
7174 if was_tracking {
7175 unsafe {
7176 e.ctx().disable_event_tracking();
7177 }
7178 }
7179 let r = self.generate_spec_inner2(
7180 e, prompt, max_new, k, true, None, None, None, None, None, None,
7181 );
7182 if was_tracking {
7183 unsafe {
7184 e.ctx().enable_event_tracking();
7185 }
7186 }
7187 r
7188 }
7189
7190 fn generate_spec_inner2(
7191 &self,
7192 e: &Engine,
7193 prompt: &[u32],
7194 max_new: usize,
7195 k: usize,
7196 graph_draft: bool,
7197 mut sess: Option<&mut SpecSession>,
7198 sampling: Option<SpecSampling>,
7199 mut constraint: Option<&mut dyn SpecConstraint>,
7200 mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
7201 prime_split: Option<usize>,
7202 pipe: Option<&SpecPipeLane>,
7203 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7204 assert!(k >= 1, "k must be >= 1");
7205 if let Some(p) = pipe {
7206 p.setup_begin()?;
7207 }
7208 // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
7209 let mut flushed = 0usize;
7210 // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
7211 // at the next round boundary (same exit as max_new reached — the session tail runs).
7212 // Initialized by the unconditional post-prime flush below.
7213 let mut keep_going;
7214 let mtp = self
7215 .mtp
7216 .as_ref()
7217 .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
7218 let n_vocab = self.output.out_features();
7219 // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
7220 // over the draft vocab and the winning index maps through d2t to a TARGET token id.
7221 // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
7222 let d_vocab = mtp
7223 .shared_head_head
7224 .as_ref()
7225 .unwrap_or(&self.output)
7226 .out_features();
7227 let n_embd = self.cfg.n_embd as usize;
7228 // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
7229 // already committed (their state is in the caches); 0 = fresh single-shot call.
7230 let session_mode = sess.is_some();
7231 let max_ctx = match sess.as_ref() {
7232 Some(s) => s.cache.max_ctx,
7233 None => prompt.len() + max_new + k + 8,
7234 };
7235 let mut own_cache;
7236 let mut own_scratch;
7237 // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
7238 // (requested split, destination slot). Single-shot per burst; fresh calls have none.
7239 let mut sess_capture: Option<(Option<usize>, &mut Option<SpecBoundaryCapture>)> = None;
7240 let (
7241 cache,
7242 scratch,
7243 mut sess_tail,
7244 mut sess_draft_slot,
7245 mut sess_pending_slot,
7246 sess_ckpt_slot,
7247 sess_telem,
7248 ): (
7249 &mut Cache,
7250 &mut MtpScratch,
7251 Option<(
7252 &mut Vec<u32>,
7253 &mut Option<CudaSlice<f32>>,
7254 &mut Option<u32>,
7255 &mut u32,
7256 &mut u32,
7257 )>,
7258 Option<&mut Option<DraftGraphCtx>>,
7259 Option<&mut Option<u32>>,
7260 Option<&mut Option<SpecCheckpoint>>,
7261 Option<&SpecTelemetryCounters>,
7262 ) = match sess.take() {
7263 Some(sr) => {
7264 let SpecSession {
7265 cache,
7266 scratch,
7267 committed,
7268 last_h,
7269 next_pred,
7270 sctr: s_sctr,
7271 uctr: s_uctr,
7272 draft_ctx,
7273 pending_tok,
7274 turn_ckpt,
7275 telem,
7276 capture_at,
7277 boundary_capture,
7278 } = sr;
7279 sess_capture = Some((capture_at.take(), boundary_capture));
7280 (
7281 cache,
7282 scratch,
7283 Some((committed, last_h, next_pred, s_sctr, s_uctr)),
7284 Some(draft_ctx),
7285 Some(pending_tok),
7286 Some(turn_ckpt),
7287 Some(telem),
7288 )
7289 }
7290 None => {
7291 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
7292 // `Cache::new` verbatim.
7293 own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
7294 // Persistent scratch = max_ctx rows (~2KB/token quantized).
7295 own_scratch = MtpScratch::new(
7296 e,
7297 &self.cfg,
7298 max_ctx,
7299 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
7300 )?;
7301 (
7302 &mut own_cache,
7303 &mut own_scratch,
7304 None,
7305 None,
7306 None,
7307 None,
7308 None,
7309 )
7310 }
7311 };
7312 let base = cache.pos;
7313 // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
7314 // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
7315 // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
7316 // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
7317 let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
7318 // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
7319 // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
7320 // acceptance-only — exactness is verify's job either way).
7321 // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
7322 // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
7323 // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
7324 // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
7325 // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
7326 // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
7327 // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
7328 // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
7329 // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
7330 // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
7331 // per round on top of the acceptance win). Draft-quality-only: exactness stays the
7332 // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
7333 // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
7334 // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
7335 // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
7336 // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
7337 // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
7338 // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
7339 // + fallback seam).
7340 // Qwen35-MoE stays on the correctness reference path until its retained verify-state
7341 // commit is proven equivalent to sequential serving on the long-prompt gate. Replaying
7342 // every accepted round through the serving-class verifier is slower, but prevents a
7343 // numerically exact verify result from carrying a drifted recurrent cache into the next
7344 // round. DENSE qwen35 runs replay-free: its verify already executes the serving batched
7345 // class (qwen35_verify_batch_layers), and the serving-class replay loop below steps
7346 // per-row T=1 (replay.len() full weight reads/round — measured 69 -> 30 tok/s on
7347 // Qwen3.8-27B, 2026-08-15); the replay-free VerifyCkpt commit is gated bit-identical by
7348 // the spec-serve battery before release.
7349 let spec_replay = spec_replay_env_enabled()
7350 || matches!(self.cfg.arch, memra_gguf::config::Arch::Qwen35Moe);
7351 if constraint.is_some() && spec_replay {
7352 return Err(
7353 "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
7354 (legacy replay commits an unmasked bonus)"
7355 .into(),
7356 );
7357 }
7358 // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
7359 // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
7360 // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
7361 let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
7362
7363 // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
7364 // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
7365 // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
7366 // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
7367 // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
7368 // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
7369 // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
7370 // generation exactly where the last turn stopped — no prime at all. The stashed
7371 // `next_pred` plays prime_logits' role: it is the token produced from the logits after
7372 // committed.last() by the same rule this entry applies to a cold prime's last row —
7373 // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
7374 // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
7375 // where the sampler and the session's Philox counters were live). `last_h` seeds the
7376 // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
7377 let continuation = prompt.is_empty();
7378 if continuation {
7379 assert!(session_mode, "empty prompt requires a session");
7380 assert!(
7381 sess_tail
7382 .as_ref()
7383 .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
7384 && lh.is_some()
7385 && (np.is_some() || carried_pending.is_some())),
7386 "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
7387 );
7388 }
7389 let mut prime_logits;
7390 let mut prompt_h: Option<CudaSlice<f32>> = None;
7391 let t_prime = std::time::Instant::now();
7392 let batched_prime = !continuation
7393 && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
7394 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
7395 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
7396 let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
7397 if prime_split.is_some() && (continuation || base != 0) {
7398 return Err("spec prime split is cold-session-only".into());
7399 }
7400 if continuation {
7401 prime_logits = Vec::new();
7402 } else if let Some(split) = prime_split {
7403 if split < crate::hybrid_forward::PRIME_MIN_T {
7404 return Err(format!(
7405 "spec prime split {split} is below PRIME_MIN_T {}",
7406 crate::hybrid_forward::PRIME_MIN_T,
7407 )
7408 .into());
7409 }
7410 // Mirror the plain worker's affinity boundary exactly. The prefix is a request-level
7411 // prime (`queued_after` keeps Step35 arm selection independent of this stop); a tail
7412 // below PRIME_MIN_T then takes the same eager tokenwise continuation as prefill_tick.
7413 // Retain every hidden row so the draft scratch fill remains one coherent prompt.
7414 let mut h_all = e.uninit(prompt.len() * n_embd)?;
7415 let (l, _, h_prefix) =
7416 self.prime_cache(e, &prompt[..split], &mut *cache, prompt.len() - split)?;
7417 e.copy_into(&mut h_all, 0, &h_prefix, split * n_embd)?;
7418 prime_logits = l;
7419 // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm states
7420 // are about to be advanced in place by the tail prime, so this is the ONLY moment
7421 // the boundary's recurrent state exists. Capture iff the worker requested exactly
7422 // this split. cache.pos == split here (the prefix prime just finished). A failed
7423 // snapshot is silent (turn_ckpt convention) — publication is an optimization,
7424 // never a correctness dependency.
7425 if let Some((requested, slot)) = sess_capture.as_mut() {
7426 if *requested == Some(split) {
7427 debug_assert_eq!(cache.pos, split, "boundary capture off the prime split");
7428 if let Ok(snap) = cache.snapshot(e) {
7429 **slot = Some(SpecBoundaryCapture {
7430 snap,
7431 pos: split,
7432 logits: prime_logits.clone(),
7433 // rows [0..split) of h_all are the prefix prime's hiddens — copied
7434 // just above, before the tail prime overwrites nothing (append-only).
7435 last_h: capture_boundary_hidden(e, &h_all, split, n_embd),
7436 });
7437 }
7438 }
7439 }
7440 let tail = &prompt[split..];
7441 if tail.len() >= crate::hybrid_forward::PRIME_MIN_T
7442 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
7443 && !e.frozen_cpu_experts_prefer_tokenwise_prime()
7444 {
7445 let (l, _, h_tail) = self.prime_cache(e, tail, &mut *cache, 0)?;
7446 e.copy_into(&mut h_all, split * n_embd, &h_tail, tail.len() * n_embd)?;
7447 prime_logits = l;
7448 } else {
7449 for (i, &tok) in tail.iter().enumerate() {
7450 let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
7451 e.copy_into(&mut h_all, (split + i) * n_embd, &h, n_embd)?;
7452 prime_logits = l;
7453 }
7454 }
7455 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
7456 eprintln!("[spec-prime] affinity split={split} tail={}", tail.len());
7457 }
7458 prompt_h = Some(h_all);
7459 } else if batched_prime {
7460 let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
7461 prime_logits = l;
7462 prompt_h = Some(hiddens);
7463 } else {
7464 prime_logits = Vec::new();
7465 prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
7466 for (i, &tok) in prompt.iter().enumerate() {
7467 let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
7468 if let Some(ph) = prompt_h.as_mut() {
7469 e.copy_into(ph, i * n_embd, &h, n_embd)?;
7470 }
7471 prime_logits = l;
7472 }
7473 }
7474 e.stream().synchronize()?;
7475 // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
7476 // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
7477 // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
7478 // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
7479 // prime_split. The mid-prompt capture above already consumed the request if it matched.
7480 if !continuation && base == 0 {
7481 if let Some((requested, slot)) = sess_capture.as_mut() {
7482 if *requested == Some(prompt.len()) && slot.is_none() {
7483 debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
7484 if let Ok(snap) = cache.snapshot(e) {
7485 **slot = Some(SpecBoundaryCapture {
7486 snap,
7487 pos: prompt.len(),
7488 logits: prime_logits.clone(),
7489 last_h: prompt_h
7490 .as_ref()
7491 .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
7492 .unwrap_or_default(),
7493 });
7494 }
7495 }
7496 }
7497 }
7498 // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
7499 // prime-subtraction hack.
7500 crate::PRIME_NANOS.store(
7501 t_prime.elapsed().as_nanos() as u64,
7502 std::sync::atomic::Ordering::Relaxed,
7503 );
7504
7505 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
7506 // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
7507 // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
7508 let host_embd = spec_host_embd();
7509 let embd_gpu = if host_embd {
7510 None
7511 } else {
7512 Some(
7513 self.embd_gpu
7514 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
7515 )
7516 };
7517 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
7518 if host_embd {
7519 eprintln!(
7520 "[spec] host-row embedding: {} bytes kept off HBM",
7521 self.embd.raw.len()
7522 );
7523 }
7524 let mut out: Vec<u32> = Vec::with_capacity(max_new);
7525 let mut total_drafted = 0usize;
7526 let mut total_accepted = 0usize;
7527
7528 // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
7529 // The sampler config, the session's Philox counters and the penalty window are parsed
7530 // HERE, above the boundary-token selection, because the boundary token must be drawn
7531 // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
7532 // selection, which is the whole mechanical reason the boundary token was an argmax:
7533 // the sampler state was not in scope yet. Nothing here depends on the round loop, so
7534 // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
7535 // below takes the argmax path it always took).
7536 // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
7537 // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
7538 // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
7539 // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
7540 let sp = sampling.unwrap_or_else(|| SpecSampling {
7541 temp: std::env::var("MEMRA_SPEC_TEMP")
7542 .ok()
7543 .and_then(|v| v.parse().ok())
7544 .unwrap_or(0.0),
7545 seed: std::env::var("MEMRA_SEED")
7546 .ok()
7547 .and_then(|v| v.parse().ok())
7548 .unwrap_or(42),
7549 top_k: std::env::var("MEMRA_TOP_K")
7550 .ok()
7551 .and_then(|v| v.parse().ok())
7552 .unwrap_or(0),
7553 top_p: std::env::var("MEMRA_TOP_P")
7554 .ok()
7555 .and_then(|v| v.parse().ok())
7556 .unwrap_or(1.0),
7557 min_p: std::env::var("MEMRA_MIN_P")
7558 .ok()
7559 .and_then(|v| v.parse().ok())
7560 .unwrap_or(0.0),
7561 penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
7562 .ok()
7563 .and_then(|v| v.parse().ok())
7564 .unwrap_or(0),
7565 penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
7566 .ok()
7567 .and_then(|v| v.parse().ok())
7568 .unwrap_or(1.0),
7569 penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
7570 .ok()
7571 .and_then(|v| v.parse().ok())
7572 .unwrap_or(0.0),
7573 penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
7574 .ok()
7575 .and_then(|v| v.parse().ok())
7576 .unwrap_or(0.0),
7577 });
7578 let (sp_temp, sp_seed) = (sp.temp, sp.seed);
7579 let sampled = sp_temp > 0.0;
7580 // Counters resume from the session (burst continuity: randomness must never repeat
7581 // across generate_spec_session calls); one-shot callers start at (0,0). Read through
7582 // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
7583 let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
7584 let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
7585 // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
7586 // for the penalized+filtered target). History = generated tokens, host-tracked window.
7587 let pen_on = sampled
7588 && sp.penalty_last_n > 0
7589 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
7590 // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
7591 // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
7592 // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
7593 // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
7594 // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
7595 // which is what the API contract says and what the plain sampler's own `history` does.
7596 // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
7597 let mut pen_hist: Vec<u32> = if pen_on {
7598 let sess_hist: &[u32] = if spec_pen_session_on() {
7599 sess_tail
7600 .as_ref()
7601 .map(|(c, ..)| c.as_slice())
7602 .unwrap_or(&[])
7603 } else {
7604 &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
7605 };
7606 pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
7607 } else {
7608 Vec::new()
7609 };
7610 // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
7611 // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
7612 // request's own filtered/penalized target through the session's Philox stream
7613 // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
7614 // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
7615 // Emit it, then FEED it to establish the loop invariant below.
7616 // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
7617 // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
7618 // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
7619 // prompt's last logits (plain constrained-greedy identity); a continuation without
7620 // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
7621 // worker never resumes constrained sessions from the pool, so this cannot fire).
7622 if let Some(c) = constraint.as_deref_mut() {
7623 if continuation && carried_pending.is_none() {
7624 return Err("constrained spec continuation requires a carried pending \
7625 (pool resume is unconstrained-only)"
7626 .into());
7627 }
7628 if !continuation {
7629 c.mask_logits(&mut prime_logits)
7630 .map_err(|e2| format!("constraint: {e2}"))?;
7631 }
7632 }
7633 let mut last_token = if let Some(b) = carried_pending {
7634 b
7635 } else if continuation {
7636 // A continuation's boundary token was DRAWN by the burst that stashed it (the
7637 // session tail below), or by `spec_session_from_restored` for a converted
7638 // prefix-cache hit — in both cases from the correct logits row with this same
7639 // session's Philox stream, which is why it can be consumed here as-is.
7640 sess_tail.as_ref().unwrap().2.unwrap()
7641 } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
7642 sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
7643 } else {
7644 // greedy (byte contract), the rollback door, or constrained (masked-argmax
7645 // identity — the worker routes sampled+constrained to the plain path, and this
7646 // function refuses the combination outright above).
7647 argmax(&prime_logits) as u32
7648 };
7649 if pen_on {
7650 // The boundary token is a GENERATED token: the plain sampler `accept()`s every
7651 // emitted token into its penalty history, and pre-lane the burst's first token
7652 // was invisible to penalties forever (never pushed, and never in `committed`
7653 // until this burst's tail). Covers the carry/continuation seeds too — neither is
7654 // in `committed` yet.
7655 pen_hist.push(last_token);
7656 }
7657 if carried_pending.is_none() {
7658 out.push(last_token);
7659 // grammar advances with every emitted token (carried pendings were consumed
7660 // by the burst that emitted them).
7661 if let Some(c) = constraint.as_deref_mut() {
7662 c.consume(last_token)
7663 .map_err(|e2| format!("constraint: {e2}"))?;
7664 }
7665 }
7666 if continuation {
7667 // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
7668 // overhang so the chain's first append lands at slot base (== committed.len()).
7669 scratch.set_len(e, base)?;
7670 }
7671 // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
7672 // concatenating to the full `out`). Called after the prime's first token and after each
7673 // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
7674 // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
7675 // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
7676 fn flush_commit(
7677 cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
7678 out: &[u32],
7679 flushed: &mut usize,
7680 ) -> bool {
7681 if let Some(f) = cb.as_mut() {
7682 let keep = f(&out[*flushed..]);
7683 *flushed = out.len();
7684 keep
7685 } else {
7686 true
7687 }
7688 }
7689 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
7690 // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
7691 // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
7692 // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
7693 // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
7694 // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
7695 // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
7696 // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
7697 // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
7698 // those, so their residual mass is p(x), correct by construction).
7699 let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
7700 match &mtp.d2t {
7701 Some(map) => Some(e.htod_u32_v(map)?),
7702 None => None,
7703 }
7704 } else {
7705 None
7706 };
7707 let mut q_full_buf: Option<CudaSlice<f32>> = None;
7708 // host Philox4x32-10 (mirrors spec_sample.cu; independent stream via ctr_lo tag)
7709 let host_u01 = |seed: u64, ctr: u32| -> f32 {
7710 let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
7711 let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
7712 let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
7713 for _ in 0..10 {
7714 let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
7715 let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
7716 let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
7717 c0 = n0;
7718 c1 = n1;
7719 c2 = n2;
7720 c3 = n3;
7721 k0 = k0.wrapping_add(0x9E3779B9);
7722 k1 = k1.wrapping_add(0xBB67AE85);
7723 }
7724 (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
7725 };
7726 let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
7727 let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
7728 let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
7729 let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
7730 let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
7731 let mut pen_hist_d: Option<CudaSlice<u32>> = None;
7732 let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
7733 // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
7734 // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
7735 // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
7736 let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
7737 let t_ent = std::time::Instant::now();
7738
7739 // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
7740 // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
7741 // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
7742 // the one that matters (a history-rewriting client mutates what the session GENERATED,
7743 // so the next turn's prompt agrees with this one up to exactly here).
7744 //
7745 // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
7746 // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
7747 // hold exactly `base + prompt.len()` rows and nothing generated.
7748 //
7749 // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
7750 // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
7751 // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
7752 // `<think>` block the client strips, so every later turn's diff diverged exactly one
7753 // token below the checkpoint and affinity declined 100% of the time. Measured on the
7754 // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
7755 // whole mechanism inert while looking, from the outside, like a working
7756 // correctness-declines-safely path — hence the decline log carries the offsets.
7757 //
7758 // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
7759 // state (the reason a spec session could not rewind before). The draft scratch needs no
7760 // copy: rows below the boundary are rewritten by the next turn's own fill.
7761 //
7762 // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
7763 // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
7764 // checkpoint rather than replacing it with a strictly worse one.
7765 //
7766 // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
7767 // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
7768 // fail the burst that is already running — so the error is swallowed, loud only under
7769 // MEMRA_DEBUG_SPEC.
7770 if let Some(slot) = sess_ckpt_slot {
7771 if !continuation {
7772 let pos = cache.pos;
7773 debug_assert_eq!(
7774 pos,
7775 base + prompt.len(),
7776 "turn checkpoint must sit at the prompt end, before the init feed"
7777 );
7778 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
7779 if let Some(ph) = &prompt_h {
7780 // hidden of the LAST primed row = the predecessor anchor at this
7781 // boundary (exactly what a fresh prime of committed[..pos] leaves in
7782 // last_h, and what the next prime's fill reads for its first row).
7783 let np = prompt.len();
7784 e.uninit(n_embd).and_then(|mut a| {
7785 e.copy_view_into(
7786 &mut a,
7787 0,
7788 &ph.slice((np - 1) * n_embd..np * n_embd),
7789 n_embd,
7790 )?;
7791 Ok(a)
7792 })
7793 } else {
7794 Err("no prompt hiddens".into())
7795 };
7796 match (cache.snapshot(e), anchor) {
7797 (Ok(snap), Ok(last_h)) => {
7798 *slot = Some(SpecCheckpoint { snap, pos, last_h });
7799 }
7800 (s, a) => {
7801 *slot = None; // a stale checkpoint would rewind to the WRONG boundary
7802 if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
7803 let err = s
7804 .err()
7805 .map(|e| e.to_string())
7806 .or_else(|| a.err().map(|e| e.to_string()))
7807 .unwrap_or_default();
7808 eprintln!(
7809 "[spec] turn checkpoint skipped ({err}); \
7810 next turn re-primes in full"
7811 );
7812 }
7813 }
7814 }
7815 }
7816 }
7817 // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
7818 // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
7819 // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
7820 // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
7821 let mut last_pred = 0u32;
7822 let mut last_col_logits: Option<CudaSlice<f32>> = None;
7823 // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
7824 // recompute in the grammar-truncation walk — retained host-side, round 0 only.
7825 let mut init_logits_host: Option<Vec<f32>> = None;
7826 let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
7827 let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
7828 last_pred = argmax(&init_logits) as u32;
7829 if constraint.is_some() {
7830 init_logits_host = Some(init_logits.clone());
7831 }
7832 // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
7833 if sampled {
7834 last_col_logits = Some(e.htod(&init_logits)?);
7835 }
7836 h
7837 } else {
7838 // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
7839 let lh = sess_tail
7840 .as_ref()
7841 .unwrap()
7842 .1
7843 .as_ref()
7844 .expect("pending carry requires last_h");
7845 e.clone_dtod(lh)?
7846 };
7847 let t_init = t_ent.elapsed();
7848 let mut last_col_stats: Option<(f32, f32, f32)> = None;
7849 // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
7850 // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
7851 // stable pointer for the graph-draft round-start copy.
7852 let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
7853 // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
7854 // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
7855 // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
7856 // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
7857 // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
7858 // overwritten below).
7859 let mut fill_prev = e.clone_dtod(&h_seed0)?;
7860 {
7861 if let Some(ph) = &prompt_h {
7862 let np = prompt.len();
7863 e.copy_view_into(
7864 &mut h_seed_buf,
7865 0,
7866 &ph.slice((np - 1) * n_embd..np * n_embd),
7867 n_embd,
7868 )?;
7869 } else if continuation {
7870 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
7871 if let Some(lh) = lh.as_ref() {
7872 e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
7873 }
7874 }
7875 }
7876 }
7877 // Persistent device prediction slots for the accept walk (max k+1 verify columns).
7878 let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
7879
7880 let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
7881 let fork_mode = OptiForkGateMode::configured();
7882 // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
7883 // the end. Metric normalization vs the reference engine: BOTH engines count
7884 // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
7885 // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
7886 let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
7887 let mut st_drafted = vec![0usize; k];
7888 let mut st_accepted = vec![0usize; k];
7889 let mut st_len_hist = vec![0usize; k + 1];
7890 let mut st_full = 0usize;
7891 // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
7892 // stop the draft chain early when the head's softmax confidence in its own pick drops
7893 // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
7894 static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
7895 let p_min = *PMIN.get_or_init(|| {
7896 std::env::var("MEMRA_SPEC_PMIN")
7897 .ok()
7898 .and_then(|v| v.parse().ok())
7899 .unwrap_or(0.0)
7900 });
7901 // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
7902 // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
7903 // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
7904 // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
7905 // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
7906 // verify batch is not); the j==0 exemption stays for pending-less rounds.
7907 let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
7908 .map(|v| v == "1")
7909 .unwrap_or(false);
7910
7911 // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
7912 // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
7913 // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
7914 // cuBLAS path in an exotic head) falls back to the eager draft chain.
7915 // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
7916 // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
7917 // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
7918 // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
7919 // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
7920 // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
7921 // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
7922 // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
7923 let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
7924 Some(c) => c,
7925 None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
7926 };
7927 // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
7928 // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
7929 if sampled && dctx.g_q.len() < d_vocab {
7930 dctx.g_q = e.zeros(d_vocab)?;
7931 dctx.g_perturb = e.zeros(d_vocab)?;
7932 }
7933 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
7934 // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
7935 // truncation (the correctness backstop) stops cutting every tight-schema round.
7936 // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
7937 // shape, so a parked graph of the other shape is dropped and recaptured.
7938 let dmask_on = constraint
7939 .as_deref()
7940 .is_some_and(|c| c.draft_mask_enabled());
7941 let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
7942 if dmask_on && dctx.g_dmask.len() < dmask_words {
7943 dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
7944 dctx.graph = None; // the old capture baked the old (or no) mask pointer
7945 dctx.failed.clear_greedy();
7946 dctx.keeper.clear();
7947 }
7948 if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
7949 dctx.graph = None;
7950 dctx.failed.clear_greedy();
7951 dctx.keeper.clear();
7952 }
7953 if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
7954 let DraftGraphCtx {
7955 g_tok,
7956 g_pos,
7957 g_seed,
7958 g_p,
7959 g_dmask,
7960 ..
7961 } = &mut dctx;
7962 // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
7963 // host uploads the position's real words, so the warmups stay grammar-free.
7964 if dmask_on {
7965 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
7966 }
7967 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
7968 // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
7969 // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
7970 // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
7971 // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
7972 // passes (and, in serve, other sessions) recycle those addresses and the replay then
7973 // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
7974 let cap_res = e.capture_graph_retained(|e| {
7975 self.mtp_head_forward_cap(
7976 e,
7977 mtp,
7978 g_tok,
7979 g_pos,
7980 g_seed,
7981 g_p,
7982 &mut *scratch,
7983 p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
7984 true,
7985 embd_gpu.expect("graph draft requires resident embedding"),
7986 embd_qt,
7987 embd_rb,
7988 d_vocab,
7989 None,
7990 None,
7991 if dmask_on {
7992 Some((g_dmask_ro, dmask_words))
7993 } else {
7994 None
7995 },
7996 )
7997 });
7998 match cap_res {
7999 Ok((g, keep)) => {
8000 scratch.set_len(e, base)?;
8001 dctx.graph = Some(g);
8002 dctx.graph_masked = dmask_on;
8003 dctx.keeper = keep;
8004 }
8005 Err(err) => {
8006 scratch.set_len(e, base)?;
8007 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
8008 // silent. Once per flip — mark returns None on an already-failed ctx.
8009 if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
8010 eprintln!("{line}");
8011 }
8012 }
8013 }
8014 }
8015 // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
8016 // graph object, built only when sampled && graph-eligible — the greedy capture above is
8017 // untouched (and skipped when sampled: its graph would never be launched). Same head
8018 // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
8019 // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
8020 // once per round); the raw head logits land in the persistent g_q for the host's
8021 // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
8022 // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
8023 // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
8024 // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
8025 // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
8026 // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
8027 // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
8028 // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
8029 // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
8030 // this compare misses at most ONCE per resumed request — the first burst recaptures
8031 // and every later burst in that request replays. A client that wants the parked graph
8032 // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
8033 // stable across its whole conversation.
8034 // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
8035 // softmax — it can hold neither per-row filter stats nor the varying penalty history.
8036 // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
8037 // force the eager draft (which computes stats/penalties per row).
8038 // KEY THE WHOLE REGIME, not just the baked constants (lane/graph-s-key-exactness-
8039 // 20260819). `s_key` used to be `(seed, temp, k)`; the filters and penalties were left
8040 // out, so a filtered request resuming a session that parked a PURE-TEMP graph kept it —
8041 // and the launch site never re-asked `pure_temp`. See [`SampledGraphKey`] for what that
8042 // costs (an unconditional accept of out-of-head draft tokens, i.e. an exactness bug on
8043 // the request shape the vendor-default flip makes the majority).
8044 let s_key = SampledGraphKey::new(sp_seed, sp_temp, k, sp.top_k, sp.top_p, sp.min_p, pen_on);
8045 let pure_temp = s_key.pure_temp();
8046 if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
8047 dctx.graph_s = None;
8048 dctx.failed.clear_sampled();
8049 dctx.s_key = None;
8050 dctx.q_slots.clear();
8051 dctx.keeper_s.clear();
8052 }
8053 if graph_draft
8054 && sampled
8055 && pure_temp
8056 && dctx.graph_s.is_none()
8057 && !dctx.failed.sampled_failed()
8058 {
8059 let DraftGraphCtx {
8060 g_tok,
8061 g_pos,
8062 g_seed,
8063 g_p,
8064 g_ctr,
8065 g_perturb,
8066 g_q,
8067 ..
8068 } = &mut dctx;
8069 // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
8070 let cap_res = e.capture_graph_retained(|e| {
8071 self.mtp_head_forward_cap(
8072 e,
8073 mtp,
8074 g_tok,
8075 g_pos,
8076 g_seed,
8077 g_p,
8078 &mut *scratch,
8079 p_min > 0.0,
8080 true,
8081 embd_gpu.expect("graph draft requires resident embedding"),
8082 embd_qt,
8083 embd_rb,
8084 d_vocab,
8085 Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
8086 None,
8087 None, // constrained spec is greedy-only — sampled never carries a hook
8088 )
8089 });
8090 match cap_res {
8091 Ok((g, keep)) => {
8092 scratch.set_len(e, base)?;
8093 for _ in 0..k {
8094 dctx.q_slots.push(e.zeros(d_vocab)?);
8095 }
8096 dctx.graph_s = Some(g);
8097 dctx.s_key = Some(s_key);
8098 dctx.keeper_s = keep;
8099 }
8100 Err(err) => {
8101 scratch.set_len(e, base)?;
8102 // LOUD flip (audit Q2): same contract as the greedy capture above.
8103 if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
8104 eprintln!("{line}");
8105 }
8106 }
8107 }
8108 }
8109 // ---- EXACTNESS GUARD, the enforceable half (lane/graph-s-key-exactness-20260819) ----
8110 // With the filters and penalties in `s_key`, a graph that SURVIVED the drop above was
8111 // captured under this request's exact regime, and capture requires `pure_temp` — so a
8112 // parked graph implies `pure_temp`. That implication is the whole exactness argument for
8113 // the graph arm, so it is asserted here rather than assumed: a future change that widens
8114 // the capture condition, narrows the key, or copies a `DraftGraphCtx` across regimes
8115 // fails LOUDLY at this line instead of silently drafting from the raw softmax while the
8116 // verify applies filter stats. Release builds refuse the graph (drop it, draft eager)
8117 // rather than launching it; the launch site re-tests `pure_temp` independently.
8118 if sampled && !pure_temp && dctx.graph_s.is_some() {
8119 debug_assert!(
8120 false,
8121 "sampled draft graph parked under {:?} survived into a FILTERED request \
8122 (top_k={} top_p={} min_p={} pen_on={}): the in-graph chain draws from the RAW \
8123 softmax, so the verify's filtered q would test a distribution the draft was \
8124 never sampled from",
8125 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
8126 );
8127 eprintln!(
8128 "[spec] BUG: dropping a parked sampled draft graph that outlived its capture \
8129 regime (s_key={:?}, request top_k={} top_p={} min_p={} pen_on={}); drafting \
8130 EAGER — the key must carry every field that shapes q",
8131 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
8132 );
8133 dctx.graph_s = None;
8134 dctx.s_key = None;
8135 dctx.q_slots.clear();
8136 dctx.keeper_s.clear();
8137 }
8138 // SKEY PROBE (MEMRA_SKEY_PROBE=1): the burst-entry facts the reachability question turns
8139 // on — is this request sampled, is it in the pure-temp regime the sampled graph is only
8140 // legal in, and is a graph PARKED from an earlier request of the same session? The launch
8141 // arms below print which chain actually ran, so the probe never restates the condition.
8142 if skey_probe() {
8143 eprintln!(
8144 "[skey] burst sampled={} pure_temp={} temp={} top_k={} top_p={} min_p={} \
8145 pen_on={} k={} graph_draft={} graph_s_parked={} s_key_parked={:?}",
8146 sampled as u8,
8147 pure_temp as u8,
8148 sp_temp,
8149 sp.top_k,
8150 sp.top_p,
8151 sp.min_p,
8152 pen_on as u8,
8153 k,
8154 graph_draft as u8,
8155 dctx.graph_s.is_some() as u8,
8156 dctx.s_key,
8157 );
8158 }
8159 let t_cap = t_ent.elapsed();
8160 // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
8161 // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
8162 // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
8163 // fill: the first chain step processes it and appends its entry at slot prompt.len().
8164 if let Some(ph) = &prompt_h {
8165 // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
8166 // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
8167 // global positions [base..base+tp). Fresh call: base==0, identical to before.
8168 scratch.set_len(e, base)?;
8169 // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
8170 // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
8171 // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
8172 // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
8173 let tp = prompt.len();
8174 let fill_chunk: usize = if crate::cache::swa_ring_on() {
8175 crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
8176 } else {
8177 // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
8178 // meaning one monolithic fill.
8179 std::env::var("MEMRA_PRIME_CHUNK")
8180 .ok()
8181 .and_then(|v| v.parse().ok())
8182 .unwrap_or(4096)
8183 };
8184 let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
8185 let mut start = 0usize;
8186 while start < tp {
8187 let end = (start + fill_chunk).min(tp);
8188 let tc = end - start;
8189 {
8190 // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
8191 // reference engine's initial pending-h is zeroed too); a session turn's row 0
8192 // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
8193 // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
8194 let mut phs = e.zeros(tc * n_embd)?;
8195 let (src_lo, dst_off) = if start == 0 {
8196 (0, n_embd)
8197 } else {
8198 ((start - 1) * n_embd, 0)
8199 };
8200 let n_copy = if start == 0 {
8201 (tc - 1) * n_embd
8202 } else {
8203 tc * n_embd
8204 };
8205 if start == 0 {
8206 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
8207 if let Some(lh) = lh.as_ref() {
8208 e.copy_into(&mut phs, 0, lh, n_embd)?;
8209 }
8210 }
8211 }
8212 if n_copy > 0 {
8213 e.copy_view_into(
8214 &mut phs,
8215 dst_off,
8216 &ph.slice(src_lo..src_lo + n_copy),
8217 n_copy,
8218 )?;
8219 }
8220 self.mtp_kv_fill(
8221 e,
8222 mtp,
8223 &prompt[start..end],
8224 &phs,
8225 base + start,
8226 &mut *scratch,
8227 embd_dev,
8228 )?;
8229 }
8230 start = end;
8231 }
8232 }
8233 // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
8234 // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
8235 // (=1 brackets the whole call in run_spec.rs, prime included.)
8236 if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
8237 unsafe extern "C" {
8238 fn cudaProfilerStart() -> i32;
8239 }
8240 unsafe {
8241 cudaProfilerStart();
8242 }
8243 }
8244 // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
8245 // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
8246 // consume each other's device outputs; the host drains the ring every M rounds. v1
8247 // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
8248 // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
8249 // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
8250 // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
8251 // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
8252 let stream_on = crate::spec::spec_stream()
8253 && !sampled
8254 && !spec_replay
8255 && constraint.is_none()
8256 && !session_mode
8257 && embd_gpu.is_some()
8258 && !crate::model::full_prec_enabled()
8259 && k + 2 < 96;
8260 let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
8261 let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
8262 if stream_on {
8263 let cap = e.capture_graph(|e| {
8264 for j in 0..k.max(1) {
8265 self.mtp_head_forward_cap(
8266 e,
8267 mtp,
8268 &mut dctx.g_tok,
8269 &mut dctx.g_pos,
8270 &mut dctx.g_seed,
8271 &mut dctx.g_p,
8272 &mut *scratch,
8273 true,
8274 true,
8275 embd_gpu.expect("round stream requires resident embedding"),
8276 embd_qt,
8277 embd_rb,
8278 d_vocab,
8279 None,
8280 Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
8281 None, // round-stream requires constraint.is_none() (see stream_on)
8282 )?;
8283 }
8284 Ok(())
8285 });
8286 match cap {
8287 Ok(g) => {
8288 scratch.set_len(e, 0)?;
8289 stream_graph = Some(g);
8290 }
8291 Err(err) => {
8292 scratch.set_len(e, 0)?;
8293 if debug_spec {
8294 eprintln!("[spec] stream-graph capture failed ({err}); stream off");
8295 }
8296 }
8297 }
8298 }
8299 let stream_active = stream_on && stream_graph.is_some();
8300 if debug_spec {
8301 eprintln!(
8302 "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
8303 crate::spec::spec_stream(),
8304 dctx.graph.is_some(),
8305 stream_graph.is_some()
8306 );
8307 }
8308 let t_v_s = k + 1;
8309 // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
8310 // module (extracted 2026-07-12; the gemma burst reuses them).
8311 let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
8312 let crate::round_stream::StreamBufs {
8313 mut vtok_d,
8314 mut brk_d,
8315 mut pend_d,
8316 last_pred_d,
8317 mut pos_ctr,
8318 mut pos_start_d,
8319 mut ring_d,
8320 acc_d: mut stream_acc,
8321 m_rounds,
8322 k: _,
8323 } = sb;
8324 let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
8325 Some(crate::round_stream::kv_len_ptr_table(
8326 e,
8327 cache,
8328 Some(&pos_ctr),
8329 )?)
8330 } else {
8331 None
8332 };
8333
8334 let t_fill = t_ent.elapsed();
8335 let mut round = 0usize;
8336 // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
8337 // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
8338 // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
8339 // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
8340 // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
8341 // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
8342 // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
8343 // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
8344 // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
8345 // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
8346 // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
8347 // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
8348 // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
8349 // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
8350 // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
8351 // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
8352 // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
8353 // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
8354 // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
8355 // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
8356 // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
8357 // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
8358 // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
8359 // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
8360 // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
8361 // K=1..8 self-consistency PASS both models with the law ON (exactness held).
8362 let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
8363 // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
8364 // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
8365 let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
8366 .ok()
8367 .and_then(|v| v.parse().ok());
8368 let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
8369 4
8370 } else if self.cfg.n_embd as usize >= 2500 {
8371 2
8372 } else {
8373 1
8374 };
8375 let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
8376 // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
8377 // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
8378 // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
8379 let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
8380 .ok()
8381 .and_then(|v| v.parse().ok())
8382 .unwrap_or(1024);
8383 let floor_at = |pos: usize| -> usize {
8384 if adapt_floor_env.is_some() || pos < floor_ctx {
8385 adapt_floor
8386 } else if adapt_floor >= 4 {
8387 1
8388 } else {
8389 adapt_floor
8390 }
8391 };
8392 // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
8393 // fixed-K default path is untouched by this whole block.
8394 let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
8395 .ok()
8396 .and_then(|v| v.parse().ok())
8397 .unwrap_or(7);
8398 let k_cap = k.min(cap_max).max(1);
8399 let mut kc = k_cap;
8400 let mut opti_fork: Option<OptiForkState> = None;
8401 let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
8402 if fork_mode != OptiForkGateMode::Disabled {
8403 let fence = crate::pp::pp_cuts(self.layers.len());
8404 let refusal = if !session_mode {
8405 Some("not-session")
8406 } else if k != 1 || adapt {
8407 Some("requires-fixed-k1")
8408 } else if sampled || constraint.is_some() || spec_replay {
8409 Some("sampled-constrained-or-replay")
8410 } else if pipe.is_some() {
8411 Some("two-session-pipeline")
8412 } else if !spec_devacc() {
8413 Some("requires-device-accept")
8414 } else if stream_active || crate::spec::spec_stream() {
8415 Some("round-stream")
8416 } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
8417 Some("swa-ring")
8418 } else if crate::pp::pp_host_bounce_active() {
8419 Some("host-bounce")
8420 } else if fork_mode == OptiForkGateMode::Controller
8421 && cache.recur.iter().any(Option::is_some)
8422 {
8423 Some("controller-requires-zero-recurrent-state")
8424 } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
8425 Some("requires-pp2")
8426 } else {
8427 None
8428 };
8429 if let Some(reason) = refusal {
8430 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8431 eprintln!("[opti-fork] refused reason={reason}");
8432 } else {
8433 let fence = fence.expect("validated PP-2 fence");
8434 let rt = crate::pp::PpNRt::get(e)?;
8435 let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
8436 let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
8437 let primary_supported =
8438 primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
8439 if !rt.cross_device() || !primary_supported {
8440 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8441 eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
8442 } else {
8443 // Both recurrent snapshots and both seed generations are allocated before
8444 // the first fork, each through its owning PP stage. Allocation failure
8445 // therefore happens before any optimistic state mutation can occur.
8446 let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
8447 let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
8448 let fork = OptiForkState::new(
8449 e,
8450 cache,
8451 fork_mode,
8452 alternate_snapshot,
8453 &h_seed_buf,
8454 &fill_prev,
8455 rt,
8456 fence[1],
8457 self.layers.len(),
8458 )?;
8459 eprintln!(
8460 "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
8461 payload_dev0={} payload_dev1={} q_threshold={:.3}",
8462 fence[1],
8463 fork.logical_payload_bytes[0],
8464 fork.logical_payload_bytes[1],
8465 fork.controller.map_or(0.0, |policy| policy.threshold),
8466 );
8467 fork_snapshot = Some(current_snapshot);
8468 opti_fork = Some(fork);
8469 }
8470 }
8471 }
8472 // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
8473 // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
8474 let mut snap = match fork_snapshot {
8475 Some(snapshot) => snapshot,
8476 None => cache.snapshot(e)?,
8477 };
8478 let mut carried_opti: Option<OptiControllerTicket> = None;
8479 // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
8480 // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
8481 let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
8482 Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
8483 } else {
8484 None
8485 };
8486 // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
8487 // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
8488 // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
8489 // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
8490 // pass of any kind). Verify still
8491 // checks every emitted token against the target -> exactness holds by construction; only
8492 // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
8493 // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
8494 // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
8495 let mut pending: Option<u32> = carried_pending;
8496 // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
8497 // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
8498 // the verify accept readback). Printed once at loop end via spec-stats.
8499 let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
8500 let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
8501 // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
8502 // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
8503 let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
8504 // grammar-truncation counters: how many rounds the verify-side cut fired and how many
8505 // already-verified tokens it threw away. THIS is the quantity draft masking targets.
8506 let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
8507 let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
8508 let mut ph_wait = 0f64;
8509 let mut ph_commit = 0f64;
8510 let mut ph_t = std::time::Instant::now();
8511 let mut ph_mark = |acc: &mut f64, on: bool| {
8512 if on {
8513 let now = std::time::Instant::now();
8514 *acc += (now - ph_t).as_secs_f64();
8515 ph_t = now;
8516 }
8517 };
8518 if let Some(p) = pipe {
8519 p.setup_end();
8520 }
8521 while keep_going && out.len() < max_new {
8522 // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
8523 // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
8524 if let (true, Some(sg), Some(ptrs)) = (
8525 stream_active && round >= 1 && pending.is_some(),
8526 &stream_graph,
8527 &stream_ptrs,
8528 ) {
8529 if debug_spec {
8530 static ONCE: std::sync::Once = std::sync::Once::new();
8531 ONCE.call_once(|| {
8532 eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
8533 });
8534 }
8535 e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
8536 e.set_u32_one(&mut pend_d, pending.unwrap())?;
8537 e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
8538 for _mi in 0..m_rounds {
8539 e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
8540 cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
8541 e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
8542 e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
8543 e.u32_copy(&pend_d, &mut dctx.g_tok)?;
8544 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8545 sg.launch()?;
8546 e.spec_assemble_verify(
8547 &g_tokp2k,
8548 &pend_d,
8549 d2t_dev.as_ref(),
8550 &mut vtok_d,
8551 &mut brk_d,
8552 p_min,
8553 k,
8554 pmin0,
8555 )?;
8556 let mut ck = VerifyCkpt::new(self.layers.len());
8557 let dummy = vec![0u32; t_v_s];
8558 let (tl_d, vx) = self.decode_step_t_core_stream(
8559 e,
8560 &dummy,
8561 0,
8562 &mut *cache,
8563 embd_dev,
8564 Some(&mut ck),
8565 Some((&vtok_d, &pos_ctr)),
8566 None,
8567 )?;
8568 for j in 0..t_v_s {
8569 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
8570 }
8571 e.spec_accept_greedy_dc(
8572 &preds_d,
8573 &vtok_d,
8574 &last_pred_d,
8575 &brk_d,
8576 &mut stream_acc,
8577 )?;
8578 e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
8579 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
8580 self.commit_verified_prefix_stream(
8581 e,
8582 &mut *cache,
8583 &snap,
8584 &ck,
8585 &stream_acc,
8586 1,
8587 t_v_s,
8588 )?;
8589 e.spec_rollback_stream(
8590 ptrs,
8591 &pos_start_d,
8592 &stream_acc,
8593 1,
8594 self.layers.len() + 1,
8595 )?;
8596 e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
8597 }
8598 e.stream().synchronize()?;
8599 let ring_h = e.dtoh_u32(&ring_d)?;
8600 let cnt = ring_h[0] as usize;
8601 for i in 0..cnt {
8602 if out.len() < max_new {
8603 out.push(ring_h[1 + i]);
8604 }
8605 }
8606 let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
8607 for il in 0..self.layers.len() {
8608 if let Some(kvl) = cache.kv[il].as_mut() {
8609 kvl.len = pos_h;
8610 }
8611 }
8612 cache.pos = pos_h;
8613 scratch.kv.len = pos_h;
8614 pending = Some(ring_h[cnt]); // last drained token = the live bonus
8615 last_token = ring_h[cnt];
8616 total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
8617 total_accepted += cnt.saturating_sub(m_rounds);
8618 if let Some(t) = sess_telem {
8619 // totals only — the burst's per-round accept counts stayed on device
8620 // (that is the point of the round-stream arm). pos_* untouched.
8621 t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
8622 }
8623 round += m_rounds;
8624 // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
8625 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
8626 continue;
8627 }
8628 let pipe_draft = match pipe {
8629 Some(p) => Some(p.draft_begin(round)?),
8630 None => None,
8631 };
8632 let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
8633 let mut current_opti = carried_opti.take();
8634 let mut fork_generation = if current_opti.is_none() && pending.is_some() {
8635 match opti_fork.as_mut() {
8636 Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
8637 None => None,
8638 Some(_) => None,
8639 }
8640 } else {
8641 None
8642 };
8643 if current_opti.is_none() {
8644 if let Some(fork) = opti_fork.as_ref() {
8645 opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
8646 } else {
8647 cache.snapshot_into(e, &mut snap)?;
8648 }
8649 } else if snap.pos != pos {
8650 return Err(format!(
8651 "optipipe carried snapshot pos {} != current pos {pos}",
8652 snap.pos
8653 )
8654 .into());
8655 } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
8656 ph_mark(&mut ph_rest, phase_on);
8657
8658 // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
8659 // p-min semantics (both paths): stop the chain early when the head's confidence in
8660 // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
8661 // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
8662 let base0 = if pending.is_some() { 1usize } else { 0usize };
8663 // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
8664 // accepted run + 1 (the gemma law — see the setup block above the loop).
8665 let k_this = if adapt { kc } else { k };
8666 let mut draft: Vec<u32> = Vec::with_capacity(k);
8667 let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
8668 let mut controller_draft_prob: Option<f32> = None;
8669 let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
8670 if let Some(ticket) = current_opti.as_mut() {
8671 let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
8672 if ticket.verify_tokens[0] != carried_pending {
8673 return Err(format!(
8674 "optipipe carried pending mismatch: ticket={} live={carried_pending}",
8675 ticket.verify_tokens[0],
8676 )
8677 .into());
8678 }
8679 draft.push(ticket.verify_tokens[1]);
8680 controller_draft_prob = Some(ticket.draft_prob);
8681 controller_eager_state = ticket
8682 .take_eager_seed()
8683 .map(|seed| (ticket.verify_tokens[1], seed));
8684 } else {
8685 // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
8686 // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
8687 // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
8688 // rejected drafts and p-min extras via the len mechanism).
8689 scratch.set_len(e, pos + base0 - 1)?;
8690 if pen_on {
8691 // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
8692 // device dedup: `penalty_last_n` is usize::MAX for any serve request with
8693 // a penalty, so without the cap this grew with the whole session.
8694 let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
8695 let w0 = pen_hist.len().saturating_sub(win);
8696 pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
8697 }
8698 if sampled {
8699 draft_logits.clear();
8700 draft_stats.clear();
8701 }
8702 // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
8703 // position's mask is computed on that clone and advanced by the PROPOSED token. The
8704 // real state moves only on emission (verify's job), so the emitted stream is
8705 // unchanged — the mask only removes tokens the verify would have truncated anyway.
8706 let mut dmask_live = dmask_on;
8707 if dmask_live {
8708 let t_c = std::time::Instant::now();
8709 constraint
8710 .as_deref_mut()
8711 .unwrap()
8712 .draft_begin()
8713 .map_err(|e2| format!("constraint: {e2}"))?;
8714 dm_clone_ns += t_c.elapsed().as_nanos();
8715 dm_rounds += 1;
8716 }
8717 if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
8718 // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
8719 // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
8720 // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
8721 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
8722 e.set_u32_one(&mut dctx.g_tok, last_token)?;
8723 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8724 for j in 0..k_this {
8725 // per-position mask upload (contents only — the graph's baked pointer is
8726 // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
8727 // mask node degrades to a no-op ban instead of needing a second graph.
8728 if dmask_live
8729 && !upload_draft_mask(
8730 e,
8731 constraint.as_deref_mut().unwrap(),
8732 &mut dctx.g_dmask,
8733 mtp.d2t.as_ref(),
8734 d_vocab,
8735 dmask_words,
8736 )?
8737 {
8738 // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
8739 // genuinely miss the legal set): neutralize the captured mask node and
8740 // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
8741 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
8742 dmask_live = false;
8743 }
8744 gr.launch()?;
8745 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
8746 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
8747 // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
8748 // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
8749 // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
8750 // replay's embed node, and the MMU fault kills the CUDA context for the
8751 // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
8752 // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
8753 // buffer (g_seed = the verify-side handoff vs head-side compute).
8754 if (idx as usize) >= d_vocab {
8755 // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
8756 // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
8757 // seed, untouched since the round-start copy — the pair discriminates
8758 // "seed arrived poisoned" from "head forward produced NaN".
8759 let seed_h = e.dtoh(&dctx.g_seed)?;
8760 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8761 let in_h = e.dtoh(&h_seed_buf)?;
8762 let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
8763 return Err(format!(
8764 "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
8765 round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
8766 round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
8767 the embed row (#87 trap)"
8768 )
8769 .into());
8770 }
8771 // trimmed draft vocab -> target token id (identity when no d2t map)
8772 let d = match &mtp.d2t {
8773 Some(map) => map[idx as usize],
8774 None => idx,
8775 };
8776 let draft_p = if p_min > 0.0
8777 || opti_fork
8778 .as_ref()
8779 .is_some_and(|fork| fork.controller.is_some())
8780 {
8781 Some(e.dtoh(&dctx.g_p)?[0])
8782 } else {
8783 None
8784 };
8785 if j == 0 {
8786 controller_draft_prob = draft_p;
8787 }
8788 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
8789 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8790 break;
8791 }
8792 }
8793 draft.push(d);
8794 // with a trimmed head the NEXT embed must read the TARGET id, not the draft
8795 // index the argmax wrote — patch the persistent token buffer (4B htod).
8796 if d != idx {
8797 e.set_u32_one(&mut dctx.g_tok, d)?;
8798 }
8799 // advance the SPECULATIVE state with the proposal; a dead chain drops to
8800 // unmasked drafting for the remaining positions (verify still arbitrates).
8801 // speculative advance; a chain the grammar can no longer follow (EOS
8802 // proposed) ends here. The captured mask node always runs, so a dead chain
8803 // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
8804 if dmask_live
8805 && !constraint
8806 .as_deref_mut()
8807 .unwrap()
8808 .draft_advance(d)
8809 .map_err(|e2| format!("constraint: {e2}"))?
8810 {
8811 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
8812 break;
8813 }
8814 }
8815 // PURE-TEMP RE-TEST (lane/graph-s-key-exactness-20260819): the sampled graph is
8816 // legal ONLY in the regime it was captured in. The condition used to read
8817 // `(sampled, &dctx.graph_s)` and trusted `s_key` to have dropped anything else —
8818 // which it could not, because the key omitted the filters. Both halves are now
8819 // enforced: the key drops a stale graph, and this site refuses to launch one.
8820 } else if let (true, Some(gr)) = (sampled && pure_temp, &dctx.graph_s) {
8821 if skey_probe() {
8822 eprintln!(
8823 "[skey] chain=graph_s round={round} pure_temp={} top_k={} \
8824 top_p={} min_p={} s_key_parked={:?}",
8825 pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
8826 );
8827 }
8828 // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
8829 // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
8830 // and decides the break. Event-counter continuity: g_ctr is host-seeded to
8831 // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
8832 // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
8833 // stream. Host sctr advances in lockstep (computed, no readback needed).
8834 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
8835 e.set_u32_one(&mut dctx.g_tok, last_token)?;
8836 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8837 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
8838 for j in 0..k_this {
8839 gr.launch()?;
8840 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
8841 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
8842 // counts the p-min-discarded token too)
8843 // q retention: ONE async D2D of the persistent head-logits buffer into this
8844 // round's slot j (stream-ordered after the replay, before the next one).
8845 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
8846 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
8847 // #87 SENTINEL TRAP (see the greedy graph arm above).
8848 if (idx as usize) >= d_vocab {
8849 let seed_h = e.dtoh(&dctx.g_seed)?;
8850 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8851 return Err(format!(
8852 "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
8853 {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
8854 {seed_nan}/{n_embd} — refusing to dereference the embed row \
8855 (#87 trap)"
8856 )
8857 .into());
8858 }
8859 let d = match &mtp.d2t {
8860 Some(map) => map[idx as usize],
8861 None => idx,
8862 };
8863 draft_idx.push(idx);
8864 if p_min > 0.0 {
8865 let p = e.dtoh(&dctx.g_p)?[0];
8866 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8867 break;
8868 }
8869 }
8870 draft.push(d);
8871 // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
8872 if d != idx {
8873 e.set_u32_one(&mut dctx.g_tok, d)?;
8874 }
8875 }
8876 // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
8877 // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
8878 for j in 0..draft.len().max(draft_idx.len()) {
8879 let rows0 = e.htod_i32(&[0])?;
8880 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
8881 e.filter_stats(
8882 &dctx.q_slots[j],
8883 d_vocab,
8884 &rows0,
8885 &mut th_d,
8886 &mut z_d,
8887 &mut mx_d,
8888 d_vocab,
8889 1,
8890 sp_temp,
8891 sp.top_k,
8892 sp.top_p,
8893 sp.min_p,
8894 )?;
8895 draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
8896 }
8897 } else {
8898 if skey_probe() && sampled {
8899 eprintln!(
8900 "[skey] chain=eager round={round} pure_temp={} top_k={} \
8901 top_p={} min_p={} s_key_parked={:?}",
8902 pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
8903 );
8904 }
8905 // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
8906 let mut e_tok = last_token;
8907 let mut d_seed = e.clone_dtod(&h_seed_buf)?;
8908 for j in 0..k_this {
8909 // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
8910 // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
8911 let mtp_pos = pos + base0 + j;
8912 // draft-side grammar mask (eager twin of the graph arm's in-graph node).
8913 // A position with no legal draft-vocab row drops to unmasked drafting for
8914 // the rest of the chain (pre-lane behaviour; verify still arbitrates).
8915 if dmask_live {
8916 dmask_live = upload_draft_mask(
8917 e,
8918 constraint.as_deref_mut().unwrap(),
8919 &mut dctx.g_dmask,
8920 mtp.d2t.as_ref(),
8921 d_vocab,
8922 dmask_words,
8923 )?;
8924 }
8925 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
8926 e,
8927 mtp,
8928 e_tok,
8929 &d_seed,
8930 &mut *scratch,
8931 mtp_pos,
8932 embd_dev,
8933 if dmask_live {
8934 Some((&dctx.g_dmask, dmask_words))
8935 } else {
8936 None
8937 },
8938 )?;
8939 let tok_d = if sampled {
8940 // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
8941 // the filtered softmax (filters off => th=0, exact v1 semantics).
8942 if perturb_buf.is_none() {
8943 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
8944 }
8945 let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
8946 if pen_on {
8947 let h = pen_hist_d.as_ref().unwrap();
8948 let nh = h.len();
8949 e.penalize_logits(
8950 &mut q_row,
8951 h,
8952 nh,
8953 sp.penalty_repeat,
8954 sp.penalty_freq,
8955 sp.penalty_present,
8956 d_vocab,
8957 )?;
8958 }
8959 let rows0 = e.htod_i32(&[0])?;
8960 let (mut th_d, mut z_d, mut mx_d) =
8961 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
8962 e.filter_stats(
8963 &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
8964 1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
8965 )?;
8966 let (th, z, mx) =
8967 (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
8968 let pb = perturb_buf.as_mut().unwrap();
8969 e.gumbel_perturb_filtered(
8970 &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
8971 )?;
8972 sctr += 1;
8973 draft_logits.push(q_row);
8974 draft_stats.push((mx, th, z));
8975 e.argmax_token_device(pb, d_vocab)?
8976 } else {
8977 e.argmax_token_device(&dl_d, d_vocab)?
8978 };
8979 let idx = e.dtoh_u32_one(&tok_d)?;
8980 // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
8981 // here because the eager chain's operands are all readable: dl_d (the head
8982 // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
8983 if (idx as usize) >= d_vocab {
8984 let dl_h = e.dtoh(&dl_d)?;
8985 let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
8986 let seed_h = e.dtoh(&d_seed)?;
8987 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8988 return Err(format!(
8989 "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
8990 round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
8991 step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
8992 embed row (#87 trap)"
8993 )
8994 .into());
8995 }
8996 let d = match &mtp.d2t {
8997 Some(map) => map[idx as usize],
8998 None => idx,
8999 };
9000 if sampled {
9001 draft_idx.push(idx);
9002 }
9003 let draft_p = if p_min > 0.0
9004 || opti_fork
9005 .as_ref()
9006 .is_some_and(|fork| fork.controller.is_some())
9007 {
9008 let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
9009 Some(e.dtoh(&p_d)?[0])
9010 } else {
9011 None
9012 };
9013 if j == 0 {
9014 controller_draft_prob = draft_p;
9015 }
9016 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
9017 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
9018 break;
9019 }
9020 }
9021 draft.push(d);
9022 e_tok = d;
9023 d_seed = h_nextn;
9024 // speculative advance; a chain the grammar can no longer follow (EOS
9025 // proposed) ends here — the prefix already proposed still rides verify.
9026 if dmask_live
9027 && !constraint
9028 .as_deref_mut()
9029 .unwrap()
9030 .draft_advance(d)
9031 .map_err(|e2| format!("constraint: {e2}"))?
9032 {
9033 break;
9034 }
9035 }
9036 if opti_fork
9037 .as_ref()
9038 .is_some_and(|fork| fork.controller.is_some())
9039 {
9040 controller_eager_state = Some((e_tok, d_seed));
9041 }
9042 }
9043 }
9044 let k_round = draft.len();
9045 if let Some(p) = pipe {
9046 p.draft_end(round);
9047 }
9048 drop(pipe_draft);
9049
9050 ph_mark(&mut ph_draft, phase_on);
9051 // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
9052 // (committing its KV/recur inside the SAME weight read); drafts follow. ---
9053 let verify_tokens: Vec<u32> = match pending {
9054 Some(b) => {
9055 let mut v = Vec::with_capacity(k_round + 1);
9056 v.push(b);
9057 v.extend_from_slice(&draft);
9058 v
9059 }
9060 None => draft.clone(),
9061 };
9062 let base = if pending.is_some() { 1 } else { 0 };
9063 // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
9064 // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
9065 let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
9066 Some(ticket.take_ckpt())
9067 } else if spec_replay {
9068 None
9069 } else {
9070 Some(VerifyCkpt::new(self.layers.len()))
9071 };
9072 let controller_can_probe = base == 1
9073 && k_round == 1
9074 && out.len().saturating_add(2) < max_new
9075 && controller_draft_prob.is_some()
9076 && opti_fork
9077 .as_ref()
9078 .and_then(|fork| fork.controller.as_ref())
9079 .is_some_and(|policy| !policy.breaker_tripped);
9080 let mut successor_attempt: Option<OptiControllerTicket> = None;
9081 let mut rejected_probe: Option<(f32, u32)> = None;
9082 let mut controller_prepared: Option<OptiControllerPrepared> = None;
9083 if controller_can_probe {
9084 // Prepare d2/q and, on admission, d3 before either current verify half is
9085 // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
9086 // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
9087 // the primary stream after N stage 1 would serialize the supposed pipeline.
9088 let eager_pos = scratch.kv.len + 1;
9089 let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
9090 e,
9091 mtp,
9092 &mut dctx,
9093 &mut *scratch,
9094 d_vocab,
9095 &mut controller_eager_state,
9096 eager_pos,
9097 embd_dev,
9098 )?;
9099 let first_probability = controller_draft_prob
9100 .ok_or("optipipe controller probe lost first-token probability")?;
9101 let q_proxy = first_probability * pending_probability;
9102 OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9103 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9104 let admitted = opti_fork
9105 .as_ref()
9106 .and_then(|fork| fork.controller.as_ref())
9107 .ok_or("optipipe controller policy disappeared")?
9108 .admit(q_proxy);
9109 if admitted {
9110 OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9111 let eager_pos = scratch.kv.len + 1;
9112 let (optimistic_draft, optimistic_draft_probability) = self
9113 .opti_controller_draft_step(
9114 e,
9115 mtp,
9116 &mut dctx,
9117 &mut *scratch,
9118 d_vocab,
9119 &mut controller_eager_state,
9120 eager_pos,
9121 embd_dev,
9122 )?;
9123 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9124 let eager_seed = controller_eager_state.take().map(|(token, seed)| {
9125 debug_assert_eq!(token, optimistic_draft);
9126 seed
9127 });
9128 controller_prepared = Some(OptiControllerPrepared {
9129 verify_tokens: [optimistic_pending, optimistic_draft],
9130 draft_prob: optimistic_draft_probability,
9131 eager_seed,
9132 q_proxy,
9133 scratch_len: scratch.kv.len,
9134 });
9135 } else {
9136 OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9137 OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9138 rejected_probe = Some((q_proxy, optimistic_pending));
9139 eprintln!(
9140 "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
9141 opti_fork
9142 .as_ref()
9143 .and_then(|fork| fork.controller.as_ref())
9144 .expect("controller policy")
9145 .threshold,
9146 );
9147 }
9148 }
9149 let fork_attempt = match fork_generation.take() {
9150 Some(generation) if base == 1 && k_round == 1 => Some(generation),
9151 Some(generation) => {
9152 opti_fork
9153 .as_mut()
9154 .expect("fork generation without fork state")
9155 .retire(generation)?;
9156 None
9157 }
9158 None => None,
9159 };
9160 let (tlogits_d, vx) = if let Some(p) = pipe {
9161 self.decode_step_t_core_pipelined(
9162 e,
9163 &verify_tokens,
9164 pos,
9165 &mut *cache,
9166 embd_dev,
9167 ckpt.as_mut(),
9168 p,
9169 round,
9170 )?
9171 } else if controller_can_probe {
9172 let fence = opti_fork
9173 .as_ref()
9174 .ok_or("optipipe controller probe lost fork state")?
9175 .fence;
9176 let boundary = match current_opti.as_mut() {
9177 Some(ticket) => ticket.take_boundary(),
9178 None => self.verify_stage0_issue(
9179 e,
9180 &verify_tokens,
9181 pos,
9182 &mut *cache,
9183 embd_dev,
9184 ckpt.as_mut(),
9185 None,
9186 &fence,
9187 Some(true),
9188 None,
9189 )?,
9190 };
9191 if let Some(prepared) = controller_prepared.take() {
9192 let generation = {
9193 let fork = opti_fork
9194 .as_mut()
9195 .ok_or("optipipe controller admission lost fork state")?;
9196 let generation = fork.reserve_successor()?;
9197 let rt = fork.rt;
9198 let snapshot_fence = fork.fence;
9199 opti_snapshot_one_stage_owned_into(
9200 e,
9201 cache,
9202 rt,
9203 &snapshot_fence,
9204 0,
9205 fork.successor_snapshot_mut(),
9206 )?;
9207 generation
9208 };
9209 let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
9210 let successor_boundary = self.verify_stage0_issue(
9211 e,
9212 &prepared.verify_tokens,
9213 pos + verify_tokens.len(),
9214 &mut *cache,
9215 embd_dev,
9216 Some(&mut successor_ckpt),
9217 None,
9218 &fence,
9219 Some(false),
9220 None,
9221 )?;
9222 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9223 let fork = opti_fork
9224 .as_ref()
9225 .ok_or("optipipe controller ticket lost fork state")?;
9226 successor_attempt = Some(fork.controller_ticket(
9227 generation,
9228 successor_boundary,
9229 successor_ckpt,
9230 prepared.verify_tokens,
9231 prepared.draft_prob,
9232 prepared.eager_seed,
9233 prepared.q_proxy,
9234 prepared.scratch_len,
9235 ));
9236 eprintln!(
9237 "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
9238 verify={:?}",
9239 generation.id,
9240 prepared.q_proxy,
9241 fork.controller.expect("controller policy").threshold,
9242 prepared.verify_tokens,
9243 );
9244 }
9245 let result = self.verify_stage1_finish(
9246 e,
9247 boundary,
9248 &mut *cache,
9249 ckpt.as_mut(),
9250 None,
9251 &fence,
9252 successor_attempt.is_none(),
9253 )?;
9254 if let Some(ticket) = current_opti.as_mut() {
9255 ticket.settle();
9256 }
9257 if successor_attempt.is_some() {
9258 let fork = opti_fork
9259 .as_mut()
9260 .ok_or("optipipe successor snapshot lost fork state")?;
9261 let rt = fork.rt;
9262 let snapshot_fence = fork.fence;
9263 opti_snapshot_one_stage_owned_into(
9264 e,
9265 cache,
9266 rt,
9267 &snapshot_fence,
9268 1,
9269 fork.successor_snapshot_mut(),
9270 )?;
9271 // Publish N only after both independent successor-state queues are complete.
9272 fork.rt.publish_to(1, &e.stream())?;
9273 }
9274 result
9275 } else if let Some(ticket) = current_opti.as_mut() {
9276 let fork = opti_fork
9277 .as_mut()
9278 .ok_or("optipipe carried controller ticket lost fork state")?;
9279 let boundary = ticket.take_boundary();
9280 let result = self.verify_stage1_finish(
9281 e,
9282 boundary,
9283 &mut *cache,
9284 ckpt.as_mut(),
9285 None,
9286 &fork.fence,
9287 true,
9288 )?;
9289 ticket.settle();
9290 result
9291 } else if let Some(generation) = fork_attempt {
9292 let fork = opti_fork
9293 .as_mut()
9294 .expect("fork generation without fork state");
9295 fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
9296 let action = fork.mode.action(generation.id);
9297 let boundary = self.verify_stage0_issue(
9298 e,
9299 &verify_tokens,
9300 pos,
9301 &mut *cache,
9302 embd_dev,
9303 ckpt.as_mut(),
9304 None,
9305 &fork.fence,
9306 Some(true),
9307 None,
9308 )?;
9309 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9310 let mut ticket = fork.ticket(generation, boundary);
9311 if action == OptiForkAction::Abort {
9312 return Err(format!(
9313 "optipipe forced abort with generation {} stage0 in flight",
9314 generation.id,
9315 )
9316 .into());
9317 }
9318 fork.reconcile(
9319 e,
9320 &mut *cache,
9321 &mut *scratch,
9322 &snap,
9323 &mut h_seed_buf,
9324 &mut fill_prev,
9325 generation,
9326 action,
9327 verify_tokens[0],
9328 )?;
9329 let result = if action == OptiForkAction::Hit {
9330 let boundary = ticket.take_boundary();
9331 self.verify_stage1_finish(
9332 e,
9333 boundary,
9334 &mut *cache,
9335 ckpt.as_mut(),
9336 None,
9337 &fork.fence,
9338 true,
9339 )?
9340 } else {
9341 // The optimistic boundary slot has no reader. Re-run the unchanged serial
9342 // verify only after E_restart published the restored stage-0 state.
9343 self.decode_step_t_core(
9344 e,
9345 &verify_tokens,
9346 pos,
9347 &mut *cache,
9348 embd_dev,
9349 ckpt.as_mut(),
9350 )?
9351 };
9352 ticket.settle();
9353 debug_assert_eq!(ticket.generation, generation);
9354 fork.retire(generation)?;
9355 result
9356 } else {
9357 self.decode_step_t_core(
9358 e,
9359 &verify_tokens,
9360 pos,
9361 &mut *cache,
9362 embd_dev,
9363 ckpt.as_mut(),
9364 )?
9365 };
9366 let pipe_accept = match pipe {
9367 Some(p) => Some(p.accept_begin(round)?),
9368 None => None,
9369 };
9370
9371 ph_mark(&mut ph_verify, phase_on);
9372 // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
9373 // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
9374 // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
9375 // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
9376 // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
9377 // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
9378 // (== the bonus), so every index shifts by `base` and last_pred is unused.
9379 let t_v = verify_tokens.len();
9380 let mut preds: Vec<u32> = Vec::new();
9381 if !sampled {
9382 for j in 0..t_v {
9383 e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
9384 }
9385 preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
9386 // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
9387 // next round's last_token = the next chain's embed lookup. Catch it at the
9388 // source with the column named — an all-NaN VERIFY column implicates the
9389 // stage-split trunk (decode_step_t_core_ppn), not the draft head.
9390 if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
9391 let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
9392 let mut probe = e.zeros(n_vocab)?;
9393 e.copy_view_into(&mut probe, 0, col, n_vocab)?;
9394 let col_h = e.dtoh(&probe)?;
9395 let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
9396 return Err(format!(
9397 "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
9398 col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
9399 — the stage-split verify produced a poisoned column (#87 trap)",
9400 preds[bad]
9401 )
9402 .into());
9403 }
9404 }
9405 ph_mark(&mut ph_wait, phase_on);
9406 let t_pred = |j: usize| -> u32 {
9407 if j == 0 && base == 0 {
9408 last_pred
9409 } else {
9410 // GREEDY-ONLY: `preds` is filled under `if !sampled` above. The debug print
9411 // used to call this from the sampled arm and panicked the worker; it now goes
9412 // through `debug_t_pred0`. Keep the strict index here — in the greedy walk an
9413 // out-of-range pred is a real bug, not something to paper over.
9414 debug_assert!(
9415 !sampled,
9416 "t_pred is greedy-only: `preds` is empty in the sampled arm"
9417 );
9418 preds[base + j - 1]
9419 }
9420 };
9421 let mut devacc_seeded = false;
9422 let mut devacc_acc: Option<CudaSlice<u32>> = None;
9423 let (n_acc, bonus) = if !sampled {
9424 // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
9425 // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
9426 // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
9427 // gated on token identity vs the host walk (the arms below are bit-equal rules).
9428 if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
9429 {
9430 let draft_d = e.htod_u32_v(&draft)?;
9431 let mut acc_out = e.alloc_u32_zeroed(2)?;
9432 e.spec_accept_greedy(
9433 &preds_d,
9434 &draft_d,
9435 last_pred,
9436 base,
9437 k_round,
9438 &mut acc_out,
9439 )?;
9440 devacc_acc = Some(acc_out.clone());
9441 // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
9442 // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
9443 // non-replay commit arms skip their host-offset seed copies (guarded below);
9444 // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
9445 // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
9446 // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
9447 // the update lands after the arms (devacc_seeded guard below).
9448 e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
9449 // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
9450 // unified rule; full accept rewrites the verify-left value). Host mirrors
9451 // update after the readback; commit_verified_prefix skips its len_d writes.
9452 if let Some(successor) = successor_attempt.as_ref() {
9453 opti_fork
9454 .as_mut()
9455 .ok_or("optipipe successor reconcile lost fork state")?
9456 .queue_actual_reconcile(
9457 e,
9458 &snap,
9459 &acc_out,
9460 successor.verify_tokens[0],
9461 base,
9462 )?;
9463 } else if let Some(ptrs) = &kv_len_ptrs {
9464 let saved: Vec<i32> = (0..self.layers.len())
9465 .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
9466 .collect();
9467 let saved_d = e.htod_i32(&saved)?;
9468 e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
9469 }
9470 devacc_seeded = true;
9471 let ab = e.dtoh_u32(&acc_out)?;
9472 (ab[0] as usize, ab[1])
9473 } else {
9474 let mut n_acc = 0usize;
9475 for j in 0..k_round {
9476 if t_pred(j) == draft[j] {
9477 n_acc += 1;
9478 } else {
9479 break;
9480 }
9481 }
9482 // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
9483 // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
9484 (n_acc, t_pred(n_acc))
9485 }
9486 } else {
9487 // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
9488 if col_buf.is_none() {
9489 col_buf = Some(e.zeros(n_vocab)?);
9490 }
9491 // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
9492 // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
9493 let mut pj = vec![0f32; k_round.max(1)];
9494 let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
9495 if k_round > 0 {
9496 let mut ids: Vec<u32> = Vec::new();
9497 let mut rows: Vec<i32> = Vec::new();
9498 for j in 0..k_round {
9499 if j > 0 || base == 1 {
9500 ids.push(draft[j]);
9501 rows.push((base + j) as i32 - 1);
9502 }
9503 }
9504 if !ids.is_empty() {
9505 let nr = rows.len();
9506 // penalties: materialize the used columns into one contiguous penalized
9507 // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
9508 // penalties: materialize used columns contiguously, penalize all rows in
9509 // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
9510 let p_rows: Vec<i32> = if pen_on {
9511 (0..nr as i32).collect()
9512 } else {
9513 rows.clone()
9514 };
9515 if pen_on {
9516 if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
9517 pcol_buf = Some(e.zeros(nr * n_vocab)?);
9518 }
9519 let pc = pcol_buf.as_mut().unwrap();
9520 for (i2, &r) in rows.iter().enumerate() {
9521 let c = r as usize;
9522 e.copy_view_into(
9523 pc,
9524 i2 * n_vocab,
9525 &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
9526 n_vocab,
9527 )?;
9528 }
9529 let h = pen_hist_d.as_ref().unwrap();
9530 let nh = h.len();
9531 e.penalize_logits_rows(
9532 pc,
9533 h,
9534 nh,
9535 sp.penalty_repeat,
9536 sp.penalty_freq,
9537 sp.penalty_present,
9538 n_vocab,
9539 nr,
9540 )?;
9541 }
9542 let p_src: &CudaSlice<f32> = if pen_on {
9543 pcol_buf.as_ref().unwrap()
9544 } else {
9545 &tlogits_d
9546 };
9547 let rowsd = e.htod_i32(&p_rows)?;
9548 let (mut th_d, mut z_d, mut mx_d) =
9549 (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
9550 e.filter_stats(
9551 p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
9552 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9553 )?;
9554 let idsd = e.htod_u32_v(&ids)?;
9555 let mut outd = e.zeros(nr)?;
9556 e.softmax_gather_filtered(
9557 p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
9558 sp_temp,
9559 )?;
9560 let outv = e.dtoh(&outd)?;
9561 let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
9562 let mut oi = 0usize;
9563 for j in 0..k_round {
9564 if j > 0 || base == 1 {
9565 pj[j] = outv[oi];
9566 oi += 1;
9567 }
9568 }
9569 col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
9570 }
9571 if base == 0 {
9572 let lc: &CudaSlice<f32> = if pen_on {
9573 if col_buf.is_none() {
9574 col_buf = Some(e.zeros(n_vocab)?);
9575 }
9576 let cb = col_buf.as_mut().unwrap();
9577 e.copy_into(
9578 cb,
9579 0,
9580 last_col_logits
9581 .as_ref()
9582 .expect("sampled: last_col_logits unset"),
9583 n_vocab,
9584 )?;
9585 let h = pen_hist_d.as_ref().unwrap();
9586 let nh = h.len();
9587 e.penalize_logits(
9588 cb,
9589 h,
9590 nh,
9591 sp.penalty_repeat,
9592 sp.penalty_freq,
9593 sp.penalty_present,
9594 n_vocab,
9595 )?;
9596 col_buf.as_ref().unwrap()
9597 } else {
9598 last_col_logits
9599 .as_ref()
9600 .expect("sampled: last_col_logits unset")
9601 };
9602 let rows0 = e.htod_i32(&[0])?;
9603 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
9604 e.filter_stats(
9605 lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
9606 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9607 )?;
9608 let idsd = e.htod_u32_v(&[draft[0]])?;
9609 let mut outd = e.zeros(1)?;
9610 e.softmax_gather_filtered(
9611 lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
9612 )?;
9613 pj[0] = e.dtoh(&outd)?[0];
9614 last_col_stats =
9615 Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
9616 }
9617 }
9618 // q source: the graph arm retained the head logits in the persistent q_slots;
9619 // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
9620 // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
9621 // computes them post-replay — graph engages only filter/penalty-free, so the
9622 // stats degenerate to th=0/full-Z there, keeping ONE accept path).
9623 let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
9624 &dctx.q_slots
9625 } else {
9626 &draft_logits
9627 };
9628 let mut n_acc = 0usize;
9629 for j in 0..k_round {
9630 let (qmx, qth, qz) = draft_stats[j];
9631 let idsd = e.htod_u32_v(&[draft_idx[j]])?;
9632 let rowsd = e.htod_i32(&[0])?;
9633 let thd = e.htod(&[qth])?;
9634 let zd = e.htod(&[qz])?;
9635 let _ = qmx;
9636 let mut outd = e.zeros(1)?;
9637 e.softmax_gather_filtered(
9638 &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
9639 sp_temp,
9640 )?;
9641 let qj = e.dtoh(&outd)?[0];
9642 let u = host_u01(sp_seed, uctr);
9643 uctr += 1;
9644 let accept = (u as f64) * (qj as f64) < pj[j] as f64;
9645 // SKEY PROBE: q == 0 for the token the draft actually proposed is the
9646 // exactness signature (see `skey_probe`). Impossible when the draft was
9647 // drawn from the same filtered distribution the verify reconstructs here;
9648 // `u * 0 < p` makes it an UNCONDITIONAL accept whenever p > 0.
9649 if skey_probe() && qj == 0.0 {
9650 eprintln!(
9651 "[skey] EXACTNESS q=0 round={round} j={j} draft_tok={} \
9652 draft_idx={} p={:e} u={u} accepted={} th_z={:?}",
9653 draft[j], draft_idx[j], pj[j], accept as u8, draft_stats[j],
9654 );
9655 }
9656 if accept {
9657 n_acc += 1;
9658 } else {
9659 break;
9660 }
9661 }
9662 let bonus = if n_acc == k_round {
9663 // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
9664 let col = base + k_round - 1;
9665 let cb = col_buf.as_mut().unwrap();
9666 e.copy_view_into(
9667 cb,
9668 0,
9669 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
9670 n_vocab,
9671 )?;
9672 if pen_on {
9673 let h = pen_hist_d.as_ref().unwrap();
9674 let nh = h.len();
9675 e.penalize_logits(
9676 cb,
9677 h,
9678 nh,
9679 sp.penalty_repeat,
9680 sp.penalty_freq,
9681 sp.penalty_present,
9682 n_vocab,
9683 )?;
9684 }
9685 if perturb_buf.is_none() {
9686 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
9687 }
9688 // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
9689 // truncation-fix; receipts research/sampfix-20260805/). The old code reused
9690 // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
9691 // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
9692 // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
9693 // last gathered column, in both base arms. `th` is a threshold in e-units of
9694 // its OWN row's max, so feeding a neighbour's (row_max, th) into
9695 // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
9696 // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
9697 // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
9698 // falls through to its smallest-index tie-break => token id 0 ("!") spliced
9699 // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
9700 // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
9701 // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
9702 // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
9703 // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
9704 // and row_max is unused once nothing is masked), so this fix is a byte-level
9705 // no-op for the untruncated serve default. One extra one-block filter_stats
9706 // per full-accept round is the whole cost.
9707 let (mx, th) = {
9708 let rows0 = e.htod_i32(&[0])?;
9709 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
9710 let cb0 = col_buf.as_ref().unwrap();
9711 e.filter_stats(
9712 cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
9713 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9714 )?;
9715 (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
9716 };
9717 let pb = perturb_buf.as_mut().unwrap();
9718 let cb2 = col_buf.as_ref().unwrap();
9719 e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
9720 sctr += 1;
9721 let td = e.argmax_token_device(pb, n_vocab)?;
9722 e.dtoh_u32_one(&td)?
9723 } else {
9724 // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
9725 let cb = col_buf.as_mut().unwrap();
9726 if n_acc > 0 || base == 1 {
9727 let col = base + n_acc - 1;
9728 e.copy_view_into(
9729 cb,
9730 0,
9731 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
9732 n_vocab,
9733 )?;
9734 } else {
9735 let lc = last_col_logits.as_ref().unwrap();
9736 e.copy_into(cb, 0, lc, n_vocab)?;
9737 }
9738 if pen_on {
9739 let h = pen_hist_d.as_ref().unwrap();
9740 let nh = h.len();
9741 e.penalize_logits(
9742 cb,
9743 h,
9744 nh,
9745 sp.penalty_repeat,
9746 sp.penalty_freq,
9747 sp.penalty_present,
9748 n_vocab,
9749 )?;
9750 }
9751 let cb2 = col_buf.as_ref().unwrap();
9752 let sc = sctr;
9753 sctr += 1;
9754 // p-stats for the reject column: from col_stats when the col was gathered,
9755 // else (j==0&&base==0) from last_col_stats.
9756 let p_stats = if n_acc > 0 || base == 1 {
9757 // col index within the gathered set == number of gathered cols before n_acc
9758 let gi = if base == 1 { n_acc } else { n_acc - 1 };
9759 col_stats.get(gi).copied().unwrap_or_else(|| {
9760 (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
9761 })
9762 } else {
9763 last_col_stats.expect("sampled: last_col_stats unset at reject")
9764 };
9765 let q_stats = draft_stats[n_acc];
9766 if let Some(map) = &d2t_dev {
9767 if q_full_buf.is_none() {
9768 q_full_buf = Some(e.zeros(n_vocab)?);
9769 }
9770 let qf = q_full_buf.as_mut().unwrap();
9771 e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
9772 let qf2 = q_full_buf.as_ref().unwrap();
9773 e.residual_sample_filtered(
9774 cb2,
9775 Some(qf2),
9776 n_vocab,
9777 sp_temp,
9778 sp_seed,
9779 sc,
9780 p_stats,
9781 q_stats,
9782 &mut sample_tok,
9783 )?;
9784 } else {
9785 e.residual_sample_filtered(
9786 cb2,
9787 Some(&q_bufs[n_acc]),
9788 n_vocab,
9789 sp_temp,
9790 sp_seed,
9791 sc,
9792 p_stats,
9793 q_stats,
9794 &mut sample_tok,
9795 )?;
9796 }
9797 e.dtoh_u32(&sample_tok)?[0]
9798 };
9799 (n_acc, bonus)
9800 };
9801 // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
9802 // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
9803 // ordering). Walk the accepted drafts through the grammar in commit order; the
9804 // first illegal token truncates acceptance at its slot, and that slot's emission
9805 // is recomputed as the MASKED argmax of the target's own verify column — token-
9806 // identical to constrained plain greedy decode (an unmasked argmax that is
9807 // grammar-legal IS the masked argmax: masking only removes competitors). The
9808 // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
9809 // measured in acceptance numbers, never hidden.
9810 let (n_acc, bonus) = match constraint.as_deref_mut() {
9811 None => (n_acc, bonus),
9812 Some(c) => {
9813 fn ce(e2: String) -> Box<dyn std::error::Error> {
9814 format!("constraint: {e2}").into()
9815 }
9816 let mut na = n_acc;
9817 let mut cut = false;
9818 for (j, &d) in draft.iter().enumerate().take(n_acc) {
9819 if c.is_allowed(d).map_err(ce)? {
9820 c.consume(d).map_err(ce)?;
9821 } else {
9822 na = j;
9823 cut = true;
9824 dm_cut_tokens += n_acc - j;
9825 break;
9826 }
9827 }
9828 if cut {
9829 dm_cuts += 1;
9830 }
9831 let mut bo = bonus;
9832 if cut || !c.is_allowed(bo).map_err(ce)? {
9833 let mut row = if na == 0 && base == 0 {
9834 init_logits_host
9835 .clone()
9836 .ok_or("constraint: init logits missing (round-0 cut)")?
9837 } else {
9838 e.dtoh_view(
9839 &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
9840 )?
9841 };
9842 c.mask_logits(&mut row).map_err(ce)?;
9843 bo = argmax(&row) as u32;
9844 }
9845 c.consume(bo).map_err(ce)?;
9846 (na, bo)
9847 }
9848 };
9849 let mut successor_valid = false;
9850 if let Some((q_proxy, expected_d2)) = rejected_probe {
9851 let v_n = n_acc == 1 && bonus == expected_d2;
9852 eprintln!(
9853 "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
9854 expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
9855 );
9856 }
9857 if let Some(successor) = successor_attempt.as_ref() {
9858 successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
9859 let generation = successor.generation;
9860 let q_proxy = successor.q_proxy;
9861 let expected_pending = successor.verify_tokens[0];
9862 let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
9863 let fork = opti_fork
9864 .as_mut()
9865 .ok_or("optipipe successor resolution lost fork state")?;
9866 fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
9867 if successor_valid {
9868 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9869 } else {
9870 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9871 OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9872 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
9873 }
9874 let breaker_tripped = fork
9875 .controller
9876 .as_mut()
9877 .expect("controller policy")
9878 .resolve(successor_valid);
9879 if breaker_tripped {
9880 OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9881 }
9882 eprintln!(
9883 "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
9884 expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
9885 resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
9886 generation.id, successor_valid, !successor_valid, breaker_tripped,
9887 );
9888 if !successor_valid {
9889 let mut successor = successor_attempt
9890 .take()
9891 .expect("controller successor disappeared on miss");
9892 successor.settle();
9893 fork.retire(generation)?;
9894 }
9895 }
9896 total_drafted += k_round;
9897 total_accepted += n_acc;
9898 if let Some(t) = sess_telem {
9899 // Greedy, rejection-sampling, and grammar truncation all converge here after
9900 // the accept decision is already on host. Fixed-size relaxed atomics only.
9901 t.record_round(k_round, n_acc);
9902 }
9903 if spec_stats {
9904 st_len_hist[k_round] += 1;
9905 for j in 0..k_round {
9906 st_drafted[j] += 1;
9907 }
9908 for j in 0..n_acc {
9909 st_accepted[j] += 1;
9910 }
9911 if n_acc == k_round {
9912 st_full += 1;
9913 }
9914 }
9915
9916 if debug_spec {
9917 eprintln!(
9918 "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
9919 out.len(),
9920 // NOT `t_pred(0)`: `preds` is filled only under `if !sampled` above, so on a
9921 // sampled request round >= 1 (base == 1) indexed an EMPTY vector and PANICKED
9922 // the GPU worker thread — a debug flag that killed the exact regime you would
9923 // set it to investigate. See `debug_t_pred0`.
9924 debug_t_pred0(sampled, base, last_pred, &preds)
9925 );
9926 }
9927
9928 // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
9929 let commit_started = std::time::Instant::now();
9930 // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
9931 // of them (overshoot past max_new included) or `committed` under-counts the cache rows
9932 // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
9933 // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
9934 for j in 0..n_acc {
9935 if !session_mode && out.len() >= max_new {
9936 break;
9937 }
9938 out.push(draft[j]);
9939 }
9940 if pen_on {
9941 pen_hist.extend_from_slice(&draft[0..n_acc]);
9942 pen_hist.push(bonus);
9943 }
9944 let bonus_emitted = session_mode || out.len() < max_new;
9945 if bonus_emitted {
9946 out.push(bonus);
9947 }
9948 last_token = bonus;
9949
9950 // --- 5. ROLLBACK + advance (§C) ---
9951 if n_acc == k_round && !spec_replay {
9952 // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
9953 // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
9954 // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
9955 // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
9956 // last_pred is dead in the pending path (t_pred reads verify col 0).
9957 //
9958 // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
9959 // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
9960 // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
9961 // trunk hidden (the last verify column). set_len first: a p-min break may have
9962 // left one extra chain append at that slot. Partial accepts need NO fill (the
9963 // chain already covered every accepted position; round-start set_len truncates).
9964 let mut vh_seed = e.zeros(n_embd)?;
9965 e.copy_view_into(
9966 &mut vh_seed,
9967 0,
9968 &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
9969 n_embd,
9970 )?;
9971 if refresh {
9972 // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
9973 // overwrite ALL committed positions' scratch entries with K/V from their EXACT
9974 // verify hiddens — the reference engine's mtp_update fills from true hiddens;
9975 // the full stack (vx) is already resident from the verify. Replaces both the
9976 // chain-approximate entries AND the old last-token-only fill. Acceptance-only
9977 // (draft attention quality); exactness stays the verify's job.
9978 scratch.set_len(e, pos)?;
9979 // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
9980 // (hidden of the last committed row before this verify batch).
9981 let mut vxs = e.zeros(t_v * n_embd)?;
9982 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
9983 if t_v > 1 {
9984 e.copy_view_into(
9985 &mut vxs,
9986 n_embd,
9987 &vx.slice(0..(t_v - 1) * n_embd),
9988 (t_v - 1) * n_embd,
9989 )?;
9990 }
9991 self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
9992 } else {
9993 scratch.set_len(e, pos + base + k_round - 1)?;
9994 // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
9995 let mut hp = e.zeros(n_embd)?;
9996 if t_v >= 2 {
9997 e.copy_view_into(
9998 &mut hp,
9999 0,
10000 &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
10001 n_embd,
10002 )?;
10003 } else {
10004 e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
10005 }
10006 self.mtp_kv_fill(
10007 e,
10008 mtp,
10009 &[draft[k_round - 1]],
10010 &hp,
10011 pos + base + k_round - 1,
10012 &mut *scratch,
10013 embd_dev,
10014 )?;
10015 }
10016 // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
10017 // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
10018 // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
10019 // col). Saves one MTP-block pass per round on top of the pairing fix.
10020 if !devacc_seeded {
10021 e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
10022 e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
10023 }
10024 pending = Some(bonus);
10025 if debug_spec {
10026 eprintln!(" -> FULL ACCEPT (bonus pending, prev-h seed)");
10027 }
10028 } else if !spec_replay && base + n_acc >= 1 {
10029 // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
10030 // the verify's first j = base+n_acc columns ARE the committed sequence, computed
10031 // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
10032 // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
10033 // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
10034 // full-accept path — the legacy duplicate trunk replay is gone. The next chain
10035 // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
10036 // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
10037 // accept (never compounds: the next verify recomputes true hiddens for all
10038 // committed columns).
10039 let j = base + n_acc;
10040 self.commit_verified_prefix(
10041 e,
10042 &mut *cache,
10043 &snap,
10044 ckpt.as_ref().unwrap(),
10045 j,
10046 devacc_seeded,
10047 if devacc_seeded {
10048 devacc_acc.as_ref().map(|a| (a, base, t_v))
10049 } else {
10050 None
10051 },
10052 )?;
10053 let mut seed = e.zeros(n_embd)?;
10054 e.copy_view_into(
10055 &mut seed,
10056 0,
10057 &vx.slice((j - 1) * n_embd..j * n_embd),
10058 n_embd,
10059 )?;
10060 // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
10061 // branch); without it the chain entries stand and only the tail truncates. Either
10062 // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
10063 // (persistent mode), rope pos+j+1 (chain convention).
10064 if refresh {
10065 scratch.set_len(e, pos)?;
10066 let mut vxs = e.zeros(j * n_embd)?;
10067 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
10068 if j > 1 {
10069 e.copy_view_into(
10070 &mut vxs,
10071 n_embd,
10072 &vx.slice(0..(j - 1) * n_embd),
10073 (j - 1) * n_embd,
10074 )?;
10075 }
10076 self.mtp_kv_fill(
10077 e,
10078 mtp,
10079 &verify_tokens[0..j],
10080 &vxs,
10081 pos,
10082 &mut *scratch,
10083 embd_dev,
10084 )?;
10085 } else {
10086 scratch.set_len(e, pos + j)?;
10087 }
10088 // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
10089 // bonus's predecessor (verify col j-1); no pseudo pass.
10090 if !devacc_seeded {
10091 e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
10092 e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
10093 }
10094 pending = Some(bonus);
10095 if debug_spec {
10096 eprintln!(" -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
10097 }
10098 } else if !spec_replay {
10099 // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
10100 // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
10101 // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
10102 // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
10103 // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
10104 // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
10105 // base=1 pending machinery, bit-identical by the decode-exact verify contract.
10106 // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
10107 // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
10108 cache.rollback(e, &snap, 0)?;
10109 scratch.set_len(e, pos)?;
10110 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
10111 pending = Some(bonus);
10112 if debug_spec {
10113 eprintln!(" -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
10114 }
10115 } else {
10116 // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
10117 // this round survives, only possible before the first pending exists, ~round 0):
10118 // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
10119 // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
10120 // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
10121 // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
10122 // trunk hidden.
10123 cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
10124 let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
10125 if let Some(b) = pending.take() {
10126 replay.push(b);
10127 }
10128 replay.extend_from_slice(&draft[0..n_acc]);
10129 replay.push(bonus);
10130 // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
10131 // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
10132 // last col exactly as before (byte-identical to the old _h_emb_dev call).
10133 let (rl_d, rx) = if self.qwen35_serving_class() {
10134 let mut logits = Vec::with_capacity(replay.len() * n_vocab);
10135 let mut hidden = e.uninit(replay.len() * n_embd)?;
10136 for (row, &token) in replay.iter().enumerate() {
10137 let (row_logits, row_hidden) =
10138 self.spec_target_step_h(e, token, &mut *cache)?;
10139 logits.extend_from_slice(&row_logits);
10140 e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
10141 }
10142 (e.htod(&logits)?, hidden)
10143 } else {
10144 self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
10145 };
10146 // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
10147 // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
10148 e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
10149 last_pred = e.dtoh_u32(&preds_d)?[0];
10150 if sampled {
10151 let lr0 = replay.len();
10152 let lc = last_col_logits
10153 .as_mut()
10154 .expect("sampled: last_col_logits unset");
10155 e.copy_view_into(
10156 lc,
10157 0,
10158 &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
10159 n_vocab,
10160 )?;
10161 }
10162 let lr = replay.len();
10163 if lr >= 2 {
10164 e.copy_view_into(
10165 &mut h_seed_buf,
10166 0,
10167 &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
10168 n_embd,
10169 )?;
10170 } else {
10171 // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
10172 // last_token, whose own-row hidden fill_prev still holds.
10173 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
10174 }
10175 // the bonus is COMMITTED here — it becomes the last committed row.
10176 let mut rh_last = e.zeros(n_embd)?;
10177 e.copy_view_into(
10178 &mut rh_last,
10179 0,
10180 &rx.slice((lr - 1) * n_embd..lr * n_embd),
10181 n_embd,
10182 )?;
10183 e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
10184 if debug_spec {
10185 eprintln!(" -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
10186 }
10187 }
10188 if devacc_seeded {
10189 // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
10190 // consumed the old value (both slots carry the same value in every non-replay arm).
10191 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
10192 }
10193 if successor_valid {
10194 let optimistic_scratch_len = successor_attempt
10195 .as_ref()
10196 .expect("valid controller successor disappeared")
10197 .scratch_len;
10198 // The normal current-round commit refreshed/truncated the logical scratch tail.
10199 // Its optimistic successor row was already written physically, so restoring only
10200 // the retained logical length makes that row live for the carried round.
10201 scratch.set_len(e, optimistic_scratch_len)?;
10202 }
10203 if let Some(current) = current_opti.take() {
10204 opti_fork
10205 .as_mut()
10206 .ok_or("optipipe current retirement lost fork state")?
10207 .retire(current.generation)?;
10208 }
10209 if successor_valid {
10210 let successor = successor_attempt
10211 .take()
10212 .expect("valid controller successor disappeared before promotion");
10213 let generation = successor.generation;
10214 opti_fork
10215 .as_mut()
10216 .ok_or("optipipe successor promotion lost fork state")?
10217 .promote_successor_snapshot(&mut snap, generation);
10218 carried_opti = Some(successor);
10219 }
10220 if anatomy_on {
10221 // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
10222 // only for this diagnostic so it does not disappear into the following draft's
10223 // first token readback.
10224 e.stream().synchronize()?;
10225 ph_commit += commit_started.elapsed().as_secs_f64();
10226 }
10227 // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
10228 // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
10229 // final position — the floor's position key reads the committed depth). Burst
10230 // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
10231 // like gemma's burst arm.
10232 if adapt {
10233 let fl_now = floor_at(cache.pos);
10234 kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
10235 }
10236 ph_mark(&mut ph_rest, phase_on);
10237 if let Some(p) = pipe {
10238 p.accept_end(round);
10239 }
10240 drop(pipe_accept);
10241 round += 1;
10242 // sse-cadence: this round's accepted drafts + bonus are committed (out is
10243 // append-only past step 4) — flush at round cadence.
10244 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
10245 }
10246 if let Some(mut ticket) = carried_opti.take() {
10247 opti_fork
10248 .as_mut()
10249 .ok_or("optipipe tail drain lost fork state")?
10250 .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
10251 }
10252 // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
10253 // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
10254 let _ = flush_commit(&mut on_commit, &out, &mut flushed);
10255
10256 if spec_stats {
10257 let per_slot: Vec<String> = (0..k)
10258 .map(|j| {
10259 if st_drafted[j] > 0 {
10260 format!(
10261 "{}/{}={:.3}",
10262 st_accepted[j],
10263 st_drafted[j],
10264 st_accepted[j] as f64 / st_drafted[j] as f64
10265 )
10266 } else {
10267 "0/0".into()
10268 }
10269 })
10270 .collect();
10271 let acc = if total_drafted > 0 {
10272 total_accepted as f64 / total_drafted as f64
10273 } else {
10274 0.0
10275 };
10276 eprintln!(
10277 "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
10278 per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
10279 tok_per_round={:.3}",
10280 per_slot.join(" "),
10281 (total_accepted + round) as f64 / round.max(1) as f64
10282 );
10283 }
10284 if constraint.is_some() {
10285 eprintln!(
10286 "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
10287 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
10288 dm_clone_ns as f64 / 1e6,
10289 dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
10290 );
10291 }
10292 if phase_on {
10293 let tot = ph_draft + ph_verify + ph_wait + ph_rest;
10294 eprintln!(
10295 "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
10296 ph_draft * 1e3,
10297 ph_draft / tot * 100.0,
10298 ph_verify * 1e3,
10299 ph_verify / tot * 100.0,
10300 ph_wait * 1e3,
10301 ph_wait / tot * 100.0,
10302 ph_rest * 1e3,
10303 ph_rest / tot * 100.0
10304 );
10305 }
10306 if anatomy_on {
10307 let rounds_f = round.max(1) as f64;
10308 let other = (ph_rest - ph_commit).max(0.0);
10309 eprintln!(
10310 "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
10311 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
10312 ph_draft * 1e3 / rounds_f,
10313 ph_verify * 1e3 / rounds_f,
10314 ph_wait * 1e3 / rounds_f,
10315 ph_commit * 1e3 / rounds_f,
10316 other * 1e3 / rounds_f,
10317 );
10318 }
10319 let _pipe_tail = pipe.map(|p| p.primary());
10320 // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
10321 // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
10322 // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
10323 // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
10324 if let Some(slot) = sess_draft_slot.take() {
10325 *slot = Some(dctx);
10326 }
10327 let t_rounds = t_ent.elapsed();
10328 if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
10329 // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
10330 // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
10331 // HERE, where the sampler, the session Philox counters and the penalty window are
10332 // all live and the boundary logits row still exists — that is the "make the state
10333 // available" half of the fix; the consuming burst then just emits it. `sctr` is
10334 // written to the session BELOW the draws so the advance is never lost.
10335 *next_pred_slot = Some(last_pred);
10336 let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
10337 let mut stashed_pending = false;
10338 if let Some(b) = pending.take() {
10339 if !sampled {
10340 // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
10341 // committing it with a solo T=1 pass — the next empty-suffix greedy burst
10342 // consumes it as round-0 verify col 0 (a plain round edge; the old tail
10343 // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
10344 // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
10345 // OUT of `committed` (cache rows == committed); the consuming call
10346 // prepends it once its verify commits the row. next_pred is unknowable
10347 // without the commit pass — None; callers gate on pending_tok too.
10348 debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
10349 if let Some(slot) = sess_pending_slot.take() {
10350 *slot = Some(b);
10351 }
10352 *next_pred_slot = None;
10353 // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
10354 // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
10355 *last_h = Some(e.clone_dtod(&fill_prev)?);
10356 stashed_pending = true;
10357 } else {
10358 // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
10359 // the sampled round-0 accept needs this pass's logits (last_col_logits).
10360 let pos_b = cache.pos;
10361 scratch.set_len(e, pos_b)?;
10362 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
10363 // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
10364 // itself — the prediction AFTER the bonus never materialized; it would have
10365 // been the next round's verify col 0). The commit's logits ARE that
10366 // prediction — so they are also the row the next burst's boundary token
10367 // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
10368 *next_pred_slot = Some(if sample_boundary {
10369 sample_boundary_token(
10370 e,
10371 &lg_b,
10372 &sp,
10373 &pen_hist,
10374 &mut sctr,
10375 "burst-tail-commit",
10376 )?
10377 } else {
10378 argmax(&lg_b) as u32
10379 });
10380 self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
10381 *last_h = Some(hb);
10382 }
10383 } else {
10384 // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
10385 *last_h = Some(e.clone_dtod(&fill_prev)?);
10386 if sample_boundary {
10387 // No pending to commit, so the boundary row is the one `last_pred` was
10388 // argmaxed from and the sampled path keeps it on device: the init feed's
10389 // logits when the burst ran zero rounds, else the legacy-replay path's
10390 // last verify column (both predict the token AFTER the last committed
10391 // row). It is retained precisely because round 0's accept test needs it,
10392 // so the draw costs no extra D2H of the [n_vocab] row.
10393 match last_col_logits.as_ref() {
10394 Some(lc) => {
10395 *next_pred_slot = Some(sample_boundary_token_dev(
10396 e,
10397 lc,
10398 n_vocab,
10399 &sp,
10400 &pen_hist,
10401 &mut sctr,
10402 "burst-tail-nopending",
10403 )?);
10404 }
10405 // NAME THE FALLBACK (house standard): unreachable today — a sampled
10406 // burst always feeds or replays, so the row exists — but if it ever
10407 // is, the stream takes a greedy token and SAYS so rather than
10408 // silently regressing to the pre-lane behaviour.
10409 None => eprintln!(
10410 "[spec-boundary] sampled tail kept the ARGMAX boundary token \
10411 (reason: no retained boundary logits row)"
10412 ),
10413 }
10414 }
10415 }
10416 *sctr_slot = sctr;
10417 *uctr_slot = uctr;
10418 committed.extend_from_slice(prompt);
10419 if let Some(cb) = carried_pending {
10420 // the consumed carry's cache row landed in round 0's verify (every pending
10421 // round commits col 0) — it joins `committed` here, in sequence order.
10422 committed.push(cb);
10423 }
10424 if stashed_pending {
10425 // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
10426 // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
10427 // 18446744073709551615 out of range for slice of length 0", killing the
10428 // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
10429 // stream". Reachable because `pending` starts as `carried_pending` (a bonus
10430 // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
10431 // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
10432 // did). So a burst that stashes a pending without emitting anything of its own —
10433 // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
10434 // guard skipping every token under a tight budget — arrives here with
10435 // out.len() == 0 and stashed_pending == true.
10436 //
10437 // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
10438 // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
10439 // just above is already accounted. Saturating, not a min/assert: an empty `out`
10440 // here is a legitimate burst shape, not a corrupt state.
10441 let emitted = out.len().saturating_sub(1);
10442 committed.extend_from_slice(&out[..emitted]);
10443 } else {
10444 committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
10445 }
10446 debug_assert_eq!(
10447 cache.pos,
10448 committed.len(),
10449 "session invariant: cache rows == committed tokens"
10450 );
10451 if setup_trace {
10452 e.stream().synchronize()?; // bound the async tail fill in the trace
10453 let t_tail = t_ent.elapsed();
10454 eprintln!(
10455 "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
10456 t_init.as_secs_f64() * 1e3,
10457 (t_cap - t_init).as_secs_f64() * 1e3,
10458 (t_fill - t_cap).as_secs_f64() * 1e3,
10459 (t_rounds - t_fill).as_secs_f64() * 1e3,
10460 (t_tail - t_rounds).as_secs_f64() * 1e3,
10461 t_tail.as_secs_f64() * 1e3,
10462 out.len(),
10463 continuation
10464 );
10465 }
10466 return Ok((out, total_drafted, total_accepted));
10467 }
10468 out.truncate(max_new);
10469 Ok((out, total_drafted, total_accepted))
10470 }
10471
10472 /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
10473 /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
10474 /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
10475 pub fn extract_dspark_anchors(
10476 &self,
10477 e: &Engine,
10478 tokens: &[u32],
10479 anchor_positions: &[usize],
10480 gamma: usize,
10481 top_k: usize,
10482 chunk: usize,
10483 temperature: f32,
10484 ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
10485 if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
10486 return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
10487 }
10488 if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
10489 return Err("DSpark anchor positions must be sorted and unique".into());
10490 }
10491 for &position in anchor_positions {
10492 if position == 0 || position + gamma >= tokens.len() {
10493 return Err(format!(
10494 "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
10495 tokens.len()
10496 )
10497 .into());
10498 }
10499 }
10500
10501 let n_vocab = self.output.out_features();
10502 let n_embd = self.cfg.n_embd as usize;
10503 let mut cache = crate::pp::new_cache(e, &self.cfg, tokens.len() + gamma + 8)?;
10504 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10505 let embd_gpu = if spec_host_embd() {
10506 None
10507 } else {
10508 Some(
10509 self.embd_gpu
10510 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10511 )
10512 };
10513 let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
10514
10515 struct PendingRecord {
10516 position: usize,
10517 hidden: Option<Vec<f32>>,
10518 tokens: Vec<u32>,
10519 target_top_ids: Vec<Option<Vec<u32>>>,
10520 target_top_logits: Vec<Option<Vec<f32>>>,
10521 target_top_probs: Vec<Option<Vec<f32>>>,
10522 target_tail_probs: Vec<Option<f32>>,
10523 }
10524
10525 let mut pending: Vec<PendingRecord> = anchor_positions
10526 .iter()
10527 .map(|&position| PendingRecord {
10528 position,
10529 hidden: None,
10530 tokens: tokens[position..=position + gamma].to_vec(),
10531 target_top_ids: vec![None; gamma],
10532 target_top_logits: vec![None; gamma],
10533 target_top_probs: vec![None; gamma],
10534 target_tail_probs: vec![None; gamma],
10535 })
10536 .collect();
10537
10538 let mut start = 0usize;
10539 while start < tokens.len() {
10540 let end = (start + chunk).min(tokens.len());
10541 let chunk_tokens = &tokens[start..end];
10542 let (target_logits, hidden_rows) =
10543 self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
10544 for record in &mut pending {
10545 let hidden_position = record.position - 1;
10546 if hidden_position >= start && hidden_position < end {
10547 let local = hidden_position - start;
10548 record.hidden = Some(
10549 e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
10550 );
10551 }
10552 for slot in 0..gamma {
10553 let target_row = record.position + slot;
10554 if target_row < start || target_row >= end {
10555 continue;
10556 }
10557 let local = target_row - start;
10558 let logits =
10559 e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
10560 let (ids, top_logits, probs, tail) =
10561 dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
10562 record.target_top_ids[slot] = Some(ids);
10563 record.target_top_logits[slot] = Some(top_logits);
10564 record.target_top_probs[slot] = Some(probs);
10565 record.target_tail_probs[slot] = Some(tail);
10566 }
10567 }
10568 start = end;
10569 }
10570
10571 pending
10572 .into_iter()
10573 .map(|record| {
10574 let hidden = record
10575 .hidden
10576 .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
10577 let target_top_ids =
10578 flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
10579 let target_top_logits = flatten_dspark_rows(
10580 record.target_top_logits,
10581 record.position,
10582 "target logits",
10583 )?;
10584 let target_top_probs =
10585 flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
10586 let target_tail_probs = record
10587 .target_tail_probs
10588 .into_iter()
10589 .enumerate()
10590 .map(|(slot, value)| {
10591 value.ok_or_else(|| {
10592 format!("missing DSpark tail at {} slot {slot}", record.position)
10593 })
10594 })
10595 .collect::<Result<Vec<_>, _>>()?;
10596 Ok(DsparkAnchorRecord {
10597 position: record.position,
10598 hidden,
10599 tokens: record.tokens,
10600 target_top_ids,
10601 target_top_logits,
10602 target_top_probs,
10603 target_tail_probs,
10604 })
10605 })
10606 .collect()
10607 }
10608
10609 /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
10610 /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
10611 /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
10612 /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
10613 /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
10614 /// quant-induced head/hidden-state mismatch from text drift.
10615 ///
10616 /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
10617 /// draft_j = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
10618 /// eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
10619 /// target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
10620 /// at forced context tokens[0..p+j]). For j==0 this equals live spec
10621 /// acceptance; for j>=1 live verify would condition on the drafts, here it
10622 /// conditions on the corpus — deterministic and arm-comparable by design.
10623 ///
10624 /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
10625 /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
10626 /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
10627 ///
10628 /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
10629 /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
10630 /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
10631 /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
10632 /// agreement vs this path — not usable as a training-data source).
10633 pub fn replay_acceptance(
10634 &self,
10635 e: &Engine,
10636 tokens: &[u32],
10637 k: usize,
10638 stride: usize,
10639 chunk: usize,
10640 mut hdump: Option<&mut std::fs::File>,
10641 ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
10642 assert!(k >= 1 && stride >= 1 && chunk >= 2);
10643 let mtp = self
10644 .mtp
10645 .as_ref()
10646 .expect("replay_acceptance requires an MTP head");
10647 let n_vocab = self.output.out_features();
10648 let d_vocab = mtp
10649 .shared_head_head
10650 .as_ref()
10651 .unwrap_or(&self.output)
10652 .out_features();
10653 let n_embd = self.cfg.n_embd as usize;
10654 let t_total = tokens.len();
10655 assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
10656 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
10657 let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
10658 let mut scratch = MtpScratch::new(
10659 e,
10660 &self.cfg,
10661 t_total + k + 8,
10662 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
10663 )?;
10664 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10665 let embd_gpu = if spec_host_embd() {
10666 None
10667 } else {
10668 Some(
10669 self.embd_gpu
10670 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10671 )
10672 };
10673 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10674
10675 // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
10676 let mut bg: Vec<u32> = vec![0; t_total + 1];
10677 let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
10678 let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
10679 let mut seed_buf = e.zeros(n_embd)?;
10680 let mut preds_d = e.alloc_u32_zeroed(chunk)?;
10681 let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
10682 let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
10683 let mut s = 0usize;
10684 while s < t_total {
10685 let cend = (s + chunk).min(t_total);
10686 let tc = cend - s;
10687 let ch = &tokens[s..cend];
10688 // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
10689 // the chunk's true hiddens.
10690 let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
10691 for j in 0..tc {
10692 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
10693 }
10694 let preds = e.dtoh_u32(&preds_d)?;
10695 for j in 0..tc {
10696 bg[s + j + 1] = preds[j];
10697 }
10698 // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
10699 // checkpoint-quality metric (position j's logits score the GOLD next token).
10700 if nll_on {
10701 let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
10702 if jmax > 0 {
10703 let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
10704 let rows: Vec<i32> = (0..jmax as i32).collect();
10705 let idsd = e.htod_u32_v(&ids)?;
10706 let rowsd = e.htod_i32(&rows)?;
10707 let mut outd = e.zeros(jmax)?;
10708 e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
10709 for pr in e.dtoh(&outd)? {
10710 nll_sum += -((pr.max(1e-30)) as f64).ln();
10711 nll_cnt += 1;
10712 }
10713 }
10714 }
10715 if let Some(f) = hdump.as_deref_mut() {
10716 use std::io::Write;
10717 let host: Vec<f32> = e.dtoh(&vx)?;
10718 // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
10719 // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
10720 let mut bytes = Vec::with_capacity(tc * n_embd * 2);
10721 for v in &host[..tc * n_embd] {
10722 let b = v.to_bits();
10723 let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
10724 bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
10725 }
10726 f.write_all(&bytes)?;
10727 }
10728 // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
10729 // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
10730 // per token saved; the forced trunk pass + hdump is all the mode needs).
10731 let chainless = stride > t_total;
10732 if chainless {
10733 e.copy_view_into(
10734 &mut prev_last_h,
10735 0,
10736 &vx.slice((tc - 1) * n_embd..tc * n_embd),
10737 n_embd,
10738 )?;
10739 s = cend;
10740 continue;
10741 }
10742 // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
10743 // row s reads the previous chunk's last true hidden, zeros at corpus start).
10744 let mut vxs = e.zeros(tc * n_embd)?;
10745 e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
10746 if tc > 1 {
10747 e.copy_view_into(
10748 &mut vxs,
10749 n_embd,
10750 &vx.slice(0..(tc - 1) * n_embd),
10751 (tc - 1) * n_embd,
10752 )?;
10753 }
10754 scratch.set_len(e, s)?;
10755 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
10756 // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
10757 // [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
10758 // truncates those approximate appends before they can ever be read.
10759 let ps: Vec<usize> = (s..cend)
10760 .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
10761 .collect();
10762 for &p in ps.iter().rev() {
10763 scratch.set_len(e, p)?;
10764 if p == s {
10765 e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
10766 } else {
10767 e.copy_view_into(
10768 &mut seed_buf,
10769 0,
10770 &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
10771 n_embd,
10772 )?;
10773 }
10774 let mut e_tok = tokens[p];
10775 let mut d_seed = e.clone_dtod(&seed_buf)?;
10776 let mut drafts: Vec<u32> = Vec::with_capacity(k);
10777 for j in 0..k {
10778 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
10779 e,
10780 mtp,
10781 e_tok,
10782 &d_seed,
10783 &mut scratch,
10784 p + 1 + j,
10785 embd_dev,
10786 None, // acceptance-oracle walk: no grammar
10787 )?;
10788 let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
10789 let idx = e.dtoh_u32_one(&tok_d)?;
10790 let d = match &mtp.d2t {
10791 Some(map) => map[idx as usize],
10792 None => idx,
10793 };
10794 drafts.push(d);
10795 e_tok = d;
10796 d_seed = h_nextn;
10797 }
10798 // targets may live in a LATER chunk's bg — resolved after the walk.
10799 rows.push((p, drafts, Vec::new()));
10800 }
10801 // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
10802 // expect scratch.len == cend with exact rows).
10803 scratch.set_len(e, s)?;
10804 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
10805 e.copy_view_into(
10806 &mut prev_last_h,
10807 0,
10808 &vx.slice((tc - 1) * n_embd..tc * n_embd),
10809 n_embd,
10810 )?;
10811 s = cend;
10812 }
10813 for (p, drafts, targets) in rows.iter_mut() {
10814 for j in 0..drafts.len() {
10815 targets.push(bg[*p + 1 + j]);
10816 }
10817 }
10818 rows.sort_by_key(|r| r.0);
10819 if nll_cnt > 0 {
10820 let mean = nll_sum / nll_cnt as f64;
10821 println!(
10822 "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
10823 mean.exp()
10824 );
10825 }
10826 Ok((rows, bg))
10827 }
10828}
10829
10830#[cfg(test)]
10831mod dspark_sparse_tests {
10832 use super::dspark_sparse_softmax_topk;
10833
10834 #[test]
10835 fn topk_keeps_full_softmax_mass_and_stable_ties() {
10836 let logits = [1.0f32, 3.0, 3.0, -2.0];
10837 let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
10838 assert_eq!(ids, vec![1, 2]);
10839 assert_eq!(top_logits, vec![3.0, 3.0]);
10840 let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
10841 let expected = 1.0 / denominator;
10842 assert!((probs[0] - expected).abs() < 1.0e-6);
10843 assert!((probs[1] - expected).abs() < 1.0e-6);
10844 assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
10845 assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
10846 }
10847}
10848
10849#[cfg(test)]
10850mod spec_replay_env_tests {
10851 use super::spec_replay_env_on;
10852
10853 #[test]
10854 fn replay_requires_literal_one() {
10855 assert!(!spec_replay_env_on(None));
10856 assert!(!spec_replay_env_on(Some("")));
10857 assert!(!spec_replay_env_on(Some("0")));
10858 assert!(!spec_replay_env_on(Some("true")));
10859 assert!(!spec_replay_env_on(Some("2")));
10860 assert!(spec_replay_env_on(Some("1")));
10861 }
10862}
10863
10864#[cfg(test)]
10865mod telem_tests {
10866 use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
10867
10868 #[test]
10869 fn synthetic_accept_masks_produce_tau_and_position_histogram() {
10870 let counters = SpecTelemetryCounters::default();
10871 for mask in [
10872 [true, true, true],
10873 [true, true, false],
10874 [true, false, false],
10875 [false, false, false],
10876 ] {
10877 let accepted = mask.iter().take_while(|&&value| value).count();
10878 counters.record_round(mask.len(), accepted);
10879 }
10880
10881 let snapshot = counters.snapshot();
10882 assert_eq!(
10883 (snapshot.rounds, snapshot.drafted, snapshot.accepted),
10884 (4, 12, 6)
10885 );
10886 assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
10887 assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
10888 assert_eq!(snapshot.tau(), 1.5);
10889 assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
10890 assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
10891 }
10892
10893 /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
10894 /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
10895 #[test]
10896 fn delta_isolates_burst_contribution() {
10897 let mut t = SpecTelemetry::default();
10898 // "previous request": 2 rounds of k=3, accepts 3 then 1.
10899 for (kr, na) in [(3usize, 3usize), (3, 1)] {
10900 t.rounds += 1;
10901 t.drafted += kr as u64;
10902 t.accepted += na as u64;
10903 for j in 0..kr {
10904 t.pos_drafted[j] += 1;
10905 }
10906 for j in 0..na {
10907 t.pos_accepted[j] += 1;
10908 }
10909 }
10910 let before = t;
10911 // "this burst": 1 round k=3, accepts 2.
10912 t.rounds += 1;
10913 t.drafted += 3;
10914 t.accepted += 2;
10915 for j in 0..3 {
10916 t.pos_drafted[j] += 1;
10917 }
10918 for j in 0..2 {
10919 t.pos_accepted[j] += 1;
10920 }
10921 let d = t.delta_since(&before);
10922 assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
10923 assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
10924 assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
10925 assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
10926 }
10927
10928 /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
10929 /// aggregation invariant.
10930 #[test]
10931 fn merge_accumulates_fieldwise() {
10932 let mut agg = SpecTelemetry::default();
10933 let mut d1 = SpecTelemetry {
10934 rounds: 2,
10935 drafted: 6,
10936 accepted: 4,
10937 ..Default::default()
10938 };
10939 d1.pos_drafted[0] = 2;
10940 d1.pos_accepted[0] = 2;
10941 let mut d2 = SpecTelemetry {
10942 rounds: 1,
10943 drafted: 3,
10944 accepted: 1,
10945 ..Default::default()
10946 };
10947 d2.pos_drafted[0] = 1;
10948 d2.pos_accepted[0] = 1;
10949 d2.pos_drafted[1] = 1;
10950 agg.merge(&d1);
10951 agg.merge(&d2);
10952 assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
10953 assert_eq!(agg.pos_drafted[0], 3);
10954 assert_eq!(agg.pos_accepted[0], 3);
10955 assert_eq!(agg.pos_drafted[1], 1);
10956 assert_eq!(agg.pos_accepted[1], 0);
10957 }
10958
10959 /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
10960 /// public metrics surface and must never publish a u64-wrapped garbage value.
10961 #[test]
10962 fn delta_saturates_never_wraps() {
10963 let small = SpecTelemetry {
10964 rounds: 1,
10965 drafted: 2,
10966 accepted: 1,
10967 ..Default::default()
10968 };
10969 let big = SpecTelemetry {
10970 rounds: 5,
10971 drafted: 15,
10972 accepted: 9,
10973 ..Default::default()
10974 };
10975 let d = small.delta_since(&big);
10976 assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
10977 }
10978}
10979
10980#[cfg(test)]
10981mod opti_fork_tests {
10982 use super::{
10983 OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
10984 };
10985
10986 #[test]
10987 fn controller_threshold_and_three_miss_breaker_are_exact() {
10988 let mut policy = OptiControllerPolicy {
10989 threshold: 0.7,
10990 consecutive_misses: 0,
10991 breaker_tripped: false,
10992 };
10993 assert!(!policy.admit(0.699_999));
10994 assert!(policy.admit(0.7));
10995 assert!(!policy.resolve(false));
10996 assert!(!policy.resolve(false));
10997 assert!(policy.resolve(false));
10998 assert!(policy.breaker_tripped);
10999 assert!(!policy.admit(1.0));
11000 assert!(
11001 !policy.resolve(true),
11002 "a resolved hit cannot re-arm a tripped request"
11003 );
11004 assert!(policy.breaker_tripped);
11005 }
11006
11007 #[test]
11008 fn zero_threshold_is_the_true_unconditional_measurement_arm() {
11009 let mut policy = OptiControllerPolicy {
11010 threshold: 0.0,
11011 consecutive_misses: 0,
11012 breaker_tripped: false,
11013 };
11014 for _ in 0..16 {
11015 assert!(policy.admit(0.0));
11016 assert!(!policy.resolve(false));
11017 }
11018 for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
11019 assert!(
11020 !policy.admit(invalid),
11021 "invalid q proxy must fail closed: {invalid}"
11022 );
11023 }
11024 assert!(!policy.breaker_tripped);
11025 assert_eq!(policy.consecutive_misses, 0);
11026 }
11027
11028 #[test]
11029 fn alternating_mode_flips_by_generation_not_round_parity() {
11030 assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
11031 assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
11032 assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
11033 assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
11034 }
11035
11036 #[test]
11037 fn live_generation_cannot_be_overwritten() {
11038 let mut tracker = OptiForkGenerationTracker::default();
11039 let g0 = tracker.reserve().unwrap();
11040 let g1 = tracker.reserve().unwrap();
11041 let err = tracker.reserve().unwrap_err().to_string();
11042 assert!(
11043 err.contains("still owns generation 0"),
11044 "unexpected error: {err}"
11045 );
11046 tracker.retire(g0).unwrap();
11047 let g2 = tracker.reserve().unwrap();
11048 assert_eq!((g2.id, g2.slot), (2, 0));
11049 tracker.retire(g1).unwrap();
11050 tracker.retire(g2).unwrap();
11051 }
11052
11053 #[test]
11054 fn teardown_rejects_a_stale_generation_tag() {
11055 let mut tracker = OptiForkGenerationTracker::default();
11056 let g0 = tracker.reserve().unwrap();
11057 tracker.retire(g0).unwrap();
11058 let err = tracker.retire(g0).unwrap_err().to_string();
11059 assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
11060 }
11061}
11062
11063#[cfg(test)]
11064mod draft_graph_fallback_tests {
11065 use super::DraftGraphFallback;
11066
11067 /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
11068 #[test]
11069 fn flip_is_loud_once_and_memoized_after() {
11070 let mut f = DraftGraphFallback::default();
11071 let line = f
11072 .mark_greedy("out of memory")
11073 .expect("first flip must return the warn line");
11074 assert!(
11075 line.contains("WARN"),
11076 "flip line must be warn-level: {line}"
11077 );
11078 assert!(
11079 line.contains("out of memory"),
11080 "flip line must carry the reason: {line}"
11081 );
11082 assert!(f.greedy_failed());
11083 // re-marking an already-failed graph is the memoization: quiet, still failed.
11084 assert!(f.mark_greedy("out of memory").is_none());
11085 assert!(f.greedy_failed());
11086 // the two graphs' flags are independent (greedy flip leaves sampled capturable).
11087 assert!(!f.sampled_failed());
11088 let line_s = f
11089 .mark_sampled("capture unsupported")
11090 .expect("sampled flip is its own flip");
11091 assert!(
11092 line_s.contains("sampled"),
11093 "sampled flip names itself: {line_s}"
11094 );
11095 assert!(f.mark_sampled("capture unsupported").is_none());
11096 }
11097
11098 /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
11099 /// and says so exactly when there was something to reset.
11100 #[test]
11101 fn reset_on_resume_clears_flags_and_logs_once() {
11102 let mut f = DraftGraphFallback::default();
11103 // clean session: resume is silent, nothing to reset.
11104 assert!(f.reset_on_resume().is_none());
11105 f.mark_greedy("oom").unwrap();
11106 f.mark_sampled("oom").unwrap();
11107 let note = f
11108 .reset_on_resume()
11109 .expect("a set flag must produce the reset note");
11110 assert!(
11111 note.contains("greedy+sampled"),
11112 "note names what was reset: {note}"
11113 );
11114 assert!(
11115 !f.greedy_failed() && !f.sampled_failed(),
11116 "both flags cleared"
11117 );
11118 // and the NEXT failure after a reset is a fresh flip — loud again.
11119 assert!(f.mark_greedy("oom again").is_some());
11120 let note2 = f.reset_on_resume().expect("greedy-only reset");
11121 assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
11122 }
11123
11124 /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
11125 /// they precede a fresh capture attempt whose own failure re-flips loudly.
11126 #[test]
11127 fn shape_change_clears_are_silent() {
11128 let mut f = DraftGraphFallback::default();
11129 f.mark_greedy("oom").unwrap();
11130 f.clear_greedy();
11131 assert!(!f.greedy_failed());
11132 f.mark_sampled("oom").unwrap();
11133 f.clear_sampled();
11134 assert!(!f.sampled_failed());
11135 // after a silent clear there is nothing left for resume to report.
11136 assert!(f.reset_on_resume().is_none());
11137 }
11138}
11139
11140/// SAMPLED DRAFT-GRAPH KEY (lane/graph-s-key-exactness-20260819).
11141///
11142/// These are the CPU teeth for an exactness bug whose live reproduction needs a GPU, a trunk, a
11143/// drafter and a two-turn session: the key itself. Every test below fails against the pre-fix key
11144/// `(seed, temp.to_bits(), k)` — `legacy_key` restates it so the collision is explicit rather
11145/// than remembered.
11146#[cfg(test)]
11147mod sampled_graph_key_tests {
11148 use super::{SampledGraphKey, debug_t_pred0};
11149
11150 /// The pre-fix key, verbatim: `let s_key = (sp_seed, sp_temp.to_bits(), k);`
11151 fn legacy_key(k: &SampledGraphKey) -> (u64, u32, usize) {
11152 (k.seed, k.temp_bits, k.k)
11153 }
11154
11155 fn pure_temp_key() -> SampledGraphKey {
11156 // temperature 1.0, filters off — today's serve default, the shape that parks a graph.
11157 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, false)
11158 }
11159
11160 /// THE COLLISION. Two requests that differ ONLY in the truncation filters shared one key, so
11161 /// a parked pure-temp graph survived into a filtered request and the launch site launched it.
11162 #[test]
11163 fn vendor_filters_change_the_key() {
11164 let parked = pure_temp_key();
11165 // qwen3.8 generation_config.json — what the vendor-default flip makes the default shape.
11166 let vendor = SampledGraphKey::new(12345, 1.0, 3, 20, 0.95, 0.0, false);
11167 assert_eq!(
11168 legacy_key(&parked),
11169 legacy_key(&vendor),
11170 "pre-fix key collided: this is the bug, and the reason a test asserts on it",
11171 );
11172 assert_ne!(parked, vendor, "post-fix key must separate the two regimes");
11173 assert!(parked.pure_temp());
11174 assert!(!vendor.pure_temp());
11175 }
11176
11177 /// Each distribution-shaping field alone is enough to drop the parked graph.
11178 #[test]
11179 fn every_filter_field_is_keyed() {
11180 let base = pure_temp_key();
11181 for (what, other) in [
11182 (
11183 "top_k",
11184 SampledGraphKey::new(12345, 1.0, 3, 20, 1.0, 0.0, false),
11185 ),
11186 (
11187 "top_p",
11188 SampledGraphKey::new(12345, 1.0, 3, 0, 0.95, 0.0, false),
11189 ),
11190 (
11191 "min_p",
11192 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.05, false),
11193 ),
11194 (
11195 "penalties",
11196 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, true),
11197 ),
11198 ] {
11199 assert_ne!(base, other, "{what} must be part of the key");
11200 assert!(!other.pure_temp(), "{what} leaves the pure-temp regime");
11201 assert_eq!(
11202 legacy_key(&base),
11203 legacy_key(&other),
11204 "{what} was invisible to the pre-fix key",
11205 );
11206 }
11207 }
11208
11209 /// The baked constants stay keyed (this half was always right — regression cover for it).
11210 #[test]
11211 fn baked_constants_stay_keyed() {
11212 let base = pure_temp_key();
11213 assert_ne!(
11214 base,
11215 SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false),
11216 "seed"
11217 );
11218 assert_ne!(
11219 base,
11220 SampledGraphKey::new(12345, 0.7, 3, 0, 1.0, 0.0, false),
11221 "temp"
11222 );
11223 assert_ne!(
11224 base,
11225 SampledGraphKey::new(12345, 1.0, 4, 0, 1.0, 0.0, false),
11226 "k"
11227 );
11228 // bitwise on temperature: 0.7f32 vs the same value re-derived must NOT differ.
11229 assert_eq!(
11230 SampledGraphKey::new(1, 0.7, 3, 0, 1.0, 0.0, false),
11231 SampledGraphKey::new(1, 7.0 / 10.0, 3, 0, 1.0, 0.0, false),
11232 );
11233 }
11234
11235 /// THE LOAD-BEARING HALF OF THE SEED DECISION (lane/session-resume-sampler-predicate-
11236 /// 20260820). The whole-session resume predicate deliberately does NOT compare `seed`: an
11237 /// omitted serve `seed` draws fresh per-request entropy, so comparing it would refuse every
11238 /// seed-omitting sampled conversation. That is only sound because the one piece of parked state
11239 /// that BAKES the seed — this graph — is re-keyed on it, so a seed change drops and recaptures.
11240 ///
11241 /// This test is the other end of that argument, asserted here rather than remembered in a
11242 /// comment: if a future change dropped `seed` from the key, the resume predicate's exclusion
11243 /// would silently become the unsound thing it is documented not to be.
11244 /// (Paired with `seed_alone_does_not_refuse` in `memra-sampling`.)
11245 #[test]
11246 fn seed_alone_still_rekeys_the_draft_graph() {
11247 let parked = pure_temp_key();
11248 let reseeded = SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false);
11249 assert_ne!(
11250 parked, reseeded,
11251 "a seed-only change MUST drop the parked sampled graph — the resume predicate's \
11252 decision not to compare seed rests on exactly this",
11253 );
11254 // Same regime on both sides: the drop is a recapture, not a fall to the eager chain
11255 // because of a filter difference.
11256 assert!(parked.pure_temp() && reseeded.pure_temp());
11257 }
11258
11259 /// `pure_temp()` is the capture guard's predicate, computed from the key so the two cannot
11260 /// drift. The equality below is the invariant the launch-site guard asserts: identical keys
11261 /// agree on the regime, so a graph that survives the drop is legal to launch.
11262 #[test]
11263 fn equal_keys_agree_on_the_regime() {
11264 let a = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
11265 let b = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
11266 assert_eq!(a, b);
11267 assert_eq!(a.pure_temp(), b.pure_temp());
11268 // top_p slightly above 1.0 (a client sending 1.0 exactly, or an operator default) is
11269 // still the unfiltered regime, matching the original `sp.top_p >= 1.0` test.
11270 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.0, 0.0, false).pure_temp());
11271 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.5, -1.0, false).pure_temp());
11272 }
11273
11274 /// MEMRA_DEBUG_SPEC on a SAMPLED spec request past round 0: the print must render without
11275 /// indexing the empty greedy `preds` vector (it panicked the GPU worker before this lane).
11276 #[test]
11277 fn debug_print_survives_the_sampled_arm() {
11278 // round >= 1 with a pending bonus == base 1, sampled == `preds` empty.
11279 assert_eq!(debug_t_pred0(true, 1, 4242, &[]), "n/a");
11280 assert_eq!(debug_t_pred0(true, 2, 4242, &[]), "n/a");
11281 // round 0 without a pending bonus still reports last_pred, in both arms.
11282 assert_eq!(debug_t_pred0(true, 0, 4242, &[]), "4242");
11283 assert_eq!(debug_t_pred0(false, 0, 4242, &[7, 8]), "4242");
11284 // greedy keeps the real prediction it always printed.
11285 assert_eq!(debug_t_pred0(false, 1, 4242, &[7, 8]), "7");
11286 assert_eq!(debug_t_pred0(false, 2, 4242, &[7, 8]), "8");
11287 }
11288}