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