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