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