memra_engine/spec.rs
1//! Qwen3.5 MTP (NextN) greedy speculative decode (research/mtp/MTP-PLAN.md §A/§B/§C/§D).
2//!
3//! Greedy spec decode is MATHEMATICALLY EXACT: the accepted+bonus token stream is token-for-token
4//! identical to plain greedy `generate`. This module provides:
5//! - `mtp_head_forward` (§A, T=1): one NextN draft-token forward.
6//! - `decode_step_t` (§D.3, T=K+1): batched target verify forward, all-column logits.
7//! - `generate_spec` (§B): the draft/verify/accept/rollback orchestrator.
8//! Cache snapshot/rollback lives in cache.rs (§D.4). The MTP head uses its OWN scratch KV (§D.6),
9//! PERSISTENT over the committed sequence (see `MtpScratch`).
10
11use crate::cache::{Cache, KvLayer};
12use crate::forward::argmax;
13use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer, MtpHead};
14use crate::Engine;
15use cudarc::driver::CudaSlice;
16
17/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
18/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
19/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
20/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
21/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
22/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
23/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
24pub(crate) fn spec_hpost() -> bool {
25 static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
26 *H.get_or_init(|| {
27 std::env::var("MEMRA_SPEC_HPOST")
28 .map(|v| v != "0")
29 .unwrap_or(false)
30 })
31}
32
33/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
34/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
35/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
36/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
37/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
38/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
39/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
40/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
41/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
42pub(crate) fn spec_lean() -> bool {
43 static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
44 // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
45 // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
46 // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
47 *L.get_or_init(|| {
48 std::env::var("MEMRA_SPEC_LEAN")
49 .map(|v| v != "0")
50 .unwrap_or(true)
51 })
52}
53
54/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
55/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
56/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
57/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
58/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
59/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
60/// ring — the ring stores raw input columns); every arithmetic kernel is the same one the
61/// t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
62/// t-loop == chained T=1 steps);
63/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
64/// pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
65/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
66pub(crate) fn spec_m2() -> bool {
67 static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
68 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
69 // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
70 // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
71 // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
72 *M.get_or_init(|| {
73 std::env::var("MEMRA_SPEC_M2")
74 .map(|v| v != "0")
75 .unwrap_or(true)
76 })
77}
78pub(crate) fn spec_stream() -> bool {
79 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
80 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
81}
82pub(crate) fn spec_stream_m() -> usize {
83 static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
84 *M.get_or_init(|| {
85 std::env::var("MEMRA_SPEC_STREAM_M")
86 .ok()
87 .and_then(|v| v.parse().ok())
88 .unwrap_or(4)
89 })
90}
91pub(crate) fn spec_devacc() -> bool {
92 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
93 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
94}
95
96/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
97/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
98/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
99/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
100/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
101/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
102/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
103/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
104/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
105pub trait SpecConstraint {
106 /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
107 /// masked argmax).
108 fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
109 /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
110 fn mask_words(&mut self) -> Result<Vec<u32>, String>;
111 /// Is `tok` consumable in the CURRENT state?
112 fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
113 /// Advance the state with an emitted token.
114 fn consume(&mut self, tok: u32) -> Result<(), String>;
115
116 // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
117 // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
118 // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
119 // loose, research/constrained-full-20260803). These three methods let the engine mask the
120 // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
121 // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
122 // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
123 // stays the correctness backstop and the emitted stream is unchanged by construction
124 // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
125 // argmax; a cut slot is recomputed as the masked argmax either way).
126 // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
127
128 /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
129 /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
130 fn draft_mask_enabled(&self) -> bool {
131 false
132 }
133 /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
134 /// slot. Called once per spec round, before the first draft position.
135 fn draft_begin(&mut self) -> Result<(), String> {
136 Ok(())
137 }
138 /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
139 /// for the draft position about to be sampled. `None` = draft masking off (no-op).
140 fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
141 Ok(None)
142 }
143 /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
144 /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
145 /// engine stops drafting; the token already pushed still goes through verify.
146 fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
147 Ok(false)
148 }
149}
150
151/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
152/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
153/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
154/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
155/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
156/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
157/// verify emits the masked argmax as usual).
158fn upload_draft_mask(
159 e: &Engine,
160 c: &mut dyn SpecConstraint,
161 dst: &mut CudaSlice<u32>,
162 d2t: Option<&Vec<u32>>,
163 d_vocab: usize,
164 words: usize,
165) -> Result<bool, Box<dyn std::error::Error>> {
166 let Some(tw) = c.draft_mask_words().map_err(|e2| format!("constraint: {e2}"))? else {
167 return Ok(false);
168 };
169 let bit = |t: usize| -> bool {
170 let w = t >> 5;
171 w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
172 };
173 let mut buf = vec![0u32; words];
174 match d2t {
175 // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
176 Some(map) => {
177 for (i, &t) in map.iter().enumerate().take(d_vocab) {
178 if bit(t as usize) {
179 buf[i >> 5] |= 1u32 << (i & 31);
180 }
181 }
182 }
183 // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
184 // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
185 None => {
186 let n = tw.len().min(words);
187 buf[..n].copy_from_slice(&tw[..n]);
188 }
189 }
190 if buf.iter().all(|w| *w == 0) {
191 return Ok(false);
192 }
193 e.htod_u32_into(dst, &buf)?;
194 Ok(true)
195}
196
197/// Keep the full token-embedding table in host memory and upload only the rows needed by each
198/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
199/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
200/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
201pub(crate) fn spec_host_embd() -> bool {
202 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
203 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
204}
205
206/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
207/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
208/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
209/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
210/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
211/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
212/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
213/// run-spec K=1..8 + acceptance identity arbitrate e2e).
214pub(crate) fn spec_fused_t() -> bool {
215 static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
216 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
217 // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
218 // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
219 *F.get_or_init(|| {
220 std::env::var("MEMRA_SPEC_FUSED_T")
221 .map(|v| v != "0")
222 .unwrap_or(true)
223 })
224}
225
226/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
227/// Only call this on such buffers — the lean contract is "identical bytes by construction".
228fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
229 if spec_lean() {
230 e.uninit(n)
231 } else {
232 e.zeros(n)
233 }
234}
235
236/// Scratch KV for the MTP block (one full-attn layer).
237///
238/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
239/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
240/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
241/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
242/// engine's "mtp_update" design). Entries come from two sources:
243/// - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
244/// hidden chain-approximate — the reference engine accepts the same);
245/// - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
246/// from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
247/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
248/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
249/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
250/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
251/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
252/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
253/// committed row across turns (the predecessor-pairing seed + fill anchor).
254/// Per-request sampling config for the sampled-spec serve path.
255#[derive(Clone, Copy, Debug)]
256pub struct SpecSampling {
257 pub temp: f32,
258 pub seed: u64,
259 pub top_k: i32, // 0 = off
260 pub top_p: f32, // 1.0 = off
261 pub min_p: f32, // 0.0 = off
262 pub penalty_last_n: usize, // 0 = penalties off
263 pub penalty_repeat: f32,
264 pub penalty_freq: f32,
265 pub penalty_present: f32,
266}
267
268/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
269/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
270pub const SPEC_TELEM_POS: usize = 8;
271
272/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
273/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
274/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
275/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
276/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
277/// in NEITHER drafted nor accepted.
278#[derive(Clone, Copy, Default, Debug)]
279pub struct SpecTelemetry {
280 /// verify rounds completed (a round-stream burst counts each of its M rounds).
281 pub rounds: u64,
282 /// tokens drafted / accepted across all rounds.
283 pub drafted: u64,
284 pub accepted: u64,
285 /// how often draft position j (0-based within a round's chain) was offered / accepted.
286 /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
287 /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
288 /// arrays cover the standard-path rounds only and their sums may undercount the totals.
289 pub pos_drafted: [u64; SPEC_TELEM_POS],
290 pub pos_accepted: [u64; SPEC_TELEM_POS],
291}
292
293impl SpecTelemetry {
294 /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
295 /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
296 /// a wrapped counter.
297 pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
298 let mut d = SpecTelemetry {
299 rounds: self.rounds.saturating_sub(prev.rounds),
300 drafted: self.drafted.saturating_sub(prev.drafted),
301 accepted: self.accepted.saturating_sub(prev.accepted),
302 ..Default::default()
303 };
304 for j in 0..SPEC_TELEM_POS {
305 d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
306 d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
307 }
308 d
309 }
310 /// Fieldwise `self += d` — the worker's per-model aggregation.
311 pub fn merge(&mut self, d: &SpecTelemetry) {
312 self.rounds += d.rounds;
313 self.drafted += d.drafted;
314 self.accepted += d.accepted;
315 for j in 0..SPEC_TELEM_POS {
316 self.pos_drafted[j] += d.pos_drafted[j];
317 self.pos_accepted[j] += d.pos_accepted[j];
318 }
319 }
320}
321
322pub struct SpecSession {
323 pub(crate) cache: Cache,
324 pub(crate) scratch: MtpScratch,
325 /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
326 /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
327 /// session must count them. Callers render output from this, not from their own echo.
328 pub committed: Vec<u32>,
329 /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
330 pub(crate) last_h: Option<CudaSlice<f32>>,
331 /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
332 /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
333 /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
334 pub next_pred: Option<u32>,
335 /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
336 /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
337 pub sctr: u32,
338 pub uctr: u32,
339 /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
340 /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
341 /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
342 /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
343 /// research/spec-serving-20260801). None before the first turn; error paths drop it
344 /// (next burst recaptures — serve retires errored sessions anyway).
345 pub(crate) draft_ctx: Option<DraftGraphCtx>,
346 /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
347 /// emitted by the last round but NOT committed to the caches. The old tail committed it with
348 /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
349 /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
350 /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
351 /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
352 /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
353 /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
354 /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
355 /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
356 /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
357 pub pending_tok: Option<u32>,
358 /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
359 /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
360 /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
361 /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
362 pub(crate) turn_ckpt: Option<SpecCheckpoint>,
363 /// Session-lifetime acceptance telemetry (lane/accept-telemetry). Host-side u64 adds at
364 /// the round accounting the loop already does — no syncs, no allocation. NOTE a
365 /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
366 /// diff with [`SpecTelemetry::delta_since`] around each burst.
367 pub telem: SpecTelemetry,
368}
369impl SpecSession {
370 /// Context capacity of the session's caches (the server's ContextFull guard).
371 pub fn cache_max_ctx(&self) -> usize {
372 self.cache.max_ctx
373 }
374 /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
375 /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
376 /// `spec_rewind_to_checkpoint`.
377 pub fn rewind_pos(&self) -> Option<usize> {
378 self.turn_ckpt.as_ref().map(|c| c.pos)
379 }
380 /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
381 /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
382 /// session has never run a turn and has no prediction to hand over.
383 pub fn demote_ready(&self) -> bool {
384 self.pending_tok.is_none() && self.next_pred.is_some()
385 }
386 /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
387 pub fn has_pending(&self) -> bool {
388 self.pending_tok.is_some()
389 }
390 /// Committed row count == cache rows (the session invariant), for the caller's own
391 /// `fed`-length cross-check at a handoff boundary.
392 pub fn committed_len(&self) -> usize {
393 self.committed.len()
394 }
395 /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
396 /// cache + next-token prediction to the plain batched-decode path.
397 ///
398 /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
399 /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
400 /// tokenwise prime of the same `committed` sequence would have left it (that is the
401 /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
402 /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
403 /// committed row — and verify-column logits are bit-identical to plain decode's logits at
404 /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
405 /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
406 /// a state indistinguishable from one the batched path produced itself: the batched tick
407 /// emits `next_pred`, feeds it into this same cache, and decodes on.
408 ///
409 /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
410 /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
411 /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
412 /// path would silently skip a token.
413 ///
414 /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
415 /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
416 /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
417 /// would mean an `mtp_kv_fill` over the whole committed history).
418 pub fn into_demoted(self) -> Option<(Cache, u32)> {
419 if self.pending_tok.is_some() {
420 return None;
421 }
422 let np = self.next_pred?;
423 debug_assert_eq!(
424 self.cache.pos,
425 self.committed.len(),
426 "demotion handoff: cache rows != committed tokens"
427 );
428 Some((self.cache, np))
429 }
430 /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
431 /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
432 /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
433 /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
434 pub fn reset_graph_fallback_on_resume(&mut self) {
435 if let Some(line) = self
436 .draft_ctx
437 .as_mut()
438 .and_then(|c| c.failed.reset_on_resume())
439 {
440 eprintln!("{line}");
441 }
442 }
443}
444
445/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
446///
447/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
448/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
449/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
450/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
451/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
452/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
453///
454/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
455/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
456/// position index, so it must be a real device COPY — that copy is the entire reason a spec
457/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
458/// below the boundary were written by this turn's fill and are never revisited (the per-round
459/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
460/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
461/// predecessor-pairing anchor the next prime's fill reads for its first row.
462///
463/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
464pub(crate) struct SpecCheckpoint {
465 snap: crate::cache::CacheSnapshot,
466 /// Committed length at the boundary (== cache.pos there, the session invariant).
467 pos: usize,
468 /// Pre-output_norm hidden of row `pos - 1`.
469 last_h: CudaSlice<f32>,
470}
471
472/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
473/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
474/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
475/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
476/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
477/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
478/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
479/// so the eager fallback doesn't pay a doomed capture attempt every burst.
480pub(crate) struct DraftGraphCtx {
481 g_tok: CudaSlice<u32>,
482 g_pos: CudaSlice<i32>,
483 g_seed: CudaSlice<f32>,
484 g_p: CudaSlice<f32>,
485 g_ctr: CudaSlice<u32>,
486 g_q: CudaSlice<f32>,
487 g_perturb: CudaSlice<f32>,
488 q_slots: Vec<CudaSlice<f32>>,
489 /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
490 /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
491 /// per-position contents the host re-uploads before each replay (the graph-promote
492 /// pattern from decode.rs). Empty unless the session drafts under a grammar.
493 g_dmask: CudaSlice<u32>,
494 /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
495 graph_masked: bool,
496 graph: Option<cudarc::driver::CudaGraph>,
497 graph_s: Option<cudarc::driver::CudaGraph>,
498 /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
499 /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
500 failed: DraftGraphFallback,
501 /// (seed, temp.to_bits(), k) baked into graph_s at its capture.
502 s_key: Option<(u64, u32, usize)>,
503 /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
504 /// pool addresses the captured graph(s) bake. Without these, the transients return to the
505 /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
506 /// co-served session in the worker) reuses those addresses — the persisted graph's replay
507 /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
508 /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
509 /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
510 /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
511 keeper: Vec<Box<dyn std::any::Any + Send>>,
512 keeper_s: Vec<Box<dyn std::any::Any + Send>>,
513}
514
515/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
516/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
517///
518/// Three contracts:
519/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
520/// (returned, not printed, so the once-per-flip contract is unit-testable); the caller
521/// `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
522/// an already-failed graph returns None (the per-burst memoization that keeps the eager
523/// fallback from paying a doomed capture attempt every burst).
524/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
525/// NEW request gets one fresh capture chance instead of carrying a transient-pressure
526/// failure for the pool's whole lifetime. Returns the note line only when a flag was
527/// actually set (quiet on the common clean-resume path).
528/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
529/// capture attempt whose own failure would re-flip loudly.
530#[derive(Default)]
531pub(crate) struct DraftGraphFallback {
532 greedy: bool,
533 sampled: bool,
534}
535impl DraftGraphFallback {
536 fn mark_greedy(&mut self, reason: &str) -> Option<String> {
537 if self.greedy {
538 return None;
539 }
540 self.greedy = true;
541 Some(format!(
542 "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
543 ))
544 }
545 fn mark_sampled(&mut self, reason: &str) -> Option<String> {
546 if self.sampled {
547 return None;
548 }
549 self.sampled = true;
550 Some(format!(
551 "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
552 ))
553 }
554 fn greedy_failed(&self) -> bool {
555 self.greedy
556 }
557 fn sampled_failed(&self) -> bool {
558 self.sampled
559 }
560 fn clear_greedy(&mut self) {
561 self.greedy = false;
562 }
563 fn clear_sampled(&mut self) {
564 self.sampled = false;
565 }
566 /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
567 /// was set (so clean resumes stay quiet).
568 pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
569 if !self.greedy && !self.sampled {
570 return None;
571 }
572 let which = match (self.greedy, self.sampled) {
573 (true, true) => "greedy+sampled",
574 (true, false) => "greedy",
575 _ => "sampled",
576 };
577 self.greedy = false;
578 self.sampled = false;
579 Some(format!(
580 "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
581 ))
582 }
583}
584
585impl DraftGraphCtx {
586 fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
587 Ok(DraftGraphCtx {
588 g_tok: e.alloc_u32_zeroed(1)?,
589 g_pos: e.htod_i32(&[0])?,
590 g_seed: e.zeros(n_embd)?,
591 g_p: e.zeros(1)?,
592 g_ctr: e.alloc_u32_zeroed(1)?,
593 g_q: e.zeros(qlen)?,
594 g_perturb: e.zeros(qlen)?,
595 q_slots: Vec::new(),
596 g_dmask: e.alloc_u32_zeroed(1)?,
597 graph_masked: false,
598 graph: None,
599 graph_s: None,
600 failed: DraftGraphFallback::default(),
601 s_key: None,
602 keeper: Vec::new(),
603 keeper_s: Vec::new(),
604 })
605 }
606}
607
608pub(crate) struct MtpScratch {
609 kv: KvLayer,
610 /// Row capacity. Doubles as the fa_decode_dc bucket_max for BOTH draft paths (graph + eager):
611 /// n_splits is sized from it ONCE, so the graph captured at round 0 stays valid for every
612 /// later t_kv (splits beyond the device len_d exit empty; the shared combine skips them) —
613 /// KV growth without recapture. Eager uses the SAME bucket_max -> identical dispatch ->
614 /// bit-identical drafts (the graph-vs-eager parity gate).
615 cap: usize,
616}
617
618fn mtp_scratch_layout(
619 cfg: &memra_gguf::config::ModelConfig,
620 geom: Option<&crate::hybrid::DraftGeom>,
621) -> (usize, usize, usize, usize) {
622 // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
623 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
624 let head_dim_k = cfg.head_dim_k as usize;
625 let head_dim_v = cfg.head_dim_v as usize;
626 assert!(
627 head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
628 "KVQUANT requires head_dim%32==0 (MTP scratch)"
629 );
630 let kv_dim_k = head_dim_k * n_head_kv;
631 let kv_dim_v = head_dim_v * n_head_kv;
632 // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
633 // policy shared with `MtpScratch::new` so admission scales the same allocation.
634 let (kbb, vbb) = crate::kv_blk_bytes();
635 let k_tok_bytes = (kv_dim_k / 32) * kbb;
636 let v_tok_bytes = (kv_dim_v / 32) * vbb;
637 (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
638}
639
640impl MtpScratch {
641 fn new(
642 e: &Engine,
643 cfg: &memra_gguf::config::ModelConfig,
644 cap: usize,
645 geom: Option<&crate::hybrid::DraftGeom>,
646 ) -> Result<Self, Box<dyn std::error::Error>> {
647 // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
648 // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
649 // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
650 // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
651 let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) =
652 mtp_scratch_layout(cfg, geom);
653 Ok(MtpScratch {
654 kv: KvLayer {
655 k: e.alloc_u8(cap * k_tok_bytes)?,
656 v: e.alloc_u8(cap * v_tok_bytes)?,
657 kv_dim_k,
658 kv_dim_v,
659 k_tok_bytes,
660 v_tok_bytes,
661 len: 0,
662 len_d: e.htod_i32(&[0])?,
663 },
664 cap,
665 })
666 }
667 /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
668 /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
669 /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
670 fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
671 self.kv.len = n;
672 e.set_i32_one(&mut self.kv.len_d, n as i32)
673 }
674}
675
676/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
677/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
678/// full weight reads per round — recomputing columns the verify had already produced
679/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
680/// to "after the first j verify columns" WITHOUT re-running the trunk:
681/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
682/// consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
683/// to the first j iterations of the verify's scan — the kernel's t-loop carries state in
684/// registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
685/// pure-copy ring rebuild.
686/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
687/// column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
688/// target: j <= t-1).
689/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
690/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
691struct GdnStash {
692 qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
693 q_l2: CudaSlice<f32>,
694 k_l2: CudaSlice<f32>,
695 v_g: CudaSlice<f32>, // [t, num_v, d_state]
696 g_log: CudaSlice<f32>,
697 beta: CudaSlice<f32>, // [t, num_v]
698}
699struct VerifyCkpt {
700 gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
701 cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
702}
703impl VerifyCkpt {
704 fn new(n_layer: usize) -> Self {
705 VerifyCkpt {
706 gdn: (0..n_layer).map(|_| None).collect(),
707 cols: (0..n_layer).map(|_| None).collect(),
708 }
709 }
710}
711
712impl HybridModel {
713 /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
714 /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
715 /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
716 /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
717 /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
718 /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
719 /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
720 /// transfer + host argmax per draft token from the K-token draft chain.
721 #[allow(clippy::too_many_arguments)]
722 fn mtp_head_forward_dev(
723 &self,
724 e: &Engine,
725 mtp: &MtpHead,
726 e_tok: u32,
727 h_seed: &CudaSlice<f32>,
728 scratch: &mut MtpScratch,
729 mtp_pos: usize,
730 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
731 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
732 // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
733 // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
734 mask: Option<(&CudaSlice<u32>, usize)>,
735 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
736 let cfg = &self.cfg;
737 let n_embd = cfg.n_embd as usize;
738 // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
739 // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
740 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
741 let eps = cfg.rms_eps;
742 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
743
744 // op A: a resident table transfers one 4B token id. The exact host-row capacity path
745 // expands this one row on CPU and transfers n_embd f32 values instead.
746 let e_emb = match embd_dev {
747 Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
748 None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
749 };
750
751 // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
752 let mut e_norm = e.zeros(n_embd)?;
753 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
754 let mut h_norm = e.zeros(n_embd)?;
755 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
756
757 // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
758 let mut concat = e.zeros(2 * n_embd)?;
759 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
760 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
761
762 // op 4: inpSA = eh_proj @ concat (eh_proj [2*n_embd, n_embd]) -> [n_embd]
763 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
764
765 // op 5: a_norm = RMSNorm(inpSA, attn_norm)
766 let mut a_norm = e.zeros(di)?;
767 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
768
769 // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
770 // scratch.cap, length from the device len_d) so eager drafts match graph drafts
771 // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
772 // advances only the device counter).
773 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
774 // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
775 // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
776 // Advances BOTH the host len and the device counter itself (unlike the dc arm,
777 // whose host-side mirror the caller does).
778 (Mixer::Full(fa), Some(g)) => self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?,
779 (Mixer::Full(fa), None) => {
780 let out =
781 self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
782 scratch.kv.len += 1;
783 out
784 }
785 (Mixer::Linear(_), _) => {
786 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
787 }
788 (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
789 };
790
791 // op 7: x1 = inpSA + attn_out
792 let mut x1 = e.zeros(di)?;
793 e.add(&inp_sa, &attn_out, &mut x1, di)?;
794
795 // op 8: z = RMSNorm(x1, post_attn_norm) (pre-FFN norm)
796 let mut z = e.zeros(di)?;
797 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
798
799 // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
800 let ffn_out = match &mtp.ffn {
801 crate::hybrid::Ffn::Dense {
802 ffn_gate,
803 ffn_up,
804 ffn_down,
805 } => {
806 let n_ff = ffn_gate.out_features();
807 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
808 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
809 (
810 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
811 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
812 )
813 } else {
814 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
815 };
816 let mut act = e.zeros(n_ff)?;
817 // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
818 // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
819 // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
820 // passes None, which is `ffn_act`'s dispatch verbatim.
821 Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
822 mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
823 &mut act, n_ff)?;
824 e.matmul(ffn_down, &act, 1)?
825 }
826 // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
827 // so they never alias trunk layer 0's cache keys.
828 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
829 };
830
831 // op 10: h_nextn = x1 + ffn_out (at di)
832 let mut h_inner = e.zeros(di)?;
833 e.add(&x1, &ffn_out, &mut h_inner, di)?;
834
835 // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
836 // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
837 let h_nextn = match mtp.geom.as_ref() {
838 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
839 None => h_inner,
840 };
841
842 // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
843 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
844 let mut final_h = e.zeros(n_embd)?;
845 e.rms_norm(
846 &h_nextn,
847 final_norm.float_data(),
848 &mut final_h,
849 n_embd,
850 1,
851 eps,
852 )?;
853
854 // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
855 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
856 let mut logits = e.matmul(head, &final_h, 1)?;
857 // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
858 // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
859 if let Some((mask_d, mw)) = mask {
860 let d_vocab = head.out_features();
861 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
862 }
863 // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
864 // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
865 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
866 }
867
868 /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
869 /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
870 /// the dc path, and all three are properties of this arch's MTP block:
871 ///
872 /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
873 /// window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
874 /// cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
875 /// mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
876 /// windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
877 /// starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
878 /// new kernel. That is deliberately not built here: see the CUDA-graph note below.
879 /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
880 /// on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
881 /// trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
882 /// resolved `Step35MtpGeom`, never from `cfg`.
883 /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
884 /// sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
885 /// fused-into-wq `q_gate_split` form the dc arm handles.
886 ///
887 /// WHY EAGER-ONLY IS NOT A GAP TODAY: `graph_draft` requires `trunk_dense`, and this SKU's
888 /// trunk is a 288-expert MoE, so the graph draft is already off for every step35 model — the
889 /// eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
890 /// than silently capturing a window-less (wrong past `win` draft rows) graph.
891 ///
892 /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
893 /// caller must not mirror.
894 fn mtp_step35_attn(
895 &self,
896 e: &Engine,
897 fa: &FullAttnLayer,
898 g: &crate::hybrid::Step35MtpGeom,
899 h: &CudaSlice<f32>,
900 pos_d: &CudaSlice<i32>,
901 scratch: &mut MtpScratch,
902 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
903 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
904 let eps = self.cfg.rms_eps;
905 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
906 let n_embd = self.cfg.n_embd as usize;
907 let gw = fa.attn_gate.as_ref()
908 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
909
910 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk)
911 && e.uses_q8_1_fast(&fa.wv) && e.uses_q8_1_fast(gw)
912 {
913 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
914 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
915 Some(t3) => t3,
916 None => (e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
917 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
918 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?),
919 };
920 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
921 } else {
922 (e.matmul(&fa.wq, h, 1)?, e.matmul(&fa.wk, h, 1)?,
923 e.matmul(&fa.wv, h, 1)?, e.matmul(gw, h, 1)?)
924 };
925
926 let mut q = e.uninit(nh * hd)?;
927 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
928 let mut k = e.uninit(nkv * hd)?;
929 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
930 // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
931 // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
932 // the resolved flag, not the constant, so an all-full sibling stays correct.
933 let ff = if g.swa { None } else {
934 self.step35_aux.as_ref().and_then(|a| a.rope_freqs.as_ref())
935 };
936 e.rope_neox2(&mut q, &mut k, pos_d, hd, g.n_rot, nh, nkv, 1, g.rope_base, 1.0, ff)?;
937
938 // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
939 // length on the host anyway, and the windowed view below needs it there to compute the
940 // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
941 // dc-family consumer of this scratch still agree.
942 let kv = &mut scratch.kv;
943 assert!(kv.len < scratch.cap, "step35 MTP scratch overflow ({} >= {})", kv.len, scratch.cap);
944 e.append_kv_quantized(&k, &v0, &mut kv.k, &mut kv.v, kv.len,
945 kv.kv_dim_k, kv.kv_dim_v, kv.k_tok_bytes, kv.v_tok_bytes, false)?;
946 kv.len += 1;
947 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
948 // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
949 // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
950 // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
951 // therefore live, not theoretical.
952 let (off, t_kv) = if g.swa && kv.len > g.window {
953 (kv.len - g.window, g.window)
954 } else {
955 (0, kv.len)
956 };
957 let k_view = e.view_u8_range(&kv.k, off * kv.k_tok_bytes, (off + t_kv) * kv.k_tok_bytes);
958 let v_view = e.view_u8_range(&kv.v, off * kv.v_tok_bytes, (off + t_kv) * kv.v_tok_bytes);
959 let mut attn = e.uninit(nh * hd)?;
960 e.fa_decode_kvmod(&q, &k_view, &v_view, &mut attn, hd, nh, nkv, t_kv, scale,
961 kv.k_tok_bytes, kv.v_tok_bytes, false)?;
962
963 let mut ag = e.uninit(nh * hd)?;
964 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
965 Ok(e.matmul(&fa.wo, &ag, 1)?)
966 }
967
968 /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
969 /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
970 /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
971 /// chain, and replays keep seeing KV growth through the device counter (no recapture).
972 /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
973 /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
974 /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
975 /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
976 /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
977 fn mtp_full_attn_dc(
978 &self,
979 e: &Engine,
980 fa: &FullAttnLayer,
981 h: &CudaSlice<f32>,
982 pos_d: &CudaSlice<i32>,
983 scratch: &mut MtpScratch,
984 geom: Option<&crate::hybrid::DraftGeom>,
985 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
986 let cfg = &self.cfg;
987 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
988 let geometry = cfg.full_attention_geometry_at(mtp_il);
989 let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
990 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(geometry.n_head_kv as usize);
991 let head_dim = geometry.head_dim_k as usize;
992 let eps = cfg.rms_eps;
993 let scale = geometry.attention_scale();
994 let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
995 let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
996
997 let (qf, mut k, v) =
998 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
999 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
1000 (
1001 e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
1002 e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
1003 e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
1004 )
1005 } else {
1006 (
1007 e.matmul(&fa.wq, h, 1)?,
1008 e.matmul(&fa.wk, h, 1)?,
1009 e.matmul(&fa.wv, h, 1)?,
1010 )
1011 };
1012 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
1013 let gated = geometry.attention_gate
1014 == memra_gguf::config::AttentionGateKind::FusedQ;
1015 let (mut q, gate) = if gated {
1016 let mut q = e.zeros(n_head * head_dim)?;
1017 let mut gate = e.zeros(n_head * head_dim)?;
1018 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
1019 (q, Some(gate))
1020 } else {
1021 (qf, None)
1022 };
1023
1024 let mut qn = e.zeros(n_head * head_dim)?;
1025 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
1026 q = qn;
1027 let mut kn = e.zeros(n_head_kv * head_dim)?;
1028 e.rms_norm(
1029 &k,
1030 fa.k_norm.float_data(),
1031 &mut kn,
1032 head_dim,
1033 n_head_kv,
1034 eps,
1035 )?;
1036 k = kn;
1037 let rope_dims = geometry.n_rot as usize;
1038 e.rope_neox(
1039 &mut q,
1040 pos_d,
1041 head_dim,
1042 rope_dims,
1043 n_head,
1044 1,
1045 geometry.rope_base,
1046 1.0,
1047 )?;
1048 e.rope_neox(
1049 &mut k,
1050 pos_d,
1051 head_dim,
1052 rope_dims,
1053 n_head_kv,
1054 1,
1055 geometry.rope_base,
1056 1.0,
1057 )?;
1058
1059 let kv = &mut scratch.kv;
1060 // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
1061 e.append_kv_quantized_dc(
1062 &k,
1063 &v,
1064 &mut kv.k,
1065 &mut kv.v,
1066 &kv.len_d,
1067 kv.kv_dim_k,
1068 kv.kv_dim_v,
1069 kv.k_tok_bytes,
1070 kv.v_tok_bytes,
1071 false,
1072 )?;
1073 e.inc_seqlen(&mut kv.len_d)?;
1074 // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
1075 // key range from the device counter.
1076 let k_view = e.view_u8(&kv.k, kv.k.len());
1077 let v_view = e.view_u8(&kv.v, kv.v.len());
1078 let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
1079 let mut attn = e.zeros(n_head * head_dim)?;
1080 e.fa_decode_dc(
1081 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
1082 scale, ktb, vtb, false,
1083 )?;
1084
1085 let attn_g = match &gate {
1086 Some(gate) => {
1087 let mut gsig = e.zeros(n_head * head_dim)?;
1088 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
1089 let mut ag = e.zeros(n_head * head_dim)?;
1090 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
1091 ag
1092 }
1093 None => attn,
1094 };
1095 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
1096 }
1097
1098 /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
1099 /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
1100 /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
1101 /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
1102 /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
1103 /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
1104 /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
1105 /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
1106 #[allow(clippy::too_many_arguments)]
1107 fn mtp_kv_fill(
1108 &self,
1109 e: &Engine,
1110 mtp: &MtpHead,
1111 tokens: &[u32],
1112 h: &CudaSlice<f32>,
1113 pos0: usize,
1114 scratch: &mut MtpScratch,
1115 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1116 ) -> Result<(), Box<dyn std::error::Error>> {
1117 let cfg = &self.cfg;
1118 let n_embd = cfg.n_embd as usize;
1119 let eps = cfg.rms_eps;
1120 let t = tokens.len();
1121 assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
1122 assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
1123 let Mixer::Full(fa) = &mtp.mixer else {
1124 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
1125 };
1126 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
1127 let pos_d = e.htod_i32(&pos_vec)?;
1128
1129 // ops A/1/2: embed + the two input norms, T-wide.
1130 let e_emb = match embd_dev {
1131 Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
1132 None => e.htod(&self.embd.gather(n_embd, tokens))?,
1133 };
1134 let mut e_norm = e.zeros(t * n_embd)?;
1135 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
1136 let mut h_norm = e.zeros(t * n_embd)?;
1137 e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
1138
1139 // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
1140 let mut concat = e.zeros(t * 2 * n_embd)?;
1141 for i in 0..t {
1142 e.copy_view_into(
1143 &mut concat,
1144 i * 2 * n_embd,
1145 &e_norm.slice(i * n_embd..(i + 1) * n_embd),
1146 n_embd,
1147 )?;
1148 e.copy_view_into(
1149 &mut concat,
1150 i * 2 * n_embd + n_embd,
1151 &h_norm.slice(i * n_embd..(i + 1) * n_embd),
1152 n_embd,
1153 )?;
1154 }
1155
1156 // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
1157 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
1158 let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
1159 let mut a_norm = e.zeros(t * di)?;
1160 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
1161
1162 // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
1163 // the fill only has to leave correct K/V rows behind for later chains to attend over.
1164 let n_head_kv = mtp
1165 .geom
1166 .as_ref()
1167 .map(|g| g.n_head_kv)
1168 .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
1169 .unwrap_or_else(|| {
1170 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
1171 cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
1172 });
1173 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
1174 let geometry = cfg.full_attention_geometry_at(mtp_il);
1175 let head_dim = geometry.head_dim_k as usize;
1176 let mut k = e.matmul(&fa.wk, &a_norm, t)?;
1177 let v = e.matmul(&fa.wv, &a_norm, t)?;
1178 let mut kn = e.zeros(t * n_head_kv * head_dim)?;
1179 e.rms_norm(
1180 &k,
1181 fa.k_norm.float_data(),
1182 &mut kn,
1183 head_dim,
1184 n_head_kv * t,
1185 eps,
1186 )?;
1187 k = kn;
1188 // step35: rotary width AND base are per-layer, and the MTP block's values come from the
1189 // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
1190 // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
1191 // writes K rows the attention arm then re-derives at a different theta: correct-looking
1192 // output with dead acceptance, invisible to the exactness gates.
1193 let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
1194 Some(s) => (
1195 s.n_rot,
1196 s.rope_base,
1197 if s.swa { None } else {
1198 self.step35_aux.as_ref().and_then(|a| a.rope_freqs.as_ref())
1199 },
1200 ),
1201 None => (geometry.n_rot as usize, geometry.rope_base, None),
1202 };
1203 match ff {
1204 Some(f) => e.rope_neox_ff(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, t,
1205 rope_base, 1.0, f)?,
1206 None => e.rope_neox(&mut k, &pos_d, head_dim, rope_dims, n_head_kv, t,
1207 rope_base, 1.0)?,
1208 }
1209
1210 let kv = &mut scratch.kv;
1211 for i in 0..t {
1212 let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
1213 let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
1214 e.append_kv_quantized_view(
1215 &k_row,
1216 &v_row,
1217 &mut kv.k,
1218 &mut kv.v,
1219 kv.len + i,
1220 kv.kv_dim_k,
1221 kv.kv_dim_v,
1222 kv.k_tok_bytes,
1223 kv.v_tok_bytes,
1224 false,
1225 )?;
1226 }
1227 kv.len += t;
1228 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
1229 Ok(())
1230 }
1231
1232 /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
1233 /// every varying input device-resident —
1234 /// - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
1235 /// so the chain feeds itself; the host reads the same 4 bytes for the draft list),
1236 /// - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
1237 /// - rope pos from the persistent `pos_d` counter (inc'd in-graph),
1238 /// - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
1239 /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
1240 /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
1241 /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
1242 /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
1243 /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
1244 /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
1245 /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
1246 /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
1247 /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
1248 /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
1249 /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
1250 /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
1251 /// seed/temp are capture-time constants (fixed per generate call, like p_min).
1252 #[allow(clippy::too_many_arguments)]
1253 fn mtp_head_forward_cap(
1254 &self,
1255 e: &Engine,
1256 mtp: &MtpHead,
1257 tok_d: &mut CudaSlice<u32>,
1258 pos_d: &mut CudaSlice<i32>,
1259 h_seed_d: &mut CudaSlice<f32>,
1260 p_d: &mut CudaSlice<f32>,
1261 scratch: &mut MtpScratch,
1262 with_prob: bool,
1263 with_head: bool,
1264 embd_gpu: &CudaSlice<u8>,
1265 embd_qt: i32,
1266 embd_rb: usize,
1267 d_vocab: usize,
1268 sampled_cap: Option<(
1269 &mut CudaSlice<u32>,
1270 &mut CudaSlice<f32>,
1271 &mut CudaSlice<f32>,
1272 u64,
1273 f32,
1274 )>,
1275 stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
1276 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
1277 // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
1278 // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
1279 // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
1280 // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
1281 mask_cap: Option<(&CudaSlice<u32>, usize)>,
1282 ) -> Result<(), Box<dyn std::error::Error>> {
1283 let cfg = &self.cfg;
1284 let n_embd = cfg.n_embd as usize;
1285 // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
1286 // whose device-counter key bound always starts at row 0 — it cannot express this block's
1287 // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
1288 // persistent scratch passes 512 rows. Nothing is lost today: `graph_draft` also requires
1289 // `trunk_dense`, and step35's trunk is a 288-expert MoE, so the eager chain
1290 // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
1291 // panic) is what the two capture sites and the round-stream capture already handle by
1292 // degrading to eager / stream-off.
1293 if mtp.step35.is_some() {
1294 return Err("step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
1295 block's SWA view offset; same root cause as the dc decode refusal) — the \
1296 eager draft chain serves this arch".into());
1297 }
1298 // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
1299 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
1300 let eps = cfg.rms_eps;
1301 let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
1302 let mut e_norm = e.zeros(n_embd)?;
1303 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
1304 let mut h_norm = e.zeros(n_embd)?;
1305 e.rms_norm(
1306 &*h_seed_d,
1307 mtp.hnorm.float_data(),
1308 &mut h_norm,
1309 n_embd,
1310 1,
1311 eps,
1312 )?;
1313 let mut concat = e.zeros(2 * n_embd)?;
1314 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
1315 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
1316 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
1317 let mut a_norm = e.zeros(di)?;
1318 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
1319 let attn_out = match &mtp.mixer {
1320 Mixer::Full(fa) => {
1321 self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
1322 }
1323 Mixer::Linear(_) => {
1324 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
1325 }
1326 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1327 };
1328 let mut x1 = e.zeros(di)?;
1329 e.add(&inp_sa, &attn_out, &mut x1, di)?;
1330 let mut z = e.zeros(di)?;
1331 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
1332 let ffn_out = match &mtp.ffn {
1333 crate::hybrid::Ffn::Dense {
1334 ffn_gate,
1335 ffn_up,
1336 ffn_down,
1337 } => {
1338 let n_ff = ffn_gate.out_features();
1339 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
1340 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
1341 (
1342 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
1343 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
1344 )
1345 } else {
1346 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
1347 };
1348 let mut act = e.zeros(n_ff)?;
1349 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
1350 e.matmul(ffn_down, &act, 1)?
1351 }
1352 // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
1353 // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
1354 // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
1355 // error arm degrades the caller to eager/stream-off.
1356 crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
1357 self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
1358 }
1359 crate::hybrid::Ffn::Moe(_) => {
1360 return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into())
1361 }
1362 };
1363 let mut h_inner = e.zeros(di)?;
1364 e.add(&x1, &ffn_out, &mut h_inner, di)?;
1365 // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
1366 let h_nextn = match mtp.geom.as_ref() {
1367 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
1368 None => h_inner,
1369 };
1370 // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
1371 let final_h = if with_head || spec_hpost() {
1372 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
1373 let mut fh = e.zeros(n_embd)?;
1374 e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
1375 Some(fh)
1376 } else {
1377 None
1378 };
1379 if with_head {
1380 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
1381 let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
1382 // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
1383 // before the argmax — proposals become legal by construction. Contents-only
1384 // per-replay upload keeps the capture valid.
1385 if let Some((mask_d, mw)) = mask_cap {
1386 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
1387 }
1388 if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
1389 // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
1390 // own buffer is pool-recycled after the capture body returns, so it can't be the
1391 // retention target), bump the device event counter, gumbel-perturb reading it,
1392 // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
1393 e.copy_into(q_out_d, 0, &logits, d_vocab)?;
1394 e.sctr_inc(ctr_d)?;
1395 e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
1396 e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
1397 // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
1398 // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
1399 if with_prob {
1400 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
1401 }
1402 } else {
1403 // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
1404 e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
1405 // p-min under a draft mask reads the MASKED row: confidence relative to the
1406 // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
1407 // is the right semantics for "does the drafter know what comes next here" and
1408 // the same row the pick came from. Draft-quality only — verify arbitrates.
1409 if with_prob {
1410 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
1411 }
1412 }
1413 }
1414 // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
1415 // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
1416 if let Some((out, slot, d2t)) = stream_pack {
1417 e.pack_tok_p(tok_d, p_d, out, slot)?;
1418 if let Some(map) = d2t {
1419 e.tok_map_u32(tok_d, map)?;
1420 }
1421 }
1422 // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
1423 if spec_hpost() {
1424 e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
1425 } else {
1426 e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
1427 }
1428 // advance the draft rope position in-graph.
1429 e.inc_seqlen(pos_d)?;
1430 Ok(())
1431 }
1432
1433 /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
1434 /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
1435 /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
1436 /// Advances `cache.pos` by T.
1437 pub fn decode_step_t(&self, e: &Engine, tokens: &[u32], pos0: usize, cache: &mut Cache)
1438 -> Result<Vec<f32>, Box<dyn std::error::Error>> {
1439 if self.is_gemma4_e4b() {
1440 return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
1441 }
1442 if self.cfg.gemma4.is_some() {
1443 return self.gemma4_decode_step_t(e, tokens, pos0, cache);
1444 }
1445 Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
1446 }
1447
1448 /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
1449 /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
1450 /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
1451 /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
1452 pub fn decode_step_t_h(
1453 &self,
1454 e: &Engine,
1455 tokens: &[u32],
1456 pos0: usize,
1457 cache: &mut Cache,
1458 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1459 self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
1460 }
1461
1462 /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
1463 /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
1464 pub fn decode_step_t_h_emb(
1465 &self,
1466 e: &Engine,
1467 tokens: &[u32],
1468 pos0: usize,
1469 cache: &mut Cache,
1470 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1471 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1472 let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
1473 Ok((e.dtoh(&logits_d)?, h_seed))
1474 }
1475
1476 /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
1477 /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
1478 /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
1479 /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
1480 /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
1481 pub fn decode_step_t_h_emb_dev(
1482 &self,
1483 e: &Engine,
1484 tokens: &[u32],
1485 pos0: usize,
1486 cache: &mut Cache,
1487 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1488 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1489 let n_embd = self.cfg.n_embd as usize;
1490 let t = tokens.len();
1491 let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
1492 // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
1493 let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
1494 e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
1495 Ok((logits, hs))
1496 }
1497
1498 /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
1499 /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
1500 /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
1501 /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
1502 /// retains/copies — they never change what any kernel computes).
1503 fn decode_step_t_core(
1504 &self,
1505 e: &Engine,
1506 tokens: &[u32],
1507 pos0: usize,
1508 cache: &mut Cache,
1509 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1510 mut ckpt: Option<&mut VerifyCkpt>,
1511 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1512 self.decode_step_t_core_stream(e, tokens, pos0, cache, embd_dev, ckpt.take(), None)
1513 }
1514
1515 /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
1516 /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
1517 /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
1518 /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
1519 /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
1520 #[allow(clippy::too_many_arguments)]
1521 fn decode_step_t_core_stream(
1522 &self,
1523 e: &Engine,
1524 tokens: &[u32],
1525 pos0: usize,
1526 cache: &mut Cache,
1527 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1528 mut ckpt: Option<&mut VerifyCkpt>,
1529 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
1530 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1531 // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
1532 // exactly as the eager and batched steps do. This is the single funnel every verify
1533 // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
1534 // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
1535 // is untouched.
1536 //
1537 // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
1538 // walk was unsplit on one stream and a sharded cross-device placement peer-read every
1539 // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
1540 // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
1541 // or a placement whose PpNRt fails to build — so a config that would still walk the
1542 // whole trunk on one stream refuses instead of regressing 28x.
1543 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
1544 if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
1545 return self.decode_step_t_core_ppn(
1546 e, tokens, pos0, cache, embd_dev, ckpt.take(), stream, &fence,
1547 );
1548 }
1549 }
1550 crate::pp::refuse_unsplit_if_remote(
1551 "decode_step_t (spec verify)",
1552 "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
1553 split (decode_step_t_core_ppn); or run spec on one device",
1554 )?;
1555 let cfg = &self.cfg;
1556 let n_embd = cfg.n_embd as usize;
1557 let eps = cfg.rms_eps;
1558 let t = tokens.len();
1559 let pos_d = match stream {
1560 Some((_, ctr)) => {
1561 let mut p = e.alloc_uninit::<i32>(t)?;
1562 e.pos_iota(ctr, &mut p, t)?;
1563 p
1564 }
1565 None => {
1566 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
1567 e.htod_i32(&pos_vec)?
1568 }
1569 };
1570
1571 // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
1572 let x = match (stream, embd_dev) {
1573 (Some((vtok, _)), Some((g, qt, rb))) => {
1574 e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
1575 }
1576 (None, Some((g, qt, rb))) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
1577 _ => e.htod(&self.embd.gather(n_embd, tokens))?,
1578 };
1579
1580 // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
1581 // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
1582 // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
1583 let x = self.verify_layers(
1584 e, x, 0, self.layers.len(), &pos_d, t, cache, ckpt.take(), stream,
1585 )?;
1586
1587 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
1588 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1589 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
1590 // stream: the device pos counter owns position; host mirror reconciles at drain.
1591 if stream.is_none() {
1592 cache.pos += t;
1593 }
1594 // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
1595 Ok((logits, if spec_hpost() { hn } else { x }))
1596 }
1597
1598 /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
1599 /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
1600 /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
1601 /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
1602 /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
1603 /// the payload).
1604 ///
1605 /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
1606 /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
1607 /// receipts):
1608 ///
1609 /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
1610 /// (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
1611 /// DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
1612 /// (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
1613 /// s>0 its own Engine even on the primary device; honouring it here is what scopes the
1614 /// pools. The verify path allocates MORE of that scratch than eager decode does (FA at
1615 /// m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
1616 ///
1617 /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
1618 /// buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
1619 /// stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
1620 /// read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
1621 /// stage derives the identical iota, and each stage's own output buffer is stream-local.
1622 ///
1623 /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
1624 /// sharded loader leaves the table with stage 0 by construction).
1625 ///
1626 /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
1627 /// both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
1628 /// n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
1629 /// model, every round.
1630 ///
1631 /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
1632 /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
1633 /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
1634 /// through the primary context by UVA — the same read the batched serving epilogue's
1635 /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
1636 /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
1637 ///
1638 /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
1639 /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
1640 /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
1641 ///
1642 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
1643 /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
1644 /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
1645 /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
1646 /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
1647 /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
1648 /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
1649 /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
1650 #[allow(clippy::too_many_arguments)]
1651 fn decode_step_t_core_ppn(
1652 &self,
1653 e: &Engine,
1654 tokens: &[u32],
1655 pos0: usize,
1656 cache: &mut Cache,
1657 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
1658 mut ckpt: Option<&mut VerifyCkpt>,
1659 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
1660 fence: &[usize],
1661 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1662 assert!(
1663 !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
1664 "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
1665 (the gemma4 arms have their own decode_step_t twins)"
1666 );
1667 let rt = crate::pp::PpNRt::get(e)?;
1668 let n_st = fence.len() - 1;
1669 assert_eq!(
1670 rt.n_stages(), n_st,
1671 "PpNRt stage count {} != fence stages {n_st}", rt.n_stages()
1672 );
1673 let n_embd = self.cfg.n_embd as usize;
1674 let eps = self.cfg.rms_eps;
1675 let t = tokens.len();
1676 let payload = t * n_embd;
1677 // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
1678 // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
1679 // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
1680 // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
1681 // stage stream and the wait would self-order into a no-op.
1682 let caller_stream = e.stream();
1683 // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
1684 // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
1685 // the primary stream still holds queued reads of them — with event tracking elided,
1686 // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
1687 // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
1688 // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
1689 // stage stream behind the caller before enqueueing new stage work.
1690 rt.fence_stages_behind(&caller_stream)?;
1691
1692 // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
1693 // stream mode each stage's own `pos_iota` over the shared read-only device counter.
1694 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
1695 match stream {
1696 Some((_, ctr)) => {
1697 let mut p = es.alloc_uninit::<i32>(t)?;
1698 es.pos_iota(ctr, &mut p, t)?;
1699 Ok(p)
1700 }
1701 None => {
1702 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
1703 es.htod_i32(&pos_vec)
1704 }
1705 }
1706 };
1707
1708 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
1709 let mut slot = {
1710 let _st0 = rt.enter(0);
1711 let e0 = rt.engine(0, e);
1712 let pos_d = stage_pos(e0)?;
1713 let x = match (stream, embd_dev) {
1714 (Some((vtok, _)), Some((g, qt, rb))) => {
1715 e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
1716 }
1717 (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
1718 _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
1719 };
1720 let x = self.verify_layers(
1721 e0, x, fence[0], fence[1], &pos_d, t, cache, ckpt.as_deref_mut(), stream,
1722 )?;
1723 rt.tx(0, &x, payload)?
1724 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
1725 };
1726
1727 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
1728 for s in 1..n_st - 1 {
1729 let _st = rt.enter(s);
1730 let es = rt.engine(s, e);
1731 let pos_d = stage_pos(es)?;
1732 let x = rt.rx(s - 1, slot, payload)?;
1733 let x = self.verify_layers(
1734 es, x, fence[s], fence[s + 1], &pos_d, t, cache, ckpt.as_deref_mut(), stream,
1735 )?;
1736 slot = rt.tx(s, &x, payload)?;
1737 }
1738
1739 // ---- LAST STAGE: RX + final range + output_norm + lm head ----
1740 let _stl = rt.enter(n_st - 1);
1741 let el = rt.engine(n_st - 1, e);
1742 let pos_d = stage_pos(el)?;
1743 let x = rt.rx(n_st - 2, slot, payload)?;
1744 let x = self.verify_layers(
1745 el, x, fence[n_st - 1], fence[n_st], &pos_d, t, cache, ckpt.as_deref_mut(), stream,
1746 )?;
1747
1748 let mut hn = vbuf(el, payload)?; // fully written by rms_norm_decode
1749 el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
1750 let logits = el.matmul_decode_exact(&self.output, &hn, t)?;
1751 // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
1752 // stream. Order the caller's stream behind that work before the buffers escape this
1753 // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
1754 // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
1755 // the following arm's KV in the same process).
1756 rt.publish_to(n_st - 1, &caller_stream)?;
1757 // stream: the device pos counter owns position; host mirror reconciles at drain.
1758 if stream.is_none() {
1759 cache.pos += t;
1760 }
1761 Ok((logits, if spec_hpost() { hn } else { x }))
1762 }
1763
1764 /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
1765 /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
1766 /// carried in from outside the range) and exits with the range's final residual materialized
1767 /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
1768 /// instead of one.
1769 ///
1770 /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
1771 /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
1772 /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
1773 /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
1774 /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
1775 /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
1776 /// code — there is no "split version" of the verify math.
1777 ///
1778 /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
1779 /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
1780 /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
1781 /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
1782 #[allow(clippy::too_many_arguments)]
1783 fn verify_layers(
1784 &self,
1785 e: &Engine,
1786 mut x: CudaSlice<f32>,
1787 lo: usize,
1788 hi: usize,
1789 pos_d: &CudaSlice<i32>,
1790 t: usize,
1791 cache: &mut Cache,
1792 mut ckpt: Option<&mut VerifyCkpt>,
1793 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
1794 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1795 let n_embd = self.cfg.n_embd as usize;
1796 let eps = self.cfg.rms_eps;
1797 // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
1798 // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
1799 // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
1800 // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
1801 // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
1802 // residual the next layer needs) as its `res` output. Falls back to the separate add
1803 // when the next layer is off the fused-q8 path.
1804 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
1805 for il in lo..hi {
1806 let layer = &self.layers[il];
1807 // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
1808 // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
1809 // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
1810 // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
1811 // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
1812 // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
1813 // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
1814 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
1815 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
1816 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
1817 // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
1818 // projections only; Linear mixer: the batched arm — the per-column fallback needs
1819 // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
1820 // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
1821 // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
1822 // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
1823 // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
1824 // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
1825 // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
1826 // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
1827 let lin_q8_only = match &layer.mixer {
1828 Mixer::Linear(la) => {
1829 (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
1830 }
1831 Mixer::Full(_) if self.cfg.step35.is_some() => false,
1832 _ => true,
1833 };
1834 // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
1835 // a non-fused layer still performs the residual add.
1836 let taken = pending.take();
1837 let (h, h_q8) = if norm_fused && lin_q8_only {
1838 let pair = match taken {
1839 // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
1840 // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
1841 Some((x1p, f1p)) => {
1842 let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
1843 let p = e.add_rms_norm_q8_1(
1844 &x1p, &f1p, layer.attn_norm.float_data(), &mut x2, n_embd, t, eps,
1845 )?;
1846 x = x2;
1847 p
1848 }
1849 None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
1850 };
1851 (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
1852 } else {
1853 if let Some((x1p, f1p)) = taken {
1854 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
1855 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
1856 x = x2;
1857 }
1858 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
1859 if norm_fused {
1860 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
1861 } else {
1862 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
1863 }
1864 (h, None)
1865 };
1866 let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
1867
1868 let mixed = match &layer.mixer {
1869 Mixer::Full(fa) => {
1870 self.full_attn_verify(e, fa, &h, h_q8_ref, pos_d, t, cache, il,
1871 stream.map(|(_, c)| c))?
1872 }
1873 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
1874 Mixer::Linear(la) => {
1875 // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
1876 // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
1877 // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
1878 // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
1879 // chained T=1 steps (bit-identical). Falls back to the sequential per-column
1880 // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
1881 // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
1882 // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
1883 // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
1884 // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
1885 // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
1886 if (t >= 3 || (t == 2 && spec_m2()))
1887 && mixer_fast
1888 && e.uses_q8_1_fast(&la.ssm_out)
1889 {
1890 let want = ckpt.is_some();
1891 let (out, stash) =
1892 self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
1893 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
1894 ck.gdn[il] = Some(st);
1895 }
1896 out
1897 } else {
1898 let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
1899 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
1900 if ckpt.is_some() && t >= 2 {
1901 Some(Vec::with_capacity(t - 1))
1902 } else {
1903 None
1904 };
1905 for col in 0..t {
1906 let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
1907 let src = h.slice(col * n_embd..(col + 1) * n_embd);
1908 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
1909 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
1910 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
1911 // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
1912 // (pure dtod — cannot change any computed value). Last column skipped:
1913 // rebuild targets are j <= t-1 columns.
1914 if let Some(cs) = col_states.as_mut() {
1915 if col + 1 < t {
1916 let rl = cache.recur[il].as_ref().unwrap();
1917 cs.push((
1918 e.clone_dtod(&rl.conv_state)?,
1919 e.clone_dtod(&rl.ssm_state)?,
1920 ));
1921 }
1922 }
1923 }
1924 if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
1925 // ReplaySSM-assessment instrumentation (2026-07-30): the
1926 // per-column clones are the only true state snapshots left in
1927 // the verify (the batched path stashes INPUTS and replays).
1928 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
1929 static ONCE: std::sync::Once = std::sync::Once::new();
1930 let bytes: usize = cs.iter()
1931 .map(|(c, s)| (c.len() + s.len()) * 4).sum();
1932 ONCE.call_once(|| eprintln!(
1933 "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
1934 cs.len(), bytes as f64 / 1e6));
1935 }
1936 ck.cols[il] = Some(cs);
1937 }
1938 out
1939 }
1940 }
1941 };
1942
1943 // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
1944 // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
1945 // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
1946 let ffn_fuse = match &layer.ffn {
1947 crate::hybrid::Ffn::Dense {
1948 ffn_gate, ffn_up, ..
1949 } => {
1950 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
1951 && e.uses_q8_1_fast(ffn_gate)
1952 && e.uses_q8_1_fast(ffn_up)
1953 }
1954 crate::hybrid::Ffn::Moe(_) => false,
1955 };
1956 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
1957 // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
1958 // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
1959 // per-row m=1 program; kernel-check pins bit-identity vs the unfused
1960 // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
1961 // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
1962 // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
1963 // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
1964 // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
1965 // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
1966 // mirror decode's dispatch or spec self-consistency fails.
1967 let dense_lim = self.cfg.clamp_shexp_at(il as u32);
1968 let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
1969 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
1970 let mut z = e.zeros(0)?; // replaced below on the unfused arms
1971 let z_q8 = if fuse_q8 {
1972 Some(e.add_rms_norm_q8_1(
1973 &x,
1974 &mixed,
1975 layer.post_attn_norm.float_data(),
1976 &mut x1,
1977 n_embd,
1978 t,
1979 eps,
1980 )?)
1981 } else {
1982 let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
1983 if ffn_fuse {
1984 e.add(&x, &mixed, &mut x1, t * n_embd)?;
1985 e.rms_norm_decode(
1986 &x1,
1987 layer.post_attn_norm.float_data(),
1988 &mut zf,
1989 n_embd,
1990 t,
1991 eps,
1992 )?;
1993 } else {
1994 e.add_rms_norm(
1995 &x,
1996 &mixed,
1997 layer.post_attn_norm.float_data(),
1998 &mut x1,
1999 &mut zf,
2000 n_embd,
2001 t,
2002 eps,
2003 )?;
2004 }
2005 z = zf;
2006 None
2007 };
2008 // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
2009 // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
2010 // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
2011 let ffn_out = match &layer.ffn {
2012 crate::hybrid::Ffn::Dense {
2013 ffn_gate,
2014 ffn_up,
2015 ffn_down,
2016 } => {
2017 let n_ff = ffn_gate.out_features();
2018 if let Some((zq, zd)) = z_q8.as_ref() {
2019 // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
2020 // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
2021 // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
2022 // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
2023 // scale_inplace store, value-exact) — the exact m=1 decode epilogue
2024 // structure at nrows=t.
2025 let pair = match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
2026 Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
2027 None => None,
2028 };
2029 let (gate, gs, up, us) = match pair {
2030 Some(x4) => x4,
2031 None => (
2032 e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
2033 1.0, // scale already applied inside _pre
2034 e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
2035 1.0,
2036 ),
2037 };
2038 if e.uses_q8_1_fast(ffn_down) {
2039 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
2040 e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
2041 } else {
2042 let mut act = vbuf(e, t * n_ff)?;
2043 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
2044 e.matmul_decode_exact(ffn_down, &act, t)?
2045 }
2046 } else {
2047 // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
2048 // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
2049 // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
2050 // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
2051 // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
2052 let (gate, up) = match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
2053 Some(pair) => pair,
2054 None => (
2055 e.matmul_decode_exact(ffn_gate, &z, t)?,
2056 e.matmul_decode_exact(ffn_up, &z, t)?,
2057 ),
2058 };
2059 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
2060 Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0, dense_lim,
2061 &mut act, t * n_ff)?;
2062 e.matmul_decode_exact(ffn_down, &act, t)?
2063 }
2064 }
2065 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
2066 };
2067 // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
2068 // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
2069 // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
2070 pending = Some((x1, ffn_out));
2071 }
2072 // RANGE's final add (no next norm INSIDE the range to fuse with; for the
2073 // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
2074 if let Some((x1p, f1p)) = pending.take() {
2075 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
2076 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
2077 x = x2;
2078 }
2079 Ok(x)
2080 }
2081 /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
2082 /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
2083 /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
2084 /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
2085 /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
2086 /// ssm state exactly like T sequential decode steps.
2087 /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
2088 /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
2089 #[allow(clippy::too_many_arguments)]
2090 fn linear_attn_verify_t(
2091 &self,
2092 e: &Engine,
2093 la: &LinearAttnLayer,
2094 h: &CudaSlice<f32>,
2095 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2096 t: usize,
2097 cache: &mut Cache,
2098 il: usize,
2099 want_stash: bool,
2100 ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
2101 let cfg = &self.cfg;
2102 let ssm = cfg.ssm.as_ref().unwrap();
2103 let d_state = ssm.state_size as usize;
2104 let num_k = ssm.group_count as usize;
2105 let num_v = ssm.time_step_rank as usize;
2106 let d_conv = ssm.conv_kernel as usize;
2107 let key_dim = d_state * num_k;
2108 let conv_dim = key_dim * 2 + d_state * num_v;
2109 let eps = cfg.rms_eps;
2110 let scale = 1.0 / (d_state as f32).sqrt();
2111
2112 // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
2113 // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
2114 // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
2115 // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
2116 // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
2117 // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
2118 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
2119 // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
2120 // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
2121 // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
2122 // Bit-identical per (tensor,token,row) — see spec_fused_t().
2123 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
2124 // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
2125 // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
2126 // and feeds every projection; the caller guaranteed all four input projections are
2127 // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
2128 let h_q8_t = if h_q8.is_none()
2129 && spec_fused_t()
2130 && (2..=4).contains(&t)
2131 && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
2132 || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
2133 {
2134 Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
2135 } else {
2136 None
2137 };
2138 // one view: the caller's fused-norm q8 or this fn's own shared quantize.
2139 let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
2140 h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
2141 let (qkv_mixed, z) = {
2142 let mut fused = None;
2143 if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
2144 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
2145 fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
2146 } else if let Some((hq, hd)) = hq8_any {
2147 if spec_fused_t() && (2..=4).contains(&t) {
2148 fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
2149 }
2150 }
2151 match (fused, hq8_any) {
2152 (Some(pair), _) => pair,
2153 (None, Some((hq, hd))) if h_q8.is_some() => (
2154 e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
2155 e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
2156 ),
2157 (None, _) => (
2158 e.matmul_decode_exact(&la.wqkv, h, t)?,
2159 e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
2160 ),
2161 }
2162 };
2163 // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
2164 // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
2165 // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
2166 // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
2167 let (beta_raw, alpha) = if t == 1 {
2168 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
2169 match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
2170 Some(((mut b, bs), (mut a, as_))) => {
2171 if bs != 1.0 {
2172 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
2173 }
2174 if as_ != 1.0 {
2175 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
2176 }
2177 (b, a)
2178 }
2179 // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
2180 // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
2181 // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
2182 None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
2183 Some((b, a)) => (b, a),
2184 None => (
2185 e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
2186 e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
2187 ),
2188 },
2189 }
2190 } else {
2191 // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
2192 // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
2193 let mut fused = None;
2194 if let Some((hq, hd)) = hq8_any {
2195 if spec_fused_t() && (2..=4).contains(&t) {
2196 fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
2197 }
2198 }
2199 match (fused, hq8_any) {
2200 (Some(pair), _) => pair,
2201 (None, Some((hq, hd))) if h_q8.is_some() => (
2202 e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
2203 e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
2204 ),
2205 (None, _) => (
2206 e.matmul_decode_exact(&la.ssm_beta, h, t)?,
2207 e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
2208 ),
2209 }
2210 };
2211
2212 // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
2213 // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
2214 let rl = cache.recur[il].as_mut().unwrap();
2215 let mut conv_out = e.uninit(conv_dim * t)?;
2216 e.ssm_conv1d_tm_state(
2217 &qkv_mixed,
2218 &mut rl.conv_state,
2219 la.ssm_conv1d.float_data(),
2220 &mut conv_out,
2221 conv_dim,
2222 t,
2223 d_conv,
2224 )?;
2225
2226 // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
2227 let mut q_g = e.uninit(d_state * num_v * t)?;
2228 let mut k_g = e.uninit(d_state * num_v * t)?;
2229 let mut v_g = e.uninit(d_state * num_v * t)?;
2230 e.qkv_to_gdn_repack(
2231 &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
2232 )?;
2233 let mut q_l2 = e.uninit(d_state * num_v * t)?;
2234 e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
2235 let mut k_l2 = e.uninit(d_state * num_v * t)?;
2236 e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
2237 let mut beta = e.uninit(t * num_v)?;
2238 e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
2239 let mut g_log = e.uninit(t * num_v)?;
2240 e.gdn_glog(
2241 &alpha,
2242 la.ssm_dt.float_data(),
2243 la.ssm_a.float_data(),
2244 &mut g_log,
2245 num_v,
2246 t,
2247 )?;
2248
2249 // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
2250 // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
2251 let mut o = e.uninit(d_state * num_v * t)?;
2252 {
2253 let crate::cache::RecurLayer {
2254 ssm_state,
2255 ssm_state_alt,
2256 ..
2257 } = rl;
2258 e.gdn_scan_s128(
2259 &q_l2,
2260 &k_l2,
2261 &v_g,
2262 &g_log,
2263 &beta,
2264 ssm_state,
2265 ssm_state_alt,
2266 &mut o,
2267 num_v,
2268 t,
2269 scale,
2270 )?;
2271 }
2272 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2273
2274 // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
2275 // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
2276 // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
2277 // T-wide launch is the per-row program; kernel-check pins bit-identity vs
2278 // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
2279 // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
2280 let out = if e.uses_q8_1_fast(&la.ssm_out) {
2281 let (gq, gd) =
2282 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
2283 e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
2284 } else {
2285 let mut gn = e.uninit(d_state * num_v * t)?;
2286 e.gated_rmsnorm(
2287 &o,
2288 la.ssm_norm.float_data(),
2289 &z,
2290 &mut gn,
2291 d_state,
2292 num_v * t,
2293 eps,
2294 )?;
2295 // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
2296 // would fall to dp4a with a different FP reduction order — same class of bug as
2297 // the input projs).
2298 e.matmul_decode_exact(&la.ssm_out, &gn, t)?
2299 };
2300 let stash = if want_stash {
2301 Some(GdnStash {
2302 qkv_mixed,
2303 q_l2,
2304 k_l2,
2305 v_g,
2306 g_log,
2307 beta,
2308 })
2309 } else {
2310 None
2311 };
2312 Ok((out, stash))
2313 }
2314
2315 /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
2316 /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
2317 /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
2318 /// are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
2319 /// verify-probe gates), so keeping them == replaying them.
2320 /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
2321 /// columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
2322 /// snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
2323 /// registers and writes it once at the end, so iterations 0..j-1 are independent of T:
2324 /// bit-identical to the verify's own state after j tokens == the eager chain state.
2325 /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
2326 /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
2327 fn commit_verified_prefix(
2328 &self,
2329 e: &Engine,
2330 cache: &mut Cache,
2331 snap: &crate::cache::CacheSnapshot,
2332 ckpt: &VerifyCkpt,
2333 j: usize,
2334 kv_lens_done: bool,
2335 dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
2336 ) -> Result<(), Box<dyn std::error::Error>> {
2337 let cfg = &self.cfg;
2338 let ssm = cfg.ssm.as_ref().unwrap();
2339 let d_state = ssm.state_size as usize;
2340 let num_k = ssm.group_count as usize;
2341 let num_v = ssm.time_step_rank as usize;
2342 let d_conv = ssm.conv_kernel as usize;
2343 let conv_dim = d_state * num_k * 2 + d_state * num_v;
2344 let scale = 1.0 / (d_state as f32).sqrt();
2345 for il in 0..self.layers.len() {
2346 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
2347 kvl.len = saved + j;
2348 // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
2349 if !kv_lens_done {
2350 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2351 }
2352 }
2353 if let Some(rl) = cache.recur[il].as_mut() {
2354 if let Some(st) = &ckpt.gdn[il] {
2355 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
2356 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
2357 if let Some((acc, base, t_v)) = dev_j {
2358 // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
2359 e.ssm_conv_ring_rebuild_dc(
2360 &st.qkv_mixed,
2361 ring_old,
2362 &mut rl.conv_state,
2363 conv_dim,
2364 acc,
2365 base,
2366 t_v,
2367 d_conv,
2368 )?;
2369 let mut o = e.uninit(d_state * num_v * j.max(1))?;
2370 e.gdn_scan_s128_dc(
2371 &st.q_l2,
2372 &st.k_l2,
2373 &st.v_g,
2374 &st.g_log,
2375 &st.beta,
2376 state_in,
2377 &mut rl.ssm_state,
2378 &mut o,
2379 num_v,
2380 acc,
2381 base,
2382 t_v,
2383 scale,
2384 )?;
2385 } else {
2386 e.ssm_conv_ring_rebuild(
2387 &st.qkv_mixed,
2388 ring_old,
2389 &mut rl.conv_state,
2390 conv_dim,
2391 j,
2392 d_conv,
2393 )?;
2394 let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
2395 e.gdn_scan_s128(
2396 &st.q_l2,
2397 &st.k_l2,
2398 &st.v_g,
2399 &st.g_log,
2400 &st.beta,
2401 state_in,
2402 &mut rl.ssm_state,
2403 &mut o,
2404 num_v,
2405 j,
2406 scale,
2407 )?;
2408 }
2409 } else if let Some(cols) = &ckpt.cols[il] {
2410 let (c, s) = &cols[j - 1];
2411 e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
2412 e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
2413 } else {
2414 return Err(
2415 "commit_verified_prefix: verify ckpt missing for linear layer".into(),
2416 );
2417 }
2418 }
2419 }
2420 cache.pos = snap.pos + j;
2421 Ok(())
2422 }
2423
2424 /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
2425 /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
2426 fn commit_verified_prefix_stream(
2427 &self,
2428 e: &Engine,
2429 cache: &mut Cache,
2430 snap: &crate::cache::CacheSnapshot,
2431 ckpt: &VerifyCkpt,
2432 acc: &CudaSlice<u32>,
2433 base: usize,
2434 t_v: usize,
2435 ) -> Result<(), Box<dyn std::error::Error>> {
2436 let cfg = &self.cfg;
2437 let ssm = cfg.ssm.as_ref().unwrap();
2438 let d_state = ssm.state_size as usize;
2439 let num_k = ssm.group_count as usize;
2440 let num_v = ssm.time_step_rank as usize;
2441 let d_conv = ssm.conv_kernel as usize;
2442 let conv_dim = d_state * num_k * 2 + d_state * num_v;
2443 let scale = 1.0 / (d_state as f32).sqrt();
2444 for il in 0..self.layers.len() {
2445 if let Some(rl) = cache.recur[il].as_mut() {
2446 let st = ckpt.gdn[il]
2447 .as_ref()
2448 .ok_or("stream restore: batched-linear stash missing")?;
2449 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
2450 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
2451 e.ssm_conv_ring_rebuild_dc(
2452 &st.qkv_mixed,
2453 ring_old,
2454 &mut rl.conv_state,
2455 conv_dim,
2456 acc,
2457 base,
2458 t_v,
2459 d_conv,
2460 )?;
2461 let mut o = e.uninit(d_state * num_v * t_v)?;
2462 e.gdn_scan_s128_dc(
2463 &st.q_l2,
2464 &st.k_l2,
2465 &st.v_g,
2466 &st.g_log,
2467 &st.beta,
2468 state_in,
2469 &mut rl.ssm_state,
2470 &mut o,
2471 num_v,
2472 acc,
2473 base,
2474 t_v,
2475 scale,
2476 )?;
2477 }
2478 }
2479 Ok(())
2480 }
2481
2482 /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
2483 /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
2484 /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
2485 /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
2486 /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
2487 pub fn decode_step_t_aux2(
2488 &self,
2489 e: &Engine,
2490 tokens: &[u32],
2491 pos0: usize,
2492 cache: &mut Cache,
2493 aux_layers: &[usize],
2494 pred_col: Option<usize>,
2495 ) -> Result<
2496 (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
2497 Box<dyn std::error::Error>,
2498 > {
2499 let cfg = &self.cfg;
2500 let n_embd = cfg.n_embd as usize;
2501 let eps = cfg.rms_eps;
2502 let t = tokens.len();
2503 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
2504 let pos_d = e.htod_i32(&pos_vec)?;
2505 let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
2506 let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
2507 let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
2508 let want_pred = pred_col.is_some();
2509
2510 for (il, layer) in self.layers.iter().enumerate() {
2511 // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
2512 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
2513 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
2514 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
2515 if norm_fused {
2516 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
2517 } else {
2518 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
2519 }
2520 let mixed = match &layer.mixer {
2521 Mixer::Full(fa) => {
2522 self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
2523 }
2524 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
2525 Mixer::Linear(la) => {
2526 let mut out = e.zeros(t * n_embd)?;
2527 for col in 0..t {
2528 let mut h_col = e.zeros(n_embd)?;
2529 let src = h.slice(col * n_embd..(col + 1) * n_embd);
2530 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
2531 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
2532 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
2533 }
2534 out
2535 }
2536 };
2537 let ffn_fuse = match &layer.ffn {
2538 crate::hybrid::Ffn::Dense {
2539 ffn_gate, ffn_up, ..
2540 } => {
2541 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
2542 && e.uses_q8_1_fast(ffn_gate)
2543 && e.uses_q8_1_fast(ffn_up)
2544 }
2545 crate::hybrid::Ffn::Moe(_) => false,
2546 };
2547 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
2548 let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
2549 if ffn_fuse {
2550 e.add(&x, &mixed, &mut x1, t * n_embd)?;
2551 e.rms_norm_decode(
2552 &x1,
2553 layer.post_attn_norm.float_data(),
2554 &mut z,
2555 n_embd,
2556 t,
2557 eps,
2558 )?;
2559 } else {
2560 e.add_rms_norm(
2561 &x,
2562 &mixed,
2563 layer.post_attn_norm.float_data(),
2564 &mut x1,
2565 &mut z,
2566 n_embd,
2567 t,
2568 eps,
2569 )?;
2570 }
2571 let ffn_out = match &layer.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 = e.matmul_decode_exact(ffn_gate, &z, t)?;
2579 let up = e.matmul_decode_exact(ffn_up, &z, t)?;
2580 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
2581 // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
2582 Self::ffn_act_lim(e, &self.cfg, &gate, &up, 1.0, 1.0,
2583 self.cfg.clamp_shexp_at(il as u32), &mut act, t * n_ff)?;
2584 e.matmul_decode_exact(ffn_down, &act, t)?
2585 }
2586 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
2587 };
2588 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
2589 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
2590 if aux_layers.contains(&il) {
2591 let mut a = e.zeros(n_embd)?;
2592 e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
2593 aux_last.push(a);
2594 if let Some(pc) = pred_col {
2595 let mut ap = e.zeros(n_embd)?;
2596 e.copy_view_into(
2597 &mut ap,
2598 0,
2599 &x2.slice(pc * n_embd..(pc + 1) * n_embd),
2600 n_embd,
2601 )?;
2602 aux_pred.push(ap);
2603 }
2604 }
2605 x = x2;
2606 }
2607 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
2608 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
2609 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
2610 let host = e.dtoh(&logits)?;
2611 cache.pos += t;
2612 Ok((
2613 host,
2614 aux_last,
2615 if want_pred { Some(aux_pred) } else { None },
2616 ))
2617 }
2618
2619 /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
2620 /// `step35_decode_attn`.
2621 ///
2622 /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
2623 /// the eager decode would have computed for the same tokens; that is what makes greedy spec
2624 /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
2625 /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
2626 /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
2627 /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
2628 /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
2629 /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
2630 /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
2631 /// position of each query row. A batched twin would have to reproduce all of that AND the
2632 /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
2633 /// take one `base_len`, not a per-row offset).
2634 ///
2635 /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
2636 /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
2637 /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
2638 /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
2639 /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
2640 /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
2641 /// step35 twin is a perf lane's job and must be gated against this arm.
2642 ///
2643 /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
2644 /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
2645 /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
2646 /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
2647 /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
2648 #[allow(clippy::too_many_arguments)]
2649 fn step35_verify(
2650 &self,
2651 e: &Engine,
2652 fa: &FullAttnLayer,
2653 h: &CudaSlice<f32>,
2654 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2655 t: usize,
2656 cache: &mut Cache,
2657 il: usize,
2658 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2659 let n_embd = self.cfg.n_embd as usize;
2660 // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
2661 // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
2662 // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
2663 // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
2664 // cannot regress it into silently reading an empty buffer.
2665 assert_eq!(
2666 h.len(),
2667 t * n_embd,
2668 "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
2669 fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
2670 h_q8.is_some()
2671 );
2672 // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
2673 // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
2674 // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
2675 // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
2676 // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
2677 // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
2678 let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
2679 for r in 0..t {
2680 // Absolute position of this query row. `cache.pos` is the committed length at round
2681 // start and every row before r has already been appended by this loop, so the r-th
2682 // verify token sits at cache.pos + r — the same position eager decode would give it.
2683 let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
2684 let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
2685 e.copy_view_into(&mut h_row, 0, &h.slice(r * n_embd..(r + 1) * n_embd), n_embd)?;
2686 // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
2687 // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
2688 let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
2689 debug_assert_eq!(o.len(), n_embd, "step35_decode_attn returns post-wo [n_embd]");
2690 e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
2691 }
2692 Ok(out)
2693 }
2694
2695 /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
2696 /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
2697 /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
2698 #[allow(clippy::too_many_arguments)]
2699 fn full_attn_verify(
2700 &self,
2701 e: &Engine,
2702 fa: &FullAttnLayer,
2703 h: &CudaSlice<f32>,
2704 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
2705 pos_d: &CudaSlice<i32>,
2706 t: usize,
2707 cache: &mut Cache,
2708 il: usize,
2709 stream_ctr: Option<&CudaSlice<i32>>,
2710 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2711 // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
2712 // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
2713 // its own arm. A verify that silently computes different attention than decode defeats the
2714 // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
2715 // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
2716 // shape and not laziness.
2717 if self.cfg.step35.is_some() {
2718 if stream_ctr.is_some() {
2719 return Err("step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
2720 cannot express the SWA offset KV view; same root cause as the dc \
2721 decode refusal) — run spec without the stream arm".into());
2722 }
2723 return self.step35_verify(e, fa, h, h_q8, t, cache, il);
2724 }
2725 let cfg = &self.cfg;
2726 let geometry = cfg.full_attention_geometry_at(il as u32);
2727 let n_head = geometry.n_head as usize;
2728 let n_head_kv = geometry.n_head_kv as usize;
2729 let head_dim = geometry.head_dim_k as usize;
2730 let eps = cfg.rms_eps;
2731 let scale = geometry.attention_scale();
2732 let n_embd = cfg.n_embd as usize;
2733
2734 // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
2735 // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
2736 // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
2737 // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
2738 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
2739 // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
2740 // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
2741 // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
2742 let (qf, mut k, v) = {
2743 let mut fused = None;
2744 let qkv_fast = e.uses_q8_1_fast(&fa.wq)
2745 && e.uses_q8_1_fast(&fa.wk)
2746 && e.uses_q8_1_fast(&fa.wv);
2747 if t == 1 && qkv_fast {
2748 let (hq_o, hd_o);
2749 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
2750 Some(p) => p,
2751 None => {
2752 (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
2753 (&hq_o, &hd_o)
2754 }
2755 };
2756 fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
2757 } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
2758 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
2759 // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
2760 // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
2761 let (hq_o, hd_o);
2762 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
2763 Some(p) => p,
2764 None => {
2765 (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
2766 (&hq_o, &hd_o)
2767 }
2768 };
2769 fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
2770 }
2771 match (fused, h_q8) {
2772 (Some(triple), _) => triple,
2773 // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
2774 // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
2775 (None, Some((hq, hd))) if qkv_fast => (
2776 e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
2777 e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
2778 e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
2779 ),
2780 (None, _) => (
2781 e.matmul_decode_exact(&fa.wq, h, t)?,
2782 e.matmul_decode_exact(&fa.wk, h, t)?,
2783 e.matmul_decode_exact(&fa.wv, h, t)?,
2784 ),
2785 }
2786 };
2787 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2788 let gated = geometry.attention_gate
2789 == memra_gguf::config::AttentionGateKind::FusedQ;
2790 let (mut q, gate) = if gated {
2791 let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
2792 let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
2793 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
2794 (q, Some(gate))
2795 } else {
2796 (qf, None)
2797 };
2798
2799 let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
2800 e.rms_norm(
2801 &q,
2802 fa.q_norm.float_data(),
2803 &mut qn,
2804 head_dim,
2805 n_head * t,
2806 eps,
2807 )?;
2808 q = qn;
2809 let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
2810 e.rms_norm(
2811 &k,
2812 fa.k_norm.float_data(),
2813 &mut kn,
2814 head_dim,
2815 n_head_kv * t,
2816 eps,
2817 )?;
2818 k = kn;
2819 let rope_dims = geometry.n_rot as usize;
2820 e.rope_neox(
2821 &mut q,
2822 pos_d,
2823 head_dim,
2824 rope_dims,
2825 n_head,
2826 t,
2827 geometry.rope_base,
2828 1.0,
2829 )?;
2830 e.rope_neox(
2831 &mut k,
2832 pos_d,
2833 head_dim,
2834 rope_dims,
2835 n_head_kv,
2836 t,
2837 geometry.rope_base,
2838 1.0,
2839 )?;
2840
2841 // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
2842 // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
2843 let kvl = cache.kv[il].as_mut().unwrap();
2844 let (kv_dim_k, kv_dim_v, ktb, vtb) =
2845 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
2846 if let Some(ctr) = stream_ctr {
2847 // stream: ONE batched append at the device counter (rows kernel = the per-view warp
2848 // math on a (block, token) grid, documented byte-identical); host len is a stale
2849 // LOWER BOUND under pre-issue (drain reconciles it).
2850 e.append_kv_quantized_rows_dc(
2851 &k,
2852 &v,
2853 &mut kvl.k,
2854 &mut kvl.v,
2855 ctr,
2856 t,
2857 kv_dim_k,
2858 kv_dim_v,
2859 ktb,
2860 vtb,
2861 crate::Engine::kv_fp8_on(),
2862 )?;
2863 } else {
2864 for i in 0..t {
2865 let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
2866 let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
2867 e.append_kv_quantized_view(
2868 &k_row,
2869 &v_row,
2870 &mut kvl.k,
2871 &mut kvl.v,
2872 kvl.len + i,
2873 kv_dim_k,
2874 kv_dim_v,
2875 ktb,
2876 vtb,
2877 crate::Engine::kv_fp8_on(),
2878 )?;
2879 }
2880 kvl.len += t;
2881 }
2882
2883 // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
2884 // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
2885 // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
2886 // which changes FP summation order and can flip argmax at tight logit margins. Query row r
2887 // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
2888 // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
2889 // keys. The verify appends all T tokens first but bounds the key range per row.
2890 //
2891 // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
2892 // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
2893 // per-row program for all T rows (grid.z = row, per-row n_splits from the same
2894 // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
2895 // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
2896 // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
2897 // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
2898 // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
2899 let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
2900 let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
2901 // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
2902 // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
2903 // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
2904 // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
2905 // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
2906 // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
2907 // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
2908 // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
2909 if let Some(ctr) = stream_ctr {
2910 // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
2911 // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
2912 // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
2913 let upper = kvl.len + t + 64;
2914 let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
2915 let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
2916 e.fa_decode_rows_dc(
2917 &q,
2918 &k_view,
2919 &v_view,
2920 &mut attn,
2921 head_dim,
2922 n_head,
2923 n_head_kv,
2924 ctr,
2925 upper.min(cache.max_ctx),
2926 t,
2927 scale,
2928 ktb,
2929 vtb,
2930 0,
2931 false,
2932 )?;
2933 } else if spec_lean() && t == 1 {
2934 let t_kv = base_len + 1;
2935 let k_view = e.view_u8(&kvl.k, t_kv * ktb);
2936 let v_view = e.view_u8(&kvl.v, t_kv * vtb);
2937 e.fa_decode_kvmod(
2938 &q,
2939 &k_view,
2940 &v_view,
2941 &mut attn,
2942 head_dim,
2943 n_head,
2944 n_head_kv,
2945 t_kv,
2946 scale,
2947 ktb,
2948 vtb,
2949 crate::Engine::kv_fp8_on(),
2950 )?;
2951 } else if e.fa_rows_eligible(base_len, head_dim) {
2952 let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
2953 let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
2954 e.fa_decode_rows(
2955 &q,
2956 &k_view,
2957 &v_view,
2958 &mut attn,
2959 head_dim,
2960 n_head,
2961 n_head_kv,
2962 base_len,
2963 t,
2964 scale,
2965 ktb,
2966 vtb,
2967 None,
2968 false,
2969 crate::Engine::kv_fp8_on(),
2970 None,
2971 )?;
2972 } else {
2973 for r in 0..t {
2974 let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
2975 let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
2976 let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
2977 // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
2978 let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
2979 let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
2980 e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
2981 let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
2982 e.fa_decode_kvmod(
2983 &q_row,
2984 &k_view_r,
2985 &v_view_r,
2986 &mut attn_row,
2987 head_dim,
2988 n_head,
2989 n_head_kv,
2990 t_kv_r,
2991 scale,
2992 ktb,
2993 vtb,
2994 crate::Engine::kv_fp8_on(),
2995 )?;
2996 e.copy_into(
2997 &mut attn,
2998 r * n_head * head_dim,
2999 &attn_row,
3000 n_head * head_dim,
3001 )?;
3002 }
3003 }
3004
3005 let attn_g = match &gate {
3006 Some(gate) => {
3007 let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
3008 e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
3009 let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
3010 e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
3011 ag
3012 }
3013 None => attn,
3014 };
3015 // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
3016 // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
3017 Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
3018 }
3019
3020 /// Context-linear bytes for a plain serving session's trunk cache.
3021 pub fn plain_session_kv_bytes_per_token(&self) -> usize {
3022 crate::cache::cache_bytes_per_token(&self.cfg)
3023 }
3024
3025 /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
3026 /// scratch. With no MTP head this equals the plain coefficient.
3027 pub fn spec_session_kv_bytes_per_token(&self) -> usize {
3028 let scratch = self
3029 .mtp
3030 .as_ref()
3031 .map(|mtp| {
3032 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
3033 k + v
3034 })
3035 .unwrap_or(0);
3036 self.plain_session_kv_bytes_per_token()
3037 .saturating_add(scratch)
3038 }
3039
3040 /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
3041 /// the NextN head to draft K tokens then verifies them in one batched target forward.
3042 /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
3043 /// acceptance rate. `k` = draft length per round.
3044 ///
3045 /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
3046 /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
3047 /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
3048 /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
3049 /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
3050 /// captured graph references is event-free; the spec loop is strictly single-stream.
3051 /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
3052 /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
3053 /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
3054 /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
3055 /// generate_spec_inner2.
3056 /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
3057 /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
3058 /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
3059 /// hybrid linear-attn states are in-place (no position index), so a session can extend but
3060 /// never rewind — `committed` is the exact token list whose state the caches hold (includes
3061 /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
3062 pub fn new_session(
3063 &self,
3064 e: &Engine,
3065 max_ctx: usize,
3066 ) -> Result<SpecSession, Box<dyn std::error::Error>> {
3067 Ok(SpecSession {
3068 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
3069 // is the SERVING spec-session path, and with the ppN door open across two cards a
3070 // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
3071 // round — the wrong-card class already fixed on the two batched serving paths
3072 // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
3073 // branch, same allocations), so single-device behavior is byte-unchanged.
3074 cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
3075 scratch: MtpScratch::new(
3076 e,
3077 &self.cfg,
3078 max_ctx,
3079 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
3080 )?,
3081 committed: Vec::new(),
3082 last_h: None,
3083 next_pred: None,
3084 sctr: 0,
3085 uctr: 0,
3086 draft_ctx: None,
3087 pending_tok: None,
3088 turn_ckpt: None,
3089 telem: SpecTelemetry::default(),
3090 })
3091 }
3092
3093 /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
3094 /// retained prompt-end checkpoint, so a request whose prompt matches
3095 /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
3096 ///
3097 /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
3098 /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
3099 /// restored from the device copy taken there, draft scratch length reset, `committed`
3100 /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
3101 /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
3102 /// every burst after it are identical to a cold run of the same token stream — the
3103 /// committed-tokens-authoritative contract.
3104 ///
3105 /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
3106 /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
3107 /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
3108 /// continue). The persistent draft graph survives: it bakes only session-stable pointers
3109 /// (the scratch KV, the resident embedding), none of which the rewind moves.
3110 ///
3111 /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
3112 /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
3113 /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
3114 pub fn spec_rewind_to_checkpoint(
3115 &self,
3116 e: &Engine,
3117 sess: &mut SpecSession,
3118 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
3119 let Some(ckpt) = sess.turn_ckpt.take() else {
3120 return Ok(None);
3121 };
3122 assert!(
3123 ckpt.pos <= sess.committed.len(),
3124 "checkpoint past committed ({} > {})",
3125 ckpt.pos,
3126 sess.committed.len()
3127 );
3128 // accept_len 0: roll all the way back to the snapshot's own boundary. `rollback` sets
3129 // each full-attn len to its saved value, restores conv/ssm by D2D copy, and sets
3130 // cache.pos = snap.pos.
3131 sess.cache.rollback(e, &ckpt.snap, 0)?;
3132 debug_assert_eq!(sess.cache.pos, ckpt.pos, "rollback landed off the checkpoint");
3133 sess.scratch.set_len(e, ckpt.pos)?;
3134 sess.committed.truncate(ckpt.pos);
3135 sess.last_h = Some(ckpt.last_h);
3136 sess.next_pred = None;
3137 sess.pending_tok = None;
3138 Ok(Some(ckpt.pos))
3139 }
3140
3141 /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
3142 /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
3143 /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
3144 /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
3145 pub fn spec_flush_pending(
3146 &self,
3147 e: &Engine,
3148 sess: &mut SpecSession,
3149 ) -> Result<(), Box<dyn std::error::Error>> {
3150 let Some(b) = sess.pending_tok.take() else {
3151 return Ok(());
3152 };
3153 let mtp = self.mtp.as_ref().expect("pending carry requires an MTP head");
3154 let n_embd = self.cfg.n_embd as usize;
3155 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
3156 let embd_gpu = if spec_host_embd() {
3157 None
3158 } else {
3159 Some(
3160 self.embd_gpu
3161 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
3162 )
3163 };
3164 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
3165 let pos_b = sess.cache.pos;
3166 sess.scratch.set_len(e, pos_b)?;
3167 let (lg_b, hb) = self.decode_step_h(e, b, &mut sess.cache)?;
3168 sess.next_pred = Some(argmax(&lg_b) as u32);
3169 let anchor = sess
3170 .last_h
3171 .as_ref()
3172 .expect("pending carry requires last_h (the predecessor-row anchor)");
3173 self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
3174 sess.last_h = Some(hb);
3175 sess.committed.push(b);
3176 Ok(())
3177 }
3178
3179 /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
3180 /// message rendered through the chat template continuation). Returns (new tokens emitted,
3181 /// drafted, accepted); session.committed grows by suffix + emitted.
3182 pub fn generate_spec_session(
3183 &self,
3184 e: &Engine,
3185 sess: &mut SpecSession,
3186 suffix: &[u32],
3187 max_new: usize,
3188 k: usize,
3189 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3190 self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
3191 }
3192
3193 /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
3194 /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
3195 /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
3196 /// for the filtered target (feat/filtered-spec).
3197 ///
3198 /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
3199 /// output — once right after the prime's first token, then once per round commit — so a
3200 /// streaming caller can flush text at round cadence instead of once per burst. The slices
3201 /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
3202 /// timing only: token bytes, session state, and exactness are untouched.
3203 ///
3204 /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
3205 /// the burst at the current round boundary, exactly as if `max_new` had been reached —
3206 /// the caller's scheduler regains control without waiting the burst out. Burst size is
3207 /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
3208 /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
3209 /// drains and the defensive tail flush can land with nothing new committed).
3210 #[allow(clippy::too_many_arguments)]
3211 pub fn generate_spec_session_sampled(
3212 &self,
3213 e: &Engine,
3214 sess: &mut SpecSession,
3215 suffix: &[u32],
3216 max_new: usize,
3217 k: usize,
3218 sampling: Option<SpecSampling>,
3219 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
3220 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3221 self.generate_spec_session_constrained(e, sess, suffix, max_new, k, sampling, None, on_commit)
3222 }
3223
3224 /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
3225 /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
3226 /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
3227 /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
3228 /// column — token-identical to constrained plain greedy decode. GREEDY only (the
3229 /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
3230 /// may drop (drafter is unconstrained); that is measured, not hidden.
3231 #[allow(clippy::too_many_arguments)]
3232 pub fn generate_spec_session_constrained(
3233 &self,
3234 e: &Engine,
3235 sess: &mut SpecSession,
3236 suffix: &[u32],
3237 max_new: usize,
3238 k: usize,
3239 sampling: Option<SpecSampling>,
3240 constraint: Option<&mut dyn SpecConstraint>,
3241 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
3242 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3243 if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
3244 return Err("constrained spec decode is greedy-only (worker routes sampled \
3245 constrained to plain decode)".into());
3246 }
3247 // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
3248 // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
3249 // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
3250 // serve continuation case — consume the carry in-loop with zero solo passes.
3251 if sess.pending_tok.is_some()
3252 && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
3253 {
3254 self.spec_flush_pending(e, sess)?;
3255 }
3256 let mtp_dense = self
3257 .mtp
3258 .as_ref()
3259 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
3260 .unwrap_or(false);
3261 let trunk_dense = self
3262 .layers
3263 .iter()
3264 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
3265 // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
3266 // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
3267 // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
3268 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
3269 && !spec_host_embd()
3270 && mtp_dense
3271 && trunk_dense
3272 && k + 2 < 96
3273 && !crate::model::full_prec_enabled();
3274 let was_tracking = e.ctx().is_event_tracking();
3275 if graph_draft && was_tracking {
3276 unsafe {
3277 e.ctx().disable_event_tracking();
3278 }
3279 }
3280 let r = self.generate_spec_inner2(e, suffix, max_new, k, graph_draft, Some(sess), sampling, constraint, on_commit);
3281 if graph_draft && was_tracking {
3282 unsafe {
3283 e.ctx().enable_event_tracking();
3284 }
3285 }
3286 let (out, d, a) = r?;
3287 Ok((out, d, a))
3288 }
3289
3290 pub fn generate_spec(
3291 &self,
3292 e: &Engine,
3293 prompt: &[u32],
3294 max_new: usize,
3295 k: usize,
3296 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3297 let mtp_dense = self
3298 .mtp
3299 .as_ref()
3300 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
3301 .unwrap_or(false);
3302 let trunk_dense = self
3303 .layers
3304 .iter()
3305 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
3306 // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
3307 // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
3308 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
3309 && !spec_host_embd()
3310 && mtp_dense
3311 && trunk_dense
3312 && k + 2 < 96
3313 && !crate::model::full_prec_enabled();
3314 if !graph_draft {
3315 return self.generate_spec_inner2(e, prompt, max_new, k, false, None, None, None, None);
3316 }
3317 let was_tracking = e.ctx().is_event_tracking();
3318 if was_tracking {
3319 unsafe {
3320 e.ctx().disable_event_tracking();
3321 }
3322 }
3323 let r = self.generate_spec_inner2(e, prompt, max_new, k, true, None, None, None, None);
3324 if was_tracking {
3325 unsafe {
3326 e.ctx().enable_event_tracking();
3327 }
3328 }
3329 r
3330 }
3331
3332 fn generate_spec_inner2(
3333 &self,
3334 e: &Engine,
3335 prompt: &[u32],
3336 max_new: usize,
3337 k: usize,
3338 graph_draft: bool,
3339 mut sess: Option<&mut SpecSession>,
3340 sampling: Option<SpecSampling>,
3341 mut constraint: Option<&mut dyn SpecConstraint>,
3342 mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
3343 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
3344 assert!(k >= 1, "k must be >= 1");
3345 // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
3346 let mut flushed = 0usize;
3347 // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
3348 // at the next round boundary (same exit as max_new reached — the session tail runs).
3349 // Initialized by the unconditional post-prime flush below.
3350 let mut keep_going;
3351 let mtp = self
3352 .mtp
3353 .as_ref()
3354 .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
3355 let n_vocab = self.output.out_features();
3356 // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
3357 // over the draft vocab and the winning index maps through d2t to a TARGET token id.
3358 // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
3359 let d_vocab = mtp
3360 .shared_head_head
3361 .as_ref()
3362 .unwrap_or(&self.output)
3363 .out_features();
3364 let n_embd = self.cfg.n_embd as usize;
3365 // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
3366 // already committed (their state is in the caches); 0 = fresh single-shot call.
3367 let session_mode = sess.is_some();
3368 let max_ctx = match sess.as_ref() {
3369 Some(s) => s.cache.max_ctx,
3370 None => prompt.len() + max_new + k + 8,
3371 };
3372 let mut own_cache;
3373 let mut own_scratch;
3374 let (
3375 cache,
3376 scratch,
3377 mut sess_tail,
3378 mut sess_draft_slot,
3379 mut sess_pending_slot,
3380 sess_ckpt_slot,
3381 mut sess_telem,
3382 ): (
3383 &mut Cache,
3384 &mut MtpScratch,
3385 Option<(
3386 &mut Vec<u32>,
3387 &mut Option<CudaSlice<f32>>,
3388 &mut Option<u32>,
3389 &mut u32,
3390 &mut u32,
3391 )>,
3392 Option<&mut Option<DraftGraphCtx>>,
3393 Option<&mut Option<u32>>,
3394 Option<&mut Option<SpecCheckpoint>>,
3395 Option<&mut SpecTelemetry>,
3396 ) = match sess.take() {
3397 Some(sr) => {
3398 let SpecSession {
3399 cache,
3400 scratch,
3401 committed,
3402 last_h,
3403 next_pred,
3404 sctr: s_sctr,
3405 uctr: s_uctr,
3406 draft_ctx,
3407 pending_tok,
3408 turn_ckpt,
3409 telem,
3410 } = sr;
3411 (
3412 cache,
3413 scratch,
3414 Some((committed, last_h, next_pred, s_sctr, s_uctr)),
3415 Some(draft_ctx),
3416 Some(pending_tok),
3417 Some(turn_ckpt),
3418 Some(telem),
3419 )
3420 }
3421 None => {
3422 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
3423 // `Cache::new` verbatim.
3424 own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
3425 // Persistent scratch = max_ctx rows (~2KB/token quantized).
3426 own_scratch = MtpScratch::new(
3427 e,
3428 &self.cfg,
3429 max_ctx,
3430 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
3431 )?;
3432 (&mut own_cache, &mut own_scratch, None, None, None, None, None)
3433 }
3434 };
3435 let base = cache.pos;
3436 // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
3437 // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
3438 // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
3439 // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
3440 let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
3441 // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
3442 // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
3443 // acceptance-only — exactness is verify's job either way).
3444 // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
3445 // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
3446 // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
3447 // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
3448 // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
3449 // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
3450 // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
3451 // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
3452 // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
3453 // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
3454 // per round on top of the acceptance win). Draft-quality-only: exactness stays the
3455 // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
3456 // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
3457 // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
3458 // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
3459 // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
3460 // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
3461 // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
3462 // + fallback seam).
3463 let spec_replay = std::env::var("MEMRA_SPEC_REPLAY").is_ok();
3464 if constraint.is_some() && spec_replay {
3465 return Err("constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
3466 (legacy replay commits an unmasked bonus)".into());
3467 }
3468 // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
3469 // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
3470 // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
3471 let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
3472
3473 // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
3474 // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
3475 // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
3476 // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
3477 // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
3478 // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
3479 // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
3480 // generation exactly where the last turn stopped — no prime at all. The stashed
3481 // `next_pred` plays prime_logits' argmax role (it IS the argmax of the logits after
3482 // committed.last()); `last_h` seeds the predecessor pairing below. Fresh calls and
3483 // non-empty suffixes take the normal path.
3484 let continuation = prompt.is_empty();
3485 if continuation {
3486 assert!(session_mode, "empty prompt requires a session");
3487 assert!(
3488 sess_tail
3489 .as_ref()
3490 .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
3491 && lh.is_some()
3492 && (np.is_some() || carried_pending.is_some())),
3493 "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
3494 );
3495 }
3496 let mut prime_logits;
3497 let mut prompt_h: Option<CudaSlice<f32>> = None;
3498 let t_prime = std::time::Instant::now();
3499 let batched_prime = !continuation
3500 && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
3501 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
3502 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
3503 if continuation {
3504 prime_logits = Vec::new();
3505 } else if batched_prime {
3506 let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
3507 prime_logits = l;
3508 prompt_h = Some(hiddens);
3509 } else {
3510 prime_logits = Vec::new();
3511 prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
3512 for (i, &tok) in prompt.iter().enumerate() {
3513 let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
3514 if let Some(ph) = prompt_h.as_mut() {
3515 e.copy_into(ph, i * n_embd, &h, n_embd)?;
3516 }
3517 prime_logits = l;
3518 }
3519 }
3520 e.stream().synchronize()?;
3521 // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
3522 // prime-subtraction hack.
3523 crate::PRIME_NANOS.store(
3524 t_prime.elapsed().as_nanos() as u64,
3525 std::sync::atomic::Ordering::Relaxed,
3526 );
3527
3528 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
3529 // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
3530 // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
3531 let host_embd = spec_host_embd();
3532 let embd_gpu = if host_embd {
3533 None
3534 } else {
3535 Some(
3536 self.embd_gpu
3537 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
3538 )
3539 };
3540 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
3541 if host_embd {
3542 eprintln!(
3543 "[spec] host-row embedding: {} bytes kept off HBM",
3544 self.embd.raw.len()
3545 );
3546 }
3547 let mut out: Vec<u32> = Vec::with_capacity(max_new);
3548 let mut total_drafted = 0usize;
3549 let mut total_accepted = 0usize;
3550
3551 // First generated token = argmax of the prompt's last logits (== greedy's first token).
3552 // Emit it, then FEED it to establish the loop invariant below.
3553 // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
3554 // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
3555 // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
3556 // prompt's last logits (plain constrained-greedy identity); a continuation without
3557 // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
3558 // worker never resumes constrained sessions from the pool, so this cannot fire).
3559 if let Some(c) = constraint.as_deref_mut() {
3560 if continuation && carried_pending.is_none() {
3561 return Err("constrained spec continuation requires a carried pending \
3562 (pool resume is unconstrained-only)".into());
3563 }
3564 if !continuation {
3565 c.mask_logits(&mut prime_logits)
3566 .map_err(|e2| format!("constraint: {e2}"))?;
3567 }
3568 }
3569 let mut last_token = if let Some(b) = carried_pending {
3570 b
3571 } else if continuation {
3572 sess_tail.as_ref().unwrap().2.unwrap()
3573 } else {
3574 argmax(&prime_logits) as u32
3575 };
3576 if carried_pending.is_none() {
3577 out.push(last_token);
3578 // grammar advances with every emitted token (carried pendings were consumed
3579 // by the burst that emitted them).
3580 if let Some(c) = constraint.as_deref_mut() {
3581 c.consume(last_token).map_err(|e2| format!("constraint: {e2}"))?;
3582 }
3583 }
3584 if continuation {
3585 // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
3586 // overhang so the chain's first append lands at slot base (== committed.len()).
3587 scratch.set_len(e, base)?;
3588 }
3589 // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
3590 // concatenating to the full `out`). Called after the prime's first token and after each
3591 // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
3592 // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
3593 // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
3594 fn flush_commit(
3595 cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
3596 out: &[u32],
3597 flushed: &mut usize,
3598 ) -> bool {
3599 if let Some(f) = cb.as_mut() {
3600 let keep = f(&out[*flushed..]);
3601 *flushed = out.len();
3602 keep
3603 } else {
3604 true
3605 }
3606 }
3607 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
3608 // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
3609 // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
3610 // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
3611 // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
3612 // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
3613 // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
3614 // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
3615 // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
3616 // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
3617 // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
3618 let sp = sampling.unwrap_or_else(|| SpecSampling {
3619 temp: std::env::var("MEMRA_SPEC_TEMP")
3620 .ok()
3621 .and_then(|v| v.parse().ok())
3622 .unwrap_or(0.0),
3623 seed: std::env::var("MEMRA_SEED")
3624 .ok()
3625 .and_then(|v| v.parse().ok())
3626 .unwrap_or(42),
3627 top_k: std::env::var("MEMRA_TOP_K")
3628 .ok()
3629 .and_then(|v| v.parse().ok())
3630 .unwrap_or(0),
3631 top_p: std::env::var("MEMRA_TOP_P")
3632 .ok()
3633 .and_then(|v| v.parse().ok())
3634 .unwrap_or(1.0),
3635 min_p: std::env::var("MEMRA_MIN_P")
3636 .ok()
3637 .and_then(|v| v.parse().ok())
3638 .unwrap_or(0.0),
3639 penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
3640 .ok()
3641 .and_then(|v| v.parse().ok())
3642 .unwrap_or(0),
3643 penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
3644 .ok()
3645 .and_then(|v| v.parse().ok())
3646 .unwrap_or(1.0),
3647 penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
3648 .ok()
3649 .and_then(|v| v.parse().ok())
3650 .unwrap_or(0.0),
3651 penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
3652 .ok()
3653 .and_then(|v| v.parse().ok())
3654 .unwrap_or(0.0),
3655 });
3656 let (sp_temp, sp_seed) = (sp.temp, sp.seed);
3657 let sampled = sp_temp > 0.0;
3658 // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
3659 // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
3660 // those, so their residual mass is p(x), correct by construction).
3661 let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
3662 match &mtp.d2t {
3663 Some(map) => Some(e.htod_u32_v(map)?),
3664 None => None,
3665 }
3666 } else {
3667 None
3668 };
3669 let mut q_full_buf: Option<CudaSlice<f32>> = None;
3670 // Counters resume from the session (burst continuity: randomness must never repeat
3671 // across generate_spec_session calls); one-shot callers start at (0,0). Read through
3672 // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
3673 let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
3674 let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
3675 // host Philox4x32-10 (mirrors spec_sample.cu; independent stream via ctr_lo tag)
3676 let host_u01 = |seed: u64, ctr: u32| -> f32 {
3677 let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
3678 let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
3679 let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
3680 for _ in 0..10 {
3681 let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
3682 let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
3683 let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
3684 c0 = n0;
3685 c1 = n1;
3686 c2 = n2;
3687 c3 = n3;
3688 k0 = k0.wrapping_add(0x9E3779B9);
3689 k1 = k1.wrapping_add(0xBB67AE85);
3690 }
3691 (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
3692 };
3693 let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
3694 let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
3695 let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
3696 let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
3697 let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
3698 // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
3699 // for the penalized+filtered target). History = generated tokens, host-tracked window.
3700 let pen_on = sampled
3701 && sp.penalty_last_n > 0
3702 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
3703 let mut pen_hist: Vec<u32> = if pen_on {
3704 prompt.iter().rev().take(64).rev().cloned().collect() // llama-parity: history spans prompt tail too
3705 } else {
3706 Vec::new()
3707 };
3708 let mut pen_hist_d: Option<CudaSlice<u32>> = None;
3709 let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
3710 // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
3711 // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
3712 // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
3713 let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
3714 let t_ent = std::time::Instant::now();
3715
3716 // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
3717 // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
3718 // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
3719 // the one that matters (a history-rewriting client mutates what the session GENERATED,
3720 // so the next turn's prompt agrees with this one up to exactly here).
3721 //
3722 // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
3723 // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
3724 // hold exactly `base + prompt.len()` rows and nothing generated.
3725 //
3726 // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
3727 // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
3728 // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
3729 // `<think>` block the client strips, so every later turn's diff diverged exactly one
3730 // token below the checkpoint and affinity declined 100% of the time. Measured on the
3731 // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
3732 // whole mechanism inert while looking, from the outside, like a working
3733 // correctness-declines-safely path — hence the decline log carries the offsets.
3734 //
3735 // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
3736 // state (the reason a spec session could not rewind before). The draft scratch needs no
3737 // copy: rows below the boundary are rewritten by the next turn's own fill.
3738 //
3739 // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
3740 // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
3741 // checkpoint rather than replacing it with a strictly worse one.
3742 //
3743 // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
3744 // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
3745 // fail the burst that is already running — so the error is swallowed, loud only under
3746 // MEMRA_DEBUG_SPEC.
3747 if let Some(slot) = sess_ckpt_slot {
3748 if !continuation {
3749 let pos = cache.pos;
3750 debug_assert_eq!(
3751 pos,
3752 base + prompt.len(),
3753 "turn checkpoint must sit at the prompt end, before the init feed"
3754 );
3755 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
3756 if let Some(ph) = &prompt_h {
3757 // hidden of the LAST primed row = the predecessor anchor at this
3758 // boundary (exactly what a fresh prime of committed[..pos] leaves in
3759 // last_h, and what the next prime's fill reads for its first row).
3760 let np = prompt.len();
3761 e.uninit(n_embd).and_then(|mut a| {
3762 e.copy_view_into(
3763 &mut a,
3764 0,
3765 &ph.slice((np - 1) * n_embd..np * n_embd),
3766 n_embd,
3767 )?;
3768 Ok(a)
3769 })
3770 } else {
3771 Err("no prompt hiddens".into())
3772 };
3773 match (cache.snapshot(e), anchor) {
3774 (Ok(snap), Ok(last_h)) => {
3775 *slot = Some(SpecCheckpoint { snap, pos, last_h });
3776 }
3777 (s, a) => {
3778 *slot = None; // a stale checkpoint would rewind to the WRONG boundary
3779 if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
3780 let err = s.err().map(|e| e.to_string())
3781 .or_else(|| a.err().map(|e| e.to_string()))
3782 .unwrap_or_default();
3783 eprintln!("[spec] turn checkpoint skipped ({err}); \
3784 next turn re-primes in full");
3785 }
3786 }
3787 }
3788 }
3789 }
3790 // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
3791 // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
3792 // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
3793 // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
3794 let mut last_pred = 0u32;
3795 let mut last_col_logits: Option<CudaSlice<f32>> = None;
3796 // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
3797 // recompute in the grammar-truncation walk — retained host-side, round 0 only.
3798 let mut init_logits_host: Option<Vec<f32>> = None;
3799 let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
3800 let (init_logits, h) = self.decode_step_h(e, last_token, &mut *cache)?;
3801 last_pred = argmax(&init_logits) as u32;
3802 if constraint.is_some() {
3803 init_logits_host = Some(init_logits.clone());
3804 }
3805 // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
3806 if sampled {
3807 last_col_logits = Some(e.htod(&init_logits)?);
3808 }
3809 h
3810 } else {
3811 // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
3812 let lh = sess_tail
3813 .as_ref()
3814 .unwrap()
3815 .1
3816 .as_ref()
3817 .expect("pending carry requires last_h");
3818 e.clone_dtod(lh)?
3819 };
3820 let t_init = t_ent.elapsed();
3821 let mut last_col_stats: Option<(f32, f32, f32)> = None;
3822 // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
3823 // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
3824 // stable pointer for the graph-draft round-start copy.
3825 let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
3826 // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
3827 // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
3828 // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
3829 // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
3830 // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
3831 // overwritten below).
3832 let mut fill_prev = e.clone_dtod(&h_seed0)?;
3833 {
3834 if let Some(ph) = &prompt_h {
3835 let np = prompt.len();
3836 e.copy_view_into(
3837 &mut h_seed_buf,
3838 0,
3839 &ph.slice((np - 1) * n_embd..np * n_embd),
3840 n_embd,
3841 )?;
3842 } else if continuation {
3843 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
3844 if let Some(lh) = lh.as_ref() {
3845 e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
3846 }
3847 }
3848 }
3849 }
3850 // Persistent device prediction slots for the accept walk (max k+1 verify columns).
3851 let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
3852
3853 let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
3854 // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
3855 // the end. Metric normalization vs the reference engine: BOTH engines count
3856 // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
3857 // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
3858 let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
3859 let mut st_drafted = vec![0usize; k];
3860 let mut st_accepted = vec![0usize; k];
3861 let mut st_len_hist = vec![0usize; k + 1];
3862 let mut st_full = 0usize;
3863 // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
3864 // stop the draft chain early when the head's softmax confidence in its own pick drops
3865 // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
3866 static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
3867 let p_min = *PMIN.get_or_init(|| {
3868 std::env::var("MEMRA_SPEC_PMIN")
3869 .ok()
3870 .and_then(|v| v.parse().ok())
3871 .unwrap_or(0.0)
3872 });
3873 // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
3874 // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
3875 // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
3876 // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
3877 // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
3878 // verify batch is not); the j==0 exemption stays for pending-less rounds.
3879 let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
3880 .map(|v| v == "1")
3881 .unwrap_or(false);
3882
3883 // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
3884 // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
3885 // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
3886 // cuBLAS path in an exotic head) falls back to the eager draft chain.
3887 // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
3888 // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
3889 // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
3890 // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
3891 // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
3892 // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
3893 // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
3894 // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
3895 let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
3896 Some(c) => c,
3897 None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
3898 };
3899 // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
3900 // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
3901 if sampled && dctx.g_q.len() < d_vocab {
3902 dctx.g_q = e.zeros(d_vocab)?;
3903 dctx.g_perturb = e.zeros(d_vocab)?;
3904 }
3905 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
3906 // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
3907 // truncation (the correctness backstop) stops cutting every tight-schema round.
3908 // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
3909 // shape, so a parked graph of the other shape is dropped and recaptured.
3910 let dmask_on = constraint.as_deref().is_some_and(|c| c.draft_mask_enabled());
3911 let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
3912 if dmask_on && dctx.g_dmask.len() < dmask_words {
3913 dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
3914 dctx.graph = None; // the old capture baked the old (or no) mask pointer
3915 dctx.failed.clear_greedy();
3916 dctx.keeper.clear();
3917 }
3918 if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
3919 dctx.graph = None;
3920 dctx.failed.clear_greedy();
3921 dctx.keeper.clear();
3922 }
3923 if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
3924 let DraftGraphCtx { g_tok, g_pos, g_seed, g_p, g_dmask, .. } = &mut dctx;
3925 // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
3926 // host uploads the position's real words, so the warmups stay grammar-free.
3927 if dmask_on {
3928 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
3929 }
3930 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
3931 // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
3932 // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
3933 // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
3934 // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
3935 // passes (and, in serve, other sessions) recycle those addresses and the replay then
3936 // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
3937 let cap_res = e.capture_graph_retained(|e| {
3938 self.mtp_head_forward_cap(
3939 e,
3940 mtp,
3941 g_tok,
3942 g_pos,
3943 g_seed,
3944 g_p,
3945 &mut *scratch,
3946 p_min > 0.0,
3947 true,
3948 embd_gpu.expect("graph draft requires resident embedding"),
3949 embd_qt,
3950 embd_rb,
3951 d_vocab,
3952 None,
3953 None,
3954 if dmask_on { Some((g_dmask_ro, dmask_words)) } else { None },
3955 )
3956 });
3957 match cap_res {
3958 Ok((g, keep)) => {
3959 scratch.set_len(e, base)?;
3960 dctx.graph = Some(g);
3961 dctx.graph_masked = dmask_on;
3962 dctx.keeper = keep;
3963 }
3964 Err(err) => {
3965 scratch.set_len(e, base)?;
3966 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
3967 // silent. Once per flip — mark returns None on an already-failed ctx.
3968 if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
3969 eprintln!("{line}");
3970 }
3971 }
3972 }
3973 }
3974 // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
3975 // graph object, built only when sampled && graph-eligible — the greedy capture above is
3976 // untouched (and skipped when sampled: its graph would never be launched). Same head
3977 // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
3978 // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
3979 // once per round); the raw head logits land in the persistent g_q for the host's
3980 // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
3981 // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
3982 // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
3983 // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
3984 // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
3985 // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
3986 // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
3987 // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
3988 // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
3989 // this compare misses at most ONCE per resumed request — the first burst recaptures
3990 // and every later burst in that request replays. A client that wants the parked graph
3991 // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
3992 // stable across its whole conversation.
3993 // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
3994 // softmax — it can hold neither per-row filter stats nor the varying penalty history.
3995 // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
3996 // force the eager draft (which computes stats/penalties per row).
3997 let pure_temp = sp.top_k == 0 && sp.top_p >= 1.0 && sp.min_p <= 0.0 && !pen_on;
3998 let s_key = (sp_seed, sp_temp.to_bits(), k);
3999 if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
4000 dctx.graph_s = None;
4001 dctx.failed.clear_sampled();
4002 dctx.s_key = None;
4003 dctx.q_slots.clear();
4004 dctx.keeper_s.clear();
4005 }
4006 if graph_draft && sampled && pure_temp && dctx.graph_s.is_none()
4007 && !dctx.failed.sampled_failed()
4008 {
4009 let DraftGraphCtx { g_tok, g_pos, g_seed, g_p, g_ctr, g_perturb, g_q, .. } = &mut dctx;
4010 // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
4011 let cap_res = e.capture_graph_retained(|e| {
4012 self.mtp_head_forward_cap(
4013 e,
4014 mtp,
4015 g_tok,
4016 g_pos,
4017 g_seed,
4018 g_p,
4019 &mut *scratch,
4020 p_min > 0.0,
4021 true,
4022 embd_gpu.expect("graph draft requires resident embedding"),
4023 embd_qt,
4024 embd_rb,
4025 d_vocab,
4026 Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
4027 None,
4028 None, // constrained spec is greedy-only — sampled never carries a hook
4029 )
4030 });
4031 match cap_res {
4032 Ok((g, keep)) => {
4033 scratch.set_len(e, base)?;
4034 for _ in 0..k {
4035 dctx.q_slots.push(e.zeros(d_vocab)?);
4036 }
4037 dctx.graph_s = Some(g);
4038 dctx.s_key = Some(s_key);
4039 dctx.keeper_s = keep;
4040 }
4041 Err(err) => {
4042 scratch.set_len(e, base)?;
4043 // LOUD flip (audit Q2): same contract as the greedy capture above.
4044 if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
4045 eprintln!("{line}");
4046 }
4047 }
4048 }
4049 }
4050 let t_cap = t_ent.elapsed();
4051 // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
4052 // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
4053 // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
4054 // fill: the first chain step processes it and appends its entry at slot prompt.len().
4055 if let Some(ph) = &prompt_h {
4056 // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
4057 // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
4058 // global positions [base..base+tp). Fresh call: base==0, identical to before.
4059 scratch.set_len(e, base)?;
4060 // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
4061 // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
4062 // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
4063 // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
4064 let fill_chunk: usize = std::env::var("MEMRA_PRIME_CHUNK")
4065 .ok()
4066 .and_then(|v| v.parse().ok())
4067 .unwrap_or(4096);
4068 let tp = prompt.len();
4069 let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
4070 let mut start = 0usize;
4071 while start < tp {
4072 let end = (start + fill_chunk).min(tp);
4073 let tc = end - start;
4074 {
4075 // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
4076 // reference engine's initial pending-h is zeroed too); a session turn's row 0
4077 // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
4078 // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
4079 let mut phs = e.zeros(tc * n_embd)?;
4080 let (src_lo, dst_off) = if start == 0 {
4081 (0, n_embd)
4082 } else {
4083 ((start - 1) * n_embd, 0)
4084 };
4085 let n_copy = if start == 0 {
4086 (tc - 1) * n_embd
4087 } else {
4088 tc * n_embd
4089 };
4090 if start == 0 {
4091 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
4092 if let Some(lh) = lh.as_ref() {
4093 e.copy_into(&mut phs, 0, lh, n_embd)?;
4094 }
4095 }
4096 }
4097 if n_copy > 0 {
4098 e.copy_view_into(
4099 &mut phs,
4100 dst_off,
4101 &ph.slice(src_lo..src_lo + n_copy),
4102 n_copy,
4103 )?;
4104 }
4105 self.mtp_kv_fill(
4106 e,
4107 mtp,
4108 &prompt[start..end],
4109 &phs,
4110 base + start,
4111 &mut *scratch,
4112 embd_dev,
4113 )?;
4114 }
4115 start = end;
4116 }
4117 }
4118 // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
4119 // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
4120 // (=1 brackets the whole call in run_spec.rs, prime included.)
4121 if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
4122 unsafe extern "C" {
4123 fn cudaProfilerStart() -> i32;
4124 }
4125 unsafe {
4126 cudaProfilerStart();
4127 }
4128 }
4129 // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
4130 // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
4131 // consume each other's device outputs; the host drains the ring every M rounds. v1
4132 // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
4133 // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
4134 // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
4135 // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
4136 // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
4137 let stream_on = crate::spec::spec_stream()
4138 && !sampled
4139 && !spec_replay
4140 && constraint.is_none()
4141 && !session_mode
4142 && embd_gpu.is_some()
4143 && !crate::model::full_prec_enabled()
4144 && k + 2 < 96;
4145 let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
4146 let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
4147 if stream_on {
4148 let cap = e.capture_graph(|e| {
4149 for j in 0..k.max(1) {
4150 self.mtp_head_forward_cap(
4151 e,
4152 mtp,
4153 &mut dctx.g_tok,
4154 &mut dctx.g_pos,
4155 &mut dctx.g_seed,
4156 &mut dctx.g_p,
4157 &mut *scratch,
4158 true,
4159 true,
4160 embd_gpu.expect("round stream requires resident embedding"),
4161 embd_qt,
4162 embd_rb,
4163 d_vocab,
4164 None,
4165 Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
4166 None, // round-stream requires constraint.is_none() (see stream_on)
4167 )?;
4168 }
4169 Ok(())
4170 });
4171 match cap {
4172 Ok(g) => {
4173 scratch.set_len(e, 0)?;
4174 stream_graph = Some(g);
4175 }
4176 Err(err) => {
4177 scratch.set_len(e, 0)?;
4178 if debug_spec {
4179 eprintln!("[spec] stream-graph capture failed ({err}); stream off");
4180 }
4181 }
4182 }
4183 }
4184 let stream_active = stream_on && stream_graph.is_some();
4185 if debug_spec {
4186 eprintln!("[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
4187 crate::spec::spec_stream(), dctx.graph.is_some(), stream_graph.is_some());
4188 }
4189 let t_v_s = k + 1;
4190 // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
4191 // module (extracted 2026-07-12; the gemma burst reuses them).
4192 let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
4193 let crate::round_stream::StreamBufs {
4194 mut vtok_d,
4195 mut brk_d,
4196 mut pend_d,
4197 last_pred_d,
4198 mut pos_ctr,
4199 mut pos_start_d,
4200 mut ring_d,
4201 acc_d: mut stream_acc,
4202 m_rounds,
4203 k: _,
4204 } = sb;
4205 let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
4206 Some(crate::round_stream::kv_len_ptr_table(
4207 e,
4208 cache,
4209 Some(&pos_ctr),
4210 )?)
4211 } else {
4212 None
4213 };
4214
4215 let t_fill = t_ent.elapsed();
4216 let mut round = 0usize;
4217 // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
4218 // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
4219 // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
4220 // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
4221 // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
4222 // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
4223 // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
4224 // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
4225 // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
4226 // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
4227 // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
4228 // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
4229 // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
4230 // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
4231 // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
4232 // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
4233 // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
4234 // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
4235 // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
4236 // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
4237 // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
4238 // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
4239 // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
4240 // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
4241 // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
4242 // K=1..8 self-consistency PASS both models with the law ON (exactness held).
4243 let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
4244 // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
4245 // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
4246 let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
4247 .ok()
4248 .and_then(|v| v.parse().ok());
4249 let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
4250 4
4251 } else if self.cfg.n_embd as usize >= 2500 {
4252 2
4253 } else {
4254 1
4255 };
4256 let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
4257 // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
4258 // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
4259 // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
4260 let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
4261 .ok()
4262 .and_then(|v| v.parse().ok())
4263 .unwrap_or(1024);
4264 let floor_at = |pos: usize| -> usize {
4265 if adapt_floor_env.is_some() || pos < floor_ctx {
4266 adapt_floor
4267 } else if adapt_floor >= 4 {
4268 1
4269 } else {
4270 adapt_floor
4271 }
4272 };
4273 // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
4274 // fixed-K default path is untouched by this whole block.
4275 let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
4276 .ok()
4277 .and_then(|v| v.parse().ok())
4278 .unwrap_or(7);
4279 let k_cap = k.min(cap_max).max(1);
4280 let mut kc = k_cap;
4281 // PERSISTENT snapshot buffers: allocate ONCE, refresh in place each round (was 2 fresh
4282 // D2D clones per linear layer per round = 48 allocs + ~50MB of pool churn per round).
4283 let mut snap = cache.snapshot(e)?;
4284 // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
4285 // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
4286 let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
4287 Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
4288 } else {
4289 None
4290 };
4291 // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
4292 // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
4293 // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
4294 // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
4295 // pass of any kind). Verify still
4296 // checks every emitted token against the target -> exactness holds by construction; only
4297 // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
4298 // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
4299 // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
4300 let mut pending: Option<u32> = carried_pending;
4301 // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
4302 // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
4303 // the verify accept readback). Printed once at loop end via spec-stats.
4304 let phase_on = std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
4305 // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
4306 // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
4307 let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
4308 // grammar-truncation counters: how many rounds the verify-side cut fired and how many
4309 // already-verified tokens it threw away. THIS is the quantity draft masking targets.
4310 let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
4311 let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
4312 let mut ph_wait = 0f64;
4313 let mut ph_t = std::time::Instant::now();
4314 let mut ph_mark = |acc: &mut f64, on: bool| {
4315 if on {
4316 let now = std::time::Instant::now();
4317 *acc += (now - ph_t).as_secs_f64();
4318 ph_t = now;
4319 }
4320 };
4321 while keep_going && out.len() < max_new {
4322 // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
4323 // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
4324 if let (true, Some(sg), Some(ptrs)) = (
4325 stream_active && round >= 1 && pending.is_some(),
4326 &stream_graph,
4327 &stream_ptrs,
4328 ) {
4329 if debug_spec {
4330 static ONCE: std::sync::Once = std::sync::Once::new();
4331 ONCE.call_once(|| {
4332 eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
4333 });
4334 }
4335 e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
4336 e.set_u32_one(&mut pend_d, pending.unwrap())?;
4337 e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
4338 for _mi in 0..m_rounds {
4339 e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
4340 cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
4341 e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
4342 e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
4343 e.u32_copy(&pend_d, &mut dctx.g_tok)?;
4344 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
4345 sg.launch()?;
4346 e.spec_assemble_verify(
4347 &g_tokp2k,
4348 &pend_d,
4349 d2t_dev.as_ref(),
4350 &mut vtok_d,
4351 &mut brk_d,
4352 p_min,
4353 k,
4354 pmin0,
4355 )?;
4356 let mut ck = VerifyCkpt::new(self.layers.len());
4357 let dummy = vec![0u32; t_v_s];
4358 let (tl_d, vx) = self.decode_step_t_core_stream(
4359 e,
4360 &dummy,
4361 0,
4362 &mut *cache,
4363 embd_dev,
4364 Some(&mut ck),
4365 Some((&vtok_d, &pos_ctr)),
4366 )?;
4367 for j in 0..t_v_s {
4368 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
4369 }
4370 e.spec_accept_greedy_dc(
4371 &preds_d,
4372 &vtok_d,
4373 &last_pred_d,
4374 &brk_d,
4375 &mut stream_acc,
4376 )?;
4377 e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
4378 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
4379 self.commit_verified_prefix_stream(
4380 e,
4381 &mut *cache,
4382 &snap,
4383 &ck,
4384 &stream_acc,
4385 1,
4386 t_v_s,
4387 )?;
4388 e.spec_rollback_stream(
4389 ptrs,
4390 &pos_start_d,
4391 &stream_acc,
4392 1,
4393 self.layers.len() + 1,
4394 )?;
4395 e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
4396 }
4397 e.stream().synchronize()?;
4398 let ring_h = e.dtoh_u32(&ring_d)?;
4399 let cnt = ring_h[0] as usize;
4400 for i in 0..cnt {
4401 if out.len() < max_new {
4402 out.push(ring_h[1 + i]);
4403 }
4404 }
4405 let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
4406 for il in 0..self.layers.len() {
4407 if let Some(kvl) = cache.kv[il].as_mut() {
4408 kvl.len = pos_h;
4409 }
4410 }
4411 cache.pos = pos_h;
4412 scratch.kv.len = pos_h;
4413 pending = Some(ring_h[cnt]); // last drained token = the live bonus
4414 last_token = ring_h[cnt];
4415 total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
4416 total_accepted += cnt.saturating_sub(m_rounds);
4417 if let Some(t) = sess_telem.as_deref_mut() {
4418 // totals only — the burst's per-round accept counts stayed on device
4419 // (that is the point of the round-stream arm). pos_* untouched.
4420 t.rounds += m_rounds as u64;
4421 t.drafted += (k * m_rounds) as u64;
4422 t.accepted += cnt.saturating_sub(m_rounds) as u64;
4423 }
4424 round += m_rounds;
4425 // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
4426 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
4427 continue;
4428 }
4429 let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
4430 cache.snapshot_into(e, &mut snap)?; // §C: snapshot BEFORE draft+verify
4431 ph_mark(&mut ph_rest, phase_on);
4432
4433 // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
4434 // p-min semantics (both paths): stop the chain early when the head's confidence in
4435 // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
4436 // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
4437 let base0 = if pending.is_some() { 1usize } else { 0usize };
4438 // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
4439 // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
4440 // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
4441 // rejected drafts and p-min extras via the len mechanism).
4442 scratch.set_len(e, pos + base0 - 1)?;
4443 if pen_on {
4444 let w0 = pen_hist.len().saturating_sub(sp.penalty_last_n);
4445 pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
4446 }
4447 // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
4448 // accepted run + 1 (the gemma law — see the setup block above the loop).
4449 let k_this = if adapt { kc } else { k };
4450 let mut draft: Vec<u32> = Vec::with_capacity(k);
4451 let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
4452 if sampled {
4453 draft_logits.clear();
4454 draft_stats.clear();
4455 }
4456 // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
4457 // position's mask is computed on that clone and advanced by the PROPOSED token. The
4458 // real state moves only on emission (verify's job), so the emitted stream is
4459 // unchanged — the mask only removes tokens the verify would have truncated anyway.
4460 let mut dmask_live = dmask_on;
4461 if dmask_live {
4462 let t_c = std::time::Instant::now();
4463 constraint
4464 .as_deref_mut()
4465 .unwrap()
4466 .draft_begin()
4467 .map_err(|e2| format!("constraint: {e2}"))?;
4468 dm_clone_ns += t_c.elapsed().as_nanos();
4469 dm_rounds += 1;
4470 }
4471 if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
4472 // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
4473 // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
4474 // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
4475 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
4476 e.set_u32_one(&mut dctx.g_tok, last_token)?;
4477 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
4478 for j in 0..k_this {
4479 // per-position mask upload (contents only — the graph's baked pointer is
4480 // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
4481 // mask node degrades to a no-op ban instead of needing a second graph.
4482 if dmask_live
4483 && !upload_draft_mask(
4484 e,
4485 constraint.as_deref_mut().unwrap(),
4486 &mut dctx.g_dmask,
4487 mtp.d2t.as_ref(),
4488 d_vocab,
4489 dmask_words,
4490 )?
4491 {
4492 // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
4493 // genuinely miss the legal set): neutralize the captured mask node and
4494 // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
4495 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
4496 dmask_live = false;
4497 }
4498 gr.launch()?;
4499 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
4500 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
4501 // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
4502 // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
4503 // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
4504 // replay's embed node, and the MMU fault kills the CUDA context for the
4505 // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
4506 // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
4507 // buffer (g_seed = the verify-side handoff vs head-side compute).
4508 if (idx as usize) >= d_vocab {
4509 // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
4510 // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
4511 // seed, untouched since the round-start copy — the pair discriminates
4512 // "seed arrived poisoned" from "head forward produced NaN".
4513 let seed_h = e.dtoh(&dctx.g_seed)?;
4514 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
4515 let in_h = e.dtoh(&h_seed_buf)?;
4516 let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
4517 return Err(format!(
4518 "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
4519 round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
4520 round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
4521 the embed row (#87 trap)"
4522 )
4523 .into());
4524 }
4525 // trimmed draft vocab -> target token id (identity when no d2t map)
4526 let d = match &mtp.d2t {
4527 Some(map) => map[idx as usize],
4528 None => idx,
4529 };
4530 if p_min > 0.0 {
4531 let p = e.dtoh(&dctx.g_p)?[0];
4532 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
4533 break;
4534 }
4535 }
4536 draft.push(d);
4537 // with a trimmed head the NEXT embed must read the TARGET id, not the draft
4538 // index the argmax wrote — patch the persistent token buffer (4B htod).
4539 if d != idx {
4540 e.set_u32_one(&mut dctx.g_tok, d)?;
4541 }
4542 // advance the SPECULATIVE state with the proposal; a dead chain drops to
4543 // unmasked drafting for the remaining positions (verify still arbitrates).
4544 // speculative advance; a chain the grammar can no longer follow (EOS
4545 // proposed) ends here. The captured mask node always runs, so a dead chain
4546 // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
4547 if dmask_live
4548 && !constraint
4549 .as_deref_mut()
4550 .unwrap()
4551 .draft_advance(d)
4552 .map_err(|e2| format!("constraint: {e2}"))?
4553 {
4554 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
4555 break;
4556 }
4557 }
4558 } else if let (true, Some(gr)) = (sampled, &dctx.graph_s) {
4559 // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
4560 // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
4561 // and decides the break. Event-counter continuity: g_ctr is host-seeded to
4562 // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
4563 // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
4564 // stream. Host sctr advances in lockstep (computed, no readback needed).
4565 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
4566 e.set_u32_one(&mut dctx.g_tok, last_token)?;
4567 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
4568 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
4569 for j in 0..k_this {
4570 gr.launch()?;
4571 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
4572 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
4573 // counts the p-min-discarded token too)
4574 // q retention: ONE async D2D of the persistent head-logits buffer into this
4575 // round's slot j (stream-ordered after the replay, before the next one).
4576 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
4577 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
4578 // #87 SENTINEL TRAP (see the greedy graph arm above).
4579 if (idx as usize) >= d_vocab {
4580 let seed_h = e.dtoh(&dctx.g_seed)?;
4581 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
4582 return Err(format!(
4583 "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
4584 {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
4585 {seed_nan}/{n_embd} — refusing to dereference the embed row \
4586 (#87 trap)"
4587 )
4588 .into());
4589 }
4590 let d = match &mtp.d2t {
4591 Some(map) => map[idx as usize],
4592 None => idx,
4593 };
4594 draft_idx.push(idx);
4595 if p_min > 0.0 {
4596 let p = e.dtoh(&dctx.g_p)?[0];
4597 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
4598 break;
4599 }
4600 }
4601 draft.push(d);
4602 // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
4603 if d != idx {
4604 e.set_u32_one(&mut dctx.g_tok, d)?;
4605 }
4606 }
4607 // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
4608 // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
4609 for j in 0..draft.len().max(draft_idx.len()) {
4610 let rows0 = e.htod_i32(&[0])?;
4611 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
4612 e.filter_stats(
4613 &dctx.q_slots[j],
4614 d_vocab,
4615 &rows0,
4616 &mut th_d,
4617 &mut z_d,
4618 &mut mx_d,
4619 d_vocab,
4620 1,
4621 sp_temp,
4622 sp.top_k,
4623 sp.top_p,
4624 sp.min_p,
4625 )?;
4626 draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
4627 }
4628 } else {
4629 // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
4630 let mut e_tok = last_token;
4631 let mut d_seed = e.clone_dtod(&h_seed_buf)?;
4632 for j in 0..k_this {
4633 // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
4634 // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
4635 let mtp_pos = pos + base0 + j;
4636 // draft-side grammar mask (eager twin of the graph arm's in-graph node).
4637 // A position with no legal draft-vocab row drops to unmasked drafting for
4638 // the rest of the chain (pre-lane behaviour; verify still arbitrates).
4639 if dmask_live {
4640 dmask_live = upload_draft_mask(
4641 e,
4642 constraint.as_deref_mut().unwrap(),
4643 &mut dctx.g_dmask,
4644 mtp.d2t.as_ref(),
4645 d_vocab,
4646 dmask_words,
4647 )?;
4648 }
4649 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
4650 e,
4651 mtp,
4652 e_tok,
4653 &d_seed,
4654 &mut *scratch,
4655 mtp_pos,
4656 embd_dev,
4657 if dmask_live { Some((&dctx.g_dmask, dmask_words)) } else { None },
4658 )?;
4659 let tok_d = if sampled {
4660 // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
4661 // the filtered softmax (filters off => th=0, exact v1 semantics).
4662 if perturb_buf.is_none() {
4663 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
4664 }
4665 let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
4666 if pen_on {
4667 let h = pen_hist_d.as_ref().unwrap();
4668 let nh = h.len();
4669 e.penalize_logits(
4670 &mut q_row,
4671 h,
4672 nh,
4673 sp.penalty_repeat,
4674 sp.penalty_freq,
4675 sp.penalty_present,
4676 d_vocab,
4677 )?;
4678 }
4679 let rows0 = e.htod_i32(&[0])?;
4680 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
4681 e.filter_stats(
4682 &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab, 1,
4683 sp_temp, sp.top_k, sp.top_p, sp.min_p,
4684 )?;
4685 let (th, z, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
4686 let pb = perturb_buf.as_mut().unwrap();
4687 e.gumbel_perturb_filtered(
4688 &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
4689 )?;
4690 sctr += 1;
4691 draft_logits.push(q_row);
4692 draft_stats.push((mx, th, z));
4693 e.argmax_token_device(pb, d_vocab)?
4694 } else {
4695 e.argmax_token_device(&dl_d, d_vocab)?
4696 };
4697 let idx = e.dtoh_u32_one(&tok_d)?;
4698 // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
4699 // here because the eager chain's operands are all readable: dl_d (the head
4700 // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
4701 if (idx as usize) >= d_vocab {
4702 let dl_h = e.dtoh(&dl_d)?;
4703 let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
4704 let seed_h = e.dtoh(&d_seed)?;
4705 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
4706 return Err(format!(
4707 "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
4708 round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
4709 step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
4710 embed row (#87 trap)"
4711 )
4712 .into());
4713 }
4714 let d = match &mtp.d2t {
4715 Some(map) => map[idx as usize],
4716 None => idx,
4717 };
4718 if sampled {
4719 draft_idx.push(idx);
4720 }
4721 if p_min > 0.0 {
4722 let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
4723 let p = e.dtoh(&p_d)?[0];
4724 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
4725 break;
4726 }
4727 }
4728 draft.push(d);
4729 e_tok = d;
4730 d_seed = h_nextn;
4731 // speculative advance; a chain the grammar can no longer follow (EOS
4732 // proposed) ends here — the prefix already proposed still rides verify.
4733 if dmask_live
4734 && !constraint
4735 .as_deref_mut()
4736 .unwrap()
4737 .draft_advance(d)
4738 .map_err(|e2| format!("constraint: {e2}"))?
4739 {
4740 break;
4741 }
4742 }
4743 }
4744 let k_round = draft.len();
4745
4746 ph_mark(&mut ph_draft, phase_on);
4747 // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
4748 // (committing its KV/recur inside the SAME weight read); drafts follow. ---
4749 let verify_tokens: Vec<u32> = match pending {
4750 Some(b) => {
4751 let mut v = Vec::with_capacity(k_round + 1);
4752 v.push(b);
4753 v.extend_from_slice(&draft);
4754 v
4755 }
4756 None => draft.clone(),
4757 };
4758 let base = if pending.is_some() { 1 } else { 0 };
4759 // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
4760 // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
4761 let mut ckpt = if spec_replay {
4762 None
4763 } else {
4764 Some(VerifyCkpt::new(self.layers.len()))
4765 };
4766 let (tlogits_d, vx) = self.decode_step_t_core(
4767 e,
4768 &verify_tokens,
4769 pos,
4770 &mut *cache,
4771 embd_dev,
4772 ckpt.as_mut(),
4773 )?;
4774
4775 ph_mark(&mut ph_verify, phase_on);
4776 // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
4777 // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
4778 // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
4779 // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
4780 // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
4781 // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
4782 // (== the bonus), so every index shifts by `base` and last_pred is unused.
4783 let t_v = verify_tokens.len();
4784 let mut preds: Vec<u32> = Vec::new();
4785 if !sampled {
4786 for j in 0..t_v {
4787 e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
4788 }
4789 preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
4790 // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
4791 // next round's last_token = the next chain's embed lookup. Catch it at the
4792 // source with the column named — an all-NaN VERIFY column implicates the
4793 // stage-split trunk (decode_step_t_core_ppn), not the draft head.
4794 if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
4795 let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
4796 let mut probe = e.zeros(n_vocab)?;
4797 e.copy_view_into(&mut probe, 0, col, n_vocab)?;
4798 let col_h = e.dtoh(&probe)?;
4799 let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
4800 return Err(format!(
4801 "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
4802 col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
4803 — the stage-split verify produced a poisoned column (#87 trap)",
4804 preds[bad]
4805 )
4806 .into());
4807 }
4808 }
4809 ph_mark(&mut ph_wait, phase_on);
4810 let t_pred = |j: usize| -> u32 {
4811 if j == 0 && base == 0 {
4812 last_pred
4813 } else {
4814 preds[base + j - 1]
4815 }
4816 };
4817 let mut devacc_seeded = false;
4818 let mut devacc_acc: Option<CudaSlice<u32>> = None;
4819 let (n_acc, bonus) = if !sampled {
4820 // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
4821 // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
4822 // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
4823 // gated on token identity vs the host walk (the arms below are bit-equal rules).
4824 if crate::spec::spec_devacc() && k_round > 0 && !spec_replay
4825 && constraint.is_none() {
4826 let draft_d = e.htod_u32_v(&draft)?;
4827 let mut acc_out = e.alloc_u32_zeroed(2)?;
4828 e.spec_accept_greedy(
4829 &preds_d,
4830 &draft_d,
4831 last_pred,
4832 base,
4833 k_round,
4834 &mut acc_out,
4835 )?;
4836 devacc_acc = Some(acc_out.clone());
4837 // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
4838 // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
4839 // non-replay commit arms skip their host-offset seed copies (guarded below);
4840 // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
4841 // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
4842 // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
4843 // the update lands after the arms (devacc_seeded guard below).
4844 e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
4845 // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
4846 // unified rule; full accept rewrites the verify-left value). Host mirrors
4847 // update after the readback; commit_verified_prefix skips its len_d writes.
4848 if let Some(ptrs) = &kv_len_ptrs {
4849 let saved: Vec<i32> = (0..self.layers.len())
4850 .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
4851 .collect();
4852 let saved_d = e.htod_i32(&saved)?;
4853 e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
4854 }
4855 devacc_seeded = true;
4856 let ab = e.dtoh_u32(&acc_out)?;
4857 (ab[0] as usize, ab[1])
4858 } else {
4859 let mut n_acc = 0usize;
4860 for j in 0..k_round {
4861 if t_pred(j) == draft[j] {
4862 n_acc += 1;
4863 } else {
4864 break;
4865 }
4866 }
4867 // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
4868 // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
4869 (n_acc, t_pred(n_acc))
4870 }
4871 } else {
4872 // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
4873 if col_buf.is_none() {
4874 col_buf = Some(e.zeros(n_vocab)?);
4875 }
4876 // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
4877 // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
4878 let mut pj = vec![0f32; k_round.max(1)];
4879 let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
4880 if k_round > 0 {
4881 let mut ids: Vec<u32> = Vec::new();
4882 let mut rows: Vec<i32> = Vec::new();
4883 for j in 0..k_round {
4884 if j > 0 || base == 1 {
4885 ids.push(draft[j]);
4886 rows.push((base + j) as i32 - 1);
4887 }
4888 }
4889 if !ids.is_empty() {
4890 let nr = rows.len();
4891 // penalties: materialize the used columns into one contiguous penalized
4892 // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
4893 // penalties: materialize used columns contiguously, penalize all rows in
4894 // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
4895 let p_rows: Vec<i32> = if pen_on {
4896 (0..nr as i32).collect()
4897 } else {
4898 rows.clone()
4899 };
4900 if pen_on {
4901 if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
4902 pcol_buf = Some(e.zeros(nr * n_vocab)?);
4903 }
4904 let pc = pcol_buf.as_mut().unwrap();
4905 for (i2, &r) in rows.iter().enumerate() {
4906 let c = r as usize;
4907 e.copy_view_into(
4908 pc,
4909 i2 * n_vocab,
4910 &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
4911 n_vocab,
4912 )?;
4913 }
4914 let h = pen_hist_d.as_ref().unwrap();
4915 let nh = h.len();
4916 e.penalize_logits_rows(
4917 pc,
4918 h,
4919 nh,
4920 sp.penalty_repeat,
4921 sp.penalty_freq,
4922 sp.penalty_present,
4923 n_vocab,
4924 nr,
4925 )?;
4926 }
4927 let p_src: &CudaSlice<f32> = if pen_on {
4928 pcol_buf.as_ref().unwrap()
4929 } else {
4930 &tlogits_d
4931 };
4932 let rowsd = e.htod_i32(&p_rows)?;
4933 let (mut th_d, mut z_d, mut mx_d) =
4934 (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
4935 e.filter_stats(
4936 p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
4937 sp_temp, sp.top_k, sp.top_p, sp.min_p,
4938 )?;
4939 let idsd = e.htod_u32_v(&ids)?;
4940 let mut outd = e.zeros(nr)?;
4941 e.softmax_gather_filtered(
4942 p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
4943 sp_temp,
4944 )?;
4945 let outv = e.dtoh(&outd)?;
4946 let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
4947 let mut oi = 0usize;
4948 for j in 0..k_round {
4949 if j > 0 || base == 1 {
4950 pj[j] = outv[oi];
4951 oi += 1;
4952 }
4953 }
4954 col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
4955 }
4956 if base == 0 {
4957 let lc: &CudaSlice<f32> = if pen_on {
4958 if col_buf.is_none() {
4959 col_buf = Some(e.zeros(n_vocab)?);
4960 }
4961 let cb = col_buf.as_mut().unwrap();
4962 e.copy_into(
4963 cb,
4964 0,
4965 last_col_logits
4966 .as_ref()
4967 .expect("sampled: last_col_logits unset"),
4968 n_vocab,
4969 )?;
4970 let h = pen_hist_d.as_ref().unwrap();
4971 let nh = h.len();
4972 e.penalize_logits(
4973 cb,
4974 h,
4975 nh,
4976 sp.penalty_repeat,
4977 sp.penalty_freq,
4978 sp.penalty_present,
4979 n_vocab,
4980 )?;
4981 col_buf.as_ref().unwrap()
4982 } else {
4983 last_col_logits
4984 .as_ref()
4985 .expect("sampled: last_col_logits unset")
4986 };
4987 let rows0 = e.htod_i32(&[0])?;
4988 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
4989 e.filter_stats(
4990 lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
4991 sp_temp, sp.top_k, sp.top_p, sp.min_p,
4992 )?;
4993 let idsd = e.htod_u32_v(&[draft[0]])?;
4994 let mut outd = e.zeros(1)?;
4995 e.softmax_gather_filtered(
4996 lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
4997 )?;
4998 pj[0] = e.dtoh(&outd)?[0];
4999 last_col_stats =
5000 Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
5001 }
5002 }
5003 // q source: the graph arm retained the head logits in the persistent q_slots;
5004 // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
5005 // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
5006 // computes them post-replay — graph engages only filter/penalty-free, so the
5007 // stats degenerate to th=0/full-Z there, keeping ONE accept path).
5008 let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
5009 &dctx.q_slots
5010 } else {
5011 &draft_logits
5012 };
5013 let mut n_acc = 0usize;
5014 for j in 0..k_round {
5015 let (qmx, qth, qz) = draft_stats[j];
5016 let idsd = e.htod_u32_v(&[draft_idx[j]])?;
5017 let rowsd = e.htod_i32(&[0])?;
5018 let thd = e.htod(&[qth])?;
5019 let zd = e.htod(&[qz])?;
5020 let _ = qmx;
5021 let mut outd = e.zeros(1)?;
5022 e.softmax_gather_filtered(
5023 &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
5024 sp_temp,
5025 )?;
5026 let qj = e.dtoh(&outd)?[0];
5027 let u = host_u01(sp_seed, uctr);
5028 uctr += 1;
5029 if (u as f64) * (qj as f64) < pj[j] as f64 {
5030 n_acc += 1;
5031 } else {
5032 break;
5033 }
5034 }
5035 let bonus = if n_acc == k_round {
5036 // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
5037 let col = base + k_round - 1;
5038 let cb = col_buf.as_mut().unwrap();
5039 e.copy_view_into(
5040 cb,
5041 0,
5042 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
5043 n_vocab,
5044 )?;
5045 if pen_on {
5046 let h = pen_hist_d.as_ref().unwrap();
5047 let nh = h.len();
5048 e.penalize_logits(
5049 cb,
5050 h,
5051 nh,
5052 sp.penalty_repeat,
5053 sp.penalty_freq,
5054 sp.penalty_present,
5055 n_vocab,
5056 )?;
5057 }
5058 if perturb_buf.is_none() {
5059 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
5060 }
5061 // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
5062 // truncation-fix; receipts research/sampfix-20260805/). The old code reused
5063 // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
5064 // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
5065 // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
5066 // last gathered column, in both base arms. `th` is a threshold in e-units of
5067 // its OWN row's max, so feeding a neighbour's (row_max, th) into
5068 // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
5069 // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
5070 // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
5071 // falls through to its smallest-index tie-break => token id 0 ("!") spliced
5072 // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
5073 // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
5074 // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
5075 // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
5076 // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
5077 // and row_max is unused once nothing is masked), so this fix is a byte-level
5078 // no-op for the untruncated serve default. One extra one-block filter_stats
5079 // per full-accept round is the whole cost.
5080 let (mx, th) = {
5081 let rows0 = e.htod_i32(&[0])?;
5082 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
5083 let cb0 = col_buf.as_ref().unwrap();
5084 e.filter_stats(
5085 cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
5086 sp_temp, sp.top_k, sp.top_p, sp.min_p,
5087 )?;
5088 (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
5089 };
5090 let pb = perturb_buf.as_mut().unwrap();
5091 let cb2 = col_buf.as_ref().unwrap();
5092 e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
5093 sctr += 1;
5094 let td = e.argmax_token_device(pb, n_vocab)?;
5095 e.dtoh_u32_one(&td)?
5096 } else {
5097 // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
5098 let cb = col_buf.as_mut().unwrap();
5099 if n_acc > 0 || base == 1 {
5100 let col = base + n_acc - 1;
5101 e.copy_view_into(
5102 cb,
5103 0,
5104 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
5105 n_vocab,
5106 )?;
5107 } else {
5108 let lc = last_col_logits.as_ref().unwrap();
5109 e.copy_into(cb, 0, lc, n_vocab)?;
5110 }
5111 if pen_on {
5112 let h = pen_hist_d.as_ref().unwrap();
5113 let nh = h.len();
5114 e.penalize_logits(
5115 cb,
5116 h,
5117 nh,
5118 sp.penalty_repeat,
5119 sp.penalty_freq,
5120 sp.penalty_present,
5121 n_vocab,
5122 )?;
5123 }
5124 let cb2 = col_buf.as_ref().unwrap();
5125 let sc = sctr;
5126 sctr += 1;
5127 // p-stats for the reject column: from col_stats when the col was gathered,
5128 // else (j==0&&base==0) from last_col_stats.
5129 let p_stats = if n_acc > 0 || base == 1 {
5130 // col index within the gathered set == number of gathered cols before n_acc
5131 let gi = if base == 1 { n_acc } else { n_acc - 1 };
5132 col_stats.get(gi).copied().unwrap_or_else(|| {
5133 (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
5134 })
5135 } else {
5136 last_col_stats.expect("sampled: last_col_stats unset at reject")
5137 };
5138 let q_stats = draft_stats[n_acc];
5139 if let Some(map) = &d2t_dev {
5140 if q_full_buf.is_none() {
5141 q_full_buf = Some(e.zeros(n_vocab)?);
5142 }
5143 let qf = q_full_buf.as_mut().unwrap();
5144 e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
5145 let qf2 = q_full_buf.as_ref().unwrap();
5146 e.residual_sample_filtered(
5147 cb2,
5148 Some(qf2),
5149 n_vocab,
5150 sp_temp,
5151 sp_seed,
5152 sc,
5153 p_stats,
5154 q_stats,
5155 &mut sample_tok,
5156 )?;
5157 } else {
5158 e.residual_sample_filtered(
5159 cb2,
5160 Some(&q_bufs[n_acc]),
5161 n_vocab,
5162 sp_temp,
5163 sp_seed,
5164 sc,
5165 p_stats,
5166 q_stats,
5167 &mut sample_tok,
5168 )?;
5169 }
5170 e.dtoh_u32(&sample_tok)?[0]
5171 };
5172 (n_acc, bonus)
5173 };
5174 // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
5175 // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
5176 // ordering). Walk the accepted drafts through the grammar in commit order; the
5177 // first illegal token truncates acceptance at its slot, and that slot's emission
5178 // is recomputed as the MASKED argmax of the target's own verify column — token-
5179 // identical to constrained plain greedy decode (an unmasked argmax that is
5180 // grammar-legal IS the masked argmax: masking only removes competitors). The
5181 // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
5182 // measured in acceptance numbers, never hidden.
5183 let (n_acc, bonus) = match constraint.as_deref_mut() {
5184 None => (n_acc, bonus),
5185 Some(c) => {
5186 fn ce(e2: String) -> Box<dyn std::error::Error> {
5187 format!("constraint: {e2}").into()
5188 }
5189 let mut na = n_acc;
5190 let mut cut = false;
5191 for (j, &d) in draft.iter().enumerate().take(n_acc) {
5192 if c.is_allowed(d).map_err(ce)? {
5193 c.consume(d).map_err(ce)?;
5194 } else {
5195 na = j;
5196 cut = true;
5197 dm_cut_tokens += n_acc - j;
5198 break;
5199 }
5200 }
5201 if cut {
5202 dm_cuts += 1;
5203 }
5204 let mut bo = bonus;
5205 if cut || !c.is_allowed(bo).map_err(ce)? {
5206 let mut row = if na == 0 && base == 0 {
5207 init_logits_host.clone()
5208 .ok_or("constraint: init logits missing (round-0 cut)")?
5209 } else {
5210 e.dtoh_view(&tlogits_d.slice(
5211 (base + na - 1) * n_vocab..(base + na) * n_vocab))?
5212 };
5213 c.mask_logits(&mut row).map_err(ce)?;
5214 bo = argmax(&row) as u32;
5215 }
5216 c.consume(bo).map_err(ce)?;
5217 (na, bo)
5218 }
5219 };
5220 total_drafted += k_round;
5221 total_accepted += n_acc;
5222 if let Some(t) = sess_telem.as_deref_mut() {
5223 // per-position accept walk (lane/accept-telemetry): host u64 adds on counts
5224 // the round already read back — zero syncs, zero allocation.
5225 t.rounds += 1;
5226 t.drafted += k_round as u64;
5227 t.accepted += n_acc as u64;
5228 for j in 0..k_round.min(SPEC_TELEM_POS) {
5229 t.pos_drafted[j] += 1;
5230 }
5231 for j in 0..n_acc.min(SPEC_TELEM_POS) {
5232 t.pos_accepted[j] += 1;
5233 }
5234 }
5235 if spec_stats {
5236 st_len_hist[k_round] += 1;
5237 for j in 0..k_round {
5238 st_drafted[j] += 1;
5239 }
5240 for j in 0..n_acc {
5241 st_accepted[j] += 1;
5242 }
5243 if n_acc == k_round {
5244 st_full += 1;
5245 }
5246 }
5247
5248 if debug_spec {
5249 eprintln!("[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}", out.len(), t_pred(0));
5250 }
5251
5252 // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
5253 // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
5254 // of them (overshoot past max_new included) or `committed` under-counts the cache rows
5255 // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
5256 // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
5257 for j in 0..n_acc {
5258 if !session_mode && out.len() >= max_new {
5259 break;
5260 }
5261 out.push(draft[j]);
5262 }
5263 if pen_on {
5264 pen_hist.extend_from_slice(&draft[0..n_acc]);
5265 pen_hist.push(bonus);
5266 }
5267 let bonus_emitted = session_mode || out.len() < max_new;
5268 if bonus_emitted {
5269 out.push(bonus);
5270 }
5271 last_token = bonus;
5272
5273 // --- 5. ROLLBACK + advance (§C) ---
5274 if n_acc == k_round {
5275 // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
5276 // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
5277 // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
5278 // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
5279 // last_pred is dead in the pending path (t_pred reads verify col 0).
5280 //
5281 // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
5282 // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
5283 // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
5284 // trunk hidden (the last verify column). set_len first: a p-min break may have
5285 // left one extra chain append at that slot. Partial accepts need NO fill (the
5286 // chain already covered every accepted position; round-start set_len truncates).
5287 let mut vh_seed = e.zeros(n_embd)?;
5288 e.copy_view_into(
5289 &mut vh_seed,
5290 0,
5291 &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
5292 n_embd,
5293 )?;
5294 if refresh {
5295 // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
5296 // overwrite ALL committed positions' scratch entries with K/V from their EXACT
5297 // verify hiddens — the reference engine's mtp_update fills from true hiddens;
5298 // the full stack (vx) is already resident from the verify. Replaces both the
5299 // chain-approximate entries AND the old last-token-only fill. Acceptance-only
5300 // (draft attention quality); exactness stays the verify's job.
5301 scratch.set_len(e, pos)?;
5302 // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
5303 // (hidden of the last committed row before this verify batch).
5304 let mut vxs = e.zeros(t_v * n_embd)?;
5305 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
5306 if t_v > 1 {
5307 e.copy_view_into(
5308 &mut vxs,
5309 n_embd,
5310 &vx.slice(0..(t_v - 1) * n_embd),
5311 (t_v - 1) * n_embd,
5312 )?;
5313 }
5314 self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
5315 } else {
5316 scratch.set_len(e, pos + base + k_round - 1)?;
5317 // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
5318 let mut hp = e.zeros(n_embd)?;
5319 if t_v >= 2 {
5320 e.copy_view_into(
5321 &mut hp,
5322 0,
5323 &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
5324 n_embd,
5325 )?;
5326 } else {
5327 e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
5328 }
5329 self.mtp_kv_fill(
5330 e,
5331 mtp,
5332 &[draft[k_round - 1]],
5333 &hp,
5334 pos + base + k_round - 1,
5335 &mut *scratch,
5336 embd_dev,
5337 )?;
5338 }
5339 // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
5340 // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
5341 // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
5342 // col). Saves one MTP-block pass per round on top of the pairing fix.
5343 if !devacc_seeded {
5344 e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
5345 e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
5346 }
5347 pending = Some(bonus);
5348 if debug_spec {
5349 eprintln!(" -> FULL ACCEPT (bonus pending, prev-h seed)");
5350 }
5351 } else if !spec_replay && base + n_acc >= 1 {
5352 // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
5353 // the verify's first j = base+n_acc columns ARE the committed sequence, computed
5354 // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
5355 // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
5356 // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
5357 // full-accept path — the legacy duplicate trunk replay is gone. The next chain
5358 // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
5359 // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
5360 // accept (never compounds: the next verify recomputes true hiddens for all
5361 // committed columns).
5362 let j = base + n_acc;
5363 self.commit_verified_prefix(
5364 e,
5365 &mut *cache,
5366 &snap,
5367 ckpt.as_ref().unwrap(),
5368 j,
5369 devacc_seeded,
5370 if devacc_seeded {
5371 devacc_acc.as_ref().map(|a| (a, base, t_v))
5372 } else {
5373 None
5374 },
5375 )?;
5376 let mut seed = e.zeros(n_embd)?;
5377 e.copy_view_into(
5378 &mut seed,
5379 0,
5380 &vx.slice((j - 1) * n_embd..j * n_embd),
5381 n_embd,
5382 )?;
5383 // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
5384 // branch); without it the chain entries stand and only the tail truncates. Either
5385 // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
5386 // (persistent mode), rope pos+j+1 (chain convention).
5387 if refresh {
5388 scratch.set_len(e, pos)?;
5389 let mut vxs = e.zeros(j * n_embd)?;
5390 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
5391 if j > 1 {
5392 e.copy_view_into(
5393 &mut vxs,
5394 n_embd,
5395 &vx.slice(0..(j - 1) * n_embd),
5396 (j - 1) * n_embd,
5397 )?;
5398 }
5399 self.mtp_kv_fill(
5400 e,
5401 mtp,
5402 &verify_tokens[0..j],
5403 &vxs,
5404 pos,
5405 &mut *scratch,
5406 embd_dev,
5407 )?;
5408 } else {
5409 scratch.set_len(e, pos + j)?;
5410 }
5411 // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
5412 // bonus's predecessor (verify col j-1); no pseudo pass.
5413 if !devacc_seeded {
5414 e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
5415 e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
5416 }
5417 pending = Some(bonus);
5418 if debug_spec {
5419 eprintln!(" -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
5420 }
5421 } else if !spec_replay {
5422 // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
5423 // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
5424 // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
5425 // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
5426 // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
5427 // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
5428 // base=1 pending machinery, bit-identical by the decode-exact verify contract.
5429 // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
5430 // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
5431 cache.rollback(e, &snap, 0)?;
5432 scratch.set_len(e, pos)?;
5433 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
5434 pending = Some(bonus);
5435 if debug_spec {
5436 eprintln!(" -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
5437 }
5438 } else {
5439 // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
5440 // this round survives, only possible before the first pending exists, ~round 0):
5441 // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
5442 // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
5443 // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
5444 // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
5445 // trunk hidden.
5446 cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
5447 let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
5448 if let Some(b) = pending.take() {
5449 replay.push(b);
5450 }
5451 replay.extend_from_slice(&draft[0..n_acc]);
5452 replay.push(bonus);
5453 // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
5454 // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
5455 // last col exactly as before (byte-identical to the old _h_emb_dev call).
5456 let (rl_d, rx) =
5457 self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?;
5458 // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
5459 // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
5460 e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
5461 last_pred = e.dtoh_u32(&preds_d)?[0];
5462 if sampled {
5463 let lr0 = replay.len();
5464 let lc = last_col_logits
5465 .as_mut()
5466 .expect("sampled: last_col_logits unset");
5467 e.copy_view_into(
5468 lc,
5469 0,
5470 &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
5471 n_vocab,
5472 )?;
5473 }
5474 let lr = replay.len();
5475 if lr >= 2 {
5476 e.copy_view_into(
5477 &mut h_seed_buf,
5478 0,
5479 &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
5480 n_embd,
5481 )?;
5482 } else {
5483 // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
5484 // last_token, whose own-row hidden fill_prev still holds.
5485 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
5486 }
5487 // the bonus is COMMITTED here — it becomes the last committed row.
5488 let mut rh_last = e.zeros(n_embd)?;
5489 e.copy_view_into(
5490 &mut rh_last,
5491 0,
5492 &rx.slice((lr - 1) * n_embd..lr * n_embd),
5493 n_embd,
5494 )?;
5495 e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
5496 if debug_spec {
5497 eprintln!(" -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
5498 }
5499 }
5500 if devacc_seeded {
5501 // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
5502 // consumed the old value (both slots carry the same value in every non-replay arm).
5503 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
5504 }
5505 // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
5506 // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
5507 // final position — the floor's position key reads the committed depth). Burst
5508 // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
5509 // like gemma's burst arm.
5510 if adapt {
5511 let fl_now = floor_at(cache.pos);
5512 kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
5513 }
5514 ph_mark(&mut ph_rest, phase_on);
5515 round += 1;
5516 // sse-cadence: this round's accepted drafts + bonus are committed (out is
5517 // append-only past step 4) — flush at round cadence.
5518 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
5519 }
5520 // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
5521 // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
5522 let _ = flush_commit(&mut on_commit, &out, &mut flushed);
5523
5524 if spec_stats {
5525 let per_slot: Vec<String> = (0..k)
5526 .map(|j| {
5527 if st_drafted[j] > 0 {
5528 format!(
5529 "{}/{}={:.3}",
5530 st_accepted[j],
5531 st_drafted[j],
5532 st_accepted[j] as f64 / st_drafted[j] as f64
5533 )
5534 } else {
5535 "0/0".into()
5536 }
5537 })
5538 .collect();
5539 let acc = if total_drafted > 0 {
5540 total_accepted as f64 / total_drafted as f64
5541 } else {
5542 0.0
5543 };
5544 eprintln!(
5545 "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
5546 per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
5547 tok_per_round={:.3}",
5548 per_slot.join(" "),
5549 (total_accepted + round) as f64 / round.max(1) as f64
5550 );
5551 }
5552 if constraint.is_some() {
5553 eprintln!(
5554 "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
5555 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
5556 dm_clone_ns as f64 / 1e6,
5557 dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
5558 );
5559 }
5560 if phase_on {
5561 let tot = ph_draft + ph_verify + ph_wait + ph_rest;
5562 eprintln!("[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
5563 ph_draft * 1e3, ph_draft / tot * 100.0,
5564 ph_verify * 1e3, ph_verify / tot * 100.0,
5565 ph_wait * 1e3, ph_wait / tot * 100.0,
5566 ph_rest * 1e3, ph_rest / tot * 100.0);
5567 }
5568 // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
5569 // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
5570 // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
5571 // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
5572 if let Some(slot) = sess_draft_slot.take() {
5573 *slot = Some(dctx);
5574 }
5575 let t_rounds = t_ent.elapsed();
5576 if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
5577 *sctr_slot = sctr;
5578 *uctr_slot = uctr;
5579 *next_pred_slot = Some(last_pred);
5580 let mut stashed_pending = false;
5581 if let Some(b) = pending.take() {
5582 if !sampled {
5583 // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
5584 // committing it with a solo T=1 pass — the next empty-suffix greedy burst
5585 // consumes it as round-0 verify col 0 (a plain round edge; the old tail
5586 // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
5587 // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
5588 // OUT of `committed` (cache rows == committed); the consuming call
5589 // prepends it once its verify commits the row. next_pred is unknowable
5590 // without the commit pass — None; callers gate on pending_tok too.
5591 debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
5592 if let Some(slot) = sess_pending_slot.take() {
5593 *slot = Some(b);
5594 }
5595 *next_pred_slot = None;
5596 // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
5597 // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
5598 *last_h = Some(e.clone_dtod(&fill_prev)?);
5599 stashed_pending = true;
5600 } else {
5601 // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
5602 // the sampled round-0 accept needs this pass's logits (last_col_logits).
5603 let pos_b = cache.pos;
5604 scratch.set_len(e, pos_b)?;
5605 let (lg_b, hb) = self.decode_step_h(e, b, &mut *cache)?;
5606 // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
5607 // itself — the prediction AFTER the bonus never materialized; it would have
5608 // been the next round's verify col 0). The commit's logits ARE that
5609 // prediction.
5610 *next_pred_slot = Some(argmax(&lg_b) as u32);
5611 self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
5612 *last_h = Some(hb);
5613 }
5614 } else {
5615 // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
5616 *last_h = Some(e.clone_dtod(&fill_prev)?);
5617 }
5618 committed.extend_from_slice(prompt);
5619 if let Some(cb) = carried_pending {
5620 // the consumed carry's cache row landed in round 0's verify (every pending
5621 // round commits col 0) — it joins `committed` here, in sequence order.
5622 committed.push(cb);
5623 }
5624 if stashed_pending {
5625 // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
5626 // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
5627 // 18446744073709551615 out of range for slice of length 0", killing the
5628 // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
5629 // stream". Reachable because `pending` starts as `carried_pending` (a bonus
5630 // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
5631 // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
5632 // did). So a burst that stashes a pending without emitting anything of its own —
5633 // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
5634 // guard skipping every token under a tight budget — arrives here with
5635 // out.len() == 0 and stashed_pending == true.
5636 //
5637 // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
5638 // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
5639 // just above is already accounted. Saturating, not a min/assert: an empty `out`
5640 // here is a legitimate burst shape, not a corrupt state.
5641 let emitted = out.len().saturating_sub(1);
5642 committed.extend_from_slice(&out[..emitted]);
5643 } else {
5644 committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
5645 }
5646 debug_assert_eq!(
5647 cache.pos,
5648 committed.len(),
5649 "session invariant: cache rows == committed tokens"
5650 );
5651 if setup_trace {
5652 e.stream().synchronize()?; // bound the async tail fill in the trace
5653 let t_tail = t_ent.elapsed();
5654 eprintln!(
5655 "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
5656 t_init.as_secs_f64() * 1e3,
5657 (t_cap - t_init).as_secs_f64() * 1e3,
5658 (t_fill - t_cap).as_secs_f64() * 1e3,
5659 (t_rounds - t_fill).as_secs_f64() * 1e3,
5660 (t_tail - t_rounds).as_secs_f64() * 1e3,
5661 t_tail.as_secs_f64() * 1e3,
5662 out.len(),
5663 continuation
5664 );
5665 }
5666 return Ok((out, total_drafted, total_accepted));
5667 }
5668 out.truncate(max_new);
5669 Ok((out, total_drafted, total_accepted))
5670 }
5671
5672 /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
5673 /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
5674 /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
5675 /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
5676 /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
5677 /// quant-induced head/hidden-state mismatch from text drift.
5678 ///
5679 /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
5680 /// draft_j = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
5681 /// eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
5682 /// target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
5683 /// at forced context tokens[0..p+j]). For j==0 this equals live spec
5684 /// acceptance; for j>=1 live verify would condition on the drafts, here it
5685 /// conditions on the corpus — deterministic and arm-comparable by design.
5686 ///
5687 /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
5688 /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
5689 /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
5690 ///
5691 /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
5692 /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
5693 /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
5694 /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
5695 /// agreement vs this path — not usable as a training-data source).
5696 pub fn replay_acceptance(
5697 &self,
5698 e: &Engine,
5699 tokens: &[u32],
5700 k: usize,
5701 stride: usize,
5702 chunk: usize,
5703 mut hdump: Option<&mut std::fs::File>,
5704 ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
5705 assert!(k >= 1 && stride >= 1 && chunk >= 2);
5706 let mtp = self
5707 .mtp
5708 .as_ref()
5709 .expect("replay_acceptance requires an MTP head");
5710 let n_vocab = self.output.out_features();
5711 let d_vocab = mtp
5712 .shared_head_head
5713 .as_ref()
5714 .unwrap_or(&self.output)
5715 .out_features();
5716 let n_embd = self.cfg.n_embd as usize;
5717 let t_total = tokens.len();
5718 assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
5719 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
5720 let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
5721 let mut scratch = MtpScratch::new(
5722 e,
5723 &self.cfg,
5724 t_total + k + 8,
5725 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5726 )?;
5727 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
5728 let embd_gpu = if spec_host_embd() {
5729 None
5730 } else {
5731 Some(
5732 self.embd_gpu
5733 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
5734 )
5735 };
5736 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
5737
5738 // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
5739 let mut bg: Vec<u32> = vec![0; t_total + 1];
5740 let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
5741 let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
5742 let mut seed_buf = e.zeros(n_embd)?;
5743 let mut preds_d = e.alloc_u32_zeroed(chunk)?;
5744 let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
5745 let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
5746 let mut s = 0usize;
5747 while s < t_total {
5748 let cend = (s + chunk).min(t_total);
5749 let tc = cend - s;
5750 let ch = &tokens[s..cend];
5751 // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
5752 // the chunk's true hiddens.
5753 let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
5754 for j in 0..tc {
5755 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
5756 }
5757 let preds = e.dtoh_u32(&preds_d)?;
5758 for j in 0..tc {
5759 bg[s + j + 1] = preds[j];
5760 }
5761 // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
5762 // checkpoint-quality metric (position j's logits score the GOLD next token).
5763 if nll_on {
5764 let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
5765 if jmax > 0 {
5766 let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
5767 let rows: Vec<i32> = (0..jmax as i32).collect();
5768 let idsd = e.htod_u32_v(&ids)?;
5769 let rowsd = e.htod_i32(&rows)?;
5770 let mut outd = e.zeros(jmax)?;
5771 e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
5772 for pr in e.dtoh(&outd)? {
5773 nll_sum += -((pr.max(1e-30)) as f64).ln();
5774 nll_cnt += 1;
5775 }
5776 }
5777 }
5778 if let Some(f) = hdump.as_deref_mut() {
5779 use std::io::Write;
5780 let host: Vec<f32> = e.dtoh(&vx)?;
5781 // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
5782 // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
5783 let mut bytes = Vec::with_capacity(tc * n_embd * 2);
5784 for v in &host[..tc * n_embd] {
5785 let b = v.to_bits();
5786 let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
5787 bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
5788 }
5789 f.write_all(&bytes)?;
5790 }
5791 // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
5792 // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
5793 // per token saved; the forced trunk pass + hdump is all the mode needs).
5794 let chainless = stride > t_total;
5795 if chainless {
5796 e.copy_view_into(
5797 &mut prev_last_h,
5798 0,
5799 &vx.slice((tc - 1) * n_embd..tc * n_embd),
5800 n_embd,
5801 )?;
5802 s = cend;
5803 continue;
5804 }
5805 // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
5806 // row s reads the previous chunk's last true hidden, zeros at corpus start).
5807 let mut vxs = e.zeros(tc * n_embd)?;
5808 e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
5809 if tc > 1 {
5810 e.copy_view_into(
5811 &mut vxs,
5812 n_embd,
5813 &vx.slice(0..(tc - 1) * n_embd),
5814 (tc - 1) * n_embd,
5815 )?;
5816 }
5817 scratch.set_len(e, s)?;
5818 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
5819 // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
5820 // [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
5821 // truncates those approximate appends before they can ever be read.
5822 let ps: Vec<usize> = (s..cend)
5823 .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
5824 .collect();
5825 for &p in ps.iter().rev() {
5826 scratch.set_len(e, p)?;
5827 if p == s {
5828 e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
5829 } else {
5830 e.copy_view_into(
5831 &mut seed_buf,
5832 0,
5833 &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
5834 n_embd,
5835 )?;
5836 }
5837 let mut e_tok = tokens[p];
5838 let mut d_seed = e.clone_dtod(&seed_buf)?;
5839 let mut drafts: Vec<u32> = Vec::with_capacity(k);
5840 for j in 0..k {
5841 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
5842 e,
5843 mtp,
5844 e_tok,
5845 &d_seed,
5846 &mut scratch,
5847 p + 1 + j,
5848 embd_dev,
5849 None, // acceptance-oracle walk: no grammar
5850 )?;
5851 let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
5852 let idx = e.dtoh_u32_one(&tok_d)?;
5853 let d = match &mtp.d2t {
5854 Some(map) => map[idx as usize],
5855 None => idx,
5856 };
5857 drafts.push(d);
5858 e_tok = d;
5859 d_seed = h_nextn;
5860 }
5861 // targets may live in a LATER chunk's bg — resolved after the walk.
5862 rows.push((p, drafts, Vec::new()));
5863 }
5864 // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
5865 // expect scratch.len == cend with exact rows).
5866 scratch.set_len(e, s)?;
5867 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
5868 e.copy_view_into(
5869 &mut prev_last_h,
5870 0,
5871 &vx.slice((tc - 1) * n_embd..tc * n_embd),
5872 n_embd,
5873 )?;
5874 s = cend;
5875 }
5876 for (p, drafts, targets) in rows.iter_mut() {
5877 for j in 0..drafts.len() {
5878 targets.push(bg[*p + 1 + j]);
5879 }
5880 }
5881 rows.sort_by_key(|r| r.0);
5882 if nll_cnt > 0 {
5883 let mean = nll_sum / nll_cnt as f64;
5884 println!(
5885 "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
5886 mean.exp()
5887 );
5888 }
5889 Ok((rows, bg))
5890 }
5891}
5892
5893#[cfg(test)]
5894mod telem_tests {
5895 use super::{SpecTelemetry, SPEC_TELEM_POS};
5896
5897 /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
5898 /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
5899 #[test]
5900 fn delta_isolates_burst_contribution() {
5901 let mut t = SpecTelemetry::default();
5902 // "previous request": 2 rounds of k=3, accepts 3 then 1.
5903 for (kr, na) in [(3usize, 3usize), (3, 1)] {
5904 t.rounds += 1;
5905 t.drafted += kr as u64;
5906 t.accepted += na as u64;
5907 for j in 0..kr { t.pos_drafted[j] += 1; }
5908 for j in 0..na { t.pos_accepted[j] += 1; }
5909 }
5910 let before = t;
5911 // "this burst": 1 round k=3, accepts 2.
5912 t.rounds += 1;
5913 t.drafted += 3;
5914 t.accepted += 2;
5915 for j in 0..3 { t.pos_drafted[j] += 1; }
5916 for j in 0..2 { t.pos_accepted[j] += 1; }
5917 let d = t.delta_since(&before);
5918 assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
5919 assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
5920 assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
5921 assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
5922 }
5923
5924 /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
5925 /// aggregation invariant.
5926 #[test]
5927 fn merge_accumulates_fieldwise() {
5928 let mut agg = SpecTelemetry::default();
5929 let mut d1 = SpecTelemetry { rounds: 2, drafted: 6, accepted: 4, ..Default::default() };
5930 d1.pos_drafted[0] = 2;
5931 d1.pos_accepted[0] = 2;
5932 let mut d2 = SpecTelemetry { rounds: 1, drafted: 3, accepted: 1, ..Default::default() };
5933 d2.pos_drafted[0] = 1;
5934 d2.pos_accepted[0] = 1;
5935 d2.pos_drafted[1] = 1;
5936 agg.merge(&d1);
5937 agg.merge(&d2);
5938 assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
5939 assert_eq!(agg.pos_drafted[0], 3);
5940 assert_eq!(agg.pos_accepted[0], 3);
5941 assert_eq!(agg.pos_drafted[1], 1);
5942 assert_eq!(agg.pos_accepted[1], 0);
5943 }
5944
5945 /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
5946 /// public metrics surface and must never publish a u64-wrapped garbage value.
5947 #[test]
5948 fn delta_saturates_never_wraps() {
5949 let small = SpecTelemetry { rounds: 1, drafted: 2, accepted: 1, ..Default::default() };
5950 let big = SpecTelemetry { rounds: 5, drafted: 15, accepted: 9, ..Default::default() };
5951 let d = small.delta_since(&big);
5952 assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
5953 }
5954}
5955
5956#[cfg(test)]
5957mod draft_graph_fallback_tests {
5958 use super::DraftGraphFallback;
5959
5960 /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
5961 #[test]
5962 fn flip_is_loud_once_and_memoized_after() {
5963 let mut f = DraftGraphFallback::default();
5964 let line = f.mark_greedy("out of memory").expect("first flip must return the warn line");
5965 assert!(line.contains("WARN"), "flip line must be warn-level: {line}");
5966 assert!(line.contains("out of memory"), "flip line must carry the reason: {line}");
5967 assert!(f.greedy_failed());
5968 // re-marking an already-failed graph is the memoization: quiet, still failed.
5969 assert!(f.mark_greedy("out of memory").is_none());
5970 assert!(f.greedy_failed());
5971 // the two graphs' flags are independent (greedy flip leaves sampled capturable).
5972 assert!(!f.sampled_failed());
5973 let line_s = f.mark_sampled("capture unsupported").expect("sampled flip is its own flip");
5974 assert!(line_s.contains("sampled"), "sampled flip names itself: {line_s}");
5975 assert!(f.mark_sampled("capture unsupported").is_none());
5976 }
5977
5978 /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
5979 /// and says so exactly when there was something to reset.
5980 #[test]
5981 fn reset_on_resume_clears_flags_and_logs_once() {
5982 let mut f = DraftGraphFallback::default();
5983 // clean session: resume is silent, nothing to reset.
5984 assert!(f.reset_on_resume().is_none());
5985 f.mark_greedy("oom").unwrap();
5986 f.mark_sampled("oom").unwrap();
5987 let note = f.reset_on_resume().expect("a set flag must produce the reset note");
5988 assert!(note.contains("greedy+sampled"), "note names what was reset: {note}");
5989 assert!(!f.greedy_failed() && !f.sampled_failed(), "both flags cleared");
5990 // and the NEXT failure after a reset is a fresh flip — loud again.
5991 assert!(f.mark_greedy("oom again").is_some());
5992 let note2 = f.reset_on_resume().expect("greedy-only reset");
5993 assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
5994 }
5995
5996 /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
5997 /// they precede a fresh capture attempt whose own failure re-flips loudly.
5998 #[test]
5999 fn shape_change_clears_are_silent() {
6000 let mut f = DraftGraphFallback::default();
6001 f.mark_greedy("oom").unwrap();
6002 f.clear_greedy();
6003 assert!(!f.greedy_failed());
6004 f.mark_sampled("oom").unwrap();
6005 f.clear_sampled();
6006 assert!(!f.sampled_failed());
6007 // after a silent clear there is nothing left for resume to report.
6008 assert!(f.reset_on_resume().is_none());
6009 }
6010}