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